Skip to content

Commit 3451dc8

Browse files
committed
gh-161769: preserve Windows error state during thread attachment
1 parent aac344d commit 3451dc8

2 files changed

Lines changed: 13 additions & 10 deletions

File tree

‎Python/ceval_gil.c‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -651,16 +651,8 @@ PyEval_SaveThread(void)
651651
void
652652
PyEval_RestoreThread(PyThreadState *tstate)
653653
{
654-
#ifdef MS_WINDOWS
655-
int err = GetLastError();
656-
#endif
657-
658654
_Py_EnsureTstateNotNULL(tstate);
659655
_PyThreadState_Attach(tstate);
660-
661-
#ifdef MS_WINDOWS
662-
SetLastError(err);
663-
#endif
664656
}
665657

666658

‎Python/pystate.c‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727
#include "pycore_time.h" // _PyTime_Init()
2828
#include "pycore_uniqueid.h" // _PyObject_FinalizePerThreadRefcounts()
2929

30+
#ifdef MS_WINDOWS
31+
# include <windows.h>
32+
#endif
33+
3034

3135
/* --------------------------------------------------------------------------
3236
CAUTION
@@ -2383,8 +2387,12 @@ tstate_wait_attach(PyThreadState *tstate)
23832387
void
23842388
_PyThreadState_Attach(PyThreadState *tstate)
23852389
{
2386-
// This is called from PyEval_RestoreThread(). Similar
2387-
// to it, we need to ensure errno doesn't change.
2390+
// Reattachment may wait for GC and change errno, even after a successful
2391+
// system call (gh-161769). Preserve the caller's error state in release
2392+
// builds as well as debug builds.
2393+
#ifdef MS_WINDOWS
2394+
DWORD last_error = GetLastError();
2395+
#endif
23882396
int err = errno;
23892397

23902398
_Py_EnsureTstateNotNULL(tstate);
@@ -2433,6 +2441,9 @@ _PyThreadState_Attach(PyThreadState *tstate)
24332441
#endif
24342442

24352443
errno = err;
2444+
#ifdef MS_WINDOWS
2445+
SetLastError(last_error);
2446+
#endif
24362447
}
24372448

24382449
static void

0 commit comments

Comments
 (0)