Coverage Report

Created: 2026-11-30 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
41.9M
{
28
41.9M
    assert((callable != NULL) ^ (where != NULL));
29
30
41.9M
    if (result == NULL) {
31
3.23M
        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
3.23M
    }
48
38.7M
    else {
49
38.7M
        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
38.7M
    }
70
41.9M
    return result;
71
41.9M
}
72
73
74
int
75
_Py_CheckSlotResult(PyObject *obj, const char *slot_name, int success)
76
146M
{
77
146M
    PyThreadState *tstate = _PyThreadState_GET();
78
146M
    if (!success) {
79
6.40M
        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
6.40M
    }
86
139M
    else {
87
139M
        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
139M
    }
94
146M
    return 1;
95
146M
}
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
0
{
104
0
    EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, func);
105
0
    PyThreadState *tstate = _PyThreadState_GET();
106
0
    return _PyObject_VectorcallTstate(tstate, func, NULL, 0, NULL);
107
0
}
108
109
110
PyObject *
111
_PyObject_VectorcallDictTstate(PyThreadState *tstate, PyObject *callable,
112
                               PyObject *const *args, size_t nargsf,
113
                               PyObject *kwargs)
114
308k
{
115
308k
    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
308k
    assert(!_PyErr_Occurred(tstate));
121
122
308k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
123
308k
    assert(nargs >= 0);
124
308k
    assert(nargs == 0 || args != NULL);
125
308k
    assert(kwargs == NULL || PyDict_Check(kwargs));
126
127
308k
    vectorcallfunc func = PyVectorcall_Function(callable);
128
308k
    if (func == NULL) {
129
        /* Use tp_call instead */
130
2.66k
        return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwargs);
131
2.66k
    }
132
133
305k
    PyObject *res;
134
305k
    if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
135
304k
        res = func(callable, args, nargsf, NULL);
136
304k
    }
137
1.60k
    else {
138
1.60k
        PyObject *kwnames;
139
1.60k
        PyObject *const *newargs;
140
1.60k
        newargs = _PyStack_UnpackDict(tstate,
141
1.60k
                                      args, nargs,
142
1.60k
                                      kwargs, &kwnames);
143
1.60k
        if (newargs == NULL) {
144
0
            return NULL;
145
0
        }
146
1.60k
        res = func(callable, newargs,
147
1.60k
                   nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
148
1.60k
        _PyStack_UnpackDict_Free(newargs, nargs, kwnames);
149
1.60k
    }
150
305k
    return _Py_CheckFunctionResult(tstate, callable, res, NULL);
151
305k
}
152
153
154
PyObject *
155
PyObject_VectorcallDict(PyObject *callable, PyObject *const *args,
156
                       size_t nargsf, PyObject *kwargs)
157
12.6k
{
158
12.6k
    PyThreadState *tstate = _PyThreadState_GET();
159
12.6k
    return _PyObject_VectorcallDictTstate(tstate, callable, args, nargsf, kwargs);
160
12.6k
}
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
416k
{
204
416k
    assert(nargs >= 0);
205
416k
    assert(nargs == 0 || args != NULL);
206
416k
    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
416k
    ternaryfunc call = Py_TYPE(callable)->tp_call;
211
416k
    if (call == NULL) {
212
0
        object_is_not_callable(tstate, callable);
213
0
        return NULL;
214
0
    }
215
216
416k
    PyObject *argstuple = PyTuple_FromArray(args, nargs);
217
416k
    if (argstuple == NULL) {
218
0
        return NULL;
219
0
    }
220
221
416k
    PyObject *kwdict;
222
416k
    if (keywords == NULL || PyDict_Check(keywords)) {
223
414k
        kwdict = keywords;
224
414k
    }
225
1.98k
    else {
226
1.98k
        if (PyTuple_GET_SIZE(keywords)) {
227
1.98k
            assert(args != NULL);
228
1.98k
            kwdict = _PyStack_AsDict(args + nargs, keywords);
229
1.98k
            if (kwdict == NULL) {
230
0
                Py_DECREF(argstuple);
231
0
                return NULL;
232
0
            }
233
1.98k
        }
234
0
        else {
235
0
            keywords = kwdict = NULL;
236
0
        }
237
1.98k
    }
238
239
416k
    PyObject *result = NULL;
240
416k
    if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object") == 0)
241
416k
    {
242
416k
        result = _PyCFunctionWithKeywords_TrampolineCall(
243
416k
            (PyCFunctionWithKeywords)call, callable, argstuple, kwdict);
244
416k
        _Py_LeaveRecursiveCallTstate(tstate);
245
416k
    }
246
247
416k
    Py_DECREF(argstuple);
248
416k
    if (kwdict != keywords) {
249
1.98k
        Py_DECREF(kwdict);
250
1.98k
    }
251
252
416k
    return _Py_CheckFunctionResult(tstate, callable, result, NULL);
253
416k
}
254
255
256
vectorcallfunc
257
PyVectorcall_Function(PyObject *callable)
258
1.12M
{
259
1.12M
    return _PyVectorcall_FunctionInline(callable);
260
1.12M
}
261
262
263
static PyObject *
264
_PyVectorcall_Call(PyThreadState *tstate, vectorcallfunc func,
265
                   PyObject *callable, PyObject *tuple, PyObject *kwargs)
