Skip to content

Commit 8892a1d

Browse files
closes bpo-38124: Fix bounds check in PyState_AddModule. (GH-16007)
The >=, checking whether a module index was in already in the module-by-index list, needed to be strict. Also, fold nested ifs into one and fix some bad spacing. (cherry picked from commit 39de95b) Co-authored-by: Benjamin Peterson <benjamin@python.org>
1 parent bf0c76c commit 8892a1d

2 files changed

Lines changed: 8 additions & 8 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix an off-by-one error in PyState_AddModule that could cause out-of-bounds
2+
memory access.

Python/pystate.c

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -484,7 +484,7 @@ _PyState_AddModule(PyObject* module, struct PyModuleDef* def)
484484
if (!state->modules_by_index)
485485
return -1;
486486
}
487-
while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
487+
while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
488488
if (PyList_Append(state->modules_by_index, Py_None) < 0)
489489
return -1;
490490
Py_INCREF(module);
@@ -502,13 +502,11 @@ PyState_AddModule(PyObject* module, struct PyModuleDef* def)
502502
return -1;
503503
}
504504
index = def->m_base.m_index;
505-
if (state->modules_by_index) {
506-
if(PyList_GET_SIZE(state->modules_by_index) >= index) {
507-
if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
508-
Py_FatalError("PyState_AddModule: Module already added!");
509-
return -1;
510-
}
511-
}
505+
if (state->modules_by_index &&
506+
index < PyList_GET_SIZE(state->modules_by_index) &&
507+
module == PyList_GET_ITEM(state->modules_by_index, index)) {
508+
Py_FatalError("PyState_AddModule: Module already added!");
509+
return -1;
512510
}
513511
return _PyState_AddModule(module, def);
514512
}

0 commit comments

Comments
 (0)