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