fix(c-api): add missing NULL check after Py_BuildValue in _test_exten…#520
Open
dynapx wants to merge 1 commit into
Open
fix(c-api): add missing NULL check after Py_BuildValue in _test_exten…#520dynapx wants to merge 1 commit into
dynapx wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
During a security and robustness audit of C-API usage using our static analysis tool, we identified a potential Null Pointer Dereference (NPD) in
src/greenlet/tests/_test_extension.c.In the
test_throwfunction,Py_BuildValue("s", msg)is called to create a string object. According to the Python C-API contract, if memory allocation fails (OOM), it returnsNULLand sets aMemoryError. However, the return valuemsg_objis currently not checked before being used.If
msg_objisNULL, it leads to a double crash hazard:msg_objis passed toPyGreenlet_Throw. SincePyGreenlet_Throwis a macro that dereferences a function pointer from_PyGreenlet_API, injecting an unvalidatedNULLpointer across the API boundary can lead to undefined behavior inside the core logic.Py_DECREF(msg_obj)is called. UnlikePy_XDECREF, thePy_DECREFmacro lacks aNULLcheck. It will attempt to accessmsg_obj->ob_refcnt, resulting in a deterministic Segmentation Fault.This hard crash truncates the exception lifecycle, destroying the original
MemoryErrorstate and preventing graceful failure.Proposed Fix
We added a standard
NULLcheck immediately afterPy_BuildValue. If allocation fails, the function now safely returnsNULLto propagate the exception properly.Impact
This PR improves the robustness of the test extension, ensuring that extreme memory exhaustion scenarios are handled gracefully without taking down the entire interpreter process.