gh-118422: Fix run_fileexflags() test (#118429)

Don't test the undefined behavior of fileno()
on a closed file, but use fstat() as a reliable
test if the file was closed or not.
This commit is contained in:
Victor Stinner 2024-04-30 22:32:55 +02:00 committed by GitHub
parent 587388ff22
commit e93c39b47e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 62 additions and 58 deletions

View file

@ -1,5 +1,7 @@
#define PYTESTCAPI_NEED_INTERNAL_API
#include "parts.h"
#include "util.h"
#include "pycore_fileutils.h" // _Py_IsValidFD()
#include <stdio.h>
#include <errno.h>
@ -71,21 +73,18 @@ run_fileexflags(PyObject *mod, PyObject *pos_args)
PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
return NULL;
}
int fd = fileno(fp);
result = PyRun_FileExFlags(fp, filename, start, globals, locals, closeit, pflags);
#if defined(__linux__) || defined(MS_WINDOWS) || defined(__APPLE__)
/* The behavior of fileno() after fclose() is undefined, but it is
* the only practical way to check whether the file was closed.
* Only test this on the known platforms. */
if (closeit && result && fileno(fp) >= 0) {
if (closeit && result && _Py_IsValidFD(fd)) {
PyErr_SetString(PyExc_AssertionError, "File was not closed after excution");
Py_DECREF(result);
fclose(fp);
return NULL;
}
#endif
if (!closeit && fileno(fp) < 0) {
if (!closeit && !_Py_IsValidFD(fd)) {
PyErr_SetString(PyExc_AssertionError, "Bad file descriptor after excution");
Py_XDECREF(result);
return NULL;