• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Type object implementation */
2 
3 #include "Python.h"
4 #include "pycore_abstract.h"      // _PySequence_IterSearch()
5 #include "pycore_call.h"          // _PyObject_VectorcallTstate()
6 #include "pycore_code.h"          // CO_FAST_FREE
7 #include "pycore_dict.h"          // _PyDict_KeysSize()
8 #include "pycore_frame.h"         // _PyInterpreterFrame
9 #include "pycore_lock.h"          // _PySeqLock_*
10 #include "pycore_long.h"          // _PyLong_IsNegative()
11 #include "pycore_memoryobject.h"  // _PyMemoryView_FromBufferProc()
12 #include "pycore_modsupport.h"    // _PyArg_NoKwnames()
13 #include "pycore_moduleobject.h"  // _PyModule_GetDef()
14 #include "pycore_object.h"        // _PyType_HasFeature()
15 #include "pycore_object_alloc.h"  // _PyObject_MallocWithType()
16 #include "pycore_pyerrors.h"      // _PyErr_Occurred()
17 #include "pycore_pystate.h"       // _PyThreadState_GET()
18 #include "pycore_symtable.h"      // _Py_Mangle()
19 #include "pycore_typeobject.h"    // struct type_cache
20 #include "pycore_unionobject.h"   // _Py_union_type_or
21 #include "pycore_weakref.h"       // _PyWeakref_GET_REF()
22 #include "opcode.h"               // MAKE_CELL
23 
24 #include <stddef.h>               // ptrdiff_t
25 
26 /*[clinic input]
27 class type "PyTypeObject *" "&PyType_Type"
28 class object "PyObject *" "&PyBaseObject_Type"
29 [clinic start generated code]*/
30 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=4b94608d231c434b]*/
31 
32 #include "clinic/typeobject.c.h"
33 
34 /* Support type attribute lookup cache */
35 
36 /* The cache can keep references to the names alive for longer than
37    they normally would.  This is why the maximum size is limited to
38    MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
39    strings are used as attribute names. */
40 #define MCACHE_MAX_ATTR_SIZE    100
41 #define MCACHE_HASH(version, name_hash)                                 \
42         (((unsigned int)(version) ^ (unsigned int)(name_hash))          \
43          & ((1 << MCACHE_SIZE_EXP) - 1))
44 
45 #define MCACHE_HASH_METHOD(type, name)                                  \
46     MCACHE_HASH(FT_ATOMIC_LOAD_UINT32_RELAXED((type)->tp_version_tag),   \
47                 ((Py_ssize_t)(name)) >> 3)
48 #define MCACHE_CACHEABLE_NAME(name)                             \
49         PyUnicode_CheckExact(name) &&                           \
50         PyUnicode_IS_READY(name) &&                             \
51         (PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE)
52 
53 #define NEXT_GLOBAL_VERSION_TAG _PyRuntime.types.next_version_tag
54 #define NEXT_VERSION_TAG(interp) \
55     (interp)->types.next_version_tag
56 
57 #ifdef Py_GIL_DISABLED
58 
59 // There's a global lock for mutation of types.  This avoids having to take
60 // additional locks while doing various subclass processing which may result
61 // in odd behaviors w.r.t. running with the GIL as the outer type lock could
62 // be released and reacquired during a subclass update if there's contention
63 // on the subclass lock.
64 #define TYPE_LOCK &PyInterpreterState_Get()->types.mutex
65 #define BEGIN_TYPE_LOCK() Py_BEGIN_CRITICAL_SECTION_MUT(TYPE_LOCK)
66 #define END_TYPE_LOCK() Py_END_CRITICAL_SECTION()
67 
68 #define BEGIN_TYPE_DICT_LOCK(d) \
69     Py_BEGIN_CRITICAL_SECTION2_MUT(TYPE_LOCK, &_PyObject_CAST(d)->ob_mutex)
70 
71 #define END_TYPE_DICT_LOCK() Py_END_CRITICAL_SECTION2()
72 
73 #define ASSERT_TYPE_LOCK_HELD() \
74     _Py_CRITICAL_SECTION_ASSERT_MUTEX_LOCKED(TYPE_LOCK)
75 
76 #else
77 
78 #define BEGIN_TYPE_LOCK()
79 #define END_TYPE_LOCK()
80 #define BEGIN_TYPE_DICT_LOCK(d)
81 #define END_TYPE_DICT_LOCK()
82 #define ASSERT_TYPE_LOCK_HELD()
83 
84 #endif
85 
86 
87 typedef struct PySlot_Offset {
88     short subslot_offset;
89     short slot_offset;
90 } PySlot_Offset;
91 
92 static void
93 slot_bf_releasebuffer(PyObject *self, Py_buffer *buffer);
94 
95 static void
96 releasebuffer_call_python(PyObject *self, Py_buffer *buffer);
97 
98 static PyObject *
99 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
100 
101 static PyObject *
102 lookup_maybe_method(PyObject *self, PyObject *attr, int *unbound);
103 
104 static int
105 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value);
106 
107 
108 static inline PyTypeObject *
type_from_ref(PyObject * ref)109 type_from_ref(PyObject *ref)
110 {
111     PyObject *obj = _PyWeakref_GET_REF(ref);
112     if (obj == NULL) {
113         return NULL;
114     }
115     return _PyType_CAST(obj);
116 }
117 
118 
119 /* helpers for for static builtin types */
120 
121 #ifndef NDEBUG
122 static inline int
managed_static_type_index_is_set(PyTypeObject * self)123 managed_static_type_index_is_set(PyTypeObject *self)
124 {
125     return self->tp_subclasses != NULL;
126 }
127 #endif
128 
129 static inline size_t
managed_static_type_index_get(PyTypeObject * self)130 managed_static_type_index_get(PyTypeObject *self)
131 {
132     assert(managed_static_type_index_is_set(self));
133     /* We store a 1-based index so 0 can mean "not initialized". */
134     return (size_t)self->tp_subclasses - 1;
135 }
136 
137 static inline void
managed_static_type_index_set(PyTypeObject * self,size_t index)138 managed_static_type_index_set(PyTypeObject *self, size_t index)
139 {
140     assert(index < _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES);
141     /* We store a 1-based index so 0 can mean "not initialized". */
142     self->tp_subclasses = (PyObject *)(index + 1);
143 }
144 
145 static inline void
managed_static_type_index_clear(PyTypeObject * self)146 managed_static_type_index_clear(PyTypeObject *self)
147 {
148     self->tp_subclasses = NULL;
149 }
150 
151 static PyTypeObject *
static_ext_type_lookup(PyInterpreterState * interp,size_t index,int64_t * p_interp_count)152 static_ext_type_lookup(PyInterpreterState *interp, size_t index,
153                        int64_t *p_interp_count)
154 {
155     assert(interp->runtime == &_PyRuntime);
156     assert(index < _Py_MAX_MANAGED_STATIC_EXT_TYPES);
157 
158     size_t full_index = index + _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES;
159     int64_t interp_count =
160             _PyRuntime.types.managed_static.types[full_index].interp_count;
161     assert((interp_count == 0) ==
162             (_PyRuntime.types.managed_static.types[full_index].type == NULL));
163     *p_interp_count = interp_count;
164 
165     PyTypeObject *type = interp->types.for_extensions.initialized[index].type;
166     if (type == NULL) {
167         return NULL;
168     }
169     assert(!interp->types.for_extensions.initialized[index].isbuiltin);
170     assert(type == _PyRuntime.types.managed_static.types[full_index].type);
171     assert(managed_static_type_index_is_set(type));
172     return type;
173 }
174 
175 static managed_static_type_state *
managed_static_type_state_get(PyInterpreterState * interp,PyTypeObject * self)176 managed_static_type_state_get(PyInterpreterState *interp, PyTypeObject *self)
177 {
178     // It's probably a builtin type.
179     size_t index = managed_static_type_index_get(self);
180     managed_static_type_state *state =
181             &(interp->types.builtins.initialized[index]);
182     if (state->type == self) {
183         return state;
184     }
185     if (index > _Py_MAX_MANAGED_STATIC_EXT_TYPES) {
186         return state;
187     }
188     return &(interp->types.for_extensions.initialized[index]);
189 }
190 
191 /* For static types we store some state in an array on each interpreter. */
192 managed_static_type_state *
_PyStaticType_GetState(PyInterpreterState * interp,PyTypeObject * self)193 _PyStaticType_GetState(PyInterpreterState *interp, PyTypeObject *self)
194 {
195     assert(self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN);
196     return managed_static_type_state_get(interp, self);
197 }
198 
199 /* Set the type's per-interpreter state. */
200 static void
managed_static_type_state_init(PyInterpreterState * interp,PyTypeObject * self,int isbuiltin,int initial)201 managed_static_type_state_init(PyInterpreterState *interp, PyTypeObject *self,
202                                int isbuiltin, int initial)
203 {
204     assert(interp->runtime == &_PyRuntime);
205 
206     size_t index;
207     if (initial) {
208         assert(!managed_static_type_index_is_set(self));
209         if (isbuiltin) {
210             index = interp->types.builtins.num_initialized;
211             assert(index < _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES);
212         }
213         else {
214             PyMutex_Lock(&interp->types.mutex);
215             index = interp->types.for_extensions.next_index;
216             interp->types.for_extensions.next_index++;
217             PyMutex_Unlock(&interp->types.mutex);
218             assert(index < _Py_MAX_MANAGED_STATIC_EXT_TYPES);
219         }
220         managed_static_type_index_set(self, index);
221     }
222     else {
223         index = managed_static_type_index_get(self);
224         if (isbuiltin) {
225             assert(index == interp->types.builtins.num_initialized);
226             assert(index < _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES);
227         }
228         else {
229             assert(index < _Py_MAX_MANAGED_STATIC_EXT_TYPES);
230         }
231     }
232     size_t full_index = isbuiltin
233         ? index
234         : index + _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES;
235 
236     assert((initial == 1) ==
237             (_PyRuntime.types.managed_static.types[full_index].interp_count == 0));
238     (void)_Py_atomic_add_int64(
239             &_PyRuntime.types.managed_static.types[full_index].interp_count, 1);
240 
241     if (initial) {
242         assert(_PyRuntime.types.managed_static.types[full_index].type == NULL);
243         _PyRuntime.types.managed_static.types[full_index].type = self;
244     }
245     else {
246         assert(_PyRuntime.types.managed_static.types[full_index].type == self);
247     }
248 
249     managed_static_type_state *state = isbuiltin
250         ? &(interp->types.builtins.initialized[index])
251         : &(interp->types.for_extensions.initialized[index]);
252 
253     /* It should only be called once for each builtin type per interpreter. */
254     assert(state->type == NULL);
255     state->type = self;
256     state->isbuiltin = isbuiltin;
257 
258     /* state->tp_subclasses is left NULL until init_subclasses() sets it. */
259     /* state->tp_weaklist is left NULL until insert_head() or insert_after()
260        (in weakrefobject.c) sets it. */
261 
262     if (isbuiltin) {
263         interp->types.builtins.num_initialized++;
264     }
265     else {
266         interp->types.for_extensions.num_initialized++;
267     }
268 }
269 
270 /* Reset the type's per-interpreter state.
271    This basically undoes what managed_static_type_state_init() did. */
272 static void
managed_static_type_state_clear(PyInterpreterState * interp,PyTypeObject * self,int isbuiltin,int final)273 managed_static_type_state_clear(PyInterpreterState *interp, PyTypeObject *self,
274                                 int isbuiltin, int final)
275 {
276     size_t index = managed_static_type_index_get(self);
277     size_t full_index = isbuiltin
278         ? index
279         : index + _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES;
280 
281     managed_static_type_state *state = isbuiltin
282         ? &(interp->types.builtins.initialized[index])
283         : &(interp->types.for_extensions.initialized[index]);
284     assert(state != NULL);
285 
286     assert(_PyRuntime.types.managed_static.types[full_index].interp_count > 0);
287     assert(_PyRuntime.types.managed_static.types[full_index].type == state->type);
288 
289     assert(state->type != NULL);
290     state->type = NULL;
291     assert(state->tp_weaklist == NULL);  // It was already cleared out.
292 
293     (void)_Py_atomic_add_int64(
294             &_PyRuntime.types.managed_static.types[full_index].interp_count, -1);
295     if (final) {
296         assert(!_PyRuntime.types.managed_static.types[full_index].interp_count);
297         _PyRuntime.types.managed_static.types[full_index].type = NULL;
298 
299         managed_static_type_index_clear(self);
300     }
301 
302     if (isbuiltin) {
303         assert(interp->types.builtins.num_initialized > 0);
304         interp->types.builtins.num_initialized--;
305     }
306     else {
307         PyMutex_Lock(&interp->types.mutex);
308         assert(interp->types.for_extensions.num_initialized > 0);
309         interp->types.for_extensions.num_initialized--;
310         if (interp->types.for_extensions.num_initialized == 0) {
311             interp->types.for_extensions.next_index = 0;
312         }
313         PyMutex_Unlock(&interp->types.mutex);
314     }
315 }
316 
317 // Also see _PyStaticType_InitBuiltin() and _PyStaticType_FiniBuiltin().
318 
319 /* end static builtin helpers */
320 
321 
322 static inline void
start_readying(PyTypeObject * type)323 start_readying(PyTypeObject *type)
324 {
325     if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
326         PyInterpreterState *interp = _PyInterpreterState_GET();
327         managed_static_type_state *state = managed_static_type_state_get(interp, type);
328         assert(state != NULL);
329         assert(!state->readying);
330         state->readying = 1;
331         return;
332     }
333     assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
334     type->tp_flags |= Py_TPFLAGS_READYING;
335 }
336 
337 static inline void
stop_readying(PyTypeObject * type)338 stop_readying(PyTypeObject *type)
339 {
340     if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
341         PyInterpreterState *interp = _PyInterpreterState_GET();
342         managed_static_type_state *state = managed_static_type_state_get(interp, type);
343         assert(state != NULL);
344         assert(state->readying);
345         state->readying = 0;
346         return;
347     }
348     assert(type->tp_flags & Py_TPFLAGS_READYING);
349     type->tp_flags &= ~Py_TPFLAGS_READYING;
350 }
351 
352 static inline int
is_readying(PyTypeObject * type)353 is_readying(PyTypeObject *type)
354 {
355     if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
356         PyInterpreterState *interp = _PyInterpreterState_GET();
357         managed_static_type_state *state = managed_static_type_state_get(interp, type);
358         assert(state != NULL);
359         return state->readying;
360     }
361     return (type->tp_flags & Py_TPFLAGS_READYING) != 0;
362 }
363 
364 
365 /* accessors for objects stored on PyTypeObject */
366 
367 static inline PyObject *
lookup_tp_dict(PyTypeObject * self)368 lookup_tp_dict(PyTypeObject *self)
369 {
370     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
371         PyInterpreterState *interp = _PyInterpreterState_GET();
372         managed_static_type_state *state = _PyStaticType_GetState(interp, self);
373         assert(state != NULL);
374         return state->tp_dict;
375     }
376     return self->tp_dict;
377 }
378 
379 PyObject *
_PyType_GetDict(PyTypeObject * self)380 _PyType_GetDict(PyTypeObject *self)
381 {
382     /* It returns a borrowed reference. */
383     return lookup_tp_dict(self);
384 }
385 
386 PyObject *
PyType_GetDict(PyTypeObject * self)387 PyType_GetDict(PyTypeObject *self)
388 {
389     PyObject *dict = lookup_tp_dict(self);
390     return _Py_XNewRef(dict);
391 }
392 
393 static inline void
set_tp_dict(PyTypeObject * self,PyObject * dict)394 set_tp_dict(PyTypeObject *self, PyObject *dict)
395 {
396     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
397         PyInterpreterState *interp = _PyInterpreterState_GET();
398         managed_static_type_state *state = _PyStaticType_GetState(interp, self);
399         assert(state != NULL);
400         state->tp_dict = dict;
401         return;
402     }
403     self->tp_dict = dict;
404 }
405 
406 static inline void
clear_tp_dict(PyTypeObject * self)407 clear_tp_dict(PyTypeObject *self)
408 {
409     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
410         PyInterpreterState *interp = _PyInterpreterState_GET();
411         managed_static_type_state *state = _PyStaticType_GetState(interp, self);
412         assert(state != NULL);
413         Py_CLEAR(state->tp_dict);
414         return;
415     }
416     Py_CLEAR(self->tp_dict);
417 }
418 
419 
420 static inline PyObject *
lookup_tp_bases(PyTypeObject * self)421 lookup_tp_bases(PyTypeObject *self)
422 {
423     return self->tp_bases;
424 }
425 
426 PyObject *
_PyType_GetBases(PyTypeObject * self)427 _PyType_GetBases(PyTypeObject *self)
428 {
429     PyObject *res;
430 
431     BEGIN_TYPE_LOCK();
432     res = lookup_tp_bases(self);
433     Py_INCREF(res);
434     END_TYPE_LOCK();
435 
436     return res;
437 }
438 
439 static inline void
set_tp_bases(PyTypeObject * self,PyObject * bases,int initial)440 set_tp_bases(PyTypeObject *self, PyObject *bases, int initial)
441 {
442     assert(PyTuple_CheckExact(bases));
443     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
444         // XXX tp_bases can probably be statically allocated for each
445         // static builtin type.
446         assert(initial);
447         assert(self->tp_bases == NULL);
448         if (PyTuple_GET_SIZE(bases) == 0) {
449             assert(self->tp_base == NULL);
450         }
451         else {
452             assert(PyTuple_GET_SIZE(bases) == 1);
453             assert(PyTuple_GET_ITEM(bases, 0) == (PyObject *)self->tp_base);
454             assert(self->tp_base->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN);
455             assert(_Py_IsImmortalLoose(self->tp_base));
456         }
457         _Py_SetImmortal(bases);
458     }
459     self->tp_bases = bases;
460 }
461 
462 static inline void
clear_tp_bases(PyTypeObject * self,int final)463 clear_tp_bases(PyTypeObject *self, int final)
464 {
465     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
466         if (final) {
467             if (self->tp_bases != NULL) {
468                 if (PyTuple_GET_SIZE(self->tp_bases) == 0) {
469                     Py_CLEAR(self->tp_bases);
470                 }
471                 else {
472                     assert(_Py_IsImmortalLoose(self->tp_bases));
473                     _Py_ClearImmortal(self->tp_bases);
474                 }
475             }
476         }
477         return;
478     }
479     Py_CLEAR(self->tp_bases);
480 }
481 
482 
483 static inline PyObject *
lookup_tp_mro(PyTypeObject * self)484 lookup_tp_mro(PyTypeObject *self)
485 {
486     ASSERT_TYPE_LOCK_HELD();
487     return self->tp_mro;
488 }
489 
490 PyObject *
_PyType_GetMRO(PyTypeObject * self)491 _PyType_GetMRO(PyTypeObject *self)
492 {
493 #ifdef Py_GIL_DISABLED
494     PyObject *mro = _Py_atomic_load_ptr_relaxed(&self->tp_mro);
495     if (mro == NULL) {
496         return NULL;
497     }
498     if (_Py_TryIncrefCompare(&self->tp_mro, mro)) {
499         return mro;
500     }
501 
502     BEGIN_TYPE_LOCK();
503     mro = lookup_tp_mro(self);
504     Py_XINCREF(mro);
505     END_TYPE_LOCK();
506     return mro;
507 #else
508     return Py_XNewRef(lookup_tp_mro(self));
509 #endif
510 }
511 
512 static inline void
set_tp_mro(PyTypeObject * self,PyObject * mro,int initial)513 set_tp_mro(PyTypeObject *self, PyObject *mro, int initial)
514 {
515     assert(PyTuple_CheckExact(mro));
516     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
517         // XXX tp_mro can probably be statically allocated for each
518         // static builtin type.
519         assert(initial);
520         assert(self->tp_mro == NULL);
521         /* Other checks are done via set_tp_bases. */
522         _Py_SetImmortal(mro);
523     }
524     self->tp_mro = mro;
525 }
526 
527 static inline void
clear_tp_mro(PyTypeObject * self,int final)528 clear_tp_mro(PyTypeObject *self, int final)
529 {
530     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
531         if (final) {
532             if (self->tp_mro != NULL) {
533                 if (PyTuple_GET_SIZE(self->tp_mro) == 0) {
534                     Py_CLEAR(self->tp_mro);
535                 }
536                 else {
537                     assert(_Py_IsImmortalLoose(self->tp_mro));
538                     _Py_ClearImmortal(self->tp_mro);
539                 }
540             }
541         }
542         return;
543     }
544     Py_CLEAR(self->tp_mro);
545 }
546 
547 
548 static PyObject *
init_tp_subclasses(PyTypeObject * self)549 init_tp_subclasses(PyTypeObject *self)
550 {
551     PyObject *subclasses = PyDict_New();
552     if (subclasses == NULL) {
553         return NULL;
554     }
555     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
556         PyInterpreterState *interp = _PyInterpreterState_GET();
557         managed_static_type_state *state = _PyStaticType_GetState(interp, self);
558         state->tp_subclasses = subclasses;
559         return subclasses;
560     }
561     self->tp_subclasses = (void *)subclasses;
562     return subclasses;
563 }
564 
565 static void
clear_tp_subclasses(PyTypeObject * self)566 clear_tp_subclasses(PyTypeObject *self)
567 {
568     /* Delete the dictionary to save memory. _PyStaticType_Dealloc()
569        callers also test if tp_subclasses is NULL to check if a static type
570        has no subclass. */
571     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
572         PyInterpreterState *interp = _PyInterpreterState_GET();
573         managed_static_type_state *state = _PyStaticType_GetState(interp, self);
574         Py_CLEAR(state->tp_subclasses);
575         return;
576     }
577     Py_CLEAR(self->tp_subclasses);
578 }
579 
580 static inline PyObject *
lookup_tp_subclasses(PyTypeObject * self)581 lookup_tp_subclasses(PyTypeObject *self)
582 {
583     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
584         PyInterpreterState *interp = _PyInterpreterState_GET();
585         managed_static_type_state *state = _PyStaticType_GetState(interp, self);
586         assert(state != NULL);
587         return state->tp_subclasses;
588     }
589     return (PyObject *)self->tp_subclasses;
590 }
591 
592 int
_PyType_HasSubclasses(PyTypeObject * self)593 _PyType_HasSubclasses(PyTypeObject *self)
594 {
595     PyInterpreterState *interp = _PyInterpreterState_GET();
596     if (self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN
597         // XXX _PyStaticType_GetState() should never return NULL.
598         && _PyStaticType_GetState(interp, self) == NULL)
599     {
600         return 0;
601     }
602     if (lookup_tp_subclasses(self) == NULL) {
603         return 0;
604     }
605     return 1;
606 }
607 
608 PyObject*
_PyType_GetSubclasses(PyTypeObject * self)609 _PyType_GetSubclasses(PyTypeObject *self)
610 {
611     PyObject *list = PyList_New(0);
612     if (list == NULL) {
613         return NULL;
614     }
615 
616     PyObject *subclasses = lookup_tp_subclasses(self);  // borrowed ref
617     if (subclasses == NULL) {
618         return list;
619     }
620     assert(PyDict_CheckExact(subclasses));
621     // The loop cannot modify tp_subclasses, there is no need
622     // to hold a strong reference (use a borrowed reference).
623 
624     Py_ssize_t i = 0;
625     PyObject *ref;  // borrowed ref
626     while (PyDict_Next(subclasses, &i, NULL, &ref)) {
627         PyTypeObject *subclass = type_from_ref(ref);
628         if (subclass == NULL) {
629             continue;
630         }
631 
632         if (PyList_Append(list, _PyObject_CAST(subclass)) < 0) {
633             Py_DECREF(list);
634             Py_DECREF(subclass);
635             return NULL;
636         }
637         Py_DECREF(subclass);
638     }
639     return list;
640 }
641 
642 /* end accessors for objects stored on PyTypeObject */
643 
644 
645 /*
646  * finds the beginning of the docstring's introspection signature.
647  * if present, returns a pointer pointing to the first '('.
648  * otherwise returns NULL.
649  *
650  * doesn't guarantee that the signature is valid, only that it
651  * has a valid prefix.  (the signature must also pass skip_signature.)
652  */
653 static const char *
find_signature(const char * name,const char * doc)654 find_signature(const char *name, const char *doc)
655 {
656     const char *dot;
657     size_t length;
658 
659     if (!doc)
660         return NULL;
661 
662     assert(name != NULL);
663 
664     /* for dotted names like classes, only use the last component */
665     dot = strrchr(name, '.');
666     if (dot)
667         name = dot + 1;
668 
669     length = strlen(name);
670     if (strncmp(doc, name, length))
671         return NULL;
672     doc += length;
673     if (*doc != '(')
674         return NULL;
675     return doc;
676 }
677 
678 #define SIGNATURE_END_MARKER         ")\n--\n\n"
679 #define SIGNATURE_END_MARKER_LENGTH  6
680 /*
681  * skips past the end of the docstring's introspection signature.
682  * (assumes doc starts with a valid signature prefix.)
683  */
684 static const char *
skip_signature(const char * doc)685 skip_signature(const char *doc)
686 {
687     while (*doc) {
688         if ((*doc == *SIGNATURE_END_MARKER) &&
689             !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
690             return doc + SIGNATURE_END_MARKER_LENGTH;
691         if ((*doc == '\n') && (doc[1] == '\n'))
692             return NULL;
693         doc++;
694     }
695     return NULL;
696 }
697 
698 int
_PyType_CheckConsistency(PyTypeObject * type)699 _PyType_CheckConsistency(PyTypeObject *type)
700 {
701 #define CHECK(expr) \
702     do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG((PyObject *)type, Py_STRINGIFY(expr)); } } while (0)
703 
704     CHECK(!_PyObject_IsFreed((PyObject *)type));
705 
706     if (!(type->tp_flags & Py_TPFLAGS_READY)) {
707         /* don't check static types before PyType_Ready() */
708         return 1;
709     }
710 
711     CHECK(Py_REFCNT(type) >= 1);
712     CHECK(PyType_Check(type));
713 
714     CHECK(!is_readying(type));
715     CHECK(lookup_tp_dict(type) != NULL);
716 
717     if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
718         // bpo-44263: tp_traverse is required if Py_TPFLAGS_HAVE_GC is set.
719         // Note: tp_clear is optional.
720         CHECK(type->tp_traverse != NULL);
721     }
722 
723     if (type->tp_flags & Py_TPFLAGS_DISALLOW_INSTANTIATION) {
724         CHECK(type->tp_new == NULL);
725         CHECK(PyDict_Contains(lookup_tp_dict(type), &_Py_ID(__new__)) == 0);
726     }
727 
728     return 1;
729 #undef CHECK
730 }
731 
732 static const char *
_PyType_DocWithoutSignature(const char * name,const char * internal_doc)733 _PyType_DocWithoutSignature(const char *name, const char *internal_doc)
734 {
735     const char *doc = find_signature(name, internal_doc);
736 
737     if (doc) {
738         doc = skip_signature(doc);
739         if (doc)
740             return doc;
741         }
742     return internal_doc;
743 }
744 
745 PyObject *
_PyType_GetDocFromInternalDoc(const char * name,const char * internal_doc)746 _PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
747 {
748     const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
749 
750     if (!doc || *doc == '\0') {
751         Py_RETURN_NONE;
752     }
753 
754     return PyUnicode_FromString(doc);
755 }
756 
757 static const char *
signature_from_flags(int flags)758 signature_from_flags(int flags)
759 {
760     switch (flags & ~METH_COEXIST) {
761         case METH_NOARGS:
762             return "($self, /)";
763         case METH_NOARGS|METH_CLASS:
764             return "($type, /)";
765         case METH_NOARGS|METH_STATIC:
766             return "()";
767         case METH_O:
768             return "($self, object, /)";
769         case METH_O|METH_CLASS:
770             return "($type, object, /)";
771         case METH_O|METH_STATIC:
772             return "(object, /)";
773         default:
774             return NULL;
775     }
776 }
777 
778 PyObject *
_PyType_GetTextSignatureFromInternalDoc(const char * name,const char * internal_doc,int flags)779 _PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc, int flags)
780 {
781     const char *start = find_signature(name, internal_doc);
782     const char *end;
783 
784     if (start)
785         end = skip_signature(start);
786     else
787         end = NULL;
788     if (!end) {
789         start = signature_from_flags(flags);
790         if (start) {
791             return PyUnicode_FromString(start);
792         }
793         Py_RETURN_NONE;
794     }
795 
796     /* back "end" up until it points just past the final ')' */
797     end -= SIGNATURE_END_MARKER_LENGTH - 1;
798     assert((end - start) >= 2); /* should be "()" at least */
799     assert(end[-1] == ')');
800     assert(end[0] == '\n');
801     return PyUnicode_FromStringAndSize(start, end - start);
802 }
803 
804 
805 static struct type_cache*
get_type_cache(void)806 get_type_cache(void)
807 {
808     PyInterpreterState *interp = _PyInterpreterState_GET();
809     return &interp->types.type_cache;
810 }
811 
812 
813 static void
type_cache_clear(struct type_cache * cache,PyObject * value)814 type_cache_clear(struct type_cache *cache, PyObject *value)
815 {
816     for (Py_ssize_t i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
817         struct type_cache_entry *entry = &cache->hashtable[i];
818 #ifdef Py_GIL_DISABLED
819         _PySeqLock_LockWrite(&entry->sequence);
820 #endif
821         entry->version = 0;
822         Py_XSETREF(entry->name, _Py_XNewRef(value));
823         entry->value = NULL;
824 #ifdef Py_GIL_DISABLED
825         _PySeqLock_UnlockWrite(&entry->sequence);
826 #endif
827     }
828 }
829 
830 
831 void
_PyType_InitCache(PyInterpreterState * interp)832 _PyType_InitCache(PyInterpreterState *interp)
833 {
834     struct type_cache *cache = &interp->types.type_cache;
835     for (Py_ssize_t i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
836         struct type_cache_entry *entry = &cache->hashtable[i];
837         assert(entry->name == NULL);
838 
839         entry->version = 0;
840         // Set to None so _PyType_LookupRef() can use Py_SETREF(),
841         // rather than using slower Py_XSETREF().
842         entry->name = Py_None;
843         entry->value = NULL;
844     }
845 }
846 
847 
848 static unsigned int
_PyType_ClearCache(PyInterpreterState * interp)849 _PyType_ClearCache(PyInterpreterState *interp)
850 {
851     struct type_cache *cache = &interp->types.type_cache;
852     // Set to None, rather than NULL, so _PyType_LookupRef() can
853     // use Py_SETREF() rather than using slower Py_XSETREF().
854     type_cache_clear(cache, Py_None);
855 
856     return NEXT_VERSION_TAG(interp) - 1;
857 }
858 
859 
860 unsigned int
PyType_ClearCache(void)861 PyType_ClearCache(void)
862 {
863     PyInterpreterState *interp = _PyInterpreterState_GET();
864     return _PyType_ClearCache(interp);
865 }
866 
867 
868 void
_PyTypes_Fini(PyInterpreterState * interp)869 _PyTypes_Fini(PyInterpreterState *interp)
870 {
871     struct type_cache *cache = &interp->types.type_cache;
872     type_cache_clear(cache, NULL);
873 
874     // All the managed static types should have been finalized already.
875     assert(interp->types.for_extensions.num_initialized == 0);
876     for (size_t i = 0; i < _Py_MAX_MANAGED_STATIC_EXT_TYPES; i++) {
877         assert(interp->types.for_extensions.initialized[i].type == NULL);
878     }
879     assert(interp->types.builtins.num_initialized == 0);
880     for (size_t i = 0; i < _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES; i++) {
881         assert(interp->types.builtins.initialized[i].type == NULL);
882     }
883 }
884 
885 
886 int
PyType_AddWatcher(PyType_WatchCallback callback)887 PyType_AddWatcher(PyType_WatchCallback callback)
888 {
889     PyInterpreterState *interp = _PyInterpreterState_GET();
890 
891     for (int i = 0; i < TYPE_MAX_WATCHERS; i++) {
892         if (!interp->type_watchers[i]) {
893             interp->type_watchers[i] = callback;
894             return i;
895         }
896     }
897 
898     PyErr_SetString(PyExc_RuntimeError, "no more type watcher IDs available");
899     return -1;
900 }
901 
902 static inline int
validate_watcher_id(PyInterpreterState * interp,int watcher_id)903 validate_watcher_id(PyInterpreterState *interp, int watcher_id)
904 {
905     if (watcher_id < 0 || watcher_id >= TYPE_MAX_WATCHERS) {
906         PyErr_Format(PyExc_ValueError, "Invalid type watcher ID %d", watcher_id);
907         return -1;
908     }
909     if (!interp->type_watchers[watcher_id]) {
910         PyErr_Format(PyExc_ValueError, "No type watcher set for ID %d", watcher_id);
911         return -1;
912     }
913     return 0;
914 }
915 
916 int
PyType_ClearWatcher(int watcher_id)917 PyType_ClearWatcher(int watcher_id)
918 {
919     PyInterpreterState *interp = _PyInterpreterState_GET();
920     if (validate_watcher_id(interp, watcher_id) < 0) {
921         return -1;
922     }
923     interp->type_watchers[watcher_id] = NULL;
924     return 0;
925 }
926 
927 static int assign_version_tag(PyInterpreterState *interp, PyTypeObject *type);
928 
929 int
PyType_Watch(int watcher_id,PyObject * obj)930 PyType_Watch(int watcher_id, PyObject* obj)
931 {
932     if (!PyType_Check(obj)) {
933         PyErr_SetString(PyExc_ValueError, "Cannot watch non-type");
934         return -1;
935     }
936     PyTypeObject *type = (PyTypeObject *)obj;
937     PyInterpreterState *interp = _PyInterpreterState_GET();
938     if (validate_watcher_id(interp, watcher_id) < 0) {
939         return -1;
940     }
941     // ensure we will get a callback on the next modification
942     BEGIN_TYPE_LOCK();
943     assign_version_tag(interp, type);
944     type->tp_watched |= (1 << watcher_id);
945     END_TYPE_LOCK();
946     return 0;
947 }
948 
949 int
PyType_Unwatch(int watcher_id,PyObject * obj)950 PyType_Unwatch(int watcher_id, PyObject* obj)
951 {
952     if (!PyType_Check(obj)) {
953         PyErr_SetString(PyExc_ValueError, "Cannot watch non-type");
954         return -1;
955     }
956     PyTypeObject *type = (PyTypeObject *)obj;
957     PyInterpreterState *interp = _PyInterpreterState_GET();
958     if (validate_watcher_id(interp, watcher_id)) {
959         return -1;
960     }
961     type->tp_watched &= ~(1 << watcher_id);
962     return 0;
963 }
964 
965 static void
set_version_unlocked(PyTypeObject * tp,unsigned int version)966 set_version_unlocked(PyTypeObject *tp, unsigned int version)
967 {
968     ASSERT_TYPE_LOCK_HELD();
969 #ifndef Py_GIL_DISABLED
970     if (version) {
971         tp->tp_versions_used++;
972     }
973 #else
974     if (version) {
975         _Py_atomic_add_uint16(&tp->tp_versions_used, 1);
976     }
977 #endif
978     FT_ATOMIC_STORE_UINT32_RELAXED(tp->tp_version_tag, version);
979 }
980 
981 static void
type_modified_unlocked(PyTypeObject * type)982 type_modified_unlocked(PyTypeObject *type)
983 {
984     /* Invalidate any cached data for the specified type and all
985        subclasses.  This function is called after the base
986        classes, mro, or attributes of the type are altered.
987 
988        Invariants:
989 
990        - before tp_version_tag can be set on a type,
991          it must first be set on all super types.
992 
993        This function clears the tp_version_tag of a
994        type (so it must first clear it on all subclasses).  The
995        tp_version_tag value is meaningless when equal to zero.
996        We don't assign new version tags eagerly, but only as
997        needed.
998      */
999     if (type->tp_version_tag == 0) {
1000         return;
1001     }
1002     // Cannot modify static builtin types.
1003     assert((type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) == 0);
1004 
1005     PyObject *subclasses = lookup_tp_subclasses(type);
1006     if (subclasses != NULL) {
1007         assert(PyDict_CheckExact(subclasses));
1008 
1009         Py_ssize_t i = 0;
1010         PyObject *ref;
1011         while (PyDict_Next(subclasses, &i, NULL, &ref)) {
1012             PyTypeObject *subclass = type_from_ref(ref);
1013             if (subclass == NULL) {
1014                 continue;
1015             }
1016             type_modified_unlocked(subclass);
1017             Py_DECREF(subclass);
1018         }
1019     }
1020 
1021     // Notify registered type watchers, if any
1022     if (type->tp_watched) {
1023         PyInterpreterState *interp = _PyInterpreterState_GET();
1024         int bits = type->tp_watched;
1025         int i = 0;
1026         while (bits) {
1027             assert(i < TYPE_MAX_WATCHERS);
1028             if (bits & 1) {
1029                 PyType_WatchCallback cb = interp->type_watchers[i];
1030                 if (cb && (cb(type) < 0)) {
1031                     PyErr_FormatUnraisable(
1032                         "Exception ignored in type watcher callback #%d for %R",
1033                         i, type);
1034                 }
1035             }
1036             i++;
1037             bits >>= 1;
1038         }
1039     }
1040 
1041     set_version_unlocked(type, 0); /* 0 is not a valid version tag */
1042     if (PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
1043         // This field *must* be invalidated if the type is modified (see the
1044         // comment on struct _specialization_cache):
1045         ((PyHeapTypeObject *)type)->_spec_cache.getitem = NULL;
1046     }
1047 }
1048 
1049 void
PyType_Modified(PyTypeObject * type)1050 PyType_Modified(PyTypeObject *type)
1051 {
1052     // Quick check without the lock held
1053     if (type->tp_version_tag == 0) {
1054         return;
1055     }
1056 
1057     BEGIN_TYPE_LOCK();
1058     type_modified_unlocked(type);
1059     END_TYPE_LOCK();
1060 }
1061 
1062 static int
1063 is_subtype_with_mro(PyObject *a_mro, PyTypeObject *a, PyTypeObject *b);
1064 
1065 static void
type_mro_modified(PyTypeObject * type,PyObject * bases)1066 type_mro_modified(PyTypeObject *type, PyObject *bases) {
1067     /*
1068        Check that all base classes or elements of the MRO of type are
1069        able to be cached.  This function is called after the base
1070        classes or mro of the type are altered.
1071 
1072        Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
1073        has a custom MRO that includes a type which is not officially
1074        super type, or if the type implements its own mro() method.
1075 
1076        Called from mro_internal, which will subsequently be called on
1077        each subclass when their mro is recursively updated.
1078      */
1079     Py_ssize_t i, n;
1080     int custom = !Py_IS_TYPE(type, &PyType_Type);
1081     int unbound;
1082 
1083     ASSERT_TYPE_LOCK_HELD();
1084     if (custom) {
1085         PyObject *mro_meth, *type_mro_meth;
1086         mro_meth = lookup_maybe_method(
1087             (PyObject *)type, &_Py_ID(mro), &unbound);
1088         if (mro_meth == NULL) {
1089             goto clear;
1090         }
1091         type_mro_meth = lookup_maybe_method(
1092             (PyObject *)&PyType_Type, &_Py_ID(mro), &unbound);
1093         if (type_mro_meth == NULL) {
1094             Py_DECREF(mro_meth);
1095             goto clear;
1096         }
1097         int custom_mro = (mro_meth != type_mro_meth);
1098         Py_DECREF(mro_meth);
1099         Py_DECREF(type_mro_meth);
1100         if (custom_mro) {
1101             goto clear;
1102         }
1103     }
1104     n = PyTuple_GET_SIZE(bases);
1105     for (i = 0; i < n; i++) {
1106         PyObject *b = PyTuple_GET_ITEM(bases, i);
1107         PyTypeObject *cls = _PyType_CAST(b);
1108 
1109         if (!is_subtype_with_mro(lookup_tp_mro(type), type, cls)) {
1110             goto clear;
1111         }
1112     }
1113     return;
1114 
1115  clear:
1116     assert(!(type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN));
1117     set_version_unlocked(type, 0); /* 0 is not a valid version tag */
1118     if (PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
1119         // This field *must* be invalidated if the type is modified (see the
1120         // comment on struct _specialization_cache):
1121         ((PyHeapTypeObject *)type)->_spec_cache.getitem = NULL;
1122     }
1123 }
1124 
1125 #define MAX_VERSIONS_PER_CLASS 1000
1126 
1127 static int
assign_version_tag(PyInterpreterState * interp,PyTypeObject * type)1128 assign_version_tag(PyInterpreterState *interp, PyTypeObject *type)
1129 {
1130     ASSERT_TYPE_LOCK_HELD();
1131 
1132     /* Ensure that the tp_version_tag is valid.
1133      * To respect the invariant, this must first be done on all super classes.
1134      * Return 0 if this cannot be done, 1 if tp_version_tag is set.
1135     */
1136     if (type->tp_version_tag != 0) {
1137         return 1;
1138     }
1139     if (!_PyType_HasFeature(type, Py_TPFLAGS_READY)) {
1140         return 0;
1141     }
1142     if (type->tp_versions_used >= MAX_VERSIONS_PER_CLASS) {
1143         return 0;
1144     }
1145 
1146     PyObject *bases = lookup_tp_bases(type);
1147     Py_ssize_t n = PyTuple_GET_SIZE(bases);
1148     for (Py_ssize_t i = 0; i < n; i++) {
1149         PyObject *b = PyTuple_GET_ITEM(bases, i);
1150         if (!assign_version_tag(interp, _PyType_CAST(b))) {
1151             return 0;
1152         }
1153     }
1154     if (type->tp_flags & Py_TPFLAGS_IMMUTABLETYPE) {
1155         /* static types */
1156         if (NEXT_GLOBAL_VERSION_TAG > _Py_MAX_GLOBAL_TYPE_VERSION_TAG) {
1157             /* We have run out of version numbers */
1158             return 0;
1159         }
1160         set_version_unlocked(type, NEXT_GLOBAL_VERSION_TAG++);
1161         assert (type->tp_version_tag <= _Py_MAX_GLOBAL_TYPE_VERSION_TAG);
1162     }
1163     else {
1164         /* heap types */
1165         if (NEXT_VERSION_TAG(interp) == 0) {
1166             /* We have run out of version numbers */
1167             return 0;
1168         }
1169         set_version_unlocked(type, NEXT_VERSION_TAG(interp)++);
1170         assert (type->tp_version_tag != 0);
1171     }
1172     return 1;
1173 }
1174 
PyUnstable_Type_AssignVersionTag(PyTypeObject * type)1175 int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
1176 {
1177     PyInterpreterState *interp = _PyInterpreterState_GET();
1178     int assigned;
1179     BEGIN_TYPE_LOCK();
1180     assigned = assign_version_tag(interp, type);
1181     END_TYPE_LOCK();
1182     return assigned;
1183 }
1184 
1185 
1186 static PyMemberDef type_members[] = {
1187     {"__basicsize__", Py_T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),Py_READONLY},
1188     {"__itemsize__", Py_T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), Py_READONLY},
1189     {"__flags__", Py_T_ULONG, offsetof(PyTypeObject, tp_flags), Py_READONLY},
1190     /* Note that this value is misleading for static builtin types,
1191        since the memory at this offset will always be NULL. */
1192     {"__weakrefoffset__", Py_T_PYSSIZET,
1193      offsetof(PyTypeObject, tp_weaklistoffset), Py_READONLY},
1194     {"__base__", _Py_T_OBJECT, offsetof(PyTypeObject, tp_base), Py_READONLY},
1195     {"__dictoffset__", Py_T_PYSSIZET,
1196      offsetof(PyTypeObject, tp_dictoffset), Py_READONLY},
1197     {0}
1198 };
1199 
1200 static int
check_set_special_type_attr(PyTypeObject * type,PyObject * value,const char * name)1201 check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
1202 {
1203     if (_PyType_HasFeature(type, Py_TPFLAGS_IMMUTABLETYPE)) {
1204         PyErr_Format(PyExc_TypeError,
1205                      "cannot set '%s' attribute of immutable type '%s'",
1206                      name, type->tp_name);
1207         return 0;
1208     }
1209     if (!value) {
1210         PyErr_Format(PyExc_TypeError,
1211                      "cannot delete '%s' attribute of immutable type '%s'",
1212                      name, type->tp_name);
1213         return 0;
1214     }
1215 
1216     if (PySys_Audit("object.__setattr__", "OsO",
1217                     type, name, value) < 0) {
1218         return 0;
1219     }
1220 
1221     return 1;
1222 }
1223 
1224 const char *
_PyType_Name(PyTypeObject * type)1225 _PyType_Name(PyTypeObject *type)
1226 {
1227     assert(type->tp_name != NULL);
1228     const char *s = strrchr(type->tp_name, '.');
1229     if (s == NULL) {
1230         s = type->tp_name;
1231     }
1232     else {
1233         s++;
1234     }
1235     return s;
1236 }
1237 
1238 static PyObject *
type_name(PyTypeObject * type,void * context)1239 type_name(PyTypeObject *type, void *context)
1240 {
1241     if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1242         PyHeapTypeObject* et = (PyHeapTypeObject*)type;
1243 
1244         return Py_NewRef(et->ht_name);
1245     }
1246     else {
1247         return PyUnicode_FromString(_PyType_Name(type));
1248     }
1249 }
1250 
1251 static PyObject *
type_qualname(PyTypeObject * type,void * context)1252 type_qualname(PyTypeObject *type, void *context)
1253 {
1254     if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1255         PyHeapTypeObject* et = (PyHeapTypeObject*)type;
1256         return Py_NewRef(et->ht_qualname);
1257     }
1258     else {
1259         return PyUnicode_FromString(_PyType_Name(type));
1260     }
1261 }
1262 
1263 static int
type_set_name(PyTypeObject * type,PyObject * value,void * context)1264 type_set_name(PyTypeObject *type, PyObject *value, void *context)
1265 {
1266     const char *tp_name;
1267     Py_ssize_t name_size;
1268 
1269     if (!check_set_special_type_attr(type, value, "__name__"))
1270         return -1;
1271     if (!PyUnicode_Check(value)) {
1272         PyErr_Format(PyExc_TypeError,
1273                      "can only assign string to %s.__name__, not '%s'",
1274                      type->tp_name, Py_TYPE(value)->tp_name);
1275         return -1;
1276     }
1277 
1278     tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
1279     if (tp_name == NULL)
1280         return -1;
1281     if (strlen(tp_name) != (size_t)name_size) {
1282         PyErr_SetString(PyExc_ValueError,
1283                         "type name must not contain null characters");
1284         return -1;
1285     }
1286 
1287     type->tp_name = tp_name;
1288     Py_SETREF(((PyHeapTypeObject*)type)->ht_name, Py_NewRef(value));
1289 
1290     return 0;
1291 }
1292 
1293 static int
type_set_qualname(PyTypeObject * type,PyObject * value,void * context)1294 type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
1295 {
1296     PyHeapTypeObject* et;
1297 
1298     if (!check_set_special_type_attr(type, value, "__qualname__"))
1299         return -1;
1300     if (!PyUnicode_Check(value)) {
1301         PyErr_Format(PyExc_TypeError,
1302                      "can only assign string to %s.__qualname__, not '%s'",
1303                      type->tp_name, Py_TYPE(value)->tp_name);
1304         return -1;
1305     }
1306 
1307     et = (PyHeapTypeObject*)type;
1308     Py_SETREF(et->ht_qualname, Py_NewRef(value));
1309     return 0;
1310 }
1311 
1312 static PyObject *
type_module(PyTypeObject * type)1313 type_module(PyTypeObject *type)
1314 {
1315     PyObject *mod;
1316     if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1317         PyObject *dict = lookup_tp_dict(type);
1318         if (PyDict_GetItemRef(dict, &_Py_ID(__module__), &mod) == 0) {
1319             PyErr_Format(PyExc_AttributeError, "__module__");
1320         }
1321     }
1322     else {
1323         const char *s = strrchr(type->tp_name, '.');
1324         if (s != NULL) {
1325             mod = PyUnicode_FromStringAndSize(
1326                 type->tp_name, (Py_ssize_t)(s - type->tp_name));
1327             if (mod != NULL) {
1328                 PyInterpreterState *interp = _PyInterpreterState_GET();
1329                 _PyUnicode_InternMortal(interp, &mod);
1330             }
1331         }
1332         else {
1333             mod = &_Py_ID(builtins);
1334         }
1335     }
1336     return mod;
1337 }
1338 
1339 static PyObject *
type_get_module(PyTypeObject * type,void * context)1340 type_get_module(PyTypeObject *type, void *context)
1341 {
1342     return type_module(type);
1343 }
1344 
1345 static int
type_set_module(PyTypeObject * type,PyObject * value,void * context)1346 type_set_module(PyTypeObject *type, PyObject *value, void *context)
1347 {
1348     if (!check_set_special_type_attr(type, value, "__module__"))
1349         return -1;
1350 
1351     PyType_Modified(type);
1352 
1353     PyObject *dict = lookup_tp_dict(type);
1354     if (PyDict_Pop(dict, &_Py_ID(__firstlineno__), NULL) < 0) {
1355         return -1;
1356     }
1357     return PyDict_SetItem(dict, &_Py_ID(__module__), value);
1358 }
1359 
1360 
1361 PyObject *
_PyType_GetFullyQualifiedName(PyTypeObject * type,char sep)1362 _PyType_GetFullyQualifiedName(PyTypeObject *type, char sep)
1363 {
1364     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1365         return PyUnicode_FromString(type->tp_name);
1366     }
1367 
1368     PyObject *qualname = type_qualname(type, NULL);
1369     if (qualname == NULL) {
1370         return NULL;
1371     }
1372 
1373     PyObject *module = type_module(type);
1374     if (module == NULL) {
1375         Py_DECREF(qualname);
1376         return NULL;
1377     }
1378 
1379     PyObject *result;
1380     if (PyUnicode_Check(module)
1381         && !_PyUnicode_Equal(module, &_Py_ID(builtins))
1382         && !_PyUnicode_Equal(module, &_Py_ID(__main__)))
1383     {
1384         result = PyUnicode_FromFormat("%U%c%U", module, sep, qualname);
1385     }
1386     else {
1387         result = Py_NewRef(qualname);
1388     }
1389     Py_DECREF(module);
1390     Py_DECREF(qualname);
1391     return result;
1392 }
1393 
1394 PyObject *
PyType_GetFullyQualifiedName(PyTypeObject * type)1395 PyType_GetFullyQualifiedName(PyTypeObject *type)
1396 {
1397     return _PyType_GetFullyQualifiedName(type, '.');
1398 }
1399 
1400 
1401 static PyObject *
type_abstractmethods(PyTypeObject * type,void * context)1402 type_abstractmethods(PyTypeObject *type, void *context)
1403 {
1404     PyObject *mod = NULL;
1405     /* type itself has an __abstractmethods__ descriptor (this). Don't return
1406        that. */
1407     if (type == &PyType_Type) {
1408         PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__abstractmethods__));
1409     }
1410     else {
1411         PyObject *dict = lookup_tp_dict(type);
1412         if (PyDict_GetItemRef(dict, &_Py_ID(__abstractmethods__), &mod) == 0) {
1413             PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__abstractmethods__));
1414         }
1415     }
1416     return mod;
1417 }
1418 
1419 static int
type_set_abstractmethods(PyTypeObject * type,PyObject * value,void * context)1420 type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
1421 {
1422     /* __abstractmethods__ should only be set once on a type, in
1423        abc.ABCMeta.__new__, so this function doesn't do anything
1424        special to update subclasses.
1425     */
1426     int abstract, res;
1427     PyObject *dict = lookup_tp_dict(type);
1428     if (value != NULL) {
1429         abstract = PyObject_IsTrue(value);
1430         if (abstract < 0)
1431             return -1;
1432         res = PyDict_SetItem(dict, &_Py_ID(__abstractmethods__), value);
1433     }
1434     else {
1435         abstract = 0;
1436         res = PyDict_Pop(dict, &_Py_ID(__abstractmethods__), NULL);
1437         if (res == 0) {
1438             PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__abstractmethods__));
1439             return -1;
1440         }
1441     }
1442     if (res < 0) {
1443         return -1;
1444     }
1445 
1446     PyType_Modified(type);
1447     if (abstract)
1448         type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
1449     else
1450         type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
1451     return 0;
1452 }
1453 
1454 static PyObject *
type_get_bases(PyTypeObject * type,void * context)1455 type_get_bases(PyTypeObject *type, void *context)
1456 {
1457     PyObject *bases = _PyType_GetBases(type);
1458     if (bases == NULL) {
1459         Py_RETURN_NONE;
1460     }
1461     return bases;
1462 }
1463 
1464 static PyObject *
type_get_mro(PyTypeObject * type,void * context)1465 type_get_mro(PyTypeObject *type, void *context)
1466 {
1467     PyObject *mro;
1468 
1469     BEGIN_TYPE_LOCK();
1470     mro = lookup_tp_mro(type);
1471     if (mro == NULL) {
1472         mro = Py_None;
1473     } else {
1474         Py_INCREF(mro);
1475     }
1476 
1477     END_TYPE_LOCK();
1478     return mro;
1479 }
1480 
1481 static PyTypeObject *best_base(PyObject *);
1482 static int mro_internal(PyTypeObject *, PyObject **);
1483 static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
1484 static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
1485 static int add_subclass(PyTypeObject*, PyTypeObject*);
1486 static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
1487 static void remove_subclass(PyTypeObject *, PyTypeObject *);
1488 static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
1489 static void update_all_slots(PyTypeObject *);
1490 
1491 typedef int (*update_callback)(PyTypeObject *, void *);
1492 static int update_subclasses(PyTypeObject *type, PyObject *attr_name,
1493                              update_callback callback, void *data);
1494 static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
1495                                    update_callback callback, void *data);
1496 
1497 static int
mro_hierarchy(PyTypeObject * type,PyObject * temp)1498 mro_hierarchy(PyTypeObject *type, PyObject *temp)
1499 {
1500     ASSERT_TYPE_LOCK_HELD();
1501 
1502     PyObject *old_mro;
1503     int res = mro_internal(type, &old_mro);
1504     if (res <= 0) {
1505         /* error / reentrance */
1506         return res;
1507     }
1508     PyObject *new_mro = lookup_tp_mro(type);
1509 
1510     PyObject *tuple;
1511     if (old_mro != NULL) {
1512         tuple = PyTuple_Pack(3, type, new_mro, old_mro);
1513     }
1514     else {
1515         tuple = PyTuple_Pack(2, type, new_mro);
1516     }
1517 
1518     if (tuple != NULL) {
1519         res = PyList_Append(temp, tuple);
1520     }
1521     else {
1522         res = -1;
1523     }
1524     Py_XDECREF(tuple);
1525 
1526     if (res < 0) {
1527         set_tp_mro(type, old_mro, 0);
1528         Py_DECREF(new_mro);
1529         return -1;
1530     }
1531     Py_XDECREF(old_mro);
1532 
1533     // Avoid creating an empty list if there is no subclass
1534     if (_PyType_HasSubclasses(type)) {
1535         /* Obtain a copy of subclasses list to iterate over.
1536 
1537            Otherwise type->tp_subclasses might be altered
1538            in the middle of the loop, for example, through a custom mro(),
1539            by invoking type_set_bases on some subclass of the type
1540            which in turn calls remove_subclass/add_subclass on this type.
1541 
1542            Finally, this makes things simple avoiding the need to deal
1543            with dictionary iterators and weak references.
1544         */
1545         PyObject *subclasses = _PyType_GetSubclasses(type);
1546         if (subclasses == NULL) {
1547             return -1;
1548         }
1549 
1550         Py_ssize_t n = PyList_GET_SIZE(subclasses);
1551         for (Py_ssize_t i = 0; i < n; i++) {
1552             PyTypeObject *subclass = _PyType_CAST(PyList_GET_ITEM(subclasses, i));
1553             res = mro_hierarchy(subclass, temp);
1554             if (res < 0) {
1555                 break;
1556             }
1557         }
1558         Py_DECREF(subclasses);
1559     }
1560 
1561     return res;
1562 }
1563 
1564 static int
type_set_bases_unlocked(PyTypeObject * type,PyObject * new_bases,void * context)1565 type_set_bases_unlocked(PyTypeObject *type, PyObject *new_bases, void *context)
1566 {
1567     // Check arguments
1568     if (!check_set_special_type_attr(type, new_bases, "__bases__")) {
1569         return -1;
1570     }
1571     assert(new_bases != NULL);
1572 
1573     if (!PyTuple_Check(new_bases)) {
1574         PyErr_Format(PyExc_TypeError,
1575              "can only assign tuple to %s.__bases__, not %s",
1576                  type->tp_name, Py_TYPE(new_bases)->tp_name);
1577         return -1;
1578     }
1579     if (PyTuple_GET_SIZE(new_bases) == 0) {
1580         PyErr_Format(PyExc_TypeError,
1581              "can only assign non-empty tuple to %s.__bases__, not ()",
1582                  type->tp_name);
1583         return -1;
1584     }
1585     Py_ssize_t n = PyTuple_GET_SIZE(new_bases);
1586     for (Py_ssize_t i = 0; i < n; i++) {
1587         PyObject *ob = PyTuple_GET_ITEM(new_bases, i);
1588         if (!PyType_Check(ob)) {
1589             PyErr_Format(PyExc_TypeError,
1590                          "%s.__bases__ must be tuple of classes, not '%s'",
1591                          type->tp_name, Py_TYPE(ob)->tp_name);
1592             return -1;
1593         }
1594         PyTypeObject *base = (PyTypeObject*)ob;
1595 
1596         if (is_subtype_with_mro(lookup_tp_mro(base), base, type) ||
1597             /* In case of reentering here again through a custom mro()
1598                the above check is not enough since it relies on
1599                base->tp_mro which would gonna be updated inside
1600                mro_internal only upon returning from the mro().
1601 
1602                However, base->tp_base has already been assigned (see
1603                below), which in turn may cause an inheritance cycle
1604                through tp_base chain.  And this is definitely
1605                not what you want to ever happen.  */
1606             (lookup_tp_mro(base) != NULL
1607              && type_is_subtype_base_chain(base, type)))
1608         {
1609             PyErr_SetString(PyExc_TypeError,
1610                             "a __bases__ item causes an inheritance cycle");
1611             return -1;
1612         }
1613     }
1614 
1615     // Compute the new MRO and the new base class
1616     PyTypeObject *new_base = best_base(new_bases);
1617     if (new_base == NULL)
1618         return -1;
1619 
1620     if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) {
1621         return -1;
1622     }
1623 
1624     PyObject *old_bases = lookup_tp_bases(type);
1625     assert(old_bases != NULL);
1626     PyTypeObject *old_base = type->tp_base;
1627 
1628     set_tp_bases(type, Py_NewRef(new_bases), 0);
1629     type->tp_base = (PyTypeObject *)Py_NewRef(new_base);
1630 
1631     PyObject *temp = PyList_New(0);
1632     if (temp == NULL) {
1633         goto bail;
1634     }
1635     if (mro_hierarchy(type, temp) < 0) {
1636         goto undo;
1637     }
1638     Py_DECREF(temp);
1639 
1640     /* Take no action in case if type->tp_bases has been replaced
1641        through reentrance.  */
1642     int res;
1643     if (lookup_tp_bases(type) == new_bases) {
1644         /* any base that was in __bases__ but now isn't, we
1645            need to remove |type| from its tp_subclasses.
1646            conversely, any class now in __bases__ that wasn't
1647            needs to have |type| added to its subclasses. */
1648 
1649         /* for now, sod that: just remove from all old_bases,
1650            add to all new_bases */
1651         remove_all_subclasses(type, old_bases);
1652         res = add_all_subclasses(type, new_bases);
1653         update_all_slots(type);
1654     }
1655     else {
1656         res = 0;
1657     }
1658 
1659     RARE_EVENT_INC(set_bases);
1660     Py_DECREF(old_bases);
1661     Py_DECREF(old_base);
1662 
1663     assert(_PyType_CheckConsistency(type));
1664     return res;
1665 
1666   undo:
1667     n = PyList_GET_SIZE(temp);
1668     for (Py_ssize_t i = n - 1; i >= 0; i--) {
1669         PyTypeObject *cls;
1670         PyObject *new_mro, *old_mro = NULL;
1671 
1672         PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
1673                           "", 2, 3, &cls, &new_mro, &old_mro);
1674         /* Do not rollback if cls has a newer version of MRO.  */
1675         if (lookup_tp_mro(cls) == new_mro) {
1676             set_tp_mro(cls, Py_XNewRef(old_mro), 0);
1677             Py_DECREF(new_mro);
1678         }
1679     }
1680     Py_DECREF(temp);
1681 
1682   bail:
1683     if (lookup_tp_bases(type) == new_bases) {
1684         assert(type->tp_base == new_base);
1685 
1686         set_tp_bases(type, old_bases, 0);
1687         type->tp_base = old_base;
1688 
1689         Py_DECREF(new_bases);
1690         Py_DECREF(new_base);
1691     }
1692     else {
1693         Py_DECREF(old_bases);
1694         Py_DECREF(old_base);
1695     }
1696 
1697     assert(_PyType_CheckConsistency(type));
1698     return -1;
1699 }
1700 
1701 static int
type_set_bases(PyTypeObject * type,PyObject * new_bases,void * context)1702 type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
1703 {
1704     int res;
1705     BEGIN_TYPE_LOCK();
1706     res = type_set_bases_unlocked(type, new_bases, context);
1707     END_TYPE_LOCK();
1708     return res;
1709 }
1710 
1711 static PyObject *
type_dict(PyTypeObject * type,void * context)1712 type_dict(PyTypeObject *type, void *context)
1713 {
1714     PyObject *dict = lookup_tp_dict(type);
1715     if (dict == NULL) {
1716         Py_RETURN_NONE;
1717     }
1718     return PyDictProxy_New(dict);
1719 }
1720 
1721 static PyObject *
type_get_doc(PyTypeObject * type,void * context)1722 type_get_doc(PyTypeObject *type, void *context)
1723 {
1724     PyObject *result;
1725     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
1726         return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
1727     }
1728     PyObject *dict = lookup_tp_dict(type);
1729     if (PyDict_GetItemRef(dict, &_Py_ID(__doc__), &result) == 0) {
1730         result = Py_NewRef(Py_None);
1731     }
1732     else if (result) {
1733         descrgetfunc descr_get = Py_TYPE(result)->tp_descr_get;
1734         if (descr_get) {
1735             Py_SETREF(result, descr_get(result, NULL, (PyObject *)type));
1736         }
1737     }
1738     return result;
1739 }
1740 
1741 static PyObject *
type_get_text_signature(PyTypeObject * type,void * context)1742 type_get_text_signature(PyTypeObject *type, void *context)
1743 {
1744     return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc, 0);
1745 }
1746 
1747 static int
type_set_doc(PyTypeObject * type,PyObject * value,void * context)1748 type_set_doc(PyTypeObject *type, PyObject *value, void *context)
1749 {
1750     if (!check_set_special_type_attr(type, value, "__doc__"))
1751         return -1;
1752     PyType_Modified(type);
1753     PyObject *dict = lookup_tp_dict(type);
1754     return PyDict_SetItem(dict, &_Py_ID(__doc__), value);
1755 }
1756 
1757 static PyObject *
type_get_annotations(PyTypeObject * type,void * context)1758 type_get_annotations(PyTypeObject *type, void *context)
1759 {
1760     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1761         PyErr_Format(PyExc_AttributeError, "type object '%s' has no attribute '__annotations__'", type->tp_name);
1762         return NULL;
1763     }
1764 
1765     PyObject *annotations;
1766     PyObject *dict = lookup_tp_dict(type);
1767     if (PyDict_GetItemRef(dict, &_Py_ID(__annotations__), &annotations) < 0) {
1768         return NULL;
1769     }
1770     if (annotations) {
1771         descrgetfunc get = Py_TYPE(annotations)->tp_descr_get;
1772         if (get) {
1773             Py_SETREF(annotations, get(annotations, NULL, (PyObject *)type));
1774         }
1775     }
1776     else {
1777         annotations = PyDict_New();
1778         if (annotations) {
1779             int result = PyDict_SetItem(
1780                     dict, &_Py_ID(__annotations__), annotations);
1781             if (result) {
1782                 Py_CLEAR(annotations);
1783             } else {
1784                 PyType_Modified(type);
1785             }
1786         }
1787     }
1788     return annotations;
1789 }
1790 
1791 static int
type_set_annotations(PyTypeObject * type,PyObject * value,void * context)1792 type_set_annotations(PyTypeObject *type, PyObject *value, void *context)
1793 {
1794     if (_PyType_HasFeature(type, Py_TPFLAGS_IMMUTABLETYPE)) {
1795         PyErr_Format(PyExc_TypeError,
1796                      "cannot set '__annotations__' attribute of immutable type '%s'",
1797                      type->tp_name);
1798         return -1;
1799     }
1800 
1801     int result;
1802     PyObject *dict = lookup_tp_dict(type);
1803     if (value != NULL) {
1804         /* set */
1805         result = PyDict_SetItem(dict, &_Py_ID(__annotations__), value);
1806     } else {
1807         /* delete */
1808         result = PyDict_Pop(dict, &_Py_ID(__annotations__), NULL);
1809         if (result == 0) {
1810             PyErr_SetString(PyExc_AttributeError, "__annotations__");
1811             return -1;
1812         }
1813     }
1814     if (result < 0) {
1815         return -1;
1816     }
1817 
1818     PyType_Modified(type);
1819     return 0;
1820 }
1821 
1822 static PyObject *
type_get_type_params(PyTypeObject * type,void * context)1823 type_get_type_params(PyTypeObject *type, void *context)
1824 {
1825     if (type == &PyType_Type) {
1826         return PyTuple_New(0);
1827     }
1828 
1829     PyObject *params;
1830     if (PyDict_GetItemRef(lookup_tp_dict(type), &_Py_ID(__type_params__), &params) == 0) {
1831         return PyTuple_New(0);
1832     }
1833     return params;
1834 }
1835 
1836 static int
type_set_type_params(PyTypeObject * type,PyObject * value,void * context)1837 type_set_type_params(PyTypeObject *type, PyObject *value, void *context)
1838 {
1839     if (!check_set_special_type_attr(type, value, "__type_params__")) {
1840         return -1;
1841     }
1842 
1843     PyObject *dict = lookup_tp_dict(type);
1844     int result = PyDict_SetItem(dict, &_Py_ID(__type_params__), value);
1845 
1846     if (result == 0) {
1847         PyType_Modified(type);
1848     }
1849     return result;
1850 }
1851 
1852 
1853 /*[clinic input]
1854 type.__instancecheck__ -> bool
1855 
1856     instance: object
1857     /
1858 
1859 Check if an object is an instance.
1860 [clinic start generated code]*/
1861 
1862 static int
type___instancecheck___impl(PyTypeObject * self,PyObject * instance)1863 type___instancecheck___impl(PyTypeObject *self, PyObject *instance)
1864 /*[clinic end generated code: output=08b6bf5f591c3618 input=cdbfeaee82c01a0f]*/
1865 {
1866     return _PyObject_RealIsInstance(instance, (PyObject *)self);
1867 }
1868 
1869 /*[clinic input]
1870 type.__subclasscheck__ -> bool
1871 
1872     subclass: object
1873     /
1874 
1875 Check if a class is a subclass.
1876 [clinic start generated code]*/
1877 
1878 static int
type___subclasscheck___impl(PyTypeObject * self,PyObject * subclass)1879 type___subclasscheck___impl(PyTypeObject *self, PyObject *subclass)
1880 /*[clinic end generated code: output=97a4e51694500941 input=071b2ca9e03355f4]*/
1881 {
1882     return _PyObject_RealIsSubclass(subclass, (PyObject *)self);
1883 }
1884 
1885 
1886 static PyGetSetDef type_getsets[] = {
1887     {"__name__", (getter)type_name, (setter)type_set_name, NULL},
1888     {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
1889     {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
1890     {"__mro__", (getter)type_get_mro, NULL, NULL},
1891     {"__module__", (getter)type_get_module, (setter)type_set_module, NULL},
1892     {"__abstractmethods__", (getter)type_abstractmethods,
1893      (setter)type_set_abstractmethods, NULL},
1894     {"__dict__",  (getter)type_dict,  NULL, NULL},
1895     {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
1896     {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
1897     {"__annotations__", (getter)type_get_annotations, (setter)type_set_annotations, NULL},
1898     {"__type_params__", (getter)type_get_type_params, (setter)type_set_type_params, NULL},
1899     {0}
1900 };
1901 
1902 static PyObject *
type_repr(PyObject * self)1903 type_repr(PyObject *self)
1904 {
1905     PyTypeObject *type = (PyTypeObject *)self;
1906     if (type->tp_name == NULL) {
1907         // type_repr() called before the type is fully initialized
1908         // by PyType_Ready().
1909         return PyUnicode_FromFormat("<class at %p>", type);
1910     }
1911 
1912     PyObject *mod = type_module(type);
1913     if (mod == NULL) {
1914         PyErr_Clear();
1915     }
1916     else if (!PyUnicode_Check(mod)) {
1917         Py_CLEAR(mod);
1918     }
1919 
1920     PyObject *name = type_qualname(type, NULL);
1921     if (name == NULL) {
1922         Py_XDECREF(mod);
1923         return NULL;
1924     }
1925 
1926     PyObject *result;
1927     if (mod != NULL && !_PyUnicode_Equal(mod, &_Py_ID(builtins))) {
1928         result = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
1929     }
1930     else {
1931         result = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
1932     }
1933     Py_XDECREF(mod);
1934     Py_DECREF(name);
1935 
1936     return result;
1937 }
1938 
1939 static PyObject *
type_call(PyObject * self,PyObject * args,PyObject * kwds)1940 type_call(PyObject *self, PyObject *args, PyObject *kwds)
1941 {
1942     PyTypeObject *type = (PyTypeObject *)self;
1943     PyObject *obj;
1944     PyThreadState *tstate = _PyThreadState_GET();
1945 
1946 #ifdef Py_DEBUG
1947     /* type_call() must not be called with an exception set,
1948        because it can clear it (directly or indirectly) and so the
1949        caller loses its exception */
1950     assert(!_PyErr_Occurred(tstate));
1951 #endif
1952 
1953     /* Special case: type(x) should return Py_TYPE(x) */
1954     /* We only want type itself to accept the one-argument form (#27157) */
1955     if (type == &PyType_Type) {
1956         assert(args != NULL && PyTuple_Check(args));
1957         assert(kwds == NULL || PyDict_Check(kwds));
1958         Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1959 
1960         if (nargs == 1 && (kwds == NULL || !PyDict_GET_SIZE(kwds))) {
1961             obj = (PyObject *) Py_TYPE(PyTuple_GET_ITEM(args, 0));
1962             return Py_NewRef(obj);
1963         }
1964 
1965         /* SF bug 475327 -- if that didn't trigger, we need 3
1966            arguments. But PyArg_ParseTuple in type_new may give
1967            a msg saying type() needs exactly 3. */
1968         if (nargs != 3) {
1969             PyErr_SetString(PyExc_TypeError,
1970                             "type() takes 1 or 3 arguments");
1971             return NULL;
1972         }
1973     }
1974 
1975     if (type->tp_new == NULL) {
1976         _PyErr_Format(tstate, PyExc_TypeError,
1977                       "cannot create '%s' instances", type->tp_name);
1978         return NULL;
1979     }
1980 
1981     obj = type->tp_new(type, args, kwds);
1982     obj = _Py_CheckFunctionResult(tstate, (PyObject*)type, obj, NULL);
1983     if (obj == NULL)
1984         return NULL;
1985 
1986     /* If the returned object is not an instance of type,
1987        it won't be initialized. */
1988     if (!PyObject_TypeCheck(obj, type))
1989         return obj;
1990 
1991     type = Py_TYPE(obj);
1992     if (type->tp_init != NULL) {
1993         int res = type->tp_init(obj, args, kwds);
1994         if (res < 0) {
1995             assert(_PyErr_Occurred(tstate));
1996             Py_SETREF(obj, NULL);
1997         }
1998         else {
1999             assert(!_PyErr_Occurred(tstate));
2000         }
2001     }
2002     return obj;
2003 }
2004 
2005 PyObject *
_PyType_NewManagedObject(PyTypeObject * type)2006 _PyType_NewManagedObject(PyTypeObject *type)
2007 {
2008     assert(type->tp_flags & Py_TPFLAGS_INLINE_VALUES);
2009     assert(_PyType_IS_GC(type));
2010     assert(type->tp_new == PyBaseObject_Type.tp_new);
2011     assert(type->tp_alloc == PyType_GenericAlloc);
2012     assert(type->tp_itemsize == 0);
2013     PyObject *obj = PyType_GenericAlloc(type, 0);
2014     if (obj == NULL) {
2015         return PyErr_NoMemory();
2016     }
2017     return obj;
2018 }
2019 
2020 PyObject *
_PyType_AllocNoTrack(PyTypeObject * type,Py_ssize_t nitems)2021 _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems)
2022 {
2023     PyObject *obj;
2024     /* The +1 on nitems is needed for most types but not all. We could save a
2025      * bit of space by allocating one less item in certain cases, depending on
2026      * the type. However, given the extra complexity (e.g. an additional type
2027      * flag to indicate when that is safe) it does not seem worth the memory
2028      * savings. An example type that doesn't need the +1 is a subclass of
2029      * tuple. See GH-100659 and GH-81381. */
2030     size_t size = _PyObject_VAR_SIZE(type, nitems+1);
2031 
2032     const size_t presize = _PyType_PreHeaderSize(type);
2033     if (type->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
2034         assert(type->tp_itemsize == 0);
2035         size += _PyInlineValuesSize(type);
2036     }
2037     char *alloc = _PyObject_MallocWithType(type, size + presize);
2038     if (alloc  == NULL) {
2039         return PyErr_NoMemory();
2040     }
2041     obj = (PyObject *)(alloc + presize);
2042     if (presize) {
2043         ((PyObject **)alloc)[0] = NULL;
2044         ((PyObject **)alloc)[1] = NULL;
2045     }
2046     if (PyType_IS_GC(type)) {
2047         _PyObject_GC_Link(obj);
2048     }
2049     memset(obj, '\0', size);
2050 
2051     if (type->tp_itemsize == 0) {
2052         _PyObject_Init(obj, type);
2053     }
2054     else {
2055         _PyObject_InitVar((PyVarObject *)obj, type, nitems);
2056     }
2057     if (type->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
2058         _PyObject_InitInlineValues(obj, type);
2059     }
2060     return obj;
2061 }
2062 
2063 PyObject *
PyType_GenericAlloc(PyTypeObject * type,Py_ssize_t nitems)2064 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
2065 {
2066     PyObject *obj = _PyType_AllocNoTrack(type, nitems);
2067     if (obj == NULL) {
2068         return NULL;
2069     }
2070 
2071     if (_PyType_IS_GC(type)) {
2072         _PyObject_GC_TRACK(obj);
2073     }
2074     return obj;
2075 }
2076 
2077 PyObject *
PyType_GenericNew(PyTypeObject * type,PyObject * args,PyObject * kwds)2078 PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
2079 {
2080     return type->tp_alloc(type, 0);
2081 }
2082 
2083 /* Helpers for subtyping */
2084 
2085 static inline PyMemberDef *
_PyHeapType_GET_MEMBERS(PyHeapTypeObject * type)2086 _PyHeapType_GET_MEMBERS(PyHeapTypeObject* type)
2087 {
2088     return PyObject_GetItemData((PyObject *)type);
2089 }
2090 
2091 static int
traverse_slots(PyTypeObject * type,PyObject * self,visitproc visit,void * arg)2092 traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
2093 {
2094     Py_ssize_t i, n;
2095     PyMemberDef *mp;
2096 
2097     n = Py_SIZE(type);
2098     mp = _PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
2099     for (i = 0; i < n; i++, mp++) {
2100         if (mp->type == Py_T_OBJECT_EX) {
2101             char *addr = (char *)self + mp->offset;
2102             PyObject *obj = *(PyObject **)addr;
2103             if (obj != NULL) {
2104                 int err = visit(obj, arg);
2105                 if (err)
2106                     return err;
2107             }
2108         }
2109     }
2110     return 0;
2111 }
2112 
2113 static int
subtype_traverse(PyObject * self,visitproc visit,void * arg)2114 subtype_traverse(PyObject *self, visitproc visit, void *arg)
2115 {
2116     PyTypeObject *type, *base;
2117     traverseproc basetraverse;
2118 
2119     /* Find the nearest base with a different tp_traverse,
2120        and traverse slots while we're at it */
2121     type = Py_TYPE(self);
2122     base = type;
2123     while ((basetraverse = base->tp_traverse) == subtype_traverse) {
2124         if (Py_SIZE(base)) {
2125             int err = traverse_slots(base, self, visit, arg);
2126             if (err)
2127                 return err;
2128         }
2129         base = base->tp_base;
2130         assert(base);
2131     }
2132 
2133     if (type->tp_dictoffset != base->tp_dictoffset) {
2134         assert(base->tp_dictoffset == 0);
2135         if (type->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
2136             assert(type->tp_dictoffset == -1);
2137             int err = PyObject_VisitManagedDict(self, visit, arg);
2138             if (err) {
2139                 return err;
2140             }
2141         }
2142         else {
2143             PyObject **dictptr = _PyObject_ComputedDictPointer(self);
2144             if (dictptr && *dictptr) {
2145                 Py_VISIT(*dictptr);
2146             }
2147         }
2148     }
2149 
2150     if (type->tp_flags & Py_TPFLAGS_HEAPTYPE
2151         && (!basetraverse || !(base->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
2152         /* For a heaptype, the instances count as references
2153            to the type.          Traverse the type so the collector
2154            can find cycles involving this link.
2155            Skip this visit if basetraverse belongs to a heap type: in that
2156            case, basetraverse will visit the type when we call it later.
2157            */
2158         Py_VISIT(type);
2159     }
2160 
2161     if (basetraverse)
2162         return basetraverse(self, visit, arg);
2163     return 0;
2164 }
2165 
2166 static void
clear_slots(PyTypeObject * type,PyObject * self)2167 clear_slots(PyTypeObject *type, PyObject *self)
2168 {
2169     Py_ssize_t i, n;
2170     PyMemberDef *mp;
2171 
2172     n = Py_SIZE(type);
2173     mp = _PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
2174     for (i = 0; i < n; i++, mp++) {
2175         if (mp->type == Py_T_OBJECT_EX && !(mp->flags & Py_READONLY)) {
2176             char *addr = (char *)self + mp->offset;
2177             PyObject *obj = *(PyObject **)addr;
2178             if (obj != NULL) {
2179                 *(PyObject **)addr = NULL;
2180                 Py_DECREF(obj);
2181             }
2182         }
2183     }
2184 }
2185 
2186 static int
subtype_clear(PyObject * self)2187 subtype_clear(PyObject *self)
2188 {
2189     PyTypeObject *type, *base;
2190     inquiry baseclear;
2191 
2192     /* Find the nearest base with a different tp_clear
2193        and clear slots while we're at it */
2194     type = Py_TYPE(self);
2195     base = type;
2196     while ((baseclear = base->tp_clear) == subtype_clear) {
2197         if (Py_SIZE(base))
2198             clear_slots(base, self);
2199         base = base->tp_base;
2200         assert(base);
2201     }
2202 
2203     /* Clear the instance dict (if any), to break cycles involving only
2204        __dict__ slots (as in the case 'self.__dict__ is self'). */
2205     if (type->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
2206         if ((base->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
2207             PyObject_ClearManagedDict(self);
2208         }
2209         else {
2210             assert((base->tp_flags & Py_TPFLAGS_INLINE_VALUES) ==
2211                    (type->tp_flags & Py_TPFLAGS_INLINE_VALUES));
2212         }
2213     }
2214     else if (type->tp_dictoffset != base->tp_dictoffset) {
2215         PyObject **dictptr = _PyObject_ComputedDictPointer(self);
2216         if (dictptr && *dictptr)
2217             Py_CLEAR(*dictptr);
2218     }
2219 
2220     if (baseclear)
2221         return baseclear(self);
2222     return 0;
2223 }
2224 
2225 static void
subtype_dealloc(PyObject * self)2226 subtype_dealloc(PyObject *self)
2227 {
2228     PyTypeObject *type, *base;
2229     destructor basedealloc;
2230     int has_finalizer;
2231 
2232     /* Extract the type; we expect it to be a heap type */
2233     type = Py_TYPE(self);
2234     _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2235 
2236     /* Test whether the type has GC exactly once */
2237 
2238     if (!_PyType_IS_GC(type)) {
2239         /* A non GC dynamic type allows certain simplifications:
2240            there's no need to call clear_slots(), or DECREF the dict,
2241            or clear weakrefs. */
2242 
2243         /* Maybe call finalizer; exit early if resurrected */
2244         if (type->tp_finalize) {
2245             if (PyObject_CallFinalizerFromDealloc(self) < 0)
2246                 return;
2247         }
2248         if (type->tp_del) {
2249             type->tp_del(self);
2250             if (Py_REFCNT(self) > 0) {
2251                 return;
2252             }
2253         }
2254 
2255         /* Find the nearest base with a different tp_dealloc */
2256         base = type;
2257         while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
2258             base = base->tp_base;
2259             assert(base);
2260         }
2261 
2262         /* Extract the type again; tp_del may have changed it */
2263         type = Py_TYPE(self);
2264 
2265         // Don't read type memory after calling basedealloc() since basedealloc()
2266         // can deallocate the type and free its memory.
2267         int type_needs_decref = (type->tp_flags & Py_TPFLAGS_HEAPTYPE
2268                                  && !(base->tp_flags & Py_TPFLAGS_HEAPTYPE));
2269 
2270         assert((type->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
2271 
2272         /* Call the base tp_dealloc() */
2273         assert(basedealloc);
2274         basedealloc(self);
2275 
2276         /* Can't reference self beyond this point. It's possible tp_del switched
2277            our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
2278            reference counting. Only decref if the base type is not already a heap
2279            allocated type. Otherwise, basedealloc should have decref'd it already */
2280         if (type_needs_decref) {
2281             Py_DECREF(type);
2282         }
2283 
2284         /* Done */
2285         return;
2286     }
2287 
2288     /* We get here only if the type has GC */
2289 
2290     /* UnTrack and re-Track around the trashcan macro, alas */
2291     /* See explanation at end of function for full disclosure */
2292     PyObject_GC_UnTrack(self);
2293     Py_TRASHCAN_BEGIN(self, subtype_dealloc);
2294 
2295     /* Find the nearest base with a different tp_dealloc */
2296     base = type;
2297     while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
2298         base = base->tp_base;
2299         assert(base);
2300     }
2301 
2302     has_finalizer = type->tp_finalize || type->tp_del;
2303 
2304     if (type->tp_finalize) {
2305         _PyObject_GC_TRACK(self);
2306         if (PyObject_CallFinalizerFromDealloc(self) < 0) {
2307             /* Resurrected */
2308             goto endlabel;
2309         }
2310         _PyObject_GC_UNTRACK(self);
2311     }
2312     /*
2313       If we added a weaklist, we clear it. Do this *before* calling tp_del,
2314       clearing slots, or clearing the instance dict.
2315 
2316       GC tracking must be off at this point. weakref callbacks (if any, and
2317       whether directly here or indirectly in something we call) may trigger GC,
2318       and if self is tracked at that point, it will look like trash to GC and GC
2319       will try to delete self again.
2320     */
2321     if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
2322         PyObject_ClearWeakRefs(self);
2323     }
2324 
2325     if (type->tp_del) {
2326         _PyObject_GC_TRACK(self);
2327         type->tp_del(self);
2328         if (Py_REFCNT(self) > 0) {
2329             /* Resurrected */
2330             goto endlabel;
2331         }
2332         _PyObject_GC_UNTRACK(self);
2333     }
2334     if (has_finalizer) {
2335         /* New weakrefs could be created during the finalizer call.
2336            If this occurs, clear them out without calling their
2337            finalizers since they might rely on part of the object
2338            being finalized that has already been destroyed. */
2339         if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
2340             _PyWeakref_ClearWeakRefsNoCallbacks(self);
2341         }
2342     }
2343 
2344     /*  Clear slots up to the nearest base with a different tp_dealloc */
2345     base = type;
2346     while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
2347         if (Py_SIZE(base))
2348             clear_slots(base, self);
2349         base = base->tp_base;
2350         assert(base);
2351     }
2352 
2353     /* If we added a dict, DECREF it, or free inline values. */
2354     if (type->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
2355         PyObject_ClearManagedDict(self);
2356     }
2357     else if (type->tp_dictoffset && !base->tp_dictoffset) {
2358         PyObject **dictptr = _PyObject_ComputedDictPointer(self);
2359         if (dictptr != NULL) {
2360             PyObject *dict = *dictptr;
2361             if (dict != NULL) {
2362                 Py_DECREF(dict);
2363                 *dictptr = NULL;
2364             }
2365         }
2366     }
2367 
2368     /* Extract the type again; tp_del may have changed it */
2369     type = Py_TYPE(self);
2370 
2371     /* Call the base tp_dealloc(); first retrack self if
2372      * basedealloc knows about gc.
2373      */
2374     if (_PyType_IS_GC(base)) {
2375         _PyObject_GC_TRACK(self);
2376     }
2377 
2378     // Don't read type memory after calling basedealloc() since basedealloc()
2379     // can deallocate the type and free its memory.
2380     int type_needs_decref = (type->tp_flags & Py_TPFLAGS_HEAPTYPE
2381                              && !(base->tp_flags & Py_TPFLAGS_HEAPTYPE));
2382 
2383     assert(basedealloc);
2384     basedealloc(self);
2385 
2386     /* Can't reference self beyond this point. It's possible tp_del switched
2387        our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
2388        reference counting. Only decref if the base type is not already a heap
2389        allocated type. Otherwise, basedealloc should have decref'd it already */
2390     if (type_needs_decref) {
2391         Py_DECREF(type);
2392     }
2393 
2394   endlabel:
2395     Py_TRASHCAN_END
2396 
2397     /* Explanation of the weirdness around the trashcan macros:
2398 
2399        Q. What do the trashcan macros do?
2400 
2401        A. Read the comment titled "Trashcan mechanism" in object.h.
2402           For one, this explains why there must be a call to GC-untrack
2403           before the trashcan begin macro.      Without understanding the
2404           trashcan code, the answers to the following questions don't make
2405           sense.
2406 
2407        Q. Why do we GC-untrack before the trashcan and then immediately
2408           GC-track again afterward?
2409 
2410        A. In the case that the base class is GC-aware, the base class
2411           probably GC-untracks the object.      If it does that using the
2412           UNTRACK macro, this will crash when the object is already
2413           untracked.  Because we don't know what the base class does, the
2414           only safe thing is to make sure the object is tracked when we
2415           call the base class dealloc.  But...  The trashcan begin macro
2416           requires that the object is *untracked* before it is called.  So
2417           the dance becomes:
2418 
2419          GC untrack
2420          trashcan begin
2421          GC track
2422 
2423        Q. Why did the last question say "immediately GC-track again"?
2424           It's nowhere near immediately.
2425 
2426        A. Because the code *used* to re-track immediately.      Bad Idea.
2427           self has a refcount of 0, and if gc ever gets its hands on it
2428           (which can happen if any weakref callback gets invoked), it
2429           looks like trash to gc too, and gc also tries to delete self
2430           then.  But we're already deleting self.  Double deallocation is
2431           a subtle disaster.
2432     */
2433 }
2434 
2435 static PyTypeObject *solid_base(PyTypeObject *type);
2436 
2437 /* type test with subclassing support */
2438 
2439 static int
type_is_subtype_base_chain(PyTypeObject * a,PyTypeObject * b)2440 type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
2441 {
2442     do {
2443         if (a == b)
2444             return 1;
2445         a = a->tp_base;
2446     } while (a != NULL);
2447 
2448     return (b == &PyBaseObject_Type);
2449 }
2450 
2451 static int
is_subtype_with_mro(PyObject * a_mro,PyTypeObject * a,PyTypeObject * b)2452 is_subtype_with_mro(PyObject *a_mro, PyTypeObject *a, PyTypeObject *b)
2453 {
2454     int res;
2455     if (a_mro != NULL) {
2456         /* Deal with multiple inheritance without recursion
2457            by walking the MRO tuple */
2458         Py_ssize_t i, n;
2459         assert(PyTuple_Check(a_mro));
2460         n = PyTuple_GET_SIZE(a_mro);
2461         res = 0;
2462         for (i = 0; i < n; i++) {
2463             if (PyTuple_GET_ITEM(a_mro, i) == (PyObject *)b) {
2464                 res = 1;
2465                 break;
2466             }
2467         }
2468     }
2469     else {
2470         /* a is not completely initialized yet; follow tp_base */
2471         res = type_is_subtype_base_chain(a, b);
2472     }
2473     return res;
2474 }
2475 
2476 int
PyType_IsSubtype(PyTypeObject * a,PyTypeObject * b)2477 PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
2478 {
2479     return is_subtype_with_mro(a->tp_mro, a, b);
2480 }
2481 
2482 /* Routines to do a method lookup in the type without looking in the
2483    instance dictionary (so we can't use PyObject_GetAttr) but still
2484    binding it to the instance.
2485 
2486    Variants:
2487 
2488    - _PyObject_LookupSpecial() returns NULL without raising an exception
2489      when the _PyType_LookupRef() call fails;
2490 
2491    - lookup_maybe_method() and lookup_method() are internal routines similar
2492      to _PyObject_LookupSpecial(), but can return unbound PyFunction
2493      to avoid temporary method object. Pass self as first argument when
2494      unbound == 1.
2495 */
2496 
2497 PyObject *
_PyObject_LookupSpecial(PyObject * self,PyObject * attr)2498 _PyObject_LookupSpecial(PyObject *self, PyObject *attr)
2499 {
2500     PyObject *res;
2501 
2502     res = _PyType_LookupRef(Py_TYPE(self), attr);
2503     if (res != NULL) {
2504         descrgetfunc f;
2505         if ((f = Py_TYPE(res)->tp_descr_get) != NULL) {
2506             Py_SETREF(res, f(res, self, (PyObject *)(Py_TYPE(self))));
2507         }
2508     }
2509     return res;
2510 }
2511 
2512 PyObject *
_PyObject_LookupSpecialId(PyObject * self,_Py_Identifier * attrid)2513 _PyObject_LookupSpecialId(PyObject *self, _Py_Identifier *attrid)
2514 {
2515     PyObject *attr = _PyUnicode_FromId(attrid);   /* borrowed */
2516     if (attr == NULL)
2517         return NULL;
2518     return _PyObject_LookupSpecial(self, attr);
2519 }
2520 
2521 static PyObject *
lookup_maybe_method(PyObject * self,PyObject * attr,int * unbound)2522 lookup_maybe_method(PyObject *self, PyObject *attr, int *unbound)
2523 {
2524     PyObject *res = _PyType_LookupRef(Py_TYPE(self), attr);
2525     if (res == NULL) {
2526         return NULL;
2527     }
2528 
2529     if (_PyType_HasFeature(Py_TYPE(res), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
2530         /* Avoid temporary PyMethodObject */
2531         *unbound = 1;
2532     }
2533     else {
2534         *unbound = 0;
2535         descrgetfunc f = Py_TYPE(res)->tp_descr_get;
2536         if (f != NULL) {
2537             Py_SETREF(res, f(res, self, (PyObject *)(Py_TYPE(self))));
2538         }
2539     }
2540     return res;
2541 }
2542 
2543 static PyObject *
lookup_method(PyObject * self,PyObject * attr,int * unbound)2544 lookup_method(PyObject *self, PyObject *attr, int *unbound)
2545 {
2546     PyObject *res = lookup_maybe_method(self, attr, unbound);
2547     if (res == NULL && !PyErr_Occurred()) {
2548         PyErr_SetObject(PyExc_AttributeError, attr);
2549     }
2550     return res;
2551 }
2552 
2553 
2554 static inline PyObject*
vectorcall_unbound(PyThreadState * tstate,int unbound,PyObject * func,PyObject * const * args,Py_ssize_t nargs)2555 vectorcall_unbound(PyThreadState *tstate, int unbound, PyObject *func,
2556                    PyObject *const *args, Py_ssize_t nargs)
2557 {
2558     size_t nargsf = nargs;
2559     if (!unbound) {
2560         /* Skip self argument, freeing up args[0] to use for
2561          * PY_VECTORCALL_ARGUMENTS_OFFSET */
2562         args++;
2563         nargsf = nargsf - 1 + PY_VECTORCALL_ARGUMENTS_OFFSET;
2564     }
2565     EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_SLOT, func);
2566     return _PyObject_VectorcallTstate(tstate, func, args, nargsf, NULL);
2567 }
2568 
2569 static PyObject*
call_unbound_noarg(int unbound,PyObject * func,PyObject * self)2570 call_unbound_noarg(int unbound, PyObject *func, PyObject *self)
2571 {
2572     if (unbound) {
2573         return PyObject_CallOneArg(func, self);
2574     }
2575     else {
2576         return _PyObject_CallNoArgs(func);
2577     }
2578 }
2579 
2580 /* A variation of PyObject_CallMethod* that uses lookup_method()
2581    instead of PyObject_GetAttrString().
2582 
2583    args is an argument vector of length nargs. The first element in this
2584    vector is the special object "self" which is used for the method lookup */
2585 static PyObject *
vectorcall_method(PyObject * name,PyObject * const * args,Py_ssize_t nargs)2586 vectorcall_method(PyObject *name, PyObject *const *args, Py_ssize_t nargs)
2587 {
2588     assert(nargs >= 1);
2589 
2590     PyThreadState *tstate = _PyThreadState_GET();
2591     int unbound;
2592     PyObject *self = args[0];
2593     PyObject *func = lookup_method(self, name, &unbound);
2594     if (func == NULL) {
2595         return NULL;
2596     }
2597     PyObject *retval = vectorcall_unbound(tstate, unbound, func, args, nargs);
2598     Py_DECREF(func);
2599     return retval;
2600 }
2601 
2602 /* Clone of vectorcall_method() that returns NotImplemented
2603  * when the lookup fails. */
2604 static PyObject *
vectorcall_maybe(PyThreadState * tstate,PyObject * name,PyObject * const * args,Py_ssize_t nargs)2605 vectorcall_maybe(PyThreadState *tstate, PyObject *name,
2606                  PyObject *const *args, Py_ssize_t nargs)
2607 {
2608     assert(nargs >= 1);
2609 
2610     int unbound;
2611     PyObject *self = args[0];
2612     PyObject *func = lookup_maybe_method(self, name, &unbound);
2613     if (func == NULL) {
2614         if (!PyErr_Occurred())
2615             Py_RETURN_NOTIMPLEMENTED;
2616         return NULL;
2617     }
2618     PyObject *retval = vectorcall_unbound(tstate, unbound, func, args, nargs);
2619     Py_DECREF(func);
2620     return retval;
2621 }
2622 
2623 /*
2624     Method resolution order algorithm C3 described in
2625     "A Monotonic Superclass Linearization for Dylan",
2626     by Kim Barrett, Bob Cassel, Paul Haahr,
2627     David A. Moon, Keith Playford, and P. Tucker Withington.
2628     (OOPSLA 1996)
2629 
2630     Some notes about the rules implied by C3:
2631 
2632     No duplicate bases.
2633     It isn't legal to repeat a class in a list of base classes.
2634 
2635     The next three properties are the 3 constraints in "C3".
2636 
2637     Local precedence order.
2638     If A precedes B in C's MRO, then A will precede B in the MRO of all
2639     subclasses of C.
2640 
2641     Monotonicity.
2642     The MRO of a class must be an extension without reordering of the
2643     MRO of each of its superclasses.
2644 
2645     Extended Precedence Graph (EPG).
2646     Linearization is consistent if there is a path in the EPG from
2647     each class to all its successors in the linearization.  See
2648     the paper for definition of EPG.
2649  */
2650 
2651 static int
tail_contains(PyObject * tuple,int whence,PyObject * o)2652 tail_contains(PyObject *tuple, int whence, PyObject *o)
2653 {
2654     Py_ssize_t j, size;
2655     size = PyTuple_GET_SIZE(tuple);
2656 
2657     for (j = whence+1; j < size; j++) {
2658         if (PyTuple_GET_ITEM(tuple, j) == o)
2659             return 1;
2660     }
2661     return 0;
2662 }
2663 
2664 static PyObject *
class_name(PyObject * cls)2665 class_name(PyObject *cls)
2666 {
2667     PyObject *name;
2668     if (PyObject_GetOptionalAttr(cls, &_Py_ID(__name__), &name) == 0) {
2669         name = PyObject_Repr(cls);
2670     }
2671     return name;
2672 }
2673 
2674 static int
check_duplicates(PyObject * tuple)2675 check_duplicates(PyObject *tuple)
2676 {
2677     Py_ssize_t i, j, n;
2678     /* Let's use a quadratic time algorithm,
2679        assuming that the bases tuples is short.
2680     */
2681     n = PyTuple_GET_SIZE(tuple);
2682     for (i = 0; i < n; i++) {
2683         PyObject *o = PyTuple_GET_ITEM(tuple, i);
2684         for (j = i + 1; j < n; j++) {
2685             if (PyTuple_GET_ITEM(tuple, j) == o) {
2686                 o = class_name(o);
2687                 if (o != NULL) {
2688                     if (PyUnicode_Check(o)) {
2689                         PyErr_Format(PyExc_TypeError,
2690                                      "duplicate base class %U", o);
2691                     }
2692                     else {
2693                         PyErr_SetString(PyExc_TypeError,
2694                                         "duplicate base class");
2695                     }
2696                     Py_DECREF(o);
2697                 }
2698                 return -1;
2699             }
2700         }
2701     }
2702     return 0;
2703 }
2704 
2705 /* Raise a TypeError for an MRO order disagreement.
2706 
2707    It's hard to produce a good error message.  In the absence of better
2708    insight into error reporting, report the classes that were candidates
2709    to be put next into the MRO.  There is some conflict between the
2710    order in which they should be put in the MRO, but it's hard to
2711    diagnose what constraint can't be satisfied.
2712 */
2713 
2714 static void
set_mro_error(PyObject ** to_merge,Py_ssize_t to_merge_size,int * remain)2715 set_mro_error(PyObject **to_merge, Py_ssize_t to_merge_size, int *remain)
2716 {
2717     Py_ssize_t i, n, off;
2718     char buf[1000];
2719     PyObject *k, *v;
2720     PyObject *set = PyDict_New();
2721     if (!set) return;
2722 
2723     for (i = 0; i < to_merge_size; i++) {
2724         PyObject *L = to_merge[i];
2725         if (remain[i] < PyTuple_GET_SIZE(L)) {
2726             PyObject *c = PyTuple_GET_ITEM(L, remain[i]);
2727             if (PyDict_SetItem(set, c, Py_None) < 0) {
2728                 Py_DECREF(set);
2729                 return;
2730             }
2731         }
2732     }
2733     n = PyDict_GET_SIZE(set);
2734 
2735     off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
2736 consistent method resolution order (MRO) for bases");
2737     i = 0;
2738     while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
2739         PyObject *name = class_name(k);
2740         const char *name_str = NULL;
2741         if (name != NULL) {
2742             if (PyUnicode_Check(name)) {
2743                 name_str = PyUnicode_AsUTF8(name);
2744             }
2745             else {
2746                 name_str = "?";
2747             }
2748         }
2749         if (name_str == NULL) {
2750             Py_XDECREF(name);
2751             Py_DECREF(set);
2752             return;
2753         }
2754         off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
2755         Py_XDECREF(name);
2756         if (--n && (size_t)(off+1) < sizeof(buf)) {
2757             buf[off++] = ',';
2758             buf[off] = '\0';
2759         }
2760     }
2761     PyErr_SetString(PyExc_TypeError, buf);
2762     Py_DECREF(set);
2763 }
2764 
2765 static int
pmerge(PyObject * acc,PyObject ** to_merge,Py_ssize_t to_merge_size)2766 pmerge(PyObject *acc, PyObject **to_merge, Py_ssize_t to_merge_size)
2767 {
2768     int res = 0;
2769     Py_ssize_t i, j, empty_cnt;
2770     int *remain;
2771 
2772     /* remain stores an index into each sublist of to_merge.
2773        remain[i] is the index of the next base in to_merge[i]
2774        that is not included in acc.
2775     */
2776     remain = PyMem_New(int, to_merge_size);
2777     if (remain == NULL) {
2778         PyErr_NoMemory();
2779         return -1;
2780     }
2781     for (i = 0; i < to_merge_size; i++)
2782         remain[i] = 0;
2783 
2784   again:
2785     empty_cnt = 0;
2786     for (i = 0; i < to_merge_size; i++) {
2787         PyObject *candidate;
2788 
2789         PyObject *cur_tuple = to_merge[i];
2790 
2791         if (remain[i] >= PyTuple_GET_SIZE(cur_tuple)) {
2792             empty_cnt++;
2793             continue;
2794         }
2795 
2796         /* Choose next candidate for MRO.
2797 
2798            The input sequences alone can determine the choice.
2799            If not, choose the class which appears in the MRO
2800            of the earliest direct superclass of the new class.
2801         */
2802 
2803         candidate = PyTuple_GET_ITEM(cur_tuple, remain[i]);
2804         for (j = 0; j < to_merge_size; j++) {
2805             PyObject *j_lst = to_merge[j];
2806             if (tail_contains(j_lst, remain[j], candidate))
2807                 goto skip; /* continue outer loop */
2808         }
2809         res = PyList_Append(acc, candidate);
2810         if (res < 0)
2811             goto out;
2812 
2813         for (j = 0; j < to_merge_size; j++) {
2814             PyObject *j_lst = to_merge[j];
2815             if (remain[j] < PyTuple_GET_SIZE(j_lst) &&
2816                 PyTuple_GET_ITEM(j_lst, remain[j]) == candidate) {
2817                 remain[j]++;
2818             }
2819         }
2820         goto again;
2821       skip: ;
2822     }
2823 
2824     if (empty_cnt != to_merge_size) {
2825         set_mro_error(to_merge, to_merge_size, remain);
2826         res = -1;
2827     }
2828 
2829   out:
2830     PyMem_Free(remain);
2831 
2832     return res;
2833 }
2834 
2835 static PyObject *
mro_implementation_unlocked(PyTypeObject * type)2836 mro_implementation_unlocked(PyTypeObject *type)
2837 {
2838     ASSERT_TYPE_LOCK_HELD();
2839 
2840     if (!_PyType_IsReady(type)) {
2841         if (PyType_Ready(type) < 0)
2842             return NULL;
2843     }
2844 
2845     PyObject *bases = lookup_tp_bases(type);
2846     Py_ssize_t n = PyTuple_GET_SIZE(bases);
2847     for (Py_ssize_t i = 0; i < n; i++) {
2848         PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, i));
2849         if (lookup_tp_mro(base) == NULL) {
2850             PyErr_Format(PyExc_TypeError,
2851                          "Cannot extend an incomplete type '%.100s'",
2852                          base->tp_name);
2853             return NULL;
2854         }
2855         assert(PyTuple_Check(lookup_tp_mro(base)));
2856     }
2857 
2858     if (n == 1) {
2859         /* Fast path: if there is a single base, constructing the MRO
2860          * is trivial.
2861          */
2862         PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, 0));
2863         PyObject *base_mro = lookup_tp_mro(base);
2864         Py_ssize_t k = PyTuple_GET_SIZE(base_mro);
2865         PyObject *result = PyTuple_New(k + 1);
2866         if (result == NULL) {
2867             return NULL;
2868         }
2869 
2870         ;
2871         PyTuple_SET_ITEM(result, 0, Py_NewRef(type));
2872         for (Py_ssize_t i = 0; i < k; i++) {
2873             PyObject *cls = PyTuple_GET_ITEM(base_mro, i);
2874             PyTuple_SET_ITEM(result, i + 1, Py_NewRef(cls));
2875         }
2876         return result;
2877     }
2878 
2879     /* This is just a basic sanity check. */
2880     if (check_duplicates(bases) < 0) {
2881         return NULL;
2882     }
2883 
2884     /* Find a superclass linearization that honors the constraints
2885        of the explicit tuples of bases and the constraints implied by
2886        each base class.
2887 
2888        to_merge is an array of tuples, where each tuple is a superclass
2889        linearization implied by a base class.  The last element of
2890        to_merge is the declared tuple of bases.
2891     */
2892     PyObject **to_merge = PyMem_New(PyObject *, n + 1);
2893     if (to_merge == NULL) {
2894         PyErr_NoMemory();
2895         return NULL;
2896     }
2897 
2898     for (Py_ssize_t i = 0; i < n; i++) {
2899         PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, i));
2900         to_merge[i] = lookup_tp_mro(base);
2901     }
2902     to_merge[n] = bases;
2903 
2904     PyObject *result = PyList_New(1);
2905     if (result == NULL) {
2906         PyMem_Free(to_merge);
2907         return NULL;
2908     }
2909 
2910     PyList_SET_ITEM(result, 0, Py_NewRef(type));
2911     if (pmerge(result, to_merge, n + 1) < 0) {
2912         Py_CLEAR(result);
2913     }
2914     PyMem_Free(to_merge);
2915 
2916     return result;
2917 }
2918 
2919 static PyObject *
mro_implementation(PyTypeObject * type)2920 mro_implementation(PyTypeObject *type)
2921 {
2922     PyObject *mro;
2923     BEGIN_TYPE_LOCK();
2924     mro = mro_implementation_unlocked(type);
2925     END_TYPE_LOCK();
2926     return mro;
2927 }
2928 
2929 /*[clinic input]
2930 type.mro
2931 
2932 Return a type's method resolution order.
2933 [clinic start generated code]*/
2934 
2935 static PyObject *
type_mro_impl(PyTypeObject * self)2936 type_mro_impl(PyTypeObject *self)
2937 /*[clinic end generated code: output=bffc4a39b5b57027 input=28414f4e156db28d]*/
2938 {
2939     PyObject *seq;
2940     seq = mro_implementation(self);
2941     if (seq != NULL && !PyList_Check(seq)) {
2942         Py_SETREF(seq, PySequence_List(seq));
2943     }
2944     return seq;
2945 }
2946 
2947 static int
mro_check(PyTypeObject * type,PyObject * mro)2948 mro_check(PyTypeObject *type, PyObject *mro)
2949 {
2950     PyTypeObject *solid;
2951     Py_ssize_t i, n;
2952 
2953     solid = solid_base(type);
2954 
2955     n = PyTuple_GET_SIZE(mro);
2956     for (i = 0; i < n; i++) {
2957         PyObject *obj = PyTuple_GET_ITEM(mro, i);
2958         if (!PyType_Check(obj)) {
2959             PyErr_Format(
2960                 PyExc_TypeError,
2961                 "mro() returned a non-class ('%.500s')",
2962                 Py_TYPE(obj)->tp_name);
2963             return -1;
2964         }
2965         PyTypeObject *base = (PyTypeObject*)obj;
2966 
2967         if (!is_subtype_with_mro(lookup_tp_mro(solid), solid, solid_base(base))) {
2968             PyErr_Format(
2969                 PyExc_TypeError,
2970                 "mro() returned base with unsuitable layout ('%.500s')",
2971                 base->tp_name);
2972             return -1;
2973         }
2974     }
2975 
2976     return 0;
2977 }
2978 
2979 /* Lookups an mcls.mro method, invokes it and checks the result (if needed,
2980    in case of a custom mro() implementation).
2981 
2982    Keep in mind that during execution of this function type->tp_mro
2983    can be replaced due to possible reentrance (for example,
2984    through type_set_bases):
2985 
2986       - when looking up the mcls.mro attribute (it could be
2987         a user-provided descriptor);
2988 
2989       - from inside a custom mro() itself;
2990 
2991       - through a finalizer of the return value of mro().
2992 */
2993 static PyObject *
mro_invoke(PyTypeObject * type)2994 mro_invoke(PyTypeObject *type)
2995 {
2996     PyObject *mro_result;
2997     PyObject *new_mro;
2998 
2999     ASSERT_TYPE_LOCK_HELD();
3000 
3001     const int custom = !Py_IS_TYPE(type, &PyType_Type);
3002 
3003     if (custom) {
3004         int unbound;
3005         PyObject *mro_meth = lookup_method(
3006             (PyObject *)type, &_Py_ID(mro), &unbound);
3007         if (mro_meth == NULL)
3008             return NULL;
3009         mro_result = call_unbound_noarg(unbound, mro_meth, (PyObject *)type);
3010         Py_DECREF(mro_meth);
3011     }
3012     else {
3013         mro_result = mro_implementation_unlocked(type);
3014     }
3015     if (mro_result == NULL)
3016         return NULL;
3017 
3018     new_mro = PySequence_Tuple(mro_result);
3019     Py_DECREF(mro_result);
3020     if (new_mro == NULL) {
3021         return NULL;
3022     }
3023 
3024     if (PyTuple_GET_SIZE(new_mro) == 0) {
3025         Py_DECREF(new_mro);
3026         PyErr_Format(PyExc_TypeError, "type MRO must not be empty");
3027         return NULL;
3028     }
3029 
3030     if (custom && mro_check(type, new_mro) < 0) {
3031         Py_DECREF(new_mro);
3032         return NULL;
3033     }
3034     return new_mro;
3035 }
3036 
3037 /* Calculates and assigns a new MRO to type->tp_mro.
3038    Return values and invariants:
3039 
3040      - Returns 1 if a new MRO value has been set to type->tp_mro due to
3041        this call of mro_internal (no tricky reentrancy and no errors).
3042 
3043        In case if p_old_mro argument is not NULL, a previous value
3044        of type->tp_mro is put there, and the ownership of this
3045        reference is transferred to a caller.
3046        Otherwise, the previous value (if any) is decref'ed.
3047 
3048      - Returns 0 in case when type->tp_mro gets changed because of
3049        reentering here through a custom mro() (see a comment to mro_invoke).
3050 
3051        In this case, a refcount of an old type->tp_mro is adjusted
3052        somewhere deeper in the call stack (by the innermost mro_internal
3053        or its caller) and may become zero upon returning from here.
3054        This also implies that the whole hierarchy of subclasses of the type
3055        has seen the new value and updated their MRO accordingly.
3056 
3057      - Returns -1 in case of an error.
3058 */
3059 static int
mro_internal_unlocked(PyTypeObject * type,int initial,PyObject ** p_old_mro)3060 mro_internal_unlocked(PyTypeObject *type, int initial, PyObject **p_old_mro)
3061 {
3062     ASSERT_TYPE_LOCK_HELD();
3063 
3064     PyObject *new_mro, *old_mro;
3065     int reent;
3066 
3067     /* Keep a reference to be able to do a reentrancy check below.
3068        Don't let old_mro be GC'ed and its address be reused for
3069        another object, like (suddenly!) a new tp_mro.  */
3070     old_mro = Py_XNewRef(lookup_tp_mro(type));
3071     new_mro = mro_invoke(type);  /* might cause reentrance */
3072     reent = (lookup_tp_mro(type) != old_mro);
3073     Py_XDECREF(old_mro);
3074     if (new_mro == NULL) {
3075         return -1;
3076     }
3077 
3078     if (reent) {
3079         Py_DECREF(new_mro);
3080         return 0;
3081     }
3082 
3083     set_tp_mro(type, new_mro, initial);
3084 
3085     type_mro_modified(type, new_mro);
3086     /* corner case: the super class might have been hidden
3087        from the custom MRO */
3088     type_mro_modified(type, lookup_tp_bases(type));
3089 
3090     // XXX Expand this to Py_TPFLAGS_IMMUTABLETYPE?
3091     if (!(type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN)) {
3092         PyType_Modified(type);
3093     }
3094     else {
3095         /* For static builtin types, this is only called during init
3096            before the method cache has been populated. */
3097         assert(type->tp_version_tag);
3098     }
3099 
3100     if (p_old_mro != NULL)
3101         *p_old_mro = old_mro;  /* transfer the ownership */
3102     else
3103         Py_XDECREF(old_mro);
3104 
3105     return 1;
3106 }
3107 
3108 static int
mro_internal(PyTypeObject * type,PyObject ** p_old_mro)3109 mro_internal(PyTypeObject *type, PyObject **p_old_mro)
3110 {
3111     int res;
3112     BEGIN_TYPE_LOCK();
3113     res = mro_internal_unlocked(type, 0, p_old_mro);
3114     END_TYPE_LOCK();
3115     return res;
3116 }
3117 
3118 /* Calculate the best base amongst multiple base classes.
3119    This is the first one that's on the path to the "solid base". */
3120 
3121 static PyTypeObject *
best_base(PyObject * bases)3122 best_base(PyObject *bases)
3123 {
3124     Py_ssize_t i, n;
3125     PyTypeObject *base, *winner, *candidate;
3126 
3127     assert(PyTuple_Check(bases));
3128     n = PyTuple_GET_SIZE(bases);
3129     assert(n > 0);
3130     base = NULL;
3131     winner = NULL;
3132     for (i = 0; i < n; i++) {
3133         PyObject *base_proto = PyTuple_GET_ITEM(bases, i);
3134         if (!PyType_Check(base_proto)) {
3135             PyErr_SetString(
3136                 PyExc_TypeError,
3137                 "bases must be types");
3138             return NULL;
3139         }
3140         PyTypeObject *base_i = (PyTypeObject *)base_proto;
3141 
3142         if (!_PyType_IsReady(base_i)) {
3143             if (PyType_Ready(base_i) < 0)
3144                 return NULL;
3145         }
3146         if (!_PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
3147             PyErr_Format(PyExc_TypeError,
3148                          "type '%.100s' is not an acceptable base type",
3149                          base_i->tp_name);
3150             return NULL;
3151         }
3152         candidate = solid_base(base_i);
3153         if (winner == NULL) {
3154             winner = candidate;
3155             base = base_i;
3156         }
3157         else if (PyType_IsSubtype(winner, candidate))
3158             ;
3159         else if (PyType_IsSubtype(candidate, winner)) {
3160             winner = candidate;
3161             base = base_i;
3162         }
3163         else {
3164             PyErr_SetString(
3165                 PyExc_TypeError,
3166                 "multiple bases have "
3167                 "instance lay-out conflict");
3168             return NULL;
3169         }
3170     }
3171     assert (base != NULL);
3172 
3173     return base;
3174 }
3175 
3176 static int
shape_differs(PyTypeObject * t1,PyTypeObject * t2)3177 shape_differs(PyTypeObject *t1, PyTypeObject *t2)
3178 {
3179     return (
3180         t1->tp_basicsize != t2->tp_basicsize ||
3181         t1->tp_itemsize != t2->tp_itemsize
3182     );
3183 }
3184 
3185 static PyTypeObject *
solid_base(PyTypeObject * type)3186 solid_base(PyTypeObject *type)
3187 {
3188     PyTypeObject *base;
3189 
3190     if (type->tp_base) {
3191         base = solid_base(type->tp_base);
3192     }
3193     else {
3194         base = &PyBaseObject_Type;
3195     }
3196     if (shape_differs(type, base)) {
3197         return type;
3198     }
3199     else {
3200         return base;
3201     }
3202 }
3203 
3204 static void object_dealloc(PyObject *);
3205 static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *);
3206 static int object_init(PyObject *, PyObject *, PyObject *);
3207 static int update_slot(PyTypeObject *, PyObject *);
3208 static void fixup_slot_dispatchers(PyTypeObject *);
3209 static int type_new_set_names(PyTypeObject *);
3210 static int type_new_init_subclass(PyTypeObject *, PyObject *);
3211 
3212 /*
3213  * Helpers for  __dict__ descriptor.  We don't want to expose the dicts
3214  * inherited from various builtin types.  The builtin base usually provides
3215  * its own __dict__ descriptor, so we use that when we can.
3216  */
3217 static PyTypeObject *
get_builtin_base_with_dict(PyTypeObject * type)3218 get_builtin_base_with_dict(PyTypeObject *type)
3219 {
3220     while (type->tp_base != NULL) {
3221         if (type->tp_dictoffset != 0 &&
3222             !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
3223             return type;
3224         type = type->tp_base;
3225     }
3226     return NULL;
3227 }
3228 
3229 static PyObject *
get_dict_descriptor(PyTypeObject * type)3230 get_dict_descriptor(PyTypeObject *type)
3231 {
3232     PyObject *descr;
3233 
3234     descr = _PyType_Lookup(type, &_Py_ID(__dict__));
3235     if (descr == NULL || !PyDescr_IsData(descr))
3236         return NULL;
3237 
3238     return descr;
3239 }
3240 
3241 static void
raise_dict_descr_error(PyObject * obj)3242 raise_dict_descr_error(PyObject *obj)
3243 {
3244     PyErr_Format(PyExc_TypeError,
3245                  "this __dict__ descriptor does not support "
3246                  "'%.200s' objects", Py_TYPE(obj)->tp_name);
3247 }
3248 
3249 static PyObject *
subtype_dict(PyObject * obj,void * context)3250 subtype_dict(PyObject *obj, void *context)
3251 {
3252     PyTypeObject *base;
3253 
3254     base = get_builtin_base_with_dict(Py_TYPE(obj));
3255     if (base != NULL) {
3256         descrgetfunc func;
3257         PyObject *descr = get_dict_descriptor(base);
3258         if (descr == NULL) {
3259             raise_dict_descr_error(obj);
3260             return NULL;
3261         }
3262         func = Py_TYPE(descr)->tp_descr_get;
3263         if (func == NULL) {
3264             raise_dict_descr_error(obj);
3265             return NULL;
3266         }
3267         return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
3268     }
3269     return PyObject_GenericGetDict(obj, context);
3270 }
3271 
3272 static int
subtype_setdict(PyObject * obj,PyObject * value,void * context)3273 subtype_setdict(PyObject *obj, PyObject *value, void *context)
3274 {
3275     PyObject **dictptr;
3276     PyTypeObject *base;
3277 
3278     base = get_builtin_base_with_dict(Py_TYPE(obj));
3279     if (base != NULL) {
3280         descrsetfunc func;
3281         PyObject *descr = get_dict_descriptor(base);
3282         if (descr == NULL) {
3283             raise_dict_descr_error(obj);
3284             return -1;
3285         }
3286         func = Py_TYPE(descr)->tp_descr_set;
3287         if (func == NULL) {
3288             raise_dict_descr_error(obj);
3289             return -1;
3290         }
3291         return func(descr, obj, value);
3292     }
3293     /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
3294     if (value != NULL && !PyDict_Check(value)) {
3295         PyErr_Format(PyExc_TypeError,
3296                      "__dict__ must be set to a dictionary, "
3297                      "not a '%.200s'", Py_TYPE(value)->tp_name);
3298         return -1;
3299     }
3300 
3301     if (Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
3302         return _PyObject_SetManagedDict(obj, value);
3303     }
3304     else {
3305         dictptr = _PyObject_ComputedDictPointer(obj);
3306         if (dictptr == NULL) {
3307             PyErr_SetString(PyExc_AttributeError,
3308                             "This object has no __dict__");
3309             return -1;
3310         }
3311         Py_CLEAR(*dictptr);
3312         *dictptr = Py_XNewRef(value);
3313     }
3314     return 0;
3315 }
3316 
3317 static PyObject *
subtype_getweakref(PyObject * obj,void * context)3318 subtype_getweakref(PyObject *obj, void *context)
3319 {
3320     PyObject **weaklistptr;
3321     PyObject *result;
3322     PyTypeObject *type = Py_TYPE(obj);
3323 
3324     if (type->tp_weaklistoffset == 0) {
3325         PyErr_SetString(PyExc_AttributeError,
3326                         "This object has no __weakref__");
3327         return NULL;
3328     }
3329     _PyObject_ASSERT((PyObject *)type,
3330                      type->tp_weaklistoffset > 0 ||
3331                      type->tp_weaklistoffset == MANAGED_WEAKREF_OFFSET);
3332     _PyObject_ASSERT((PyObject *)type,
3333                      ((type->tp_weaklistoffset + (Py_ssize_t)sizeof(PyObject *))
3334                       <= type->tp_basicsize));
3335     weaklistptr = (PyObject **)((char *)obj + type->tp_weaklistoffset);
3336     if (*weaklistptr == NULL)
3337         result = Py_None;
3338     else
3339         result = *weaklistptr;
3340     return Py_NewRef(result);
3341 }
3342 
3343 /* Three variants on the subtype_getsets list. */
3344 
3345 static PyGetSetDef subtype_getsets_full[] = {
3346     {"__dict__", subtype_dict, subtype_setdict,
3347      PyDoc_STR("dictionary for instance variables")},
3348     {"__weakref__", subtype_getweakref, NULL,
3349      PyDoc_STR("list of weak references to the object")},
3350     {0}
3351 };
3352 
3353 static PyGetSetDef subtype_getsets_dict_only[] = {
3354     {"__dict__", subtype_dict, subtype_setdict,
3355      PyDoc_STR("dictionary for instance variables")},
3356     {0}
3357 };
3358 
3359 static PyGetSetDef subtype_getsets_weakref_only[] = {
3360     {"__weakref__", subtype_getweakref, NULL,
3361      PyDoc_STR("list of weak references to the object")},
3362     {0}
3363 };
3364 
3365 static int
valid_identifier(PyObject * s)3366 valid_identifier(PyObject *s)
3367 {
3368     if (!PyUnicode_Check(s)) {
3369         PyErr_Format(PyExc_TypeError,
3370                      "__slots__ items must be strings, not '%.200s'",
3371                      Py_TYPE(s)->tp_name);
3372         return 0;
3373     }
3374     if (!PyUnicode_IsIdentifier(s)) {
3375         PyErr_SetString(PyExc_TypeError,
3376                         "__slots__ must be identifiers");
3377         return 0;
3378     }
3379     return 1;
3380 }
3381 
3382 static int
type_init(PyObject * cls,PyObject * args,PyObject * kwds)3383 type_init(PyObject *cls, PyObject *args, PyObject *kwds)
3384 {
3385     assert(args != NULL && PyTuple_Check(args));
3386     assert(kwds == NULL || PyDict_Check(kwds));
3387 
3388     if (kwds != NULL && PyTuple_GET_SIZE(args) == 1 &&
3389         PyDict_GET_SIZE(kwds) != 0) {
3390         PyErr_SetString(PyExc_TypeError,
3391                         "type.__init__() takes no keyword arguments");
3392         return -1;
3393     }
3394 
3395     if ((PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
3396         PyErr_SetString(PyExc_TypeError,
3397                         "type.__init__() takes 1 or 3 arguments");
3398         return -1;
3399     }
3400 
3401     return 0;
3402 }
3403 
3404 
3405 unsigned long
PyType_GetFlags(PyTypeObject * type)3406 PyType_GetFlags(PyTypeObject *type)
3407 {
3408     return FT_ATOMIC_LOAD_ULONG_RELAXED(type->tp_flags);
3409 }
3410 
3411 
3412 int
PyType_SUPPORTS_WEAKREFS(PyTypeObject * type)3413 PyType_SUPPORTS_WEAKREFS(PyTypeObject *type)
3414 {
3415     return _PyType_SUPPORTS_WEAKREFS(type);
3416 }
3417 
3418 
3419 /* Determine the most derived metatype. */
3420 PyTypeObject *
_PyType_CalculateMetaclass(PyTypeObject * metatype,PyObject * bases)3421 _PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
3422 {
3423     Py_ssize_t i, nbases;
3424     PyTypeObject *winner;
3425     PyObject *tmp;
3426     PyTypeObject *tmptype;
3427 
3428     /* Determine the proper metatype to deal with this,
3429        and check for metatype conflicts while we're at it.
3430        Note that if some other metatype wins to contract,
3431        it's possible that its instances are not types. */
3432 
3433     nbases = PyTuple_GET_SIZE(bases);
3434     winner = metatype;
3435     for (i = 0; i < nbases; i++) {
3436         tmp = PyTuple_GET_ITEM(bases, i);
3437         tmptype = Py_TYPE(tmp);
3438         if (PyType_IsSubtype(winner, tmptype))
3439             continue;
3440         if (PyType_IsSubtype(tmptype, winner)) {
3441             winner = tmptype;
3442             continue;
3443         }
3444         /* else: */
3445         PyErr_SetString(PyExc_TypeError,
3446                         "metaclass conflict: "
3447                         "the metaclass of a derived class "
3448                         "must be a (non-strict) subclass "
3449                         "of the metaclasses of all its bases");
3450         return NULL;
3451     }
3452     return winner;
3453 }
3454 
3455 
3456 // Forward declaration
3457 static PyObject *
3458 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds);
3459 
3460 typedef struct {
3461     PyTypeObject *metatype;
3462     PyObject *args;
3463     PyObject *kwds;
3464     PyObject *orig_dict;
3465     PyObject *name;
3466     PyObject *bases;
3467     PyTypeObject *base;
3468     PyObject *slots;
3469     Py_ssize_t nslot;
3470     int add_dict;
3471     int add_weak;
3472     int may_add_dict;
3473     int may_add_weak;
3474 } type_new_ctx;
3475 
3476 
3477 /* Check for valid slot names and two special cases */
3478 static int
type_new_visit_slots(type_new_ctx * ctx)3479 type_new_visit_slots(type_new_ctx *ctx)
3480 {
3481     PyObject *slots = ctx->slots;
3482     Py_ssize_t nslot = ctx->nslot;
3483     for (Py_ssize_t i = 0; i < nslot; i++) {
3484         PyObject *name = PyTuple_GET_ITEM(slots, i);
3485         if (!valid_identifier(name)) {
3486             return -1;
3487         }
3488         assert(PyUnicode_Check(name));
3489         if (_PyUnicode_Equal(name, &_Py_ID(__dict__))) {
3490             if (!ctx->may_add_dict || ctx->add_dict != 0) {
3491                 PyErr_SetString(PyExc_TypeError,
3492                     "__dict__ slot disallowed: "
3493                     "we already got one");
3494                 return -1;
3495             }
3496             ctx->add_dict++;
3497         }
3498         if (_PyUnicode_Equal(name, &_Py_ID(__weakref__))) {
3499             if (!ctx->may_add_weak || ctx->add_weak != 0) {
3500                 PyErr_SetString(PyExc_TypeError,
3501                     "__weakref__ slot disallowed: "
3502                     "we already got one");
3503                 return -1;
3504             }
3505             ctx->add_weak++;
3506         }
3507     }
3508     return 0;
3509 }
3510 
3511 
3512 /* Copy slots into a list, mangle names and sort them.
3513    Sorted names are needed for __class__ assignment.
3514    Convert them back to tuple at the end.
3515 */
3516 static PyObject*
type_new_copy_slots(type_new_ctx * ctx,PyObject * dict)3517 type_new_copy_slots(type_new_ctx *ctx, PyObject *dict)
3518 {
3519     PyObject *slots = ctx->slots;
3520     Py_ssize_t nslot = ctx->nslot;
3521 
3522     Py_ssize_t new_nslot = nslot - ctx->add_dict - ctx->add_weak;
3523     PyObject *new_slots = PyList_New(new_nslot);
3524     if (new_slots == NULL) {
3525         return NULL;
3526     }
3527 
3528     Py_ssize_t j = 0;
3529     for (Py_ssize_t i = 0; i < nslot; i++) {
3530         PyObject *slot = PyTuple_GET_ITEM(slots, i);
3531         if ((ctx->add_dict && _PyUnicode_Equal(slot, &_Py_ID(__dict__))) ||
3532             (ctx->add_weak && _PyUnicode_Equal(slot, &_Py_ID(__weakref__))))
3533         {
3534             continue;
3535         }
3536 
3537         slot =_Py_Mangle(ctx->name, slot);
3538         if (!slot) {
3539             goto error;
3540         }
3541         PyList_SET_ITEM(new_slots, j, slot);
3542 
3543         int r = PyDict_Contains(dict, slot);
3544         if (r < 0) {
3545             goto error;
3546         }
3547         if (r > 0) {
3548             /* CPython inserts these names (when needed)
3549                into the namespace when creating a class.  They will be deleted
3550                below so won't act as class variables. */
3551             if (!_PyUnicode_Equal(slot, &_Py_ID(__qualname__)) &&
3552                 !_PyUnicode_Equal(slot, &_Py_ID(__classcell__)) &&
3553                 !_PyUnicode_Equal(slot, &_Py_ID(__classdictcell__)))
3554             {
3555                 PyErr_Format(PyExc_ValueError,
3556                              "%R in __slots__ conflicts with class variable",
3557                              slot);
3558                 goto error;
3559             }
3560         }
3561 
3562         j++;
3563     }
3564     assert(j == new_nslot);
3565 
3566     if (PyList_Sort(new_slots) == -1) {
3567         goto error;
3568     }
3569 
3570     PyObject *tuple = PyList_AsTuple(new_slots);
3571     Py_DECREF(new_slots);
3572     if (tuple == NULL) {
3573         return NULL;
3574     }
3575 
3576     assert(PyTuple_GET_SIZE(tuple) == new_nslot);
3577     return tuple;
3578 
3579 error:
3580     Py_DECREF(new_slots);
3581     return NULL;
3582 }
3583 
3584 
3585 static void
type_new_slots_bases(type_new_ctx * ctx)3586 type_new_slots_bases(type_new_ctx *ctx)
3587 {
3588     Py_ssize_t nbases = PyTuple_GET_SIZE(ctx->bases);
3589     if (nbases > 1 &&
3590         ((ctx->may_add_dict && ctx->add_dict == 0) ||
3591          (ctx->may_add_weak && ctx->add_weak == 0)))
3592     {
3593         for (Py_ssize_t i = 0; i < nbases; i++) {
3594             PyObject *obj = PyTuple_GET_ITEM(ctx->bases, i);
3595             if (obj == (PyObject *)ctx->base) {
3596                 /* Skip primary base */
3597                 continue;
3598             }
3599             PyTypeObject *base = _PyType_CAST(obj);
3600 
3601             if (ctx->may_add_dict && ctx->add_dict == 0 &&
3602                 base->tp_dictoffset != 0)
3603             {
3604                 ctx->add_dict++;
3605             }
3606             if (ctx->may_add_weak && ctx->add_weak == 0 &&
3607                 base->tp_weaklistoffset != 0)
3608             {
3609                 ctx->add_weak++;
3610             }
3611             if (ctx->may_add_dict && ctx->add_dict == 0) {
3612                 continue;
3613             }
3614             if (ctx->may_add_weak && ctx->add_weak == 0) {
3615                 continue;
3616             }
3617             /* Nothing more to check */
3618             break;
3619         }
3620     }
3621 }
3622 
3623 
3624 static int
type_new_slots_impl(type_new_ctx * ctx,PyObject * dict)3625 type_new_slots_impl(type_new_ctx *ctx, PyObject *dict)
3626 {
3627     /* Are slots allowed? */
3628     if (ctx->nslot > 0 && ctx->base->tp_itemsize != 0) {
3629         PyErr_Format(PyExc_TypeError,
3630                      "nonempty __slots__ not supported for subtype of '%s'",
3631                      ctx->base->tp_name);
3632         return -1;
3633     }
3634 
3635     if (type_new_visit_slots(ctx) < 0) {
3636         return -1;
3637     }
3638 
3639     PyObject *new_slots = type_new_copy_slots(ctx, dict);
3640     if (new_slots == NULL) {
3641         return -1;
3642     }
3643     assert(PyTuple_CheckExact(new_slots));
3644 
3645     Py_XSETREF(ctx->slots, new_slots);
3646     ctx->nslot = PyTuple_GET_SIZE(new_slots);
3647 
3648     /* Secondary bases may provide weakrefs or dict */
3649     type_new_slots_bases(ctx);
3650     return 0;
3651 }
3652 
3653 
3654 static Py_ssize_t
type_new_slots(type_new_ctx * ctx,PyObject * dict)3655 type_new_slots(type_new_ctx *ctx, PyObject *dict)
3656 {
3657     // Check for a __slots__ sequence variable in dict, and count it
3658     ctx->add_dict = 0;
3659     ctx->add_weak = 0;
3660     ctx->may_add_dict = (ctx->base->tp_dictoffset == 0);
3661     ctx->may_add_weak = (ctx->base->tp_weaklistoffset == 0
3662                          && ctx->base->tp_itemsize == 0);
3663 
3664     if (ctx->slots == NULL) {
3665         if (ctx->may_add_dict) {
3666             ctx->add_dict++;
3667         }
3668         if (ctx->may_add_weak) {
3669             ctx->add_weak++;
3670         }
3671     }
3672     else {
3673         /* Have slots */
3674         if (type_new_slots_impl(ctx, dict) < 0) {
3675             return -1;
3676         }
3677     }
3678     return 0;
3679 }
3680 
3681 
3682 static PyTypeObject*
type_new_alloc(type_new_ctx * ctx)3683 type_new_alloc(type_new_ctx *ctx)
3684 {
3685     PyTypeObject *metatype = ctx->metatype;
3686     PyTypeObject *type;
3687 
3688     // Allocate the type object
3689     type = (PyTypeObject *)metatype->tp_alloc(metatype, ctx->nslot);
3690     if (type == NULL) {
3691         return NULL;
3692     }
3693     PyHeapTypeObject *et = (PyHeapTypeObject *)type;
3694 
3695     // Initialize tp_flags.
3696     // All heap types need GC, since we can create a reference cycle by storing
3697     // an instance on one of its parents.
3698     type->tp_flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
3699                       Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC);
3700 
3701     // Initialize essential fields
3702     type->tp_as_async = &et->as_async;
3703     type->tp_as_number = &et->as_number;
3704     type->tp_as_sequence = &et->as_sequence;
3705     type->tp_as_mapping = &et->as_mapping;
3706     type->tp_as_buffer = &et->as_buffer;
3707 
3708     set_tp_bases(type, Py_NewRef(ctx->bases), 1);
3709     type->tp_base = (PyTypeObject *)Py_NewRef(ctx->base);
3710 
3711     type->tp_dealloc = subtype_dealloc;
3712     /* Always override allocation strategy to use regular heap */
3713     type->tp_alloc = PyType_GenericAlloc;
3714     type->tp_free = PyObject_GC_Del;
3715 
3716     type->tp_traverse = subtype_traverse;
3717     type->tp_clear = subtype_clear;
3718 
3719     et->ht_name = Py_NewRef(ctx->name);
3720     et->ht_module = NULL;
3721     et->_ht_tpname = NULL;
3722 
3723     _PyObject_SetDeferredRefcount((PyObject *)et);
3724 
3725     return type;
3726 }
3727 
3728 
3729 static int
type_new_set_name(const type_new_ctx * ctx,PyTypeObject * type)3730 type_new_set_name(const type_new_ctx *ctx, PyTypeObject *type)
3731 {
3732     Py_ssize_t name_size;
3733     type->tp_name = PyUnicode_AsUTF8AndSize(ctx->name, &name_size);
3734     if (!type->tp_name) {
3735         return -1;
3736     }
3737     if (strlen(type->tp_name) != (size_t)name_size) {
3738         PyErr_SetString(PyExc_ValueError,
3739                         "type name must not contain null characters");
3740         return -1;
3741     }
3742     return 0;
3743 }
3744 
3745 
3746 /* Set __module__ in the dict */
3747 static int
type_new_set_module(PyTypeObject * type)3748 type_new_set_module(PyTypeObject *type)
3749 {
3750     PyObject *dict = lookup_tp_dict(type);
3751     int r = PyDict_Contains(dict, &_Py_ID(__module__));
3752     if (r < 0) {
3753         return -1;
3754     }
3755     if (r > 0) {
3756         return 0;
3757     }
3758 
3759     PyObject *globals = PyEval_GetGlobals();
3760     if (globals == NULL) {
3761         return 0;
3762     }
3763 
3764     PyObject *module;
3765     r = PyDict_GetItemRef(globals, &_Py_ID(__name__), &module);
3766     if (module) {
3767         r = PyDict_SetItem(dict, &_Py_ID(__module__), module);
3768         Py_DECREF(module);
3769     }
3770     return r;
3771 }
3772 
3773 
3774 /* Set ht_qualname to dict['__qualname__'] if available, else to
3775    __name__.  The __qualname__ accessor will look for ht_qualname. */
3776 static int
type_new_set_ht_name(PyTypeObject * type)3777 type_new_set_ht_name(PyTypeObject *type)
3778 {
3779     PyHeapTypeObject *et = (PyHeapTypeObject *)type;
3780     PyObject *dict = lookup_tp_dict(type);
3781     PyObject *qualname;
3782     if (PyDict_GetItemRef(dict, &_Py_ID(__qualname__), &qualname) < 0) {
3783         return -1;
3784     }
3785     if (qualname != NULL) {
3786         if (!PyUnicode_Check(qualname)) {
3787             PyErr_Format(PyExc_TypeError,
3788                     "type __qualname__ must be a str, not %s",
3789                     Py_TYPE(qualname)->tp_name);
3790             Py_DECREF(qualname);
3791             return -1;
3792         }
3793         et->ht_qualname = qualname;
3794         if (PyDict_DelItem(dict, &_Py_ID(__qualname__)) < 0) {
3795             return -1;
3796         }
3797     }
3798     else {
3799         et->ht_qualname = Py_NewRef(et->ht_name);
3800     }
3801     return 0;
3802 }
3803 
3804 
3805 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
3806    and is a string.  The __doc__ accessor will first look for tp_doc;
3807    if that fails, it will still look into __dict__. */
3808 static int
type_new_set_doc(PyTypeObject * type)3809 type_new_set_doc(PyTypeObject *type)
3810 {
3811     PyObject *dict = lookup_tp_dict(type);
3812     PyObject *doc = PyDict_GetItemWithError(dict, &_Py_ID(__doc__));
3813     if (doc == NULL) {
3814         if (PyErr_Occurred()) {
3815             return -1;
3816         }
3817         // no __doc__ key
3818         return 0;
3819     }
3820     if (!PyUnicode_Check(doc)) {
3821         // ignore non-string __doc__
3822         return 0;
3823     }
3824 
3825     const char *doc_str = PyUnicode_AsUTF8(doc);
3826     if (doc_str == NULL) {
3827         return -1;
3828     }
3829 
3830     // Silently truncate the docstring if it contains a null byte
3831     Py_ssize_t size = strlen(doc_str) + 1;
3832     char *tp_doc = (char *)PyMem_Malloc(size);
3833     if (tp_doc == NULL) {
3834         PyErr_NoMemory();
3835         return -1;
3836     }
3837 
3838     memcpy(tp_doc, doc_str, size);
3839     type->tp_doc = tp_doc;
3840     return 0;
3841 }
3842 
3843 
3844 static int
type_new_staticmethod(PyTypeObject * type,PyObject * attr)3845 type_new_staticmethod(PyTypeObject *type, PyObject *attr)
3846 {
3847     PyObject *dict = lookup_tp_dict(type);
3848     PyObject *func = PyDict_GetItemWithError(dict, attr);
3849     if (func == NULL) {
3850         if (PyErr_Occurred()) {
3851             return -1;
3852         }
3853         return 0;
3854     }
3855     if (!PyFunction_Check(func)) {
3856         return 0;
3857     }
3858 
3859     PyObject *static_func = PyStaticMethod_New(func);
3860     if (static_func == NULL) {
3861         return -1;
3862     }
3863     if (PyDict_SetItem(dict, attr, static_func) < 0) {
3864         Py_DECREF(static_func);
3865         return -1;
3866     }
3867     Py_DECREF(static_func);
3868     return 0;
3869 }
3870 
3871 
3872 static int
type_new_classmethod(PyTypeObject * type,PyObject * attr)3873 type_new_classmethod(PyTypeObject *type, PyObject *attr)
3874 {
3875     PyObject *dict = lookup_tp_dict(type);
3876     PyObject *func = PyDict_GetItemWithError(dict, attr);
3877     if (func == NULL) {
3878         if (PyErr_Occurred()) {
3879             return -1;
3880         }
3881         return 0;
3882     }
3883     if (!PyFunction_Check(func)) {
3884         return 0;
3885     }
3886 
3887     PyObject *method = PyClassMethod_New(func);
3888     if (method == NULL) {
3889         return -1;
3890     }
3891 
3892     if (PyDict_SetItem(dict, attr, method) < 0) {
3893         Py_DECREF(method);
3894         return -1;
3895     }
3896     Py_DECREF(method);
3897     return 0;
3898 }
3899 
3900 
3901 /* Add descriptors for custom slots from __slots__, or for __dict__ */
3902 static int
type_new_descriptors(const type_new_ctx * ctx,PyTypeObject * type)3903 type_new_descriptors(const type_new_ctx *ctx, PyTypeObject *type)
3904 {
3905     PyHeapTypeObject *et = (PyHeapTypeObject *)type;
3906     Py_ssize_t slotoffset = ctx->base->tp_basicsize;
3907     if (et->ht_slots != NULL) {
3908         PyMemberDef *mp = _PyHeapType_GET_MEMBERS(et);
3909         Py_ssize_t nslot = PyTuple_GET_SIZE(et->ht_slots);
3910         for (Py_ssize_t i = 0; i < nslot; i++, mp++) {
3911             mp->name = PyUnicode_AsUTF8(
3912                 PyTuple_GET_ITEM(et->ht_slots, i));
3913             if (mp->name == NULL) {
3914                 return -1;
3915             }
3916             mp->type = Py_T_OBJECT_EX;
3917             mp->offset = slotoffset;
3918 
3919             /* __dict__ and __weakref__ are already filtered out */
3920             assert(strcmp(mp->name, "__dict__") != 0);
3921             assert(strcmp(mp->name, "__weakref__") != 0);
3922 
3923             slotoffset += sizeof(PyObject *);
3924         }
3925     }
3926 
3927     if (ctx->add_weak) {
3928         assert((type->tp_flags & Py_TPFLAGS_MANAGED_WEAKREF) == 0);
3929         type->tp_flags |= Py_TPFLAGS_MANAGED_WEAKREF;
3930         type->tp_weaklistoffset = MANAGED_WEAKREF_OFFSET;
3931     }
3932     if (ctx->add_dict) {
3933         assert((type->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
3934         type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
3935         type->tp_dictoffset = -1;
3936     }
3937 
3938     type->tp_basicsize = slotoffset;
3939     type->tp_itemsize = ctx->base->tp_itemsize;
3940     type->tp_members = _PyHeapType_GET_MEMBERS(et);
3941     return 0;
3942 }
3943 
3944 
3945 static void
type_new_set_slots(const type_new_ctx * ctx,PyTypeObject * type)3946 type_new_set_slots(const type_new_ctx *ctx, PyTypeObject *type)
3947 {
3948     if (type->tp_weaklistoffset && type->tp_dictoffset) {
3949         type->tp_getset = subtype_getsets_full;
3950     }
3951     else if (type->tp_weaklistoffset && !type->tp_dictoffset) {
3952         type->tp_getset = subtype_getsets_weakref_only;
3953     }
3954     else if (!type->tp_weaklistoffset && type->tp_dictoffset) {
3955         type->tp_getset = subtype_getsets_dict_only;
3956     }
3957     else {
3958         type->tp_getset = NULL;
3959     }
3960 
3961     /* Special case some slots */
3962     if (type->tp_dictoffset != 0 || ctx->nslot > 0) {
3963         PyTypeObject *base = ctx->base;
3964         if (base->tp_getattr == NULL && base->tp_getattro == NULL) {
3965             type->tp_getattro = PyObject_GenericGetAttr;
3966         }
3967         if (base->tp_setattr == NULL && base->tp_setattro == NULL) {
3968             type->tp_setattro = PyObject_GenericSetAttr;
3969         }
3970     }
3971 }
3972 
3973 
3974 /* store type in class' cell if one is supplied */
3975 static int
type_new_set_classcell(PyTypeObject * type)3976 type_new_set_classcell(PyTypeObject *type)
3977 {
3978     PyObject *dict = lookup_tp_dict(type);
3979     PyObject *cell = PyDict_GetItemWithError(dict, &_Py_ID(__classcell__));
3980     if (cell == NULL) {
3981         if (PyErr_Occurred()) {
3982             return -1;
3983         }
3984         return 0;
3985     }
3986 
3987     /* At least one method requires a reference to its defining class */
3988     if (!PyCell_Check(cell)) {
3989         PyErr_Format(PyExc_TypeError,
3990                      "__classcell__ must be a nonlocal cell, not %.200R",
3991                      Py_TYPE(cell));
3992         return -1;
3993     }
3994 
3995     (void)PyCell_Set(cell, (PyObject *) type);
3996     if (PyDict_DelItem(dict, &_Py_ID(__classcell__)) < 0) {
3997         return -1;
3998     }
3999     return 0;
4000 }
4001 
4002 static int
type_new_set_classdictcell(PyTypeObject * type)4003 type_new_set_classdictcell(PyTypeObject *type)
4004 {
4005     PyObject *dict = lookup_tp_dict(type);
4006     PyObject *cell = PyDict_GetItemWithError(dict, &_Py_ID(__classdictcell__));
4007     if (cell == NULL) {
4008         if (PyErr_Occurred()) {
4009             return -1;
4010         }
4011         return 0;
4012     }
4013 
4014     /* At least one method requires a reference to the dict of its defining class */
4015     if (!PyCell_Check(cell)) {
4016         PyErr_Format(PyExc_TypeError,
4017                      "__classdictcell__ must be a nonlocal cell, not %.200R",
4018                      Py_TYPE(cell));
4019         return -1;
4020     }
4021 
4022     (void)PyCell_Set(cell, (PyObject *)dict);
4023     if (PyDict_DelItem(dict, &_Py_ID(__classdictcell__)) < 0) {
4024         return -1;
4025     }
4026     return 0;
4027 }
4028 
4029 static int
type_new_set_attrs(const type_new_ctx * ctx,PyTypeObject * type)4030 type_new_set_attrs(const type_new_ctx *ctx, PyTypeObject *type)
4031 {
4032     if (type_new_set_name(ctx, type) < 0) {
4033         return -1;
4034     }
4035 
4036     if (type_new_set_module(type) < 0) {
4037         return -1;
4038     }
4039 
4040     if (type_new_set_ht_name(type) < 0) {
4041         return -1;
4042     }
4043 
4044     if (type_new_set_doc(type) < 0) {
4045         return -1;
4046     }
4047 
4048     /* Special-case __new__: if it's a plain function,
4049        make it a static function */
4050     if (type_new_staticmethod(type, &_Py_ID(__new__)) < 0) {
4051         return -1;
4052     }
4053 
4054     /* Special-case __init_subclass__ and __class_getitem__:
4055        if they are plain functions, make them classmethods */
4056     if (type_new_classmethod(type, &_Py_ID(__init_subclass__)) < 0) {
4057         return -1;
4058     }
4059     if (type_new_classmethod(type, &_Py_ID(__class_getitem__)) < 0) {
4060         return -1;
4061     }
4062 
4063     if (type_new_descriptors(ctx, type) < 0) {
4064         return -1;
4065     }
4066 
4067     type_new_set_slots(ctx, type);
4068 
4069     if (type_new_set_classcell(type) < 0) {
4070         return -1;
4071     }
4072     if (type_new_set_classdictcell(type) < 0) {
4073         return -1;
4074     }
4075     return 0;
4076 }
4077 
4078 
4079 static int
type_new_get_slots(type_new_ctx * ctx,PyObject * dict)4080 type_new_get_slots(type_new_ctx *ctx, PyObject *dict)
4081 {
4082     PyObject *slots = PyDict_GetItemWithError(dict, &_Py_ID(__slots__));
4083     if (slots == NULL) {
4084         if (PyErr_Occurred()) {
4085             return -1;
4086         }
4087         ctx->slots = NULL;
4088         ctx->nslot = 0;
4089         return 0;
4090     }
4091 
4092     // Make it into a tuple
4093     PyObject *new_slots;
4094     if (PyUnicode_Check(slots)) {
4095         new_slots = PyTuple_Pack(1, slots);
4096     }
4097     else {
4098         new_slots = PySequence_Tuple(slots);
4099     }
4100     if (new_slots == NULL) {
4101         return -1;
4102     }
4103     assert(PyTuple_CheckExact(new_slots));
4104     ctx->slots = new_slots;
4105     ctx->nslot = PyTuple_GET_SIZE(new_slots);
4106     return 0;
4107 }
4108 
4109 
4110 static PyTypeObject*
type_new_init(type_new_ctx * ctx)4111 type_new_init(type_new_ctx *ctx)
4112 {
4113     PyObject *dict = PyDict_Copy(ctx->orig_dict);
4114     if (dict == NULL) {
4115         goto error;
4116     }
4117 
4118     if (type_new_get_slots(ctx, dict) < 0) {
4119         goto error;
4120     }
4121     assert(!PyErr_Occurred());
4122 
4123     if (type_new_slots(ctx, dict) < 0) {
4124         goto error;
4125     }
4126 
4127     PyTypeObject *type = type_new_alloc(ctx);
4128     if (type == NULL) {
4129         goto error;
4130     }
4131 
4132     set_tp_dict(type, dict);
4133 
4134     PyHeapTypeObject *et = (PyHeapTypeObject*)type;
4135     et->ht_slots = ctx->slots;
4136     ctx->slots = NULL;
4137 
4138     return type;
4139 
4140 error:
4141     Py_CLEAR(ctx->slots);
4142     Py_XDECREF(dict);
4143     return NULL;
4144 }
4145 
4146 
4147 static PyObject*
type_new_impl(type_new_ctx * ctx)4148 type_new_impl(type_new_ctx *ctx)
4149 {
4150     PyTypeObject *type = type_new_init(ctx);
4151     if (type == NULL) {
4152         return NULL;
4153     }
4154 
4155     if (type_new_set_attrs(ctx, type) < 0) {
4156         goto error;
4157     }
4158 
4159     /* Initialize the rest */
4160     if (PyType_Ready(type) < 0) {
4161         goto error;
4162     }
4163 
4164     // Put the proper slots in place
4165     fixup_slot_dispatchers(type);
4166 
4167     if (!_PyDict_HasOnlyStringKeys(type->tp_dict)) {
4168         if (PyErr_WarnFormat(
4169                 PyExc_RuntimeWarning,
4170                 1,
4171                 "non-string key in the __dict__ of class %.200s",
4172                 type->tp_name) == -1)
4173         {
4174             goto error;
4175         }
4176     }
4177 
4178     if (type_new_set_names(type) < 0) {
4179         goto error;
4180     }
4181 
4182     if (type_new_init_subclass(type, ctx->kwds) < 0) {
4183         goto error;
4184     }
4185 
4186     assert(_PyType_CheckConsistency(type));
4187 
4188     return (PyObject *)type;
4189 
4190 error:
4191     Py_DECREF(type);
4192     return NULL;
4193 }
4194 
4195 
4196 static int
type_new_get_bases(type_new_ctx * ctx,PyObject ** type)4197 type_new_get_bases(type_new_ctx *ctx, PyObject **type)
4198 {
4199     Py_ssize_t nbases = PyTuple_GET_SIZE(ctx->bases);
4200     if (nbases == 0) {
4201         // Adjust for empty tuple bases
4202         ctx->base = &PyBaseObject_Type;
4203         PyObject *new_bases = PyTuple_Pack(1, ctx->base);
4204         if (new_bases == NULL) {
4205             return -1;
4206         }
4207         ctx->bases = new_bases;
4208         return 0;
4209     }
4210 
4211     for (Py_ssize_t i = 0; i < nbases; i++) {
4212         PyObject *base = PyTuple_GET_ITEM(ctx->bases, i);
4213         if (PyType_Check(base)) {
4214             continue;
4215         }
4216         int rc = PyObject_HasAttrWithError(base, &_Py_ID(__mro_entries__));
4217         if (rc < 0) {
4218             return -1;
4219         }
4220         if (rc) {
4221             PyErr_SetString(PyExc_TypeError,
4222                             "type() doesn't support MRO entry resolution; "
4223                             "use types.new_class()");
4224             return -1;
4225         }
4226     }
4227 
4228     // Search the bases for the proper metatype to deal with this
4229     PyTypeObject *winner;
4230     winner = _PyType_CalculateMetaclass(ctx->metatype, ctx->bases);
4231     if (winner == NULL) {
4232         return -1;
4233     }
4234 
4235     if (winner != ctx->metatype) {
4236         if (winner->tp_new != type_new) {
4237             /* Pass it to the winner */
4238             *type = winner->tp_new(winner, ctx->args, ctx->kwds);
4239             if (*type == NULL) {
4240                 return -1;
4241             }
4242             return 1;
4243         }
4244 
4245         ctx->metatype = winner;
4246     }
4247 
4248     /* Calculate best base, and check that all bases are type objects */
4249     PyTypeObject *base = best_base(ctx->bases);
4250     if (base == NULL) {
4251         return -1;
4252     }
4253 
4254     ctx->base = base;
4255     ctx->bases = Py_NewRef(ctx->bases);
4256     return 0;
4257 }
4258 
4259 
4260 static PyObject *
type_new(PyTypeObject * metatype,PyObject * args,PyObject * kwds)4261 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
4262 {
4263     assert(args != NULL && PyTuple_Check(args));
4264     assert(kwds == NULL || PyDict_Check(kwds));
4265 
4266     /* Parse arguments: (name, bases, dict) */
4267     PyObject *name, *bases, *orig_dict;
4268     if (!PyArg_ParseTuple(args, "UO!O!:type.__new__",
4269                           &name,
4270                           &PyTuple_Type, &bases,
4271                           &PyDict_Type, &orig_dict))
4272     {
4273         return NULL;
4274     }
4275 
4276     type_new_ctx ctx = {
4277         .metatype = metatype,
4278         .args = args,
4279         .kwds = kwds,
4280         .orig_dict = orig_dict,
4281         .name = name,
4282         .bases = bases,
4283         .base = NULL,
4284         .slots = NULL,
4285         .nslot = 0,
4286         .add_dict = 0,
4287         .add_weak = 0,
4288         .may_add_dict = 0,
4289         .may_add_weak = 0};
4290     PyObject *type = NULL;
4291     int res = type_new_get_bases(&ctx, &type);
4292     if (res < 0) {
4293         assert(PyErr_Occurred());
4294         return NULL;
4295     }
4296     if (res == 1) {
4297         assert(type != NULL);
4298         return type;
4299     }
4300     assert(ctx.base != NULL);
4301     assert(ctx.bases != NULL);
4302 
4303     type = type_new_impl(&ctx);
4304     Py_DECREF(ctx.bases);
4305     return type;
4306 }
4307 
4308 
4309 static PyObject *
type_vectorcall(PyObject * metatype,PyObject * const * args,size_t nargsf,PyObject * kwnames)4310 type_vectorcall(PyObject *metatype, PyObject *const *args,
4311                  size_t nargsf, PyObject *kwnames)
4312 {
4313     Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
4314     if (nargs == 1 && metatype == (PyObject *)&PyType_Type){
4315         if (!_PyArg_NoKwnames("type", kwnames)) {
4316             return NULL;
4317         }
4318         return Py_NewRef(Py_TYPE(args[0]));
4319     }
4320     /* In other (much less common) cases, fall back to
4321        more flexible calling conventions. */
4322     PyThreadState *tstate = _PyThreadState_GET();
4323     return _PyObject_MakeTpCall(tstate, metatype, args, nargs, kwnames);
4324 }
4325 
4326 /* An array of type slot offsets corresponding to Py_tp_* constants,
4327   * for use in e.g. PyType_Spec and PyType_GetSlot.
4328   * Each entry has two offsets: "slot_offset" and "subslot_offset".
4329   * If is subslot_offset is -1, slot_offset is an offset within the
4330   * PyTypeObject struct.
4331   * Otherwise slot_offset is an offset to a pointer to a sub-slots struct
4332   * (such as "tp_as_number"), and subslot_offset is the offset within
4333   * that struct.
4334   * The actual table is generated by a script.
4335   */
4336 static const PySlot_Offset pyslot_offsets[] = {
4337     {0, 0},
4338 #include "typeslots.inc"
4339 };
4340 
4341 /* Align up to the nearest multiple of alignof(max_align_t)
4342  * (like _Py_ALIGN_UP, but for a size rather than pointer)
4343  */
4344 static Py_ssize_t
_align_up(Py_ssize_t size)4345 _align_up(Py_ssize_t size)
4346 {
4347     return (size + ALIGNOF_MAX_ALIGN_T - 1) & ~(ALIGNOF_MAX_ALIGN_T - 1);
4348 }
4349 
4350 /* Given a PyType_FromMetaclass `bases` argument (NULL, type, or tuple of
4351  * types), return a tuple of types.
4352  */
4353 inline static PyObject *
get_bases_tuple(PyObject * bases_in,PyType_Spec * spec)4354 get_bases_tuple(PyObject *bases_in, PyType_Spec *spec)
4355 {
4356     if (!bases_in) {
4357         /* Default: look in the spec, fall back to (type,). */
4358         PyTypeObject *base = &PyBaseObject_Type;  // borrowed ref
4359         PyObject *bases = NULL;  // borrowed ref
4360         const PyType_Slot *slot;
4361         for (slot = spec->slots; slot->slot; slot++) {
4362             switch (slot->slot) {
4363                 case Py_tp_base:
4364                     base = slot->pfunc;
4365                     break;
4366                 case Py_tp_bases:
4367                     bases = slot->pfunc;
4368                     break;
4369             }
4370         }
4371         if (!bases) {
4372             return PyTuple_Pack(1, base);
4373         }
4374         if (PyTuple_Check(bases)) {
4375             return Py_NewRef(bases);
4376         }
4377         PyErr_SetString(PyExc_SystemError, "Py_tp_bases is not a tuple");
4378         return NULL;
4379     }
4380     if (PyTuple_Check(bases_in)) {
4381         return Py_NewRef(bases_in);
4382     }
4383     // Not a tuple, should be a single type
4384     return PyTuple_Pack(1, bases_in);
4385 }
4386 
4387 static inline int
check_basicsize_includes_size_and_offsets(PyTypeObject * type)4388 check_basicsize_includes_size_and_offsets(PyTypeObject* type)
4389 {
4390     if (type->tp_alloc != PyType_GenericAlloc) {
4391         // Custom allocators can ignore tp_basicsize
4392         return 1;
4393     }
4394     Py_ssize_t max = (Py_ssize_t)type->tp_basicsize;
4395 
4396     if (type->tp_base && type->tp_base->tp_basicsize > type->tp_basicsize) {
4397         PyErr_Format(PyExc_TypeError,
4398                      "tp_basicsize for type '%s' (%d) is too small for base '%s' (%d)",
4399                      type->tp_name, type->tp_basicsize,
4400                      type->tp_base->tp_name, type->tp_base->tp_basicsize);
4401         return 0;
4402     }
4403     if (type->tp_weaklistoffset + (Py_ssize_t)sizeof(PyObject*) > max) {
4404         PyErr_Format(PyExc_TypeError,
4405                      "weaklist offset %d is out of bounds for type '%s' (tp_basicsize = %d)",
4406                      type->tp_weaklistoffset,
4407                      type->tp_name, type->tp_basicsize);
4408         return 0;
4409     }
4410     if (type->tp_dictoffset + (Py_ssize_t)sizeof(PyObject*) > max) {
4411         PyErr_Format(PyExc_TypeError,
4412                      "dict offset %d is out of bounds for type '%s' (tp_basicsize = %d)",
4413                      type->tp_dictoffset,
4414                      type->tp_name, type->tp_basicsize);
4415         return 0;
4416     }
4417     if (type->tp_vectorcall_offset + (Py_ssize_t)sizeof(vectorcallfunc*) > max) {
4418         PyErr_Format(PyExc_TypeError,
4419                      "vectorcall offset %d is out of bounds for type '%s' (tp_basicsize = %d)",
4420                      type->tp_vectorcall_offset,
4421                      type->tp_name, type->tp_basicsize);
4422         return 0;
4423     }
4424     return 1;
4425 }
4426 
4427 static PyObject *
_PyType_FromMetaclass_impl(PyTypeObject * metaclass,PyObject * module,PyType_Spec * spec,PyObject * bases_in,int _allow_tp_new)4428 _PyType_FromMetaclass_impl(
4429     PyTypeObject *metaclass, PyObject *module,
4430     PyType_Spec *spec, PyObject *bases_in, int _allow_tp_new)
4431 {
4432     /* Invariant: A non-NULL value in one of these means this function holds
4433      * a strong reference or owns allocated memory.
4434      * These get decrefed/freed/returned at the end, on both success and error.
4435      */
4436     PyHeapTypeObject *res = NULL;
4437     PyTypeObject *type;
4438     PyObject *bases = NULL;
4439     char *tp_doc = NULL;
4440     PyObject *ht_name = NULL;
4441     char *_ht_tpname = NULL;
4442 
4443     int r;
4444 
4445     /* Prepare slots that need special handling.
4446      * Keep in mind that a slot can be given multiple times:
4447      * if that would cause trouble (leaks, UB, ...), raise an exception.
4448      */
4449 
4450     const PyType_Slot *slot;
4451     Py_ssize_t nmembers = 0;
4452     Py_ssize_t weaklistoffset, dictoffset, vectorcalloffset;
4453     char *res_start;
4454 
4455     nmembers = weaklistoffset = dictoffset = vectorcalloffset = 0;
4456     for (slot = spec->slots; slot->slot; slot++) {
4457         if (slot->slot < 0
4458             || (size_t)slot->slot >= Py_ARRAY_LENGTH(pyslot_offsets)) {
4459             PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
4460             goto finally;
4461         }
4462         switch (slot->slot) {
4463         case Py_tp_members:
4464             if (nmembers != 0) {
4465                 PyErr_SetString(
4466                     PyExc_SystemError,
4467                     "Multiple Py_tp_members slots are not supported.");
4468                 goto finally;
4469             }
4470             for (const PyMemberDef *memb = slot->pfunc; memb->name != NULL; memb++) {
4471                 nmembers++;
4472                 if (strcmp(memb->name, "__weaklistoffset__") == 0) {
4473                     // The PyMemberDef must be a Py_ssize_t and readonly
4474                     assert(memb->type == Py_T_PYSSIZET);
4475                     assert(memb->flags == Py_READONLY);
4476                     weaklistoffset = memb->offset;
4477                 }
4478                 if (strcmp(memb->name, "__dictoffset__") == 0) {
4479                     // The PyMemberDef must be a Py_ssize_t and readonly
4480                     assert(memb->type == Py_T_PYSSIZET);
4481                     assert(memb->flags == Py_READONLY);
4482                     dictoffset = memb->offset;
4483                 }
4484                 if (strcmp(memb->name, "__vectorcalloffset__") == 0) {
4485                     // The PyMemberDef must be a Py_ssize_t and readonly
4486                     assert(memb->type == Py_T_PYSSIZET);
4487                     assert(memb->flags == Py_READONLY);
4488                     vectorcalloffset = memb->offset;
4489                 }
4490                 if (memb->flags & Py_RELATIVE_OFFSET) {
4491                     if (spec->basicsize > 0) {
4492                         PyErr_SetString(
4493                             PyExc_SystemError,
4494                             "With Py_RELATIVE_OFFSET, basicsize must be negative.");
4495                         goto finally;
4496                     }
4497                     if (memb->offset < 0 || memb->offset >= -spec->basicsize) {
4498                         PyErr_SetString(
4499                             PyExc_SystemError,
4500                             "Member offset out of range (0..-basicsize)");
4501                         goto finally;
4502                     }
4503                 }
4504             }
4505             break;
4506         case Py_tp_doc:
4507             /* For the docstring slot, which usually points to a static string
4508                literal, we need to make a copy */
4509             if (tp_doc != NULL) {
4510                 PyErr_SetString(
4511                     PyExc_SystemError,
4512                     "Multiple Py_tp_doc slots are not supported.");
4513                 goto finally;
4514             }
4515             if (slot->pfunc == NULL) {
4516                 PyMem_Free(tp_doc);
4517                 tp_doc = NULL;
4518             }
4519             else {
4520                 size_t len = strlen(slot->pfunc)+1;
4521                 tp_doc = PyMem_Malloc(len);
4522                 if (tp_doc == NULL) {
4523                     PyErr_NoMemory();
4524                     goto finally;
4525                 }
4526                 memcpy(tp_doc, slot->pfunc, len);
4527             }
4528             break;
4529         }
4530     }
4531 
4532     /* Prepare the type name and qualname */
4533 
4534     if (spec->name == NULL) {
4535         PyErr_SetString(PyExc_SystemError,
4536                         "Type spec does not define the name field.");
4537         goto finally;
4538     }
4539 
4540     const char *s = strrchr(spec->name, '.');
4541     if (s == NULL) {
4542         s = spec->name;
4543     }
4544     else {
4545         s++;
4546     }
4547 
4548     ht_name = PyUnicode_FromString(s);
4549     if (!ht_name) {
4550         goto finally;
4551     }
4552 
4553     /* Copy spec->name to a buffer we own.
4554     *
4555     * Unfortunately, we can't use tp_name directly (with some
4556     * flag saying that it should be deallocated with the type),
4557     * because tp_name is public API and may be set independently
4558     * of any such flag.
4559     * So, we use a separate buffer, _ht_tpname, that's always
4560     * deallocated with the type (if it's non-NULL).
4561     */
4562     Py_ssize_t name_buf_len = strlen(spec->name) + 1;
4563     _ht_tpname = PyMem_Malloc(name_buf_len);
4564     if (_ht_tpname == NULL) {
4565         goto finally;
4566     }
4567     memcpy(_ht_tpname, spec->name, name_buf_len);
4568 
4569     /* Get a tuple of bases.
4570      * bases is a strong reference (unlike bases_in).
4571      */
4572     bases = get_bases_tuple(bases_in, spec);
4573     if (!bases) {
4574         goto finally;
4575     }
4576 
4577     /* If this is an immutable type, check if all bases are also immutable,
4578      * and (for now) fire a deprecation warning if not.
4579      * (This isn't necessary for static types: those can't have heap bases,
4580      * and only heap types can be mutable.)
4581      */
4582     if (spec->flags & Py_TPFLAGS_IMMUTABLETYPE) {
4583         for (int i=0; i<PyTuple_GET_SIZE(bases); i++) {
4584             PyTypeObject *b = (PyTypeObject*)PyTuple_GET_ITEM(bases, i);
4585             if (!b) {
4586                 goto finally;
4587             }
4588             if (!_PyType_HasFeature(b, Py_TPFLAGS_IMMUTABLETYPE)) {
4589                 if (PyErr_WarnFormat(
4590                     PyExc_DeprecationWarning,
4591                     0,
4592                     "Creating immutable type %s from mutable base %s is "
4593                     "deprecated, and slated to be disallowed in Python 3.14.",
4594                     spec->name,
4595                     b->tp_name))
4596                 {
4597                     goto finally;
4598                 }
4599             }
4600         }
4601     }
4602 
4603     /* Calculate the metaclass */
4604 
4605     if (!metaclass) {
4606         metaclass = &PyType_Type;
4607     }
4608     metaclass = _PyType_CalculateMetaclass(metaclass, bases);
4609     if (metaclass == NULL) {
4610         goto finally;
4611     }
4612     if (!PyType_Check(metaclass)) {
4613         PyErr_Format(PyExc_TypeError,
4614                      "Metaclass '%R' is not a subclass of 'type'.",
4615                      metaclass);
4616         goto finally;
4617     }
4618     if (metaclass->tp_new && metaclass->tp_new != PyType_Type.tp_new) {
4619         if (_allow_tp_new) {
4620             if (PyErr_WarnFormat(
4621                     PyExc_DeprecationWarning, 1,
4622                     "Type %s uses PyType_Spec with a metaclass that has custom "
4623                     "tp_new. This is deprecated and will no longer be allowed in "
4624                     "Python 3.14.", spec->name) < 0) {
4625                 goto finally;
4626             }
4627         }
4628         else {
4629             PyErr_SetString(
4630                 PyExc_TypeError,
4631                 "Metaclasses with custom tp_new are not supported.");
4632             goto finally;
4633         }
4634     }
4635 
4636     /* Calculate best base, and check that all bases are type objects */
4637     PyTypeObject *base = best_base(bases);  // borrowed ref
4638     if (base == NULL) {
4639         goto finally;
4640     }
4641     // best_base should check Py_TPFLAGS_BASETYPE & raise a proper exception,
4642     // here we just check its work
4643     assert(_PyType_HasFeature(base, Py_TPFLAGS_BASETYPE));
4644 
4645     /* Calculate sizes */
4646 
4647     Py_ssize_t basicsize = spec->basicsize;
4648     Py_ssize_t type_data_offset = spec->basicsize;
4649     if (basicsize == 0) {
4650         /* Inherit */
4651         basicsize = base->tp_basicsize;
4652     }
4653     else if (basicsize < 0) {
4654         /* Extend */
4655         type_data_offset = _align_up(base->tp_basicsize);
4656         basicsize = type_data_offset + _align_up(-spec->basicsize);
4657 
4658         /* Inheriting variable-sized types is limited */
4659         if (base->tp_itemsize
4660             && !((base->tp_flags | spec->flags) & Py_TPFLAGS_ITEMS_AT_END))
4661         {
4662             PyErr_SetString(
4663                 PyExc_SystemError,
4664                 "Cannot extend variable-size class without Py_TPFLAGS_ITEMS_AT_END.");
4665             goto finally;
4666         }
4667     }
4668 
4669     Py_ssize_t itemsize = spec->itemsize;
4670 
4671     /* Allocate the new type
4672      *
4673      * Between here and PyType_Ready, we should limit:
4674      * - calls to Python code
4675      * - raising exceptions
4676      * - memory allocations
4677      */
4678 
4679     res = (PyHeapTypeObject*)metaclass->tp_alloc(metaclass, nmembers);
4680     if (res == NULL) {
4681         goto finally;
4682     }
4683     res_start = (char*)res;
4684 
4685     type = &res->ht_type;
4686     /* The flags must be initialized early, before the GC traverses us */
4687     type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
4688 
4689     res->ht_module = Py_XNewRef(module);
4690 
4691     /* Initialize essential fields */
4692 
4693     type->tp_as_async = &res->as_async;
4694     type->tp_as_number = &res->as_number;
4695     type->tp_as_sequence = &res->as_sequence;
4696     type->tp_as_mapping = &res->as_mapping;
4697     type->tp_as_buffer = &res->as_buffer;
4698 
4699     /* Set slots we have prepared */
4700 
4701     type->tp_base = (PyTypeObject *)Py_NewRef(base);
4702     set_tp_bases(type, bases, 1);
4703     bases = NULL;  // We give our reference to bases to the type
4704 
4705     type->tp_doc = tp_doc;
4706     tp_doc = NULL;  // Give ownership of the allocated memory to the type
4707 
4708     res->ht_qualname = Py_NewRef(ht_name);
4709     res->ht_name = ht_name;
4710     ht_name = NULL;  // Give our reference to the type
4711 
4712     type->tp_name = _ht_tpname;
4713     res->_ht_tpname = _ht_tpname;
4714     _ht_tpname = NULL;  // Give ownership to the type
4715 
4716     /* Copy the sizes */
4717 
4718     type->tp_basicsize = basicsize;
4719     type->tp_itemsize = itemsize;
4720 
4721     /* Copy all the ordinary slots */
4722 
4723     for (slot = spec->slots; slot->slot; slot++) {
4724         switch (slot->slot) {
4725         case Py_tp_base:
4726         case Py_tp_bases:
4727         case Py_tp_doc:
4728             /* Processed above */
4729             break;
4730         case Py_tp_members:
4731             {
4732                 /* Move the slots to the heap type itself */
4733                 size_t len = Py_TYPE(type)->tp_itemsize * nmembers;
4734                 memcpy(_PyHeapType_GET_MEMBERS(res), slot->pfunc, len);
4735                 type->tp_members = _PyHeapType_GET_MEMBERS(res);
4736                 PyMemberDef *memb;
4737                 Py_ssize_t i;
4738                 for (memb = _PyHeapType_GET_MEMBERS(res), i = nmembers;
4739                      i > 0; ++memb, --i)
4740                 {
4741                     if (memb->flags & Py_RELATIVE_OFFSET) {
4742                         memb->flags &= ~Py_RELATIVE_OFFSET;
4743                         memb->offset += type_data_offset;
4744                     }
4745                 }
4746             }
4747             break;
4748         default:
4749             {
4750                 /* Copy other slots directly */
4751                 PySlot_Offset slotoffsets = pyslot_offsets[slot->slot];
4752                 short slot_offset = slotoffsets.slot_offset;
4753                 if (slotoffsets.subslot_offset == -1) {
4754                     /* Set a slot in the main PyTypeObject */
4755                     *(void**)((char*)res_start + slot_offset) = slot->pfunc;
4756                 }
4757                 else {
4758                     void *procs = *(void**)((char*)res_start + slot_offset);
4759                     short subslot_offset = slotoffsets.subslot_offset;
4760                     *(void**)((char*)procs + subslot_offset) = slot->pfunc;
4761                 }
4762             }
4763             break;
4764         }
4765     }
4766     if (type->tp_dealloc == NULL) {
4767         /* It's a heap type, so needs the heap types' dealloc.
4768            subtype_dealloc will call the base type's tp_dealloc, if
4769            necessary. */
4770         type->tp_dealloc = subtype_dealloc;
4771     }
4772 
4773     /* Set up offsets */
4774 
4775     type->tp_vectorcall_offset = vectorcalloffset;
4776     type->tp_weaklistoffset = weaklistoffset;
4777     type->tp_dictoffset = dictoffset;
4778 
4779     /* Ready the type (which includes inheritance).
4780      *
4781      * After this call we should generally only touch up what's
4782      * accessible to Python code, like __dict__.
4783      */
4784 
4785     if (PyType_Ready(type) < 0) {
4786         goto finally;
4787     }
4788 
4789     if (!check_basicsize_includes_size_and_offsets(type)) {
4790         goto finally;
4791     }
4792 
4793     PyObject *dict = lookup_tp_dict(type);
4794     if (type->tp_doc) {
4795         PyObject *__doc__ = PyUnicode_FromString(_PyType_DocWithoutSignature(type->tp_name, type->tp_doc));
4796         if (!__doc__) {
4797             goto finally;
4798         }
4799         r = PyDict_SetItem(dict, &_Py_ID(__doc__), __doc__);
4800         Py_DECREF(__doc__);
4801         if (r < 0) {
4802             goto finally;
4803         }
4804     }
4805 
4806     if (weaklistoffset) {
4807         if (PyDict_DelItem(dict, &_Py_ID(__weaklistoffset__)) < 0) {
4808             goto finally;
4809         }
4810     }
4811     if (dictoffset) {
4812         if (PyDict_DelItem(dict, &_Py_ID(__dictoffset__)) < 0) {
4813             goto finally;
4814         }
4815     }
4816 
4817     /* Set type.__module__ */
4818     r = PyDict_Contains(dict, &_Py_ID(__module__));
4819     if (r < 0) {
4820         goto finally;
4821     }
4822     if (r == 0) {
4823         s = strrchr(spec->name, '.');
4824         if (s != NULL) {
4825             PyObject *modname = PyUnicode_FromStringAndSize(
4826                     spec->name, (Py_ssize_t)(s - spec->name));
4827             if (modname == NULL) {
4828                 goto finally;
4829             }
4830             r = PyDict_SetItem(dict, &_Py_ID(__module__), modname);
4831             Py_DECREF(modname);
4832             if (r != 0) {
4833                 goto finally;
4834             }
4835         }
4836         else {
4837             if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
4838                     "builtin type %.200s has no __module__ attribute",
4839                     spec->name))
4840                 goto finally;
4841         }
4842     }
4843 
4844     assert(_PyType_CheckConsistency(type));
4845 
4846  finally:
4847     if (PyErr_Occurred()) {
4848         Py_CLEAR(res);
4849     }
4850     Py_XDECREF(bases);
4851     PyMem_Free(tp_doc);
4852     Py_XDECREF(ht_name);
4853     PyMem_Free(_ht_tpname);
4854     return (PyObject*)res;
4855 }
4856 
4857 PyObject *
PyType_FromMetaclass(PyTypeObject * metaclass,PyObject * module,PyType_Spec * spec,PyObject * bases_in)4858 PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module,
4859                      PyType_Spec *spec, PyObject *bases_in)
4860 {
4861     return _PyType_FromMetaclass_impl(metaclass, module, spec, bases_in, 0);
4862 }
4863 
4864 PyObject *
PyType_FromModuleAndSpec(PyObject * module,PyType_Spec * spec,PyObject * bases)4865 PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
4866 {
4867     return _PyType_FromMetaclass_impl(NULL, module, spec, bases, 1);
4868 }
4869 
4870 PyObject *
PyType_FromSpecWithBases(PyType_Spec * spec,PyObject * bases)4871 PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
4872 {
4873     return _PyType_FromMetaclass_impl(NULL, NULL, spec, bases, 1);
4874 }
4875 
4876 PyObject *
PyType_FromSpec(PyType_Spec * spec)4877 PyType_FromSpec(PyType_Spec *spec)
4878 {
4879     return _PyType_FromMetaclass_impl(NULL, NULL, spec, NULL, 1);
4880 }
4881 
4882 PyObject *
PyType_GetName(PyTypeObject * type)4883 PyType_GetName(PyTypeObject *type)
4884 {
4885     return type_name(type, NULL);
4886 }
4887 
4888 PyObject *
PyType_GetQualName(PyTypeObject * type)4889 PyType_GetQualName(PyTypeObject *type)
4890 {
4891     return type_qualname(type, NULL);
4892 }
4893 
4894 PyObject *
PyType_GetModuleName(PyTypeObject * type)4895 PyType_GetModuleName(PyTypeObject *type)
4896 {
4897     return type_module(type);
4898 }
4899 
4900 void *
PyType_GetSlot(PyTypeObject * type,int slot)4901 PyType_GetSlot(PyTypeObject *type, int slot)
4902 {
4903     void *parent_slot;
4904     int slots_len = Py_ARRAY_LENGTH(pyslot_offsets);
4905 
4906     if (slot <= 0 || slot >= slots_len) {
4907         PyErr_BadInternalCall();
4908         return NULL;
4909     }
4910 
4911     parent_slot = *(void**)((char*)type + pyslot_offsets[slot].slot_offset);
4912     if (parent_slot == NULL) {
4913         return NULL;
4914     }
4915     /* Return slot directly if we have no sub slot. */
4916     if (pyslot_offsets[slot].subslot_offset == -1) {
4917         return parent_slot;
4918     }
4919     return *(void**)((char*)parent_slot + pyslot_offsets[slot].subslot_offset);
4920 }
4921 
4922 PyObject *
PyType_GetModule(PyTypeObject * type)4923 PyType_GetModule(PyTypeObject *type)
4924 {
4925     assert(PyType_Check(type));
4926     if (!_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
4927         PyErr_Format(
4928             PyExc_TypeError,
4929             "PyType_GetModule: Type '%s' is not a heap type",
4930             type->tp_name);
4931         return NULL;
4932     }
4933 
4934     PyHeapTypeObject* et = (PyHeapTypeObject*)type;
4935     if (!et->ht_module) {
4936         PyErr_Format(
4937             PyExc_TypeError,
4938             "PyType_GetModule: Type '%s' has no associated module",
4939             type->tp_name);
4940         return NULL;
4941     }
4942     return et->ht_module;
4943 
4944 }
4945 
4946 void *
PyType_GetModuleState(PyTypeObject * type)4947 PyType_GetModuleState(PyTypeObject *type)
4948 {
4949     PyObject *m = PyType_GetModule(type);
4950     if (m == NULL) {
4951         return NULL;
4952     }
4953     return _PyModule_GetState(m);
4954 }
4955 
4956 
4957 /* Get the module of the first superclass where the module has the
4958  * given PyModuleDef.
4959  */
4960 static inline PyObject *
get_module_by_def(PyTypeObject * type,PyModuleDef * def)4961 get_module_by_def(PyTypeObject *type, PyModuleDef *def)
4962 {
4963     assert(PyType_Check(type));
4964 
4965     if (!_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
4966         // type_ready_mro() ensures that no heap type is
4967         // contained in a static type MRO.
4968         return NULL;
4969     }
4970     else {
4971         PyHeapTypeObject *ht = (PyHeapTypeObject*)type;
4972         PyObject *module = ht->ht_module;
4973         if (module && _PyModule_GetDef(module) == def) {
4974             return module;
4975         }
4976     }
4977 
4978     PyObject *res = NULL;
4979     BEGIN_TYPE_LOCK();
4980 
4981     PyObject *mro = lookup_tp_mro(type);
4982     // The type must be ready
4983     assert(mro != NULL);
4984     assert(PyTuple_Check(mro));
4985     // mro_invoke() ensures that the type MRO cannot be empty.
4986     assert(PyTuple_GET_SIZE(mro) >= 1);
4987     // Also, the first item in the MRO is the type itself, which
4988     // we already checked above. We skip it in the loop.
4989     assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type);
4990 
4991     Py_ssize_t n = PyTuple_GET_SIZE(mro);
4992     for (Py_ssize_t i = 1; i < n; i++) {
4993         PyObject *super = PyTuple_GET_ITEM(mro, i);
4994         if(!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) {
4995             // Static types in the MRO need to be skipped
4996             continue;
4997         }
4998 
4999         PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
5000         PyObject *module = ht->ht_module;
5001         if (module && _PyModule_GetDef(module) == def) {
5002             res = module;
5003             break;
5004         }
5005     }
5006     END_TYPE_LOCK();
5007     return res;
5008 }
5009 
5010 PyObject *
PyType_GetModuleByDef(PyTypeObject * type,PyModuleDef * def)5011 PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
5012 {
5013     PyObject *module = get_module_by_def(type, def);
5014     if (module == NULL) {
5015         PyErr_Format(
5016             PyExc_TypeError,
5017             "PyType_GetModuleByDef: No superclass of '%s' has the given module",
5018             type->tp_name);
5019     }
5020     return module;
5021 }
5022 
5023 PyObject *
_PyType_GetModuleByDef2(PyTypeObject * left,PyTypeObject * right,PyModuleDef * def)5024 _PyType_GetModuleByDef2(PyTypeObject *left, PyTypeObject *right,
5025                         PyModuleDef *def)
5026 {
5027     PyObject *module = get_module_by_def(left, def);
5028     if (module == NULL) {
5029         module = get_module_by_def(right, def);
5030         if (module == NULL) {
5031             PyErr_Format(
5032                 PyExc_TypeError,
5033                 "PyType_GetModuleByDef: No superclass of '%s' nor '%s' has "
5034                 "the given module", left->tp_name, right->tp_name);
5035         }
5036     }
5037     return module;
5038 }
5039 
5040 void *
PyObject_GetTypeData(PyObject * obj,PyTypeObject * cls)5041 PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls)
5042 {
5043     assert(PyObject_TypeCheck(obj, cls));
5044     return (char *)obj + _align_up(cls->tp_base->tp_basicsize);
5045 }
5046 
5047 Py_ssize_t
PyType_GetTypeDataSize(PyTypeObject * cls)5048 PyType_GetTypeDataSize(PyTypeObject *cls)
5049 {
5050     ptrdiff_t result = cls->tp_basicsize - _align_up(cls->tp_base->tp_basicsize);
5051     if (result < 0) {
5052         return 0;
5053     }
5054     return result;
5055 }
5056 
5057 void *
PyObject_GetItemData(PyObject * obj)5058 PyObject_GetItemData(PyObject *obj)
5059 {
5060     if (!PyType_HasFeature(Py_TYPE(obj), Py_TPFLAGS_ITEMS_AT_END)) {
5061         PyErr_Format(PyExc_TypeError,
5062                      "type '%s' does not have Py_TPFLAGS_ITEMS_AT_END",
5063                      Py_TYPE(obj)->tp_name);
5064         return NULL;
5065     }
5066     return (char *)obj + Py_TYPE(obj)->tp_basicsize;
5067 }
5068 
5069 /* Internal API to look for a name through the MRO, bypassing the method cache.
5070    This returns a borrowed reference, and might set an exception.
5071    'error' is set to: -1: error with exception; 1: error without exception; 0: ok */
5072 static PyObject *
find_name_in_mro(PyTypeObject * type,PyObject * name,int * error)5073 find_name_in_mro(PyTypeObject *type, PyObject *name, int *error)
5074 {
5075     ASSERT_TYPE_LOCK_HELD();
5076 
5077     Py_hash_t hash = _PyObject_HashFast(name);
5078     if (hash == -1) {
5079         *error = -1;
5080         return NULL;
5081     }
5082 
5083     /* Look in tp_dict of types in MRO */
5084     PyObject *mro = lookup_tp_mro(type);
5085     if (mro == NULL) {
5086         if (!is_readying(type)) {
5087             if (PyType_Ready(type) < 0) {
5088                 *error = -1;
5089                 return NULL;
5090             }
5091             mro = lookup_tp_mro(type);
5092         }
5093         if (mro == NULL) {
5094             *error = 1;
5095             return NULL;
5096         }
5097     }
5098 
5099     PyObject *res = NULL;
5100     /* Keep a strong reference to mro because type->tp_mro can be replaced
5101        during dict lookup, e.g. when comparing to non-string keys. */
5102     Py_INCREF(mro);
5103     Py_ssize_t n = PyTuple_GET_SIZE(mro);
5104     for (Py_ssize_t i = 0; i < n; i++) {
5105         PyObject *base = PyTuple_GET_ITEM(mro, i);
5106         PyObject *dict = lookup_tp_dict(_PyType_CAST(base));
5107         assert(dict && PyDict_Check(dict));
5108         if (_PyDict_GetItemRef_KnownHash((PyDictObject *)dict, name, hash, &res) < 0) {
5109             *error = -1;
5110             goto done;
5111         }
5112         if (res != NULL) {
5113             break;
5114         }
5115     }
5116     *error = 0;
5117 done:
5118     Py_DECREF(mro);
5119     return res;
5120 }
5121 
5122 /* Check if the "readied" PyUnicode name
5123    is a double-underscore special name. */
5124 static int
is_dunder_name(PyObject * name)5125 is_dunder_name(PyObject *name)
5126 {
5127     Py_ssize_t length = PyUnicode_GET_LENGTH(name);
5128     int kind = PyUnicode_KIND(name);
5129     /* Special names contain at least "__x__" and are always ASCII. */
5130     if (length > 4 && kind == PyUnicode_1BYTE_KIND) {
5131         const Py_UCS1 *characters = PyUnicode_1BYTE_DATA(name);
5132         return (
5133             ((characters[length-2] == '_') && (characters[length-1] == '_')) &&
5134             ((characters[0] == '_') && (characters[1] == '_'))
5135         );
5136     }
5137     return 0;
5138 }
5139 
5140 static PyObject *
update_cache(struct type_cache_entry * entry,PyObject * name,unsigned int version_tag,PyObject * value)5141 update_cache(struct type_cache_entry *entry, PyObject *name, unsigned int version_tag, PyObject *value)
5142 {
5143     _Py_atomic_store_uint32_relaxed(&entry->version, version_tag);
5144     _Py_atomic_store_ptr_relaxed(&entry->value, value); /* borrowed */
5145     assert(_PyASCIIObject_CAST(name)->hash != -1);
5146     OBJECT_STAT_INC_COND(type_cache_collisions, entry->name != Py_None && entry->name != name);
5147     // We're releasing this under the lock for simplicity sake because it's always a
5148     // exact unicode object or Py_None so it's safe to do so.
5149     PyObject *old_name = entry->name;
5150     _Py_atomic_store_ptr_relaxed(&entry->name, Py_NewRef(name));
5151     return old_name;
5152 }
5153 
5154 #if Py_GIL_DISABLED
5155 
5156 static void
update_cache_gil_disabled(struct type_cache_entry * entry,PyObject * name,unsigned int version_tag,PyObject * value)5157 update_cache_gil_disabled(struct type_cache_entry *entry, PyObject *name,
5158                           unsigned int version_tag, PyObject *value)
5159 {
5160     _PySeqLock_LockWrite(&entry->sequence);
5161 
5162     // update the entry
5163     if (entry->name == name &&
5164         entry->value == value &&
5165         entry->version == version_tag) {
5166         // We raced with another update, bail and restore previous sequence.
5167         _PySeqLock_AbandonWrite(&entry->sequence);
5168         return;
5169     }
5170 
5171     PyObject *old_value = update_cache(entry, name, version_tag, value);
5172 
5173     // Then update sequence to the next valid value
5174     _PySeqLock_UnlockWrite(&entry->sequence);
5175 
5176     Py_DECREF(old_value);
5177 }
5178 
5179 #endif
5180 
5181 void
_PyTypes_AfterFork(void)5182 _PyTypes_AfterFork(void)
5183 {
5184 #ifdef Py_GIL_DISABLED
5185     struct type_cache *cache = get_type_cache();
5186     for (Py_ssize_t i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
5187         struct type_cache_entry *entry = &cache->hashtable[i];
5188         if (_PySeqLock_AfterFork(&entry->sequence)) {
5189             // Entry was in the process of updating while forking, clear it...
5190             entry->value = NULL;
5191             Py_SETREF(entry->name, Py_None);
5192             entry->version = 0;
5193         }
5194     }
5195 #endif
5196 }
5197 
5198 /* Internal API to look for a name through the MRO.
5199    This returns a borrowed reference, and doesn't set an exception! */
5200 PyObject *
_PyType_LookupRef(PyTypeObject * type,PyObject * name)5201 _PyType_LookupRef(PyTypeObject *type, PyObject *name)
5202 {
5203     PyObject *res;
5204     int error;
5205     PyInterpreterState *interp = _PyInterpreterState_GET();
5206 
5207     unsigned int h = MCACHE_HASH_METHOD(type, name);
5208     struct type_cache *cache = get_type_cache();
5209     struct type_cache_entry *entry = &cache->hashtable[h];
5210 #ifdef Py_GIL_DISABLED
5211     // synchronize-with other writing threads by doing an acquire load on the sequence
5212     while (1) {
5213         uint32_t sequence = _PySeqLock_BeginRead(&entry->sequence);
5214         uint32_t entry_version = _Py_atomic_load_uint32_relaxed(&entry->version);
5215         uint32_t type_version = _Py_atomic_load_uint32_acquire(&type->tp_version_tag);
5216         if (entry_version == type_version &&
5217             _Py_atomic_load_ptr_relaxed(&entry->name) == name) {
5218             OBJECT_STAT_INC_COND(type_cache_hits, !is_dunder_name(name));
5219             OBJECT_STAT_INC_COND(type_cache_dunder_hits, is_dunder_name(name));
5220             PyObject *value = _Py_atomic_load_ptr_relaxed(&entry->value);
5221             // If the sequence is still valid then we're done
5222             if (value == NULL || _Py_TryIncref(value)) {
5223                 if (_PySeqLock_EndRead(&entry->sequence, sequence)) {
5224                     return value;
5225                 }
5226                 Py_XDECREF(value);
5227             }
5228             else {
5229                 // If we can't incref the object we need to fallback to locking
5230                 break;
5231             }
5232         }
5233         else {
5234             // cache miss
5235             break;
5236         }
5237     }
5238 #else
5239     if (entry->version == type->tp_version_tag &&
5240         entry->name == name) {
5241         assert(type->tp_version_tag);
5242         OBJECT_STAT_INC_COND(type_cache_hits, !is_dunder_name(name));
5243         OBJECT_STAT_INC_COND(type_cache_dunder_hits, is_dunder_name(name));
5244         Py_XINCREF(entry->value);
5245         return entry->value;
5246     }
5247 #endif
5248     OBJECT_STAT_INC_COND(type_cache_misses, !is_dunder_name(name));
5249     OBJECT_STAT_INC_COND(type_cache_dunder_misses, is_dunder_name(name));
5250 
5251     /* We may end up clearing live exceptions below, so make sure it's ours. */
5252     assert(!PyErr_Occurred());
5253 
5254     // We need to atomically do the lookup and capture the version before
5255     // anyone else can modify our mro or mutate the type.
5256 
5257     int has_version = 0;
5258     int version = 0;
5259     BEGIN_TYPE_LOCK();
5260     res = find_name_in_mro(type, name, &error);
5261     if (MCACHE_CACHEABLE_NAME(name)) {
5262         has_version = assign_version_tag(interp, type);
5263         version = type->tp_version_tag;
5264     }
5265     END_TYPE_LOCK();
5266 
5267     /* Only put NULL results into cache if there was no error. */
5268     if (error) {
5269         /* It's not ideal to clear the error condition,
5270            but this function is documented as not setting
5271            an exception, and I don't want to change that.
5272            E.g., when PyType_Ready() can't proceed, it won't
5273            set the "ready" flag, so future attempts to ready
5274            the same type will call it again -- hopefully
5275            in a context that propagates the exception out.
5276         */
5277         if (error == -1) {
5278             PyErr_Clear();
5279         }
5280         return NULL;
5281     }
5282 
5283     if (has_version) {
5284 #if Py_GIL_DISABLED
5285         update_cache_gil_disabled(entry, name, version, res);
5286 #else
5287         PyObject *old_value = update_cache(entry, name, version, res);
5288         Py_DECREF(old_value);
5289 #endif
5290     }
5291     return res;
5292 }
5293 
5294 PyObject *
_PyType_Lookup(PyTypeObject * type,PyObject * name)5295 _PyType_Lookup(PyTypeObject *type, PyObject *name)
5296 {
5297     PyObject *res = _PyType_LookupRef(type, name);
5298     Py_XDECREF(res);
5299     return res;
5300 }
5301 
5302 PyObject *
_PyType_LookupId(PyTypeObject * type,_Py_Identifier * name)5303 _PyType_LookupId(PyTypeObject *type, _Py_Identifier *name)
5304 {
5305     PyObject *oname;
5306     oname = _PyUnicode_FromId(name);   /* borrowed */
5307     if (oname == NULL)
5308         return NULL;
5309     return _PyType_Lookup(type, oname);
5310 }
5311 
5312 static void
set_flags(PyTypeObject * self,unsigned long mask,unsigned long flags)5313 set_flags(PyTypeObject *self, unsigned long mask, unsigned long flags)
5314 {
5315     ASSERT_TYPE_LOCK_HELD();
5316     self->tp_flags = (self->tp_flags & ~mask) | flags;
5317 }
5318 
5319 void
_PyType_SetFlags(PyTypeObject * self,unsigned long mask,unsigned long flags)5320 _PyType_SetFlags(PyTypeObject *self, unsigned long mask, unsigned long flags)
5321 {
5322     BEGIN_TYPE_LOCK();
5323     set_flags(self, mask, flags);
5324     END_TYPE_LOCK();
5325 }
5326 
5327 static void
set_flags_recursive(PyTypeObject * self,unsigned long mask,unsigned long flags)5328 set_flags_recursive(PyTypeObject *self, unsigned long mask, unsigned long flags)
5329 {
5330     if (PyType_HasFeature(self, Py_TPFLAGS_IMMUTABLETYPE) ||
5331         (self->tp_flags & mask) == flags)
5332     {
5333         return;
5334     }
5335 
5336     set_flags(self, mask, flags);
5337 
5338     PyObject *children = _PyType_GetSubclasses(self);
5339     if (children == NULL) {
5340         return;
5341     }
5342 
5343     for (Py_ssize_t i = 0; i < PyList_GET_SIZE(children); i++) {
5344         PyObject *child = PyList_GET_ITEM(children, i);
5345         set_flags_recursive((PyTypeObject *)child, mask, flags);
5346     }
5347     Py_DECREF(children);
5348 }
5349 
5350 void
_PyType_SetFlagsRecursive(PyTypeObject * self,unsigned long mask,unsigned long flags)5351 _PyType_SetFlagsRecursive(PyTypeObject *self, unsigned long mask, unsigned long flags)
5352 {
5353     BEGIN_TYPE_LOCK();
5354     set_flags_recursive(self, mask, flags);
5355     END_TYPE_LOCK();
5356 }
5357 
5358 /* This is similar to PyObject_GenericGetAttr(),
5359    but uses _PyType_LookupRef() instead of just looking in type->tp_dict.
5360 
5361    The argument suppress_missing_attribute is used to provide a
5362    fast path for hasattr. The possible values are:
5363 
5364    * NULL: do not suppress the exception
5365    * Non-zero pointer: suppress the PyExc_AttributeError and
5366      set *suppress_missing_attribute to 1 to signal we are returning NULL while
5367      having suppressed the exception (other exceptions are not suppressed)
5368 
5369    */
5370 PyObject *
_Py_type_getattro_impl(PyTypeObject * type,PyObject * name,int * suppress_missing_attribute)5371 _Py_type_getattro_impl(PyTypeObject *type, PyObject *name, int * suppress_missing_attribute)
5372 {
5373     PyTypeObject *metatype = Py_TYPE(type);
5374     PyObject *meta_attribute, *attribute;
5375     descrgetfunc meta_get;
5376     PyObject* res;
5377 
5378     if (!PyUnicode_Check(name)) {
5379         PyErr_Format(PyExc_TypeError,
5380                      "attribute name must be string, not '%.200s'",
5381                      Py_TYPE(name)->tp_name);
5382         return NULL;
5383     }
5384 
5385     /* Initialize this type (we'll assume the metatype is initialized) */
5386     if (!_PyType_IsReady(type)) {
5387         if (PyType_Ready(type) < 0)
5388             return NULL;
5389     }
5390 
5391     /* No readable descriptor found yet */
5392     meta_get = NULL;
5393 
5394     /* Look for the attribute in the metatype */
5395     meta_attribute = _PyType_LookupRef(metatype, name);
5396 
5397     if (meta_attribute != NULL) {
5398         meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
5399 
5400         if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
5401             /* Data descriptors implement tp_descr_set to intercept
5402              * writes. Assume the attribute is not overridden in
5403              * type's tp_dict (and bases): call the descriptor now.
5404              */
5405             res = meta_get(meta_attribute, (PyObject *)type,
5406                            (PyObject *)metatype);
5407             Py_DECREF(meta_attribute);
5408             return res;
5409         }
5410     }
5411 
5412     /* No data descriptor found on metatype. Look in tp_dict of this
5413      * type and its bases */
5414     attribute = _PyType_LookupRef(type, name);
5415     if (attribute != NULL) {
5416         /* Implement descriptor functionality, if any */
5417         descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
5418 
5419         Py_XDECREF(meta_attribute);
5420 
5421         if (local_get != NULL) {
5422             /* NULL 2nd argument indicates the descriptor was
5423              * found on the target object itself (or a base)  */
5424             res = local_get(attribute, (PyObject *)NULL,
5425                             (PyObject *)type);
5426             Py_DECREF(attribute);
5427             return res;
5428         }
5429 
5430         return attribute;
5431     }
5432 
5433     /* No attribute found in local __dict__ (or bases): use the
5434      * descriptor from the metatype, if any */
5435     if (meta_get != NULL) {
5436         PyObject *res;
5437         res = meta_get(meta_attribute, (PyObject *)type,
5438                        (PyObject *)metatype);
5439         Py_DECREF(meta_attribute);
5440         return res;
5441     }
5442 
5443     /* If an ordinary attribute was found on the metatype, return it now */
5444     if (meta_attribute != NULL) {
5445         return meta_attribute;
5446     }
5447 
5448     /* Give up */
5449     if (suppress_missing_attribute == NULL) {
5450         PyErr_Format(PyExc_AttributeError,
5451                         "type object '%.100s' has no attribute '%U'",
5452                         type->tp_name, name);
5453     } else {
5454         // signal the caller we have not set an PyExc_AttributeError and gave up
5455         *suppress_missing_attribute = 1;
5456     }
5457     return NULL;
5458 }
5459 
5460 /* This is similar to PyObject_GenericGetAttr(),
5461    but uses _PyType_LookupRef() instead of just looking in type->tp_dict. */
5462 PyObject *
_Py_type_getattro(PyObject * type,PyObject * name)5463 _Py_type_getattro(PyObject *type, PyObject *name)
5464 {
5465     return _Py_type_getattro_impl((PyTypeObject *)type, name, NULL);
5466 }
5467 
5468 static int
type_update_dict(PyTypeObject * type,PyDictObject * dict,PyObject * name,PyObject * value,PyObject ** old_value)5469 type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name,
5470                  PyObject *value, PyObject **old_value)
5471 {
5472     // We don't want any re-entrancy between when we update the dict
5473     // and call type_modified_unlocked, including running the destructor
5474     // of the current value as it can observe the cache in an inconsistent
5475     // state.  Because we have an exact unicode and our dict has exact
5476     // unicodes we know that this will all complete without releasing
5477     // the locks.
5478     if (_PyDict_GetItemRef_Unicode_LockHeld(dict, name, old_value) < 0) {
5479         return -1;
5480     }
5481 
5482     /* Clear the VALID_VERSION flag of 'type' and all its
5483         subclasses.  This could possibly be unified with the
5484         update_subclasses() recursion in update_slot(), but carefully:
5485         they each have their own conditions on which to stop
5486         recursing into subclasses. */
5487     type_modified_unlocked(type);
5488 
5489     if (_PyDict_SetItem_LockHeld(dict, name, value) < 0) {
5490         PyErr_Format(PyExc_AttributeError,
5491                      "type object '%.50s' has no attribute '%U'",
5492                      ((PyTypeObject*)type)->tp_name, name);
5493         _PyObject_SetAttributeErrorContext((PyObject *)type, name);
5494         return -1;
5495     }
5496 
5497     if (is_dunder_name(name)) {
5498         return update_slot(type, name);
5499     }
5500 
5501     return 0;
5502 }
5503 
5504 static int
type_setattro(PyObject * self,PyObject * name,PyObject * value)5505 type_setattro(PyObject *self, PyObject *name, PyObject *value)
5506 {
5507     PyTypeObject *type = (PyTypeObject *)self;
5508     int res;
5509     if (type->tp_flags & Py_TPFLAGS_IMMUTABLETYPE) {
5510         PyErr_Format(
5511             PyExc_TypeError,
5512             "cannot set %R attribute of immutable type '%s'",
5513             name, type->tp_name);
5514         return -1;
5515     }
5516     if (!PyUnicode_Check(name)) {
5517         PyErr_Format(PyExc_TypeError,
5518                      "attribute name must be string, not '%.200s'",
5519                      Py_TYPE(name)->tp_name);
5520         return -1;
5521     }
5522 
5523     if (PyUnicode_CheckExact(name)) {
5524         Py_INCREF(name);
5525     }
5526     else {
5527         name = _PyUnicode_Copy(name);
5528         if (name == NULL)
5529             return -1;
5530     }
5531     if (!PyUnicode_CHECK_INTERNED(name)) {
5532         PyInterpreterState *interp = _PyInterpreterState_GET();
5533         _PyUnicode_InternMortal(interp, &name);
5534         if (!PyUnicode_CHECK_INTERNED(name)) {
5535             PyErr_SetString(PyExc_MemoryError,
5536                             "Out of memory interning an attribute name");
5537             Py_DECREF(name);
5538             return -1;
5539         }
5540     }
5541 
5542     PyTypeObject *metatype = Py_TYPE(type);
5543     assert(!_PyType_HasFeature(metatype, Py_TPFLAGS_INLINE_VALUES));
5544     assert(!_PyType_HasFeature(metatype, Py_TPFLAGS_MANAGED_DICT));
5545 
5546     PyObject *old_value = NULL;
5547     PyObject *descr = _PyType_LookupRef(metatype, name);
5548     if (descr != NULL) {
5549         descrsetfunc f = Py_TYPE(descr)->tp_descr_set;
5550         if (f != NULL) {
5551             res = f(descr, (PyObject *)type, value);
5552             goto done;
5553         }
5554     }
5555 
5556     PyObject *dict = type->tp_dict;
5557     if (dict == NULL) {
5558         // We don't just do PyType_Ready because we could already be readying
5559         BEGIN_TYPE_LOCK();
5560         dict = type->tp_dict;
5561         if (dict == NULL) {
5562             dict = type->tp_dict = PyDict_New();
5563         }
5564         END_TYPE_LOCK();
5565         if (dict == NULL) {
5566             res = -1;
5567             goto done;
5568         }
5569     }
5570 
5571     BEGIN_TYPE_DICT_LOCK(dict);
5572     res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value);
5573     assert(_PyType_CheckConsistency(type));
5574     END_TYPE_DICT_LOCK();
5575 
5576 done:
5577     Py_DECREF(name);
5578     Py_XDECREF(descr);
5579     Py_XDECREF(old_value);
5580     return res;
5581 }
5582 
5583 
5584 static void
type_dealloc_common(PyTypeObject * type)5585 type_dealloc_common(PyTypeObject *type)
5586 {
5587     PyObject *bases = lookup_tp_bases(type);
5588     if (bases != NULL) {
5589         PyObject *exc = PyErr_GetRaisedException();
5590         remove_all_subclasses(type, bases);
5591         PyErr_SetRaisedException(exc);
5592     }
5593 }
5594 
5595 
5596 static void
clear_static_tp_subclasses(PyTypeObject * type,int isbuiltin)5597 clear_static_tp_subclasses(PyTypeObject *type, int isbuiltin)
5598 {
5599     PyObject *subclasses = lookup_tp_subclasses(type);
5600     if (subclasses == NULL) {
5601         return;
5602     }
5603 
5604     /* Normally it would be a problem to finalize the type if its
5605        tp_subclasses wasn't cleared first.  However, this is only
5606        ever called at the end of runtime finalization, so we can be
5607        more liberal in cleaning up.  If the given type still has
5608        subtypes at this point then some extension module did not
5609        correctly finalize its objects.
5610 
5611        We can safely obliterate such subtypes since the extension
5612        module and its objects won't be used again, except maybe if
5613        the runtime were re-initialized.  In that case the sticky
5614        situation would only happen if the module were re-imported
5615        then and only if the subtype were stored in a global and only
5616        if that global were not overwritten during import.  We'd be
5617        fine since the extension is otherwise unsafe and unsupported
5618        in that situation, and likely problematic already.
5619 
5620        In any case, this situation means at least some memory is
5621        going to leak.  This mostly only affects embedding scenarios.
5622      */
5623 
5624 #ifndef NDEBUG
5625     // For now we just do a sanity check and then clear tp_subclasses.
5626     Py_ssize_t i = 0;
5627     PyObject *key, *ref;  // borrowed ref
5628     while (PyDict_Next(subclasses, &i, &key, &ref)) {
5629         PyTypeObject *subclass = type_from_ref(ref);
5630         if (subclass == NULL) {
5631             continue;
5632         }
5633         // All static builtin subtypes should have been finalized already.
5634         assert(!isbuiltin || !(subclass->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN));
5635         Py_DECREF(subclass);
5636     }
5637 #else
5638     (void)isbuiltin;
5639 #endif
5640 
5641     clear_tp_subclasses(type);
5642 }
5643 
5644 static void
clear_static_type_objects(PyInterpreterState * interp,PyTypeObject * type,int isbuiltin,int final)5645 clear_static_type_objects(PyInterpreterState *interp, PyTypeObject *type,
5646                           int isbuiltin, int final)
5647 {
5648     if (final) {
5649         Py_CLEAR(type->tp_cache);
5650     }
5651     clear_tp_dict(type);
5652     clear_tp_bases(type, final);
5653     clear_tp_mro(type, final);
5654     clear_static_tp_subclasses(type, isbuiltin);
5655 }
5656 
5657 
5658 static void
fini_static_type(PyInterpreterState * interp,PyTypeObject * type,int isbuiltin,int final)5659 fini_static_type(PyInterpreterState *interp, PyTypeObject *type,
5660                  int isbuiltin, int final)
5661 {
5662     assert(type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN);
5663     assert(_Py_IsImmortalLoose((PyObject *)type));
5664 
5665     type_dealloc_common(type);
5666 
5667     clear_static_type_objects(interp, type, isbuiltin, final);
5668 
5669     if (final) {
5670         type->tp_flags &= ~Py_TPFLAGS_READY;
5671         type->tp_version_tag = 0;
5672     }
5673 
5674     _PyStaticType_ClearWeakRefs(interp, type);
5675     managed_static_type_state_clear(interp, type, isbuiltin, final);
5676     /* We leave _Py_TPFLAGS_STATIC_BUILTIN set on tp_flags. */
5677 }
5678 
5679 void
_PyTypes_FiniExtTypes(PyInterpreterState * interp)5680 _PyTypes_FiniExtTypes(PyInterpreterState *interp)
5681 {
5682     for (size_t i = _Py_MAX_MANAGED_STATIC_EXT_TYPES; i > 0; i--) {
5683         if (interp->types.for_extensions.num_initialized == 0) {
5684             break;
5685         }
5686         int64_t count = 0;
5687         PyTypeObject *type = static_ext_type_lookup(interp, i-1, &count);
5688         if (type == NULL) {
5689             continue;
5690         }
5691         int final = (count == 1);
5692         fini_static_type(interp, type, 0, final);
5693     }
5694 }
5695 
5696 void
_PyStaticType_FiniBuiltin(PyInterpreterState * interp,PyTypeObject * type)5697 _PyStaticType_FiniBuiltin(PyInterpreterState *interp, PyTypeObject *type)
5698 {
5699     fini_static_type(interp, type, 1, _Py_IsMainInterpreter(interp));
5700 }
5701 
5702 
5703 static void
type_dealloc(PyObject * self)5704 type_dealloc(PyObject *self)
5705 {
5706     PyTypeObject *type = (PyTypeObject *)self;
5707 
5708     // Assert this is a heap-allocated type object
5709     _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
5710 
5711     _PyObject_GC_UNTRACK(type);
5712 
5713     type_dealloc_common(type);
5714 
5715     // PyObject_ClearWeakRefs() raises an exception if Py_REFCNT() != 0
5716     assert(Py_REFCNT(type) == 0);
5717     PyObject_ClearWeakRefs((PyObject *)type);
5718 
5719     Py_XDECREF(type->tp_base);
5720     Py_XDECREF(type->tp_dict);
5721     Py_XDECREF(type->tp_bases);
5722     Py_XDECREF(type->tp_mro);
5723     Py_XDECREF(type->tp_cache);
5724     clear_tp_subclasses(type);
5725 
5726     /* A type's tp_doc is heap allocated, unlike the tp_doc slots
5727      * of most other objects.  It's okay to cast it to char *.
5728      */
5729     PyMem_Free((char *)type->tp_doc);
5730 
5731     PyHeapTypeObject *et = (PyHeapTypeObject *)type;
5732     Py_XDECREF(et->ht_name);
5733     Py_XDECREF(et->ht_qualname);
5734     Py_XDECREF(et->ht_slots);
5735     if (et->ht_cached_keys) {
5736         _PyDictKeys_DecRef(et->ht_cached_keys);
5737     }
5738     Py_XDECREF(et->ht_module);
5739     PyMem_Free(et->_ht_tpname);
5740     Py_TYPE(type)->tp_free((PyObject *)type);
5741 }
5742 
5743 
5744 /*[clinic input]
5745 type.__subclasses__
5746 
5747 Return a list of immediate subclasses.
5748 [clinic start generated code]*/
5749 
5750 static PyObject *
type___subclasses___impl(PyTypeObject * self)5751 type___subclasses___impl(PyTypeObject *self)
5752 /*[clinic end generated code: output=eb5eb54485942819 input=5af66132436f9a7b]*/
5753 {
5754     return _PyType_GetSubclasses(self);
5755 }
5756 
5757 static PyObject *
type_prepare(PyObject * self,PyObject * const * args,Py_ssize_t nargs,PyObject * kwnames)5758 type_prepare(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
5759              PyObject *kwnames)
5760 {
5761     return PyDict_New();
5762 }
5763 
5764 
5765 /*
5766    Merge the __dict__ of aclass into dict, and recursively also all
5767    the __dict__s of aclass's base classes.  The order of merging isn't
5768    defined, as it's expected that only the final set of dict keys is
5769    interesting.
5770    Return 0 on success, -1 on error.
5771 */
5772 
5773 static int
merge_class_dict(PyObject * dict,PyObject * aclass)5774 merge_class_dict(PyObject *dict, PyObject *aclass)
5775 {
5776     PyObject *classdict;
5777     PyObject *bases;
5778 
5779     assert(PyDict_Check(dict));
5780     assert(aclass);
5781 
5782     /* Merge in the type's dict (if any). */
5783     if (PyObject_GetOptionalAttr(aclass, &_Py_ID(__dict__), &classdict) < 0) {
5784         return -1;
5785     }
5786     if (classdict != NULL) {
5787         int status = PyDict_Update(dict, classdict);
5788         Py_DECREF(classdict);
5789         if (status < 0)
5790             return -1;
5791     }
5792 
5793     /* Recursively merge in the base types' (if any) dicts. */
5794     if (PyObject_GetOptionalAttr(aclass, &_Py_ID(__bases__), &bases) < 0) {
5795         return -1;
5796     }
5797     if (bases != NULL) {
5798         /* We have no guarantee that bases is a real tuple */
5799         Py_ssize_t i, n;
5800         n = PySequence_Size(bases); /* This better be right */
5801         if (n < 0) {
5802             Py_DECREF(bases);
5803             return -1;
5804         }
5805         else {
5806             for (i = 0; i < n; i++) {
5807                 int status;
5808                 PyObject *base = PySequence_GetItem(bases, i);
5809                 if (base == NULL) {
5810                     Py_DECREF(bases);
5811                     return -1;
5812                 }
5813                 status = merge_class_dict(dict, base);
5814                 Py_DECREF(base);
5815                 if (status < 0) {
5816                     Py_DECREF(bases);
5817                     return -1;
5818                 }
5819             }
5820         }
5821         Py_DECREF(bases);
5822     }
5823     return 0;
5824 }
5825 
5826 /* __dir__ for type objects: returns __dict__ and __bases__.
5827    We deliberately don't suck up its __class__, as methods belonging to the
5828    metaclass would probably be more confusing than helpful.
5829 */
5830 /*[clinic input]
5831 type.__dir__
5832 
5833 Specialized __dir__ implementation for types.
5834 [clinic start generated code]*/
5835 
5836 static PyObject *
type___dir___impl(PyTypeObject * self)5837 type___dir___impl(PyTypeObject *self)
5838 /*[clinic end generated code: output=69d02fe92c0f15fa input=7733befbec645968]*/
5839 {
5840     PyObject *result = NULL;
5841     PyObject *dict = PyDict_New();
5842 
5843     if (dict != NULL && merge_class_dict(dict, (PyObject *)self) == 0)
5844         result = PyDict_Keys(dict);
5845 
5846     Py_XDECREF(dict);
5847     return result;
5848 }
5849 
5850 /*[clinic input]
5851 type.__sizeof__
5852 
5853 Return memory consumption of the type object.
5854 [clinic start generated code]*/
5855 
5856 static PyObject *
type___sizeof___impl(PyTypeObject * self)5857 type___sizeof___impl(PyTypeObject *self)
5858 /*[clinic end generated code: output=766f4f16cd3b1854 input=99398f24b9cf45d6]*/
5859 {
5860     size_t size;
5861     if (self->tp_flags & Py_TPFLAGS_HEAPTYPE) {
5862         PyHeapTypeObject* et = (PyHeapTypeObject*)self;
5863         size = sizeof(PyHeapTypeObject);
5864         if (et->ht_cached_keys)
5865             size += _PyDict_KeysSize(et->ht_cached_keys);
5866     }
5867     else {
5868         size = sizeof(PyTypeObject);
5869     }
5870     return PyLong_FromSize_t(size);
5871 }
5872 
5873 static PyMethodDef type_methods[] = {
5874     TYPE_MRO_METHODDEF
5875     TYPE___SUBCLASSES___METHODDEF
5876     {"__prepare__", _PyCFunction_CAST(type_prepare),
5877      METH_FASTCALL | METH_KEYWORDS | METH_CLASS,
5878      PyDoc_STR("__prepare__($cls, name, bases, /, **kwds)\n"
5879                "--\n"
5880                "\n"
5881                "Create the namespace for the class statement")},
5882     TYPE___INSTANCECHECK___METHODDEF
5883     TYPE___SUBCLASSCHECK___METHODDEF
5884     TYPE___DIR___METHODDEF
5885     TYPE___SIZEOF___METHODDEF
5886     {0}
5887 };
5888 
5889 PyDoc_STRVAR(type_doc,
5890 "type(object) -> the object's type\n"
5891 "type(name, bases, dict, **kwds) -> a new type");
5892 
5893 static int
type_traverse(PyObject * self,visitproc visit,void * arg)5894 type_traverse(PyObject *self, visitproc visit, void *arg)
5895 {
5896     PyTypeObject *type = (PyTypeObject *)self;
5897 
5898     /* Because of type_is_gc(), the collector only calls this
5899        for heaptypes. */
5900     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
5901         char msg[200];
5902         sprintf(msg, "type_traverse() called on non-heap type '%.100s'",
5903                 type->tp_name);
5904         _PyObject_ASSERT_FAILED_MSG((PyObject *)type, msg);
5905     }
5906 
5907     Py_VISIT(type->tp_dict);
5908     Py_VISIT(type->tp_cache);
5909     Py_VISIT(type->tp_mro);
5910     Py_VISIT(type->tp_bases);
5911     Py_VISIT(type->tp_base);
5912     Py_VISIT(((PyHeapTypeObject *)type)->ht_module);
5913 
5914     /* There's no need to visit others because they can't be involved
5915        in cycles:
5916        type->tp_subclasses is a list of weak references,
5917        ((PyHeapTypeObject *)type)->ht_slots is a tuple of strings,
5918        ((PyHeapTypeObject *)type)->ht_*name are strings.
5919        */
5920 
5921     return 0;
5922 }
5923 
5924 static int
type_clear(PyObject * self)5925 type_clear(PyObject *self)
5926 {
5927     PyTypeObject *type = (PyTypeObject *)self;
5928 
5929     /* Because of type_is_gc(), the collector only calls this
5930        for heaptypes. */
5931     _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
5932 
5933     /* We need to invalidate the method cache carefully before clearing
5934        the dict, so that other objects caught in a reference cycle
5935        don't start calling destroyed methods.
5936 
5937        Otherwise, we need to clear tp_mro, which is
5938        part of a hard cycle (its first element is the class itself) that
5939        won't be broken otherwise (it's a tuple and tuples don't have a
5940        tp_clear handler).
5941        We also need to clear ht_module, if present: the module usually holds a
5942        reference to its class. None of the other fields need to be
5943 
5944        cleared, and here's why:
5945 
5946        tp_cache:
5947            Not used; if it were, it would be a dict.
5948 
5949        tp_bases, tp_base:
5950            If these are involved in a cycle, there must be at least
5951            one other, mutable object in the cycle, e.g. a base
5952            class's dict; the cycle will be broken that way.
5953 
5954        tp_subclasses:
5955            A dict of weak references can't be part of a cycle; and
5956            dicts have their own tp_clear.
5957 
5958        slots (in PyHeapTypeObject):
5959            A tuple of strings can't be part of a cycle.
5960     */
5961 
5962     PyType_Modified(type);
5963     PyObject *dict = lookup_tp_dict(type);
5964     if (dict) {
5965         PyDict_Clear(dict);
5966     }
5967     Py_CLEAR(((PyHeapTypeObject *)type)->ht_module);
5968 
5969     Py_CLEAR(type->tp_mro);
5970 
5971     return 0;
5972 }
5973 
5974 static int
type_is_gc(PyObject * type)5975 type_is_gc(PyObject *type)
5976 {
5977     return ((PyTypeObject *)type)->tp_flags & Py_TPFLAGS_HEAPTYPE;
5978 }
5979 
5980 
5981 static PyNumberMethods type_as_number = {
5982         .nb_or = _Py_union_type_or, // Add __or__ function
5983 };
5984 
5985 PyTypeObject PyType_Type = {
5986     PyVarObject_HEAD_INIT(&PyType_Type, 0)
5987     "type",                                     /* tp_name */
5988     sizeof(PyHeapTypeObject),                   /* tp_basicsize */
5989     sizeof(PyMemberDef),                        /* tp_itemsize */
5990     type_dealloc,                               /* tp_dealloc */
5991     offsetof(PyTypeObject, tp_vectorcall),      /* tp_vectorcall_offset */
5992     0,                                          /* tp_getattr */
5993     0,                                          /* tp_setattr */
5994     0,                                          /* tp_as_async */
5995     type_repr,                                  /* tp_repr */
5996     &type_as_number,                            /* tp_as_number */
5997     0,                                          /* tp_as_sequence */
5998     0,                                          /* tp_as_mapping */
5999     0,                                          /* tp_hash */
6000     type_call,                                  /* tp_call */
6001     0,                                          /* tp_str */
6002     _Py_type_getattro,                          /* tp_getattro */
6003     type_setattro,                              /* tp_setattro */
6004     0,                                          /* tp_as_buffer */
6005     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6006     Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS |
6007     Py_TPFLAGS_HAVE_VECTORCALL |
6008     Py_TPFLAGS_ITEMS_AT_END,                    /* tp_flags */
6009     type_doc,                                   /* tp_doc */
6010     type_traverse,                              /* tp_traverse */
6011     type_clear,                                 /* tp_clear */
6012     0,                                          /* tp_richcompare */
6013     offsetof(PyTypeObject, tp_weaklist),        /* tp_weaklistoffset */
6014     0,                                          /* tp_iter */
6015     0,                                          /* tp_iternext */
6016     type_methods,                               /* tp_methods */
6017     type_members,                               /* tp_members */
6018     type_getsets,                               /* tp_getset */
6019     0,                                          /* tp_base */
6020     0,                                          /* tp_dict */
6021     0,                                          /* tp_descr_get */
6022     0,                                          /* tp_descr_set */
6023     offsetof(PyTypeObject, tp_dict),            /* tp_dictoffset */
6024     type_init,                                  /* tp_init */
6025     0,                                          /* tp_alloc */
6026     type_new,                                   /* tp_new */
6027     PyObject_GC_Del,                            /* tp_free */
6028     type_is_gc,                                 /* tp_is_gc */
6029     .tp_vectorcall = type_vectorcall,
6030 };
6031 
6032 
6033 /* The base type of all types (eventually)... except itself. */
6034 
6035 /* You may wonder why object.__new__() only complains about arguments
6036    when object.__init__() is not overridden, and vice versa.
6037 
6038    Consider the use cases:
6039 
6040    1. When neither is overridden, we want to hear complaints about
6041       excess (i.e., any) arguments, since their presence could
6042       indicate there's a bug.
6043 
6044    2. When defining an Immutable type, we are likely to override only
6045       __new__(), since __init__() is called too late to initialize an
6046       Immutable object.  Since __new__() defines the signature for the
6047       type, it would be a pain to have to override __init__() just to
6048       stop it from complaining about excess arguments.
6049 
6050    3. When defining a Mutable type, we are likely to override only
6051       __init__().  So here the converse reasoning applies: we don't
6052       want to have to override __new__() just to stop it from
6053       complaining.
6054 
6055    4. When __init__() is overridden, and the subclass __init__() calls
6056       object.__init__(), the latter should complain about excess
6057       arguments; ditto for __new__().
6058 
6059    Use cases 2 and 3 make it unattractive to unconditionally check for
6060    excess arguments.  The best solution that addresses all four use
6061    cases is as follows: __init__() complains about excess arguments
6062    unless __new__() is overridden and __init__() is not overridden
6063    (IOW, if __init__() is overridden or __new__() is not overridden);
6064    symmetrically, __new__() complains about excess arguments unless
6065    __init__() is overridden and __new__() is not overridden
6066    (IOW, if __new__() is overridden or __init__() is not overridden).
6067 
6068    However, for backwards compatibility, this breaks too much code.
6069    Therefore, in 2.6, we'll *warn* about excess arguments when both
6070    methods are overridden; for all other cases we'll use the above
6071    rules.
6072 
6073 */
6074 
6075 /* Forward */
6076 static PyObject *
6077 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
6078 
6079 static int
excess_args(PyObject * args,PyObject * kwds)6080 excess_args(PyObject *args, PyObject *kwds)
6081 {
6082     return PyTuple_GET_SIZE(args) ||
6083         (kwds && PyDict_Check(kwds) && PyDict_GET_SIZE(kwds));
6084 }
6085 
6086 static int
object_init(PyObject * self,PyObject * args,PyObject * kwds)6087 object_init(PyObject *self, PyObject *args, PyObject *kwds)
6088 {
6089     PyTypeObject *type = Py_TYPE(self);
6090     if (excess_args(args, kwds)) {
6091         if (type->tp_init != object_init) {
6092             PyErr_SetString(PyExc_TypeError,
6093                             "object.__init__() takes exactly one argument (the instance to initialize)");
6094             return -1;
6095         }
6096         if (type->tp_new == object_new) {
6097             PyErr_Format(PyExc_TypeError,
6098                          "%.200s.__init__() takes exactly one argument (the instance to initialize)",
6099                          type->tp_name);
6100             return -1;
6101         }
6102     }
6103     return 0;
6104 }
6105 
6106 static PyObject *
object_new(PyTypeObject * type,PyObject * args,PyObject * kwds)6107 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6108 {
6109     if (excess_args(args, kwds)) {
6110         if (type->tp_new != object_new) {
6111             PyErr_SetString(PyExc_TypeError,
6112                             "object.__new__() takes exactly one argument (the type to instantiate)");
6113             return NULL;
6114         }
6115         if (type->tp_init == object_init) {
6116             PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments",
6117                          type->tp_name);
6118             return NULL;
6119         }
6120     }
6121 
6122     if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
6123         PyObject *abstract_methods;
6124         PyObject *sorted_methods;
6125         PyObject *joined;
6126         PyObject* comma_w_quotes_sep;
6127         Py_ssize_t method_count;
6128 
6129         /* Compute "', '".join(sorted(type.__abstractmethods__))
6130            into joined. */
6131         abstract_methods = type_abstractmethods(type, NULL);
6132         if (abstract_methods == NULL)
6133             return NULL;
6134         sorted_methods = PySequence_List(abstract_methods);
6135         Py_DECREF(abstract_methods);
6136         if (sorted_methods == NULL)
6137             return NULL;
6138         if (PyList_Sort(sorted_methods)) {
6139             Py_DECREF(sorted_methods);
6140             return NULL;
6141         }
6142         comma_w_quotes_sep = PyUnicode_FromString("', '");
6143         if (!comma_w_quotes_sep) {
6144             Py_DECREF(sorted_methods);
6145             return NULL;
6146         }
6147         joined = PyUnicode_Join(comma_w_quotes_sep, sorted_methods);
6148         Py_DECREF(comma_w_quotes_sep);
6149         if (joined == NULL)  {
6150             Py_DECREF(sorted_methods);
6151             return NULL;
6152         }
6153         method_count = PyObject_Length(sorted_methods);
6154         Py_DECREF(sorted_methods);
6155         if (method_count == -1) {
6156             Py_DECREF(joined);
6157             return NULL;
6158         }
6159 
6160         PyErr_Format(PyExc_TypeError,
6161                      "Can't instantiate abstract class %s "
6162                      "without an implementation for abstract method%s '%U'",
6163                      type->tp_name,
6164                      method_count > 1 ? "s" : "",
6165                      joined);
6166         Py_DECREF(joined);
6167         return NULL;
6168     }
6169     PyObject *obj = type->tp_alloc(type, 0);
6170     if (obj == NULL) {
6171         return NULL;
6172     }
6173     return obj;
6174 }
6175 
6176 static void
object_dealloc(PyObject * self)6177 object_dealloc(PyObject *self)
6178 {
6179     Py_TYPE(self)->tp_free(self);
6180 }
6181 
6182 static PyObject *
object_repr(PyObject * self)6183 object_repr(PyObject *self)
6184 {
6185     PyTypeObject *type;
6186     PyObject *mod, *name, *rtn;
6187 
6188     type = Py_TYPE(self);
6189     mod = type_module(type);
6190     if (mod == NULL)
6191         PyErr_Clear();
6192     else if (!PyUnicode_Check(mod)) {
6193         Py_SETREF(mod, NULL);
6194     }
6195     name = type_qualname(type, NULL);
6196     if (name == NULL) {
6197         Py_XDECREF(mod);
6198         return NULL;
6199     }
6200     if (mod != NULL && !_PyUnicode_Equal(mod, &_Py_ID(builtins)))
6201         rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
6202     else
6203         rtn = PyUnicode_FromFormat("<%s object at %p>",
6204                                   type->tp_name, self);
6205     Py_XDECREF(mod);
6206     Py_DECREF(name);
6207     return rtn;
6208 }
6209 
6210 static PyObject *
object_str(PyObject * self)6211 object_str(PyObject *self)
6212 {
6213     unaryfunc f;
6214 
6215     f = Py_TYPE(self)->tp_repr;
6216     if (f == NULL)
6217         f = object_repr;
6218     return f(self);
6219 }
6220 
6221 static PyObject *
object_richcompare(PyObject * self,PyObject * other,int op)6222 object_richcompare(PyObject *self, PyObject *other, int op)
6223 {
6224     PyObject *res;
6225 
6226     switch (op) {
6227 
6228     case Py_EQ:
6229         /* Return NotImplemented instead of False, so if two
6230            objects are compared, both get a chance at the
6231            comparison.  See issue #1393. */
6232         res = Py_NewRef((self == other) ? Py_True : Py_NotImplemented);
6233         break;
6234 
6235     case Py_NE:
6236         /* By default, __ne__() delegates to __eq__() and inverts the result,
6237            unless the latter returns NotImplemented. */
6238         if (Py_TYPE(self)->tp_richcompare == NULL) {
6239             res = Py_NewRef(Py_NotImplemented);
6240             break;
6241         }
6242         res = (*Py_TYPE(self)->tp_richcompare)(self, other, Py_EQ);
6243         if (res != NULL && res != Py_NotImplemented) {
6244             int ok = PyObject_IsTrue(res);
6245             Py_DECREF(res);
6246             if (ok < 0)
6247                 res = NULL;
6248             else {
6249                 if (ok)
6250                     res = Py_NewRef(Py_False);
6251                 else
6252                     res = Py_NewRef(Py_True);
6253             }
6254         }
6255         break;
6256 
6257     default:
6258         res = Py_NewRef(Py_NotImplemented);
6259         break;
6260     }
6261 
6262     return res;
6263 }
6264 
6265 PyObject*
_Py_BaseObject_RichCompare(PyObject * self,PyObject * other,int op)6266 _Py_BaseObject_RichCompare(PyObject* self, PyObject* other, int op)
6267 {
6268     return object_richcompare(self, other, op);
6269 }
6270 
6271 static PyObject *
object_get_class(PyObject * self,void * closure)6272 object_get_class(PyObject *self, void *closure)
6273 {
6274     return Py_NewRef(Py_TYPE(self));
6275 }
6276 
6277 static int
compatible_with_tp_base(PyTypeObject * child)6278 compatible_with_tp_base(PyTypeObject *child)
6279 {
6280     PyTypeObject *parent = child->tp_base;
6281     return (parent != NULL &&
6282             child->tp_basicsize == parent->tp_basicsize &&
6283             child->tp_itemsize == parent->tp_itemsize &&
6284             child->tp_dictoffset == parent->tp_dictoffset &&
6285             child->tp_weaklistoffset == parent->tp_weaklistoffset &&
6286             ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
6287              (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
6288             (child->tp_dealloc == subtype_dealloc ||
6289              child->tp_dealloc == parent->tp_dealloc));
6290 }
6291 
6292 static int
same_slots_added(PyTypeObject * a,PyTypeObject * b)6293 same_slots_added(PyTypeObject *a, PyTypeObject *b)
6294 {
6295     PyTypeObject *base = a->tp_base;
6296     Py_ssize_t size;
6297     PyObject *slots_a, *slots_b;
6298 
6299     assert(base == b->tp_base);
6300     size = base->tp_basicsize;
6301     if (a->tp_dictoffset == size && b->tp_dictoffset == size)
6302         size += sizeof(PyObject *);
6303     if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
6304         size += sizeof(PyObject *);
6305 
6306     /* Check slots compliance */
6307     if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
6308         !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
6309         return 0;
6310     }
6311     slots_a = ((PyHeapTypeObject *)a)->ht_slots;
6312     slots_b = ((PyHeapTypeObject *)b)->ht_slots;
6313     if (slots_a && slots_b) {
6314         if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
6315             return 0;
6316         size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
6317     }
6318     return size == a->tp_basicsize && size == b->tp_basicsize;
6319 }
6320 
6321 static int
compatible_for_assignment(PyTypeObject * oldto,PyTypeObject * newto,const char * attr)6322 compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
6323 {
6324     PyTypeObject *newbase, *oldbase;
6325 
6326     if (newto->tp_free != oldto->tp_free) {
6327         PyErr_Format(PyExc_TypeError,
6328                      "%s assignment: "
6329                      "'%s' deallocator differs from '%s'",
6330                      attr,
6331                      newto->tp_name,
6332                      oldto->tp_name);
6333         return 0;
6334     }
6335     /*
6336      It's tricky to tell if two arbitrary types are sufficiently compatible as
6337      to be interchangeable; e.g., even if they have the same tp_basicsize, they
6338      might have totally different struct fields. It's much easier to tell if a
6339      type and its supertype are compatible; e.g., if they have the same
6340      tp_basicsize, then that means they have identical fields. So to check
6341      whether two arbitrary types are compatible, we first find the highest
6342      supertype that each is compatible with, and then if those supertypes are
6343      compatible then the original types must also be compatible.
6344     */
6345     newbase = newto;
6346     oldbase = oldto;
6347     while (compatible_with_tp_base(newbase))
6348         newbase = newbase->tp_base;
6349     while (compatible_with_tp_base(oldbase))
6350         oldbase = oldbase->tp_base;
6351     if (newbase != oldbase &&
6352         (newbase->tp_base != oldbase->tp_base ||
6353          !same_slots_added(newbase, oldbase))) {
6354         goto differs;
6355     }
6356     if ((oldto->tp_flags & Py_TPFLAGS_INLINE_VALUES) !=
6357         ((newto->tp_flags & Py_TPFLAGS_INLINE_VALUES)))
6358     {
6359         goto differs;
6360     }
6361     /* The above does not check for the preheader */
6362     if ((oldto->tp_flags & Py_TPFLAGS_PREHEADER) ==
6363         ((newto->tp_flags & Py_TPFLAGS_PREHEADER)))
6364     {
6365         return 1;
6366     }
6367 differs:
6368     PyErr_Format(PyExc_TypeError,
6369                     "%s assignment: "
6370                     "'%s' object layout differs from '%s'",
6371                     attr,
6372                     newto->tp_name,
6373                     oldto->tp_name);
6374     return 0;
6375 }
6376 
6377 
6378 
6379 static int
object_set_class_world_stopped(PyObject * self,PyTypeObject * newto)6380 object_set_class_world_stopped(PyObject *self, PyTypeObject *newto)
6381 {
6382     PyTypeObject *oldto = Py_TYPE(self);
6383 
6384     /* In versions of CPython prior to 3.5, the code in
6385        compatible_for_assignment was not set up to correctly check for memory
6386        layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
6387        disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
6388        HEAPTYPE.
6389 
6390        During the 3.5 development cycle, we fixed the code in
6391        compatible_for_assignment to correctly check compatibility between
6392        arbitrary types, and started allowing __class__ assignment in all cases
6393        where the old and new types did in fact have compatible slots and
6394        memory layout (regardless of whether they were implemented as HEAPTYPEs
6395        or not).
6396 
6397        Just before 3.5 was released, though, we discovered that this led to
6398        problems with immutable types like int, where the interpreter assumes
6399        they are immutable and interns some values. Formerly this wasn't a
6400        problem, because they really were immutable -- in particular, all the
6401        types where the interpreter applied this interning trick happened to
6402        also be statically allocated, so the old HEAPTYPE rules were
6403        "accidentally" stopping them from allowing __class__ assignment. But
6404        with the changes to __class__ assignment, we started allowing code like
6405 
6406          class MyInt(int):
6407              ...
6408          # Modifies the type of *all* instances of 1 in the whole program,
6409          # including future instances (!), because the 1 object is interned.
6410          (1).__class__ = MyInt
6411 
6412        (see https://bugs.python.org/issue24912).
6413 
6414        In theory the proper fix would be to identify which classes rely on
6415        this invariant and somehow disallow __class__ assignment only for them,
6416        perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
6417        "denylisting" approach). But in practice, since this problem wasn't
6418        noticed late in the 3.5 RC cycle, we're taking the conservative
6419        approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
6420        to have, plus an "allowlist". For now, the allowlist consists only of
6421        ModuleType subtypes, since those are the cases that motivated the patch
6422        in the first place -- see https://bugs.python.org/issue22986 -- and
6423        since module objects are mutable we can be sure that they are
6424        definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
6425        ModuleType subtype -> ModuleType subtype.
6426 
6427        So far as we know, all the code beyond the following 'if' statement
6428        will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
6429        needed only to protect that subset of non-HEAPTYPE classes for which
6430        the interpreter has baked in the assumption that all instances are
6431        truly immutable.
6432     */
6433     if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
6434           PyType_IsSubtype(oldto, &PyModule_Type)) &&
6435         (_PyType_HasFeature(newto, Py_TPFLAGS_IMMUTABLETYPE) ||
6436          _PyType_HasFeature(oldto, Py_TPFLAGS_IMMUTABLETYPE))) {
6437         PyErr_Format(PyExc_TypeError,
6438                      "__class__ assignment only supported for mutable types "
6439                      "or ModuleType subclasses");
6440         return -1;
6441     }
6442 
6443     if (compatible_for_assignment(oldto, newto, "__class__")) {
6444         /* Changing the class will change the implicit dict keys,
6445          * so we must materialize the dictionary first. */
6446         if (oldto->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
6447             PyDictObject *dict = _PyObject_GetManagedDict(self);
6448             if (dict == NULL) {
6449                 dict = _PyObject_MaterializeManagedDict_LockHeld(self);
6450                 if (dict == NULL) {
6451                     return -1;
6452                 }
6453             }
6454 
6455             assert(_PyObject_GetManagedDict(self) == dict);
6456 
6457             if (_PyDict_DetachFromObject(dict, self) < 0) {
6458                 return -1;
6459             }
6460 
6461         }
6462         if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE) {
6463             Py_INCREF(newto);
6464         }
6465 
6466         Py_SET_TYPE(self, newto);
6467 
6468         return 0;
6469     }
6470     else {
6471         return -1;
6472     }
6473 }
6474 
6475 static int
object_set_class(PyObject * self,PyObject * value,void * closure)6476 object_set_class(PyObject *self, PyObject *value, void *closure)
6477 {
6478 
6479     if (value == NULL) {
6480         PyErr_SetString(PyExc_TypeError,
6481                         "can't delete __class__ attribute");
6482         return -1;
6483     }
6484     if (!PyType_Check(value)) {
6485         PyErr_Format(PyExc_TypeError,
6486           "__class__ must be set to a class, not '%s' object",
6487           Py_TYPE(value)->tp_name);
6488         return -1;
6489     }
6490     PyTypeObject *newto = (PyTypeObject *)value;
6491 
6492     if (PySys_Audit("object.__setattr__", "OsO",
6493                     self, "__class__", value) < 0) {
6494         return -1;
6495     }
6496 
6497 #ifdef Py_GIL_DISABLED
6498     PyInterpreterState *interp = _PyInterpreterState_GET();
6499     _PyEval_StopTheWorld(interp);
6500 #endif
6501     PyTypeObject *oldto = Py_TYPE(self);
6502     int res = object_set_class_world_stopped(self, newto);
6503 #ifdef Py_GIL_DISABLED
6504     _PyEval_StartTheWorld(interp);
6505 #endif
6506     if (res == 0) {
6507         if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE) {
6508             Py_DECREF(oldto);
6509         }
6510 
6511         RARE_EVENT_INC(set_class);
6512         return 0;
6513     }
6514     return res;
6515 }
6516 
6517 static PyGetSetDef object_getsets[] = {
6518     {"__class__", object_get_class, object_set_class,
6519      PyDoc_STR("the object's class")},
6520     {0}
6521 };
6522 
6523 
6524 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
6525    We fall back to helpers in copyreg for:
6526    - pickle protocols < 2
6527    - calculating the list of slot names (done only once per class)
6528    - the __newobj__ function (which is used as a token but never called)
6529 */
6530 
6531 static PyObject *
import_copyreg(void)6532 import_copyreg(void)
6533 {
6534     /* Try to fetch cached copy of copyreg from sys.modules first in an
6535        attempt to avoid the import overhead. Previously this was implemented
6536        by storing a reference to the cached module in a static variable, but
6537        this broke when multiple embedded interpreters were in use (see issue
6538        #17408 and #19088). */
6539     PyObject *copyreg_module = PyImport_GetModule(&_Py_ID(copyreg));
6540     if (copyreg_module != NULL) {
6541         return copyreg_module;
6542     }
6543     if (PyErr_Occurred()) {
6544         return NULL;
6545     }
6546     return PyImport_Import(&_Py_ID(copyreg));
6547 }
6548 
6549 static PyObject *
_PyType_GetSlotNames(PyTypeObject * cls)6550 _PyType_GetSlotNames(PyTypeObject *cls)
6551 {
6552     PyObject *copyreg;
6553     PyObject *slotnames;
6554 
6555     assert(PyType_Check(cls));
6556 
6557     /* Get the slot names from the cache in the class if possible. */
6558     PyObject *dict = lookup_tp_dict(cls);
6559     if (PyDict_GetItemRef(dict, &_Py_ID(__slotnames__), &slotnames) < 0) {
6560         return NULL;
6561     }
6562     if (slotnames != NULL) {
6563         if (slotnames != Py_None && !PyList_Check(slotnames)) {
6564             PyErr_Format(PyExc_TypeError,
6565                          "%.200s.__slotnames__ should be a list or None, "
6566                          "not %.200s",
6567                          cls->tp_name, Py_TYPE(slotnames)->tp_name);
6568             Py_DECREF(slotnames);
6569             return NULL;
6570         }
6571         return slotnames;
6572     }
6573 
6574     /* The class does not have the slot names cached yet. */
6575     copyreg = import_copyreg();
6576     if (copyreg == NULL)
6577         return NULL;
6578 
6579     /* Use _slotnames function from the copyreg module to find the slots
6580        by this class and its bases. This function will cache the result
6581        in __slotnames__. */
6582     slotnames = PyObject_CallMethodOneArg(
6583             copyreg, &_Py_ID(_slotnames), (PyObject *)cls);
6584     Py_DECREF(copyreg);
6585     if (slotnames == NULL)
6586         return NULL;
6587 
6588     if (slotnames != Py_None && !PyList_Check(slotnames)) {
6589         PyErr_SetString(PyExc_TypeError,
6590                         "copyreg._slotnames didn't return a list or None");
6591         Py_DECREF(slotnames);
6592         return NULL;
6593     }
6594 
6595     return slotnames;
6596 }
6597 
6598 static PyObject *
object_getstate_default(PyObject * obj,int required)6599 object_getstate_default(PyObject *obj, int required)
6600 {
6601     PyObject *state;
6602     PyObject *slotnames;
6603 
6604     if (required && Py_TYPE(obj)->tp_itemsize) {
6605         PyErr_Format(PyExc_TypeError,
6606                      "cannot pickle %.200s objects",
6607                      Py_TYPE(obj)->tp_name);
6608         return NULL;
6609     }
6610 
6611     if (_PyObject_IsInstanceDictEmpty(obj)) {
6612         state = Py_NewRef(Py_None);
6613     }
6614     else {
6615         state = PyObject_GenericGetDict(obj, NULL);
6616         if (state == NULL) {
6617             return NULL;
6618         }
6619     }
6620 
6621     slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
6622     if (slotnames == NULL) {
6623         Py_DECREF(state);
6624         return NULL;
6625     }
6626 
6627     assert(slotnames == Py_None || PyList_Check(slotnames));
6628     if (required) {
6629         Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
6630         if (Py_TYPE(obj)->tp_dictoffset &&
6631             (Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0)
6632         {
6633             basicsize += sizeof(PyObject *);
6634         }
6635         if (Py_TYPE(obj)->tp_weaklistoffset > 0) {
6636             basicsize += sizeof(PyObject *);
6637         }
6638         if (slotnames != Py_None) {
6639             basicsize += sizeof(PyObject *) * PyList_GET_SIZE(slotnames);
6640         }
6641         if (Py_TYPE(obj)->tp_basicsize > basicsize) {
6642             Py_DECREF(slotnames);
6643             Py_DECREF(state);
6644             PyErr_Format(PyExc_TypeError,
6645                          "cannot pickle '%.200s' object",
6646                          Py_TYPE(obj)->tp_name);
6647             return NULL;
6648         }
6649     }
6650 
6651     if (slotnames != Py_None && PyList_GET_SIZE(slotnames) > 0) {
6652         PyObject *slots;
6653         Py_ssize_t slotnames_size, i;
6654 
6655         slots = PyDict_New();
6656         if (slots == NULL) {
6657             Py_DECREF(slotnames);
6658             Py_DECREF(state);
6659             return NULL;
6660         }
6661 
6662         slotnames_size = PyList_GET_SIZE(slotnames);
6663         for (i = 0; i < slotnames_size; i++) {
6664             PyObject *name, *value;
6665 
6666             name = Py_NewRef(PyList_GET_ITEM(slotnames, i));
6667             if (PyObject_GetOptionalAttr(obj, name, &value) < 0) {
6668                 Py_DECREF(name);
6669                 goto error;
6670             }
6671             if (value == NULL) {
6672                 Py_DECREF(name);
6673                 /* It is not an error if the attribute is not present. */
6674             }
6675             else {
6676                 int err = PyDict_SetItem(slots, name, value);
6677                 Py_DECREF(name);
6678                 Py_DECREF(value);
6679                 if (err) {
6680                     goto error;
6681                 }
6682             }
6683 
6684             /* The list is stored on the class so it may mutate while we
6685                iterate over it */
6686             if (slotnames_size != PyList_GET_SIZE(slotnames)) {
6687                 PyErr_Format(PyExc_RuntimeError,
6688                              "__slotsname__ changed size during iteration");
6689                 goto error;
6690             }
6691 
6692             /* We handle errors within the loop here. */
6693             if (0) {
6694               error:
6695                 Py_DECREF(slotnames);
6696                 Py_DECREF(slots);
6697                 Py_DECREF(state);
6698                 return NULL;
6699             }
6700         }
6701 
6702         /* If we found some slot attributes, pack them in a tuple along
6703            the original attribute dictionary. */
6704         if (PyDict_GET_SIZE(slots) > 0) {
6705             PyObject *state2;
6706 
6707             state2 = PyTuple_Pack(2, state, slots);
6708             Py_DECREF(state);
6709             if (state2 == NULL) {
6710                 Py_DECREF(slotnames);
6711                 Py_DECREF(slots);
6712                 return NULL;
6713             }
6714             state = state2;
6715         }
6716         Py_DECREF(slots);
6717     }
6718     Py_DECREF(slotnames);
6719 
6720     return state;
6721 }
6722 
6723 static PyObject *
object_getstate(PyObject * obj,int required)6724 object_getstate(PyObject *obj, int required)
6725 {
6726     PyObject *getstate, *state;
6727 
6728     getstate = PyObject_GetAttr(obj, &_Py_ID(__getstate__));
6729     if (getstate == NULL) {
6730         return NULL;
6731     }
6732     if (PyCFunction_Check(getstate) &&
6733         PyCFunction_GET_SELF(getstate) == obj &&
6734         PyCFunction_GET_FUNCTION(getstate) == object___getstate__)
6735     {
6736         /* If __getstate__ is not overridden pass the required argument. */
6737         state = object_getstate_default(obj, required);
6738     }
6739     else {
6740         state = _PyObject_CallNoArgs(getstate);
6741     }
6742     Py_DECREF(getstate);
6743     return state;
6744 }
6745 
6746 PyObject *
_PyObject_GetState(PyObject * obj)6747 _PyObject_GetState(PyObject *obj)
6748 {
6749     return object_getstate(obj, 0);
6750 }
6751 
6752 /*[clinic input]
6753 object.__getstate__
6754 
6755 Helper for pickle.
6756 [clinic start generated code]*/
6757 
6758 static PyObject *
object___getstate___impl(PyObject * self)6759 object___getstate___impl(PyObject *self)
6760 /*[clinic end generated code: output=5a2500dcb6217e9e input=692314d8fbe194ee]*/
6761 {
6762     return object_getstate_default(self, 0);
6763 }
6764 
6765 static int
_PyObject_GetNewArguments(PyObject * obj,PyObject ** args,PyObject ** kwargs)6766 _PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
6767 {
6768     PyObject *getnewargs, *getnewargs_ex;
6769 
6770     if (args == NULL || kwargs == NULL) {
6771         PyErr_BadInternalCall();
6772         return -1;
6773     }
6774 
6775     /* We first attempt to fetch the arguments for __new__ by calling
6776        __getnewargs_ex__ on the object. */
6777     getnewargs_ex = _PyObject_LookupSpecial(obj, &_Py_ID(__getnewargs_ex__));
6778     if (getnewargs_ex != NULL) {
6779         PyObject *newargs = _PyObject_CallNoArgs(getnewargs_ex);
6780         Py_DECREF(getnewargs_ex);
6781         if (newargs == NULL) {
6782             return -1;
6783         }
6784         if (!PyTuple_Check(newargs)) {
6785             PyErr_Format(PyExc_TypeError,
6786                          "__getnewargs_ex__ should return a tuple, "
6787                          "not '%.200s'", Py_TYPE(newargs)->tp_name);
6788             Py_DECREF(newargs);
6789             return -1;
6790         }
6791         if (PyTuple_GET_SIZE(newargs) != 2) {
6792             PyErr_Format(PyExc_ValueError,
6793                          "__getnewargs_ex__ should return a tuple of "
6794                          "length 2, not %zd", PyTuple_GET_SIZE(newargs));
6795             Py_DECREF(newargs);
6796             return -1;
6797         }
6798         *args = Py_NewRef(PyTuple_GET_ITEM(newargs, 0));
6799         *kwargs = Py_NewRef(PyTuple_GET_ITEM(newargs, 1));
6800         Py_DECREF(newargs);
6801 
6802         /* XXX We should perhaps allow None to be passed here. */
6803         if (!PyTuple_Check(*args)) {
6804             PyErr_Format(PyExc_TypeError,
6805                          "first item of the tuple returned by "
6806                          "__getnewargs_ex__ must be a tuple, not '%.200s'",
6807                          Py_TYPE(*args)->tp_name);
6808             Py_CLEAR(*args);
6809             Py_CLEAR(*kwargs);
6810             return -1;
6811         }
6812         if (!PyDict_Check(*kwargs)) {
6813             PyErr_Format(PyExc_TypeError,
6814                          "second item of the tuple returned by "
6815                          "__getnewargs_ex__ must be a dict, not '%.200s'",
6816                          Py_TYPE(*kwargs)->tp_name);
6817             Py_CLEAR(*args);
6818             Py_CLEAR(*kwargs);
6819             return -1;
6820         }
6821         return 0;
6822     } else if (PyErr_Occurred()) {
6823         return -1;
6824     }
6825 
6826     /* The object does not have __getnewargs_ex__ so we fallback on using
6827        __getnewargs__ instead. */
6828     getnewargs = _PyObject_LookupSpecial(obj, &_Py_ID(__getnewargs__));
6829     if (getnewargs != NULL) {
6830         *args = _PyObject_CallNoArgs(getnewargs);
6831         Py_DECREF(getnewargs);
6832         if (*args == NULL) {
6833             return -1;
6834         }
6835         if (!PyTuple_Check(*args)) {
6836             PyErr_Format(PyExc_TypeError,
6837                          "__getnewargs__ should return a tuple, "
6838                          "not '%.200s'", Py_TYPE(*args)->tp_name);
6839             Py_CLEAR(*args);
6840             return -1;
6841         }
6842         *kwargs = NULL;
6843         return 0;
6844     } else if (PyErr_Occurred()) {
6845         return -1;
6846     }
6847 
6848     /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
6849        mean __new__ does not takes any arguments on this object, or that the
6850        object does not implement the reduce protocol for pickling or
6851        copying. */
6852     *args = NULL;
6853     *kwargs = NULL;
6854     return 0;
6855 }
6856 
6857 static int
_PyObject_GetItemsIter(PyObject * obj,PyObject ** listitems,PyObject ** dictitems)6858 _PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
6859                        PyObject **dictitems)
6860 {
6861     if (listitems == NULL || dictitems == NULL) {
6862         PyErr_BadInternalCall();
6863         return -1;
6864     }
6865 
6866     if (!PyList_Check(obj)) {
6867         *listitems = Py_NewRef(Py_None);
6868     }
6869     else {
6870         *listitems = PyObject_GetIter(obj);
6871         if (*listitems == NULL)
6872             return -1;
6873     }
6874 
6875     if (!PyDict_Check(obj)) {
6876         *dictitems = Py_NewRef(Py_None);
6877     }
6878     else {
6879         PyObject *items = PyObject_CallMethodNoArgs(obj, &_Py_ID(items));
6880         if (items == NULL) {
6881             Py_CLEAR(*listitems);
6882             return -1;
6883         }
6884         *dictitems = PyObject_GetIter(items);
6885         Py_DECREF(items);
6886         if (*dictitems == NULL) {
6887             Py_CLEAR(*listitems);
6888             return -1;
6889         }
6890     }
6891 
6892     assert(*listitems != NULL && *dictitems != NULL);
6893 
6894     return 0;
6895 }
6896 
6897 static PyObject *
reduce_newobj(PyObject * obj)6898 reduce_newobj(PyObject *obj)
6899 {
6900     PyObject *args = NULL, *kwargs = NULL;
6901     PyObject *copyreg;
6902     PyObject *newobj, *newargs, *state, *listitems, *dictitems;
6903     PyObject *result;
6904     int hasargs;
6905 
6906     if (Py_TYPE(obj)->tp_new == NULL) {
6907         PyErr_Format(PyExc_TypeError,
6908                      "cannot pickle '%.200s' object",
6909                      Py_TYPE(obj)->tp_name);
6910         return NULL;
6911     }
6912     if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
6913         return NULL;
6914 
6915     copyreg = import_copyreg();
6916     if (copyreg == NULL) {
6917         Py_XDECREF(args);
6918         Py_XDECREF(kwargs);
6919         return NULL;
6920     }
6921     hasargs = (args != NULL);
6922     if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
6923         PyObject *cls;
6924         Py_ssize_t i, n;
6925 
6926         Py_XDECREF(kwargs);
6927         newobj = PyObject_GetAttr(copyreg, &_Py_ID(__newobj__));
6928         Py_DECREF(copyreg);
6929         if (newobj == NULL) {
6930             Py_XDECREF(args);
6931             return NULL;
6932         }
6933         n = args ? PyTuple_GET_SIZE(args) : 0;
6934         newargs = PyTuple_New(n+1);
6935         if (newargs == NULL) {
6936             Py_XDECREF(args);
6937             Py_DECREF(newobj);
6938             return NULL;
6939         }
6940         cls = (PyObject *) Py_TYPE(obj);
6941         PyTuple_SET_ITEM(newargs, 0, Py_NewRef(cls));
6942         for (i = 0; i < n; i++) {
6943             PyObject *v = PyTuple_GET_ITEM(args, i);
6944             PyTuple_SET_ITEM(newargs, i+1, Py_NewRef(v));
6945         }
6946         Py_XDECREF(args);
6947     }
6948     else if (args != NULL) {
6949         newobj = PyObject_GetAttr(copyreg, &_Py_ID(__newobj_ex__));
6950         Py_DECREF(copyreg);
6951         if (newobj == NULL) {
6952             Py_DECREF(args);
6953             Py_DECREF(kwargs);
6954             return NULL;
6955         }
6956         newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
6957         Py_DECREF(args);
6958         Py_DECREF(kwargs);
6959         if (newargs == NULL) {
6960             Py_DECREF(newobj);
6961             return NULL;
6962         }
6963     }
6964     else {
6965         /* args == NULL */
6966         Py_DECREF(copyreg);
6967         Py_DECREF(kwargs);
6968         PyErr_BadInternalCall();
6969         return NULL;
6970     }
6971 
6972     state = object_getstate(obj, !(hasargs || PyList_Check(obj) || PyDict_Check(obj)));
6973     if (state == NULL) {
6974         Py_DECREF(newobj);
6975         Py_DECREF(newargs);
6976         return NULL;
6977     }
6978     if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
6979         Py_DECREF(newobj);
6980         Py_DECREF(newargs);
6981         Py_DECREF(state);
6982         return NULL;
6983     }
6984 
6985     result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
6986     Py_DECREF(newobj);
6987     Py_DECREF(newargs);
6988     Py_DECREF(state);
6989     Py_DECREF(listitems);
6990     Py_DECREF(dictitems);
6991     return result;
6992 }
6993 
6994 /*
6995  * There were two problems when object.__reduce__ and object.__reduce_ex__
6996  * were implemented in the same function:
6997  *  - trying to pickle an object with a custom __reduce__ method that
6998  *    fell back to object.__reduce__ in certain circumstances led to
6999  *    infinite recursion at Python level and eventual RecursionError.
7000  *  - Pickling objects that lied about their type by overwriting the
7001  *    __class__ descriptor could lead to infinite recursion at C level
7002  *    and eventual segfault.
7003  *
7004  * Because of backwards compatibility, the two methods still have to
7005  * behave in the same way, even if this is not required by the pickle
7006  * protocol. This common functionality was moved to the _common_reduce
7007  * function.
7008  */
7009 static PyObject *
_common_reduce(PyObject * self,int proto)7010 _common_reduce(PyObject *self, int proto)
7011 {
7012     PyObject *copyreg, *res;
7013 
7014     if (proto >= 2)
7015         return reduce_newobj(self);
7016 
7017     copyreg = import_copyreg();
7018     if (!copyreg)
7019         return NULL;
7020 
7021     res = PyObject_CallMethod(copyreg, "_reduce_ex", "Oi", self, proto);
7022     Py_DECREF(copyreg);
7023 
7024     return res;
7025 }
7026 
7027 /*[clinic input]
7028 object.__reduce__
7029 
7030 Helper for pickle.
7031 [clinic start generated code]*/
7032 
7033 static PyObject *
object___reduce___impl(PyObject * self)7034 object___reduce___impl(PyObject *self)
7035 /*[clinic end generated code: output=d4ca691f891c6e2f input=11562e663947e18b]*/
7036 {
7037     return _common_reduce(self, 0);
7038 }
7039 
7040 /*[clinic input]
7041 object.__reduce_ex__
7042 
7043   protocol: int
7044   /
7045 
7046 Helper for pickle.
7047 [clinic start generated code]*/
7048 
7049 static PyObject *
object___reduce_ex___impl(PyObject * self,int protocol)7050 object___reduce_ex___impl(PyObject *self, int protocol)
7051 /*[clinic end generated code: output=2e157766f6b50094 input=f326b43fb8a4c5ff]*/
7052 {
7053     PyObject *reduce;
7054     if (PyObject_GetOptionalAttr(self, &_Py_ID(__reduce__), &reduce) < 0) {
7055         return NULL;
7056     }
7057     if (reduce != NULL) {
7058         PyObject *cls, *clsreduce;
7059         int override;
7060 
7061         cls = (PyObject *) Py_TYPE(self);
7062         clsreduce = PyObject_GetAttr(cls, &_Py_ID(__reduce__));
7063         if (clsreduce == NULL) {
7064             Py_DECREF(reduce);
7065             return NULL;
7066         }
7067 
7068         PyInterpreterState *interp = _PyInterpreterState_GET();
7069         override = (clsreduce != _Py_INTERP_CACHED_OBJECT(interp, objreduce));
7070         Py_DECREF(clsreduce);
7071         if (override) {
7072             PyObject *res = _PyObject_CallNoArgs(reduce);
7073             Py_DECREF(reduce);
7074             return res;
7075         }
7076         else
7077             Py_DECREF(reduce);
7078     }
7079 
7080     return _common_reduce(self, protocol);
7081 }
7082 
7083 static PyObject *
object_subclasshook(PyObject * cls,PyObject * args)7084 object_subclasshook(PyObject *cls, PyObject *args)
7085 {
7086     Py_RETURN_NOTIMPLEMENTED;
7087 }
7088 
7089 PyDoc_STRVAR(object_subclasshook_doc,
7090 "Abstract classes can override this to customize issubclass().\n"
7091 "\n"
7092 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
7093 "It should return True, False or NotImplemented.  If it returns\n"
7094 "NotImplemented, the normal algorithm is used.  Otherwise, it\n"
7095 "overrides the normal algorithm (and the outcome is cached).\n");
7096 
7097 static PyObject *
object_init_subclass(PyObject * cls,PyObject * arg)7098 object_init_subclass(PyObject *cls, PyObject *arg)
7099 {
7100     Py_RETURN_NONE;
7101 }
7102 
7103 PyDoc_STRVAR(object_init_subclass_doc,
7104 "This method is called when a class is subclassed.\n"
7105 "\n"
7106 "The default implementation does nothing. It may be\n"
7107 "overridden to extend subclasses.\n");
7108 
7109 /*[clinic input]
7110 object.__format__
7111 
7112   format_spec: unicode
7113   /
7114 
7115 Default object formatter.
7116 
7117 Return str(self) if format_spec is empty. Raise TypeError otherwise.
7118 [clinic start generated code]*/
7119 
7120 static PyObject *
object___format___impl(PyObject * self,PyObject * format_spec)7121 object___format___impl(PyObject *self, PyObject *format_spec)
7122 /*[clinic end generated code: output=34897efb543a974b input=b94d8feb006689ea]*/
7123 {
7124     /* Issue 7994: If we're converting to a string, we
7125        should reject format specifications */
7126     if (PyUnicode_GET_LENGTH(format_spec) > 0) {
7127         PyErr_Format(PyExc_TypeError,
7128                      "unsupported format string passed to %.200s.__format__",
7129                      Py_TYPE(self)->tp_name);
7130         return NULL;
7131     }
7132     return PyObject_Str(self);
7133 }
7134 
7135 /*[clinic input]
7136 object.__sizeof__
7137 
7138 Size of object in memory, in bytes.
7139 [clinic start generated code]*/
7140 
7141 static PyObject *
object___sizeof___impl(PyObject * self)7142 object___sizeof___impl(PyObject *self)
7143 /*[clinic end generated code: output=73edab332f97d550 input=1200ff3dfe485306]*/
7144 {
7145     Py_ssize_t res, isize;
7146 
7147     res = 0;
7148     isize = Py_TYPE(self)->tp_itemsize;
7149     if (isize > 0) {
7150         /* This assumes that ob_size is valid if tp_itemsize is not 0,
7151          which isn't true for PyLongObject. */
7152         res = _PyVarObject_CAST(self)->ob_size * isize;
7153     }
7154     res += Py_TYPE(self)->tp_basicsize;
7155 
7156     return PyLong_FromSsize_t(res);
7157 }
7158 
7159 /* __dir__ for generic objects: returns __dict__, __class__,
7160    and recursively up the __class__.__bases__ chain.
7161 */
7162 /*[clinic input]
7163 object.__dir__
7164 
7165 Default dir() implementation.
7166 [clinic start generated code]*/
7167 
7168 static PyObject *
object___dir___impl(PyObject * self)7169 object___dir___impl(PyObject *self)
7170 /*[clinic end generated code: output=66dd48ea62f26c90 input=0a89305bec669b10]*/
7171 {
7172     PyObject *result = NULL;
7173     PyObject *dict = NULL;
7174     PyObject *itsclass = NULL;
7175 
7176     /* Get __dict__ (which may or may not be a real dict...) */
7177     if (PyObject_GetOptionalAttr(self, &_Py_ID(__dict__), &dict) < 0) {
7178         return NULL;
7179     }
7180     if (dict == NULL) {
7181         dict = PyDict_New();
7182     }
7183     else if (!PyDict_Check(dict)) {
7184         Py_DECREF(dict);
7185         dict = PyDict_New();
7186     }
7187     else {
7188         /* Copy __dict__ to avoid mutating it. */
7189         PyObject *temp = PyDict_Copy(dict);
7190         Py_SETREF(dict, temp);
7191     }
7192 
7193     if (dict == NULL)
7194         goto error;
7195 
7196     /* Merge in attrs reachable from its class. */
7197     if (PyObject_GetOptionalAttr(self, &_Py_ID(__class__), &itsclass) < 0) {
7198         goto error;
7199     }
7200     /* XXX(tomer): Perhaps fall back to Py_TYPE(obj) if no
7201                    __class__ exists? */
7202     if (itsclass != NULL && merge_class_dict(dict, itsclass) < 0)
7203         goto error;
7204 
7205     result = PyDict_Keys(dict);
7206     /* fall through */
7207 error:
7208     Py_XDECREF(itsclass);
7209     Py_XDECREF(dict);
7210     return result;
7211 }
7212 
7213 static PyMethodDef object_methods[] = {
7214     OBJECT___REDUCE_EX___METHODDEF
7215     OBJECT___REDUCE___METHODDEF
7216     OBJECT___GETSTATE___METHODDEF
7217     {"__subclasshook__", object_subclasshook, METH_CLASS | METH_O,
7218      object_subclasshook_doc},
7219     {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
7220      object_init_subclass_doc},
7221     OBJECT___FORMAT___METHODDEF
7222     OBJECT___SIZEOF___METHODDEF
7223     OBJECT___DIR___METHODDEF
7224     {0}
7225 };
7226 
7227 PyDoc_STRVAR(object_doc,
7228 "object()\n--\n\n"
7229 "The base class of the class hierarchy.\n\n"
7230 "When called, it accepts no arguments and returns a new featureless\n"
7231 "instance that has no instance attributes and cannot be given any.\n");
7232 
7233 PyTypeObject PyBaseObject_Type = {
7234     PyVarObject_HEAD_INIT(&PyType_Type, 0)
7235     "object",                                   /* tp_name */
7236     sizeof(PyObject),                           /* tp_basicsize */
7237     0,                                          /* tp_itemsize */
7238     object_dealloc,                             /* tp_dealloc */
7239     0,                                          /* tp_vectorcall_offset */
7240     0,                                          /* tp_getattr */
7241     0,                                          /* tp_setattr */
7242     0,                                          /* tp_as_async */
7243     object_repr,                                /* tp_repr */
7244     0,                                          /* tp_as_number */
7245     0,                                          /* tp_as_sequence */
7246     0,                                          /* tp_as_mapping */
7247     PyObject_GenericHash,                       /* tp_hash */
7248     0,                                          /* tp_call */
7249     object_str,                                 /* tp_str */
7250     PyObject_GenericGetAttr,                    /* tp_getattro */
7251     PyObject_GenericSetAttr,                    /* tp_setattro */
7252     0,                                          /* tp_as_buffer */
7253     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
7254     object_doc,                                 /* tp_doc */
7255     0,                                          /* tp_traverse */
7256     0,                                          /* tp_clear */
7257     object_richcompare,                         /* tp_richcompare */
7258     0,                                          /* tp_weaklistoffset */
7259     0,                                          /* tp_iter */
7260     0,                                          /* tp_iternext */
7261     object_methods,                             /* tp_methods */
7262     0,                                          /* tp_members */
7263     object_getsets,                             /* tp_getset */
7264     0,                                          /* tp_base */
7265     0,                                          /* tp_dict */
7266     0,                                          /* tp_descr_get */
7267     0,                                          /* tp_descr_set */
7268     0,                                          /* tp_dictoffset */
7269     object_init,                                /* tp_init */
7270     PyType_GenericAlloc,                        /* tp_alloc */
7271     object_new,                                 /* tp_new */
7272     PyObject_Del,                               /* tp_free */
7273 };
7274 
7275 
7276 static int
type_add_method(PyTypeObject * type,PyMethodDef * meth)7277 type_add_method(PyTypeObject *type, PyMethodDef *meth)
7278 {
7279     PyObject *descr;
7280     int isdescr = 1;
7281     if (meth->ml_flags & METH_CLASS) {
7282         if (meth->ml_flags & METH_STATIC) {
7283             PyErr_SetString(PyExc_ValueError,
7284                     "method cannot be both class and static");
7285             return -1;
7286         }
7287         descr = PyDescr_NewClassMethod(type, meth);
7288     }
7289     else if (meth->ml_flags & METH_STATIC) {
7290         PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
7291         if (cfunc == NULL) {
7292             return -1;
7293         }
7294         descr = PyStaticMethod_New(cfunc);
7295         isdescr = 0;  // PyStaticMethod is not PyDescrObject
7296         Py_DECREF(cfunc);
7297     }
7298     else {
7299         descr = PyDescr_NewMethod(type, meth);
7300     }
7301     if (descr == NULL) {
7302         return -1;
7303     }
7304 
7305     PyObject *name;
7306     if (isdescr) {
7307         name = PyDescr_NAME(descr);
7308     }
7309     else {
7310         name = PyUnicode_FromString(meth->ml_name);
7311         if (name == NULL) {
7312             Py_DECREF(descr);
7313             return -1;
7314         }
7315     }
7316 
7317     int err;
7318     PyObject *dict = lookup_tp_dict(type);
7319     if (!(meth->ml_flags & METH_COEXIST)) {
7320         err = PyDict_SetDefaultRef(dict, name, descr, NULL) < 0;
7321     }
7322     else {
7323         err = PyDict_SetItem(dict, name, descr) < 0;
7324     }
7325     if (!isdescr) {
7326         Py_DECREF(name);
7327     }
7328     Py_DECREF(descr);
7329     if (err) {
7330         return -1;
7331     }
7332     return 0;
7333 }
7334 
7335 int
_PyType_AddMethod(PyTypeObject * type,PyMethodDef * meth)7336 _PyType_AddMethod(PyTypeObject *type, PyMethodDef *meth)
7337 {
7338     return type_add_method(type, meth);
7339 }
7340 
7341 
7342 /* Add the methods from tp_methods to the __dict__ in a type object */
7343 static int
type_add_methods(PyTypeObject * type)7344 type_add_methods(PyTypeObject *type)
7345 {
7346     PyMethodDef *meth = type->tp_methods;
7347     if (meth == NULL) {
7348         return 0;
7349     }
7350 
7351     for (; meth->ml_name != NULL; meth++) {
7352         if (type_add_method(type, meth) < 0) {
7353             return -1;
7354         }
7355     }
7356     return 0;
7357 }
7358 
7359 
7360 static int
type_add_members(PyTypeObject * type)7361 type_add_members(PyTypeObject *type)
7362 {
7363     PyMemberDef *memb = type->tp_members;
7364     if (memb == NULL) {
7365         return 0;
7366     }
7367 
7368     PyObject *dict = lookup_tp_dict(type);
7369     for (; memb->name != NULL; memb++) {
7370         PyObject *descr = PyDescr_NewMember(type, memb);
7371         if (descr == NULL)
7372             return -1;
7373 
7374         if (PyDict_SetDefaultRef(dict, PyDescr_NAME(descr), descr, NULL) < 0) {
7375             Py_DECREF(descr);
7376             return -1;
7377         }
7378         Py_DECREF(descr);
7379     }
7380     return 0;
7381 }
7382 
7383 
7384 static int
type_add_getset(PyTypeObject * type)7385 type_add_getset(PyTypeObject *type)
7386 {
7387     PyGetSetDef *gsp = type->tp_getset;
7388     if (gsp == NULL) {
7389         return 0;
7390     }
7391 
7392     PyObject *dict = lookup_tp_dict(type);
7393     for (; gsp->name != NULL; gsp++) {
7394         PyObject *descr = PyDescr_NewGetSet(type, gsp);
7395         if (descr == NULL) {
7396             return -1;
7397         }
7398 
7399         if (PyDict_SetDefaultRef(dict, PyDescr_NAME(descr), descr, NULL) < 0) {
7400             Py_DECREF(descr);
7401             return -1;
7402         }
7403         Py_DECREF(descr);
7404     }
7405     return 0;
7406 }
7407 
7408 
7409 static void
inherit_special(PyTypeObject * type,PyTypeObject * base)7410 inherit_special(PyTypeObject *type, PyTypeObject *base)
7411 {
7412     /* Copying tp_traverse and tp_clear is connected to the GC flags */
7413     if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
7414         (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
7415         (!type->tp_traverse && !type->tp_clear)) {
7416         type->tp_flags |= Py_TPFLAGS_HAVE_GC;
7417         if (type->tp_traverse == NULL)
7418             type->tp_traverse = base->tp_traverse;
7419         if (type->tp_clear == NULL)
7420             type->tp_clear = base->tp_clear;
7421     }
7422     type->tp_flags |= (base->tp_flags & Py_TPFLAGS_PREHEADER);
7423 
7424     if (type->tp_basicsize == 0)
7425         type->tp_basicsize = base->tp_basicsize;
7426 
7427     /* Copy other non-function slots */
7428 
7429 #define COPYVAL(SLOT) \
7430     if (type->SLOT == 0) { type->SLOT = base->SLOT; }
7431 
7432     COPYVAL(tp_itemsize);
7433     COPYVAL(tp_weaklistoffset);
7434     COPYVAL(tp_dictoffset);
7435 
7436 #undef COPYVAL
7437 
7438     /* Setup fast subclass flags */
7439     PyObject *mro = lookup_tp_mro(base);
7440     if (is_subtype_with_mro(mro, base, (PyTypeObject*)PyExc_BaseException)) {
7441         type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
7442     }
7443     else if (is_subtype_with_mro(mro, base, &PyType_Type)) {
7444         type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
7445     }
7446     else if (is_subtype_with_mro(mro, base, &PyLong_Type)) {
7447         type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
7448     }
7449     else if (is_subtype_with_mro(mro, base, &PyBytes_Type)) {
7450         type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
7451     }
7452     else if (is_subtype_with_mro(mro, base, &PyUnicode_Type)) {
7453         type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
7454     }
7455     else if (is_subtype_with_mro(mro, base, &PyTuple_Type)) {
7456         type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
7457     }
7458     else if (is_subtype_with_mro(mro, base, &PyList_Type)) {
7459         type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
7460     }
7461     else if (is_subtype_with_mro(mro, base, &PyDict_Type)) {
7462         type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
7463     }
7464 
7465     /* Setup some inheritable flags */
7466     if (PyType_HasFeature(base, _Py_TPFLAGS_MATCH_SELF)) {
7467         type->tp_flags |= _Py_TPFLAGS_MATCH_SELF;
7468     }
7469     if (PyType_HasFeature(base, Py_TPFLAGS_ITEMS_AT_END)) {
7470         type->tp_flags |= Py_TPFLAGS_ITEMS_AT_END;
7471     }
7472 }
7473 
7474 static int
overrides_hash(PyTypeObject * type)7475 overrides_hash(PyTypeObject *type)
7476 {
7477     PyObject *dict = lookup_tp_dict(type);
7478 
7479     assert(dict != NULL);
7480     int r = PyDict_Contains(dict, &_Py_ID(__eq__));
7481     if (r == 0) {
7482         r = PyDict_Contains(dict, &_Py_ID(__hash__));
7483     }
7484     return r;
7485 }
7486 
7487 static int
inherit_slots(PyTypeObject * type,PyTypeObject * base)7488 inherit_slots(PyTypeObject *type, PyTypeObject *base)
7489 {
7490     PyTypeObject *basebase;
7491 
7492 #undef SLOTDEFINED
7493 #undef COPYSLOT
7494 #undef COPYNUM
7495 #undef COPYSEQ
7496 #undef COPYMAP
7497 #undef COPYBUF
7498 
7499 #define SLOTDEFINED(SLOT) \
7500     (base->SLOT != 0 && \
7501      (basebase == NULL || base->SLOT != basebase->SLOT))
7502 
7503 #define COPYSLOT(SLOT) \
7504     if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
7505 
7506 #define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
7507 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
7508 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
7509 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
7510 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
7511 
7512     /* This won't inherit indirect slots (from tp_as_number etc.)
7513        if type doesn't provide the space. */
7514 
7515     if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
7516         basebase = base->tp_base;
7517         if (basebase->tp_as_number == NULL)
7518             basebase = NULL;
7519         COPYNUM(nb_add);
7520         COPYNUM(nb_subtract);
7521         COPYNUM(nb_multiply);
7522         COPYNUM(nb_remainder);
7523         COPYNUM(nb_divmod);
7524         COPYNUM(nb_power);
7525         COPYNUM(nb_negative);
7526         COPYNUM(nb_positive);
7527         COPYNUM(nb_absolute);
7528         COPYNUM(nb_bool);
7529         COPYNUM(nb_invert);
7530         COPYNUM(nb_lshift);
7531         COPYNUM(nb_rshift);
7532         COPYNUM(nb_and);
7533         COPYNUM(nb_xor);
7534         COPYNUM(nb_or);
7535         COPYNUM(nb_int);
7536         COPYNUM(nb_float);
7537         COPYNUM(nb_inplace_add);
7538         COPYNUM(nb_inplace_subtract);
7539         COPYNUM(nb_inplace_multiply);
7540         COPYNUM(nb_inplace_remainder);
7541         COPYNUM(nb_inplace_power);
7542         COPYNUM(nb_inplace_lshift);
7543         COPYNUM(nb_inplace_rshift);
7544         COPYNUM(nb_inplace_and);
7545         COPYNUM(nb_inplace_xor);
7546         COPYNUM(nb_inplace_or);
7547         COPYNUM(nb_true_divide);
7548         COPYNUM(nb_floor_divide);
7549         COPYNUM(nb_inplace_true_divide);
7550         COPYNUM(nb_inplace_floor_divide);
7551         COPYNUM(nb_index);
7552         COPYNUM(nb_matrix_multiply);
7553         COPYNUM(nb_inplace_matrix_multiply);
7554     }
7555 
7556     if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
7557         basebase = base->tp_base;
7558         if (basebase->tp_as_async == NULL)
7559             basebase = NULL;
7560         COPYASYNC(am_await);
7561         COPYASYNC(am_aiter);
7562         COPYASYNC(am_anext);
7563     }
7564 
7565     if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
7566         basebase = base->tp_base;
7567         if (basebase->tp_as_sequence == NULL)
7568             basebase = NULL;
7569         COPYSEQ(sq_length);
7570         COPYSEQ(sq_concat);
7571         COPYSEQ(sq_repeat);
7572         COPYSEQ(sq_item);
7573         COPYSEQ(sq_ass_item);
7574         COPYSEQ(sq_contains);
7575         COPYSEQ(sq_inplace_concat);
7576         COPYSEQ(sq_inplace_repeat);
7577     }
7578 
7579     if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
7580         basebase = base->tp_base;
7581         if (basebase->tp_as_mapping == NULL)
7582             basebase = NULL;
7583         COPYMAP(mp_length);
7584         COPYMAP(mp_subscript);
7585         COPYMAP(mp_ass_subscript);
7586     }
7587 
7588     if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
7589         basebase = base->tp_base;
7590         if (basebase->tp_as_buffer == NULL)
7591             basebase = NULL;
7592         COPYBUF(bf_getbuffer);
7593         COPYBUF(bf_releasebuffer);
7594     }
7595 
7596     basebase = base->tp_base;
7597 
7598     COPYSLOT(tp_dealloc);
7599     if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
7600         type->tp_getattr = base->tp_getattr;
7601         type->tp_getattro = base->tp_getattro;
7602     }
7603     if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
7604         type->tp_setattr = base->tp_setattr;
7605         type->tp_setattro = base->tp_setattro;
7606     }
7607     COPYSLOT(tp_repr);
7608     /* tp_hash see tp_richcompare */
7609     {
7610         /* Always inherit tp_vectorcall_offset to support PyVectorcall_Call().
7611          * If Py_TPFLAGS_HAVE_VECTORCALL is not inherited, then vectorcall
7612          * won't be used automatically. */
7613         COPYSLOT(tp_vectorcall_offset);
7614 
7615         /* Inherit Py_TPFLAGS_HAVE_VECTORCALL if tp_call is not overridden */
7616         if (!type->tp_call &&
7617             _PyType_HasFeature(base, Py_TPFLAGS_HAVE_VECTORCALL))
7618         {
7619             type->tp_flags |= Py_TPFLAGS_HAVE_VECTORCALL;
7620         }
7621         COPYSLOT(tp_call);
7622     }
7623     COPYSLOT(tp_str);
7624     {
7625         /* Copy comparison-related slots only when
7626            not overriding them anywhere */
7627         if (type->tp_richcompare == NULL &&
7628             type->tp_hash == NULL)
7629         {
7630             int r = overrides_hash(type);
7631             if (r < 0) {
7632                 return -1;
7633             }
7634             if (!r) {
7635                 type->tp_richcompare = base->tp_richcompare;
7636                 type->tp_hash = base->tp_hash;
7637             }
7638         }
7639     }
7640     {
7641         COPYSLOT(tp_iter);
7642         COPYSLOT(tp_iternext);
7643     }
7644     {
7645         COPYSLOT(tp_descr_get);
7646         /* Inherit Py_TPFLAGS_METHOD_DESCRIPTOR if tp_descr_get was inherited,
7647          * but only for extension types */
7648         if (base->tp_descr_get &&
7649             type->tp_descr_get == base->tp_descr_get &&
7650             _PyType_HasFeature(type, Py_TPFLAGS_IMMUTABLETYPE) &&
7651             _PyType_HasFeature(base, Py_TPFLAGS_METHOD_DESCRIPTOR))
7652         {
7653             type->tp_flags |= Py_TPFLAGS_METHOD_DESCRIPTOR;
7654         }
7655         COPYSLOT(tp_descr_set);
7656         COPYSLOT(tp_dictoffset);
7657         COPYSLOT(tp_init);
7658         COPYSLOT(tp_alloc);
7659         COPYSLOT(tp_is_gc);
7660         COPYSLOT(tp_finalize);
7661         if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
7662             (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
7663             /* They agree about gc. */
7664             COPYSLOT(tp_free);
7665         }
7666         else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
7667                  type->tp_free == NULL &&
7668                  base->tp_free == PyObject_Free) {
7669             /* A bit of magic to plug in the correct default
7670              * tp_free function when a derived class adds gc,
7671              * didn't define tp_free, and the base uses the
7672              * default non-gc tp_free.
7673              */
7674             type->tp_free = PyObject_GC_Del;
7675         }
7676         /* else they didn't agree about gc, and there isn't something
7677          * obvious to be done -- the type is on its own.
7678          */
7679     }
7680     return 0;
7681 }
7682 
7683 static int add_operators(PyTypeObject *);
7684 static int add_tp_new_wrapper(PyTypeObject *type);
7685 
7686 #define COLLECTION_FLAGS (Py_TPFLAGS_SEQUENCE | Py_TPFLAGS_MAPPING)
7687 
7688 static int
type_ready_pre_checks(PyTypeObject * type)7689 type_ready_pre_checks(PyTypeObject *type)
7690 {
7691     /* Consistency checks for PEP 590:
7692      * - Py_TPFLAGS_METHOD_DESCRIPTOR requires tp_descr_get
7693      * - Py_TPFLAGS_HAVE_VECTORCALL requires tp_call and
7694      *   tp_vectorcall_offset > 0
7695      * To avoid mistakes, we require this before inheriting.
7696      */
7697     if (type->tp_flags & Py_TPFLAGS_METHOD_DESCRIPTOR) {
7698         _PyObject_ASSERT((PyObject *)type, type->tp_descr_get != NULL);
7699     }
7700     if (type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) {
7701         _PyObject_ASSERT((PyObject *)type, type->tp_vectorcall_offset > 0);
7702         _PyObject_ASSERT((PyObject *)type, type->tp_call != NULL);
7703     }
7704 
7705     /* Consistency checks for pattern matching
7706      * Py_TPFLAGS_SEQUENCE and Py_TPFLAGS_MAPPING are mutually exclusive */
7707     _PyObject_ASSERT((PyObject *)type, (type->tp_flags & COLLECTION_FLAGS) != COLLECTION_FLAGS);
7708 
7709     if (type->tp_name == NULL) {
7710         PyErr_Format(PyExc_SystemError,
7711                      "Type does not define the tp_name field.");
7712         return -1;
7713     }
7714     return 0;
7715 }
7716 
7717 
7718 static int
type_ready_set_base(PyTypeObject * type)7719 type_ready_set_base(PyTypeObject *type)
7720 {
7721     /* Initialize tp_base (defaults to BaseObject unless that's us) */
7722     PyTypeObject *base = type->tp_base;
7723     if (base == NULL && type != &PyBaseObject_Type) {
7724         base = &PyBaseObject_Type;
7725         if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
7726             type->tp_base = (PyTypeObject*)Py_NewRef((PyObject*)base);
7727         }
7728         else {
7729             type->tp_base = base;
7730         }
7731     }
7732     assert(type->tp_base != NULL || type == &PyBaseObject_Type);
7733 
7734     /* Now the only way base can still be NULL is if type is
7735      * &PyBaseObject_Type. */
7736 
7737     /* Initialize the base class */
7738     if (base != NULL && !_PyType_IsReady(base)) {
7739         if (PyType_Ready(base) < 0) {
7740             return -1;
7741         }
7742     }
7743 
7744     return 0;
7745 }
7746 
7747 static int
type_ready_set_type(PyTypeObject * type)7748 type_ready_set_type(PyTypeObject *type)
7749 {
7750     /* Initialize ob_type if NULL.      This means extensions that want to be
7751        compilable separately on Windows can call PyType_Ready() instead of
7752        initializing the ob_type field of their type objects. */
7753     /* The test for base != NULL is really unnecessary, since base is only
7754        NULL when type is &PyBaseObject_Type, and we know its ob_type is
7755        not NULL (it's initialized to &PyType_Type).      But coverity doesn't
7756        know that. */
7757     PyTypeObject *base = type->tp_base;
7758     if (Py_IS_TYPE(type, NULL) && base != NULL) {
7759         Py_SET_TYPE(type, Py_TYPE(base));
7760     }
7761 
7762     return 0;
7763 }
7764 
7765 static int
type_ready_set_bases(PyTypeObject * type,int initial)7766 type_ready_set_bases(PyTypeObject *type, int initial)
7767 {
7768     if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
7769         if (!initial) {
7770             assert(lookup_tp_bases(type) != NULL);
7771             return 0;
7772         }
7773         assert(lookup_tp_bases(type) == NULL);
7774     }
7775 
7776     PyObject *bases = lookup_tp_bases(type);
7777     if (bases == NULL) {
7778         PyTypeObject *base = type->tp_base;
7779         if (base == NULL) {
7780             bases = PyTuple_New(0);
7781         }
7782         else {
7783             bases = PyTuple_Pack(1, base);
7784         }
7785         if (bases == NULL) {
7786             return -1;
7787         }
7788         set_tp_bases(type, bases, 1);
7789     }
7790     return 0;
7791 }
7792 
7793 
7794 static int
type_ready_set_dict(PyTypeObject * type)7795 type_ready_set_dict(PyTypeObject *type)
7796 {
7797     if (lookup_tp_dict(type) != NULL) {
7798         return 0;
7799     }
7800 
7801     PyObject *dict = PyDict_New();
7802     if (dict == NULL) {
7803         return -1;
7804     }
7805     set_tp_dict(type, dict);
7806     return 0;
7807 }
7808 
7809 
7810 /* If the type dictionary doesn't contain a __doc__, set it from
7811    the tp_doc slot. */
7812 static int
type_dict_set_doc(PyTypeObject * type)7813 type_dict_set_doc(PyTypeObject *type)
7814 {
7815     PyObject *dict = lookup_tp_dict(type);
7816     int r = PyDict_Contains(dict, &_Py_ID(__doc__));
7817     if (r < 0) {
7818         return -1;
7819     }
7820     if (r > 0) {
7821         return 0;
7822     }
7823 
7824     if (type->tp_doc != NULL) {
7825         const char *doc_str;
7826         doc_str = _PyType_DocWithoutSignature(type->tp_name, type->tp_doc);
7827         PyObject *doc = PyUnicode_FromString(doc_str);
7828         if (doc == NULL) {
7829             return -1;
7830         }
7831 
7832         if (PyDict_SetItem(dict, &_Py_ID(__doc__), doc) < 0) {
7833             Py_DECREF(doc);
7834             return -1;
7835         }
7836         Py_DECREF(doc);
7837     }
7838     else {
7839         if (PyDict_SetItem(dict, &_Py_ID(__doc__), Py_None) < 0) {
7840             return -1;
7841         }
7842     }
7843     return 0;
7844 }
7845 
7846 
7847 static int
type_ready_fill_dict(PyTypeObject * type)7848 type_ready_fill_dict(PyTypeObject *type)
7849 {
7850     /* Add type-specific descriptors to tp_dict */
7851     if (add_operators(type) < 0) {
7852         return -1;
7853     }
7854     if (type_add_methods(type) < 0) {
7855         return -1;
7856     }
7857     if (type_add_members(type) < 0) {
7858         return -1;
7859     }
7860     if (type_add_getset(type) < 0) {
7861         return -1;
7862     }
7863     if (type_dict_set_doc(type) < 0) {
7864         return -1;
7865     }
7866     return 0;
7867 }
7868 
7869 static int
type_ready_preheader(PyTypeObject * type)7870 type_ready_preheader(PyTypeObject *type)
7871 {
7872     if (type->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
7873         if (type->tp_dictoffset > 0 || type->tp_dictoffset < -1) {
7874             PyErr_Format(PyExc_TypeError,
7875                         "type %s has the Py_TPFLAGS_MANAGED_DICT flag "
7876                         "but tp_dictoffset is set",
7877                         type->tp_name);
7878             return -1;
7879         }
7880         type->tp_dictoffset = -1;
7881     }
7882     if (type->tp_flags & Py_TPFLAGS_MANAGED_WEAKREF) {
7883         if (type->tp_weaklistoffset != 0 &&
7884             type->tp_weaklistoffset != MANAGED_WEAKREF_OFFSET)
7885         {
7886             PyErr_Format(PyExc_TypeError,
7887                         "type %s has the Py_TPFLAGS_MANAGED_WEAKREF flag "
7888                         "but tp_weaklistoffset is set",
7889                         type->tp_name);
7890             return -1;
7891         }
7892         type->tp_weaklistoffset = MANAGED_WEAKREF_OFFSET;
7893     }
7894     return 0;
7895 }
7896 
7897 static int
type_ready_mro(PyTypeObject * type,int initial)7898 type_ready_mro(PyTypeObject *type, int initial)
7899 {
7900     ASSERT_TYPE_LOCK_HELD();
7901 
7902     if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) {
7903         if (!initial) {
7904             assert(lookup_tp_mro(type) != NULL);
7905             return 0;
7906         }
7907         assert(lookup_tp_mro(type) == NULL);
7908     }
7909 
7910     /* Calculate method resolution order */
7911     if (mro_internal_unlocked(type, initial, NULL) < 0) {
7912         return -1;
7913     }
7914     PyObject *mro = lookup_tp_mro(type);
7915     assert(mro != NULL);
7916     assert(PyTuple_Check(mro));
7917 
7918     /* All bases of statically allocated type should be statically allocated,
7919        and static builtin types must have static builtin bases. */
7920     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
7921         assert(type->tp_flags & Py_TPFLAGS_IMMUTABLETYPE);
7922         Py_ssize_t n = PyTuple_GET_SIZE(mro);
7923         for (Py_ssize_t i = 0; i < n; i++) {
7924             PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(mro, i));
7925             if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {
7926                 PyErr_Format(PyExc_TypeError,
7927                              "type '%.100s' is not dynamically allocated but "
7928                              "its base type '%.100s' is dynamically allocated",
7929                              type->tp_name, base->tp_name);
7930                 return -1;
7931             }
7932             assert(!(type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) ||
7933                    (base->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN));
7934         }
7935     }
7936     return 0;
7937 }
7938 
7939 
7940 // For static types, inherit tp_as_xxx structures from the base class
7941 // if it's NULL.
7942 //
7943 // For heap types, tp_as_xxx structures are not NULL: they are set to the
7944 // PyHeapTypeObject.as_xxx fields by type_new_alloc().
7945 static void
type_ready_inherit_as_structs(PyTypeObject * type,PyTypeObject * base)7946 type_ready_inherit_as_structs(PyTypeObject *type, PyTypeObject *base)
7947 {
7948     if (type->tp_as_async == NULL) {
7949         type->tp_as_async = base->tp_as_async;
7950     }
7951     if (type->tp_as_number == NULL) {
7952         type->tp_as_number = base->tp_as_number;
7953     }
7954     if (type->tp_as_sequence == NULL) {
7955         type->tp_as_sequence = base->tp_as_sequence;
7956     }
7957     if (type->tp_as_mapping == NULL) {
7958         type->tp_as_mapping = base->tp_as_mapping;
7959     }
7960     if (type->tp_as_buffer == NULL) {
7961         type->tp_as_buffer = base->tp_as_buffer;
7962     }
7963 }
7964 
7965 static void
inherit_patma_flags(PyTypeObject * type,PyTypeObject * base)7966 inherit_patma_flags(PyTypeObject *type, PyTypeObject *base) {
7967     if ((type->tp_flags & COLLECTION_FLAGS) == 0) {
7968         type->tp_flags |= base->tp_flags & COLLECTION_FLAGS;
7969     }
7970 }
7971 
7972 static int
type_ready_inherit(PyTypeObject * type)7973 type_ready_inherit(PyTypeObject *type)
7974 {
7975     ASSERT_TYPE_LOCK_HELD();
7976 
7977     /* Inherit special flags from dominant base */
7978     PyTypeObject *base = type->tp_base;
7979     if (base != NULL) {
7980         inherit_special(type, base);
7981     }
7982 
7983     // Inherit slots
7984     PyObject *mro = lookup_tp_mro(type);
7985     Py_ssize_t n = PyTuple_GET_SIZE(mro);
7986     for (Py_ssize_t i = 1; i < n; i++) {
7987         PyObject *b = PyTuple_GET_ITEM(mro, i);
7988         if (PyType_Check(b)) {
7989             if (inherit_slots(type, (PyTypeObject *)b) < 0) {
7990                 return -1;
7991             }
7992             inherit_patma_flags(type, (PyTypeObject *)b);
7993         }
7994     }
7995 
7996     if (base != NULL) {
7997         type_ready_inherit_as_structs(type, base);
7998     }
7999 
8000     /* Sanity check for tp_free. */
8001     if (_PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
8002         (type->tp_free == NULL || type->tp_free == PyObject_Del))
8003     {
8004         /* This base class needs to call tp_free, but doesn't have
8005          * one, or its tp_free is for non-gc'ed objects.
8006          */
8007         PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
8008                      "gc and is a base type but has inappropriate "
8009                      "tp_free slot",
8010                      type->tp_name);
8011         return -1;
8012     }
8013 
8014     return 0;
8015 }
8016 
8017 
8018 /* Hack for tp_hash and __hash__.
8019    If after all that, tp_hash is still NULL, and __hash__ is not in
8020    tp_dict, set tp_hash to PyObject_HashNotImplemented and
8021    tp_dict['__hash__'] equal to None.
8022    This signals that __hash__ is not inherited. */
8023 static int
type_ready_set_hash(PyTypeObject * type)8024 type_ready_set_hash(PyTypeObject *type)
8025 {
8026     if (type->tp_hash != NULL) {
8027         return 0;
8028     }
8029 
8030     PyObject *dict = lookup_tp_dict(type);
8031     int r = PyDict_Contains(dict, &_Py_ID(__hash__));
8032     if (r < 0) {
8033         return -1;
8034     }
8035     if (r > 0) {
8036         return 0;
8037     }
8038 
8039     if (PyDict_SetItem(dict, &_Py_ID(__hash__), Py_None) < 0) {
8040         return -1;
8041     }
8042     type->tp_hash = PyObject_HashNotImplemented;
8043     return 0;
8044 }
8045 
8046 
8047 /* Link into each base class's list of subclasses */
8048 static int
type_ready_add_subclasses(PyTypeObject * type)8049 type_ready_add_subclasses(PyTypeObject *type)
8050 {
8051     PyObject *bases = lookup_tp_bases(type);
8052     Py_ssize_t nbase = PyTuple_GET_SIZE(bases);
8053     for (Py_ssize_t i = 0; i < nbase; i++) {
8054         PyObject *b = PyTuple_GET_ITEM(bases, i);
8055         if (PyType_Check(b) && add_subclass((PyTypeObject *)b, type) < 0) {
8056             return -1;
8057         }
8058     }
8059     return 0;
8060 }
8061 
8062 
8063 // Set tp_new and the "__new__" key in the type dictionary.
8064 // Use the Py_TPFLAGS_DISALLOW_INSTANTIATION flag.
8065 static int
type_ready_set_new(PyTypeObject * type,int initial)8066 type_ready_set_new(PyTypeObject *type, int initial)
8067 {
8068     PyTypeObject *base = type->tp_base;
8069     /* The condition below could use some explanation.
8070 
8071        It appears that tp_new is not inherited for static types whose base
8072        class is 'object'; this seems to be a precaution so that old extension
8073        types don't suddenly become callable (object.__new__ wouldn't insure the
8074        invariants that the extension type's own factory function ensures).
8075 
8076        Heap types, of course, are under our control, so they do inherit tp_new;
8077        static extension types that specify some other built-in type as the
8078        default also inherit object.__new__. */
8079     if (type->tp_new == NULL
8080         && base == &PyBaseObject_Type
8081         && !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
8082     {
8083         type->tp_flags |= Py_TPFLAGS_DISALLOW_INSTANTIATION;
8084     }
8085 
8086     if (!(type->tp_flags & Py_TPFLAGS_DISALLOW_INSTANTIATION)) {
8087         if (type->tp_new != NULL) {
8088             if (initial || base == NULL || type->tp_new != base->tp_new) {
8089                 // If "__new__" key does not exists in the type dictionary,
8090                 // set it to tp_new_wrapper().
8091                 if (add_tp_new_wrapper(type) < 0) {
8092                     return -1;
8093                 }
8094             }
8095         }
8096         else {
8097             // tp_new is NULL: inherit tp_new from base
8098             type->tp_new = base->tp_new;
8099         }
8100     }
8101     else {
8102         // Py_TPFLAGS_DISALLOW_INSTANTIATION sets tp_new to NULL
8103         type->tp_new = NULL;
8104     }
8105     return 0;
8106 }
8107 
8108 static int
type_ready_managed_dict(PyTypeObject * type)8109 type_ready_managed_dict(PyTypeObject *type)
8110 {
8111     if (!(type->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
8112         return 0;
8113     }
8114     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
8115         PyErr_Format(PyExc_SystemError,
8116                      "type %s has the Py_TPFLAGS_MANAGED_DICT flag "
8117                      "but not Py_TPFLAGS_HEAPTYPE flag",
8118                      type->tp_name);
8119         return -1;
8120     }
8121     PyHeapTypeObject* et = (PyHeapTypeObject*)type;
8122     if (et->ht_cached_keys == NULL) {
8123         et->ht_cached_keys = _PyDict_NewKeysForClass();
8124         if (et->ht_cached_keys == NULL) {
8125             PyErr_NoMemory();
8126             return -1;
8127         }
8128     }
8129     if (type->tp_itemsize == 0 && type->tp_basicsize == sizeof(PyObject)) {
8130         type->tp_flags |= Py_TPFLAGS_INLINE_VALUES;
8131     }
8132     return 0;
8133 }
8134 
8135 static int
type_ready_post_checks(PyTypeObject * type)8136 type_ready_post_checks(PyTypeObject *type)
8137 {
8138     // bpo-44263: tp_traverse is required if Py_TPFLAGS_HAVE_GC is set.
8139     // Note: tp_clear is optional.
8140     if (type->tp_flags & Py_TPFLAGS_HAVE_GC
8141         && type->tp_traverse == NULL)
8142     {
8143         PyErr_Format(PyExc_SystemError,
8144                      "type %s has the Py_TPFLAGS_HAVE_GC flag "
8145                      "but has no traverse function",
8146                      type->tp_name);
8147         return -1;
8148     }
8149     if (type->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
8150         if (type->tp_dictoffset != -1) {
8151             PyErr_Format(PyExc_SystemError,
8152                         "type %s has the Py_TPFLAGS_MANAGED_DICT flag "
8153                         "but tp_dictoffset is set to incompatible value",
8154                         type->tp_name);
8155             return -1;
8156         }
8157     }
8158     else if (type->tp_dictoffset < (Py_ssize_t)sizeof(PyObject)) {
8159         if (type->tp_dictoffset + type->tp_basicsize <= 0) {
8160             PyErr_Format(PyExc_SystemError,
8161                          "type %s has a tp_dictoffset that is too small",
8162                          type->tp_name);
8163         }
8164     }
8165     return 0;
8166 }
8167 
8168 
8169 static int
type_ready(PyTypeObject * type,int initial)8170 type_ready(PyTypeObject *type, int initial)
8171 {
8172     ASSERT_TYPE_LOCK_HELD();
8173 
8174     _PyObject_ASSERT((PyObject *)type, !is_readying(type));
8175     start_readying(type);
8176 
8177     if (type_ready_pre_checks(type) < 0) {
8178         goto error;
8179     }
8180 
8181 #ifdef Py_TRACE_REFS
8182     /* PyType_Ready is the closest thing we have to a choke point
8183      * for type objects, so is the best place I can think of to try
8184      * to get type objects into the doubly-linked list of all objects.
8185      * Still, not all type objects go through PyType_Ready.
8186      */
8187     _Py_AddToAllObjects((PyObject *)type);
8188 #endif
8189 
8190     /* Initialize tp_dict: _PyType_IsReady() tests if tp_dict != NULL */
8191     if (type_ready_set_dict(type) < 0) {
8192         goto error;
8193     }
8194     if (type_ready_set_base(type) < 0) {
8195         goto error;
8196     }
8197     if (type_ready_set_type(type) < 0) {
8198         goto error;
8199     }
8200     if (type_ready_set_bases(type, initial) < 0) {
8201         goto error;
8202     }
8203     if (type_ready_mro(type, initial) < 0) {
8204         goto error;
8205     }
8206     if (type_ready_set_new(type, initial) < 0) {
8207         goto error;
8208     }
8209     if (type_ready_fill_dict(type) < 0) {
8210         goto error;
8211     }
8212     if (initial) {
8213         if (type_ready_inherit(type) < 0) {
8214             goto error;
8215         }
8216         if (type_ready_preheader(type) < 0) {
8217             goto error;
8218         }
8219     }
8220     if (type_ready_set_hash(type) < 0) {
8221         goto error;
8222     }
8223     if (type_ready_add_subclasses(type) < 0) {
8224         goto error;
8225     }
8226     if (initial) {
8227         if (type_ready_managed_dict(type) < 0) {
8228             goto error;
8229         }
8230         if (type_ready_post_checks(type) < 0) {
8231             goto error;
8232         }
8233     }
8234 
8235     /* All done -- set the ready flag */
8236     type->tp_flags = type->tp_flags | Py_TPFLAGS_READY;
8237     stop_readying(type);
8238 
8239     assert(_PyType_CheckConsistency(type));
8240     return 0;
8241 
8242 error:
8243     stop_readying(type);
8244     return -1;
8245 }
8246 
8247 int
PyType_Ready(PyTypeObject * type)8248 PyType_Ready(PyTypeObject *type)
8249 {
8250     if (type->tp_flags & Py_TPFLAGS_READY) {
8251         assert(_PyType_CheckConsistency(type));
8252         return 0;
8253     }
8254     assert(!(type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN));
8255 
8256     /* Historically, all static types were immutable. See bpo-43908 */
8257     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
8258         type->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE;
8259         /* Static types must be immortal */
8260         _Py_SetImmortalUntracked((PyObject *)type);
8261     }
8262 
8263     int res;
8264     BEGIN_TYPE_LOCK();
8265     if (!(type->tp_flags & Py_TPFLAGS_READY)) {
8266         res = type_ready(type, 1);
8267     } else {
8268         res = 0;
8269         assert(_PyType_CheckConsistency(type));
8270     }
8271     END_TYPE_LOCK();
8272     return res;
8273 }
8274 
8275 
8276 static int
init_static_type(PyInterpreterState * interp,PyTypeObject * self,int isbuiltin,int initial)8277 init_static_type(PyInterpreterState *interp, PyTypeObject *self,
8278                  int isbuiltin, int initial)
8279 {
8280     assert(_Py_IsImmortal((PyObject *)self));
8281     assert(!(self->tp_flags & Py_TPFLAGS_HEAPTYPE));
8282     assert(!(self->tp_flags & Py_TPFLAGS_MANAGED_DICT));
8283     assert(!(self->tp_flags & Py_TPFLAGS_MANAGED_WEAKREF));
8284 
8285     if ((self->tp_flags & Py_TPFLAGS_READY) == 0) {
8286         assert(initial);
8287 
8288         self->tp_flags |= _Py_TPFLAGS_STATIC_BUILTIN;
8289         self->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE;
8290 
8291         assert(NEXT_GLOBAL_VERSION_TAG <= _Py_MAX_GLOBAL_TYPE_VERSION_TAG);
8292         self->tp_version_tag = NEXT_GLOBAL_VERSION_TAG++;
8293     }
8294     else {
8295         assert(!initial);
8296         assert(self->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN);
8297         assert(self->tp_version_tag != 0);
8298     }
8299 
8300     managed_static_type_state_init(interp, self, isbuiltin, initial);
8301 
8302     int res;
8303     BEGIN_TYPE_LOCK();
8304     res = type_ready(self, initial);
8305     END_TYPE_LOCK();
8306     if (res < 0) {
8307         _PyStaticType_ClearWeakRefs(interp, self);
8308         managed_static_type_state_clear(interp, self, isbuiltin, initial);
8309     }
8310     return res;
8311 }
8312 
8313 int
_PyStaticType_InitForExtension(PyInterpreterState * interp,PyTypeObject * self)8314 _PyStaticType_InitForExtension(PyInterpreterState *interp, PyTypeObject *self)
8315 {
8316     return init_static_type(interp, self, 0, ((self->tp_flags & Py_TPFLAGS_READY) == 0));
8317 }
8318 
8319 int
_PyStaticType_InitBuiltin(PyInterpreterState * interp,PyTypeObject * self)8320 _PyStaticType_InitBuiltin(PyInterpreterState *interp, PyTypeObject *self)
8321 {
8322     return init_static_type(interp, self, 1, _Py_IsMainInterpreter(interp));
8323 }
8324 
8325 
8326 static int
add_subclass(PyTypeObject * base,PyTypeObject * type)8327 add_subclass(PyTypeObject *base, PyTypeObject *type)
8328 {
8329     PyObject *key = PyLong_FromVoidPtr((void *) type);
8330     if (key == NULL)
8331         return -1;
8332 
8333     PyObject *ref = PyWeakref_NewRef((PyObject *)type, NULL);
8334     if (ref == NULL) {
8335         Py_DECREF(key);
8336         return -1;
8337     }
8338 
8339     // Only get tp_subclasses after creating the key and value.
8340     // PyWeakref_NewRef() can trigger a garbage collection which can execute
8341     // arbitrary Python code and so modify base->tp_subclasses.
8342     PyObject *subclasses = lookup_tp_subclasses(base);
8343     if (subclasses == NULL) {
8344         subclasses = init_tp_subclasses(base);
8345         if (subclasses == NULL) {
8346             Py_DECREF(key);
8347             Py_DECREF(ref);
8348             return -1;
8349         }
8350     }
8351     assert(PyDict_CheckExact(subclasses));
8352 
8353     int result = PyDict_SetItem(subclasses, key, ref);
8354     Py_DECREF(ref);
8355     Py_DECREF(key);
8356     return result;
8357 }
8358 
8359 static int
add_all_subclasses(PyTypeObject * type,PyObject * bases)8360 add_all_subclasses(PyTypeObject *type, PyObject *bases)
8361 {
8362     Py_ssize_t n = PyTuple_GET_SIZE(bases);
8363     int res = 0;
8364     for (Py_ssize_t i = 0; i < n; i++) {
8365         PyObject *obj = PyTuple_GET_ITEM(bases, i);
8366         // bases tuple must only contain types
8367         PyTypeObject *base = _PyType_CAST(obj);
8368         if (add_subclass(base, type) < 0) {
8369             res = -1;
8370         }
8371     }
8372     return res;
8373 }
8374 
8375 static PyObject *
get_subclasses_key(PyTypeObject * type,PyTypeObject * base)8376 get_subclasses_key(PyTypeObject *type, PyTypeObject *base)
8377 {
8378     PyObject *key = PyLong_FromVoidPtr((void *) type);
8379     if (key != NULL) {
8380         return key;
8381     }
8382     PyErr_Clear();
8383 
8384     /* This basically means we're out of memory.
8385        We fall back to manually traversing the values. */
8386     Py_ssize_t i = 0;
8387     PyObject *ref;  // borrowed ref
8388     PyObject *subclasses = lookup_tp_subclasses(base);
8389     if (subclasses != NULL) {
8390         while (PyDict_Next(subclasses, &i, &key, &ref)) {
8391             PyTypeObject *subclass = type_from_ref(ref);
8392             if (subclass == NULL) {
8393                 continue;
8394             }
8395             if (subclass == type) {
8396                 Py_DECREF(subclass);
8397                 return Py_NewRef(key);
8398             }
8399             Py_DECREF(subclass);
8400         }
8401     }
8402     /* It wasn't found. */
8403     return NULL;
8404 }
8405 
8406 static void
remove_subclass(PyTypeObject * base,PyTypeObject * type)8407 remove_subclass(PyTypeObject *base, PyTypeObject *type)
8408 {
8409     PyObject *subclasses = lookup_tp_subclasses(base);  // borrowed ref
8410     if (subclasses == NULL) {
8411         return;
8412     }
8413     assert(PyDict_CheckExact(subclasses));
8414 
8415     PyObject *key = get_subclasses_key(type, base);
8416     if (key != NULL && PyDict_DelItem(subclasses, key)) {
8417         /* This can happen if the type initialization errored out before
8418            the base subclasses were updated (e.g. a non-str __qualname__
8419            was passed in the type dict). */
8420         PyErr_Clear();
8421     }
8422     Py_XDECREF(key);
8423 
8424     if (PyDict_Size(subclasses) == 0) {
8425         clear_tp_subclasses(base);
8426     }
8427 }
8428 
8429 static void
remove_all_subclasses(PyTypeObject * type,PyObject * bases)8430 remove_all_subclasses(PyTypeObject *type, PyObject *bases)
8431 {
8432     assert(bases != NULL);
8433     // remove_subclass() can clear the current exception
8434     assert(!PyErr_Occurred());
8435 
8436     for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(bases); i++) {
8437         PyObject *base = PyTuple_GET_ITEM(bases, i);
8438         if (PyType_Check(base)) {
8439             remove_subclass((PyTypeObject*) base, type);
8440         }
8441     }
8442     assert(!PyErr_Occurred());
8443 }
8444 
8445 static int
check_num_args(PyObject * ob,int n)8446 check_num_args(PyObject *ob, int n)
8447 {
8448     if (!PyTuple_CheckExact(ob)) {
8449         PyErr_SetString(PyExc_SystemError,
8450             "PyArg_UnpackTuple() argument list is not a tuple");
8451         return 0;
8452     }
8453     if (n == PyTuple_GET_SIZE(ob))
8454         return 1;
8455     PyErr_Format(
8456         PyExc_TypeError,
8457         "expected %d argument%s, got %zd", n, n == 1 ? "" : "s", PyTuple_GET_SIZE(ob));
8458     return 0;
8459 }
8460 
8461 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
8462 
8463 /* There's a wrapper *function* for each distinct function typedef used
8464    for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
8465    wrapper *table* for each distinct operation (e.g. __len__, __add__).
8466    Most tables have only one entry; the tables for binary operators have two
8467    entries, one regular and one with reversed arguments. */
8468 
8469 static PyObject *
wrap_lenfunc(PyObject * self,PyObject * args,void * wrapped)8470 wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
8471 {
8472     lenfunc func = (lenfunc)wrapped;
8473     Py_ssize_t res;
8474 
8475     if (!check_num_args(args, 0))
8476         return NULL;
8477     res = (*func)(self);
8478     if (res == -1 && PyErr_Occurred())
8479         return NULL;
8480     return PyLong_FromSsize_t(res);
8481 }
8482 
8483 static PyObject *
wrap_inquirypred(PyObject * self,PyObject * args,void * wrapped)8484 wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
8485 {
8486     inquiry func = (inquiry)wrapped;
8487     int res;
8488 
8489     if (!check_num_args(args, 0))
8490         return NULL;
8491     res = (*func)(self);
8492     if (res == -1 && PyErr_Occurred())
8493         return NULL;
8494     return PyBool_FromLong((long)res);
8495 }
8496 
8497 static PyObject *
wrap_binaryfunc(PyObject * self,PyObject * args,void * wrapped)8498 wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
8499 {
8500     binaryfunc func = (binaryfunc)wrapped;
8501     PyObject *other;
8502 
8503     if (!check_num_args(args, 1))
8504         return NULL;
8505     other = PyTuple_GET_ITEM(args, 0);
8506     return (*func)(self, other);
8507 }
8508 
8509 static PyObject *
wrap_binaryfunc_l(PyObject * self,PyObject * args,void * wrapped)8510 wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
8511 {
8512     binaryfunc func = (binaryfunc)wrapped;
8513     PyObject *other;
8514 
8515     if (!check_num_args(args, 1))
8516         return NULL;
8517     other = PyTuple_GET_ITEM(args, 0);
8518     return (*func)(self, other);
8519 }
8520 
8521 static PyObject *
wrap_binaryfunc_r(PyObject * self,PyObject * args,void * wrapped)8522 wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
8523 {
8524     binaryfunc func = (binaryfunc)wrapped;
8525     PyObject *other;
8526 
8527     if (!check_num_args(args, 1))
8528         return NULL;
8529     other = PyTuple_GET_ITEM(args, 0);
8530     return (*func)(other, self);
8531 }
8532 
8533 static PyObject *
wrap_ternaryfunc(PyObject * self,PyObject * args,void * wrapped)8534 wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
8535 {
8536     ternaryfunc func = (ternaryfunc)wrapped;
8537     PyObject *other;
8538     PyObject *third = Py_None;
8539 
8540     /* Note: This wrapper only works for __pow__() */
8541 
8542     if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
8543         return NULL;
8544     return (*func)(self, other, third);
8545 }
8546 
8547 static PyObject *
wrap_ternaryfunc_r(PyObject * self,PyObject * args,void * wrapped)8548 wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
8549 {
8550     ternaryfunc func = (ternaryfunc)wrapped;
8551     PyObject *other;
8552     PyObject *third = Py_None;
8553 
8554     /* Note: This wrapper only works for __pow__() */
8555 
8556     if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
8557         return NULL;
8558     return (*func)(other, self, third);
8559 }
8560 
8561 static PyObject *
wrap_unaryfunc(PyObject * self,PyObject * args,void * wrapped)8562 wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
8563 {
8564     unaryfunc func = (unaryfunc)wrapped;
8565 
8566     if (!check_num_args(args, 0))
8567         return NULL;
8568     return (*func)(self);
8569 }
8570 
8571 static PyObject *
wrap_indexargfunc(PyObject * self,PyObject * args,void * wrapped)8572 wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
8573 {
8574     ssizeargfunc func = (ssizeargfunc)wrapped;
8575     PyObject* o;
8576     Py_ssize_t i;
8577 
8578     if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
8579         return NULL;
8580     i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
8581     if (i == -1 && PyErr_Occurred())
8582         return NULL;
8583     return (*func)(self, i);
8584 }
8585 
8586 static Py_ssize_t
getindex(PyObject * self,PyObject * arg)8587 getindex(PyObject *self, PyObject *arg)
8588 {
8589     Py_ssize_t i;
8590 
8591     i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
8592     if (i == -1 && PyErr_Occurred())
8593         return -1;
8594     if (i < 0) {
8595         PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
8596         if (sq && sq->sq_length) {
8597             Py_ssize_t n = (*sq->sq_length)(self);
8598             if (n < 0) {
8599                 assert(PyErr_Occurred());
8600                 return -1;
8601             }
8602             i += n;
8603         }
8604     }
8605     return i;
8606 }
8607 
8608 static PyObject *
wrap_sq_item(PyObject * self,PyObject * args,void * wrapped)8609 wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
8610 {
8611     ssizeargfunc func = (ssizeargfunc)wrapped;
8612     PyObject *arg;
8613     Py_ssize_t i;
8614 
8615     if (PyTuple_GET_SIZE(args) == 1) {
8616         arg = PyTuple_GET_ITEM(args, 0);
8617         i = getindex(self, arg);
8618         if (i == -1 && PyErr_Occurred())
8619             return NULL;
8620         return (*func)(self, i);
8621     }
8622     check_num_args(args, 1);
8623     assert(PyErr_Occurred());
8624     return NULL;
8625 }
8626 
8627 static PyObject *
wrap_sq_setitem(PyObject * self,PyObject * args,void * wrapped)8628 wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
8629 {
8630     ssizeobjargproc func = (ssizeobjargproc)wrapped;
8631     Py_ssize_t i;
8632     int res;
8633     PyObject *arg, *value;
8634 
8635     if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
8636         return NULL;
8637     i = getindex(self, arg);
8638     if (i == -1 && PyErr_Occurred())
8639         return NULL;
8640     res = (*func)(self, i, value);
8641     if (res == -1 && PyErr_Occurred())
8642         return NULL;
8643     Py_RETURN_NONE;
8644 }
8645 
8646 static PyObject *
wrap_sq_delitem(PyObject * self,PyObject * args,void * wrapped)8647 wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
8648 {
8649     ssizeobjargproc func = (ssizeobjargproc)wrapped;
8650     Py_ssize_t i;
8651     int res;
8652     PyObject *arg;
8653 
8654     if (!check_num_args(args, 1))
8655         return NULL;
8656     arg = PyTuple_GET_ITEM(args, 0);
8657     i = getindex(self, arg);
8658     if (i == -1 && PyErr_Occurred())
8659         return NULL;
8660     res = (*func)(self, i, NULL);
8661     if (res == -1 && PyErr_Occurred())
8662         return NULL;
8663     Py_RETURN_NONE;
8664 }
8665 
8666 /* XXX objobjproc is a misnomer; should be objargpred */
8667 static PyObject *
wrap_objobjproc(PyObject * self,PyObject * args,void * wrapped)8668 wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
8669 {
8670     objobjproc func = (objobjproc)wrapped;
8671     int res;
8672     PyObject *value;
8673 
8674     if (!check_num_args(args, 1))
8675         return NULL;
8676     value = PyTuple_GET_ITEM(args, 0);
8677     res = (*func)(self, value);
8678     if (res == -1 && PyErr_Occurred())
8679         return NULL;
8680     else
8681         return PyBool_FromLong(res);
8682 }
8683 
8684 static PyObject *
wrap_objobjargproc(PyObject * self,PyObject * args,void * wrapped)8685 wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
8686 {
8687     objobjargproc func = (objobjargproc)wrapped;
8688     int res;
8689     PyObject *key, *value;
8690 
8691     if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
8692         return NULL;
8693     res = (*func)(self, key, value);
8694     if (res == -1 && PyErr_Occurred())
8695         return NULL;
8696     Py_RETURN_NONE;
8697 }
8698 
8699 static PyObject *
wrap_delitem(PyObject * self,PyObject * args,void * wrapped)8700 wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
8701 {
8702     objobjargproc func = (objobjargproc)wrapped;
8703     int res;
8704     PyObject *key;
8705 
8706     if (!check_num_args(args, 1))
8707         return NULL;
8708     key = PyTuple_GET_ITEM(args, 0);
8709     res = (*func)(self, key, NULL);
8710     if (res == -1 && PyErr_Occurred())
8711         return NULL;
8712     Py_RETURN_NONE;
8713 }
8714 
8715 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
8716    This is called the Carlo Verre hack after its discoverer.  See
8717    https://mail.python.org/pipermail/python-dev/2003-April/034535.html
8718    */
8719 static int
hackcheck_unlocked(PyObject * self,setattrofunc func,const char * what)8720 hackcheck_unlocked(PyObject *self, setattrofunc func, const char *what)
8721 {
8722     PyTypeObject *type = Py_TYPE(self);
8723 
8724     ASSERT_TYPE_LOCK_HELD();
8725 
8726     PyObject *mro = lookup_tp_mro(type);
8727     if (!mro) {
8728         /* Probably ok not to check the call in this case. */
8729         return 1;
8730     }
8731     assert(PyTuple_Check(mro));
8732 
8733     /* Find the (base) type that defined the type's slot function. */
8734     PyTypeObject *defining_type = type;
8735     Py_ssize_t i;
8736     for (i = PyTuple_GET_SIZE(mro) - 1; i >= 0; i--) {
8737         PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(mro, i));
8738         if (base->tp_setattro == slot_tp_setattro) {
8739             /* Ignore Python classes:
8740                they never define their own C-level setattro. */
8741         }
8742         else if (base->tp_setattro == type->tp_setattro) {
8743             defining_type = base;
8744             break;
8745         }
8746     }
8747 
8748     /* Reject calls that jump over intermediate C-level overrides. */
8749     for (PyTypeObject *base = defining_type; base; base = base->tp_base) {
8750         if (base->tp_setattro == func) {
8751             /* 'func' is the right slot function to call. */
8752             break;
8753         }
8754         else if (base->tp_setattro != slot_tp_setattro) {
8755             /* 'base' is not a Python class and overrides 'func'.
8756                Its tp_setattro should be called instead. */
8757             PyErr_Format(PyExc_TypeError,
8758                          "can't apply this %s to %s object",
8759                          what,
8760                          type->tp_name);
8761             return 0;
8762         }
8763     }
8764     return 1;
8765 }
8766 
8767 static int
hackcheck(PyObject * self,setattrofunc func,const char * what)8768 hackcheck(PyObject *self, setattrofunc func, const char *what)
8769 {
8770     if (!PyType_Check(self)) {
8771         return 1;
8772     }
8773 
8774     int res;
8775     BEGIN_TYPE_LOCK();
8776     res = hackcheck_unlocked(self, func, what);
8777     END_TYPE_LOCK();
8778     return res;
8779 }
8780 
8781 static PyObject *
wrap_setattr(PyObject * self,PyObject * args,void * wrapped)8782 wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
8783 {
8784     setattrofunc func = (setattrofunc)wrapped;
8785     int res;
8786     PyObject *name, *value;
8787 
8788     if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
8789         return NULL;
8790     if (!hackcheck(self, func, "__setattr__"))
8791         return NULL;
8792     res = (*func)(self, name, value);
8793     if (res < 0)
8794         return NULL;
8795     Py_RETURN_NONE;
8796 }
8797 
8798 static PyObject *
wrap_delattr(PyObject * self,PyObject * args,void * wrapped)8799 wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
8800 {
8801     setattrofunc func = (setattrofunc)wrapped;
8802     int res;
8803     PyObject *name;
8804 
8805     if (!check_num_args(args, 1))
8806         return NULL;
8807     name = PyTuple_GET_ITEM(args, 0);
8808     if (!hackcheck(self, func, "__delattr__"))
8809         return NULL;
8810     res = (*func)(self, name, NULL);
8811     if (res < 0)
8812         return NULL;
8813     Py_RETURN_NONE;
8814 }
8815 
8816 static PyObject *
wrap_hashfunc(PyObject * self,PyObject * args,void * wrapped)8817 wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
8818 {
8819     hashfunc func = (hashfunc)wrapped;
8820     Py_hash_t res;
8821 
8822     if (!check_num_args(args, 0))
8823         return NULL;
8824     res = (*func)(self);
8825     if (res == -1 && PyErr_Occurred())
8826         return NULL;
8827     return PyLong_FromSsize_t(res);
8828 }
8829 
8830 static PyObject *
wrap_call(PyObject * self,PyObject * args,void * wrapped,PyObject * kwds)8831 wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
8832 {
8833     ternaryfunc func = (ternaryfunc)wrapped;
8834 
8835     return (*func)(self, args, kwds);
8836 }
8837 
8838 static PyObject *
wrap_del(PyObject * self,PyObject * args,void * wrapped)8839 wrap_del(PyObject *self, PyObject *args, void *wrapped)
8840 {
8841     destructor func = (destructor)wrapped;
8842 
8843     if (!check_num_args(args, 0))
8844         return NULL;
8845 
8846     (*func)(self);
8847     Py_RETURN_NONE;
8848 }
8849 
8850 static PyObject *
wrap_richcmpfunc(PyObject * self,PyObject * args,void * wrapped,int op)8851 wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
8852 {
8853     richcmpfunc func = (richcmpfunc)wrapped;
8854     PyObject *other;
8855 
8856     if (!check_num_args(args, 1))
8857         return NULL;
8858     other = PyTuple_GET_ITEM(args, 0);
8859     return (*func)(self, other, op);
8860 }
8861 
8862 #undef RICHCMP_WRAPPER
8863 #define RICHCMP_WRAPPER(NAME, OP) \
8864 static PyObject * \
8865 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
8866 { \
8867     return wrap_richcmpfunc(self, args, wrapped, OP); \
8868 }
8869 
RICHCMP_WRAPPER(lt,Py_LT)8870 RICHCMP_WRAPPER(lt, Py_LT)
8871 RICHCMP_WRAPPER(le, Py_LE)
8872 RICHCMP_WRAPPER(eq, Py_EQ)
8873 RICHCMP_WRAPPER(ne, Py_NE)
8874 RICHCMP_WRAPPER(gt, Py_GT)
8875 RICHCMP_WRAPPER(ge, Py_GE)
8876 
8877 static PyObject *
8878 wrap_next(PyObject *self, PyObject *args, void *wrapped)
8879 {
8880     unaryfunc func = (unaryfunc)wrapped;
8881     PyObject *res;
8882 
8883     if (!check_num_args(args, 0))
8884         return NULL;
8885     res = (*func)(self);
8886     if (res == NULL && !PyErr_Occurred())
8887         PyErr_SetNone(PyExc_StopIteration);
8888     return res;
8889 }
8890 
8891 static PyObject *
wrap_descr_get(PyObject * self,PyObject * args,void * wrapped)8892 wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
8893 {
8894     descrgetfunc func = (descrgetfunc)wrapped;
8895     PyObject *obj;
8896     PyObject *type = NULL;
8897 
8898     if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
8899         return NULL;
8900     if (obj == Py_None)
8901         obj = NULL;
8902     if (type == Py_None)
8903         type = NULL;
8904     if (type == NULL && obj == NULL) {
8905         PyErr_SetString(PyExc_TypeError,
8906                         "__get__(None, None) is invalid");
8907         return NULL;
8908     }
8909     return (*func)(self, obj, type);
8910 }
8911 
8912 static PyObject *
wrap_descr_set(PyObject * self,PyObject * args,void * wrapped)8913 wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
8914 {
8915     descrsetfunc func = (descrsetfunc)wrapped;
8916     PyObject *obj, *value;
8917     int ret;
8918 
8919     if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
8920         return NULL;
8921     ret = (*func)(self, obj, value);
8922     if (ret < 0)
8923         return NULL;
8924     Py_RETURN_NONE;
8925 }
8926 
8927 static PyObject *
wrap_descr_delete(PyObject * self,PyObject * args,void * wrapped)8928 wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
8929 {
8930     descrsetfunc func = (descrsetfunc)wrapped;
8931     PyObject *obj;
8932     int ret;
8933 
8934     if (!check_num_args(args, 1))
8935         return NULL;
8936     obj = PyTuple_GET_ITEM(args, 0);
8937     ret = (*func)(self, obj, NULL);
8938     if (ret < 0)
8939         return NULL;
8940     Py_RETURN_NONE;
8941 }
8942 
8943 static PyObject *
wrap_buffer(PyObject * self,PyObject * args,void * wrapped)8944 wrap_buffer(PyObject *self, PyObject *args, void *wrapped)
8945 {
8946     PyObject *arg = NULL;
8947 
8948     if (!PyArg_UnpackTuple(args, "", 1, 1, &arg)) {
8949         return NULL;
8950     }
8951     Py_ssize_t flags = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
8952     if (flags == -1 && PyErr_Occurred()) {
8953         return NULL;
8954     }
8955     if (flags > INT_MAX || flags < INT_MIN) {
8956         PyErr_SetString(PyExc_OverflowError,
8957                         "buffer flags out of range");
8958         return NULL;
8959     }
8960 
8961     return _PyMemoryView_FromBufferProc(self, (int)flags,
8962                                         (getbufferproc)wrapped);
8963 }
8964 
8965 static PyObject *
wrap_releasebuffer(PyObject * self,PyObject * args,void * wrapped)8966 wrap_releasebuffer(PyObject *self, PyObject *args, void *wrapped)
8967 {
8968     PyObject *arg = NULL;
8969     if (!PyArg_UnpackTuple(args, "", 1, 1, &arg)) {
8970         return NULL;
8971     }
8972     if (!PyMemoryView_Check(arg)) {
8973         PyErr_SetString(PyExc_TypeError,
8974                         "expected a memoryview object");
8975         return NULL;
8976     }
8977     PyMemoryViewObject *mview = (PyMemoryViewObject *)arg;
8978     if (mview->view.obj == NULL) {
8979         // Already released, ignore
8980         Py_RETURN_NONE;
8981     }
8982     if (mview->view.obj != self) {
8983         PyErr_SetString(PyExc_ValueError,
8984                         "memoryview's buffer is not this object");
8985         return NULL;
8986     }
8987     if (mview->flags & _Py_MEMORYVIEW_RELEASED) {
8988         PyErr_SetString(PyExc_ValueError,
8989                         "memoryview's buffer has already been released");
8990         return NULL;
8991     }
8992     PyObject *res = PyObject_CallMethodNoArgs((PyObject *)mview, &_Py_ID(release));
8993     if (res == NULL) {
8994         return NULL;
8995     }
8996     Py_DECREF(res);
8997     Py_RETURN_NONE;
8998 }
8999 
9000 static PyObject *
wrap_init(PyObject * self,PyObject * args,void * wrapped,PyObject * kwds)9001 wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
9002 {
9003     initproc func = (initproc)wrapped;
9004 
9005     if (func(self, args, kwds) < 0)
9006         return NULL;
9007     Py_RETURN_NONE;
9008 }
9009 
9010 static PyObject *
tp_new_wrapper(PyObject * self,PyObject * args,PyObject * kwds)9011 tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
9012 {
9013     PyTypeObject *staticbase;
9014     PyObject *arg0, *res;
9015 
9016     if (self == NULL || !PyType_Check(self)) {
9017         PyErr_Format(PyExc_SystemError,
9018                      "__new__() called with non-type 'self'");
9019         return NULL;
9020     }
9021     PyTypeObject *type = (PyTypeObject *)self;
9022 
9023     if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
9024         PyErr_Format(PyExc_TypeError,
9025                      "%s.__new__(): not enough arguments",
9026                      type->tp_name);
9027         return NULL;
9028     }
9029     arg0 = PyTuple_GET_ITEM(args, 0);
9030     if (!PyType_Check(arg0)) {
9031         PyErr_Format(PyExc_TypeError,
9032                      "%s.__new__(X): X is not a type object (%s)",
9033                      type->tp_name,
9034                      Py_TYPE(arg0)->tp_name);
9035         return NULL;
9036     }
9037     PyTypeObject *subtype = (PyTypeObject *)arg0;
9038 
9039     if (!PyType_IsSubtype(subtype, type)) {
9040         PyErr_Format(PyExc_TypeError,
9041                      "%s.__new__(%s): %s is not a subtype of %s",
9042                      type->tp_name,
9043                      subtype->tp_name,
9044                      subtype->tp_name,
9045                      type->tp_name);
9046         return NULL;
9047     }
9048 
9049     /* Check that the use doesn't do something silly and unsafe like
9050        object.__new__(dict).  To do this, we check that the
9051        most derived base that's not a heap type is this type. */
9052     staticbase = subtype;
9053     while (staticbase && (staticbase->tp_new == slot_tp_new))
9054         staticbase = staticbase->tp_base;
9055     /* If staticbase is NULL now, it is a really weird type.
9056        In the spirit of backwards compatibility (?), just shut up. */
9057     if (staticbase && staticbase->tp_new != type->tp_new) {
9058         PyErr_Format(PyExc_TypeError,
9059                      "%s.__new__(%s) is not safe, use %s.__new__()",
9060                      type->tp_name,
9061                      subtype->tp_name,
9062                      staticbase->tp_name);
9063         return NULL;
9064     }
9065 
9066     args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
9067     if (args == NULL)
9068         return NULL;
9069     res = type->tp_new(subtype, args, kwds);
9070     Py_DECREF(args);
9071     return res;
9072 }
9073 
9074 static struct PyMethodDef tp_new_methoddef[] = {
9075     {"__new__", _PyCFunction_CAST(tp_new_wrapper), METH_VARARGS|METH_KEYWORDS,
9076      PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
9077                "Create and return a new object.  "
9078                "See help(type) for accurate signature.")},
9079     {0}
9080 };
9081 
9082 static int
add_tp_new_wrapper(PyTypeObject * type)9083 add_tp_new_wrapper(PyTypeObject *type)
9084 {
9085     PyObject *dict = lookup_tp_dict(type);
9086     int r = PyDict_Contains(dict, &_Py_ID(__new__));
9087     if (r > 0) {
9088         return 0;
9089     }
9090     if (r < 0) {
9091         return -1;
9092     }
9093 
9094     PyObject *func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
9095     if (func == NULL) {
9096         return -1;
9097     }
9098     r = PyDict_SetItem(dict, &_Py_ID(__new__), func);
9099     Py_DECREF(func);
9100     return r;
9101 }
9102 
9103 /* Slot wrappers that call the corresponding __foo__ slot.  See comments
9104    below at override_slots() for more explanation. */
9105 
9106 #define SLOT0(FUNCNAME, DUNDER) \
9107 static PyObject * \
9108 FUNCNAME(PyObject *self) \
9109 { \
9110     PyObject* stack[1] = {self}; \
9111     return vectorcall_method(&_Py_ID(DUNDER), stack, 1); \
9112 }
9113 
9114 #define SLOT1(FUNCNAME, DUNDER, ARG1TYPE) \
9115 static PyObject * \
9116 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
9117 { \
9118     PyObject* stack[2] = {self, arg1}; \
9119     return vectorcall_method(&_Py_ID(DUNDER), stack, 2); \
9120 }
9121 
9122 /* Boolean helper for SLOT1BINFULL().
9123    right.__class__ is a nontrivial subclass of left.__class__. */
9124 static int
method_is_overloaded(PyObject * left,PyObject * right,PyObject * name)9125 method_is_overloaded(PyObject *left, PyObject *right, PyObject *name)
9126 {
9127     PyObject *a, *b;
9128     int ok;
9129 
9130     if (PyObject_GetOptionalAttr((PyObject *)(Py_TYPE(right)), name, &b) < 0) {
9131         return -1;
9132     }
9133     if (b == NULL) {
9134         /* If right doesn't have it, it's not overloaded */
9135         return 0;
9136     }
9137 
9138     if (PyObject_GetOptionalAttr((PyObject *)(Py_TYPE(left)), name, &a) < 0) {
9139         Py_DECREF(b);
9140         return -1;
9141     }
9142     if (a == NULL) {
9143         Py_DECREF(b);
9144         /* If right has it but left doesn't, it's overloaded */
9145         return 1;
9146     }
9147 
9148     ok = PyObject_RichCompareBool(a, b, Py_NE);
9149     Py_DECREF(a);
9150     Py_DECREF(b);
9151     return ok;
9152 }
9153 
9154 
9155 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, DUNDER, RDUNDER) \
9156 static PyObject * \
9157 FUNCNAME(PyObject *self, PyObject *other) \
9158 { \
9159     PyObject* stack[2]; \
9160     PyThreadState *tstate = _PyThreadState_GET(); \
9161     int do_other = !Py_IS_TYPE(self, Py_TYPE(other)) && \
9162         Py_TYPE(other)->tp_as_number != NULL && \
9163         Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
9164     if (Py_TYPE(self)->tp_as_number != NULL && \
9165         Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
9166         PyObject *r; \
9167         if (do_other && PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { \
9168             int ok = method_is_overloaded(self, other, &_Py_ID(RDUNDER)); \
9169             if (ok < 0) { \
9170                 return NULL; \
9171             } \
9172             if (ok) { \
9173                 stack[0] = other; \
9174                 stack[1] = self; \
9175                 r = vectorcall_maybe(tstate, &_Py_ID(RDUNDER), stack, 2); \
9176                 if (r != Py_NotImplemented) \
9177                     return r; \
9178                 Py_DECREF(r); \
9179                 do_other = 0; \
9180             } \
9181         } \
9182         stack[0] = self; \
9183         stack[1] = other; \
9184         r = vectorcall_maybe(tstate, &_Py_ID(DUNDER), stack, 2); \
9185         if (r != Py_NotImplemented || \
9186             Py_IS_TYPE(other, Py_TYPE(self))) \
9187             return r; \
9188         Py_DECREF(r); \
9189     } \
9190     if (do_other) { \
9191         stack[0] = other; \
9192         stack[1] = self; \
9193         return vectorcall_maybe(tstate, &_Py_ID(RDUNDER), stack, 2); \
9194     } \
9195     Py_RETURN_NOTIMPLEMENTED; \
9196 }
9197 
9198 #define SLOT1BIN(FUNCNAME, SLOTNAME, DUNDER, RDUNDER) \
9199     SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, DUNDER, RDUNDER)
9200 
9201 static Py_ssize_t
slot_sq_length(PyObject * self)9202 slot_sq_length(PyObject *self)
9203 {
9204     PyObject* stack[1] = {self};
9205     PyObject *res = vectorcall_method(&_Py_ID(__len__), stack, 1);
9206     Py_ssize_t len;
9207 
9208     if (res == NULL)
9209         return -1;
9210 
9211     Py_SETREF(res, _PyNumber_Index(res));
9212     if (res == NULL)
9213         return -1;
9214 
9215     assert(PyLong_Check(res));
9216     if (_PyLong_IsNegative((PyLongObject *)res)) {
9217         Py_DECREF(res);
9218         PyErr_SetString(PyExc_ValueError,
9219                         "__len__() should return >= 0");
9220         return -1;
9221     }
9222 
9223     len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
9224     assert(len >= 0 || PyErr_ExceptionMatches(PyExc_OverflowError));
9225     Py_DECREF(res);
9226     return len;
9227 }
9228 
9229 static PyObject *
slot_sq_item(PyObject * self,Py_ssize_t i)9230 slot_sq_item(PyObject *self, Py_ssize_t i)
9231 {
9232     PyObject *ival = PyLong_FromSsize_t(i);
9233     if (ival == NULL) {
9234         return NULL;
9235     }
9236     PyObject *stack[2] = {self, ival};
9237     PyObject *retval = vectorcall_method(&_Py_ID(__getitem__), stack, 2);
9238     Py_DECREF(ival);
9239     return retval;
9240 }
9241 
9242 static int
slot_sq_ass_item(PyObject * self,Py_ssize_t index,PyObject * value)9243 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
9244 {
9245     PyObject *stack[3];
9246     PyObject *res;
9247     PyObject *index_obj;
9248 
9249     index_obj = PyLong_FromSsize_t(index);
9250     if (index_obj == NULL) {
9251         return -1;
9252     }
9253 
9254     stack[0] = self;
9255     stack[1] = index_obj;
9256     if (value == NULL) {
9257         res = vectorcall_method(&_Py_ID(__delitem__), stack, 2);
9258     }
9259     else {
9260         stack[2] = value;
9261         res = vectorcall_method(&_Py_ID(__setitem__), stack, 3);
9262     }
9263     Py_DECREF(index_obj);
9264 
9265     if (res == NULL) {
9266         return -1;
9267     }
9268     Py_DECREF(res);
9269     return 0;
9270 }
9271 
9272 static int
slot_sq_contains(PyObject * self,PyObject * value)9273 slot_sq_contains(PyObject *self, PyObject *value)
9274 {
9275     PyThreadState *tstate = _PyThreadState_GET();
9276     PyObject *func, *res;
9277     int result = -1, unbound;
9278 
9279     func = lookup_maybe_method(self, &_Py_ID(__contains__), &unbound);
9280     if (func == Py_None) {
9281         Py_DECREF(func);
9282         PyErr_Format(PyExc_TypeError,
9283                      "'%.200s' object is not a container",
9284                      Py_TYPE(self)->tp_name);
9285         return -1;
9286     }
9287     if (func != NULL) {
9288         PyObject *args[2] = {self, value};
9289         res = vectorcall_unbound(tstate, unbound, func, args, 2);
9290         Py_DECREF(func);
9291         if (res != NULL) {
9292             result = PyObject_IsTrue(res);
9293             Py_DECREF(res);
9294         }
9295     }
9296     else if (! PyErr_Occurred()) {
9297         /* Possible results: -1 and 1 */
9298         result = (int)_PySequence_IterSearch(self, value,
9299                                          PY_ITERSEARCH_CONTAINS);
9300     }
9301     return result;
9302 }
9303 
9304 #define slot_mp_length slot_sq_length
9305 
SLOT1(slot_mp_subscript,__getitem__,PyObject *)9306 SLOT1(slot_mp_subscript, __getitem__, PyObject *)
9307 
9308 static int
9309 slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
9310 {
9311     PyObject *stack[3];
9312     PyObject *res;
9313 
9314     stack[0] = self;
9315     stack[1] = key;
9316     if (value == NULL) {
9317         res = vectorcall_method(&_Py_ID(__delitem__), stack, 2);
9318     }
9319     else {
9320         stack[2] = value;
9321         res = vectorcall_method(&_Py_ID(__setitem__), stack, 3);
9322     }
9323 
9324     if (res == NULL)
9325         return -1;
9326     Py_DECREF(res);
9327     return 0;
9328 }
9329 
9330 SLOT1BIN(slot_nb_add, nb_add, __add__, __radd__)
9331 SLOT1BIN(slot_nb_subtract, nb_subtract, __sub__, __rsub__)
9332 SLOT1BIN(slot_nb_multiply, nb_multiply, __mul__, __rmul__)
9333 SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, __matmul__, __rmatmul__)
9334 SLOT1BIN(slot_nb_remainder, nb_remainder, __mod__, __rmod__)
9335 SLOT1BIN(slot_nb_divmod, nb_divmod, __divmod__, __rdivmod__)
9336 
9337 static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
9338 
SLOT1BINFULL(slot_nb_power_binary,slot_nb_power,nb_power,__pow__,__rpow__)9339 SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, nb_power, __pow__, __rpow__)
9340 
9341 static PyObject *
9342 slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
9343 {
9344     if (modulus == Py_None)
9345         return slot_nb_power_binary(self, other);
9346     /* Three-arg power doesn't use __rpow__.  But ternary_op
9347        can call this when the second argument's type uses
9348        slot_nb_power, so check before calling self.__pow__. */
9349     if (Py_TYPE(self)->tp_as_number != NULL &&
9350         Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
9351         PyObject* stack[3] = {self, other, modulus};
9352         return vectorcall_method(&_Py_ID(__pow__), stack, 3);
9353     }
9354     Py_RETURN_NOTIMPLEMENTED;
9355 }
9356 
SLOT0(slot_nb_negative,__neg__)9357 SLOT0(slot_nb_negative, __neg__)
9358 SLOT0(slot_nb_positive, __pos__)
9359 SLOT0(slot_nb_absolute, __abs__)
9360 
9361 static int
9362 slot_nb_bool(PyObject *self)
9363 {
9364     PyObject *func, *value;
9365     int result, unbound;
9366     int using_len = 0;
9367 
9368     func = lookup_maybe_method(self, &_Py_ID(__bool__), &unbound);
9369     if (func == NULL) {
9370         if (PyErr_Occurred()) {
9371             return -1;
9372         }
9373 
9374         func = lookup_maybe_method(self, &_Py_ID(__len__), &unbound);
9375         if (func == NULL) {
9376             if (PyErr_Occurred()) {
9377                 return -1;
9378             }
9379             return 1;
9380         }
9381         using_len = 1;
9382     }
9383 
9384     value = call_unbound_noarg(unbound, func, self);
9385     if (value == NULL) {
9386         goto error;
9387     }
9388 
9389     if (using_len) {
9390         /* bool type enforced by slot_nb_len */
9391         result = PyObject_IsTrue(value);
9392     }
9393     else if (PyBool_Check(value)) {
9394         result = PyObject_IsTrue(value);
9395     }
9396     else {
9397         PyErr_Format(PyExc_TypeError,
9398                      "__bool__ should return "
9399                      "bool, returned %s",
9400                      Py_TYPE(value)->tp_name);
9401         result = -1;
9402     }
9403 
9404     Py_DECREF(value);
9405     Py_DECREF(func);
9406     return result;
9407 
9408 error:
9409     Py_DECREF(func);
9410     return -1;
9411 }
9412 
9413 
9414 static PyObject *
slot_nb_index(PyObject * self)9415 slot_nb_index(PyObject *self)
9416 {
9417     PyObject *stack[1] = {self};
9418     return vectorcall_method(&_Py_ID(__index__), stack, 1);
9419 }
9420 
9421 
SLOT0(slot_nb_invert,__invert__)9422 SLOT0(slot_nb_invert, __invert__)
9423 SLOT1BIN(slot_nb_lshift, nb_lshift, __lshift__, __rlshift__)
9424 SLOT1BIN(slot_nb_rshift, nb_rshift, __rshift__, __rrshift__)
9425 SLOT1BIN(slot_nb_and, nb_and, __and__, __rand__)
9426 SLOT1BIN(slot_nb_xor, nb_xor, __xor__, __rxor__)
9427 SLOT1BIN(slot_nb_or, nb_or, __or__, __ror__)
9428 
9429 SLOT0(slot_nb_int, __int__)
9430 SLOT0(slot_nb_float, __float__)
9431 SLOT1(slot_nb_inplace_add, __iadd__, PyObject *)
9432 SLOT1(slot_nb_inplace_subtract, __isub__, PyObject *)
9433 SLOT1(slot_nb_inplace_multiply, __imul__, PyObject *)
9434 SLOT1(slot_nb_inplace_matrix_multiply, __imatmul__, PyObject *)
9435 SLOT1(slot_nb_inplace_remainder, __imod__, PyObject *)
9436 /* Can't use SLOT1 here, because nb_inplace_power is ternary */
9437 static PyObject *
9438 slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
9439 {
9440     PyObject *stack[2] = {self, arg1};
9441     return vectorcall_method(&_Py_ID(__ipow__), stack, 2);
9442 }
SLOT1(slot_nb_inplace_lshift,__ilshift__,PyObject *)9443 SLOT1(slot_nb_inplace_lshift, __ilshift__, PyObject *)
9444 SLOT1(slot_nb_inplace_rshift, __irshift__, PyObject *)
9445 SLOT1(slot_nb_inplace_and, __iand__, PyObject *)
9446 SLOT1(slot_nb_inplace_xor, __ixor__, PyObject *)
9447 SLOT1(slot_nb_inplace_or, __ior__, PyObject *)
9448 SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
9449          __floordiv__, __rfloordiv__)
9450 SLOT1BIN(slot_nb_true_divide, nb_true_divide, __truediv__, __rtruediv__)
9451 SLOT1(slot_nb_inplace_floor_divide, __ifloordiv__, PyObject *)
9452 SLOT1(slot_nb_inplace_true_divide, __itruediv__, PyObject *)
9453 
9454 static PyObject *
9455 slot_tp_repr(PyObject *self)
9456 {
9457     PyObject *func, *res;
9458     int unbound;
9459 
9460     func = lookup_maybe_method(self, &_Py_ID(__repr__), &unbound);
9461     if (func != NULL) {
9462         res = call_unbound_noarg(unbound, func, self);
9463         Py_DECREF(func);
9464         return res;
9465     }
9466     PyErr_Clear();
9467     return PyUnicode_FromFormat("<%s object at %p>",
9468                                Py_TYPE(self)->tp_name, self);
9469 }
9470 
SLOT0(slot_tp_str,__str__)9471 SLOT0(slot_tp_str, __str__)
9472 
9473 static Py_hash_t
9474 slot_tp_hash(PyObject *self)
9475 {
9476     PyObject *func, *res;
9477     Py_ssize_t h;
9478     int unbound;
9479 
9480     func = lookup_maybe_method(self, &_Py_ID(__hash__), &unbound);
9481 
9482     if (func == Py_None) {
9483         Py_SETREF(func, NULL);
9484     }
9485 
9486     if (func == NULL) {
9487         return PyObject_HashNotImplemented(self);
9488     }
9489 
9490     res = call_unbound_noarg(unbound, func, self);
9491     Py_DECREF(func);
9492     if (res == NULL)
9493         return -1;
9494 
9495     if (!PyLong_Check(res)) {
9496         PyErr_SetString(PyExc_TypeError,
9497                         "__hash__ method should return an integer");
9498         return -1;
9499     }
9500     /* Transform the PyLong `res` to a Py_hash_t `h`.  For an existing
9501        hashable Python object x, hash(x) will always lie within the range of
9502        Py_hash_t.  Therefore our transformation must preserve values that
9503        already lie within this range, to ensure that if x.__hash__() returns
9504        hash(y) then hash(x) == hash(y). */
9505     h = PyLong_AsSsize_t(res);
9506     if (h == -1 && PyErr_Occurred()) {
9507         /* res was not within the range of a Py_hash_t, so we're free to
9508            use any sufficiently bit-mixing transformation;
9509            long.__hash__ will do nicely. */
9510         PyErr_Clear();
9511         h = PyLong_Type.tp_hash(res);
9512     }
9513     /* -1 is reserved for errors. */
9514     if (h == -1)
9515         h = -2;
9516     Py_DECREF(res);
9517     return h;
9518 }
9519 
9520 static PyObject *
slot_tp_call(PyObject * self,PyObject * args,PyObject * kwds)9521 slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
9522 {
9523     PyThreadState *tstate = _PyThreadState_GET();
9524     int unbound;
9525 
9526     PyObject *meth = lookup_method(self, &_Py_ID(__call__), &unbound);
9527     if (meth == NULL) {
9528         return NULL;
9529     }
9530 
9531     PyObject *res;
9532     if (unbound) {
9533         res = _PyObject_Call_Prepend(tstate, meth, self, args, kwds);
9534     }
9535     else {
9536         res = _PyObject_Call(tstate, meth, args, kwds);
9537     }
9538 
9539     Py_DECREF(meth);
9540     return res;
9541 }
9542 
9543 /* There are two slot dispatch functions for tp_getattro.
9544 
9545    - _Py_slot_tp_getattro() is used when __getattribute__ is overridden
9546      but no __getattr__ hook is present;
9547 
9548    - _Py_slot_tp_getattr_hook() is used when a __getattr__ hook is present.
9549 
9550    The code in update_one_slot() always installs _Py_slot_tp_getattr_hook();
9551    this detects the absence of __getattr__ and then installs the simpler
9552    slot if necessary. */
9553 
9554 PyObject *
_Py_slot_tp_getattro(PyObject * self,PyObject * name)9555 _Py_slot_tp_getattro(PyObject *self, PyObject *name)
9556 {
9557     PyObject *stack[2] = {self, name};
9558     return vectorcall_method(&_Py_ID(__getattribute__), stack, 2);
9559 }
9560 
9561 static inline PyObject *
call_attribute(PyObject * self,PyObject * attr,PyObject * name)9562 call_attribute(PyObject *self, PyObject *attr, PyObject *name)
9563 {
9564     PyObject *res, *descr = NULL;
9565 
9566     if (_PyType_HasFeature(Py_TYPE(attr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
9567         PyObject *args[] = { self, name };
9568         res = PyObject_Vectorcall(attr, args, 2, NULL);
9569         return res;
9570     }
9571 
9572     descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
9573 
9574     if (f != NULL) {
9575         descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
9576         if (descr == NULL)
9577             return NULL;
9578         else
9579             attr = descr;
9580     }
9581     res = PyObject_CallOneArg(attr, name);
9582     Py_XDECREF(descr);
9583     return res;
9584 }
9585 
9586 PyObject *
_Py_slot_tp_getattr_hook(PyObject * self,PyObject * name)9587 _Py_slot_tp_getattr_hook(PyObject *self, PyObject *name)
9588 {
9589     PyTypeObject *tp = Py_TYPE(self);
9590     PyObject *getattr, *getattribute, *res;
9591 
9592     /* speed hack: we could use lookup_maybe, but that would resolve the
9593        method fully for each attribute lookup for classes with
9594        __getattr__, even when the attribute is present. So we use
9595        _PyType_LookupRef and create the method only when needed, with
9596        call_attribute. */
9597     getattr = _PyType_LookupRef(tp, &_Py_ID(__getattr__));
9598     if (getattr == NULL) {
9599         /* No __getattr__ hook: use a simpler dispatcher */
9600         tp->tp_getattro = _Py_slot_tp_getattro;
9601         return _Py_slot_tp_getattro(self, name);
9602     }
9603     /* speed hack: we could use lookup_maybe, but that would resolve the
9604        method fully for each attribute lookup for classes with
9605        __getattr__, even when self has the default __getattribute__
9606        method. So we use _PyType_LookupRef and create the method only when
9607        needed, with call_attribute. */
9608     getattribute = _PyType_LookupRef(tp, &_Py_ID(__getattribute__));
9609     if (getattribute == NULL ||
9610         (Py_IS_TYPE(getattribute, &PyWrapperDescr_Type) &&
9611          ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
9612              (void *)PyObject_GenericGetAttr)) {
9613         Py_XDECREF(getattribute);
9614         res = _PyObject_GenericGetAttrWithDict(self, name, NULL, 1);
9615         /* if res == NULL with no exception set, then it must be an
9616            AttributeError suppressed by us. */
9617         if (res == NULL && !PyErr_Occurred()) {
9618             res = call_attribute(self, getattr, name);
9619         }
9620     }
9621     else {
9622         res = call_attribute(self, getattribute, name);
9623         Py_DECREF(getattribute);
9624         if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
9625             PyErr_Clear();
9626             res = call_attribute(self, getattr, name);
9627         }
9628     }
9629 
9630     Py_DECREF(getattr);
9631     return res;
9632 }
9633 
9634 static int
slot_tp_setattro(PyObject * self,PyObject * name,PyObject * value)9635 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
9636 {
9637     PyObject *stack[3];
9638     PyObject *res;
9639 
9640     stack[0] = self;
9641     stack[1] = name;
9642     if (value == NULL) {
9643         res = vectorcall_method(&_Py_ID(__delattr__), stack, 2);
9644     }
9645     else {
9646         stack[2] = value;
9647         res = vectorcall_method(&_Py_ID(__setattr__), stack, 3);
9648     }
9649     if (res == NULL)
9650         return -1;
9651     Py_DECREF(res);
9652     return 0;
9653 }
9654 
9655 static PyObject *name_op[] = {
9656     &_Py_ID(__lt__),
9657     &_Py_ID(__le__),
9658     &_Py_ID(__eq__),
9659     &_Py_ID(__ne__),
9660     &_Py_ID(__gt__),
9661     &_Py_ID(__ge__),
9662 };
9663 
9664 static PyObject *
slot_tp_richcompare(PyObject * self,PyObject * other,int op)9665 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
9666 {
9667     PyThreadState *tstate = _PyThreadState_GET();
9668 
9669     int unbound;
9670     PyObject *func = lookup_maybe_method(self, name_op[op], &unbound);
9671     if (func == NULL) {
9672         PyErr_Clear();
9673         Py_RETURN_NOTIMPLEMENTED;
9674     }
9675 
9676     PyObject *stack[2] = {self, other};
9677     PyObject *res = vectorcall_unbound(tstate, unbound, func, stack, 2);
9678     Py_DECREF(func);
9679     return res;
9680 }
9681 
9682 static PyObject *
slot_tp_iter(PyObject * self)9683 slot_tp_iter(PyObject *self)
9684 {
9685     int unbound;
9686     PyObject *func, *res;
9687 
9688     func = lookup_maybe_method(self, &_Py_ID(__iter__), &unbound);
9689     if (func == Py_None) {
9690         Py_DECREF(func);
9691         PyErr_Format(PyExc_TypeError,
9692                      "'%.200s' object is not iterable",
9693                      Py_TYPE(self)->tp_name);
9694         return NULL;
9695     }
9696 
9697     if (func != NULL) {
9698         res = call_unbound_noarg(unbound, func, self);
9699         Py_DECREF(func);
9700         return res;
9701     }
9702 
9703     PyErr_Clear();
9704     func = lookup_maybe_method(self, &_Py_ID(__getitem__), &unbound);
9705     if (func == NULL) {
9706         PyErr_Format(PyExc_TypeError,
9707                      "'%.200s' object is not iterable",
9708                      Py_TYPE(self)->tp_name);
9709         return NULL;
9710     }
9711     Py_DECREF(func);
9712     return PySeqIter_New(self);
9713 }
9714 
9715 static PyObject *
slot_tp_iternext(PyObject * self)9716 slot_tp_iternext(PyObject *self)
9717 {
9718     PyObject *stack[1] = {self};
9719     return vectorcall_method(&_Py_ID(__next__), stack, 1);
9720 }
9721 
9722 static PyObject *
slot_tp_descr_get(PyObject * self,PyObject * obj,PyObject * type)9723 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
9724 {
9725     PyTypeObject *tp = Py_TYPE(self);
9726     PyObject *get;
9727 
9728     get = _PyType_LookupRef(tp, &_Py_ID(__get__));
9729     if (get == NULL) {
9730         /* Avoid further slowdowns */
9731         if (tp->tp_descr_get == slot_tp_descr_get)
9732             tp->tp_descr_get = NULL;
9733         return Py_NewRef(self);
9734     }
9735     if (obj == NULL)
9736         obj = Py_None;
9737     if (type == NULL)
9738         type = Py_None;
9739     PyObject *stack[3] = {self, obj, type};
9740     PyObject *res = PyObject_Vectorcall(get, stack, 3, NULL);
9741     Py_DECREF(get);
9742     return res;
9743 }
9744 
9745 static int
slot_tp_descr_set(PyObject * self,PyObject * target,PyObject * value)9746 slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
9747 {
9748     PyObject* stack[3];
9749     PyObject *res;
9750 
9751     stack[0] = self;
9752     stack[1] = target;
9753     if (value == NULL) {
9754         res = vectorcall_method(&_Py_ID(__delete__), stack, 2);
9755     }
9756     else {
9757         stack[2] = value;
9758         res = vectorcall_method(&_Py_ID(__set__), stack, 3);
9759     }
9760     if (res == NULL)
9761         return -1;
9762     Py_DECREF(res);
9763     return 0;
9764 }
9765 
9766 static int
slot_tp_init(PyObject * self,PyObject * args,PyObject * kwds)9767 slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
9768 {
9769     PyThreadState *tstate = _PyThreadState_GET();
9770 
9771     int unbound;
9772     PyObject *meth = lookup_method(self, &_Py_ID(__init__), &unbound);
9773     if (meth == NULL) {
9774         return -1;
9775     }
9776 
9777     PyObject *res;
9778     if (unbound) {
9779         res = _PyObject_Call_Prepend(tstate, meth, self, args, kwds);
9780     }
9781     else {
9782         res = _PyObject_Call(tstate, meth, args, kwds);
9783     }
9784     Py_DECREF(meth);
9785     if (res == NULL)
9786         return -1;
9787     if (res != Py_None) {
9788         PyErr_Format(PyExc_TypeError,
9789                      "__init__() should return None, not '%.200s'",
9790                      Py_TYPE(res)->tp_name);
9791         Py_DECREF(res);
9792         return -1;
9793     }
9794     Py_DECREF(res);
9795     return 0;
9796 }
9797 
9798 static PyObject *
slot_tp_new(PyTypeObject * type,PyObject * args,PyObject * kwds)9799 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9800 {
9801     PyThreadState *tstate = _PyThreadState_GET();
9802     PyObject *func, *result;
9803 
9804     func = PyObject_GetAttr((PyObject *)type, &_Py_ID(__new__));
9805     if (func == NULL) {
9806         return NULL;
9807     }
9808 
9809     result = _PyObject_Call_Prepend(tstate, func, (PyObject *)type, args, kwds);
9810     Py_DECREF(func);
9811     return result;
9812 }
9813 
9814 static void
slot_tp_finalize(PyObject * self)9815 slot_tp_finalize(PyObject *self)
9816 {
9817     int unbound;
9818     PyObject *del, *res;
9819 
9820     /* Save the current exception, if any. */
9821     PyObject *exc = PyErr_GetRaisedException();
9822 
9823     /* Execute __del__ method, if any. */
9824     del = lookup_maybe_method(self, &_Py_ID(__del__), &unbound);
9825     if (del != NULL) {
9826         res = call_unbound_noarg(unbound, del, self);
9827         if (res == NULL)
9828             PyErr_WriteUnraisable(del);
9829         else
9830             Py_DECREF(res);
9831         Py_DECREF(del);
9832     }
9833 
9834     /* Restore the saved exception. */
9835     PyErr_SetRaisedException(exc);
9836 }
9837 
9838 typedef struct _PyBufferWrapper {
9839     PyObject_HEAD
9840     PyObject *mv;
9841     PyObject *obj;
9842 } PyBufferWrapper;
9843 
9844 static int
bufferwrapper_traverse(PyBufferWrapper * self,visitproc visit,void * arg)9845 bufferwrapper_traverse(PyBufferWrapper *self, visitproc visit, void *arg)
9846 {
9847     Py_VISIT(self->mv);
9848     Py_VISIT(self->obj);
9849     return 0;
9850 }
9851 
9852 static void
bufferwrapper_dealloc(PyObject * self)9853 bufferwrapper_dealloc(PyObject *self)
9854 {
9855     PyBufferWrapper *bw = (PyBufferWrapper *)self;
9856 
9857     _PyObject_GC_UNTRACK(self);
9858     Py_XDECREF(bw->mv);
9859     Py_XDECREF(bw->obj);
9860     Py_TYPE(self)->tp_free(self);
9861 }
9862 
9863 static void
bufferwrapper_releasebuf(PyObject * self,Py_buffer * view)9864 bufferwrapper_releasebuf(PyObject *self, Py_buffer *view)
9865 {
9866     PyBufferWrapper *bw = (PyBufferWrapper *)self;
9867 
9868     if (bw->mv == NULL || bw->obj == NULL) {
9869         // Already released
9870         return;
9871     }
9872 
9873     PyObject *mv = bw->mv;
9874     PyObject *obj = bw->obj;
9875 
9876     assert(PyMemoryView_Check(mv));
9877     Py_TYPE(mv)->tp_as_buffer->bf_releasebuffer(mv, view);
9878     // We only need to call bf_releasebuffer if it's a Python function. If it's a C
9879     // bf_releasebuf, it will be called when the memoryview is released.
9880     if (((PyMemoryViewObject *)mv)->view.obj != obj
9881             && Py_TYPE(obj)->tp_as_buffer != NULL
9882             && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer == slot_bf_releasebuffer) {
9883         releasebuffer_call_python(obj, view);
9884     }
9885 
9886     Py_CLEAR(bw->mv);
9887     Py_CLEAR(bw->obj);
9888 }
9889 
9890 static PyBufferProcs bufferwrapper_as_buffer = {
9891     .bf_releasebuffer = bufferwrapper_releasebuf,
9892 };
9893 
9894 
9895 PyTypeObject _PyBufferWrapper_Type = {
9896     PyVarObject_HEAD_INIT(&PyType_Type, 0)
9897     .tp_name = "_buffer_wrapper",
9898     .tp_basicsize = sizeof(PyBufferWrapper),
9899     .tp_alloc = PyType_GenericAlloc,
9900     .tp_free = PyObject_GC_Del,
9901     .tp_traverse = (traverseproc)bufferwrapper_traverse,
9902     .tp_dealloc = bufferwrapper_dealloc,
9903     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
9904     .tp_as_buffer = &bufferwrapper_as_buffer,
9905 };
9906 
9907 static int
slot_bf_getbuffer(PyObject * self,Py_buffer * buffer,int flags)9908 slot_bf_getbuffer(PyObject *self, Py_buffer *buffer, int flags)
9909 {
9910     PyObject *flags_obj = PyLong_FromLong(flags);
9911     if (flags_obj == NULL) {
9912         return -1;
9913     }
9914     PyBufferWrapper *wrapper = NULL;
9915     PyObject *stack[2] = {self, flags_obj};
9916     PyObject *ret = vectorcall_method(&_Py_ID(__buffer__), stack, 2);
9917     if (ret == NULL) {
9918         goto fail;
9919     }
9920     if (!PyMemoryView_Check(ret)) {
9921         PyErr_Format(PyExc_TypeError,
9922                      "__buffer__ returned non-memoryview object");
9923         goto fail;
9924     }
9925 
9926     if (PyObject_GetBuffer(ret, buffer, flags) < 0) {
9927         goto fail;
9928     }
9929     assert(buffer->obj == ret);
9930 
9931     wrapper = PyObject_GC_New(PyBufferWrapper, &_PyBufferWrapper_Type);
9932     if (wrapper == NULL) {
9933         goto fail;
9934     }
9935     wrapper->mv = ret;
9936     wrapper->obj = Py_NewRef(self);
9937     _PyObject_GC_TRACK(wrapper);
9938 
9939     buffer->obj = (PyObject *)wrapper;
9940     Py_DECREF(ret);
9941     Py_DECREF(flags_obj);
9942     return 0;
9943 
9944 fail:
9945     Py_XDECREF(wrapper);
9946     Py_XDECREF(ret);
9947     Py_DECREF(flags_obj);
9948     return -1;
9949 }
9950 
9951 static releasebufferproc
releasebuffer_maybe_call_super_unlocked(PyObject * self,Py_buffer * buffer)9952 releasebuffer_maybe_call_super_unlocked(PyObject *self, Py_buffer *buffer)
9953 {
9954     PyTypeObject *self_type = Py_TYPE(self);
9955     PyObject *mro = lookup_tp_mro(self_type);
9956     if (mro == NULL) {
9957         return NULL;
9958     }
9959 
9960     assert(PyTuple_Check(mro));
9961     Py_ssize_t n = PyTuple_GET_SIZE(mro);
9962     Py_ssize_t i;
9963 
9964     /* No need to check the last one: it's gonna be skipped anyway.  */
9965     for (i = 0;  i < n -1; i++) {
9966         if ((PyObject *)(self_type) == PyTuple_GET_ITEM(mro, i))
9967             break;
9968     }
9969     i++;  /* skip self_type */
9970     if (i >= n)
9971         return NULL;
9972 
9973     for (; i < n; i++) {
9974         PyObject *obj = PyTuple_GET_ITEM(mro, i);
9975         if (!PyType_Check(obj)) {
9976             continue;
9977         }
9978         PyTypeObject *base_type = (PyTypeObject *)obj;
9979         if (base_type->tp_as_buffer != NULL
9980             && base_type->tp_as_buffer->bf_releasebuffer != NULL
9981             && base_type->tp_as_buffer->bf_releasebuffer != slot_bf_releasebuffer) {
9982             return base_type->tp_as_buffer->bf_releasebuffer;
9983         }
9984     }
9985 
9986     return NULL;
9987 }
9988 
9989 static void
releasebuffer_maybe_call_super(PyObject * self,Py_buffer * buffer)9990 releasebuffer_maybe_call_super(PyObject *self, Py_buffer *buffer)
9991 {
9992     releasebufferproc base_releasebuffer;
9993 
9994     BEGIN_TYPE_LOCK();
9995     base_releasebuffer = releasebuffer_maybe_call_super_unlocked(self, buffer);
9996     END_TYPE_LOCK();
9997 
9998     if (base_releasebuffer != NULL) {
9999         base_releasebuffer(self, buffer);
10000     }
10001 }
10002 
10003 static void
releasebuffer_call_python(PyObject * self,Py_buffer * buffer)10004 releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
10005 {
10006     // bf_releasebuffer may be called while an exception is already active.
10007     // We have no way to report additional errors up the stack, because
10008     // this slot returns void, so we simply stash away the active exception
10009     // and restore it after the call to Python returns.
10010     PyObject *exc = PyErr_GetRaisedException();
10011 
10012     PyObject *mv;
10013     bool is_buffer_wrapper = Py_TYPE(buffer->obj) == &_PyBufferWrapper_Type;
10014     if (is_buffer_wrapper) {
10015         // Make sure we pass the same memoryview to
10016         // __release_buffer__() that __buffer__() returned.
10017         PyBufferWrapper *bw = (PyBufferWrapper *)buffer->obj;
10018         if (bw->mv == NULL) {
10019             goto end;
10020         }
10021         mv = Py_NewRef(bw->mv);
10022     }
10023     else {
10024         // This means we are not dealing with a memoryview returned
10025         // from a Python __buffer__ function.
10026         mv = PyMemoryView_FromBuffer(buffer);
10027         if (mv == NULL) {
10028             PyErr_FormatUnraisable("Exception ignored in bf_releasebuffer of %s", Py_TYPE(self)->tp_name);
10029             goto end;
10030         }
10031         // Set the memoryview to restricted mode, which forbids
10032         // users from saving any reference to the underlying buffer
10033         // (e.g., by doing .cast()). This is necessary to ensure
10034         // no Python code retains a reference to the to-be-released
10035         // buffer.
10036         ((PyMemoryViewObject *)mv)->flags |= _Py_MEMORYVIEW_RESTRICTED;
10037     }
10038     PyObject *stack[2] = {self, mv};
10039     PyObject *ret = vectorcall_method(&_Py_ID(__release_buffer__), stack, 2);
10040     if (ret == NULL) {
10041         PyErr_FormatUnraisable("Exception ignored in __release_buffer__ of %s", Py_TYPE(self)->tp_name);
10042     }
10043     else {
10044         Py_DECREF(ret);
10045     }
10046     if (!is_buffer_wrapper) {
10047         PyObject *res = PyObject_CallMethodNoArgs(mv, &_Py_ID(release));
10048         if (res == NULL) {
10049             PyErr_FormatUnraisable("Exception ignored in bf_releasebuffer of %s", Py_TYPE(self)->tp_name);
10050         }
10051         else {
10052             Py_DECREF(res);
10053         }
10054     }
10055     Py_DECREF(mv);
10056 end:
10057     assert(!PyErr_Occurred());
10058 
10059     PyErr_SetRaisedException(exc);
10060 }
10061 
10062 /*
10063  * bf_releasebuffer is very delicate, because we need to ensure that
10064  * C bf_releasebuffer slots are called correctly (or we'll leak memory),
10065  * but we cannot trust any __release_buffer__ implemented in Python to
10066  * do so correctly. Therefore, if a base class has a C bf_releasebuffer
10067  * slot, we call it directly here. That is safe because this function
10068  * only gets called from C callers of the bf_releasebuffer slot. Python
10069  * code that calls __release_buffer__ directly instead goes through
10070  * wrap_releasebuffer(), which doesn't call the bf_releasebuffer slot
10071  * directly but instead simply releases the associated memoryview.
10072  */
10073 static void
slot_bf_releasebuffer(PyObject * self,Py_buffer * buffer)10074 slot_bf_releasebuffer(PyObject *self, Py_buffer *buffer)
10075 {
10076     releasebuffer_call_python(self, buffer);
10077     releasebuffer_maybe_call_super(self, buffer);
10078 }
10079 
10080 static PyObject *
slot_am_await(PyObject * self)10081 slot_am_await(PyObject *self)
10082 {
10083     int unbound;
10084     PyObject *func, *res;
10085 
10086     func = lookup_maybe_method(self, &_Py_ID(__await__), &unbound);
10087     if (func != NULL) {
10088         res = call_unbound_noarg(unbound, func, self);
10089         Py_DECREF(func);
10090         return res;
10091     }
10092     PyErr_Format(PyExc_AttributeError,
10093                  "object %.50s does not have __await__ method",
10094                  Py_TYPE(self)->tp_name);
10095     return NULL;
10096 }
10097 
10098 static PyObject *
slot_am_aiter(PyObject * self)10099 slot_am_aiter(PyObject *self)
10100 {
10101     int unbound;
10102     PyObject *func, *res;
10103 
10104     func = lookup_maybe_method(self, &_Py_ID(__aiter__), &unbound);
10105     if (func != NULL) {
10106         res = call_unbound_noarg(unbound, func, self);
10107         Py_DECREF(func);
10108         return res;
10109     }
10110     PyErr_Format(PyExc_AttributeError,
10111                  "object %.50s does not have __aiter__ method",
10112                  Py_TYPE(self)->tp_name);
10113     return NULL;
10114 }
10115 
10116 static PyObject *
slot_am_anext(PyObject * self)10117 slot_am_anext(PyObject *self)
10118 {
10119     int unbound;
10120     PyObject *func, *res;
10121 
10122     func = lookup_maybe_method(self, &_Py_ID(__anext__), &unbound);
10123     if (func != NULL) {
10124         res = call_unbound_noarg(unbound, func, self);
10125         Py_DECREF(func);
10126         return res;
10127     }
10128     PyErr_Format(PyExc_AttributeError,
10129                  "object %.50s does not have __anext__ method",
10130                  Py_TYPE(self)->tp_name);
10131     return NULL;
10132 }
10133 
10134 /*
10135 Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
10136 
10137 The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
10138 which incorporates the additional structures used for numbers, sequences and
10139 mappings.  Note that multiple names may map to the same slot (e.g. __eq__,
10140 __ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
10141 (e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
10142 an all-zero entry.
10143 */
10144 
10145 #undef TPSLOT
10146 #undef FLSLOT
10147 #undef BUFSLOT
10148 #undef AMSLOT
10149 #undef ETSLOT
10150 #undef SQSLOT
10151 #undef MPSLOT
10152 #undef NBSLOT
10153 #undef UNSLOT
10154 #undef IBSLOT
10155 #undef BINSLOT
10156 #undef RBINSLOT
10157 
10158 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10159     {#NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
10160      PyDoc_STR(DOC), .name_strobj = &_Py_ID(NAME)}
10161 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
10162     {#NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
10163      PyDoc_STR(DOC), FLAGS, .name_strobj = &_Py_ID(NAME) }
10164 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10165     {#NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
10166      PyDoc_STR(DOC), .name_strobj = &_Py_ID(NAME) }
10167 #define BUFSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10168     ETSLOT(NAME, as_buffer.SLOT, FUNCTION, WRAPPER, DOC)
10169 #define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10170     ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
10171 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10172     ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
10173 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10174     ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
10175 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10176     ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
10177 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10178     ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
10179            #NAME "($self, /)\n--\n\n" DOC)
10180 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
10181     ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
10182            #NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
10183 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
10184     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
10185            #NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
10186 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
10187     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
10188            #NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
10189 #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
10190     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
10191            #NAME "($self, value, /)\n--\n\n" DOC)
10192 #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
10193     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
10194            #NAME "($self, value, /)\n--\n\n" DOC)
10195 
10196 static pytype_slotdef slotdefs[] = {
10197     TPSLOT(__getattribute__, tp_getattr, NULL, NULL, ""),
10198     TPSLOT(__getattr__, tp_getattr, NULL, NULL, ""),
10199     TPSLOT(__setattr__, tp_setattr, NULL, NULL, ""),
10200     TPSLOT(__delattr__, tp_setattr, NULL, NULL, ""),
10201     TPSLOT(__repr__, tp_repr, slot_tp_repr, wrap_unaryfunc,
10202            "__repr__($self, /)\n--\n\nReturn repr(self)."),
10203     TPSLOT(__hash__, tp_hash, slot_tp_hash, wrap_hashfunc,
10204            "__hash__($self, /)\n--\n\nReturn hash(self)."),
10205     FLSLOT(__call__, tp_call, slot_tp_call, (wrapperfunc)(void(*)(void))wrap_call,
10206            "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
10207            PyWrapperFlag_KEYWORDS),
10208     TPSLOT(__str__, tp_str, slot_tp_str, wrap_unaryfunc,
10209            "__str__($self, /)\n--\n\nReturn str(self)."),
10210     TPSLOT(__getattribute__, tp_getattro, _Py_slot_tp_getattr_hook,
10211            wrap_binaryfunc,
10212            "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
10213     TPSLOT(__getattr__, tp_getattro, _Py_slot_tp_getattr_hook, NULL,
10214            "__getattr__($self, name, /)\n--\n\nImplement getattr(self, name)."),
10215     TPSLOT(__setattr__, tp_setattro, slot_tp_setattro, wrap_setattr,
10216            "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
10217     TPSLOT(__delattr__, tp_setattro, slot_tp_setattro, wrap_delattr,
10218            "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
10219     TPSLOT(__lt__, tp_richcompare, slot_tp_richcompare, richcmp_lt,
10220            "__lt__($self, value, /)\n--\n\nReturn self<value."),
10221     TPSLOT(__le__, tp_richcompare, slot_tp_richcompare, richcmp_le,
10222            "__le__($self, value, /)\n--\n\nReturn self<=value."),
10223     TPSLOT(__eq__, tp_richcompare, slot_tp_richcompare, richcmp_eq,
10224            "__eq__($self, value, /)\n--\n\nReturn self==value."),
10225     TPSLOT(__ne__, tp_richcompare, slot_tp_richcompare, richcmp_ne,
10226            "__ne__($self, value, /)\n--\n\nReturn self!=value."),
10227     TPSLOT(__gt__, tp_richcompare, slot_tp_richcompare, richcmp_gt,
10228            "__gt__($self, value, /)\n--\n\nReturn self>value."),
10229     TPSLOT(__ge__, tp_richcompare, slot_tp_richcompare, richcmp_ge,
10230            "__ge__($self, value, /)\n--\n\nReturn self>=value."),
10231     TPSLOT(__iter__, tp_iter, slot_tp_iter, wrap_unaryfunc,
10232            "__iter__($self, /)\n--\n\nImplement iter(self)."),
10233     TPSLOT(__next__, tp_iternext, slot_tp_iternext, wrap_next,
10234            "__next__($self, /)\n--\n\nImplement next(self)."),
10235     TPSLOT(__get__, tp_descr_get, slot_tp_descr_get, wrap_descr_get,
10236            "__get__($self, instance, owner=None, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
10237     TPSLOT(__set__, tp_descr_set, slot_tp_descr_set, wrap_descr_set,
10238            "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
10239     TPSLOT(__delete__, tp_descr_set, slot_tp_descr_set,
10240            wrap_descr_delete,
10241            "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
10242     FLSLOT(__init__, tp_init, slot_tp_init, (wrapperfunc)(void(*)(void))wrap_init,
10243            "__init__($self, /, *args, **kwargs)\n--\n\n"
10244            "Initialize self.  See help(type(self)) for accurate signature.",
10245            PyWrapperFlag_KEYWORDS),
10246     TPSLOT(__new__, tp_new, slot_tp_new, NULL,
10247            "__new__(type, /, *args, **kwargs)\n--\n\n"
10248            "Create and return new object.  See help(type) for accurate signature."),
10249     TPSLOT(__del__, tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del,
10250            "__del__($self, /)\n--\n\n"
10251            "Called when the instance is about to be destroyed."),
10252 
10253     BUFSLOT(__buffer__, bf_getbuffer, slot_bf_getbuffer, wrap_buffer,
10254             "__buffer__($self, flags, /)\n--\n\n"
10255             "Return a buffer object that exposes the underlying memory of the object."),
10256     BUFSLOT(__release_buffer__, bf_releasebuffer, slot_bf_releasebuffer, wrap_releasebuffer,
10257             "__release_buffer__($self, buffer, /)\n--\n\n"
10258             "Release the buffer object that exposes the underlying memory of the object."),
10259 
10260     AMSLOT(__await__, am_await, slot_am_await, wrap_unaryfunc,
10261            "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
10262     AMSLOT(__aiter__, am_aiter, slot_am_aiter, wrap_unaryfunc,
10263            "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
10264     AMSLOT(__anext__, am_anext, slot_am_anext, wrap_unaryfunc,
10265            "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
10266 
10267     BINSLOT(__add__, nb_add, slot_nb_add,
10268            "+"),
10269     RBINSLOT(__radd__, nb_add, slot_nb_add,
10270            "+"),
10271     BINSLOT(__sub__, nb_subtract, slot_nb_subtract,
10272            "-"),
10273     RBINSLOT(__rsub__, nb_subtract, slot_nb_subtract,
10274            "-"),
10275     BINSLOT(__mul__, nb_multiply, slot_nb_multiply,
10276            "*"),
10277     RBINSLOT(__rmul__, nb_multiply, slot_nb_multiply,
10278            "*"),
10279     BINSLOT(__mod__, nb_remainder, slot_nb_remainder,
10280            "%"),
10281     RBINSLOT(__rmod__, nb_remainder, slot_nb_remainder,
10282            "%"),
10283     BINSLOTNOTINFIX(__divmod__, nb_divmod, slot_nb_divmod,
10284            "Return divmod(self, value)."),
10285     RBINSLOTNOTINFIX(__rdivmod__, nb_divmod, slot_nb_divmod,
10286            "Return divmod(value, self)."),
10287     NBSLOT(__pow__, nb_power, slot_nb_power, wrap_ternaryfunc,
10288            "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
10289     NBSLOT(__rpow__, nb_power, slot_nb_power, wrap_ternaryfunc_r,
10290            "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
10291     UNSLOT(__neg__, nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
10292     UNSLOT(__pos__, nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
10293     UNSLOT(__abs__, nb_absolute, slot_nb_absolute, wrap_unaryfunc,
10294            "abs(self)"),
10295     UNSLOT(__bool__, nb_bool, slot_nb_bool, wrap_inquirypred,
10296            "True if self else False"),
10297     UNSLOT(__invert__, nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
10298     BINSLOT(__lshift__, nb_lshift, slot_nb_lshift, "<<"),
10299     RBINSLOT(__rlshift__, nb_lshift, slot_nb_lshift, "<<"),
10300     BINSLOT(__rshift__, nb_rshift, slot_nb_rshift, ">>"),
10301     RBINSLOT(__rrshift__, nb_rshift, slot_nb_rshift, ">>"),
10302     BINSLOT(__and__, nb_and, slot_nb_and, "&"),
10303     RBINSLOT(__rand__, nb_and, slot_nb_and, "&"),
10304     BINSLOT(__xor__, nb_xor, slot_nb_xor, "^"),
10305     RBINSLOT(__rxor__, nb_xor, slot_nb_xor, "^"),
10306     BINSLOT(__or__, nb_or, slot_nb_or, "|"),
10307     RBINSLOT(__ror__, nb_or, slot_nb_or, "|"),
10308     UNSLOT(__int__, nb_int, slot_nb_int, wrap_unaryfunc,
10309            "int(self)"),
10310     UNSLOT(__float__, nb_float, slot_nb_float, wrap_unaryfunc,
10311            "float(self)"),
10312     IBSLOT(__iadd__, nb_inplace_add, slot_nb_inplace_add,
10313            wrap_binaryfunc, "+="),
10314     IBSLOT(__isub__, nb_inplace_subtract, slot_nb_inplace_subtract,
10315            wrap_binaryfunc, "-="),
10316     IBSLOT(__imul__, nb_inplace_multiply, slot_nb_inplace_multiply,
10317            wrap_binaryfunc, "*="),
10318     IBSLOT(__imod__, nb_inplace_remainder, slot_nb_inplace_remainder,
10319            wrap_binaryfunc, "%="),
10320     IBSLOT(__ipow__, nb_inplace_power, slot_nb_inplace_power,
10321            wrap_ternaryfunc, "**="),
10322     IBSLOT(__ilshift__, nb_inplace_lshift, slot_nb_inplace_lshift,
10323            wrap_binaryfunc, "<<="),
10324     IBSLOT(__irshift__, nb_inplace_rshift, slot_nb_inplace_rshift,
10325            wrap_binaryfunc, ">>="),
10326     IBSLOT(__iand__, nb_inplace_and, slot_nb_inplace_and,
10327            wrap_binaryfunc, "&="),
10328     IBSLOT(__ixor__, nb_inplace_xor, slot_nb_inplace_xor,
10329            wrap_binaryfunc, "^="),
10330     IBSLOT(__ior__, nb_inplace_or, slot_nb_inplace_or,
10331            wrap_binaryfunc, "|="),
10332     BINSLOT(__floordiv__, nb_floor_divide, slot_nb_floor_divide, "//"),
10333     RBINSLOT(__rfloordiv__, nb_floor_divide, slot_nb_floor_divide, "//"),
10334     BINSLOT(__truediv__, nb_true_divide, slot_nb_true_divide, "/"),
10335     RBINSLOT(__rtruediv__, nb_true_divide, slot_nb_true_divide, "/"),
10336     IBSLOT(__ifloordiv__, nb_inplace_floor_divide,
10337            slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
10338     IBSLOT(__itruediv__, nb_inplace_true_divide,
10339            slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
10340     NBSLOT(__index__, nb_index, slot_nb_index, wrap_unaryfunc,
10341            "__index__($self, /)\n--\n\n"
10342            "Return self converted to an integer, if self is suitable "
10343            "for use as an index into a list."),
10344     BINSLOT(__matmul__, nb_matrix_multiply, slot_nb_matrix_multiply,
10345             "@"),
10346     RBINSLOT(__rmatmul__, nb_matrix_multiply, slot_nb_matrix_multiply,
10347              "@"),
10348     IBSLOT(__imatmul__, nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
10349            wrap_binaryfunc, "@="),
10350     MPSLOT(__len__, mp_length, slot_mp_length, wrap_lenfunc,
10351            "__len__($self, /)\n--\n\nReturn len(self)."),
10352     MPSLOT(__getitem__, mp_subscript, slot_mp_subscript,
10353            wrap_binaryfunc,
10354            "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
10355     MPSLOT(__setitem__, mp_ass_subscript, slot_mp_ass_subscript,
10356            wrap_objobjargproc,
10357            "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
10358     MPSLOT(__delitem__, mp_ass_subscript, slot_mp_ass_subscript,
10359            wrap_delitem,
10360            "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
10361 
10362     SQSLOT(__len__, sq_length, slot_sq_length, wrap_lenfunc,
10363            "__len__($self, /)\n--\n\nReturn len(self)."),
10364     /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
10365        The logic in abstract.c always falls back to nb_add/nb_multiply in
10366        this case.  Defining both the nb_* and the sq_* slots to call the
10367        user-defined methods has unexpected side-effects, as shown by
10368        test_descr.notimplemented() */
10369     SQSLOT(__add__, sq_concat, NULL, wrap_binaryfunc,
10370            "__add__($self, value, /)\n--\n\nReturn self+value."),
10371     SQSLOT(__mul__, sq_repeat, NULL, wrap_indexargfunc,
10372            "__mul__($self, value, /)\n--\n\nReturn self*value."),
10373     SQSLOT(__rmul__, sq_repeat, NULL, wrap_indexargfunc,
10374            "__rmul__($self, value, /)\n--\n\nReturn value*self."),
10375     SQSLOT(__getitem__, sq_item, slot_sq_item, wrap_sq_item,
10376            "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
10377     SQSLOT(__setitem__, sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
10378            "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
10379     SQSLOT(__delitem__, sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
10380            "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
10381     SQSLOT(__contains__, sq_contains, slot_sq_contains, wrap_objobjproc,
10382            "__contains__($self, key, /)\n--\n\nReturn bool(key in self)."),
10383     SQSLOT(__iadd__, sq_inplace_concat, NULL,
10384            wrap_binaryfunc,
10385            "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
10386     SQSLOT(__imul__, sq_inplace_repeat, NULL,
10387            wrap_indexargfunc,
10388            "__imul__($self, value, /)\n--\n\nImplement self*=value."),
10389 
10390     {NULL}
10391 };
10392 
10393 /* Given a type pointer and an offset gotten from a slotdef entry, return a
10394    pointer to the actual slot.  This is not quite the same as simply adding
10395    the offset to the type pointer, since it takes care to indirect through the
10396    proper indirection pointer (as_buffer, etc.); it returns NULL if the
10397    indirection pointer is NULL. */
10398 static void **
slotptr(PyTypeObject * type,int ioffset)10399 slotptr(PyTypeObject *type, int ioffset)
10400 {
10401     char *ptr;
10402     long offset = ioffset;
10403 
10404     /* Note: this depends on the order of the members of PyHeapTypeObject! */
10405     assert(offset >= 0);
10406     assert((size_t)offset < offsetof(PyHeapTypeObject, ht_name));
10407     if ((size_t)offset >= offsetof(PyHeapTypeObject, as_buffer)) {
10408         ptr = (char *)type->tp_as_buffer;
10409         offset -= offsetof(PyHeapTypeObject, as_buffer);
10410     }
10411     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
10412         ptr = (char *)type->tp_as_sequence;
10413         offset -= offsetof(PyHeapTypeObject, as_sequence);
10414     }
10415     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
10416         ptr = (char *)type->tp_as_mapping;
10417         offset -= offsetof(PyHeapTypeObject, as_mapping);
10418     }
10419     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
10420         ptr = (char *)type->tp_as_number;
10421         offset -= offsetof(PyHeapTypeObject, as_number);
10422     }
10423     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
10424         ptr = (char *)type->tp_as_async;
10425         offset -= offsetof(PyHeapTypeObject, as_async);
10426     }
10427     else {
10428         ptr = (char *)type;
10429     }
10430     if (ptr != NULL)
10431         ptr += offset;
10432     return (void **)ptr;
10433 }
10434 
10435 /* Return a slot pointer for a given name, but ONLY if the attribute has
10436    exactly one slot function.  The name must be an interned string. */
10437 static void **
resolve_slotdups(PyTypeObject * type,PyObject * name)10438 resolve_slotdups(PyTypeObject *type, PyObject *name)
10439 {
10440     /* XXX Maybe this could be optimized more -- but is it worth it? */
10441 
10442     /* pname and ptrs act as a little cache */
10443     PyInterpreterState *interp = _PyInterpreterState_GET();
10444 #define pname _Py_INTERP_CACHED_OBJECT(interp, type_slots_pname)
10445 #define ptrs _Py_INTERP_CACHED_OBJECT(interp, type_slots_ptrs)
10446     pytype_slotdef *p, **pp;
10447     void **res, **ptr;
10448 
10449     if (pname != name) {
10450         /* Collect all slotdefs that match name into ptrs. */
10451         pname = name;
10452         pp = ptrs;
10453         for (p = slotdefs; p->name_strobj; p++) {
10454             if (p->name_strobj == name)
10455                 *pp++ = p;
10456         }
10457         *pp = NULL;
10458     }
10459 
10460     /* Look in all slots of the type matching the name. If exactly one of these
10461        has a filled-in slot, return a pointer to that slot.
10462        Otherwise, return NULL. */
10463     res = NULL;
10464     for (pp = ptrs; *pp; pp++) {
10465         ptr = slotptr(type, (*pp)->offset);
10466         if (ptr == NULL || *ptr == NULL)
10467             continue;
10468         if (res != NULL)
10469             return NULL;
10470         res = ptr;
10471     }
10472     return res;
10473 #undef pname
10474 #undef ptrs
10475 }
10476 
10477 
10478 /* Common code for update_slots_callback() and fixup_slot_dispatchers().
10479  *
10480  * This is meant to set a "slot" like type->tp_repr or
10481  * type->tp_as_sequence->sq_concat by looking up special methods like
10482  * __repr__ or __add__. The opposite (adding special methods from slots) is
10483  * done by add_operators(), called from PyType_Ready(). Since update_one_slot()
10484  * calls PyType_Ready() if needed, the special methods are already in place.
10485  *
10486  * The special methods corresponding to each slot are defined in the "slotdef"
10487  * array. Note that one slot may correspond to multiple special methods and vice
10488  * versa. For example, tp_richcompare uses 6 methods __lt__, ..., __ge__ and
10489  * tp_as_number->nb_add uses __add__ and __radd__. In the other direction,
10490  * __add__ is used by the number and sequence protocols and __getitem__ by the
10491  * sequence and mapping protocols. This causes a lot of complications.
10492  *
10493  * In detail, update_one_slot() does the following:
10494  *
10495  * First of all, if the slot in question does not exist, return immediately.
10496  * This can happen for example if it's tp_as_number->nb_add but tp_as_number
10497  * is NULL.
10498  *
10499  * For the given slot, we loop over all the special methods with a name
10500  * corresponding to that slot (for example, for tp_descr_set, this would be
10501  * __set__ and __delete__) and we look up these names in the MRO of the type.
10502  * If we don't find any special method, the slot is set to NULL (regardless of
10503  * what was in the slot before).
10504  *
10505  * Suppose that we find exactly one special method. If it's a wrapper_descriptor
10506  * (i.e. a special method calling a slot, for example str.__repr__ which calls
10507  * the tp_repr for the 'str' class) with the correct name ("__repr__" for
10508  * tp_repr), for the right class, calling the right wrapper C function (like
10509  * wrap_unaryfunc for tp_repr), then the slot is set to the slot that the
10510  * wrapper_descriptor originally wrapped. For example, a class inheriting
10511  * from 'str' and not redefining __repr__ will have tp_repr set to the tp_repr
10512  * of 'str'.
10513  * In all other cases where the special method exists, the slot is set to a
10514  * wrapper calling the special method. There is one exception: if the special
10515  * method is a wrapper_descriptor with the correct name but the type has
10516  * precisely one slot set for that name and that slot is not the one that we
10517  * are updating, then NULL is put in the slot (this exception is the only place
10518  * in update_one_slot() where the *existing* slots matter).
10519  *
10520  * When there are multiple special methods for the same slot, the above is
10521  * applied for each special method. As long as the results agree, the common
10522  * resulting slot is applied. If the results disagree, then a wrapper for
10523  * the special methods is installed. This is always safe, but less efficient
10524  * because it uses method lookup instead of direct C calls.
10525  *
10526  * There are some further special cases for specific slots, like supporting
10527  * __hash__ = None for tp_hash and special code for tp_new.
10528  *
10529  * When done, return a pointer to the next slotdef with a different offset,
10530  * because that's convenient for fixup_slot_dispatchers(). This function never
10531  * sets an exception: if an internal error happens (unlikely), it's ignored. */
10532 static pytype_slotdef *
update_one_slot(PyTypeObject * type,pytype_slotdef * p)10533 update_one_slot(PyTypeObject *type, pytype_slotdef *p)
10534 {
10535     ASSERT_TYPE_LOCK_HELD();
10536 
10537     PyObject *descr;
10538     PyWrapperDescrObject *d;
10539 
10540     // The correct specialized C function, like "tp_repr of str" in the
10541     // example above
10542     void *specific = NULL;
10543 
10544     // A generic wrapper that uses method lookup (safe but slow)
10545     void *generic = NULL;
10546 
10547     // Set to 1 if the generic wrapper is necessary
10548     int use_generic = 0;
10549 
10550     int offset = p->offset;
10551     int error;
10552     void **ptr = slotptr(type, offset);
10553 
10554     if (ptr == NULL) {
10555         do {
10556             ++p;
10557         } while (p->offset == offset);
10558         return p;
10559     }
10560     /* We may end up clearing live exceptions below, so make sure it's ours. */
10561     assert(!PyErr_Occurred());
10562     do {
10563         /* Use faster uncached lookup as we won't get any cache hits during type setup. */
10564         descr = find_name_in_mro(type, p->name_strobj, &error);
10565         if (descr == NULL) {
10566             if (error == -1) {
10567                 /* It is unlikely but not impossible that there has been an exception
10568                    during lookup. Since this function originally expected no errors,
10569                    we ignore them here in order to keep up the interface. */
10570                 PyErr_Clear();
10571             }
10572             if (ptr == (void**)&type->tp_iternext) {
10573                 specific = (void *)_PyObject_NextNotImplemented;
10574             }
10575             continue;
10576         }
10577         if (Py_IS_TYPE(descr, &PyWrapperDescr_Type) &&
10578             ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
10579             void **tptr = resolve_slotdups(type, p->name_strobj);
10580             if (tptr == NULL || tptr == ptr)
10581                 generic = p->function;
10582             d = (PyWrapperDescrObject *)descr;
10583             if ((specific == NULL || specific == d->d_wrapped) &&
10584                 d->d_base->wrapper == p->wrapper &&
10585                 is_subtype_with_mro(lookup_tp_mro(type), type, PyDescr_TYPE(d)))
10586             {
10587                 specific = d->d_wrapped;
10588             }
10589             else {
10590                 /* We cannot use the specific slot function because either
10591                    - it is not unique: there are multiple methods for this
10592                      slot and they conflict
10593                    - the signature is wrong (as checked by the ->wrapper
10594                      comparison above)
10595                    - it's wrapping the wrong class
10596                  */
10597                 use_generic = 1;
10598             }
10599         }
10600         else if (Py_IS_TYPE(descr, &PyCFunction_Type) &&
10601                  PyCFunction_GET_FUNCTION(descr) ==
10602                  _PyCFunction_CAST(tp_new_wrapper) &&
10603                  ptr == (void**)&type->tp_new)
10604         {
10605             /* The __new__ wrapper is not a wrapper descriptor,
10606                so must be special-cased differently.
10607                If we don't do this, creating an instance will
10608                always use slot_tp_new which will look up
10609                __new__ in the MRO which will call tp_new_wrapper
10610                which will look through the base classes looking
10611                for a static base and call its tp_new (usually
10612                PyType_GenericNew), after performing various
10613                sanity checks and constructing a new argument
10614                list.  Cut all that nonsense short -- this speeds
10615                up instance creation tremendously. */
10616             specific = (void *)type->tp_new;
10617             /* XXX I'm not 100% sure that there isn't a hole
10618                in this reasoning that requires additional
10619                sanity checks.  I'll buy the first person to
10620                point out a bug in this reasoning a beer. */
10621         }
10622         else if (descr == Py_None &&
10623                  ptr == (void**)&type->tp_hash) {
10624             /* We specifically allow __hash__ to be set to None
10625                to prevent inheritance of the default
10626                implementation from object.__hash__ */
10627             specific = (void *)PyObject_HashNotImplemented;
10628         }
10629         else {
10630             use_generic = 1;
10631             generic = p->function;
10632             if (p->function == slot_tp_call) {
10633                 /* A generic __call__ is incompatible with vectorcall */
10634                 type->tp_flags &= ~Py_TPFLAGS_HAVE_VECTORCALL;
10635             }
10636         }
10637         Py_DECREF(descr);
10638     } while ((++p)->offset == offset);
10639     if (specific && !use_generic)
10640         *ptr = specific;
10641     else
10642         *ptr = generic;
10643     return p;
10644 }
10645 
10646 /* In the type, update the slots whose slotdefs are gathered in the pp array.
10647    This is a callback for update_subclasses(). */
10648 static int
update_slots_callback(PyTypeObject * type,void * data)10649 update_slots_callback(PyTypeObject *type, void *data)
10650 {
10651     ASSERT_TYPE_LOCK_HELD();
10652 
10653     pytype_slotdef **pp = (pytype_slotdef **)data;
10654     for (; *pp; pp++) {
10655         update_one_slot(type, *pp);
10656     }
10657     return 0;
10658 }
10659 
10660 /* Update the slots after assignment to a class (type) attribute. */
10661 static int
update_slot(PyTypeObject * type,PyObject * name)10662 update_slot(PyTypeObject *type, PyObject *name)
10663 {
10664     pytype_slotdef *ptrs[MAX_EQUIV];
10665     pytype_slotdef *p;
10666     pytype_slotdef **pp;
10667     int offset;
10668 
10669     ASSERT_TYPE_LOCK_HELD();
10670     assert(PyUnicode_CheckExact(name));
10671     assert(PyUnicode_CHECK_INTERNED(name));
10672 
10673     pp = ptrs;
10674     for (p = slotdefs; p->name; p++) {
10675         assert(PyUnicode_CheckExact(p->name_strobj));
10676         assert(PyUnicode_CHECK_INTERNED(p->name_strobj));
10677         assert(PyUnicode_CheckExact(name));
10678         /* bpo-40521: Using interned strings. */
10679         if (p->name_strobj == name) {
10680             *pp++ = p;
10681         }
10682     }
10683     *pp = NULL;
10684     for (pp = ptrs; *pp; pp++) {
10685         p = *pp;
10686         offset = p->offset;
10687         while (p > slotdefs && (p-1)->offset == offset)
10688             --p;
10689         *pp = p;
10690     }
10691     if (ptrs[0] == NULL)
10692         return 0; /* Not an attribute that affects any slots */
10693     return update_subclasses(type, name,
10694                              update_slots_callback, (void *)ptrs);
10695 }
10696 
10697 /* Store the proper functions in the slot dispatches at class (type)
10698    definition time, based upon which operations the class overrides in its
10699    dict. */
10700 static void
fixup_slot_dispatchers(PyTypeObject * type)10701 fixup_slot_dispatchers(PyTypeObject *type)
10702 {
10703     // This lock isn't strictly necessary because the type has not been
10704     // exposed to anyone else yet, but update_ont_slot calls find_name_in_mro
10705     // where we'd like to assert that the type is locked.
10706     BEGIN_TYPE_LOCK();
10707 
10708     assert(!PyErr_Occurred());
10709     for (pytype_slotdef *p = slotdefs; p->name; ) {
10710         p = update_one_slot(type, p);
10711     }
10712 
10713     END_TYPE_LOCK();
10714 }
10715 
10716 static void
update_all_slots(PyTypeObject * type)10717 update_all_slots(PyTypeObject* type)
10718 {
10719     pytype_slotdef *p;
10720 
10721     ASSERT_TYPE_LOCK_HELD();
10722 
10723     /* Clear the VALID_VERSION flag of 'type' and all its subclasses. */
10724     PyType_Modified(type);
10725 
10726     for (p = slotdefs; p->name; p++) {
10727         /* update_slot returns int but can't actually fail */
10728         update_slot(type, p->name_strobj);
10729     }
10730 }
10731 
10732 
10733 /* Call __set_name__ on all attributes (including descriptors)
10734   in a newly generated type */
10735 static int
type_new_set_names(PyTypeObject * type)10736 type_new_set_names(PyTypeObject *type)
10737 {
10738     PyObject *dict = lookup_tp_dict(type);
10739     PyObject *names_to_set = PyDict_Copy(dict);
10740     if (names_to_set == NULL) {
10741         return -1;
10742     }
10743 
10744     Py_ssize_t i = 0;
10745     PyObject *key, *value;
10746     while (PyDict_Next(names_to_set, &i, &key, &value)) {
10747         PyObject *set_name = _PyObject_LookupSpecial(value,
10748                                                      &_Py_ID(__set_name__));
10749         if (set_name == NULL) {
10750             if (PyErr_Occurred()) {
10751                 goto error;
10752             }
10753             continue;
10754         }
10755 
10756         PyObject *res = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
10757         Py_DECREF(set_name);
10758 
10759         if (res == NULL) {
10760             _PyErr_FormatNote(
10761                 "Error calling __set_name__ on '%.100s' instance %R "
10762                 "in '%.100s'",
10763                 Py_TYPE(value)->tp_name, key, type->tp_name);
10764             goto error;
10765         }
10766         else {
10767             Py_DECREF(res);
10768         }
10769     }
10770 
10771     Py_DECREF(names_to_set);
10772     return 0;
10773 
10774 error:
10775     Py_DECREF(names_to_set);
10776     return -1;
10777 }
10778 
10779 
10780 /* Call __init_subclass__ on the parent of a newly generated type */
10781 static int
type_new_init_subclass(PyTypeObject * type,PyObject * kwds)10782 type_new_init_subclass(PyTypeObject *type, PyObject *kwds)
10783 {
10784     PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
10785     PyObject *super = PyObject_Vectorcall((PyObject *)&PySuper_Type,
10786                                           args, 2, NULL);
10787     if (super == NULL) {
10788         return -1;
10789     }
10790 
10791     PyObject *func = PyObject_GetAttr(super, &_Py_ID(__init_subclass__));
10792     Py_DECREF(super);
10793     if (func == NULL) {
10794         return -1;
10795     }
10796 
10797     PyObject *result = PyObject_VectorcallDict(func, NULL, 0, kwds);
10798     Py_DECREF(func);
10799     if (result == NULL) {
10800         return -1;
10801     }
10802 
10803     Py_DECREF(result);
10804     return 0;
10805 }
10806 
10807 
10808 /* recurse_down_subclasses() and update_subclasses() are mutually
10809    recursive functions to call a callback for all subclasses,
10810    but refraining from recursing into subclasses that define 'attr_name'. */
10811 
10812 static int
update_subclasses(PyTypeObject * type,PyObject * attr_name,update_callback callback,void * data)10813 update_subclasses(PyTypeObject *type, PyObject *attr_name,
10814                   update_callback callback, void *data)
10815 {
10816     if (callback(type, data) < 0) {
10817         return -1;
10818     }
10819     return recurse_down_subclasses(type, attr_name, callback, data);
10820 }
10821 
10822 static int
recurse_down_subclasses(PyTypeObject * type,PyObject * attr_name,update_callback callback,void * data)10823 recurse_down_subclasses(PyTypeObject *type, PyObject *attr_name,
10824                         update_callback callback, void *data)
10825 {
10826     // It is safe to use a borrowed reference because update_subclasses() is
10827     // only used with update_slots_callback() which doesn't modify
10828     // tp_subclasses.
10829     PyObject *subclasses = lookup_tp_subclasses(type);  // borrowed ref
10830     if (subclasses == NULL) {
10831         return 0;
10832     }
10833     assert(PyDict_CheckExact(subclasses));
10834 
10835     Py_ssize_t i = 0;
10836     PyObject *ref;
10837     while (PyDict_Next(subclasses, &i, NULL, &ref)) {
10838         PyTypeObject *subclass = type_from_ref(ref);
10839         if (subclass == NULL) {
10840             continue;
10841         }
10842 
10843         /* Avoid recursing down into unaffected classes */
10844         PyObject *dict = lookup_tp_dict(subclass);
10845         if (dict != NULL && PyDict_Check(dict)) {
10846             int r = PyDict_Contains(dict, attr_name);
10847             if (r < 0) {
10848                 Py_DECREF(subclass);
10849                 return -1;
10850             }
10851             if (r > 0) {
10852                 Py_DECREF(subclass);
10853                 continue;
10854             }
10855         }
10856 
10857         if (update_subclasses(subclass, attr_name, callback, data) < 0) {
10858             Py_DECREF(subclass);
10859             return -1;
10860         }
10861         Py_DECREF(subclass);
10862     }
10863     return 0;
10864 }
10865 
10866 static int
expect_manually_inherited(PyTypeObject * type,void ** slot)10867 expect_manually_inherited(PyTypeObject *type, void **slot)
10868 {
10869     PyObject *typeobj = (PyObject *)type;
10870     if (slot == (void *)&type->tp_init) {
10871         /* This is a best-effort list of builtin exception types
10872            that have their own tp_init function. */
10873         if (typeobj != PyExc_BaseException
10874             && typeobj != PyExc_BaseExceptionGroup
10875             && typeobj != PyExc_ImportError
10876             && typeobj != PyExc_NameError
10877             && typeobj != PyExc_OSError
10878             && typeobj != PyExc_StopIteration
10879             && typeobj != PyExc_SyntaxError
10880             && typeobj != PyExc_UnicodeDecodeError
10881             && typeobj != PyExc_UnicodeEncodeError
10882 
10883             && type != &PyBool_Type
10884             && type != &PyBytes_Type
10885             && type != &PyMemoryView_Type
10886             && type != &PyComplex_Type
10887             && type != &PyEnum_Type
10888             && type != &PyFilter_Type
10889             && type != &PyFloat_Type
10890             && type != &PyFrozenSet_Type
10891             && type != &PyLong_Type
10892             && type != &PyMap_Type
10893             && type != &PyRange_Type
10894             && type != &PyReversed_Type
10895             && type != &PySlice_Type
10896             && type != &PyTuple_Type
10897             && type != &PyUnicode_Type
10898             && type != &PyZip_Type)
10899 
10900         {
10901             return 1;
10902         }
10903     }
10904     else if (slot == (void *)&type->tp_str) {
10905         /* This is a best-effort list of builtin exception types
10906            that have their own tp_str function. */
10907         if (typeobj == PyExc_AttributeError || typeobj == PyExc_NameError) {
10908             return 1;
10909         }
10910     }
10911     else if (slot == (void *)&type->tp_getattr
10912              || slot == (void *)&type->tp_getattro)
10913     {
10914         /* This is a best-effort list of builtin types
10915            that have their own tp_getattr function. */
10916         if (typeobj == PyExc_BaseException
10917             || type == &PyByteArray_Type
10918             || type == &PyBytes_Type
10919             || type == &PyComplex_Type
10920             || type == &PyDict_Type
10921             || type == &PyEnum_Type
10922             || type == &PyFilter_Type
10923             || type == &PyLong_Type
10924             || type == &PyList_Type
10925             || type == &PyMap_Type
10926             || type == &PyMemoryView_Type
10927             || type == &PyProperty_Type
10928             || type == &PyRange_Type
10929             || type == &PyReversed_Type
10930             || type == &PySet_Type
10931             || type == &PySlice_Type
10932             || type == &PySuper_Type
10933             || type == &PyTuple_Type
10934             || type == &PyZip_Type)
10935         {
10936             return 1;
10937         }
10938     }
10939 
10940     /* It must be inherited (see type_ready_inherit()).. */
10941     return 0;
10942 }
10943 
10944 /* This function is called by PyType_Ready() to populate the type's
10945    dictionary with method descriptors for function slots.  For each
10946    function slot (like tp_repr) that's defined in the type, one or more
10947    corresponding descriptors are added in the type's tp_dict dictionary
10948    under the appropriate name (like __repr__).  Some function slots
10949    cause more than one descriptor to be added (for example, the nb_add
10950    slot adds both __add__ and __radd__ descriptors) and some function
10951    slots compete for the same descriptor (for example both sq_item and
10952    mp_subscript generate a __getitem__ descriptor).
10953 
10954    In the latter case, the first slotdef entry encountered wins.  Since
10955    slotdef entries are sorted by the offset of the slot in the
10956    PyHeapTypeObject, this gives us some control over disambiguating
10957    between competing slots: the members of PyHeapTypeObject are listed
10958    from most general to least general, so the most general slot is
10959    preferred.  In particular, because as_mapping comes before as_sequence,
10960    for a type that defines both mp_subscript and sq_item, mp_subscript
10961    wins.
10962 
10963    This only adds new descriptors and doesn't overwrite entries in
10964    tp_dict that were previously defined.  The descriptors contain a
10965    reference to the C function they must call, so that it's safe if they
10966    are copied into a subtype's __dict__ and the subtype has a different
10967    C function in its slot -- calling the method defined by the
10968    descriptor will call the C function that was used to create it,
10969    rather than the C function present in the slot when it is called.
10970    (This is important because a subtype may have a C function in the
10971    slot that calls the method from the dictionary, and we want to avoid
10972    infinite recursion here.) */
10973 
10974 static int
add_operators(PyTypeObject * type)10975 add_operators(PyTypeObject *type)
10976 {
10977     PyObject *dict = lookup_tp_dict(type);
10978     pytype_slotdef *p;
10979     PyObject *descr;
10980     void **ptr;
10981 
10982     for (p = slotdefs; p->name; p++) {
10983         if (p->wrapper == NULL)
10984             continue;
10985         ptr = slotptr(type, p->offset);
10986         if (!ptr || !*ptr)
10987             continue;
10988         if (type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN
10989             && type->tp_base != NULL)
10990         {
10991             /* Also ignore when the type slot has been inherited. */
10992             void **ptr_base = slotptr(type->tp_base, p->offset);
10993             if (ptr_base && *ptr == *ptr_base) {
10994                 /* Ideally we would always ignore any manually inherited
10995                    slots, Which would mean inheriting the slot wrapper
10996                    using normal attribute lookup rather than keeping
10997                    a distinct copy.  However, that would introduce
10998                    a slight change in behavior that could break
10999                    existing code.
11000 
11001                    In the meantime, look the other way when the definition
11002                    explicitly inherits the slot. */
11003                 if (!expect_manually_inherited(type, ptr)) {
11004                     continue;
11005                 }
11006             }
11007         }
11008         int r = PyDict_Contains(dict, p->name_strobj);
11009         if (r > 0)
11010             continue;
11011         if (r < 0) {
11012             return -1;
11013         }
11014         if (*ptr == (void *)PyObject_HashNotImplemented) {
11015             /* Classes may prevent the inheritance of the tp_hash
11016                slot by storing PyObject_HashNotImplemented in it. Make it
11017                visible as a None value for the __hash__ attribute. */
11018             if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
11019                 return -1;
11020         }
11021         else {
11022             descr = PyDescr_NewWrapper(type, p, *ptr);
11023             if (descr == NULL)
11024                 return -1;
11025             if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
11026                 Py_DECREF(descr);
11027                 return -1;
11028             }
11029             Py_DECREF(descr);
11030         }
11031     }
11032     return 0;
11033 }
11034 
11035 
11036 /* Cooperative 'super' */
11037 
11038 typedef struct {
11039     PyObject_HEAD
11040     PyTypeObject *type;
11041     PyObject *obj;
11042     PyTypeObject *obj_type;
11043 } superobject;
11044 
11045 static PyMemberDef super_members[] = {
11046     {"__thisclass__", _Py_T_OBJECT, offsetof(superobject, type), Py_READONLY,
11047      "the class invoking super()"},
11048     {"__self__",  _Py_T_OBJECT, offsetof(superobject, obj), Py_READONLY,
11049      "the instance invoking super(); may be None"},
11050     {"__self_class__", _Py_T_OBJECT, offsetof(superobject, obj_type), Py_READONLY,
11051      "the type of the instance invoking super(); may be None"},
11052     {0}
11053 };
11054 
11055 static void
super_dealloc(PyObject * self)11056 super_dealloc(PyObject *self)
11057 {
11058     superobject *su = (superobject *)self;
11059 
11060     _PyObject_GC_UNTRACK(self);
11061     Py_XDECREF(su->obj);
11062     Py_XDECREF(su->type);
11063     Py_XDECREF(su->obj_type);
11064     Py_TYPE(self)->tp_free(self);
11065 }
11066 
11067 static PyObject *
super_repr(PyObject * self)11068 super_repr(PyObject *self)
11069 {
11070     superobject *su = (superobject *)self;
11071 
11072     if (su->obj_type)
11073         return PyUnicode_FromFormat(
11074             "<super: <class '%s'>, <%s object>>",
11075             su->type ? su->type->tp_name : "NULL",
11076             su->obj_type->tp_name);
11077     else
11078         return PyUnicode_FromFormat(
11079             "<super: <class '%s'>, NULL>",
11080             su->type ? su->type->tp_name : "NULL");
11081 }
11082 
11083 /* Do a super lookup without executing descriptors or falling back to getattr
11084 on the super object itself.
11085 
11086 May return NULL with or without an exception set, like PyDict_GetItemWithError. */
11087 static PyObject *
_super_lookup_descr(PyTypeObject * su_type,PyTypeObject * su_obj_type,PyObject * name)11088 _super_lookup_descr(PyTypeObject *su_type, PyTypeObject *su_obj_type, PyObject *name)
11089 {
11090     PyObject *mro, *res;
11091     Py_ssize_t i, n;
11092 
11093     BEGIN_TYPE_LOCK();
11094     mro = lookup_tp_mro(su_obj_type);
11095     /* keep a strong reference to mro because su_obj_type->tp_mro can be
11096        replaced during PyDict_GetItemRef(dict, name, &res) and because
11097        another thread can modify it after we end the critical section
11098        below  */
11099     Py_XINCREF(mro);
11100     END_TYPE_LOCK();
11101 
11102     if (mro == NULL)
11103         return NULL;
11104 
11105     assert(PyTuple_Check(mro));
11106     n = PyTuple_GET_SIZE(mro);
11107 
11108     /* No need to check the last one: it's gonna be skipped anyway.  */
11109     for (i = 0; i+1 < n; i++) {
11110         if ((PyObject *)(su_type) == PyTuple_GET_ITEM(mro, i))
11111             break;
11112     }
11113     i++;  /* skip su->type (if any)  */
11114     if (i >= n) {
11115         Py_DECREF(mro);
11116         return NULL;
11117     }
11118 
11119     do {
11120         PyObject *obj = PyTuple_GET_ITEM(mro, i);
11121         PyObject *dict = lookup_tp_dict(_PyType_CAST(obj));
11122         assert(dict != NULL && PyDict_Check(dict));
11123 
11124         if (PyDict_GetItemRef(dict, name, &res) != 0) {
11125             // found or error
11126             Py_DECREF(mro);
11127             return res;
11128         }
11129 
11130         i++;
11131     } while (i < n);
11132     Py_DECREF(mro);
11133     return NULL;
11134 }
11135 
11136 // if `method` is non-NULL, we are looking for a method descriptor,
11137 // and setting `*method = 1` means we found one.
11138 static PyObject *
do_super_lookup(superobject * su,PyTypeObject * su_type,PyObject * su_obj,PyTypeObject * su_obj_type,PyObject * name,int * method)11139 do_super_lookup(superobject *su, PyTypeObject *su_type, PyObject *su_obj,
11140                 PyTypeObject *su_obj_type, PyObject *name, int *method)
11141 {
11142     PyObject *res;
11143     int temp_su = 0;
11144 
11145     if (su_obj_type == NULL) {
11146         goto skip;
11147     }
11148 
11149     res = _super_lookup_descr(su_type, su_obj_type, name);
11150     if (res != NULL) {
11151         if (method && _PyType_HasFeature(Py_TYPE(res), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
11152             *method = 1;
11153         }
11154         else {
11155             descrgetfunc f = Py_TYPE(res)->tp_descr_get;
11156             if (f != NULL) {
11157                 PyObject *res2;
11158                 res2 = f(res,
11159                     /* Only pass 'obj' param if this is instance-mode super
11160                     (See SF ID #743627)  */
11161                     (su_obj == (PyObject *)su_obj_type) ? NULL : su_obj,
11162                     (PyObject *)su_obj_type);
11163                 Py_SETREF(res, res2);
11164             }
11165         }
11166 
11167         return res;
11168     }
11169     else if (PyErr_Occurred()) {
11170         return NULL;
11171     }
11172 
11173   skip:
11174     if (su == NULL) {
11175         PyObject *args[] = {(PyObject *)su_type, su_obj};
11176         su = (superobject *)PyObject_Vectorcall((PyObject *)&PySuper_Type, args, 2, NULL);
11177         if (su == NULL) {
11178             return NULL;
11179         }
11180         temp_su = 1;
11181     }
11182     res = PyObject_GenericGetAttr((PyObject *)su, name);
11183     if (temp_su) {
11184         Py_DECREF(su);
11185     }
11186     return res;
11187 }
11188 
11189 static PyObject *
super_getattro(PyObject * self,PyObject * name)11190 super_getattro(PyObject *self, PyObject *name)
11191 {
11192     superobject *su = (superobject *)self;
11193 
11194     /* We want __class__ to return the class of the super object
11195        (i.e. super, or a subclass), not the class of su->obj. */
11196     if (PyUnicode_Check(name) &&
11197         PyUnicode_GET_LENGTH(name) == 9 &&
11198         _PyUnicode_Equal(name, &_Py_ID(__class__)))
11199         return PyObject_GenericGetAttr(self, name);
11200 
11201     return do_super_lookup(su, su->type, su->obj, su->obj_type, name, NULL);
11202 }
11203 
11204 static PyTypeObject *
supercheck(PyTypeObject * type,PyObject * obj)11205 supercheck(PyTypeObject *type, PyObject *obj)
11206 {
11207     /* Check that a super() call makes sense.  Return a type object.
11208 
11209        obj can be a class, or an instance of one:
11210 
11211        - If it is a class, it must be a subclass of 'type'.      This case is
11212          used for class methods; the return value is obj.
11213 
11214        - If it is an instance, it must be an instance of 'type'.  This is
11215          the normal case; the return value is obj.__class__.
11216 
11217        But... when obj is an instance, we want to allow for the case where
11218        Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
11219        This will allow using super() with a proxy for obj.
11220     */
11221 
11222     /* Check for first bullet above (special case) */
11223     if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
11224         return (PyTypeObject *)Py_NewRef(obj);
11225     }
11226 
11227     /* Normal case */
11228     if (PyType_IsSubtype(Py_TYPE(obj), type)) {
11229         return (PyTypeObject*)Py_NewRef(Py_TYPE(obj));
11230     }
11231     else {
11232         /* Try the slow way */
11233         PyObject *class_attr;
11234 
11235         if (PyObject_GetOptionalAttr(obj, &_Py_ID(__class__), &class_attr) < 0) {
11236             return NULL;
11237         }
11238         if (class_attr != NULL &&
11239             PyType_Check(class_attr) &&
11240             (PyTypeObject *)class_attr != Py_TYPE(obj))
11241         {
11242             int ok = PyType_IsSubtype(
11243                 (PyTypeObject *)class_attr, type);
11244             if (ok) {
11245                 return (PyTypeObject *)class_attr;
11246             }
11247         }
11248         Py_XDECREF(class_attr);
11249     }
11250 
11251     const char *type_or_instance, *obj_str;
11252 
11253     if (PyType_Check(obj)) {
11254         type_or_instance = "type";
11255         obj_str = ((PyTypeObject*)obj)->tp_name;
11256     }
11257     else {
11258         type_or_instance = "instance of";
11259         obj_str = Py_TYPE(obj)->tp_name;
11260     }
11261 
11262     PyErr_Format(PyExc_TypeError,
11263                 "super(type, obj): obj (%s %.200s) is not "
11264                 "an instance or subtype of type (%.200s).",
11265                 type_or_instance, obj_str, type->tp_name);
11266 
11267     return NULL;
11268 }
11269 
11270 PyObject *
_PySuper_Lookup(PyTypeObject * su_type,PyObject * su_obj,PyObject * name,int * method)11271 _PySuper_Lookup(PyTypeObject *su_type, PyObject *su_obj, PyObject *name, int *method)
11272 {
11273     PyTypeObject *su_obj_type = supercheck(su_type, su_obj);
11274     if (su_obj_type == NULL) {
11275         return NULL;
11276     }
11277     PyObject *res = do_super_lookup(NULL, su_type, su_obj, su_obj_type, name, method);
11278     Py_DECREF(su_obj_type);
11279     return res;
11280 }
11281 
11282 static PyObject *
super_descr_get(PyObject * self,PyObject * obj,PyObject * type)11283 super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
11284 {
11285     superobject *su = (superobject *)self;
11286     superobject *newobj;
11287 
11288     if (obj == NULL || obj == Py_None || su->obj != NULL) {
11289         /* Not binding to an object, or already bound */
11290         return Py_NewRef(self);
11291     }
11292     if (!Py_IS_TYPE(su, &PySuper_Type))
11293         /* If su is an instance of a (strict) subclass of super,
11294            call its type */
11295         return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
11296                                             su->type, obj, NULL);
11297     else {
11298         /* Inline the common case */
11299         PyTypeObject *obj_type = supercheck(su->type, obj);
11300         if (obj_type == NULL)
11301             return NULL;
11302         newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
11303                                                  NULL, NULL);
11304         if (newobj == NULL) {
11305             Py_DECREF(obj_type);
11306             return NULL;
11307         }
11308         newobj->type = (PyTypeObject*)Py_NewRef(su->type);
11309         newobj->obj = Py_NewRef(obj);
11310         newobj->obj_type = obj_type;
11311         return (PyObject *)newobj;
11312     }
11313 }
11314 
11315 static int
super_init_without_args(_PyInterpreterFrame * cframe,PyCodeObject * co,PyTypeObject ** type_p,PyObject ** obj_p)11316 super_init_without_args(_PyInterpreterFrame *cframe, PyCodeObject *co,
11317                         PyTypeObject **type_p, PyObject **obj_p)
11318 {
11319     if (co->co_argcount == 0) {
11320         PyErr_SetString(PyExc_RuntimeError,
11321                         "super(): no arguments");
11322         return -1;
11323     }
11324 
11325     assert(_PyFrame_GetCode(cframe)->co_nlocalsplus > 0);
11326     PyObject *firstarg = _PyFrame_GetLocalsArray(cframe)[0];
11327     // The first argument might be a cell.
11328     if (firstarg != NULL && (_PyLocals_GetKind(co->co_localspluskinds, 0) & CO_FAST_CELL)) {
11329         // "firstarg" is a cell here unless (very unlikely) super()
11330         // was called from the C-API before the first MAKE_CELL op.
11331         if (_PyInterpreterFrame_LASTI(cframe) >= 0) {
11332             // MAKE_CELL and COPY_FREE_VARS have no quickened forms, so no need
11333             // to use _PyOpcode_Deopt here:
11334             assert(_PyCode_CODE(co)[0].op.code == MAKE_CELL ||
11335                    _PyCode_CODE(co)[0].op.code == COPY_FREE_VARS);
11336             assert(PyCell_Check(firstarg));
11337             firstarg = PyCell_GET(firstarg);
11338         }
11339     }
11340     if (firstarg == NULL) {
11341         PyErr_SetString(PyExc_RuntimeError,
11342                         "super(): arg[0] deleted");
11343         return -1;
11344     }
11345 
11346     // Look for __class__ in the free vars.
11347     PyTypeObject *type = NULL;
11348     int i = PyUnstable_Code_GetFirstFree(co);
11349     for (; i < co->co_nlocalsplus; i++) {
11350         assert((_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_FREE) != 0);
11351         PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
11352         assert(PyUnicode_Check(name));
11353         if (_PyUnicode_Equal(name, &_Py_ID(__class__))) {
11354             PyObject *cell = _PyFrame_GetLocalsArray(cframe)[i];
11355             if (cell == NULL || !PyCell_Check(cell)) {
11356                 PyErr_SetString(PyExc_RuntimeError,
11357                   "super(): bad __class__ cell");
11358                 return -1;
11359             }
11360             type = (PyTypeObject *) PyCell_GET(cell);
11361             if (type == NULL) {
11362                 PyErr_SetString(PyExc_RuntimeError,
11363                   "super(): empty __class__ cell");
11364                 return -1;
11365             }
11366             if (!PyType_Check(type)) {
11367                 PyErr_Format(PyExc_RuntimeError,
11368                   "super(): __class__ is not a type (%s)",
11369                   Py_TYPE(type)->tp_name);
11370                 return -1;
11371             }
11372             break;
11373         }
11374     }
11375     if (type == NULL) {
11376         PyErr_SetString(PyExc_RuntimeError,
11377                         "super(): __class__ cell not found");
11378         return -1;
11379     }
11380 
11381     *type_p = type;
11382     *obj_p = firstarg;
11383     return 0;
11384 }
11385 
11386 static int super_init_impl(PyObject *self, PyTypeObject *type, PyObject *obj);
11387 
11388 static int
super_init(PyObject * self,PyObject * args,PyObject * kwds)11389 super_init(PyObject *self, PyObject *args, PyObject *kwds)
11390 {
11391     PyTypeObject *type = NULL;
11392     PyObject *obj = NULL;
11393 
11394     if (!_PyArg_NoKeywords("super", kwds))
11395         return -1;
11396     if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
11397         return -1;
11398     if (super_init_impl(self, type, obj) < 0) {
11399         return -1;
11400     }
11401     return 0;
11402 }
11403 
11404 static inline int
super_init_impl(PyObject * self,PyTypeObject * type,PyObject * obj)11405 super_init_impl(PyObject *self, PyTypeObject *type, PyObject *obj) {
11406     superobject *su = (superobject *)self;
11407     PyTypeObject *obj_type = NULL;
11408     if (type == NULL) {
11409         /* Call super(), without args -- fill in from __class__
11410            and first local variable on the stack. */
11411         PyThreadState *tstate = _PyThreadState_GET();
11412         _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
11413         if (frame == NULL) {
11414             PyErr_SetString(PyExc_RuntimeError,
11415                             "super(): no current frame");
11416             return -1;
11417         }
11418         int res = super_init_without_args(frame, _PyFrame_GetCode(frame), &type, &obj);
11419 
11420         if (res < 0) {
11421             return -1;
11422         }
11423     }
11424 
11425     if (obj == Py_None)
11426         obj = NULL;
11427     if (obj != NULL) {
11428         obj_type = supercheck(type, obj);
11429         if (obj_type == NULL)
11430             return -1;
11431         Py_INCREF(obj);
11432     }
11433     Py_XSETREF(su->type, (PyTypeObject*)Py_NewRef(type));
11434     Py_XSETREF(su->obj, obj);
11435     Py_XSETREF(su->obj_type, obj_type);
11436     return 0;
11437 }
11438 
11439 PyDoc_STRVAR(super_doc,
11440 "super() -> same as super(__class__, <first argument>)\n"
11441 "super(type) -> unbound super object\n"
11442 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
11443 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
11444 "Typical use to call a cooperative superclass method:\n"
11445 "class C(B):\n"
11446 "    def meth(self, arg):\n"
11447 "        super().meth(arg)\n"
11448 "This works for class methods too:\n"
11449 "class C(B):\n"
11450 "    @classmethod\n"
11451 "    def cmeth(cls, arg):\n"
11452 "        super().cmeth(arg)\n");
11453 
11454 static int
super_traverse(PyObject * self,visitproc visit,void * arg)11455 super_traverse(PyObject *self, visitproc visit, void *arg)
11456 {
11457     superobject *su = (superobject *)self;
11458 
11459     Py_VISIT(su->obj);
11460     Py_VISIT(su->type);
11461     Py_VISIT(su->obj_type);
11462 
11463     return 0;
11464 }
11465 
11466 static PyObject *
super_vectorcall(PyObject * self,PyObject * const * args,size_t nargsf,PyObject * kwnames)11467 super_vectorcall(PyObject *self, PyObject *const *args,
11468     size_t nargsf, PyObject *kwnames)
11469 {
11470     assert(PyType_Check(self));
11471     if (!_PyArg_NoKwnames("super", kwnames)) {
11472         return NULL;
11473     }
11474     Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
11475     if (!_PyArg_CheckPositional("super()", nargs, 0, 2)) {
11476         return NULL;
11477     }
11478     PyTypeObject *type = NULL;
11479     PyObject *obj = NULL;
11480     PyTypeObject *self_type = (PyTypeObject *)self;
11481     PyObject *su = self_type->tp_alloc(self_type, 0);
11482     if (su == NULL) {
11483         return NULL;
11484     }
11485     // 1 or 2 argument form super().
11486     if (nargs != 0) {
11487         PyObject *arg0 = args[0];
11488         if (!PyType_Check(arg0)) {
11489             PyErr_Format(PyExc_TypeError,
11490                 "super() argument 1 must be a type, not %.200s", Py_TYPE(arg0)->tp_name);
11491             goto fail;
11492         }
11493         type = (PyTypeObject *)arg0;
11494     }
11495     if (nargs == 2) {
11496         obj = args[1];
11497     }
11498     if (super_init_impl(su, type, obj) < 0) {
11499         goto fail;
11500     }
11501     return su;
11502 fail:
11503     Py_DECREF(su);
11504     return NULL;
11505 }
11506 
11507 PyTypeObject PySuper_Type = {
11508     PyVarObject_HEAD_INIT(&PyType_Type, 0)
11509     "super",                                    /* tp_name */
11510     sizeof(superobject),                        /* tp_basicsize */
11511     0,                                          /* tp_itemsize */
11512     /* methods */
11513     super_dealloc,                              /* tp_dealloc */
11514     0,                                          /* tp_vectorcall_offset */
11515     0,                                          /* tp_getattr */
11516     0,                                          /* tp_setattr */
11517     0,                                          /* tp_as_async */
11518     super_repr,                                 /* tp_repr */
11519     0,                                          /* tp_as_number */
11520     0,                                          /* tp_as_sequence */
11521     0,                                          /* tp_as_mapping */
11522     0,                                          /* tp_hash */
11523     0,                                          /* tp_call */
11524     0,                                          /* tp_str */
11525     super_getattro,                             /* tp_getattro */
11526     0,                                          /* tp_setattro */
11527     0,                                          /* tp_as_buffer */
11528     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
11529         Py_TPFLAGS_BASETYPE,                    /* tp_flags */
11530     super_doc,                                  /* tp_doc */
11531     super_traverse,                             /* tp_traverse */
11532     0,                                          /* tp_clear */
11533     0,                                          /* tp_richcompare */
11534     0,                                          /* tp_weaklistoffset */
11535     0,                                          /* tp_iter */
11536     0,                                          /* tp_iternext */
11537     0,                                          /* tp_methods */
11538     super_members,                              /* tp_members */
11539     0,                                          /* tp_getset */
11540     0,                                          /* tp_base */
11541     0,                                          /* tp_dict */
11542     super_descr_get,                            /* tp_descr_get */
11543     0,                                          /* tp_descr_set */
11544     0,                                          /* tp_dictoffset */
11545     super_init,                                 /* tp_init */
11546     PyType_GenericAlloc,                        /* tp_alloc */
11547     PyType_GenericNew,                          /* tp_new */
11548     PyObject_GC_Del,                            /* tp_free */
11549     .tp_vectorcall = (vectorcallfunc)super_vectorcall,
11550 };
11551