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