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 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
22 strvec_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 if (DeleteFileW(wpathname))
296 /* read-only files cannot be removed */
297 _wchmod(wpathname, 0666);
298 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
299 if (!is_file_in_use_error(GetLastError()))
302 * We assume that some other process had the source or
303 * destination file open at the wrong moment and retry.
304 * In order to give the other process a higher chance to
305 * complete its operation, we give up our time slice now.
306 * If we have to retry again, we do sleep a bit.
311 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
312 ask_yes_no_if_possible("Unlink of file '%s' failed. "
313 "Should I try again?", pathname))
314 ret = _wunlink(wpathname);
318 static int is_dir_empty(const wchar_t *wpath)
320 WIN32_FIND_DATAW findbuf;
322 wchar_t wbuf[MAX_PATH + 2];
324 wcscat(wbuf, L"\\*");
325 handle = FindFirstFileW(wbuf, &findbuf);
326 if (handle == INVALID_HANDLE_VALUE)
327 return GetLastError() == ERROR_NO_MORE_FILES;
329 while (!wcscmp(findbuf.cFileName, L".") ||
330 !wcscmp(findbuf.cFileName, L".."))
331 if (!FindNextFileW(handle, &findbuf)) {
332 DWORD err = GetLastError();
334 return err == ERROR_NO_MORE_FILES;
340 int mingw_rmdir(const char *pathname)
343 wchar_t wpathname[MAX_PATH];
344 if (xutftowcs_path(wpathname, pathname) < 0)
347 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
348 if (!is_file_in_use_error(GetLastError()))
349 errno = err_win_to_posix(GetLastError());
352 if (!is_dir_empty(wpathname)) {
357 * We assume that some other process had the source or
358 * destination file open at the wrong moment and retry.
359 * In order to give the other process a higher chance to
360 * complete its operation, we give up our time slice now.
361 * If we have to retry again, we do sleep a bit.
366 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
367 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
368 "Should I try again?", pathname))
369 ret = _wrmdir(wpathname);
371 invalidate_lstat_cache();
375 static inline int needs_hiding(const char *path)
377 const char *basename;
379 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
382 /* We cannot use basename(), as it would remove trailing slashes */
383 win32_skip_dos_drive_prefix((char **)&path);
387 for (basename = path; *path; path++)
388 if (is_dir_sep(*path)) {
391 } while (is_dir_sep(*path));
392 /* ignore trailing slashes */
399 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
400 return *basename == '.';
402 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
403 return !strncasecmp(".git", basename, 4) &&
404 (!basename[4] || is_dir_sep(basename[4]));
407 static int set_hidden_flag(const wchar_t *path, int set)
409 DWORD original = GetFileAttributesW(path), modified;
411 modified = original | FILE_ATTRIBUTE_HIDDEN;
413 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
414 if (original == modified || SetFileAttributesW(path, modified))
416 errno = err_win_to_posix(GetLastError());
420 int mingw_mkdir(const char *path, int mode)
423 wchar_t wpath[MAX_PATH];
425 if (!is_valid_win32_path(path, 0)) {
430 if (xutftowcs_path(wpath, path) < 0)
432 ret = _wmkdir(wpath);
433 if (!ret && needs_hiding(path))
434 return set_hidden_flag(wpath, 1);
439 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
440 * is documented in [1] as opening a writable file handle in append mode.
441 * (It is believed that) this is atomic since it is maintained by the
442 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
444 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
446 * This trick does not appear to work for named pipes. Instead it creates
447 * a named pipe client handle that cannot be written to. Callers should
448 * just use the regular _wopen() for them. (And since client handle gets
449 * bound to a unique server handle, it isn't really an issue.)
451 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
455 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
457 /* only these flags are supported */
458 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
459 return errno = ENOSYS, -1;
462 * FILE_SHARE_WRITE is required to permit child processes
463 * to append to the file.
465 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
466 FILE_SHARE_WRITE | FILE_SHARE_READ,
467 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
468 if (handle == INVALID_HANDLE_VALUE) {
469 DWORD err = GetLastError();
472 * Some network storage solutions (e.g. Isilon) might return
473 * ERROR_INVALID_PARAMETER instead of expected error
474 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
475 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
477 if (err == ERROR_INVALID_PARAMETER)
478 err = ERROR_PATH_NOT_FOUND;
480 errno = err_win_to_posix(err);
485 * No O_APPEND here, because the CRT uses it only to reset the
486 * file pointer to EOF before each write(); but that is not
487 * necessary (and may lead to races) for a file created with
490 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
497 * Does the pathname map to the local named pipe filesystem?
498 * That is, does it have a "//./pipe/" prefix?
500 static int is_local_named_pipe_path(const char *filename)
502 return (is_dir_sep(filename[0]) &&
503 is_dir_sep(filename[1]) &&
504 filename[2] == '.' &&
505 is_dir_sep(filename[3]) &&
506 !strncasecmp(filename+4, "pipe", 4) &&
507 is_dir_sep(filename[8]) &&
511 int mingw_open (const char *filename, int oflags, ...)
513 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
516 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
517 wchar_t wfilename[MAX_PATH];
520 va_start(args, oflags);
521 mode = va_arg(args, int);
524 if (!is_valid_win32_path(filename, !create)) {
525 errno = create ? EINVAL : ENOENT;
529 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
530 open_fn = mingw_open_append;
534 if (filename && !strcmp(filename, "/dev/null"))
535 wcscpy(wfilename, L"nul");
536 else if (xutftowcs_path(wfilename, filename) < 0)
539 fd = open_fn(wfilename, oflags, mode);
541 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
542 DWORD attrs = GetFileAttributesW(wfilename);
543 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
546 if ((oflags & O_CREAT) && needs_hiding(filename)) {
548 * Internally, _wopen() uses the CreateFile() API which errors
549 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
550 * specified and an already existing file's attributes do not
551 * match *exactly*. As there is no mode or flag we can set that
552 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
553 * again *without* the O_CREAT flag (that corresponds to the
554 * CREATE_ALWAYS flag of CreateFile()).
556 if (fd < 0 && errno == EACCES)
557 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
558 if (fd >= 0 && set_hidden_flag(wfilename, 1))
559 warning("could not mark '%s' as hidden.", filename);
564 static BOOL WINAPI ctrl_ignore(DWORD type)
570 int mingw_fgetc(FILE *stream)
573 if (!isatty(_fileno(stream)))
574 return fgetc(stream);
576 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
579 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
582 /* Ctrl+C was pressed, simulate SIGINT and retry */
585 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
590 FILE *mingw_fopen (const char *filename, const char *otype)
592 int hide = needs_hiding(filename);
594 wchar_t wfilename[MAX_PATH], wotype[4];
595 if (filename && !strcmp(filename, "/dev/null"))
596 wcscpy(wfilename, L"nul");
597 else if (!is_valid_win32_path(filename, 1)) {
598 int create = otype && strchr(otype, 'w');
599 errno = create ? EINVAL : ENOENT;
601 } else if (xutftowcs_path(wfilename, filename) < 0)
604 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
607 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
608 error("could not unhide %s", filename);
611 file = _wfopen(wfilename, wotype);
612 if (!file && GetLastError() == ERROR_INVALID_NAME)
614 if (file && hide && set_hidden_flag(wfilename, 1))
615 warning("could not mark '%s' as hidden.", filename);
619 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
621 int hide = needs_hiding(filename);
623 wchar_t wfilename[MAX_PATH], wotype[4];
624 if (filename && !strcmp(filename, "/dev/null"))
625 wcscpy(wfilename, L"nul");
626 else if (!is_valid_win32_path(filename, 1)) {
627 int create = otype && strchr(otype, 'w');
628 errno = create ? EINVAL : ENOENT;
630 } else if (xutftowcs_path(wfilename, filename) < 0)
633 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
636 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
637 error("could not unhide %s", filename);
640 file = _wfreopen(wfilename, wotype, stream);
641 if (file && hide && set_hidden_flag(wfilename, 1))
642 warning("could not mark '%s' as hidden.", filename);
647 int mingw_fflush(FILE *stream)
649 int ret = fflush(stream);
652 * write() is used behind the scenes of stdio output functions.
653 * Since git code does not check for errors after each stdio write
654 * operation, it can happen that write() is called by a later
655 * stdio function even if an earlier write() call failed. In the
656 * case of a pipe whose readable end was closed, only the first
657 * call to write() reports EPIPE on Windows. Subsequent write()
658 * calls report EINVAL. It is impossible to notice whether this
659 * fflush invocation triggered such a case, therefore, we have to
660 * catch all EINVAL errors whole-sale.
662 if (ret && errno == EINVAL)
669 ssize_t mingw_write(int fd, const void *buf, size_t len)
671 ssize_t result = write(fd, buf, len);
673 if (result < 0 && errno == EINVAL && buf) {
674 /* check if fd is a pipe */
675 HANDLE h = (HANDLE) _get_osfhandle(fd);
676 if (GetFileType(h) == FILE_TYPE_PIPE)
685 int mingw_access(const char *filename, int mode)
687 wchar_t wfilename[MAX_PATH];
688 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
690 if (xutftowcs_path(wfilename, filename) < 0)
692 /* X_OK is not supported by the MSVCRT version */
693 return _waccess(wfilename, mode & ~X_OK);
696 int mingw_chdir(const char *dirname)
698 wchar_t wdirname[MAX_PATH];
699 if (xutftowcs_path(wdirname, dirname) < 0)
701 return _wchdir(wdirname);
704 int mingw_chmod(const char *filename, int mode)
706 wchar_t wfilename[MAX_PATH];
707 if (xutftowcs_path(wfilename, filename) < 0)
709 return _wchmod(wfilename, mode);
713 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
714 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
716 static inline long long filetime_to_hnsec(const FILETIME *ft)
718 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
719 /* Windows to Unix Epoch conversion */
720 return winTime - 116444736000000000LL;
723 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
725 long long hnsec = filetime_to_hnsec(ft);
726 ts->tv_sec = (time_t)(hnsec / 10000000);
727 ts->tv_nsec = (hnsec % 10000000) * 100;
731 * Verifies that safe_create_leading_directories() would succeed.
733 static int has_valid_directory_prefix(wchar_t *wfilename)
735 int n = wcslen(wfilename);
738 wchar_t c = wfilename[--n];
744 wfilename[n] = L'\0';
745 attributes = GetFileAttributesW(wfilename);
747 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
748 attributes == FILE_ATTRIBUTE_DEVICE)
750 if (attributes == INVALID_FILE_ATTRIBUTES)
751 switch (GetLastError()) {
752 case ERROR_PATH_NOT_FOUND:
754 case ERROR_FILE_NOT_FOUND:
755 /* This implies parent directory exists. */
763 /* We keep the do_lstat code in a separate function to avoid recursion.
764 * When a path ends with a slash, the stat will fail with ENOENT. In
765 * this case, we strip the trailing slashes and stat again.
767 * If follow is true then act like stat() and report on the link
768 * target. Otherwise report on the link itself.
770 static int do_lstat(int follow, const char *file_name, struct stat *buf)
772 WIN32_FILE_ATTRIBUTE_DATA fdata;
773 wchar_t wfilename[MAX_PATH];
774 if (xutftowcs_path(wfilename, file_name) < 0)
777 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
782 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
783 buf->st_size = fdata.nFileSizeLow |
784 (((off_t)fdata.nFileSizeHigh)<<32);
785 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
786 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
787 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
788 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
789 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
790 WIN32_FIND_DATAW findbuf;
791 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
792 if (handle != INVALID_HANDLE_VALUE) {
793 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
794 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
796 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
797 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
799 buf->st_mode = S_IFLNK;
801 buf->st_mode |= S_IREAD;
802 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
803 buf->st_mode |= S_IWRITE;
810 switch (GetLastError()) {
811 case ERROR_ACCESS_DENIED:
812 case ERROR_SHARING_VIOLATION:
813 case ERROR_LOCK_VIOLATION:
814 case ERROR_SHARING_BUFFER_EXCEEDED:
817 case ERROR_BUFFER_OVERFLOW:
818 errno = ENAMETOOLONG;
820 case ERROR_NOT_ENOUGH_MEMORY:
823 case ERROR_PATH_NOT_FOUND:
824 if (!has_valid_directory_prefix(wfilename)) {
836 /* We provide our own lstat/fstat functions, since the provided
837 * lstat/fstat functions are so slow. These stat functions are
838 * tailored for Git's usage (read: fast), and are not meant to be
839 * complete. Note that Git stat()s are redirected to mingw_lstat()
840 * too, since Windows doesn't really handle symlinks that well.
842 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
845 char alt_name[PATH_MAX];
847 if (!do_lstat(follow, file_name, buf))
850 /* if file_name ended in a '/', Windows returned ENOENT;
851 * try again without trailing slashes
856 namelen = strlen(file_name);
857 if (namelen && file_name[namelen-1] != '/')
859 while (namelen && file_name[namelen-1] == '/')
861 if (!namelen || namelen >= PATH_MAX)
864 memcpy(alt_name, file_name, namelen);
865 alt_name[namelen] = 0;
866 return do_lstat(follow, alt_name, buf);
869 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
871 BY_HANDLE_FILE_INFORMATION fdata;
873 if (!GetFileInformationByHandle(hnd, &fdata)) {
874 errno = err_win_to_posix(GetLastError());
882 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
883 buf->st_size = fdata.nFileSizeLow |
884 (((off_t)fdata.nFileSizeHigh)<<32);
885 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
886 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
887 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
888 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
892 int mingw_lstat(const char *file_name, struct stat *buf)
894 return do_stat_internal(0, file_name, buf);
896 int mingw_stat(const char *file_name, struct stat *buf)
898 return do_stat_internal(1, file_name, buf);
901 int mingw_fstat(int fd, struct stat *buf)
903 HANDLE fh = (HANDLE)_get_osfhandle(fd);
904 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
908 return get_file_info_by_handle(fh, buf);
912 /* initialize stat fields */
913 memset(buf, 0, sizeof(*buf));
916 if (type == FILE_TYPE_CHAR) {
917 buf->st_mode = _S_IFCHR;
919 buf->st_mode = _S_IFIFO;
920 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
921 buf->st_size = avail;
931 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
933 long long winTime = t * 10000000LL + 116444736000000000LL;
934 ft->dwLowDateTime = winTime;
935 ft->dwHighDateTime = winTime >> 32;
938 int mingw_utime (const char *file_name, const struct utimbuf *times)
943 wchar_t wfilename[MAX_PATH];
944 if (xutftowcs_path(wfilename, file_name) < 0)
947 /* must have write permission */
948 attrs = GetFileAttributesW(wfilename);
949 if (attrs != INVALID_FILE_ATTRIBUTES &&
950 (attrs & FILE_ATTRIBUTE_READONLY)) {
951 /* ignore errors here; open() will report them */
952 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
955 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
961 time_t_to_filetime(times->modtime, &mft);
962 time_t_to_filetime(times->actime, &aft);
964 GetSystemTimeAsFileTime(&mft);
967 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
975 if (attrs != INVALID_FILE_ATTRIBUTES &&
976 (attrs & FILE_ATTRIBUTE_READONLY)) {
977 /* ignore errors again */
978 SetFileAttributesW(wfilename, attrs);
984 size_t mingw_strftime(char *s, size_t max,
985 const char *format, const struct tm *tm)
987 /* a pointer to the original strftime in case we can't find the UCRT version */
988 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
990 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, strftime, char *, size_t,
991 const char *, const struct tm *);
993 if (INIT_PROC_ADDR(strftime))
994 ret = strftime(s, max, format, tm);
996 ret = fallback(s, max, format, tm);
998 if (!ret && errno == EINVAL)
999 die("invalid strftime format: '%s'", format);
1003 unsigned int sleep (unsigned int seconds)
1005 Sleep(seconds*1000);
1009 char *mingw_mktemp(char *template)
1011 wchar_t wtemplate[MAX_PATH];
1012 if (xutftowcs_path(wtemplate, template) < 0)
1014 if (!_wmktemp(wtemplate))
1016 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1021 int mkstemp(char *template)
1023 char *filename = mktemp(template);
1024 if (filename == NULL)
1026 return open(filename, O_RDWR | O_CREAT, 0600);
1029 int gettimeofday(struct timeval *tv, void *tz)
1034 GetSystemTimeAsFileTime(&ft);
1035 hnsec = filetime_to_hnsec(&ft);
1036 tv->tv_sec = hnsec / 10000000;
1037 tv->tv_usec = (hnsec % 10000000) / 10;
1041 int pipe(int filedes[2])
1045 /* this creates non-inheritable handles */
1046 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1047 errno = err_win_to_posix(GetLastError());
1050 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1051 if (filedes[0] < 0) {
1056 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1057 if (filedes[1] < 0) {
1065 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1067 if (gmtime_s(result, timep) == 0)
1072 struct tm *localtime_r(const time_t *timep, struct tm *result)
1074 if (localtime_s(result, timep) == 0)
1079 char *mingw_getcwd(char *pointer, int len)
1081 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1082 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1084 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1085 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1088 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1089 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1090 HANDLE hnd = CreateFileW(cwd, 0,
1091 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1092 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1093 if (hnd == INVALID_HANDLE_VALUE)
1095 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1097 if (!ret || ret >= ARRAY_SIZE(wpointer))
1099 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1103 if (!ret || ret >= ARRAY_SIZE(wpointer))
1105 if (xwcstoutf(pointer, wpointer, len) < 0)
1107 convert_slashes(pointer);
1112 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1113 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1115 static const char *quote_arg_msvc(const char *arg)
1117 /* count chars to quote */
1119 int force_quotes = 0;
1121 const char *p = arg;
1122 if (!*p) force_quotes = 1;
1124 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1128 else if (*p == '\\') {
1130 while (*p == '\\') {
1135 if (*p == '"' || !*p)
1142 if (!force_quotes && n == 0)
1145 /* insert \ where necessary */
1146 d = q = xmalloc(st_add3(len, n, 3));
1151 else if (*arg == '\\') {
1153 while (*arg == '\\') {
1157 if (*arg == '"' || !*arg) {
1160 /* don't escape the surrounding end quote */
1175 static const char *quote_arg_msys2(const char *arg)
1177 struct strbuf buf = STRBUF_INIT;
1178 const char *p2 = arg, *p;
1180 for (p = arg; *p; p++) {
1181 int ws = isspace(*p);
1182 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1183 *p != '?' && *p != '*' && *p != '~')
1186 strbuf_addch(&buf, '"');
1188 strbuf_add(&buf, p2, p - p2);
1189 if (*p == '\\' || *p == '"')
1190 strbuf_addch(&buf, '\\');
1195 strbuf_addch(&buf, '"');
1199 strbuf_add(&buf, p2, p - p2);
1201 strbuf_addch(&buf, '"');
1202 return strbuf_detach(&buf, 0);
1205 static const char *parse_interpreter(const char *cmd)
1207 static char buf[100];
1211 /* don't even try a .exe */
1213 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1216 fd = open(cmd, O_RDONLY);
1219 n = read(fd, buf, sizeof(buf)-1);
1221 if (n < 4) /* at least '#!/x' and not error */
1224 if (buf[0] != '#' || buf[1] != '!')
1227 p = buf + strcspn(buf, "\r\n");
1232 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1235 if ((opt = strchr(p+1, ' ')))
1241 * exe_only means that we only want to detect .exe files, but not scripts
1242 * (which do not have an extension)
1244 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1245 int isexe, int exe_only)
1247 char path[MAX_PATH];
1248 wchar_t wpath[MAX_PATH];
1249 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1251 if (xutftowcs_path(wpath, path) < 0)
1254 if (!isexe && _waccess(wpath, F_OK) == 0)
1255 return xstrdup(path);
1256 wpath[wcslen(wpath)-4] = '\0';
1257 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1258 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1259 path[strlen(path)-4] = '\0';
1260 return xstrdup(path);
1267 * Determines the absolute path of cmd using the split path in path.
1268 * If cmd contains a slash or backslash, no lookup is performed.
1270 static char *path_lookup(const char *cmd, int exe_only)
1274 int len = strlen(cmd);
1275 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1277 if (strpbrk(cmd, "/\\"))
1278 return xstrdup(cmd);
1280 path = mingw_getenv("PATH");
1285 const char *sep = strchrnul(path, ';');
1286 int dirlen = sep - path;
1288 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1297 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1299 while (*s && *s != c)
1304 /* Compare only keys */
1305 static int wenvcmp(const void *a, const void *b)
1307 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1308 size_t p_len, q_len;
1311 p_len = wcschrnul(p, L'=') - p;
1312 q_len = wcschrnul(q, L'=') - q;
1314 /* If the length differs, include the shorter key's NUL */
1317 else if (p_len > q_len)
1320 return _wcsnicmp(p, q, p_len);
1324 * Build an environment block combining the inherited environment
1325 * merged with the given list of settings.
1327 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1328 * Values of the form "KEY" in deltaenv delete inherited values.
1330 * Multiple entries in deltaenv for the same key are explicitly allowed.
1332 * We return a contiguous block of UNICODE strings with a final trailing
1335 static wchar_t *make_environment_block(char **deltaenv)
1337 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1338 size_t wlen, s, delta_size, size;
1340 wchar_t **array = NULL;
1341 size_t alloc = 0, nr = 0, i;
1343 size = 1; /* for extra NUL at the end */
1345 /* If there is no deltaenv to apply, simply return a copy. */
1346 if (!deltaenv || !*deltaenv) {
1347 for (p = wenv; p && *p; ) {
1348 size_t s = wcslen(p) + 1;
1353 ALLOC_ARRAY(result, size);
1354 COPY_ARRAY(result, wenv, size);
1355 FreeEnvironmentStringsW(wenv);
1360 * If there is a deltaenv, let's accumulate all keys into `array`,
1361 * sort them using the stable git_stable_qsort() and then copy,
1362 * skipping duplicate keys
1364 for (p = wenv; p && *p; ) {
1365 ALLOC_GROW(array, nr + 1, alloc);
1372 /* (over-)assess size needed for wchar version of deltaenv */
1373 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1374 delta_size += strlen(deltaenv[i]) * 2 + 1;
1375 ALLOC_ARRAY(wdeltaenv, delta_size);
1377 /* convert the deltaenv, appending to array */
1378 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1379 ALLOC_GROW(array, nr + 1, alloc);
1380 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1385 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1386 ALLOC_ARRAY(result, size + delta_size);
1388 for (p = result, i = 0; i < nr; i++) {
1389 /* Skip any duplicate keys; last one wins */
1390 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1393 /* Skip "to delete" entry */
1394 if (!wcschr(array[i], L'='))
1397 size = wcslen(array[i]) + 1;
1398 COPY_ARRAY(p, array[i], size);
1405 FreeEnvironmentStringsW(wenv);
1409 static void do_unset_environment_variables(void)
1412 char *p = unset_environment_variables;
1419 char *comma = strchr(p, ',');
1431 struct pinfo_t *next;
1435 static struct pinfo_t *pinfo = NULL;
1436 CRITICAL_SECTION pinfo_cs;
1438 /* Used to match and chomp off path components */
1439 static inline int match_last_path_component(const char *path, size_t *len,
1440 const char *component)
1442 size_t component_len = strlen(component);
1443 if (*len < component_len + 1 ||
1444 !is_dir_sep(path[*len - component_len - 1]) ||
1445 fspathncmp(path + *len - component_len, component, component_len))
1447 *len -= component_len + 1;
1448 /* chomp off repeated dir separators */
1449 while (*len > 0 && is_dir_sep(path[*len - 1]))
1454 static int is_msys2_sh(const char *cmd)
1459 if (!strcmp(cmd, "sh")) {
1460 static int ret = -1;
1466 p = path_lookup(cmd, 0);
1470 size_t len = strlen(p);
1472 ret = match_last_path_component(p, &len, "sh.exe") &&
1473 match_last_path_component(p, &len, "bin") &&
1474 match_last_path_component(p, &len, "usr");
1480 if (ends_with(cmd, "\\sh.exe")) {
1484 sh = path_lookup("sh", 0);
1486 return !fspathcmp(cmd, sh);
1492 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1494 int prepend_cmd, int fhin, int fhout, int fherr)
1496 static int restrict_handle_inheritance = -1;
1498 PROCESS_INFORMATION pi;
1499 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1500 HANDLE stdhandles[3];
1501 DWORD stdhandles_count = 0;
1504 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1505 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1508 const char *(*quote_arg)(const char *arg) =
1509 is_msys2_sh(cmd ? cmd : *argv) ?
1510 quote_arg_msys2 : quote_arg_msvc;
1511 const char *strace_env;
1513 /* Make sure to override previous errors, if any */
1516 if (restrict_handle_inheritance < 0)
1517 restrict_handle_inheritance = core_restrict_inherited_handles;
1519 * The following code to restrict which handles are inherited seems
1520 * to work properly only on Windows 7 and later, so let's disable it
1521 * on Windows Vista and 2008.
1523 if (restrict_handle_inheritance < 0)
1524 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1526 do_unset_environment_variables();
1528 /* Determine whether or not we are associated to a console */
1529 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1530 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1531 FILE_ATTRIBUTE_NORMAL, NULL);
1532 if (cons == INVALID_HANDLE_VALUE) {
1533 /* There is no console associated with this process.
1534 * Since the child is a console process, Windows
1535 * would normally create a console window. But
1536 * since we'll be redirecting std streams, we do
1537 * not need the console.
1538 * It is necessary to use DETACHED_PROCESS
1539 * instead of CREATE_NO_WINDOW to make ssh
1540 * recognize that it has no console.
1542 flags |= DETACHED_PROCESS;
1544 /* There is already a console. If we specified
1545 * DETACHED_PROCESS here, too, Windows would
1546 * disassociate the child from the console.
1547 * The same is true for CREATE_NO_WINDOW.
1552 memset(&si, 0, sizeof(si));
1553 si.StartupInfo.cb = sizeof(si);
1554 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1555 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1556 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1558 /* The list of handles cannot contain duplicates */
1559 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1560 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1561 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1562 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1563 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1564 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1565 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1566 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1567 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1568 if (stdhandles_count)
1569 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1571 if (*argv && !strcmp(cmd, *argv))
1573 else if (xutftowcs_path(wcmd, cmd) < 0)
1575 if (dir && xutftowcs_path(wdir, dir) < 0)
1578 /* concatenate argv, quoting args as we go */
1579 strbuf_init(&args, 0);
1581 char *quoted = (char *)quote_arg(cmd);
1582 strbuf_addstr(&args, quoted);
1586 for (; *argv; argv++) {
1587 char *quoted = (char *)quote_arg(*argv);
1589 strbuf_addch(&args, ' ');
1590 strbuf_addstr(&args, quoted);
1591 if (quoted != *argv)
1595 strace_env = getenv("GIT_STRACE_COMMANDS");
1597 char *p = path_lookup("strace.exe", 1);
1599 return error("strace not found!");
1600 if (xutftowcs_path(wcmd, p) < 0) {
1605 if (!strcmp("1", strace_env) ||
1606 !strcasecmp("yes", strace_env) ||
1607 !strcasecmp("true", strace_env))
1608 strbuf_insert(&args, 0, "strace ", 7);
1610 const char *quoted = quote_arg(strace_env);
1611 struct strbuf buf = STRBUF_INIT;
1612 strbuf_addf(&buf, "strace -o %s ", quoted);
1613 if (quoted != strace_env)
1614 free((char *)quoted);
1615 strbuf_insert(&args, 0, buf.buf, buf.len);
1616 strbuf_release(&buf);
1620 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1621 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1622 strbuf_release(&args);
1624 wenvblk = make_environment_block(deltaenv);
1626 memset(&pi, 0, sizeof(pi));
1627 if (restrict_handle_inheritance && stdhandles_count &&
1628 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1629 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1630 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1631 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1632 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1633 UpdateProcThreadAttribute(attr_list, 0,
1634 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1636 stdhandles_count * sizeof(HANDLE),
1638 si.lpAttributeList = attr_list;
1639 flags |= EXTENDED_STARTUPINFO_PRESENT;
1642 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1643 stdhandles_count ? TRUE : FALSE,
1644 flags, wenvblk, dir ? wdir : NULL,
1645 &si.StartupInfo, &pi);
1648 * On Windows 2008 R2, it seems that specifying certain types of handles
1649 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1650 * error. Rather than playing finicky and fragile games, let's just try
1651 * to detect this situation and simply try again without restricting any
1652 * handle inheritance. This is still better than failing to create
1655 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1656 DWORD err = GetLastError();
1657 struct strbuf buf = STRBUF_INIT;
1659 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1661 * On Windows 7 and earlier, handles on pipes and character
1662 * devices are inherited automatically, and cannot be
1663 * specified in the thread handle list. Rather than trying
1664 * to catch each and every corner case (and running the
1665 * chance of *still* forgetting a few), let's just fall
1666 * back to creating the process without trying to limit the
1667 * handle inheritance.
1669 !(err == ERROR_INVALID_PARAMETER &&
1670 GetVersion() >> 16 < 9200) &&
1671 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1675 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1677 for (i = 0; i < stdhandles_count; i++) {
1678 HANDLE h = stdhandles[i];
1679 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1680 "handle info (%d) %lx\n", i, h,
1682 GetHandleInformation(h, &fl),
1685 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1686 "at\nhttps://github.com/git-for-windows/"
1687 "git/issues/new\n\n"
1688 "To suppress this warning, please set "
1689 "the environment variable\n\n"
1690 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1693 restrict_handle_inheritance = 0;
1694 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1695 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1696 TRUE, flags, wenvblk, dir ? wdir : NULL,
1697 &si.StartupInfo, &pi);
1699 errno = err_win_to_posix(GetLastError());
1700 if (ret && buf.len) {
1701 warning("failed to restrict file handles (%ld)\n\n%s",
1704 strbuf_release(&buf);
1706 errno = err_win_to_posix(GetLastError());
1708 if (si.lpAttributeList)
1709 DeleteProcThreadAttributeList(si.lpAttributeList);
1711 HeapFree(GetProcessHeap(), 0, attr_list);
1719 CloseHandle(pi.hThread);
1722 * The process ID is the human-readable identifier of the process
1723 * that we want to present in log and error messages. The handle
1724 * is not useful for this purpose. But we cannot close it, either,
1725 * because it is not possible to turn a process ID into a process
1726 * handle after the process terminated.
1727 * Keep the handle in a list for waitpid.
1729 EnterCriticalSection(&pinfo_cs);
1731 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1732 info->pid = pi.dwProcessId;
1733 info->proc = pi.hProcess;
1737 LeaveCriticalSection(&pinfo_cs);
1739 return (pid_t)pi.dwProcessId;
1742 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1744 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1747 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1749 int fhin, int fhout, int fherr)
1752 char *prog = path_lookup(cmd, 0);
1759 const char *interpr = parse_interpreter(prog);
1762 const char *argv0 = argv[0];
1763 char *iprog = path_lookup(interpr, 1);
1770 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1771 fhin, fhout, fherr);
1777 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1778 fhin, fhout, fherr);
1784 static int try_shell_exec(const char *cmd, char *const *argv)
1786 const char *interpr = parse_interpreter(cmd);
1792 prog = path_lookup(interpr, 1);
1800 while (argv[argc]) argc++;
1801 ALLOC_ARRAY(argv2, argc + 1);
1802 argv2[0] = (char *)cmd; /* full path to the script file */
1803 COPY_ARRAY(&argv2[1], &argv[1], argc);
1804 exec_id = trace2_exec(prog, argv2);
1805 pid = mingw_spawnv(prog, argv2, 1);
1808 if (waitpid(pid, &status, 0) < 0)
1810 trace2_exec_result(exec_id, status);
1813 trace2_exec_result(exec_id, -1);
1814 pid = 1; /* indicate that we tried but failed */
1821 int mingw_execv(const char *cmd, char *const *argv)
1823 /* check if git_command is a shell script */
1824 if (!try_shell_exec(cmd, argv)) {
1828 exec_id = trace2_exec(cmd, (const char **)argv);
1829 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1831 trace2_exec_result(exec_id, -1);
1834 if (waitpid(pid, &status, 0) < 0)
1836 trace2_exec_result(exec_id, status);
1842 int mingw_execvp(const char *cmd, char *const *argv)
1844 char *prog = path_lookup(cmd, 0);
1847 mingw_execv(prog, argv);
1855 int mingw_kill(pid_t pid, int sig)
1857 if (pid > 0 && sig == SIGTERM) {
1858 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1860 if (TerminateProcess(h, -1)) {
1865 errno = err_win_to_posix(GetLastError());
1868 } else if (pid > 0 && sig == 0) {
1869 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1881 * UTF-8 versions of getenv(), putenv() and unsetenv().
1882 * Internally, they use the CRT's stock UNICODE routines
1883 * to avoid data loss.
1885 char *mingw_getenv(const char *name)
1887 #define GETENV_MAX_RETAIN 64
1888 static char *values[GETENV_MAX_RETAIN];
1889 static int value_counter;
1890 int len_key, len_value;
1893 wchar_t w_value[32768];
1895 if (!name || !*name)
1898 len_key = strlen(name) + 1;
1899 /* We cannot use xcalloc() here because that uses getenv() itself */
1900 w_key = calloc(len_key, sizeof(wchar_t));
1902 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1903 xutftowcs(w_key, name, len_key);
1904 /* GetEnvironmentVariableW() only sets the last error upon failure */
1905 SetLastError(ERROR_SUCCESS);
1906 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1907 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1913 len_value = len_value * 3 + 1;
1914 /* We cannot use xcalloc() here because that uses getenv() itself */
1915 value = calloc(len_value, sizeof(char));
1917 die("Out of memory, (tried to allocate %u bytes)", len_value);
1918 xwcstoutf(value, w_value, len_value);
1921 * We return `value` which is an allocated value and the caller is NOT
1922 * expecting to have to free it, so we keep a round-robin array,
1923 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1925 free(values[value_counter]);
1926 values[value_counter++] = value;
1927 if (value_counter >= ARRAY_SIZE(values))
1933 int mingw_putenv(const char *namevalue)
1936 wchar_t *wide, *equal;
1939 if (!namevalue || !*namevalue)
1942 size = strlen(namevalue) * 2 + 1;
1943 wide = calloc(size, sizeof(wchar_t));
1945 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1946 xutftowcs(wide, namevalue, size);
1947 equal = wcschr(wide, L'=');
1949 result = SetEnvironmentVariableW(wide, NULL);
1952 result = SetEnvironmentVariableW(wide, equal + 1);
1957 errno = err_win_to_posix(GetLastError());
1959 return result ? 0 : -1;
1962 static void ensure_socket_initialization(void)
1965 static int initialized = 0;
1970 if (WSAStartup(MAKEWORD(2,2), &wsa))
1971 die("unable to initialize winsock subsystem, error %d",
1974 atexit((void(*)(void)) WSACleanup);
1979 int mingw_gethostname(char *name, int namelen)
1981 ensure_socket_initialization();
1982 return gethostname(name, namelen);
1985 #undef gethostbyname
1986 struct hostent *mingw_gethostbyname(const char *host)
1988 ensure_socket_initialization();
1989 return gethostbyname(host);
1993 int mingw_getaddrinfo(const char *node, const char *service,
1994 const struct addrinfo *hints, struct addrinfo **res)
1996 ensure_socket_initialization();
1997 return getaddrinfo(node, service, hints, res);
2000 int mingw_socket(int domain, int type, int protocol)
2005 ensure_socket_initialization();
2006 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2007 if (s == INVALID_SOCKET) {
2009 * WSAGetLastError() values are regular BSD error codes
2010 * biased by WSABASEERR.
2011 * However, strerror() does not know about networking
2012 * specific errors, which are values beginning at 38 or so.
2013 * Therefore, we choose to leave the biased error code
2014 * in errno so that _if_ someone looks up the code somewhere,
2015 * then it is at least the number that are usually listed.
2017 errno = WSAGetLastError();
2020 /* convert into a file descriptor */
2021 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2023 return error("unable to make a socket file descriptor: %s",
2030 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2032 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2033 return connect(s, sa, sz);
2037 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2039 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2040 return bind(s, sa, sz);
2044 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2046 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2047 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2051 int mingw_shutdown(int sockfd, int how)
2053 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2054 return shutdown(s, how);
2058 int mingw_listen(int sockfd, int backlog)
2060 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2061 return listen(s, backlog);
2065 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2069 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2070 SOCKET s2 = accept(s1, sa, sz);
2072 /* convert into a file descriptor */
2073 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2076 return error("unable to make a socket file descriptor: %s",
2083 int mingw_rename(const char *pold, const char *pnew)
2087 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2088 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2092 * Try native rename() first to get errno right.
2093 * It is based on MoveFile(), which cannot overwrite existing files.
2095 if (!_wrename(wpold, wpnew))
2097 if (errno != EEXIST)
2100 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2102 /* TODO: translate more errors */
2103 gle = GetLastError();
2104 if (gle == ERROR_ACCESS_DENIED &&
2105 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2106 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2107 DWORD attrsold = GetFileAttributesW(wpold);
2108 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2109 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2111 else if (!_wrmdir(wpnew))
2115 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2116 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2117 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2119 gle = GetLastError();
2120 /* revert file attributes on failure */
2121 SetFileAttributesW(wpnew, attrs);
2124 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2126 * We assume that some other process had the source or
2127 * destination file open at the wrong moment and retry.
2128 * In order to give the other process a higher chance to
2129 * complete its operation, we give up our time slice now.
2130 * If we have to retry again, we do sleep a bit.
2132 Sleep(delay[tries]);
2136 if (gle == ERROR_ACCESS_DENIED &&
2137 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2138 "Should I try again?", pold, pnew))
2146 * Note that this doesn't return the actual pagesize, but
2147 * the allocation granularity. If future Windows specific git code
2148 * needs the real getpagesize function, we need to find another solution.
2150 int mingw_getpagesize(void)
2154 return si.dwAllocationGranularity;
2157 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2158 enum EXTENDED_NAME_FORMAT {
2160 NameUserPrincipal = 8
2163 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2165 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2166 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2167 static wchar_t wbuffer[1024];
2170 if (!INIT_PROC_ADDR(GetUserNameExW))
2173 len = ARRAY_SIZE(wbuffer);
2174 if (GetUserNameExW(type, wbuffer, &len)) {
2175 char *converted = xmalloc((len *= 3));
2176 if (xwcstoutf(converted, wbuffer, len) >= 0)
2184 char *mingw_query_user_email(void)
2186 return get_extended_user_info(NameUserPrincipal);
2189 struct passwd *getpwuid(int uid)
2191 static unsigned initialized;
2192 static char user_name[100];
2193 static struct passwd *p;
2200 len = ARRAY_SIZE(buf);
2201 if (!GetUserNameW(buf, &len)) {
2206 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2211 p = xmalloc(sizeof(*p));
2212 p->pw_name = user_name;
2213 p->pw_gecos = get_extended_user_info(NameDisplay);
2215 p->pw_gecos = "unknown";
2222 static HANDLE timer_event;
2223 static HANDLE timer_thread;
2224 static int timer_interval;
2225 static int one_shot;
2226 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2228 /* The timer works like this:
2229 * The thread, ticktack(), is a trivial routine that most of the time
2230 * only waits to receive the signal to terminate. The main thread tells
2231 * the thread to terminate by setting the timer_event to the signalled
2233 * But ticktack() interrupts the wait state after the timer's interval
2234 * length to call the signal handler.
2237 static unsigned __stdcall ticktack(void *dummy)
2239 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2240 mingw_raise(SIGALRM);
2247 static int start_timer_thread(void)
2249 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2251 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2253 return errno = ENOMEM,
2254 error("cannot start timer thread");
2256 return errno = ENOMEM,
2257 error("cannot allocate resources for timer");
2261 static void stop_timer_thread(void)
2264 SetEvent(timer_event); /* tell thread to terminate */
2266 int rc = WaitForSingleObject(timer_thread, 10000);
2267 if (rc == WAIT_TIMEOUT)
2268 error("timer thread did not terminate timely");
2269 else if (rc != WAIT_OBJECT_0)
2270 error("waiting for timer thread failed: %lu",
2272 CloseHandle(timer_thread);
2275 CloseHandle(timer_event);
2277 timer_thread = NULL;
2280 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2282 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2285 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2287 static const struct timeval zero;
2288 static int atexit_done;
2291 return errno = EINVAL,
2292 error("setitimer param 3 != NULL not implemented");
2293 if (!is_timeval_eq(&in->it_interval, &zero) &&
2294 !is_timeval_eq(&in->it_interval, &in->it_value))
2295 return errno = EINVAL,
2296 error("setitimer: it_interval must be zero or eq it_value");
2299 stop_timer_thread();
2301 if (is_timeval_eq(&in->it_value, &zero) &&
2302 is_timeval_eq(&in->it_interval, &zero))
2305 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2306 one_shot = is_timeval_eq(&in->it_interval, &zero);
2308 atexit(stop_timer_thread);
2311 return start_timer_thread();
2314 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2317 return errno = EINVAL,
2318 error("sigaction only implemented for SIGALRM");
2320 return errno = EINVAL,
2321 error("sigaction: param 3 != NULL not implemented");
2323 timer_fn = in->sa_handler;
2328 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2340 sigint_fn = handler;
2344 return signal(sig, handler);
2351 int mingw_raise(int sig)
2355 if (timer_fn == SIG_DFL) {
2356 if (isatty(STDERR_FILENO))
2357 fputs("Alarm clock\n", stderr);
2358 exit(128 + SIGALRM);
2359 } else if (timer_fn != SIG_IGN)
2364 if (sigint_fn == SIG_DFL)
2366 else if (sigint_fn != SIG_IGN)
2370 #if defined(_MSC_VER)
2377 case SIGABRT_COMPAT:
2379 * The <signal.h> header in the MS C Runtime defines 8 signals
2380 * as being supported on the platform. Anything else causes an
2381 * "Invalid signal or error" (which in DEBUG builds causes the
2382 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2383 * already know will fail.
2400 int link(const char *oldpath, const char *newpath)
2402 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2403 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2404 xutftowcs_path(wnewpath, newpath) < 0)
2407 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2408 errno = err_win_to_posix(GetLastError());
2414 pid_t waitpid(pid_t pid, int *status, int options)
2416 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2423 if (pid > 0 && options & WNOHANG) {
2424 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2428 options &= ~WNOHANG;
2432 struct pinfo_t **ppinfo;
2433 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2439 GetExitCodeProcess(h, (LPDWORD)status);
2441 EnterCriticalSection(&pinfo_cs);
2445 struct pinfo_t *info = *ppinfo;
2446 if (info->pid == pid) {
2447 CloseHandle(info->proc);
2448 *ppinfo = info->next;
2452 ppinfo = &info->next;
2455 LeaveCriticalSection(&pinfo_cs);
2466 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2468 int upos = 0, wpos = 0;
2469 const unsigned char *utf = (const unsigned char*) utfs;
2470 if (!utf || !wcs || wcslen < 1) {
2474 /* reserve space for \0 */
2479 while (upos < utflen) {
2480 int c = utf[upos++] & 0xff;
2481 if (utflen == INT_MAX && c == 0)
2484 if (wpos >= wcslen) {
2493 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2494 (utf[upos] & 0xc0) == 0x80) {
2496 c = ((c & 0x1f) << 6);
2497 c |= (utf[upos++] & 0x3f);
2499 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2500 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2501 (utf[upos] & 0xc0) == 0x80 &&
2502 (utf[upos + 1] & 0xc0) == 0x80) {
2504 c = ((c & 0x0f) << 12);
2505 c |= ((utf[upos++] & 0x3f) << 6);
2506 c |= (utf[upos++] & 0x3f);
2508 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2509 wpos + 1 < wcslen &&
2510 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2511 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2512 (utf[upos] & 0xc0) == 0x80 &&
2513 (utf[upos + 1] & 0xc0) == 0x80 &&
2514 (utf[upos + 2] & 0xc0) == 0x80) {
2515 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2516 c = ((c & 0x07) << 18);
2517 c |= ((utf[upos++] & 0x3f) << 12);
2518 c |= ((utf[upos++] & 0x3f) << 6);
2519 c |= (utf[upos++] & 0x3f);
2521 wcs[wpos++] = 0xd800 | (c >> 10);
2522 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2523 } else if (c >= 0xa0) {
2524 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2527 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2528 static const char *hex = "0123456789abcdef";
2529 wcs[wpos++] = hex[c >> 4];
2531 wcs[wpos++] = hex[c & 0x0f];
2538 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2540 if (!wcs || !utf || utflen < 1) {
2544 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2551 static void setup_windows_environment(void)
2553 char *tmp = getenv("TMPDIR");
2555 /* on Windows it is TMP and TEMP */
2557 if (!(tmp = getenv("TMP")))
2558 tmp = getenv("TEMP");
2560 setenv("TMPDIR", tmp, 1);
2561 tmp = getenv("TMPDIR");
2567 * Convert all dir separators to forward slashes,
2568 * to help shell commands called from the Git
2569 * executable (by not mistaking the dir separators
2570 * for escape characters).
2572 convert_slashes(tmp);
2575 /* simulate TERM to enable auto-color (see color.c) */
2576 if (!getenv("TERM"))
2577 setenv("TERM", "cygwin", 1);
2579 /* calculate HOME if not set */
2580 if (!getenv("HOME")) {
2582 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2583 * location, thus also check if the path exists (i.e. is not
2586 if ((tmp = getenv("HOMEDRIVE"))) {
2587 struct strbuf buf = STRBUF_INIT;
2588 strbuf_addstr(&buf, tmp);
2589 if ((tmp = getenv("HOMEPATH"))) {
2590 strbuf_addstr(&buf, tmp);
2591 if (is_directory(buf.buf))
2592 setenv("HOME", buf.buf, 1);
2594 tmp = NULL; /* use $USERPROFILE */
2596 strbuf_release(&buf);
2598 /* use $USERPROFILE if the home share is not available */
2599 if (!tmp && (tmp = getenv("USERPROFILE")))
2600 setenv("HOME", tmp, 1);
2604 int is_valid_win32_path(const char *path, int allow_literal_nul)
2606 const char *p = path;
2607 int preceding_space_or_period = 0, i = 0, periods = 0;
2612 skip_dos_drive_prefix((char **)&path);
2619 case '/': case '\\':
2620 /* cannot end in ` ` or `.`, except for `.` and `..` */
2621 if (preceding_space_or_period &&
2622 (i != periods || periods > 2))
2627 i = periods = preceding_space_or_period = 0;
2631 case 'a': case 'A': /* AUX */
2632 if (((c = path[++i]) != 'u' && c != 'U') ||
2633 ((c = path[++i]) != 'x' && c != 'X')) {
2634 not_a_reserved_name:
2640 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2641 if ((c = path[++i]) != 'o' && c != 'O')
2642 goto not_a_reserved_name;
2644 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2646 if (c < '1' || c > '9')
2647 goto not_a_reserved_name;
2648 } else if (c == 'n' || c == 'N') { /* CON */
2650 if ((c == 'i' || c == 'I') &&
2651 ((c = path[i + 2]) == 'n' ||
2654 i += 3; /* CONIN$ */
2655 else if ((c == 'o' || c == 'O') &&
2656 ((c = path[i + 2]) == 'u' ||
2658 ((c = path[i + 3]) == 't' ||
2661 i += 4; /* CONOUT$ */
2663 goto not_a_reserved_name;
2665 case 'l': case 'L': /* LPT<N> */
2666 if (((c = path[++i]) != 'p' && c != 'P') ||
2667 ((c = path[++i]) != 't' && c != 'T') ||
2668 !isdigit(path[++i]))
2669 goto not_a_reserved_name;
2671 case 'n': case 'N': /* NUL */
2672 if (((c = path[++i]) != 'u' && c != 'U') ||
2673 ((c = path[++i]) != 'l' && c != 'L') ||
2674 (allow_literal_nul &&
2675 !path[i + 1] && p == path))
2676 goto not_a_reserved_name;
2678 case 'p': case 'P': /* PRN */
2679 if (((c = path[++i]) != 'r' && c != 'R') ||
2680 ((c = path[++i]) != 'n' && c != 'N'))
2681 goto not_a_reserved_name;
2688 * So far, this looks like a reserved name. Let's see
2689 * whether it actually is one: trailing spaces, a file
2690 * extension, or an NTFS Alternate Data Stream do not
2691 * matter, the name is still reserved if any of those
2692 * follow immediately after the actual name.
2695 if (path[i] == ' ') {
2696 preceding_space_or_period = 1;
2697 while (path[++i] == ' ')
2698 ; /* skip all spaces */
2702 if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2703 goto not_a_reserved_name;
2705 /* contains reserved name */
2711 preceding_space_or_period = 1;
2714 case ':': /* DOS drive prefix was already skipped */
2715 case '<': case '>': case '"': case '|': case '?': case '*':
2716 /* illegal character */
2719 if (c > '\0' && c < '\x20')
2720 /* illegal character */
2723 preceding_space_or_period = 0;
2728 #if !defined(_MSC_VER)
2730 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2731 * mingw startup code, see init.c in mingw runtime).
2736 static NORETURN void die_startup(void)
2738 fputs("fatal: not enough memory for initialization", stderr);
2742 static void *malloc_startup(size_t size)
2744 void *result = malloc(size);
2750 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2752 len = xwcstoutf(buffer, wcs, len) + 1;
2753 return memcpy(malloc_startup(len), buffer, len);
2756 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2757 DWORD desired_access, DWORD flags)
2759 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2760 wchar_t buf[MAX_PATH];
2761 DWORD max = ARRAY_SIZE(buf);
2763 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2765 if (!ret || ret >= max)
2768 /* make sure this does not leak into child processes */
2769 SetEnvironmentVariableW(key, NULL);
2770 if (!wcscmp(buf, L"off")) {
2772 handle = GetStdHandle(std_id);
2773 if (handle != INVALID_HANDLE_VALUE)
2774 CloseHandle(handle);
2777 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2778 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2779 if (handle == INVALID_HANDLE_VALUE) {
2781 handle = GetStdHandle(std_id);
2782 if (handle != INVALID_HANDLE_VALUE)
2783 CloseHandle(handle);
2785 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2786 SetStdHandle(std_id, handle);
2788 /* do *not* close the new_fd: that would close stdout */
2792 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2794 if (handle != INVALID_HANDLE_VALUE) {
2795 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2796 SetStdHandle(std_id, handle);
2802 static void maybe_redirect_std_handles(void)
2804 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2805 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2806 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2807 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2808 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2809 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2819 * We implement wmain() and compile with -municode, which would
2820 * normally ignore main(), but we call the latter from the former
2821 * so that we can handle non-ASCII command-line parameters
2824 * To be more compatible with the core git code, we convert
2825 * argv into UTF8 and pass them directly to main().
2827 int wmain(int argc, const wchar_t **wargv)
2829 int i, maxlen, exit_status;
2830 char *buffer, **save;
2833 trace2_initialize_clock();
2837 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2840 #ifdef USE_MSVC_CRTDBG
2841 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2845 maybe_redirect_std_handles();
2847 /* determine size of argv and environ conversion buffer */
2848 maxlen = wcslen(wargv[0]);
2849 for (i = 1; i < argc; i++)
2850 maxlen = max(maxlen, wcslen(wargv[i]));
2852 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2853 maxlen = 3 * maxlen + 1;
2854 buffer = malloc_startup(maxlen);
2857 * Create a UTF-8 version of w_argv. Also create a "save" copy
2858 * to remember all the string pointers because parse_options()
2859 * will remove claimed items from the argv that we pass down.
2861 ALLOC_ARRAY(argv, argc + 1);
2862 ALLOC_ARRAY(save, argc + 1);
2863 for (i = 0; i < argc; i++)
2864 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2865 argv[i] = save[i] = NULL;
2868 /* fix Windows specific environment settings */
2869 setup_windows_environment();
2871 unset_environment_variables = xstrdup("PERL5LIB");
2873 /* initialize critical section for waitpid pinfo_t list */
2874 InitializeCriticalSection(&pinfo_cs);
2876 /* set up default file mode and file modes for stdin/out/err */
2878 _setmode(_fileno(stdin), _O_BINARY);
2879 _setmode(_fileno(stdout), _O_BINARY);
2880 _setmode(_fileno(stderr), _O_BINARY);
2882 /* initialize Unicode console */
2885 /* invoke the real main() using our utf8 version of argv. */
2886 exit_status = main(argc, argv);
2888 for (i = 0; i < argc; i++)
2896 int uname(struct utsname *buf)
2898 unsigned v = (unsigned)GetVersion();
2899 memset(buf, 0, sizeof(*buf));
2900 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2901 xsnprintf(buf->release, sizeof(buf->release),
2902 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2903 /* assuming NT variants only.. */
2904 xsnprintf(buf->version, sizeof(buf->version),
2905 "%u", (v >> 16) & 0x7fff);