Coverage Report

Created: 2026-06-09 06:53

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