Skip to content

[3.6] bpo-24618: Add a check in the code constructor. (GH-8283) #8311

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed reading invalid memory when create the code object with too small
varnames tuple or too large argument counts.
29 changes: 24 additions & 5 deletions Objects/codeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ PyCode_New(int argcount, int kwonlyargcount,
{
PyCodeObject *co;
unsigned char *cell2arg = NULL;
Py_ssize_t i, n_cellvars;
Py_ssize_t i, n_cellvars, n_varnames, total_args;

/* Check argument types */
if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
Expand Down Expand Up @@ -150,23 +150,42 @@ PyCode_New(int argcount, int kwonlyargcount,
flags &= ~CO_NOFREE;
}

n_varnames = PyTuple_GET_SIZE(varnames);
if (argcount <= n_varnames && kwonlyargcount <= n_varnames) {
/* Never overflows. */
total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount +
((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
}
else {
total_args = n_varnames + 1;
}
if (total_args > n_varnames) {
PyErr_SetString(PyExc_ValueError, "code: varnames is too small");
return NULL;
}

/* Create mapping between cells and arguments if needed. */
if (n_cellvars) {
Py_ssize_t total_args = argcount + kwonlyargcount +
((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars;
bool used_cell2arg = false;
cell2arg = PyMem_MALLOC(alloc_size);
if (cell2arg == NULL)
if (cell2arg == NULL) {
PyErr_NoMemory();
return NULL;
}
memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size);
/* Find cells which are also arguments. */
for (i = 0; i < n_cellvars; i++) {
Py_ssize_t j;
PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
for (j = 0; j < total_args; j++) {
PyObject *arg = PyTuple_GET_ITEM(varnames, j);
if (!PyUnicode_Compare(cell, arg)) {
int cmp = PyUnicode_Compare(cell, arg);
if (cmp == -1 && PyErr_Occurred()) {
PyMem_FREE(cell2arg);
return NULL;
}
if (cmp == 0) {
cell2arg[i] = j;
used_cell2arg = true;
break;
Expand Down