266
797k
{
267
797k
    assert(func != NULL);
268
269
797k
    Py_ssize_t nargs = PyTuple_GET_SIZE(tuple);
270
271
    /* Fast path for no keywords */
272
797k
    if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) {
273
797k
        return func(callable, _PyTuple_ITEMS(tuple), nargs, NULL);
274
797k
    }
275
276
    /* Convert arguments & call */
277
0
    PyObject *const *args;
278
0
    PyObject *kwnames;
279
0
    args = _PyStack_UnpackDict(tstate,
280
0
                               _PyTuple_ITEMS(tuple), nargs,
281
0
                               kwargs, &kwnames);
282
0
    if (args == NULL) {
283
0
        return NULL;
284
0
    }
285
0
    PyObject *result = func(callable, args,
286
0
                            nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
287
0
    _PyStack_UnpackDict_Free(args, nargs, kwnames);
288
289
0
    return _Py_CheckFunctionResult(tstate, callable, result, NULL);
290
0
}
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
1.87M
{
326
1.87M
    PyThreadState *tstate = _PyThreadState_GET();
327
1.87M
    return _PyObject_VectorcallTstate(tstate, callable,
328
1.87M
                                      args, nargsf, kwnames);
329
1.87M
}
330
331
332
PyObject *
333
_PyObject_Call(PyThreadState *tstate, PyObject *callable,
334
               PyObject *args, PyObject *kwargs)
335
820k
{
336
820k
    ternaryfunc call;
337
820k
    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
820k
    assert(!_PyErr_Occurred(tstate));
343
820k
    assert(PyTuple_Check(args));
344
820k
    assert(kwargs == NULL || PyDict_Check(kwargs));
345
820k
    EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, callable);
346
820k
    vectorcallfunc vector_func = PyVectorcall_Function(callable);
347
820k
    if (vector_func != NULL) {
348
797k
        return _PyVectorcall_Call(tstate, vector_func, callable, args, kwargs);
349
797k
    }
350
23.4k
    else {
351
23.4k
        call = Py_TYPE(callable)->tp_call;
352
23.4k
        if (call == NULL) {
353
0
            object_is_not_callable(tstate, callable);
354
0
            return NULL;
355
0
        }
356
357
23.4k
        if (_Py_EnterRecursiveCallTstate(tstate, " while calling a Python object")) {
358
0
            return NULL;
359
0
        }
360
361
23.4k
        result = (*call)(callable, args, kwargs);
362
363
23.4k
        _Py_LeaveRecursiveCallTstate(tstate);
364
365
23.4k
        return _Py_CheckFunctionResult(tstate, callable, result, NULL);
366
23.4k
    }
367
820k
}
368
369
PyObject *
370
PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
371
820k
{
372
820k
    PyThreadState *tstate = _PyThreadState_GET();
373
820k
    return _PyObject_Call(tstate, callable, args, kwargs);
374
820k
}
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
5.45M
{
388
5.45M
    EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, func);
389
5.45M
    assert(arg != NULL);
390
5.45M
    PyObject *_args[2];
391
5.45M
    PyObject **args = _args + 1;  // For PY_VECTORCALL_ARGUMENTS_OFFSET
392
5.45M
    args[0] = arg;
393
5.45M
    PyThreadState *tstate = _PyThreadState_GET();
394
5.45M
    size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
395
5.45M
    return _PyObject_VectorcallTstate(tstate, func, args, nargsf, NULL);
396
5.45M
}
397
398
399
/* --- PyFunction call functions ---------------------------------- */
400
401
PyObject *
402
_PyFunction_Vectorcall(PyObject *func, PyObject* const* stack,
403
                       size_t nargsf, PyObject *kwnames)
