diff --git a/Include/internal/pycore_ceval.h b/Include/internal/pycore_ceval.h index c404fc6e67d193..dc2b0a34176fe6 100644 --- a/Include/internal/pycore_ceval.h +++ b/Include/internal/pycore_ceval.h @@ -298,6 +298,7 @@ PyAPI_FUNC(void) _PyEval_FormatAwaitableError(PyThreadState *tstate, PyTypeObjec PyAPI_FUNC(void) _PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc, const char *format_str, PyObject *obj); PyAPI_FUNC(void) _PyEval_FormatExcUnbound(PyThreadState *tstate, PyCodeObject *co, int oparg); PyAPI_FUNC(void) _PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwargs, PyObject *dupkey); +PyAPI_FUNC(int) _PyEval_MergeKwargs(PyThreadState *tstate, PyObject *func, PyObject *dict, PyObject *kwargs); PyAPI_FUNC(PyObject *) _PyEval_ImportFrom(PyThreadState *, PyObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyEval_LazyImportName( diff --git a/Include/internal/pycore_magic_number.h b/Include/internal/pycore_magic_number.h index 041256df56b493..ab4f5b36ed639f 100644 --- a/Include/internal/pycore_magic_number.h +++ b/Include/internal/pycore_magic_number.h @@ -306,6 +306,7 @@ Known values: Python 3.16a1 3706 (Add INTRINSIC_MATCH_CLASS_ISINSTANCE) Python 3.16a1 3707 (GET_AWAITABLE also pushes NULL and None for SEND) Python 3.16a1 3708 (GET_ANEXT also pushes NULL and None for SEND) + Python 3.16a1 3709 (Push a lone ** call argument without DICT_MERGE) Python 3.17 will start with 3750 @@ -315,7 +316,7 @@ Known values: */ -#define PYC_MAGIC_NUMBER 3708 +#define PYC_MAGIC_NUMBER 3709 /* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes (little-endian) and then appending b'\r\n'. */ #define PYC_MAGIC_NUMBER_TOKEN \ diff --git a/Lib/test/test_call.py b/Lib/test/test_call.py index 8d8b7f9bbc38fb..98ebc245602a1d 100644 --- a/Lib/test/test_call.py +++ b/Lib/test/test_call.py @@ -95,6 +95,71 @@ def test_kwargs_order_preserved_in_c_functions(self): self.assertEqual(list(collections.OrderedDict(b=1, a=2, c=3)), ['b', 'a', 'c']) + def test_kwargs_unpacking_mutation_isolated(self): + # gh-86199: a callee mutating its **kwargs must never affect the + # caller's dict. + def fn(**kw): + kw['injected'] = None + d = {'a': 1} + fn(**d) + self.assertEqual(d, {'a': 1}) + e = {} + fn(**e) + self.assertEqual(e, {}) + + @cpython_only + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_kwargs_unpacking_not_aliased_in_tp_call(self): + # gh-86199: a tp_call callee receives a private copy of the kwargs + # dict, never the caller's dict. + get_kwargs = _testcapi.get_kwargs # METH_VARARGS | METH_KEYWORDS + d = {'a': 1} + self.assertIsNot(get_kwargs(**d), d) + self.assertEqual(get_kwargs(**d), d) + e = {} + self.assertIsNot(get_kwargs(**e), e) + + @cpython_only + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_vectorcalldict_kwargs_not_aliased_in_tp_call(self): + # gh-86795: PyObject_VectorcallDict() must not hand the caller's + # kwargs dict to a tp_call callee either. + get_kwargs = _testcapi.get_kwargs # METH_VARARGS | METH_KEYWORDS + d = {'a': 1} + res = _testcapi.pyobject_fastcalldict(get_kwargs, (), d) + self.assertEqual(res, d) + self.assertIsNot(res, d) + + @cpython_only + def test_kwargs_merge_saves_stack_pointer(self): + # gh-86199: DICT_MERGE can run arbitrary code (the keys() and + # __getitem__() of the mapping), so the frame's stack pointer must + # be saved first: the mapping has to be visible to the GC. + visible = [] + + class Mapping: + def keys(self): + referents = gc.get_referents(gen) + visible.append(any(x is self for x in referents)) + gc.collect() + return ['b'] + + def __getitem__(self, key): + return 2 + + def fn(**kw): + return kw + + mapping = Mapping() + + def caller(): + d = {'a': 1} + yield fn(**d, **mapping) + + gen = caller() + self.assertEqual(next(gen), {'a': 1, 'b': 2}) + self.assertEqual(visible, [True]) + def test_frames_are_popped_after_failed_calls(self): # GH-93252: stuff blows up if we don't pop the new frame after # recovering from failed calls: diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 88077aacecbf5b..3fc867112cffcd 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -6151,11 +6151,12 @@ def testfunc(n): def test_dict_merge(self): def testfunc(n): - d = {"a": 1, "b": 2} + d = {"a": 1} + e = {"b": 2} def f(**kwargs): return kwargs for _ in range(n): - x = f(**d) + x = f(**d, **e) return x res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD) @@ -6166,6 +6167,23 @@ def f(**kwargs): self.assertGreaterEqual(count_ops(ex, "_POP_TOP_NOP"), 1) self.assertLessEqual(count_ops(ex, "_POP_TOP"), 2) + def test_call_function_ex_single_kwargs_unpack(self): + # gh-86199: f(**d) no longer copies d with DICT_MERGE + def testfunc(n): + d = {"a": 1, "b": 2} + def f(**kwargs): + return kwargs + for _ in range(n): + x = f(**d) + return x + + res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD) + self.assertEqual(res, {"a": 1, "b": 2}) + uops = get_opnames(ex) + + self.assertNotIn("_DICT_MERGE", uops) + self.assertIn("_MAKE_CALLARGS_A_TUPLE", uops) + def test_list_extend(self): def testfunc(n): a = [1, 2, 3] diff --git a/Lib/test/test_free_threading/test_kwargs_unpack.py b/Lib/test/test_free_threading/test_kwargs_unpack.py new file mode 100644 index 00000000000000..eaa8103d784858 --- /dev/null +++ b/Lib/test/test_free_threading/test_kwargs_unpack.py @@ -0,0 +1,45 @@ +import unittest +from unittest import TestCase + +from test.support import threading_helper, import_helper + +_testcapi = import_helper.import_module("_testcapi") + +threading_helper.requires_working_threading(module=True) + + +class TestKwargsUnpackRace(TestCase): + def test_mutate_kwargs_during_unpack(self): + # gh-86199: unpacking a shared kwargs dict must tolerate another + # thread resizing it. + num_mutators, num_callers = 2, 6 + iters = 1000 + min_keys, max_keys = 4, 3000 + + fastcalldict = _testcapi.pyobject_fastcalldict + + def target(**kwargs): + return len(kwargs) + + shared = {f"k{i}": i for i in range(min_keys)} + + def resize_kwargs(): + for _ in range(iters): + for i in range(min_keys, max_keys): + shared[f"k{i}"] = i + for i in range(max_keys - 1, min_keys - 1, -1): + shared.pop(f"k{i}", None) + + def call_target(): + for _ in range(iters): + try: + fastcalldict(target, (), shared) + except Exception: + pass + + threading_helper.run_concurrently( + [resize_kwargs] * num_mutators + [call_target] * num_callers) + + +if __name__ == "__main__": + unittest.main() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-24-23-59-00.gh-issue-86199.pQk3vX.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-24-23-59-00.gh-issue-86199.pQk3vX.rst new file mode 100644 index 00000000000000..2202a80da2ef98 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-24-23-59-00.gh-issue-86199.pQk3vX.rst @@ -0,0 +1,7 @@ +Speed up calls of the form ``f(**kwargs)`` by no longer always copying the +keyword arguments before the call; such calls are now up to 1.4x faster. +This also fixes :c:func:`PyObject_Call` and :c:func:`PyObject_VectorcallDict` +to copy the keyword arguments before passing them to a callee that would +otherwise receive the caller's dict, so a called object can no longer mutate +the caller's dict (:gh:`86795`), and makes unpacking a shared +keyword-arguments dict safe on the free-threaded build. diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 8bb3f857437792..4773982e7fd98f 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -2772,6 +2772,7 @@ _PyStackRef func_st; _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef null; _PyStackRef callargs_st; _PyStackRef kwargs_st; @@ -2789,6 +2790,7 @@ } // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; func = func_st; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); @@ -2815,10 +2817,40 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _CALL_FUNCTION_EX_NON_PY_GENERAL { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; null = stack_pointer[-3]; func_st = func; @@ -2885,6 +2917,7 @@ static_assert(INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX == 1, "incorrect cache size"); _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef func_st; _PyStackRef callargs_st; _PyStackRef kwargs_st; @@ -2901,6 +2934,7 @@ } // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; func = stack_pointer[-4]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); @@ -2927,6 +2961,36 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _CHECK_IS_PY_CALLABLE_EX { @@ -2945,7 +3009,7 @@ } // _PY_FRAME_EX { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; PyObject *func = PyStackRef_AsPyObjectBorrow(func_st); PyObject *callargs = PyStackRef_AsPyObjectSteal(callargs_st); @@ -3018,6 +3082,7 @@ opcode = CALL_FUNCTION_EX; _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef func_st; _PyStackRef null; _PyStackRef callargs_st; @@ -3043,6 +3108,7 @@ } // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); if (!PyTuple_CheckExact(callargs_o)) { @@ -3068,10 +3134,40 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _DO_CALL_FUNCTION_EX { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; null = stack_pointer[-3]; func_st = func; @@ -5962,20 +6058,11 @@ PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); PyObject *dict_o = PyStackRef_AsPyObjectBorrow(dict); PyObject *update_o = PyStackRef_AsPyObjectBorrow(update); - PyObject *dupkey = NULL; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = _PyDict_MergeUniq(dict_o, update_o, &dupkey); + int err = _PyEval_MergeKwargs(tstate, callable_o, dict_o, update_o); _PyFrame_StackPointerInvalidate(frame); if (err < 0) { - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyEval_FormatKwargsError(tstate, callable_o, update_o, dupkey); - _PyFrame_StackPointerInvalidate(frame); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - Py_XDECREF(dupkey); - _PyFrame_StackPointerInvalidate(frame); JUMP_TO_LABEL(error); } u = update; @@ -7251,6 +7338,7 @@ opcode = INSTRUMENTED_CALL_FUNCTION_EX; _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef func_st; _PyStackRef null; _PyStackRef callargs_st; @@ -7259,6 +7347,7 @@ /* Skip 1 cache entry */ // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; func = stack_pointer[-4]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); @@ -7285,10 +7374,40 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _DO_CALL_FUNCTION_EX { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; null = stack_pointer[-3]; func_st = func; diff --git a/Objects/call.c b/Objects/call.c index a79f167aacc8c0..518b08157cd5b2 100644 --- a/Objects/call.c +++ b/Objects/call.c @@ -1,6 +1,7 @@ #include "Python.h" #include "pycore_call.h" // _PyObject_CallNoArgsTstate() #include "pycore_ceval.h" // _Py_EnterRecursiveCallTstate() +#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION() #include "pycore_dict.h" // _PyDict_FromItems() #include "pycore_function.h" // _PyFunction_Vectorcall() definition #include "pycore_modsupport.h" // _Py_VaBuildStack() @@ -219,8 +220,22 @@ _PyObject_MakeTpCall(PyThreadState *tstate, PyObject *callable, } PyObject *kwdict; - if (keywords == NULL || PyDict_Check(keywords)) { - kwdict = keywords; + if (keywords == NULL) { + kwdict = NULL; + } + else if (PyDict_Check(keywords)) { + /* Pass tp_call a copy of the dict so that the callee cannot + mutate the caller's dict. */ + if (PyDict_GET_SIZE(keywords)) { + kwdict = PyDict_Copy(keywords); + if (kwdict == NULL) { + Py_DECREF(argstuple); + return NULL; + } + } + else { + keywords = kwdict = NULL; + } } else { if (PyTuple_GET_SIZE(keywords)) { @@ -358,10 +373,23 @@ _PyObject_Call(PyThreadState *tstate, PyObject *callable, return NULL; } - result = (*call)(callable, args, kwargs); + /* Pass tp_call a copy of kwargs so that the callee cannot + mutate the caller's dict (gh-86199, gh-86795). */ + PyObject *kwcopy = NULL; + if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) { + kwcopy = PyDict_Copy(kwargs); + if (kwcopy == NULL) { + _Py_LeaveRecursiveCallTstate(tstate); + return NULL; + } + } + + result = (*call)(callable, args, kwcopy); _Py_LeaveRecursiveCallTstate(tstate); + Py_XDECREF(kwcopy); + return _Py_CheckFunctionResult(tstate, callable, result, NULL); } } @@ -1053,7 +1081,11 @@ _PyStack_UnpackDict(PyThreadState *tstate, assert(kwargs != NULL); assert(PyDict_Check(kwargs)); + PyObject **stack; + PyObject *kwnames; Py_ssize_t nkwargs = PyDict_GET_SIZE(kwargs); + +retry:; /* Check for overflow in the PyMem_Malloc() call below. The subtraction * in this check cannot overflow: both maxnargs and nkwargs are * non-negative signed integers, so their difference fits in the type. */ @@ -1064,13 +1096,13 @@ _PyStack_UnpackDict(PyThreadState *tstate, } /* Add 1 to support PY_VECTORCALL_ARGUMENTS_OFFSET */ - PyObject **stack = PyMem_Malloc((1 + nargs + nkwargs) * sizeof(args[0])); + stack = PyMem_Malloc((1 + nargs + nkwargs) * sizeof(args[0])); if (stack == NULL) { _PyErr_NoMemory(tstate); return NULL; } - PyObject *kwnames = PyTuple_New(nkwargs); + kwnames = PyTuple_New(nkwargs); if (kwnames == NULL) { PyMem_Free(stack); return NULL; @@ -1084,17 +1116,28 @@ _PyStack_UnpackDict(PyThreadState *tstate, } PyObject **kwstack = stack + nargs; - /* This loop doesn't support lookup function mutating the dictionary - to change its size. It's a deliberate choice for speed, this function is - called in the performance critical hot code. */ + /* Copy the items out under the dict's lock. The loop allocates + nothing, so the critical section is never suspended mid-loop. */ Py_ssize_t pos = 0, i = 0; PyObject *key, *value; unsigned long keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; - while (PyDict_Next(kwargs, &pos, &key, &value)) { - keys_are_strings &= Py_TYPE(key)->tp_flags; - PyTuple_SET_ITEM(kwnames, i, Py_NewRef(key)); - kwstack[i] = Py_NewRef(value); - i++; + Py_BEGIN_CRITICAL_SECTION(kwargs); + if (PyDict_GET_SIZE(kwargs) == nkwargs) { + while (PyDict_Next(kwargs, &pos, &key, &value)) { + keys_are_strings &= Py_TYPE(key)->tp_flags; + PyTuple_SET_ITEM(kwnames, i, Py_NewRef(key)); + kwstack[i] = Py_NewRef(value); + i++; + } + } + Py_END_CRITICAL_SECTION(); + if (i != nkwargs) { + /* Resized before we locked it; redo with the new size. */ + assert(i == 0); + PyMem_Free(stack - 1); + Py_DECREF(kwnames); + nkwargs = PyDict_GET_SIZE(kwargs); + goto retry; } /* keys_are_strings has the value Py_TPFLAGS_UNICODE_SUBCLASS if that diff --git a/Python/bytecodes.c b/Python/bytecodes.c index c6f1f61f3e08fe..647b9c19b436f0 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -2614,12 +2614,9 @@ dummy_func( PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); PyObject *dict_o = PyStackRef_AsPyObjectBorrow(dict); PyObject *update_o = PyStackRef_AsPyObjectBorrow(update); - PyObject *dupkey = NULL; - int err = _PyDict_MergeUniq(dict_o, update_o, &dupkey); + int err = _PyEval_MergeKwargs(tstate, callable_o, dict_o, update_o); if (err < 0) { - _PyEval_FormatKwargsError(tstate, callable_o, update_o, dupkey); - Py_XDECREF(dupkey); ERROR_NO_POP(); } u = update; @@ -5603,13 +5600,29 @@ dummy_func( callargs = PyStackRef_FromPyObjectSteal(tuple_o); PyStackRef_CLOSE(temp); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + PyObject *dict_o = PyDict_New(); + if (dict_o == NULL) { + ERROR_NO_POP(); + } + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + if (err < 0) { + Py_DECREF(dict_o); + ERROR_NO_POP(); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + PyStackRef_CLOSE(temp); + } } op(_DO_CALL_FUNCTION_EX, (func_st, null, callargs_st, kwargs_st -- result)) { (void)null; PyObject *func = PyStackRef_AsPyObjectBorrow(func_st); - // DICT_MERGE is called before this opcode if there are kwargs. + // _MAKE_CALLARGS_A_TUPLE is called before this op. // It converts all dict subtypes in kwargs into regular dicts. EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_FUNCTION_EX, func); PyObject *result_o; diff --git a/Python/ceval.c b/Python/ceval.c index 446e6a8be4da91..50126bf0dee72f 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -3517,6 +3517,24 @@ _PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwarg } } +/* Merge the mapping 'kwargs' into 'dict' for a call to 'func', + raising TypeError on a duplicate key or a non-mapping (DICT_MERGE). + Kept out of the instruction bodies: taking the address of a local + there defeats the tail-calling interpreter on MSVC (C4737). */ +int +_PyEval_MergeKwargs(PyThreadState *tstate, PyObject *func, + PyObject *dict, PyObject *kwargs) +{ + PyObject *dupkey = NULL; + if (_PyDict_MergeUniq(dict, kwargs, &dupkey) < 0) { + _PyEval_FormatKwargsError(tstate, func, kwargs, dupkey); + Py_XDECREF(dupkey); + return -1; + } + assert(dupkey == NULL); + return 0; +} + void _PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc, const char *format_str, PyObject *obj) diff --git a/Python/codegen.c b/Python/codegen.c index ab6e6137752f40..77ce90bc548ea5 100644 --- a/Python/codegen.c +++ b/Python/codegen.c @@ -4525,7 +4525,13 @@ codegen_call_helper_impl(compiler *c, location loc, BUILD_LIST, LIST_APPEND, LIST_EXTEND, 1)); } /* Then keyword arguments */ - if (nkwelts) { + if (nkwelts == 1 && + ((keyword_ty)asdl_seq_GET(keywords, 0))->arg == NULL) + { + /* A lone ** unpacking: CALL_FUNCTION_EX converts it if needed. */ + VISIT(c, expr, ((keyword_ty)asdl_seq_GET(keywords, 0))->value); + } + else if (nkwelts) { /* Has a new dict been pushed */ int have_dict = 0; diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index 5df8120e7424b9..07a1c2f7e698d6 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -11357,23 +11357,14 @@ PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); PyObject *dict_o = PyStackRef_AsPyObjectBorrow(dict); PyObject *update_o = PyStackRef_AsPyObjectBorrow(update); - PyObject *dupkey = NULL; stack_pointer[0] = update; stack_pointer += 1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = _PyDict_MergeUniq(dict_o, update_o, &dupkey); + int err = _PyEval_MergeKwargs(tstate, callable_o, dict_o, update_o); _PyFrame_StackPointerInvalidate(frame); if (err < 0) { - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyEval_FormatKwargsError(tstate, callable_o, update_o, dupkey); - _PyFrame_StackPointerInvalidate(frame); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - Py_XDECREF(dupkey); - _PyFrame_StackPointerInvalidate(frame); SET_CURRENT_CACHED_VALUES(0); JUMP_TO_ERROR(); } @@ -20207,18 +20198,20 @@ case _MAKE_CALLARGS_A_TUPLE_r33: { CHECK_CURRENT_CACHED_VALUES(3); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef kwargs; _PyStackRef callargs; _PyStackRef func; _PyStackRef _stack_item_0 = _tos_cache0; _PyStackRef _stack_item_1 = _tos_cache1; _PyStackRef _stack_item_2 = _tos_cache2; + kwargs = _stack_item_2; callargs = _stack_item_1; func = stack_pointer[-1]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); if (!PyTuple_CheckExact(callargs_o)) { stack_pointer[0] = _stack_item_0; stack_pointer[1] = callargs; - stack_pointer[2] = _stack_item_2; + stack_pointer[2] = kwargs; stack_pointer += 3; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -20246,7 +20239,44 @@ _PyFrame_StackPointerInvalidate(frame); stack_pointer += -3; } - _tos_cache2 = _stack_item_2; + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[0] = _stack_item_0; + stack_pointer[1] = callargs; + stack_pointer[2] = kwargs; + stack_pointer += 3; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_ERROR(); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_ERROR(); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -3; + } + _tos_cache2 = kwargs; _tos_cache1 = callargs; _tos_cache0 = _stack_item_0; SET_CURRENT_CACHED_VALUES(3); diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 3af7863e80d2c6..1edf994f9f318d 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -2772,6 +2772,7 @@ _PyStackRef func_st; _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef null; _PyStackRef callargs_st; _PyStackRef kwargs_st; @@ -2789,6 +2790,7 @@ } // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; func = func_st; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); @@ -2815,10 +2817,40 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _CALL_FUNCTION_EX_NON_PY_GENERAL { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; null = stack_pointer[-3]; func_st = func; @@ -2885,6 +2917,7 @@ static_assert(INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX == 1, "incorrect cache size"); _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef func_st; _PyStackRef callargs_st; _PyStackRef kwargs_st; @@ -2901,6 +2934,7 @@ } // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; func = stack_pointer[-4]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); @@ -2927,6 +2961,36 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _CHECK_IS_PY_CALLABLE_EX { @@ -2945,7 +3009,7 @@ } // _PY_FRAME_EX { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; PyObject *func = PyStackRef_AsPyObjectBorrow(func_st); PyObject *callargs = PyStackRef_AsPyObjectSteal(callargs_st); @@ -3018,6 +3082,7 @@ opcode = CALL_FUNCTION_EX; _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef func_st; _PyStackRef null; _PyStackRef callargs_st; @@ -3043,6 +3108,7 @@ } // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); if (!PyTuple_CheckExact(callargs_o)) { @@ -3068,10 +3134,40 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _DO_CALL_FUNCTION_EX { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; null = stack_pointer[-3]; func_st = func; @@ -5962,20 +6058,11 @@ PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); PyObject *dict_o = PyStackRef_AsPyObjectBorrow(dict); PyObject *update_o = PyStackRef_AsPyObjectBorrow(update); - PyObject *dupkey = NULL; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = _PyDict_MergeUniq(dict_o, update_o, &dupkey); + int err = _PyEval_MergeKwargs(tstate, callable_o, dict_o, update_o); _PyFrame_StackPointerInvalidate(frame); if (err < 0) { - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyEval_FormatKwargsError(tstate, callable_o, update_o, dupkey); - _PyFrame_StackPointerInvalidate(frame); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - Py_XDECREF(dupkey); - _PyFrame_StackPointerInvalidate(frame); JUMP_TO_LABEL(error); } u = update; @@ -7251,6 +7338,7 @@ opcode = INSTRUMENTED_CALL_FUNCTION_EX; _PyStackRef func; _PyStackRef callargs; + _PyStackRef kwargs; _PyStackRef func_st; _PyStackRef null; _PyStackRef callargs_st; @@ -7259,6 +7347,7 @@ /* Skip 1 cache entry */ // _MAKE_CALLARGS_A_TUPLE { + kwargs = stack_pointer[-1]; callargs = stack_pointer[-2]; func = stack_pointer[-4]; PyObject *callargs_o = PyStackRef_AsPyObjectBorrow(callargs); @@ -7285,10 +7374,40 @@ PyStackRef_CLOSE(temp); _PyFrame_StackPointerInvalidate(frame); } + PyObject *kwargs_o = PyStackRef_AsPyObjectBorrow(kwargs); + if (kwargs_o != NULL && !PyDict_CheckExact(kwargs_o)) { + stack_pointer[-2] = callargs; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *dict_o = PyDict_New(); + _PyFrame_StackPointerInvalidate(frame); + if (dict_o == NULL) { + JUMP_TO_LABEL(error); + } + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = _PyEval_MergeKwargs( + tstate, PyStackRef_AsPyObjectBorrow(func), dict_o, kwargs_o); + _PyFrame_StackPointerInvalidate(frame); + if (err < 0) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + Py_DECREF(dict_o); + _PyFrame_StackPointerInvalidate(frame); + JUMP_TO_LABEL(error); + } + _PyStackRef temp = kwargs; + kwargs = PyStackRef_FromPyObjectSteal(dict_o); + stack_pointer[-1] = kwargs; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } } // _DO_CALL_FUNCTION_EX { - kwargs_st = stack_pointer[-1]; + kwargs_st = kwargs; callargs_st = callargs; null = stack_pointer[-3]; func_st = func;