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