404
21.6M
{
405
21.6M
    assert(PyFunction_Check(func));
406
21.6M
    PyFunctionObject *f = (PyFunctionObject *)func;
407
21.6M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
408
21.6M
    assert(nargs >= 0);
409
21.6M
    PyThreadState *tstate = _PyThreadState_GET();
410
21.6M
    assert(nargs == 0 || stack != NULL);
411
21.6M
    EVAL_CALL_STAT_INC(EVAL_CALL_FUNCTION_VECTORCALL);
412
21.6M
    if (((PyCodeObject *)f->func_code)->co_flags & CO_OPTIMIZED) {
413
21.6M
        return _PyEval_Vector(tstate, f, NULL, stack, nargs, kwnames);
414
21.6M
    }
415
0
    else {
416
0
        return _PyEval_Vector(tstate, f, f->func_globals, stack, nargs, kwnames);
417
0
    }
418
21.6M
}
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
19.9k
{
462
19.9k
    PyThreadState *tstate = _PyThreadState_GET();
463
19.9k
    assert(!_PyErr_Occurred(tstate));
464
19.9k
    if (args == NULL) {
465
19.9k
        return _PyObject_CallNoArgsTstate(tstate, callable);
466
19.9k
    }
467
0
    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
0
    return _PyObject_Call(tstate, callable, args, NULL);
473
0
}
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
295k
{
481
295k
    assert(PyTuple_Check(args));
482
483
295k
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
484
295k
    PyObject **stack;
485
486
295k
    Py_ssize_t argcount = PyTuple_GET_SIZE(args);
487
295k
    if (argcount + 1 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
488
142k
        stack = small_stack;
489
142k
    }
490
153k
    else {
491
153k
        stack = PyMem_Malloc((argcount + 1) * sizeof(PyObject *));
492
153k
        if (stack == NULL) {
493
0
            PyErr_NoMemory();
494
0
            return NULL;
495
0
        }
496
153k
    }
497
498
    /* use borrowed references */
499
295k
    stack[0] = obj;
500
295k
    memcpy(&stack[1],
501
295k
           _PyTuple_ITEMS(args),
502
0
           argcount * sizeof(PyObject *));
503
504
0
    PyObject *result = _PyObject_VectorcallDictTstate(tstate, callable,
505
295k
                                                      stack, argcount + 1,
506
295k
                                                      kwargs);
507
295k
    if (stack != small_stack) {
508
153k
        PyMem_Free(stack);
509
153k
    }
510
295k
    return result;
511
295k
}
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
283k
{
520
283k
    PyObject* small_stack[_PY_FASTCALL_SMALL_STACK];
521
283k
    const Py_ssize_t small_stack_len = Py_ARRAY_LENGTH(small_stack);
522
283k
    PyObject **stack;
523
283k
    Py_ssize_t nargs, i;
524
283k
    PyObject *result;
525
526
283k
    if (callable == NULL) {
527
0
        return null_error(tstate);
528
0
    }
529
530
283k
    if (!format || !*format) {
531
0
        return _PyObject_CallNoArgsTstate(tstate, callable);
532
0
    }
533
534
283k
    stack = _Py_VaBuildStack(small_stack, small_stack_len,
535
283k
                             format, va, &nargs);
536
283k
    if (stack == NULL) {
537
0
        return NULL;
538
0
    }
539
283k
    EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, callable);
540
283k
    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
22
        PyObject *args = stack[0];
546
22
        result = _PyObject_VectorcallTstate(tstate, callable,
547
22
                                            _PyTuple_ITEMS(args),
548
22
                                            PyTuple_GET_SIZE(args),
549
22
                                            NULL);
550
22
    }
551
283k
    else {
552
283k
        result = _PyObject_VectorcallTstate(tstate, callable,
553
283k
                                            stack, nargs, NULL);
554
283k
    }
555
556
1.46M
    for (i = 0; i < nargs; ++i) {
557
1.18M
        Py_DECREF(stack[i]);
558
1.18M
    }
559
283k
    if (stack != small_stack) {
560
0
        PyMem_Free(stack);
561
0
    }
562
283k
    return result;
563
283k
}
564
565
566
PyObject *
567
PyObject_CallFunction(PyObject *callable, const char *format, ...)
568
283k
{
569
283k
    va_list va;
570
283k
    PyObject *result;
571
283k
    PyThreadState *tstate = _PyThreadState_GET();
572
573
283k
    va_start(va, format);
574
283k
    result = _PyObject_CallFunctionVa(tstate, callable, format, va);
575
283k
    va_end(va);
576
577
283k
    return result;
578
283k
}
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 *obj, PyObject *name,
617
           const char *format, va_list va)
