Skip to content

Commit a6e8493

Browse files
brianfcolemanserhiy-storchaka
authored andcommitted
bpo-29683 - Fixes to _PyCode_SetExtra when co_extra->ce->extras is (#402)
allocated. On PyMem_Realloc failure, _PyCode_SetExtra should free co_extra if co_extra->ce_extras could not be allocated. On PyMem_Realloc success, _PyCode_SetExtra should set all unused slots in co_extra->ce_extras to NULL.
1 parent 65bd0bd commit a6e8493

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 3.6.1 release candidate 1?
1010
Core and Builtins
1111
-----------------
1212

13+
- bpo-29683: Fixes to memory allocation in _PyCode_SetExtra. Patch by
14+
Brian Coleman.
15+
1316
- bpo-29684: Fix minor regression of PyEval_CallObjectWithKeywords.
1417
It should raise TypeError when kwargs is not a dict. But it might
1518
cause segv when args=NULL and kwargs is not a dict.

Objects/codeobject.c

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -856,16 +856,15 @@ _PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
856856
_PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
857857

858858
if (co_extra == NULL) {
859-
o->co_extra = (_PyCodeObjectExtra*) PyMem_Malloc(
860-
sizeof(_PyCodeObjectExtra));
861-
if (o->co_extra == NULL) {
859+
co_extra = PyMem_Malloc(sizeof(_PyCodeObjectExtra));
860+
if (co_extra == NULL) {
862861
return -1;
863862
}
864-
co_extra = (_PyCodeObjectExtra *) o->co_extra;
865863

866864
co_extra->ce_extras = PyMem_Malloc(
867865
tstate->co_extra_user_count * sizeof(void*));
868866
if (co_extra->ce_extras == NULL) {
867+
PyMem_Free(co_extra);
869868
return -1;
870869
}
871870

@@ -874,20 +873,25 @@ _PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
874873
for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
875874
co_extra->ce_extras[i] = NULL;
876875
}
876+
877+
o->co_extra = co_extra;
877878
}
878879
else if (co_extra->ce_size <= index) {
879-
co_extra->ce_extras = PyMem_Realloc(
880+
void** ce_extras = PyMem_Realloc(
880881
co_extra->ce_extras, tstate->co_extra_user_count * sizeof(void*));
881882

882-
if (co_extra->ce_extras == NULL) {
883+
if (ce_extras == NULL) {
883884
return -1;
884885
}
885886

886-
co_extra->ce_size = tstate->co_extra_user_count;
887-
888-
for (Py_ssize_t i = co_extra->ce_size; i < co_extra->ce_size; i++) {
889-
co_extra->ce_extras[i] = NULL;
887+
for (Py_ssize_t i = co_extra->ce_size;
888+
i < tstate->co_extra_user_count;
889+
i++) {
890+
ce_extras[i] = NULL;
890891
}
892+
893+
co_extra->ce_extras = ce_extras;
894+
co_extra->ce_size = tstate->co_extra_user_count;
891895
}
892896

893897
co_extra->ce_extras[index] = extra;

0 commit comments

Comments
 (0)