1 #include "../git-compat-util.h"
6 #include "../run-command.h"
8 #include "win32/lazyload.h"
12 #define HCAST(type, handle) ((type)(intptr_t)handle)
14 static const int delay[] = { 0, 1, 10, 20, 40 };
16 int err_win_to_posix(DWORD winerr)
20 case ERROR_ACCESS_DENIED: error = EACCES; break;
21 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
22 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
23 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
24 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
25 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
26 case ERROR_BAD_COMMAND: error = EIO; break;
27 case ERROR_BAD_DEVICE: error = ENODEV; break;
28 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
29 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
30 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
31 case ERROR_BAD_LENGTH: error = EINVAL; break;
32 case ERROR_BAD_PATHNAME: error = ENOENT; break;
33 case ERROR_BAD_PIPE: error = EPIPE; break;
34 case ERROR_BAD_UNIT: error = ENODEV; break;
35 case ERROR_BAD_USERNAME: error = EINVAL; break;
36 case ERROR_BROKEN_PIPE: error = EPIPE; break;
37 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
38 case ERROR_BUSY: error = EBUSY; break;
39 case ERROR_BUSY_DRIVE: error = EBUSY; break;
40 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
41 case ERROR_CANNOT_MAKE: error = EACCES; break;
42 case ERROR_CANTOPEN: error = EIO; break;
43 case ERROR_CANTREAD: error = EIO; break;
44 case ERROR_CANTWRITE: error = EIO; break;
45 case ERROR_CRC: error = EIO; break;
46 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
47 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
48 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
49 case ERROR_DIRECTORY: error = EINVAL; break;
50 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
51 case ERROR_DISK_CHANGE: error = EIO; break;
52 case ERROR_DISK_FULL: error = ENOSPC; break;
53 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
54 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
55 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
56 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
57 case ERROR_FILE_EXISTS: error = EEXIST; break;
58 case ERROR_FILE_INVALID: error = ENODEV; break;
59 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
60 case ERROR_GEN_FAILURE: error = EIO; break;
61 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
62 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
63 case ERROR_INVALID_ACCESS: error = EACCES; break;
64 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
65 case ERROR_INVALID_BLOCK: error = EFAULT; break;
66 case ERROR_INVALID_DATA: error = EINVAL; break;
67 case ERROR_INVALID_DRIVE: error = ENODEV; break;
68 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
69 case ERROR_INVALID_FLAGS: error = EINVAL; break;
70 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
71 case ERROR_INVALID_HANDLE: error = EBADF; break;
72 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
73 case ERROR_INVALID_NAME: error = EINVAL; break;
74 case ERROR_INVALID_OWNER: error = EINVAL; break;
75 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
76 case ERROR_INVALID_PASSWORD: error = EPERM; break;
77 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
78 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
79 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
80 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
81 case ERROR_IO_DEVICE: error = EIO; break;
82 case ERROR_IO_INCOMPLETE: error = EINTR; break;
83 case ERROR_LOCKED: error = EBUSY; break;
84 case ERROR_LOCK_VIOLATION: error = EACCES; break;
85 case ERROR_LOGON_FAILURE: error = EACCES; break;
86 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
87 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
88 case ERROR_MORE_DATA: error = EPIPE; break;
89 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
90 case ERROR_NOACCESS: error = EFAULT; break;
91 case ERROR_NONE_MAPPED: error = EINVAL; break;
92 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
93 case ERROR_NOT_READY: error = EAGAIN; break;
94 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
95 case ERROR_NO_DATA: error = EPIPE; break;
96 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
97 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
98 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
99 case ERROR_OPEN_FAILED: error = EIO; break;
100 case ERROR_OPEN_FILES: error = EBUSY; break;
101 case ERROR_OPERATION_ABORTED: error = EINTR; break;
102 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
103 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
104 case ERROR_PATH_BUSY: error = EBUSY; break;
105 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
106 case ERROR_PIPE_BUSY: error = EBUSY; break;
107 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
108 case ERROR_PIPE_LISTENING: error = EPIPE; break;
109 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
110 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
111 case ERROR_READ_FAULT: error = EIO; break;
112 case ERROR_SEEK: error = EIO; break;
113 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
114 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
115 case ERROR_SHARING_VIOLATION: error = EACCES; break;
116 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
117 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
118 case ERROR_SWAPERROR: error = ENOENT; break;
119 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
120 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
121 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
122 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
123 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
124 case ERROR_WRITE_FAULT: error = EIO; break;
125 case ERROR_WRITE_PROTECT: error = EROFS; break;
130 static inline int is_file_in_use_error(DWORD errcode)
133 case ERROR_SHARING_VIOLATION:
134 case ERROR_ACCESS_DENIED:
141 static int read_yes_no_answer(void)
145 if (fgets(answer, sizeof(answer), stdin)) {
146 size_t answer_len = strlen(answer);
147 int got_full_line = 0, c;
149 /* remove the newline */
150 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
151 answer[answer_len-2] = '\0';
153 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
154 answer[answer_len-1] = '\0';
157 /* flush the buffer in case we did not get the full line */
159 while ((c = getchar()) != EOF && c != '\n')
162 /* we could not read, return the
163 * default answer which is no */
166 if (tolower(answer[0]) == 'y' && !answer[1])
168 if (!strncasecmp(answer, "yes", sizeof(answer)))
170 if (tolower(answer[0]) == 'n' && !answer[1])
172 if (!strncasecmp(answer, "no", sizeof(answer)))
175 /* did not find an answer we understand */
179 static int ask_yes_no_if_possible(const char *format, ...)
182 const char *retry_hook[] = { NULL, NULL, NULL };
185 va_start(args, format);
186 vsnprintf(question, sizeof(question), format, args);
189 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
190 retry_hook[1] = question;
191 return !run_command_v_opt(retry_hook, 0);
194 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
199 fprintf(stderr, "%s (y/n) ", question);
201 if ((answer = read_yes_no_answer()) >= 0)
204 fprintf(stderr, "Sorry, I did not understand your answer. "
205 "Please type 'y' or 'n'\n");
210 enum hide_dotfiles_type {
211 HIDE_DOTFILES_FALSE = 0,
213 HIDE_DOTFILES_DOTGITONLY
216 static int core_restrict_inherited_handles = -1;
217 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
218 static char *unset_environment_variables;
220 int mingw_core_config(const char *var, const char *value, void *cb)
222 if (!strcmp(var, "core.hidedotfiles")) {
223 if (value && !strcasecmp(value, "dotgitonly"))
224 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
226 hide_dotfiles = git_config_bool(var, value);
230 if (!strcmp(var, "core.unsetenvvars")) {
231 free(unset_environment_variables);
232 unset_environment_variables = xstrdup(value);
236 if (!strcmp(var, "core.restrictinheritedhandles")) {
237 if (value && !strcasecmp(value, "auto"))
238 core_restrict_inherited_handles = -1;
240 core_restrict_inherited_handles =
241 git_config_bool(var, value);
248 /* Normalizes NT paths as returned by some low-level APIs. */
249 static wchar_t *normalize_ntpath(wchar_t *wbuf)
252 /* fix absolute path prefixes */
253 if (wbuf[0] == '\\') {
254 /* strip NT namespace prefixes */
255 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
256 !wcsncmp(wbuf, L"\\\\?\\", 4))
258 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
260 /* replace remaining '...UNC\' with '\\' */
261 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
266 /* convert backslashes to slashes */
267 for (i = 0; wbuf[i]; i++)
273 int mingw_unlink(const char *pathname)
276 wchar_t wpathname[MAX_PATH];
277 if (xutftowcs_path(wpathname, pathname) < 0)
280 /* read-only files cannot be removed */
281 _wchmod(wpathname, 0666);
282 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
283 if (!is_file_in_use_error(GetLastError()))
286 * We assume that some other process had the source or
287 * destination file open at the wrong moment and retry.
288 * In order to give the other process a higher chance to
289 * complete its operation, we give up our time slice now.
290 * If we have to retry again, we do sleep a bit.
295 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
296 ask_yes_no_if_possible("Unlink of file '%s' failed. "
297 "Should I try again?", pathname))
298 ret = _wunlink(wpathname);
302 static int is_dir_empty(const wchar_t *wpath)
304 WIN32_FIND_DATAW findbuf;
306 wchar_t wbuf[MAX_PATH + 2];
308 wcscat(wbuf, L"\\*");
309 handle = FindFirstFileW(wbuf, &findbuf);
310 if (handle == INVALID_HANDLE_VALUE)
311 return GetLastError() == ERROR_NO_MORE_FILES;
313 while (!wcscmp(findbuf.cFileName, L".") ||
314 !wcscmp(findbuf.cFileName, L".."))
315 if (!FindNextFileW(handle, &findbuf)) {
316 DWORD err = GetLastError();
318 return err == ERROR_NO_MORE_FILES;
324 int mingw_rmdir(const char *pathname)
327 wchar_t wpathname[MAX_PATH];
328 if (xutftowcs_path(wpathname, pathname) < 0)
331 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
332 if (!is_file_in_use_error(GetLastError()))
333 errno = err_win_to_posix(GetLastError());
336 if (!is_dir_empty(wpathname)) {
341 * We assume that some other process had the source or
342 * destination file open at the wrong moment and retry.
343 * In order to give the other process a higher chance to
344 * complete its operation, we give up our time slice now.
345 * If we have to retry again, we do sleep a bit.
350 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
351 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
352 "Should I try again?", pathname))
353 ret = _wrmdir(wpathname);
357 static inline int needs_hiding(const char *path)
359 const char *basename;
361 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
364 /* We cannot use basename(), as it would remove trailing slashes */
365 win32_skip_dos_drive_prefix((char **)&path);
369 for (basename = path; *path; path++)
370 if (is_dir_sep(*path)) {
373 } while (is_dir_sep(*path));
374 /* ignore trailing slashes */
381 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
382 return *basename == '.';
384 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
385 return !strncasecmp(".git", basename, 4) &&
386 (!basename[4] || is_dir_sep(basename[4]));
389 static int set_hidden_flag(const wchar_t *path, int set)
391 DWORD original = GetFileAttributesW(path), modified;
393 modified = original | FILE_ATTRIBUTE_HIDDEN;
395 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
396 if (original == modified || SetFileAttributesW(path, modified))
398 errno = err_win_to_posix(GetLastError());
402 int mingw_mkdir(const char *path, int mode)
405 wchar_t wpath[MAX_PATH];
407 if (!is_valid_win32_path(path)) {
412 if (xutftowcs_path(wpath, path) < 0)
414 ret = _wmkdir(wpath);
415 if (!ret && needs_hiding(path))
416 return set_hidden_flag(wpath, 1);
421 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
422 * is documented in [1] as opening a writable file handle in append mode.
423 * (It is believed that) this is atomic since it is maintained by the
424 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
426 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
428 * This trick does not appear to work for named pipes. Instead it creates
429 * a named pipe client handle that cannot be written to. Callers should
430 * just use the regular _wopen() for them. (And since client handle gets
431 * bound to a unique server handle, it isn't really an issue.)
433 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
437 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
439 /* only these flags are supported */
440 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
441 return errno = ENOSYS, -1;
444 * FILE_SHARE_WRITE is required to permit child processes
445 * to append to the file.
447 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
448 FILE_SHARE_WRITE | FILE_SHARE_READ,
449 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
450 if (handle == INVALID_HANDLE_VALUE)
451 return errno = err_win_to_posix(GetLastError()), -1;
454 * No O_APPEND here, because the CRT uses it only to reset the
455 * file pointer to EOF before each write(); but that is not
456 * necessary (and may lead to races) for a file created with
459 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
466 * Does the pathname map to the local named pipe filesystem?
467 * That is, does it have a "//./pipe/" prefix?
469 static int is_local_named_pipe_path(const char *filename)
471 return (is_dir_sep(filename[0]) &&
472 is_dir_sep(filename[1]) &&
473 filename[2] == '.' &&
474 is_dir_sep(filename[3]) &&
475 !strncasecmp(filename+4, "pipe", 4) &&
476 is_dir_sep(filename[8]) &&
480 int mingw_open (const char *filename, int oflags, ...)
482 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
485 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
486 wchar_t wfilename[MAX_PATH];
489 va_start(args, oflags);
490 mode = va_arg(args, int);
493 if (!is_valid_win32_path(filename)) {
494 errno = create ? EINVAL : ENOENT;
498 if (filename && !strcmp(filename, "/dev/null"))
501 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
502 open_fn = mingw_open_append;
506 if (xutftowcs_path(wfilename, filename) < 0)
508 fd = open_fn(wfilename, oflags, mode);
510 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
511 DWORD attrs = GetFileAttributesW(wfilename);
512 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
515 if ((oflags & O_CREAT) && needs_hiding(filename)) {
517 * Internally, _wopen() uses the CreateFile() API which errors
518 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
519 * specified and an already existing file's attributes do not
520 * match *exactly*. As there is no mode or flag we can set that
521 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
522 * again *without* the O_CREAT flag (that corresponds to the
523 * CREATE_ALWAYS flag of CreateFile()).
525 if (fd < 0 && errno == EACCES)
526 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
527 if (fd >= 0 && set_hidden_flag(wfilename, 1))
528 warning("could not mark '%s' as hidden.", filename);
533 static BOOL WINAPI ctrl_ignore(DWORD type)
539 int mingw_fgetc(FILE *stream)
542 if (!isatty(_fileno(stream)))
543 return fgetc(stream);
545 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
548 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
551 /* Ctrl+C was pressed, simulate SIGINT and retry */
554 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
559 FILE *mingw_fopen (const char *filename, const char *otype)
561 int hide = needs_hiding(filename);
563 wchar_t wfilename[MAX_PATH], wotype[4];
564 if (!is_valid_win32_path(filename)) {
565 int create = otype && strchr(otype, 'w');
566 errno = create ? EINVAL : ENOENT;
569 if (filename && !strcmp(filename, "/dev/null"))
571 if (xutftowcs_path(wfilename, filename) < 0 ||
572 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
574 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
575 error("could not unhide %s", filename);
578 file = _wfopen(wfilename, wotype);
579 if (!file && GetLastError() == ERROR_INVALID_NAME)
581 if (file && hide && set_hidden_flag(wfilename, 1))
582 warning("could not mark '%s' as hidden.", filename);
586 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
588 int hide = needs_hiding(filename);
590 wchar_t wfilename[MAX_PATH], wotype[4];
591 if (!is_valid_win32_path(filename)) {
592 int create = otype && strchr(otype, 'w');
593 errno = create ? EINVAL : ENOENT;
596 if (filename && !strcmp(filename, "/dev/null"))
598 if (xutftowcs_path(wfilename, filename) < 0 ||
599 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
601 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
602 error("could not unhide %s", filename);
605 file = _wfreopen(wfilename, wotype, stream);
606 if (file && hide && set_hidden_flag(wfilename, 1))
607 warning("could not mark '%s' as hidden.", filename);
612 int mingw_fflush(FILE *stream)
614 int ret = fflush(stream);
617 * write() is used behind the scenes of stdio output functions.
618 * Since git code does not check for errors after each stdio write
619 * operation, it can happen that write() is called by a later
620 * stdio function even if an earlier write() call failed. In the
621 * case of a pipe whose readable end was closed, only the first
622 * call to write() reports EPIPE on Windows. Subsequent write()
623 * calls report EINVAL. It is impossible to notice whether this
624 * fflush invocation triggered such a case, therefore, we have to
625 * catch all EINVAL errors whole-sale.
627 if (ret && errno == EINVAL)
634 ssize_t mingw_write(int fd, const void *buf, size_t len)
636 ssize_t result = write(fd, buf, len);
638 if (result < 0 && errno == EINVAL && buf) {
639 /* check if fd is a pipe */
640 HANDLE h = (HANDLE) _get_osfhandle(fd);
641 if (GetFileType(h) == FILE_TYPE_PIPE)
650 int mingw_access(const char *filename, int mode)
652 wchar_t wfilename[MAX_PATH];
653 if (xutftowcs_path(wfilename, filename) < 0)
655 /* X_OK is not supported by the MSVCRT version */
656 return _waccess(wfilename, mode & ~X_OK);
659 int mingw_chdir(const char *dirname)
661 wchar_t wdirname[MAX_PATH];
662 if (xutftowcs_path(wdirname, dirname) < 0)
664 return _wchdir(wdirname);
667 int mingw_chmod(const char *filename, int mode)
669 wchar_t wfilename[MAX_PATH];
670 if (xutftowcs_path(wfilename, filename) < 0)
672 return _wchmod(wfilename, mode);
676 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
677 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
679 static inline long long filetime_to_hnsec(const FILETIME *ft)
681 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
682 /* Windows to Unix Epoch conversion */
683 return winTime - 116444736000000000LL;
686 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
688 long long hnsec = filetime_to_hnsec(ft);
689 ts->tv_sec = (time_t)(hnsec / 10000000);
690 ts->tv_nsec = (hnsec % 10000000) * 100;
694 * Verifies that safe_create_leading_directories() would succeed.
696 static int has_valid_directory_prefix(wchar_t *wfilename)
698 int n = wcslen(wfilename);
701 wchar_t c = wfilename[--n];
707 wfilename[n] = L'\0';
708 attributes = GetFileAttributesW(wfilename);
710 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
711 attributes == FILE_ATTRIBUTE_DEVICE)
713 if (attributes == INVALID_FILE_ATTRIBUTES)
714 switch (GetLastError()) {
715 case ERROR_PATH_NOT_FOUND:
717 case ERROR_FILE_NOT_FOUND:
718 /* This implies parent directory exists. */
726 /* We keep the do_lstat code in a separate function to avoid recursion.
727 * When a path ends with a slash, the stat will fail with ENOENT. In
728 * this case, we strip the trailing slashes and stat again.
730 * If follow is true then act like stat() and report on the link
731 * target. Otherwise report on the link itself.
733 static int do_lstat(int follow, const char *file_name, struct stat *buf)
735 WIN32_FILE_ATTRIBUTE_DATA fdata;
736 wchar_t wfilename[MAX_PATH];
737 if (xutftowcs_path(wfilename, file_name) < 0)
740 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
745 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
746 buf->st_size = fdata.nFileSizeLow |
747 (((off_t)fdata.nFileSizeHigh)<<32);
748 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
749 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
750 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
751 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
752 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
753 WIN32_FIND_DATAW findbuf;
754 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
755 if (handle != INVALID_HANDLE_VALUE) {
756 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
757 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
759 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
760 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
762 buf->st_mode = S_IFLNK;
764 buf->st_mode |= S_IREAD;
765 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
766 buf->st_mode |= S_IWRITE;
773 switch (GetLastError()) {
774 case ERROR_ACCESS_DENIED:
775 case ERROR_SHARING_VIOLATION:
776 case ERROR_LOCK_VIOLATION:
777 case ERROR_SHARING_BUFFER_EXCEEDED:
780 case ERROR_BUFFER_OVERFLOW:
781 errno = ENAMETOOLONG;
783 case ERROR_NOT_ENOUGH_MEMORY:
786 case ERROR_PATH_NOT_FOUND:
787 if (!has_valid_directory_prefix(wfilename)) {
799 /* We provide our own lstat/fstat functions, since the provided
800 * lstat/fstat functions are so slow. These stat functions are
801 * tailored for Git's usage (read: fast), and are not meant to be
802 * complete. Note that Git stat()s are redirected to mingw_lstat()
803 * too, since Windows doesn't really handle symlinks that well.
805 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
808 char alt_name[PATH_MAX];
810 if (!do_lstat(follow, file_name, buf))
813 /* if file_name ended in a '/', Windows returned ENOENT;
814 * try again without trailing slashes
819 namelen = strlen(file_name);
820 if (namelen && file_name[namelen-1] != '/')
822 while (namelen && file_name[namelen-1] == '/')
824 if (!namelen || namelen >= PATH_MAX)
827 memcpy(alt_name, file_name, namelen);
828 alt_name[namelen] = 0;
829 return do_lstat(follow, alt_name, buf);
832 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
834 BY_HANDLE_FILE_INFORMATION fdata;
836 if (!GetFileInformationByHandle(hnd, &fdata)) {
837 errno = err_win_to_posix(GetLastError());
845 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
846 buf->st_size = fdata.nFileSizeLow |
847 (((off_t)fdata.nFileSizeHigh)<<32);
848 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
849 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
850 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
851 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
855 int mingw_lstat(const char *file_name, struct stat *buf)
857 return do_stat_internal(0, file_name, buf);
859 int mingw_stat(const char *file_name, struct stat *buf)
861 return do_stat_internal(1, file_name, buf);
864 int mingw_fstat(int fd, struct stat *buf)
866 HANDLE fh = (HANDLE)_get_osfhandle(fd);
867 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
871 return get_file_info_by_handle(fh, buf);
875 /* initialize stat fields */
876 memset(buf, 0, sizeof(*buf));
879 if (type == FILE_TYPE_CHAR) {
880 buf->st_mode = _S_IFCHR;
882 buf->st_mode = _S_IFIFO;
883 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
884 buf->st_size = avail;
894 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
896 long long winTime = t * 10000000LL + 116444736000000000LL;
897 ft->dwLowDateTime = winTime;
898 ft->dwHighDateTime = winTime >> 32;
901 int mingw_utime (const char *file_name, const struct utimbuf *times)
906 wchar_t wfilename[MAX_PATH];
907 if (xutftowcs_path(wfilename, file_name) < 0)
910 /* must have write permission */
911 attrs = GetFileAttributesW(wfilename);
912 if (attrs != INVALID_FILE_ATTRIBUTES &&
913 (attrs & FILE_ATTRIBUTE_READONLY)) {
914 /* ignore errors here; open() will report them */
915 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
918 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
924 time_t_to_filetime(times->modtime, &mft);
925 time_t_to_filetime(times->actime, &aft);
927 GetSystemTimeAsFileTime(&mft);
930 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
938 if (attrs != INVALID_FILE_ATTRIBUTES &&
939 (attrs & FILE_ATTRIBUTE_READONLY)) {
940 /* ignore errors again */
941 SetFileAttributesW(wfilename, attrs);
947 size_t mingw_strftime(char *s, size_t max,
948 const char *format, const struct tm *tm)
950 size_t ret = strftime(s, max, format, tm);
952 if (!ret && errno == EINVAL)
953 die("invalid strftime format: '%s'", format);
957 unsigned int sleep (unsigned int seconds)
963 char *mingw_mktemp(char *template)
965 wchar_t wtemplate[MAX_PATH];
966 if (xutftowcs_path(wtemplate, template) < 0)
968 if (!_wmktemp(wtemplate))
970 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
975 int mkstemp(char *template)
977 char *filename = mktemp(template);
978 if (filename == NULL)
980 return open(filename, O_RDWR | O_CREAT, 0600);
983 int gettimeofday(struct timeval *tv, void *tz)
988 GetSystemTimeAsFileTime(&ft);
989 hnsec = filetime_to_hnsec(&ft);
990 tv->tv_sec = hnsec / 10000000;
991 tv->tv_usec = (hnsec % 10000000) / 10;
995 int pipe(int filedes[2])
999 /* this creates non-inheritable handles */
1000 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1001 errno = err_win_to_posix(GetLastError());
1004 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1005 if (filedes[0] < 0) {
1010 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1011 if (filedes[1] < 0) {
1019 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1021 if (gmtime_s(result, timep) == 0)
1026 struct tm *localtime_r(const time_t *timep, struct tm *result)
1028 if (localtime_s(result, timep) == 0)
1033 char *mingw_getcwd(char *pointer, int len)
1035 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1036 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1038 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1039 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1042 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1043 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1044 HANDLE hnd = CreateFileW(cwd, 0,
1045 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1046 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1047 if (hnd == INVALID_HANDLE_VALUE)
1049 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1051 if (!ret || ret >= ARRAY_SIZE(wpointer))
1053 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1057 if (!ret || ret >= ARRAY_SIZE(wpointer))
1059 if (xwcstoutf(pointer, wpointer, len) < 0)
1061 convert_slashes(pointer);
1066 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1067 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1069 static const char *quote_arg_msvc(const char *arg)
1071 /* count chars to quote */
1073 int force_quotes = 0;
1075 const char *p = arg;
1076 if (!*p) force_quotes = 1;
1078 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1082 else if (*p == '\\') {
1084 while (*p == '\\') {
1089 if (*p == '"' || !*p)
1096 if (!force_quotes && n == 0)
1099 /* insert \ where necessary */
1100 d = q = xmalloc(st_add3(len, n, 3));
1105 else if (*arg == '\\') {
1107 while (*arg == '\\') {
1111 if (*arg == '"' || !*arg) {
1114 /* don't escape the surrounding end quote */
1129 static const char *quote_arg_msys2(const char *arg)
1131 struct strbuf buf = STRBUF_INIT;
1132 const char *p2 = arg, *p;
1134 for (p = arg; *p; p++) {
1135 int ws = isspace(*p);
1136 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1137 *p != '?' && *p != '*' && *p != '~')
1140 strbuf_addch(&buf, '"');
1142 strbuf_add(&buf, p2, p - p2);
1143 if (*p == '\\' || *p == '"')
1144 strbuf_addch(&buf, '\\');
1149 strbuf_addch(&buf, '"');
1153 strbuf_add(&buf, p2, p - p2);
1155 strbuf_addch(&buf, '"');
1156 return strbuf_detach(&buf, 0);
1159 static const char *parse_interpreter(const char *cmd)
1161 static char buf[100];
1165 /* don't even try a .exe */
1167 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1170 fd = open(cmd, O_RDONLY);
1173 n = read(fd, buf, sizeof(buf)-1);
1175 if (n < 4) /* at least '#!/x' and not error */
1178 if (buf[0] != '#' || buf[1] != '!')
1181 p = buf + strcspn(buf, "\r\n");
1186 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1189 if ((opt = strchr(p+1, ' ')))
1195 * exe_only means that we only want to detect .exe files, but not scripts
1196 * (which do not have an extension)
1198 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1199 int isexe, int exe_only)
1201 char path[MAX_PATH];
1202 wchar_t wpath[MAX_PATH];
1203 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1205 if (xutftowcs_path(wpath, path) < 0)
1208 if (!isexe && _waccess(wpath, F_OK) == 0)
1209 return xstrdup(path);
1210 wpath[wcslen(wpath)-4] = '\0';
1211 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1212 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1213 path[strlen(path)-4] = '\0';
1214 return xstrdup(path);
1221 * Determines the absolute path of cmd using the split path in path.
1222 * If cmd contains a slash or backslash, no lookup is performed.
1224 static char *path_lookup(const char *cmd, int exe_only)
1228 int len = strlen(cmd);
1229 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1231 if (strchr(cmd, '/') || strchr(cmd, '\\'))
1232 return xstrdup(cmd);
1234 path = mingw_getenv("PATH");
1239 const char *sep = strchrnul(path, ';');
1240 int dirlen = sep - path;
1242 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1251 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1253 while (*s && *s != c)
1258 /* Compare only keys */
1259 static int wenvcmp(const void *a, const void *b)
1261 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1262 size_t p_len, q_len;
1265 p_len = wcschrnul(p, L'=') - p;
1266 q_len = wcschrnul(q, L'=') - q;
1268 /* If the length differs, include the shorter key's NUL */
1271 else if (p_len > q_len)
1274 return _wcsnicmp(p, q, p_len);
1278 * Build an environment block combining the inherited environment
1279 * merged with the given list of settings.
1281 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1282 * Values of the form "KEY" in deltaenv delete inherited values.
1284 * Multiple entries in deltaenv for the same key are explicitly allowed.
1286 * We return a contiguous block of UNICODE strings with a final trailing
1289 static wchar_t *make_environment_block(char **deltaenv)
1291 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1292 size_t wlen, s, delta_size, size;
1294 wchar_t **array = NULL;
1295 size_t alloc = 0, nr = 0, i;
1297 size = 1; /* for extra NUL at the end */
1299 /* If there is no deltaenv to apply, simply return a copy. */
1300 if (!deltaenv || !*deltaenv) {
1301 for (p = wenv; p && *p; ) {
1302 size_t s = wcslen(p) + 1;
1307 ALLOC_ARRAY(result, size);
1308 COPY_ARRAY(result, wenv, size);
1309 FreeEnvironmentStringsW(wenv);
1314 * If there is a deltaenv, let's accumulate all keys into `array`,
1315 * sort them using the stable git_stable_qsort() and then copy,
1316 * skipping duplicate keys
1318 for (p = wenv; p && *p; ) {
1319 ALLOC_GROW(array, nr + 1, alloc);
1326 /* (over-)assess size needed for wchar version of deltaenv */
1327 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1328 delta_size += strlen(deltaenv[i]) * 2 + 1;
1329 ALLOC_ARRAY(wdeltaenv, delta_size);
1331 /* convert the deltaenv, appending to array */
1332 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1333 ALLOC_GROW(array, nr + 1, alloc);
1334 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1339 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1340 ALLOC_ARRAY(result, size + delta_size);
1342 for (p = result, i = 0; i < nr; i++) {
1343 /* Skip any duplicate keys; last one wins */
1344 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1347 /* Skip "to delete" entry */
1348 if (!wcschr(array[i], L'='))
1351 size = wcslen(array[i]) + 1;
1352 COPY_ARRAY(p, array[i], size);
1359 FreeEnvironmentStringsW(wenv);
1363 static void do_unset_environment_variables(void)
1366 char *p = unset_environment_variables;
1373 char *comma = strchr(p, ',');
1385 struct pinfo_t *next;
1389 static struct pinfo_t *pinfo = NULL;
1390 CRITICAL_SECTION pinfo_cs;
1392 /* Used to match and chomp off path components */
1393 static inline int match_last_path_component(const char *path, size_t *len,
1394 const char *component)
1396 size_t component_len = strlen(component);
1397 if (*len < component_len + 1 ||
1398 !is_dir_sep(path[*len - component_len - 1]) ||
1399 fspathncmp(path + *len - component_len, component, component_len))
1401 *len -= component_len + 1;
1402 /* chomp off repeated dir separators */
1403 while (*len > 0 && is_dir_sep(path[*len - 1]))
1408 static int is_msys2_sh(const char *cmd)
1413 if (!strcmp(cmd, "sh")) {
1414 static int ret = -1;
1420 p = path_lookup(cmd, 0);
1424 size_t len = strlen(p);
1426 ret = match_last_path_component(p, &len, "sh.exe") &&
1427 match_last_path_component(p, &len, "bin") &&
1428 match_last_path_component(p, &len, "usr");
1434 if (ends_with(cmd, "\\sh.exe")) {
1438 sh = path_lookup("sh", 0);
1440 return !fspathcmp(cmd, sh);
1446 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1448 int prepend_cmd, int fhin, int fhout, int fherr)
1450 static int restrict_handle_inheritance = -1;
1452 PROCESS_INFORMATION pi;
1453 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1454 HANDLE stdhandles[3];
1455 DWORD stdhandles_count = 0;
1458 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1459 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1462 const char *(*quote_arg)(const char *arg) =
1463 is_msys2_sh(cmd ? cmd : *argv) ?
1464 quote_arg_msys2 : quote_arg_msvc;
1466 /* Make sure to override previous errors, if any */
1469 if (restrict_handle_inheritance < 0)
1470 restrict_handle_inheritance = core_restrict_inherited_handles;
1472 * The following code to restrict which handles are inherited seems
1473 * to work properly only on Windows 7 and later, so let's disable it
1474 * on Windows Vista and 2008.
1476 if (restrict_handle_inheritance < 0)
1477 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1479 do_unset_environment_variables();
1481 /* Determine whether or not we are associated to a console */
1482 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1483 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1484 FILE_ATTRIBUTE_NORMAL, NULL);
1485 if (cons == INVALID_HANDLE_VALUE) {
1486 /* There is no console associated with this process.
1487 * Since the child is a console process, Windows
1488 * would normally create a console window. But
1489 * since we'll be redirecting std streams, we do
1490 * not need the console.
1491 * It is necessary to use DETACHED_PROCESS
1492 * instead of CREATE_NO_WINDOW to make ssh
1493 * recognize that it has no console.
1495 flags |= DETACHED_PROCESS;
1497 /* There is already a console. If we specified
1498 * DETACHED_PROCESS here, too, Windows would
1499 * disassociate the child from the console.
1500 * The same is true for CREATE_NO_WINDOW.
1505 memset(&si, 0, sizeof(si));
1506 si.StartupInfo.cb = sizeof(si);
1507 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1508 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1509 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1511 /* The list of handles cannot contain duplicates */
1512 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1513 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1514 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1515 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1516 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1517 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1518 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1519 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1520 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1521 if (stdhandles_count)
1522 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1524 if (*argv && !strcmp(cmd, *argv))
1526 else if (xutftowcs_path(wcmd, cmd) < 0)
1528 if (dir && xutftowcs_path(wdir, dir) < 0)
1531 /* concatenate argv, quoting args as we go */
1532 strbuf_init(&args, 0);
1534 char *quoted = (char *)quote_arg(cmd);
1535 strbuf_addstr(&args, quoted);
1539 for (; *argv; argv++) {
1540 char *quoted = (char *)quote_arg(*argv);
1542 strbuf_addch(&args, ' ');
1543 strbuf_addstr(&args, quoted);
1544 if (quoted != *argv)
1548 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1549 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1550 strbuf_release(&args);
1552 wenvblk = make_environment_block(deltaenv);
1554 memset(&pi, 0, sizeof(pi));
1555 if (restrict_handle_inheritance && stdhandles_count &&
1556 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1557 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1558 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1559 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1560 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1561 UpdateProcThreadAttribute(attr_list, 0,
1562 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1564 stdhandles_count * sizeof(HANDLE),
1566 si.lpAttributeList = attr_list;
1567 flags |= EXTENDED_STARTUPINFO_PRESENT;
1570 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1571 stdhandles_count ? TRUE : FALSE,
1572 flags, wenvblk, dir ? wdir : NULL,
1573 &si.StartupInfo, &pi);
1576 * On Windows 2008 R2, it seems that specifying certain types of handles
1577 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1578 * error. Rather than playing finicky and fragile games, let's just try
1579 * to detect this situation and simply try again without restricting any
1580 * handle inheritance. This is still better than failing to create
1583 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1584 DWORD err = GetLastError();
1585 struct strbuf buf = STRBUF_INIT;
1587 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1589 * On Windows 7 and earlier, handles on pipes and character
1590 * devices are inherited automatically, and cannot be
1591 * specified in the thread handle list. Rather than trying
1592 * to catch each and every corner case (and running the
1593 * chance of *still* forgetting a few), let's just fall
1594 * back to creating the process without trying to limit the
1595 * handle inheritance.
1597 !(err == ERROR_INVALID_PARAMETER &&
1598 GetVersion() >> 16 < 9200) &&
1599 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1603 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1605 for (i = 0; i < stdhandles_count; i++) {
1606 HANDLE h = stdhandles[i];
1607 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1608 "handle info (%d) %lx\n", i, h,
1610 GetHandleInformation(h, &fl),
1613 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1614 "at\nhttps://github.com/git-for-windows/"
1615 "git/issues/new\n\n"
1616 "To suppress this warning, please set "
1617 "the environment variable\n\n"
1618 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1621 restrict_handle_inheritance = 0;
1622 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1623 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1624 TRUE, flags, wenvblk, dir ? wdir : NULL,
1625 &si.StartupInfo, &pi);
1627 errno = err_win_to_posix(GetLastError());
1628 if (ret && buf.len) {
1629 warning("failed to restrict file handles (%ld)\n\n%s",
1632 strbuf_release(&buf);
1634 errno = err_win_to_posix(GetLastError());
1636 if (si.lpAttributeList)
1637 DeleteProcThreadAttributeList(si.lpAttributeList);
1639 HeapFree(GetProcessHeap(), 0, attr_list);
1647 CloseHandle(pi.hThread);
1650 * The process ID is the human-readable identifier of the process
1651 * that we want to present in log and error messages. The handle
1652 * is not useful for this purpose. But we cannot close it, either,
1653 * because it is not possible to turn a process ID into a process
1654 * handle after the process terminated.
1655 * Keep the handle in a list for waitpid.
1657 EnterCriticalSection(&pinfo_cs);
1659 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1660 info->pid = pi.dwProcessId;
1661 info->proc = pi.hProcess;
1665 LeaveCriticalSection(&pinfo_cs);
1667 return (pid_t)pi.dwProcessId;
1670 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1672 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1675 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1677 int fhin, int fhout, int fherr)
1680 char *prog = path_lookup(cmd, 0);
1687 const char *interpr = parse_interpreter(prog);
1690 const char *argv0 = argv[0];
1691 char *iprog = path_lookup(interpr, 1);
1698 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1699 fhin, fhout, fherr);
1705 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1706 fhin, fhout, fherr);
1712 static int try_shell_exec(const char *cmd, char *const *argv)
1714 const char *interpr = parse_interpreter(cmd);
1720 prog = path_lookup(interpr, 1);
1728 while (argv[argc]) argc++;
1729 ALLOC_ARRAY(argv2, argc + 1);
1730 argv2[0] = (char *)cmd; /* full path to the script file */
1731 COPY_ARRAY(&argv2[1], &argv[1], argc);
1732 exec_id = trace2_exec(prog, argv2);
1733 pid = mingw_spawnv(prog, argv2, 1);
1736 if (waitpid(pid, &status, 0) < 0)
1738 trace2_exec_result(exec_id, status);
1741 trace2_exec_result(exec_id, -1);
1742 pid = 1; /* indicate that we tried but failed */
1749 int mingw_execv(const char *cmd, char *const *argv)
1751 /* check if git_command is a shell script */
1752 if (!try_shell_exec(cmd, argv)) {
1756 exec_id = trace2_exec(cmd, (const char **)argv);
1757 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1759 trace2_exec_result(exec_id, -1);
1762 if (waitpid(pid, &status, 0) < 0)
1764 trace2_exec_result(exec_id, status);
1770 int mingw_execvp(const char *cmd, char *const *argv)
1772 char *prog = path_lookup(cmd, 0);
1775 mingw_execv(prog, argv);
1783 int mingw_kill(pid_t pid, int sig)
1785 if (pid > 0 && sig == SIGTERM) {
1786 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1788 if (TerminateProcess(h, -1)) {
1793 errno = err_win_to_posix(GetLastError());
1796 } else if (pid > 0 && sig == 0) {
1797 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1809 * UTF-8 versions of getenv(), putenv() and unsetenv().
1810 * Internally, they use the CRT's stock UNICODE routines
1811 * to avoid data loss.
1813 char *mingw_getenv(const char *name)
1815 #define GETENV_MAX_RETAIN 64
1816 static char *values[GETENV_MAX_RETAIN];
1817 static int value_counter;
1818 int len_key, len_value;
1821 wchar_t w_value[32768];
1823 if (!name || !*name)
1826 len_key = strlen(name) + 1;
1827 /* We cannot use xcalloc() here because that uses getenv() itself */
1828 w_key = calloc(len_key, sizeof(wchar_t));
1830 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1831 xutftowcs(w_key, name, len_key);
1832 /* GetEnvironmentVariableW() only sets the last error upon failure */
1833 SetLastError(ERROR_SUCCESS);
1834 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1835 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1841 len_value = len_value * 3 + 1;
1842 /* We cannot use xcalloc() here because that uses getenv() itself */
1843 value = calloc(len_value, sizeof(char));
1845 die("Out of memory, (tried to allocate %u bytes)", len_value);
1846 xwcstoutf(value, w_value, len_value);
1849 * We return `value` which is an allocated value and the caller is NOT
1850 * expecting to have to free it, so we keep a round-robin array,
1851 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1853 free(values[value_counter]);
1854 values[value_counter++] = value;
1855 if (value_counter >= ARRAY_SIZE(values))
1861 int mingw_putenv(const char *namevalue)
1864 wchar_t *wide, *equal;
1867 if (!namevalue || !*namevalue)
1870 size = strlen(namevalue) * 2 + 1;
1871 wide = calloc(size, sizeof(wchar_t));
1873 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1874 xutftowcs(wide, namevalue, size);
1875 equal = wcschr(wide, L'=');
1877 result = SetEnvironmentVariableW(wide, NULL);
1880 result = SetEnvironmentVariableW(wide, equal + 1);
1885 errno = err_win_to_posix(GetLastError());
1887 return result ? 0 : -1;
1890 static void ensure_socket_initialization(void)
1893 static int initialized = 0;
1898 if (WSAStartup(MAKEWORD(2,2), &wsa))
1899 die("unable to initialize winsock subsystem, error %d",
1902 atexit((void(*)(void)) WSACleanup);
1907 int mingw_gethostname(char *name, int namelen)
1909 ensure_socket_initialization();
1910 return gethostname(name, namelen);
1913 #undef gethostbyname
1914 struct hostent *mingw_gethostbyname(const char *host)
1916 ensure_socket_initialization();
1917 return gethostbyname(host);
1921 int mingw_getaddrinfo(const char *node, const char *service,
1922 const struct addrinfo *hints, struct addrinfo **res)
1924 ensure_socket_initialization();
1925 return getaddrinfo(node, service, hints, res);
1928 int mingw_socket(int domain, int type, int protocol)
1933 ensure_socket_initialization();
1934 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1935 if (s == INVALID_SOCKET) {
1937 * WSAGetLastError() values are regular BSD error codes
1938 * biased by WSABASEERR.
1939 * However, strerror() does not know about networking
1940 * specific errors, which are values beginning at 38 or so.
1941 * Therefore, we choose to leave the biased error code
1942 * in errno so that _if_ someone looks up the code somewhere,
1943 * then it is at least the number that are usually listed.
1945 errno = WSAGetLastError();
1948 /* convert into a file descriptor */
1949 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1951 return error("unable to make a socket file descriptor: %s",
1958 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1960 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1961 return connect(s, sa, sz);
1965 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1967 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1968 return bind(s, sa, sz);
1972 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1974 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1975 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1979 int mingw_shutdown(int sockfd, int how)
1981 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1982 return shutdown(s, how);
1986 int mingw_listen(int sockfd, int backlog)
1988 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1989 return listen(s, backlog);
1993 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1997 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1998 SOCKET s2 = accept(s1, sa, sz);
2000 /* convert into a file descriptor */
2001 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2004 return error("unable to make a socket file descriptor: %s",
2011 int mingw_rename(const char *pold, const char *pnew)
2015 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2016 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2020 * Try native rename() first to get errno right.
2021 * It is based on MoveFile(), which cannot overwrite existing files.
2023 if (!_wrename(wpold, wpnew))
2025 if (errno != EEXIST)
2028 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2030 /* TODO: translate more errors */
2031 gle = GetLastError();
2032 if (gle == ERROR_ACCESS_DENIED &&
2033 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2034 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2035 DWORD attrsold = GetFileAttributesW(wpold);
2036 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2037 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2039 else if (!_wrmdir(wpnew))
2043 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2044 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2045 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2047 gle = GetLastError();
2048 /* revert file attributes on failure */
2049 SetFileAttributesW(wpnew, attrs);
2052 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2054 * We assume that some other process had the source or
2055 * destination file open at the wrong moment and retry.
2056 * In order to give the other process a higher chance to
2057 * complete its operation, we give up our time slice now.
2058 * If we have to retry again, we do sleep a bit.
2060 Sleep(delay[tries]);
2064 if (gle == ERROR_ACCESS_DENIED &&
2065 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2066 "Should I try again?", pold, pnew))
2074 * Note that this doesn't return the actual pagesize, but
2075 * the allocation granularity. If future Windows specific git code
2076 * needs the real getpagesize function, we need to find another solution.
2078 int mingw_getpagesize(void)
2082 return si.dwAllocationGranularity;
2085 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2086 enum EXTENDED_NAME_FORMAT {
2088 NameUserPrincipal = 8
2091 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2093 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2094 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2095 static wchar_t wbuffer[1024];
2098 if (!INIT_PROC_ADDR(GetUserNameExW))
2101 len = ARRAY_SIZE(wbuffer);
2102 if (GetUserNameExW(type, wbuffer, &len)) {
2103 char *converted = xmalloc((len *= 3));
2104 if (xwcstoutf(converted, wbuffer, len) >= 0)
2112 char *mingw_query_user_email(void)
2114 return get_extended_user_info(NameUserPrincipal);
2117 struct passwd *getpwuid(int uid)
2119 static unsigned initialized;
2120 static char user_name[100];
2121 static struct passwd *p;
2128 len = ARRAY_SIZE(buf);
2129 if (!GetUserNameW(buf, &len)) {
2134 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2139 p = xmalloc(sizeof(*p));
2140 p->pw_name = user_name;
2141 p->pw_gecos = get_extended_user_info(NameDisplay);
2143 p->pw_gecos = "unknown";
2150 static HANDLE timer_event;
2151 static HANDLE timer_thread;
2152 static int timer_interval;
2153 static int one_shot;
2154 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2156 /* The timer works like this:
2157 * The thread, ticktack(), is a trivial routine that most of the time
2158 * only waits to receive the signal to terminate. The main thread tells
2159 * the thread to terminate by setting the timer_event to the signalled
2161 * But ticktack() interrupts the wait state after the timer's interval
2162 * length to call the signal handler.
2165 static unsigned __stdcall ticktack(void *dummy)
2167 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2168 mingw_raise(SIGALRM);
2175 static int start_timer_thread(void)
2177 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2179 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2181 return errno = ENOMEM,
2182 error("cannot start timer thread");
2184 return errno = ENOMEM,
2185 error("cannot allocate resources for timer");
2189 static void stop_timer_thread(void)
2192 SetEvent(timer_event); /* tell thread to terminate */
2194 int rc = WaitForSingleObject(timer_thread, 10000);
2195 if (rc == WAIT_TIMEOUT)
2196 error("timer thread did not terminate timely");
2197 else if (rc != WAIT_OBJECT_0)
2198 error("waiting for timer thread failed: %lu",
2200 CloseHandle(timer_thread);
2203 CloseHandle(timer_event);
2205 timer_thread = NULL;
2208 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2210 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2213 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2215 static const struct timeval zero;
2216 static int atexit_done;
2219 return errno = EINVAL,
2220 error("setitimer param 3 != NULL not implemented");
2221 if (!is_timeval_eq(&in->it_interval, &zero) &&
2222 !is_timeval_eq(&in->it_interval, &in->it_value))
2223 return errno = EINVAL,
2224 error("setitimer: it_interval must be zero or eq it_value");
2227 stop_timer_thread();
2229 if (is_timeval_eq(&in->it_value, &zero) &&
2230 is_timeval_eq(&in->it_interval, &zero))
2233 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2234 one_shot = is_timeval_eq(&in->it_interval, &zero);
2236 atexit(stop_timer_thread);
2239 return start_timer_thread();
2242 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2245 return errno = EINVAL,
2246 error("sigaction only implemented for SIGALRM");
2248 return errno = EINVAL,
2249 error("sigaction: param 3 != NULL not implemented");
2251 timer_fn = in->sa_handler;
2256 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2268 sigint_fn = handler;
2272 return signal(sig, handler);
2279 int mingw_raise(int sig)
2283 if (timer_fn == SIG_DFL) {
2284 if (isatty(STDERR_FILENO))
2285 fputs("Alarm clock\n", stderr);
2286 exit(128 + SIGALRM);
2287 } else if (timer_fn != SIG_IGN)
2292 if (sigint_fn == SIG_DFL)
2294 else if (sigint_fn != SIG_IGN)
2298 #if defined(_MSC_VER)
2305 case SIGABRT_COMPAT:
2307 * The <signal.h> header in the MS C Runtime defines 8 signals
2308 * as being supported on the platform. Anything else causes an
2309 * "Invalid signal or error" (which in DEBUG builds causes the
2310 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2311 * already know will fail.
2328 int link(const char *oldpath, const char *newpath)
2330 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2331 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2332 xutftowcs_path(wnewpath, newpath) < 0)
2335 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2336 errno = err_win_to_posix(GetLastError());
2342 pid_t waitpid(pid_t pid, int *status, int options)
2344 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2351 if (pid > 0 && options & WNOHANG) {
2352 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2356 options &= ~WNOHANG;
2360 struct pinfo_t **ppinfo;
2361 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2367 GetExitCodeProcess(h, (LPDWORD)status);
2369 EnterCriticalSection(&pinfo_cs);
2373 struct pinfo_t *info = *ppinfo;
2374 if (info->pid == pid) {
2375 CloseHandle(info->proc);
2376 *ppinfo = info->next;
2380 ppinfo = &info->next;
2383 LeaveCriticalSection(&pinfo_cs);
2394 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2396 int upos = 0, wpos = 0;
2397 const unsigned char *utf = (const unsigned char*) utfs;
2398 if (!utf || !wcs || wcslen < 1) {
2402 /* reserve space for \0 */
2407 while (upos < utflen) {
2408 int c = utf[upos++] & 0xff;
2409 if (utflen == INT_MAX && c == 0)
2412 if (wpos >= wcslen) {
2421 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2422 (utf[upos] & 0xc0) == 0x80) {
2424 c = ((c & 0x1f) << 6);
2425 c |= (utf[upos++] & 0x3f);
2427 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2428 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2429 (utf[upos] & 0xc0) == 0x80 &&
2430 (utf[upos + 1] & 0xc0) == 0x80) {
2432 c = ((c & 0x0f) << 12);
2433 c |= ((utf[upos++] & 0x3f) << 6);
2434 c |= (utf[upos++] & 0x3f);
2436 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2437 wpos + 1 < wcslen &&
2438 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2439 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2440 (utf[upos] & 0xc0) == 0x80 &&
2441 (utf[upos + 1] & 0xc0) == 0x80 &&
2442 (utf[upos + 2] & 0xc0) == 0x80) {
2443 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2444 c = ((c & 0x07) << 18);
2445 c |= ((utf[upos++] & 0x3f) << 12);
2446 c |= ((utf[upos++] & 0x3f) << 6);
2447 c |= (utf[upos++] & 0x3f);
2449 wcs[wpos++] = 0xd800 | (c >> 10);
2450 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2451 } else if (c >= 0xa0) {
2452 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2455 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2456 static const char *hex = "0123456789abcdef";
2457 wcs[wpos++] = hex[c >> 4];
2459 wcs[wpos++] = hex[c & 0x0f];
2466 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2468 if (!wcs || !utf || utflen < 1) {
2472 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2479 static void setup_windows_environment(void)
2481 char *tmp = getenv("TMPDIR");
2483 /* on Windows it is TMP and TEMP */
2485 if (!(tmp = getenv("TMP")))
2486 tmp = getenv("TEMP");
2488 setenv("TMPDIR", tmp, 1);
2489 tmp = getenv("TMPDIR");
2495 * Convert all dir separators to forward slashes,
2496 * to help shell commands called from the Git
2497 * executable (by not mistaking the dir separators
2498 * for escape characters).
2500 convert_slashes(tmp);
2503 /* simulate TERM to enable auto-color (see color.c) */
2504 if (!getenv("TERM"))
2505 setenv("TERM", "cygwin", 1);
2507 /* calculate HOME if not set */
2508 if (!getenv("HOME")) {
2510 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2511 * location, thus also check if the path exists (i.e. is not
2514 if ((tmp = getenv("HOMEDRIVE"))) {
2515 struct strbuf buf = STRBUF_INIT;
2516 strbuf_addstr(&buf, tmp);
2517 if ((tmp = getenv("HOMEPATH"))) {
2518 strbuf_addstr(&buf, tmp);
2519 if (is_directory(buf.buf))
2520 setenv("HOME", buf.buf, 1);
2522 tmp = NULL; /* use $USERPROFILE */
2524 strbuf_release(&buf);
2526 /* use $USERPROFILE if the home share is not available */
2527 if (!tmp && (tmp = getenv("USERPROFILE")))
2528 setenv("HOME", tmp, 1);
2532 int is_valid_win32_path(const char *path)
2534 int preceding_space_or_period = 0, i = 0, periods = 0;
2539 skip_dos_drive_prefix((char **)&path);
2545 case '/': case '\\':
2546 /* cannot end in ` ` or `.`, except for `.` and `..` */
2547 if (preceding_space_or_period &&
2548 (i != periods || periods > 2))
2553 i = periods = preceding_space_or_period = 0;
2559 preceding_space_or_period = 1;
2562 case ':': /* DOS drive prefix was already skipped */
2563 case '<': case '>': case '"': case '|': case '?': case '*':
2564 /* illegal character */
2567 if (c > '\0' && c < '\x20')
2568 /* illegal character */
2571 preceding_space_or_period = 0;
2576 #if !defined(_MSC_VER)
2578 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2579 * mingw startup code, see init.c in mingw runtime).
2584 static NORETURN void die_startup(void)
2586 fputs("fatal: not enough memory for initialization", stderr);
2590 static void *malloc_startup(size_t size)
2592 void *result = malloc(size);
2598 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2600 len = xwcstoutf(buffer, wcs, len) + 1;
2601 return memcpy(malloc_startup(len), buffer, len);
2604 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2605 DWORD desired_access, DWORD flags)
2607 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2608 wchar_t buf[MAX_PATH];
2609 DWORD max = ARRAY_SIZE(buf);
2611 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2613 if (!ret || ret >= max)
2616 /* make sure this does not leak into child processes */
2617 SetEnvironmentVariableW(key, NULL);
2618 if (!wcscmp(buf, L"off")) {
2620 handle = GetStdHandle(std_id);
2621 if (handle != INVALID_HANDLE_VALUE)
2622 CloseHandle(handle);
2625 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2626 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2627 if (handle == INVALID_HANDLE_VALUE) {
2629 handle = GetStdHandle(std_id);
2630 if (handle != INVALID_HANDLE_VALUE)
2631 CloseHandle(handle);
2633 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2634 SetStdHandle(std_id, handle);
2636 /* do *not* close the new_fd: that would close stdout */
2640 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2642 if (handle != INVALID_HANDLE_VALUE) {
2643 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2644 SetStdHandle(std_id, handle);
2650 static void maybe_redirect_std_handles(void)
2652 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2653 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2654 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2655 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2656 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2657 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2667 * We implement wmain() and compile with -municode, which would
2668 * normally ignore main(), but we call the latter from the former
2669 * so that we can handle non-ASCII command-line parameters
2672 * To be more compatible with the core git code, we convert
2673 * argv into UTF8 and pass them directly to main().
2675 int wmain(int argc, const wchar_t **wargv)
2677 int i, maxlen, exit_status;
2678 char *buffer, **save;
2681 trace2_initialize_clock();
2685 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2688 #ifdef USE_MSVC_CRTDBG
2689 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2693 maybe_redirect_std_handles();
2695 /* determine size of argv and environ conversion buffer */
2696 maxlen = wcslen(wargv[0]);
2697 for (i = 1; i < argc; i++)
2698 maxlen = max(maxlen, wcslen(wargv[i]));
2700 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2701 maxlen = 3 * maxlen + 1;
2702 buffer = malloc_startup(maxlen);
2705 * Create a UTF-8 version of w_argv. Also create a "save" copy
2706 * to remember all the string pointers because parse_options()
2707 * will remove claimed items from the argv that we pass down.
2709 ALLOC_ARRAY(argv, argc + 1);
2710 ALLOC_ARRAY(save, argc + 1);
2711 for (i = 0; i < argc; i++)
2712 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2713 argv[i] = save[i] = NULL;
2716 /* fix Windows specific environment settings */
2717 setup_windows_environment();
2719 unset_environment_variables = xstrdup("PERL5LIB");
2721 /* initialize critical section for waitpid pinfo_t list */
2722 InitializeCriticalSection(&pinfo_cs);
2724 /* set up default file mode and file modes for stdin/out/err */
2726 _setmode(_fileno(stdin), _O_BINARY);
2727 _setmode(_fileno(stdout), _O_BINARY);
2728 _setmode(_fileno(stderr), _O_BINARY);
2730 /* initialize Unicode console */
2733 /* invoke the real main() using our utf8 version of argv. */
2734 exit_status = main(argc, argv);
2736 for (i = 0; i < argc; i++)
2744 int uname(struct utsname *buf)
2746 unsigned v = (unsigned)GetVersion();
2747 memset(buf, 0, sizeof(*buf));
2748 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2749 xsnprintf(buf->release, sizeof(buf->release),
2750 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2751 /* assuming NT variants only.. */
2752 xsnprintf(buf->version, sizeof(buf->version),
2753 "%u", (v >> 16) & 0x7fff);