618
46.6k
{
619
46.6k
    PyObject *result = NULL;
620
621
46.6k
    _PyCStackRef self, method;
622
46.6k
    _PyThreadState_PushCStackRef(tstate, &self);
623
46.6k
    _PyThreadState_PushCStackRef(tstate, &method);
624
46.6k
    self.ref = PyStackRef_FromPyObjectBorrow(obj);
625
626
46.6k
    int res = _PyObject_GetMethodStackRef(tstate, &self.ref, name, &method.ref);
627
46.6k
    if (res < 0) {
628
0
        goto exit;
629
0
    }
630
631
46.6k
    PyObject *callable = PyStackRef_AsPyObjectBorrow(method.ref);
632
46.6k
    PyObject *self_obj = PyStackRef_AsPyObjectBorrow(self.ref);
633
634
46.6k
    if (!PyCallable_Check(callable)) {
635
0
        _PyErr_Format(tstate, PyExc_TypeError,
636
0
                      "attribute of type '%.200s' is not callable",
637
0
                      Py_TYPE(callable)->tp_name);
638
0
        goto exit;
639
0
    }
640
641
    /* Build the positional arguments from the format string. */
642
46.6k
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
643
46.6k
    Py_ssize_t nargs = 0;
644
46.6k
    PyObject **built = NULL;
645
46.6k
    if (format != NULL && *format != '\0') {
646
44.4k
        built = _Py_VaBuildStack(small_stack, _PY_FASTCALL_SMALL_STACK,
647
44.4k
                                 format, va, &nargs);
648
44.4k
        if (built == NULL) {
649
0
            goto exit;
650
0
        }
651
44.4k
    }
652
653
    /* Backward compat: a single tuple from "O" is unpacked. */
654
46.6k
    PyObject *const *args = built;
655
46.6k
    Py_ssize_t n = nargs;
656
46.6k
    if (nargs == 1 && PyTuple_Check(built[0])) {
657
0
        args = _PyTuple_ITEMS(built[0]);
658
0
        n = PyTuple_GET_SIZE(built[0]);
659
0
    }
660
661
46.6k
    if (self_obj != NULL) {
662
23.9k
        result = _PyObject_VectorcallPrepend(tstate, callable, self_obj, args, n, NULL);
663
23.9k
    }
664
22.7k
    else {
665
22.7k
        result = _PyObject_VectorcallTstate(tstate, callable, args, n, NULL);
666
22.7k
    }
667
668
91.9k
    for (Py_ssize_t i = 0; i < nargs; i++) {
669
45.3k
        Py_DECREF(built[i]);
670
45.3k
    }
671
46.6k
    if (built != small_stack) {
672
2.27k
        PyMem_Free(built);
673
2.27k
    }
674
675
46.6k
exit:
676
46.6k
    _PyThreadState_PopCStackRef(tstate, &method);
677
46.6k
    _PyThreadState_PopCStackRef(tstate, &self);
678
46.6k
    return result;
679
46.6k
}
680
681
PyObject *
682
PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
683
46.5k
{
684
46.5k
    PyThreadState *tstate = _PyThreadState_GET();
685
686
46.5k
    if (obj == NULL || name == NULL) {
687
0
        return null_error(tstate);
688
0
    }
689
690
46.5k
    PyObject *name_obj = PyUnicode_FromString(name);
691
46.5k
    if (name_obj == NULL) {
692
0
        return NULL;
693
0
    }
694
695
46.5k
    va_list va;
696
46.5k
    va_start(va, format);
697
46.5k
    PyObject *retval = callmethod(tstate, obj, name_obj, format, va);
698
46.5k
    va_end(va);
699
700
46.5k
    Py_DECREF(name_obj);
701
46.5k
    return retval;
702
46.5k
}
703
704
705
/* PyEval_CallMethod is exact copy of PyObject_CallMethod.
706
   Function removed in Python 3.13 API but kept in the stable ABI. */
707
PyAPI_FUNC(PyObject*)
708
PyEval_CallMethod(PyObject *obj, const char *name, const char *format, ...)
709
0
{
710
0
    PyThreadState *tstate = _PyThreadState_GET();
711
0
    if (obj == NULL || name == NULL) {
712
0
        return null_error(tstate);
713
0
    }
714
715
0
    PyObject *name_obj = PyUnicode_FromString(name);
716
0
    if (name_obj == NULL) {
717
0
        return NULL;
718
0
    }
719
720
0
    va_list va;
721
0
    va_start(va, format);
722
0
    PyObject *retval = callmethod(tstate, obj, name_obj, format, va);
723
0
    va_end(va);
724
725
0
    Py_DECREF(name_obj);
726
0
    return retval;
727
0
}
728
729
730
PyObject *
731
_PyObject_CallMethod(PyObject *obj, PyObject *name,
732
                     const char *format, ...)
