Skip to content

Commit 6023cac

Browse files
gh-445: Set the UCRT's app type in the alias launcher before calling Py_Main (#446)
The launcher links the C runtime statically, so its startup code sets the app type only in its own copy. Python, loaded in-process through python3.dll, uses the shared UCRT, whose app type stays unknown. The UCRT then doesn't update the process's standard handles when Python swaps fds 0-2 with os.dup2 (as pytest's fd capture does), GetStdHandle keeps returning a closed handle, and a subprocess that inherits stdin fails with WinError 6. Set it to console (or GUI for the windowed launcher) before calling Py_Main, as python.exe's own startup would.
1 parent 791e4d7 commit 6023cac

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

‎src/pymanager/launcher.cpp‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33

44
#include "_launch.h"
55

6+
#ifndef PY_WINDOWED
7+
#define PY_WINDOWED 0
8+
#endif
9+
610
#define MAXLEN 32768
711

812
// HRESULT-compatible error codes
@@ -252,6 +256,22 @@ launch_by_dll(void *main_func_ptr, wchar_t *executable, int argc, wchar_t **argv
252256
newArgv[i] = argv[i];
253257
}
254258

259+
// This launcher links the C runtime statically, so its startup code tells only
260+
// its own copy what kind of app this is. Python uses the shared UCRT, which
261+
// would otherwise stay "unknown", and then no longer updates the process's
262+
// standard handles when Python swaps fds 0-2 (os.dup2, as pytest's capture
263+
// does): GetStdHandle keeps returning a closed handle, and a subprocess that
264+
// inherits it fails with WinError 6. Tell it what python.exe's startup would.
265+
HMODULE ucrt = GetModuleHandleW(L"ucrtbase.dll");
266+
if (ucrt) {
267+
typedef void (__cdecl *set_app_type_t)(int);
268+
set_app_type_t set_app_type = (set_app_type_t)GetProcAddress(ucrt, "_set_app_type");
269+
if (set_app_type) {
270+
// _crt_console_app (1) or _crt_gui_app (2), as for python.exe and pythonw.exe
271+
(*set_app_type)(PY_WINDOWED ? 2 : 1);
272+
}
273+
}
274+
255275
// Our caller assumes that any error result happens before we launch. From
256276
// this point on, exit_code is set (possibly to an error), and so we should
257277
// only return 0.

0 commit comments

Comments
 (0)