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