@@ -2192,13 +2192,71 @@ static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2192
2192
return memcpy (malloc_startup (len ), buffer , len );
2193
2193
}
2194
2194
2195
+ static void maybe_redirect_std_handle (const wchar_t * key , DWORD std_id , int fd ,
2196
+ DWORD desired_access , DWORD flags )
2197
+ {
2198
+ DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING ;
2199
+ wchar_t buf [MAX_LONG_PATH ];
2200
+ DWORD max = ARRAY_SIZE (buf );
2201
+ HANDLE handle ;
2202
+ DWORD ret = GetEnvironmentVariableW (key , buf , max );
2203
+
2204
+ if (!ret || ret >= max )
2205
+ return ;
2206
+
2207
+ /* make sure this does not leak into child processes */
2208
+ SetEnvironmentVariableW (key , NULL );
2209
+ if (!wcscmp (buf , L"off" )) {
2210
+ close (fd );
2211
+ handle = GetStdHandle (std_id );
2212
+ if (handle != INVALID_HANDLE_VALUE )
2213
+ CloseHandle (handle );
2214
+ return ;
2215
+ }
2216
+ if (std_id == STD_ERROR_HANDLE && !wcscmp (buf , L"2>&1" )) {
2217
+ handle = GetStdHandle (STD_OUTPUT_HANDLE );
2218
+ if (handle == INVALID_HANDLE_VALUE ) {
2219
+ close (fd );
2220
+ handle = GetStdHandle (std_id );
2221
+ if (handle != INVALID_HANDLE_VALUE )
2222
+ CloseHandle (handle );
2223
+ } else {
2224
+ int new_fd = _open_osfhandle ((intptr_t )handle , O_BINARY );
2225
+ SetStdHandle (std_id , handle );
2226
+ dup2 (new_fd , fd );
2227
+ /* do *not* close the new_fd: that would close stdout */
2228
+ }
2229
+ return ;
2230
+ }
2231
+ handle = CreateFileW (buf , desired_access , 0 , NULL , create_flag ,
2232
+ flags , NULL );
2233
+ if (handle != INVALID_HANDLE_VALUE ) {
2234
+ int new_fd = _open_osfhandle ((intptr_t )handle , O_BINARY );
2235
+ SetStdHandle (std_id , handle );
2236
+ dup2 (new_fd , fd );
2237
+ close (new_fd );
2238
+ }
2239
+ }
2240
+
2241
+ static void maybe_redirect_std_handles (void )
2242
+ {
2243
+ maybe_redirect_std_handle (L"GIT_REDIRECT_STDIN" , STD_INPUT_HANDLE , 0 ,
2244
+ GENERIC_READ , FILE_ATTRIBUTE_NORMAL );
2245
+ maybe_redirect_std_handle (L"GIT_REDIRECT_STDOUT" , STD_OUTPUT_HANDLE , 1 ,
2246
+ GENERIC_WRITE , FILE_ATTRIBUTE_NORMAL );
2247
+ maybe_redirect_std_handle (L"GIT_REDIRECT_STDERR" , STD_ERROR_HANDLE , 2 ,
2248
+ GENERIC_WRITE , FILE_FLAG_NO_BUFFERING );
2249
+ }
2250
+
2195
2251
void mingw_startup (void )
2196
2252
{
2197
2253
int i , maxlen , argc ;
2198
2254
char * buffer ;
2199
2255
wchar_t * * wenv , * * wargv ;
2200
2256
_startupinfo si ;
2201
2257
2258
+ maybe_redirect_std_handles ();
2259
+
2202
2260
/* get wide char arguments and environment */
2203
2261
si .newmode = 0 ;
2204
2262
if (__wgetmainargs (& argc , & wargv , & wenv , _CRT_glob , & si ) < 0 )
0 commit comments