8000 bpo-24618: Add a check in the code constructor. (GH-8283) · python/cpython@bd47384 · GitHub
[go: up one dir, main page]

Skip to content

Commit bd47384

Browse files
bpo-24618: Add a check in the code constructor. (GH-8283)
Check that the size of the varnames tuple is enough at least for all arguments.
1 parent 15c7b2a commit bd47384

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed reading invalid memory when create the code object with too small
2+
varnames tuple or too large argument counts.

Objects/codeobject.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ PyCode_New(int argcount, int kwonlyargcount,
103103
{
104104
PyCodeObject *co;
105105
Py_ssize_t *cell2arg = NULL;
106-
Py_ssize_t i, n_cellvars;
106+
Py_ssize_t i, n_cellvars, n_varnames, total_args;
107107

108108
/* Check argument types */
109109
if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
@@ -138,10 +138,22 @@ PyCode_New(int argcount, int kwonlyargcount,
138138
flags &= ~CO_NOFREE;
139139
}
140140

141+
n_varnames = PyTuple_GET_SIZE(varnames);
142+
if (argcount <= n_varnames && kwonlyargcount <= n_varnames) {
143+
/* Never overflows. */
144+
total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount +
145+
((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
146+
}
147+
else {
148+
total_args = n_varnames + 1;
149+
}
150+
if (total_args > n_varnames) {
151+
PyErr_SetString(PyExc_ValueError, "code: varnames is too small");
152+
return NULL;
153+
}
154+
141155
/* Create mapping between cells and arguments if needed. */
142156
if (n_cellvars) {
143-
Py_ssize_t total_args = argcount + kwonlyargcount +
144-
((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
145157
bool used_cell2arg = false;
146158
cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
147159
if (cell2arg == NULL) {

0 commit comments

Comments
 (0)
0