1 /* Abstract Object Interface (many thanks to Jim Fulton) */
2 
3 #include "Python.h"
4 #include "pycore_abstract.h"      // _PyIndex_Check()
5 #include "pycore_call.h"          // _PyObject_CallNoArgs()
6 #include "pycore_ceval.h"         // _Py_EnterRecursiveCallTstate()
7 #include "pycore_object.h"        // _Py_CheckSlotResult()
8 #include "pycore_pyerrors.h"      // _PyErr_Occurred()
9 #include "pycore_pystate.h"       // _PyThreadState_GET()
10 #include "pycore_unionobject.h"   // _PyUnion_Check()
11 #include <ctype.h>
12 #include <stddef.h>               // offsetof()
13 
14 
15 
16 /* Shorthands to return certain errors */
17 
18 static PyObject *
type_error(const char * msg,PyObject * obj)19 type_error(const char *msg, PyObject *obj)
20 {
21     PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
22     return NULL;
23 }
24 
25 static PyObject *
null_error(void)26 null_error(void)
27 {
28     PyThreadState *tstate = _PyThreadState_GET();
29     if (!_PyErr_Occurred(tstate)) {
30         _PyErr_SetString(tstate, PyExc_SystemError,
31                          "null argument to internal routine");
32     }
33     return NULL;
34 }
35 
36 /* Operations on any object */
37 
38 PyObject *
PyObject_Type(PyObject * o)39 PyObject_Type(PyObject *o)
40 {
41     PyObject *v;
42 
43     if (o == NULL) {
44         return null_error();
45     }
46 
47     v = (PyObject *)Py_TYPE(o);
48     Py_INCREF(v);
49     return v;
50 }
51 
52 Py_ssize_t
PyObject_Size(PyObject * o)53 PyObject_Size(PyObject *o)
54 {
55     if (o == NULL) {
56         null_error();
57         return -1;
58     }
59 
60     PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
61     if (m && m->sq_length) {
62         Py_ssize_t len = m->sq_length(o);
63         assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
64         return len;
65     }
66 
67     return PyMapping_Size(o);
68 }
69 
70 #undef PyObject_Length
71 Py_ssize_t
PyObject_Length(PyObject * o)72 PyObject_Length(PyObject *o)
73 {
74     return PyObject_Size(o);
75 }
76 #define PyObject_Length PyObject_Size
77 
78 int
_PyObject_HasLen(PyObject * o)79 _PyObject_HasLen(PyObject *o) {
80     return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
81         (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
82 }
83 
84 /* The length hint function returns a non-negative value from o.__len__()
85    or o.__length_hint__(). If those methods aren't found the defaultvalue is
86    returned.  If one of the calls fails with an exception other than TypeError
87    this function returns -1.
88 */
89 
90 Py_ssize_t
PyObject_LengthHint(PyObject * o,Py_ssize_t defaultvalue)91 PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
92 {
93     PyObject *hint, *result;
94     Py_ssize_t res;
95     if (_PyObject_HasLen(o)) {
96         res = PyObject_Length(o);
97         if (res < 0) {
98             PyThreadState *tstate = _PyThreadState_GET();
99             assert(_PyErr_Occurred(tstate));
100             if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
101                 return -1;
102             }
103             _PyErr_Clear(tstate);
104         }
105         else {
106             return res;
107         }
108     }
109     hint = _PyObject_LookupSpecial(o, &_Py_ID(__length_hint__));
110     if (hint == NULL) {
111         if (PyErr_Occurred()) {
112             return -1;
113         }
114         return defaultvalue;
115     }
116     result = _PyObject_CallNoArgs(hint);
117     Py_DECREF(hint);
118     if (result == NULL) {
119         PyThreadState *tstate = _PyThreadState_GET();
120         if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
121             _PyErr_Clear(tstate);
122             return defaultvalue;
123         }
124         return -1;
125     }
126     else if (result == Py_NotImplemented) {
127         Py_DECREF(result);
128         return defaultvalue;
129     }
130     if (!PyLong_Check(result)) {
131         PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
132             Py_TYPE(result)->tp_name);
133         Py_DECREF(result);
134         return -1;
135     }
136     res = PyLong_AsSsize_t(result);
137     Py_DECREF(result);
138     if (res < 0 && PyErr_Occurred()) {
139         return -1;
140     }
141     if (res < 0) {
142         PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
143         return -1;
144     }
145     return res;
146 }
147 
148 PyObject *
PyObject_GetItem(PyObject * o,PyObject * key)149 PyObject_GetItem(PyObject *o, PyObject *key)
150 {
151     if (o == NULL || key == NULL) {
152         return null_error();
153     }
154 
155     PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
156     if (m && m->mp_subscript) {
157         PyObject *item = m->mp_subscript(o, key);
158         assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL));
159         return item;
160     }
161 
162     PySequenceMethods *ms = Py_TYPE(o)->tp_as_sequence;
163     if (ms && ms->sq_item) {
164         if (_PyIndex_Check(key)) {
165             Py_ssize_t key_value;
166             key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
167             if (key_value == -1 && PyErr_Occurred())
168                 return NULL;
169             return PySequence_GetItem(o, key_value);
170         }
171         else {
172             return type_error("sequence index must "
173                               "be integer, not '%.200s'", key);
174         }
175     }
176 
177     if (PyType_Check(o)) {
178         PyObject *meth, *result;
179 
180         // Special case type[int], but disallow other types so str[int] fails
181         if ((PyTypeObject*)o == &PyType_Type) {
182             return Py_GenericAlias(o, key);
183         }
184 
185         if (_PyObject_LookupAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) {
186             return NULL;
187         }
188         if (meth && meth != Py_None) {
189             result = PyObject_CallOneArg(meth, key);
190             Py_DECREF(meth);
191             return result;
192         }
193         Py_XDECREF(meth);
194         PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable",
195                      ((PyTypeObject *)o)->tp_name);
196         return NULL;
197     }
198 
199     return type_error("'%.200s' object is not subscriptable", o);
200 }
201 
202 int
PyObject_SetItem(PyObject * o,PyObject * key,PyObject * value)203 PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
204 {
205     if (o == NULL || key == NULL || value == NULL) {
206         null_error();
207         return -1;
208     }
209 
210     PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
211     if (m && m->mp_ass_subscript) {
212         int res = m->mp_ass_subscript(o, key, value);
213         assert(_Py_CheckSlotResult(o, "__setitem__", res >= 0));
214         return res;
215     }
216 
217     if (Py_TYPE(o)->tp_as_sequence) {
218         if (_PyIndex_Check(key)) {
219             Py_ssize_t key_value;
220             key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
221             if (key_value == -1 && PyErr_Occurred())
222                 return -1;
223             return PySequence_SetItem(o, key_value, value);
224         }
225         else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
226             type_error("sequence index must be "
227                        "integer, not '%.200s'", key);
228             return -1;
229         }
230     }
231 
232     type_error("'%.200s' object does not support item assignment", o);
233     return -1;
234 }
235 
236 int
PyObject_DelItem(PyObject * o,PyObject * key)237 PyObject_DelItem(PyObject *o, PyObject *key)
238 {
239     if (o == NULL || key == NULL) {
240         null_error();
241         return -1;
242     }
243 
244     PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
245     if (m && m->mp_ass_subscript) {
246         int res = m->mp_ass_subscript(o, key, (PyObject*)NULL);
247         assert(_Py_CheckSlotResult(o, "__delitem__", res >= 0));
248         return res;
249     }
250 
251     if (Py_TYPE(o)->tp_as_sequence) {
252         if (_PyIndex_Check(key)) {
253             Py_ssize_t key_value;
254             key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
255             if (key_value == -1 && PyErr_Occurred())
256                 return -1;
257             return PySequence_DelItem(o, key_value);
258         }
259         else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
260             type_error("sequence index must be "
261                        "integer, not '%.200s'", key);
262             return -1;
263         }
264     }
265 
266     type_error("'%.200s' object does not support item deletion", o);
267     return -1;
268 }
269 
270 int
PyObject_DelItemString(PyObject * o,const char * key)271 PyObject_DelItemString(PyObject *o, const char *key)
272 {
273     PyObject *okey;
274     int ret;
275 
276     if (o == NULL || key == NULL) {
277         null_error();
278         return -1;
279     }
280     okey = PyUnicode_FromString(key);
281     if (okey == NULL)
282         return -1;
283     ret = PyObject_DelItem(o, okey);
284     Py_DECREF(okey);
285     return ret;
286 }
287 
288 
289 /* Return 1 if the getbuffer function is available, otherwise return 0. */
290 int
PyObject_CheckBuffer(PyObject * obj)291 PyObject_CheckBuffer(PyObject *obj)
292 {
293     PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
294     return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
295 }
296 
297 
298 /* We release the buffer right after use of this function which could
299    cause issues later on.  Don't use these functions in new code.
300  */
301 int
PyObject_CheckReadBuffer(PyObject * obj)302 PyObject_CheckReadBuffer(PyObject *obj)
303 {
304     PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
305     Py_buffer view;
306 
307     if (pb == NULL ||
308         pb->bf_getbuffer == NULL)
309         return 0;
310     if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
311         PyErr_Clear();
312         return 0;
313     }
314     PyBuffer_Release(&view);
315     return 1;
316 }
317 
318 static int
as_read_buffer(PyObject * obj,const void ** buffer,Py_ssize_t * buffer_len)319 as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
320 {
321     Py_buffer view;
322 
323     if (obj == NULL || buffer == NULL || buffer_len == NULL) {
324         null_error();
325         return -1;
326     }
327     if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
328         return -1;
329 
330     *buffer = view.buf;
331     *buffer_len = view.len;
332     PyBuffer_Release(&view);
333     return 0;
334 }
335 
336 int
PyObject_AsCharBuffer(PyObject * obj,const char ** buffer,Py_ssize_t * buffer_len)337 PyObject_AsCharBuffer(PyObject *obj,
338                       const char **buffer,
339                       Py_ssize_t *buffer_len)
340 {
341     return as_read_buffer(obj, (const void **)buffer, buffer_len);
342 }
343 
PyObject_AsReadBuffer(PyObject * obj,const void ** buffer,Py_ssize_t * buffer_len)344 int PyObject_AsReadBuffer(PyObject *obj,
345                           const void **buffer,
346                           Py_ssize_t *buffer_len)
347 {
348     return as_read_buffer(obj, buffer, buffer_len);
349 }
350 
PyObject_AsWriteBuffer(PyObject * obj,void ** buffer,Py_ssize_t * buffer_len)351 int PyObject_AsWriteBuffer(PyObject *obj,
352                            void **buffer,
353                            Py_ssize_t *buffer_len)
354 {
355     PyBufferProcs *pb;
356     Py_buffer view;
357 
358     if (obj == NULL || buffer == NULL || buffer_len == NULL) {
359         null_error();
360         return -1;
361     }
362     pb = Py_TYPE(obj)->tp_as_buffer;
363     if (pb == NULL ||
364         pb->bf_getbuffer == NULL ||
365         ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
366         PyErr_SetString(PyExc_TypeError,
367                         "expected a writable bytes-like object");
368         return -1;
369     }
370 
371     *buffer = view.buf;
372     *buffer_len = view.len;
373     PyBuffer_Release(&view);
374     return 0;
375 }
376 
377 /* Buffer C-API for Python 3.0 */
378 
379 int
PyObject_GetBuffer(PyObject * obj,Py_buffer * view,int flags)380 PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
381 {
382     PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
383 
384     if (pb == NULL || pb->bf_getbuffer == NULL) {
385         PyErr_Format(PyExc_TypeError,
386                      "a bytes-like object is required, not '%.100s'",
387                      Py_TYPE(obj)->tp_name);
388         return -1;
389     }
390     int res = (*pb->bf_getbuffer)(obj, view, flags);
391     assert(_Py_CheckSlotResult(obj, "getbuffer", res >= 0));
392     return res;
393 }
394 
395 static int
_IsFortranContiguous(const Py_buffer * view)396 _IsFortranContiguous(const Py_buffer *view)
397 {
398     Py_ssize_t sd, dim;
399     int i;
400 
401     /* 1) len = product(shape) * itemsize
402        2) itemsize > 0
403        3) len = 0 <==> exists i: shape[i] = 0 */
404     if (view->len == 0) return 1;
405     if (view->strides == NULL) {  /* C-contiguous by definition */
406         /* Trivially F-contiguous */
407         if (view->ndim <= 1) return 1;
408 
409         /* ndim > 1 implies shape != NULL */
410         assert(view->shape != NULL);
411 
412         /* Effectively 1-d */
413         sd = 0;
414         for (i=0; i<view->ndim; i++) {
415             if (view->shape[i] > 1) sd += 1;
416         }
417         return sd <= 1;
418     }
419 
420     /* strides != NULL implies both of these */
421     assert(view->ndim > 0);
422     assert(view->shape != NULL);
423 
424     sd = view->itemsize;
425     for (i=0; i<view->ndim; i++) {
426         dim = view->shape[i];
427         if (dim > 1 && view->strides[i] != sd) {
428             return 0;
429         }
430         sd *= dim;
431     }
432     return 1;
433 }
434 
435 static int
_IsCContiguous(const Py_buffer * view)436 _IsCContiguous(const Py_buffer *view)
437 {
438     Py_ssize_t sd, dim;
439     int i;
440 
441     /* 1) len = product(shape) * itemsize
442        2) itemsize > 0
443        3) len = 0 <==> exists i: shape[i] = 0 */
444     if (view->len == 0) return 1;
445     if (view->strides == NULL) return 1; /* C-contiguous by definition */
446 
447     /* strides != NULL implies both of these */
448     assert(view->ndim > 0);
449     assert(view->shape != NULL);
450 
451     sd = view->itemsize;
452     for (i=view->ndim-1; i>=0; i--) {
453         dim = view->shape[i];
454         if (dim > 1 && view->strides[i] != sd) {
455             return 0;
456         }
457         sd *= dim;
458     }
459     return 1;
460 }
461 
462 int
PyBuffer_IsContiguous(const Py_buffer * view,char order)463 PyBuffer_IsContiguous(const Py_buffer *view, char order)
464 {
465 
466     if (view->suboffsets != NULL) return 0;
467 
468     if (order == 'C')
469         return _IsCContiguous(view);
470     else if (order == 'F')
471         return _IsFortranContiguous(view);
472     else if (order == 'A')
473         return (_IsCContiguous(view) || _IsFortranContiguous(view));
474     return 0;
475 }
476 
477 
478 void*
PyBuffer_GetPointer(const Py_buffer * view,const Py_ssize_t * indices)479 PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
480 {
481     char* pointer;
482     int i;
483     pointer = (char *)view->buf;
484     for (i = 0; i < view->ndim; i++) {
485         pointer += view->strides[i]*indices[i];
486         if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
487             pointer = *((char**)pointer) + view->suboffsets[i];
488         }
489     }
490     return (void*)pointer;
491 }
492 
493 
494 void
_Py_add_one_to_index_F(int nd,Py_ssize_t * index,const Py_ssize_t * shape)495 _Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
496 {
497     int k;
498 
499     for (k=0; k<nd; k++) {
500         if (index[k] < shape[k]-1) {
501             index[k]++;
502             break;
503         }
504         else {
505             index[k] = 0;
506         }
507     }
508 }
509 
510 void
_Py_add_one_to_index_C(int nd,Py_ssize_t * index,const Py_ssize_t * shape)511 _Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
512 {
513     int k;
514 
515     for (k=nd-1; k>=0; k--) {
516         if (index[k] < shape[k]-1) {
517             index[k]++;
518             break;
519         }
520         else {
521             index[k] = 0;
522         }
523     }
524 }
525 
526 Py_ssize_t
PyBuffer_SizeFromFormat(const char * format)527 PyBuffer_SizeFromFormat(const char *format)
528 {
529     PyObject *structmodule = NULL;
530     PyObject *calcsize = NULL;
531     PyObject *res = NULL;
532     PyObject *fmt = NULL;
533     Py_ssize_t itemsize = -1;
534 
535     structmodule = PyImport_ImportModule("struct");
536     if (structmodule == NULL) {
537         return itemsize;
538     }
539 
540     calcsize = PyObject_GetAttrString(structmodule, "calcsize");
541     if (calcsize == NULL) {
542         goto done;
543     }
544 
545     fmt = PyUnicode_FromString(format);
546     if (fmt == NULL) {
547         goto done;
548     }
549 
550     res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
551     if (res == NULL) {
552         goto done;
553     }
554 
555     itemsize = PyLong_AsSsize_t(res);
556     if (itemsize < 0) {
557         goto done;
558     }
559 
560 done:
561     Py_DECREF(structmodule);
562     Py_XDECREF(calcsize);
563     Py_XDECREF(fmt);
564     Py_XDECREF(res);
565     return itemsize;
566 }
567 
568 int
PyBuffer_FromContiguous(const Py_buffer * view,const void * buf,Py_ssize_t len,char fort)569 PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
570 {
571     int k;
572     void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
573     Py_ssize_t *indices, elements;
574     char *ptr;
575     const char *src;
576 
577     if (len > view->len) {
578         len = view->len;
579     }
580 
581     if (PyBuffer_IsContiguous(view, fort)) {
582         /* simplest copy is all that is needed */
583         memcpy(view->buf, buf, len);
584         return 0;
585     }
586 
587     /* Otherwise a more elaborate scheme is needed */
588 
589     /* view->ndim <= 64 */
590     indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
591     if (indices == NULL) {
592         PyErr_NoMemory();
593         return -1;
594     }
595     for (k=0; k<view->ndim;k++) {
596         indices[k] = 0;
597     }
598 
599     if (fort == 'F') {
600         addone = _Py_add_one_to_index_F;
601     }
602     else {
603         addone = _Py_add_one_to_index_C;
604     }
605     src = buf;
606     /* XXX : This is not going to be the fastest code in the world
607              several optimizations are possible.
608      */
609     elements = len / view->itemsize;
610     while (elements--) {
611         ptr = PyBuffer_GetPointer(view, indices);
612         memcpy(ptr, src, view->itemsize);
613         src += view->itemsize;
614         addone(view->ndim, indices, view->shape);
615     }
616 
617     PyMem_Free(indices);
618     return 0;
619 }
620 
PyObject_CopyData(PyObject * dest,PyObject * src)621 int PyObject_CopyData(PyObject *dest, PyObject *src)
622 {
623     Py_buffer view_dest, view_src;
624     int k;
625     Py_ssize_t *indices, elements;
626     char *dptr, *sptr;
627 
628     if (!PyObject_CheckBuffer(dest) ||
629         !PyObject_CheckBuffer(src)) {
630         PyErr_SetString(PyExc_TypeError,
631                         "both destination and source must be "\
632                         "bytes-like objects");
633         return -1;
634     }
635 
636     if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
637     if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
638         PyBuffer_Release(&view_dest);
639         return -1;
640     }
641 
642     if (view_dest.len < view_src.len) {
643         PyErr_SetString(PyExc_BufferError,
644                         "destination is too small to receive data from source");
645         PyBuffer_Release(&view_dest);
646         PyBuffer_Release(&view_src);
647         return -1;
648     }
649 
650     if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
651          PyBuffer_IsContiguous(&view_src, 'C')) ||
652         (PyBuffer_IsContiguous(&view_dest, 'F') &&
653          PyBuffer_IsContiguous(&view_src, 'F'))) {
654         /* simplest copy is all that is needed */
655         memcpy(view_dest.buf, view_src.buf, view_src.len);
656         PyBuffer_Release(&view_dest);
657         PyBuffer_Release(&view_src);
658         return 0;
659     }
660 
661     /* Otherwise a more elaborate copy scheme is needed */
662 
663     /* XXX(nnorwitz): need to check for overflow! */
664     indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
665     if (indices == NULL) {
666         PyErr_NoMemory();
667         PyBuffer_Release(&view_dest);
668         PyBuffer_Release(&view_src);
669         return -1;
670     }
671     for (k=0; k<view_src.ndim;k++) {
672         indices[k] = 0;
673     }
674     elements = 1;
675     for (k=0; k<view_src.ndim; k++) {
676         /* XXX(nnorwitz): can this overflow? */
677         elements *= view_src.shape[k];
678     }
679     while (elements--) {
680         _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
681         dptr = PyBuffer_GetPointer(&view_dest, indices);
682         sptr = PyBuffer_GetPointer(&view_src, indices);
683         memcpy(dptr, sptr, view_src.itemsize);
684     }
685     PyMem_Free(indices);
686     PyBuffer_Release(&view_dest);
687     PyBuffer_Release(&view_src);
688     return 0;
689 }
690 
691 void
PyBuffer_FillContiguousStrides(int nd,Py_ssize_t * shape,Py_ssize_t * strides,int itemsize,char fort)692 PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
693                                Py_ssize_t *strides, int itemsize,
694                                char fort)
695 {
696     int k;
697     Py_ssize_t sd;
698 
699     sd = itemsize;
700     if (fort == 'F') {
701         for (k=0; k<nd; k++) {
702             strides[k] = sd;
703             sd *= shape[k];
704         }
705     }
706     else {
707         for (k=nd-1; k>=0; k--) {
708             strides[k] = sd;
709             sd *= shape[k];
710         }
711     }
712     return;
713 }
714 
715 int
PyBuffer_FillInfo(Py_buffer * view,PyObject * obj,void * buf,Py_ssize_t len,int readonly,int flags)716 PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
717                   int readonly, int flags)
718 {
719     if (view == NULL) {
720         PyErr_SetString(PyExc_BufferError,
721                         "PyBuffer_FillInfo: view==NULL argument is obsolete");
722         return -1;
723     }
724 
725     if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
726         (readonly == 1)) {
727         PyErr_SetString(PyExc_BufferError,
728                         "Object is not writable.");
729         return -1;
730     }
731 
732     view->obj = obj;
733     if (obj)
734         Py_INCREF(obj);
735     view->buf = buf;
736     view->len = len;
737     view->readonly = readonly;
738     view->itemsize = 1;
739     view->format = NULL;
740     if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
741         view->format = "B";
742     view->ndim = 1;
743     view->shape = NULL;
744     if ((flags & PyBUF_ND) == PyBUF_ND)
745         view->shape = &(view->len);
746     view->strides = NULL;
747     if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
748         view->strides = &(view->itemsize);
749     view->suboffsets = NULL;
750     view->internal = NULL;
751     return 0;
752 }
753 
754 void
PyBuffer_Release(Py_buffer * view)755 PyBuffer_Release(Py_buffer *view)
756 {
757     PyObject *obj = view->obj;
758     PyBufferProcs *pb;
759     if (obj == NULL)
760         return;
761     pb = Py_TYPE(obj)->tp_as_buffer;
762     if (pb && pb->bf_releasebuffer) {
763         pb->bf_releasebuffer(obj, view);
764     }
765     view->obj = NULL;
766     Py_DECREF(obj);
767 }
768 
769 PyObject *
PyObject_Format(PyObject * obj,PyObject * format_spec)770 PyObject_Format(PyObject *obj, PyObject *format_spec)
771 {
772     PyObject *meth;
773     PyObject *empty = NULL;
774     PyObject *result = NULL;
775 
776     if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
777         PyErr_Format(PyExc_SystemError,
778                      "Format specifier must be a string, not %.200s",
779                      Py_TYPE(format_spec)->tp_name);
780         return NULL;
781     }
782 
783     /* Fast path for common types. */
784     if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
785         if (PyUnicode_CheckExact(obj)) {
786             Py_INCREF(obj);
787             return obj;
788         }
789         if (PyLong_CheckExact(obj)) {
790             return PyObject_Str(obj);
791         }
792     }
793 
794     /* If no format_spec is provided, use an empty string */
795     if (format_spec == NULL) {
796         empty = PyUnicode_New(0, 0);
797         format_spec = empty;
798     }
799 
800     /* Find the (unbound!) __format__ method */
801     meth = _PyObject_LookupSpecial(obj, &_Py_ID(__format__));
802     if (meth == NULL) {
803         PyThreadState *tstate = _PyThreadState_GET();
804         if (!_PyErr_Occurred(tstate)) {
805             _PyErr_Format(tstate, PyExc_TypeError,
806                           "Type %.100s doesn't define __format__",
807                           Py_TYPE(obj)->tp_name);
808         }
809         goto done;
810     }
811 
812     /* And call it. */
813     result = PyObject_CallOneArg(meth, format_spec);
814     Py_DECREF(meth);
815 
816     if (result && !PyUnicode_Check(result)) {
817         PyErr_Format(PyExc_TypeError,
818                      "__format__ must return a str, not %.200s",
819                      Py_TYPE(result)->tp_name);
820         Py_DECREF(result);
821         result = NULL;
822         goto done;
823     }
824 
825 done:
826     Py_XDECREF(empty);
827     return result;
828 }
829 /* Operations on numbers */
830 
831 int
PyNumber_Check(PyObject * o)832 PyNumber_Check(PyObject *o)
833 {
834     if (o == NULL)
835         return 0;
836     PyNumberMethods *nb = Py_TYPE(o)->tp_as_number;
837     return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o));
838 }
839 
840 /* Binary operators */
841 
842 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
843 #define NB_BINOP(nb_methods, slot) \
844         (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
845 #define NB_TERNOP(nb_methods, slot) \
846         (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
847 
848 /*
849   Calling scheme used for binary operations:
850 
851   Order operations are tried until either a valid result or error:
852     w.op(v,w)[*], v.op(v,w), w.op(v,w)
853 
854   [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
855       Py_TYPE(v)
856  */
857 
858 static PyObject *
binary_op1(PyObject * v,PyObject * w,const int op_slot,const char * op_name)859 binary_op1(PyObject *v, PyObject *w, const int op_slot
860 #ifndef NDEBUG
861            , const char *op_name
862 #endif
863            )
864 {
865     binaryfunc slotv;
866     if (Py_TYPE(v)->tp_as_number != NULL) {
867         slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
868     }
869     else {
870         slotv = NULL;
871     }
872 
873     binaryfunc slotw;
874     if (!Py_IS_TYPE(w, Py_TYPE(v)) && Py_TYPE(w)->tp_as_number != NULL) {
875         slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
876         if (slotw == slotv) {
877             slotw = NULL;
878         }
879     }
880     else {
881         slotw = NULL;
882     }
883 
884     if (slotv) {
885         PyObject *x;
886         if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
887             x = slotw(v, w);
888             if (x != Py_NotImplemented)
889                 return x;
890             Py_DECREF(x); /* can't do it */
891             slotw = NULL;
892         }
893         x = slotv(v, w);
894         assert(_Py_CheckSlotResult(v, op_name, x != NULL));
895         if (x != Py_NotImplemented) {
896             return x;
897         }
898         Py_DECREF(x); /* can't do it */
899     }
900     if (slotw) {
901         PyObject *x = slotw(v, w);
902         assert(_Py_CheckSlotResult(w, op_name, x != NULL));
903         if (x != Py_NotImplemented) {
904             return x;
905         }
906         Py_DECREF(x); /* can't do it */
907     }
908     Py_RETURN_NOTIMPLEMENTED;
909 }
910 
911 #ifdef NDEBUG
912 #  define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot)
913 #else
914 #  define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot, op_name)
915 #endif
916 
917 static PyObject *
binop_type_error(PyObject * v,PyObject * w,const char * op_name)918 binop_type_error(PyObject *v, PyObject *w, const char *op_name)
919 {
920     PyErr_Format(PyExc_TypeError,
921                  "unsupported operand type(s) for %.100s: "
922                  "'%.100s' and '%.100s'",
923                  op_name,
924                  Py_TYPE(v)->tp_name,
925                  Py_TYPE(w)->tp_name);
926     return NULL;
927 }
928 
929 static PyObject *
binary_op(PyObject * v,PyObject * w,const int op_slot,const char * op_name)930 binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
931 {
932     PyObject *result = BINARY_OP1(v, w, op_slot, op_name);
933     if (result == Py_NotImplemented) {
934         Py_DECREF(result);
935 
936         if (op_slot == NB_SLOT(nb_rshift) &&
937             PyCFunction_CheckExact(v) &&
938             strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
939         {
940             PyErr_Format(PyExc_TypeError,
941                 "unsupported operand type(s) for %.100s: "
942                 "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
943                 "file=<output_stream>)\"?",
944                 op_name,
945                 Py_TYPE(v)->tp_name,
946                 Py_TYPE(w)->tp_name);
947             return NULL;
948         }
949         return binop_type_error(v, w, op_name);
950     }
951     return result;
952 }
953 
954 
955 /*
956   Calling scheme used for ternary operations:
957 
958   Order operations are tried until either a valid result or error:
959     v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
960  */
961 
962 static PyObject *
ternary_op(PyObject * v,PyObject * w,PyObject * z,const int op_slot,const char * op_name)963 ternary_op(PyObject *v,
964            PyObject *w,
965            PyObject *z,
966            const int op_slot,
967            const char *op_name
968            )
969 {
970     PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
971     PyNumberMethods *mw = Py_TYPE(w)->tp_as_number;
972 
973     ternaryfunc slotv;
974     if (mv != NULL) {
975         slotv = NB_TERNOP(mv, op_slot);
976     }
977     else {
978         slotv = NULL;
979     }
980 
981     ternaryfunc slotw;
982     if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
983         slotw = NB_TERNOP(mw, op_slot);
984         if (slotw == slotv) {
985             slotw = NULL;
986         }
987     }
988     else {
989         slotw = NULL;
990     }
991 
992     if (slotv) {
993         PyObject *x;
994         if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
995             x = slotw(v, w, z);
996             if (x != Py_NotImplemented) {
997                 return x;
998             }
999             Py_DECREF(x); /* can't do it */
1000             slotw = NULL;
1001         }
1002         x = slotv(v, w, z);
1003         assert(_Py_CheckSlotResult(v, op_name, x != NULL));
1004         if (x != Py_NotImplemented) {
1005             return x;
1006         }
1007         Py_DECREF(x); /* can't do it */
1008     }
1009     if (slotw) {
1010         PyObject *x = slotw(v, w, z);
1011         assert(_Py_CheckSlotResult(w, op_name, x != NULL));
1012         if (x != Py_NotImplemented) {
1013             return x;
1014         }
1015         Py_DECREF(x); /* can't do it */
1016     }
1017 
1018     PyNumberMethods *mz = Py_TYPE(z)->tp_as_number;
1019     if (mz != NULL) {
1020         ternaryfunc slotz = NB_TERNOP(mz, op_slot);
1021         if (slotz == slotv || slotz == slotw) {
1022             slotz = NULL;
1023         }
1024         if (slotz) {
1025             PyObject *x = slotz(v, w, z);
1026             assert(_Py_CheckSlotResult(z, op_name, x != NULL));
1027             if (x != Py_NotImplemented) {
1028                 return x;
1029             }
1030             Py_DECREF(x); /* can't do it */
1031         }
1032     }
1033 
1034     if (z == Py_None) {
1035         PyErr_Format(
1036             PyExc_TypeError,
1037             "unsupported operand type(s) for %.100s: "
1038             "'%.100s' and '%.100s'",
1039             op_name,
1040             Py_TYPE(v)->tp_name,
1041             Py_TYPE(w)->tp_name);
1042     }
1043     else {
1044         PyErr_Format(
1045             PyExc_TypeError,
1046             "unsupported operand type(s) for %.100s: "
1047             "'%.100s', '%.100s', '%.100s'",
1048             op_name,
1049             Py_TYPE(v)->tp_name,
1050             Py_TYPE(w)->tp_name,
1051             Py_TYPE(z)->tp_name);
1052     }
1053     return NULL;
1054 }
1055 
1056 #define BINARY_FUNC(func, op, op_name) \
1057     PyObject * \
1058     func(PyObject *v, PyObject *w) { \
1059         return binary_op(v, w, NB_SLOT(op), op_name); \
1060     }
1061 
1062 BINARY_FUNC(PyNumber_Or, nb_or, "|")
1063 BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1064 BINARY_FUNC(PyNumber_And, nb_and, "&")
1065 BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1066 BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1067 BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
1068 BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
1069 
1070 PyObject *
PyNumber_Add(PyObject * v,PyObject * w)1071 PyNumber_Add(PyObject *v, PyObject *w)
1072 {
1073     PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_add), "+");
1074     if (result != Py_NotImplemented) {
1075         return result;
1076     }
1077     Py_DECREF(result);
1078 
1079     PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
1080     if (m && m->sq_concat) {
1081         result = (*m->sq_concat)(v, w);
1082         assert(_Py_CheckSlotResult(v, "+", result != NULL));
1083         return result;
1084     }
1085 
1086     return binop_type_error(v, w, "+");
1087 }
1088 
1089 static PyObject *
sequence_repeat(ssizeargfunc repeatfunc,PyObject * seq,PyObject * n)1090 sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
1091 {
1092     Py_ssize_t count;
1093     if (_PyIndex_Check(n)) {
1094         count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1095         if (count == -1 && PyErr_Occurred()) {
1096             return NULL;
1097         }
1098     }
1099     else {
1100         return type_error("can't multiply sequence by "
1101                           "non-int of type '%.200s'", n);
1102     }
1103     PyObject *res = (*repeatfunc)(seq, count);
1104     assert(_Py_CheckSlotResult(seq, "*", res != NULL));
1105     return res;
1106 }
1107 
1108 PyObject *
PyNumber_Multiply(PyObject * v,PyObject * w)1109 PyNumber_Multiply(PyObject *v, PyObject *w)
1110 {
1111     PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_multiply), "*");
1112     if (result == Py_NotImplemented) {
1113         PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1114         PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
1115         Py_DECREF(result);
1116         if  (mv && mv->sq_repeat) {
1117             return sequence_repeat(mv->sq_repeat, v, w);
1118         }
1119         else if (mw && mw->sq_repeat) {
1120             return sequence_repeat(mw->sq_repeat, w, v);
1121         }
1122         result = binop_type_error(v, w, "*");
1123     }
1124     return result;
1125 }
1126 
1127 PyObject *
PyNumber_MatrixMultiply(PyObject * v,PyObject * w)1128 PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
1129 {
1130     return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
1131 }
1132 
1133 PyObject *
PyNumber_FloorDivide(PyObject * v,PyObject * w)1134 PyNumber_FloorDivide(PyObject *v, PyObject *w)
1135 {
1136     return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
1137 }
1138 
1139 PyObject *
PyNumber_TrueDivide(PyObject * v,PyObject * w)1140 PyNumber_TrueDivide(PyObject *v, PyObject *w)
1141 {
1142     return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
1143 }
1144 
1145 PyObject *
PyNumber_Remainder(PyObject * v,PyObject * w)1146 PyNumber_Remainder(PyObject *v, PyObject *w)
1147 {
1148     return binary_op(v, w, NB_SLOT(nb_remainder), "%");
1149 }
1150 
1151 PyObject *
PyNumber_Power(PyObject * v,PyObject * w,PyObject * z)1152 PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
1153 {
1154     return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
1155 }
1156 
1157 PyObject *
_PyNumber_PowerNoMod(PyObject * lhs,PyObject * rhs)1158 _PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs)
1159 {
1160     return PyNumber_Power(lhs, rhs, Py_None);
1161 }
1162 
1163 /* Binary in-place operators */
1164 
1165 /* The in-place operators are defined to fall back to the 'normal',
1166    non in-place operations, if the in-place methods are not in place.
1167 
1168    - If the left hand object has the appropriate struct members, and
1169      they are filled, call the appropriate function and return the
1170      result.  No coercion is done on the arguments; the left-hand object
1171      is the one the operation is performed on, and it's up to the
1172      function to deal with the right-hand object.
1173 
1174    - Otherwise, in-place modification is not supported. Handle it exactly as
1175      a non in-place operation of the same kind.
1176 
1177    */
1178 
1179 static PyObject *
binary_iop1(PyObject * v,PyObject * w,const int iop_slot,const int op_slot,const char * op_name)1180 binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot
1181 #ifndef NDEBUG
1182             , const char *op_name
1183 #endif
1184             )
1185 {
1186     PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1187     if (mv != NULL) {
1188         binaryfunc slot = NB_BINOP(mv, iop_slot);
1189         if (slot) {
1190             PyObject *x = (slot)(v, w);
1191             assert(_Py_CheckSlotResult(v, op_name, x != NULL));
1192             if (x != Py_NotImplemented) {
1193                 return x;
1194             }
1195             Py_DECREF(x);
1196         }
1197     }
1198 #ifdef NDEBUG
1199     return binary_op1(v, w, op_slot);
1200 #else
1201     return binary_op1(v, w, op_slot, op_name);
1202 #endif
1203 }
1204 
1205 #ifdef NDEBUG
1206 #  define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot)
1207 #else
1208 #  define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot, op_name)
1209 #endif
1210 
1211 static PyObject *
binary_iop(PyObject * v,PyObject * w,const int iop_slot,const int op_slot,const char * op_name)1212 binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1213                 const char *op_name)
1214 {
1215     PyObject *result = BINARY_IOP1(v, w, iop_slot, op_slot, op_name);
1216     if (result == Py_NotImplemented) {
1217         Py_DECREF(result);
1218         return binop_type_error(v, w, op_name);
1219     }
1220     return result;
1221 }
1222 
1223 static PyObject *
ternary_iop(PyObject * v,PyObject * w,PyObject * z,const int iop_slot,const int op_slot,const char * op_name)1224 ternary_iop(PyObject *v, PyObject *w, PyObject *z, const int iop_slot, const int op_slot,
1225                 const char *op_name)
1226 {
1227     PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1228     if (mv != NULL) {
1229         ternaryfunc slot = NB_TERNOP(mv, iop_slot);
1230         if (slot) {
1231             PyObject *x = (slot)(v, w, z);
1232             if (x != Py_NotImplemented) {
1233                 return x;
1234             }
1235             Py_DECREF(x);
1236         }
1237     }
1238     return ternary_op(v, w, z, op_slot, op_name);
1239 }
1240 
1241 #define INPLACE_BINOP(func, iop, op, op_name) \
1242     PyObject * \
1243     func(PyObject *v, PyObject *w) { \
1244         return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1245     }
1246 
1247 INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1248 INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1249 INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1250 INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1251 INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1252 INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1253 INPLACE_BINOP(PyNumber_InPlaceMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
1254 INPLACE_BINOP(PyNumber_InPlaceFloorDivide, nb_inplace_floor_divide, nb_floor_divide, "//=")
1255 INPLACE_BINOP(PyNumber_InPlaceTrueDivide, nb_inplace_true_divide, nb_true_divide,  "/=")
1256 INPLACE_BINOP(PyNumber_InPlaceRemainder, nb_inplace_remainder, nb_remainder, "%=")
1257 
1258 PyObject *
PyNumber_InPlaceAdd(PyObject * v,PyObject * w)1259 PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1260 {
1261     PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_add),
1262                                    NB_SLOT(nb_add), "+=");
1263     if (result == Py_NotImplemented) {
1264         PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
1265         Py_DECREF(result);
1266         if (m != NULL) {
1267             binaryfunc func = m->sq_inplace_concat;
1268             if (func == NULL)
1269                 func = m->sq_concat;
1270             if (func != NULL) {
1271                 result = func(v, w);
1272                 assert(_Py_CheckSlotResult(v, "+=", result != NULL));
1273                 return result;
1274             }
1275         }
1276         result = binop_type_error(v, w, "+=");
1277     }
1278     return result;
1279 }
1280 
1281 PyObject *
PyNumber_InPlaceMultiply(PyObject * v,PyObject * w)1282 PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1283 {
1284     PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_multiply),
1285                                    NB_SLOT(nb_multiply), "*=");
1286     if (result == Py_NotImplemented) {
1287         ssizeargfunc f = NULL;
1288         PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1289         PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
1290         Py_DECREF(result);
1291         if (mv != NULL) {
1292             f = mv->sq_inplace_repeat;
1293             if (f == NULL)
1294                 f = mv->sq_repeat;
1295             if (f != NULL)
1296                 return sequence_repeat(f, v, w);
1297         }
1298         else if (mw != NULL) {
1299             /* Note that the right hand operand should not be
1300              * mutated in this case so sq_inplace_repeat is not
1301              * used. */
1302             if (mw->sq_repeat)
1303                 return sequence_repeat(mw->sq_repeat, w, v);
1304         }
1305         result = binop_type_error(v, w, "*=");
1306     }
1307     return result;
1308 }
1309 
1310 PyObject *
PyNumber_InPlacePower(PyObject * v,PyObject * w,PyObject * z)1311 PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1312 {
1313     return ternary_iop(v, w, z, NB_SLOT(nb_inplace_power),
1314                                 NB_SLOT(nb_power), "**=");
1315 }
1316 
1317 PyObject *
_PyNumber_InPlacePowerNoMod(PyObject * lhs,PyObject * rhs)1318 _PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs)
1319 {
1320     return PyNumber_InPlacePower(lhs, rhs, Py_None);
1321 }
1322 
1323 
1324 /* Unary operators and functions */
1325 
1326 PyObject *
PyNumber_Negative(PyObject * o)1327 PyNumber_Negative(PyObject *o)
1328 {
1329     if (o == NULL) {
1330         return null_error();
1331     }
1332 
1333     PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1334     if (m && m->nb_negative) {
1335         PyObject *res = (*m->nb_negative)(o);
1336         assert(_Py_CheckSlotResult(o, "__neg__", res != NULL));
1337         return res;
1338     }
1339 
1340     return type_error("bad operand type for unary -: '%.200s'", o);
1341 }
1342 
1343 PyObject *
PyNumber_Positive(PyObject * o)1344 PyNumber_Positive(PyObject *o)
1345 {
1346     if (o == NULL) {
1347         return null_error();
1348     }
1349 
1350     PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1351     if (m && m->nb_positive) {
1352         PyObject *res = (*m->nb_positive)(o);
1353         assert(_Py_CheckSlotResult(o, "__pos__", res != NULL));
1354         return res;
1355     }
1356 
1357     return type_error("bad operand type for unary +: '%.200s'", o);
1358 }
1359 
1360 PyObject *
PyNumber_Invert(PyObject * o)1361 PyNumber_Invert(PyObject *o)
1362 {
1363     if (o == NULL) {
1364         return null_error();
1365     }
1366 
1367     PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1368     if (m && m->nb_invert) {
1369         PyObject *res = (*m->nb_invert)(o);
1370         assert(_Py_CheckSlotResult(o, "__invert__", res != NULL));
1371         return res;
1372     }
1373 
1374     return type_error("bad operand type for unary ~: '%.200s'", o);
1375 }
1376 
1377 PyObject *
PyNumber_Absolute(PyObject * o)1378 PyNumber_Absolute(PyObject *o)
1379 {
1380     if (o == NULL) {
1381         return null_error();
1382     }
1383 
1384     PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1385     if (m && m->nb_absolute) {
1386         PyObject *res = m->nb_absolute(o);
1387         assert(_Py_CheckSlotResult(o, "__abs__", res != NULL));
1388         return res;
1389     }
1390 
1391     return type_error("bad operand type for abs(): '%.200s'", o);
1392 }
1393 
1394 
1395 int
PyIndex_Check(PyObject * obj)1396 PyIndex_Check(PyObject *obj)
1397 {
1398     return _PyIndex_Check(obj);
1399 }
1400 
1401 
1402 /* Return a Python int from the object item.
1403    Can return an instance of int subclass.
1404    Raise TypeError if the result is not an int
1405    or if the object cannot be interpreted as an index.
1406 */
1407 PyObject *
_PyNumber_Index(PyObject * item)1408 _PyNumber_Index(PyObject *item)
1409 {
1410     if (item == NULL) {
1411         return null_error();
1412     }
1413 
1414     if (PyLong_Check(item)) {
1415         Py_INCREF(item);
1416         return item;
1417     }
1418     if (!_PyIndex_Check(item)) {
1419         PyErr_Format(PyExc_TypeError,
1420                      "'%.200s' object cannot be interpreted "
1421                      "as an integer", Py_TYPE(item)->tp_name);
1422         return NULL;
1423     }
1424 
1425     PyObject *result = Py_TYPE(item)->tp_as_number->nb_index(item);
1426     assert(_Py_CheckSlotResult(item, "__index__", result != NULL));
1427     if (!result || PyLong_CheckExact(result)) {
1428         return result;
1429     }
1430 
1431     if (!PyLong_Check(result)) {
1432         PyErr_Format(PyExc_TypeError,
1433                      "__index__ returned non-int (type %.200s)",
1434                      Py_TYPE(result)->tp_name);
1435         Py_DECREF(result);
1436         return NULL;
1437     }
1438     /* Issue #17576: warn if 'result' not of exact type int. */
1439     if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1440             "__index__ returned non-int (type %.200s).  "
1441             "The ability to return an instance of a strict subclass of int "
1442             "is deprecated, and may be removed in a future version of Python.",
1443             Py_TYPE(result)->tp_name)) {
1444         Py_DECREF(result);
1445         return NULL;
1446     }
1447     return result;
1448 }
1449 
1450 /* Return an exact Python int from the object item.
1451    Raise TypeError if the result is not an int
1452    or if the object cannot be interpreted as an index.
1453 */
1454 PyObject *
PyNumber_Index(PyObject * item)1455 PyNumber_Index(PyObject *item)
1456 {
1457     PyObject *result = _PyNumber_Index(item);
1458     if (result != NULL && !PyLong_CheckExact(result)) {
1459         Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1460     }
1461     return result;
1462 }
1463 
1464 /* Return an error on Overflow only if err is not NULL*/
1465 
1466 Py_ssize_t
PyNumber_AsSsize_t(PyObject * item,PyObject * err)1467 PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1468 {
1469     Py_ssize_t result;
1470     PyObject *runerr;
1471     PyObject *value = _PyNumber_Index(item);
1472     if (value == NULL)
1473         return -1;
1474 
1475     /* We're done if PyLong_AsSsize_t() returns without error. */
1476     result = PyLong_AsSsize_t(value);
1477     if (result != -1)
1478         goto finish;
1479 
1480     PyThreadState *tstate = _PyThreadState_GET();
1481     runerr = _PyErr_Occurred(tstate);
1482     if (!runerr) {
1483         goto finish;
1484     }
1485 
1486     /* Error handling code -- only manage OverflowError differently */
1487     if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
1488         goto finish;
1489     }
1490     _PyErr_Clear(tstate);
1491 
1492     /* If no error-handling desired then the default clipping
1493        is sufficient. */
1494     if (!err) {
1495         assert(PyLong_Check(value));
1496         /* Whether or not it is less than or equal to
1497            zero is determined by the sign of ob_size
1498         */
1499         if (_PyLong_Sign(value) < 0)
1500             result = PY_SSIZE_T_MIN;
1501         else
1502             result = PY_SSIZE_T_MAX;
1503     }
1504     else {
1505         /* Otherwise replace the error with caller's error object. */
1506         _PyErr_Format(tstate, err,
1507                       "cannot fit '%.200s' into an index-sized integer",
1508                       Py_TYPE(item)->tp_name);
1509     }
1510 
1511  finish:
1512     Py_DECREF(value);
1513     return result;
1514 }
1515 
1516 
1517 PyObject *
PyNumber_Long(PyObject * o)1518 PyNumber_Long(PyObject *o)
1519 {
1520     PyObject *result;
1521     PyNumberMethods *m;
1522     PyObject *trunc_func;
1523     Py_buffer view;
1524 
1525     if (o == NULL) {
1526         return null_error();
1527     }
1528 
1529     if (PyLong_CheckExact(o)) {
1530         Py_INCREF(o);
1531         return o;
1532     }
1533     m = Py_TYPE(o)->tp_as_number;
1534     if (m && m->nb_int) { /* This should include subclasses of int */
1535         /* Convert using the nb_int slot, which should return something
1536            of exact type int. */
1537         result = m->nb_int(o);
1538         assert(_Py_CheckSlotResult(o, "__int__", result != NULL));
1539         if (!result || PyLong_CheckExact(result)) {
1540             return result;
1541         }
1542 
1543         if (!PyLong_Check(result)) {
1544             PyErr_Format(PyExc_TypeError,
1545                          "__int__ returned non-int (type %.200s)",
1546                          Py_TYPE(result)->tp_name);
1547             Py_DECREF(result);
1548             return NULL;
1549         }
1550         /* Issue #17576: warn if 'result' not of exact type int. */
1551         if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1552                 "__int__ returned non-int (type %.200s).  "
1553                 "The ability to return an instance of a strict subclass of int "
1554                 "is deprecated, and may be removed in a future version of Python.",
1555                 Py_TYPE(result)->tp_name)) {
1556             Py_DECREF(result);
1557             return NULL;
1558         }
1559         Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1560         return result;
1561     }
1562     if (m && m->nb_index) {
1563         return PyNumber_Index(o);
1564     }
1565     trunc_func = _PyObject_LookupSpecial(o, &_Py_ID(__trunc__));
1566     if (trunc_func) {
1567         if (PyErr_WarnEx(PyExc_DeprecationWarning,
1568                 "The delegation of int() to __trunc__ is deprecated.", 1)) {
1569             Py_DECREF(trunc_func);
1570             return NULL;
1571         }
1572         result = _PyObject_CallNoArgs(trunc_func);
1573         Py_DECREF(trunc_func);
1574         if (result == NULL || PyLong_CheckExact(result)) {
1575             return result;
1576         }
1577         if (PyLong_Check(result)) {
1578             Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1579             return result;
1580         }
1581         /* __trunc__ is specified to return an Integral type,
1582            but int() needs to return an int. */
1583         if (!PyIndex_Check(result)) {
1584             PyErr_Format(
1585                 PyExc_TypeError,
1586                 "__trunc__ returned non-Integral (type %.200s)",
1587                 Py_TYPE(result)->tp_name);
1588             Py_DECREF(result);
1589             return NULL;
1590         }
1591         Py_SETREF(result, PyNumber_Index(result));
1592         return result;
1593     }
1594     if (PyErr_Occurred())
1595         return NULL;
1596 
1597     if (PyUnicode_Check(o))
1598         /* The below check is done in PyLong_FromUnicodeObject(). */
1599         return PyLong_FromUnicodeObject(o, 10);
1600 
1601     if (PyBytes_Check(o))
1602         /* need to do extra error checking that PyLong_FromString()
1603          * doesn't do.  In particular int('9\x005') must raise an
1604          * exception, not truncate at the null.
1605          */
1606         return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1607                                  PyBytes_GET_SIZE(o), 10);
1608 
1609     if (PyByteArray_Check(o))
1610         return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1611                                  PyByteArray_GET_SIZE(o), 10);
1612 
1613     if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
1614         PyObject *bytes;
1615 
1616         /* Copy to NUL-terminated buffer. */
1617         bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1618         if (bytes == NULL) {
1619             PyBuffer_Release(&view);
1620             return NULL;
1621         }
1622         result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1623                                    PyBytes_GET_SIZE(bytes), 10);
1624         Py_DECREF(bytes);
1625         PyBuffer_Release(&view);
1626         return result;
1627     }
1628 
1629     return type_error("int() argument must be a string, a bytes-like object "
1630                       "or a real number, not '%.200s'", o);
1631 }
1632 
1633 PyObject *
PyNumber_Float(PyObject * o)1634 PyNumber_Float(PyObject *o)
1635 {
1636     if (o == NULL) {
1637         return null_error();
1638     }
1639 
1640     if (PyFloat_CheckExact(o)) {
1641         return Py_NewRef(o);
1642     }
1643 
1644     PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1645     if (m && m->nb_float) { /* This should include subclasses of float */
1646         PyObject *res = m->nb_float(o);
1647         assert(_Py_CheckSlotResult(o, "__float__", res != NULL));
1648         if (!res || PyFloat_CheckExact(res)) {
1649             return res;
1650         }
1651 
1652         if (!PyFloat_Check(res)) {
1653             PyErr_Format(PyExc_TypeError,
1654                          "%.50s.__float__ returned non-float (type %.50s)",
1655                          Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
1656             Py_DECREF(res);
1657             return NULL;
1658         }
1659         /* Issue #26983: warn if 'res' not of exact type float. */
1660         if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1661                 "%.50s.__float__ returned non-float (type %.50s).  "
1662                 "The ability to return an instance of a strict subclass of float "
1663                 "is deprecated, and may be removed in a future version of Python.",
1664                 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
1665             Py_DECREF(res);
1666             return NULL;
1667         }
1668         double val = PyFloat_AS_DOUBLE(res);
1669         Py_DECREF(res);
1670         return PyFloat_FromDouble(val);
1671     }
1672 
1673     if (m && m->nb_index) {
1674         PyObject *res = _PyNumber_Index(o);
1675         if (!res) {
1676             return NULL;
1677         }
1678         double val = PyLong_AsDouble(res);
1679         Py_DECREF(res);
1680         if (val == -1.0 && PyErr_Occurred()) {
1681             return NULL;
1682         }
1683         return PyFloat_FromDouble(val);
1684     }
1685 
1686     /* A float subclass with nb_float == NULL */
1687     if (PyFloat_Check(o)) {
1688         return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
1689     }
1690     return PyFloat_FromString(o);
1691 }
1692 
1693 
1694 PyObject *
PyNumber_ToBase(PyObject * n,int base)1695 PyNumber_ToBase(PyObject *n, int base)
1696 {
1697     if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1698         PyErr_SetString(PyExc_SystemError,
1699                         "PyNumber_ToBase: base must be 2, 8, 10 or 16");
1700         return NULL;
1701     }
1702     PyObject *index = _PyNumber_Index(n);
1703     if (!index)
1704         return NULL;
1705     PyObject *res = _PyLong_Format(index, base);
1706     Py_DECREF(index);
1707     return res;
1708 }
1709 
1710 
1711 /* Operations on sequences */
1712 
1713 int
PySequence_Check(PyObject * s)1714 PySequence_Check(PyObject *s)
1715 {
1716     if (PyDict_Check(s))
1717         return 0;
1718     return Py_TYPE(s)->tp_as_sequence &&
1719         Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
1720 }
1721 
1722 Py_ssize_t
PySequence_Size(PyObject * s)1723 PySequence_Size(PyObject *s)
1724 {
1725     if (s == NULL) {
1726         null_error();
1727         return -1;
1728     }
1729 
1730     PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1731     if (m && m->sq_length) {
1732         Py_ssize_t len = m->sq_length(s);
1733         assert(_Py_CheckSlotResult(s, "__len__", len >= 0));
1734         return len;
1735     }
1736 
1737     if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
1738         type_error("%.200s is not a sequence", s);
1739         return -1;
1740     }
1741     type_error("object of type '%.200s' has no len()", s);
1742     return -1;
1743 }
1744 
1745 #undef PySequence_Length
1746 Py_ssize_t
PySequence_Length(PyObject * s)1747 PySequence_Length(PyObject *s)
1748 {
1749     return PySequence_Size(s);
1750 }
1751 #define PySequence_Length PySequence_Size
1752 
1753 PyObject *
PySequence_Concat(PyObject * s,PyObject * o)1754 PySequence_Concat(PyObject *s, PyObject *o)
1755 {
1756     if (s == NULL || o == NULL) {
1757         return null_error();
1758     }
1759 
1760     PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1761     if (m && m->sq_concat) {
1762         PyObject *res = m->sq_concat(s, o);
1763         assert(_Py_CheckSlotResult(s, "+", res != NULL));
1764         return res;
1765     }
1766 
1767     /* Instances of user classes defining an __add__() method only
1768        have an nb_add slot, not an sq_concat slot.      So we fall back
1769        to nb_add if both arguments appear to be sequences. */
1770     if (PySequence_Check(s) && PySequence_Check(o)) {
1771         PyObject *result = BINARY_OP1(s, o, NB_SLOT(nb_add), "+");
1772         if (result != Py_NotImplemented)
1773             return result;
1774         Py_DECREF(result);
1775     }
1776     return type_error("'%.200s' object can't be concatenated", s);
1777 }
1778 
1779 PyObject *
PySequence_Repeat(PyObject * o,Py_ssize_t count)1780 PySequence_Repeat(PyObject *o, Py_ssize_t count)
1781 {
1782     if (o == NULL) {
1783         return null_error();
1784     }
1785 
1786     PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
1787     if (m && m->sq_repeat) {
1788         PyObject *res = m->sq_repeat(o, count);
1789         assert(_Py_CheckSlotResult(o, "*", res != NULL));
1790         return res;
1791     }
1792 
1793     /* Instances of user classes defining a __mul__() method only
1794        have an nb_multiply slot, not an sq_repeat slot. so we fall back
1795        to nb_multiply if o appears to be a sequence. */
1796     if (PySequence_Check(o)) {
1797         PyObject *n, *result;
1798         n = PyLong_FromSsize_t(count);
1799         if (n == NULL)
1800             return NULL;
1801         result = BINARY_OP1(o, n, NB_SLOT(nb_multiply), "*");
1802         Py_DECREF(n);
1803         if (result != Py_NotImplemented)
1804             return result;
1805         Py_DECREF(result);
1806     }
1807     return type_error("'%.200s' object can't be repeated", o);
1808 }
1809 
1810 PyObject *
PySequence_InPlaceConcat(PyObject * s,PyObject * o)1811 PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1812 {
1813     if (s == NULL || o == NULL) {
1814         return null_error();
1815     }
1816 
1817     PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1818     if (m && m->sq_inplace_concat) {
1819         PyObject *res = m->sq_inplace_concat(s, o);
1820         assert(_Py_CheckSlotResult(s, "+=", res != NULL));
1821         return res;
1822     }
1823     if (m && m->sq_concat) {
1824         PyObject *res = m->sq_concat(s, o);
1825         assert(_Py_CheckSlotResult(s, "+", res != NULL));
1826         return res;
1827     }
1828 
1829     if (PySequence_Check(s) && PySequence_Check(o)) {
1830         PyObject *result = BINARY_IOP1(s, o, NB_SLOT(nb_inplace_add),
1831                                        NB_SLOT(nb_add), "+=");
1832         if (result != Py_NotImplemented)
1833             return result;
1834         Py_DECREF(result);
1835     }
1836     return type_error("'%.200s' object can't be concatenated", s);
1837 }
1838 
1839 PyObject *
PySequence_InPlaceRepeat(PyObject * o,Py_ssize_t count)1840 PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1841 {
1842     if (o == NULL) {
1843         return null_error();
1844     }
1845 
1846     PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
1847     if (m && m->sq_inplace_repeat) {
1848         PyObject *res = m->sq_inplace_repeat(o, count);
1849         assert(_Py_CheckSlotResult(o, "*=", res != NULL));
1850         return res;
1851     }
1852     if (m && m->sq_repeat) {
1853         PyObject *res = m->sq_repeat(o, count);
1854         assert(_Py_CheckSlotResult(o, "*", res != NULL));
1855         return res;
1856     }
1857 
1858     if (PySequence_Check(o)) {
1859         PyObject *n, *result;
1860         n = PyLong_FromSsize_t(count);
1861         if (n == NULL)
1862             return NULL;
1863         result = BINARY_IOP1(o, n, NB_SLOT(nb_inplace_multiply),
1864                              NB_SLOT(nb_multiply), "*=");
1865         Py_DECREF(n);
1866         if (result != Py_NotImplemented)
1867             return result;
1868         Py_DECREF(result);
1869     }
1870     return type_error("'%.200s' object can't be repeated", o);
1871 }
1872 
1873 PyObject *
PySequence_GetItem(PyObject * s,Py_ssize_t i)1874 PySequence_GetItem(PyObject *s, Py_ssize_t i)
1875 {
1876     if (s == NULL) {
1877         return null_error();
1878     }
1879 
1880     PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1881     if (m && m->sq_item) {
1882         if (i < 0) {
1883             if (m->sq_length) {
1884                 Py_ssize_t l = (*m->sq_length)(s);
1885                 assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1886                 if (l < 0) {
1887                     return NULL;
1888                 }
1889                 i += l;
1890             }
1891         }
1892         PyObject *res = m->sq_item(s, i);
1893         assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
1894         return res;
1895     }
1896 
1897     if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
1898         return type_error("%.200s is not a sequence", s);
1899     }
1900     return type_error("'%.200s' object does not support indexing", s);
1901 }
1902 
1903 PyObject *
PySequence_GetSlice(PyObject * s,Py_ssize_t i1,Py_ssize_t i2)1904 PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1905 {
1906     if (!s) {
1907         return null_error();
1908     }
1909 
1910     PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
1911     if (mp && mp->mp_subscript) {
1912         PyObject *slice = _PySlice_FromIndices(i1, i2);
1913         if (!slice) {
1914             return NULL;
1915         }
1916         PyObject *res = mp->mp_subscript(s, slice);
1917         assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
1918         Py_DECREF(slice);
1919         return res;
1920     }
1921 
1922     return type_error("'%.200s' object is unsliceable", s);
1923 }
1924 
1925 int
PySequence_SetItem(PyObject * s,Py_ssize_t i,PyObject * o)1926 PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
1927 {
1928     if (s == NULL) {
1929         null_error();
1930         return -1;
1931     }
1932 
1933     PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1934     if (m && m->sq_ass_item) {
1935         if (i < 0) {
1936             if (m->sq_length) {
1937                 Py_ssize_t l = (*m->sq_length)(s);
1938                 assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1939                 if (l < 0) {
1940                     return -1;
1941                 }
1942                 i += l;
1943             }
1944         }
1945         int res = m->sq_ass_item(s, i, o);
1946         assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
1947         return res;
1948     }
1949 
1950     if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
1951         type_error("%.200s is not a sequence", s);
1952         return -1;
1953     }
1954     type_error("'%.200s' object does not support item assignment", s);
1955     return -1;
1956 }
1957 
1958 int
PySequence_DelItem(PyObject * s,Py_ssize_t i)1959 PySequence_DelItem(PyObject *s, Py_ssize_t i)
1960 {
1961     if (s == NULL) {
1962         null_error();
1963         return -1;
1964     }
1965 
1966     PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1967     if (m && m->sq_ass_item) {
1968         if (i < 0) {
1969             if (m->sq_length) {
1970                 Py_ssize_t l = (*m->sq_length)(s);
1971                 assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1972                 if (l < 0) {
1973                     return -1;
1974                 }
1975                 i += l;
1976             }
1977         }
1978         int res = m->sq_ass_item(s, i, (PyObject *)NULL);
1979         assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
1980         return res;
1981     }
1982 
1983     if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
1984         type_error("%.200s is not a sequence", s);
1985         return -1;
1986     }
1987     type_error("'%.200s' object doesn't support item deletion", s);
1988     return -1;
1989 }
1990 
1991 int
PySequence_SetSlice(PyObject * s,Py_ssize_t i1,Py_ssize_t i2,PyObject * o)1992 PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
1993 {
1994     if (s == NULL) {
1995         null_error();
1996         return -1;
1997     }
1998 
1999     PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
2000     if (mp && mp->mp_ass_subscript) {
2001         PyObject *slice = _PySlice_FromIndices(i1, i2);
2002         if (!slice)
2003             return -1;
2004         int res = mp->mp_ass_subscript(s, slice, o);
2005         assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
2006         Py_DECREF(slice);
2007         return res;
2008     }
2009 
2010     type_error("'%.200s' object doesn't support slice assignment", s);
2011     return -1;
2012 }
2013 
2014 int
PySequence_DelSlice(PyObject * s,Py_ssize_t i1,Py_ssize_t i2)2015 PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
2016 {
2017     if (s == NULL) {
2018         null_error();
2019         return -1;
2020     }
2021 
2022     PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
2023     if (mp && mp->mp_ass_subscript) {
2024         PyObject *slice = _PySlice_FromIndices(i1, i2);
2025         if (!slice) {
2026             return -1;
2027         }
2028         int res = mp->mp_ass_subscript(s, slice, NULL);
2029         assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
2030         Py_DECREF(slice);
2031         return res;
2032     }
2033     type_error("'%.200s' object doesn't support slice deletion", s);
2034     return -1;
2035 }
2036 
2037 PyObject *
PySequence_Tuple(PyObject * v)2038 PySequence_Tuple(PyObject *v)
2039 {
2040     PyObject *it;  /* iter(v) */
2041     Py_ssize_t n;             /* guess for result tuple size */
2042     PyObject *result = NULL;
2043     Py_ssize_t j;
2044 
2045     if (v == NULL) {
2046         return null_error();
2047     }
2048 
2049     /* Special-case the common tuple and list cases, for efficiency. */
2050     if (PyTuple_CheckExact(v)) {
2051         /* Note that we can't know whether it's safe to return
2052            a tuple *subclass* instance as-is, hence the restriction
2053            to exact tuples here.  In contrast, lists always make
2054            a copy, so there's no need for exactness below. */
2055         Py_INCREF(v);
2056         return v;
2057     }
2058     if (PyList_CheckExact(v))
2059         return PyList_AsTuple(v);
2060 
2061     /* Get iterator. */
2062     it = PyObject_GetIter(v);
2063     if (it == NULL)
2064         return NULL;
2065 
2066     /* Guess result size and allocate space. */
2067     n = PyObject_LengthHint(v, 10);
2068     if (n == -1)
2069         goto Fail;
2070     result = PyTuple_New(n);
2071     if (result == NULL)
2072         goto Fail;
2073 
2074     /* Fill the tuple. */
2075     for (j = 0; ; ++j) {
2076         PyObject *item = PyIter_Next(it);
2077         if (item == NULL) {
2078             if (PyErr_Occurred())
2079                 goto Fail;
2080             break;
2081         }
2082         if (j >= n) {
2083             size_t newn = (size_t)n;
2084             /* The over-allocation strategy can grow a bit faster
2085                than for lists because unlike lists the
2086                over-allocation isn't permanent -- we reclaim
2087                the excess before the end of this routine.
2088                So, grow by ten and then add 25%.
2089             */
2090             newn += 10u;
2091             newn += newn >> 2;
2092             if (newn > PY_SSIZE_T_MAX) {
2093                 /* Check for overflow */
2094                 PyErr_NoMemory();
2095                 Py_DECREF(item);
2096                 goto Fail;
2097             }
2098             n = (Py_ssize_t)newn;
2099             if (_PyTuple_Resize(&result, n) != 0) {
2100                 Py_DECREF(item);
2101                 goto Fail;
2102             }
2103         }
2104         PyTuple_SET_ITEM(result, j, item);
2105     }
2106 
2107     /* Cut tuple back if guess was too large. */
2108     if (j < n &&
2109         _PyTuple_Resize(&result, j) != 0)
2110         goto Fail;
2111 
2112     Py_DECREF(it);
2113     return result;
2114 
2115 Fail:
2116     Py_XDECREF(result);
2117     Py_DECREF(it);
2118     return NULL;
2119 }
2120 
2121 PyObject *
PySequence_List(PyObject * v)2122 PySequence_List(PyObject *v)
2123 {
2124     PyObject *result;  /* result list */
2125     PyObject *rv;          /* return value from PyList_Extend */
2126 
2127     if (v == NULL) {
2128         return null_error();
2129     }
2130 
2131     result = PyList_New(0);
2132     if (result == NULL)
2133         return NULL;
2134 
2135     rv = _PyList_Extend((PyListObject *)result, v);
2136     if (rv == NULL) {
2137         Py_DECREF(result);
2138         return NULL;
2139     }
2140     Py_DECREF(rv);
2141     return result;
2142 }
2143 
2144 PyObject *
PySequence_Fast(PyObject * v,const char * m)2145 PySequence_Fast(PyObject *v, const char *m)
2146 {
2147     PyObject *it;
2148 
2149     if (v == NULL) {
2150         return null_error();
2151     }
2152 
2153     if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2154         Py_INCREF(v);
2155         return v;
2156     }
2157 
2158     it = PyObject_GetIter(v);
2159     if (it == NULL) {
2160         PyThreadState *tstate = _PyThreadState_GET();
2161         if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2162             _PyErr_SetString(tstate, PyExc_TypeError, m);
2163         }
2164         return NULL;
2165     }
2166 
2167     v = PySequence_List(it);
2168     Py_DECREF(it);
2169 
2170     return v;
2171 }
2172 
2173 /* Iterate over seq.  Result depends on the operation:
2174    PY_ITERSEARCH_COUNT:  -1 if error, else # of times obj appears in seq.
2175    PY_ITERSEARCH_INDEX:  0-based index of first occurrence of obj in seq;
2176     set ValueError and return -1 if none found; also return -1 on error.
2177    Py_ITERSEARCH_CONTAINS:  return 1 if obj in seq, else 0; -1 on error.
2178 */
2179 Py_ssize_t
_PySequence_IterSearch(PyObject * seq,PyObject * obj,int operation)2180 _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
2181 {
2182     Py_ssize_t n;
2183     int wrapped;  /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2184     PyObject *it;  /* iter(seq) */
2185 
2186     if (seq == NULL || obj == NULL) {
2187         null_error();
2188         return -1;
2189     }
2190 
2191     it = PyObject_GetIter(seq);
2192     if (it == NULL) {
2193         if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2194             type_error("argument of type '%.200s' is not iterable", seq);
2195         }
2196         return -1;
2197     }
2198 
2199     n = wrapped = 0;
2200     for (;;) {
2201         int cmp;
2202         PyObject *item = PyIter_Next(it);
2203         if (item == NULL) {
2204             if (PyErr_Occurred())
2205                 goto Fail;
2206             break;
2207         }
2208 
2209         cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
2210         Py_DECREF(item);
2211         if (cmp < 0)
2212             goto Fail;
2213         if (cmp > 0) {
2214             switch (operation) {
2215             case PY_ITERSEARCH_COUNT:
2216                 if (n == PY_SSIZE_T_MAX) {
2217                     PyErr_SetString(PyExc_OverflowError,
2218                            "count exceeds C integer size");
2219                     goto Fail;
2220                 }
2221                 ++n;
2222                 break;
2223 
2224             case PY_ITERSEARCH_INDEX:
2225                 if (wrapped) {
2226                     PyErr_SetString(PyExc_OverflowError,
2227                            "index exceeds C integer size");
2228                     goto Fail;
2229                 }
2230                 goto Done;
2231 
2232             case PY_ITERSEARCH_CONTAINS:
2233                 n = 1;
2234                 goto Done;
2235 
2236             default:
2237                 Py_UNREACHABLE();
2238             }
2239         }
2240 
2241         if (operation == PY_ITERSEARCH_INDEX) {
2242             if (n == PY_SSIZE_T_MAX)
2243                 wrapped = 1;
2244             ++n;
2245         }
2246     }
2247 
2248     if (operation != PY_ITERSEARCH_INDEX)
2249         goto Done;
2250 
2251     PyErr_SetString(PyExc_ValueError,
2252                     "sequence.index(x): x not in sequence");
2253     /* fall into failure code */
2254 Fail:
2255     n = -1;
2256     /* fall through */
2257 Done:
2258     Py_DECREF(it);
2259     return n;
2260 
2261 }
2262 
2263 /* Return # of times o appears in s. */
2264 Py_ssize_t
PySequence_Count(PyObject * s,PyObject * o)2265 PySequence_Count(PyObject *s, PyObject *o)
2266 {
2267     return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
2268 }
2269 
2270 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2271  * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2272  */
2273 int
PySequence_Contains(PyObject * seq,PyObject * ob)2274 PySequence_Contains(PyObject *seq, PyObject *ob)
2275 {
2276     PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
2277     if (sqm != NULL && sqm->sq_contains != NULL) {
2278         int res = (*sqm->sq_contains)(seq, ob);
2279         assert(_Py_CheckSlotResult(seq, "__contains__", res >= 0));
2280         return res;
2281     }
2282     Py_ssize_t result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2283     return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
2284 }
2285 
2286 /* Backwards compatibility */
2287 #undef PySequence_In
2288 int
PySequence_In(PyObject * w,PyObject * v)2289 PySequence_In(PyObject *w, PyObject *v)
2290 {
2291     return PySequence_Contains(w, v);
2292 }
2293 
2294 Py_ssize_t
PySequence_Index(PyObject * s,PyObject * o)2295 PySequence_Index(PyObject *s, PyObject *o)
2296 {
2297     return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
2298 }
2299 
2300 /* Operations on mappings */
2301 
2302 int
PyMapping_Check(PyObject * o)2303 PyMapping_Check(PyObject *o)
2304 {
2305     return o && Py_TYPE(o)->tp_as_mapping &&
2306         Py_TYPE(o)->tp_as_mapping->mp_subscript;
2307 }
2308 
2309 Py_ssize_t
PyMapping_Size(PyObject * o)2310 PyMapping_Size(PyObject *o)
2311 {
2312     if (o == NULL) {
2313         null_error();
2314         return -1;
2315     }
2316 
2317     PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
2318     if (m && m->mp_length) {
2319         Py_ssize_t len = m->mp_length(o);
2320         assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
2321         return len;
2322     }
2323 
2324     if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
2325         type_error("%.200s is not a mapping", o);
2326         return -1;
2327     }
2328     /* PyMapping_Size() can be called from PyObject_Size(). */
2329     type_error("object of type '%.200s' has no len()", o);
2330     return -1;
2331 }
2332 
2333 #undef PyMapping_Length
2334 Py_ssize_t
PyMapping_Length(PyObject * o)2335 PyMapping_Length(PyObject *o)
2336 {
2337     return PyMapping_Size(o);
2338 }
2339 #define PyMapping_Length PyMapping_Size
2340 
2341 PyObject *
PyMapping_GetItemString(PyObject * o,const char * key)2342 PyMapping_GetItemString(PyObject *o, const char *key)
2343 {
2344     PyObject *okey, *r;
2345 
2346     if (key == NULL) {
2347         return null_error();
2348     }
2349 
2350     okey = PyUnicode_FromString(key);
2351     if (okey == NULL)
2352         return NULL;
2353     r = PyObject_GetItem(o, okey);
2354     Py_DECREF(okey);
2355     return r;
2356 }
2357 
2358 int
PyMapping_SetItemString(PyObject * o,const char * key,PyObject * value)2359 PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
2360 {
2361     PyObject *okey;
2362     int r;
2363 
2364     if (key == NULL) {
2365         null_error();
2366         return -1;
2367     }
2368 
2369     okey = PyUnicode_FromString(key);
2370     if (okey == NULL)
2371         return -1;
2372     r = PyObject_SetItem(o, okey, value);
2373     Py_DECREF(okey);
2374     return r;
2375 }
2376 
2377 int
PyMapping_HasKeyString(PyObject * o,const char * key)2378 PyMapping_HasKeyString(PyObject *o, const char *key)
2379 {
2380     PyObject *v;
2381 
2382     v = PyMapping_GetItemString(o, key);
2383     if (v) {
2384         Py_DECREF(v);
2385         return 1;
2386     }
2387     PyErr_Clear();
2388     return 0;
2389 }
2390 
2391 int
PyMapping_HasKey(PyObject * o,PyObject * key)2392 PyMapping_HasKey(PyObject *o, PyObject *key)
2393 {
2394     PyObject *v;
2395 
2396     v = PyObject_GetItem(o, key);
2397     if (v) {
2398         Py_DECREF(v);
2399         return 1;
2400     }
2401     PyErr_Clear();
2402     return 0;
2403 }
2404 
2405 /* This function is quite similar to PySequence_Fast(), but specialized to be
2406    a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2407  */
2408 static PyObject *
method_output_as_list(PyObject * o,PyObject * meth)2409 method_output_as_list(PyObject *o, PyObject *meth)
2410 {
2411     PyObject *it, *result, *meth_output;
2412 
2413     assert(o != NULL);
2414     meth_output = PyObject_CallMethodNoArgs(o, meth);
2415     if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2416         return meth_output;
2417     }
2418     it = PyObject_GetIter(meth_output);
2419     if (it == NULL) {
2420         PyThreadState *tstate = _PyThreadState_GET();
2421         if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2422             _PyErr_Format(tstate, PyExc_TypeError,
2423                           "%.200s.%U() returned a non-iterable (type %.200s)",
2424                           Py_TYPE(o)->tp_name,
2425                           meth,
2426                           Py_TYPE(meth_output)->tp_name);
2427         }
2428         Py_DECREF(meth_output);
2429         return NULL;
2430     }
2431     Py_DECREF(meth_output);
2432     result = PySequence_List(it);
2433     Py_DECREF(it);
2434     return result;
2435 }
2436 
2437 PyObject *
PyMapping_Keys(PyObject * o)2438 PyMapping_Keys(PyObject *o)
2439 {
2440     if (o == NULL) {
2441         return null_error();
2442     }
2443     if (PyDict_CheckExact(o)) {
2444         return PyDict_Keys(o);
2445     }
2446     return method_output_as_list(o, &_Py_ID(keys));
2447 }
2448 
2449 PyObject *
PyMapping_Items(PyObject * o)2450 PyMapping_Items(PyObject *o)
2451 {
2452     if (o == NULL) {
2453         return null_error();
2454     }
2455     if (PyDict_CheckExact(o)) {
2456         return PyDict_Items(o);
2457     }
2458     return method_output_as_list(o, &_Py_ID(items));
2459 }
2460 
2461 PyObject *
PyMapping_Values(PyObject * o)2462 PyMapping_Values(PyObject *o)
2463 {
2464     if (o == NULL) {
2465         return null_error();
2466     }
2467     if (PyDict_CheckExact(o)) {
2468         return PyDict_Values(o);
2469     }
2470     return method_output_as_list(o, &_Py_ID(values));
2471 }
2472 
2473 /* isinstance(), issubclass() */
2474 
2475 /* abstract_get_bases() has logically 4 return states:
2476  *
2477  * 1. getattr(cls, '__bases__') could raise an AttributeError
2478  * 2. getattr(cls, '__bases__') could raise some other exception
2479  * 3. getattr(cls, '__bases__') could return a tuple
2480  * 4. getattr(cls, '__bases__') could return something other than a tuple
2481  *
2482  * Only state #3 is a non-error state and only it returns a non-NULL object
2483  * (it returns the retrieved tuple).
2484  *
2485  * Any raised AttributeErrors are masked by clearing the exception and
2486  * returning NULL.  If an object other than a tuple comes out of __bases__,
2487  * then again, the return value is NULL.  So yes, these two situations
2488  * produce exactly the same results: NULL is returned and no error is set.
2489  *
2490  * If some exception other than AttributeError is raised, then NULL is also
2491  * returned, but the exception is not cleared.  That's because we want the
2492  * exception to be propagated along.
2493  *
2494  * Callers are expected to test for PyErr_Occurred() when the return value
2495  * is NULL to decide whether a valid exception should be propagated or not.
2496  * When there's no exception to propagate, it's customary for the caller to
2497  * set a TypeError.
2498  */
2499 static PyObject *
abstract_get_bases(PyObject * cls)2500 abstract_get_bases(PyObject *cls)
2501 {
2502     PyObject *bases;
2503 
2504     (void)_PyObject_LookupAttr(cls, &_Py_ID(__bases__), &bases);
2505     if (bases != NULL && !PyTuple_Check(bases)) {
2506         Py_DECREF(bases);
2507         return NULL;
2508     }
2509     return bases;
2510 }
2511 
2512 
2513 static int
abstract_issubclass(PyObject * derived,PyObject * cls)2514 abstract_issubclass(PyObject *derived, PyObject *cls)
2515 {
2516     PyObject *bases = NULL;
2517     Py_ssize_t i, n;
2518     int r = 0;
2519 
2520     while (1) {
2521         if (derived == cls) {
2522             Py_XDECREF(bases); /* See below comment */
2523             return 1;
2524         }
2525         /* Use XSETREF to drop bases reference *after* finishing with
2526            derived; bases might be the only reference to it.
2527            XSETREF is used instead of SETREF, because bases is NULL on the
2528            first iteration of the loop.
2529         */
2530         Py_XSETREF(bases, abstract_get_bases(derived));
2531         if (bases == NULL) {
2532             if (PyErr_Occurred())
2533                 return -1;
2534             return 0;
2535         }
2536         n = PyTuple_GET_SIZE(bases);
2537         if (n == 0) {
2538             Py_DECREF(bases);
2539             return 0;
2540         }
2541         /* Avoid recursivity in the single inheritance case */
2542         if (n == 1) {
2543             derived = PyTuple_GET_ITEM(bases, 0);
2544             continue;
2545         }
2546         break;
2547     }
2548     assert(n >= 2);
2549     if (_Py_EnterRecursiveCall(" in __issubclass__")) {
2550         Py_DECREF(bases);
2551         return -1;
2552     }
2553     for (i = 0; i < n; i++) {
2554         r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2555         if (r != 0) {
2556             break;
2557         }
2558     }
2559     _Py_LeaveRecursiveCall();
2560     Py_DECREF(bases);
2561     return r;
2562 }
2563 
2564 static int
check_class(PyObject * cls,const char * error)2565 check_class(PyObject *cls, const char *error)
2566 {
2567     PyObject *bases = abstract_get_bases(cls);
2568     if (bases == NULL) {
2569         /* Do not mask errors. */
2570         PyThreadState *tstate = _PyThreadState_GET();
2571         if (!_PyErr_Occurred(tstate)) {
2572             _PyErr_SetString(tstate, PyExc_TypeError, error);
2573         }
2574         return 0;
2575     }
2576     Py_DECREF(bases);
2577     return -1;
2578 }
2579 
2580 static int
object_isinstance(PyObject * inst,PyObject * cls)2581 object_isinstance(PyObject *inst, PyObject *cls)
2582 {
2583     PyObject *icls;
2584     int retval;
2585     if (PyType_Check(cls)) {
2586         retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2587         if (retval == 0) {
2588             retval = _PyObject_LookupAttr(inst, &_Py_ID(__class__), &icls);
2589             if (icls != NULL) {
2590                 if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
2591                     retval = PyType_IsSubtype(
2592                         (PyTypeObject *)icls,
2593                         (PyTypeObject *)cls);
2594                 }
2595                 else {
2596                     retval = 0;
2597                 }
2598                 Py_DECREF(icls);
2599             }
2600         }
2601     }
2602     else {
2603         if (!check_class(cls,
2604             "isinstance() arg 2 must be a type, a tuple of types, or a union"))
2605             return -1;
2606         retval = _PyObject_LookupAttr(inst, &_Py_ID(__class__), &icls);
2607         if (icls != NULL) {
2608             retval = abstract_issubclass(icls, cls);
2609             Py_DECREF(icls);
2610         }
2611     }
2612 
2613     return retval;
2614 }
2615 
2616 static int
object_recursive_isinstance(PyThreadState * tstate,PyObject * inst,PyObject * cls)2617 object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
2618 {
2619     /* Quick test for an exact match */
2620     if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
2621         return 1;
2622     }
2623 
2624     /* We know what type's __instancecheck__ does. */
2625     if (PyType_CheckExact(cls)) {
2626         return object_isinstance(inst, cls);
2627     }
2628 
2629     if (_PyUnion_Check(cls)) {
2630         cls = _Py_union_args(cls);
2631     }
2632 
2633     if (PyTuple_Check(cls)) {
2634         /* Not a general sequence -- that opens up the road to
2635            recursion and stack overflow. */
2636         if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
2637             return -1;
2638         }
2639         Py_ssize_t n = PyTuple_GET_SIZE(cls);
2640         int r = 0;
2641         for (Py_ssize_t i = 0; i < n; ++i) {
2642             PyObject *item = PyTuple_GET_ITEM(cls, i);
2643             r = object_recursive_isinstance(tstate, inst, item);
2644             if (r != 0) {
2645                 /* either found it, or got an error */
2646                 break;
2647             }
2648         }
2649         _Py_LeaveRecursiveCallTstate(tstate);
2650         return r;
2651     }
2652 
2653     PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__));
2654     if (checker != NULL) {
2655         if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
2656             Py_DECREF(checker);
2657             return -1;
2658         }
2659 
2660         PyObject *res = PyObject_CallOneArg(checker, inst);
2661         _Py_LeaveRecursiveCallTstate(tstate);
2662         Py_DECREF(checker);
2663 
2664         if (res == NULL) {
2665             return -1;
2666         }
2667         int ok = PyObject_IsTrue(res);
2668         Py_DECREF(res);
2669 
2670         return ok;
2671     }
2672     else if (_PyErr_Occurred(tstate)) {
2673         return -1;
2674     }
2675 
2676     /* cls has no __instancecheck__() method */
2677     return object_isinstance(inst, cls);
2678 }
2679 
2680 
2681 int
PyObject_IsInstance(PyObject * inst,PyObject * cls)2682 PyObject_IsInstance(PyObject *inst, PyObject *cls)
2683 {
2684     PyThreadState *tstate = _PyThreadState_GET();
2685     return object_recursive_isinstance(tstate, inst, cls);
2686 }
2687 
2688 
2689 static  int
recursive_issubclass(PyObject * derived,PyObject * cls)2690 recursive_issubclass(PyObject *derived, PyObject *cls)
2691 {
2692     if (PyType_Check(cls) && PyType_Check(derived)) {
2693         /* Fast path (non-recursive) */
2694         return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2695     }
2696     if (!check_class(derived,
2697                      "issubclass() arg 1 must be a class"))
2698         return -1;
2699 
2700     if (!_PyUnion_Check(cls) && !check_class(cls,
2701                             "issubclass() arg 2 must be a class,"
2702                             " a tuple of classes, or a union")) {
2703         return -1;
2704     }
2705 
2706     return abstract_issubclass(derived, cls);
2707 }
2708 
2709 static int
object_issubclass(PyThreadState * tstate,PyObject * derived,PyObject * cls)2710 object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
2711 {
2712     PyObject *checker;
2713 
2714     /* We know what type's __subclasscheck__ does. */
2715     if (PyType_CheckExact(cls)) {
2716         /* Quick test for an exact match */
2717         if (derived == cls)
2718             return 1;
2719         return recursive_issubclass(derived, cls);
2720     }
2721 
2722     if (_PyUnion_Check(cls)) {
2723         cls = _Py_union_args(cls);
2724     }
2725 
2726     if (PyTuple_Check(cls)) {
2727 
2728         if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
2729             return -1;
2730         }
2731         Py_ssize_t n = PyTuple_GET_SIZE(cls);
2732         int r = 0;
2733         for (Py_ssize_t i = 0; i < n; ++i) {
2734             PyObject *item = PyTuple_GET_ITEM(cls, i);
2735             r = object_issubclass(tstate, derived, item);
2736             if (r != 0)
2737                 /* either found it, or got an error */
2738                 break;
2739         }
2740         _Py_LeaveRecursiveCallTstate(tstate);
2741         return r;
2742     }
2743 
2744     checker = _PyObject_LookupSpecial(cls, &_Py_ID(__subclasscheck__));
2745     if (checker != NULL) {
2746         int ok = -1;
2747         if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
2748             Py_DECREF(checker);
2749             return ok;
2750         }
2751         PyObject *res = PyObject_CallOneArg(checker, derived);
2752         _Py_LeaveRecursiveCallTstate(tstate);
2753         Py_DECREF(checker);
2754         if (res != NULL) {
2755             ok = PyObject_IsTrue(res);
2756             Py_DECREF(res);
2757         }
2758         return ok;
2759     }
2760     else if (_PyErr_Occurred(tstate)) {
2761         return -1;
2762     }
2763 
2764     /* Probably never reached anymore. */
2765     return recursive_issubclass(derived, cls);
2766 }
2767 
2768 
2769 int
PyObject_IsSubclass(PyObject * derived,PyObject * cls)2770 PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2771 {
2772     PyThreadState *tstate = _PyThreadState_GET();
2773     return object_issubclass(tstate, derived, cls);
2774 }
2775 
2776 
2777 int
_PyObject_RealIsInstance(PyObject * inst,PyObject * cls)2778 _PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2779 {
2780     return object_isinstance(inst, cls);
2781 }
2782 
2783 int
_PyObject_RealIsSubclass(PyObject * derived,PyObject * cls)2784 _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2785 {
2786     return recursive_issubclass(derived, cls);
2787 }
2788 
2789 
2790 PyObject *
PyObject_GetIter(PyObject * o)2791 PyObject_GetIter(PyObject *o)
2792 {
2793     PyTypeObject *t = Py_TYPE(o);
2794     getiterfunc f;
2795 
2796     f = t->tp_iter;
2797     if (f == NULL) {
2798         if (PySequence_Check(o))
2799             return PySeqIter_New(o);
2800         return type_error("'%.200s' object is not iterable", o);
2801     }
2802     else {
2803         PyObject *res = (*f)(o);
2804         if (res != NULL && !PyIter_Check(res)) {
2805             PyErr_Format(PyExc_TypeError,
2806                          "iter() returned non-iterator "
2807                          "of type '%.100s'",
2808                          Py_TYPE(res)->tp_name);
2809             Py_DECREF(res);
2810             res = NULL;
2811         }
2812         return res;
2813     }
2814 }
2815 
2816 PyObject *
PyObject_GetAIter(PyObject * o)2817 PyObject_GetAIter(PyObject *o) {
2818     PyTypeObject *t = Py_TYPE(o);
2819     unaryfunc f;
2820 
2821     if (t->tp_as_async == NULL || t->tp_as_async->am_aiter == NULL) {
2822         return type_error("'%.200s' object is not an async iterable", o);
2823     }
2824     f = t->tp_as_async->am_aiter;
2825     PyObject *it = (*f)(o);
2826     if (it != NULL && !PyAIter_Check(it)) {
2827         PyErr_Format(PyExc_TypeError,
2828                      "aiter() returned not an async iterator of type '%.100s'",
2829                      Py_TYPE(it)->tp_name);
2830         Py_DECREF(it);
2831         it = NULL;
2832     }
2833     return it;
2834 }
2835 
2836 int
PyIter_Check(PyObject * obj)2837 PyIter_Check(PyObject *obj)
2838 {
2839     PyTypeObject *tp = Py_TYPE(obj);
2840     return (tp->tp_iternext != NULL &&
2841             tp->tp_iternext != &_PyObject_NextNotImplemented);
2842 }
2843 
2844 int
PyAIter_Check(PyObject * obj)2845 PyAIter_Check(PyObject *obj)
2846 {
2847     PyTypeObject *tp = Py_TYPE(obj);
2848     return (tp->tp_as_async != NULL &&
2849             tp->tp_as_async->am_anext != NULL &&
2850             tp->tp_as_async->am_anext != &_PyObject_NextNotImplemented);
2851 }
2852 
2853 /* Return next item.
2854  * If an error occurs, return NULL.  PyErr_Occurred() will be true.
2855  * If the iteration terminates normally, return NULL and clear the
2856  * PyExc_StopIteration exception (if it was set).  PyErr_Occurred()
2857  * will be false.
2858  * Else return the next object.  PyErr_Occurred() will be false.
2859  */
2860 PyObject *
PyIter_Next(PyObject * iter)2861 PyIter_Next(PyObject *iter)
2862 {
2863     PyObject *result;
2864     result = (*Py_TYPE(iter)->tp_iternext)(iter);
2865     if (result == NULL) {
2866         PyThreadState *tstate = _PyThreadState_GET();
2867         if (_PyErr_Occurred(tstate)
2868             && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
2869         {
2870             _PyErr_Clear(tstate);
2871         }
2872     }
2873     return result;
2874 }
2875 
2876 PySendResult
PyIter_Send(PyObject * iter,PyObject * arg,PyObject ** result)2877 PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
2878 {
2879     assert(arg != NULL);
2880     assert(result != NULL);
2881     if (Py_TYPE(iter)->tp_as_async && Py_TYPE(iter)->tp_as_async->am_send) {
2882         PySendResult res = Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result);
2883         assert(_Py_CheckSlotResult(iter, "am_send", res != PYGEN_ERROR));
2884         return res;
2885     }
2886     if (arg == Py_None && PyIter_Check(iter)) {
2887         *result = Py_TYPE(iter)->tp_iternext(iter);
2888     }
2889     else {
2890         *result = PyObject_CallMethodOneArg(iter, &_Py_ID(send), arg);
2891     }
2892     if (*result != NULL) {
2893         return PYGEN_NEXT;
2894     }
2895     if (_PyGen_FetchStopIterationValue(result) == 0) {
2896         return PYGEN_RETURN;
2897     }
2898     return PYGEN_ERROR;
2899 }
2900 
2901 /*
2902  * Flatten a sequence of bytes() objects into a C array of
2903  * NULL terminated string pointers with a NULL char* terminating the array.
2904  * (ie: an argv or env list)
2905  *
2906  * Memory allocated for the returned list is allocated using PyMem_Malloc()
2907  * and MUST be freed by _Py_FreeCharPArray().
2908  */
2909 char *const *
_PySequence_BytesToCharpArray(PyObject * self)2910 _PySequence_BytesToCharpArray(PyObject* self)
2911 {
2912     char **array;
2913     Py_ssize_t i, argc;
2914     PyObject *item = NULL;
2915     Py_ssize_t size;
2916 
2917     argc = PySequence_Size(self);
2918     if (argc == -1)
2919         return NULL;
2920 
2921     assert(argc >= 0);
2922 
2923     if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2924         PyErr_NoMemory();
2925         return NULL;
2926     }
2927 
2928     array = PyMem_Malloc((argc + 1) * sizeof(char *));
2929     if (array == NULL) {
2930         PyErr_NoMemory();
2931         return NULL;
2932     }
2933     for (i = 0; i < argc; ++i) {
2934         char *data;
2935         item = PySequence_GetItem(self, i);
2936         if (item == NULL) {
2937             /* NULL terminate before freeing. */
2938             array[i] = NULL;
2939             goto fail;
2940         }
2941         /* check for embedded null bytes */
2942         if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
2943             /* NULL terminate before freeing. */
2944             array[i] = NULL;
2945             goto fail;
2946         }
2947         size = PyBytes_GET_SIZE(item) + 1;
2948         array[i] = PyMem_Malloc(size);
2949         if (!array[i]) {
2950             PyErr_NoMemory();
2951             goto fail;
2952         }
2953         memcpy(array[i], data, size);
2954         Py_DECREF(item);
2955     }
2956     array[argc] = NULL;
2957 
2958     return array;
2959 
2960 fail:
2961     Py_XDECREF(item);
2962     _Py_FreeCharPArray(array);
2963     return NULL;
2964 }
2965 
2966 
2967 /* Free's a NULL terminated char** array of C strings. */
2968 void
_Py_FreeCharPArray(char * const array[])2969 _Py_FreeCharPArray(char *const array[])
2970 {
2971     Py_ssize_t i;
2972     for (i = 0; array[i] != NULL; ++i) {
2973         PyMem_Free(array[i]);
2974     }
2975     PyMem_Free((void*)array);
2976 }
2977