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