733
132
{
734
132
    PyThreadState *tstate = _PyThreadState_GET();
735
132
    if (obj == NULL || name == NULL) {
736
0
        return null_error(tstate);
737
0
    }
738
739
132
    va_list va;
740
132
    va_start(va, format);
741
132
    PyObject *retval = callmethod(tstate, obj, name, format, va);
742
132
    va_end(va);
743
744
132
    return retval;
745
132
}
746
747
748
PyObject *
749
_PyObject_CallMethodId(PyObject *obj, _Py_Identifier *name,
750
                       const char *format, ...)
751
0
{
752
0
    PyThreadState *tstate = _PyThreadState_GET();
753
0
    if (obj == NULL || name == NULL) {
754
0
        return null_error(tstate);
755
0
    }
756
757
0
_Py_COMP_DIAG_PUSH
758
0
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
759
0
    PyObject *name_obj = _PyUnicode_FromId(name); /* borrowed */
760
0
_Py_COMP_DIAG_POP
761
0
    if (name_obj == NULL) {
762
0
        return NULL;
763
0
    }
764
765
0
    va_list va;
766
0
    va_start(va, format);
767
0
    PyObject *retval = callmethod(tstate, obj, name_obj, format, va);
768
0
    va_end(va);
769
770
0
    return retval;
771
0
}
772
773
774
// _PyObject_CallMethod_SizeT is exact copy of PyObject_CallMethod.
775
// This function must be kept because it is part of the stable ABI.
776
PyAPI_FUNC(PyObject *)  /* abi_only */
777
_PyObject_CallMethod_SizeT(PyObject *obj, const char *name,
778
                           const char *format, ...)
779
0
{
780
0
    PyThreadState *tstate = _PyThreadState_GET();
781
0
    if (obj == NULL || name == NULL) {
782
0
        return null_error(tstate);
783
0
    }
784
785
0
    PyObject *name_obj = PyUnicode_FromString(name);
786
0
    if (name_obj == NULL) {
787
0
        return NULL;
788
0
    }
789
790
0
    va_list va;
791
0
    va_start(va, format);
792
0
    PyObject *retval = callmethod(tstate, obj, name_obj, format, va);
793
0
    va_end(va);
794
795
0
    Py_DECREF(name_obj);
796
0
    return retval;
797
0
}
798
799
800
/* --- Call with "..." arguments ---------------------------------- */
801
802
static PyObject *
803
object_vacall(PyThreadState *tstate, PyObject *base,
804
              PyObject *callable, va_list vargs)
805
164k
{
806
164k
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
807
164k
    PyObject **stack;
808
164k
    Py_ssize_t nargs;
809
164k
    PyObject *result;
810
164k
    Py_ssize_t i;
811
164k
    va_list countva;
812
813
164k
    if (callable == NULL) {
814
0
        return null_error(tstate);
815
0
    }
816
817
    /* Count the number of arguments */
818
164k
    va_copy(countva, vargs);
819
164k
    nargs = base ? 1 : 0;
820
1.36M
    while (1) {
821
1.36M
        PyObject *arg = va_arg(countva, PyObject *);
822
1.36M
        if (arg == NULL) {
823
164k
            break;
824
164k
        }
825
1.20M
        nargs++;
826
1.20M
    }
827
164k
    va_end(countva);
828
829
    /* Copy arguments */
830
164k
    if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
831
10.3k
        stack = small_stack;
832
10.3k
    }
833
153k
    else {
834
153k
        stack = PyMem_Malloc(nargs * sizeof(stack[0]));
835
153k
        if (stack == NULL) {
836
0
            PyErr_NoMemory();
837
0
            return NULL;
838
0
        }
839
153k
    }
840
841
164k
    i = 0;
842
164k
    if (base) {
843
0
        stack[i++] = base;
844
0
    }
845
846
1.36M
    for (; i < nargs; ++i) {
847
1.20M
        stack[i] = va_arg(vargs, PyObject *);
848
1.20M
    }
849
850
#ifdef Py_STATS
851
    if (PyFunction_Check(callable)) {
852
        EVAL_CALL_STAT_INC(EVAL_CALL_API);
853
    }
854
#endif
855
    /* Call the function */
856
164k
    result = _PyObject_VectorcallTstate(tstate, callable, stack, nargs, NULL);
857
858
164k
    if (stack != small_stack) {
859
153k
        PyMem_Free(stack);
860
153k
    }
861
164k
    return result;
862
164k
}
863
864
PyObject *
865
_PyObject_VectorcallPrepend(PyThreadState *tstate, PyObject *callable,
866
                            PyObject *arg, PyObject *const *args,
867
                            size_t nargsf, PyObject *kwnames)
