]> git.ipfire.org Git - thirdparty/git.git/blame - compat/mingw.c
win32: special-case `ENOSPC` when writing to a pipe
[thirdparty/git.git] / compat / mingw.c
CommitLineData
f4626df5 1#include "../git-compat-util.h"
444dc903 2#include "win32.h"
bdc77d1d 3#include <aclapi.h>
e883e04b 4#include <sddl.h>
28a559c0 5#include <conio.h>
85faec9d 6#include <wchar.h>
7e5d7768 7#include "../strbuf.h"
c9b78400 8#include "../run-command.h"
0b027f6c 9#include "../abspath.h"
36bf1958 10#include "../alloc.h"
564be791 11#include "win32/lazyload.h"
bdfbb0ea 12#include "../config.h"
32a8f510 13#include "../environment.h"
74ea5c95 14#include "../trace2.h"
cb2a5135 15#include "../symlinks.h"
d5ebb50d 16#include "../wrapper.h"
9e9da23c 17#include "dir.h"
f394e093 18#include "gettext.h"
4a9b2049
MA
19#define SECURITY_WIN32
20#include <sspi.h>
f4626df5 21
7c00bc39
JS
22#define HCAST(type, handle) ((type)(intptr_t)handle)
23
19e12549
HV
24static const int delay[] = { 0, 1, 10, 20, 40 };
25
08809c09
JS
26void open_in_gdb(void)
27{
28 static struct child_process cp = CHILD_PROCESS_INIT;
29 extern char *_pgmptr;
30
ef8d7ac4
JK
31 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
32 strvec_pushf(&cp.args, "--pid=%d", getpid());
08809c09
JS
33 cp.clean_on_exit = 1;
34 if (start_command(&cp) < 0)
35 die_errno("Could not start gdb");
36 sleep(1);
37}
38
44626dc7 39int err_win_to_posix(DWORD winerr)
b3debd2b
PK
40{
41 int error = ENOSYS;
42 switch(winerr) {
43 case ERROR_ACCESS_DENIED: error = EACCES; break;
44 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
45 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
46 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
47 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
48 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
49 case ERROR_BAD_COMMAND: error = EIO; break;
50 case ERROR_BAD_DEVICE: error = ENODEV; break;
51 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
52 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
53 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
54 case ERROR_BAD_LENGTH: error = EINVAL; break;
55 case ERROR_BAD_PATHNAME: error = ENOENT; break;
56 case ERROR_BAD_PIPE: error = EPIPE; break;
57 case ERROR_BAD_UNIT: error = ENODEV; break;
58 case ERROR_BAD_USERNAME: error = EINVAL; break;
59 case ERROR_BROKEN_PIPE: error = EPIPE; break;
60 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
61 case ERROR_BUSY: error = EBUSY; break;
62 case ERROR_BUSY_DRIVE: error = EBUSY; break;
63 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
64 case ERROR_CANNOT_MAKE: error = EACCES; break;
65 case ERROR_CANTOPEN: error = EIO; break;
66 case ERROR_CANTREAD: error = EIO; break;
67 case ERROR_CANTWRITE: error = EIO; break;
68 case ERROR_CRC: error = EIO; break;
69 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
70 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
71 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
72 case ERROR_DIRECTORY: error = EINVAL; break;
73 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
74 case ERROR_DISK_CHANGE: error = EIO; break;
75 case ERROR_DISK_FULL: error = ENOSPC; break;
76 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
77 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
78 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
79 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
80 case ERROR_FILE_EXISTS: error = EEXIST; break;
81 case ERROR_FILE_INVALID: error = ENODEV; break;
82 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
83 case ERROR_GEN_FAILURE: error = EIO; break;
84 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
85 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
86 case ERROR_INVALID_ACCESS: error = EACCES; break;
87 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
88 case ERROR_INVALID_BLOCK: error = EFAULT; break;
89 case ERROR_INVALID_DATA: error = EINVAL; break;
90 case ERROR_INVALID_DRIVE: error = ENODEV; break;
91 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
92 case ERROR_INVALID_FLAGS: error = EINVAL; break;
93 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
94 case ERROR_INVALID_HANDLE: error = EBADF; break;
95 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
96 case ERROR_INVALID_NAME: error = EINVAL; break;
97 case ERROR_INVALID_OWNER: error = EINVAL; break;
98 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
99 case ERROR_INVALID_PASSWORD: error = EPERM; break;
100 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
101 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
102 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
103 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
104 case ERROR_IO_DEVICE: error = EIO; break;
105 case ERROR_IO_INCOMPLETE: error = EINTR; break;
106 case ERROR_LOCKED: error = EBUSY; break;
107 case ERROR_LOCK_VIOLATION: error = EACCES; break;
108 case ERROR_LOGON_FAILURE: error = EACCES; break;
109 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
110 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
111 case ERROR_MORE_DATA: error = EPIPE; break;
112 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
113 case ERROR_NOACCESS: error = EFAULT; break;
114 case ERROR_NONE_MAPPED: error = EINVAL; break;
115 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
116 case ERROR_NOT_READY: error = EAGAIN; break;
117 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
118 case ERROR_NO_DATA: error = EPIPE; break;
119 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
120 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
121 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
122 case ERROR_OPEN_FAILED: error = EIO; break;
123 case ERROR_OPEN_FILES: error = EBUSY; break;
124 case ERROR_OPERATION_ABORTED: error = EINTR; break;
125 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
126 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
127 case ERROR_PATH_BUSY: error = EBUSY; break;
128 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
129 case ERROR_PIPE_BUSY: error = EBUSY; break;
130 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
131 case ERROR_PIPE_LISTENING: error = EPIPE; break;
132 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
133 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
134 case ERROR_READ_FAULT: error = EIO; break;
135 case ERROR_SEEK: error = EIO; break;
136 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
137 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
138 case ERROR_SHARING_VIOLATION: error = EACCES; break;
139 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
3ba3720b 140 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
b3debd2b
PK
141 case ERROR_SWAPERROR: error = ENOENT; break;
142 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
143 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
144 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
145 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
146 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
147 case ERROR_WRITE_FAULT: error = EIO; break;
148 case ERROR_WRITE_PROTECT: error = EROFS; break;
149 }
150 return error;
151}
152
19e12549
HV
153static inline int is_file_in_use_error(DWORD errcode)
154{
155 switch (errcode) {
156 case ERROR_SHARING_VIOLATION:
157 case ERROR_ACCESS_DENIED:
158 return 1;
159 }
160
161 return 0;
162}
163
c9b78400
HV
164static int read_yes_no_answer(void)
165{
166 char answer[1024];
167
168 if (fgets(answer, sizeof(answer), stdin)) {
169 size_t answer_len = strlen(answer);
170 int got_full_line = 0, c;
171
172 /* remove the newline */
173 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
174 answer[answer_len-2] = '\0';
175 got_full_line = 1;
176 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
177 answer[answer_len-1] = '\0';
178 got_full_line = 1;
179 }
180 /* flush the buffer in case we did not get the full line */
181 if (!got_full_line)
182 while ((c = getchar()) != EOF && c != '\n')
183 ;
184 } else
185 /* we could not read, return the
186 * default answer which is no */
187 return 0;
188
189 if (tolower(answer[0]) == 'y' && !answer[1])
190 return 1;
191 if (!strncasecmp(answer, "yes", sizeof(answer)))
192 return 1;
193 if (tolower(answer[0]) == 'n' && !answer[1])
194 return 0;
195 if (!strncasecmp(answer, "no", sizeof(answer)))
196 return 0;
197
198 /* did not find an answer we understand */
199 return -1;
200}
201
202static int ask_yes_no_if_possible(const char *format, ...)
203{
204 char question[4096];
4120294c 205 const char *retry_hook;
c9b78400
HV
206 va_list args;
207
208 va_start(args, format);
209 vsnprintf(question, sizeof(question), format, args);
210 va_end(args);
211
4120294c
RS
212 retry_hook = mingw_getenv("GIT_ASK_YESNO");
213 if (retry_hook) {
214 struct child_process cmd = CHILD_PROCESS_INIT;
215
216 strvec_pushl(&cmd.args, retry_hook, question, NULL);
217 return !run_command(&cmd);
c9b78400
HV
218 }
219
220 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
221 return 0;
222
223 while (1) {
224 int answer;
225 fprintf(stderr, "%s (y/n) ", question);
226
227 if ((answer = read_yes_no_answer()) >= 0)
228 return answer;
229
230 fprintf(stderr, "Sorry, I did not understand your answer. "
231 "Please type 'y' or 'n'\n");
232 }
233}
234
bdfbb0ea
JS
235/* Windows only */
236enum hide_dotfiles_type {
237 HIDE_DOTFILES_FALSE = 0,
238 HIDE_DOTFILES_TRUE,
239 HIDE_DOTFILES_DOTGITONLY
240};
241
ac33519d 242static int core_restrict_inherited_handles = -1;
bdfbb0ea 243static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
0e218f91 244static char *unset_environment_variables;
bdfbb0ea 245
a4e7e317
GC
246int mingw_core_config(const char *var, const char *value,
247 const struct config_context *ctx, void *cb)
70fc5793 248{
bdfbb0ea
JS
249 if (!strcmp(var, "core.hidedotfiles")) {
250 if (value && !strcasecmp(value, "dotgitonly"))
251 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
252 else
253 hide_dotfiles = git_config_bool(var, value);
254 return 0;
255 }
256
0e218f91
JS
257 if (!strcmp(var, "core.unsetenvvars")) {
258 free(unset_environment_variables);
259 unset_environment_variables = xstrdup(value);
260 return 0;
261 }
262
ac33519d
JS
263 if (!strcmp(var, "core.restrictinheritedhandles")) {
264 if (value && !strcasecmp(value, "auto"))
265 core_restrict_inherited_handles = -1;
266 else
267 core_restrict_inherited_handles =
268 git_config_bool(var, value);
269 return 0;
270 }
271
70fc5793
JS
272 return 0;
273}
274
4745feeb
AS
275/* Normalizes NT paths as returned by some low-level APIs. */
276static wchar_t *normalize_ntpath(wchar_t *wbuf)
277{
278 int i;
279 /* fix absolute path prefixes */
280 if (wbuf[0] == '\\') {
281 /* strip NT namespace prefixes */
282 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
283 !wcsncmp(wbuf, L"\\\\?\\", 4))
284 wbuf += 4;
285 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
286 wbuf += 12;
287 /* replace remaining '...UNC\' with '\\' */
288 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
289 wbuf += 2;
290 *wbuf = '\\';
291 }
292 }
293 /* convert backslashes to slashes */
294 for (i = 0; wbuf[i]; i++)
295 if (wbuf[i] == '\\')
296 wbuf[i] = '/';
297 return wbuf;
298}
299
337967fb
HV
300int mingw_unlink(const char *pathname)
301{
19e12549 302 int ret, tries = 0;
85faec9d
KB
303 wchar_t wpathname[MAX_PATH];
304 if (xutftowcs_path(wpathname, pathname) < 0)
305 return -1;
19e12549 306
680e0b45
JH
307 if (DeleteFileW(wpathname))
308 return 0;
309
337967fb 310 /* read-only files cannot be removed */
85faec9d
KB
311 _wchmod(wpathname, 0666);
312 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
19e12549
HV
313 if (!is_file_in_use_error(GetLastError()))
314 break;
315 /*
316 * We assume that some other process had the source or
317 * destination file open at the wrong moment and retry.
318 * In order to give the other process a higher chance to
319 * complete its operation, we give up our time slice now.
320 * If we have to retry again, we do sleep a bit.
321 */
322 Sleep(delay[tries]);
323 tries++;
324 }
c9b78400
HV
325 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
326 ask_yes_no_if_possible("Unlink of file '%s' failed. "
327 "Should I try again?", pathname))
85faec9d 328 ret = _wunlink(wpathname);
19e12549 329 return ret;
337967fb
HV
330}
331
85faec9d 332static int is_dir_empty(const wchar_t *wpath)
ab1a11be 333{
85faec9d 334 WIN32_FIND_DATAW findbuf;
ab1a11be 335 HANDLE handle;
85faec9d
KB
336 wchar_t wbuf[MAX_PATH + 2];
337 wcscpy(wbuf, wpath);
338 wcscat(wbuf, L"\\*");
339 handle = FindFirstFileW(wbuf, &findbuf);
340 if (handle == INVALID_HANDLE_VALUE)
ab1a11be 341 return GetLastError() == ERROR_NO_MORE_FILES;
ab1a11be 342
85faec9d
KB
343 while (!wcscmp(findbuf.cFileName, L".") ||
344 !wcscmp(findbuf.cFileName, L".."))
345 if (!FindNextFileW(handle, &findbuf)) {
346 DWORD err = GetLastError();
347 FindClose(handle);
348 return err == ERROR_NO_MORE_FILES;
ab1a11be
JS
349 }
350 FindClose(handle);
ab1a11be
JS
351 return 0;
352}
353
4f288100
HV
354int mingw_rmdir(const char *pathname)
355{
356 int ret, tries = 0;
85faec9d 357 wchar_t wpathname[MAX_PATH];
3e7d4888
TB
358 struct stat st;
359
360 /*
361 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
362 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
363 * symbolic link (if it points to a directory).
364 *
365 * This behavior breaks the assumption of e.g. `remove_path()` which
366 * upon successful deletion of a file will attempt to remove its parent
367 * directories recursively until failure (which usually happens when
368 * the directory is not empty).
369 *
370 * Therefore, before calling `_wrmdir()`, we first check if the path is
371 * a symbolic link. If it is, we exit and return the same error as
372 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
373 */
374 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
375 errno = ENOTDIR;
376 return -1;
377 }
378
85faec9d
KB
379 if (xutftowcs_path(wpathname, pathname) < 0)
380 return -1;
4f288100 381
85faec9d 382 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
4f288100 383 if (!is_file_in_use_error(GetLastError()))
a83b2b57
EFL
384 errno = err_win_to_posix(GetLastError());
385 if (errno != EACCES)
4f288100 386 break;
85faec9d 387 if (!is_dir_empty(wpathname)) {
ab1a11be
JS
388 errno = ENOTEMPTY;
389 break;
390 }
4f288100
HV
391 /*
392 * We assume that some other process had the source or
393 * destination file open at the wrong moment and retry.
394 * In order to give the other process a higher chance to
395 * complete its operation, we give up our time slice now.
396 * If we have to retry again, we do sleep a bit.
397 */
398 Sleep(delay[tries]);
399 tries++;
400 }
a83b2b57 401 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
4f288100
HV
402 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
403 "Should I try again?", pathname))
85faec9d 404 ret = _wrmdir(wpathname);
684dd4c2
MT
405 if (!ret)
406 invalidate_lstat_cache();
85faec9d
KB
407 return ret;
408}
409
f30afdab
JS
410static inline int needs_hiding(const char *path)
411{
412 const char *basename;
413
414 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
415 return 0;
416
417 /* We cannot use basename(), as it would remove trailing slashes */
1cadad6f 418 win32_skip_dos_drive_prefix((char **)&path);
f30afdab
JS
419 if (!*path)
420 return 0;
421
422 for (basename = path; *path; path++)
423 if (is_dir_sep(*path)) {
424 do {
425 path++;
426 } while (is_dir_sep(*path));
427 /* ignore trailing slashes */
428 if (*path)
429 basename = path;
60e6569a
JS
430 else
431 break;
f30afdab
JS
432 }
433
434 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
435 return *basename == '.';
436
437 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
438 return !strncasecmp(".git", basename, 4) &&
439 (!basename[4] || is_dir_sep(basename[4]));
440}
441
442static int set_hidden_flag(const wchar_t *path, int set)
443{
444 DWORD original = GetFileAttributesW(path), modified;
445 if (set)
446 modified = original | FILE_ATTRIBUTE_HIDDEN;
447 else
448 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
449 if (original == modified || SetFileAttributesW(path, modified))
450 return 0;
451 errno = err_win_to_posix(GetLastError());
452 return -1;
453}
454
85faec9d
KB
455int mingw_mkdir(const char *path, int mode)
456{
457 int ret;
458 wchar_t wpath[MAX_PATH];
d2c84dad 459
4dc42c6c 460 if (!is_valid_win32_path(path, 0)) {
d2c84dad
JS
461 errno = EINVAL;
462 return -1;
463 }
464
85faec9d
KB
465 if (xutftowcs_path(wpath, path) < 0)
466 return -1;
467 ret = _wmkdir(wpath);
f30afdab
JS
468 if (!ret && needs_hiding(path))
469 return set_hidden_flag(wpath, 1);
4f288100
HV
470 return ret;
471}
472
eeaf7dda
JH
473/*
474 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
475 * is documented in [1] as opening a writable file handle in append mode.
476 * (It is believed that) this is atomic since it is maintained by the
477 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
478 *
479 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
480 *
481 * This trick does not appear to work for named pipes. Instead it creates
482 * a named pipe client handle that cannot be written to. Callers should
483 * just use the regular _wopen() for them. (And since client handle gets
484 * bound to a unique server handle, it isn't really an issue.)
485 */
d6410975
JS
486static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
487{
488 HANDLE handle;
489 int fd;
490 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
491
492 /* only these flags are supported */
493 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
494 return errno = ENOSYS, -1;
495
496 /*
497 * FILE_SHARE_WRITE is required to permit child processes
498 * to append to the file.
499 */
500 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
501 FILE_SHARE_WRITE | FILE_SHARE_READ,
502 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
23eafd92
NS
503 if (handle == INVALID_HANDLE_VALUE) {
504 DWORD err = GetLastError();
505
506 /*
507 * Some network storage solutions (e.g. Isilon) might return
508 * ERROR_INVALID_PARAMETER instead of expected error
509 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
510 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
511 */
512 if (err == ERROR_INVALID_PARAMETER)
513 err = ERROR_PATH_NOT_FOUND;
514
515 errno = err_win_to_posix(err);
516 return -1;
517 }
eeaf7dda 518
d6410975
JS
519 /*
520 * No O_APPEND here, because the CRT uses it only to reset the
eeaf7dda
JH
521 * file pointer to EOF before each write(); but that is not
522 * necessary (and may lead to races) for a file created with
523 * FILE_APPEND_DATA.
d6410975
JS
524 */
525 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
526 if (fd < 0)
527 CloseHandle(handle);
528 return fd;
529}
530
eeaf7dda
JH
531/*
532 * Does the pathname map to the local named pipe filesystem?
533 * That is, does it have a "//./pipe/" prefix?
534 */
535static int is_local_named_pipe_path(const char *filename)
536{
537 return (is_dir_sep(filename[0]) &&
538 is_dir_sep(filename[1]) &&
539 filename[2] == '.' &&
540 is_dir_sep(filename[3]) &&
541 !strncasecmp(filename+4, "pipe", 4) &&
542 is_dir_sep(filename[8]) &&
543 filename[9]);
544}
545
3e4a1ba0
JS
546int mingw_open (const char *filename, int oflags, ...)
547{
d6410975 548 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
3e4a1ba0
JS
549 va_list args;
550 unsigned mode;
d2c84dad 551 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
85faec9d 552 wchar_t wfilename[MAX_PATH];
d6410975 553 open_fn_t open_fn;
0d30ad71 554
3e4a1ba0
JS
555 va_start(args, oflags);
556 mode = va_arg(args, int);
557 va_end(args);
558
4dc42c6c 559 if (!is_valid_win32_path(filename, !create)) {
d2c84dad
JS
560 errno = create ? EINVAL : ENOENT;
561 return -1;
562 }
563
eeaf7dda 564 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
d6410975
JS
565 open_fn = mingw_open_append;
566 else
567 open_fn = _wopen;
568
98d9b23e
JS
569 if (filename && !strcmp(filename, "/dev/null"))
570 wcscpy(wfilename, L"nul");
571 else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 572 return -1;
98d9b23e 573
d6410975 574 fd = open_fn(wfilename, oflags, mode);
0d30ad71 575
ba6fad02 576 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
85faec9d 577 DWORD attrs = GetFileAttributesW(wfilename);
3e4a1ba0
JS
578 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
579 errno = EISDIR;
580 }
f30afdab
JS
581 if ((oflags & O_CREAT) && needs_hiding(filename)) {
582 /*
583 * Internally, _wopen() uses the CreateFile() API which errors
584 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
585 * specified and an already existing file's attributes do not
586 * match *exactly*. As there is no mode or flag we can set that
587 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
588 * again *without* the O_CREAT flag (that corresponds to the
589 * CREATE_ALWAYS flag of CreateFile()).
590 */
591 if (fd < 0 && errno == EACCES)
d6410975 592 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
f30afdab
JS
593 if (fd >= 0 && set_hidden_flag(wfilename, 1))
594 warning("could not mark '%s' as hidden.", filename);
595 }
3e4a1ba0
JS
596 return fd;
597}
598
176478a8
EFL
599static BOOL WINAPI ctrl_ignore(DWORD type)
600{
601 return TRUE;
602}
603
604#undef fgetc
605int mingw_fgetc(FILE *stream)
606{
607 int ch;
608 if (!isatty(_fileno(stream)))
609 return fgetc(stream);
610
611 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
612 while (1) {
613 ch = fgetc(stream);
614 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
615 break;
616
617 /* Ctrl+C was pressed, simulate SIGINT and retry */
618 mingw_raise(SIGINT);
619 }
620 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
621 return ch;
622}
623
3fdcdbdf
JS
624#undef fopen
625FILE *mingw_fopen (const char *filename, const char *otype)
626{
f30afdab 627 int hide = needs_hiding(filename);
85faec9d
KB
628 FILE *file;
629 wchar_t wfilename[MAX_PATH], wotype[4];
4dc42c6c
JS
630 if (filename && !strcmp(filename, "/dev/null"))
631 wcscpy(wfilename, L"nul");
632 else if (!is_valid_win32_path(filename, 1)) {
d2c84dad
JS
633 int create = otype && strchr(otype, 'w');
634 errno = create ? EINVAL : ENOENT;
635 return NULL;
4dc42c6c 636 } else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 637 return NULL;
98d9b23e
JS
638
639 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
85faec9d 640 return NULL;
98d9b23e 641
f30afdab
JS
642 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
643 error("could not unhide %s", filename);
644 return NULL;
645 }
85faec9d 646 file = _wfopen(wfilename, wotype);
e5b31344
JS
647 if (!file && GetLastError() == ERROR_INVALID_NAME)
648 errno = ENOENT;
f30afdab
JS
649 if (file && hide && set_hidden_flag(wfilename, 1))
650 warning("could not mark '%s' as hidden.", filename);
85faec9d 651 return file;
3fdcdbdf
JS
652}
653
3fdcdbdf
JS
654FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
655{
f30afdab 656 int hide = needs_hiding(filename);
85faec9d
KB
657 FILE *file;
658 wchar_t wfilename[MAX_PATH], wotype[4];
4dc42c6c
JS
659 if (filename && !strcmp(filename, "/dev/null"))
660 wcscpy(wfilename, L"nul");
661 else if (!is_valid_win32_path(filename, 1)) {
d2c84dad
JS
662 int create = otype && strchr(otype, 'w');
663 errno = create ? EINVAL : ENOENT;
664 return NULL;
4dc42c6c 665 } else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 666 return NULL;
98d9b23e
JS
667
668 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
85faec9d 669 return NULL;
98d9b23e 670
f30afdab
JS
671 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
672 error("could not unhide %s", filename);
673 return NULL;
674 }
85faec9d 675 file = _wfreopen(wfilename, wotype, stream);
f30afdab
JS
676 if (file && hide && set_hidden_flag(wfilename, 1))
677 warning("could not mark '%s' as hidden.", filename);
85faec9d 678 return file;
3fdcdbdf
JS
679}
680
84adb641
JS
681#undef fflush
682int mingw_fflush(FILE *stream)
683{
684 int ret = fflush(stream);
685
686 /*
687 * write() is used behind the scenes of stdio output functions.
688 * Since git code does not check for errors after each stdio write
689 * operation, it can happen that write() is called by a later
690 * stdio function even if an earlier write() call failed. In the
691 * case of a pipe whose readable end was closed, only the first
692 * call to write() reports EPIPE on Windows. Subsequent write()
693 * calls report EINVAL. It is impossible to notice whether this
694 * fflush invocation triggered such a case, therefore, we have to
695 * catch all EINVAL errors whole-sale.
696 */
697 if (ret && errno == EINVAL)
698 errno = EPIPE;
699
700 return ret;
701}
702
2b86292e
JS
703#undef write
704ssize_t mingw_write(int fd, const void *buf, size_t len)
705{
706 ssize_t result = write(fd, buf, len);
707
19ed0dff
JS
708 if (result < 0 && (errno == EINVAL || errno == ENOSPC) && buf) {
709 int orig = errno;
710
2b86292e
JS
711 /* check if fd is a pipe */
712 HANDLE h = (HANDLE) _get_osfhandle(fd);
19ed0dff
JS
713 if (GetFileType(h) != FILE_TYPE_PIPE)
714 errno = orig;
715 else if (orig == EINVAL)
2b86292e 716 errno = EPIPE;
19ed0dff
JS
717 else {
718 DWORD buf_size;
719
720 if (!GetNamedPipeInfo(h, NULL, NULL, &buf_size, NULL))
721 buf_size = 4096;
722 if (len > buf_size)
723 return write(fd, buf, buf_size);
724 errno = orig;
725 }
2b86292e
JS
726 }
727
728 return result;
729}
730
85faec9d
KB
731int mingw_access(const char *filename, int mode)
732{
733 wchar_t wfilename[MAX_PATH];
9160068a
JS
734 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
735 return 0;
85faec9d
KB
736 if (xutftowcs_path(wfilename, filename) < 0)
737 return -1;
738 /* X_OK is not supported by the MSVCRT version */
739 return _waccess(wfilename, mode & ~X_OK);
740}
741
742int mingw_chdir(const char *dirname)
743{
744 wchar_t wdirname[MAX_PATH];
745 if (xutftowcs_path(wdirname, dirname) < 0)
746 return -1;
747 return _wchdir(wdirname);
748}
749
750int mingw_chmod(const char *filename, int mode)
751{
752 wchar_t wfilename[MAX_PATH];
753 if (xutftowcs_path(wfilename, filename) < 0)
754 return -1;
755 return _wchmod(wfilename, mode);
756}
757
a6d15bc3
JS
758/*
759 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
760 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
761 */
762static inline long long filetime_to_hnsec(const FILETIME *ft)
5411bdc4
MSO
763{
764 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
a6d15bc3
JS
765 /* Windows to Unix Epoch conversion */
766 return winTime - 116444736000000000LL;
767}
768
d7e8c874 769static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
a6d15bc3 770{
d7e8c874
KB
771 long long hnsec = filetime_to_hnsec(ft);
772 ts->tv_sec = (time_t)(hnsec / 10000000);
773 ts->tv_nsec = (hnsec % 10000000) * 100;
5411bdc4
MSO
774}
775
4b0abd5c
JS
776/**
777 * Verifies that safe_create_leading_directories() would succeed.
778 */
779static int has_valid_directory_prefix(wchar_t *wfilename)
780{
781 int n = wcslen(wfilename);
782
783 while (n > 0) {
784 wchar_t c = wfilename[--n];
785 DWORD attributes;
786
787 if (!is_dir_sep(c))
788 continue;
789
790 wfilename[n] = L'\0';
791 attributes = GetFileAttributesW(wfilename);
792 wfilename[n] = c;
82ba1191
JS
793 if (attributes &
794 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
4b0abd5c
JS
795 return 1;
796 if (attributes == INVALID_FILE_ATTRIBUTES)
797 switch (GetLastError()) {
798 case ERROR_PATH_NOT_FOUND:
799 continue;
800 case ERROR_FILE_NOT_FOUND:
801 /* This implies parent directory exists. */
802 return 1;
803 }
804 return 0;
805 }
806 return 1;
807}
808
5411bdc4
MSO
809/* We keep the do_lstat code in a separate function to avoid recursion.
810 * When a path ends with a slash, the stat will fail with ENOENT. In
811 * this case, we strip the trailing slashes and stat again.
9b9784ca
PT
812 *
813 * If follow is true then act like stat() and report on the link
814 * target. Otherwise report on the link itself.
5411bdc4 815 */
9b9784ca 816static int do_lstat(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
817{
818 WIN32_FILE_ATTRIBUTE_DATA fdata;
85faec9d
KB
819 wchar_t wfilename[MAX_PATH];
820 if (xutftowcs_path(wfilename, file_name) < 0)
821 return -1;
5411bdc4 822
85faec9d 823 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
5411bdc4
MSO
824 buf->st_ino = 0;
825 buf->st_gid = 0;
826 buf->st_uid = 0;
180964f0 827 buf->st_nlink = 1;
444dc903 828 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
1d4e4cd4
JS
829 buf->st_size = fdata.nFileSizeLow |
830 (((off_t)fdata.nFileSizeHigh)<<32);
8252df62 831 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
832 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
833 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
834 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
9b9784ca 835 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
85faec9d
KB
836 WIN32_FIND_DATAW findbuf;
837 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
9b9784ca
PT
838 if (handle != INVALID_HANDLE_VALUE) {
839 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
840 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
841 if (follow) {
842 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
843 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
844 } else {
845 buf->st_mode = S_IFLNK;
846 }
847 buf->st_mode |= S_IREAD;
848 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
849 buf->st_mode |= S_IWRITE;
850 }
851 FindClose(handle);
852 }
853 }
5411bdc4
MSO
854 return 0;
855 }
85faec9d
KB
856 switch (GetLastError()) {
857 case ERROR_ACCESS_DENIED:
858 case ERROR_SHARING_VIOLATION:
859 case ERROR_LOCK_VIOLATION:
860 case ERROR_SHARING_BUFFER_EXCEEDED:
861 errno = EACCES;
862 break;
863 case ERROR_BUFFER_OVERFLOW:
864 errno = ENAMETOOLONG;
865 break;
866 case ERROR_NOT_ENOUGH_MEMORY:
867 errno = ENOMEM;
868 break;
4b0abd5c
JS
869 case ERROR_PATH_NOT_FOUND:
870 if (!has_valid_directory_prefix(wfilename)) {
871 errno = ENOTDIR;
872 break;
873 }
874 /* fallthru */
85faec9d
KB
875 default:
876 errno = ENOENT;
877 break;
878 }
5411bdc4
MSO
879 return -1;
880}
881
882/* We provide our own lstat/fstat functions, since the provided
883 * lstat/fstat functions are so slow. These stat functions are
884 * tailored for Git's usage (read: fast), and are not meant to be
885 * complete. Note that Git stat()s are redirected to mingw_lstat()
886 * too, since Windows doesn't really handle symlinks that well.
887 */
9b9784ca 888static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
889{
890 int namelen;
58aa3d2a 891 char alt_name[PATH_MAX];
5411bdc4 892
9b9784ca 893 if (!do_lstat(follow, file_name, buf))
5411bdc4
MSO
894 return 0;
895
896 /* if file_name ended in a '/', Windows returned ENOENT;
897 * try again without trailing slashes
898 */
899 if (errno != ENOENT)
900 return -1;
901
902 namelen = strlen(file_name);
903 if (namelen && file_name[namelen-1] != '/')
904 return -1;
905 while (namelen && file_name[namelen-1] == '/')
906 --namelen;
907 if (!namelen || namelen >= PATH_MAX)
908 return -1;
909
910 memcpy(alt_name, file_name, namelen);
911 alt_name[namelen] = 0;
9b9784ca
PT
912 return do_lstat(follow, alt_name, buf);
913}
914
7bf19838
JS
915static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
916{
917 BY_HANDLE_FILE_INFORMATION fdata;
918
919 if (!GetFileInformationByHandle(hnd, &fdata)) {
920 errno = err_win_to_posix(GetLastError());
921 return -1;
922 }
923
924 buf->st_ino = 0;
925 buf->st_gid = 0;
926 buf->st_uid = 0;
927 buf->st_nlink = 1;
928 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
929 buf->st_size = fdata.nFileSizeLow |
930 (((off_t)fdata.nFileSizeHigh)<<32);
931 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
932 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
933 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
934 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
7bf19838
JS
935 return 0;
936}
937
9b9784ca
PT
938int mingw_lstat(const char *file_name, struct stat *buf)
939{
940 return do_stat_internal(0, file_name, buf);
941}
942int mingw_stat(const char *file_name, struct stat *buf)
943{
944 return do_stat_internal(1, file_name, buf);
5411bdc4
MSO
945}
946
180964f0 947int mingw_fstat(int fd, struct stat *buf)
5411bdc4
MSO
948{
949 HANDLE fh = (HANDLE)_get_osfhandle(fd);
d75e6973 950 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
5411bdc4 951
d75e6973
KB
952 switch (type) {
953 case FILE_TYPE_DISK:
954 return get_file_info_by_handle(fh, buf);
5411bdc4 955
d75e6973
KB
956 case FILE_TYPE_CHAR:
957 case FILE_TYPE_PIPE:
958 /* initialize stat fields */
959 memset(buf, 0, sizeof(*buf));
180964f0 960 buf->st_nlink = 1;
d75e6973
KB
961
962 if (type == FILE_TYPE_CHAR) {
963 buf->st_mode = _S_IFCHR;
964 } else {
965 buf->st_mode = _S_IFIFO;
966 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
967 buf->st_size = avail;
968 }
5411bdc4 969 return 0;
7bf19838 970
d75e6973
KB
971 default:
972 errno = EBADF;
973 return -1;
5411bdc4 974 }
5411bdc4
MSO
975}
976
7c0ffa1c
JS
977static inline void time_t_to_filetime(time_t t, FILETIME *ft)
978{
979 long long winTime = t * 10000000LL + 116444736000000000LL;
980 ft->dwLowDateTime = winTime;
981 ft->dwHighDateTime = winTime >> 32;
982}
983
984int mingw_utime (const char *file_name, const struct utimbuf *times)
985{
986 FILETIME mft, aft;
090a3085 987 int rc;
85faec9d
KB
988 DWORD attrs;
989 wchar_t wfilename[MAX_PATH];
090a3085
TK
990 HANDLE osfilehandle;
991
85faec9d
KB
992 if (xutftowcs_path(wfilename, file_name) < 0)
993 return -1;
7c0ffa1c
JS
994
995 /* must have write permission */
85faec9d 996 attrs = GetFileAttributesW(wfilename);
852f098c
JS
997 if (attrs != INVALID_FILE_ATTRIBUTES &&
998 (attrs & FILE_ATTRIBUTE_READONLY)) {
999 /* ignore errors here; open() will report them */
85faec9d 1000 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
852f098c
JS
1001 }
1002
090a3085
TK
1003 osfilehandle = CreateFileW(wfilename,
1004 FILE_WRITE_ATTRIBUTES,
1005 0 /*FileShare.None*/,
1006 NULL,
1007 OPEN_EXISTING,
1008 (attrs != INVALID_FILE_ATTRIBUTES &&
1009 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
1010 FILE_FLAG_BACKUP_SEMANTICS : 0,
1011 NULL);
1012 if (osfilehandle == INVALID_HANDLE_VALUE) {
1013 errno = err_win_to_posix(GetLastError());
852f098c
JS
1014 rc = -1;
1015 goto revert_attrs;
1016 }
7c0ffa1c 1017
ded2d476
SG
1018 if (times) {
1019 time_t_to_filetime(times->modtime, &mft);
1020 time_t_to_filetime(times->actime, &aft);
1021 } else {
1022 GetSystemTimeAsFileTime(&mft);
1023 aft = mft;
1024 }
090a3085
TK
1025
1026 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
7c0ffa1c
JS
1027 errno = EINVAL;
1028 rc = -1;
1029 } else
1030 rc = 0;
090a3085
TK
1031
1032 if (osfilehandle != INVALID_HANDLE_VALUE)
1033 CloseHandle(osfilehandle);
852f098c
JS
1034
1035revert_attrs:
1036 if (attrs != INVALID_FILE_ATTRIBUTES &&
1037 (attrs & FILE_ATTRIBUTE_READONLY)) {
1038 /* ignore errors again */
85faec9d 1039 SetFileAttributesW(wfilename, attrs);
852f098c 1040 }
7c0ffa1c
JS
1041 return rc;
1042}
1043
9ee0540a
JS
1044#undef strftime
1045size_t mingw_strftime(char *s, size_t max,
1046 const char *format, const struct tm *tm)
1047{
a748f3f3
MA
1048 /* a pointer to the original strftime in case we can't find the UCRT version */
1049 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1050 size_t ret;
4a9b2049 1051 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
a748f3f3
MA
1052 const char *, const struct tm *);
1053
1054 if (INIT_PROC_ADDR(strftime))
1055 ret = strftime(s, max, format, tm);
1056 else
1057 ret = fallback(s, max, format, tm);
9ee0540a
JS
1058
1059 if (!ret && errno == EINVAL)
1060 die("invalid strftime format: '%s'", format);
1061 return ret;
1062}
1063
f4626df5
JS
1064unsigned int sleep (unsigned int seconds)
1065{
1066 Sleep(seconds*1000);
1067 return 0;
1068}
1069
85faec9d
KB
1070char *mingw_mktemp(char *template)
1071{
1072 wchar_t wtemplate[MAX_PATH];
1073 if (xutftowcs_path(wtemplate, template) < 0)
1074 return NULL;
1075 if (!_wmktemp(wtemplate))
1076 return NULL;
1077 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1078 return NULL;
1079 return template;
1080}
1081
f4626df5
JS
1082int mkstemp(char *template)
1083{
ae25974d 1084 return git_mkstemp_mode(template, 0600);
f4626df5
JS
1085}
1086
1087int gettimeofday(struct timeval *tv, void *tz)
1088{
a6d15bc3
JS
1089 FILETIME ft;
1090 long long hnsec;
1091
1092 GetSystemTimeAsFileTime(&ft);
1093 hnsec = filetime_to_hnsec(&ft);
1094 tv->tv_sec = hnsec / 10000000;
1095 tv->tv_usec = (hnsec % 10000000) / 10;
a42a0c2e 1096 return 0;
f4626df5
JS
1097}
1098
897bb8cb
JS
1099int pipe(int filedes[2])
1100{
3e34d665 1101 HANDLE h[2];
897bb8cb 1102
3e34d665
JS
1103 /* this creates non-inheritable handles */
1104 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1105 errno = err_win_to_posix(GetLastError());
897bb8cb
JS
1106 return -1;
1107 }
7c00bc39 1108 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
3e34d665 1109 if (filedes[0] < 0) {
897bb8cb
JS
1110 CloseHandle(h[0]);
1111 CloseHandle(h[1]);
1112 return -1;
1113 }
7c00bc39 1114 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
c3cb7b6f 1115 if (filedes[1] < 0) {
897bb8cb 1116 close(filedes[0]);
897bb8cb
JS
1117 CloseHandle(h[1]);
1118 return -1;
1119 }
897bb8cb
JS
1120 return 0;
1121}
1122
9e12400d 1123#ifndef __MINGW64__
f4626df5
JS
1124struct tm *gmtime_r(const time_t *timep, struct tm *result)
1125{
0109d676
ĐTCD
1126 if (gmtime_s(result, timep) == 0)
1127 return result;
1128 return NULL;
f4626df5
JS
1129}
1130
1131struct tm *localtime_r(const time_t *timep, struct tm *result)
1132{
0109d676
ĐTCD
1133 if (localtime_s(result, timep) == 0)
1134 return result;
1135 return NULL;
f4626df5 1136}
9e12400d 1137#endif
f4626df5 1138
25fe217b
JS
1139char *mingw_getcwd(char *pointer, int len)
1140{
937974fc
JS
1141 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1142 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1143
1144 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1145 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1146 return NULL;
1147 }
1148 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
4745feeb
AS
1149 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1150 HANDLE hnd = CreateFileW(cwd, 0,
1151 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1152 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1153 if (hnd == INVALID_HANDLE_VALUE)
1154 return NULL;
1155 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1156 CloseHandle(hnd);
1157 if (!ret || ret >= ARRAY_SIZE(wpointer))
1158 return NULL;
1159 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1160 return NULL;
1161 return pointer;
1162 }
937974fc 1163 if (!ret || ret >= ARRAY_SIZE(wpointer))
85faec9d 1164 return NULL;
e2724c1e
JS
1165 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1166 errno = ENOENT;
1167 return NULL;
1168 }
85faec9d
KB
1169 if (xwcstoutf(pointer, wpointer, len) < 0)
1170 return NULL;
8e9b2080 1171 convert_slashes(pointer);
85faec9d 1172 return pointer;
25fe217b
JS
1173}
1174
7e5d7768 1175/*
2ef2ae29
JS
1176 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1177 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
7e5d7768 1178 */
9e9da23c 1179static const char *quote_arg_msvc(const char *arg)
7e5d7768
JS
1180{
1181 /* count chars to quote */
1182 int len = 0, n = 0;
1183 int force_quotes = 0;
1184 char *q, *d;
1185 const char *p = arg;
1186 if (!*p) force_quotes = 1;
1187 while (*p) {
3aea1a5a 1188 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
7e5d7768
JS
1189 force_quotes = 1;
1190 else if (*p == '"')
1191 n++;
1192 else if (*p == '\\') {
1193 int count = 0;
1194 while (*p == '\\') {
1195 count++;
1196 p++;
1197 len++;
1198 }
6d868416 1199 if (*p == '"' || !*p)
7e5d7768
JS
1200 n += count*2 + 1;
1201 continue;
1202 }
1203 len++;
1204 p++;
1205 }
1206 if (!force_quotes && n == 0)
1207 return arg;
1208
1209 /* insert \ where necessary */
50a6c8ef 1210 d = q = xmalloc(st_add3(len, n, 3));
7e5d7768
JS
1211 *d++ = '"';
1212 while (*arg) {
1213 if (*arg == '"')
1214 *d++ = '\\';
1215 else if (*arg == '\\') {
1216 int count = 0;
1217 while (*arg == '\\') {
1218 count++;
1219 *d++ = *arg++;
1220 }
6d868416 1221 if (*arg == '"' || !*arg) {
7e5d7768
JS
1222 while (count-- > 0)
1223 *d++ = '\\';
6d868416
JS
1224 /* don't escape the surrounding end quote */
1225 if (!*arg)
1226 break;
7e5d7768
JS
1227 *d++ = '\\';
1228 }
1229 }
1230 *d++ = *arg++;
1231 }
1232 *d++ = '"';
6d868416 1233 *d++ = '\0';
7e5d7768
JS
1234 return q;
1235}
1236
9e9da23c
JS
1237#include "quote.h"
1238
1239static const char *quote_arg_msys2(const char *arg)
1240{
1241 struct strbuf buf = STRBUF_INIT;
1242 const char *p2 = arg, *p;
1243
1244 for (p = arg; *p; p++) {
1245 int ws = isspace(*p);
7d8b6769
JS
1246 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1247 *p != '?' && *p != '*' && *p != '~')
9e9da23c
JS
1248 continue;
1249 if (!buf.len)
1250 strbuf_addch(&buf, '"');
1251 if (p != p2)
1252 strbuf_add(&buf, p2, p - p2);
7d8b6769 1253 if (*p == '\\' || *p == '"')
9e9da23c
JS
1254 strbuf_addch(&buf, '\\');
1255 p2 = p;
1256 }
1257
1258 if (p == arg)
1259 strbuf_addch(&buf, '"');
1260 else if (!buf.len)
1261 return arg;
1262 else
04522edb 1263 strbuf_add(&buf, p2, p - p2);
9e9da23c
JS
1264
1265 strbuf_addch(&buf, '"');
1266 return strbuf_detach(&buf, 0);
1267}
1268
f1a4dfb8
JS
1269static const char *parse_interpreter(const char *cmd)
1270{
1271 static char buf[100];
1272 char *p, *opt;
1273 int n, fd;
1274
1275 /* don't even try a .exe */
1276 n = strlen(cmd);
1277 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1278 return NULL;
1279
1280 fd = open(cmd, O_RDONLY);
1281 if (fd < 0)
1282 return NULL;
1283 n = read(fd, buf, sizeof(buf)-1);
1284 close(fd);
1285 if (n < 4) /* at least '#!/x' and not error */
1286 return NULL;
1287
1288 if (buf[0] != '#' || buf[1] != '!')
1289 return NULL;
1290 buf[n] = '\0';
bedc4279
PH
1291 p = buf + strcspn(buf, "\r\n");
1292 if (!*p)
f1a4dfb8
JS
1293 return NULL;
1294
1295 *p = '\0';
1296 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1297 return NULL;
1298 /* strip options */
1299 if ((opt = strchr(p+1, ' ')))
1300 *opt = '\0';
1301 return p+1;
1302}
1303
f1a4dfb8
JS
1304/*
1305 * exe_only means that we only want to detect .exe files, but not scripts
1306 * (which do not have an extension)
1307 */
e0ca1ca2
RS
1308static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1309 int isexe, int exe_only)
f1a4dfb8
JS
1310{
1311 char path[MAX_PATH];
4e1a641e 1312 wchar_t wpath[MAX_PATH];
e0ca1ca2 1313 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
f1a4dfb8 1314
4e1a641e
AR
1315 if (xutftowcs_path(wpath, path) < 0)
1316 return NULL;
1317
1318 if (!isexe && _waccess(wpath, F_OK) == 0)
f1a4dfb8 1319 return xstrdup(path);
4e1a641e
AR
1320 wpath[wcslen(wpath)-4] = '\0';
1321 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1322 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1323 path[strlen(path)-4] = '\0';
fe77b695 1324 return xstrdup(path);
4e1a641e
AR
1325 }
1326 }
f1a4dfb8
JS
1327 return NULL;
1328}
1329
1330/*
22e5e58a 1331 * Determines the absolute path of cmd using the split path in path.
f1a4dfb8
JS
1332 * If cmd contains a slash or backslash, no lookup is performed.
1333 */
e0ca1ca2 1334static char *path_lookup(const char *cmd, int exe_only)
f1a4dfb8 1335{
e0ca1ca2 1336 const char *path;
f1a4dfb8
JS
1337 char *prog = NULL;
1338 int len = strlen(cmd);
1339 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1340
2ce6d075 1341 if (strpbrk(cmd, "/\\"))
e0ca1ca2
RS
1342 return xstrdup(cmd);
1343
1344 path = mingw_getenv("PATH");
1345 if (!path)
1346 return NULL;
f1a4dfb8 1347
e0ca1ca2
RS
1348 while (!prog) {
1349 const char *sep = strchrnul(path, ';');
1350 int dirlen = sep - path;
1351 if (dirlen)
1352 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1353 if (!*sep)
1354 break;
1355 path = sep + 1;
1356 }
f1a4dfb8
JS
1357
1358 return prog;
1359}
1360
2bf46a9f
MA
1361char *mingw_locate_in_PATH(const char *cmd)
1362{
1363 return path_lookup(cmd, 0);
1364}
1365
fe21c6b2
JS
1366static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1367{
1368 while (*s && *s != c)
1369 s++;
1370 return s;
1371}
1372
1373/* Compare only keys */
1374static int wenvcmp(const void *a, const void *b)
1375{
1376 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1377 size_t p_len, q_len;
1378
1379 /* Find the keys */
1380 p_len = wcschrnul(p, L'=') - p;
1381 q_len = wcschrnul(q, L'=') - q;
f279242d 1382
fe21c6b2
JS
1383 /* If the length differs, include the shorter key's NUL */
1384 if (p_len < q_len)
1385 p_len++;
1386 else if (p_len > q_len)
1387 p_len = q_len + 1;
1388
1389 return _wcsnicmp(p, q, p_len);
1390}
f279242d 1391
df0e998c 1392/*
fe21c6b2
JS
1393 * Build an environment block combining the inherited environment
1394 * merged with the given list of settings.
1395 *
1396 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1397 * Values of the form "KEY" in deltaenv delete inherited values.
1398 *
1399 * Multiple entries in deltaenv for the same key are explicitly allowed.
1400 *
1401 * We return a contiguous block of UNICODE strings with a final trailing
1402 * zero word.
df0e998c 1403 */
77734da2 1404static wchar_t *make_environment_block(char **deltaenv)
7e5d7768 1405{
fe21c6b2
JS
1406 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1407 size_t wlen, s, delta_size, size;
df0e998c 1408
fe21c6b2
JS
1409 wchar_t **array = NULL;
1410 size_t alloc = 0, nr = 0, i;
df0e998c 1411
fe21c6b2
JS
1412 size = 1; /* for extra NUL at the end */
1413
1414 /* If there is no deltaenv to apply, simply return a copy. */
1415 if (!deltaenv || !*deltaenv) {
1416 for (p = wenv; p && *p; ) {
1417 size_t s = wcslen(p) + 1;
1418 size += s;
1419 p += s;
1420 }
77734da2 1421
6e578410 1422 DUP_ARRAY(result, wenv, size);
fe21c6b2
JS
1423 FreeEnvironmentStringsW(wenv);
1424 return result;
1425 }
77734da2 1426
fe21c6b2
JS
1427 /*
1428 * If there is a deltaenv, let's accumulate all keys into `array`,
97fff610
JS
1429 * sort them using the stable git_stable_qsort() and then copy,
1430 * skipping duplicate keys
fe21c6b2
JS
1431 */
1432 for (p = wenv; p && *p; ) {
1433 ALLOC_GROW(array, nr + 1, alloc);
1434 s = wcslen(p) + 1;
1435 array[nr++] = p;
1436 p += s;
1437 size += s;
df0e998c 1438 }
fe21c6b2
JS
1439
1440 /* (over-)assess size needed for wchar version of deltaenv */
1441 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1442 delta_size += strlen(deltaenv[i]) * 2 + 1;
1443 ALLOC_ARRAY(wdeltaenv, delta_size);
1444
1445 /* convert the deltaenv, appending to array */
1446 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1447 ALLOC_GROW(array, nr + 1, alloc);
1448 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1449 array[nr++] = p;
1450 p += wlen + 1;
1451 }
df0e998c 1452
97fff610 1453 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
fe21c6b2 1454 ALLOC_ARRAY(result, size + delta_size);
df0e998c 1455
fe21c6b2
JS
1456 for (p = result, i = 0; i < nr; i++) {
1457 /* Skip any duplicate keys; last one wins */
1458 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1459 i++;
77734da2 1460
fe21c6b2
JS
1461 /* Skip "to delete" entry */
1462 if (!wcschr(array[i], L'='))
1463 continue;
77734da2 1464
fe21c6b2 1465 size = wcslen(array[i]) + 1;
552fc501 1466 COPY_ARRAY(p, array[i], size);
fe21c6b2 1467 p += size;
df0e998c 1468 }
fe21c6b2
JS
1469 *p = L'\0';
1470
1471 free(array);
1472 free(wdeltaenv);
1473 FreeEnvironmentStringsW(wenv);
1474 return result;
7e5d7768
JS
1475}
1476
0e218f91
JS
1477static void do_unset_environment_variables(void)
1478{
1479 static int done;
1480 char *p = unset_environment_variables;
1481
1482 if (done || !p)
1483 return;
1484 done = 1;
1485
1486 for (;;) {
1487 char *comma = strchr(p, ',');
1488
1489 if (comma)
1490 *comma = '\0';
1491 unsetenv(p);
1492 if (!comma)
1493 break;
1494 p = comma + 1;
1495 }
1496}
1497
52de4db5
EFL
1498struct pinfo_t {
1499 struct pinfo_t *next;
1500 pid_t pid;
1501 HANDLE proc;
657b35f4
RJ
1502};
1503static struct pinfo_t *pinfo = NULL;
52de4db5
EFL
1504CRITICAL_SECTION pinfo_cs;
1505
9e9da23c
JS
1506/* Used to match and chomp off path components */
1507static inline int match_last_path_component(const char *path, size_t *len,
1508 const char *component)
1509{
1510 size_t component_len = strlen(component);
1511 if (*len < component_len + 1 ||
1512 !is_dir_sep(path[*len - component_len - 1]) ||
1513 fspathncmp(path + *len - component_len, component, component_len))
1514 return 0;
1515 *len -= component_len + 1;
1516 /* chomp off repeated dir separators */
1517 while (*len > 0 && is_dir_sep(path[*len - 1]))
1518 (*len)--;
1519 return 1;
1520}
1521
1522static int is_msys2_sh(const char *cmd)
1523{
e2ba3d6f
JS
1524 if (!cmd)
1525 return 0;
1526
1527 if (!strcmp(cmd, "sh")) {
9e9da23c
JS
1528 static int ret = -1;
1529 char *p;
1530
1531 if (ret >= 0)
1532 return ret;
1533
1534 p = path_lookup(cmd, 0);
1535 if (!p)
1536 ret = 0;
1537 else {
1538 size_t len = strlen(p);
1539
1540 ret = match_last_path_component(p, &len, "sh.exe") &&
1541 match_last_path_component(p, &len, "bin") &&
1542 match_last_path_component(p, &len, "usr");
1543 free(p);
1544 }
1545 return ret;
1546 }
e2ba3d6f
JS
1547
1548 if (ends_with(cmd, "\\sh.exe")) {
1549 static char *sh;
1550
1551 if (!sh)
1552 sh = path_lookup("sh", 0);
1553
1554 return !fspathcmp(cmd, sh);
1555 }
1556
9e9da23c
JS
1557 return 0;
1558}
1559
77734da2 1560static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1561 const char *dir,
75301f90 1562 int prepend_cmd, int fhin, int fhout, int fherr)
7e5d7768 1563{
ac33519d 1564 static int restrict_handle_inheritance = -1;
9a780a38 1565 STARTUPINFOEXW si;
7e5d7768 1566 PROCESS_INFORMATION pi;
9a780a38
JS
1567 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1568 HANDLE stdhandles[3];
1569 DWORD stdhandles_count = 0;
1570 SIZE_T size;
7eb2619c
KB
1571 struct strbuf args;
1572 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1573 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
7e5d7768 1574 BOOL ret;
0e218f91 1575 HANDLE cons;
9e9da23c 1576 const char *(*quote_arg)(const char *arg) =
49f7a76d
JS
1577 is_msys2_sh(cmd ? cmd : *argv) ?
1578 quote_arg_msys2 : quote_arg_msvc;
3efc128c 1579 const char *strace_env;
0e218f91 1580
4d0375ca
JS
1581 /* Make sure to override previous errors, if any */
1582 errno = 0;
1583
ac33519d
JS
1584 if (restrict_handle_inheritance < 0)
1585 restrict_handle_inheritance = core_restrict_inherited_handles;
1586 /*
1587 * The following code to restrict which handles are inherited seems
1588 * to work properly only on Windows 7 and later, so let's disable it
1589 * on Windows Vista and 2008.
1590 */
1591 if (restrict_handle_inheritance < 0)
1592 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1593
0e218f91 1594 do_unset_environment_variables();
7e5d7768
JS
1595
1596 /* Determine whether or not we are associated to a console */
94238859 1597 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
7e5d7768
JS
1598 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1599 FILE_ATTRIBUTE_NORMAL, NULL);
1600 if (cons == INVALID_HANDLE_VALUE) {
1601 /* There is no console associated with this process.
1602 * Since the child is a console process, Windows
1603 * would normally create a console window. But
1604 * since we'll be redirecting std streams, we do
1605 * not need the console.
19fb896f
AG
1606 * It is necessary to use DETACHED_PROCESS
1607 * instead of CREATE_NO_WINDOW to make ssh
1608 * recognize that it has no console.
7e5d7768 1609 */
7eb2619c 1610 flags |= DETACHED_PROCESS;
7e5d7768
JS
1611 } else {
1612 /* There is already a console. If we specified
19fb896f 1613 * DETACHED_PROCESS here, too, Windows would
7e5d7768 1614 * disassociate the child from the console.
19fb896f 1615 * The same is true for CREATE_NO_WINDOW.
7e5d7768
JS
1616 * Go figure!
1617 */
7e5d7768
JS
1618 CloseHandle(cons);
1619 }
1620 memset(&si, 0, sizeof(si));
9a780a38
JS
1621 si.StartupInfo.cb = sizeof(si);
1622 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1623 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1624 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1625
1626 /* The list of handles cannot contain duplicates */
1627 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1628 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1629 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1630 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1631 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1632 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1633 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1634 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1635 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1636 if (stdhandles_count)
1637 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
7e5d7768 1638
eb7c7863
JS
1639 if (*argv && !strcmp(cmd, *argv))
1640 wcmd[0] = L'\0';
1641 else if (xutftowcs_path(wcmd, cmd) < 0)
99c3c76d
KB
1642 return -1;
1643 if (dir && xutftowcs_path(wdir, dir) < 0)
1644 return -1;
1645
7e5d7768
JS
1646 /* concatenate argv, quoting args as we go */
1647 strbuf_init(&args, 0);
1648 if (prepend_cmd) {
1649 char *quoted = (char *)quote_arg(cmd);
1650 strbuf_addstr(&args, quoted);
1651 if (quoted != cmd)
1652 free(quoted);
1653 }
1654 for (; *argv; argv++) {
1655 char *quoted = (char *)quote_arg(*argv);
1656 if (*args.buf)
1657 strbuf_addch(&args, ' ');
1658 strbuf_addstr(&args, quoted);
1659 if (quoted != *argv)
1660 free(quoted);
1661 }
1662
3efc128c
JS
1663 strace_env = getenv("GIT_STRACE_COMMANDS");
1664 if (strace_env) {
1665 char *p = path_lookup("strace.exe", 1);
1666 if (!p)
1667 return error("strace not found!");
1668 if (xutftowcs_path(wcmd, p) < 0) {
1669 free(p);
1670 return -1;
1671 }
1672 free(p);
1673 if (!strcmp("1", strace_env) ||
1674 !strcasecmp("yes", strace_env) ||
1675 !strcasecmp("true", strace_env))
1676 strbuf_insert(&args, 0, "strace ", 7);
1677 else {
1678 const char *quoted = quote_arg(strace_env);
1679 struct strbuf buf = STRBUF_INIT;
1680 strbuf_addf(&buf, "strace -o %s ", quoted);
1681 if (quoted != strace_env)
1682 free((char *)quoted);
1683 strbuf_insert(&args, 0, buf.buf, buf.len);
1684 strbuf_release(&buf);
1685 }
1686 }
1687
8d5b3325 1688 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
99c3c76d
KB
1689 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1690 strbuf_release(&args);
1691
77734da2 1692 wenvblk = make_environment_block(deltaenv);
7e5d7768
JS
1693
1694 memset(&pi, 0, sizeof(pi));
9a780a38
JS
1695 if (restrict_handle_inheritance && stdhandles_count &&
1696 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1697 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1698 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1699 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1700 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1701 UpdateProcThreadAttribute(attr_list, 0,
1702 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1703 stdhandles,
1704 stdhandles_count * sizeof(HANDLE),
1705 NULL, NULL)) {
1706 si.lpAttributeList = attr_list;
1707 flags |= EXTENDED_STARTUPINFO_PRESENT;
1708 }
1709
1710 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1711 stdhandles_count ? TRUE : FALSE,
1712 flags, wenvblk, dir ? wdir : NULL,
1713 &si.StartupInfo, &pi);
1714
1715 /*
1716 * On Windows 2008 R2, it seems that specifying certain types of handles
1717 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1718 * error. Rather than playing finicky and fragile games, let's just try
1719 * to detect this situation and simply try again without restricting any
1720 * handle inheritance. This is still better than failing to create
1721 * processes.
1722 */
1723 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1724 DWORD err = GetLastError();
1725 struct strbuf buf = STRBUF_INIT;
1726
1727 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1728 /*
1729 * On Windows 7 and earlier, handles on pipes and character
1730 * devices are inherited automatically, and cannot be
1731 * specified in the thread handle list. Rather than trying
1732 * to catch each and every corner case (and running the
1733 * chance of *still* forgetting a few), let's just fall
1734 * back to creating the process without trying to limit the
1735 * handle inheritance.
1736 */
1737 !(err == ERROR_INVALID_PARAMETER &&
1738 GetVersion() >> 16 < 9200) &&
1739 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1740 DWORD fl = 0;
1741 int i;
1742
1743 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1744
1745 for (i = 0; i < stdhandles_count; i++) {
1746 HANDLE h = stdhandles[i];
1747 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1748 "handle info (%d) %lx\n", i, h,
1749 GetFileType(h),
1750 GetHandleInformation(h, &fl),
1751 fl);
1752 }
1753 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1754 "at\nhttps://github.com/git-for-windows/"
1755 "git/issues/new\n\n"
1756 "To suppress this warning, please set "
1757 "the environment variable\n\n"
1758 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1759 "\n");
1760 }
1761 restrict_handle_inheritance = 0;
1762 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1763 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1764 TRUE, flags, wenvblk, dir ? wdir : NULL,
1765 &si.StartupInfo, &pi);
4d0375ca 1766 if (!ret)
9a780a38 1767 errno = err_win_to_posix(GetLastError());
4d0375ca 1768 if (ret && buf.len) {
9a780a38
JS
1769 warning("failed to restrict file handles (%ld)\n\n%s",
1770 err, buf.buf);
1771 }
1772 strbuf_release(&buf);
1773 } else if (!ret)
1774 errno = err_win_to_posix(GetLastError());
1775
1776 if (si.lpAttributeList)
1777 DeleteProcThreadAttributeList(si.lpAttributeList);
1778 if (attr_list)
1779 HeapFree(GetProcessHeap(), 0, attr_list);
7e5d7768 1780
7eb2619c 1781 free(wenvblk);
99c3c76d 1782 free(wargs);
7e5d7768 1783
9a780a38 1784 if (!ret)
7e5d7768 1785 return -1;
9a780a38 1786
7e5d7768 1787 CloseHandle(pi.hThread);
52de4db5
EFL
1788
1789 /*
1790 * The process ID is the human-readable identifier of the process
1791 * that we want to present in log and error messages. The handle
1792 * is not useful for this purpose. But we cannot close it, either,
1793 * because it is not possible to turn a process ID into a process
1794 * handle after the process terminated.
1795 * Keep the handle in a list for waitpid.
1796 */
1797 EnterCriticalSection(&pinfo_cs);
1798 {
1799 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1800 info->pid = pi.dwProcessId;
1801 info->proc = pi.hProcess;
1802 info->next = pinfo;
1803 pinfo = info;
1804 }
1805 LeaveCriticalSection(&pinfo_cs);
1806
1807 return (pid_t)pi.dwProcessId;
7e5d7768
JS
1808}
1809
3e66e47b 1810static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
75301f90 1811{
77734da2 1812 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
75301f90
JS
1813}
1814
77734da2 1815pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1816 const char *dir,
75301f90 1817 int fhin, int fhout, int fherr)
7e5d7768
JS
1818{
1819 pid_t pid;
e0ca1ca2 1820 char *prog = path_lookup(cmd, 0);
7e5d7768
JS
1821
1822 if (!prog) {
1823 errno = ENOENT;
1824 pid = -1;
1825 }
1826 else {
1827 const char *interpr = parse_interpreter(prog);
1828
1829 if (interpr) {
1830 const char *argv0 = argv[0];
e0ca1ca2 1831 char *iprog = path_lookup(interpr, 1);
7e5d7768
JS
1832 argv[0] = prog;
1833 if (!iprog) {
1834 errno = ENOENT;
1835 pid = -1;
1836 }
1837 else {
77734da2 1838 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
75301f90 1839 fhin, fhout, fherr);
7e5d7768
JS
1840 free(iprog);
1841 }
1842 argv[0] = argv0;
1843 }
1844 else
77734da2 1845 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
75301f90 1846 fhin, fhout, fherr);
7e5d7768
JS
1847 free(prog);
1848 }
7e5d7768
JS
1849 return pid;
1850}
1851
3e66e47b 1852static int try_shell_exec(const char *cmd, char *const *argv)
f1a4dfb8
JS
1853{
1854 const char *interpr = parse_interpreter(cmd);
f1a4dfb8
JS
1855 char *prog;
1856 int pid = 0;
1857
1858 if (!interpr)
1859 return 0;
e0ca1ca2 1860 prog = path_lookup(interpr, 1);
f1a4dfb8 1861 if (prog) {
ee4512ed 1862 int exec_id;
f1a4dfb8 1863 int argc = 0;
12fb9bd8 1864 char **argv2;
f1a4dfb8 1865 while (argv[argc]) argc++;
b32fa95f 1866 ALLOC_ARRAY(argv2, argc + 1);
7e5d7768 1867 argv2[0] = (char *)cmd; /* full path to the script file */
51bd6be3 1868 COPY_ARRAY(&argv2[1], &argv[1], argc);
09884f35
RS
1869 exec_id = trace2_exec(prog, (const char **)argv2);
1870 pid = mingw_spawnv(prog, (const char **)argv2, 1);
f1a4dfb8
JS
1871 if (pid >= 0) {
1872 int status;
1873 if (waitpid(pid, &status, 0) < 0)
1874 status = 255;
ee4512ed 1875 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1876 exit(status);
1877 }
ee4512ed 1878 trace2_exec_result(exec_id, -1);
f1a4dfb8
JS
1879 pid = 1; /* indicate that we tried but failed */
1880 free(prog);
1881 free(argv2);
1882 }
f1a4dfb8
JS
1883 return pid;
1884}
1885
3e66e47b 1886int mingw_execv(const char *cmd, char *const *argv)
f1a4dfb8
JS
1887{
1888 /* check if git_command is a shell script */
3e66e47b 1889 if (!try_shell_exec(cmd, argv)) {
f1a4dfb8 1890 int pid, status;
ee4512ed 1891 int exec_id;
f1a4dfb8 1892
ee4512ed 1893 exec_id = trace2_exec(cmd, (const char **)argv);
3e66e47b 1894 pid = mingw_spawnv(cmd, (const char **)argv, 0);
ee4512ed
JH
1895 if (pid < 0) {
1896 trace2_exec_result(exec_id, -1);
570f1e6e 1897 return -1;
ee4512ed 1898 }
f1a4dfb8
JS
1899 if (waitpid(pid, &status, 0) < 0)
1900 status = 255;
ee4512ed 1901 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1902 exit(status);
1903 }
570f1e6e 1904 return -1;
f1a4dfb8
JS
1905}
1906
1696d723 1907int mingw_execvp(const char *cmd, char *const *argv)
f1a4dfb8 1908{
e0ca1ca2 1909 char *prog = path_lookup(cmd, 0);
f1a4dfb8
JS
1910
1911 if (prog) {
3e66e47b 1912 mingw_execv(prog, argv);
f1a4dfb8
JS
1913 free(prog);
1914 } else
1915 errno = ENOENT;
1916
1696d723 1917 return -1;
f1a4dfb8
JS
1918}
1919
82fc07b7
EFL
1920int mingw_kill(pid_t pid, int sig)
1921{
1922 if (pid > 0 && sig == SIGTERM) {
1923 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1924
1925 if (TerminateProcess(h, -1)) {
1926 CloseHandle(h);
1927 return 0;
1928 }
1929
1930 errno = err_win_to_posix(GetLastError());
1931 CloseHandle(h);
1932 return -1;
64a99eb4
NTND
1933 } else if (pid > 0 && sig == 0) {
1934 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1935 if (h) {
1936 CloseHandle(h);
1937 return 0;
1938 }
82fc07b7
EFL
1939 }
1940
1941 errno = EINVAL;
1942 return -1;
1943}
1944
343ff06d 1945/*
fe21c6b2
JS
1946 * UTF-8 versions of getenv(), putenv() and unsetenv().
1947 * Internally, they use the CRT's stock UNICODE routines
1948 * to avoid data loss.
343ff06d 1949 */
fe21c6b2 1950char *mingw_getenv(const char *name)
343ff06d 1951{
ca1b4116 1952#define GETENV_MAX_RETAIN 64
fe21c6b2
JS
1953 static char *values[GETENV_MAX_RETAIN];
1954 static int value_counter;
1955 int len_key, len_value;
1956 wchar_t *w_key;
1957 char *value;
1958 wchar_t w_value[32768];
343ff06d 1959
fe21c6b2
JS
1960 if (!name || !*name)
1961 return NULL;
ba26f296 1962
fe21c6b2
JS
1963 len_key = strlen(name) + 1;
1964 /* We cannot use xcalloc() here because that uses getenv() itself */
1965 w_key = calloc(len_key, sizeof(wchar_t));
1966 if (!w_key)
1967 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1968 xutftowcs(w_key, name, len_key);
61d1d92a
JS
1969 /* GetEnvironmentVariableW() only sets the last error upon failure */
1970 SetLastError(ERROR_SUCCESS);
fe21c6b2
JS
1971 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1972 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1973 free(w_key);
1974 return NULL;
ba26f296 1975 }
fe21c6b2
JS
1976 free(w_key);
1977
1978 len_value = len_value * 3 + 1;
1979 /* We cannot use xcalloc() here because that uses getenv() itself */
1980 value = calloc(len_value, sizeof(char));
1981 if (!value)
1982 die("Out of memory, (tried to allocate %u bytes)", len_value);
1983 xwcstoutf(value, w_value, len_value);
1984
1985 /*
1986 * We return `value` which is an allocated value and the caller is NOT
1987 * expecting to have to free it, so we keep a round-robin array,
1988 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1989 */
1990 free(values[value_counter]);
1991 values[value_counter++] = value;
1992 if (value_counter >= ARRAY_SIZE(values))
1993 value_counter = 0;
1994
1995 return value;
ba26f296
JS
1996}
1997
fe21c6b2 1998int mingw_putenv(const char *namevalue)
ba26f296 1999{
fe21c6b2
JS
2000 int size;
2001 wchar_t *wide, *equal;
2002 BOOL result;
ba26f296 2003
fe21c6b2
JS
2004 if (!namevalue || !*namevalue)
2005 return 0;
ba26f296 2006
fe21c6b2
JS
2007 size = strlen(namevalue) * 2 + 1;
2008 wide = calloc(size, sizeof(wchar_t));
2009 if (!wide)
2010 die("Out of memory, (tried to allocate %u wchar_t's)", size);
2011 xutftowcs(wide, namevalue, size);
2012 equal = wcschr(wide, L'=');
2013 if (!equal)
2014 result = SetEnvironmentVariableW(wide, NULL);
2015 else {
2016 *equal = L'\0';
2017 result = SetEnvironmentVariableW(wide, equal + 1);
ba26f296 2018 }
fe21c6b2 2019 free(wide);
2affea41 2020
fe21c6b2
JS
2021 if (!result)
2022 errno = err_win_to_posix(GetLastError());
df599e96 2023
fe21c6b2 2024 return result ? 0 : -1;
06bc4b79
JS
2025}
2026
b7cc9f82 2027static void ensure_socket_initialization(void)
746fb857
JS
2028{
2029 WSADATA wsa;
b7cc9f82
MS
2030 static int initialized = 0;
2031
2032 if (initialized)
2033 return;
746fb857
JS
2034
2035 if (WSAStartup(MAKEWORD(2,2), &wsa))
2036 die("unable to initialize winsock subsystem, error %d",
2037 WSAGetLastError());
fe3b2b7b 2038
b9f0193b 2039 atexit((void(*)(void)) WSACleanup);
b7cc9f82
MS
2040 initialized = 1;
2041}
2042
13d24b01
PT
2043#undef gethostname
2044int mingw_gethostname(char *name, int namelen)
2045{
2046 ensure_socket_initialization();
2047 return gethostname(name, namelen);
2048}
2049
b7cc9f82
MS
2050#undef gethostbyname
2051struct hostent *mingw_gethostbyname(const char *host)
2052{
2053 ensure_socket_initialization();
746fb857
JS
2054 return gethostbyname(host);
2055}
2056
b9f0193b 2057#undef getaddrinfo
fe3b2b7b
MS
2058int mingw_getaddrinfo(const char *node, const char *service,
2059 const struct addrinfo *hints, struct addrinfo **res)
2060{
2061 ensure_socket_initialization();
b9f0193b 2062 return getaddrinfo(node, service, hints, res);
fe3b2b7b
MS
2063}
2064
746fb857
JS
2065int mingw_socket(int domain, int type, int protocol)
2066{
2067 int sockfd;
772991af
MP
2068 SOCKET s;
2069
2070 ensure_socket_initialization();
2071 s = WSASocket(domain, type, protocol, NULL, 0, 0);
746fb857
JS
2072 if (s == INVALID_SOCKET) {
2073 /*
2074 * WSAGetLastError() values are regular BSD error codes
2075 * biased by WSABASEERR.
2076 * However, strerror() does not know about networking
2077 * specific errors, which are values beginning at 38 or so.
2078 * Therefore, we choose to leave the biased error code
2079 * in errno so that _if_ someone looks up the code somewhere,
2080 * then it is at least the number that are usually listed.
2081 */
2082 errno = WSAGetLastError();
2083 return -1;
2084 }
2085 /* convert into a file descriptor */
2086 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2087 closesocket(s);
2088 return error("unable to make a socket file descriptor: %s",
2089 strerror(errno));
2090 }
2091 return sockfd;
2092}
2093
2094#undef connect
2095int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2096{
2097 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2098 return connect(s, sa, sz);
2099}
2100
772991af
MP
2101#undef bind
2102int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2103{
2104 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2105 return bind(s, sa, sz);
2106}
2107
2108#undef setsockopt
2109int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2110{
2111 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2112 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2113}
2114
a7941795
JS
2115#undef shutdown
2116int mingw_shutdown(int sockfd, int how)
2117{
2118 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2119 return shutdown(s, how);
2120}
2121
772991af
MP
2122#undef listen
2123int mingw_listen(int sockfd, int backlog)
2124{
2125 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2126 return listen(s, backlog);
2127}
2128
2129#undef accept
2130int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2131{
2132 int sockfd2;
2133
2134 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2135 SOCKET s2 = accept(s1, sa, sz);
2136
2137 /* convert into a file descriptor */
2138 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2139 int err = errno;
2140 closesocket(s2);
2141 return error("unable to make a socket file descriptor: %s",
2142 strerror(err));
2143 }
2144 return sockfd2;
2145}
2146
ea9e98c3
JS
2147#undef rename
2148int mingw_rename(const char *pold, const char *pnew)
2149{
6ac6f878
JS
2150 DWORD attrs, gle;
2151 int tries = 0;
85faec9d
KB
2152 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2153 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2154 return -1;
632f7017 2155
ea9e98c3
JS
2156 /*
2157 * Try native rename() first to get errno right.
2158 * It is based on MoveFile(), which cannot overwrite existing files.
2159 */
85faec9d 2160 if (!_wrename(wpold, wpnew))
ea9e98c3
JS
2161 return 0;
2162 if (errno != EEXIST)
2163 return -1;
6ac6f878 2164repeat:
85faec9d 2165 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
ea9e98c3
JS
2166 return 0;
2167 /* TODO: translate more errors */
6ac6f878
JS
2168 gle = GetLastError();
2169 if (gle == ERROR_ACCESS_DENIED &&
85faec9d 2170 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
632f7017 2171 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
4426fb51 2172 DWORD attrsold = GetFileAttributesW(wpold);
2173 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2174 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2175 errno = EISDIR;
2176 else if (!_wrmdir(wpnew))
2177 goto repeat;
ea9e98c3
JS
2178 return -1;
2179 }
632f7017 2180 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
85faec9d
KB
2181 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2182 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
632f7017 2183 return 0;
6ac6f878 2184 gle = GetLastError();
632f7017 2185 /* revert file attributes on failure */
85faec9d 2186 SetFileAttributesW(wpnew, attrs);
632f7017 2187 }
ea9e98c3 2188 }
6ac6f878
JS
2189 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2190 /*
2191 * We assume that some other process had the source or
2192 * destination file open at the wrong moment and retry.
2193 * In order to give the other process a higher chance to
2194 * complete its operation, we give up our time slice now.
2195 * If we have to retry again, we do sleep a bit.
2196 */
2197 Sleep(delay[tries]);
2198 tries++;
2199 goto repeat;
2200 }
c9b78400
HV
2201 if (gle == ERROR_ACCESS_DENIED &&
2202 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2203 "Should I try again?", pold, pnew))
2204 goto repeat;
2205
ea9e98c3
JS
2206 errno = EACCES;
2207 return -1;
2208}
2209
b1b95204
RJ
2210/*
2211 * Note that this doesn't return the actual pagesize, but
2212 * the allocation granularity. If future Windows specific git code
2213 * needs the real getpagesize function, we need to find another solution.
2214 */
2215int mingw_getpagesize(void)
2216{
2217 SYSTEM_INFO si;
2218 GetSystemInfo(&si);
2219 return si.dwAllocationGranularity;
2220}
2221
564be791
JS
2222/* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2223enum EXTENDED_NAME_FORMAT {
2224 NameDisplay = 3,
2225 NameUserPrincipal = 8
2226};
2227
2228static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2229{
4a9b2049 2230 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
564be791
JS
2231 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2232 static wchar_t wbuffer[1024];
2233 DWORD len;
2234
2235 if (!INIT_PROC_ADDR(GetUserNameExW))
2236 return NULL;
2237
2238 len = ARRAY_SIZE(wbuffer);
2239 if (GetUserNameExW(type, wbuffer, &len)) {
2240 char *converted = xmalloc((len *= 3));
2241 if (xwcstoutf(converted, wbuffer, len) >= 0)
2242 return converted;
2243 free(converted);
2244 }
2245
2246 return NULL;
2247}
2248
501afcb8
JS
2249char *mingw_query_user_email(void)
2250{
2251 return get_extended_user_info(NameUserPrincipal);
2252}
2253
f4626df5
JS
2254struct passwd *getpwuid(int uid)
2255{
55b6513e 2256 static unsigned initialized;
f7597aca 2257 static char user_name[100];
55b6513e 2258 static struct passwd *p;
39a98e9b 2259 wchar_t buf[100];
55b6513e 2260 DWORD len;
f7597aca 2261
55b6513e
JS
2262 if (initialized)
2263 return p;
f7597aca 2264
697bdd22 2265 len = ARRAY_SIZE(buf);
39a98e9b
JS
2266 if (!GetUserNameW(buf, &len)) {
2267 initialized = 1;
2268 return NULL;
2269 }
2270
2271 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
55b6513e 2272 initialized = 1;
f7597aca 2273 return NULL;
55b6513e
JS
2274 }
2275
2276 p = xmalloc(sizeof(*p));
2277 p->pw_name = user_name;
564be791
JS
2278 p->pw_gecos = get_extended_user_info(NameDisplay);
2279 if (!p->pw_gecos)
2280 p->pw_gecos = "unknown";
55b6513e
JS
2281 p->pw_dir = NULL;
2282
2283 initialized = 1;
2284 return p;
f4626df5
JS
2285}
2286
6072fc31
JS
2287static HANDLE timer_event;
2288static HANDLE timer_thread;
2289static int timer_interval;
2290static int one_shot;
176478a8 2291static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
6072fc31
JS
2292
2293/* The timer works like this:
2294 * The thread, ticktack(), is a trivial routine that most of the time
2295 * only waits to receive the signal to terminate. The main thread tells
2296 * the thread to terminate by setting the timer_event to the signalled
2297 * state.
2298 * But ticktack() interrupts the wait state after the timer's interval
2299 * length to call the signal handler.
2300 */
2301
d7fa500f 2302static unsigned __stdcall ticktack(void *dummy)
6072fc31
JS
2303{
2304 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
176478a8 2305 mingw_raise(SIGALRM);
6072fc31
JS
2306 if (one_shot)
2307 break;
2308 }
2309 return 0;
2310}
2311
2312static int start_timer_thread(void)
2313{
2314 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2315 if (timer_event) {
2316 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2317 if (!timer_thread )
2318 return errno = ENOMEM,
2319 error("cannot start timer thread");
2320 } else
2321 return errno = ENOMEM,
2322 error("cannot allocate resources for timer");
2323 return 0;
2324}
2325
2326static void stop_timer_thread(void)
2327{
2328 if (timer_event)
2329 SetEvent(timer_event); /* tell thread to terminate */
2330 if (timer_thread) {
72d63b2f 2331 int rc = WaitForSingleObject(timer_thread, 10000);
6072fc31
JS
2332 if (rc == WAIT_TIMEOUT)
2333 error("timer thread did not terminate timely");
2334 else if (rc != WAIT_OBJECT_0)
2335 error("waiting for timer thread failed: %lu",
2336 GetLastError());
2337 CloseHandle(timer_thread);
2338 }
2339 if (timer_event)
2340 CloseHandle(timer_event);
2341 timer_event = NULL;
2342 timer_thread = NULL;
2343}
2344
2345static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2346{
2347 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2348}
2349
f4626df5
JS
2350int setitimer(int type, struct itimerval *in, struct itimerval *out)
2351{
6072fc31
JS
2352 static const struct timeval zero;
2353 static int atexit_done;
2354
afe8a907 2355 if (out)
6072fc31
JS
2356 return errno = EINVAL,
2357 error("setitimer param 3 != NULL not implemented");
2358 if (!is_timeval_eq(&in->it_interval, &zero) &&
2359 !is_timeval_eq(&in->it_interval, &in->it_value))
2360 return errno = EINVAL,
2361 error("setitimer: it_interval must be zero or eq it_value");
2362
2363 if (timer_thread)
2364 stop_timer_thread();
2365
2366 if (is_timeval_eq(&in->it_value, &zero) &&
2367 is_timeval_eq(&in->it_interval, &zero))
2368 return 0;
2369
2370 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2371 one_shot = is_timeval_eq(&in->it_interval, &zero);
2372 if (!atexit_done) {
2373 atexit(stop_timer_thread);
2374 atexit_done = 1;
2375 }
2376 return start_timer_thread();
f4626df5
JS
2377}
2378
2379int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2380{
6072fc31
JS
2381 if (sig != SIGALRM)
2382 return errno = EINVAL,
2383 error("sigaction only implemented for SIGALRM");
afe8a907 2384 if (out)
6072fc31
JS
2385 return errno = EINVAL,
2386 error("sigaction: param 3 != NULL not implemented");
2387
2388 timer_fn = in->sa_handler;
2389 return 0;
2390}
2391
2392#undef signal
2393sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2394{
a4540658 2395 sig_handler_t old;
176478a8
EFL
2396
2397 switch (sig) {
2398 case SIGALRM:
a4540658 2399 old = timer_fn;
176478a8
EFL
2400 timer_fn = handler;
2401 break;
2402
2403 case SIGINT:
a4540658 2404 old = sigint_fn;
176478a8
EFL
2405 sigint_fn = handler;
2406 break;
2407
2408 default:
6072fc31 2409 return signal(sig, handler);
176478a8
EFL
2410 }
2411
6072fc31 2412 return old;
f4626df5 2413}
4804aabc 2414
176478a8
EFL
2415#undef raise
2416int mingw_raise(int sig)
2417{
2418 switch (sig) {
2419 case SIGALRM:
2420 if (timer_fn == SIG_DFL) {
2421 if (isatty(STDERR_FILENO))
2422 fputs("Alarm clock\n", stderr);
2423 exit(128 + SIGALRM);
2424 } else if (timer_fn != SIG_IGN)
2425 timer_fn(SIGALRM);
2426 return 0;
2427
2428 case SIGINT:
2429 if (sigint_fn == SIG_DFL)
2430 exit(128 + SIGINT);
2431 else if (sigint_fn != SIG_IGN)
2432 sigint_fn(SIGINT);
2433 return 0;
2434
446df603
JH
2435#if defined(_MSC_VER)
2436 case SIGILL:
2437 case SIGFPE:
2438 case SIGSEGV:
2439 case SIGTERM:
2440 case SIGBREAK:
2441 case SIGABRT:
2442 case SIGABRT_COMPAT:
2443 /*
2444 * The <signal.h> header in the MS C Runtime defines 8 signals
2445 * as being supported on the platform. Anything else causes an
2446 * "Invalid signal or error" (which in DEBUG builds causes the
2447 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2448 * already know will fail.
2449 */
2450 return raise(sig);
2451 default:
2452 errno = EINVAL;
2453 return -1;
2454
2455#else
2456
176478a8
EFL
2457 default:
2458 return raise(sig);
446df603
JH
2459
2460#endif
2461
176478a8
EFL
2462 }
2463}
2464
7be401e0
PK
2465int link(const char *oldpath, const char *newpath)
2466{
85faec9d
KB
2467 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2468 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2469 xutftowcs_path(wnewpath, newpath) < 0)
2470 return -1;
2471
1e1a876b 2472 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
7be401e0
PK
2473 errno = err_win_to_posix(GetLastError());
2474 return -1;
2475 }
2476 return 0;
2477}
0dbbbc1e 2478
956d86d1 2479pid_t waitpid(pid_t pid, int *status, int options)
52de4db5
EFL
2480{
2481 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2482 FALSE, pid);
2483 if (!h) {
2484 errno = ECHILD;
2485 return -1;
2486 }
2487
ef7108ca
EFL
2488 if (pid > 0 && options & WNOHANG) {
2489 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2490 CloseHandle(h);
2491 return 0;
2492 }
2493 options &= ~WNOHANG;
2494 }
2495
52de4db5
EFL
2496 if (options == 0) {
2497 struct pinfo_t **ppinfo;
2498 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2499 CloseHandle(h);
2500 return 0;
2501 }
2502
2503 if (status)
2504 GetExitCodeProcess(h, (LPDWORD)status);
2505
2506 EnterCriticalSection(&pinfo_cs);
2507
2508 ppinfo = &pinfo;
2509 while (*ppinfo) {
2510 struct pinfo_t *info = *ppinfo;
2511 if (info->pid == pid) {
2512 CloseHandle(info->proc);
2513 *ppinfo = info->next;
2514 free(info);
2515 break;
2516 }
2517 ppinfo = &info->next;
2518 }
2519
2520 LeaveCriticalSection(&pinfo_cs);
2521
2522 CloseHandle(h);
2523 return pid;
2524 }
2525 CloseHandle(h);
2526
2527 errno = EINVAL;
2528 return -1;
2529}
c2369bdf 2530
1c950a59
KB
2531int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2532{
2533 int upos = 0, wpos = 0;
2534 const unsigned char *utf = (const unsigned char*) utfs;
2535 if (!utf || !wcs || wcslen < 1) {
2536 errno = EINVAL;
2537 return -1;
2538 }
2539 /* reserve space for \0 */
2540 wcslen--;
2541 if (utflen < 0)
2542 utflen = INT_MAX;
2543
2544 while (upos < utflen) {
2545 int c = utf[upos++] & 0xff;
2546 if (utflen == INT_MAX && c == 0)
2547 break;
2548
2549 if (wpos >= wcslen) {
2550 wcs[wpos] = 0;
2551 errno = ERANGE;
2552 return -1;
2553 }
2554
2555 if (c < 0x80) {
2556 /* ASCII */
2557 wcs[wpos++] = c;
2558 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2559 (utf[upos] & 0xc0) == 0x80) {
2560 /* 2-byte utf-8 */
2561 c = ((c & 0x1f) << 6);
2562 c |= (utf[upos++] & 0x3f);
2563 wcs[wpos++] = c;
2564 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2565 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2566 (utf[upos] & 0xc0) == 0x80 &&
2567 (utf[upos + 1] & 0xc0) == 0x80) {
2568 /* 3-byte utf-8 */
2569 c = ((c & 0x0f) << 12);
2570 c |= ((utf[upos++] & 0x3f) << 6);
2571 c |= (utf[upos++] & 0x3f);
2572 wcs[wpos++] = c;
2573 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2574 wpos + 1 < wcslen &&
2575 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2576 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2577 (utf[upos] & 0xc0) == 0x80 &&
2578 (utf[upos + 1] & 0xc0) == 0x80 &&
2579 (utf[upos + 2] & 0xc0) == 0x80) {
2580 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2581 c = ((c & 0x07) << 18);
2582 c |= ((utf[upos++] & 0x3f) << 12);
2583 c |= ((utf[upos++] & 0x3f) << 6);
2584 c |= (utf[upos++] & 0x3f);
2585 c -= 0x10000;
2586 wcs[wpos++] = 0xd800 | (c >> 10);
2587 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2588 } else if (c >= 0xa0) {
2589 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2590 wcs[wpos++] = c;
2591 } else {
2592 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2593 static const char *hex = "0123456789abcdef";
2594 wcs[wpos++] = hex[c >> 4];
2595 if (wpos < wcslen)
2596 wcs[wpos++] = hex[c & 0x0f];
2597 }
2598 }
2599 wcs[wpos] = 0;
2600 return wpos;
2601}
2602
2603int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2604{
2605 if (!wcs || !utf || utflen < 1) {
2606 errno = EINVAL;
2607 return -1;
2608 }
2609 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2610 if (utflen)
2611 return utflen - 1;
2612 errno = ERANGE;
2613 return -1;
2614}
2615
0767172b 2616static void setup_windows_environment(void)
02e6edc0 2617{
1fc7bf79
JS
2618 char *tmp = getenv("TMPDIR");
2619
02e6edc0 2620 /* on Windows it is TMP and TEMP */
1fc7bf79
JS
2621 if (!tmp) {
2622 if (!(tmp = getenv("TMP")))
02e6edc0 2623 tmp = getenv("TEMP");
1fc7bf79 2624 if (tmp) {
02e6edc0 2625 setenv("TMPDIR", tmp, 1);
1fc7bf79
JS
2626 tmp = getenv("TMPDIR");
2627 }
2628 }
2629
2630 if (tmp) {
2631 /*
2632 * Convert all dir separators to forward slashes,
2633 * to help shell commands called from the Git
2634 * executable (by not mistaking the dir separators
2635 * for escape characters).
2636 */
8e9b2080 2637 convert_slashes(tmp);
02e6edc0
KB
2638 }
2639
2640 /* simulate TERM to enable auto-color (see color.c) */
2641 if (!getenv("TERM"))
2642 setenv("TERM", "cygwin", 1);
e12a9556
KB
2643
2644 /* calculate HOME if not set */
2645 if (!getenv("HOME")) {
2646 /*
2647 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2648 * location, thus also check if the path exists (i.e. is not
2649 * disconnected)
2650 */
2651 if ((tmp = getenv("HOMEDRIVE"))) {
2652 struct strbuf buf = STRBUF_INIT;
2653 strbuf_addstr(&buf, tmp);
2654 if ((tmp = getenv("HOMEPATH"))) {
2655 strbuf_addstr(&buf, tmp);
2656 if (is_directory(buf.buf))
2657 setenv("HOME", buf.buf, 1);
2658 else
2659 tmp = NULL; /* use $USERPROFILE */
2660 }
2661 strbuf_release(&buf);
2662 }
2663 /* use $USERPROFILE if the home share is not available */
2664 if (!tmp && (tmp = getenv("USERPROFILE")))
2665 setenv("HOME", tmp, 1);
2666 }
02e6edc0
KB
2667}
2668
bdc77d1d
JS
2669static PSID get_current_user_sid(void)
2670{
2671 HANDLE token;
2672 DWORD len = 0;
2673 PSID result = NULL;
2674
2675 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2676 return NULL;
2677
2678 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2679 TOKEN_USER *info = xmalloc((size_t)len);
2680 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2681 len = GetLengthSid(info->User.Sid);
2682 result = xmalloc(len);
2683 if (!CopySid(len, result, info->User.Sid)) {
2684 error(_("failed to copy SID (%ld)"),
2685 GetLastError());
2686 FREE_AND_NULL(result);
2687 }
2688 }
2689 FREE_AND_NULL(info);
2690 }
2691 CloseHandle(token);
2692
2693 return result;
2694}
2695
7c83470e
JS
2696static int acls_supported(const char *path)
2697{
2698 size_t offset = offset_1st_component(path);
2699 WCHAR wroot[MAX_PATH];
2700 DWORD file_system_flags;
2701
2702 if (offset &&
2703 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2704 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2705 &file_system_flags, NULL, 0))
2706 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2707
2708 return 0;
2709}
2710
17d3883f 2711int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
bdc77d1d
JS
2712{
2713 WCHAR wpath[MAX_PATH];
2714 PSID sid = NULL;
2715 PSECURITY_DESCRIPTOR descriptor = NULL;
2716 DWORD err;
2717
2718 static wchar_t home[MAX_PATH];
2719
2720 int result = 0;
2721
2722 if (xutftowcs_path(wpath, path) < 0)
2723 return 0;
2724
2725 /*
2726 * On Windows, the home directory is owned by the administrator, but for
2727 * all practical purposes, it belongs to the user. Do pretend that it is
2728 * owned by the user.
2729 */
2730 if (!*home) {
2731 DWORD size = ARRAY_SIZE(home);
2732 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2733 if (!len || len > size)
2734 wcscpy(home, L"::N/A::");
2735 }
2736 if (!wcsicmp(wpath, home))
2737 return 1;
2738
2739 /* Get the owner SID */
2740 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2741 OWNER_SECURITY_INFORMATION |
2742 DACL_SECURITY_INFORMATION,
2743 &sid, NULL, NULL, NULL, &descriptor);
2744
2745 if (err != ERROR_SUCCESS)
2746 error(_("failed to get owner for '%s' (%ld)"), path, err);
2747 else if (sid && IsValidSid(sid)) {
2748 /* Now, verify that the SID matches the current user's */
2749 static PSID current_user_sid;
3f7207e2 2750 BOOL is_member;
bdc77d1d
JS
2751
2752 if (!current_user_sid)
2753 current_user_sid = get_current_user_sid();
2754
2755 if (current_user_sid &&
2756 IsValidSid(current_user_sid) &&
2757 EqualSid(sid, current_user_sid))
2758 result = 1;
3f7207e2
JS
2759 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
2760 CheckTokenMembership(NULL, sid, &is_member) &&
2761 is_member)
2762 /*
2763 * If owned by the Administrators group, and the
2764 * current user is an administrator, we consider that
2765 * okay, too.
2766 */
2767 result = 1;
7c83470e
JS
2768 else if (report &&
2769 IsWellKnownSid(sid, WinWorldSid) &&
2770 !acls_supported(path)) {
2771 /*
2772 * On FAT32 volumes, ownership is not actually recorded.
2773 */
4eb1ccec 2774 strbuf_addf(report, "'%s' is on a file system that does "
7c83470e
JS
2775 "not record ownership\n", path);
2776 } else if (report) {
e883e04b
JS
2777 LPSTR str1, str2, to_free1 = NULL, to_free2 = NULL;
2778
2779 if (ConvertSidToStringSidA(sid, &str1))
2780 to_free1 = str1;
2781 else
2782 str1 = "(inconvertible)";
2783
2784 if (!current_user_sid)
2785 str2 = "(none)";
2786 else if (!IsValidSid(current_user_sid))
2787 str2 = "(invalid)";
2788 else if (ConvertSidToStringSidA(current_user_sid, &str2))
2789 to_free2 = str2;
2790 else
2791 str2 = "(inconvertible)";
2792 strbuf_addf(report,
2793 "'%s' is owned by:\n"
2794 "\t'%s'\nbut the current user is:\n"
2795 "\t'%s'\n", path, str1, str2);
2796 LocalFree(to_free1);
2797 LocalFree(to_free2);
2798 }
bdc77d1d
JS
2799 }
2800
2801 /*
2802 * We can release the security descriptor struct only now because `sid`
2803 * actually points into this struct.
2804 */
2805 if (descriptor)
2806 LocalFree(descriptor);
2807
2808 return result;
2809}
2810
4dc42c6c 2811int is_valid_win32_path(const char *path, int allow_literal_nul)
d2c84dad 2812{
4dc42c6c 2813 const char *p = path;
d2c84dad
JS
2814 int preceding_space_or_period = 0, i = 0, periods = 0;
2815
2816 if (!protect_ntfs)
2817 return 1;
2818
817ddd64 2819 skip_dos_drive_prefix((char **)&path);
4dc42c6c 2820 goto segment_start;
817ddd64 2821
d2c84dad
JS
2822 for (;;) {
2823 char c = *(path++);
2824 switch (c) {
2825 case '\0':
2826 case '/': case '\\':
2827 /* cannot end in ` ` or `.`, except for `.` and `..` */
2828 if (preceding_space_or_period &&
2829 (i != periods || periods > 2))
2830 return 0;
2831 if (!c)
2832 return 1;
2833
2834 i = periods = preceding_space_or_period = 0;
4dc42c6c
JS
2835
2836segment_start:
2837 switch (*path) {
2838 case 'a': case 'A': /* AUX */
2839 if (((c = path[++i]) != 'u' && c != 'U') ||
2840 ((c = path[++i]) != 'x' && c != 'X')) {
2841not_a_reserved_name:
2842 path += i;
2843 continue;
2844 }
2845 break;
b6852e19
JS
2846 case 'c': case 'C':
2847 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
4dc42c6c
JS
2848 if ((c = path[++i]) != 'o' && c != 'O')
2849 goto not_a_reserved_name;
2850 c = path[++i];
b6852e19
JS
2851 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2852 c = path[++i];
2853 if (c < '1' || c > '9')
4dc42c6c
JS
2854 goto not_a_reserved_name;
2855 } else if (c == 'n' || c == 'N') { /* CON */
2856 c = path[i + 1];
2857 if ((c == 'i' || c == 'I') &&
2858 ((c = path[i + 2]) == 'n' ||
2859 c == 'N') &&
2860 path[i + 3] == '$')
2861 i += 3; /* CONIN$ */
2862 else if ((c == 'o' || c == 'O') &&
2863 ((c = path[i + 2]) == 'u' ||
2864 c == 'U') &&
2865 ((c = path[i + 3]) == 't' ||
2866 c == 'T') &&
2867 path[i + 4] == '$')
2868 i += 4; /* CONOUT$ */
2869 } else
2870 goto not_a_reserved_name;
2871 break;
2872 case 'l': case 'L': /* LPT<N> */
2873 if (((c = path[++i]) != 'p' && c != 'P') ||
2874 ((c = path[++i]) != 't' && c != 'T') ||
2875 !isdigit(path[++i]))
2876 goto not_a_reserved_name;
2877 break;
2878 case 'n': case 'N': /* NUL */
2879 if (((c = path[++i]) != 'u' && c != 'U') ||
2880 ((c = path[++i]) != 'l' && c != 'L') ||
2881 (allow_literal_nul &&
2882 !path[i + 1] && p == path))
2883 goto not_a_reserved_name;
2884 break;
2885 case 'p': case 'P': /* PRN */
2886 if (((c = path[++i]) != 'r' && c != 'R') ||
2887 ((c = path[++i]) != 'n' && c != 'N'))
2888 goto not_a_reserved_name;
2889 break;
2890 default:
2891 continue;
2892 }
2893
2894 /*
2895 * So far, this looks like a reserved name. Let's see
2896 * whether it actually is one: trailing spaces, a file
2897 * extension, or an NTFS Alternate Data Stream do not
2898 * matter, the name is still reserved if any of those
2899 * follow immediately after the actual name.
2900 */
2901 i++;
2902 if (path[i] == ' ') {
2903 preceding_space_or_period = 1;
2904 while (path[++i] == ' ')
2905 ; /* skip all spaces */
2906 }
2907
2908 c = path[i];
9fd512c8 2909 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
4dc42c6c
JS
2910 goto not_a_reserved_name;
2911
2912 /* contains reserved name */
2913 return 0;
d2c84dad
JS
2914 case '.':
2915 periods++;
2916 /* fallthru */
2917 case ' ':
2918 preceding_space_or_period = 1;
2919 i++;
2920 continue;
817ddd64
JS
2921 case ':': /* DOS drive prefix was already skipped */
2922 case '<': case '>': case '"': case '|': case '?': case '*':
2923 /* illegal character */
2924 return 0;
2925 default:
2926 if (c > '\0' && c < '\x20')
2927 /* illegal character */
2928 return 0;
d2c84dad
JS
2929 }
2930 preceding_space_or_period = 0;
2931 i++;
2932 }
2933}
2934
396ff754 2935#if !defined(_MSC_VER)
5901dc66
KB
2936/*
2937 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2938 * mingw startup code, see init.c in mingw runtime).
2939 */
2940int _CRT_glob = 0;
396ff754 2941#endif
3f046148 2942
0767172b 2943static NORETURN void die_startup(void)
3f046148
KB
2944{
2945 fputs("fatal: not enough memory for initialization", stderr);
2946 exit(128);
2947}
2948
6f1c189c
KB
2949static void *malloc_startup(size_t size)
2950{
2951 void *result = malloc(size);
2952 if (!result)
2953 die_startup();
2954 return result;
2955}
2956
2957static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2958{
2959 len = xwcstoutf(buffer, wcs, len) + 1;
2960 return memcpy(malloc_startup(len), buffer, len);
2961}
2962
3f944424
JS
2963static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2964 DWORD desired_access, DWORD flags)
2965{
2966 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2967 wchar_t buf[MAX_PATH];
2968 DWORD max = ARRAY_SIZE(buf);
2969 HANDLE handle;
2970 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2971
2972 if (!ret || ret >= max)
2973 return;
2974
2975 /* make sure this does not leak into child processes */
2976 SetEnvironmentVariableW(key, NULL);
2977 if (!wcscmp(buf, L"off")) {
2978 close(fd);
2979 handle = GetStdHandle(std_id);
2980 if (handle != INVALID_HANDLE_VALUE)
2981 CloseHandle(handle);
2982 return;
2983 }
1a172e4a
JS
2984 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2985 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2986 if (handle == INVALID_HANDLE_VALUE) {
2987 close(fd);
2988 handle = GetStdHandle(std_id);
2989 if (handle != INVALID_HANDLE_VALUE)
2990 CloseHandle(handle);
2991 } else {
2992 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2993 SetStdHandle(std_id, handle);
2994 dup2(new_fd, fd);
2995 /* do *not* close the new_fd: that would close stdout */
2996 }
2997 return;
2998 }
3f944424
JS
2999 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
3000 flags, NULL);
3001 if (handle != INVALID_HANDLE_VALUE) {
3002 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3003 SetStdHandle(std_id, handle);
3004 dup2(new_fd, fd);
3005 close(new_fd);
3006 }
3007}
3008
3009static void maybe_redirect_std_handles(void)
3010{
3011 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
3012 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
3013 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
3014 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
3015 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
3016 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
3017}
3018
dce7d295
JH
3019#ifdef _MSC_VER
3020#ifdef _DEBUG
3021#include <crtdbg.h>
3022#endif
3023#endif
3024
396ff754
JS
3025/*
3026 * We implement wmain() and compile with -municode, which would
3027 * normally ignore main(), but we call the latter from the former
3028 * so that we can handle non-ASCII command-line parameters
3029 * appropriately.
3030 *
3031 * To be more compatible with the core git code, we convert
3032 * argv into UTF8 and pass them directly to main().
3033 */
3034int wmain(int argc, const wchar_t **wargv)
13f1df43 3035{
396ff754
JS
3036 int i, maxlen, exit_status;
3037 char *buffer, **save;
3038 const char **argv;
3f046148 3039
a0897249
JH
3040 trace2_initialize_clock();
3041
556702f8 3042#ifdef _MSC_VER
f6a63937
JS
3043#ifdef _DEBUG
3044 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3045#endif
3046
556702f8
JH
3047#ifdef USE_MSVC_CRTDBG
3048 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3049#endif
3050#endif
3051
3f944424
JS
3052 maybe_redirect_std_handles();
3053
3f046148 3054 /* determine size of argv and environ conversion buffer */
86e25458 3055 maxlen = wcslen(wargv[0]);
3f046148
KB
3056 for (i = 1; i < argc; i++)
3057 maxlen = max(maxlen, wcslen(wargv[i]));
3058
3059 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3060 maxlen = 3 * maxlen + 1;
6f1c189c 3061 buffer = malloc_startup(maxlen);
3f046148 3062
396ff754
JS
3063 /*
3064 * Create a UTF-8 version of w_argv. Also create a "save" copy
3065 * to remember all the string pointers because parse_options()
3066 * will remove claimed items from the argv that we pass down.
3067 */
3068 ALLOC_ARRAY(argv, argc + 1);
3069 ALLOC_ARRAY(save, argc + 1);
86e25458 3070 for (i = 0; i < argc; i++)
396ff754
JS
3071 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3072 argv[i] = save[i] = NULL;
3f046148 3073 free(buffer);
13f1df43 3074
6dc71543 3075 /* fix Windows specific environment settings */
02e6edc0 3076 setup_windows_environment();
baea068d 3077
0e218f91
JS
3078 unset_environment_variables = xstrdup("PERL5LIB");
3079
13f1df43
KB
3080 /* initialize critical section for waitpid pinfo_t list */
3081 InitializeCriticalSection(&pinfo_cs);
3082
3083 /* set up default file mode and file modes for stdin/out/err */
3084 _fmode = _O_BINARY;
3085 _setmode(_fileno(stdin), _O_BINARY);
3086 _setmode(_fileno(stdout), _O_BINARY);
3087 _setmode(_fileno(stderr), _O_BINARY);
eac14f89
KB
3088
3089 /* initialize Unicode console */
3090 winansi_init();
396ff754
JS
3091
3092 /* invoke the real main() using our utf8 version of argv. */
3093 exit_status = main(argc, argv);
3094
3095 for (i = 0; i < argc; i++)
3096 free(save[i]);
3097 free(save);
3098 free(argv);
3099
3100 return exit_status;
13f1df43 3101}
7b6aff06
NTND
3102
3103int uname(struct utsname *buf)
3104{
d62c89af 3105 unsigned v = (unsigned)GetVersion();
7b6aff06 3106 memset(buf, 0, sizeof(*buf));
5096d490
JK
3107 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3108 xsnprintf(buf->release, sizeof(buf->release),
3109 "%u.%u", v & 0xff, (v >> 8) & 0xff);
7b6aff06 3110 /* assuming NT variants only.. */
5096d490
JK
3111 xsnprintf(buf->version, sizeof(buf->version),
3112 "%u", (v >> 16) & 0x7fff);
7b6aff06
NTND
3113 return 0;
3114}