From 265f962f91ebf4ea018fb259f690341059c5c2a7 Mon Sep 17 00:00:00 2001 From: Ammar Askar Date: Thu, 4 Jun 2020 11:59:55 -0700 Subject: [PATCH] Restrict co_code to be under INT_MAX in codeobject --- Objects/codeobject.c | 8 ++++++++ Objects/frameobject.c | 6 +++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Objects/codeobject.c b/Objects/codeobject.c index 737635943aced5..cb4fb681243336 100644 --- a/Objects/codeobject.c +++ b/Objects/codeobject.c @@ -166,6 +166,14 @@ PyCode_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int kwonlyargcount, return NULL; } + /* Make sure that code is indexable with an int, this is + a long running assumption in ceval.c and many parts of + the interpreter. */ + if (PyBytes_GET_SIZE(code) > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, "co_code larger than INT_MAX"); + return NULL; + } + /* Check for any inner or outer closure references */ n_cellvars = PyTuple_GET_SIZE(cellvars); if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) { diff --git a/Objects/frameobject.c b/Objects/frameobject.c index b6d073bd456d03..5043d0ef424146 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -397,9 +397,9 @@ frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignore return -1; } - int len = Py_SAFE_DOWNCAST( - PyBytes_GET_SIZE(f->f_code->co_code)/sizeof(_Py_CODEUNIT), - Py_ssize_t, int); + /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this + * should never overflow. */ + int len = (int)(PyBytes_GET_SIZE(f->f_code->co_code) / sizeof(_Py_CODEUNIT)); int *lines = marklines(f->f_code, len); if (lines == NULL) { return -1;