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 void open_in_gdb(void)
18 static struct child_process cp = CHILD_PROCESS_INIT;
21 argv_array_pushl(&cp.args, "mintty", "gdb", NULL);
22 argv_array_pushf(&cp.args, "--pid=%d", getpid());
24 if (start_command(&cp) < 0)
25 die_errno("Could not start gdb");
29 int err_win_to_posix(DWORD winerr)
33 case ERROR_ACCESS_DENIED: error = EACCES; break;
34 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
35 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
36 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
37 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
38 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
39 case ERROR_BAD_COMMAND: error = EIO; break;
40 case ERROR_BAD_DEVICE: error = ENODEV; break;
41 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
42 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
43 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
44 case ERROR_BAD_LENGTH: error = EINVAL; break;
45 case ERROR_BAD_PATHNAME: error = ENOENT; break;
46 case ERROR_BAD_PIPE: error = EPIPE; break;
47 case ERROR_BAD_UNIT: error = ENODEV; break;
48 case ERROR_BAD_USERNAME: error = EINVAL; break;
49 case ERROR_BROKEN_PIPE: error = EPIPE; break;
50 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
51 case ERROR_BUSY: error = EBUSY; break;
52 case ERROR_BUSY_DRIVE: error = EBUSY; break;
53 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
54 case ERROR_CANNOT_MAKE: error = EACCES; break;
55 case ERROR_CANTOPEN: error = EIO; break;
56 case ERROR_CANTREAD: error = EIO; break;
57 case ERROR_CANTWRITE: error = EIO; break;
58 case ERROR_CRC: error = EIO; break;
59 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
60 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
61 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
62 case ERROR_DIRECTORY: error = EINVAL; break;
63 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
64 case ERROR_DISK_CHANGE: error = EIO; break;
65 case ERROR_DISK_FULL: error = ENOSPC; break;
66 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
67 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
68 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
69 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
70 case ERROR_FILE_EXISTS: error = EEXIST; break;
71 case ERROR_FILE_INVALID: error = ENODEV; break;
72 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
73 case ERROR_GEN_FAILURE: error = EIO; break;
74 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
75 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
76 case ERROR_INVALID_ACCESS: error = EACCES; break;
77 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
78 case ERROR_INVALID_BLOCK: error = EFAULT; break;
79 case ERROR_INVALID_DATA: error = EINVAL; break;
80 case ERROR_INVALID_DRIVE: error = ENODEV; break;
81 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
82 case ERROR_INVALID_FLAGS: error = EINVAL; break;
83 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
84 case ERROR_INVALID_HANDLE: error = EBADF; break;
85 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
86 case ERROR_INVALID_NAME: error = EINVAL; break;
87 case ERROR_INVALID_OWNER: error = EINVAL; break;
88 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
89 case ERROR_INVALID_PASSWORD: error = EPERM; break;
90 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
91 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
92 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
93 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
94 case ERROR_IO_DEVICE: error = EIO; break;
95 case ERROR_IO_INCOMPLETE: error = EINTR; break;
96 case ERROR_LOCKED: error = EBUSY; break;
97 case ERROR_LOCK_VIOLATION: error = EACCES; break;
98 case ERROR_LOGON_FAILURE: error = EACCES; break;
99 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
100 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
101 case ERROR_MORE_DATA: error = EPIPE; break;
102 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
103 case ERROR_NOACCESS: error = EFAULT; break;
104 case ERROR_NONE_MAPPED: error = EINVAL; break;
105 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
106 case ERROR_NOT_READY: error = EAGAIN; break;
107 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
108 case ERROR_NO_DATA: error = EPIPE; break;
109 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
110 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
111 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
112 case ERROR_OPEN_FAILED: error = EIO; break;
113 case ERROR_OPEN_FILES: error = EBUSY; break;
114 case ERROR_OPERATION_ABORTED: error = EINTR; break;
115 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
116 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
117 case ERROR_PATH_BUSY: error = EBUSY; break;
118 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
119 case ERROR_PIPE_BUSY: error = EBUSY; break;
120 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
121 case ERROR_PIPE_LISTENING: error = EPIPE; break;
122 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
123 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
124 case ERROR_READ_FAULT: error = EIO; break;
125 case ERROR_SEEK: error = EIO; break;
126 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
127 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
128 case ERROR_SHARING_VIOLATION: error = EACCES; break;
129 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
130 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
131 case ERROR_SWAPERROR: error = ENOENT; break;
132 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
133 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
134 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
135 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
136 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
137 case ERROR_WRITE_FAULT: error = EIO; break;
138 case ERROR_WRITE_PROTECT: error = EROFS; break;
143 static inline int is_file_in_use_error(DWORD errcode)
146 case ERROR_SHARING_VIOLATION:
147 case ERROR_ACCESS_DENIED:
154 static int read_yes_no_answer(void)
158 if (fgets(answer, sizeof(answer), stdin)) {
159 size_t answer_len = strlen(answer);
160 int got_full_line = 0, c;
162 /* remove the newline */
163 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
164 answer[answer_len-2] = '\0';
166 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
167 answer[answer_len-1] = '\0';
170 /* flush the buffer in case we did not get the full line */
172 while ((c = getchar()) != EOF && c != '\n')
175 /* we could not read, return the
176 * default answer which is no */
179 if (tolower(answer[0]) == 'y' && !answer[1])
181 if (!strncasecmp(answer, "yes", sizeof(answer)))
183 if (tolower(answer[0]) == 'n' && !answer[1])
185 if (!strncasecmp(answer, "no", sizeof(answer)))
188 /* did not find an answer we understand */
192 static int ask_yes_no_if_possible(const char *format, ...)
195 const char *retry_hook[] = { NULL, NULL, NULL };
198 va_start(args, format);
199 vsnprintf(question, sizeof(question), format, args);
202 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
203 retry_hook[1] = question;
204 return !run_command_v_opt(retry_hook, 0);
207 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
212 fprintf(stderr, "%s (y/n) ", question);
214 if ((answer = read_yes_no_answer()) >= 0)
217 fprintf(stderr, "Sorry, I did not understand your answer. "
218 "Please type 'y' or 'n'\n");
223 enum hide_dotfiles_type {
224 HIDE_DOTFILES_FALSE = 0,
226 HIDE_DOTFILES_DOTGITONLY
229 static int core_restrict_inherited_handles = -1;
230 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
231 static char *unset_environment_variables;
233 int mingw_core_config(const char *var, const char *value, void *cb)
235 if (!strcmp(var, "core.hidedotfiles")) {
236 if (value && !strcasecmp(value, "dotgitonly"))
237 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
239 hide_dotfiles = git_config_bool(var, value);
243 if (!strcmp(var, "core.unsetenvvars")) {
244 free(unset_environment_variables);
245 unset_environment_variables = xstrdup(value);
249 if (!strcmp(var, "core.restrictinheritedhandles")) {
250 if (value && !strcasecmp(value, "auto"))
251 core_restrict_inherited_handles = -1;
253 core_restrict_inherited_handles =
254 git_config_bool(var, value);
261 /* Normalizes NT paths as returned by some low-level APIs. */
262 static wchar_t *normalize_ntpath(wchar_t *wbuf)
265 /* fix absolute path prefixes */
266 if (wbuf[0] == '\\') {
267 /* strip NT namespace prefixes */
268 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
269 !wcsncmp(wbuf, L"\\\\?\\", 4))
271 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
273 /* replace remaining '...UNC\' with '\\' */
274 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
279 /* convert backslashes to slashes */
280 for (i = 0; wbuf[i]; i++)
286 int mingw_unlink(const char *pathname)
289 wchar_t wpathname[MAX_PATH];
290 if (xutftowcs_path(wpathname, pathname) < 0)
293 /* read-only files cannot be removed */
294 _wchmod(wpathname, 0666);
295 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
296 if (!is_file_in_use_error(GetLastError()))
299 * We assume that some other process had the source or
300 * destination file open at the wrong moment and retry.
301 * In order to give the other process a higher chance to
302 * complete its operation, we give up our time slice now.
303 * If we have to retry again, we do sleep a bit.
308 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
309 ask_yes_no_if_possible("Unlink of file '%s' failed. "
310 "Should I try again?", pathname))
311 ret = _wunlink(wpathname);
315 static int is_dir_empty(const wchar_t *wpath)
317 WIN32_FIND_DATAW findbuf;
319 wchar_t wbuf[MAX_PATH + 2];
321 wcscat(wbuf, L"\\*");
322 handle = FindFirstFileW(wbuf, &findbuf);
323 if (handle == INVALID_HANDLE_VALUE)
324 return GetLastError() == ERROR_NO_MORE_FILES;
326 while (!wcscmp(findbuf.cFileName, L".") ||
327 !wcscmp(findbuf.cFileName, L".."))
328 if (!FindNextFileW(handle, &findbuf)) {
329 DWORD err = GetLastError();
331 return err == ERROR_NO_MORE_FILES;
337 int mingw_rmdir(const char *pathname)
340 wchar_t wpathname[MAX_PATH];
341 if (xutftowcs_path(wpathname, pathname) < 0)
344 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
345 if (!is_file_in_use_error(GetLastError()))
346 errno = err_win_to_posix(GetLastError());
349 if (!is_dir_empty(wpathname)) {
354 * We assume that some other process had the source or
355 * destination file open at the wrong moment and retry.
356 * In order to give the other process a higher chance to
357 * complete its operation, we give up our time slice now.
358 * If we have to retry again, we do sleep a bit.
363 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
364 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
365 "Should I try again?", pathname))
366 ret = _wrmdir(wpathname);
368 invalidate_lstat_cache();
372 static inline int needs_hiding(const char *path)
374 const char *basename;
376 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
379 /* We cannot use basename(), as it would remove trailing slashes */
380 win32_skip_dos_drive_prefix((char **)&path);
384 for (basename = path; *path; path++)
385 if (is_dir_sep(*path)) {
388 } while (is_dir_sep(*path));
389 /* ignore trailing slashes */
396 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
397 return *basename == '.';
399 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
400 return !strncasecmp(".git", basename, 4) &&
401 (!basename[4] || is_dir_sep(basename[4]));
404 static int set_hidden_flag(const wchar_t *path, int set)
406 DWORD original = GetFileAttributesW(path), modified;
408 modified = original | FILE_ATTRIBUTE_HIDDEN;
410 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
411 if (original == modified || SetFileAttributesW(path, modified))
413 errno = err_win_to_posix(GetLastError());
417 int mingw_mkdir(const char *path, int mode)
420 wchar_t wpath[MAX_PATH];
422 if (!is_valid_win32_path(path, 0)) {
427 if (xutftowcs_path(wpath, path) < 0)
429 ret = _wmkdir(wpath);
430 if (!ret && needs_hiding(path))
431 return set_hidden_flag(wpath, 1);
436 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
437 * is documented in [1] as opening a writable file handle in append mode.
438 * (It is believed that) this is atomic since it is maintained by the
439 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
441 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
443 * This trick does not appear to work for named pipes. Instead it creates
444 * a named pipe client handle that cannot be written to. Callers should
445 * just use the regular _wopen() for them. (And since client handle gets
446 * bound to a unique server handle, it isn't really an issue.)
448 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
452 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
454 /* only these flags are supported */
455 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
456 return errno = ENOSYS, -1;
459 * FILE_SHARE_WRITE is required to permit child processes
460 * to append to the file.
462 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
463 FILE_SHARE_WRITE | FILE_SHARE_READ,
464 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
465 if (handle == INVALID_HANDLE_VALUE)
466 return errno = err_win_to_posix(GetLastError()), -1;
469 * No O_APPEND here, because the CRT uses it only to reset the
470 * file pointer to EOF before each write(); but that is not
471 * necessary (and may lead to races) for a file created with
474 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
481 * Does the pathname map to the local named pipe filesystem?
482 * That is, does it have a "//./pipe/" prefix?
484 static int is_local_named_pipe_path(const char *filename)
486 return (is_dir_sep(filename[0]) &&
487 is_dir_sep(filename[1]) &&
488 filename[2] == '.' &&
489 is_dir_sep(filename[3]) &&
490 !strncasecmp(filename+4, "pipe", 4) &&
491 is_dir_sep(filename[8]) &&
495 int mingw_open (const char *filename, int oflags, ...)
497 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
500 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
501 wchar_t wfilename[MAX_PATH];
504 va_start(args, oflags);
505 mode = va_arg(args, int);
508 if (!is_valid_win32_path(filename, !create)) {
509 errno = create ? EINVAL : ENOENT;
513 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
514 open_fn = mingw_open_append;
518 if (filename && !strcmp(filename, "/dev/null"))
519 wcscpy(wfilename, L"nul");
520 else if (xutftowcs_path(wfilename, filename) < 0)
523 fd = open_fn(wfilename, oflags, mode);
525 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
526 DWORD attrs = GetFileAttributesW(wfilename);
527 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
530 if ((oflags & O_CREAT) && needs_hiding(filename)) {
532 * Internally, _wopen() uses the CreateFile() API which errors
533 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
534 * specified and an already existing file's attributes do not
535 * match *exactly*. As there is no mode or flag we can set that
536 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
537 * again *without* the O_CREAT flag (that corresponds to the
538 * CREATE_ALWAYS flag of CreateFile()).
540 if (fd < 0 && errno == EACCES)
541 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
542 if (fd >= 0 && set_hidden_flag(wfilename, 1))
543 warning("could not mark '%s' as hidden.", filename);
548 static BOOL WINAPI ctrl_ignore(DWORD type)
554 int mingw_fgetc(FILE *stream)
557 if (!isatty(_fileno(stream)))
558 return fgetc(stream);
560 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
563 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
566 /* Ctrl+C was pressed, simulate SIGINT and retry */
569 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
574 FILE *mingw_fopen (const char *filename, const char *otype)
576 int hide = needs_hiding(filename);
578 wchar_t wfilename[MAX_PATH], wotype[4];
579 if (filename && !strcmp(filename, "/dev/null"))
580 wcscpy(wfilename, L"nul");
581 else if (!is_valid_win32_path(filename, 1)) {
582 int create = otype && strchr(otype, 'w');
583 errno = create ? EINVAL : ENOENT;
585 } else if (xutftowcs_path(wfilename, filename) < 0)
588 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
591 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
592 error("could not unhide %s", filename);
595 file = _wfopen(wfilename, wotype);
596 if (!file && GetLastError() == ERROR_INVALID_NAME)
598 if (file && hide && set_hidden_flag(wfilename, 1))
599 warning("could not mark '%s' as hidden.", filename);
603 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
605 int hide = needs_hiding(filename);
607 wchar_t wfilename[MAX_PATH], wotype[4];
608 if (filename && !strcmp(filename, "/dev/null"))
609 wcscpy(wfilename, L"nul");
610 else if (!is_valid_win32_path(filename, 1)) {
611 int create = otype && strchr(otype, 'w');
612 errno = create ? EINVAL : ENOENT;
614 } else if (xutftowcs_path(wfilename, filename) < 0)
617 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
620 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
621 error("could not unhide %s", filename);
624 file = _wfreopen(wfilename, wotype, stream);
625 if (file && hide && set_hidden_flag(wfilename, 1))
626 warning("could not mark '%s' as hidden.", filename);
631 int mingw_fflush(FILE *stream)
633 int ret = fflush(stream);
636 * write() is used behind the scenes of stdio output functions.
637 * Since git code does not check for errors after each stdio write
638 * operation, it can happen that write() is called by a later
639 * stdio function even if an earlier write() call failed. In the
640 * case of a pipe whose readable end was closed, only the first
641 * call to write() reports EPIPE on Windows. Subsequent write()
642 * calls report EINVAL. It is impossible to notice whether this
643 * fflush invocation triggered such a case, therefore, we have to
644 * catch all EINVAL errors whole-sale.
646 if (ret && errno == EINVAL)
653 ssize_t mingw_write(int fd, const void *buf, size_t len)
655 ssize_t result = write(fd, buf, len);
657 if (result < 0 && errno == EINVAL && buf) {
658 /* check if fd is a pipe */
659 HANDLE h = (HANDLE) _get_osfhandle(fd);
660 if (GetFileType(h) == FILE_TYPE_PIPE)
669 int mingw_access(const char *filename, int mode)
671 wchar_t wfilename[MAX_PATH];
672 if (xutftowcs_path(wfilename, filename) < 0)
674 /* X_OK is not supported by the MSVCRT version */
675 return _waccess(wfilename, mode & ~X_OK);
678 int mingw_chdir(const char *dirname)
680 wchar_t wdirname[MAX_PATH];
681 if (xutftowcs_path(wdirname, dirname) < 0)
683 return _wchdir(wdirname);
686 int mingw_chmod(const char *filename, int mode)
688 wchar_t wfilename[MAX_PATH];
689 if (xutftowcs_path(wfilename, filename) < 0)
691 return _wchmod(wfilename, mode);
695 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
696 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
698 static inline long long filetime_to_hnsec(const FILETIME *ft)
700 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
701 /* Windows to Unix Epoch conversion */
702 return winTime - 116444736000000000LL;
705 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
707 long long hnsec = filetime_to_hnsec(ft);
708 ts->tv_sec = (time_t)(hnsec / 10000000);
709 ts->tv_nsec = (hnsec % 10000000) * 100;
713 * Verifies that safe_create_leading_directories() would succeed.
715 static int has_valid_directory_prefix(wchar_t *wfilename)
717 int n = wcslen(wfilename);
720 wchar_t c = wfilename[--n];
726 wfilename[n] = L'\0';
727 attributes = GetFileAttributesW(wfilename);
729 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
730 attributes == FILE_ATTRIBUTE_DEVICE)
732 if (attributes == INVALID_FILE_ATTRIBUTES)
733 switch (GetLastError()) {
734 case ERROR_PATH_NOT_FOUND:
736 case ERROR_FILE_NOT_FOUND:
737 /* This implies parent directory exists. */
745 /* We keep the do_lstat code in a separate function to avoid recursion.
746 * When a path ends with a slash, the stat will fail with ENOENT. In
747 * this case, we strip the trailing slashes and stat again.
749 * If follow is true then act like stat() and report on the link
750 * target. Otherwise report on the link itself.
752 static int do_lstat(int follow, const char *file_name, struct stat *buf)
754 WIN32_FILE_ATTRIBUTE_DATA fdata;
755 wchar_t wfilename[MAX_PATH];
756 if (xutftowcs_path(wfilename, file_name) < 0)
759 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
764 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
765 buf->st_size = fdata.nFileSizeLow |
766 (((off_t)fdata.nFileSizeHigh)<<32);
767 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
768 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
769 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
770 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
771 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
772 WIN32_FIND_DATAW findbuf;
773 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
774 if (handle != INVALID_HANDLE_VALUE) {
775 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
776 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
778 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
779 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
781 buf->st_mode = S_IFLNK;
783 buf->st_mode |= S_IREAD;
784 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
785 buf->st_mode |= S_IWRITE;
792 switch (GetLastError()) {
793 case ERROR_ACCESS_DENIED:
794 case ERROR_SHARING_VIOLATION:
795 case ERROR_LOCK_VIOLATION:
796 case ERROR_SHARING_BUFFER_EXCEEDED:
799 case ERROR_BUFFER_OVERFLOW:
800 errno = ENAMETOOLONG;
802 case ERROR_NOT_ENOUGH_MEMORY:
805 case ERROR_PATH_NOT_FOUND:
806 if (!has_valid_directory_prefix(wfilename)) {
818 /* We provide our own lstat/fstat functions, since the provided
819 * lstat/fstat functions are so slow. These stat functions are
820 * tailored for Git's usage (read: fast), and are not meant to be
821 * complete. Note that Git stat()s are redirected to mingw_lstat()
822 * too, since Windows doesn't really handle symlinks that well.
824 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
827 char alt_name[PATH_MAX];
829 if (!do_lstat(follow, file_name, buf))
832 /* if file_name ended in a '/', Windows returned ENOENT;
833 * try again without trailing slashes
838 namelen = strlen(file_name);
839 if (namelen && file_name[namelen-1] != '/')
841 while (namelen && file_name[namelen-1] == '/')
843 if (!namelen || namelen >= PATH_MAX)
846 memcpy(alt_name, file_name, namelen);
847 alt_name[namelen] = 0;
848 return do_lstat(follow, alt_name, buf);
851 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
853 BY_HANDLE_FILE_INFORMATION fdata;
855 if (!GetFileInformationByHandle(hnd, &fdata)) {
856 errno = err_win_to_posix(GetLastError());
864 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
865 buf->st_size = fdata.nFileSizeLow |
866 (((off_t)fdata.nFileSizeHigh)<<32);
867 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
868 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
869 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
870 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
874 int mingw_lstat(const char *file_name, struct stat *buf)
876 return do_stat_internal(0, file_name, buf);
878 int mingw_stat(const char *file_name, struct stat *buf)
880 return do_stat_internal(1, file_name, buf);
883 int mingw_fstat(int fd, struct stat *buf)
885 HANDLE fh = (HANDLE)_get_osfhandle(fd);
886 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
890 return get_file_info_by_handle(fh, buf);
894 /* initialize stat fields */
895 memset(buf, 0, sizeof(*buf));
898 if (type == FILE_TYPE_CHAR) {
899 buf->st_mode = _S_IFCHR;
901 buf->st_mode = _S_IFIFO;
902 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
903 buf->st_size = avail;
913 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
915 long long winTime = t * 10000000LL + 116444736000000000LL;
916 ft->dwLowDateTime = winTime;
917 ft->dwHighDateTime = winTime >> 32;
920 int mingw_utime (const char *file_name, const struct utimbuf *times)
925 wchar_t wfilename[MAX_PATH];
926 if (xutftowcs_path(wfilename, file_name) < 0)
929 /* must have write permission */
930 attrs = GetFileAttributesW(wfilename);
931 if (attrs != INVALID_FILE_ATTRIBUTES &&
932 (attrs & FILE_ATTRIBUTE_READONLY)) {
933 /* ignore errors here; open() will report them */
934 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
937 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
943 time_t_to_filetime(times->modtime, &mft);
944 time_t_to_filetime(times->actime, &aft);
946 GetSystemTimeAsFileTime(&mft);
949 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
957 if (attrs != INVALID_FILE_ATTRIBUTES &&
958 (attrs & FILE_ATTRIBUTE_READONLY)) {
959 /* ignore errors again */
960 SetFileAttributesW(wfilename, attrs);
966 size_t mingw_strftime(char *s, size_t max,
967 const char *format, const struct tm *tm)
969 size_t ret = strftime(s, max, format, tm);
971 if (!ret && errno == EINVAL)
972 die("invalid strftime format: '%s'", format);
976 unsigned int sleep (unsigned int seconds)
982 char *mingw_mktemp(char *template)
984 wchar_t wtemplate[MAX_PATH];
985 if (xutftowcs_path(wtemplate, template) < 0)
987 if (!_wmktemp(wtemplate))
989 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
994 int mkstemp(char *template)
996 char *filename = mktemp(template);
997 if (filename == NULL)
999 return open(filename, O_RDWR | O_CREAT, 0600);
1002 int gettimeofday(struct timeval *tv, void *tz)
1007 GetSystemTimeAsFileTime(&ft);
1008 hnsec = filetime_to_hnsec(&ft);
1009 tv->tv_sec = hnsec / 10000000;
1010 tv->tv_usec = (hnsec % 10000000) / 10;
1014 int pipe(int filedes[2])
1018 /* this creates non-inheritable handles */
1019 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1020 errno = err_win_to_posix(GetLastError());
1023 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1024 if (filedes[0] < 0) {
1029 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1030 if (filedes[1] < 0) {
1038 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1040 if (gmtime_s(result, timep) == 0)
1045 struct tm *localtime_r(const time_t *timep, struct tm *result)
1047 if (localtime_s(result, timep) == 0)
1052 char *mingw_getcwd(char *pointer, int len)
1054 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1055 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1057 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1058 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1061 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1062 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1063 HANDLE hnd = CreateFileW(cwd, 0,
1064 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1065 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1066 if (hnd == INVALID_HANDLE_VALUE)
1068 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1070 if (!ret || ret >= ARRAY_SIZE(wpointer))
1072 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1076 if (!ret || ret >= ARRAY_SIZE(wpointer))
1078 if (xwcstoutf(pointer, wpointer, len) < 0)
1080 convert_slashes(pointer);
1085 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1086 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1088 static const char *quote_arg_msvc(const char *arg)
1090 /* count chars to quote */
1092 int force_quotes = 0;
1094 const char *p = arg;
1095 if (!*p) force_quotes = 1;
1097 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1101 else if (*p == '\\') {
1103 while (*p == '\\') {
1108 if (*p == '"' || !*p)
1115 if (!force_quotes && n == 0)
1118 /* insert \ where necessary */
1119 d = q = xmalloc(st_add3(len, n, 3));
1124 else if (*arg == '\\') {
1126 while (*arg == '\\') {
1130 if (*arg == '"' || !*arg) {
1133 /* don't escape the surrounding end quote */
1148 static const char *quote_arg_msys2(const char *arg)
1150 struct strbuf buf = STRBUF_INIT;
1151 const char *p2 = arg, *p;
1153 for (p = arg; *p; p++) {
1154 int ws = isspace(*p);
1155 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1156 *p != '?' && *p != '*' && *p != '~')
1159 strbuf_addch(&buf, '"');
1161 strbuf_add(&buf, p2, p - p2);
1162 if (*p == '\\' || *p == '"')
1163 strbuf_addch(&buf, '\\');
1168 strbuf_addch(&buf, '"');
1172 strbuf_add(&buf, p2, p - p2);
1174 strbuf_addch(&buf, '"');
1175 return strbuf_detach(&buf, 0);
1178 static const char *parse_interpreter(const char *cmd)
1180 static char buf[100];
1184 /* don't even try a .exe */
1186 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1189 fd = open(cmd, O_RDONLY);
1192 n = read(fd, buf, sizeof(buf)-1);
1194 if (n < 4) /* at least '#!/x' and not error */
1197 if (buf[0] != '#' || buf[1] != '!')
1200 p = buf + strcspn(buf, "\r\n");
1205 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1208 if ((opt = strchr(p+1, ' ')))
1214 * exe_only means that we only want to detect .exe files, but not scripts
1215 * (which do not have an extension)
1217 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1218 int isexe, int exe_only)
1220 char path[MAX_PATH];
1221 wchar_t wpath[MAX_PATH];
1222 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1224 if (xutftowcs_path(wpath, path) < 0)
1227 if (!isexe && _waccess(wpath, F_OK) == 0)
1228 return xstrdup(path);
1229 wpath[wcslen(wpath)-4] = '\0';
1230 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1231 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1232 path[strlen(path)-4] = '\0';
1233 return xstrdup(path);
1240 * Determines the absolute path of cmd using the split path in path.
1241 * If cmd contains a slash or backslash, no lookup is performed.
1243 static char *path_lookup(const char *cmd, int exe_only)
1247 int len = strlen(cmd);
1248 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1250 if (strpbrk(cmd, "/\\"))
1251 return xstrdup(cmd);
1253 path = mingw_getenv("PATH");
1258 const char *sep = strchrnul(path, ';');
1259 int dirlen = sep - path;
1261 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1270 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1272 while (*s && *s != c)
1277 /* Compare only keys */
1278 static int wenvcmp(const void *a, const void *b)
1280 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1281 size_t p_len, q_len;
1284 p_len = wcschrnul(p, L'=') - p;
1285 q_len = wcschrnul(q, L'=') - q;
1287 /* If the length differs, include the shorter key's NUL */
1290 else if (p_len > q_len)
1293 return _wcsnicmp(p, q, p_len);
1297 * Build an environment block combining the inherited environment
1298 * merged with the given list of settings.
1300 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1301 * Values of the form "KEY" in deltaenv delete inherited values.
1303 * Multiple entries in deltaenv for the same key are explicitly allowed.
1305 * We return a contiguous block of UNICODE strings with a final trailing
1308 static wchar_t *make_environment_block(char **deltaenv)
1310 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1311 size_t wlen, s, delta_size, size;
1313 wchar_t **array = NULL;
1314 size_t alloc = 0, nr = 0, i;
1316 size = 1; /* for extra NUL at the end */
1318 /* If there is no deltaenv to apply, simply return a copy. */
1319 if (!deltaenv || !*deltaenv) {
1320 for (p = wenv; p && *p; ) {
1321 size_t s = wcslen(p) + 1;
1326 ALLOC_ARRAY(result, size);
1327 COPY_ARRAY(result, wenv, size);
1328 FreeEnvironmentStringsW(wenv);
1333 * If there is a deltaenv, let's accumulate all keys into `array`,
1334 * sort them using the stable git_stable_qsort() and then copy,
1335 * skipping duplicate keys
1337 for (p = wenv; p && *p; ) {
1338 ALLOC_GROW(array, nr + 1, alloc);
1345 /* (over-)assess size needed for wchar version of deltaenv */
1346 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1347 delta_size += strlen(deltaenv[i]) * 2 + 1;
1348 ALLOC_ARRAY(wdeltaenv, delta_size);
1350 /* convert the deltaenv, appending to array */
1351 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1352 ALLOC_GROW(array, nr + 1, alloc);
1353 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1358 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1359 ALLOC_ARRAY(result, size + delta_size);
1361 for (p = result, i = 0; i < nr; i++) {
1362 /* Skip any duplicate keys; last one wins */
1363 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1366 /* Skip "to delete" entry */
1367 if (!wcschr(array[i], L'='))
1370 size = wcslen(array[i]) + 1;
1371 COPY_ARRAY(p, array[i], size);
1378 FreeEnvironmentStringsW(wenv);
1382 static void do_unset_environment_variables(void)
1385 char *p = unset_environment_variables;
1392 char *comma = strchr(p, ',');
1404 struct pinfo_t *next;
1408 static struct pinfo_t *pinfo = NULL;
1409 CRITICAL_SECTION pinfo_cs;
1411 /* Used to match and chomp off path components */
1412 static inline int match_last_path_component(const char *path, size_t *len,
1413 const char *component)
1415 size_t component_len = strlen(component);
1416 if (*len < component_len + 1 ||
1417 !is_dir_sep(path[*len - component_len - 1]) ||
1418 fspathncmp(path + *len - component_len, component, component_len))
1420 *len -= component_len + 1;
1421 /* chomp off repeated dir separators */
1422 while (*len > 0 && is_dir_sep(path[*len - 1]))
1427 static int is_msys2_sh(const char *cmd)
1432 if (!strcmp(cmd, "sh")) {
1433 static int ret = -1;
1439 p = path_lookup(cmd, 0);
1443 size_t len = strlen(p);
1445 ret = match_last_path_component(p, &len, "sh.exe") &&
1446 match_last_path_component(p, &len, "bin") &&
1447 match_last_path_component(p, &len, "usr");
1453 if (ends_with(cmd, "\\sh.exe")) {
1457 sh = path_lookup("sh", 0);
1459 return !fspathcmp(cmd, sh);
1465 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1467 int prepend_cmd, int fhin, int fhout, int fherr)
1469 static int restrict_handle_inheritance = -1;
1471 PROCESS_INFORMATION pi;
1472 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1473 HANDLE stdhandles[3];
1474 DWORD stdhandles_count = 0;
1477 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1478 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1481 const char *(*quote_arg)(const char *arg) =
1482 is_msys2_sh(cmd ? cmd : *argv) ?
1483 quote_arg_msys2 : quote_arg_msvc;
1485 /* Make sure to override previous errors, if any */
1488 if (restrict_handle_inheritance < 0)
1489 restrict_handle_inheritance = core_restrict_inherited_handles;
1491 * The following code to restrict which handles are inherited seems
1492 * to work properly only on Windows 7 and later, so let's disable it
1493 * on Windows Vista and 2008.
1495 if (restrict_handle_inheritance < 0)
1496 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1498 do_unset_environment_variables();
1500 /* Determine whether or not we are associated to a console */
1501 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1502 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1503 FILE_ATTRIBUTE_NORMAL, NULL);
1504 if (cons == INVALID_HANDLE_VALUE) {
1505 /* There is no console associated with this process.
1506 * Since the child is a console process, Windows
1507 * would normally create a console window. But
1508 * since we'll be redirecting std streams, we do
1509 * not need the console.
1510 * It is necessary to use DETACHED_PROCESS
1511 * instead of CREATE_NO_WINDOW to make ssh
1512 * recognize that it has no console.
1514 flags |= DETACHED_PROCESS;
1516 /* There is already a console. If we specified
1517 * DETACHED_PROCESS here, too, Windows would
1518 * disassociate the child from the console.
1519 * The same is true for CREATE_NO_WINDOW.
1524 memset(&si, 0, sizeof(si));
1525 si.StartupInfo.cb = sizeof(si);
1526 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1527 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1528 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1530 /* The list of handles cannot contain duplicates */
1531 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1532 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1533 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1534 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1535 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1536 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1537 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1538 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1539 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1540 if (stdhandles_count)
1541 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1543 if (*argv && !strcmp(cmd, *argv))
1545 else if (xutftowcs_path(wcmd, cmd) < 0)
1547 if (dir && xutftowcs_path(wdir, dir) < 0)
1550 /* concatenate argv, quoting args as we go */
1551 strbuf_init(&args, 0);
1553 char *quoted = (char *)quote_arg(cmd);
1554 strbuf_addstr(&args, quoted);
1558 for (; *argv; argv++) {
1559 char *quoted = (char *)quote_arg(*argv);
1561 strbuf_addch(&args, ' ');
1562 strbuf_addstr(&args, quoted);
1563 if (quoted != *argv)
1567 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1568 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1569 strbuf_release(&args);
1571 wenvblk = make_environment_block(deltaenv);
1573 memset(&pi, 0, sizeof(pi));
1574 if (restrict_handle_inheritance && stdhandles_count &&
1575 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1576 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1577 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1578 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1579 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1580 UpdateProcThreadAttribute(attr_list, 0,
1581 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1583 stdhandles_count * sizeof(HANDLE),
1585 si.lpAttributeList = attr_list;
1586 flags |= EXTENDED_STARTUPINFO_PRESENT;
1589 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1590 stdhandles_count ? TRUE : FALSE,
1591 flags, wenvblk, dir ? wdir : NULL,
1592 &si.StartupInfo, &pi);
1595 * On Windows 2008 R2, it seems that specifying certain types of handles
1596 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1597 * error. Rather than playing finicky and fragile games, let's just try
1598 * to detect this situation and simply try again without restricting any
1599 * handle inheritance. This is still better than failing to create
1602 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1603 DWORD err = GetLastError();
1604 struct strbuf buf = STRBUF_INIT;
1606 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1608 * On Windows 7 and earlier, handles on pipes and character
1609 * devices are inherited automatically, and cannot be
1610 * specified in the thread handle list. Rather than trying
1611 * to catch each and every corner case (and running the
1612 * chance of *still* forgetting a few), let's just fall
1613 * back to creating the process without trying to limit the
1614 * handle inheritance.
1616 !(err == ERROR_INVALID_PARAMETER &&
1617 GetVersion() >> 16 < 9200) &&
1618 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1622 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1624 for (i = 0; i < stdhandles_count; i++) {
1625 HANDLE h = stdhandles[i];
1626 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1627 "handle info (%d) %lx\n", i, h,
1629 GetHandleInformation(h, &fl),
1632 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1633 "at\nhttps://github.com/git-for-windows/"
1634 "git/issues/new\n\n"
1635 "To suppress this warning, please set "
1636 "the environment variable\n\n"
1637 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1640 restrict_handle_inheritance = 0;
1641 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1642 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1643 TRUE, flags, wenvblk, dir ? wdir : NULL,
1644 &si.StartupInfo, &pi);
1646 errno = err_win_to_posix(GetLastError());
1647 if (ret && buf.len) {
1648 warning("failed to restrict file handles (%ld)\n\n%s",
1651 strbuf_release(&buf);
1653 errno = err_win_to_posix(GetLastError());
1655 if (si.lpAttributeList)
1656 DeleteProcThreadAttributeList(si.lpAttributeList);
1658 HeapFree(GetProcessHeap(), 0, attr_list);
1666 CloseHandle(pi.hThread);
1669 * The process ID is the human-readable identifier of the process
1670 * that we want to present in log and error messages. The handle
1671 * is not useful for this purpose. But we cannot close it, either,
1672 * because it is not possible to turn a process ID into a process
1673 * handle after the process terminated.
1674 * Keep the handle in a list for waitpid.
1676 EnterCriticalSection(&pinfo_cs);
1678 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1679 info->pid = pi.dwProcessId;
1680 info->proc = pi.hProcess;
1684 LeaveCriticalSection(&pinfo_cs);
1686 return (pid_t)pi.dwProcessId;
1689 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1691 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1694 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1696 int fhin, int fhout, int fherr)
1699 char *prog = path_lookup(cmd, 0);
1706 const char *interpr = parse_interpreter(prog);
1709 const char *argv0 = argv[0];
1710 char *iprog = path_lookup(interpr, 1);
1717 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1718 fhin, fhout, fherr);
1724 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1725 fhin, fhout, fherr);
1731 static int try_shell_exec(const char *cmd, char *const *argv)
1733 const char *interpr = parse_interpreter(cmd);
1739 prog = path_lookup(interpr, 1);
1747 while (argv[argc]) argc++;
1748 ALLOC_ARRAY(argv2, argc + 1);
1749 argv2[0] = (char *)cmd; /* full path to the script file */
1750 COPY_ARRAY(&argv2[1], &argv[1], argc);
1751 exec_id = trace2_exec(prog, argv2);
1752 pid = mingw_spawnv(prog, argv2, 1);
1755 if (waitpid(pid, &status, 0) < 0)
1757 trace2_exec_result(exec_id, status);
1760 trace2_exec_result(exec_id, -1);
1761 pid = 1; /* indicate that we tried but failed */
1768 int mingw_execv(const char *cmd, char *const *argv)
1770 /* check if git_command is a shell script */
1771 if (!try_shell_exec(cmd, argv)) {
1775 exec_id = trace2_exec(cmd, (const char **)argv);
1776 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1778 trace2_exec_result(exec_id, -1);
1781 if (waitpid(pid, &status, 0) < 0)
1783 trace2_exec_result(exec_id, status);
1789 int mingw_execvp(const char *cmd, char *const *argv)
1791 char *prog = path_lookup(cmd, 0);
1794 mingw_execv(prog, argv);
1802 int mingw_kill(pid_t pid, int sig)
1804 if (pid > 0 && sig == SIGTERM) {
1805 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1807 if (TerminateProcess(h, -1)) {
1812 errno = err_win_to_posix(GetLastError());
1815 } else if (pid > 0 && sig == 0) {
1816 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1828 * UTF-8 versions of getenv(), putenv() and unsetenv().
1829 * Internally, they use the CRT's stock UNICODE routines
1830 * to avoid data loss.
1832 char *mingw_getenv(const char *name)
1834 #define GETENV_MAX_RETAIN 64
1835 static char *values[GETENV_MAX_RETAIN];
1836 static int value_counter;
1837 int len_key, len_value;
1840 wchar_t w_value[32768];
1842 if (!name || !*name)
1845 len_key = strlen(name) + 1;
1846 /* We cannot use xcalloc() here because that uses getenv() itself */
1847 w_key = calloc(len_key, sizeof(wchar_t));
1849 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1850 xutftowcs(w_key, name, len_key);
1851 /* GetEnvironmentVariableW() only sets the last error upon failure */
1852 SetLastError(ERROR_SUCCESS);
1853 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1854 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1860 len_value = len_value * 3 + 1;
1861 /* We cannot use xcalloc() here because that uses getenv() itself */
1862 value = calloc(len_value, sizeof(char));
1864 die("Out of memory, (tried to allocate %u bytes)", len_value);
1865 xwcstoutf(value, w_value, len_value);
1868 * We return `value` which is an allocated value and the caller is NOT
1869 * expecting to have to free it, so we keep a round-robin array,
1870 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1872 free(values[value_counter]);
1873 values[value_counter++] = value;
1874 if (value_counter >= ARRAY_SIZE(values))
1880 int mingw_putenv(const char *namevalue)
1883 wchar_t *wide, *equal;
1886 if (!namevalue || !*namevalue)
1889 size = strlen(namevalue) * 2 + 1;
1890 wide = calloc(size, sizeof(wchar_t));
1892 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1893 xutftowcs(wide, namevalue, size);
1894 equal = wcschr(wide, L'=');
1896 result = SetEnvironmentVariableW(wide, NULL);
1899 result = SetEnvironmentVariableW(wide, equal + 1);
1904 errno = err_win_to_posix(GetLastError());
1906 return result ? 0 : -1;
1909 static void ensure_socket_initialization(void)
1912 static int initialized = 0;
1917 if (WSAStartup(MAKEWORD(2,2), &wsa))
1918 die("unable to initialize winsock subsystem, error %d",
1921 atexit((void(*)(void)) WSACleanup);
1926 int mingw_gethostname(char *name, int namelen)
1928 ensure_socket_initialization();
1929 return gethostname(name, namelen);
1932 #undef gethostbyname
1933 struct hostent *mingw_gethostbyname(const char *host)
1935 ensure_socket_initialization();
1936 return gethostbyname(host);
1940 int mingw_getaddrinfo(const char *node, const char *service,
1941 const struct addrinfo *hints, struct addrinfo **res)
1943 ensure_socket_initialization();
1944 return getaddrinfo(node, service, hints, res);
1947 int mingw_socket(int domain, int type, int protocol)
1952 ensure_socket_initialization();
1953 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1954 if (s == INVALID_SOCKET) {
1956 * WSAGetLastError() values are regular BSD error codes
1957 * biased by WSABASEERR.
1958 * However, strerror() does not know about networking
1959 * specific errors, which are values beginning at 38 or so.
1960 * Therefore, we choose to leave the biased error code
1961 * in errno so that _if_ someone looks up the code somewhere,
1962 * then it is at least the number that are usually listed.
1964 errno = WSAGetLastError();
1967 /* convert into a file descriptor */
1968 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1970 return error("unable to make a socket file descriptor: %s",
1977 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1979 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1980 return connect(s, sa, sz);
1984 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1986 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1987 return bind(s, sa, sz);
1991 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1993 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1994 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1998 int mingw_shutdown(int sockfd, int how)
2000 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2001 return shutdown(s, how);
2005 int mingw_listen(int sockfd, int backlog)
2007 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2008 return listen(s, backlog);
2012 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2016 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2017 SOCKET s2 = accept(s1, sa, sz);
2019 /* convert into a file descriptor */
2020 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2023 return error("unable to make a socket file descriptor: %s",
2030 int mingw_rename(const char *pold, const char *pnew)
2034 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2035 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2039 * Try native rename() first to get errno right.
2040 * It is based on MoveFile(), which cannot overwrite existing files.
2042 if (!_wrename(wpold, wpnew))
2044 if (errno != EEXIST)
2047 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2049 /* TODO: translate more errors */
2050 gle = GetLastError();
2051 if (gle == ERROR_ACCESS_DENIED &&
2052 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2053 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2054 DWORD attrsold = GetFileAttributesW(wpold);
2055 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2056 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2058 else if (!_wrmdir(wpnew))
2062 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2063 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2064 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2066 gle = GetLastError();
2067 /* revert file attributes on failure */
2068 SetFileAttributesW(wpnew, attrs);
2071 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2073 * We assume that some other process had the source or
2074 * destination file open at the wrong moment and retry.
2075 * In order to give the other process a higher chance to
2076 * complete its operation, we give up our time slice now.
2077 * If we have to retry again, we do sleep a bit.
2079 Sleep(delay[tries]);
2083 if (gle == ERROR_ACCESS_DENIED &&
2084 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2085 "Should I try again?", pold, pnew))
2093 * Note that this doesn't return the actual pagesize, but
2094 * the allocation granularity. If future Windows specific git code
2095 * needs the real getpagesize function, we need to find another solution.
2097 int mingw_getpagesize(void)
2101 return si.dwAllocationGranularity;
2104 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2105 enum EXTENDED_NAME_FORMAT {
2107 NameUserPrincipal = 8
2110 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2112 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2113 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2114 static wchar_t wbuffer[1024];
2117 if (!INIT_PROC_ADDR(GetUserNameExW))
2120 len = ARRAY_SIZE(wbuffer);
2121 if (GetUserNameExW(type, wbuffer, &len)) {
2122 char *converted = xmalloc((len *= 3));
2123 if (xwcstoutf(converted, wbuffer, len) >= 0)
2131 char *mingw_query_user_email(void)
2133 return get_extended_user_info(NameUserPrincipal);
2136 struct passwd *getpwuid(int uid)
2138 static unsigned initialized;
2139 static char user_name[100];
2140 static struct passwd *p;
2147 len = ARRAY_SIZE(buf);
2148 if (!GetUserNameW(buf, &len)) {
2153 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2158 p = xmalloc(sizeof(*p));
2159 p->pw_name = user_name;
2160 p->pw_gecos = get_extended_user_info(NameDisplay);
2162 p->pw_gecos = "unknown";
2169 static HANDLE timer_event;
2170 static HANDLE timer_thread;
2171 static int timer_interval;
2172 static int one_shot;
2173 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2175 /* The timer works like this:
2176 * The thread, ticktack(), is a trivial routine that most of the time
2177 * only waits to receive the signal to terminate. The main thread tells
2178 * the thread to terminate by setting the timer_event to the signalled
2180 * But ticktack() interrupts the wait state after the timer's interval
2181 * length to call the signal handler.
2184 static unsigned __stdcall ticktack(void *dummy)
2186 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2187 mingw_raise(SIGALRM);
2194 static int start_timer_thread(void)
2196 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2198 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2200 return errno = ENOMEM,
2201 error("cannot start timer thread");
2203 return errno = ENOMEM,
2204 error("cannot allocate resources for timer");
2208 static void stop_timer_thread(void)
2211 SetEvent(timer_event); /* tell thread to terminate */
2213 int rc = WaitForSingleObject(timer_thread, 10000);
2214 if (rc == WAIT_TIMEOUT)
2215 error("timer thread did not terminate timely");
2216 else if (rc != WAIT_OBJECT_0)
2217 error("waiting for timer thread failed: %lu",
2219 CloseHandle(timer_thread);
2222 CloseHandle(timer_event);
2224 timer_thread = NULL;
2227 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2229 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2232 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2234 static const struct timeval zero;
2235 static int atexit_done;
2238 return errno = EINVAL,
2239 error("setitimer param 3 != NULL not implemented");
2240 if (!is_timeval_eq(&in->it_interval, &zero) &&
2241 !is_timeval_eq(&in->it_interval, &in->it_value))
2242 return errno = EINVAL,
2243 error("setitimer: it_interval must be zero or eq it_value");
2246 stop_timer_thread();
2248 if (is_timeval_eq(&in->it_value, &zero) &&
2249 is_timeval_eq(&in->it_interval, &zero))
2252 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2253 one_shot = is_timeval_eq(&in->it_interval, &zero);
2255 atexit(stop_timer_thread);
2258 return start_timer_thread();
2261 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2264 return errno = EINVAL,
2265 error("sigaction only implemented for SIGALRM");
2267 return errno = EINVAL,
2268 error("sigaction: param 3 != NULL not implemented");
2270 timer_fn = in->sa_handler;
2275 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2287 sigint_fn = handler;
2291 return signal(sig, handler);
2298 int mingw_raise(int sig)
2302 if (timer_fn == SIG_DFL) {
2303 if (isatty(STDERR_FILENO))
2304 fputs("Alarm clock\n", stderr);
2305 exit(128 + SIGALRM);
2306 } else if (timer_fn != SIG_IGN)
2311 if (sigint_fn == SIG_DFL)
2313 else if (sigint_fn != SIG_IGN)
2317 #if defined(_MSC_VER)
2324 case SIGABRT_COMPAT:
2326 * The <signal.h> header in the MS C Runtime defines 8 signals
2327 * as being supported on the platform. Anything else causes an
2328 * "Invalid signal or error" (which in DEBUG builds causes the
2329 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2330 * already know will fail.
2347 int link(const char *oldpath, const char *newpath)
2349 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2350 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2351 xutftowcs_path(wnewpath, newpath) < 0)
2354 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2355 errno = err_win_to_posix(GetLastError());
2361 pid_t waitpid(pid_t pid, int *status, int options)
2363 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2370 if (pid > 0 && options & WNOHANG) {
2371 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2375 options &= ~WNOHANG;
2379 struct pinfo_t **ppinfo;
2380 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2386 GetExitCodeProcess(h, (LPDWORD)status);
2388 EnterCriticalSection(&pinfo_cs);
2392 struct pinfo_t *info = *ppinfo;
2393 if (info->pid == pid) {
2394 CloseHandle(info->proc);
2395 *ppinfo = info->next;
2399 ppinfo = &info->next;
2402 LeaveCriticalSection(&pinfo_cs);
2413 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2415 int upos = 0, wpos = 0;
2416 const unsigned char *utf = (const unsigned char*) utfs;
2417 if (!utf || !wcs || wcslen < 1) {
2421 /* reserve space for \0 */
2426 while (upos < utflen) {
2427 int c = utf[upos++] & 0xff;
2428 if (utflen == INT_MAX && c == 0)
2431 if (wpos >= wcslen) {
2440 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2441 (utf[upos] & 0xc0) == 0x80) {
2443 c = ((c & 0x1f) << 6);
2444 c |= (utf[upos++] & 0x3f);
2446 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2447 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2448 (utf[upos] & 0xc0) == 0x80 &&
2449 (utf[upos + 1] & 0xc0) == 0x80) {
2451 c = ((c & 0x0f) << 12);
2452 c |= ((utf[upos++] & 0x3f) << 6);
2453 c |= (utf[upos++] & 0x3f);
2455 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2456 wpos + 1 < wcslen &&
2457 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2458 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2459 (utf[upos] & 0xc0) == 0x80 &&
2460 (utf[upos + 1] & 0xc0) == 0x80 &&
2461 (utf[upos + 2] & 0xc0) == 0x80) {
2462 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2463 c = ((c & 0x07) << 18);
2464 c |= ((utf[upos++] & 0x3f) << 12);
2465 c |= ((utf[upos++] & 0x3f) << 6);
2466 c |= (utf[upos++] & 0x3f);
2468 wcs[wpos++] = 0xd800 | (c >> 10);
2469 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2470 } else if (c >= 0xa0) {
2471 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2474 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2475 static const char *hex = "0123456789abcdef";
2476 wcs[wpos++] = hex[c >> 4];
2478 wcs[wpos++] = hex[c & 0x0f];
2485 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2487 if (!wcs || !utf || utflen < 1) {
2491 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2498 static void setup_windows_environment(void)
2500 char *tmp = getenv("TMPDIR");
2502 /* on Windows it is TMP and TEMP */
2504 if (!(tmp = getenv("TMP")))
2505 tmp = getenv("TEMP");
2507 setenv("TMPDIR", tmp, 1);
2508 tmp = getenv("TMPDIR");
2514 * Convert all dir separators to forward slashes,
2515 * to help shell commands called from the Git
2516 * executable (by not mistaking the dir separators
2517 * for escape characters).
2519 convert_slashes(tmp);
2522 /* simulate TERM to enable auto-color (see color.c) */
2523 if (!getenv("TERM"))
2524 setenv("TERM", "cygwin", 1);
2526 /* calculate HOME if not set */
2527 if (!getenv("HOME")) {
2529 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2530 * location, thus also check if the path exists (i.e. is not
2533 if ((tmp = getenv("HOMEDRIVE"))) {
2534 struct strbuf buf = STRBUF_INIT;
2535 strbuf_addstr(&buf, tmp);
2536 if ((tmp = getenv("HOMEPATH"))) {
2537 strbuf_addstr(&buf, tmp);
2538 if (is_directory(buf.buf))
2539 setenv("HOME", buf.buf, 1);
2541 tmp = NULL; /* use $USERPROFILE */
2543 strbuf_release(&buf);
2545 /* use $USERPROFILE if the home share is not available */
2546 if (!tmp && (tmp = getenv("USERPROFILE")))
2547 setenv("HOME", tmp, 1);
2551 int is_valid_win32_path(const char *path, int allow_literal_nul)
2553 const char *p = path;
2554 int preceding_space_or_period = 0, i = 0, periods = 0;
2559 skip_dos_drive_prefix((char **)&path);
2566 case '/': case '\\':
2567 /* cannot end in ` ` or `.`, except for `.` and `..` */
2568 if (preceding_space_or_period &&
2569 (i != periods || periods > 2))
2574 i = periods = preceding_space_or_period = 0;
2578 case 'a': case 'A': /* AUX */
2579 if (((c = path[++i]) != 'u' && c != 'U') ||
2580 ((c = path[++i]) != 'x' && c != 'X')) {
2581 not_a_reserved_name:
2586 case 'c': case 'C': /* COM<N>, CON, CONIN$, CONOUT$ */
2587 if ((c = path[++i]) != 'o' && c != 'O')
2588 goto not_a_reserved_name;
2590 if (c == 'm' || c == 'M') { /* COM<N> */
2591 if (!isdigit(path[++i]))
2592 goto not_a_reserved_name;
2593 } else if (c == 'n' || c == 'N') { /* CON */
2595 if ((c == 'i' || c == 'I') &&
2596 ((c = path[i + 2]) == 'n' ||
2599 i += 3; /* CONIN$ */
2600 else if ((c == 'o' || c == 'O') &&
2601 ((c = path[i + 2]) == 'u' ||
2603 ((c = path[i + 3]) == 't' ||
2606 i += 4; /* CONOUT$ */
2608 goto not_a_reserved_name;
2610 case 'l': case 'L': /* LPT<N> */
2611 if (((c = path[++i]) != 'p' && c != 'P') ||
2612 ((c = path[++i]) != 't' && c != 'T') ||
2613 !isdigit(path[++i]))
2614 goto not_a_reserved_name;
2616 case 'n': case 'N': /* NUL */
2617 if (((c = path[++i]) != 'u' && c != 'U') ||
2618 ((c = path[++i]) != 'l' && c != 'L') ||
2619 (allow_literal_nul &&
2620 !path[i + 1] && p == path))
2621 goto not_a_reserved_name;
2623 case 'p': case 'P': /* PRN */
2624 if (((c = path[++i]) != 'r' && c != 'R') ||
2625 ((c = path[++i]) != 'n' && c != 'N'))
2626 goto not_a_reserved_name;
2633 * So far, this looks like a reserved name. Let's see
2634 * whether it actually is one: trailing spaces, a file
2635 * extension, or an NTFS Alternate Data Stream do not
2636 * matter, the name is still reserved if any of those
2637 * follow immediately after the actual name.
2640 if (path[i] == ' ') {
2641 preceding_space_or_period = 1;
2642 while (path[++i] == ' ')
2643 ; /* skip all spaces */
2647 if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2648 goto not_a_reserved_name;
2650 /* contains reserved name */
2656 preceding_space_or_period = 1;
2659 case ':': /* DOS drive prefix was already skipped */
2660 case '<': case '>': case '"': case '|': case '?': case '*':
2661 /* illegal character */
2664 if (c > '\0' && c < '\x20')
2665 /* illegal character */
2668 preceding_space_or_period = 0;
2673 #if !defined(_MSC_VER)
2675 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2676 * mingw startup code, see init.c in mingw runtime).
2681 static NORETURN void die_startup(void)
2683 fputs("fatal: not enough memory for initialization", stderr);
2687 static void *malloc_startup(size_t size)
2689 void *result = malloc(size);
2695 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2697 len = xwcstoutf(buffer, wcs, len) + 1;
2698 return memcpy(malloc_startup(len), buffer, len);
2701 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2702 DWORD desired_access, DWORD flags)
2704 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2705 wchar_t buf[MAX_PATH];
2706 DWORD max = ARRAY_SIZE(buf);
2708 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2710 if (!ret || ret >= max)
2713 /* make sure this does not leak into child processes */
2714 SetEnvironmentVariableW(key, NULL);
2715 if (!wcscmp(buf, L"off")) {
2717 handle = GetStdHandle(std_id);
2718 if (handle != INVALID_HANDLE_VALUE)
2719 CloseHandle(handle);
2722 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2723 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2724 if (handle == INVALID_HANDLE_VALUE) {
2726 handle = GetStdHandle(std_id);
2727 if (handle != INVALID_HANDLE_VALUE)
2728 CloseHandle(handle);
2730 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2731 SetStdHandle(std_id, handle);
2733 /* do *not* close the new_fd: that would close stdout */
2737 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2739 if (handle != INVALID_HANDLE_VALUE) {
2740 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2741 SetStdHandle(std_id, handle);
2747 static void maybe_redirect_std_handles(void)
2749 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2750 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2751 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2752 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2753 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2754 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2764 * We implement wmain() and compile with -municode, which would
2765 * normally ignore main(), but we call the latter from the former
2766 * so that we can handle non-ASCII command-line parameters
2769 * To be more compatible with the core git code, we convert
2770 * argv into UTF8 and pass them directly to main().
2772 int wmain(int argc, const wchar_t **wargv)
2774 int i, maxlen, exit_status;
2775 char *buffer, **save;
2778 trace2_initialize_clock();
2782 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2785 #ifdef USE_MSVC_CRTDBG
2786 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2790 maybe_redirect_std_handles();
2792 /* determine size of argv and environ conversion buffer */
2793 maxlen = wcslen(wargv[0]);
2794 for (i = 1; i < argc; i++)
2795 maxlen = max(maxlen, wcslen(wargv[i]));
2797 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2798 maxlen = 3 * maxlen + 1;
2799 buffer = malloc_startup(maxlen);
2802 * Create a UTF-8 version of w_argv. Also create a "save" copy
2803 * to remember all the string pointers because parse_options()
2804 * will remove claimed items from the argv that we pass down.
2806 ALLOC_ARRAY(argv, argc + 1);
2807 ALLOC_ARRAY(save, argc + 1);
2808 for (i = 0; i < argc; i++)
2809 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2810 argv[i] = save[i] = NULL;
2813 /* fix Windows specific environment settings */
2814 setup_windows_environment();
2816 unset_environment_variables = xstrdup("PERL5LIB");
2818 /* initialize critical section for waitpid pinfo_t list */
2819 InitializeCriticalSection(&pinfo_cs);
2821 /* set up default file mode and file modes for stdin/out/err */
2823 _setmode(_fileno(stdin), _O_BINARY);
2824 _setmode(_fileno(stdout), _O_BINARY);
2825 _setmode(_fileno(stderr), _O_BINARY);
2827 /* initialize Unicode console */
2830 /* invoke the real main() using our utf8 version of argv. */
2831 exit_status = main(argc, argv);
2833 for (i = 0; i < argc; i++)
2841 int uname(struct utsname *buf)
2843 unsigned v = (unsigned)GetVersion();
2844 memset(buf, 0, sizeof(*buf));
2845 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2846 xsnprintf(buf->release, sizeof(buf->release),
2847 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2848 /* assuming NT variants only.. */
2849 xsnprintf(buf->version, sizeof(buf->version),
2850 "%u", (v >> 16) & 0x7fff);