• 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 n = PyTuple_GET_SIZE(mro);
3711     for (Py_ssize_t i = 0; i < n; i++) {
3712         PyObject *super = PyTuple_GET_ITEM(mro, i);
3713         if(!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) {
3714             // Static types in the MRO need to be skipped
3715             continue;
3716         }
3717 
3718         PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
3719         PyObject *module = ht->ht_module;
3720         if (module && _PyModule_GetDef(module) == def) {
3721             return module;
3722         }
3723     }
3724 
3725     PyErr_Format(
3726         PyExc_TypeError,
3727         "_PyType_GetModuleByDef: No superclass of '%s' has the given module",
3728         type->tp_name);
3729     return NULL;
3730 }
3731 
3732 
3733 /* Internal API to look for a name through the MRO, bypassing the method cache.
3734    This returns a borrowed reference, and might set an exception.
3735    'error' is set to: -1: error with exception; 1: error without exception; 0: ok */
3736 static PyObject *
find_name_in_mro(PyTypeObject * type,PyObject * name,int * error)3737 find_name_in_mro(PyTypeObject *type, PyObject *name, int *error)
3738 {
3739     Py_ssize_t i, n;
3740     PyObject *mro, *res, *base, *dict;
3741     Py_hash_t hash;
3742 
3743     if (!PyUnicode_CheckExact(name) ||
3744         (hash = ((PyASCIIObject *) name)->hash) == -1)
3745     {
3746         hash = PyObject_Hash(name);
3747         if (hash == -1) {
3748             *error = -1;
3749             return NULL;
3750         }
3751     }
3752 
3753     /* Look in tp_dict of types in MRO */
3754     mro = type->tp_mro;
3755 
3756     if (mro == NULL) {
3757         if ((type->tp_flags & Py_TPFLAGS_READYING) == 0) {
3758             if (PyType_Ready(type) < 0) {
3759                 *error = -1;
3760                 return NULL;
3761             }
3762             mro = type->tp_mro;
3763         }
3764         if (mro == NULL) {
3765             *error = 1;
3766             return NULL;
3767         }
3768     }
3769 
3770     res = NULL;
3771     /* Keep a strong reference to mro because type->tp_mro can be replaced
3772        during dict lookup, e.g. when comparing to non-string keys. */
3773     Py_INCREF(mro);
3774     assert(PyTuple_Check(mro));
3775     n = PyTuple_GET_SIZE(mro);
3776     for (i = 0; i < n; i++) {
3777         base = PyTuple_GET_ITEM(mro, i);
3778         assert(PyType_Check(base));
3779         dict = ((PyTypeObject *)base)->tp_dict;
3780         assert(dict && PyDict_Check(dict));
3781         res = _PyDict_GetItem_KnownHash(dict, name, hash);
3782         if (res != NULL)
3783             break;
3784         if (PyErr_Occurred()) {
3785             *error = -1;
3786             goto done;
3787         }
3788     }
3789     *error = 0;
3790 done:
3791     Py_DECREF(mro);
3792     return res;
3793 }
3794 
3795 /* Internal API to look for a name through the MRO.
3796    This returns a borrowed reference, and doesn't set an exception! */
3797 PyObject *
_PyType_Lookup(PyTypeObject * type,PyObject * name)3798 _PyType_Lookup(PyTypeObject *type, PyObject *name)
3799 {
3800     PyObject *res;
3801     int error;
3802 
3803     unsigned int h = MCACHE_HASH_METHOD(type, name);
3804     struct type_cache *cache = get_type_cache();
3805     struct type_cache_entry *entry = &cache->hashtable[h];
3806     if (entry->version == type->tp_version_tag &&
3807         entry->name == name) {
3808 #if MCACHE_STATS
3809         cache->hits++;
3810 #endif
3811         assert(_PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG));
3812         return entry->value;
3813     }
3814 
3815     /* We may end up clearing live exceptions below, so make sure it's ours. */
3816     assert(!PyErr_Occurred());
3817 
3818     res = find_name_in_mro(type, name, &error);
3819     /* Only put NULL results into cache if there was no error. */
3820     if (error) {
3821         /* It's not ideal to clear the error condition,
3822            but this function is documented as not setting
3823            an exception, and I don't want to change that.
3824            E.g., when PyType_Ready() can't proceed, it won't
3825            set the "ready" flag, so future attempts to ready
3826            the same type will call it again -- hopefully
3827            in a context that propagates the exception out.
3828         */
3829         if (error == -1) {
3830             PyErr_Clear();
3831         }
3832         return NULL;
3833     }
3834 
3835     if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(cache, type)) {
3836         h = MCACHE_HASH_METHOD(type, name);
3837         struct type_cache_entry *entry = &cache->hashtable[h];
3838         entry->version = type->tp_version_tag;
3839         entry->value = res;  /* borrowed */
3840         assert(((PyASCIIObject *)(name))->hash != -1);
3841 #if MCACHE_STATS
3842         if (entry->name != Py_None && entry->name != name) {
3843             cache->collisions++;
3844         }
3845         else {
3846             cache->misses++;
3847         }
3848 #endif
3849         assert(_PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG));
3850         Py_SETREF(entry->name, Py_NewRef(name));
3851     }
3852     return res;
3853 }
3854 
3855 PyObject *
_PyType_LookupId(PyTypeObject * type,struct _Py_Identifier * name)3856 _PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
3857 {
3858     PyObject *oname;
3859     oname = _PyUnicode_FromId(name);   /* borrowed */
3860     if (oname == NULL)
3861         return NULL;
3862     return _PyType_Lookup(type, oname);
3863 }
3864 
3865 /* Check if the "readied" PyUnicode name
3866    is a double-underscore special name. */
3867 static int
is_dunder_name(PyObject * name)3868 is_dunder_name(PyObject *name)
3869 {
3870     Py_ssize_t length = PyUnicode_GET_LENGTH(name);
3871     int kind = PyUnicode_KIND(name);
3872     /* Special names contain at least "__x__" and are always ASCII. */
3873     if (length > 4 && kind == PyUnicode_1BYTE_KIND) {
3874         const Py_UCS1 *characters = PyUnicode_1BYTE_DATA(name);
3875         return (
3876             ((characters[length-2] == '_') && (characters[length-1] == '_')) &&
3877             ((characters[0] == '_') && (characters[1] == '_'))
3878         );
3879     }
3880     return 0;
3881 }
3882 
3883 /* This is similar to PyObject_GenericGetAttr(),
3884    but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
3885 static PyObject *
type_getattro(PyTypeObject * type,PyObject * name)3886 type_getattro(PyTypeObject *type, PyObject *name)
3887 {
3888     PyTypeObject *metatype = Py_TYPE(type);
3889     PyObject *meta_attribute, *attribute;
3890     descrgetfunc meta_get;
3891     PyObject* res;
3892 
3893     if (!PyUnicode_Check(name)) {
3894         PyErr_Format(PyExc_TypeError,
3895                      "attribute name must be string, not '%.200s'",
3896                      Py_TYPE(name)->tp_name);
3897         return NULL;
3898     }
3899 
3900     /* Initialize this type (we'll assume the metatype is initialized) */
3901     if (!_PyType_IsReady(type)) {
3902         if (PyType_Ready(type) < 0)
3903             return NULL;
3904     }
3905 
3906     /* No readable descriptor found yet */
3907     meta_get = NULL;
3908 
3909     /* Look for the attribute in the metatype */
3910     meta_attribute = _PyType_Lookup(metatype, name);
3911 
3912     if (meta_attribute != NULL) {
3913         Py_INCREF(meta_attribute);
3914         meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
3915 
3916         if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
3917             /* Data descriptors implement tp_descr_set to intercept
3918              * writes. Assume the attribute is not overridden in
3919              * type's tp_dict (and bases): call the descriptor now.
3920              */
3921             res = meta_get(meta_attribute, (PyObject *)type,
3922                            (PyObject *)metatype);
3923             Py_DECREF(meta_attribute);
3924             return res;
3925         }
3926     }
3927 
3928     /* No data descriptor found on metatype. Look in tp_dict of this
3929      * type and its bases */
3930     attribute = _PyType_Lookup(type, name);
3931     if (attribute != NULL) {
3932         /* Implement descriptor functionality, if any */
3933         Py_INCREF(attribute);
3934         descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
3935 
3936         Py_XDECREF(meta_attribute);
3937 
3938         if (local_get != NULL) {
3939             /* NULL 2nd argument indicates the descriptor was
3940              * found on the target object itself (or a base)  */
3941             res = local_get(attribute, (PyObject *)NULL,
3942                             (PyObject *)type);
3943             Py_DECREF(attribute);
3944             return res;
3945         }
3946 
3947         return attribute;
3948     }
3949 
3950     /* No attribute found in local __dict__ (or bases): use the
3951      * descriptor from the metatype, if any */
3952     if (meta_get != NULL) {
3953         PyObject *res;
3954         res = meta_get(meta_attribute, (PyObject *)type,
3955                        (PyObject *)metatype);
3956         Py_DECREF(meta_attribute);
3957         return res;
3958     }
3959 
3960     /* If an ordinary attribute was found on the metatype, return it now */
3961     if (meta_attribute != NULL) {
3962         return meta_attribute;
3963     }
3964 
3965     /* Give up */
3966     PyErr_Format(PyExc_AttributeError,
3967                  "type object '%.50s' has no attribute '%U'",
3968                  type->tp_name, name);
3969     return NULL;
3970 }
3971 
3972 static int
type_setattro(PyTypeObject * type,PyObject * name,PyObject * value)3973 type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3974 {
3975     int res;
3976     if (type->tp_flags & Py_TPFLAGS_IMMUTABLETYPE) {
3977         PyErr_Format(
3978             PyExc_TypeError,
3979             "cannot set %R attribute of immutable type '%s'",
3980             name, type->tp_name);
3981         return -1;
3982     }
3983     if (PyUnicode_Check(name)) {
3984         if (PyUnicode_CheckExact(name)) {
3985             if (PyUnicode_READY(name) == -1)
3986                 return -1;
3987             Py_INCREF(name);
3988         }
3989         else {
3990             name = _PyUnicode_Copy(name);
3991             if (name == NULL)
3992                 return -1;
3993         }
3994 #ifdef INTERN_NAME_STRINGS
3995         if (!PyUnicode_CHECK_INTERNED(name)) {
3996             PyUnicode_InternInPlace(&name);
3997             if (!PyUnicode_CHECK_INTERNED(name)) {
3998                 PyErr_SetString(PyExc_MemoryError,
3999                                 "Out of memory interning an attribute name");
4000                 Py_DECREF(name);
4001                 return -1;
4002             }
4003         }
4004 #endif
4005     }
4006     else {
4007         /* Will fail in _PyObject_GenericSetAttrWithDict. */
4008         Py_INCREF(name);
4009     }
4010     res = _PyObject_GenericSetAttrWithDict((PyObject *)type, name, value, NULL);
4011     if (res == 0) {
4012         /* Clear the VALID_VERSION flag of 'type' and all its
4013            subclasses.  This could possibly be unified with the
4014            update_subclasses() recursion in update_slot(), but carefully:
4015            they each have their own conditions on which to stop
4016            recursing into subclasses. */
4017         PyType_Modified(type);
4018 
4019         if (is_dunder_name(name)) {
4020             res = update_slot(type, name);
4021         }
4022         assert(_PyType_CheckConsistency(type));
4023     }
4024     Py_DECREF(name);
4025     return res;
4026 }
4027 
4028 extern void
4029 _PyDictKeys_DecRef(PyDictKeysObject *keys);
4030 
4031 static void
type_dealloc(PyTypeObject * type)4032 type_dealloc(PyTypeObject *type)
4033 {
4034     PyHeapTypeObject *et;
4035     PyObject *tp, *val, *tb;
4036 
4037     /* Assert this is a heap-allocated type object */
4038     _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
4039     _PyObject_GC_UNTRACK(type);
4040     PyErr_Fetch(&tp, &val, &tb);
4041     remove_all_subclasses(type, type->tp_bases);
4042     PyErr_Restore(tp, val, tb);
4043     PyObject_ClearWeakRefs((PyObject *)type);
4044     et = (PyHeapTypeObject *)type;
4045     Py_XDECREF(type->tp_base);
4046     Py_XDECREF(type->tp_dict);
4047     Py_XDECREF(type->tp_bases);
4048     Py_XDECREF(type->tp_mro);
4049     Py_XDECREF(type->tp_cache);
4050     Py_XDECREF(type->tp_subclasses);
4051     /* A type's tp_doc is heap allocated, unlike the tp_doc slots
4052      * of most other objects.  It's okay to cast it to char *.
4053      */
4054     PyObject_Free((char *)type->tp_doc);
4055     Py_XDECREF(et->ht_name);
4056     Py_XDECREF(et->ht_qualname);
4057     Py_XDECREF(et->ht_slots);
4058     if (et->ht_cached_keys) {
4059         _PyDictKeys_DecRef(et->ht_cached_keys);
4060     }
4061     Py_XDECREF(et->ht_module);
4062     Py_TYPE(type)->tp_free((PyObject *)type);
4063 }
4064 
4065 /*[clinic input]
4066 type.__subclasses__
4067 
4068 Return a list of immediate subclasses.
4069 [clinic start generated code]*/
4070 
4071 static PyObject *
type___subclasses___impl(PyTypeObject * self)4072 type___subclasses___impl(PyTypeObject *self)
4073 /*[clinic end generated code: output=eb5eb54485942819 input=5af66132436f9a7b]*/
4074 {
4075     PyObject *list, *raw, *ref;
4076     Py_ssize_t i;
4077 
4078     list = PyList_New(0);
4079     if (list == NULL)
4080         return NULL;
4081     raw = self->tp_subclasses;
4082     if (raw == NULL)
4083         return list;
4084     assert(PyDict_CheckExact(raw));
4085     i = 0;
4086     while (PyDict_Next(raw, &i, NULL, &ref)) {
4087         assert(PyWeakref_CheckRef(ref));
4088         ref = PyWeakref_GET_OBJECT(ref);
4089         if (ref != Py_None) {
4090             if (PyList_Append(list, ref) < 0) {
4091                 Py_DECREF(list);
4092                 return NULL;
4093             }
4094         }
4095     }
4096     return list;
4097 }
4098 
4099 static PyObject *
type_prepare(PyObject * self,PyObject * const * args,Py_ssize_t nargs,PyObject * kwnames)4100 type_prepare(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
4101              PyObject *kwnames)
4102 {
4103     return PyDict_New();
4104 }
4105 
4106 /*
4107    Merge the __dict__ of aclass into dict, and recursively also all
4108    the __dict__s of aclass's base classes.  The order of merging isn't
4109    defined, as it's expected that only the final set of dict keys is
4110    interesting.
4111    Return 0 on success, -1 on error.
4112 */
4113 
4114 static int
merge_class_dict(PyObject * dict,PyObject * aclass)4115 merge_class_dict(PyObject *dict, PyObject *aclass)
4116 {
4117     PyObject *classdict;
4118     PyObject *bases;
4119     _Py_IDENTIFIER(__bases__);
4120 
4121     assert(PyDict_Check(dict));
4122     assert(aclass);
4123 
4124     /* Merge in the type's dict (if any). */
4125     if (_PyObject_LookupAttrId(aclass, &PyId___dict__, &classdict) < 0) {
4126         return -1;
4127     }
4128     if (classdict != NULL) {
4129         int status = PyDict_Update(dict, classdict);
4130         Py_DECREF(classdict);
4131         if (status < 0)
4132             return -1;
4133     }
4134 
4135     /* Recursively merge in the base types' (if any) dicts. */
4136     if (_PyObject_LookupAttrId(aclass, &PyId___bases__, &bases) < 0) {
4137         return -1;
4138     }
4139     if (bases != NULL) {
4140         /* We have no guarantee that bases is a real tuple */
4141         Py_ssize_t i, n;
4142         n = PySequence_Size(bases); /* This better be right */
4143         if (n < 0) {
4144             Py_DECREF(bases);
4145             return -1;
4146         }
4147         else {
4148             for (i = 0; i < n; i++) {
4149                 int status;
4150                 PyObject *base = PySequence_GetItem(bases, i);
4151                 if (base == NULL) {
4152                     Py_DECREF(bases);
4153                     return -1;
4154                 }
4155                 status = merge_class_dict(dict, base);
4156                 Py_DECREF(base);
4157                 if (status < 0) {
4158                     Py_DECREF(bases);
4159                     return -1;
4160                 }
4161             }
4162         }
4163         Py_DECREF(bases);
4164     }
4165     return 0;
4166 }
4167 
4168 /* __dir__ for type objects: returns __dict__ and __bases__.
4169    We deliberately don't suck up its __class__, as methods belonging to the
4170    metaclass would probably be more confusing than helpful.
4171 */
4172 /*[clinic input]
4173 type.__dir__
4174 
4175 Specialized __dir__ implementation for types.
4176 [clinic start generated code]*/
4177 
4178 static PyObject *
type___dir___impl(PyTypeObject * self)4179 type___dir___impl(PyTypeObject *self)
4180 /*[clinic end generated code: output=69d02fe92c0f15fa input=7733befbec645968]*/
4181 {
4182     PyObject *result = NULL;
4183     PyObject *dict = PyDict_New();
4184 
4185     if (dict != NULL && merge_class_dict(dict, (PyObject *)self) == 0)
4186         result = PyDict_Keys(dict);
4187 
4188     Py_XDECREF(dict);
4189     return result;
4190 }
4191 
4192 /*[clinic input]
4193 type.__sizeof__
4194 
4195 Return memory consumption of the type object.
4196 [clinic start generated code]*/
4197 
4198 static PyObject *
type___sizeof___impl(PyTypeObject * self)4199 type___sizeof___impl(PyTypeObject *self)
4200 /*[clinic end generated code: output=766f4f16cd3b1854 input=99398f24b9cf45d6]*/
4201 {
4202     Py_ssize_t size;
4203     if (self->tp_flags & Py_TPFLAGS_HEAPTYPE) {
4204         PyHeapTypeObject* et = (PyHeapTypeObject*)self;
4205         size = sizeof(PyHeapTypeObject);
4206         if (et->ht_cached_keys)
4207             size += _PyDict_KeysSize(et->ht_cached_keys);
4208     }
4209     else
4210         size = sizeof(PyTypeObject);
4211     return PyLong_FromSsize_t(size);
4212 }
4213 
4214 static PyMethodDef type_methods[] = {
4215     TYPE_MRO_METHODDEF
4216     TYPE___SUBCLASSES___METHODDEF
4217     {"__prepare__", (PyCFunction)(void(*)(void))type_prepare,
4218      METH_FASTCALL | METH_KEYWORDS | METH_CLASS,
4219      PyDoc_STR("__prepare__() -> dict\n"
4220                "used to create the namespace for the class statement")},
4221     TYPE___INSTANCECHECK___METHODDEF
4222     TYPE___SUBCLASSCHECK___METHODDEF
4223     TYPE___DIR___METHODDEF
4224     TYPE___SIZEOF___METHODDEF
4225     {0}
4226 };
4227 
4228 PyDoc_STRVAR(type_doc,
4229 "type(object) -> the object's type\n"
4230 "type(name, bases, dict, **kwds) -> a new type");
4231 
4232 static int
type_traverse(PyTypeObject * type,visitproc visit,void * arg)4233 type_traverse(PyTypeObject *type, visitproc visit, void *arg)
4234 {
4235     /* Because of type_is_gc(), the collector only calls this
4236        for heaptypes. */
4237     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4238         char msg[200];
4239         sprintf(msg, "type_traverse() called on non-heap type '%.100s'",
4240                 type->tp_name);
4241         _PyObject_ASSERT_FAILED_MSG((PyObject *)type, msg);
4242     }
4243 
4244     Py_VISIT(type->tp_dict);
4245     Py_VISIT(type->tp_cache);
4246     Py_VISIT(type->tp_mro);
4247     Py_VISIT(type->tp_bases);
4248     Py_VISIT(type->tp_base);
4249     Py_VISIT(((PyHeapTypeObject *)type)->ht_module);
4250 
4251     /* There's no need to visit type->tp_subclasses or
4252        ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
4253        in cycles; tp_subclasses is a list of weak references,
4254        and slots is a tuple of strings. */
4255 
4256     return 0;
4257 }
4258 
4259 static int
type_clear(PyTypeObject * type)4260 type_clear(PyTypeObject *type)
4261 {
4262     PyDictKeysObject *cached_keys;
4263     /* Because of type_is_gc(), the collector only calls this
4264        for heaptypes. */
4265     _PyObject_ASSERT((PyObject *)type, type->tp_flags & Py_TPFLAGS_HEAPTYPE);
4266 
4267     /* We need to invalidate the method cache carefully before clearing
4268        the dict, so that other objects caught in a reference cycle
4269        don't start calling destroyed methods.
4270 
4271        Otherwise, the we need to clear tp_mro, which is
4272        part of a hard cycle (its first element is the class itself) that
4273        won't be broken otherwise (it's a tuple and tuples don't have a
4274        tp_clear handler).
4275        We also need to clear ht_module, if present: the module usually holds a
4276        reference to its class. None of the other fields need to be
4277 
4278        cleared, and here's why:
4279 
4280        tp_cache:
4281            Not used; if it were, it would be a dict.
4282 
4283        tp_bases, tp_base:
4284            If these are involved in a cycle, there must be at least
4285            one other, mutable object in the cycle, e.g. a base
4286            class's dict; the cycle will be broken that way.
4287 
4288        tp_subclasses:
4289            A dict of weak references can't be part of a cycle; and
4290            dicts have their own tp_clear.
4291 
4292        slots (in PyHeapTypeObject):
4293            A tuple of strings can't be part of a cycle.
4294     */
4295 
4296     PyType_Modified(type);
4297     cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
4298     if (cached_keys != NULL) {
4299         ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
4300         _PyDictKeys_DecRef(cached_keys);
4301     }
4302     if (type->tp_dict) {
4303         PyDict_Clear(type->tp_dict);
4304     }
4305     Py_CLEAR(((PyHeapTypeObject *)type)->ht_module);
4306 
4307     Py_CLEAR(type->tp_mro);
4308 
4309     return 0;
4310 }
4311 
4312 static int
type_is_gc(PyTypeObject * type)4313 type_is_gc(PyTypeObject *type)
4314 {
4315     return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
4316 }
4317 
4318 
4319 static PyNumberMethods type_as_number = {
4320         .nb_or = _Py_union_type_or, // Add __or__ function
4321 };
4322 
4323 PyTypeObject PyType_Type = {
4324     PyVarObject_HEAD_INIT(&PyType_Type, 0)
4325     "type",                                     /* tp_name */
4326     sizeof(PyHeapTypeObject),                   /* tp_basicsize */
4327     sizeof(PyMemberDef),                        /* tp_itemsize */
4328     (destructor)type_dealloc,                   /* tp_dealloc */
4329     offsetof(PyTypeObject, tp_vectorcall),      /* tp_vectorcall_offset */
4330     0,                                          /* tp_getattr */
4331     0,                                          /* tp_setattr */
4332     0,                                          /* tp_as_async */
4333     (reprfunc)type_repr,                        /* tp_repr */
4334     &type_as_number,                            /* tp_as_number */
4335     0,                                          /* tp_as_sequence */
4336     0,                                          /* tp_as_mapping */
4337     0,                                          /* tp_hash */
4338     (ternaryfunc)type_call,                     /* tp_call */
4339     0,                                          /* tp_str */
4340     (getattrofunc)type_getattro,                /* tp_getattro */
4341     (setattrofunc)type_setattro,                /* tp_setattro */
4342     0,                                          /* tp_as_buffer */
4343     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4344     Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS |
4345     Py_TPFLAGS_HAVE_VECTORCALL,                 /* tp_flags */
4346     type_doc,                                   /* tp_doc */
4347     (traverseproc)type_traverse,                /* tp_traverse */
4348     (inquiry)type_clear,                        /* tp_clear */
4349     0,                                          /* tp_richcompare */
4350     offsetof(PyTypeObject, tp_weaklist),        /* tp_weaklistoffset */
4351     0,                                          /* tp_iter */
4352     0,                                          /* tp_iternext */
4353     type_methods,                               /* tp_methods */
4354     type_members,                               /* tp_members */
4355     type_getsets,                               /* tp_getset */
4356     0,                                          /* tp_base */
4357     0,                                          /* tp_dict */
4358     0,                                          /* tp_descr_get */
4359     0,                                          /* tp_descr_set */
4360     offsetof(PyTypeObject, tp_dict),            /* tp_dictoffset */
4361     type_init,                                  /* tp_init */
4362     0,                                          /* tp_alloc */
4363     type_new,                                   /* tp_new */
4364     PyObject_GC_Del,                            /* tp_free */
4365     (inquiry)type_is_gc,                        /* tp_is_gc */
4366     .tp_vectorcall = type_vectorcall,
4367 };
4368 
4369 
4370 /* The base type of all types (eventually)... except itself. */
4371 
4372 /* You may wonder why object.__new__() only complains about arguments
4373    when object.__init__() is not overridden, and vice versa.
4374 
4375    Consider the use cases:
4376 
4377    1. When neither is overridden, we want to hear complaints about
4378       excess (i.e., any) arguments, since their presence could
4379       indicate there's a bug.
4380 
4381    2. When defining an Immutable type, we are likely to override only
4382       __new__(), since __init__() is called too late to initialize an
4383       Immutable object.  Since __new__() defines the signature for the
4384       type, it would be a pain to have to override __init__() just to
4385       stop it from complaining about excess arguments.
4386 
4387    3. When defining a Mutable type, we are likely to override only
4388       __init__().  So here the converse reasoning applies: we don't
4389       want to have to override __new__() just to stop it from
4390       complaining.
4391 
4392    4. When __init__() is overridden, and the subclass __init__() calls
4393       object.__init__(), the latter should complain about excess
4394       arguments; ditto for __new__().
4395 
4396    Use cases 2 and 3 make it unattractive to unconditionally check for
4397    excess arguments.  The best solution that addresses all four use
4398    cases is as follows: __init__() complains about excess arguments
4399    unless __new__() is overridden and __init__() is not overridden
4400    (IOW, if __init__() is overridden or __new__() is not overridden);
4401    symmetrically, __new__() complains about excess arguments unless
4402    __init__() is overridden and __new__() is not overridden
4403    (IOW, if __new__() is overridden or __init__() is not overridden).
4404 
4405    However, for backwards compatibility, this breaks too much code.
4406    Therefore, in 2.6, we'll *warn* about excess arguments when both
4407    methods are overridden; for all other cases we'll use the above
4408    rules.
4409 
4410 */
4411 
4412 /* Forward */
4413 static PyObject *
4414 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
4415 
4416 static int
excess_args(PyObject * args,PyObject * kwds)4417 excess_args(PyObject *args, PyObject *kwds)
4418 {
4419     return PyTuple_GET_SIZE(args) ||
4420         (kwds && PyDict_Check(kwds) && PyDict_GET_SIZE(kwds));
4421 }
4422 
4423 static int
object_init(PyObject * self,PyObject * args,PyObject * kwds)4424 object_init(PyObject *self, PyObject *args, PyObject *kwds)
4425 {
4426     PyTypeObject *type = Py_TYPE(self);
4427     if (excess_args(args, kwds)) {
4428         if (type->tp_init != object_init) {
4429             PyErr_SetString(PyExc_TypeError,
4430                             "object.__init__() takes exactly one argument (the instance to initialize)");
4431             return -1;
4432         }
4433         if (type->tp_new == object_new) {
4434             PyErr_Format(PyExc_TypeError,
4435                          "%.200s.__init__() takes exactly one argument (the instance to initialize)",
4436                          type->tp_name);
4437             return -1;
4438         }
4439     }
4440     return 0;
4441 }
4442 
4443 static PyObject *
object_new(PyTypeObject * type,PyObject * args,PyObject * kwds)4444 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4445 {
4446     if (excess_args(args, kwds)) {
4447         if (type->tp_new != object_new) {
4448             PyErr_SetString(PyExc_TypeError,
4449                             "object.__new__() takes exactly one argument (the type to instantiate)");
4450             return NULL;
4451         }
4452         if (type->tp_init == object_init) {
4453             PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments",
4454                          type->tp_name);
4455             return NULL;
4456         }
4457     }
4458 
4459     if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
4460         PyObject *abstract_methods;
4461         PyObject *sorted_methods;
4462         PyObject *joined;
4463         PyObject *comma;
4464         _Py_static_string(comma_id, ", ");
4465         Py_ssize_t method_count;
4466 
4467         /* Compute ", ".join(sorted(type.__abstractmethods__))
4468            into joined. */
4469         abstract_methods = type_abstractmethods(type, NULL);
4470         if (abstract_methods == NULL)
4471             return NULL;
4472         sorted_methods = PySequence_List(abstract_methods);
4473         Py_DECREF(abstract_methods);
4474         if (sorted_methods == NULL)
4475             return NULL;
4476         if (PyList_Sort(sorted_methods)) {
4477             Py_DECREF(sorted_methods);
4478             return NULL;
4479         }
4480         comma = _PyUnicode_FromId(&comma_id);
4481         if (comma == NULL) {
4482             Py_DECREF(sorted_methods);
4483             return NULL;
4484         }
4485         joined = PyUnicode_Join(comma, sorted_methods);
4486         method_count = PyObject_Length(sorted_methods);
4487         Py_DECREF(sorted_methods);
4488         if (joined == NULL)
4489             return NULL;
4490         if (method_count == -1)
4491             return NULL;
4492 
4493         PyErr_Format(PyExc_TypeError,
4494                      "Can't instantiate abstract class %s "
4495                      "with abstract method%s %U",
4496                      type->tp_name,
4497                      method_count > 1 ? "s" : "",
4498                      joined);
4499         Py_DECREF(joined);
4500         return NULL;
4501     }
4502     return type->tp_alloc(type, 0);
4503 }
4504 
4505 static void
object_dealloc(PyObject * self)4506 object_dealloc(PyObject *self)
4507 {
4508     Py_TYPE(self)->tp_free(self);
4509 }
4510 
4511 static PyObject *
object_repr(PyObject * self)4512 object_repr(PyObject *self)
4513 {
4514     PyTypeObject *type;
4515     PyObject *mod, *name, *rtn;
4516 
4517     type = Py_TYPE(self);
4518     mod = type_module(type, NULL);
4519     if (mod == NULL)
4520         PyErr_Clear();
4521     else if (!PyUnicode_Check(mod)) {
4522         Py_DECREF(mod);
4523         mod = NULL;
4524     }
4525     name = type_qualname(type, NULL);
4526     if (name == NULL) {
4527         Py_XDECREF(mod);
4528         return NULL;
4529     }
4530     if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
4531         rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
4532     else
4533         rtn = PyUnicode_FromFormat("<%s object at %p>",
4534                                   type->tp_name, self);
4535     Py_XDECREF(mod);
4536     Py_DECREF(name);
4537     return rtn;
4538 }
4539 
4540 static PyObject *
object_str(PyObject * self)4541 object_str(PyObject *self)
4542 {
4543     unaryfunc f;
4544 
4545     f = Py_TYPE(self)->tp_repr;
4546     if (f == NULL)
4547         f = object_repr;
4548     return f(self);
4549 }
4550 
4551 static PyObject *
object_richcompare(PyObject * self,PyObject * other,int op)4552 object_richcompare(PyObject *self, PyObject *other, int op)
4553 {
4554     PyObject *res;
4555 
4556     switch (op) {
4557 
4558     case Py_EQ:
4559         /* Return NotImplemented instead of False, so if two
4560            objects are compared, both get a chance at the
4561            comparison.  See issue #1393. */
4562         res = (self == other) ? Py_True : Py_NotImplemented;
4563         Py_INCREF(res);
4564         break;
4565 
4566     case Py_NE:
4567         /* By default, __ne__() delegates to __eq__() and inverts the result,
4568            unless the latter returns NotImplemented. */
4569         if (Py_TYPE(self)->tp_richcompare == NULL) {
4570             res = Py_NotImplemented;
4571             Py_INCREF(res);
4572             break;
4573         }
4574         res = (*Py_TYPE(self)->tp_richcompare)(self, other, Py_EQ);
4575         if (res != NULL && res != Py_NotImplemented) {
4576             int ok = PyObject_IsTrue(res);
4577             Py_DECREF(res);
4578             if (ok < 0)
4579                 res = NULL;
4580             else {
4581                 if (ok)
4582                     res = Py_False;
4583                 else
4584                     res = Py_True;
4585                 Py_INCREF(res);
4586             }
4587         }
4588         break;
4589 
4590     default:
4591         res = Py_NotImplemented;
4592         Py_INCREF(res);
4593         break;
4594     }
4595 
4596     return res;
4597 }
4598 
4599 static PyObject *
object_get_class(PyObject * self,void * closure)4600 object_get_class(PyObject *self, void *closure)
4601 {
4602     Py_INCREF(Py_TYPE(self));
4603     return (PyObject *)(Py_TYPE(self));
4604 }
4605 
4606 static int
compatible_with_tp_base(PyTypeObject * child)4607 compatible_with_tp_base(PyTypeObject *child)
4608 {
4609     PyTypeObject *parent = child->tp_base;
4610     return (parent != NULL &&
4611             child->tp_basicsize == parent->tp_basicsize &&
4612             child->tp_itemsize == parent->tp_itemsize &&
4613             child->tp_dictoffset == parent->tp_dictoffset &&
4614             child->tp_weaklistoffset == parent->tp_weaklistoffset &&
4615             ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4616              (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
4617             (child->tp_dealloc == subtype_dealloc ||
4618              child->tp_dealloc == parent->tp_dealloc));
4619 }
4620 
4621 static int
same_slots_added(PyTypeObject * a,PyTypeObject * b)4622 same_slots_added(PyTypeObject *a, PyTypeObject *b)
4623 {
4624     PyTypeObject *base = a->tp_base;
4625     Py_ssize_t size;
4626     PyObject *slots_a, *slots_b;
4627 
4628     assert(base == b->tp_base);
4629     size = base->tp_basicsize;
4630     if (a->tp_dictoffset == size && b->tp_dictoffset == size)
4631         size += sizeof(PyObject *);
4632     if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
4633         size += sizeof(PyObject *);
4634 
4635     /* Check slots compliance */
4636     if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
4637         !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4638         return 0;
4639     }
4640     slots_a = ((PyHeapTypeObject *)a)->ht_slots;
4641     slots_b = ((PyHeapTypeObject *)b)->ht_slots;
4642     if (slots_a && slots_b) {
4643         if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
4644             return 0;
4645         size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
4646     }
4647     return size == a->tp_basicsize && size == b->tp_basicsize;
4648 }
4649 
4650 static int
compatible_for_assignment(PyTypeObject * oldto,PyTypeObject * newto,const char * attr)4651 compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
4652 {
4653     PyTypeObject *newbase, *oldbase;
4654 
4655     if (newto->tp_free != oldto->tp_free) {
4656         PyErr_Format(PyExc_TypeError,
4657                      "%s assignment: "
4658                      "'%s' deallocator differs from '%s'",
4659                      attr,
4660                      newto->tp_name,
4661                      oldto->tp_name);
4662         return 0;
4663     }
4664     /*
4665      It's tricky to tell if two arbitrary types are sufficiently compatible as
4666      to be interchangeable; e.g., even if they have the same tp_basicsize, they
4667      might have totally different struct fields. It's much easier to tell if a
4668      type and its supertype are compatible; e.g., if they have the same
4669      tp_basicsize, then that means they have identical fields. So to check
4670      whether two arbitrary types are compatible, we first find the highest
4671      supertype that each is compatible with, and then if those supertypes are
4672      compatible then the original types must also be compatible.
4673     */
4674     newbase = newto;
4675     oldbase = oldto;
4676     while (compatible_with_tp_base(newbase))
4677         newbase = newbase->tp_base;
4678     while (compatible_with_tp_base(oldbase))
4679         oldbase = oldbase->tp_base;
4680     if (newbase != oldbase &&
4681         (newbase->tp_base != oldbase->tp_base ||
4682          !same_slots_added(newbase, oldbase))) {
4683         PyErr_Format(PyExc_TypeError,
4684                      "%s assignment: "
4685                      "'%s' object layout differs from '%s'",
4686                      attr,
4687                      newto->tp_name,
4688                      oldto->tp_name);
4689         return 0;
4690     }
4691 
4692     return 1;
4693 }
4694 
4695 static int
object_set_class(PyObject * self,PyObject * value,void * closure)4696 object_set_class(PyObject *self, PyObject *value, void *closure)
4697 {
4698     PyTypeObject *oldto = Py_TYPE(self);
4699     PyTypeObject *newto;
4700 
4701     if (value == NULL) {
4702         PyErr_SetString(PyExc_TypeError,
4703                         "can't delete __class__ attribute");
4704         return -1;
4705     }
4706     if (!PyType_Check(value)) {
4707         PyErr_Format(PyExc_TypeError,
4708           "__class__ must be set to a class, not '%s' object",
4709           Py_TYPE(value)->tp_name);
4710         return -1;
4711     }
4712     if (PySys_Audit("object.__setattr__", "OsO",
4713                     self, "__class__", value) < 0) {
4714         return -1;
4715     }
4716 
4717     newto = (PyTypeObject *)value;
4718     /* In versions of CPython prior to 3.5, the code in
4719        compatible_for_assignment was not set up to correctly check for memory
4720        layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
4721        disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
4722        HEAPTYPE.
4723 
4724        During the 3.5 development cycle, we fixed the code in
4725        compatible_for_assignment to correctly check compatibility between
4726        arbitrary types, and started allowing __class__ assignment in all cases
4727        where the old and new types did in fact have compatible slots and
4728        memory layout (regardless of whether they were implemented as HEAPTYPEs
4729        or not).
4730 
4731        Just before 3.5 was released, though, we discovered that this led to
4732        problems with immutable types like int, where the interpreter assumes
4733        they are immutable and interns some values. Formerly this wasn't a
4734        problem, because they really were immutable -- in particular, all the
4735        types where the interpreter applied this interning trick happened to
4736        also be statically allocated, so the old HEAPTYPE rules were
4737        "accidentally" stopping them from allowing __class__ assignment. But
4738        with the changes to __class__ assignment, we started allowing code like
4739 
4740          class MyInt(int):
4741              ...
4742          # Modifies the type of *all* instances of 1 in the whole program,
4743          # including future instances (!), because the 1 object is interned.
4744          (1).__class__ = MyInt
4745 
4746        (see https://bugs.python.org/issue24912).
4747 
4748        In theory the proper fix would be to identify which classes rely on
4749        this invariant and somehow disallow __class__ assignment only for them,
4750        perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
4751        "denylisting" approach). But in practice, since this problem wasn't
4752        noticed late in the 3.5 RC cycle, we're taking the conservative
4753        approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
4754        to have, plus an "allowlist". For now, the allowlist consists only of
4755        ModuleType subtypes, since those are the cases that motivated the patch
4756        in the first place -- see https://bugs.python.org/issue22986 -- and
4757        since module objects are mutable we can be sure that they are
4758        definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
4759        ModuleType subtype -> ModuleType subtype.
4760 
4761        So far as we know, all the code beyond the following 'if' statement
4762        will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
4763        needed only to protect that subset of non-HEAPTYPE classes for which
4764        the interpreter has baked in the assumption that all instances are
4765        truly immutable.
4766     */
4767     if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
4768           PyType_IsSubtype(oldto, &PyModule_Type)) &&
4769         (_PyType_HasFeature(newto, Py_TPFLAGS_IMMUTABLETYPE) ||
4770          _PyType_HasFeature(oldto, Py_TPFLAGS_IMMUTABLETYPE))) {
4771         PyErr_Format(PyExc_TypeError,
4772                      "__class__ assignment only supported for mutable types "
4773                      "or ModuleType subclasses");
4774         return -1;
4775     }
4776 
4777     if (compatible_for_assignment(oldto, newto, "__class__")) {
4778         if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE) {
4779             Py_INCREF(newto);
4780         }
4781         Py_SET_TYPE(self, newto);
4782         if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
4783             Py_DECREF(oldto);
4784         return 0;
4785     }
4786     else {
4787         return -1;
4788     }
4789 }
4790 
4791 static PyGetSetDef object_getsets[] = {
4792     {"__class__", object_get_class, object_set_class,
4793      PyDoc_STR("the object's class")},
4794     {0}
4795 };
4796 
4797 
4798 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
4799    We fall back to helpers in copyreg for:
4800    - pickle protocols < 2
4801    - calculating the list of slot names (done only once per class)
4802    - the __newobj__ function (which is used as a token but never called)
4803 */
4804 
4805 static PyObject *
import_copyreg(void)4806 import_copyreg(void)
4807 {
4808     PyObject *copyreg_str;
4809     PyObject *copyreg_module;
4810     _Py_IDENTIFIER(copyreg);
4811 
4812     copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
4813     if (copyreg_str == NULL) {
4814         return NULL;
4815     }
4816     /* Try to fetch cached copy of copyreg from sys.modules first in an
4817        attempt to avoid the import overhead. Previously this was implemented
4818        by storing a reference to the cached module in a static variable, but
4819        this broke when multiple embedded interpreters were in use (see issue
4820        #17408 and #19088). */
4821     copyreg_module = PyImport_GetModule(copyreg_str);
4822     if (copyreg_module != NULL) {
4823         return copyreg_module;
4824     }
4825     if (PyErr_Occurred()) {
4826         return NULL;
4827     }
4828     return PyImport_Import(copyreg_str);
4829 }
4830 
4831 static PyObject *
_PyType_GetSlotNames(PyTypeObject * cls)4832 _PyType_GetSlotNames(PyTypeObject *cls)
4833 {
4834     PyObject *copyreg;
4835     PyObject *slotnames;
4836     _Py_IDENTIFIER(__slotnames__);
4837     _Py_IDENTIFIER(_slotnames);
4838 
4839     assert(PyType_Check(cls));
4840 
4841     /* Get the slot names from the cache in the class if possible. */
4842     slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
4843     if (slotnames != NULL) {
4844         if (slotnames != Py_None && !PyList_Check(slotnames)) {
4845             PyErr_Format(PyExc_TypeError,
4846                          "%.200s.__slotnames__ should be a list or None, "
4847                          "not %.200s",
4848                          cls->tp_name, Py_TYPE(slotnames)->tp_name);
4849             return NULL;
4850         }
4851         Py_INCREF(slotnames);
4852         return slotnames;
4853     }
4854     else {
4855         if (PyErr_Occurred()) {
4856             return NULL;
4857         }
4858         /* The class does not have the slot names cached yet. */
4859     }
4860 
4861     copyreg = import_copyreg();
4862     if (copyreg == NULL)
4863         return NULL;
4864 
4865     /* Use _slotnames function from the copyreg module to find the slots
4866        by this class and its bases. This function will cache the result
4867        in __slotnames__. */
4868     slotnames = _PyObject_CallMethodIdOneArg(copyreg, &PyId__slotnames,
4869                                              (PyObject *)cls);
4870     Py_DECREF(copyreg);
4871     if (slotnames == NULL)
4872         return NULL;
4873 
4874     if (slotnames != Py_None && !PyList_Check(slotnames)) {
4875         PyErr_SetString(PyExc_TypeError,
4876                         "copyreg._slotnames didn't return a list or None");
4877         Py_DECREF(slotnames);
4878         return NULL;
4879     }
4880 
4881     return slotnames;
4882 }
4883 
4884 static PyObject *
_PyObject_GetState(PyObject * obj,int required)4885 _PyObject_GetState(PyObject *obj, int required)
4886 {
4887     PyObject *state;
4888     PyObject *getstate;
4889     _Py_IDENTIFIER(__getstate__);
4890 
4891     if (_PyObject_LookupAttrId(obj, &PyId___getstate__, &getstate) < 0) {
4892         return NULL;
4893     }
4894     if (getstate == NULL) {
4895         PyObject *slotnames;
4896 
4897         if (required && Py_TYPE(obj)->tp_itemsize) {
4898             PyErr_Format(PyExc_TypeError,
4899                          "cannot pickle '%.200s' object",
4900                          Py_TYPE(obj)->tp_name);
4901             return NULL;
4902         }
4903 
4904         {
4905             PyObject **dict;
4906             dict = _PyObject_GetDictPtr(obj);
4907             /* It is possible that the object's dict is not initialized
4908                yet. In this case, we will return None for the state.
4909                We also return None if the dict is empty to make the behavior
4910                consistent regardless whether the dict was initialized or not.
4911                This make unit testing easier. */
4912             if (dict != NULL && *dict != NULL && PyDict_GET_SIZE(*dict)) {
4913                 state = *dict;
4914             }
4915             else {
4916                 state = Py_None;
4917             }
4918             Py_INCREF(state);
4919         }
4920 
4921         slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
4922         if (slotnames == NULL) {
4923             Py_DECREF(state);
4924             return NULL;
4925         }
4926 
4927         assert(slotnames == Py_None || PyList_Check(slotnames));
4928         if (required) {
4929             Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
4930             if (Py_TYPE(obj)->tp_dictoffset)
4931                 basicsize += sizeof(PyObject *);
4932             if (Py_TYPE(obj)->tp_weaklistoffset)
4933                 basicsize += sizeof(PyObject *);
4934             if (slotnames != Py_None)
4935                 basicsize += sizeof(PyObject *) * PyList_GET_SIZE(slotnames);
4936             if (Py_TYPE(obj)->tp_basicsize > basicsize) {
4937                 Py_DECREF(slotnames);
4938                 Py_DECREF(state);
4939                 PyErr_Format(PyExc_TypeError,
4940                              "cannot pickle '%.200s' object",
4941                              Py_TYPE(obj)->tp_name);
4942                 return NULL;
4943             }
4944         }
4945 
4946         if (slotnames != Py_None && PyList_GET_SIZE(slotnames) > 0) {
4947             PyObject *slots;
4948             Py_ssize_t slotnames_size, i;
4949 
4950             slots = PyDict_New();
4951             if (slots == NULL) {
4952                 Py_DECREF(slotnames);
4953                 Py_DECREF(state);
4954                 return NULL;
4955             }
4956 
4957             slotnames_size = PyList_GET_SIZE(slotnames);
4958             for (i = 0; i < slotnames_size; i++) {
4959                 PyObject *name, *value;
4960 
4961                 name = PyList_GET_ITEM(slotnames, i);
4962                 Py_INCREF(name);
4963                 if (_PyObject_LookupAttr(obj, name, &value) < 0) {
4964                     goto error;
4965                 }
4966                 if (value == NULL) {
4967                     Py_DECREF(name);
4968                     /* It is not an error if the attribute is not present. */
4969                 }
4970                 else {
4971                     int err = PyDict_SetItem(slots, name, value);
4972                     Py_DECREF(name);
4973                     Py_DECREF(value);
4974                     if (err) {
4975                         goto error;
4976                     }
4977                 }
4978 
4979                 /* The list is stored on the class so it may mutate while we
4980                    iterate over it */
4981                 if (slotnames_size != PyList_GET_SIZE(slotnames)) {
4982                     PyErr_Format(PyExc_RuntimeError,
4983                                  "__slotsname__ changed size during iteration");
4984                     goto error;
4985                 }
4986 
4987                 /* We handle errors within the loop here. */
4988                 if (0) {
4989                   error:
4990                     Py_DECREF(slotnames);
4991                     Py_DECREF(slots);
4992                     Py_DECREF(state);
4993                     return NULL;
4994                 }
4995             }
4996 
4997             /* If we found some slot attributes, pack them in a tuple along
4998                the original attribute dictionary. */
4999             if (PyDict_GET_SIZE(slots) > 0) {
5000                 PyObject *state2;
5001 
5002                 state2 = PyTuple_Pack(2, state, slots);
5003                 Py_DECREF(state);
5004                 if (state2 == NULL) {
5005                     Py_DECREF(slotnames);
5006                     Py_DECREF(slots);
5007                     return NULL;
5008                 }
5009                 state = state2;
5010             }
5011             Py_DECREF(slots);
5012         }
5013         Py_DECREF(slotnames);
5014     }
5015     else { /* getstate != NULL */
5016         state = _PyObject_CallNoArg(getstate);
5017         Py_DECREF(getstate);
5018         if (state == NULL)
5019             return NULL;
5020     }
5021 
5022     return state;
5023 }
5024 
5025 static int
_PyObject_GetNewArguments(PyObject * obj,PyObject ** args,PyObject ** kwargs)5026 _PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
5027 {
5028     PyObject *getnewargs, *getnewargs_ex;
5029     _Py_IDENTIFIER(__getnewargs_ex__);
5030     _Py_IDENTIFIER(__getnewargs__);
5031 
5032     if (args == NULL || kwargs == NULL) {
5033         PyErr_BadInternalCall();
5034         return -1;
5035     }
5036 
5037     /* We first attempt to fetch the arguments for __new__ by calling
5038        __getnewargs_ex__ on the object. */
5039     getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
5040     if (getnewargs_ex != NULL) {
5041         PyObject *newargs = _PyObject_CallNoArg(getnewargs_ex);
5042         Py_DECREF(getnewargs_ex);
5043         if (newargs == NULL) {
5044             return -1;
5045         }
5046         if (!PyTuple_Check(newargs)) {
5047             PyErr_Format(PyExc_TypeError,
5048                          "__getnewargs_ex__ should return a tuple, "
5049                          "not '%.200s'", Py_TYPE(newargs)->tp_name);
5050             Py_DECREF(newargs);
5051             return -1;
5052         }
5053         if (PyTuple_GET_SIZE(newargs) != 2) {
5054             PyErr_Format(PyExc_ValueError,
5055                          "__getnewargs_ex__ should return a tuple of "
5056                          "length 2, not %zd", PyTuple_GET_SIZE(newargs));
5057             Py_DECREF(newargs);
5058             return -1;
5059         }
5060         *args = PyTuple_GET_ITEM(newargs, 0);
5061         Py_INCREF(*args);
5062         *kwargs = PyTuple_GET_ITEM(newargs, 1);
5063         Py_INCREF(*kwargs);
5064         Py_DECREF(newargs);
5065 
5066         /* XXX We should perhaps allow None to be passed here. */
5067         if (!PyTuple_Check(*args)) {
5068             PyErr_Format(PyExc_TypeError,
5069                          "first item of the tuple returned by "
5070                          "__getnewargs_ex__ must be a tuple, not '%.200s'",
5071                          Py_TYPE(*args)->tp_name);
5072             Py_CLEAR(*args);
5073             Py_CLEAR(*kwargs);
5074             return -1;
5075         }
5076         if (!PyDict_Check(*kwargs)) {
5077             PyErr_Format(PyExc_TypeError,
5078                          "second item of the tuple returned by "
5079                          "__getnewargs_ex__ must be a dict, not '%.200s'",
5080                          Py_TYPE(*kwargs)->tp_name);
5081             Py_CLEAR(*args);
5082             Py_CLEAR(*kwargs);
5083             return -1;
5084         }
5085         return 0;
5086     } else if (PyErr_Occurred()) {
5087         return -1;
5088     }
5089 
5090     /* The object does not have __getnewargs_ex__ so we fallback on using
5091        __getnewargs__ instead. */
5092     getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
5093     if (getnewargs != NULL) {
5094         *args = _PyObject_CallNoArg(getnewargs);
5095         Py_DECREF(getnewargs);
5096         if (*args == NULL) {
5097             return -1;
5098         }
5099         if (!PyTuple_Check(*args)) {
5100             PyErr_Format(PyExc_TypeError,
5101                          "__getnewargs__ should return a tuple, "
5102                          "not '%.200s'", Py_TYPE(*args)->tp_name);
5103             Py_CLEAR(*args);
5104             return -1;
5105         }
5106         *kwargs = NULL;
5107         return 0;
5108     } else if (PyErr_Occurred()) {
5109         return -1;
5110     }
5111 
5112     /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
5113        mean __new__ does not takes any arguments on this object, or that the
5114        object does not implement the reduce protocol for pickling or
5115        copying. */
5116     *args = NULL;
5117     *kwargs = NULL;
5118     return 0;
5119 }
5120 
5121 static int
_PyObject_GetItemsIter(PyObject * obj,PyObject ** listitems,PyObject ** dictitems)5122 _PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
5123                        PyObject **dictitems)
5124 {
5125     if (listitems == NULL || dictitems == NULL) {
5126         PyErr_BadInternalCall();
5127         return -1;
5128     }
5129 
5130     if (!PyList_Check(obj)) {
5131         *listitems = Py_None;
5132         Py_INCREF(*listitems);
5133     }
5134     else {
5135         *listitems = PyObject_GetIter(obj);
5136         if (*listitems == NULL)
5137             return -1;
5138     }
5139 
5140     if (!PyDict_Check(obj)) {
5141         *dictitems = Py_None;
5142         Py_INCREF(*dictitems);
5143     }
5144     else {
5145         PyObject *items;
5146         _Py_IDENTIFIER(items);
5147 
5148         items = _PyObject_CallMethodIdNoArgs(obj, &PyId_items);
5149         if (items == NULL) {
5150             Py_CLEAR(*listitems);
5151             return -1;
5152         }
5153         *dictitems = PyObject_GetIter(items);
5154         Py_DECREF(items);
5155         if (*dictitems == NULL) {
5156             Py_CLEAR(*listitems);
5157             return -1;
5158         }
5159     }
5160 
5161     assert(*listitems != NULL && *dictitems != NULL);
5162 
5163     return 0;
5164 }
5165 
5166 static PyObject *
reduce_newobj(PyObject * obj)5167 reduce_newobj(PyObject *obj)
5168 {
5169     PyObject *args = NULL, *kwargs = NULL;
5170     PyObject *copyreg;
5171     PyObject *newobj, *newargs, *state, *listitems, *dictitems;
5172     PyObject *result;
5173     int hasargs;
5174 
5175     if (Py_TYPE(obj)->tp_new == NULL) {
5176         PyErr_Format(PyExc_TypeError,
5177                      "cannot pickle '%.200s' object",
5178                      Py_TYPE(obj)->tp_name);
5179         return NULL;
5180     }
5181     if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
5182         return NULL;
5183 
5184     copyreg = import_copyreg();
5185     if (copyreg == NULL) {
5186         Py_XDECREF(args);
5187         Py_XDECREF(kwargs);
5188         return NULL;
5189     }
5190     hasargs = (args != NULL);
5191     if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
5192         _Py_IDENTIFIER(__newobj__);
5193         PyObject *cls;
5194         Py_ssize_t i, n;
5195 
5196         Py_XDECREF(kwargs);
5197         newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
5198         Py_DECREF(copyreg);
5199         if (newobj == NULL) {
5200             Py_XDECREF(args);
5201             return NULL;
5202         }
5203         n = args ? PyTuple_GET_SIZE(args) : 0;
5204         newargs = PyTuple_New(n+1);
5205         if (newargs == NULL) {
5206             Py_XDECREF(args);
5207             Py_DECREF(newobj);
5208             return NULL;
5209         }
5210         cls = (PyObject *) Py_TYPE(obj);
5211         Py_INCREF(cls);
5212         PyTuple_SET_ITEM(newargs, 0, cls);
5213         for (i = 0; i < n; i++) {
5214             PyObject *v = PyTuple_GET_ITEM(args, i);
5215             Py_INCREF(v);
5216             PyTuple_SET_ITEM(newargs, i+1, v);
5217         }
5218         Py_XDECREF(args);
5219     }
5220     else if (args != NULL) {
5221         _Py_IDENTIFIER(__newobj_ex__);
5222 
5223         newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
5224         Py_DECREF(copyreg);
5225         if (newobj == NULL) {
5226             Py_DECREF(args);
5227             Py_DECREF(kwargs);
5228             return NULL;
5229         }
5230         newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
5231         Py_DECREF(args);
5232         Py_DECREF(kwargs);
5233         if (newargs == NULL) {
5234             Py_DECREF(newobj);
5235             return NULL;
5236         }
5237     }
5238     else {
5239         /* args == NULL */
5240         Py_DECREF(kwargs);
5241         PyErr_BadInternalCall();
5242         return NULL;
5243     }
5244 
5245     state = _PyObject_GetState(obj,
5246                 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
5247     if (state == NULL) {
5248         Py_DECREF(newobj);
5249         Py_DECREF(newargs);
5250         return NULL;
5251     }
5252     if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
5253         Py_DECREF(newobj);
5254         Py_DECREF(newargs);
5255         Py_DECREF(state);
5256         return NULL;
5257     }
5258 
5259     result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
5260     Py_DECREF(newobj);
5261     Py_DECREF(newargs);
5262     Py_DECREF(state);
5263     Py_DECREF(listitems);
5264     Py_DECREF(dictitems);
5265     return result;
5266 }
5267 
5268 /*
5269  * There were two problems when object.__reduce__ and object.__reduce_ex__
5270  * were implemented in the same function:
5271  *  - trying to pickle an object with a custom __reduce__ method that
5272  *    fell back to object.__reduce__ in certain circumstances led to
5273  *    infinite recursion at Python level and eventual RecursionError.
5274  *  - Pickling objects that lied about their type by overwriting the
5275  *    __class__ descriptor could lead to infinite recursion at C level
5276  *    and eventual segfault.
5277  *
5278  * Because of backwards compatibility, the two methods still have to
5279  * behave in the same way, even if this is not required by the pickle
5280  * protocol. This common functionality was moved to the _common_reduce
5281  * function.
5282  */
5283 static PyObject *
_common_reduce(PyObject * self,int proto)5284 _common_reduce(PyObject *self, int proto)
5285 {
5286     PyObject *copyreg, *res;
5287 
5288     if (proto >= 2)
5289         return reduce_newobj(self);
5290 
5291     copyreg = import_copyreg();
5292     if (!copyreg)
5293         return NULL;
5294 
5295     res = PyObject_CallMethod(copyreg, "_reduce_ex", "Oi", self, proto);
5296     Py_DECREF(copyreg);
5297 
5298     return res;
5299 }
5300 
5301 /*[clinic input]
5302 object.__reduce__
5303 
5304 Helper for pickle.
5305 [clinic start generated code]*/
5306 
5307 static PyObject *
object___reduce___impl(PyObject * self)5308 object___reduce___impl(PyObject *self)
5309 /*[clinic end generated code: output=d4ca691f891c6e2f input=11562e663947e18b]*/
5310 {
5311     return _common_reduce(self, 0);
5312 }
5313 
5314 /*[clinic input]
5315 object.__reduce_ex__
5316 
5317   protocol: int
5318   /
5319 
5320 Helper for pickle.
5321 [clinic start generated code]*/
5322 
5323 static PyObject *
object___reduce_ex___impl(PyObject * self,int protocol)5324 object___reduce_ex___impl(PyObject *self, int protocol)
5325 /*[clinic end generated code: output=2e157766f6b50094 input=f326b43fb8a4c5ff]*/
5326 {
5327     static PyObject *objreduce;
5328     PyObject *reduce, *res;
5329     _Py_IDENTIFIER(__reduce__);
5330 
5331     if (objreduce == NULL) {
5332         objreduce = _PyDict_GetItemIdWithError(PyBaseObject_Type.tp_dict,
5333                                                &PyId___reduce__);
5334         if (objreduce == NULL && PyErr_Occurred()) {
5335             return NULL;
5336         }
5337     }
5338 
5339     if (_PyObject_LookupAttrId(self, &PyId___reduce__, &reduce) < 0) {
5340         return NULL;
5341     }
5342     if (reduce != NULL) {
5343         PyObject *cls, *clsreduce;
5344         int override;
5345 
5346         cls = (PyObject *) Py_TYPE(self);
5347         clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
5348         if (clsreduce == NULL) {
5349             Py_DECREF(reduce);
5350             return NULL;
5351         }
5352         override = (clsreduce != objreduce);
5353         Py_DECREF(clsreduce);
5354         if (override) {
5355             res = _PyObject_CallNoArg(reduce);
5356             Py_DECREF(reduce);
5357             return res;
5358         }
5359         else
5360             Py_DECREF(reduce);
5361     }
5362 
5363     return _common_reduce(self, protocol);
5364 }
5365 
5366 static PyObject *
object_subclasshook(PyObject * cls,PyObject * args)5367 object_subclasshook(PyObject *cls, PyObject *args)
5368 {
5369     Py_RETURN_NOTIMPLEMENTED;
5370 }
5371 
5372 PyDoc_STRVAR(object_subclasshook_doc,
5373 "Abstract classes can override this to customize issubclass().\n"
5374 "\n"
5375 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
5376 "It should return True, False or NotImplemented.  If it returns\n"
5377 "NotImplemented, the normal algorithm is used.  Otherwise, it\n"
5378 "overrides the normal algorithm (and the outcome is cached).\n");
5379 
5380 static PyObject *
object_init_subclass(PyObject * cls,PyObject * arg)5381 object_init_subclass(PyObject *cls, PyObject *arg)
5382 {
5383     Py_RETURN_NONE;
5384 }
5385 
5386 PyDoc_STRVAR(object_init_subclass_doc,
5387 "This method is called when a class is subclassed.\n"
5388 "\n"
5389 "The default implementation does nothing. It may be\n"
5390 "overridden to extend subclasses.\n");
5391 
5392 /*[clinic input]
5393 object.__format__
5394 
5395   format_spec: unicode
5396   /
5397 
5398 Default object formatter.
5399 [clinic start generated code]*/
5400 
5401 static PyObject *
object___format___impl(PyObject * self,PyObject * format_spec)5402 object___format___impl(PyObject *self, PyObject *format_spec)
5403 /*[clinic end generated code: output=34897efb543a974b input=7c3b3bc53a6fb7fa]*/
5404 {
5405     /* Issue 7994: If we're converting to a string, we
5406        should reject format specifications */
5407     if (PyUnicode_GET_LENGTH(format_spec) > 0) {
5408         PyErr_Format(PyExc_TypeError,
5409                      "unsupported format string passed to %.200s.__format__",
5410                      Py_TYPE(self)->tp_name);
5411         return NULL;
5412     }
5413     return PyObject_Str(self);
5414 }
5415 
5416 /*[clinic input]
5417 object.__sizeof__
5418 
5419 Size of object in memory, in bytes.
5420 [clinic start generated code]*/
5421 
5422 static PyObject *
object___sizeof___impl(PyObject * self)5423 object___sizeof___impl(PyObject *self)
5424 /*[clinic end generated code: output=73edab332f97d550 input=1200ff3dfe485306]*/
5425 {
5426     Py_ssize_t res, isize;
5427 
5428     res = 0;
5429     isize = Py_TYPE(self)->tp_itemsize;
5430     if (isize > 0)
5431         res = Py_SIZE(self) * isize;
5432     res += Py_TYPE(self)->tp_basicsize;
5433 
5434     return PyLong_FromSsize_t(res);
5435 }
5436 
5437 /* __dir__ for generic objects: returns __dict__, __class__,
5438    and recursively up the __class__.__bases__ chain.
5439 */
5440 /*[clinic input]
5441 object.__dir__
5442 
5443 Default dir() implementation.
5444 [clinic start generated code]*/
5445 
5446 static PyObject *
object___dir___impl(PyObject * self)5447 object___dir___impl(PyObject *self)
5448 /*[clinic end generated code: output=66dd48ea62f26c90 input=0a89305bec669b10]*/
5449 {
5450     PyObject *result = NULL;
5451     PyObject *dict = NULL;
5452     PyObject *itsclass = NULL;
5453 
5454     /* Get __dict__ (which may or may not be a real dict...) */
5455     if (_PyObject_LookupAttrId(self, &PyId___dict__, &dict) < 0) {
5456         return NULL;
5457     }
5458     if (dict == NULL) {
5459         dict = PyDict_New();
5460     }
5461     else if (!PyDict_Check(dict)) {
5462         Py_DECREF(dict);
5463         dict = PyDict_New();
5464     }
5465     else {
5466         /* Copy __dict__ to avoid mutating it. */
5467         PyObject *temp = PyDict_Copy(dict);
5468         Py_DECREF(dict);
5469         dict = temp;
5470     }
5471 
5472     if (dict == NULL)
5473         goto error;
5474 
5475     /* Merge in attrs reachable from its class. */
5476     if (_PyObject_LookupAttrId(self, &PyId___class__, &itsclass) < 0) {
5477         goto error;
5478     }
5479     /* XXX(tomer): Perhaps fall back to Py_TYPE(obj) if no
5480                    __class__ exists? */
5481     if (itsclass != NULL && merge_class_dict(dict, itsclass) < 0)
5482         goto error;
5483 
5484     result = PyDict_Keys(dict);
5485     /* fall through */
5486 error:
5487     Py_XDECREF(itsclass);
5488     Py_XDECREF(dict);
5489     return result;
5490 }
5491 
5492 static PyMethodDef object_methods[] = {
5493     OBJECT___REDUCE_EX___METHODDEF
5494     OBJECT___REDUCE___METHODDEF
5495     {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
5496      object_subclasshook_doc},
5497     {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
5498      object_init_subclass_doc},
5499     OBJECT___FORMAT___METHODDEF
5500     OBJECT___SIZEOF___METHODDEF
5501     OBJECT___DIR___METHODDEF
5502     {0}
5503 };
5504 
5505 PyDoc_STRVAR(object_doc,
5506 "object()\n--\n\n"
5507 "The base class of the class hierarchy.\n\n"
5508 "When called, it accepts no arguments and returns a new featureless\n"
5509 "instance that has no instance attributes and cannot be given any.\n");
5510 
5511 PyTypeObject PyBaseObject_Type = {
5512     PyVarObject_HEAD_INIT(&PyType_Type, 0)
5513     "object",                                   /* tp_name */
5514     sizeof(PyObject),                           /* tp_basicsize */
5515     0,                                          /* tp_itemsize */
5516     object_dealloc,                             /* tp_dealloc */
5517     0,                                          /* tp_vectorcall_offset */
5518     0,                                          /* tp_getattr */
5519     0,                                          /* tp_setattr */
5520     0,                                          /* tp_as_async */
5521     object_repr,                                /* tp_repr */
5522     0,                                          /* tp_as_number */
5523     0,                                          /* tp_as_sequence */
5524     0,                                          /* tp_as_mapping */
5525     (hashfunc)_Py_HashPointer,                  /* tp_hash */
5526     0,                                          /* tp_call */
5527     object_str,                                 /* tp_str */
5528     PyObject_GenericGetAttr,                    /* tp_getattro */
5529     PyObject_GenericSetAttr,                    /* tp_setattro */
5530     0,                                          /* tp_as_buffer */
5531     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
5532     object_doc,                                 /* tp_doc */
5533     0,                                          /* tp_traverse */
5534     0,                                          /* tp_clear */
5535     object_richcompare,                         /* tp_richcompare */
5536     0,                                          /* tp_weaklistoffset */
5537     0,                                          /* tp_iter */
5538     0,                                          /* tp_iternext */
5539     object_methods,                             /* tp_methods */
5540     0,                                          /* tp_members */
5541     object_getsets,                             /* tp_getset */
5542     0,                                          /* tp_base */
5543     0,                                          /* tp_dict */
5544     0,                                          /* tp_descr_get */
5545     0,                                          /* tp_descr_set */
5546     0,                                          /* tp_dictoffset */
5547     object_init,                                /* tp_init */
5548     PyType_GenericAlloc,                        /* tp_alloc */
5549     object_new,                                 /* tp_new */
5550     PyObject_Del,                               /* tp_free */
5551 };
5552 
5553 
5554 static int
type_add_method(PyTypeObject * type,PyMethodDef * meth)5555 type_add_method(PyTypeObject *type, PyMethodDef *meth)
5556 {
5557     PyObject *descr;
5558     int isdescr = 1;
5559     if (meth->ml_flags & METH_CLASS) {
5560         if (meth->ml_flags & METH_STATIC) {
5561             PyErr_SetString(PyExc_ValueError,
5562                     "method cannot be both class and static");
5563             return -1;
5564         }
5565         descr = PyDescr_NewClassMethod(type, meth);
5566     }
5567     else if (meth->ml_flags & METH_STATIC) {
5568         PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
5569         if (cfunc == NULL) {
5570             return -1;
5571         }
5572         descr = PyStaticMethod_New(cfunc);
5573         isdescr = 0;  // PyStaticMethod is not PyDescrObject
5574         Py_DECREF(cfunc);
5575     }
5576     else {
5577         descr = PyDescr_NewMethod(type, meth);
5578     }
5579     if (descr == NULL) {
5580         return -1;
5581     }
5582 
5583     PyObject *name;
5584     if (isdescr) {
5585         name = PyDescr_NAME(descr);
5586     }
5587     else {
5588         name = PyUnicode_FromString(meth->ml_name);
5589         if (name == NULL) {
5590             Py_DECREF(descr);
5591             return -1;
5592         }
5593     }
5594 
5595     int err;
5596     if (!(meth->ml_flags & METH_COEXIST)) {
5597         err = PyDict_SetDefault(type->tp_dict, name, descr) == NULL;
5598     }
5599     else {
5600         err = PyDict_SetItem(type->tp_dict, name, descr) < 0;
5601     }
5602     if (!isdescr) {
5603         Py_DECREF(name);
5604     }
5605     Py_DECREF(descr);
5606     if (err) {
5607         return -1;
5608     }
5609     return 0;
5610 }
5611 
5612 
5613 /* Add the methods from tp_methods to the __dict__ in a type object */
5614 static int
type_add_methods(PyTypeObject * type)5615 type_add_methods(PyTypeObject *type)
5616 {
5617     PyMethodDef *meth = type->tp_methods;
5618     if (meth == NULL) {
5619         return 0;
5620     }
5621 
5622     for (; meth->ml_name != NULL; meth++) {
5623         if (type_add_method(type, meth) < 0) {
5624             return -1;
5625         }
5626     }
5627     return 0;
5628 }
5629 
5630 
5631 static int
type_add_members(PyTypeObject * type)5632 type_add_members(PyTypeObject *type)
5633 {
5634     PyMemberDef *memb = type->tp_members;
5635     if (memb == NULL) {
5636         return 0;
5637     }
5638 
5639     PyObject *dict = type->tp_dict;
5640     for (; memb->name != NULL; memb++) {
5641         PyObject *descr = PyDescr_NewMember(type, memb);
5642         if (descr == NULL)
5643             return -1;
5644 
5645         if (PyDict_SetDefault(dict, PyDescr_NAME(descr), descr) == NULL) {
5646             Py_DECREF(descr);
5647             return -1;
5648         }
5649         Py_DECREF(descr);
5650     }
5651     return 0;
5652 }
5653 
5654 
5655 static int
type_add_getset(PyTypeObject * type)5656 type_add_getset(PyTypeObject *type)
5657 {
5658     PyGetSetDef *gsp = type->tp_getset;
5659     if (gsp == NULL) {
5660         return 0;
5661     }
5662 
5663     PyObject *dict = type->tp_dict;
5664     for (; gsp->name != NULL; gsp++) {
5665         PyObject *descr = PyDescr_NewGetSet(type, gsp);
5666         if (descr == NULL) {
5667             return -1;
5668         }
5669 
5670         if (PyDict_SetDefault(dict, PyDescr_NAME(descr), descr) == NULL) {
5671             Py_DECREF(descr);
5672             return -1;
5673         }
5674         Py_DECREF(descr);
5675     }
5676     return 0;
5677 }
5678 
5679 
5680 static void
inherit_special(PyTypeObject * type,PyTypeObject * base)5681 inherit_special(PyTypeObject *type, PyTypeObject *base)
5682 {
5683     /* Copying tp_traverse and tp_clear is connected to the GC flags */
5684     if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
5685         (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
5686         (!type->tp_traverse && !type->tp_clear)) {
5687         type->tp_flags |= Py_TPFLAGS_HAVE_GC;
5688         if (type->tp_traverse == NULL)
5689             type->tp_traverse = base->tp_traverse;
5690         if (type->tp_clear == NULL)
5691             type->tp_clear = base->tp_clear;
5692     }
5693 
5694     if (type->tp_basicsize == 0)
5695         type->tp_basicsize = base->tp_basicsize;
5696 
5697     /* Copy other non-function slots */
5698 
5699 #define COPYVAL(SLOT) \
5700     if (type->SLOT == 0) { type->SLOT = base->SLOT; }
5701 
5702     COPYVAL(tp_itemsize);
5703     COPYVAL(tp_weaklistoffset);
5704     COPYVAL(tp_dictoffset);
5705 #undef COPYVAL
5706 
5707     /* Setup fast subclass flags */
5708     if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) {
5709         type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
5710     }
5711     else if (PyType_IsSubtype(base, &PyType_Type)) {
5712         type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
5713     }
5714     else if (PyType_IsSubtype(base, &PyLong_Type)) {
5715         type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
5716     }
5717     else if (PyType_IsSubtype(base, &PyBytes_Type)) {
5718         type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
5719     }
5720     else if (PyType_IsSubtype(base, &PyUnicode_Type)) {
5721         type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
5722     }
5723     else if (PyType_IsSubtype(base, &PyTuple_Type)) {
5724         type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
5725     }
5726     else if (PyType_IsSubtype(base, &PyList_Type)) {
5727         type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
5728     }
5729     else if (PyType_IsSubtype(base, &PyDict_Type)) {
5730         type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
5731     }
5732     if (PyType_HasFeature(base, _Py_TPFLAGS_MATCH_SELF)) {
5733         type->tp_flags |= _Py_TPFLAGS_MATCH_SELF;
5734     }
5735 }
5736 
5737 static int
overrides_hash(PyTypeObject * type)5738 overrides_hash(PyTypeObject *type)
5739 {
5740     PyObject *dict = type->tp_dict;
5741     _Py_IDENTIFIER(__eq__);
5742 
5743     assert(dict != NULL);
5744     int r = _PyDict_ContainsId(dict, &PyId___eq__);
5745     if (r == 0) {
5746         r = _PyDict_ContainsId(dict, &PyId___hash__);
5747     }
5748     return r;
5749 }
5750 
5751 static int
inherit_slots(PyTypeObject * type,PyTypeObject * base)5752 inherit_slots(PyTypeObject *type, PyTypeObject *base)
5753 {
5754     PyTypeObject *basebase;
5755 
5756 #undef SLOTDEFINED
5757 #undef COPYSLOT
5758 #undef COPYNUM
5759 #undef COPYSEQ
5760 #undef COPYMAP
5761 #undef COPYBUF
5762 
5763 #define SLOTDEFINED(SLOT) \
5764     (base->SLOT != 0 && \
5765      (basebase == NULL || base->SLOT != basebase->SLOT))
5766 
5767 #define COPYSLOT(SLOT) \
5768     if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
5769 
5770 #define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
5771 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
5772 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
5773 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
5774 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
5775 
5776     /* This won't inherit indirect slots (from tp_as_number etc.)
5777        if type doesn't provide the space. */
5778 
5779     if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
5780         basebase = base->tp_base;
5781         if (basebase->tp_as_number == NULL)
5782             basebase = NULL;
5783         COPYNUM(nb_add);
5784         COPYNUM(nb_subtract);
5785         COPYNUM(nb_multiply);
5786         COPYNUM(nb_remainder);
5787         COPYNUM(nb_divmod);
5788         COPYNUM(nb_power);
5789         COPYNUM(nb_negative);
5790         COPYNUM(nb_positive);
5791         COPYNUM(nb_absolute);
5792         COPYNUM(nb_bool);
5793         COPYNUM(nb_invert);
5794         COPYNUM(nb_lshift);
5795         COPYNUM(nb_rshift);
5796         COPYNUM(nb_and);
5797         COPYNUM(nb_xor);
5798         COPYNUM(nb_or);
5799         COPYNUM(nb_int);
5800         COPYNUM(nb_float);
5801         COPYNUM(nb_inplace_add);
5802         COPYNUM(nb_inplace_subtract);
5803         COPYNUM(nb_inplace_multiply);
5804         COPYNUM(nb_inplace_remainder);
5805         COPYNUM(nb_inplace_power);
5806         COPYNUM(nb_inplace_lshift);
5807         COPYNUM(nb_inplace_rshift);
5808         COPYNUM(nb_inplace_and);
5809         COPYNUM(nb_inplace_xor);
5810         COPYNUM(nb_inplace_or);
5811         COPYNUM(nb_true_divide);
5812         COPYNUM(nb_floor_divide);
5813         COPYNUM(nb_inplace_true_divide);
5814         COPYNUM(nb_inplace_floor_divide);
5815         COPYNUM(nb_index);
5816         COPYNUM(nb_matrix_multiply);
5817         COPYNUM(nb_inplace_matrix_multiply);
5818     }
5819 
5820     if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
5821         basebase = base->tp_base;
5822         if (basebase->tp_as_async == NULL)
5823             basebase = NULL;
5824         COPYASYNC(am_await);
5825         COPYASYNC(am_aiter);
5826         COPYASYNC(am_anext);
5827     }
5828 
5829     if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
5830         basebase = base->tp_base;
5831         if (basebase->tp_as_sequence == NULL)
5832             basebase = NULL;
5833         COPYSEQ(sq_length);
5834         COPYSEQ(sq_concat);
5835         COPYSEQ(sq_repeat);
5836         COPYSEQ(sq_item);
5837         COPYSEQ(sq_ass_item);
5838         COPYSEQ(sq_contains);
5839         COPYSEQ(sq_inplace_concat);
5840         COPYSEQ(sq_inplace_repeat);
5841     }
5842 
5843     if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
5844         basebase = base->tp_base;
5845         if (basebase->tp_as_mapping == NULL)
5846             basebase = NULL;
5847         COPYMAP(mp_length);
5848         COPYMAP(mp_subscript);
5849         COPYMAP(mp_ass_subscript);
5850     }
5851 
5852     if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
5853         basebase = base->tp_base;
5854         if (basebase->tp_as_buffer == NULL)
5855             basebase = NULL;
5856         COPYBUF(bf_getbuffer);
5857         COPYBUF(bf_releasebuffer);
5858     }
5859 
5860     basebase = base->tp_base;
5861 
5862     COPYSLOT(tp_dealloc);
5863     if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
5864         type->tp_getattr = base->tp_getattr;
5865         type->tp_getattro = base->tp_getattro;
5866     }
5867     if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
5868         type->tp_setattr = base->tp_setattr;
5869         type->tp_setattro = base->tp_setattro;
5870     }
5871     COPYSLOT(tp_repr);
5872     /* tp_hash see tp_richcompare */
5873     {
5874         /* Always inherit tp_vectorcall_offset to support PyVectorcall_Call().
5875          * If Py_TPFLAGS_HAVE_VECTORCALL is not inherited, then vectorcall
5876          * won't be used automatically. */
5877         COPYSLOT(tp_vectorcall_offset);
5878 
5879         /* Inherit Py_TPFLAGS_HAVE_VECTORCALL for non-heap types
5880         * if tp_call is not overridden */
5881         if (!type->tp_call &&
5882             (base->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) &&
5883             !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
5884         {
5885             type->tp_flags |= Py_TPFLAGS_HAVE_VECTORCALL;
5886         }
5887         COPYSLOT(tp_call);
5888     }
5889     COPYSLOT(tp_str);
5890     {
5891         /* Copy comparison-related slots only when
5892            not overriding them anywhere */
5893         if (type->tp_richcompare == NULL &&
5894             type->tp_hash == NULL)
5895         {
5896             int r = overrides_hash(type);
5897             if (r < 0) {
5898                 return -1;
5899             }
5900             if (!r) {
5901                 type->tp_richcompare = base->tp_richcompare;
5902                 type->tp_hash = base->tp_hash;
5903             }
5904         }
5905     }
5906     {
5907         COPYSLOT(tp_iter);
5908         COPYSLOT(tp_iternext);
5909     }
5910     {
5911         COPYSLOT(tp_descr_get);
5912         /* Inherit Py_TPFLAGS_METHOD_DESCRIPTOR if tp_descr_get was inherited,
5913          * but only for extension types */
5914         if (base->tp_descr_get &&
5915             type->tp_descr_get == base->tp_descr_get &&
5916             !(type->tp_flags & Py_TPFLAGS_HEAPTYPE) &&
5917             (base->tp_flags & Py_TPFLAGS_METHOD_DESCRIPTOR))
5918         {
5919             type->tp_flags |= Py_TPFLAGS_METHOD_DESCRIPTOR;
5920         }
5921         COPYSLOT(tp_descr_set);
5922         COPYSLOT(tp_dictoffset);
5923         COPYSLOT(tp_init);
5924         COPYSLOT(tp_alloc);
5925         COPYSLOT(tp_is_gc);
5926         COPYSLOT(tp_finalize);
5927         if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
5928             (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
5929             /* They agree about gc. */
5930             COPYSLOT(tp_free);
5931         }
5932         else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
5933                  type->tp_free == NULL &&
5934                  base->tp_free == PyObject_Free) {
5935             /* A bit of magic to plug in the correct default
5936              * tp_free function when a derived class adds gc,
5937              * didn't define tp_free, and the base uses the
5938              * default non-gc tp_free.
5939              */
5940             type->tp_free = PyObject_GC_Del;
5941         }
5942         /* else they didn't agree about gc, and there isn't something
5943          * obvious to be done -- the type is on its own.
5944          */
5945     }
5946     return 0;
5947 }
5948 
5949 static int add_operators(PyTypeObject *);
5950 static int add_tp_new_wrapper(PyTypeObject *type);
5951 
5952 #define COLLECTION_FLAGS (Py_TPFLAGS_SEQUENCE | Py_TPFLAGS_MAPPING)
5953 
5954 static int
type_ready_checks(PyTypeObject * type)5955 type_ready_checks(PyTypeObject *type)
5956 {
5957     /* Consistency checks for PEP 590:
5958      * - Py_TPFLAGS_METHOD_DESCRIPTOR requires tp_descr_get
5959      * - Py_TPFLAGS_HAVE_VECTORCALL requires tp_call and
5960      *   tp_vectorcall_offset > 0
5961      * To avoid mistakes, we require this before inheriting.
5962      */
5963     if (type->tp_flags & Py_TPFLAGS_METHOD_DESCRIPTOR) {
5964         _PyObject_ASSERT((PyObject *)type, type->tp_descr_get != NULL);
5965     }
5966     if (type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) {
5967         _PyObject_ASSERT((PyObject *)type, type->tp_vectorcall_offset > 0);
5968         _PyObject_ASSERT((PyObject *)type, type->tp_call != NULL);
5969     }
5970 
5971     /* Consistency checks for pattern matching
5972      * Py_TPFLAGS_SEQUENCE and Py_TPFLAGS_MAPPING are mutually exclusive */
5973     _PyObject_ASSERT((PyObject *)type, (type->tp_flags & COLLECTION_FLAGS) != COLLECTION_FLAGS);
5974 
5975     if (type->tp_name == NULL) {
5976         PyErr_Format(PyExc_SystemError,
5977                      "Type does not define the tp_name field.");
5978         return -1;
5979     }
5980     return 0;
5981 }
5982 
5983 
5984 static int
type_ready_set_bases(PyTypeObject * type)5985 type_ready_set_bases(PyTypeObject *type)
5986 {
5987     /* Initialize tp_base (defaults to BaseObject unless that's us) */
5988     PyTypeObject *base = type->tp_base;
5989     if (base == NULL && type != &PyBaseObject_Type) {
5990         base = &PyBaseObject_Type;
5991         if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
5992             type->tp_base = (PyTypeObject*)Py_NewRef((PyObject*)base);
5993         }
5994         else {
5995             type->tp_base = base;
5996         }
5997     }
5998     assert(type->tp_base != NULL || type == &PyBaseObject_Type);
5999 
6000     /* Now the only way base can still be NULL is if type is
6001      * &PyBaseObject_Type. */
6002 
6003     /* Initialize the base class */
6004     if (base != NULL && !_PyType_IsReady(base)) {
6005         if (PyType_Ready(base) < 0) {
6006             return -1;
6007         }
6008     }
6009 
6010     /* Initialize ob_type if NULL.      This means extensions that want to be
6011        compilable separately on Windows can call PyType_Ready() instead of
6012        initializing the ob_type field of their type objects. */
6013     /* The test for base != NULL is really unnecessary, since base is only
6014        NULL when type is &PyBaseObject_Type, and we know its ob_type is
6015        not NULL (it's initialized to &PyType_Type).      But coverity doesn't
6016        know that. */
6017     if (Py_IS_TYPE(type, NULL) && base != NULL) {
6018         Py_SET_TYPE(type, Py_TYPE(base));
6019     }
6020 
6021     /* Initialize tp_bases */
6022     PyObject *bases = type->tp_bases;
6023     if (bases == NULL) {
6024         PyTypeObject *base = type->tp_base;
6025         if (base == NULL) {
6026             bases = PyTuple_New(0);
6027         }
6028         else {
6029             bases = PyTuple_Pack(1, base);
6030         }
6031         if (bases == NULL) {
6032             return -1;
6033         }
6034         type->tp_bases = bases;
6035     }
6036     return 0;
6037 }
6038 
6039 
6040 static int
type_ready_set_dict(PyTypeObject * type)6041 type_ready_set_dict(PyTypeObject *type)
6042 {
6043     if (type->tp_dict != NULL) {
6044         return 0;
6045     }
6046 
6047     PyObject *dict = PyDict_New();
6048     if (dict == NULL) {
6049         return -1;
6050     }
6051     type->tp_dict = dict;
6052     return 0;
6053 }
6054 
6055 
6056 /* If the type dictionary doesn't contain a __doc__, set it from
6057    the tp_doc slot. */
6058 static int
type_dict_set_doc(PyTypeObject * type)6059 type_dict_set_doc(PyTypeObject *type)
6060 {
6061     int r = _PyDict_ContainsId(type->tp_dict, &PyId___doc__);
6062     if (r < 0) {
6063         return -1;
6064     }
6065     if (r > 0) {
6066         return 0;
6067     }
6068 
6069     if (type->tp_doc != NULL) {
6070         const char *doc_str;
6071         doc_str = _PyType_DocWithoutSignature(type->tp_name, type->tp_doc);
6072         PyObject *doc = PyUnicode_FromString(doc_str);
6073         if (doc == NULL) {
6074             return -1;
6075         }
6076 
6077         if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
6078             Py_DECREF(doc);
6079             return -1;
6080         }
6081         Py_DECREF(doc);
6082     }
6083     else {
6084         if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, Py_None) < 0) {
6085             return -1;
6086         }
6087     }
6088     return 0;
6089 }
6090 
6091 
6092 static int
type_ready_fill_dict(PyTypeObject * type)6093 type_ready_fill_dict(PyTypeObject *type)
6094 {
6095     /* Add type-specific descriptors to tp_dict */
6096     if (add_operators(type) < 0) {
6097         return -1;
6098     }
6099     if (type_add_methods(type) < 0) {
6100         return -1;
6101     }
6102     if (type_add_members(type) < 0) {
6103         return -1;
6104     }
6105     if (type_add_getset(type) < 0) {
6106         return -1;
6107     }
6108     if (type_dict_set_doc(type) < 0) {
6109         return -1;
6110     }
6111     return 0;
6112 }
6113 
6114 
6115 static int
type_ready_mro(PyTypeObject * type)6116 type_ready_mro(PyTypeObject *type)
6117 {
6118     /* Calculate method resolution order */
6119     if (mro_internal(type, NULL) < 0) {
6120         return -1;
6121     }
6122     assert(type->tp_mro != NULL);
6123     assert(PyTuple_Check(type->tp_mro));
6124 
6125     /* All bases of statically allocated type should be statically allocated */
6126     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
6127         PyObject *mro = type->tp_mro;
6128         Py_ssize_t n = PyTuple_GET_SIZE(mro);
6129         for (Py_ssize_t i = 0; i < n; i++) {
6130             PyTypeObject *base = (PyTypeObject *)PyTuple_GET_ITEM(mro, i);
6131             if (PyType_Check(base) && (base->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
6132                 PyErr_Format(PyExc_TypeError,
6133                              "type '%.100s' is not dynamically allocated but "
6134                              "its base type '%.100s' is dynamically allocated",
6135                              type->tp_name, base->tp_name);
6136                 return -1;
6137             }
6138         }
6139     }
6140     return 0;
6141 }
6142 
6143 
6144 // For static types, inherit tp_as_xxx structures from the base class
6145 // if it's NULL.
6146 //
6147 // For heap types, tp_as_xxx structures are not NULL: they are set to the
6148 // PyHeapTypeObject.as_xxx fields by type_new_alloc().
6149 static void
type_ready_inherit_as_structs(PyTypeObject * type,PyTypeObject * base)6150 type_ready_inherit_as_structs(PyTypeObject *type, PyTypeObject *base)
6151 {
6152     if (type->tp_as_async == NULL) {
6153         type->tp_as_async = base->tp_as_async;
6154     }
6155     if (type->tp_as_number == NULL) {
6156         type->tp_as_number = base->tp_as_number;
6157     }
6158     if (type->tp_as_sequence == NULL) {
6159         type->tp_as_sequence = base->tp_as_sequence;
6160     }
6161     if (type->tp_as_mapping == NULL) {
6162         type->tp_as_mapping = base->tp_as_mapping;
6163     }
6164     if (type->tp_as_buffer == NULL) {
6165         type->tp_as_buffer = base->tp_as_buffer;
6166     }
6167 }
6168 
6169 static void
inherit_patma_flags(PyTypeObject * type,PyTypeObject * base)6170 inherit_patma_flags(PyTypeObject *type, PyTypeObject *base) {
6171     if ((type->tp_flags & COLLECTION_FLAGS) == 0) {
6172         type->tp_flags |= base->tp_flags & COLLECTION_FLAGS;
6173     }
6174 }
6175 
6176 static int
type_ready_inherit(PyTypeObject * type)6177 type_ready_inherit(PyTypeObject *type)
6178 {
6179     /* Inherit special flags from dominant base */
6180     PyTypeObject *base = type->tp_base;
6181     if (base != NULL) {
6182         inherit_special(type, base);
6183     }
6184 
6185     // Inherit slots
6186     PyObject *mro = type->tp_mro;
6187     Py_ssize_t n = PyTuple_GET_SIZE(type->tp_mro);
6188     for (Py_ssize_t i = 1; i < n; i++) {
6189         PyObject *b = PyTuple_GET_ITEM(mro, i);
6190         if (PyType_Check(b)) {
6191             if (inherit_slots(type, (PyTypeObject *)b) < 0) {
6192                 return -1;
6193             }
6194             inherit_patma_flags(type, (PyTypeObject *)b);
6195         }
6196     }
6197 
6198     if (base != NULL) {
6199         type_ready_inherit_as_structs(type, base);
6200     }
6201 
6202     /* Sanity check for tp_free. */
6203     if (_PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
6204         (type->tp_free == NULL || type->tp_free == PyObject_Del))
6205     {
6206         /* This base class needs to call tp_free, but doesn't have
6207          * one, or its tp_free is for non-gc'ed objects.
6208          */
6209         PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
6210                      "gc and is a base type but has inappropriate "
6211                      "tp_free slot",
6212                      type->tp_name);
6213         return -1;
6214     }
6215 
6216     return 0;
6217 }
6218 
6219 
6220 /* Hack for tp_hash and __hash__.
6221    If after all that, tp_hash is still NULL, and __hash__ is not in
6222    tp_dict, set tp_hash to PyObject_HashNotImplemented and
6223    tp_dict['__hash__'] equal to None.
6224    This signals that __hash__ is not inherited. */
6225 static int
type_ready_set_hash(PyTypeObject * type)6226 type_ready_set_hash(PyTypeObject *type)
6227 {
6228     if (type->tp_hash != NULL) {
6229         return 0;
6230     }
6231 
6232     int r = _PyDict_ContainsId(type->tp_dict, &PyId___hash__);
6233     if (r < 0) {
6234         return -1;
6235     }
6236     if (r > 0) {
6237         return 0;
6238     }
6239 
6240     if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0) {
6241         return -1;
6242     }
6243     type->tp_hash = PyObject_HashNotImplemented;
6244     return 0;
6245 }
6246 
6247 
6248 /* Link into each base class's list of subclasses */
6249 static int
type_ready_add_subclasses(PyTypeObject * type)6250 type_ready_add_subclasses(PyTypeObject *type)
6251 {
6252     PyObject *bases = type->tp_bases;
6253     Py_ssize_t nbase = PyTuple_GET_SIZE(bases);
6254     for (Py_ssize_t i = 0; i < nbase; i++) {
6255         PyObject *b = PyTuple_GET_ITEM(bases, i);
6256         if (PyType_Check(b) && add_subclass((PyTypeObject *)b, type) < 0) {
6257             return -1;
6258         }
6259     }
6260     return 0;
6261 }
6262 
6263 
6264 // Set tp_new and the "__new__" key in the type dictionary.
6265 // Use the Py_TPFLAGS_DISALLOW_INSTANTIATION flag.
6266 static int
type_ready_set_new(PyTypeObject * type)6267 type_ready_set_new(PyTypeObject *type)
6268 {
6269     PyTypeObject *base = type->tp_base;
6270     /* The condition below could use some explanation.
6271 
6272        It appears that tp_new is not inherited for static types whose base
6273        class is 'object'; this seems to be a precaution so that old extension
6274        types don't suddenly become callable (object.__new__ wouldn't insure the
6275        invariants that the extension type's own factory function ensures).
6276 
6277        Heap types, of course, are under our control, so they do inherit tp_new;
6278        static extension types that specify some other built-in type as the
6279        default also inherit object.__new__. */
6280     if (type->tp_new == NULL
6281         && base == &PyBaseObject_Type
6282         && !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
6283     {
6284         type->tp_flags |= Py_TPFLAGS_DISALLOW_INSTANTIATION;
6285     }
6286 
6287     if (!(type->tp_flags & Py_TPFLAGS_DISALLOW_INSTANTIATION)) {
6288         if (type->tp_new != NULL) {
6289             // If "__new__" key does not exists in the type dictionary,
6290             // set it to tp_new_wrapper().
6291             if (add_tp_new_wrapper(type) < 0) {
6292                 return -1;
6293             }
6294         }
6295         else {
6296             // tp_new is NULL: inherit tp_new from base
6297             type->tp_new = base->tp_new;
6298         }
6299     }
6300     else {
6301         // Py_TPFLAGS_DISALLOW_INSTANTIATION sets tp_new to NULL
6302         type->tp_new = NULL;
6303     }
6304     return 0;
6305 }
6306 
6307 
6308 static int
type_ready(PyTypeObject * type)6309 type_ready(PyTypeObject *type)
6310 {
6311     if (type_ready_checks(type) < 0) {
6312         return -1;
6313     }
6314 
6315 #ifdef Py_TRACE_REFS
6316     /* PyType_Ready is the closest thing we have to a choke point
6317      * for type objects, so is the best place I can think of to try
6318      * to get type objects into the doubly-linked list of all objects.
6319      * Still, not all type objects go through PyType_Ready.
6320      */
6321     _Py_AddToAllObjects((PyObject *)type, 0);
6322 #endif
6323 
6324     /* Initialize tp_dict: _PyType_IsReady() tests if tp_dict != NULL */
6325     if (type_ready_set_dict(type) < 0) {
6326         return -1;
6327     }
6328     if (type_ready_set_bases(type) < 0) {
6329         return -1;
6330     }
6331     if (type_ready_mro(type) < 0) {
6332         return -1;
6333     }
6334     if (type_ready_set_new(type) < 0) {
6335         return -1;
6336     }
6337     if (type_ready_fill_dict(type) < 0) {
6338         return -1;
6339     }
6340     if (type_ready_inherit(type) < 0) {
6341         return -1;
6342     }
6343     if (type_ready_set_hash(type) < 0) {
6344         return -1;
6345     }
6346     if (type_ready_add_subclasses(type) < 0) {
6347         return -1;
6348     }
6349     return 0;
6350 }
6351 
6352 
6353 int
PyType_Ready(PyTypeObject * type)6354 PyType_Ready(PyTypeObject *type)
6355 {
6356     if (type->tp_flags & Py_TPFLAGS_READY) {
6357         assert(_PyType_CheckConsistency(type));
6358         return 0;
6359     }
6360     _PyObject_ASSERT((PyObject *)type,
6361                      (type->tp_flags & Py_TPFLAGS_READYING) == 0);
6362 
6363     type->tp_flags |= Py_TPFLAGS_READYING;
6364 
6365     /* Historically, all static types were immutable. See bpo-43908 */
6366     if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
6367         type->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE;
6368     }
6369 
6370     if (type_ready(type) < 0) {
6371         type->tp_flags &= ~Py_TPFLAGS_READYING;
6372         return -1;
6373     }
6374 
6375     /* All done -- set the ready flag */
6376     type->tp_flags = (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
6377     assert(_PyType_CheckConsistency(type));
6378     return 0;
6379 }
6380 
6381 
6382 static int
add_subclass(PyTypeObject * base,PyTypeObject * type)6383 add_subclass(PyTypeObject *base, PyTypeObject *type)
6384 {
6385     PyObject *key = PyLong_FromVoidPtr((void *) type);
6386     if (key == NULL)
6387         return -1;
6388 
6389     PyObject *ref = PyWeakref_NewRef((PyObject *)type, NULL);
6390     if (ref == NULL) {
6391         Py_DECREF(key);
6392         return -1;
6393     }
6394 
6395     // Only get tp_subclasses after creating the key and value.
6396     // PyWeakref_NewRef() can trigger a garbage collection which can execute
6397     // arbitrary Python code and so modify base->tp_subclasses.
6398     PyObject *dict = base->tp_subclasses;
6399     if (dict == NULL) {
6400         base->tp_subclasses = dict = PyDict_New();
6401         if (dict == NULL)
6402             return -1;
6403     }
6404     assert(PyDict_CheckExact(dict));
6405 
6406     int result = PyDict_SetItem(dict, key, ref);
6407     Py_DECREF(ref);
6408     Py_DECREF(key);
6409     return result;
6410 }
6411 
6412 static int
add_all_subclasses(PyTypeObject * type,PyObject * bases)6413 add_all_subclasses(PyTypeObject *type, PyObject *bases)
6414 {
6415     int res = 0;
6416 
6417     if (bases) {
6418         Py_ssize_t i;
6419         for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
6420             PyObject *base = PyTuple_GET_ITEM(bases, i);
6421             if (PyType_Check(base) &&
6422                 add_subclass((PyTypeObject*)base, type) < 0)
6423                 res = -1;
6424         }
6425     }
6426 
6427     return res;
6428 }
6429 
6430 static void
remove_subclass(PyTypeObject * base,PyTypeObject * type)6431 remove_subclass(PyTypeObject *base, PyTypeObject *type)
6432 {
6433     PyObject *dict, *key;
6434 
6435     dict = base->tp_subclasses;
6436     if (dict == NULL) {
6437         return;
6438     }
6439     assert(PyDict_CheckExact(dict));
6440     key = PyLong_FromVoidPtr((void *) type);
6441     if (key == NULL || PyDict_DelItem(dict, key)) {
6442         /* This can happen if the type initialization errored out before
6443            the base subclasses were updated (e.g. a non-str __qualname__
6444            was passed in the type dict). */
6445         PyErr_Clear();
6446     }
6447     Py_XDECREF(key);
6448 }
6449 
6450 static void
remove_all_subclasses(PyTypeObject * type,PyObject * bases)6451 remove_all_subclasses(PyTypeObject *type, PyObject *bases)
6452 {
6453     if (bases) {
6454         Py_ssize_t i;
6455         for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
6456             PyObject *base = PyTuple_GET_ITEM(bases, i);
6457             if (PyType_Check(base))
6458                 remove_subclass((PyTypeObject*) base, type);
6459         }
6460     }
6461 }
6462 
6463 static int
check_num_args(PyObject * ob,int n)6464 check_num_args(PyObject *ob, int n)
6465 {
6466     if (!PyTuple_CheckExact(ob)) {
6467         PyErr_SetString(PyExc_SystemError,
6468             "PyArg_UnpackTuple() argument list is not a tuple");
6469         return 0;
6470     }
6471     if (n == PyTuple_GET_SIZE(ob))
6472         return 1;
6473     PyErr_Format(
6474         PyExc_TypeError,
6475         "expected %d argument%s, got %zd", n, n == 1 ? "" : "s", PyTuple_GET_SIZE(ob));
6476     return 0;
6477 }
6478 
6479 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
6480 
6481 /* There's a wrapper *function* for each distinct function typedef used
6482    for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
6483    wrapper *table* for each distinct operation (e.g. __len__, __add__).
6484    Most tables have only one entry; the tables for binary operators have two
6485    entries, one regular and one with reversed arguments. */
6486 
6487 static PyObject *
wrap_lenfunc(PyObject * self,PyObject * args,void * wrapped)6488 wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
6489 {
6490     lenfunc func = (lenfunc)wrapped;
6491     Py_ssize_t res;
6492 
6493     if (!check_num_args(args, 0))
6494         return NULL;
6495     res = (*func)(self);
6496     if (res == -1 && PyErr_Occurred())
6497         return NULL;
6498     return PyLong_FromSsize_t(res);
6499 }
6500 
6501 static PyObject *
wrap_inquirypred(PyObject * self,PyObject * args,void * wrapped)6502 wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
6503 {
6504     inquiry func = (inquiry)wrapped;
6505     int res;
6506 
6507     if (!check_num_args(args, 0))
6508         return NULL;
6509     res = (*func)(self);
6510     if (res == -1 && PyErr_Occurred())
6511         return NULL;
6512     return PyBool_FromLong((long)res);
6513 }
6514 
6515 static PyObject *
wrap_binaryfunc(PyObject * self,PyObject * args,void * wrapped)6516 wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
6517 {
6518     binaryfunc func = (binaryfunc)wrapped;
6519     PyObject *other;
6520 
6521     if (!check_num_args(args, 1))
6522         return NULL;
6523     other = PyTuple_GET_ITEM(args, 0);
6524     return (*func)(self, other);
6525 }
6526 
6527 static PyObject *
wrap_binaryfunc_l(PyObject * self,PyObject * args,void * wrapped)6528 wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
6529 {
6530     binaryfunc func = (binaryfunc)wrapped;
6531     PyObject *other;
6532 
6533     if (!check_num_args(args, 1))
6534         return NULL;
6535     other = PyTuple_GET_ITEM(args, 0);
6536     return (*func)(self, other);
6537 }
6538 
6539 static PyObject *
wrap_binaryfunc_r(PyObject * self,PyObject * args,void * wrapped)6540 wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
6541 {
6542     binaryfunc func = (binaryfunc)wrapped;
6543     PyObject *other;
6544 
6545     if (!check_num_args(args, 1))
6546         return NULL;
6547     other = PyTuple_GET_ITEM(args, 0);
6548     return (*func)(other, self);
6549 }
6550 
6551 static PyObject *
wrap_ternaryfunc(PyObject * self,PyObject * args,void * wrapped)6552 wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
6553 {
6554     ternaryfunc func = (ternaryfunc)wrapped;
6555     PyObject *other;
6556     PyObject *third = Py_None;
6557 
6558     /* Note: This wrapper only works for __pow__() */
6559 
6560     if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
6561         return NULL;
6562     return (*func)(self, other, third);
6563 }
6564 
6565 static PyObject *
wrap_ternaryfunc_r(PyObject * self,PyObject * args,void * wrapped)6566 wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
6567 {
6568     ternaryfunc func = (ternaryfunc)wrapped;
6569     PyObject *other;
6570     PyObject *third = Py_None;
6571 
6572     /* Note: This wrapper only works for __pow__() */
6573 
6574     if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
6575         return NULL;
6576     return (*func)(other, self, third);
6577 }
6578 
6579 static PyObject *
wrap_unaryfunc(PyObject * self,PyObject * args,void * wrapped)6580 wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
6581 {
6582     unaryfunc func = (unaryfunc)wrapped;
6583 
6584     if (!check_num_args(args, 0))
6585         return NULL;
6586     return (*func)(self);
6587 }
6588 
6589 static PyObject *
wrap_indexargfunc(PyObject * self,PyObject * args,void * wrapped)6590 wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
6591 {
6592     ssizeargfunc func = (ssizeargfunc)wrapped;
6593     PyObject* o;
6594     Py_ssize_t i;
6595 
6596     if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
6597         return NULL;
6598     i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
6599     if (i == -1 && PyErr_Occurred())
6600         return NULL;
6601     return (*func)(self, i);
6602 }
6603 
6604 static Py_ssize_t
getindex(PyObject * self,PyObject * arg)6605 getindex(PyObject *self, PyObject *arg)
6606 {
6607     Py_ssize_t i;
6608 
6609     i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
6610     if (i == -1 && PyErr_Occurred())
6611         return -1;
6612     if (i < 0) {
6613         PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
6614         if (sq && sq->sq_length) {
6615             Py_ssize_t n = (*sq->sq_length)(self);
6616             if (n < 0) {
6617                 assert(PyErr_Occurred());
6618                 return -1;
6619             }
6620             i += n;
6621         }
6622     }
6623     return i;
6624 }
6625 
6626 static PyObject *
wrap_sq_item(PyObject * self,PyObject * args,void * wrapped)6627 wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
6628 {
6629     ssizeargfunc func = (ssizeargfunc)wrapped;
6630     PyObject *arg;
6631     Py_ssize_t i;
6632 
6633     if (PyTuple_GET_SIZE(args) == 1) {
6634         arg = PyTuple_GET_ITEM(args, 0);
6635         i = getindex(self, arg);
6636         if (i == -1 && PyErr_Occurred())
6637             return NULL;
6638         return (*func)(self, i);
6639     }
6640     check_num_args(args, 1);
6641     assert(PyErr_Occurred());
6642     return NULL;
6643 }
6644 
6645 static PyObject *
wrap_sq_setitem(PyObject * self,PyObject * args,void * wrapped)6646 wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
6647 {
6648     ssizeobjargproc func = (ssizeobjargproc)wrapped;
6649     Py_ssize_t i;
6650     int res;
6651     PyObject *arg, *value;
6652 
6653     if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
6654         return NULL;
6655     i = getindex(self, arg);
6656     if (i == -1 && PyErr_Occurred())
6657         return NULL;
6658     res = (*func)(self, i, value);
6659     if (res == -1 && PyErr_Occurred())
6660         return NULL;
6661     Py_RETURN_NONE;
6662 }
6663 
6664 static PyObject *
wrap_sq_delitem(PyObject * self,PyObject * args,void * wrapped)6665 wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
6666 {
6667     ssizeobjargproc func = (ssizeobjargproc)wrapped;
6668     Py_ssize_t i;
6669     int res;
6670     PyObject *arg;
6671 
6672     if (!check_num_args(args, 1))
6673         return NULL;
6674     arg = PyTuple_GET_ITEM(args, 0);
6675     i = getindex(self, arg);
6676     if (i == -1 && PyErr_Occurred())
6677         return NULL;
6678     res = (*func)(self, i, NULL);
6679     if (res == -1 && PyErr_Occurred())
6680         return NULL;
6681     Py_RETURN_NONE;
6682 }
6683 
6684 /* XXX objobjproc is a misnomer; should be objargpred */
6685 static PyObject *
wrap_objobjproc(PyObject * self,PyObject * args,void * wrapped)6686 wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
6687 {
6688     objobjproc func = (objobjproc)wrapped;
6689     int res;
6690     PyObject *value;
6691 
6692     if (!check_num_args(args, 1))
6693         return NULL;
6694     value = PyTuple_GET_ITEM(args, 0);
6695     res = (*func)(self, value);
6696     if (res == -1 && PyErr_Occurred())
6697         return NULL;
6698     else
6699         return PyBool_FromLong(res);
6700 }
6701 
6702 static PyObject *
wrap_objobjargproc(PyObject * self,PyObject * args,void * wrapped)6703 wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
6704 {
6705     objobjargproc func = (objobjargproc)wrapped;
6706     int res;
6707     PyObject *key, *value;
6708 
6709     if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
6710         return NULL;
6711     res = (*func)(self, key, value);
6712     if (res == -1 && PyErr_Occurred())
6713         return NULL;
6714     Py_RETURN_NONE;
6715 }
6716 
6717 static PyObject *
wrap_delitem(PyObject * self,PyObject * args,void * wrapped)6718 wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
6719 {
6720     objobjargproc func = (objobjargproc)wrapped;
6721     int res;
6722     PyObject *key;
6723 
6724     if (!check_num_args(args, 1))
6725         return NULL;
6726     key = PyTuple_GET_ITEM(args, 0);
6727     res = (*func)(self, key, NULL);
6728     if (res == -1 && PyErr_Occurred())
6729         return NULL;
6730     Py_RETURN_NONE;
6731 }
6732 
6733 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
6734    This is called the Carlo Verre hack after its discoverer.  See
6735    https://mail.python.org/pipermail/python-dev/2003-April/034535.html
6736    */
6737 static int
hackcheck(PyObject * self,setattrofunc func,const char * what)6738 hackcheck(PyObject *self, setattrofunc func, const char *what)
6739 {
6740     PyTypeObject *type = Py_TYPE(self);
6741     PyObject *mro = type->tp_mro;
6742     if (!mro) {
6743         /* Probably ok not to check the call in this case. */
6744         return 1;
6745     }
6746     assert(PyTuple_Check(mro));
6747 
6748     /* Find the (base) type that defined the type's slot function. */
6749     PyTypeObject *defining_type = type;
6750     Py_ssize_t i;
6751     for (i = PyTuple_GET_SIZE(mro) - 1; i >= 0; i--) {
6752         PyTypeObject *base = (PyTypeObject*) PyTuple_GET_ITEM(mro, i);
6753         if (base->tp_setattro == slot_tp_setattro) {
6754             /* Ignore Python classes:
6755                they never define their own C-level setattro. */
6756         }
6757         else if (base->tp_setattro == type->tp_setattro) {
6758             defining_type = base;
6759             break;
6760         }
6761     }
6762 
6763     /* Reject calls that jump over intermediate C-level overrides. */
6764     for (PyTypeObject *base = defining_type; base; base = base->tp_base) {
6765         if (base->tp_setattro == func) {
6766             /* 'func' is the right slot function to call. */
6767             break;
6768         }
6769         else if (base->tp_setattro != slot_tp_setattro) {
6770             /* 'base' is not a Python class and overrides 'func'.
6771                Its tp_setattro should be called instead. */
6772             PyErr_Format(PyExc_TypeError,
6773                          "can't apply this %s to %s object",
6774                          what,
6775                          type->tp_name);
6776             return 0;
6777         }
6778     }
6779     return 1;
6780 }
6781 
6782 static PyObject *
wrap_setattr(PyObject * self,PyObject * args,void * wrapped)6783 wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
6784 {
6785     setattrofunc func = (setattrofunc)wrapped;
6786     int res;
6787     PyObject *name, *value;
6788 
6789     if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
6790         return NULL;
6791     if (!hackcheck(self, func, "__setattr__"))
6792         return NULL;
6793     res = (*func)(self, name, value);
6794     if (res < 0)
6795         return NULL;
6796     Py_RETURN_NONE;
6797 }
6798 
6799 static PyObject *
wrap_delattr(PyObject * self,PyObject * args,void * wrapped)6800 wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
6801 {
6802     setattrofunc func = (setattrofunc)wrapped;
6803     int res;
6804     PyObject *name;
6805 
6806     if (!check_num_args(args, 1))
6807         return NULL;
6808     name = PyTuple_GET_ITEM(args, 0);
6809     if (!hackcheck(self, func, "__delattr__"))
6810         return NULL;
6811     res = (*func)(self, name, NULL);
6812     if (res < 0)
6813         return NULL;
6814     Py_RETURN_NONE;
6815 }
6816 
6817 static PyObject *
wrap_hashfunc(PyObject * self,PyObject * args,void * wrapped)6818 wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
6819 {
6820     hashfunc func = (hashfunc)wrapped;
6821     Py_hash_t res;
6822 
6823     if (!check_num_args(args, 0))
6824         return NULL;
6825     res = (*func)(self);
6826     if (res == -1 && PyErr_Occurred())
6827         return NULL;
6828     return PyLong_FromSsize_t(res);
6829 }
6830 
6831 static PyObject *
wrap_call(PyObject * self,PyObject * args,void * wrapped,PyObject * kwds)6832 wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
6833 {
6834     ternaryfunc func = (ternaryfunc)wrapped;
6835 
6836     return (*func)(self, args, kwds);
6837 }
6838 
6839 static PyObject *
wrap_del(PyObject * self,PyObject * args,void * wrapped)6840 wrap_del(PyObject *self, PyObject *args, void *wrapped)
6841 {
6842     destructor func = (destructor)wrapped;
6843 
6844     if (!check_num_args(args, 0))
6845         return NULL;
6846 
6847     (*func)(self);
6848     Py_RETURN_NONE;
6849 }
6850 
6851 static PyObject *
wrap_richcmpfunc(PyObject * self,PyObject * args,void * wrapped,int op)6852 wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
6853 {
6854     richcmpfunc func = (richcmpfunc)wrapped;
6855     PyObject *other;
6856 
6857     if (!check_num_args(args, 1))
6858         return NULL;
6859     other = PyTuple_GET_ITEM(args, 0);
6860     return (*func)(self, other, op);
6861 }
6862 
6863 #undef RICHCMP_WRAPPER
6864 #define RICHCMP_WRAPPER(NAME, OP) \
6865 static PyObject * \
6866 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
6867 { \
6868     return wrap_richcmpfunc(self, args, wrapped, OP); \
6869 }
6870 
RICHCMP_WRAPPER(lt,Py_LT)6871 RICHCMP_WRAPPER(lt, Py_LT)
6872 RICHCMP_WRAPPER(le, Py_LE)
6873 RICHCMP_WRAPPER(eq, Py_EQ)
6874 RICHCMP_WRAPPER(ne, Py_NE)
6875 RICHCMP_WRAPPER(gt, Py_GT)
6876 RICHCMP_WRAPPER(ge, Py_GE)
6877 
6878 static PyObject *
6879 wrap_next(PyObject *self, PyObject *args, void *wrapped)
6880 {
6881     unaryfunc func = (unaryfunc)wrapped;
6882     PyObject *res;
6883 
6884     if (!check_num_args(args, 0))
6885         return NULL;
6886     res = (*func)(self);
6887     if (res == NULL && !PyErr_Occurred())
6888         PyErr_SetNone(PyExc_StopIteration);
6889     return res;
6890 }
6891 
6892 static PyObject *
wrap_descr_get(PyObject * self,PyObject * args,void * wrapped)6893 wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
6894 {
6895     descrgetfunc func = (descrgetfunc)wrapped;
6896     PyObject *obj;
6897     PyObject *type = NULL;
6898 
6899     if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
6900         return NULL;
6901     if (obj == Py_None)
6902         obj = NULL;
6903     if (type == Py_None)
6904         type = NULL;
6905     if (type == NULL &&obj == NULL) {
6906         PyErr_SetString(PyExc_TypeError,
6907                         "__get__(None, None) is invalid");
6908         return NULL;
6909     }
6910     return (*func)(self, obj, type);
6911 }
6912 
6913 static PyObject *
wrap_descr_set(PyObject * self,PyObject * args,void * wrapped)6914 wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
6915 {
6916     descrsetfunc func = (descrsetfunc)wrapped;
6917     PyObject *obj, *value;
6918     int ret;
6919 
6920     if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
6921         return NULL;
6922     ret = (*func)(self, obj, value);
6923     if (ret < 0)
6924         return NULL;
6925     Py_RETURN_NONE;
6926 }
6927 
6928 static PyObject *
wrap_descr_delete(PyObject * self,PyObject * args,void * wrapped)6929 wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
6930 {
6931     descrsetfunc func = (descrsetfunc)wrapped;
6932     PyObject *obj;
6933     int ret;
6934 
6935     if (!check_num_args(args, 1))
6936         return NULL;
6937     obj = PyTuple_GET_ITEM(args, 0);
6938     ret = (*func)(self, obj, NULL);
6939     if (ret < 0)
6940         return NULL;
6941     Py_RETURN_NONE;
6942 }
6943 
6944 static PyObject *
wrap_init(PyObject * self,PyObject * args,void * wrapped,PyObject * kwds)6945 wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
6946 {
6947     initproc func = (initproc)wrapped;
6948 
6949     if (func(self, args, kwds) < 0)
6950         return NULL;
6951     Py_RETURN_NONE;
6952 }
6953 
6954 static PyObject *
tp_new_wrapper(PyObject * self,PyObject * args,PyObject * kwds)6955 tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
6956 {
6957     PyTypeObject *type, *subtype, *staticbase;
6958     PyObject *arg0, *res;
6959 
6960     if (self == NULL || !PyType_Check(self)) {
6961         PyErr_Format(PyExc_SystemError,
6962                      "__new__() called with non-type 'self'");
6963         return NULL;
6964     }
6965     type = (PyTypeObject *)self;
6966 
6967     if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
6968         PyErr_Format(PyExc_TypeError,
6969                      "%s.__new__(): not enough arguments",
6970                      type->tp_name);
6971         return NULL;
6972     }
6973     arg0 = PyTuple_GET_ITEM(args, 0);
6974     if (!PyType_Check(arg0)) {
6975         PyErr_Format(PyExc_TypeError,
6976                      "%s.__new__(X): X is not a type object (%s)",
6977                      type->tp_name,
6978                      Py_TYPE(arg0)->tp_name);
6979         return NULL;
6980     }
6981     subtype = (PyTypeObject *)arg0;
6982     if (!PyType_IsSubtype(subtype, type)) {
6983         PyErr_Format(PyExc_TypeError,
6984                      "%s.__new__(%s): %s is not a subtype of %s",
6985                      type->tp_name,
6986                      subtype->tp_name,
6987                      subtype->tp_name,
6988                      type->tp_name);
6989         return NULL;
6990     }
6991 
6992     /* Check that the use doesn't do something silly and unsafe like
6993        object.__new__(dict).  To do this, we check that the
6994        most derived base that's not a heap type is this type. */
6995     staticbase = subtype;
6996     while (staticbase && (staticbase->tp_new == slot_tp_new))
6997         staticbase = staticbase->tp_base;
6998     /* If staticbase is NULL now, it is a really weird type.
6999        In the spirit of backwards compatibility (?), just shut up. */
7000     if (staticbase && staticbase->tp_new != type->tp_new) {
7001         PyErr_Format(PyExc_TypeError,
7002                      "%s.__new__(%s) is not safe, use %s.__new__()",
7003                      type->tp_name,
7004                      subtype->tp_name,
7005                      staticbase->tp_name);
7006         return NULL;
7007     }
7008 
7009     args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
7010     if (args == NULL)
7011         return NULL;
7012     res = type->tp_new(subtype, args, kwds);
7013     Py_DECREF(args);
7014     return res;
7015 }
7016 
7017 static struct PyMethodDef tp_new_methoddef[] = {
7018     {"__new__", (PyCFunction)(void(*)(void))tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
7019      PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
7020                "Create and return a new object.  "
7021                "See help(type) for accurate signature.")},
7022     {0}
7023 };
7024 
7025 static int
add_tp_new_wrapper(PyTypeObject * type)7026 add_tp_new_wrapper(PyTypeObject *type)
7027 {
7028     int r = _PyDict_ContainsId(type->tp_dict, &PyId___new__);
7029     if (r > 0) {
7030         return 0;
7031     }
7032     if (r < 0) {
7033         return -1;
7034     }
7035 
7036     PyObject *func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
7037     if (func == NULL) {
7038         return -1;
7039     }
7040     r = _PyDict_SetItemId(type->tp_dict, &PyId___new__, func);
7041     Py_DECREF(func);
7042     return r;
7043 }
7044 
7045 /* Slot wrappers that call the corresponding __foo__ slot.  See comments
7046    below at override_slots() for more explanation. */
7047 
7048 #define SLOT0(FUNCNAME, OPSTR) \
7049 static PyObject * \
7050 FUNCNAME(PyObject *self) \
7051 { \
7052     PyObject* stack[1] = {self}; \
7053     _Py_static_string(id, OPSTR); \
7054     return vectorcall_method(&id, stack, 1); \
7055 }
7056 
7057 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE) \
7058 static PyObject * \
7059 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
7060 { \
7061     PyObject* stack[2] = {self, arg1}; \
7062     _Py_static_string(id, OPSTR); \
7063     return vectorcall_method(&id, stack, 2); \
7064 }
7065 
7066 /* Boolean helper for SLOT1BINFULL().
7067    right.__class__ is a nontrivial subclass of left.__class__. */
7068 static int
method_is_overloaded(PyObject * left,PyObject * right,struct _Py_Identifier * name)7069 method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
7070 {
7071     PyObject *a, *b;
7072     int ok;
7073 
7074     if (_PyObject_LookupAttrId((PyObject *)(Py_TYPE(right)), name, &b) < 0) {
7075         return -1;
7076     }
7077     if (b == NULL) {
7078         /* If right doesn't have it, it's not overloaded */
7079         return 0;
7080     }
7081 
7082     if (_PyObject_LookupAttrId((PyObject *)(Py_TYPE(left)), name, &a) < 0) {
7083         Py_DECREF(b);
7084         return -1;
7085     }
7086     if (a == NULL) {
7087         Py_DECREF(b);
7088         /* If right has it but left doesn't, it's overloaded */
7089         return 1;
7090     }
7091 
7092     ok = PyObject_RichCompareBool(a, b, Py_NE);
7093     Py_DECREF(a);
7094     Py_DECREF(b);
7095     return ok;
7096 }
7097 
7098 
7099 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
7100 static PyObject * \
7101 FUNCNAME(PyObject *self, PyObject *other) \
7102 { \
7103     PyObject* stack[2]; \
7104     PyThreadState *tstate = _PyThreadState_GET(); \
7105     _Py_static_string(op_id, OPSTR); \
7106     _Py_static_string(rop_id, ROPSTR); \
7107     int do_other = !Py_IS_TYPE(self, Py_TYPE(other)) && \
7108         Py_TYPE(other)->tp_as_number != NULL && \
7109         Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
7110     if (Py_TYPE(self)->tp_as_number != NULL && \
7111         Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
7112         PyObject *r; \
7113         if (do_other && PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { \
7114             int ok = method_is_overloaded(self, other, &rop_id); \
7115             if (ok < 0) { \
7116                 return NULL; \
7117             } \
7118             if (ok) { \
7119                 stack[0] = other; \
7120                 stack[1] = self; \
7121                 r = vectorcall_maybe(tstate, &rop_id, stack, 2); \
7122                 if (r != Py_NotImplemented) \
7123                     return r; \
7124                 Py_DECREF(r); \
7125                 do_other = 0; \
7126             } \
7127         } \
7128         stack[0] = self; \
7129         stack[1] = other; \
7130         r = vectorcall_maybe(tstate, &op_id, stack, 2); \
7131         if (r != Py_NotImplemented || \
7132             Py_IS_TYPE(other, Py_TYPE(self))) \
7133             return r; \
7134         Py_DECREF(r); \
7135     } \
7136     if (do_other) { \
7137         stack[0] = other; \
7138         stack[1] = self; \
7139         return vectorcall_maybe(tstate, &rop_id, stack, 2); \
7140     } \
7141     Py_RETURN_NOTIMPLEMENTED; \
7142 }
7143 
7144 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
7145     SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
7146 
7147 static Py_ssize_t
slot_sq_length(PyObject * self)7148 slot_sq_length(PyObject *self)
7149 {
7150     PyObject* stack[1] = {self};
7151     PyObject *res = vectorcall_method(&PyId___len__, stack, 1);
7152     Py_ssize_t len;
7153 
7154     if (res == NULL)
7155         return -1;
7156 
7157     Py_SETREF(res, _PyNumber_Index(res));
7158     if (res == NULL)
7159         return -1;
7160 
7161     assert(PyLong_Check(res));
7162     if (Py_SIZE(res) < 0) {
7163         Py_DECREF(res);
7164         PyErr_SetString(PyExc_ValueError,
7165                         "__len__() should return >= 0");
7166         return -1;
7167     }
7168 
7169     len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
7170     assert(len >= 0 || PyErr_ExceptionMatches(PyExc_OverflowError));
7171     Py_DECREF(res);
7172     return len;
7173 }
7174 
7175 static PyObject *
slot_sq_item(PyObject * self,Py_ssize_t i)7176 slot_sq_item(PyObject *self, Py_ssize_t i)
7177 {
7178     PyObject *ival = PyLong_FromSsize_t(i);
7179     if (ival == NULL) {
7180         return NULL;
7181     }
7182     PyObject *stack[2] = {self, ival};
7183     PyObject *retval = vectorcall_method(&PyId___getitem__, stack, 2);
7184     Py_DECREF(ival);
7185     return retval;
7186 }
7187 
7188 static int
slot_sq_ass_item(PyObject * self,Py_ssize_t index,PyObject * value)7189 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
7190 {
7191     PyObject *stack[3];
7192     PyObject *res;
7193     PyObject *index_obj;
7194 
7195     index_obj = PyLong_FromSsize_t(index);
7196     if (index_obj == NULL) {
7197         return -1;
7198     }
7199 
7200     stack[0] = self;
7201     stack[1] = index_obj;
7202     if (value == NULL) {
7203         res = vectorcall_method(&PyId___delitem__, stack, 2);
7204     }
7205     else {
7206         stack[2] = value;
7207         res = vectorcall_method(&PyId___setitem__, stack, 3);
7208     }
7209     Py_DECREF(index_obj);
7210 
7211     if (res == NULL) {
7212         return -1;
7213     }
7214     Py_DECREF(res);
7215     return 0;
7216 }
7217 
7218 static int
slot_sq_contains(PyObject * self,PyObject * value)7219 slot_sq_contains(PyObject *self, PyObject *value)
7220 {
7221     PyThreadState *tstate = _PyThreadState_GET();
7222     PyObject *func, *res;
7223     int result = -1, unbound;
7224     _Py_IDENTIFIER(__contains__);
7225 
7226     func = lookup_maybe_method(self, &PyId___contains__, &unbound);
7227     if (func == Py_None) {
7228         Py_DECREF(func);
7229         PyErr_Format(PyExc_TypeError,
7230                      "'%.200s' object is not a container",
7231                      Py_TYPE(self)->tp_name);
7232         return -1;
7233     }
7234     if (func != NULL) {
7235         PyObject *args[2] = {self, value};
7236         res = vectorcall_unbound(tstate, unbound, func, args, 2);
7237         Py_DECREF(func);
7238         if (res != NULL) {
7239             result = PyObject_IsTrue(res);
7240             Py_DECREF(res);
7241         }
7242     }
7243     else if (! PyErr_Occurred()) {
7244         /* Possible results: -1 and 1 */
7245         result = (int)_PySequence_IterSearch(self, value,
7246                                          PY_ITERSEARCH_CONTAINS);
7247     }
7248     return result;
7249 }
7250 
7251 #define slot_mp_length slot_sq_length
7252 
7253 SLOT1(slot_mp_subscript, "__getitem__", PyObject *)
7254 
7255 static int
slot_mp_ass_subscript(PyObject * self,PyObject * key,PyObject * value)7256 slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
7257 {
7258     PyObject *stack[3];
7259     PyObject *res;
7260 
7261     stack[0] = self;
7262     stack[1] = key;
7263     if (value == NULL) {
7264         res = vectorcall_method(&PyId___delitem__, stack, 2);
7265     }
7266     else {
7267         stack[2] = value;
7268         res = vectorcall_method(&PyId___setitem__, stack, 3);
7269     }
7270 
7271     if (res == NULL)
7272         return -1;
7273     Py_DECREF(res);
7274     return 0;
7275 }
7276 
7277 SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
7278 SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
7279 SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
7280 SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
7281 SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
7282 SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
7283 
7284 static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
7285 
7286 SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
7287              nb_power, "__pow__", "__rpow__")
7288 
7289 static PyObject *
slot_nb_power(PyObject * self,PyObject * other,PyObject * modulus)7290 slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
7291 {
7292     _Py_IDENTIFIER(__pow__);
7293 
7294     if (modulus == Py_None)
7295         return slot_nb_power_binary(self, other);
7296     /* Three-arg power doesn't use __rpow__.  But ternary_op
7297        can call this when the second argument's type uses
7298        slot_nb_power, so check before calling self.__pow__. */
7299     if (Py_TYPE(self)->tp_as_number != NULL &&
7300         Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
7301         PyObject* stack[3] = {self, other, modulus};
7302         return vectorcall_method(&PyId___pow__, stack, 3);
7303     }
7304     Py_RETURN_NOTIMPLEMENTED;
7305 }
7306 
7307 SLOT0(slot_nb_negative, "__neg__")
7308 SLOT0(slot_nb_positive, "__pos__")
7309 SLOT0(slot_nb_absolute, "__abs__")
7310 
7311 static int
slot_nb_bool(PyObject * self)7312 slot_nb_bool(PyObject *self)
7313 {
7314     PyObject *func, *value;
7315     int result, unbound;
7316     int using_len = 0;
7317     _Py_IDENTIFIER(__bool__);
7318 
7319     func = lookup_maybe_method(self, &PyId___bool__, &unbound);
7320     if (func == NULL) {
7321         if (PyErr_Occurred()) {
7322             return -1;
7323         }
7324 
7325         func = lookup_maybe_method(self, &PyId___len__, &unbound);
7326         if (func == NULL) {
7327             if (PyErr_Occurred()) {
7328                 return -1;
7329             }
7330             return 1;
7331         }
7332         using_len = 1;
7333     }
7334 
7335     value = call_unbound_noarg(unbound, func, self);
7336     if (value == NULL) {
7337         goto error;
7338     }
7339 
7340     if (using_len) {
7341         /* bool type enforced by slot_nb_len */
7342         result = PyObject_IsTrue(value);
7343     }
7344     else if (PyBool_Check(value)) {
7345         result = PyObject_IsTrue(value);
7346     }
7347     else {
7348         PyErr_Format(PyExc_TypeError,
7349                      "__bool__ should return "
7350                      "bool, returned %s",
7351                      Py_TYPE(value)->tp_name);
7352         result = -1;
7353     }
7354 
7355     Py_DECREF(value);
7356     Py_DECREF(func);
7357     return result;
7358 
7359 error:
7360     Py_DECREF(func);
7361     return -1;
7362 }
7363 
7364 
7365 static PyObject *
slot_nb_index(PyObject * self)7366 slot_nb_index(PyObject *self)
7367 {
7368     _Py_IDENTIFIER(__index__);
7369     PyObject *stack[1] = {self};
7370     return vectorcall_method(&PyId___index__, stack, 1);
7371 }
7372 
7373 
7374 SLOT0(slot_nb_invert, "__invert__")
7375 SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
7376 SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
7377 SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
7378 SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
7379 SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
7380 
7381 SLOT0(slot_nb_int, "__int__")
7382 SLOT0(slot_nb_float, "__float__")
7383 SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *)
7384 SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *)
7385 SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *)
7386 SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *)
7387 SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *)
7388 /* Can't use SLOT1 here, because nb_inplace_power is ternary */
7389 static PyObject *
slot_nb_inplace_power(PyObject * self,PyObject * arg1,PyObject * arg2)7390 slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
7391 {
7392     PyObject *stack[2] = {self, arg1};
7393     _Py_IDENTIFIER(__ipow__);
7394     return vectorcall_method(&PyId___ipow__, stack, 2);
7395 }
7396 SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *)
7397 SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *)
7398 SLOT1(slot_nb_inplace_and, "__iand__", PyObject *)
7399 SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *)
7400 SLOT1(slot_nb_inplace_or, "__ior__", PyObject *)
7401 SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
7402          "__floordiv__", "__rfloordiv__")
7403 SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
7404 SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *)
7405 SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *)
7406 
7407 static PyObject *
slot_tp_repr(PyObject * self)7408 slot_tp_repr(PyObject *self)
7409 {
7410     PyObject *func, *res;
7411     _Py_IDENTIFIER(__repr__);
7412     int unbound;
7413 
7414     func = lookup_maybe_method(self, &PyId___repr__, &unbound);
7415     if (func != NULL) {
7416         res = call_unbound_noarg(unbound, func, self);
7417         Py_DECREF(func);
7418         return res;
7419     }
7420     PyErr_Clear();
7421     return PyUnicode_FromFormat("<%s object at %p>",
7422                                Py_TYPE(self)->tp_name, self);
7423 }
7424 
7425 SLOT0(slot_tp_str, "__str__")
7426 
7427 static Py_hash_t
slot_tp_hash(PyObject * self)7428 slot_tp_hash(PyObject *self)
7429 {
7430     PyObject *func, *res;
7431     Py_ssize_t h;
7432     int unbound;
7433 
7434     func = lookup_maybe_method(self, &PyId___hash__, &unbound);
7435 
7436     if (func == Py_None) {
7437         Py_DECREF(func);
7438         func = NULL;
7439     }
7440 
7441     if (func == NULL) {
7442         return PyObject_HashNotImplemented(self);
7443     }
7444 
7445     res = call_unbound_noarg(unbound, func, self);
7446     Py_DECREF(func);
7447     if (res == NULL)
7448         return -1;
7449 
7450     if (!PyLong_Check(res)) {
7451         PyErr_SetString(PyExc_TypeError,
7452                         "__hash__ method should return an integer");
7453         return -1;
7454     }
7455     /* Transform the PyLong `res` to a Py_hash_t `h`.  For an existing
7456        hashable Python object x, hash(x) will always lie within the range of
7457        Py_hash_t.  Therefore our transformation must preserve values that
7458        already lie within this range, to ensure that if x.__hash__() returns
7459        hash(y) then hash(x) == hash(y). */
7460     h = PyLong_AsSsize_t(res);
7461     if (h == -1 && PyErr_Occurred()) {
7462         /* res was not within the range of a Py_hash_t, so we're free to
7463            use any sufficiently bit-mixing transformation;
7464            long.__hash__ will do nicely. */
7465         PyErr_Clear();
7466         h = PyLong_Type.tp_hash(res);
7467     }
7468     /* -1 is reserved for errors. */
7469     if (h == -1)
7470         h = -2;
7471     Py_DECREF(res);
7472     return h;
7473 }
7474 
7475 static PyObject *
slot_tp_call(PyObject * self,PyObject * args,PyObject * kwds)7476 slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
7477 {
7478     PyThreadState *tstate = _PyThreadState_GET();
7479     _Py_IDENTIFIER(__call__);
7480     int unbound;
7481 
7482     PyObject *meth = lookup_method(self, &PyId___call__, &unbound);
7483     if (meth == NULL) {
7484         return NULL;
7485     }
7486 
7487     PyObject *res;
7488     if (unbound) {
7489         res = _PyObject_Call_Prepend(tstate, meth, self, args, kwds);
7490     }
7491     else {
7492         res = _PyObject_Call(tstate, meth, args, kwds);
7493     }
7494 
7495     Py_DECREF(meth);
7496     return res;
7497 }
7498 
7499 /* There are two slot dispatch functions for tp_getattro.
7500 
7501    - slot_tp_getattro() is used when __getattribute__ is overridden
7502      but no __getattr__ hook is present;
7503 
7504    - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
7505 
7506    The code in update_one_slot() always installs slot_tp_getattr_hook(); this
7507    detects the absence of __getattr__ and then installs the simpler slot if
7508    necessary. */
7509 
7510 static PyObject *
slot_tp_getattro(PyObject * self,PyObject * name)7511 slot_tp_getattro(PyObject *self, PyObject *name)
7512 {
7513     PyObject *stack[2] = {self, name};
7514     return vectorcall_method(&PyId___getattribute__, stack, 2);
7515 }
7516 
7517 static PyObject *
call_attribute(PyObject * self,PyObject * attr,PyObject * name)7518 call_attribute(PyObject *self, PyObject *attr, PyObject *name)
7519 {
7520     PyObject *res, *descr = NULL;
7521     descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
7522 
7523     if (f != NULL) {
7524         descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
7525         if (descr == NULL)
7526             return NULL;
7527         else
7528             attr = descr;
7529     }
7530     res = PyObject_CallOneArg(attr, name);
7531     Py_XDECREF(descr);
7532     return res;
7533 }
7534 
7535 static PyObject *
slot_tp_getattr_hook(PyObject * self,PyObject * name)7536 slot_tp_getattr_hook(PyObject *self, PyObject *name)
7537 {
7538     PyTypeObject *tp = Py_TYPE(self);
7539     PyObject *getattr, *getattribute, *res;
7540     _Py_IDENTIFIER(__getattr__);
7541 
7542     /* speed hack: we could use lookup_maybe, but that would resolve the
7543        method fully for each attribute lookup for classes with
7544        __getattr__, even when the attribute is present. So we use
7545        _PyType_Lookup and create the method only when needed, with
7546        call_attribute. */
7547     getattr = _PyType_LookupId(tp, &PyId___getattr__);
7548     if (getattr == NULL) {
7549         /* No __getattr__ hook: use a simpler dispatcher */
7550         tp->tp_getattro = slot_tp_getattro;
7551         return slot_tp_getattro(self, name);
7552     }
7553     Py_INCREF(getattr);
7554     /* speed hack: we could use lookup_maybe, but that would resolve the
7555        method fully for each attribute lookup for classes with
7556        __getattr__, even when self has the default __getattribute__
7557        method. So we use _PyType_Lookup and create the method only when
7558        needed, with call_attribute. */
7559     getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
7560     if (getattribute == NULL ||
7561         (Py_IS_TYPE(getattribute, &PyWrapperDescr_Type) &&
7562          ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
7563          (void *)PyObject_GenericGetAttr))
7564         res = PyObject_GenericGetAttr(self, name);
7565     else {
7566         Py_INCREF(getattribute);
7567         res = call_attribute(self, getattribute, name);
7568         Py_DECREF(getattribute);
7569     }
7570     if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
7571         PyErr_Clear();
7572         res = call_attribute(self, getattr, name);
7573     }
7574     Py_DECREF(getattr);
7575     return res;
7576 }
7577 
7578 static int
slot_tp_setattro(PyObject * self,PyObject * name,PyObject * value)7579 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
7580 {
7581     PyObject *stack[3];
7582     PyObject *res;
7583     _Py_IDENTIFIER(__delattr__);
7584     _Py_IDENTIFIER(__setattr__);
7585 
7586     stack[0] = self;
7587     stack[1] = name;
7588     if (value == NULL) {
7589         res = vectorcall_method(&PyId___delattr__, stack, 2);
7590     }
7591     else {
7592         stack[2] = value;
7593         res = vectorcall_method(&PyId___setattr__, stack, 3);
7594     }
7595     if (res == NULL)
7596         return -1;
7597     Py_DECREF(res);
7598     return 0;
7599 }
7600 
7601 static _Py_Identifier name_op[] = {
7602     _Py_static_string_init("__lt__"),
7603     _Py_static_string_init("__le__"),
7604     _Py_static_string_init("__eq__"),
7605     _Py_static_string_init("__ne__"),
7606     _Py_static_string_init("__gt__"),
7607     _Py_static_string_init("__ge__"),
7608 };
7609 
7610 static PyObject *
slot_tp_richcompare(PyObject * self,PyObject * other,int op)7611 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
7612 {
7613     PyThreadState *tstate = _PyThreadState_GET();
7614 
7615     int unbound;
7616     PyObject *func = lookup_maybe_method(self, &name_op[op], &unbound);
7617     if (func == NULL) {
7618         PyErr_Clear();
7619         Py_RETURN_NOTIMPLEMENTED;
7620     }
7621 
7622     PyObject *stack[2] = {self, other};
7623     PyObject *res = vectorcall_unbound(tstate, unbound, func, stack, 2);
7624     Py_DECREF(func);
7625     return res;
7626 }
7627 
7628 static PyObject *
slot_tp_iter(PyObject * self)7629 slot_tp_iter(PyObject *self)
7630 {
7631     int unbound;
7632     PyObject *func, *res;
7633     _Py_IDENTIFIER(__iter__);
7634 
7635     func = lookup_maybe_method(self, &PyId___iter__, &unbound);
7636     if (func == Py_None) {
7637         Py_DECREF(func);
7638         PyErr_Format(PyExc_TypeError,
7639                      "'%.200s' object is not iterable",
7640                      Py_TYPE(self)->tp_name);
7641         return NULL;
7642     }
7643 
7644     if (func != NULL) {
7645         res = call_unbound_noarg(unbound, func, self);
7646         Py_DECREF(func);
7647         return res;
7648     }
7649 
7650     PyErr_Clear();
7651     func = lookup_maybe_method(self, &PyId___getitem__, &unbound);
7652     if (func == NULL) {
7653         PyErr_Format(PyExc_TypeError,
7654                      "'%.200s' object is not iterable",
7655                      Py_TYPE(self)->tp_name);
7656         return NULL;
7657     }
7658     Py_DECREF(func);
7659     return PySeqIter_New(self);
7660 }
7661 
7662 static PyObject *
slot_tp_iternext(PyObject * self)7663 slot_tp_iternext(PyObject *self)
7664 {
7665     _Py_IDENTIFIER(__next__);
7666     PyObject *stack[1] = {self};
7667     return vectorcall_method(&PyId___next__, stack, 1);
7668 }
7669 
7670 static PyObject *
slot_tp_descr_get(PyObject * self,PyObject * obj,PyObject * type)7671 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7672 {
7673     PyTypeObject *tp = Py_TYPE(self);
7674     PyObject *get;
7675     _Py_IDENTIFIER(__get__);
7676 
7677     get = _PyType_LookupId(tp, &PyId___get__);
7678     if (get == NULL) {
7679         /* Avoid further slowdowns */
7680         if (tp->tp_descr_get == slot_tp_descr_get)
7681             tp->tp_descr_get = NULL;
7682         Py_INCREF(self);
7683         return self;
7684     }
7685     if (obj == NULL)
7686         obj = Py_None;
7687     if (type == NULL)
7688         type = Py_None;
7689     return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
7690 }
7691 
7692 static int
slot_tp_descr_set(PyObject * self,PyObject * target,PyObject * value)7693 slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
7694 {
7695     PyObject* stack[3];
7696     PyObject *res;
7697     _Py_IDENTIFIER(__delete__);
7698     _Py_IDENTIFIER(__set__);
7699 
7700     stack[0] = self;
7701     stack[1] = target;
7702     if (value == NULL) {
7703         res = vectorcall_method(&PyId___delete__, stack, 2);
7704     }
7705     else {
7706         stack[2] = value;
7707         res = vectorcall_method(&PyId___set__, stack, 3);
7708     }
7709     if (res == NULL)
7710         return -1;
7711     Py_DECREF(res);
7712     return 0;
7713 }
7714 
7715 static int
slot_tp_init(PyObject * self,PyObject * args,PyObject * kwds)7716 slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
7717 {
7718     PyThreadState *tstate = _PyThreadState_GET();
7719 
7720     _Py_IDENTIFIER(__init__);
7721     int unbound;
7722     PyObject *meth = lookup_method(self, &PyId___init__, &unbound);
7723     if (meth == NULL) {
7724         return -1;
7725     }
7726 
7727     PyObject *res;
7728     if (unbound) {
7729         res = _PyObject_Call_Prepend(tstate, meth, self, args, kwds);
7730     }
7731     else {
7732         res = _PyObject_Call(tstate, meth, args, kwds);
7733     }
7734     Py_DECREF(meth);
7735     if (res == NULL)
7736         return -1;
7737     if (res != Py_None) {
7738         PyErr_Format(PyExc_TypeError,
7739                      "__init__() should return None, not '%.200s'",
7740                      Py_TYPE(res)->tp_name);
7741         Py_DECREF(res);
7742         return -1;
7743     }
7744     Py_DECREF(res);
7745     return 0;
7746 }
7747 
7748 static PyObject *
slot_tp_new(PyTypeObject * type,PyObject * args,PyObject * kwds)7749 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
7750 {
7751     PyThreadState *tstate = _PyThreadState_GET();
7752     PyObject *func, *result;
7753 
7754     func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
7755     if (func == NULL) {
7756         return NULL;
7757     }
7758 
7759     result = _PyObject_Call_Prepend(tstate, func, (PyObject *)type, args, kwds);
7760     Py_DECREF(func);
7761     return result;
7762 }
7763 
7764 static void
slot_tp_finalize(PyObject * self)7765 slot_tp_finalize(PyObject *self)
7766 {
7767     _Py_IDENTIFIER(__del__);
7768     int unbound;
7769     PyObject *del, *res;
7770     PyObject *error_type, *error_value, *error_traceback;
7771 
7772     /* Save the current exception, if any. */
7773     PyErr_Fetch(&error_type, &error_value, &error_traceback);
7774 
7775     /* Execute __del__ method, if any. */
7776     del = lookup_maybe_method(self, &PyId___del__, &unbound);
7777     if (del != NULL) {
7778         res = call_unbound_noarg(unbound, del, self);
7779         if (res == NULL)
7780             PyErr_WriteUnraisable(del);
7781         else
7782             Py_DECREF(res);
7783         Py_DECREF(del);
7784     }
7785 
7786     /* Restore the saved exception. */
7787     PyErr_Restore(error_type, error_value, error_traceback);
7788 }
7789 
7790 static PyObject *
slot_am_await(PyObject * self)7791 slot_am_await(PyObject *self)
7792 {
7793     int unbound;
7794     PyObject *func, *res;
7795     _Py_IDENTIFIER(__await__);
7796 
7797     func = lookup_maybe_method(self, &PyId___await__, &unbound);
7798     if (func != NULL) {
7799         res = call_unbound_noarg(unbound, func, self);
7800         Py_DECREF(func);
7801         return res;
7802     }
7803     PyErr_Format(PyExc_AttributeError,
7804                  "object %.50s does not have __await__ method",
7805                  Py_TYPE(self)->tp_name);
7806     return NULL;
7807 }
7808 
7809 static PyObject *
slot_am_aiter(PyObject * self)7810 slot_am_aiter(PyObject *self)
7811 {
7812     int unbound;
7813     PyObject *func, *res;
7814     _Py_IDENTIFIER(__aiter__);
7815 
7816     func = lookup_maybe_method(self, &PyId___aiter__, &unbound);
7817     if (func != NULL) {
7818         res = call_unbound_noarg(unbound, func, self);
7819         Py_DECREF(func);
7820         return res;
7821     }
7822     PyErr_Format(PyExc_AttributeError,
7823                  "object %.50s does not have __aiter__ method",
7824                  Py_TYPE(self)->tp_name);
7825     return NULL;
7826 }
7827 
7828 static PyObject *
slot_am_anext(PyObject * self)7829 slot_am_anext(PyObject *self)
7830 {
7831     int unbound;
7832     PyObject *func, *res;
7833     _Py_IDENTIFIER(__anext__);
7834 
7835     func = lookup_maybe_method(self, &PyId___anext__, &unbound);
7836     if (func != NULL) {
7837         res = call_unbound_noarg(unbound, func, self);
7838         Py_DECREF(func);
7839         return res;
7840     }
7841     PyErr_Format(PyExc_AttributeError,
7842                  "object %.50s does not have __anext__ method",
7843                  Py_TYPE(self)->tp_name);
7844     return NULL;
7845 }
7846 
7847 /*
7848 Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
7849 
7850 The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
7851 which incorporates the additional structures used for numbers, sequences and
7852 mappings.  Note that multiple names may map to the same slot (e.g. __eq__,
7853 __ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
7854 (e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
7855 an all-zero entry.  (This table is further initialized in
7856 _PyTypes_InitSlotDefs().)
7857 */
7858 
7859 typedef struct wrapperbase slotdef;
7860 
7861 #undef TPSLOT
7862 #undef FLSLOT
7863 #undef AMSLOT
7864 #undef ETSLOT
7865 #undef SQSLOT
7866 #undef MPSLOT
7867 #undef NBSLOT
7868 #undef UNSLOT
7869 #undef IBSLOT
7870 #undef BINSLOT
7871 #undef RBINSLOT
7872 
7873 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7874     {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
7875      PyDoc_STR(DOC)}
7876 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
7877     {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
7878      PyDoc_STR(DOC), FLAGS}
7879 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7880     {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
7881      PyDoc_STR(DOC)}
7882 #define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7883     ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
7884 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7885     ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
7886 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7887     ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
7888 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7889     ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
7890 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7891     ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
7892            NAME "($self, /)\n--\n\n" DOC)
7893 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
7894     ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
7895            NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
7896 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
7897     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
7898            NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
7899 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
7900     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
7901            NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
7902 #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
7903     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
7904            NAME "($self, value, /)\n--\n\n" DOC)
7905 #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
7906     ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
7907            NAME "($self, value, /)\n--\n\n" DOC)
7908 
7909 static slotdef slotdefs[] = {
7910     TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
7911     TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
7912     TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
7913     TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
7914     TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
7915            "__repr__($self, /)\n--\n\nReturn repr(self)."),
7916     TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
7917            "__hash__($self, /)\n--\n\nReturn hash(self)."),
7918     FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)(void(*)(void))wrap_call,
7919            "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
7920            PyWrapperFlag_KEYWORDS),
7921     TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
7922            "__str__($self, /)\n--\n\nReturn str(self)."),
7923     TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
7924            wrap_binaryfunc,
7925            "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
7926     TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
7927     TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
7928            "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
7929     TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
7930            "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
7931     TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
7932            "__lt__($self, value, /)\n--\n\nReturn self<value."),
7933     TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
7934            "__le__($self, value, /)\n--\n\nReturn self<=value."),
7935     TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
7936            "__eq__($self, value, /)\n--\n\nReturn self==value."),
7937     TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
7938            "__ne__($self, value, /)\n--\n\nReturn self!=value."),
7939     TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
7940            "__gt__($self, value, /)\n--\n\nReturn self>value."),
7941     TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
7942            "__ge__($self, value, /)\n--\n\nReturn self>=value."),
7943     TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
7944            "__iter__($self, /)\n--\n\nImplement iter(self)."),
7945     TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
7946            "__next__($self, /)\n--\n\nImplement next(self)."),
7947     TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
7948            "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
7949     TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
7950            "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
7951     TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
7952            wrap_descr_delete,
7953            "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
7954     FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)(void(*)(void))wrap_init,
7955            "__init__($self, /, *args, **kwargs)\n--\n\n"
7956            "Initialize self.  See help(type(self)) for accurate signature.",
7957            PyWrapperFlag_KEYWORDS),
7958     TPSLOT("__new__", tp_new, slot_tp_new, NULL,
7959            "__new__(type, /, *args, **kwargs)\n--\n\n"
7960            "Create and return new object.  See help(type) for accurate signature."),
7961     TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
7962 
7963     AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
7964            "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
7965     AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
7966            "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
7967     AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
7968            "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
7969 
7970     BINSLOT("__add__", nb_add, slot_nb_add,
7971            "+"),
7972     RBINSLOT("__radd__", nb_add, slot_nb_add,
7973            "+"),
7974     BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
7975            "-"),
7976     RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
7977            "-"),
7978     BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
7979            "*"),
7980     RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
7981            "*"),
7982     BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
7983            "%"),
7984     RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
7985            "%"),
7986     BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
7987            "Return divmod(self, value)."),
7988     RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
7989            "Return divmod(value, self)."),
7990     NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
7991            "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
7992     NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
7993            "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
7994     UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
7995     UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
7996     UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
7997            "abs(self)"),
7998     UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
7999            "True if self else False"),
8000     UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
8001     BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
8002     RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
8003     BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
8004     RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
8005     BINSLOT("__and__", nb_and, slot_nb_and, "&"),
8006     RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
8007     BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
8008     RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
8009     BINSLOT("__or__", nb_or, slot_nb_or, "|"),
8010     RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
8011     UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
8012            "int(self)"),
8013     UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
8014            "float(self)"),
8015     IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
8016            wrap_binaryfunc, "+="),
8017     IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
8018            wrap_binaryfunc, "-="),
8019     IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
8020            wrap_binaryfunc, "*="),
8021     IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
8022            wrap_binaryfunc, "%="),
8023     IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
8024            wrap_ternaryfunc, "**="),
8025     IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
8026            wrap_binaryfunc, "<<="),
8027     IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
8028            wrap_binaryfunc, ">>="),
8029     IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
8030            wrap_binaryfunc, "&="),
8031     IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
8032            wrap_binaryfunc, "^="),
8033     IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
8034            wrap_binaryfunc, "|="),
8035     BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
8036     RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
8037     BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
8038     RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
8039     IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
8040            slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
8041     IBSLOT("__itruediv__", nb_inplace_true_divide,
8042            slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
8043     NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
8044            "__index__($self, /)\n--\n\n"
8045            "Return self converted to an integer, if self is suitable "
8046            "for use as an index into a list."),
8047     BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
8048             "@"),
8049     RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
8050              "@"),
8051     IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
8052            wrap_binaryfunc, "@="),
8053     MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
8054            "__len__($self, /)\n--\n\nReturn len(self)."),
8055     MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
8056            wrap_binaryfunc,
8057            "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
8058     MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
8059            wrap_objobjargproc,
8060            "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
8061     MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
8062            wrap_delitem,
8063            "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
8064 
8065     SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
8066            "__len__($self, /)\n--\n\nReturn len(self)."),
8067     /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
8068        The logic in abstract.c always falls back to nb_add/nb_multiply in
8069        this case.  Defining both the nb_* and the sq_* slots to call the
8070        user-defined methods has unexpected side-effects, as shown by
8071        test_descr.notimplemented() */
8072     SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
8073            "__add__($self, value, /)\n--\n\nReturn self+value."),
8074     SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
8075            "__mul__($self, value, /)\n--\n\nReturn self*value."),
8076     SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
8077            "__rmul__($self, value, /)\n--\n\nReturn value*self."),
8078     SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
8079            "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
8080     SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
8081            "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
8082     SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
8083            "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
8084     SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
8085            "__contains__($self, key, /)\n--\n\nReturn key in self."),
8086     SQSLOT("__iadd__", sq_inplace_concat, NULL,
8087            wrap_binaryfunc,
8088            "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
8089     SQSLOT("__imul__", sq_inplace_repeat, NULL,
8090            wrap_indexargfunc,
8091            "__imul__($self, value, /)\n--\n\nImplement self*=value."),
8092 
8093     {NULL}
8094 };
8095 
8096 /* Given a type pointer and an offset gotten from a slotdef entry, return a
8097    pointer to the actual slot.  This is not quite the same as simply adding
8098    the offset to the type pointer, since it takes care to indirect through the
8099    proper indirection pointer (as_buffer, etc.); it returns NULL if the
8100    indirection pointer is NULL. */
8101 static void **
slotptr(PyTypeObject * type,int ioffset)8102 slotptr(PyTypeObject *type, int ioffset)
8103 {
8104     char *ptr;
8105     long offset = ioffset;
8106 
8107     /* Note: this depends on the order of the members of PyHeapTypeObject! */
8108     assert(offset >= 0);
8109     assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
8110     if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
8111         ptr = (char *)type->tp_as_sequence;
8112         offset -= offsetof(PyHeapTypeObject, as_sequence);
8113     }
8114     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
8115         ptr = (char *)type->tp_as_mapping;
8116         offset -= offsetof(PyHeapTypeObject, as_mapping);
8117     }
8118     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
8119         ptr = (char *)type->tp_as_number;
8120         offset -= offsetof(PyHeapTypeObject, as_number);
8121     }
8122     else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
8123         ptr = (char *)type->tp_as_async;
8124         offset -= offsetof(PyHeapTypeObject, as_async);
8125     }
8126     else {
8127         ptr = (char *)type;
8128     }
8129     if (ptr != NULL)
8130         ptr += offset;
8131     return (void **)ptr;
8132 }
8133 
8134 /* Length of array of slotdef pointers used to store slots with the
8135    same __name__.  There should be at most MAX_EQUIV-1 slotdef entries with
8136    the same __name__, for any __name__. Since that's a static property, it is
8137    appropriate to declare fixed-size arrays for this. */
8138 #define MAX_EQUIV 10
8139 
8140 /* Return a slot pointer for a given name, but ONLY if the attribute has
8141    exactly one slot function.  The name must be an interned string. */
8142 static void **
resolve_slotdups(PyTypeObject * type,PyObject * name)8143 resolve_slotdups(PyTypeObject *type, PyObject *name)
8144 {
8145     /* XXX Maybe this could be optimized more -- but is it worth it? */
8146 
8147     /* pname and ptrs act as a little cache */
8148     static PyObject *pname;
8149     static slotdef *ptrs[MAX_EQUIV];
8150     slotdef *p, **pp;
8151     void **res, **ptr;
8152 
8153     if (pname != name) {
8154         /* Collect all slotdefs that match name into ptrs. */
8155         pname = name;
8156         pp = ptrs;
8157         for (p = slotdefs; p->name_strobj; p++) {
8158             if (p->name_strobj == name)
8159                 *pp++ = p;
8160         }
8161         *pp = NULL;
8162     }
8163 
8164     /* Look in all slots of the type matching the name. If exactly one of these
8165        has a filled-in slot, return a pointer to that slot.
8166        Otherwise, return NULL. */
8167     res = NULL;
8168     for (pp = ptrs; *pp; pp++) {
8169         ptr = slotptr(type, (*pp)->offset);
8170         if (ptr == NULL || *ptr == NULL)
8171             continue;
8172         if (res != NULL)
8173             return NULL;
8174         res = ptr;
8175     }
8176     return res;
8177 }
8178 
8179 
8180 /* Common code for update_slots_callback() and fixup_slot_dispatchers().
8181  *
8182  * This is meant to set a "slot" like type->tp_repr or
8183  * type->tp_as_sequence->sq_concat by looking up special methods like
8184  * __repr__ or __add__. The opposite (adding special methods from slots) is
8185  * done by add_operators(), called from PyType_Ready(). Since update_one_slot()
8186  * calls PyType_Ready() if needed, the special methods are already in place.
8187  *
8188  * The special methods corresponding to each slot are defined in the "slotdef"
8189  * array. Note that one slot may correspond to multiple special methods and vice
8190  * versa. For example, tp_richcompare uses 6 methods __lt__, ..., __ge__ and
8191  * tp_as_number->nb_add uses __add__ and __radd__. In the other direction,
8192  * __add__ is used by the number and sequence protocols and __getitem__ by the
8193  * sequence and mapping protocols. This causes a lot of complications.
8194  *
8195  * In detail, update_one_slot() does the following:
8196  *
8197  * First of all, if the slot in question does not exist, return immediately.
8198  * This can happen for example if it's tp_as_number->nb_add but tp_as_number
8199  * is NULL.
8200  *
8201  * For the given slot, we loop over all the special methods with a name
8202  * corresponding to that slot (for example, for tp_descr_set, this would be
8203  * __set__ and __delete__) and we look up these names in the MRO of the type.
8204  * If we don't find any special method, the slot is set to NULL (regardless of
8205  * what was in the slot before).
8206  *
8207  * Suppose that we find exactly one special method. If it's a wrapper_descriptor
8208  * (i.e. a special method calling a slot, for example str.__repr__ which calls
8209  * the tp_repr for the 'str' class) with the correct name ("__repr__" for
8210  * tp_repr), for the right class, calling the right wrapper C function (like
8211  * wrap_unaryfunc for tp_repr), then the slot is set to the slot that the
8212  * wrapper_descriptor originally wrapped. For example, a class inheriting
8213  * from 'str' and not redefining __repr__ will have tp_repr set to the tp_repr
8214  * of 'str'.
8215  * In all other cases where the special method exists, the slot is set to a
8216  * wrapper calling the special method. There is one exception: if the special
8217  * method is a wrapper_descriptor with the correct name but the type has
8218  * precisely one slot set for that name and that slot is not the one that we
8219  * are updating, then NULL is put in the slot (this exception is the only place
8220  * in update_one_slot() where the *existing* slots matter).
8221  *
8222  * When there are multiple special methods for the same slot, the above is
8223  * applied for each special method. As long as the results agree, the common
8224  * resulting slot is applied. If the results disagree, then a wrapper for
8225  * the special methods is installed. This is always safe, but less efficient
8226  * because it uses method lookup instead of direct C calls.
8227  *
8228  * There are some further special cases for specific slots, like supporting
8229  * __hash__ = None for tp_hash and special code for tp_new.
8230  *
8231  * When done, return a pointer to the next slotdef with a different offset,
8232  * because that's convenient for fixup_slot_dispatchers(). This function never
8233  * sets an exception: if an internal error happens (unlikely), it's ignored. */
8234 static slotdef *
update_one_slot(PyTypeObject * type,slotdef * p)8235 update_one_slot(PyTypeObject *type, slotdef *p)
8236 {
8237     PyObject *descr;
8238     PyWrapperDescrObject *d;
8239     void *generic = NULL, *specific = NULL;
8240     int use_generic = 0;
8241     int offset = p->offset;
8242     int error;
8243     void **ptr = slotptr(type, offset);
8244 
8245     if (ptr == NULL) {
8246         do {
8247             ++p;
8248         } while (p->offset == offset);
8249         return p;
8250     }
8251     /* We may end up clearing live exceptions below, so make sure it's ours. */
8252     assert(!PyErr_Occurred());
8253     do {
8254         /* Use faster uncached lookup as we won't get any cache hits during type setup. */
8255         descr = find_name_in_mro(type, p->name_strobj, &error);
8256         if (descr == NULL) {
8257             if (error == -1) {
8258                 /* It is unlikely but not impossible that there has been an exception
8259                    during lookup. Since this function originally expected no errors,
8260                    we ignore them here in order to keep up the interface. */
8261                 PyErr_Clear();
8262             }
8263             if (ptr == (void**)&type->tp_iternext) {
8264                 specific = (void *)_PyObject_NextNotImplemented;
8265             }
8266             continue;
8267         }
8268         if (Py_IS_TYPE(descr, &PyWrapperDescr_Type) &&
8269             ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
8270             void **tptr = resolve_slotdups(type, p->name_strobj);
8271             if (tptr == NULL || tptr == ptr)
8272                 generic = p->function;
8273             d = (PyWrapperDescrObject *)descr;
8274             if ((specific == NULL || specific == d->d_wrapped) &&
8275                 d->d_base->wrapper == p->wrapper &&
8276                 PyType_IsSubtype(type, PyDescr_TYPE(d)))
8277             {
8278                 specific = d->d_wrapped;
8279             }
8280             else {
8281                 /* We cannot use the specific slot function because either
8282                    - it is not unique: there are multiple methods for this
8283                      slot and they conflict
8284                    - the signature is wrong (as checked by the ->wrapper
8285                      comparison above)
8286                    - it's wrapping the wrong class
8287                  */
8288                 use_generic = 1;
8289             }
8290         }
8291         else if (Py_IS_TYPE(descr, &PyCFunction_Type) &&
8292                  PyCFunction_GET_FUNCTION(descr) ==
8293                  (PyCFunction)(void(*)(void))tp_new_wrapper &&
8294                  ptr == (void**)&type->tp_new)
8295         {
8296             /* The __new__ wrapper is not a wrapper descriptor,
8297                so must be special-cased differently.
8298                If we don't do this, creating an instance will
8299                always use slot_tp_new which will look up
8300                __new__ in the MRO which will call tp_new_wrapper
8301                which will look through the base classes looking
8302                for a static base and call its tp_new (usually
8303                PyType_GenericNew), after performing various
8304                sanity checks and constructing a new argument
8305                list.  Cut all that nonsense short -- this speeds
8306                up instance creation tremendously. */
8307             specific = (void *)type->tp_new;
8308             /* XXX I'm not 100% sure that there isn't a hole
8309                in this reasoning that requires additional
8310                sanity checks.  I'll buy the first person to
8311                point out a bug in this reasoning a beer. */
8312         }
8313         else if (descr == Py_None &&
8314                  ptr == (void**)&type->tp_hash) {
8315             /* We specifically allow __hash__ to be set to None
8316                to prevent inheritance of the default
8317                implementation from object.__hash__ */
8318             specific = (void *)PyObject_HashNotImplemented;
8319         }
8320         else {
8321             use_generic = 1;
8322             generic = p->function;
8323         }
8324     } while ((++p)->offset == offset);
8325     if (specific && !use_generic)
8326         *ptr = specific;
8327     else
8328         *ptr = generic;
8329     return p;
8330 }
8331 
8332 /* In the type, update the slots whose slotdefs are gathered in the pp array.
8333    This is a callback for update_subclasses(). */
8334 static int
update_slots_callback(PyTypeObject * type,void * data)8335 update_slots_callback(PyTypeObject *type, void *data)
8336 {
8337     slotdef **pp = (slotdef **)data;
8338 
8339     for (; *pp; pp++)
8340         update_one_slot(type, *pp);
8341     return 0;
8342 }
8343 
8344 static int slotdefs_initialized = 0;
8345 /* Initialize the slotdefs table by adding interned string objects for the
8346    names. */
8347 PyStatus
_PyTypes_InitSlotDefs(void)8348 _PyTypes_InitSlotDefs(void)
8349 {
8350     if (slotdefs_initialized) {
8351         return _PyStatus_OK();
8352     }
8353 
8354     for (slotdef *p = slotdefs; p->name; p++) {
8355         /* Slots must be ordered by their offset in the PyHeapTypeObject. */
8356         assert(!p[1].name || p->offset <= p[1].offset);
8357 #ifdef INTERN_NAME_STRINGS
8358         p->name_strobj = PyUnicode_InternFromString(p->name);
8359         if (!p->name_strobj || !PyUnicode_CHECK_INTERNED(p->name_strobj)) {
8360             return _PyStatus_NO_MEMORY();
8361         }
8362 #else
8363         p->name_strobj = PyUnicode_FromString(p->name);
8364         if (!p->name_strobj) {
8365             return _PyStatus_NO_MEMORY();
8366         }
8367 #endif
8368     }
8369     slotdefs_initialized = 1;
8370     return _PyStatus_OK();
8371 }
8372 
8373 /* Undo _PyTypes_InitSlotDefs(), releasing the interned strings. */
clear_slotdefs(void)8374 static void clear_slotdefs(void)
8375 {
8376     for (slotdef *p = slotdefs; p->name; p++) {
8377         Py_CLEAR(p->name_strobj);
8378     }
8379     slotdefs_initialized = 0;
8380 }
8381 
8382 /* Update the slots after assignment to a class (type) attribute. */
8383 static int
update_slot(PyTypeObject * type,PyObject * name)8384 update_slot(PyTypeObject *type, PyObject *name)
8385 {
8386     slotdef *ptrs[MAX_EQUIV];
8387     slotdef *p;
8388     slotdef **pp;
8389     int offset;
8390 
8391     assert(PyUnicode_CheckExact(name));
8392 #ifdef INTERN_NAME_STRINGS
8393     assert(PyUnicode_CHECK_INTERNED(name));
8394 #endif
8395 
8396     assert(slotdefs_initialized);
8397     pp = ptrs;
8398     for (p = slotdefs; p->name; p++) {
8399         assert(PyUnicode_CheckExact(p->name_strobj));
8400         assert(PyUnicode_CheckExact(name));
8401 #ifdef INTERN_NAME_STRINGS
8402         if (p->name_strobj == name) {
8403             *pp++ = p;
8404         }
8405 #else
8406         if (p->name_strobj == name || _PyUnicode_EQ(p->name_strobj, name)) {
8407             *pp++ = p;
8408         }
8409 #endif
8410     }
8411     *pp = NULL;
8412     for (pp = ptrs; *pp; pp++) {
8413         p = *pp;
8414         offset = p->offset;
8415         while (p > slotdefs && (p-1)->offset == offset)
8416             --p;
8417         *pp = p;
8418     }
8419     if (ptrs[0] == NULL)
8420         return 0; /* Not an attribute that affects any slots */
8421     return update_subclasses(type, name,
8422                              update_slots_callback, (void *)ptrs);
8423 }
8424 
8425 /* Store the proper functions in the slot dispatches at class (type)
8426    definition time, based upon which operations the class overrides in its
8427    dict. */
8428 static void
fixup_slot_dispatchers(PyTypeObject * type)8429 fixup_slot_dispatchers(PyTypeObject *type)
8430 {
8431     assert(!PyErr_Occurred());
8432     assert(slotdefs_initialized);
8433     for (slotdef *p = slotdefs; p->name; ) {
8434         p = update_one_slot(type, p);
8435     }
8436 }
8437 
8438 static void
update_all_slots(PyTypeObject * type)8439 update_all_slots(PyTypeObject* type)
8440 {
8441     slotdef *p;
8442 
8443     /* Clear the VALID_VERSION flag of 'type' and all its subclasses. */
8444     PyType_Modified(type);
8445 
8446     assert(slotdefs_initialized);
8447     for (p = slotdefs; p->name; p++) {
8448         /* update_slot returns int but can't actually fail */
8449         update_slot(type, p->name_strobj);
8450     }
8451 }
8452 
8453 
8454 /* Call __set_name__ on all attributes (including descriptors)
8455   in a newly generated type */
8456 static int
type_new_set_names(PyTypeObject * type)8457 type_new_set_names(PyTypeObject *type)
8458 {
8459     PyObject *names_to_set = PyDict_Copy(type->tp_dict);
8460     if (names_to_set == NULL) {
8461         return -1;
8462     }
8463 
8464     Py_ssize_t i = 0;
8465     PyObject *key, *value;
8466     while (PyDict_Next(names_to_set, &i, &key, &value)) {
8467         PyObject *set_name = _PyObject_LookupSpecial(value, &PyId___set_name__);
8468         if (set_name == NULL) {
8469             if (PyErr_Occurred()) {
8470                 goto error;
8471             }
8472             continue;
8473         }
8474 
8475         PyObject *res = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
8476         Py_DECREF(set_name);
8477 
8478         if (res == NULL) {
8479             _PyErr_FormatFromCause(PyExc_RuntimeError,
8480                 "Error calling __set_name__ on '%.100s' instance %R "
8481                 "in '%.100s'",
8482                 Py_TYPE(value)->tp_name, key, type->tp_name);
8483             goto error;
8484         }
8485         Py_DECREF(res);
8486     }
8487 
8488     Py_DECREF(names_to_set);
8489     return 0;
8490 
8491 error:
8492     Py_DECREF(names_to_set);
8493     return -1;
8494 }
8495 
8496 
8497 /* Call __init_subclass__ on the parent of a newly generated type */
8498 static int
type_new_init_subclass(PyTypeObject * type,PyObject * kwds)8499 type_new_init_subclass(PyTypeObject *type, PyObject *kwds)
8500 {
8501     PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
8502     PyObject *super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
8503     if (super == NULL) {
8504         return -1;
8505     }
8506 
8507     PyObject *func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
8508     Py_DECREF(super);
8509     if (func == NULL) {
8510         return -1;
8511     }
8512 
8513     PyObject *result = PyObject_VectorcallDict(func, NULL, 0, kwds);
8514     Py_DECREF(func);
8515     if (result == NULL) {
8516         return -1;
8517     }
8518 
8519     Py_DECREF(result);
8520     return 0;
8521 }
8522 
8523 
8524 /* recurse_down_subclasses() and update_subclasses() are mutually
8525    recursive functions to call a callback for all subclasses,
8526    but refraining from recursing into subclasses that define 'name'. */
8527 
8528 static int
update_subclasses(PyTypeObject * type,PyObject * name,update_callback callback,void * data)8529 update_subclasses(PyTypeObject *type, PyObject *name,
8530                   update_callback callback, void *data)
8531 {
8532     if (callback(type, data) < 0)
8533         return -1;
8534     return recurse_down_subclasses(type, name, callback, data);
8535 }
8536 
8537 static int
recurse_down_subclasses(PyTypeObject * type,PyObject * name,update_callback callback,void * data)8538 recurse_down_subclasses(PyTypeObject *type, PyObject *name,
8539                         update_callback callback, void *data)
8540 {
8541     PyTypeObject *subclass;
8542     PyObject *ref, *subclasses, *dict;
8543     Py_ssize_t i;
8544 
8545     subclasses = type->tp_subclasses;
8546     if (subclasses == NULL)
8547         return 0;
8548     assert(PyDict_CheckExact(subclasses));
8549     i = 0;
8550     while (PyDict_Next(subclasses, &i, NULL, &ref)) {
8551         assert(PyWeakref_CheckRef(ref));
8552         subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
8553         assert(subclass != NULL);
8554         if ((PyObject *)subclass == Py_None)
8555             continue;
8556         assert(PyType_Check(subclass));
8557         /* Avoid recursing down into unaffected classes */
8558         dict = subclass->tp_dict;
8559         if (dict != NULL && PyDict_Check(dict)) {
8560             int r = PyDict_Contains(dict, name);
8561             if (r > 0) {
8562                 continue;
8563             }
8564             if (r < 0) {
8565                 return -1;
8566             }
8567         }
8568         if (update_subclasses(subclass, name, callback, data) < 0)
8569             return -1;
8570     }
8571     return 0;
8572 }
8573 
8574 /* This function is called by PyType_Ready() to populate the type's
8575    dictionary with method descriptors for function slots.  For each
8576    function slot (like tp_repr) that's defined in the type, one or more
8577    corresponding descriptors are added in the type's tp_dict dictionary
8578    under the appropriate name (like __repr__).  Some function slots
8579    cause more than one descriptor to be added (for example, the nb_add
8580    slot adds both __add__ and __radd__ descriptors) and some function
8581    slots compete for the same descriptor (for example both sq_item and
8582    mp_subscript generate a __getitem__ descriptor).
8583 
8584    In the latter case, the first slotdef entry encountered wins.  Since
8585    slotdef entries are sorted by the offset of the slot in the
8586    PyHeapTypeObject, this gives us some control over disambiguating
8587    between competing slots: the members of PyHeapTypeObject are listed
8588    from most general to least general, so the most general slot is
8589    preferred.  In particular, because as_mapping comes before as_sequence,
8590    for a type that defines both mp_subscript and sq_item, mp_subscript
8591    wins.
8592 
8593    This only adds new descriptors and doesn't overwrite entries in
8594    tp_dict that were previously defined.  The descriptors contain a
8595    reference to the C function they must call, so that it's safe if they
8596    are copied into a subtype's __dict__ and the subtype has a different
8597    C function in its slot -- calling the method defined by the
8598    descriptor will call the C function that was used to create it,
8599    rather than the C function present in the slot when it is called.
8600    (This is important because a subtype may have a C function in the
8601    slot that calls the method from the dictionary, and we want to avoid
8602    infinite recursion here.) */
8603 
8604 static int
add_operators(PyTypeObject * type)8605 add_operators(PyTypeObject *type)
8606 {
8607     PyObject *dict = type->tp_dict;
8608     slotdef *p;
8609     PyObject *descr;
8610     void **ptr;
8611 
8612     assert(slotdefs_initialized);
8613     for (p = slotdefs; p->name; p++) {
8614         if (p->wrapper == NULL)
8615             continue;
8616         ptr = slotptr(type, p->offset);
8617         if (!ptr || !*ptr)
8618             continue;
8619         int r = PyDict_Contains(dict, p->name_strobj);
8620         if (r > 0)
8621             continue;
8622         if (r < 0) {
8623             return -1;
8624         }
8625         if (*ptr == (void *)PyObject_HashNotImplemented) {
8626             /* Classes may prevent the inheritance of the tp_hash
8627                slot by storing PyObject_HashNotImplemented in it. Make it
8628                visible as a None value for the __hash__ attribute. */
8629             if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
8630                 return -1;
8631         }
8632         else {
8633             descr = PyDescr_NewWrapper(type, p, *ptr);
8634             if (descr == NULL)
8635                 return -1;
8636             if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
8637                 Py_DECREF(descr);
8638                 return -1;
8639             }
8640             Py_DECREF(descr);
8641         }
8642     }
8643     return 0;
8644 }
8645 
8646 
8647 /* Cooperative 'super' */
8648 
8649 typedef struct {
8650     PyObject_HEAD
8651     PyTypeObject *type;
8652     PyObject *obj;
8653     PyTypeObject *obj_type;
8654 } superobject;
8655 
8656 static PyMemberDef super_members[] = {
8657     {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
8658      "the class invoking super()"},
8659     {"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
8660      "the instance invoking super(); may be None"},
8661     {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
8662      "the type of the instance invoking super(); may be None"},
8663     {0}
8664 };
8665 
8666 static void
super_dealloc(PyObject * self)8667 super_dealloc(PyObject *self)
8668 {
8669     superobject *su = (superobject *)self;
8670 
8671     _PyObject_GC_UNTRACK(self);
8672     Py_XDECREF(su->obj);
8673     Py_XDECREF(su->type);
8674     Py_XDECREF(su->obj_type);
8675     Py_TYPE(self)->tp_free(self);
8676 }
8677 
8678 static PyObject *
super_repr(PyObject * self)8679 super_repr(PyObject *self)
8680 {
8681     superobject *su = (superobject *)self;
8682 
8683     if (su->obj_type)
8684         return PyUnicode_FromFormat(
8685             "<super: <class '%s'>, <%s object>>",
8686             su->type ? su->type->tp_name : "NULL",
8687             su->obj_type->tp_name);
8688     else
8689         return PyUnicode_FromFormat(
8690             "<super: <class '%s'>, NULL>",
8691             su->type ? su->type->tp_name : "NULL");
8692 }
8693 
8694 static PyObject *
super_getattro(PyObject * self,PyObject * name)8695 super_getattro(PyObject *self, PyObject *name)
8696 {
8697     superobject *su = (superobject *)self;
8698     PyTypeObject *starttype;
8699     PyObject *mro;
8700     Py_ssize_t i, n;
8701 
8702     starttype = su->obj_type;
8703     if (starttype == NULL)
8704         goto skip;
8705 
8706     /* We want __class__ to return the class of the super object
8707        (i.e. super, or a subclass), not the class of su->obj. */
8708     if (PyUnicode_Check(name) &&
8709         PyUnicode_GET_LENGTH(name) == 9 &&
8710         _PyUnicode_EqualToASCIIId(name, &PyId___class__))
8711         goto skip;
8712 
8713     mro = starttype->tp_mro;
8714     if (mro == NULL)
8715         goto skip;
8716 
8717     assert(PyTuple_Check(mro));
8718     n = PyTuple_GET_SIZE(mro);
8719 
8720     /* No need to check the last one: it's gonna be skipped anyway.  */
8721     for (i = 0; i+1 < n; i++) {
8722         if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
8723             break;
8724     }
8725     i++;  /* skip su->type (if any)  */
8726     if (i >= n)
8727         goto skip;
8728 
8729     /* keep a strong reference to mro because starttype->tp_mro can be
8730        replaced during PyDict_GetItemWithError(dict, name)  */
8731     Py_INCREF(mro);
8732     do {
8733         PyObject *res, *tmp, *dict;
8734         descrgetfunc f;
8735 
8736         tmp = PyTuple_GET_ITEM(mro, i);
8737         assert(PyType_Check(tmp));
8738 
8739         dict = ((PyTypeObject *)tmp)->tp_dict;
8740         assert(dict != NULL && PyDict_Check(dict));
8741 
8742         res = PyDict_GetItemWithError(dict, name);
8743         if (res != NULL) {
8744             Py_INCREF(res);
8745 
8746             f = Py_TYPE(res)->tp_descr_get;
8747             if (f != NULL) {
8748                 tmp = f(res,
8749                     /* Only pass 'obj' param if this is instance-mode super
8750                        (See SF ID #743627)  */
8751                     (su->obj == (PyObject *)starttype) ? NULL : su->obj,
8752                     (PyObject *)starttype);
8753                 Py_DECREF(res);
8754                 res = tmp;
8755             }
8756 
8757             Py_DECREF(mro);
8758             return res;
8759         }
8760         else if (PyErr_Occurred()) {
8761             Py_DECREF(mro);
8762             return NULL;
8763         }
8764 
8765         i++;
8766     } while (i < n);
8767     Py_DECREF(mro);
8768 
8769   skip:
8770     return PyObject_GenericGetAttr(self, name);
8771 }
8772 
8773 static PyTypeObject *
supercheck(PyTypeObject * type,PyObject * obj)8774 supercheck(PyTypeObject *type, PyObject *obj)
8775 {
8776     /* Check that a super() call makes sense.  Return a type object.
8777 
8778        obj can be a class, or an instance of one:
8779 
8780        - If it is a class, it must be a subclass of 'type'.      This case is
8781          used for class methods; the return value is obj.
8782 
8783        - If it is an instance, it must be an instance of 'type'.  This is
8784          the normal case; the return value is obj.__class__.
8785 
8786        But... when obj is an instance, we want to allow for the case where
8787        Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
8788        This will allow using super() with a proxy for obj.
8789     */
8790 
8791     /* Check for first bullet above (special case) */
8792     if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
8793         Py_INCREF(obj);
8794         return (PyTypeObject *)obj;
8795     }
8796 
8797     /* Normal case */
8798     if (PyType_IsSubtype(Py_TYPE(obj), type)) {
8799         Py_INCREF(Py_TYPE(obj));
8800         return Py_TYPE(obj);
8801     }
8802     else {
8803         /* Try the slow way */
8804         PyObject *class_attr;
8805 
8806         if (_PyObject_LookupAttrId(obj, &PyId___class__, &class_attr) < 0) {
8807             return NULL;
8808         }
8809         if (class_attr != NULL &&
8810             PyType_Check(class_attr) &&
8811             (PyTypeObject *)class_attr != Py_TYPE(obj))
8812         {
8813             int ok = PyType_IsSubtype(
8814                 (PyTypeObject *)class_attr, type);
8815             if (ok)
8816                 return (PyTypeObject *)class_attr;
8817         }
8818         Py_XDECREF(class_attr);
8819     }
8820 
8821     PyErr_SetString(PyExc_TypeError,
8822                     "super(type, obj): "
8823                     "obj must be an instance or subtype of type");
8824     return NULL;
8825 }
8826 
8827 static PyObject *
super_descr_get(PyObject * self,PyObject * obj,PyObject * type)8828 super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
8829 {
8830     superobject *su = (superobject *)self;
8831     superobject *newobj;
8832 
8833     if (obj == NULL || obj == Py_None || su->obj != NULL) {
8834         /* Not binding to an object, or already bound */
8835         Py_INCREF(self);
8836         return self;
8837     }
8838     if (!Py_IS_TYPE(su, &PySuper_Type))
8839         /* If su is an instance of a (strict) subclass of super,
8840            call its type */
8841         return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
8842                                             su->type, obj, NULL);
8843     else {
8844         /* Inline the common case */
8845         PyTypeObject *obj_type = supercheck(su->type, obj);
8846         if (obj_type == NULL)
8847             return NULL;
8848         newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
8849                                                  NULL, NULL);
8850         if (newobj == NULL)
8851             return NULL;
8852         Py_INCREF(su->type);
8853         Py_INCREF(obj);
8854         newobj->type = su->type;
8855         newobj->obj = obj;
8856         newobj->obj_type = obj_type;
8857         return (PyObject *)newobj;
8858     }
8859 }
8860 
8861 static int
super_init_without_args(PyFrameObject * f,PyCodeObject * co,PyTypeObject ** type_p,PyObject ** obj_p)8862 super_init_without_args(PyFrameObject *f, PyCodeObject *co,
8863                         PyTypeObject **type_p, PyObject **obj_p)
8864 {
8865     if (co->co_argcount == 0) {
8866         PyErr_SetString(PyExc_RuntimeError,
8867                         "super(): no arguments");
8868         return -1;
8869     }
8870 
8871     PyObject *obj = f->f_localsplus[0];
8872     Py_ssize_t i, n;
8873     if (obj == NULL && co->co_cell2arg) {
8874         /* The first argument might be a cell. */
8875         n = PyTuple_GET_SIZE(co->co_cellvars);
8876         for (i = 0; i < n; i++) {
8877             if (co->co_cell2arg[i] == 0) {
8878                 PyObject *cell = f->f_localsplus[co->co_nlocals + i];
8879                 assert(PyCell_Check(cell));
8880                 obj = PyCell_GET(cell);
8881                 break;
8882             }
8883         }
8884     }
8885     if (obj == NULL) {
8886         PyErr_SetString(PyExc_RuntimeError,
8887                         "super(): arg[0] deleted");
8888         return -1;
8889     }
8890 
8891     if (co->co_freevars == NULL) {
8892         n = 0;
8893     }
8894     else {
8895         assert(PyTuple_Check(co->co_freevars));
8896         n = PyTuple_GET_SIZE(co->co_freevars);
8897     }
8898 
8899     PyTypeObject *type = NULL;
8900     for (i = 0; i < n; i++) {
8901         PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
8902         assert(PyUnicode_Check(name));
8903         if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
8904             Py_ssize_t index = co->co_nlocals +
8905                 PyTuple_GET_SIZE(co->co_cellvars) + i;
8906             PyObject *cell = f->f_localsplus[index];
8907             if (cell == NULL || !PyCell_Check(cell)) {
8908                 PyErr_SetString(PyExc_RuntimeError,
8909                   "super(): bad __class__ cell");
8910                 return -1;
8911             }
8912             type = (PyTypeObject *) PyCell_GET(cell);
8913             if (type == NULL) {
8914                 PyErr_SetString(PyExc_RuntimeError,
8915                   "super(): empty __class__ cell");
8916                 return -1;
8917             }
8918             if (!PyType_Check(type)) {
8919                 PyErr_Format(PyExc_RuntimeError,
8920                   "super(): __class__ is not a type (%s)",
8921                   Py_TYPE(type)->tp_name);
8922                 return -1;
8923             }
8924             break;
8925         }
8926     }
8927     if (type == NULL) {
8928         PyErr_SetString(PyExc_RuntimeError,
8929                         "super(): __class__ cell not found");
8930         return -1;
8931     }
8932 
8933     *type_p = type;
8934     *obj_p = obj;
8935     return 0;
8936 }
8937 
8938 static int
super_init(PyObject * self,PyObject * args,PyObject * kwds)8939 super_init(PyObject *self, PyObject *args, PyObject *kwds)
8940 {
8941     superobject *su = (superobject *)self;
8942     PyTypeObject *type = NULL;
8943     PyObject *obj = NULL;
8944     PyTypeObject *obj_type = NULL;
8945 
8946     if (!_PyArg_NoKeywords("super", kwds))
8947         return -1;
8948     if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
8949         return -1;
8950 
8951     if (type == NULL) {
8952         /* Call super(), without args -- fill in from __class__
8953            and first local variable on the stack. */
8954         PyThreadState *tstate = _PyThreadState_GET();
8955         PyFrameObject *frame = PyThreadState_GetFrame(tstate);
8956         if (frame == NULL) {
8957             PyErr_SetString(PyExc_RuntimeError,
8958                             "super(): no current frame");
8959             return -1;
8960         }
8961 
8962         PyCodeObject *code = PyFrame_GetCode(frame);
8963         int res = super_init_without_args(frame, code, &type, &obj);
8964         Py_DECREF(frame);
8965         Py_DECREF(code);
8966 
8967         if (res < 0) {
8968             return -1;
8969         }
8970     }
8971 
8972     if (obj == Py_None)
8973         obj = NULL;
8974     if (obj != NULL) {
8975         obj_type = supercheck(type, obj);
8976         if (obj_type == NULL)
8977             return -1;
8978         Py_INCREF(obj);
8979     }
8980     Py_INCREF(type);
8981     Py_XSETREF(su->type, type);
8982     Py_XSETREF(su->obj, obj);
8983     Py_XSETREF(su->obj_type, obj_type);
8984     return 0;
8985 }
8986 
8987 PyDoc_STRVAR(super_doc,
8988 "super() -> same as super(__class__, <first argument>)\n"
8989 "super(type) -> unbound super object\n"
8990 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
8991 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
8992 "Typical use to call a cooperative superclass method:\n"
8993 "class C(B):\n"
8994 "    def meth(self, arg):\n"
8995 "        super().meth(arg)\n"
8996 "This works for class methods too:\n"
8997 "class C(B):\n"
8998 "    @classmethod\n"
8999 "    def cmeth(cls, arg):\n"
9000 "        super().cmeth(arg)\n");
9001 
9002 static int
super_traverse(PyObject * self,visitproc visit,void * arg)9003 super_traverse(PyObject *self, visitproc visit, void *arg)
9004 {
9005     superobject *su = (superobject *)self;
9006 
9007     Py_VISIT(su->obj);
9008     Py_VISIT(su->type);
9009     Py_VISIT(su->obj_type);
9010 
9011     return 0;
9012 }
9013 
9014 PyTypeObject PySuper_Type = {
9015     PyVarObject_HEAD_INIT(&PyType_Type, 0)
9016     "super",                                    /* tp_name */
9017     sizeof(superobject),                        /* tp_basicsize */
9018     0,                                          /* tp_itemsize */
9019     /* methods */
9020     super_dealloc,                              /* tp_dealloc */
9021     0,                                          /* tp_vectorcall_offset */
9022     0,                                          /* tp_getattr */
9023     0,                                          /* tp_setattr */
9024     0,                                          /* tp_as_async */
9025     super_repr,                                 /* tp_repr */
9026     0,                                          /* tp_as_number */
9027     0,                                          /* tp_as_sequence */
9028     0,                                          /* tp_as_mapping */
9029     0,                                          /* tp_hash */
9030     0,                                          /* tp_call */
9031     0,                                          /* tp_str */
9032     super_getattro,                             /* tp_getattro */
9033     0,                                          /* tp_setattro */
9034     0,                                          /* tp_as_buffer */
9035     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
9036         Py_TPFLAGS_BASETYPE,                    /* tp_flags */
9037     super_doc,                                  /* tp_doc */
9038     super_traverse,                             /* tp_traverse */
9039     0,                                          /* tp_clear */
9040     0,                                          /* tp_richcompare */
9041     0,                                          /* tp_weaklistoffset */
9042     0,                                          /* tp_iter */
9043     0,                                          /* tp_iternext */
9044     0,                                          /* tp_methods */
9045     super_members,                              /* tp_members */
9046     0,                                          /* tp_getset */
9047     0,                                          /* tp_base */
9048     0,                                          /* tp_dict */
9049     super_descr_get,                            /* tp_descr_get */
9050     0,                                          /* tp_descr_set */
9051     0,                                          /* tp_dictoffset */
9052     super_init,                                 /* tp_init */
9053     PyType_GenericAlloc,                        /* tp_alloc */
9054     PyType_GenericNew,                          /* tp_new */
9055     PyObject_GC_Del,                            /* tp_free */
9056 };
9057