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