868
59.8k
{
869
59.8k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
870
59.8k
    assert(nargs == 0 || args[nargs-1]);
871
872
59.8k
    PyObject *result;
873
59.8k
    if (nargsf & PY_VECTORCALL_ARGUMENTS_OFFSET) {
874
        /* PY_VECTORCALL_ARGUMENTS_OFFSET is set, so we are allowed to mutate the vector */
875
790
        PyObject **newargs = (PyObject**)args - 1;
876
790
        nargs += 1;
877
790
        PyObject *tmp = newargs[0];
878
790
        newargs[0] = arg;
879
790
        assert(newargs[nargs-1]);
880
790
        result = _PyObject_VectorcallTstate(tstate, callable, newargs,
881
790
                                            nargs, kwnames);
882
790
        newargs[0] = tmp;
883
790
    }
884
59.0k
    else {
885
59.0k
        Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
886
59.0k
        Py_ssize_t totalargs = nargs + nkwargs;
887
59.0k
        if (totalargs == 0) {
888
2.11k
            return _PyObject_VectorcallTstate(tstate, callable, &arg, 1, NULL);
889
2.11k
        }
890
891
56.9k
        PyObject *newargs_stack[_PY_FASTCALL_SMALL_STACK];
892
56.9k
        PyObject **newargs;
893
56.9k
        if (totalargs <= (Py_ssize_t)Py_ARRAY_LENGTH(newargs_stack) - 1) {
894
56.9k
            newargs = newargs_stack;
895
56.9k
        }
896
0
        else {
897
0
            newargs = PyMem_Malloc((totalargs+1) * sizeof(PyObject *));
898
0
            if (newargs == NULL) {
899
0
                _PyErr_NoMemory(tstate);
900
0
                return NULL;
901
0
            }
902
0
        }
903
        /* use borrowed references */
904
56.9k
        newargs[0] = arg;
905
        /* bpo-37138: since totalargs > 0, it's impossible that args is NULL.
906
         * We need this, since calling memcpy() with a NULL pointer is
907
         * undefined behaviour. */
908
56.9k
        assert(args != NULL);
909
56.9k
        memcpy(newargs + 1, args, totalargs * sizeof(PyObject *));
910
56.9k
        result = _PyObject_VectorcallTstate(tstate, callable,
911
56.9k
                                            newargs, nargs+1, kwnames);
912
56.9k
        if (newargs != newargs_stack) {
913
0
            PyMem_Free(newargs);
914
0
        }
915
56.9k
    }
916
57.7k
    return result;
917
59.8k
}
918
919
PyObject *
920
PyObject_VectorcallMethod(PyObject *name, PyObject *const *args,
921
                           size_t nargsf, PyObject *kwnames)
922
489k
{
923
489k
    assert(name != NULL);
924
489k
    assert(args != NULL);
925
489k
    assert(PyVectorcall_NARGS(nargsf) >= 1);
926
927
489k
    PyThreadState *tstate = _PyThreadState_GET();
928
489k
    _PyCStackRef self, method;
929
489k
    _PyThreadState_PushCStackRef(tstate, &self);
930
489k
    _PyThreadState_PushCStackRef(tstate, &method);
931
    /* Use args[0] as "self" argument */
932
489k
    self.ref = PyStackRef_FromPyObjectBorrow(args[0]);
933
489k
    int unbound = _PyObject_GetMethodStackRef(tstate, &self.ref, name, &method.ref);
934
489k
    if (unbound < 0) {
935
0
        _PyThreadState_PopCStackRef(tstate, &method);
936
0
        _PyThreadState_PopCStackRef(tstate, &self);
937
0
        return NULL;
938
0
    }
939
940
489k
    PyObject *callable = PyStackRef_AsPyObjectBorrow(method.ref);
941
489k
    PyObject *self_obj = PyStackRef_AsPyObjectBorrow(self.ref);
942
489k
    PyObject *result;
943
944
489k
    EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_METHOD, callable);
945
489k
    if (self_obj == NULL) {
946
        /* Skip "self". We can keep PY_VECTORCALL_ARGUMENTS_OFFSET since
947
         * args[-1] in the onward call is args[0] here. */
948
1.46k
        result = _PyObject_VectorcallTstate(tstate, callable,
949
1.46k
                                            args + 1, nargsf - 1, kwnames);
950
1.46k
    }
