• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "Python.h"
2 #include "pycore_call.h"          // _PyObject_CallNoArgsTstate()
3 #include "pycore_ceval.h"         // _Py_EnterRecursiveCallTstate()
4 #include "pycore_dict.h"          // _PyDict_FromItems()
5 #include "pycore_function.h"      // _PyFunction_Vectorcall() definition
6 #include "pycore_modsupport.h"    // _Py_VaBuildStack()
7 #include "pycore_object.h"        // _PyCFunctionWithKeywords_TrampolineCall()
8 #include "pycore_pyerrors.h"      // _PyErr_Occurred()
9 #include "pycore_pystate.h"       // _PyThreadState_GET()
10 #include "pycore_tuple.h"         // _PyTuple_ITEMS()
11 
12 
13 static PyObject *
null_error(PyThreadState * tstate)14 null_error(PyThreadState *tstate)
15 {
16     if (!_PyErr_Occurred(tstate)) {
17         _PyErr_SetString(tstate, PyExc_SystemError,
18                          "null argument to internal routine");
19     }
20     return NULL;
21 }
22 
23 
24 PyObject*
_Py_CheckFunctionResult(PyThreadState * tstate,PyObject * callable,PyObject * result,const char * where)25 _Py_CheckFunctionResult(PyThreadState *tstate, PyObject *callable,
26                         PyObject *result, const char *where)
27 {
28     assert((callable != NULL) ^ (where != NULL));
29 
30     if (result == NULL) {
31         if (!_PyErr_Occurred(tstate)) {
32             if (callable)
33                 _PyErr_Format(tstate, PyExc_SystemError,
34                               "%R returned NULL without setting an exception",
35                               callable);
36             else
37                 _PyErr_Format(tstate, PyExc_SystemError,
38                               "%s returned NULL without setting an exception",
39                               where);
40 #ifdef Py_DEBUG
41             /* Ensure that the bug is caught in debug mode.
42                Py_FatalError() logs the SystemError exception raised above. */
43             Py_FatalError("a function returned NULL without setting an exception");
44 #endif
45             return NULL;
46         }
47     }
48     else {
49         if (_PyErr_Occurred(tstate)) {
50             Py_DECREF(result);
51 
52             if (callable) {
53                 _PyErr_FormatFromCauseTstate(
54                     tstate, PyExc_SystemError,
55                     "%R returned a result with an exception set", callable);
56             }
57             else {
58                 _PyErr_FormatFromCauseTstate(
59                     tstate, PyExc_SystemError,
60                     "%s returned a result with an exception set", where);
61             }
62 #ifdef Py_DEBUG
63             /* Ensure that the bug is caught in debug mode.
64                Py_FatalError() logs the SystemError exception raised above. */
65             Py_FatalError("a function returned a result with an exception set");
66 #endif
67             return NULL;
68         }
69     }
70     return result;
71 }
72 
73 
74 int
_Py_CheckSlotResult(PyObject * obj,const char * slot_name,int success)75 _Py_CheckSlotResult(PyObject *obj, const char *slot_name, int success)
76 {
77     PyThreadState *tstate = _PyThreadState_GET();
78     if (!success) {
79         if (!_PyErr_Occurred(tstate)) {
80             _Py_FatalErrorFormat(__func__,
81                                  "Slot %s of type %s failed "
82                                  "without setting an exception",
83                                  slot_name, Py_TYPE(obj)->tp_name);
84         }
85     }
86     else {
87         if (_PyErr_Occurred(tstate)) {
88             _Py_FatalErrorFormat(__func__,
89                                  "Slot %s of type %s succeeded "
90                                  "with an exception set",
91                                  slot_name, Py_TYPE(obj)->tp_name);
92         }
93     }
94     return 1;
95 }
96 
97 
98 /* --- Core PyObject call functions ------------------------------- */
99 
100 /* Call a callable Python object without any arguments */
101 PyObject *
PyObject_CallNoArgs(PyObject * func)102 PyObject_CallNoArgs(PyObject *func)
103 {
104     EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, func);
105     PyThreadState *tstate = _PyThreadState_GET();
106     return _PyObject_VectorcallTstate(tstate, func, NULL, 0, NULL);
107 }
108 
109 
110 PyObject *
_PyObject_VectorcallDictTstate(PyThreadState * tstate,PyObject * callable,PyObject * const * args,size_t nargsf,PyObject * kwargs)111 _PyObject_VectorcallDictTstate(PyThreadState *tstate, PyObject *callable,
112                                PyObject *const *args, size_t nargsf,
113                                PyObject *kwargs)
114 {
115     assert(callable != NULL);
116 
117     /* PyObject_VectorcallDict() must not be called with an exception set,
118        because it can clear it (directly or indirectly) and so the
119        caller loses its exception */
120     assert(!_PyErr_Occurred(tstate));
121 
122     Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
123     assert(nargs >= 0);
124     assert(nargs == 0 || args != NULL);
125     assert(kwargs == NULL || PyDict_Check(kwargs));
126 
127     vectorcallfunc func = PyVectorcall_Function(callable);
128     if (func == NULL) {
129         /* Use tp_call instead */
130         return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwargs);
131     }
132 
133     PyObject *res;
134     if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
135         res = func(callable, args, nargsf, NULL);
136     }
137     else {
138         PyObject *kwnames;
139         PyObject *const *newargs;
140         newargs = _PyStack_UnpackDict(tstate,
141                                       args, nargs,
142                                       kwargs, &kwnames);
143         if (newargs == NULL) {
144             return NULL;
145         }
146         res = func(callable, newargs,
147                    nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
148         _PyStack_UnpackDict_Free(newargs, nargs, kwnames);
149     }
150     return _Py_CheckFunctionResult(tstate, callable, res, NULL);
151 }
152 
153 
154 PyObject *
PyObject_VectorcallDict(PyObject * callable,PyObject * const * args,size_t nargsf,PyObject * kwargs)155 PyObject_VectorcallDict(PyObject *callable, PyObject *const *args,
156                        size_t nargsf, PyObject *kwargs)
157 {
158     PyThreadState *tstate = _PyThreadState_GET();
159     return _PyObject_VectorcallDictTstate(tstate, callable, args, nargsf, kwargs);
160 }
161 
162 static void
object_is_not_callable(PyThreadState * tstate,PyObject * callable)163 object_is_not_callable(PyThreadState *tstate, PyObject *callable)
164 {
165     if (Py_IS_TYPE(callable, &PyModule_Type)) {
166         // >>> import pprint
167         // >>> pprint(thing)
168         // Traceback (most recent call last):
169         //   File "<stdin>", line 1, in <module>
170         // TypeError: 'module' object is not callable. Did you mean: 'pprint.pprint(...)'?
171         PyObject *name = PyModule_GetNameObject(callable);
172         if (name == NULL) {
173             _PyErr_Clear(tstate);
174             goto basic_type_error;
175         }
176         PyObject *attr;
177         int res = PyObject_GetOptionalAttr(callable, name, &attr);
178         if (res < 0) {
179             _PyErr_Clear(tstate);
180         }
181         else if (res > 0 && PyCallable_Check(attr)) {
182             _PyErr_Format(tstate, PyExc_TypeError,
183                           "'%.200s' object is not callable. "
184                           "Did you mean: '%U.%U(...)'?",
185                           Py_TYPE(callable)->tp_name, name, name);
186             Py_DECREF(attr);
187             Py_DECREF(name);
188             return;
189         }
190         Py_XDECREF(attr);
191         Py_DECREF(name);
192     }
193 basic_type_error:
194     _PyErr_Format(tstate, PyExc_TypeError, "'%.200s' object is not callable",
195                   Py_TYPE(callable)->tp_name);
196 }
197 
198 
199 PyObject *
_PyObject_MakeTpCall(PyThreadState * tstate,PyObject * callable,PyObject * const * args,Py_ssize_t nargs,PyObject * keywords)200 _PyObject_MakeTpCall(PyThreadState *tstate, PyObject *callable,
201                      PyObject *const *args, Py_ssize_t nargs,
202                      PyObject *keywords)
203 {
204     assert(nargs >= 0);
205     assert(nargs == 0 || args != NULL);
206     assert(keywords == NULL || PyTuple_Check(keywords) || PyDict_Check(keywords));
207 
208     /* Slow path: build a temporary tuple for positional arguments and a
209      * temporary dictionary for keyword arguments (if any) */
210     ternaryfunc call = Py_TYPE(callable)->tp_call;
211     if (call == NULL) {
212         object_is_not_callable(tstate, callable);
213         return NULL;
214     }
215 
216     PyObject *argstuple = _PyTuple_FromArray(args, nargs);
217     if (argstuple == NULL) {
218         return NULL;
219     }
220 
221     PyObject *kwdict;
222     if (keywords == NULL || PyDict_Check(keywords)) {
223         kwdict = keywords;
224     }
225     else {
226         if (PyTuple_GET_SIZE(keywords)) {
227             assert(args != NULL);
228             kwdict = _PyStack_AsDict(args + nargs, keywords);
229             if (kwdict == NULL) {
230                 Py_DECREF(argstuple);
231                 return NULL;
232             }
233         }
234         else {
235             keywords = kwdict = NULL;
236         }
237     }
238 
239     PyObject *result = NULL;
240     if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object") == 0)
241     {
242         result = _PyCFunctionWithKeywords_TrampolineCall(
243             (PyCFunctionWithKeywords)call, callable, argstuple, kwdict);
244         _Py_LeaveRecursiveCallTstate(tstate);
245     }
246 
247     Py_DECREF(argstuple);
248     if (kwdict != keywords) {
249         Py_DECREF(kwdict);
250     }
251 
252     return _Py_CheckFunctionResult(tstate, callable, result, NULL);
253 }
254 
255 
256 vectorcallfunc
PyVectorcall_Function(PyObject * callable)257 PyVectorcall_Function(PyObject *callable)
258 {
259     return _PyVectorcall_FunctionInline(callable);
260 }
261 
262 
263 static PyObject *
_PyVectorcall_Call(PyThreadState * tstate,vectorcallfunc func,PyObject * callable,PyObject * tuple,PyObject * kwargs)264 _PyVectorcall_Call(PyThreadState *tstate, vectorcallfunc func,
265                    PyObject *callable, PyObject *tuple, PyObject *kwargs)
266 {
267     assert(func != NULL);
268 
269     Py_ssize_t nargs = PyTuple_GET_SIZE(tuple);
270 
271     /* Fast path for no keywords */
272     if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
273         return func(callable, _PyTuple_ITEMS(tuple), nargs, NULL);
274     }
275 
276     /* Convert arguments & call */
277     PyObject *const *args;
278     PyObject *kwnames;
279     args = _PyStack_UnpackDict(tstate,
280                                _PyTuple_ITEMS(tuple), nargs,
281                                kwargs, &kwnames);
282     if (args == NULL) {
283         return NULL;
284     }
285     PyObject *result = func(callable, args,
286                             nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
287     _PyStack_UnpackDict_Free(args, nargs, kwnames);
288 
289     return _Py_CheckFunctionResult(tstate, callable, result, NULL);
290 }
291 
292 
293 PyObject *
PyVectorcall_Call(PyObject * callable,PyObject * tuple,PyObject * kwargs)294 PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *kwargs)
295 {
296     PyThreadState *tstate = _PyThreadState_GET();
297 
298     /* get vectorcallfunc as in _PyVectorcall_Function, but without
299      * the Py_TPFLAGS_HAVE_VECTORCALL check */
300     Py_ssize_t offset = Py_TYPE(callable)->tp_vectorcall_offset;
301     if (offset <= 0) {
302         _PyErr_Format(tstate, PyExc_TypeError,
303                       "'%.200s' object does not support vectorcall",
304                       Py_TYPE(callable)->tp_name);
305         return NULL;
306     }
307     assert(PyCallable_Check(callable));
308 
309     vectorcallfunc func;
310     memcpy(&func, (char *) callable + offset, sizeof(func));
311     if (func == NULL) {
312         _PyErr_Format(tstate, PyExc_TypeError,
313                       "'%.200s' object does not support vectorcall",
314                       Py_TYPE(callable)->tp_name);
315         return NULL;
316     }
317 
318     return _PyVectorcall_Call(tstate, func, callable, tuple, kwargs);
319 }
320 
321 
322 PyObject *
PyObject_Vectorcall(PyObject * callable,PyObject * const * args,size_t nargsf,PyObject * kwnames)323 PyObject_Vectorcall(PyObject *callable, PyObject *const *args,
324                      size_t nargsf, PyObject *kwnames)
325 {
326     PyThreadState *tstate = _PyThreadState_GET();
327     return _PyObject_VectorcallTstate(tstate, callable,
328                                       args, nargsf, kwnames);
329 }
330 
331 
332 PyObject *
_PyObject_Call(PyThreadState * tstate,PyObject * callable,PyObject * args,PyObject * kwargs)333 _PyObject_Call(PyThreadState *tstate, PyObject *callable,
334                PyObject *args, PyObject *kwargs)
335 {
336     ternaryfunc call;
337     PyObject *result;
338 
339     /* PyObject_Call() must not be called with an exception set,
340        because it can clear it (directly or indirectly) and so the
341        caller loses its exception */
342     assert(!_PyErr_Occurred(tstate));
343     assert(PyTuple_Check(args));
344     assert(kwargs == NULL || PyDict_Check(kwargs));
345     EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, callable);
346     vectorcallfunc vector_func = PyVectorcall_Function(callable);
347     if (vector_func != NULL) {
348         return _PyVectorcall_Call(tstate, vector_func, callable, args, kwargs);
349     }
350     else {
351         call = Py_TYPE(callable)->tp_call;
352         if (call == NULL) {
353             object_is_not_callable(tstate, callable);
354             return NULL;
355         }
356 
357         if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object")) {
358             return NULL;
359         }
360 
361         result = (*call)(callable, args, kwargs);
362 
363         _Py_LeaveRecursiveCallTstate(tstate);
364 
365         return _Py_CheckFunctionResult(tstate, callable, result, NULL);
366     }
367 }
368 
369 PyObject *
PyObject_Call(PyObject * callable,PyObject * args,PyObject * kwargs)370 PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
371 {
372     PyThreadState *tstate = _PyThreadState_GET();
373     return _PyObject_Call(tstate, callable, args, kwargs);
374 }
375 
376 
377 /* Function removed in the Python 3.13 API but kept in the stable ABI. */
378 PyAPI_FUNC(PyObject *)
PyCFunction_Call(PyObject * callable,PyObject * args,PyObject * kwargs)379 PyCFunction_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
380 {
381     return PyObject_Call(callable, args, kwargs);
382 }
383 
384 
385 PyObject *
PyObject_CallOneArg(PyObject * func,PyObject * arg)386 PyObject_CallOneArg(PyObject *func, PyObject *arg)
387 {
388     EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, func);
389     assert(arg != NULL);
390     PyObject *_args[2];
391     PyObject **args = _args + 1;  // For PY_VECTORCALL_ARGUMENTS_OFFSET
392     args[0] = arg;
393     PyThreadState *tstate = _PyThreadState_GET();
394     size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
395     return _PyObject_VectorcallTstate(tstate, func, args, nargsf, NULL);
396 }
397 
398 
399 /* --- PyFunction call functions ---------------------------------- */
400 
401 PyObject *
_PyFunction_Vectorcall(PyObject * func,PyObject * const * stack,size_t nargsf,PyObject * kwnames)402 _PyFunction_Vectorcall(PyObject *func, PyObject* const* stack,
403                        size_t nargsf, PyObject *kwnames)
404 {
405     assert(PyFunction_Check(func));
406     PyFunctionObject *f = (PyFunctionObject *)func;
407     Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
408     assert(nargs >= 0);
409     PyThreadState *tstate = _PyThreadState_GET();
410     assert(nargs == 0 || stack != NULL);
411     EVAL_CALL_STAT_INC(EVAL_CALL_FUNCTION_VECTORCALL);
412     if (((PyCodeObject *)f->func_code)->co_flags & CO_OPTIMIZED) {
413         return _PyEval_Vector(tstate, f, NULL, stack, nargs, kwnames);
414     }
415     else {
416         return _PyEval_Vector(tstate, f, f->func_globals, stack, nargs, kwnames);
417     }
418 }
419 
420 /* --- More complex call functions -------------------------------- */
421 
422 /* External interface to call any callable object.
423    The args must be a tuple or NULL.  The kwargs must be a dict or NULL.
424    Function removed in Python 3.13 API but kept in the stable ABI. */
425 PyAPI_FUNC(PyObject*)
PyEval_CallObjectWithKeywords(PyObject * callable,PyObject * args,PyObject * kwargs)426 PyEval_CallObjectWithKeywords(PyObject *callable,
427                               PyObject *args, PyObject *kwargs)
428 {
429     PyThreadState *tstate = _PyThreadState_GET();
430 #ifdef Py_DEBUG
431     /* PyEval_CallObjectWithKeywords() must not be called with an exception
432        set. It raises a new exception if parameters are invalid or if
433        PyTuple_New() fails, and so the original exception is lost. */
434     assert(!_PyErr_Occurred(tstate));
435 #endif
436 
437     if (args != NULL && !PyTuple_Check(args)) {
438         _PyErr_SetString(tstate, PyExc_TypeError,
439                          "argument list must be a tuple");
440         return NULL;
441     }
442 
443     if (kwargs != NULL && !PyDict_Check(kwargs)) {
444         _PyErr_SetString(tstate, PyExc_TypeError,
445                          "keyword list must be a dictionary");
446         return NULL;
447     }
448 
449     if (args == NULL) {
450         return _PyObject_VectorcallDictTstate(tstate, callable,
451                                               NULL, 0, kwargs);
452     }
453     else {
454         return _PyObject_Call(tstate, callable, args, kwargs);
455     }
456 }
457 
458 
459 PyObject *
PyObject_CallObject(PyObject * callable,PyObject * args)460 PyObject_CallObject(PyObject *callable, PyObject *args)
461 {
462     PyThreadState *tstate = _PyThreadState_GET();
463     assert(!_PyErr_Occurred(tstate));
464     if (args == NULL) {
465         return _PyObject_CallNoArgsTstate(tstate, callable);
466     }
467     if (!PyTuple_Check(args)) {
468         _PyErr_SetString(tstate, PyExc_TypeError,
469                          "argument list must be a tuple");
470         return NULL;
471     }
472     return _PyObject_Call(tstate, callable, args, NULL);
473 }
474 
475 
476 /* Call callable(obj, *args, **kwargs). */
477 PyObject *
_PyObject_Call_Prepend(PyThreadState * tstate,PyObject * callable,PyObject * obj,PyObject * args,PyObject * kwargs)478 _PyObject_Call_Prepend(PyThreadState *tstate, PyObject *callable,
479                        PyObject *obj, PyObject *args, PyObject *kwargs)
480 {
481     assert(PyTuple_Check(args));
482 
483     PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
484     PyObject **stack;
485 
486     Py_ssize_t argcount = PyTuple_GET_SIZE(args);
487     if (argcount + 1 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
488         stack = small_stack;
489     }
490     else {
491         stack = PyMem_Malloc((argcount + 1) * sizeof(PyObject *));
492         if (stack == NULL) {
493             PyErr_NoMemory();
494             return NULL;
495         }
496     }
497 
498     /* use borrowed references */
499     stack[0] = obj;
500     memcpy(&stack[1],
501            _PyTuple_ITEMS(args),
502            argcount * sizeof(PyObject *));
503 
504     PyObject *result = _PyObject_VectorcallDictTstate(tstate, callable,
505                                                       stack, argcount + 1,
506                                                       kwargs);
507     if (stack != small_stack) {
508         PyMem_Free(stack);
509     }
510     return result;
511 }
512 
513 
514 /* --- Call with a format string ---------------------------------- */
515 
516 static PyObject *
_PyObject_CallFunctionVa(PyThreadState * tstate,PyObject * callable,const char * format,va_list va)517 _PyObject_CallFunctionVa(PyThreadState *tstate, PyObject *callable,
518                          const char *format, va_list va)
519 {
520     PyObject* small_stack[_PY_FASTCALL_SMALL_STACK];
521     const Py_ssize_t small_stack_len = Py_ARRAY_LENGTH(small_stack);
522     PyObject **stack;
523     Py_ssize_t nargs, i;
524     PyObject *result;
525 
526     if (callable == NULL) {
527         return null_error(tstate);
528     }
529 
530     if (!format || !*format) {
531         return _PyObject_CallNoArgsTstate(tstate, callable);
532     }
533 
534     stack = _Py_VaBuildStack(small_stack, small_stack_len,
535                              format, va, &nargs);
536     if (stack == NULL) {
537         return NULL;
538     }
539     EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, callable);
540     if (nargs == 1 && PyTuple_Check(stack[0])) {
541         /* Special cases for backward compatibility:
542            - PyObject_CallFunction(func, "O", tuple) calls func(*tuple)
543            - PyObject_CallFunction(func, "(OOO)", arg1, arg2, arg3) calls
544              func(*(arg1, arg2, arg3)): func(arg1, arg2, arg3) */
545         PyObject *args = stack[0];
546         result = _PyObject_VectorcallTstate(tstate, callable,
547                                             _PyTuple_ITEMS(args),
548                                             PyTuple_GET_SIZE(args),
549                                             NULL);
550     }
551     else {
552         result = _PyObject_VectorcallTstate(tstate, callable,
553                                             stack, nargs, NULL);
554     }
555 
556     for (i = 0; i < nargs; ++i) {
557         Py_DECREF(stack[i]);
558     }
559     if (stack != small_stack) {
560         PyMem_Free(stack);
561     }
562     return result;
563 }
564 
565 
566 PyObject *
PyObject_CallFunction(PyObject * callable,const char * format,...)567 PyObject_CallFunction(PyObject *callable, const char *format, ...)
568 {
569     va_list va;
570     PyObject *result;
571     PyThreadState *tstate = _PyThreadState_GET();
572 
573     va_start(va, format);
574     result = _PyObject_CallFunctionVa(tstate, callable, format, va);
575     va_end(va);
576 
577     return result;
578 }
579 
580 
581 /* PyEval_CallFunction is exact copy of PyObject_CallFunction.
582    Function removed in Python 3.13 API but kept in the stable ABI. */
583 PyAPI_FUNC(PyObject*)
PyEval_CallFunction(PyObject * callable,const char * format,...)584 PyEval_CallFunction(PyObject *callable, const char *format, ...)
585 {
586     va_list va;
587     PyObject *result;
588     PyThreadState *tstate = _PyThreadState_GET();
589 
590     va_start(va, format);
591     result = _PyObject_CallFunctionVa(tstate, callable, format, va);
592     va_end(va);
593 
594     return result;
595 }
596 
597 
598 /* _PyObject_CallFunction_SizeT is exact copy of PyObject_CallFunction.
599  * This function must be kept because it is part of the stable ABI.
600  */
601 PyAPI_FUNC(PyObject *)  /* abi_only */
_PyObject_CallFunction_SizeT(PyObject * callable,const char * format,...)602 _PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...)
603 {
604     PyThreadState *tstate = _PyThreadState_GET();
605 
606     va_list va;
607     va_start(va, format);
608     PyObject *result = _PyObject_CallFunctionVa(tstate, callable, format, va);
609     va_end(va);
610 
611     return result;
612 }
613 
614 
615 static PyObject*
callmethod(PyThreadState * tstate,PyObject * callable,const char * format,va_list va)616 callmethod(PyThreadState *tstate, PyObject* callable, const char *format, va_list va)
617 {
618     assert(callable != NULL);
619     if (!PyCallable_Check(callable)) {
620         _PyErr_Format(tstate, PyExc_TypeError,
621                       "attribute of type '%.200s' is not callable",
622                       Py_TYPE(callable)->tp_name);
623         return NULL;
624     }
625 
626     return _PyObject_CallFunctionVa(tstate, callable, format, va);
627 }
628 
629 PyObject *
PyObject_CallMethod(PyObject * obj,const char * name,const char * format,...)630 PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
631 {
632     PyThreadState *tstate = _PyThreadState_GET();
633 
634     if (obj == NULL || name == NULL) {
635         return null_error(tstate);
636     }
637 
638     PyObject *callable = PyObject_GetAttrString(obj, name);
639     if (callable == NULL) {
640         return NULL;
641     }
642 
643     va_list va;
644     va_start(va, format);
645     PyObject *retval = callmethod(tstate, callable, format, va);
646     va_end(va);
647 
648     Py_DECREF(callable);
649     return retval;
650 }
651 
652 
653 /* PyEval_CallMethod is exact copy of PyObject_CallMethod.
654    Function removed in Python 3.13 API but kept in the stable ABI. */
655 PyAPI_FUNC(PyObject*)
PyEval_CallMethod(PyObject * obj,const char * name,const char * format,...)656 PyEval_CallMethod(PyObject *obj, const char *name, const char *format, ...)
657 {
658     PyThreadState *tstate = _PyThreadState_GET();
659     if (obj == NULL || name == NULL) {
660         return null_error(tstate);
661     }
662 
663     PyObject *callable = PyObject_GetAttrString(obj, name);
664     if (callable == NULL) {
665         return NULL;
666     }
667 
668     va_list va;
669     va_start(va, format);
670     PyObject *retval = callmethod(tstate, callable, format, va);
671     va_end(va);
672 
673     Py_DECREF(callable);
674     return retval;
675 }
676 
677 
678 PyObject *
_PyObject_CallMethod(PyObject * obj,PyObject * name,const char * format,...)679 _PyObject_CallMethod(PyObject *obj, PyObject *name,
680                      const char *format, ...)
681 {
682     PyThreadState *tstate = _PyThreadState_GET();
683     if (obj == NULL || name == NULL) {
684         return null_error(tstate);
685     }
686 
687     PyObject *callable = PyObject_GetAttr(obj, name);
688     if (callable == NULL) {
689         return NULL;
690     }
691 
692     va_list va;
693     va_start(va, format);
694     PyObject *retval = callmethod(tstate, callable, format, va);
695     va_end(va);
696 
697     Py_DECREF(callable);
698     return retval;
699 }
700 
701 
702 PyObject *
_PyObject_CallMethodId(PyObject * obj,_Py_Identifier * name,const char * format,...)703 _PyObject_CallMethodId(PyObject *obj, _Py_Identifier *name,
704                        const char *format, ...)
705 {
706     PyThreadState *tstate = _PyThreadState_GET();
707     if (obj == NULL || name == NULL) {
708         return null_error(tstate);
709     }
710 
711     PyObject *callable = _PyObject_GetAttrId(obj, name);
712     if (callable == NULL) {
713         return NULL;
714     }
715 
716     va_list va;
717     va_start(va, format);
718     PyObject *retval = callmethod(tstate, callable, format, va);
719     va_end(va);
720 
721     Py_DECREF(callable);
722     return retval;
723 }
724 
725 
_PyObject_CallMethodFormat(PyThreadState * tstate,PyObject * callable,const char * format,...)726 PyObject * _PyObject_CallMethodFormat(PyThreadState *tstate, PyObject *callable,
727                                       const char *format, ...)
728 {
729     va_list va;
730     va_start(va, format);
731     PyObject *retval = callmethod(tstate, callable, format, va);
732     va_end(va);
733     return retval;
734 }
735 
736 
737 // _PyObject_CallMethod_SizeT is exact copy of PyObject_CallMethod.
738 // This function must be kept because it is part of the stable ABI.
739 PyAPI_FUNC(PyObject *)  /* abi_only */
_PyObject_CallMethod_SizeT(PyObject * obj,const char * name,const char * format,...)740 _PyObject_CallMethod_SizeT(PyObject *obj, const char *name,
741                            const char *format, ...)
742 {
743     PyThreadState *tstate = _PyThreadState_GET();
744     if (obj == NULL || name == NULL) {
745         return null_error(tstate);
746     }
747 
748     PyObject *callable = PyObject_GetAttrString(obj, name);
749     if (callable == NULL) {
750         return NULL;
751     }
752 
753     va_list va;
754     va_start(va, format);
755     PyObject *retval = callmethod(tstate, callable, format, va);
756     va_end(va);
757 
758     Py_DECREF(callable);
759     return retval;
760 }
761 
762 
763 /* --- Call with "..." arguments ---------------------------------- */
764 
765 static PyObject *
object_vacall(PyThreadState * tstate,PyObject * base,PyObject * callable,va_list vargs)766 object_vacall(PyThreadState *tstate, PyObject *base,
767               PyObject *callable, va_list vargs)
768 {
769     PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
770     PyObject **stack;
771     Py_ssize_t nargs;
772     PyObject *result;
773     Py_ssize_t i;
774     va_list countva;
775 
776     if (callable == NULL) {
777         return null_error(tstate);
778     }
779 
780     /* Count the number of arguments */
781     va_copy(countva, vargs);
782     nargs = base ? 1 : 0;
783     while (1) {
784         PyObject *arg = va_arg(countva, PyObject *);
785         if (arg == NULL) {
786             break;
787         }
788         nargs++;
789     }
790     va_end(countva);
791 
792     /* Copy arguments */
793     if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
794         stack = small_stack;
795     }
796     else {
797         stack = PyMem_Malloc(nargs * sizeof(stack[0]));
798         if (stack == NULL) {
799             PyErr_NoMemory();
800             return NULL;
801         }
802     }
803 
804     i = 0;
805     if (base) {
806         stack[i++] = base;
807     }
808 
809     for (; i < nargs; ++i) {
810         stack[i] = va_arg(vargs, PyObject *);
811     }
812 
813 #ifdef Py_STATS
814     if (PyFunction_Check(callable)) {
815         EVAL_CALL_STAT_INC(EVAL_CALL_API);
816     }
817 #endif
818     /* Call the function */
819     result = _PyObject_VectorcallTstate(tstate, callable, stack, nargs, NULL);
820 
821     if (stack != small_stack) {
822         PyMem_Free(stack);
823     }
824     return result;
825 }
826 
827 
828 PyObject *
PyObject_VectorcallMethod(PyObject * name,PyObject * const * args,size_t nargsf,PyObject * kwnames)829 PyObject_VectorcallMethod(PyObject *name, PyObject *const *args,
830                            size_t nargsf, PyObject *kwnames)
831 {
832     assert(name != NULL);
833     assert(args != NULL);
834     assert(PyVectorcall_NARGS(nargsf) >= 1);
835 
836     PyThreadState *tstate = _PyThreadState_GET();
837     PyObject *callable = NULL;
838     /* Use args[0] as "self" argument */
839     int unbound = _PyObject_GetMethod(args[0], name, &callable);
840     if (callable == NULL) {
841         return NULL;
842     }
843 
844     if (unbound) {
845         /* We must remove PY_VECTORCALL_ARGUMENTS_OFFSET since
846          * that would be interpreted as allowing to change args[-1] */
847         nargsf &= ~PY_VECTORCALL_ARGUMENTS_OFFSET;
848     }
849     else {
850         /* Skip "self". We can keep PY_VECTORCALL_ARGUMENTS_OFFSET since
851          * args[-1] in the onward call is args[0] here. */
852         args++;
853         nargsf--;
854     }
855     EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_METHOD, callable);
856     PyObject *result = _PyObject_VectorcallTstate(tstate, callable,
857                                                   args, nargsf, kwnames);
858     Py_DECREF(callable);
859     return result;
860 }
861 
862 
863 PyObject *
PyObject_CallMethodObjArgs(PyObject * obj,PyObject * name,...)864 PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)
865 {
866     PyThreadState *tstate = _PyThreadState_GET();
867     if (obj == NULL || name == NULL) {
868         return null_error(tstate);
869     }
870 
871     PyObject *callable = NULL;
872     int is_method = _PyObject_GetMethod(obj, name, &callable);
873     if (callable == NULL) {
874         return NULL;
875     }
876     obj = is_method ? obj : NULL;
877 
878     va_list vargs;
879     va_start(vargs, name);
880     PyObject *result = object_vacall(tstate, obj, callable, vargs);
881     va_end(vargs);
882 
883     Py_DECREF(callable);
884     return result;
885 }
886 
887 
888 PyObject *
_PyObject_CallMethodIdObjArgs(PyObject * obj,_Py_Identifier * name,...)889 _PyObject_CallMethodIdObjArgs(PyObject *obj, _Py_Identifier *name, ...)
890 {
891     PyThreadState *tstate = _PyThreadState_GET();
892     if (obj == NULL || name == NULL) {
893         return null_error(tstate);
894     }
895 
896     PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
897     if (!oname) {
898         return NULL;
899     }
900 
901     PyObject *callable = NULL;
902     int is_method = _PyObject_GetMethod(obj, oname, &callable);
903     if (callable == NULL) {
904         return NULL;
905     }
906     obj = is_method ? obj : NULL;
907 
908     va_list vargs;
909     va_start(vargs, name);
910     PyObject *result = object_vacall(tstate, obj, callable, vargs);
911     va_end(vargs);
912 
913     Py_DECREF(callable);
914     return result;
915 }
916 
917 
918 PyObject *
PyObject_CallFunctionObjArgs(PyObject * callable,...)919 PyObject_CallFunctionObjArgs(PyObject *callable, ...)
920 {
921     PyThreadState *tstate = _PyThreadState_GET();
922     va_list vargs;
923     PyObject *result;
924 
925     va_start(vargs, callable);
926     result = object_vacall(tstate, NULL, callable, vargs);
927     va_end(vargs);
928 
929     return result;
930 }
931 
932 
933 /* --- PyStack functions ------------------------------------------ */
934 
935 PyObject *
_PyStack_AsDict(PyObject * const * values,PyObject * kwnames)936 _PyStack_AsDict(PyObject *const *values, PyObject *kwnames)
937 {
938     Py_ssize_t nkwargs;
939 
940     assert(kwnames != NULL);
941     nkwargs = PyTuple_GET_SIZE(kwnames);
942     return _PyDict_FromItems(&PyTuple_GET_ITEM(kwnames, 0), 1,
943                              values, 1, nkwargs);
944 }
945 
946 
947 /* Convert (args, nargs, kwargs: dict) into a (stack, nargs, kwnames: tuple).
948 
949    Allocate a new argument vector and keyword names tuple. Return the argument
950    vector; return NULL with exception set on error. Return the keyword names
951    tuple in *p_kwnames.
952 
953    This also checks that all keyword names are strings. If not, a TypeError is
954    raised.
955 
956    The newly allocated argument vector supports PY_VECTORCALL_ARGUMENTS_OFFSET.
957 
958    When done, you must call _PyStack_UnpackDict_Free(stack, nargs, kwnames) */
959 PyObject *const *
_PyStack_UnpackDict(PyThreadState * tstate,PyObject * const * args,Py_ssize_t nargs,PyObject * kwargs,PyObject ** p_kwnames)960 _PyStack_UnpackDict(PyThreadState *tstate,
961                     PyObject *const *args, Py_ssize_t nargs,
962                     PyObject *kwargs, PyObject **p_kwnames)
963 {
964     assert(nargs >= 0);
965     assert(kwargs != NULL);
966     assert(PyDict_Check(kwargs));
967 
968     Py_ssize_t nkwargs = PyDict_GET_SIZE(kwargs);
969     /* Check for overflow in the PyMem_Malloc() call below. The subtraction
970      * in this check cannot overflow: both maxnargs and nkwargs are
971      * non-negative signed integers, so their difference fits in the type. */
972     Py_ssize_t maxnargs = PY_SSIZE_T_MAX / sizeof(args[0]) - 1;
973     if (nargs > maxnargs - nkwargs) {
974         _PyErr_NoMemory(tstate);
975         return NULL;
976     }
977 
978     /* Add 1 to support PY_VECTORCALL_ARGUMENTS_OFFSET */
979     PyObject **stack = PyMem_Malloc((1 + nargs + nkwargs) * sizeof(args[0]));
980     if (stack == NULL) {
981         _PyErr_NoMemory(tstate);
982         return NULL;
983     }
984 
985     PyObject *kwnames = PyTuple_New(nkwargs);
986     if (kwnames == NULL) {
987         PyMem_Free(stack);
988         return NULL;
989     }
990 
991     stack++;  /* For PY_VECTORCALL_ARGUMENTS_OFFSET */
992 
993     /* Copy positional arguments */
994     for (Py_ssize_t i = 0; i < nargs; i++) {
995         stack[i] = Py_NewRef(args[i]);
996     }
997 
998     PyObject **kwstack = stack + nargs;
999     /* This loop doesn't support lookup function mutating the dictionary
1000        to change its size. It's a deliberate choice for speed, this function is
1001        called in the performance critical hot code. */
1002     Py_ssize_t pos = 0, i = 0;
1003     PyObject *key, *value;
1004     unsigned long keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS;
1005     while (PyDict_Next(kwargs, &pos, &key, &value)) {
1006         keys_are_strings &= Py_TYPE(key)->tp_flags;
1007         PyTuple_SET_ITEM(kwnames, i, Py_NewRef(key));
1008         kwstack[i] = Py_NewRef(value);
1009         i++;
1010     }
1011 
1012     /* keys_are_strings has the value Py_TPFLAGS_UNICODE_SUBCLASS if that
1013      * flag is set for all keys. Otherwise, keys_are_strings equals 0.
1014      * We do this check once at the end instead of inside the loop above
1015      * because it simplifies the deallocation in the failing case.
1016      * It happens to also make the loop above slightly more efficient. */
1017     if (!keys_are_strings) {
1018         _PyErr_SetString(tstate, PyExc_TypeError,
1019                          "keywords must be strings");
1020         _PyStack_UnpackDict_Free(stack, nargs, kwnames);
1021         return NULL;
1022     }
1023 
1024     *p_kwnames = kwnames;
1025     return stack;
1026 }
1027 
1028 void
_PyStack_UnpackDict_Free(PyObject * const * stack,Py_ssize_t nargs,PyObject * kwnames)1029 _PyStack_UnpackDict_Free(PyObject *const *stack, Py_ssize_t nargs,
1030                          PyObject *kwnames)
1031 {
1032     Py_ssize_t n = PyTuple_GET_SIZE(kwnames) + nargs;
1033     for (Py_ssize_t i = 0; i < n; i++) {
1034         Py_DECREF(stack[i]);
1035     }
1036     _PyStack_UnpackDict_FreeNoDecRef(stack, kwnames);
1037 }
1038 
1039 void
_PyStack_UnpackDict_FreeNoDecRef(PyObject * const * stack,PyObject * kwnames)1040 _PyStack_UnpackDict_FreeNoDecRef(PyObject *const *stack, PyObject *kwnames)
1041 {
1042     PyMem_Free((PyObject **)stack - 1);
1043     Py_DECREF(kwnames);
1044 }
1045 
1046 // Export for the stable ABI
1047 #undef PyVectorcall_NARGS
1048 Py_ssize_t
PyVectorcall_NARGS(size_t n)1049 PyVectorcall_NARGS(size_t n)
1050 {
1051     return _PyVectorcall_NARGS(n);
1052 }
1053