@@ -2139,13 +2139,71 @@ static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2139
2139
return memcpy (malloc_startup (len ), buffer , len );
2140
2140
}
2141
2141
2142
+ static void maybe_redirect_std_handle (const wchar_t * key , DWORD std_id , int fd ,
2143
+ DWORD desired_access , DWORD flags )
2144
+ {
2145
+ DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING ;
2146
+ wchar_t buf [MAX_PATH ];
2147
+ DWORD max = ARRAY_SIZE (buf );
2148
+ HANDLE handle ;
2149
+ DWORD ret = GetEnvironmentVariableW (key , buf , max );
2150
+
2151
+ if (!ret || ret >= max )
2152
+ return ;
2153
+
2154
+ /* make sure this does not leak into child processes */
2155
+ SetEnvironmentVariableW (key , NULL );
2156
+ if (!wcscmp (buf , L"off" )) {
2157
+ close (fd );
2158
+ handle = GetStdHandle (std_id );
2159
+ if (handle != INVALID_HANDLE_VALUE )
2160
+ CloseHandle (handle );
2161
+ return ;
2162
+ }
2163
+ if (std_id == STD_ERROR_HANDLE && !wcscmp (buf , L"2>&1" )) {
2164
+ handle = GetStdHandle (STD_OUTPUT_HANDLE );
2165
+ if (handle == INVALID_HANDLE_VALUE ) {
2166
+ close (fd );
2167
+ handle = GetStdHandle (std_id );
2168
+ if (handle != INVALID_HANDLE_VALUE )
2169
+ CloseHandle (handle );
2170
+ } else {
2171
+ int new_fd = _open_osfhandle ((intptr_t )handle , O_BINARY );
2172
+ SetStdHandle (std_id , handle );
2173
+ dup2 (new_fd , fd );
2174
+ /* do *not* close the new_fd: that would close stdout */
2175
+ }
2176
+ return ;
2177
+ }
2178
+ handle = CreateFileW (buf , desired_access , 0 , NULL , create_flag ,
2179
+ flags , NULL );
2180
+ if (handle != INVALID_HANDLE_VALUE ) {
2181
+ int new_fd = _open_osfhandle ((intptr_t )handle , O_BINARY );
2182
+ SetStdHandle (std_id , handle );
2183
+ dup2 (new_fd , fd );
2184
+ close (new_fd );
2185
+ }
2186
+ }
2187
+
2188
+ static void maybe_redirect_std_handles (void )
2189
+ {
2190
+ maybe_redirect_std_handle (L"GIT_REDIRECT_STDIN" , STD_INPUT_HANDLE , 0 ,
2191
+ GENERIC_READ , FILE_ATTRIBUTE_NORMAL );
2192
+ maybe_redirect_std_handle (L"GIT_REDIRECT_STDOUT" , STD_OUTPUT_HANDLE , 1 ,
2193
+ GENERIC_WRITE , FILE_ATTRIBUTE_NORMAL );
2194
+ maybe_redirect_std_handle (L"GIT_REDIRECT_STDERR" , STD_ERROR_HANDLE , 2 ,
2195
+ GENERIC_WRITE , FILE_FLAG_NO_BUFFERING );
2196
+ }
2197
+
2142
2198
void mingw_startup (void )
2143
2199
{
2144
2200
int i , maxlen , argc ;
2145
2201
char * buffer ;
2146
2202
wchar_t * * wenv , * * wargv ;
2147
2203
_startupinfo si ;
2148
2204
2205
+ maybe_redirect_std_handles ();
2206
+
2149
2207
/* get wide char arguments and environment */
2150
2208
si .newmode = 0 ;
2151
2209
if (__wgetmainargs (& argc , & wargv , & wenv , _CRT_glob , & si ) < 0 )
0 commit comments