951
488k
    else if (self_obj == args[0]) {
952
        /* We must remove PY_VECTORCALL_ARGUMENTS_OFFSET since
953
         * that would be interpreted as allowing to change args[-1] */
954
488k
        result = _PyObject_VectorcallTstate(tstate, callable, args,
955
488k
                                            nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET,
956
488k
                                            kwnames);
957
488k
    }
958
0
    else {
959
        /* classmethod: self_obj is the type, not args[0]. Replace
960
         * args[0] with self_obj and call the underlying callable. */
961
0
        result = _PyObject_VectorcallPrepend(tstate, callable, self_obj,
962
0
                                             args + 1, nargsf - 1, kwnames);
963
0
    }
964
489k
    _PyThreadState_PopCStackRef(tstate, &method);
965
489k
    _PyThreadState_PopCStackRef(tstate, &self);
966
489k
    return result;
967
489k
}
968
969
970
PyObject *
971
PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)
972
1.53k
{
973
1.53k
    PyThreadState *tstate = _PyThreadState_GET();
974
1.53k
    if (obj == NULL || name == NULL) {
975
0
        return null_error(tstate);
976
0
    }
977
978
1.53k
    _PyCStackRef self, method;
979
1.53k
    _PyThreadState_PushCStackRef(tstate, &self);
980
1.53k
    _PyThreadState_PushCStackRef(tstate, &method);
981
1.53k
    self.ref = PyStackRef_FromPyObjectBorrow(obj);
982
1.53k
    int res = _PyObject_GetMethodStackRef(tstate, &self.ref, name, &method.ref);
983
1.53k
    if (res < 0) {
984
0
        _PyThreadState_PopCStackRef(tstate, &method);
985
0
        _PyThreadState_PopCStackRef(tstate, &self);
986
0
        return NULL;
987
0
    }
988
1.53k
    PyObject *callable = PyStackRef_AsPyObjectBorrow(method.ref);
989
1.53k
    PyObject *self_obj = PyStackRef_AsPyObjectBorrow(self.ref);
990
991
1.53k
    va_list vargs;
992
1.53k
    va_start(vargs, name);
993
1.53k
    PyObject *result = object_vacall(tstate, self_obj, callable, vargs);
994
1.53k
    va_end(vargs);
995
996
1.53k
    _PyThreadState_PopCStackRef(tstate, &method);
997
1.53k
    _PyThreadState_PopCStackRef(tstate, &self);
998
1.53k
    return result;
999
1.53k
}
1000
1001
1002
PyObject *
1003
PyObject_CallFunctionObjArgs(PyObject *callable, ...)
1004
162k
{
1005
162k
    PyThreadState *tstate = _PyThreadState_GET();
1006
162k
    va_list vargs;
1007
162k
    PyObject *result;
1008
1009
162k
    va_start(vargs, callable);
1010
162k
    result = object_vacall(tstate, NULL, callable, vargs);
1011
162k
    va_end(vargs);
1012
1013
162k
    return result;
1014
162k
}
1015
1016
1017
/* --- PyStack functions ------------------------------------------ */
1018
1019
PyObject *
1020
_PyStack_AsDict(PyObject *const *values, PyObject *kwnames)
1021
2.24k
{
1022
2.24k
    Py_ssize_t nkwargs;
1023
1024
2.24k
    assert(kwnames != NULL);
1025
2.24k
    nkwargs = PyTuple_GET_SIZE(kwnames);
1026
2.24k
    return _PyDict_FromItems(&PyTuple_GET_ITEM(kwnames, 0), 1,
1027
2.24k
                             values, 1, nkwargs);
1028
2.24k
}
1029
1030
1031
/* Convert (args, nargs, kwargs: dict) into a (stack, nargs, kwnames: tuple).
1032
1033
   Allocate a new argument vector and keyword names tuple. Return the argument
1034
   vector; return NULL with exception set on error. Return the keyword names
1035
   tuple in *p_kwnames.
1036
1037
   This also checks that all keyword names are strings. If not, a TypeError is
1038
   raised.
1039
1040
   The newly allocated argument vector supports PY_VECTORCALL_ARGUMENTS_OFFSET.
1041
1042
   The positional arguments are borrowed references from the input array
1043
   (which must be kept alive by the caller). The keyword argument values
1044
   are new references.
1045
1046
   When done, you must call _PyStack_UnpackDict_Free(stack, nargs, kwnames) */
1047
PyObject *const *
1048
_PyStack_UnpackDict(PyThreadState *tstate,
1049
                    PyObject *const *args, Py_ssize_t nargs,
1050
                    PyObject *kwargs, PyObject **p_kwnames)
