blob: a4af816e30994ee26cd3a8944c10f3680cabfc71 [file] [log] [blame]
Victor Stinnerc22bfaa2017-02-12 19:27:05 +01001#include "Python.h"
2#include "frameobject.h"
3
4
5static PyObject *
6null_error(void)
7{
8 if (!PyErr_Occurred())
9 PyErr_SetString(PyExc_SystemError,
10 "null argument to internal routine");
11 return NULL;
12}
13
14
15PyObject*
16_Py_CheckFunctionResult(PyObject *callable, PyObject *result, const char *where)
17{
18 int err_occurred = (PyErr_Occurred() != NULL);
19
20 assert((callable != NULL) ^ (where != NULL));
21
22 if (result == NULL) {
23 if (!err_occurred) {
24 if (callable)
25 PyErr_Format(PyExc_SystemError,
26 "%R returned NULL without setting an error",
27 callable);
28 else
29 PyErr_Format(PyExc_SystemError,
30 "%s returned NULL without setting an error",
31 where);
32#ifdef Py_DEBUG
33 /* Ensure that the bug is caught in debug mode */
34 Py_FatalError("a function returned NULL without setting an error");
35#endif
36 return NULL;
37 }
38 }
39 else {
40 if (err_occurred) {
41 Py_DECREF(result);
42
43 if (callable) {
44 _PyErr_FormatFromCause(PyExc_SystemError,
45 "%R returned a result with an error set",
46 callable);
47 }
48 else {
49 _PyErr_FormatFromCause(PyExc_SystemError,
50 "%s returned a result with an error set",
51 where);
52 }
53#ifdef Py_DEBUG
54 /* Ensure that the bug is caught in debug mode */
55 Py_FatalError("a function returned a result with an error set");
56#endif
57 return NULL;
58 }
59 }
60 return result;
61}
62
63
64/* --- Core PyObject call functions ------------------------------- */
65
66PyObject *
67_PyObject_FastCallDict(PyObject *callable, PyObject **args, Py_ssize_t nargs,
68 PyObject *kwargs)
69{
70 /* _PyObject_FastCallDict() must not be called with an exception set,
71 because it can clear it (directly or indirectly) and so the
72 caller loses its exception */
73 assert(!PyErr_Occurred());
74
75 assert(callable != NULL);
76 assert(nargs >= 0);
77 assert(nargs == 0 || args != NULL);
78 assert(kwargs == NULL || PyDict_Check(kwargs));
79
80 if (PyFunction_Check(callable)) {
81 return _PyFunction_FastCallDict(callable, args, nargs, kwargs);
82 }
83 else if (PyCFunction_Check(callable)) {
84 return _PyCFunction_FastCallDict(callable, args, nargs, kwargs);
85 }
86 else {
87 PyObject *argstuple, *result;
88 ternaryfunc call;
89
90 /* Slow-path: build a temporary tuple */
91 call = callable->ob_type->tp_call;
92 if (call == NULL) {
93 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
94 callable->ob_type->tp_name);
95 return NULL;
96 }
97
98 argstuple = _PyStack_AsTuple(args, nargs);
99 if (argstuple == NULL) {
100 return NULL;
101 }
102
103 if (Py_EnterRecursiveCall(" while calling a Python object")) {
104 Py_DECREF(argstuple);
105 return NULL;
106 }
107
108 result = (*call)(callable, argstuple, kwargs);
109
110 Py_LeaveRecursiveCall();
111 Py_DECREF(argstuple);
112
113 result = _Py_CheckFunctionResult(callable, result, NULL);
114 return result;
115 }
116}
117
118
119PyObject *
120_PyObject_FastCallKeywords(PyObject *callable, PyObject **stack, Py_ssize_t nargs,
121 PyObject *kwnames)
122{
123 /* _PyObject_FastCallKeywords() must not be called with an exception set,
124 because it can clear it (directly or indirectly) and so the
125 caller loses its exception */
126 assert(!PyErr_Occurred());
127
128 assert(nargs >= 0);
129 assert(kwnames == NULL || PyTuple_CheckExact(kwnames));
130
131 /* kwnames must only contains str strings, no subclass, and all keys must
132 be unique: these checks are implemented in Python/ceval.c and
133 _PyArg_ParseStackAndKeywords(). */
134
135 if (PyFunction_Check(callable)) {
136 return _PyFunction_FastCallKeywords(callable, stack, nargs, kwnames);
137 }
138 if (PyCFunction_Check(callable)) {
139 return _PyCFunction_FastCallKeywords(callable, stack, nargs, kwnames);
140 }
141 else {
142 /* Slow-path: build a temporary tuple for positional arguments and a
143 temporary dictionary for keyword arguments (if any) */
144
145 ternaryfunc call;
146 PyObject *argstuple;
147 PyObject *kwdict, *result;
148 Py_ssize_t nkwargs;
149
150 nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
151 assert((nargs == 0 && nkwargs == 0) || stack != NULL);
152
153 call = callable->ob_type->tp_call;
154 if (call == NULL) {
155 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
156 callable->ob_type->tp_name);
157 return NULL;
158 }
159
160 argstuple = _PyStack_AsTuple(stack, nargs);
161 if (argstuple == NULL) {
162 return NULL;
163 }
164
165 if (nkwargs > 0) {
166 kwdict = _PyStack_AsDict(stack + nargs, kwnames);
167 if (kwdict == NULL) {
168 Py_DECREF(argstuple);
169 return NULL;
170 }
171 }
172 else {
173 kwdict = NULL;
174 }
175
176 if (Py_EnterRecursiveCall(" while calling a Python object")) {
177 Py_DECREF(argstuple);
178 Py_XDECREF(kwdict);
179 return NULL;
180 }
181
182 result = (*call)(callable, argstuple, kwdict);
183
184 Py_LeaveRecursiveCall();
185
186 Py_DECREF(argstuple);
187 Py_XDECREF(kwdict);
188
189 result = _Py_CheckFunctionResult(callable, result, NULL);
190 return result;
191 }
192}
193
194
195PyObject *
196PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
197{
198 ternaryfunc call;
199 PyObject *result;
200
201 /* PyObject_Call() must not be called with an exception set,
202 because it can clear it (directly or indirectly) and so the
203 caller loses its exception */
204 assert(!PyErr_Occurred());
205 assert(PyTuple_Check(args));
206 assert(kwargs == NULL || PyDict_Check(kwargs));
207
208 if (PyFunction_Check(callable)) {
209 return _PyFunction_FastCallDict(callable,
210 &PyTuple_GET_ITEM(args, 0),
211 PyTuple_GET_SIZE(args),
212 kwargs);
213 }
214 else if (PyCFunction_Check(callable)) {
215 return PyCFunction_Call(callable, args, kwargs);
216 }
217 else {
218 call = callable->ob_type->tp_call;
219 if (call == NULL) {
220 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
221 callable->ob_type->tp_name);
222 return NULL;
223 }
224
225 if (Py_EnterRecursiveCall(" while calling a Python object"))
226 return NULL;
227
228 result = (*call)(callable, args, kwargs);
229
230 Py_LeaveRecursiveCall();
231
232 return _Py_CheckFunctionResult(callable, result, NULL);
233 }
234}
235
236
237/* --- PyFunction call functions ---------------------------------- */
238
239static PyObject* _Py_HOT_FUNCTION
240function_code_fastcall(PyCodeObject *co, PyObject **args, Py_ssize_t nargs,
241 PyObject *globals)
242{
243 PyFrameObject *f;
244 PyThreadState *tstate = PyThreadState_GET();
245 PyObject **fastlocals;
246 Py_ssize_t i;
247 PyObject *result;
248
249 assert(globals != NULL);
250 /* XXX Perhaps we should create a specialized
251 _PyFrame_New_NoTrack() that doesn't take locals, but does
252 take builtins without sanity checking them.
253 */
254 assert(tstate != NULL);
255 f = _PyFrame_New_NoTrack(tstate, co, globals, NULL);
256 if (f == NULL) {
257 return NULL;
258 }
259
260 fastlocals = f->f_localsplus;
261
262 for (i = 0; i < nargs; i++) {
263 Py_INCREF(*args);
264 fastlocals[i] = *args++;
265 }
266 result = PyEval_EvalFrameEx(f,0);
267
268 if (Py_REFCNT(f) > 1) {
269 Py_DECREF(f);
270 _PyObject_GC_TRACK(f);
271 }
272 else {
273 ++tstate->recursion_depth;
274 Py_DECREF(f);
275 --tstate->recursion_depth;
276 }
277 return result;
278}
279
280
281PyObject *
282_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs,
283 PyObject *kwargs)
284{
285 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
286 PyObject *globals = PyFunction_GET_GLOBALS(func);
287 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
288 PyObject *kwdefs, *closure, *name, *qualname;
289 PyObject *kwtuple, **k;
290 PyObject **d;
291 Py_ssize_t nd, nk;
292 PyObject *result;
293
294 assert(func != NULL);
295 assert(nargs >= 0);
296 assert(nargs == 0 || args != NULL);
297 assert(kwargs == NULL || PyDict_Check(kwargs));
298
299 if (co->co_kwonlyargcount == 0 &&
300 (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) &&
301 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE))
302 {
303 /* Fast paths */
304 if (argdefs == NULL && co->co_argcount == nargs) {
305 return function_code_fastcall(co, args, nargs, globals);
306 }
307 else if (nargs == 0 && argdefs != NULL
308 && co->co_argcount == Py_SIZE(argdefs)) {
309 /* function called with no arguments, but all parameters have
310 a default value: use default values as arguments .*/
311 args = &PyTuple_GET_ITEM(argdefs, 0);
312 return function_code_fastcall(co, args, Py_SIZE(argdefs), globals);
313 }
314 }
315
316 nk = (kwargs != NULL) ? PyDict_GET_SIZE(kwargs) : 0;
317 if (nk != 0) {
318 Py_ssize_t pos, i;
319
Victor Stinner561ca802017-02-23 18:26:43 +0100320 /* bpo-29318, bpo-27840: Caller and callee functions must not share
321 the dictionary: kwargs must be copied. */
Victor Stinnerc22bfaa2017-02-12 19:27:05 +0100322 kwtuple = PyTuple_New(2 * nk);
323 if (kwtuple == NULL) {
324 return NULL;
325 }
326
327 k = &PyTuple_GET_ITEM(kwtuple, 0);
328 pos = i = 0;
329 while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) {
330 /* We must hold strong references because keyword arguments can be
331 indirectly modified while the function is called:
332 see issue #2016 and test_extcall */
333 Py_INCREF(k[i]);
334 Py_INCREF(k[i+1]);
335 i += 2;
336 }
337 nk = i / 2;
338 }
339 else {
340 kwtuple = NULL;
341 k = NULL;
342 }
343
344 kwdefs = PyFunction_GET_KW_DEFAULTS(func);
345 closure = PyFunction_GET_CLOSURE(func);
346 name = ((PyFunctionObject *)func) -> func_name;
347 qualname = ((PyFunctionObject *)func) -> func_qualname;
348
349 if (argdefs != NULL) {
350 d = &PyTuple_GET_ITEM(argdefs, 0);
351 nd = Py_SIZE(argdefs);
352 }
353 else {
354 d = NULL;
355 nd = 0;
356 }
357
358 result = _PyEval_EvalCodeWithName((PyObject*)co, globals, (PyObject *)NULL,
359 args, nargs,
360 k, k + 1, nk, 2,
361 d, nd, kwdefs,
362 closure, name, qualname);
363 Py_XDECREF(kwtuple);
364 return result;
365}
366
367PyObject *
368_PyFunction_FastCallKeywords(PyObject *func, PyObject **stack,
369 Py_ssize_t nargs, PyObject *kwnames)
370{
371 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
372 PyObject *globals = PyFunction_GET_GLOBALS(func);
373 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
374 PyObject *kwdefs, *closure, *name, *qualname;
375 PyObject **d;
376 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
377 Py_ssize_t nd;
378
379 assert(PyFunction_Check(func));
380 assert(nargs >= 0);
381 assert(kwnames == NULL || PyTuple_CheckExact(kwnames));
382 assert((nargs == 0 && nkwargs == 0) || stack != NULL);
383 /* kwnames must only contains str strings, no subclass, and all keys must
384 be unique */
385
386 if (co->co_kwonlyargcount == 0 && nkwargs == 0 &&
387 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE))
388 {
389 if (argdefs == NULL && co->co_argcount == nargs) {
390 return function_code_fastcall(co, stack, nargs, globals);
391 }
392 else if (nargs == 0 && argdefs != NULL
393 && co->co_argcount == Py_SIZE(argdefs)) {
394 /* function called with no arguments, but all parameters have
395 a default value: use default values as arguments .*/
396 stack = &PyTuple_GET_ITEM(argdefs, 0);
397 return function_code_fastcall(co, stack, Py_SIZE(argdefs), globals);
398 }
399 }
400
401 kwdefs = PyFunction_GET_KW_DEFAULTS(func);
402 closure = PyFunction_GET_CLOSURE(func);
403 name = ((PyFunctionObject *)func) -> func_name;
404 qualname = ((PyFunctionObject *)func) -> func_qualname;
405
406 if (argdefs != NULL) {
407 d = &PyTuple_GET_ITEM(argdefs, 0);
408 nd = Py_SIZE(argdefs);
409 }
410 else {
411 d = NULL;
412 nd = 0;
413 }
414 return _PyEval_EvalCodeWithName((PyObject*)co, globals, (PyObject *)NULL,
415 stack, nargs,
416 nkwargs ? &PyTuple_GET_ITEM(kwnames, 0) : NULL,
417 stack + nargs,
418 nkwargs, 1,
419 d, (int)nd, kwdefs,
420 closure, name, qualname);
421}
422
423
424/* --- PyCFunction call functions --------------------------------- */
425
426PyObject *
427_PyMethodDef_RawFastCallDict(PyMethodDef *method, PyObject *self, PyObject **args,
428 Py_ssize_t nargs, PyObject *kwargs)
429{
430 /* _PyMethodDef_RawFastCallDict() must not be called with an exception set,
431 because it can clear it (directly or indirectly) and so the
432 caller loses its exception */
433 assert(!PyErr_Occurred());
434
435 assert(method != NULL);
436 assert(nargs >= 0);
437 assert(nargs == 0 || args != NULL);
438 assert(kwargs == NULL || PyDict_Check(kwargs));
439
440 PyCFunction meth = method->ml_meth;
441 int flags = method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST);
442 PyObject *result = NULL;
443
444 if (Py_EnterRecursiveCall(" while calling a Python object")) {
445 return NULL;
446 }
447
448 switch (flags)
449 {
450 case METH_NOARGS:
451 if (nargs != 0) {
452 PyErr_Format(PyExc_TypeError,
453 "%.200s() takes no arguments (%zd given)",
454 method->ml_name, nargs);
455 goto exit;
456 }
457
458 if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) {
459 goto no_keyword_error;
460 }
461
462 result = (*meth) (self, NULL);
463 break;
464
465 case METH_O:
466 if (nargs != 1) {
467 PyErr_Format(PyExc_TypeError,
468 "%.200s() takes exactly one argument (%zd given)",
469 method->ml_name, nargs);
470 goto exit;
471 }
472
473 if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) {
474 goto no_keyword_error;
475 }
476
477 result = (*meth) (self, args[0]);
478 break;
479
480 case METH_VARARGS:
481 if (!(flags & METH_KEYWORDS)
482 && kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) {
483 goto no_keyword_error;
484 }
485 /* fall through next case */
486
487 case METH_VARARGS | METH_KEYWORDS:
488 {
489 /* Slow-path: create a temporary tuple for positional arguments */
490 PyObject *argstuple = _PyStack_AsTuple(args, nargs);
491 if (argstuple == NULL) {
492 goto exit;
493 }
494
495 if (flags & METH_KEYWORDS) {
496 result = (*(PyCFunctionWithKeywords)meth) (self, argstuple, kwargs);
497 }
498 else {
499 result = (*meth) (self, argstuple);
500 }
501 Py_DECREF(argstuple);
502 break;
503 }
504
505 case METH_FASTCALL:
506 {
507 PyObject **stack;
508 PyObject *kwnames;
509 _PyCFunctionFast fastmeth = (_PyCFunctionFast)meth;
510
511 if (_PyStack_UnpackDict(args, nargs, kwargs, &stack, &kwnames) < 0) {
512 goto exit;
513 }
514
515 result = (*fastmeth) (self, stack, nargs, kwnames);
516 if (stack != args) {
517 PyMem_Free(stack);
518 }
519 Py_XDECREF(kwnames);
520 break;
521 }
522
523 default:
524 PyErr_SetString(PyExc_SystemError,
525 "Bad call flags in _PyMethodDef_RawFastCallDict. "
526 "METH_OLDARGS is no longer supported!");
527 goto exit;
528 }
529
530 goto exit;
531
532no_keyword_error:
533 PyErr_Format(PyExc_TypeError,
534 "%.200s() takes no keyword arguments",
535 method->ml_name, nargs);
536
537exit:
538 Py_LeaveRecursiveCall();
539 return result;
540}
541
542
543PyObject *
544_PyCFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs,
545 PyObject *kwargs)
546{
547 PyObject *result;
548
549 assert(func != NULL);
550 assert(PyCFunction_Check(func));
551
552 result = _PyMethodDef_RawFastCallDict(((PyCFunctionObject*)func)->m_ml,
553 PyCFunction_GET_SELF(func),
554 args, nargs, kwargs);
555 result = _Py_CheckFunctionResult(func, result, NULL);
556 return result;
557}
558
559
560PyObject *
561_PyMethodDef_RawFastCallKeywords(PyMethodDef *method, PyObject *self, PyObject **args,
562 Py_ssize_t nargs, PyObject *kwnames)
563{
564 /* _PyMethodDef_RawFastCallKeywords() must not be called with an exception set,
565 because it can clear it (directly or indirectly) and so the
566 caller loses its exception */
567 assert(!PyErr_Occurred());
568
569 assert(method != NULL);
570 assert(nargs >= 0);
571 assert(kwnames == NULL || PyTuple_CheckExact(kwnames));
572 /* kwnames must only contains str strings, no subclass, and all keys must
573 be unique */
574
575 PyCFunction meth = method->ml_meth;
576 int flags = method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST);
577 Py_ssize_t nkwargs = kwnames == NULL ? 0 : PyTuple_Size(kwnames);
578 PyObject *result = NULL;
579
580 if (Py_EnterRecursiveCall(" while calling a Python object")) {
581 return NULL;
582 }
583
584 switch (flags)
585 {
586 case METH_NOARGS:
587 if (nargs != 0) {
588 PyErr_Format(PyExc_TypeError,
589 "%.200s() takes no arguments (%zd given)",
590 method->ml_name, nargs);
591 goto exit;
592 }
593
594 if (nkwargs) {
595 goto no_keyword_error;
596 }
597
598 result = (*meth) (self, NULL);
599 break;
600
601 case METH_O:
602 if (nargs != 1) {
603 PyErr_Format(PyExc_TypeError,
604 "%.200s() takes exactly one argument (%zd given)",
605 method->ml_name, nargs);
606 goto exit;
607 }
608
609 if (nkwargs) {
610 goto no_keyword_error;
611 }
612
613 result = (*meth) (self, args[0]);
614 break;
615
616 case METH_FASTCALL:
617 /* Fast-path: avoid temporary dict to pass keyword arguments */
618 result = ((_PyCFunctionFast)meth) (self, args, nargs, kwnames);
619 break;
620
621 case METH_VARARGS:
622 case METH_VARARGS | METH_KEYWORDS:
623 {
624 /* Slow-path: create a temporary tuple for positional arguments
625 and a temporary dict for keyword arguments */
626 PyObject *argtuple;
627
628 if (!(flags & METH_KEYWORDS) && nkwargs) {
629 goto no_keyword_error;
630 }
631
632 argtuple = _PyStack_AsTuple(args, nargs);
633 if (argtuple == NULL) {
634 goto exit;
635 }
636
637 if (flags & METH_KEYWORDS) {
638 PyObject *kwdict;
639
640 if (nkwargs > 0) {
641 kwdict = _PyStack_AsDict(args + nargs, kwnames);
642 if (kwdict == NULL) {
643 Py_DECREF(argtuple);
644 goto exit;
645 }
646 }
647 else {
648 kwdict = NULL;
649 }
650
651 result = (*(PyCFunctionWithKeywords)meth) (self, argtuple, kwdict);
652 Py_XDECREF(kwdict);
653 }
654 else {
655 result = (*meth) (self, argtuple);
656 }
657 Py_DECREF(argtuple);
658 break;
659 }
660
661 default:
662 PyErr_SetString(PyExc_SystemError,
663 "Bad call flags in _PyCFunction_FastCallKeywords. "
664 "METH_OLDARGS is no longer supported!");
665 goto exit;
666 }
667
668 goto exit;
669
670no_keyword_error:
671 PyErr_Format(PyExc_TypeError,
672 "%.200s() takes no keyword arguments",
673 method->ml_name);
674
675exit:
676 Py_LeaveRecursiveCall();
677 return result;
678}
679
680
681PyObject *
682_PyCFunction_FastCallKeywords(PyObject *func, PyObject **args,
683 Py_ssize_t nargs, PyObject *kwnames)
684{
685 PyObject *result;
686
687 assert(func != NULL);
688 assert(PyCFunction_Check(func));
689
690 result = _PyMethodDef_RawFastCallKeywords(((PyCFunctionObject*)func)->m_ml,
691 PyCFunction_GET_SELF(func),
692 args, nargs, kwnames);
693 result = _Py_CheckFunctionResult(func, result, NULL);
694 return result;
695}
696
697
698static PyObject *
699cfunction_call_varargs(PyObject *func, PyObject *args, PyObject *kwargs)
700{
701 assert(!PyErr_Occurred());
702
703 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
704 PyObject *self = PyCFunction_GET_SELF(func);
705 PyObject *result;
706
707 if (PyCFunction_GET_FLAGS(func) & METH_KEYWORDS) {
708 if (Py_EnterRecursiveCall(" while calling a Python object")) {
709 return NULL;
710 }
711
712 result = (*(PyCFunctionWithKeywords)meth)(self, args, kwargs);
713
714 Py_LeaveRecursiveCall();
715 }
716 else {
717 if (kwargs != NULL && PyDict_Size(kwargs) != 0) {
718 PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
719 ((PyCFunctionObject*)func)->m_ml->ml_name);
720 return NULL;
721 }
722
723 if (Py_EnterRecursiveCall(" while calling a Python object")) {
724 return NULL;
725 }
726
727 result = (*meth)(self, args);
728
729 Py_LeaveRecursiveCall();
730 }
731
732 return _Py_CheckFunctionResult(func, result, NULL);
733}
734
735
736PyObject *
737PyCFunction_Call(PyObject *func, PyObject *args, PyObject *kwargs)
738{
739 /* first try METH_VARARGS to pass directly args tuple unchanged.
740 _PyMethodDef_RawFastCallDict() creates a new temporary tuple
741 for METH_VARARGS. */
742 if (PyCFunction_GET_FLAGS(func) & METH_VARARGS) {
743 return cfunction_call_varargs(func, args, kwargs);
744 }
745 else {
746 return _PyCFunction_FastCallDict(func,
747 &PyTuple_GET_ITEM(args, 0),
748 PyTuple_GET_SIZE(args),
749 kwargs);
750 }
751}
752
753
754/* --- More complex call functions -------------------------------- */
755
756/* External interface to call any callable object.
757 The args must be a tuple or NULL. The kwargs must be a dict or NULL. */
758PyObject *
759PyEval_CallObjectWithKeywords(PyObject *callable,
760 PyObject *args, PyObject *kwargs)
761{
762#ifdef Py_DEBUG
763 /* PyEval_CallObjectWithKeywords() must not be called with an exception
764 set. It raises a new exception if parameters are invalid or if
765 PyTuple_New() fails, and so the original exception is lost. */
766 assert(!PyErr_Occurred());
767#endif
768
INADA Naoki3824cd82017-03-01 20:41:03 +0900769 if (args != NULL && !PyTuple_Check(args)) {
Victor Stinnerc22bfaa2017-02-12 19:27:05 +0100770 PyErr_SetString(PyExc_TypeError,
771 "argument list must be a tuple");
772 return NULL;
773 }
774
775 if (kwargs != NULL && !PyDict_Check(kwargs)) {
776 PyErr_SetString(PyExc_TypeError,
777 "keyword list must be a dictionary");
778 return NULL;
779 }
780
INADA Naoki3824cd82017-03-01 20:41:03 +0900781 if (args == NULL) {
782 return _PyObject_FastCallDict(callable, NULL, 0, kwargs);
783 }
784 else {
785 return PyObject_Call(callable, args, kwargs);
786 }
Victor Stinnerc22bfaa2017-02-12 19:27:05 +0100787}
788
789
790PyObject *
791PyObject_CallObject(PyObject *callable, PyObject *args)
792{
793 return PyEval_CallObjectWithKeywords(callable, args, NULL);
794}
795
796
797/* Positional arguments are obj followed by args:
798 call callable(obj, *args, **kwargs) */
799PyObject *
800_PyObject_FastCall_Prepend(PyObject *callable,
801 PyObject *obj, PyObject **args, Py_ssize_t nargs)
802{
803 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
804 PyObject **args2;
805 PyObject *result;
806
807 nargs++;
808 if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
809 args2 = small_stack;
810 }
811 else {
812 args2 = PyMem_Malloc(nargs * sizeof(PyObject *));
813 if (args2 == NULL) {
814 PyErr_NoMemory();
815 return NULL;
816 }
817 }
818
819 /* use borrowed references */
820 args2[0] = obj;
821 memcpy(&args2[1],
822 args,
823 (nargs - 1)* sizeof(PyObject *));
824
825 result = _PyObject_FastCall(callable, args2, nargs);
826 if (args2 != small_stack) {
827 PyMem_Free(args2);
828 }
829 return result;
830}
831
832
833/* Call callable(obj, *args, **kwargs). */
834PyObject *
835_PyObject_Call_Prepend(PyObject *callable,
836 PyObject *obj, PyObject *args, PyObject *kwargs)
837{
838 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
839 PyObject **stack;
840 Py_ssize_t argcount;
841 PyObject *result;
842
843 assert(PyTuple_Check(args));
844
845 argcount = PyTuple_GET_SIZE(args);
846 if (argcount + 1 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
847 stack = small_stack;
848 }
849 else {
850 stack = PyMem_Malloc((argcount + 1) * sizeof(PyObject *));
851 if (stack == NULL) {
852 PyErr_NoMemory();
853 return NULL;
854 }
855 }
856
857 /* use borrowed references */
858 stack[0] = obj;
859 memcpy(&stack[1],
860 &PyTuple_GET_ITEM(args, 0),
861 argcount * sizeof(PyObject *));
862
863 result = _PyObject_FastCallDict(callable,
864 stack, argcount + 1,
865 kwargs);
866 if (stack != small_stack) {
867 PyMem_Free(stack);
868 }
869 return result;
870}
871
872
873/* --- Call with a format string ---------------------------------- */
874
875static PyObject *
876_PyObject_CallFunctionVa(PyObject *callable, const char *format,
877 va_list va, int is_size_t)
878{
879 PyObject* small_stack[_PY_FASTCALL_SMALL_STACK];
880 const Py_ssize_t small_stack_len = Py_ARRAY_LENGTH(small_stack);
881 PyObject **stack;
882 Py_ssize_t nargs, i;
883 PyObject *result;
884
885 if (callable == NULL) {
886 return null_error();
887 }
888
889 if (!format || !*format) {
890 return _PyObject_CallNoArg(callable);
891 }
892
893 if (is_size_t) {
894 stack = _Py_VaBuildStack_SizeT(small_stack, small_stack_len,
895 format, va, &nargs);
896 }
897 else {
898 stack = _Py_VaBuildStack(small_stack, small_stack_len,
899 format, va, &nargs);
900 }
901 if (stack == NULL) {
902 return NULL;
903 }
904
905 if (nargs == 1 && PyTuple_Check(stack[0])) {
906 /* Special cases for backward compatibility:
907 - PyObject_CallFunction(func, "O", tuple) calls func(*tuple)
908 - PyObject_CallFunction(func, "(OOO)", arg1, arg2, arg3) calls
909 func(*(arg1, arg2, arg3)): func(arg1, arg2, arg3) */
910 PyObject *args = stack[0];
911 result = _PyObject_FastCall(callable,
912 &PyTuple_GET_ITEM(args, 0),
913 PyTuple_GET_SIZE(args));
914 }
915 else {
916 result = _PyObject_FastCall(callable, stack, nargs);
917 }
918
919 for (i = 0; i < nargs; ++i) {
920 Py_DECREF(stack[i]);
921 }
922 if (stack != small_stack) {
923 PyMem_Free(stack);
924 }
925 return result;
926}
927
928
929PyObject *
930PyObject_CallFunction(PyObject *callable, const char *format, ...)
931{
932 va_list va;
933 PyObject *result;
934
935 va_start(va, format);
936 result = _PyObject_CallFunctionVa(callable, format, va, 0);
937 va_end(va);
938
939 return result;
940}
941
942
943PyObject *
944PyEval_CallFunction(PyObject *callable, const char *format, ...)
945{
946 va_list vargs;
947 PyObject *args;
948 PyObject *res;
949
950 va_start(vargs, format);
951
952 args = Py_VaBuildValue(format, vargs);
953 va_end(vargs);
954
955 if (args == NULL)
956 return NULL;
957
958 res = PyEval_CallObject(callable, args);
959 Py_DECREF(args);
960
961 return res;
962}
963
964
965PyObject *
966_PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...)
967{
968 va_list va;
969 PyObject *result;
970
971 va_start(va, format);
972 result = _PyObject_CallFunctionVa(callable, format, va, 1);
973 va_end(va);
974
975 return result;
976}
977
978
979static PyObject*
980callmethod(PyObject* callable, const char *format, va_list va, int is_size_t)
981{
982 assert(callable != NULL);
983
984 if (!PyCallable_Check(callable)) {
985 PyErr_Format(PyExc_TypeError,
986 "attribute of type '%.200s' is not callable",
987 Py_TYPE(callable)->tp_name);
988 return NULL;
989 }
990
991 return _PyObject_CallFunctionVa(callable, format, va, is_size_t);
992}
993
994
995PyObject *
996PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
997{
998 va_list va;
999 PyObject *callable, *retval;
1000
1001 if (obj == NULL || name == NULL) {
1002 return null_error();
1003 }
1004
1005 callable = PyObject_GetAttrString(obj, name);
1006 if (callable == NULL)
1007 return NULL;
1008
1009 va_start(va, format);
1010 retval = callmethod(callable, format, va, 0);
1011 va_end(va);
1012
1013 Py_DECREF(callable);
1014 return retval;
1015}
1016
1017
1018PyObject *
1019PyEval_CallMethod(PyObject *obj, const char *name, const char *format, ...)
1020{
1021 va_list vargs;
1022 PyObject *meth;
1023 PyObject *args;
1024 PyObject *res;
1025
1026 meth = PyObject_GetAttrString(obj, name);
1027 if (meth == NULL)
1028 return NULL;
1029
1030 va_start(vargs, format);
1031
1032 args = Py_VaBuildValue(format, vargs);
1033 va_end(vargs);
1034
1035 if (args == NULL) {
1036 Py_DECREF(meth);
1037 return NULL;
1038 }
1039
1040 res = PyEval_CallObject(meth, args);
1041 Py_DECREF(meth);
1042 Py_DECREF(args);
1043
1044 return res;
1045}
1046
1047
1048PyObject *
1049_PyObject_CallMethodId(PyObject *obj, _Py_Identifier *name,
1050 const char *format, ...)
1051{
1052 va_list va;
1053 PyObject *callable, *retval;
1054
1055 if (obj == NULL || name == NULL) {
1056 return null_error();
1057 }
1058
1059 callable = _PyObject_GetAttrId(obj, name);
1060 if (callable == NULL)
1061 return NULL;
1062
1063 va_start(va, format);
1064 retval = callmethod(callable, format, va, 0);
1065 va_end(va);
1066
1067 Py_DECREF(callable);
1068 return retval;
1069}
1070
1071
1072PyObject *
1073_PyObject_CallMethod_SizeT(PyObject *obj, const char *name,
1074 const char *format, ...)
1075{
1076 va_list va;
1077 PyObject *callable, *retval;
1078
1079 if (obj == NULL || name == NULL) {
1080 return null_error();
1081 }
1082
1083 callable = PyObject_GetAttrString(obj, name);
1084 if (callable == NULL)
1085 return NULL;
1086
1087 va_start(va, format);
1088 retval = callmethod(callable, format, va, 1);
1089 va_end(va);
1090
1091 Py_DECREF(callable);
1092 return retval;
1093}
1094
1095
1096PyObject *
1097_PyObject_CallMethodId_SizeT(PyObject *obj, _Py_Identifier *name,
1098 const char *format, ...)
1099{
1100 va_list va;
1101 PyObject *callable, *retval;
1102
1103 if (obj == NULL || name == NULL) {
1104 return null_error();
1105 }
1106
1107 callable = _PyObject_GetAttrId(obj, name);
1108 if (callable == NULL) {
1109 return NULL;
1110 }
1111
1112 va_start(va, format);
1113 retval = callmethod(callable, format, va, 1);
1114 va_end(va);
1115
1116 Py_DECREF(callable);
1117 return retval;
1118}
1119
1120
1121/* --- Call with "..." arguments ---------------------------------- */
1122
1123static PyObject *
1124object_vacall(PyObject *callable, va_list vargs)
1125{
1126 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
1127 PyObject **stack;
1128 Py_ssize_t nargs;
1129 PyObject *result;
1130 Py_ssize_t i;
1131 va_list countva;
1132
1133 if (callable == NULL) {
1134 return null_error();
1135 }
1136
1137 /* Count the number of arguments */
1138 va_copy(countva, vargs);
1139 nargs = 0;
1140 while (1) {
1141 PyObject *arg = va_arg(countva, PyObject *);
1142 if (arg == NULL) {
1143 break;
1144 }
1145 nargs++;
1146 }
1147 va_end(countva);
1148
1149 /* Copy arguments */
1150 if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1151 stack = small_stack;
1152 }
1153 else {
1154 stack = PyMem_Malloc(nargs * sizeof(stack[0]));
1155 if (stack == NULL) {
1156 PyErr_NoMemory();
1157 return NULL;
1158 }
1159 }
1160
1161 for (i = 0; i < nargs; ++i) {
1162 stack[i] = va_arg(vargs, PyObject *);
1163 }
1164
1165 /* Call the function */
1166 result = _PyObject_FastCall(callable, stack, nargs);
1167
1168 if (stack != small_stack) {
1169 PyMem_Free(stack);
1170 }
1171 return result;
1172}
1173
1174
1175PyObject *
1176PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
1177{
1178 va_list vargs;
1179 PyObject *result;
1180
1181 if (callable == NULL || name == NULL) {
1182 return null_error();
1183 }
1184
1185 callable = PyObject_GetAttr(callable, name);
1186 if (callable == NULL) {
1187 return NULL;
1188 }
1189
1190 va_start(vargs, name);
1191 result = object_vacall(callable, vargs);
1192 va_end(vargs);
1193
1194 Py_DECREF(callable);
1195 return result;
1196}
1197
1198
1199PyObject *
1200_PyObject_CallMethodIdObjArgs(PyObject *obj,
1201 struct _Py_Identifier *name, ...)
1202{
1203 va_list vargs;
1204 PyObject *callable, *result;
1205
1206 if (obj == NULL || name == NULL) {
1207 return null_error();
1208 }
1209
1210 callable = _PyObject_GetAttrId(obj, name);
1211 if (callable == NULL) {
1212 return NULL;
1213 }
1214
1215 va_start(vargs, name);
1216 result = object_vacall(callable, vargs);
1217 va_end(vargs);
1218
1219 Py_DECREF(callable);
1220 return result;
1221}
1222
1223
1224PyObject *
1225PyObject_CallFunctionObjArgs(PyObject *callable, ...)
1226{
1227 va_list vargs;
1228 PyObject *result;
1229
1230 va_start(vargs, callable);
1231 result = object_vacall(callable, vargs);
1232 va_end(vargs);
1233
1234 return result;
1235}
1236
1237
1238/* --- PyStack functions ------------------------------------------ */
1239
1240/* Issue #29234: Inlining _PyStack_AsTuple() into callers increases their
1241 stack consumption, Disable inlining to optimize the stack consumption. */
1242PyObject* _Py_NO_INLINE
1243_PyStack_AsTuple(PyObject **stack, Py_ssize_t nargs)
1244{
1245 PyObject *args;
1246 Py_ssize_t i;
1247
1248 args = PyTuple_New(nargs);
1249 if (args == NULL) {
1250 return NULL;
1251 }
1252
1253 for (i=0; i < nargs; i++) {
1254 PyObject *item = stack[i];
1255 Py_INCREF(item);
1256 PyTuple_SET_ITEM(args, i, item);
1257 }
1258 return args;
1259}
1260
1261
1262PyObject*
1263_PyStack_AsTupleSlice(PyObject **stack, Py_ssize_t nargs,
1264 Py_ssize_t start, Py_ssize_t end)
1265{
1266 PyObject *args;
1267 Py_ssize_t i;
1268
1269 assert(0 <= start);
1270 assert(end <= nargs);
1271 assert(start <= end);
1272
1273 args = PyTuple_New(end - start);
1274 if (args == NULL) {
1275 return NULL;
1276 }
1277
1278 for (i=start; i < end; i++) {
1279 PyObject *item = stack[i];
1280 Py_INCREF(item);
1281 PyTuple_SET_ITEM(args, i - start, item);
1282 }
1283 return args;
1284}
1285
1286
1287PyObject *
1288_PyStack_AsDict(PyObject **values, PyObject *kwnames)
1289{
1290 Py_ssize_t nkwargs;
1291 PyObject *kwdict;
1292 Py_ssize_t i;
1293
1294 assert(kwnames != NULL);
1295 nkwargs = PyTuple_GET_SIZE(kwnames);
1296 kwdict = _PyDict_NewPresized(nkwargs);
1297 if (kwdict == NULL) {
1298 return NULL;
1299 }
1300
1301 for (i = 0; i < nkwargs; i++) {
1302 PyObject *key = PyTuple_GET_ITEM(kwnames, i);
1303 PyObject *value = *values++;
1304 /* If key already exists, replace it with the new value */
1305 if (PyDict_SetItem(kwdict, key, value)) {
1306 Py_DECREF(kwdict);
1307 return NULL;
1308 }
1309 }
1310 return kwdict;
1311}
1312
1313
1314int
1315_PyStack_UnpackDict(PyObject **args, Py_ssize_t nargs, PyObject *kwargs,
1316 PyObject ***p_stack, PyObject **p_kwnames)
1317{
1318 PyObject **stack, **kwstack;
1319 Py_ssize_t nkwargs;
1320 Py_ssize_t pos, i;
1321 PyObject *key, *value;
1322 PyObject *kwnames;
1323
1324 assert(nargs >= 0);
1325 assert(kwargs == NULL || PyDict_CheckExact(kwargs));
1326
1327 if (kwargs == NULL || (nkwargs = PyDict_GET_SIZE(kwargs)) == 0) {
1328 *p_stack = args;
1329 *p_kwnames = NULL;
1330 return 0;
1331 }
1332
1333 if ((size_t)nargs > PY_SSIZE_T_MAX / sizeof(stack[0]) - (size_t)nkwargs) {
1334 PyErr_NoMemory();
1335 return -1;
1336 }
1337
1338 stack = PyMem_Malloc((nargs + nkwargs) * sizeof(stack[0]));
1339 if (stack == NULL) {
1340 PyErr_NoMemory();
1341 return -1;
1342 }
1343
1344 kwnames = PyTuple_New(nkwargs);
1345 if (kwnames == NULL) {
1346 PyMem_Free(stack);
1347 return -1;
1348 }
1349
1350 /* Copy position arguments (borrowed references) */
1351 memcpy(stack, args, nargs * sizeof(stack[0]));
1352
1353 kwstack = stack + nargs;
1354 pos = i = 0;
1355 /* This loop doesn't support lookup function mutating the dictionary
1356 to change its size. It's a deliberate choice for speed, this function is
1357 called in the performance critical hot code. */
1358 while (PyDict_Next(kwargs, &pos, &key, &value)) {
1359 Py_INCREF(key);
1360 PyTuple_SET_ITEM(kwnames, i, key);
1361 /* The stack contains borrowed references */
1362 kwstack[i] = value;
1363 i++;
1364 }
1365
1366 *p_stack = stack;
1367 *p_kwnames = kwnames;
1368 return 0;
1369}