Merge branch 'rs/archive-with-attr-pathspec-fix'
[git/gitster.git] / compat / mingw.c
blob0e851ecae29b90347bde8c40c6c0bb9b3c1d5597
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "../git-compat-util.h"
4 #include "win32.h"
5 #include <aclapi.h>
6 #include <sddl.h>
7 #include <conio.h>
8 #include <wchar.h>
9 #include "../strbuf.h"
10 #include "../run-command.h"
11 #include "../abspath.h"
12 #include "../alloc.h"
13 #include "win32/lazyload.h"
14 #include "../config.h"
15 #include "../environment.h"
16 #include "../trace2.h"
17 #include "../symlinks.h"
18 #include "../wrapper.h"
19 #include "dir.h"
20 #include "gettext.h"
21 #define SECURITY_WIN32
22 #include <sspi.h>
24 #define HCAST(type, handle) ((type)(intptr_t)handle)
26 static const int delay[] = { 0, 1, 10, 20, 40 };
28 void open_in_gdb(void)
30 static struct child_process cp = CHILD_PROCESS_INIT;
32 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
33 strvec_pushf(&cp.args, "--pid=%d", getpid());
34 cp.clean_on_exit = 1;
35 if (start_command(&cp) < 0)
36 die_errno("Could not start gdb");
37 sleep(1);
40 int err_win_to_posix(DWORD winerr)
42 int error = ENOSYS;
43 switch(winerr) {
44 case ERROR_ACCESS_DENIED: error = EACCES; break;
45 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
46 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
47 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
48 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
49 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
50 case ERROR_BAD_COMMAND: error = EIO; break;
51 case ERROR_BAD_DEVICE: error = ENODEV; break;
52 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
53 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
54 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
55 case ERROR_BAD_LENGTH: error = EINVAL; break;
56 case ERROR_BAD_PATHNAME: error = ENOENT; break;
57 case ERROR_BAD_PIPE: error = EPIPE; break;
58 case ERROR_BAD_UNIT: error = ENODEV; break;
59 case ERROR_BAD_USERNAME: error = EINVAL; break;
60 case ERROR_BROKEN_PIPE: error = EPIPE; break;
61 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
62 case ERROR_BUSY: error = EBUSY; break;
63 case ERROR_BUSY_DRIVE: error = EBUSY; break;
64 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
65 case ERROR_CANNOT_MAKE: error = EACCES; break;
66 case ERROR_CANTOPEN: error = EIO; break;
67 case ERROR_CANTREAD: error = EIO; break;
68 case ERROR_CANTWRITE: error = EIO; break;
69 case ERROR_CRC: error = EIO; break;
70 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
71 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
72 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
73 case ERROR_DIRECTORY: error = EINVAL; break;
74 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
75 case ERROR_DISK_CHANGE: error = EIO; break;
76 case ERROR_DISK_FULL: error = ENOSPC; break;
77 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
78 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
79 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
80 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
81 case ERROR_FILE_EXISTS: error = EEXIST; break;
82 case ERROR_FILE_INVALID: error = ENODEV; break;
83 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
84 case ERROR_GEN_FAILURE: error = EIO; break;
85 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
86 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
87 case ERROR_INVALID_ACCESS: error = EACCES; break;
88 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
89 case ERROR_INVALID_BLOCK: error = EFAULT; break;
90 case ERROR_INVALID_DATA: error = EINVAL; break;
91 case ERROR_INVALID_DRIVE: error = ENODEV; break;
92 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
93 case ERROR_INVALID_FLAGS: error = EINVAL; break;
94 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
95 case ERROR_INVALID_HANDLE: error = EBADF; break;
96 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
97 case ERROR_INVALID_NAME: error = EINVAL; break;
98 case ERROR_INVALID_OWNER: error = EINVAL; break;
99 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
100 case ERROR_INVALID_PASSWORD: error = EPERM; break;
101 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
102 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
103 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
104 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
105 case ERROR_IO_DEVICE: error = EIO; break;
106 case ERROR_IO_INCOMPLETE: error = EINTR; break;
107 case ERROR_LOCKED: error = EBUSY; break;
108 case ERROR_LOCK_VIOLATION: error = EACCES; break;
109 case ERROR_LOGON_FAILURE: error = EACCES; break;
110 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
111 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
112 case ERROR_MORE_DATA: error = EPIPE; break;
113 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
114 case ERROR_NOACCESS: error = EFAULT; break;
115 case ERROR_NONE_MAPPED: error = EINVAL; break;
116 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
117 case ERROR_NOT_READY: error = EAGAIN; break;
118 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
119 case ERROR_NO_DATA: error = EPIPE; break;
120 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
121 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
122 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
123 case ERROR_OPEN_FAILED: error = EIO; break;
124 case ERROR_OPEN_FILES: error = EBUSY; break;
125 case ERROR_OPERATION_ABORTED: error = EINTR; break;
126 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
127 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
128 case ERROR_PATH_BUSY: error = EBUSY; break;
129 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
130 case ERROR_PIPE_BUSY: error = EBUSY; break;
131 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
132 case ERROR_PIPE_LISTENING: error = EPIPE; break;
133 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
134 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
135 case ERROR_READ_FAULT: error = EIO; break;
136 case ERROR_SEEK: error = EIO; break;
137 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
138 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
139 case ERROR_SHARING_VIOLATION: error = EACCES; break;
140 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
141 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
142 case ERROR_SWAPERROR: error = ENOENT; break;
143 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
144 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
145 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
146 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
147 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
148 case ERROR_WRITE_FAULT: error = EIO; break;
149 case ERROR_WRITE_PROTECT: error = EROFS; break;
151 return error;
154 static inline int is_file_in_use_error(DWORD errcode)
156 switch (errcode) {
157 case ERROR_SHARING_VIOLATION:
158 case ERROR_ACCESS_DENIED:
159 return 1;
162 return 0;
165 static int read_yes_no_answer(void)
167 char answer[1024];
169 if (fgets(answer, sizeof(answer), stdin)) {
170 size_t answer_len = strlen(answer);
171 int got_full_line = 0, c;
173 /* remove the newline */
174 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
175 answer[answer_len-2] = '\0';
176 got_full_line = 1;
177 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
178 answer[answer_len-1] = '\0';
179 got_full_line = 1;
181 /* flush the buffer in case we did not get the full line */
182 if (!got_full_line)
183 while ((c = getchar()) != EOF && c != '\n')
185 } else
186 /* we could not read, return the
187 * default answer which is no */
188 return 0;
190 if (tolower(answer[0]) == 'y' && !answer[1])
191 return 1;
192 if (!strncasecmp(answer, "yes", sizeof(answer)))
193 return 1;
194 if (tolower(answer[0]) == 'n' && !answer[1])
195 return 0;
196 if (!strncasecmp(answer, "no", sizeof(answer)))
197 return 0;
199 /* did not find an answer we understand */
200 return -1;
203 static int ask_yes_no_if_possible(const char *format, ...)
205 char question[4096];
206 const char *retry_hook;
207 va_list args;
209 va_start(args, format);
210 vsnprintf(question, sizeof(question), format, args);
211 va_end(args);
213 retry_hook = mingw_getenv("GIT_ASK_YESNO");
214 if (retry_hook) {
215 struct child_process cmd = CHILD_PROCESS_INIT;
217 strvec_pushl(&cmd.args, retry_hook, question, NULL);
218 return !run_command(&cmd);
221 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
222 return 0;
224 while (1) {
225 int answer;
226 fprintf(stderr, "%s (y/n) ", question);
228 if ((answer = read_yes_no_answer()) >= 0)
229 return answer;
231 fprintf(stderr, "Sorry, I did not understand your answer. "
232 "Please type 'y' or 'n'\n");
236 /* Windows only */
237 enum hide_dotfiles_type {
238 HIDE_DOTFILES_FALSE = 0,
239 HIDE_DOTFILES_TRUE,
240 HIDE_DOTFILES_DOTGITONLY
243 static int core_restrict_inherited_handles = -1;
244 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
245 static char *unset_environment_variables;
247 int mingw_core_config(const char *var, const char *value,
248 const struct config_context *ctx UNUSED,
249 void *cb UNUSED)
251 if (!strcmp(var, "core.hidedotfiles")) {
252 if (value && !strcasecmp(value, "dotgitonly"))
253 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
254 else
255 hide_dotfiles = git_config_bool(var, value);
256 return 0;
259 if (!strcmp(var, "core.unsetenvvars")) {
260 if (!value)
261 return config_error_nonbool(var);
262 free(unset_environment_variables);
263 unset_environment_variables = xstrdup(value);
264 return 0;
267 if (!strcmp(var, "core.restrictinheritedhandles")) {
268 if (value && !strcasecmp(value, "auto"))
269 core_restrict_inherited_handles = -1;
270 else
271 core_restrict_inherited_handles =
272 git_config_bool(var, value);
273 return 0;
276 return 0;
279 /* Normalizes NT paths as returned by some low-level APIs. */
280 static wchar_t *normalize_ntpath(wchar_t *wbuf)
282 int i;
283 /* fix absolute path prefixes */
284 if (wbuf[0] == '\\') {
285 /* strip NT namespace prefixes */
286 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
287 !wcsncmp(wbuf, L"\\\\?\\", 4))
288 wbuf += 4;
289 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
290 wbuf += 12;
291 /* replace remaining '...UNC\' with '\\' */
292 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
293 wbuf += 2;
294 *wbuf = '\\';
297 /* convert backslashes to slashes */
298 for (i = 0; wbuf[i]; i++)
299 if (wbuf[i] == '\\')
300 wbuf[i] = '/';
301 return wbuf;
304 int mingw_unlink(const char *pathname)
306 int ret, tries = 0;
307 wchar_t wpathname[MAX_PATH];
308 if (xutftowcs_path(wpathname, pathname) < 0)
309 return -1;
311 if (DeleteFileW(wpathname))
312 return 0;
314 /* read-only files cannot be removed */
315 _wchmod(wpathname, 0666);
316 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
317 if (!is_file_in_use_error(GetLastError()))
318 break;
320 * We assume that some other process had the source or
321 * destination file open at the wrong moment and retry.
322 * In order to give the other process a higher chance to
323 * complete its operation, we give up our time slice now.
324 * If we have to retry again, we do sleep a bit.
326 Sleep(delay[tries]);
327 tries++;
329 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
330 ask_yes_no_if_possible("Unlink of file '%s' failed. "
331 "Should I try again?", pathname))
332 ret = _wunlink(wpathname);
333 return ret;
336 static int is_dir_empty(const wchar_t *wpath)
338 WIN32_FIND_DATAW findbuf;
339 HANDLE handle;
340 wchar_t wbuf[MAX_PATH + 2];
341 wcscpy(wbuf, wpath);
342 wcscat(wbuf, L"\\*");
343 handle = FindFirstFileW(wbuf, &findbuf);
344 if (handle == INVALID_HANDLE_VALUE)
345 return GetLastError() == ERROR_NO_MORE_FILES;
347 while (!wcscmp(findbuf.cFileName, L".") ||
348 !wcscmp(findbuf.cFileName, L".."))
349 if (!FindNextFileW(handle, &findbuf)) {
350 DWORD err = GetLastError();
351 FindClose(handle);
352 return err == ERROR_NO_MORE_FILES;
354 FindClose(handle);
355 return 0;
358 int mingw_rmdir(const char *pathname)
360 int ret, tries = 0;
361 wchar_t wpathname[MAX_PATH];
362 struct stat st;
365 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
366 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
367 * symbolic link (if it points to a directory).
369 * This behavior breaks the assumption of e.g. `remove_path()` which
370 * upon successful deletion of a file will attempt to remove its parent
371 * directories recursively until failure (which usually happens when
372 * the directory is not empty).
374 * Therefore, before calling `_wrmdir()`, we first check if the path is
375 * a symbolic link. If it is, we exit and return the same error as
376 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
378 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
379 errno = ENOTDIR;
380 return -1;
383 if (xutftowcs_path(wpathname, pathname) < 0)
384 return -1;
386 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
387 if (!is_file_in_use_error(GetLastError()))
388 errno = err_win_to_posix(GetLastError());
389 if (errno != EACCES)
390 break;
391 if (!is_dir_empty(wpathname)) {
392 errno = ENOTEMPTY;
393 break;
396 * We assume that some other process had the source or
397 * destination file open at the wrong moment and retry.
398 * In order to give the other process a higher chance to
399 * complete its operation, we give up our time slice now.
400 * If we have to retry again, we do sleep a bit.
402 Sleep(delay[tries]);
403 tries++;
405 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
406 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
407 "Should I try again?", pathname))
408 ret = _wrmdir(wpathname);
409 if (!ret)
410 invalidate_lstat_cache();
411 return ret;
414 static inline int needs_hiding(const char *path)
416 const char *basename;
418 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
419 return 0;
421 /* We cannot use basename(), as it would remove trailing slashes */
422 win32_skip_dos_drive_prefix((char **)&path);
423 if (!*path)
424 return 0;
426 for (basename = path; *path; path++)
427 if (is_dir_sep(*path)) {
428 do {
429 path++;
430 } while (is_dir_sep(*path));
431 /* ignore trailing slashes */
432 if (*path)
433 basename = path;
434 else
435 break;
438 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
439 return *basename == '.';
441 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
442 return !strncasecmp(".git", basename, 4) &&
443 (!basename[4] || is_dir_sep(basename[4]));
446 static int set_hidden_flag(const wchar_t *path, int set)
448 DWORD original = GetFileAttributesW(path), modified;
449 if (set)
450 modified = original | FILE_ATTRIBUTE_HIDDEN;
451 else
452 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
453 if (original == modified || SetFileAttributesW(path, modified))
454 return 0;
455 errno = err_win_to_posix(GetLastError());
456 return -1;
459 int mingw_mkdir(const char *path, int mode UNUSED)
461 int ret;
462 wchar_t wpath[MAX_PATH];
464 if (!is_valid_win32_path(path, 0)) {
465 errno = EINVAL;
466 return -1;
469 if (xutftowcs_path(wpath, path) < 0)
470 return -1;
471 ret = _wmkdir(wpath);
472 if (!ret && needs_hiding(path))
473 return set_hidden_flag(wpath, 1);
474 return ret;
478 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
479 * is documented in [1] as opening a writable file handle in append mode.
480 * (It is believed that) this is atomic since it is maintained by the
481 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
483 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
485 * This trick does not appear to work for named pipes. Instead it creates
486 * a named pipe client handle that cannot be written to. Callers should
487 * just use the regular _wopen() for them. (And since client handle gets
488 * bound to a unique server handle, it isn't really an issue.)
490 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
492 HANDLE handle;
493 int fd;
494 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
496 /* only these flags are supported */
497 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
498 return errno = ENOSYS, -1;
501 * FILE_SHARE_WRITE is required to permit child processes
502 * to append to the file.
504 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
505 FILE_SHARE_WRITE | FILE_SHARE_READ,
506 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
507 if (handle == INVALID_HANDLE_VALUE) {
508 DWORD err = GetLastError();
511 * Some network storage solutions (e.g. Isilon) might return
512 * ERROR_INVALID_PARAMETER instead of expected error
513 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
514 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
516 if (err == ERROR_INVALID_PARAMETER)
517 err = ERROR_PATH_NOT_FOUND;
519 errno = err_win_to_posix(err);
520 return -1;
524 * No O_APPEND here, because the CRT uses it only to reset the
525 * file pointer to EOF before each write(); but that is not
526 * necessary (and may lead to races) for a file created with
527 * FILE_APPEND_DATA.
529 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
530 if (fd < 0)
531 CloseHandle(handle);
532 return fd;
536 * Does the pathname map to the local named pipe filesystem?
537 * That is, does it have a "//./pipe/" prefix?
539 static int is_local_named_pipe_path(const char *filename)
541 return (is_dir_sep(filename[0]) &&
542 is_dir_sep(filename[1]) &&
543 filename[2] == '.' &&
544 is_dir_sep(filename[3]) &&
545 !strncasecmp(filename+4, "pipe", 4) &&
546 is_dir_sep(filename[8]) &&
547 filename[9]);
550 int mingw_open (const char *filename, int oflags, ...)
552 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
553 va_list args;
554 unsigned mode;
555 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
556 wchar_t wfilename[MAX_PATH];
557 open_fn_t open_fn;
559 va_start(args, oflags);
560 mode = va_arg(args, int);
561 va_end(args);
563 if (!is_valid_win32_path(filename, !create)) {
564 errno = create ? EINVAL : ENOENT;
565 return -1;
568 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
569 open_fn = mingw_open_append;
570 else
571 open_fn = _wopen;
573 if (filename && !strcmp(filename, "/dev/null"))
574 wcscpy(wfilename, L"nul");
575 else if (xutftowcs_path(wfilename, filename) < 0)
576 return -1;
578 fd = open_fn(wfilename, oflags, mode);
580 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
581 DWORD attrs = GetFileAttributesW(wfilename);
582 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
583 errno = EISDIR;
585 if ((oflags & O_CREAT) && needs_hiding(filename)) {
587 * Internally, _wopen() uses the CreateFile() API which errors
588 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
589 * specified and an already existing file's attributes do not
590 * match *exactly*. As there is no mode or flag we can set that
591 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
592 * again *without* the O_CREAT flag (that corresponds to the
593 * CREATE_ALWAYS flag of CreateFile()).
595 if (fd < 0 && errno == EACCES)
596 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
597 if (fd >= 0 && set_hidden_flag(wfilename, 1))
598 warning("could not mark '%s' as hidden.", filename);
600 return fd;
603 static BOOL WINAPI ctrl_ignore(DWORD type UNUSED)
605 return TRUE;
608 #undef fgetc
609 int mingw_fgetc(FILE *stream)
611 int ch;
612 if (!isatty(_fileno(stream)))
613 return fgetc(stream);
615 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
616 while (1) {
617 ch = fgetc(stream);
618 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
619 break;
621 /* Ctrl+C was pressed, simulate SIGINT and retry */
622 mingw_raise(SIGINT);
624 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
625 return ch;
628 #undef fopen
629 FILE *mingw_fopen (const char *filename, const char *otype)
631 int hide = needs_hiding(filename);
632 FILE *file;
633 wchar_t wfilename[MAX_PATH], wotype[4];
634 if (filename && !strcmp(filename, "/dev/null"))
635 wcscpy(wfilename, L"nul");
636 else if (!is_valid_win32_path(filename, 1)) {
637 int create = otype && strchr(otype, 'w');
638 errno = create ? EINVAL : ENOENT;
639 return NULL;
640 } else if (xutftowcs_path(wfilename, filename) < 0)
641 return NULL;
643 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
644 return NULL;
646 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
647 error("could not unhide %s", filename);
648 return NULL;
650 file = _wfopen(wfilename, wotype);
651 if (!file && GetLastError() == ERROR_INVALID_NAME)
652 errno = ENOENT;
653 if (file && hide && set_hidden_flag(wfilename, 1))
654 warning("could not mark '%s' as hidden.", filename);
655 return file;
658 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
660 int hide = needs_hiding(filename);
661 FILE *file;
662 wchar_t wfilename[MAX_PATH], wotype[4];
663 if (filename && !strcmp(filename, "/dev/null"))
664 wcscpy(wfilename, L"nul");
665 else if (!is_valid_win32_path(filename, 1)) {
666 int create = otype && strchr(otype, 'w');
667 errno = create ? EINVAL : ENOENT;
668 return NULL;
669 } else if (xutftowcs_path(wfilename, filename) < 0)
670 return NULL;
672 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
673 return NULL;
675 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
676 error("could not unhide %s", filename);
677 return NULL;
679 file = _wfreopen(wfilename, wotype, stream);
680 if (file && hide && set_hidden_flag(wfilename, 1))
681 warning("could not mark '%s' as hidden.", filename);
682 return file;
685 #undef fflush
686 int mingw_fflush(FILE *stream)
688 int ret = fflush(stream);
691 * write() is used behind the scenes of stdio output functions.
692 * Since git code does not check for errors after each stdio write
693 * operation, it can happen that write() is called by a later
694 * stdio function even if an earlier write() call failed. In the
695 * case of a pipe whose readable end was closed, only the first
696 * call to write() reports EPIPE on Windows. Subsequent write()
697 * calls report EINVAL. It is impossible to notice whether this
698 * fflush invocation triggered such a case, therefore, we have to
699 * catch all EINVAL errors whole-sale.
701 if (ret && errno == EINVAL)
702 errno = EPIPE;
704 return ret;
707 #undef write
708 ssize_t mingw_write(int fd, const void *buf, size_t len)
710 ssize_t result = write(fd, buf, len);
712 if (result < 0 && (errno == EINVAL || errno == ENOSPC) && buf) {
713 int orig = errno;
715 /* check if fd is a pipe */
716 HANDLE h = (HANDLE) _get_osfhandle(fd);
717 if (GetFileType(h) != FILE_TYPE_PIPE)
718 errno = orig;
719 else if (orig == EINVAL)
720 errno = EPIPE;
721 else {
722 DWORD buf_size;
724 if (!GetNamedPipeInfo(h, NULL, NULL, &buf_size, NULL))
725 buf_size = 4096;
726 if (len > buf_size)
727 return write(fd, buf, buf_size);
728 errno = orig;
732 return result;
735 int mingw_access(const char *filename, int mode)
737 wchar_t wfilename[MAX_PATH];
738 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
739 return 0;
740 if (xutftowcs_path(wfilename, filename) < 0)
741 return -1;
742 /* X_OK is not supported by the MSVCRT version */
743 return _waccess(wfilename, mode & ~X_OK);
746 int mingw_chdir(const char *dirname)
748 wchar_t wdirname[MAX_PATH];
749 if (xutftowcs_path(wdirname, dirname) < 0)
750 return -1;
751 return _wchdir(wdirname);
754 int mingw_chmod(const char *filename, int mode)
756 wchar_t wfilename[MAX_PATH];
757 if (xutftowcs_path(wfilename, filename) < 0)
758 return -1;
759 return _wchmod(wfilename, mode);
763 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
764 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
766 static inline long long filetime_to_hnsec(const FILETIME *ft)
768 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
769 /* Windows to Unix Epoch conversion */
770 return winTime - 116444736000000000LL;
773 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
775 long long hnsec = filetime_to_hnsec(ft);
776 ts->tv_sec = (time_t)(hnsec / 10000000);
777 ts->tv_nsec = (hnsec % 10000000) * 100;
781 * Verifies that safe_create_leading_directories() would succeed.
783 static int has_valid_directory_prefix(wchar_t *wfilename)
785 int n = wcslen(wfilename);
787 while (n > 0) {
788 wchar_t c = wfilename[--n];
789 DWORD attributes;
791 if (!is_dir_sep(c))
792 continue;
794 wfilename[n] = L'\0';
795 attributes = GetFileAttributesW(wfilename);
796 wfilename[n] = c;
797 if (attributes &
798 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
799 return 1;
800 if (attributes == INVALID_FILE_ATTRIBUTES)
801 switch (GetLastError()) {
802 case ERROR_PATH_NOT_FOUND:
803 continue;
804 case ERROR_FILE_NOT_FOUND:
805 /* This implies parent directory exists. */
806 return 1;
808 return 0;
810 return 1;
813 /* We keep the do_lstat code in a separate function to avoid recursion.
814 * When a path ends with a slash, the stat will fail with ENOENT. In
815 * this case, we strip the trailing slashes and stat again.
817 * If follow is true then act like stat() and report on the link
818 * target. Otherwise report on the link itself.
820 static int do_lstat(int follow, const char *file_name, struct stat *buf)
822 WIN32_FILE_ATTRIBUTE_DATA fdata;
823 wchar_t wfilename[MAX_PATH];
824 if (xutftowcs_path(wfilename, file_name) < 0)
825 return -1;
827 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
828 buf->st_ino = 0;
829 buf->st_gid = 0;
830 buf->st_uid = 0;
831 buf->st_nlink = 1;
832 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
833 buf->st_size = fdata.nFileSizeLow |
834 (((off_t)fdata.nFileSizeHigh)<<32);
835 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
836 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
837 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
838 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
839 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
840 WIN32_FIND_DATAW findbuf;
841 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
842 if (handle != INVALID_HANDLE_VALUE) {
843 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
844 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
845 if (follow) {
846 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
847 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
848 } else {
849 buf->st_mode = S_IFLNK;
851 buf->st_mode |= S_IREAD;
852 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
853 buf->st_mode |= S_IWRITE;
855 FindClose(handle);
858 return 0;
860 switch (GetLastError()) {
861 case ERROR_ACCESS_DENIED:
862 case ERROR_SHARING_VIOLATION:
863 case ERROR_LOCK_VIOLATION:
864 case ERROR_SHARING_BUFFER_EXCEEDED:
865 errno = EACCES;
866 break;
867 case ERROR_BUFFER_OVERFLOW:
868 errno = ENAMETOOLONG;
869 break;
870 case ERROR_NOT_ENOUGH_MEMORY:
871 errno = ENOMEM;
872 break;
873 case ERROR_PATH_NOT_FOUND:
874 if (!has_valid_directory_prefix(wfilename)) {
875 errno = ENOTDIR;
876 break;
878 /* fallthru */
879 default:
880 errno = ENOENT;
881 break;
883 return -1;
886 /* We provide our own lstat/fstat functions, since the provided
887 * lstat/fstat functions are so slow. These stat functions are
888 * tailored for Git's usage (read: fast), and are not meant to be
889 * complete. Note that Git stat()s are redirected to mingw_lstat()
890 * too, since Windows doesn't really handle symlinks that well.
892 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
894 int namelen;
895 char alt_name[PATH_MAX];
897 if (!do_lstat(follow, file_name, buf))
898 return 0;
900 /* if file_name ended in a '/', Windows returned ENOENT;
901 * try again without trailing slashes
903 if (errno != ENOENT)
904 return -1;
906 namelen = strlen(file_name);
907 if (namelen && file_name[namelen-1] != '/')
908 return -1;
909 while (namelen && file_name[namelen-1] == '/')
910 --namelen;
911 if (!namelen || namelen >= PATH_MAX)
912 return -1;
914 memcpy(alt_name, file_name, namelen);
915 alt_name[namelen] = 0;
916 return do_lstat(follow, alt_name, buf);
919 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
921 BY_HANDLE_FILE_INFORMATION fdata;
923 if (!GetFileInformationByHandle(hnd, &fdata)) {
924 errno = err_win_to_posix(GetLastError());
925 return -1;
928 buf->st_ino = 0;
929 buf->st_gid = 0;
930 buf->st_uid = 0;
931 buf->st_nlink = 1;
932 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
933 buf->st_size = fdata.nFileSizeLow |
934 (((off_t)fdata.nFileSizeHigh)<<32);
935 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
936 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
937 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
938 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
939 return 0;
942 int mingw_lstat(const char *file_name, struct stat *buf)
944 return do_stat_internal(0, file_name, buf);
946 int mingw_stat(const char *file_name, struct stat *buf)
948 return do_stat_internal(1, file_name, buf);
951 int mingw_fstat(int fd, struct stat *buf)
953 HANDLE fh = (HANDLE)_get_osfhandle(fd);
954 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
956 switch (type) {
957 case FILE_TYPE_DISK:
958 return get_file_info_by_handle(fh, buf);
960 case FILE_TYPE_CHAR:
961 case FILE_TYPE_PIPE:
962 /* initialize stat fields */
963 memset(buf, 0, sizeof(*buf));
964 buf->st_nlink = 1;
966 if (type == FILE_TYPE_CHAR) {
967 buf->st_mode = _S_IFCHR;
968 } else {
969 buf->st_mode = _S_IFIFO;
970 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
971 buf->st_size = avail;
973 return 0;
975 default:
976 errno = EBADF;
977 return -1;
981 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
983 long long winTime = t * 10000000LL + 116444736000000000LL;
984 ft->dwLowDateTime = winTime;
985 ft->dwHighDateTime = winTime >> 32;
988 int mingw_utime (const char *file_name, const struct utimbuf *times)
990 FILETIME mft, aft;
991 int rc;
992 DWORD attrs;
993 wchar_t wfilename[MAX_PATH];
994 HANDLE osfilehandle;
996 if (xutftowcs_path(wfilename, file_name) < 0)
997 return -1;
999 /* must have write permission */
1000 attrs = GetFileAttributesW(wfilename);
1001 if (attrs != INVALID_FILE_ATTRIBUTES &&
1002 (attrs & FILE_ATTRIBUTE_READONLY)) {
1003 /* ignore errors here; open() will report them */
1004 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
1007 osfilehandle = CreateFileW(wfilename,
1008 FILE_WRITE_ATTRIBUTES,
1009 0 /*FileShare.None*/,
1010 NULL,
1011 OPEN_EXISTING,
1012 (attrs != INVALID_FILE_ATTRIBUTES &&
1013 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
1014 FILE_FLAG_BACKUP_SEMANTICS : 0,
1015 NULL);
1016 if (osfilehandle == INVALID_HANDLE_VALUE) {
1017 errno = err_win_to_posix(GetLastError());
1018 rc = -1;
1019 goto revert_attrs;
1022 if (times) {
1023 time_t_to_filetime(times->modtime, &mft);
1024 time_t_to_filetime(times->actime, &aft);
1025 } else {
1026 GetSystemTimeAsFileTime(&mft);
1027 aft = mft;
1030 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
1031 errno = EINVAL;
1032 rc = -1;
1033 } else
1034 rc = 0;
1036 if (osfilehandle != INVALID_HANDLE_VALUE)
1037 CloseHandle(osfilehandle);
1039 revert_attrs:
1040 if (attrs != INVALID_FILE_ATTRIBUTES &&
1041 (attrs & FILE_ATTRIBUTE_READONLY)) {
1042 /* ignore errors again */
1043 SetFileAttributesW(wfilename, attrs);
1045 return rc;
1048 #undef strftime
1049 size_t mingw_strftime(char *s, size_t max,
1050 const char *format, const struct tm *tm)
1052 /* a pointer to the original strftime in case we can't find the UCRT version */
1053 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1054 size_t ret;
1055 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1056 const char *, const struct tm *);
1058 if (INIT_PROC_ADDR(strftime))
1059 ret = strftime(s, max, format, tm);
1060 else
1061 ret = fallback(s, max, format, tm);
1063 if (!ret && errno == EINVAL)
1064 die("invalid strftime format: '%s'", format);
1065 return ret;
1068 unsigned int sleep (unsigned int seconds)
1070 Sleep(seconds*1000);
1071 return 0;
1074 char *mingw_mktemp(char *template)
1076 wchar_t wtemplate[MAX_PATH];
1077 if (xutftowcs_path(wtemplate, template) < 0)
1078 return NULL;
1079 if (!_wmktemp(wtemplate))
1080 return NULL;
1081 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1082 return NULL;
1083 return template;
1086 int mkstemp(char *template)
1088 return git_mkstemp_mode(template, 0600);
1091 int gettimeofday(struct timeval *tv, void *tz UNUSED)
1093 FILETIME ft;
1094 long long hnsec;
1096 GetSystemTimeAsFileTime(&ft);
1097 hnsec = filetime_to_hnsec(&ft);
1098 tv->tv_sec = hnsec / 10000000;
1099 tv->tv_usec = (hnsec % 10000000) / 10;
1100 return 0;
1103 int pipe(int filedes[2])
1105 HANDLE h[2];
1107 /* this creates non-inheritable handles */
1108 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1109 errno = err_win_to_posix(GetLastError());
1110 return -1;
1112 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1113 if (filedes[0] < 0) {
1114 CloseHandle(h[0]);
1115 CloseHandle(h[1]);
1116 return -1;
1118 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1119 if (filedes[1] < 0) {
1120 close(filedes[0]);
1121 CloseHandle(h[1]);
1122 return -1;
1124 return 0;
1127 #ifndef __MINGW64__
1128 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1130 if (gmtime_s(result, timep) == 0)
1131 return result;
1132 return NULL;
1135 struct tm *localtime_r(const time_t *timep, struct tm *result)
1137 if (localtime_s(result, timep) == 0)
1138 return result;
1139 return NULL;
1141 #endif
1143 char *mingw_getcwd(char *pointer, int len)
1145 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1146 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1148 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1149 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1150 return NULL;
1152 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1153 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1154 HANDLE hnd = CreateFileW(cwd, 0,
1155 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1156 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1157 if (hnd == INVALID_HANDLE_VALUE)
1158 return NULL;
1159 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1160 CloseHandle(hnd);
1161 if (!ret || ret >= ARRAY_SIZE(wpointer))
1162 return NULL;
1163 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1164 return NULL;
1165 return pointer;
1167 if (!ret || ret >= ARRAY_SIZE(wpointer))
1168 return NULL;
1169 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1170 errno = ENOENT;
1171 return NULL;
1173 if (xwcstoutf(pointer, wpointer, len) < 0)
1174 return NULL;
1175 convert_slashes(pointer);
1176 return pointer;
1180 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1181 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1183 static const char *quote_arg_msvc(const char *arg)
1185 /* count chars to quote */
1186 int len = 0, n = 0;
1187 int force_quotes = 0;
1188 char *q, *d;
1189 const char *p = arg;
1190 if (!*p) force_quotes = 1;
1191 while (*p) {
1192 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1193 force_quotes = 1;
1194 else if (*p == '"')
1195 n++;
1196 else if (*p == '\\') {
1197 int count = 0;
1198 while (*p == '\\') {
1199 count++;
1200 p++;
1201 len++;
1203 if (*p == '"' || !*p)
1204 n += count*2 + 1;
1205 continue;
1207 len++;
1208 p++;
1210 if (!force_quotes && n == 0)
1211 return arg;
1213 /* insert \ where necessary */
1214 d = q = xmalloc(st_add3(len, n, 3));
1215 *d++ = '"';
1216 while (*arg) {
1217 if (*arg == '"')
1218 *d++ = '\\';
1219 else if (*arg == '\\') {
1220 int count = 0;
1221 while (*arg == '\\') {
1222 count++;
1223 *d++ = *arg++;
1225 if (*arg == '"' || !*arg) {
1226 while (count-- > 0)
1227 *d++ = '\\';
1228 /* don't escape the surrounding end quote */
1229 if (!*arg)
1230 break;
1231 *d++ = '\\';
1234 *d++ = *arg++;
1236 *d++ = '"';
1237 *d++ = '\0';
1238 return q;
1241 #include "quote.h"
1243 static const char *quote_arg_msys2(const char *arg)
1245 struct strbuf buf = STRBUF_INIT;
1246 const char *p2 = arg, *p;
1248 for (p = arg; *p; p++) {
1249 int ws = isspace(*p);
1250 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1251 *p != '?' && *p != '*' && *p != '~')
1252 continue;
1253 if (!buf.len)
1254 strbuf_addch(&buf, '"');
1255 if (p != p2)
1256 strbuf_add(&buf, p2, p - p2);
1257 if (*p == '\\' || *p == '"')
1258 strbuf_addch(&buf, '\\');
1259 p2 = p;
1262 if (p == arg)
1263 strbuf_addch(&buf, '"');
1264 else if (!buf.len)
1265 return arg;
1266 else
1267 strbuf_add(&buf, p2, p - p2);
1269 strbuf_addch(&buf, '"');
1270 return strbuf_detach(&buf, 0);
1273 static const char *parse_interpreter(const char *cmd)
1275 static char buf[100];
1276 char *p, *opt;
1277 int n, fd;
1279 /* don't even try a .exe */
1280 n = strlen(cmd);
1281 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1282 return NULL;
1284 fd = open(cmd, O_RDONLY);
1285 if (fd < 0)
1286 return NULL;
1287 n = read(fd, buf, sizeof(buf)-1);
1288 close(fd);
1289 if (n < 4) /* at least '#!/x' and not error */
1290 return NULL;
1292 if (buf[0] != '#' || buf[1] != '!')
1293 return NULL;
1294 buf[n] = '\0';
1295 p = buf + strcspn(buf, "\r\n");
1296 if (!*p)
1297 return NULL;
1299 *p = '\0';
1300 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1301 return NULL;
1302 /* strip options */
1303 if ((opt = strchr(p+1, ' ')))
1304 *opt = '\0';
1305 return p+1;
1309 * exe_only means that we only want to detect .exe files, but not scripts
1310 * (which do not have an extension)
1312 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1313 int isexe, int exe_only)
1315 char path[MAX_PATH];
1316 wchar_t wpath[MAX_PATH];
1317 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1319 if (xutftowcs_path(wpath, path) < 0)
1320 return NULL;
1322 if (!isexe && _waccess(wpath, F_OK) == 0)
1323 return xstrdup(path);
1324 wpath[wcslen(wpath)-4] = '\0';
1325 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1326 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1327 path[strlen(path)-4] = '\0';
1328 return xstrdup(path);
1331 return NULL;
1335 * Determines the absolute path of cmd using the split path in path.
1336 * If cmd contains a slash or backslash, no lookup is performed.
1338 static char *path_lookup(const char *cmd, int exe_only)
1340 const char *path;
1341 char *prog = NULL;
1342 int len = strlen(cmd);
1343 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1345 if (strpbrk(cmd, "/\\"))
1346 return xstrdup(cmd);
1348 path = mingw_getenv("PATH");
1349 if (!path)
1350 return NULL;
1352 while (!prog) {
1353 const char *sep = strchrnul(path, ';');
1354 int dirlen = sep - path;
1355 if (dirlen)
1356 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1357 if (!*sep)
1358 break;
1359 path = sep + 1;
1362 return prog;
1365 char *mingw_locate_in_PATH(const char *cmd)
1367 return path_lookup(cmd, 0);
1370 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1372 while (*s && *s != c)
1373 s++;
1374 return s;
1377 /* Compare only keys */
1378 static int wenvcmp(const void *a, const void *b)
1380 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1381 size_t p_len, q_len;
1383 /* Find the keys */
1384 p_len = wcschrnul(p, L'=') - p;
1385 q_len = wcschrnul(q, L'=') - q;
1387 /* If the length differs, include the shorter key's NUL */
1388 if (p_len < q_len)
1389 p_len++;
1390 else if (p_len > q_len)
1391 p_len = q_len + 1;
1393 return _wcsnicmp(p, q, p_len);
1397 * Build an environment block combining the inherited environment
1398 * merged with the given list of settings.
1400 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1401 * Values of the form "KEY" in deltaenv delete inherited values.
1403 * Multiple entries in deltaenv for the same key are explicitly allowed.
1405 * We return a contiguous block of UNICODE strings with a final trailing
1406 * zero word.
1408 static wchar_t *make_environment_block(char **deltaenv)
1410 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1411 size_t wlen, s, delta_size, size;
1413 wchar_t **array = NULL;
1414 size_t alloc = 0, nr = 0, i;
1416 size = 1; /* for extra NUL at the end */
1418 /* If there is no deltaenv to apply, simply return a copy. */
1419 if (!deltaenv || !*deltaenv) {
1420 for (p = wenv; p && *p; ) {
1421 size_t s = wcslen(p) + 1;
1422 size += s;
1423 p += s;
1426 DUP_ARRAY(result, wenv, size);
1427 FreeEnvironmentStringsW(wenv);
1428 return result;
1432 * If there is a deltaenv, let's accumulate all keys into `array`,
1433 * sort them using the stable git_stable_qsort() and then copy,
1434 * skipping duplicate keys
1436 for (p = wenv; p && *p; ) {
1437 ALLOC_GROW(array, nr + 1, alloc);
1438 s = wcslen(p) + 1;
1439 array[nr++] = p;
1440 p += s;
1441 size += s;
1444 /* (over-)assess size needed for wchar version of deltaenv */
1445 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1446 delta_size += strlen(deltaenv[i]) * 2 + 1;
1447 ALLOC_ARRAY(wdeltaenv, delta_size);
1449 /* convert the deltaenv, appending to array */
1450 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1451 ALLOC_GROW(array, nr + 1, alloc);
1452 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1453 array[nr++] = p;
1454 p += wlen + 1;
1457 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1458 ALLOC_ARRAY(result, size + delta_size);
1460 for (p = result, i = 0; i < nr; i++) {
1461 /* Skip any duplicate keys; last one wins */
1462 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1463 i++;
1465 /* Skip "to delete" entry */
1466 if (!wcschr(array[i], L'='))
1467 continue;
1469 size = wcslen(array[i]) + 1;
1470 COPY_ARRAY(p, array[i], size);
1471 p += size;
1473 *p = L'\0';
1475 free(array);
1476 free(wdeltaenv);
1477 FreeEnvironmentStringsW(wenv);
1478 return result;
1481 static void do_unset_environment_variables(void)
1483 static int done;
1484 char *p = unset_environment_variables;
1486 if (done || !p)
1487 return;
1488 done = 1;
1490 for (;;) {
1491 char *comma = strchr(p, ',');
1493 if (comma)
1494 *comma = '\0';
1495 unsetenv(p);
1496 if (!comma)
1497 break;
1498 p = comma + 1;
1502 struct pinfo_t {
1503 struct pinfo_t *next;
1504 pid_t pid;
1505 HANDLE proc;
1507 static struct pinfo_t *pinfo = NULL;
1508 CRITICAL_SECTION pinfo_cs;
1510 /* Used to match and chomp off path components */
1511 static inline int match_last_path_component(const char *path, size_t *len,
1512 const char *component)
1514 size_t component_len = strlen(component);
1515 if (*len < component_len + 1 ||
1516 !is_dir_sep(path[*len - component_len - 1]) ||
1517 fspathncmp(path + *len - component_len, component, component_len))
1518 return 0;
1519 *len -= component_len + 1;
1520 /* chomp off repeated dir separators */
1521 while (*len > 0 && is_dir_sep(path[*len - 1]))
1522 (*len)--;
1523 return 1;
1526 static int is_msys2_sh(const char *cmd)
1528 if (!cmd)
1529 return 0;
1531 if (!strcmp(cmd, "sh")) {
1532 static int ret = -1;
1533 char *p;
1535 if (ret >= 0)
1536 return ret;
1538 p = path_lookup(cmd, 0);
1539 if (!p)
1540 ret = 0;
1541 else {
1542 size_t len = strlen(p);
1544 ret = match_last_path_component(p, &len, "sh.exe") &&
1545 match_last_path_component(p, &len, "bin") &&
1546 match_last_path_component(p, &len, "usr");
1547 free(p);
1549 return ret;
1552 if (ends_with(cmd, "\\sh.exe") || ends_with(cmd, "/sh.exe")) {
1553 static char *sh;
1555 if (!sh)
1556 sh = path_lookup("sh", 0);
1558 return !fspathcmp(cmd, sh);
1561 return 0;
1564 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1565 const char *dir,
1566 int prepend_cmd, int fhin, int fhout, int fherr)
1568 static int restrict_handle_inheritance = -1;
1569 STARTUPINFOEXW si;
1570 PROCESS_INFORMATION pi;
1571 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1572 HANDLE stdhandles[3];
1573 DWORD stdhandles_count = 0;
1574 SIZE_T size;
1575 struct strbuf args;
1576 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1577 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1578 BOOL ret;
1579 HANDLE cons;
1580 const char *(*quote_arg)(const char *arg) =
1581 is_msys2_sh(cmd ? cmd : *argv) ?
1582 quote_arg_msys2 : quote_arg_msvc;
1583 const char *strace_env;
1585 /* Make sure to override previous errors, if any */
1586 errno = 0;
1588 if (restrict_handle_inheritance < 0)
1589 restrict_handle_inheritance = core_restrict_inherited_handles;
1591 * The following code to restrict which handles are inherited seems
1592 * to work properly only on Windows 7 and later, so let's disable it
1593 * on Windows Vista and 2008.
1595 if (restrict_handle_inheritance < 0)
1596 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1598 do_unset_environment_variables();
1600 /* Determine whether or not we are associated to a console */
1601 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1602 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1603 FILE_ATTRIBUTE_NORMAL, NULL);
1604 if (cons == INVALID_HANDLE_VALUE) {
1605 /* There is no console associated with this process.
1606 * Since the child is a console process, Windows
1607 * would normally create a console window. But
1608 * since we'll be redirecting std streams, we do
1609 * not need the console.
1610 * It is necessary to use DETACHED_PROCESS
1611 * instead of CREATE_NO_WINDOW to make ssh
1612 * recognize that it has no console.
1614 flags |= DETACHED_PROCESS;
1615 } else {
1616 /* There is already a console. If we specified
1617 * DETACHED_PROCESS here, too, Windows would
1618 * disassociate the child from the console.
1619 * The same is true for CREATE_NO_WINDOW.
1620 * Go figure!
1622 CloseHandle(cons);
1624 memset(&si, 0, sizeof(si));
1625 si.StartupInfo.cb = sizeof(si);
1626 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1627 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1628 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1630 /* The list of handles cannot contain duplicates */
1631 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1632 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1633 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1634 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1635 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1636 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1637 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1638 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1639 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1640 if (stdhandles_count)
1641 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1643 if (*argv && !strcmp(cmd, *argv))
1644 wcmd[0] = L'\0';
1645 else if (xutftowcs_path(wcmd, cmd) < 0)
1646 return -1;
1647 if (dir && xutftowcs_path(wdir, dir) < 0)
1648 return -1;
1650 /* concatenate argv, quoting args as we go */
1651 strbuf_init(&args, 0);
1652 if (prepend_cmd) {
1653 char *quoted = (char *)quote_arg(cmd);
1654 strbuf_addstr(&args, quoted);
1655 if (quoted != cmd)
1656 free(quoted);
1658 for (; *argv; argv++) {
1659 char *quoted = (char *)quote_arg(*argv);
1660 if (*args.buf)
1661 strbuf_addch(&args, ' ');
1662 strbuf_addstr(&args, quoted);
1663 if (quoted != *argv)
1664 free(quoted);
1667 strace_env = getenv("GIT_STRACE_COMMANDS");
1668 if (strace_env) {
1669 char *p = path_lookup("strace.exe", 1);
1670 if (!p)
1671 return error("strace not found!");
1672 if (xutftowcs_path(wcmd, p) < 0) {
1673 free(p);
1674 return -1;
1676 free(p);
1677 if (!strcmp("1", strace_env) ||
1678 !strcasecmp("yes", strace_env) ||
1679 !strcasecmp("true", strace_env))
1680 strbuf_insert(&args, 0, "strace ", 7);
1681 else {
1682 const char *quoted = quote_arg(strace_env);
1683 struct strbuf buf = STRBUF_INIT;
1684 strbuf_addf(&buf, "strace -o %s ", quoted);
1685 if (quoted != strace_env)
1686 free((char *)quoted);
1687 strbuf_insert(&args, 0, buf.buf, buf.len);
1688 strbuf_release(&buf);
1692 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1693 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1694 strbuf_release(&args);
1696 wenvblk = make_environment_block(deltaenv);
1698 memset(&pi, 0, sizeof(pi));
1699 if (restrict_handle_inheritance && stdhandles_count &&
1700 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1701 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1702 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1703 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1704 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1705 UpdateProcThreadAttribute(attr_list, 0,
1706 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1707 stdhandles,
1708 stdhandles_count * sizeof(HANDLE),
1709 NULL, NULL)) {
1710 si.lpAttributeList = attr_list;
1711 flags |= EXTENDED_STARTUPINFO_PRESENT;
1714 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1715 stdhandles_count ? TRUE : FALSE,
1716 flags, wenvblk, dir ? wdir : NULL,
1717 &si.StartupInfo, &pi);
1720 * On Windows 2008 R2, it seems that specifying certain types of handles
1721 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1722 * error. Rather than playing finicky and fragile games, let's just try
1723 * to detect this situation and simply try again without restricting any
1724 * handle inheritance. This is still better than failing to create
1725 * processes.
1727 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1728 DWORD err = GetLastError();
1729 struct strbuf buf = STRBUF_INIT;
1731 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1733 * On Windows 7 and earlier, handles on pipes and character
1734 * devices are inherited automatically, and cannot be
1735 * specified in the thread handle list. Rather than trying
1736 * to catch each and every corner case (and running the
1737 * chance of *still* forgetting a few), let's just fall
1738 * back to creating the process without trying to limit the
1739 * handle inheritance.
1741 !(err == ERROR_INVALID_PARAMETER &&
1742 GetVersion() >> 16 < 9200) &&
1743 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1744 DWORD fl = 0;
1745 int i;
1747 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1749 for (i = 0; i < stdhandles_count; i++) {
1750 HANDLE h = stdhandles[i];
1751 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1752 "handle info (%d) %lx\n", i, h,
1753 GetFileType(h),
1754 GetHandleInformation(h, &fl),
1755 fl);
1757 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1758 "at\nhttps://github.com/git-for-windows/"
1759 "git/issues/new\n\n"
1760 "To suppress this warning, please set "
1761 "the environment variable\n\n"
1762 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1763 "\n");
1765 restrict_handle_inheritance = 0;
1766 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1767 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1768 TRUE, flags, wenvblk, dir ? wdir : NULL,
1769 &si.StartupInfo, &pi);
1770 if (!ret)
1771 errno = err_win_to_posix(GetLastError());
1772 if (ret && buf.len) {
1773 warning("failed to restrict file handles (%ld)\n\n%s",
1774 err, buf.buf);
1776 strbuf_release(&buf);
1777 } else if (!ret)
1778 errno = err_win_to_posix(GetLastError());
1780 if (si.lpAttributeList)
1781 DeleteProcThreadAttributeList(si.lpAttributeList);
1782 if (attr_list)
1783 HeapFree(GetProcessHeap(), 0, attr_list);
1785 free(wenvblk);
1786 free(wargs);
1788 if (!ret)
1789 return -1;
1791 CloseHandle(pi.hThread);
1794 * The process ID is the human-readable identifier of the process
1795 * that we want to present in log and error messages. The handle
1796 * is not useful for this purpose. But we cannot close it, either,
1797 * because it is not possible to turn a process ID into a process
1798 * handle after the process terminated.
1799 * Keep the handle in a list for waitpid.
1801 EnterCriticalSection(&pinfo_cs);
1803 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1804 info->pid = pi.dwProcessId;
1805 info->proc = pi.hProcess;
1806 info->next = pinfo;
1807 pinfo = info;
1809 LeaveCriticalSection(&pinfo_cs);
1811 return (pid_t)pi.dwProcessId;
1814 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1816 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1819 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1820 const char *dir,
1821 int fhin, int fhout, int fherr)
1823 pid_t pid;
1824 char *prog = path_lookup(cmd, 0);
1826 if (!prog) {
1827 errno = ENOENT;
1828 pid = -1;
1830 else {
1831 const char *interpr = parse_interpreter(prog);
1833 if (interpr) {
1834 const char *argv0 = argv[0];
1835 char *iprog = path_lookup(interpr, 1);
1836 argv[0] = prog;
1837 if (!iprog) {
1838 errno = ENOENT;
1839 pid = -1;
1841 else {
1842 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1843 fhin, fhout, fherr);
1844 free(iprog);
1846 argv[0] = argv0;
1848 else
1849 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1850 fhin, fhout, fherr);
1851 free(prog);
1853 return pid;
1856 static int try_shell_exec(const char *cmd, char *const *argv)
1858 const char *interpr = parse_interpreter(cmd);
1859 char *prog;
1860 int pid = 0;
1862 if (!interpr)
1863 return 0;
1864 prog = path_lookup(interpr, 1);
1865 if (prog) {
1866 int exec_id;
1867 int argc = 0;
1868 char **argv2;
1869 while (argv[argc]) argc++;
1870 ALLOC_ARRAY(argv2, argc + 1);
1871 argv2[0] = (char *)cmd; /* full path to the script file */
1872 COPY_ARRAY(&argv2[1], &argv[1], argc);
1873 exec_id = trace2_exec(prog, (const char **)argv2);
1874 pid = mingw_spawnv(prog, (const char **)argv2, 1);
1875 if (pid >= 0) {
1876 int status;
1877 if (waitpid(pid, &status, 0) < 0)
1878 status = 255;
1879 trace2_exec_result(exec_id, status);
1880 exit(status);
1882 trace2_exec_result(exec_id, -1);
1883 pid = 1; /* indicate that we tried but failed */
1884 free(prog);
1885 free(argv2);
1887 return pid;
1890 int mingw_execv(const char *cmd, char *const *argv)
1892 /* check if git_command is a shell script */
1893 if (!try_shell_exec(cmd, argv)) {
1894 int pid, status;
1895 int exec_id;
1897 exec_id = trace2_exec(cmd, (const char **)argv);
1898 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1899 if (pid < 0) {
1900 trace2_exec_result(exec_id, -1);
1901 return -1;
1903 if (waitpid(pid, &status, 0) < 0)
1904 status = 255;
1905 trace2_exec_result(exec_id, status);
1906 exit(status);
1908 return -1;
1911 int mingw_execvp(const char *cmd, char *const *argv)
1913 char *prog = path_lookup(cmd, 0);
1915 if (prog) {
1916 mingw_execv(prog, argv);
1917 free(prog);
1918 } else
1919 errno = ENOENT;
1921 return -1;
1924 int mingw_kill(pid_t pid, int sig)
1926 if (pid > 0 && sig == SIGTERM) {
1927 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1929 if (TerminateProcess(h, -1)) {
1930 CloseHandle(h);
1931 return 0;
1934 errno = err_win_to_posix(GetLastError());
1935 CloseHandle(h);
1936 return -1;
1937 } else if (pid > 0 && sig == 0) {
1938 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1939 if (h) {
1940 CloseHandle(h);
1941 return 0;
1945 errno = EINVAL;
1946 return -1;
1950 * UTF-8 versions of getenv(), putenv() and unsetenv().
1951 * Internally, they use the CRT's stock UNICODE routines
1952 * to avoid data loss.
1954 char *mingw_getenv(const char *name)
1956 #define GETENV_MAX_RETAIN 64
1957 static char *values[GETENV_MAX_RETAIN];
1958 static int value_counter;
1959 int len_key, len_value;
1960 wchar_t *w_key;
1961 char *value;
1962 wchar_t w_value[32768];
1964 if (!name || !*name)
1965 return NULL;
1967 len_key = strlen(name) + 1;
1968 /* We cannot use xcalloc() here because that uses getenv() itself */
1969 w_key = calloc(len_key, sizeof(wchar_t));
1970 if (!w_key)
1971 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1972 xutftowcs(w_key, name, len_key);
1973 /* GetEnvironmentVariableW() only sets the last error upon failure */
1974 SetLastError(ERROR_SUCCESS);
1975 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1976 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1977 free(w_key);
1978 return NULL;
1980 free(w_key);
1982 len_value = len_value * 3 + 1;
1983 /* We cannot use xcalloc() here because that uses getenv() itself */
1984 value = calloc(len_value, sizeof(char));
1985 if (!value)
1986 die("Out of memory, (tried to allocate %u bytes)", len_value);
1987 xwcstoutf(value, w_value, len_value);
1990 * We return `value` which is an allocated value and the caller is NOT
1991 * expecting to have to free it, so we keep a round-robin array,
1992 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1994 free(values[value_counter]);
1995 values[value_counter++] = value;
1996 if (value_counter >= ARRAY_SIZE(values))
1997 value_counter = 0;
1999 return value;
2002 int mingw_putenv(const char *namevalue)
2004 int size;
2005 wchar_t *wide, *equal;
2006 BOOL result;
2008 if (!namevalue || !*namevalue)
2009 return 0;
2011 size = strlen(namevalue) * 2 + 1;
2012 wide = calloc(size, sizeof(wchar_t));
2013 if (!wide)
2014 die("Out of memory, (tried to allocate %u wchar_t's)", size);
2015 xutftowcs(wide, namevalue, size);
2016 equal = wcschr(wide, L'=');
2017 if (!equal)
2018 result = SetEnvironmentVariableW(wide, NULL);
2019 else {
2020 *equal = L'\0';
2021 result = SetEnvironmentVariableW(wide, equal + 1);
2023 free(wide);
2025 if (!result)
2026 errno = err_win_to_posix(GetLastError());
2028 return result ? 0 : -1;
2031 static void ensure_socket_initialization(void)
2033 WSADATA wsa;
2034 static int initialized = 0;
2036 if (initialized)
2037 return;
2039 if (WSAStartup(MAKEWORD(2,2), &wsa))
2040 die("unable to initialize winsock subsystem, error %d",
2041 WSAGetLastError());
2043 atexit((void(*)(void)) WSACleanup);
2044 initialized = 1;
2047 #undef gethostname
2048 int mingw_gethostname(char *name, int namelen)
2050 ensure_socket_initialization();
2051 return gethostname(name, namelen);
2054 #undef gethostbyname
2055 struct hostent *mingw_gethostbyname(const char *host)
2057 ensure_socket_initialization();
2058 return gethostbyname(host);
2061 #undef getaddrinfo
2062 int mingw_getaddrinfo(const char *node, const char *service,
2063 const struct addrinfo *hints, struct addrinfo **res)
2065 ensure_socket_initialization();
2066 return getaddrinfo(node, service, hints, res);
2069 int mingw_socket(int domain, int type, int protocol)
2071 int sockfd;
2072 SOCKET s;
2074 ensure_socket_initialization();
2075 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2076 if (s == INVALID_SOCKET) {
2078 * WSAGetLastError() values are regular BSD error codes
2079 * biased by WSABASEERR.
2080 * However, strerror() does not know about networking
2081 * specific errors, which are values beginning at 38 or so.
2082 * Therefore, we choose to leave the biased error code
2083 * in errno so that _if_ someone looks up the code somewhere,
2084 * then it is at least the number that are usually listed.
2086 errno = WSAGetLastError();
2087 return -1;
2089 /* convert into a file descriptor */
2090 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2091 closesocket(s);
2092 return error("unable to make a socket file descriptor: %s",
2093 strerror(errno));
2095 return sockfd;
2098 #undef connect
2099 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2101 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2102 return connect(s, sa, sz);
2105 #undef bind
2106 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2108 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2109 return bind(s, sa, sz);
2112 #undef setsockopt
2113 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2115 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2116 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2119 #undef shutdown
2120 int mingw_shutdown(int sockfd, int how)
2122 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2123 return shutdown(s, how);
2126 #undef listen
2127 int mingw_listen(int sockfd, int backlog)
2129 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2130 return listen(s, backlog);
2133 #undef accept
2134 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2136 int sockfd2;
2138 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2139 SOCKET s2 = accept(s1, sa, sz);
2141 /* convert into a file descriptor */
2142 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2143 int err = errno;
2144 closesocket(s2);
2145 return error("unable to make a socket file descriptor: %s",
2146 strerror(err));
2148 return sockfd2;
2151 #undef rename
2152 int mingw_rename(const char *pold, const char *pnew)
2154 DWORD attrs, gle;
2155 int tries = 0;
2156 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2157 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2158 return -1;
2161 * Try native rename() first to get errno right.
2162 * It is based on MoveFile(), which cannot overwrite existing files.
2164 if (!_wrename(wpold, wpnew))
2165 return 0;
2166 if (errno != EEXIST)
2167 return -1;
2168 repeat:
2169 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2170 return 0;
2171 /* TODO: translate more errors */
2172 gle = GetLastError();
2173 if (gle == ERROR_ACCESS_DENIED &&
2174 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2175 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2176 DWORD attrsold = GetFileAttributesW(wpold);
2177 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2178 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2179 errno = EISDIR;
2180 else if (!_wrmdir(wpnew))
2181 goto repeat;
2182 return -1;
2184 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2185 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2186 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2187 return 0;
2188 gle = GetLastError();
2189 /* revert file attributes on failure */
2190 SetFileAttributesW(wpnew, attrs);
2193 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2195 * We assume that some other process had the source or
2196 * destination file open at the wrong moment and retry.
2197 * In order to give the other process a higher chance to
2198 * complete its operation, we give up our time slice now.
2199 * If we have to retry again, we do sleep a bit.
2201 Sleep(delay[tries]);
2202 tries++;
2203 goto repeat;
2205 if (gle == ERROR_ACCESS_DENIED &&
2206 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2207 "Should I try again?", pold, pnew))
2208 goto repeat;
2210 errno = EACCES;
2211 return -1;
2215 * Note that this doesn't return the actual pagesize, but
2216 * the allocation granularity. If future Windows specific git code
2217 * needs the real getpagesize function, we need to find another solution.
2219 int mingw_getpagesize(void)
2221 SYSTEM_INFO si;
2222 GetSystemInfo(&si);
2223 return si.dwAllocationGranularity;
2226 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2227 enum EXTENDED_NAME_FORMAT {
2228 NameDisplay = 3,
2229 NameUserPrincipal = 8
2232 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2234 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2235 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2236 static wchar_t wbuffer[1024];
2237 DWORD len;
2239 if (!INIT_PROC_ADDR(GetUserNameExW))
2240 return NULL;
2242 len = ARRAY_SIZE(wbuffer);
2243 if (GetUserNameExW(type, wbuffer, &len)) {
2244 char *converted = xmalloc((len *= 3));
2245 if (xwcstoutf(converted, wbuffer, len) >= 0)
2246 return converted;
2247 free(converted);
2250 return NULL;
2253 char *mingw_query_user_email(void)
2255 return get_extended_user_info(NameUserPrincipal);
2258 struct passwd *getpwuid(int uid UNUSED)
2260 static unsigned initialized;
2261 static char user_name[100];
2262 static struct passwd *p;
2263 wchar_t buf[100];
2264 DWORD len;
2266 if (initialized)
2267 return p;
2269 len = ARRAY_SIZE(buf);
2270 if (!GetUserNameW(buf, &len)) {
2271 initialized = 1;
2272 return NULL;
2275 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2276 initialized = 1;
2277 return NULL;
2280 p = xmalloc(sizeof(*p));
2281 p->pw_name = user_name;
2282 p->pw_gecos = get_extended_user_info(NameDisplay);
2283 if (!p->pw_gecos)
2285 * Data returned by getpwuid(3P) is treated as internal and
2286 * must never be written to or freed.
2288 p->pw_gecos = (char *) "unknown";
2289 p->pw_dir = NULL;
2291 initialized = 1;
2292 return p;
2295 static HANDLE timer_event;
2296 static HANDLE timer_thread;
2297 static int timer_interval;
2298 static int one_shot;
2299 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2301 /* The timer works like this:
2302 * The thread, ticktack(), is a trivial routine that most of the time
2303 * only waits to receive the signal to terminate. The main thread tells
2304 * the thread to terminate by setting the timer_event to the signalled
2305 * state.
2306 * But ticktack() interrupts the wait state after the timer's interval
2307 * length to call the signal handler.
2310 static unsigned __stdcall ticktack(void *dummy UNUSED)
2312 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2313 mingw_raise(SIGALRM);
2314 if (one_shot)
2315 break;
2317 return 0;
2320 static int start_timer_thread(void)
2322 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2323 if (timer_event) {
2324 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2325 if (!timer_thread )
2326 return errno = ENOMEM,
2327 error("cannot start timer thread");
2328 } else
2329 return errno = ENOMEM,
2330 error("cannot allocate resources for timer");
2331 return 0;
2334 static void stop_timer_thread(void)
2336 if (timer_event)
2337 SetEvent(timer_event); /* tell thread to terminate */
2338 if (timer_thread) {
2339 int rc = WaitForSingleObject(timer_thread, 10000);
2340 if (rc == WAIT_TIMEOUT)
2341 error("timer thread did not terminate timely");
2342 else if (rc != WAIT_OBJECT_0)
2343 error("waiting for timer thread failed: %lu",
2344 GetLastError());
2345 CloseHandle(timer_thread);
2347 if (timer_event)
2348 CloseHandle(timer_event);
2349 timer_event = NULL;
2350 timer_thread = NULL;
2353 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2355 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2358 int setitimer(int type UNUSED, struct itimerval *in, struct itimerval *out)
2360 static const struct timeval zero;
2361 static int atexit_done;
2363 if (out)
2364 return errno = EINVAL,
2365 error("setitimer param 3 != NULL not implemented");
2366 if (!is_timeval_eq(&in->it_interval, &zero) &&
2367 !is_timeval_eq(&in->it_interval, &in->it_value))
2368 return errno = EINVAL,
2369 error("setitimer: it_interval must be zero or eq it_value");
2371 if (timer_thread)
2372 stop_timer_thread();
2374 if (is_timeval_eq(&in->it_value, &zero) &&
2375 is_timeval_eq(&in->it_interval, &zero))
2376 return 0;
2378 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2379 one_shot = is_timeval_eq(&in->it_interval, &zero);
2380 if (!atexit_done) {
2381 atexit(stop_timer_thread);
2382 atexit_done = 1;
2384 return start_timer_thread();
2387 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2389 if (sig != SIGALRM)
2390 return errno = EINVAL,
2391 error("sigaction only implemented for SIGALRM");
2392 if (out)
2393 return errno = EINVAL,
2394 error("sigaction: param 3 != NULL not implemented");
2396 timer_fn = in->sa_handler;
2397 return 0;
2400 #undef signal
2401 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2403 sig_handler_t old;
2405 switch (sig) {
2406 case SIGALRM:
2407 old = timer_fn;
2408 timer_fn = handler;
2409 break;
2411 case SIGINT:
2412 old = sigint_fn;
2413 sigint_fn = handler;
2414 break;
2416 default:
2417 return signal(sig, handler);
2420 return old;
2423 #undef raise
2424 int mingw_raise(int sig)
2426 switch (sig) {
2427 case SIGALRM:
2428 if (timer_fn == SIG_DFL) {
2429 if (isatty(STDERR_FILENO))
2430 fputs("Alarm clock\n", stderr);
2431 exit(128 + SIGALRM);
2432 } else if (timer_fn != SIG_IGN)
2433 timer_fn(SIGALRM);
2434 return 0;
2436 case SIGINT:
2437 if (sigint_fn == SIG_DFL)
2438 exit(128 + SIGINT);
2439 else if (sigint_fn != SIG_IGN)
2440 sigint_fn(SIGINT);
2441 return 0;
2443 #if defined(_MSC_VER)
2444 case SIGILL:
2445 case SIGFPE:
2446 case SIGSEGV:
2447 case SIGTERM:
2448 case SIGBREAK:
2449 case SIGABRT:
2450 case SIGABRT_COMPAT:
2452 * The <signal.h> header in the MS C Runtime defines 8 signals
2453 * as being supported on the platform. Anything else causes an
2454 * "Invalid signal or error" (which in DEBUG builds causes the
2455 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2456 * already know will fail.
2458 return raise(sig);
2459 default:
2460 errno = EINVAL;
2461 return -1;
2463 #else
2465 default:
2466 return raise(sig);
2468 #endif
2473 int link(const char *oldpath, const char *newpath)
2475 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2476 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2477 xutftowcs_path(wnewpath, newpath) < 0)
2478 return -1;
2480 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2481 errno = err_win_to_posix(GetLastError());
2482 return -1;
2484 return 0;
2487 pid_t waitpid(pid_t pid, int *status, int options)
2489 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2490 FALSE, pid);
2491 if (!h) {
2492 errno = ECHILD;
2493 return -1;
2496 if (pid > 0 && options & WNOHANG) {
2497 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2498 CloseHandle(h);
2499 return 0;
2501 options &= ~WNOHANG;
2504 if (options == 0) {
2505 struct pinfo_t **ppinfo;
2506 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2507 CloseHandle(h);
2508 return 0;
2511 if (status)
2512 GetExitCodeProcess(h, (LPDWORD)status);
2514 EnterCriticalSection(&pinfo_cs);
2516 ppinfo = &pinfo;
2517 while (*ppinfo) {
2518 struct pinfo_t *info = *ppinfo;
2519 if (info->pid == pid) {
2520 CloseHandle(info->proc);
2521 *ppinfo = info->next;
2522 free(info);
2523 break;
2525 ppinfo = &info->next;
2528 LeaveCriticalSection(&pinfo_cs);
2530 CloseHandle(h);
2531 return pid;
2533 CloseHandle(h);
2535 errno = EINVAL;
2536 return -1;
2539 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2541 int upos = 0, wpos = 0;
2542 const unsigned char *utf = (const unsigned char*) utfs;
2543 if (!utf || !wcs || wcslen < 1) {
2544 errno = EINVAL;
2545 return -1;
2547 /* reserve space for \0 */
2548 wcslen--;
2549 if (utflen < 0)
2550 utflen = INT_MAX;
2552 while (upos < utflen) {
2553 int c = utf[upos++] & 0xff;
2554 if (utflen == INT_MAX && c == 0)
2555 break;
2557 if (wpos >= wcslen) {
2558 wcs[wpos] = 0;
2559 errno = ERANGE;
2560 return -1;
2563 if (c < 0x80) {
2564 /* ASCII */
2565 wcs[wpos++] = c;
2566 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2567 (utf[upos] & 0xc0) == 0x80) {
2568 /* 2-byte utf-8 */
2569 c = ((c & 0x1f) << 6);
2570 c |= (utf[upos++] & 0x3f);
2571 wcs[wpos++] = c;
2572 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2573 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2574 (utf[upos] & 0xc0) == 0x80 &&
2575 (utf[upos + 1] & 0xc0) == 0x80) {
2576 /* 3-byte utf-8 */
2577 c = ((c & 0x0f) << 12);
2578 c |= ((utf[upos++] & 0x3f) << 6);
2579 c |= (utf[upos++] & 0x3f);
2580 wcs[wpos++] = c;
2581 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2582 wpos + 1 < wcslen &&
2583 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2584 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2585 (utf[upos] & 0xc0) == 0x80 &&
2586 (utf[upos + 1] & 0xc0) == 0x80 &&
2587 (utf[upos + 2] & 0xc0) == 0x80) {
2588 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2589 c = ((c & 0x07) << 18);
2590 c |= ((utf[upos++] & 0x3f) << 12);
2591 c |= ((utf[upos++] & 0x3f) << 6);
2592 c |= (utf[upos++] & 0x3f);
2593 c -= 0x10000;
2594 wcs[wpos++] = 0xd800 | (c >> 10);
2595 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2596 } else if (c >= 0xa0) {
2597 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2598 wcs[wpos++] = c;
2599 } else {
2600 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2601 static const char *hex = "0123456789abcdef";
2602 wcs[wpos++] = hex[c >> 4];
2603 if (wpos < wcslen)
2604 wcs[wpos++] = hex[c & 0x0f];
2607 wcs[wpos] = 0;
2608 return wpos;
2611 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2613 if (!wcs || !utf || utflen < 1) {
2614 errno = EINVAL;
2615 return -1;
2617 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2618 if (utflen)
2619 return utflen - 1;
2620 errno = ERANGE;
2621 return -1;
2624 static void setup_windows_environment(void)
2626 char *tmp = getenv("TMPDIR");
2628 /* on Windows it is TMP and TEMP */
2629 if (!tmp) {
2630 if (!(tmp = getenv("TMP")))
2631 tmp = getenv("TEMP");
2632 if (tmp) {
2633 setenv("TMPDIR", tmp, 1);
2634 tmp = getenv("TMPDIR");
2638 if (tmp) {
2640 * Convert all dir separators to forward slashes,
2641 * to help shell commands called from the Git
2642 * executable (by not mistaking the dir separators
2643 * for escape characters).
2645 convert_slashes(tmp);
2648 /* simulate TERM to enable auto-color (see color.c) */
2649 if (!getenv("TERM"))
2650 setenv("TERM", "cygwin", 1);
2652 /* calculate HOME if not set */
2653 if (!getenv("HOME")) {
2655 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2656 * location, thus also check if the path exists (i.e. is not
2657 * disconnected)
2659 if ((tmp = getenv("HOMEDRIVE"))) {
2660 struct strbuf buf = STRBUF_INIT;
2661 strbuf_addstr(&buf, tmp);
2662 if ((tmp = getenv("HOMEPATH"))) {
2663 strbuf_addstr(&buf, tmp);
2664 if (is_directory(buf.buf))
2665 setenv("HOME", buf.buf, 1);
2666 else
2667 tmp = NULL; /* use $USERPROFILE */
2669 strbuf_release(&buf);
2671 /* use $USERPROFILE if the home share is not available */
2672 if (!tmp && (tmp = getenv("USERPROFILE")))
2673 setenv("HOME", tmp, 1);
2677 static PSID get_current_user_sid(void)
2679 HANDLE token;
2680 DWORD len = 0;
2681 PSID result = NULL;
2683 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2684 return NULL;
2686 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2687 TOKEN_USER *info = xmalloc((size_t)len);
2688 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2689 len = GetLengthSid(info->User.Sid);
2690 result = xmalloc(len);
2691 if (!CopySid(len, result, info->User.Sid)) {
2692 error(_("failed to copy SID (%ld)"),
2693 GetLastError());
2694 FREE_AND_NULL(result);
2697 FREE_AND_NULL(info);
2699 CloseHandle(token);
2701 return result;
2704 static BOOL user_sid_to_user_name(PSID sid, LPSTR *str)
2706 SID_NAME_USE pe_use;
2707 DWORD len_user = 0, len_domain = 0;
2708 BOOL translate_sid_to_user;
2711 * returns only FALSE, because the string pointers are NULL
2713 LookupAccountSidA(NULL, sid, NULL, &len_user, NULL, &len_domain,
2714 &pe_use);
2716 * Alloc needed space of the strings
2718 ALLOC_ARRAY((*str), (size_t)len_domain + (size_t)len_user);
2719 translate_sid_to_user = LookupAccountSidA(NULL, sid,
2720 (*str) + len_domain, &len_user, *str, &len_domain, &pe_use);
2721 if (!translate_sid_to_user)
2722 FREE_AND_NULL(*str);
2723 else
2724 (*str)[len_domain] = '/';
2725 return translate_sid_to_user;
2728 static int acls_supported(const char *path)
2730 size_t offset = offset_1st_component(path);
2731 WCHAR wroot[MAX_PATH];
2732 DWORD file_system_flags;
2734 if (offset &&
2735 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2736 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2737 &file_system_flags, NULL, 0))
2738 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2740 return 0;
2743 int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
2745 WCHAR wpath[MAX_PATH];
2746 PSID sid = NULL;
2747 PSECURITY_DESCRIPTOR descriptor = NULL;
2748 DWORD err;
2750 static wchar_t home[MAX_PATH];
2752 int result = 0;
2754 if (xutftowcs_path(wpath, path) < 0)
2755 return 0;
2758 * On Windows, the home directory is owned by the administrator, but for
2759 * all practical purposes, it belongs to the user. Do pretend that it is
2760 * owned by the user.
2762 if (!*home) {
2763 DWORD size = ARRAY_SIZE(home);
2764 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2765 if (!len || len > size)
2766 wcscpy(home, L"::N/A::");
2768 if (!wcsicmp(wpath, home))
2769 return 1;
2771 /* Get the owner SID */
2772 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2773 OWNER_SECURITY_INFORMATION |
2774 DACL_SECURITY_INFORMATION,
2775 &sid, NULL, NULL, NULL, &descriptor);
2777 if (err != ERROR_SUCCESS)
2778 error(_("failed to get owner for '%s' (%ld)"), path, err);
2779 else if (sid && IsValidSid(sid)) {
2780 /* Now, verify that the SID matches the current user's */
2781 static PSID current_user_sid;
2782 BOOL is_member;
2784 if (!current_user_sid)
2785 current_user_sid = get_current_user_sid();
2787 if (current_user_sid &&
2788 IsValidSid(current_user_sid) &&
2789 EqualSid(sid, current_user_sid))
2790 result = 1;
2791 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
2792 CheckTokenMembership(NULL, sid, &is_member) &&
2793 is_member)
2795 * If owned by the Administrators group, and the
2796 * current user is an administrator, we consider that
2797 * okay, too.
2799 result = 1;
2800 else if (report &&
2801 IsWellKnownSid(sid, WinWorldSid) &&
2802 !acls_supported(path)) {
2804 * On FAT32 volumes, ownership is not actually recorded.
2806 strbuf_addf(report, "'%s' is on a file system that does "
2807 "not record ownership\n", path);
2808 } else if (report) {
2809 PCSTR str1, str2, str3, str4;
2810 LPSTR to_free1 = NULL, to_free3 = NULL,
2811 to_local_free2 = NULL, to_local_free4 = NULL;
2813 if (user_sid_to_user_name(sid, &to_free1))
2814 str1 = to_free1;
2815 else
2816 str1 = "(inconvertible)";
2817 if (ConvertSidToStringSidA(sid, &to_local_free2))
2818 str2 = to_local_free2;
2819 else
2820 str2 = "(inconvertible)";
2822 if (!current_user_sid) {
2823 str3 = "(none)";
2824 str4 = "(none)";
2826 else if (!IsValidSid(current_user_sid)) {
2827 str3 = "(invalid)";
2828 str4 = "(invalid)";
2829 } else {
2830 if (user_sid_to_user_name(current_user_sid,
2831 &to_free3))
2832 str3 = to_free3;
2833 else
2834 str3 = "(inconvertible)";
2835 if (ConvertSidToStringSidA(current_user_sid,
2836 &to_local_free4))
2837 str4 = to_local_free4;
2838 else
2839 str4 = "(inconvertible)";
2841 strbuf_addf(report,
2842 "'%s' is owned by:\n"
2843 "\t%s (%s)\nbut the current user is:\n"
2844 "\t%s (%s)\n",
2845 path, str1, str2, str3, str4);
2846 free(to_free1);
2847 LocalFree(to_local_free2);
2848 free(to_free3);
2849 LocalFree(to_local_free4);
2854 * We can release the security descriptor struct only now because `sid`
2855 * actually points into this struct.
2857 if (descriptor)
2858 LocalFree(descriptor);
2860 return result;
2863 int is_valid_win32_path(const char *path, int allow_literal_nul)
2865 const char *p = path;
2866 int preceding_space_or_period = 0, i = 0, periods = 0;
2868 if (!protect_ntfs)
2869 return 1;
2871 skip_dos_drive_prefix((char **)&path);
2872 goto segment_start;
2874 for (;;) {
2875 char c = *(path++);
2876 switch (c) {
2877 case '\0':
2878 case '/': case '\\':
2879 /* cannot end in ` ` or `.`, except for `.` and `..` */
2880 if (preceding_space_or_period &&
2881 (i != periods || periods > 2))
2882 return 0;
2883 if (!c)
2884 return 1;
2886 i = periods = preceding_space_or_period = 0;
2888 segment_start:
2889 switch (*path) {
2890 case 'a': case 'A': /* AUX */
2891 if (((c = path[++i]) != 'u' && c != 'U') ||
2892 ((c = path[++i]) != 'x' && c != 'X')) {
2893 not_a_reserved_name:
2894 path += i;
2895 continue;
2897 break;
2898 case 'c': case 'C':
2899 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2900 if ((c = path[++i]) != 'o' && c != 'O')
2901 goto not_a_reserved_name;
2902 c = path[++i];
2903 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2904 c = path[++i];
2905 if (c < '1' || c > '9')
2906 goto not_a_reserved_name;
2907 } else if (c == 'n' || c == 'N') { /* CON */
2908 c = path[i + 1];
2909 if ((c == 'i' || c == 'I') &&
2910 ((c = path[i + 2]) == 'n' ||
2911 c == 'N') &&
2912 path[i + 3] == '$')
2913 i += 3; /* CONIN$ */
2914 else if ((c == 'o' || c == 'O') &&
2915 ((c = path[i + 2]) == 'u' ||
2916 c == 'U') &&
2917 ((c = path[i + 3]) == 't' ||
2918 c == 'T') &&
2919 path[i + 4] == '$')
2920 i += 4; /* CONOUT$ */
2921 } else
2922 goto not_a_reserved_name;
2923 break;
2924 case 'l': case 'L': /* LPT<N> */
2925 if (((c = path[++i]) != 'p' && c != 'P') ||
2926 ((c = path[++i]) != 't' && c != 'T') ||
2927 !isdigit(path[++i]))
2928 goto not_a_reserved_name;
2929 break;
2930 case 'n': case 'N': /* NUL */
2931 if (((c = path[++i]) != 'u' && c != 'U') ||
2932 ((c = path[++i]) != 'l' && c != 'L') ||
2933 (allow_literal_nul &&
2934 !path[i + 1] && p == path))
2935 goto not_a_reserved_name;
2936 break;
2937 case 'p': case 'P': /* PRN */
2938 if (((c = path[++i]) != 'r' && c != 'R') ||
2939 ((c = path[++i]) != 'n' && c != 'N'))
2940 goto not_a_reserved_name;
2941 break;
2942 default:
2943 continue;
2947 * So far, this looks like a reserved name. Let's see
2948 * whether it actually is one: trailing spaces, a file
2949 * extension, or an NTFS Alternate Data Stream do not
2950 * matter, the name is still reserved if any of those
2951 * follow immediately after the actual name.
2953 i++;
2954 if (path[i] == ' ') {
2955 preceding_space_or_period = 1;
2956 while (path[++i] == ' ')
2957 ; /* skip all spaces */
2960 c = path[i];
2961 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
2962 goto not_a_reserved_name;
2964 /* contains reserved name */
2965 return 0;
2966 case '.':
2967 periods++;
2968 /* fallthru */
2969 case ' ':
2970 preceding_space_or_period = 1;
2971 i++;
2972 continue;
2973 case ':': /* DOS drive prefix was already skipped */
2974 case '<': case '>': case '"': case '|': case '?': case '*':
2975 /* illegal character */
2976 return 0;
2977 default:
2978 if (c > '\0' && c < '\x20')
2979 /* illegal character */
2980 return 0;
2982 preceding_space_or_period = 0;
2983 i++;
2987 #if !defined(_MSC_VER)
2989 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2990 * mingw startup code, see init.c in mingw runtime).
2992 int _CRT_glob = 0;
2993 #endif
2995 static NORETURN void die_startup(void)
2997 fputs("fatal: not enough memory for initialization", stderr);
2998 exit(128);
3001 static void *malloc_startup(size_t size)
3003 void *result = malloc(size);
3004 if (!result)
3005 die_startup();
3006 return result;
3009 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
3011 len = xwcstoutf(buffer, wcs, len) + 1;
3012 return memcpy(malloc_startup(len), buffer, len);
3015 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
3016 DWORD desired_access, DWORD flags)
3018 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
3019 wchar_t buf[MAX_PATH];
3020 DWORD max = ARRAY_SIZE(buf);
3021 HANDLE handle;
3022 DWORD ret = GetEnvironmentVariableW(key, buf, max);
3024 if (!ret || ret >= max)
3025 return;
3027 /* make sure this does not leak into child processes */
3028 SetEnvironmentVariableW(key, NULL);
3029 if (!wcscmp(buf, L"off")) {
3030 close(fd);
3031 handle = GetStdHandle(std_id);
3032 if (handle != INVALID_HANDLE_VALUE)
3033 CloseHandle(handle);
3034 return;
3036 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
3037 handle = GetStdHandle(STD_OUTPUT_HANDLE);
3038 if (handle == INVALID_HANDLE_VALUE) {
3039 close(fd);
3040 handle = GetStdHandle(std_id);
3041 if (handle != INVALID_HANDLE_VALUE)
3042 CloseHandle(handle);
3043 } else {
3044 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3045 SetStdHandle(std_id, handle);
3046 dup2(new_fd, fd);
3047 /* do *not* close the new_fd: that would close stdout */
3049 return;
3051 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
3052 flags, NULL);
3053 if (handle != INVALID_HANDLE_VALUE) {
3054 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3055 SetStdHandle(std_id, handle);
3056 dup2(new_fd, fd);
3057 close(new_fd);
3061 static void maybe_redirect_std_handles(void)
3063 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
3064 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
3065 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
3066 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
3067 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
3068 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
3071 #ifdef _MSC_VER
3072 #ifdef _DEBUG
3073 #include <crtdbg.h>
3074 #endif
3075 #endif
3078 * We implement wmain() and compile with -municode, which would
3079 * normally ignore main(), but we call the latter from the former
3080 * so that we can handle non-ASCII command-line parameters
3081 * appropriately.
3083 * To be more compatible with the core git code, we convert
3084 * argv into UTF8 and pass them directly to main().
3086 int wmain(int argc, const wchar_t **wargv)
3088 int i, maxlen, exit_status;
3089 char *buffer, **save;
3090 const char **argv;
3092 trace2_initialize_clock();
3094 #ifdef _MSC_VER
3095 #ifdef _DEBUG
3096 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3097 #endif
3099 #ifdef USE_MSVC_CRTDBG
3100 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3101 #endif
3102 #endif
3104 maybe_redirect_std_handles();
3106 /* determine size of argv and environ conversion buffer */
3107 maxlen = wcslen(wargv[0]);
3108 for (i = 1; i < argc; i++)
3109 maxlen = max(maxlen, wcslen(wargv[i]));
3111 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3112 maxlen = 3 * maxlen + 1;
3113 buffer = malloc_startup(maxlen);
3116 * Create a UTF-8 version of w_argv. Also create a "save" copy
3117 * to remember all the string pointers because parse_options()
3118 * will remove claimed items from the argv that we pass down.
3120 ALLOC_ARRAY(argv, argc + 1);
3121 ALLOC_ARRAY(save, argc + 1);
3122 for (i = 0; i < argc; i++)
3123 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3124 argv[i] = save[i] = NULL;
3125 free(buffer);
3127 /* fix Windows specific environment settings */
3128 setup_windows_environment();
3130 unset_environment_variables = xstrdup("PERL5LIB");
3132 /* initialize critical section for waitpid pinfo_t list */
3133 InitializeCriticalSection(&pinfo_cs);
3135 /* set up default file mode and file modes for stdin/out/err */
3136 _fmode = _O_BINARY;
3137 _setmode(_fileno(stdin), _O_BINARY);
3138 _setmode(_fileno(stdout), _O_BINARY);
3139 _setmode(_fileno(stderr), _O_BINARY);
3141 /* initialize Unicode console */
3142 winansi_init();
3144 /* invoke the real main() using our utf8 version of argv. */
3145 exit_status = main(argc, argv);
3147 for (i = 0; i < argc; i++)
3148 free(save[i]);
3149 free(save);
3150 free(argv);
3152 return exit_status;
3155 int uname(struct utsname *buf)
3157 unsigned v = (unsigned)GetVersion();
3158 memset(buf, 0, sizeof(*buf));
3159 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3160 xsnprintf(buf->release, sizeof(buf->release),
3161 "%u.%u", v & 0xff, (v >> 8) & 0xff);
3162 /* assuming NT variants only.. */
3163 xsnprintf(buf->version, sizeof(buf->version),
3164 "%u", (v >> 16) & 0x7fff);
3165 return 0;
3168 #ifndef NO_UNIX_SOCKETS
3169 int mingw_have_unix_sockets(void)
3171 SC_HANDLE scm, srvc;
3172 SERVICE_STATUS_PROCESS status;
3173 DWORD bytes;
3174 int ret = 0;
3175 scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT);
3176 if (scm) {
3177 srvc = OpenServiceA(scm, "afunix", SERVICE_QUERY_STATUS);
3178 if (srvc) {
3179 if(QueryServiceStatusEx(srvc, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &bytes))
3180 ret = status.dwCurrentState == SERVICE_RUNNING;
3181 CloseServiceHandle(srvc);
3183 CloseServiceHandle(scm);
3185 return ret;
3187 #endif