1051
1.60k
{
1052
1.60k
    assert(nargs >= 0);
1053
1.60k
    assert(kwargs != NULL);
1054
1.60k
    assert(PyDict_Check(kwargs));
1055
1056
1.60k
    Py_ssize_t nkwargs = PyDict_GET_SIZE(kwargs);
1057
    /* Check for overflow in the PyMem_Malloc() call below. The subtraction
1058
     * in this check cannot overflow: both maxnargs and nkwargs are
1059
     * non-negative signed integers, so their difference fits in the type. */
1060
1.60k
    Py_ssize_t maxnargs = PY_SSIZE_T_MAX / sizeof(args[0]) - 1;
1061
1.60k
    if (nargs > maxnargs - nkwargs) {
1062
0
        _PyErr_NoMemory(tstate);
1063
0
        return NULL;
1064
0
    }
1065
1066
    /* Add 1 to support PY_VECTORCALL_ARGUMENTS_OFFSET */
1067
1.60k
    PyObject **stack = PyMem_Malloc((1 + nargs + nkwargs) * sizeof(args[0]));
1068
1.60k
    if (stack == NULL) {
1069
0
        _PyErr_NoMemory(tstate);
1070
0
        return NULL;
1071
0
    }
1072
1073
1.60k
    PyObject *kwnames = PyTuple_New(nkwargs);
1074
1.60k
    if (kwnames == NULL) {
1075
0
        PyMem_Free(stack);
1076
0
        return NULL;
1077
0
    }
1078
1079
1.60k
    stack++;  /* For PY_VECTORCALL_ARGUMENTS_OFFSET */
1080
1081
    /* Copy positional arguments (borrowed references) */
1082
5.47k
    for (Py_ssize_t i = 0; i < nargs; i++) {
1083
3.86k
        stack[i] = args[i];
1084
3.86k
    }
1085
1086
1.60k
    PyObject **kwstack = stack + nargs;
1087
    /* This loop doesn't support lookup function mutating the dictionary
1088
       to change its size. It's a deliberate choice for speed, this function is
1089
       called in the performance critical hot code. */
1090
1.60k
    Py_ssize_t pos = 0, i = 0;
1091
1.60k
    PyObject *key, *value;
1092
1.60k
    unsigned long keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS;
1093
6.75k
    while (PyDict_Next(kwargs, &pos, &key, &value)) {
1094
5.15k
        keys_are_strings &= Py_TYPE(key)->tp_flags;
1095
5.15k
        PyTuple_SET_ITEM(kwnames, i, Py_NewRef(key));
1096
5.15k
        kwstack[i] = Py_NewRef(value);
1097
5.15k
        i++;
1098
5.15k
    }
1099
1100
    /* keys_are_strings has the value Py_TPFLAGS_UNICODE_SUBCLASS if that
1101
     * flag is set for all keys. Otherwise, keys_are_strings equals 0.
1102
     * We do this check once at the end instead of inside the loop above
1103
     * because it simplifies the deallocation in the failing case.
1104
     * It happens to also make the loop above slightly more efficient. */
1105
1.60k
    if (!keys_are_strings) {
1106
0
        _PyErr_SetString(tstate, PyExc_TypeError,
1107
0
                         "keywords must be strings");
1108
0
        _PyStack_UnpackDict_Free(stack, nargs, kwnames);
1109
0
        return NULL;
1110
0
    }
1111
1112
1.60k
    *p_kwnames = kwnames;
1113
1.60k
    return stack;
1114
1.60k
}
1115
1116
void
1117
_PyStack_UnpackDict_Free(PyObject *const *stack, Py_ssize_t nargs,
1118
                         PyObject *kwnames)
1119
1.60k
{
1120
    /* Only decref kwargs values, positional args are borrowed */
1121
1.60k
    Py_ssize_t nkwargs = PyTuple_GET_SIZE(kwnames);
1122
6.75k
    for (Py_ssize_t i = 0; i < nkwargs; i++) {
1123
5.15k
        Py_DECREF(stack[nargs + i]);
1124
5.15k
    }
1125
1.60k
    _PyStack_UnpackDict_FreeNoDecRef(stack, kwnames);
1126
1.60k
}
1127
1128
void
1129
_PyStack_UnpackDict_FreeNoDecRef(PyObject *const *stack, PyObject *kwnames)
1130
1.60k
{
1131
1.60k
    PyMem_Free((PyObject **)stack - 1);
1132
1.60k
    Py_DECREF(kwnames);
1133
1.60k
}
1134
1135
// Export for the stable ABI
1136
#undef PyVectorcall_NARGS
1137
Py_ssize_t
1138
PyVectorcall_NARGS(size_t n)
1139
0
{
1140
0
    return _PyVectorcall_NARGS(n);
1141
0
}