Skip to content

PyErr_SetFromErrno() etc should be called immediately after setting the error code #107913

Closed
@serhiy-storchaka

Description

@serhiy-storchaka

Functions like PyErr_SetFromErrno() rely on global variable errno (actually it is thread local, but it does not matter here). They should be called immediately after using a functions which set errno. Calling other function (like close()) can change the value of errno. Py_DECREF() and PyBuffer_Release() can execute arbitrary code, in particularly the code which changes the value of errno. Even PyMem_Free() is not safe, because it the memory allocator can be customized.

There is the same issue with SetFromWindowsErr() and friends. If pass 0 as Windows error code, it calls GetLastError() to retrieve the global value which can be changed at that time if some functions were called before SetFromWindowsErr().

Most uses in the code are correct, but there are several sites in the code where some cleanup code is inserted between function which sets the error code and function which consumes it.

Two ways to resolve this issue:

  1. Reorganize the code so that PyErr_SetFromErrno() and SetFromWindowsErr() are called immediately after function which sets the error code (not counting simple memory reads or writes). In some cases it may require duplicating the cleanup code (usually just one line).

  2. Save the error code to a local variable before executing the intermediate code and restore it after.

Linked PRs

Metadata

Metadata

Labels

3.11only security fixes3.12only security fixes3.13bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions