mingw: detect when MSYS2's sh is to be spawned more robustly
[alt-git.git] / compat / mingw.c
blob5dbaae981e40fa3ef91f54a29ce9a42aaedf68c9
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include <wchar.h>
5 #include "../strbuf.h"
6 #include "../run-command.h"
7 #include "../cache.h"
8 #include "win32/lazyload.h"
9 #include "../config.h"
10 #include "dir.h"
12 #define HCAST(type, handle) ((type)(intptr_t)handle)
14 static const int delay[] = { 0, 1, 10, 20, 40 };
16 int err_win_to_posix(DWORD winerr)
18 int error = ENOSYS;
19 switch(winerr) {
20 case ERROR_ACCESS_DENIED: error = EACCES; break;
21 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
22 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
23 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
24 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
25 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
26 case ERROR_BAD_COMMAND: error = EIO; break;
27 case ERROR_BAD_DEVICE: error = ENODEV; break;
28 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
29 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
30 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
31 case ERROR_BAD_LENGTH: error = EINVAL; break;
32 case ERROR_BAD_PATHNAME: error = ENOENT; break;
33 case ERROR_BAD_PIPE: error = EPIPE; break;
34 case ERROR_BAD_UNIT: error = ENODEV; break;
35 case ERROR_BAD_USERNAME: error = EINVAL; break;
36 case ERROR_BROKEN_PIPE: error = EPIPE; break;
37 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
38 case ERROR_BUSY: error = EBUSY; break;
39 case ERROR_BUSY_DRIVE: error = EBUSY; break;
40 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
41 case ERROR_CANNOT_MAKE: error = EACCES; break;
42 case ERROR_CANTOPEN: error = EIO; break;
43 case ERROR_CANTREAD: error = EIO; break;
44 case ERROR_CANTWRITE: error = EIO; break;
45 case ERROR_CRC: error = EIO; break;
46 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
47 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
48 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
49 case ERROR_DIRECTORY: error = EINVAL; break;
50 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
51 case ERROR_DISK_CHANGE: error = EIO; break;
52 case ERROR_DISK_FULL: error = ENOSPC; break;
53 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
54 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
55 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
56 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
57 case ERROR_FILE_EXISTS: error = EEXIST; break;
58 case ERROR_FILE_INVALID: error = ENODEV; break;
59 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
60 case ERROR_GEN_FAILURE: error = EIO; break;
61 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
62 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
63 case ERROR_INVALID_ACCESS: error = EACCES; break;
64 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
65 case ERROR_INVALID_BLOCK: error = EFAULT; break;
66 case ERROR_INVALID_DATA: error = EINVAL; break;
67 case ERROR_INVALID_DRIVE: error = ENODEV; break;
68 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
69 case ERROR_INVALID_FLAGS: error = EINVAL; break;
70 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
71 case ERROR_INVALID_HANDLE: error = EBADF; break;
72 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
73 case ERROR_INVALID_NAME: error = EINVAL; break;
74 case ERROR_INVALID_OWNER: error = EINVAL; break;
75 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
76 case ERROR_INVALID_PASSWORD: error = EPERM; break;
77 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
78 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
79 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
80 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
81 case ERROR_IO_DEVICE: error = EIO; break;
82 case ERROR_IO_INCOMPLETE: error = EINTR; break;
83 case ERROR_LOCKED: error = EBUSY; break;
84 case ERROR_LOCK_VIOLATION: error = EACCES; break;
85 case ERROR_LOGON_FAILURE: error = EACCES; break;
86 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
87 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
88 case ERROR_MORE_DATA: error = EPIPE; break;
89 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
90 case ERROR_NOACCESS: error = EFAULT; break;
91 case ERROR_NONE_MAPPED: error = EINVAL; break;
92 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
93 case ERROR_NOT_READY: error = EAGAIN; break;
94 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
95 case ERROR_NO_DATA: error = EPIPE; break;
96 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
97 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
98 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
99 case ERROR_OPEN_FAILED: error = EIO; break;
100 case ERROR_OPEN_FILES: error = EBUSY; break;
101 case ERROR_OPERATION_ABORTED: error = EINTR; break;
102 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
103 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
104 case ERROR_PATH_BUSY: error = EBUSY; break;
105 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
106 case ERROR_PIPE_BUSY: error = EBUSY; break;
107 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
108 case ERROR_PIPE_LISTENING: error = EPIPE; break;
109 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
110 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
111 case ERROR_READ_FAULT: error = EIO; break;
112 case ERROR_SEEK: error = EIO; break;
113 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
114 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
115 case ERROR_SHARING_VIOLATION: error = EACCES; break;
116 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
117 case ERROR_SWAPERROR: error = ENOENT; break;
118 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
119 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
120 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
121 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
122 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
123 case ERROR_WRITE_FAULT: error = EIO; break;
124 case ERROR_WRITE_PROTECT: error = EROFS; break;
126 return error;
129 static inline int is_file_in_use_error(DWORD errcode)
131 switch (errcode) {
132 case ERROR_SHARING_VIOLATION:
133 case ERROR_ACCESS_DENIED:
134 return 1;
137 return 0;
140 static int read_yes_no_answer(void)
142 char answer[1024];
144 if (fgets(answer, sizeof(answer), stdin)) {
145 size_t answer_len = strlen(answer);
146 int got_full_line = 0, c;
148 /* remove the newline */
149 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
150 answer[answer_len-2] = '\0';
151 got_full_line = 1;
152 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
153 answer[answer_len-1] = '\0';
154 got_full_line = 1;
156 /* flush the buffer in case we did not get the full line */
157 if (!got_full_line)
158 while ((c = getchar()) != EOF && c != '\n')
160 } else
161 /* we could not read, return the
162 * default answer which is no */
163 return 0;
165 if (tolower(answer[0]) == 'y' && !answer[1])
166 return 1;
167 if (!strncasecmp(answer, "yes", sizeof(answer)))
168 return 1;
169 if (tolower(answer[0]) == 'n' && !answer[1])
170 return 0;
171 if (!strncasecmp(answer, "no", sizeof(answer)))
172 return 0;
174 /* did not find an answer we understand */
175 return -1;
178 static int ask_yes_no_if_possible(const char *format, ...)
180 char question[4096];
181 const char *retry_hook[] = { NULL, NULL, NULL };
182 va_list args;
184 va_start(args, format);
185 vsnprintf(question, sizeof(question), format, args);
186 va_end(args);
188 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
189 retry_hook[1] = question;
190 return !run_command_v_opt(retry_hook, 0);
193 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
194 return 0;
196 while (1) {
197 int answer;
198 fprintf(stderr, "%s (y/n) ", question);
200 if ((answer = read_yes_no_answer()) >= 0)
201 return answer;
203 fprintf(stderr, "Sorry, I did not understand your answer. "
204 "Please type 'y' or 'n'\n");
208 /* Windows only */
209 enum hide_dotfiles_type {
210 HIDE_DOTFILES_FALSE = 0,
211 HIDE_DOTFILES_TRUE,
212 HIDE_DOTFILES_DOTGITONLY
215 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
216 static char *unset_environment_variables;
218 int mingw_core_config(const char *var, const char *value, void *cb)
220 if (!strcmp(var, "core.hidedotfiles")) {
221 if (value && !strcasecmp(value, "dotgitonly"))
222 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
223 else
224 hide_dotfiles = git_config_bool(var, value);
225 return 0;
228 if (!strcmp(var, "core.unsetenvvars")) {
229 free(unset_environment_variables);
230 unset_environment_variables = xstrdup(value);
231 return 0;
234 return 0;
237 /* Normalizes NT paths as returned by some low-level APIs. */
238 static wchar_t *normalize_ntpath(wchar_t *wbuf)
240 int i;
241 /* fix absolute path prefixes */
242 if (wbuf[0] == '\\') {
243 /* strip NT namespace prefixes */
244 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
245 !wcsncmp(wbuf, L"\\\\?\\", 4))
246 wbuf += 4;
247 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
248 wbuf += 12;
249 /* replace remaining '...UNC\' with '\\' */
250 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
251 wbuf += 2;
252 *wbuf = '\\';
255 /* convert backslashes to slashes */
256 for (i = 0; wbuf[i]; i++)
257 if (wbuf[i] == '\\')
258 wbuf[i] = '/';
259 return wbuf;
262 int mingw_unlink(const char *pathname)
264 int ret, tries = 0;
265 wchar_t wpathname[MAX_PATH];
266 if (xutftowcs_path(wpathname, pathname) < 0)
267 return -1;
269 /* read-only files cannot be removed */
270 _wchmod(wpathname, 0666);
271 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
272 if (!is_file_in_use_error(GetLastError()))
273 break;
275 * We assume that some other process had the source or
276 * destination file open at the wrong moment and retry.
277 * In order to give the other process a higher chance to
278 * complete its operation, we give up our time slice now.
279 * If we have to retry again, we do sleep a bit.
281 Sleep(delay[tries]);
282 tries++;
284 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
285 ask_yes_no_if_possible("Unlink of file '%s' failed. "
286 "Should I try again?", pathname))
287 ret = _wunlink(wpathname);
288 return ret;
291 static int is_dir_empty(const wchar_t *wpath)
293 WIN32_FIND_DATAW findbuf;
294 HANDLE handle;
295 wchar_t wbuf[MAX_PATH + 2];
296 wcscpy(wbuf, wpath);
297 wcscat(wbuf, L"\\*");
298 handle = FindFirstFileW(wbuf, &findbuf);
299 if (handle == INVALID_HANDLE_VALUE)
300 return GetLastError() == ERROR_NO_MORE_FILES;
302 while (!wcscmp(findbuf.cFileName, L".") ||
303 !wcscmp(findbuf.cFileName, L".."))
304 if (!FindNextFileW(handle, &findbuf)) {
305 DWORD err = GetLastError();
306 FindClose(handle);
307 return err == ERROR_NO_MORE_FILES;
309 FindClose(handle);
310 return 0;
313 int mingw_rmdir(const char *pathname)
315 int ret, tries = 0;
316 wchar_t wpathname[MAX_PATH];
317 if (xutftowcs_path(wpathname, pathname) < 0)
318 return -1;
320 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
321 if (!is_file_in_use_error(GetLastError()))
322 errno = err_win_to_posix(GetLastError());
323 if (errno != EACCES)
324 break;
325 if (!is_dir_empty(wpathname)) {
326 errno = ENOTEMPTY;
327 break;
330 * We assume that some other process had the source or
331 * destination file open at the wrong moment and retry.
332 * In order to give the other process a higher chance to
333 * complete its operation, we give up our time slice now.
334 * If we have to retry again, we do sleep a bit.
336 Sleep(delay[tries]);
337 tries++;
339 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
340 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
341 "Should I try again?", pathname))
342 ret = _wrmdir(wpathname);
343 return ret;
346 static inline int needs_hiding(const char *path)
348 const char *basename;
350 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
351 return 0;
353 /* We cannot use basename(), as it would remove trailing slashes */
354 win32_skip_dos_drive_prefix((char **)&path);
355 if (!*path)
356 return 0;
358 for (basename = path; *path; path++)
359 if (is_dir_sep(*path)) {
360 do {
361 path++;
362 } while (is_dir_sep(*path));
363 /* ignore trailing slashes */
364 if (*path)
365 basename = path;
368 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
369 return *basename == '.';
371 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
372 return !strncasecmp(".git", basename, 4) &&
373 (!basename[4] || is_dir_sep(basename[4]));
376 static int set_hidden_flag(const wchar_t *path, int set)
378 DWORD original = GetFileAttributesW(path), modified;
379 if (set)
380 modified = original | FILE_ATTRIBUTE_HIDDEN;
381 else
382 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
383 if (original == modified || SetFileAttributesW(path, modified))
384 return 0;
385 errno = err_win_to_posix(GetLastError());
386 return -1;
389 int mingw_mkdir(const char *path, int mode)
391 int ret;
392 wchar_t wpath[MAX_PATH];
394 if (!is_valid_win32_path(path)) {
395 errno = EINVAL;
396 return -1;
399 if (xutftowcs_path(wpath, path) < 0)
400 return -1;
401 ret = _wmkdir(wpath);
402 if (!ret && needs_hiding(path))
403 return set_hidden_flag(wpath, 1);
404 return ret;
408 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
409 * is documented in [1] as opening a writable file handle in append mode.
410 * (It is believed that) this is atomic since it is maintained by the
411 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
413 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
415 * This trick does not appear to work for named pipes. Instead it creates
416 * a named pipe client handle that cannot be written to. Callers should
417 * just use the regular _wopen() for them. (And since client handle gets
418 * bound to a unique server handle, it isn't really an issue.)
420 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
422 HANDLE handle;
423 int fd;
424 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
426 /* only these flags are supported */
427 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
428 return errno = ENOSYS, -1;
431 * FILE_SHARE_WRITE is required to permit child processes
432 * to append to the file.
434 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
435 FILE_SHARE_WRITE | FILE_SHARE_READ,
436 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
437 if (handle == INVALID_HANDLE_VALUE)
438 return errno = err_win_to_posix(GetLastError()), -1;
441 * No O_APPEND here, because the CRT uses it only to reset the
442 * file pointer to EOF before each write(); but that is not
443 * necessary (and may lead to races) for a file created with
444 * FILE_APPEND_DATA.
446 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
447 if (fd < 0)
448 CloseHandle(handle);
449 return fd;
453 * Does the pathname map to the local named pipe filesystem?
454 * That is, does it have a "//./pipe/" prefix?
456 static int is_local_named_pipe_path(const char *filename)
458 return (is_dir_sep(filename[0]) &&
459 is_dir_sep(filename[1]) &&
460 filename[2] == '.' &&
461 is_dir_sep(filename[3]) &&
462 !strncasecmp(filename+4, "pipe", 4) &&
463 is_dir_sep(filename[8]) &&
464 filename[9]);
467 int mingw_open (const char *filename, int oflags, ...)
469 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
470 va_list args;
471 unsigned mode;
472 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
473 wchar_t wfilename[MAX_PATH];
474 open_fn_t open_fn;
476 va_start(args, oflags);
477 mode = va_arg(args, int);
478 va_end(args);
480 if (!is_valid_win32_path(filename)) {
481 errno = create ? EINVAL : ENOENT;
482 return -1;
485 if (filename && !strcmp(filename, "/dev/null"))
486 filename = "nul";
488 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
489 open_fn = mingw_open_append;
490 else
491 open_fn = _wopen;
493 if (xutftowcs_path(wfilename, filename) < 0)
494 return -1;
495 fd = open_fn(wfilename, oflags, mode);
497 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
498 DWORD attrs = GetFileAttributesW(wfilename);
499 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
500 errno = EISDIR;
502 if ((oflags & O_CREAT) && needs_hiding(filename)) {
504 * Internally, _wopen() uses the CreateFile() API which errors
505 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
506 * specified and an already existing file's attributes do not
507 * match *exactly*. As there is no mode or flag we can set that
508 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
509 * again *without* the O_CREAT flag (that corresponds to the
510 * CREATE_ALWAYS flag of CreateFile()).
512 if (fd < 0 && errno == EACCES)
513 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
514 if (fd >= 0 && set_hidden_flag(wfilename, 1))
515 warning("could not mark '%s' as hidden.", filename);
517 return fd;
520 static BOOL WINAPI ctrl_ignore(DWORD type)
522 return TRUE;
525 #undef fgetc
526 int mingw_fgetc(FILE *stream)
528 int ch;
529 if (!isatty(_fileno(stream)))
530 return fgetc(stream);
532 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
533 while (1) {
534 ch = fgetc(stream);
535 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
536 break;
538 /* Ctrl+C was pressed, simulate SIGINT and retry */
539 mingw_raise(SIGINT);
541 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
542 return ch;
545 #undef fopen
546 FILE *mingw_fopen (const char *filename, const char *otype)
548 int hide = needs_hiding(filename);
549 FILE *file;
550 wchar_t wfilename[MAX_PATH], wotype[4];
551 if (!is_valid_win32_path(filename)) {
552 int create = otype && strchr(otype, 'w');
553 errno = create ? EINVAL : ENOENT;
554 return NULL;
556 if (filename && !strcmp(filename, "/dev/null"))
557 filename = "nul";
558 if (xutftowcs_path(wfilename, filename) < 0 ||
559 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
560 return NULL;
561 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
562 error("could not unhide %s", filename);
563 return NULL;
565 file = _wfopen(wfilename, wotype);
566 if (!file && GetLastError() == ERROR_INVALID_NAME)
567 errno = ENOENT;
568 if (file && hide && set_hidden_flag(wfilename, 1))
569 warning("could not mark '%s' as hidden.", filename);
570 return file;
573 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
575 int hide = needs_hiding(filename);
576 FILE *file;
577 wchar_t wfilename[MAX_PATH], wotype[4];
578 if (!is_valid_win32_path(filename)) {
579 int create = otype && strchr(otype, 'w');
580 errno = create ? EINVAL : ENOENT;
581 return NULL;
583 if (filename && !strcmp(filename, "/dev/null"))
584 filename = "nul";
585 if (xutftowcs_path(wfilename, filename) < 0 ||
586 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
587 return NULL;
588 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
589 error("could not unhide %s", filename);
590 return NULL;
592 file = _wfreopen(wfilename, wotype, stream);
593 if (file && hide && set_hidden_flag(wfilename, 1))
594 warning("could not mark '%s' as hidden.", filename);
595 return file;
598 #undef fflush
599 int mingw_fflush(FILE *stream)
601 int ret = fflush(stream);
604 * write() is used behind the scenes of stdio output functions.
605 * Since git code does not check for errors after each stdio write
606 * operation, it can happen that write() is called by a later
607 * stdio function even if an earlier write() call failed. In the
608 * case of a pipe whose readable end was closed, only the first
609 * call to write() reports EPIPE on Windows. Subsequent write()
610 * calls report EINVAL. It is impossible to notice whether this
611 * fflush invocation triggered such a case, therefore, we have to
612 * catch all EINVAL errors whole-sale.
614 if (ret && errno == EINVAL)
615 errno = EPIPE;
617 return ret;
620 #undef write
621 ssize_t mingw_write(int fd, const void *buf, size_t len)
623 ssize_t result = write(fd, buf, len);
625 if (result < 0 && errno == EINVAL && buf) {
626 /* check if fd is a pipe */
627 HANDLE h = (HANDLE) _get_osfhandle(fd);
628 if (GetFileType(h) == FILE_TYPE_PIPE)
629 errno = EPIPE;
630 else
631 errno = EINVAL;
634 return result;
637 int mingw_access(const char *filename, int mode)
639 wchar_t wfilename[MAX_PATH];
640 if (xutftowcs_path(wfilename, filename) < 0)
641 return -1;
642 /* X_OK is not supported by the MSVCRT version */
643 return _waccess(wfilename, mode & ~X_OK);
646 int mingw_chdir(const char *dirname)
648 wchar_t wdirname[MAX_PATH];
649 if (xutftowcs_path(wdirname, dirname) < 0)
650 return -1;
651 return _wchdir(wdirname);
654 int mingw_chmod(const char *filename, int mode)
656 wchar_t wfilename[MAX_PATH];
657 if (xutftowcs_path(wfilename, filename) < 0)
658 return -1;
659 return _wchmod(wfilename, mode);
663 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
664 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
666 static inline long long filetime_to_hnsec(const FILETIME *ft)
668 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
669 /* Windows to Unix Epoch conversion */
670 return winTime - 116444736000000000LL;
673 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
675 long long hnsec = filetime_to_hnsec(ft);
676 ts->tv_sec = (time_t)(hnsec / 10000000);
677 ts->tv_nsec = (hnsec % 10000000) * 100;
681 * Verifies that safe_create_leading_directories() would succeed.
683 static int has_valid_directory_prefix(wchar_t *wfilename)
685 int n = wcslen(wfilename);
687 while (n > 0) {
688 wchar_t c = wfilename[--n];
689 DWORD attributes;
691 if (!is_dir_sep(c))
692 continue;
694 wfilename[n] = L'\0';
695 attributes = GetFileAttributesW(wfilename);
696 wfilename[n] = c;
697 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
698 attributes == FILE_ATTRIBUTE_DEVICE)
699 return 1;
700 if (attributes == INVALID_FILE_ATTRIBUTES)
701 switch (GetLastError()) {
702 case ERROR_PATH_NOT_FOUND:
703 continue;
704 case ERROR_FILE_NOT_FOUND:
705 /* This implies parent directory exists. */
706 return 1;
708 return 0;
710 return 1;
713 /* We keep the do_lstat code in a separate function to avoid recursion.
714 * When a path ends with a slash, the stat will fail with ENOENT. In
715 * this case, we strip the trailing slashes and stat again.
717 * If follow is true then act like stat() and report on the link
718 * target. Otherwise report on the link itself.
720 static int do_lstat(int follow, const char *file_name, struct stat *buf)
722 WIN32_FILE_ATTRIBUTE_DATA fdata;
723 wchar_t wfilename[MAX_PATH];
724 if (xutftowcs_path(wfilename, file_name) < 0)
725 return -1;
727 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
728 buf->st_ino = 0;
729 buf->st_gid = 0;
730 buf->st_uid = 0;
731 buf->st_nlink = 1;
732 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
733 buf->st_size = fdata.nFileSizeLow |
734 (((off_t)fdata.nFileSizeHigh)<<32);
735 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
736 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
737 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
738 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
739 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
740 WIN32_FIND_DATAW findbuf;
741 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
742 if (handle != INVALID_HANDLE_VALUE) {
743 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
744 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
745 if (follow) {
746 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
747 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
748 } else {
749 buf->st_mode = S_IFLNK;
751 buf->st_mode |= S_IREAD;
752 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
753 buf->st_mode |= S_IWRITE;
755 FindClose(handle);
758 return 0;
760 switch (GetLastError()) {
761 case ERROR_ACCESS_DENIED:
762 case ERROR_SHARING_VIOLATION:
763 case ERROR_LOCK_VIOLATION:
764 case ERROR_SHARING_BUFFER_EXCEEDED:
765 errno = EACCES;
766 break;
767 case ERROR_BUFFER_OVERFLOW:
768 errno = ENAMETOOLONG;
769 break;
770 case ERROR_NOT_ENOUGH_MEMORY:
771 errno = ENOMEM;
772 break;
773 case ERROR_PATH_NOT_FOUND:
774 if (!has_valid_directory_prefix(wfilename)) {
775 errno = ENOTDIR;
776 break;
778 /* fallthru */
779 default:
780 errno = ENOENT;
781 break;
783 return -1;
786 /* We provide our own lstat/fstat functions, since the provided
787 * lstat/fstat functions are so slow. These stat functions are
788 * tailored for Git's usage (read: fast), and are not meant to be
789 * complete. Note that Git stat()s are redirected to mingw_lstat()
790 * too, since Windows doesn't really handle symlinks that well.
792 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
794 int namelen;
795 char alt_name[PATH_MAX];
797 if (!do_lstat(follow, file_name, buf))
798 return 0;
800 /* if file_name ended in a '/', Windows returned ENOENT;
801 * try again without trailing slashes
803 if (errno != ENOENT)
804 return -1;
806 namelen = strlen(file_name);
807 if (namelen && file_name[namelen-1] != '/')
808 return -1;
809 while (namelen && file_name[namelen-1] == '/')
810 --namelen;
811 if (!namelen || namelen >= PATH_MAX)
812 return -1;
814 memcpy(alt_name, file_name, namelen);
815 alt_name[namelen] = 0;
816 return do_lstat(follow, alt_name, buf);
819 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
821 BY_HANDLE_FILE_INFORMATION fdata;
823 if (!GetFileInformationByHandle(hnd, &fdata)) {
824 errno = err_win_to_posix(GetLastError());
825 return -1;
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 return 0;
842 int mingw_lstat(const char *file_name, struct stat *buf)
844 return do_stat_internal(0, file_name, buf);
846 int mingw_stat(const char *file_name, struct stat *buf)
848 return do_stat_internal(1, file_name, buf);
851 int mingw_fstat(int fd, struct stat *buf)
853 HANDLE fh = (HANDLE)_get_osfhandle(fd);
854 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
856 switch (type) {
857 case FILE_TYPE_DISK:
858 return get_file_info_by_handle(fh, buf);
860 case FILE_TYPE_CHAR:
861 case FILE_TYPE_PIPE:
862 /* initialize stat fields */
863 memset(buf, 0, sizeof(*buf));
864 buf->st_nlink = 1;
866 if (type == FILE_TYPE_CHAR) {
867 buf->st_mode = _S_IFCHR;
868 } else {
869 buf->st_mode = _S_IFIFO;
870 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
871 buf->st_size = avail;
873 return 0;
875 default:
876 errno = EBADF;
877 return -1;
881 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
883 long long winTime = t * 10000000LL + 116444736000000000LL;
884 ft->dwLowDateTime = winTime;
885 ft->dwHighDateTime = winTime >> 32;
888 int mingw_utime (const char *file_name, const struct utimbuf *times)
890 FILETIME mft, aft;
891 int fh, rc;
892 DWORD attrs;
893 wchar_t wfilename[MAX_PATH];
894 if (xutftowcs_path(wfilename, file_name) < 0)
895 return -1;
897 /* must have write permission */
898 attrs = GetFileAttributesW(wfilename);
899 if (attrs != INVALID_FILE_ATTRIBUTES &&
900 (attrs & FILE_ATTRIBUTE_READONLY)) {
901 /* ignore errors here; open() will report them */
902 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
905 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
906 rc = -1;
907 goto revert_attrs;
910 if (times) {
911 time_t_to_filetime(times->modtime, &mft);
912 time_t_to_filetime(times->actime, &aft);
913 } else {
914 GetSystemTimeAsFileTime(&mft);
915 aft = mft;
917 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
918 errno = EINVAL;
919 rc = -1;
920 } else
921 rc = 0;
922 close(fh);
924 revert_attrs:
925 if (attrs != INVALID_FILE_ATTRIBUTES &&
926 (attrs & FILE_ATTRIBUTE_READONLY)) {
927 /* ignore errors again */
928 SetFileAttributesW(wfilename, attrs);
930 return rc;
933 #undef strftime
934 size_t mingw_strftime(char *s, size_t max,
935 const char *format, const struct tm *tm)
937 size_t ret = strftime(s, max, format, tm);
939 if (!ret && errno == EINVAL)
940 die("invalid strftime format: '%s'", format);
941 return ret;
944 unsigned int sleep (unsigned int seconds)
946 Sleep(seconds*1000);
947 return 0;
950 char *mingw_mktemp(char *template)
952 wchar_t wtemplate[MAX_PATH];
953 if (xutftowcs_path(wtemplate, template) < 0)
954 return NULL;
955 if (!_wmktemp(wtemplate))
956 return NULL;
957 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
958 return NULL;
959 return template;
962 int mkstemp(char *template)
964 char *filename = mktemp(template);
965 if (filename == NULL)
966 return -1;
967 return open(filename, O_RDWR | O_CREAT, 0600);
970 int gettimeofday(struct timeval *tv, void *tz)
972 FILETIME ft;
973 long long hnsec;
975 GetSystemTimeAsFileTime(&ft);
976 hnsec = filetime_to_hnsec(&ft);
977 tv->tv_sec = hnsec / 10000000;
978 tv->tv_usec = (hnsec % 10000000) / 10;
979 return 0;
982 int pipe(int filedes[2])
984 HANDLE h[2];
986 /* this creates non-inheritable handles */
987 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
988 errno = err_win_to_posix(GetLastError());
989 return -1;
991 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
992 if (filedes[0] < 0) {
993 CloseHandle(h[0]);
994 CloseHandle(h[1]);
995 return -1;
997 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
998 if (filedes[1] < 0) {
999 close(filedes[0]);
1000 CloseHandle(h[1]);
1001 return -1;
1003 return 0;
1006 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1008 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
1009 memcpy(result, gmtime(timep), sizeof(struct tm));
1010 return result;
1013 struct tm *localtime_r(const time_t *timep, struct tm *result)
1015 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
1016 memcpy(result, localtime(timep), sizeof(struct tm));
1017 return result;
1020 char *mingw_getcwd(char *pointer, int len)
1022 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1023 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1025 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1026 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1027 return NULL;
1029 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1030 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1031 HANDLE hnd = CreateFileW(cwd, 0,
1032 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1033 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1034 if (hnd == INVALID_HANDLE_VALUE)
1035 return NULL;
1036 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1037 CloseHandle(hnd);
1038 if (!ret || ret >= ARRAY_SIZE(wpointer))
1039 return NULL;
1040 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1041 return NULL;
1042 return pointer;
1044 if (!ret || ret >= ARRAY_SIZE(wpointer))
1045 return NULL;
1046 if (xwcstoutf(pointer, wpointer, len) < 0)
1047 return NULL;
1048 convert_slashes(pointer);
1049 return pointer;
1053 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1054 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1056 static const char *quote_arg_msvc(const char *arg)
1058 /* count chars to quote */
1059 int len = 0, n = 0;
1060 int force_quotes = 0;
1061 char *q, *d;
1062 const char *p = arg;
1063 if (!*p) force_quotes = 1;
1064 while (*p) {
1065 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1066 force_quotes = 1;
1067 else if (*p == '"')
1068 n++;
1069 else if (*p == '\\') {
1070 int count = 0;
1071 while (*p == '\\') {
1072 count++;
1073 p++;
1074 len++;
1076 if (*p == '"' || !*p)
1077 n += count*2 + 1;
1078 continue;
1080 len++;
1081 p++;
1083 if (!force_quotes && n == 0)
1084 return arg;
1086 /* insert \ where necessary */
1087 d = q = xmalloc(st_add3(len, n, 3));
1088 *d++ = '"';
1089 while (*arg) {
1090 if (*arg == '"')
1091 *d++ = '\\';
1092 else if (*arg == '\\') {
1093 int count = 0;
1094 while (*arg == '\\') {
1095 count++;
1096 *d++ = *arg++;
1098 if (*arg == '"' || !*arg) {
1099 while (count-- > 0)
1100 *d++ = '\\';
1101 /* don't escape the surrounding end quote */
1102 if (!*arg)
1103 break;
1104 *d++ = '\\';
1107 *d++ = *arg++;
1109 *d++ = '"';
1110 *d++ = '\0';
1111 return q;
1114 #include "quote.h"
1116 static const char *quote_arg_msys2(const char *arg)
1118 struct strbuf buf = STRBUF_INIT;
1119 const char *p2 = arg, *p;
1121 for (p = arg; *p; p++) {
1122 int ws = isspace(*p);
1123 if (!ws && *p != '\\' && *p != '"' && *p != '{')
1124 continue;
1125 if (!buf.len)
1126 strbuf_addch(&buf, '"');
1127 if (p != p2)
1128 strbuf_add(&buf, p2, p - p2);
1129 if (!ws && *p != '{')
1130 strbuf_addch(&buf, '\\');
1131 p2 = p;
1134 if (p == arg)
1135 strbuf_addch(&buf, '"');
1136 else if (!buf.len)
1137 return arg;
1138 else
1139 strbuf_add(&buf, p2, p - p2),
1141 strbuf_addch(&buf, '"');
1142 return strbuf_detach(&buf, 0);
1145 static const char *parse_interpreter(const char *cmd)
1147 static char buf[100];
1148 char *p, *opt;
1149 int n, fd;
1151 /* don't even try a .exe */
1152 n = strlen(cmd);
1153 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1154 return NULL;
1156 fd = open(cmd, O_RDONLY);
1157 if (fd < 0)
1158 return NULL;
1159 n = read(fd, buf, sizeof(buf)-1);
1160 close(fd);
1161 if (n < 4) /* at least '#!/x' and not error */
1162 return NULL;
1164 if (buf[0] != '#' || buf[1] != '!')
1165 return NULL;
1166 buf[n] = '\0';
1167 p = buf + strcspn(buf, "\r\n");
1168 if (!*p)
1169 return NULL;
1171 *p = '\0';
1172 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1173 return NULL;
1174 /* strip options */
1175 if ((opt = strchr(p+1, ' ')))
1176 *opt = '\0';
1177 return p+1;
1181 * exe_only means that we only want to detect .exe files, but not scripts
1182 * (which do not have an extension)
1184 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1185 int isexe, int exe_only)
1187 char path[MAX_PATH];
1188 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1190 if (!isexe && access(path, F_OK) == 0)
1191 return xstrdup(path);
1192 path[strlen(path)-4] = '\0';
1193 if ((!exe_only || isexe) && access(path, F_OK) == 0)
1194 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
1195 return xstrdup(path);
1196 return NULL;
1200 * Determines the absolute path of cmd using the split path in path.
1201 * If cmd contains a slash or backslash, no lookup is performed.
1203 static char *path_lookup(const char *cmd, int exe_only)
1205 const char *path;
1206 char *prog = NULL;
1207 int len = strlen(cmd);
1208 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1210 if (strchr(cmd, '/') || strchr(cmd, '\\'))
1211 return xstrdup(cmd);
1213 path = mingw_getenv("PATH");
1214 if (!path)
1215 return NULL;
1217 while (!prog) {
1218 const char *sep = strchrnul(path, ';');
1219 int dirlen = sep - path;
1220 if (dirlen)
1221 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1222 if (!*sep)
1223 break;
1224 path = sep + 1;
1227 return prog;
1230 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1232 while (*s && *s != c)
1233 s++;
1234 return s;
1237 /* Compare only keys */
1238 static int wenvcmp(const void *a, const void *b)
1240 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1241 size_t p_len, q_len;
1243 /* Find the keys */
1244 p_len = wcschrnul(p, L'=') - p;
1245 q_len = wcschrnul(q, L'=') - q;
1247 /* If the length differs, include the shorter key's NUL */
1248 if (p_len < q_len)
1249 p_len++;
1250 else if (p_len > q_len)
1251 p_len = q_len + 1;
1253 return _wcsnicmp(p, q, p_len);
1256 /* We need a stable sort to convert the environment between UTF-16 <-> UTF-8 */
1257 #ifndef INTERNAL_QSORT
1258 #include "qsort.c"
1259 #endif
1262 * Build an environment block combining the inherited environment
1263 * merged with the given list of settings.
1265 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1266 * Values of the form "KEY" in deltaenv delete inherited values.
1268 * Multiple entries in deltaenv for the same key are explicitly allowed.
1270 * We return a contiguous block of UNICODE strings with a final trailing
1271 * zero word.
1273 static wchar_t *make_environment_block(char **deltaenv)
1275 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1276 size_t wlen, s, delta_size, size;
1278 wchar_t **array = NULL;
1279 size_t alloc = 0, nr = 0, i;
1281 size = 1; /* for extra NUL at the end */
1283 /* If there is no deltaenv to apply, simply return a copy. */
1284 if (!deltaenv || !*deltaenv) {
1285 for (p = wenv; p && *p; ) {
1286 size_t s = wcslen(p) + 1;
1287 size += s;
1288 p += s;
1291 ALLOC_ARRAY(result, size);
1292 memcpy(result, wenv, size * sizeof(*wenv));
1293 FreeEnvironmentStringsW(wenv);
1294 return result;
1298 * If there is a deltaenv, let's accumulate all keys into `array`,
1299 * sort them using the stable git_qsort() and then copy, skipping
1300 * duplicate keys
1302 for (p = wenv; p && *p; ) {
1303 ALLOC_GROW(array, nr + 1, alloc);
1304 s = wcslen(p) + 1;
1305 array[nr++] = p;
1306 p += s;
1307 size += s;
1310 /* (over-)assess size needed for wchar version of deltaenv */
1311 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1312 delta_size += strlen(deltaenv[i]) * 2 + 1;
1313 ALLOC_ARRAY(wdeltaenv, delta_size);
1315 /* convert the deltaenv, appending to array */
1316 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1317 ALLOC_GROW(array, nr + 1, alloc);
1318 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1319 array[nr++] = p;
1320 p += wlen + 1;
1323 git_qsort(array, nr, sizeof(*array), wenvcmp);
1324 ALLOC_ARRAY(result, size + delta_size);
1326 for (p = result, i = 0; i < nr; i++) {
1327 /* Skip any duplicate keys; last one wins */
1328 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1329 i++;
1331 /* Skip "to delete" entry */
1332 if (!wcschr(array[i], L'='))
1333 continue;
1335 size = wcslen(array[i]) + 1;
1336 memcpy(p, array[i], size * sizeof(*p));
1337 p += size;
1339 *p = L'\0';
1341 free(array);
1342 free(wdeltaenv);
1343 FreeEnvironmentStringsW(wenv);
1344 return result;
1347 static void do_unset_environment_variables(void)
1349 static int done;
1350 char *p = unset_environment_variables;
1352 if (done || !p)
1353 return;
1354 done = 1;
1356 for (;;) {
1357 char *comma = strchr(p, ',');
1359 if (comma)
1360 *comma = '\0';
1361 unsetenv(p);
1362 if (!comma)
1363 break;
1364 p = comma + 1;
1368 struct pinfo_t {
1369 struct pinfo_t *next;
1370 pid_t pid;
1371 HANDLE proc;
1373 static struct pinfo_t *pinfo = NULL;
1374 CRITICAL_SECTION pinfo_cs;
1376 /* Used to match and chomp off path components */
1377 static inline int match_last_path_component(const char *path, size_t *len,
1378 const char *component)
1380 size_t component_len = strlen(component);
1381 if (*len < component_len + 1 ||
1382 !is_dir_sep(path[*len - component_len - 1]) ||
1383 fspathncmp(path + *len - component_len, component, component_len))
1384 return 0;
1385 *len -= component_len + 1;
1386 /* chomp off repeated dir separators */
1387 while (*len > 0 && is_dir_sep(path[*len - 1]))
1388 (*len)--;
1389 return 1;
1392 static int is_msys2_sh(const char *cmd)
1394 if (!cmd)
1395 return 0;
1397 if (!strcmp(cmd, "sh")) {
1398 static int ret = -1;
1399 char *p;
1401 if (ret >= 0)
1402 return ret;
1404 p = path_lookup(cmd, 0);
1405 if (!p)
1406 ret = 0;
1407 else {
1408 size_t len = strlen(p);
1410 ret = match_last_path_component(p, &len, "sh.exe") &&
1411 match_last_path_component(p, &len, "bin") &&
1412 match_last_path_component(p, &len, "usr");
1413 free(p);
1415 return ret;
1418 if (ends_with(cmd, "\\sh.exe")) {
1419 static char *sh;
1421 if (!sh)
1422 sh = path_lookup("sh", 0);
1424 return !fspathcmp(cmd, sh);
1427 return 0;
1430 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1431 const char *dir,
1432 int prepend_cmd, int fhin, int fhout, int fherr)
1434 STARTUPINFOW si;
1435 PROCESS_INFORMATION pi;
1436 struct strbuf args;
1437 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1438 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1439 BOOL ret;
1440 HANDLE cons;
1441 const char *(*quote_arg)(const char *arg) =
1442 is_msys2_sh(*argv) ? quote_arg_msys2 : quote_arg_msvc;
1444 do_unset_environment_variables();
1446 /* Determine whether or not we are associated to a console */
1447 cons = CreateFile("CONOUT$", GENERIC_WRITE,
1448 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1449 FILE_ATTRIBUTE_NORMAL, NULL);
1450 if (cons == INVALID_HANDLE_VALUE) {
1451 /* There is no console associated with this process.
1452 * Since the child is a console process, Windows
1453 * would normally create a console window. But
1454 * since we'll be redirecting std streams, we do
1455 * not need the console.
1456 * It is necessary to use DETACHED_PROCESS
1457 * instead of CREATE_NO_WINDOW to make ssh
1458 * recognize that it has no console.
1460 flags |= DETACHED_PROCESS;
1461 } else {
1462 /* There is already a console. If we specified
1463 * DETACHED_PROCESS here, too, Windows would
1464 * disassociate the child from the console.
1465 * The same is true for CREATE_NO_WINDOW.
1466 * Go figure!
1468 CloseHandle(cons);
1470 memset(&si, 0, sizeof(si));
1471 si.cb = sizeof(si);
1472 si.dwFlags = STARTF_USESTDHANDLES;
1473 si.hStdInput = winansi_get_osfhandle(fhin);
1474 si.hStdOutput = winansi_get_osfhandle(fhout);
1475 si.hStdError = winansi_get_osfhandle(fherr);
1477 if (xutftowcs_path(wcmd, cmd) < 0)
1478 return -1;
1479 if (dir && xutftowcs_path(wdir, dir) < 0)
1480 return -1;
1482 /* concatenate argv, quoting args as we go */
1483 strbuf_init(&args, 0);
1484 if (prepend_cmd) {
1485 char *quoted = (char *)quote_arg(cmd);
1486 strbuf_addstr(&args, quoted);
1487 if (quoted != cmd)
1488 free(quoted);
1490 for (; *argv; argv++) {
1491 char *quoted = (char *)quote_arg(*argv);
1492 if (*args.buf)
1493 strbuf_addch(&args, ' ');
1494 strbuf_addstr(&args, quoted);
1495 if (quoted != *argv)
1496 free(quoted);
1499 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1500 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1501 strbuf_release(&args);
1503 wenvblk = make_environment_block(deltaenv);
1505 memset(&pi, 0, sizeof(pi));
1506 ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,
1507 wenvblk, dir ? wdir : NULL, &si, &pi);
1509 free(wenvblk);
1510 free(wargs);
1512 if (!ret) {
1513 errno = ENOENT;
1514 return -1;
1516 CloseHandle(pi.hThread);
1519 * The process ID is the human-readable identifier of the process
1520 * that we want to present in log and error messages. The handle
1521 * is not useful for this purpose. But we cannot close it, either,
1522 * because it is not possible to turn a process ID into a process
1523 * handle after the process terminated.
1524 * Keep the handle in a list for waitpid.
1526 EnterCriticalSection(&pinfo_cs);
1528 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1529 info->pid = pi.dwProcessId;
1530 info->proc = pi.hProcess;
1531 info->next = pinfo;
1532 pinfo = info;
1534 LeaveCriticalSection(&pinfo_cs);
1536 return (pid_t)pi.dwProcessId;
1539 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1541 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1544 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1545 const char *dir,
1546 int fhin, int fhout, int fherr)
1548 pid_t pid;
1549 char *prog = path_lookup(cmd, 0);
1551 if (!prog) {
1552 errno = ENOENT;
1553 pid = -1;
1555 else {
1556 const char *interpr = parse_interpreter(prog);
1558 if (interpr) {
1559 const char *argv0 = argv[0];
1560 char *iprog = path_lookup(interpr, 1);
1561 argv[0] = prog;
1562 if (!iprog) {
1563 errno = ENOENT;
1564 pid = -1;
1566 else {
1567 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1568 fhin, fhout, fherr);
1569 free(iprog);
1571 argv[0] = argv0;
1573 else
1574 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1575 fhin, fhout, fherr);
1576 free(prog);
1578 return pid;
1581 static int try_shell_exec(const char *cmd, char *const *argv)
1583 const char *interpr = parse_interpreter(cmd);
1584 char *prog;
1585 int pid = 0;
1587 if (!interpr)
1588 return 0;
1589 prog = path_lookup(interpr, 1);
1590 if (prog) {
1591 int argc = 0;
1592 const char **argv2;
1593 while (argv[argc]) argc++;
1594 ALLOC_ARRAY(argv2, argc + 1);
1595 argv2[0] = (char *)cmd; /* full path to the script file */
1596 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1597 pid = mingw_spawnv(prog, argv2, 1);
1598 if (pid >= 0) {
1599 int status;
1600 if (waitpid(pid, &status, 0) < 0)
1601 status = 255;
1602 exit(status);
1604 pid = 1; /* indicate that we tried but failed */
1605 free(prog);
1606 free(argv2);
1608 return pid;
1611 int mingw_execv(const char *cmd, char *const *argv)
1613 /* check if git_command is a shell script */
1614 if (!try_shell_exec(cmd, argv)) {
1615 int pid, status;
1617 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1618 if (pid < 0)
1619 return -1;
1620 if (waitpid(pid, &status, 0) < 0)
1621 status = 255;
1622 exit(status);
1624 return -1;
1627 int mingw_execvp(const char *cmd, char *const *argv)
1629 char *prog = path_lookup(cmd, 0);
1631 if (prog) {
1632 mingw_execv(prog, argv);
1633 free(prog);
1634 } else
1635 errno = ENOENT;
1637 return -1;
1640 int mingw_kill(pid_t pid, int sig)
1642 if (pid > 0 && sig == SIGTERM) {
1643 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1645 if (TerminateProcess(h, -1)) {
1646 CloseHandle(h);
1647 return 0;
1650 errno = err_win_to_posix(GetLastError());
1651 CloseHandle(h);
1652 return -1;
1653 } else if (pid > 0 && sig == 0) {
1654 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1655 if (h) {
1656 CloseHandle(h);
1657 return 0;
1661 errno = EINVAL;
1662 return -1;
1666 * UTF-8 versions of getenv(), putenv() and unsetenv().
1667 * Internally, they use the CRT's stock UNICODE routines
1668 * to avoid data loss.
1670 char *mingw_getenv(const char *name)
1672 #define GETENV_MAX_RETAIN 64
1673 static char *values[GETENV_MAX_RETAIN];
1674 static int value_counter;
1675 int len_key, len_value;
1676 wchar_t *w_key;
1677 char *value;
1678 wchar_t w_value[32768];
1680 if (!name || !*name)
1681 return NULL;
1683 len_key = strlen(name) + 1;
1684 /* We cannot use xcalloc() here because that uses getenv() itself */
1685 w_key = calloc(len_key, sizeof(wchar_t));
1686 if (!w_key)
1687 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1688 xutftowcs(w_key, name, len_key);
1689 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1690 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1691 free(w_key);
1692 return NULL;
1694 free(w_key);
1696 len_value = len_value * 3 + 1;
1697 /* We cannot use xcalloc() here because that uses getenv() itself */
1698 value = calloc(len_value, sizeof(char));
1699 if (!value)
1700 die("Out of memory, (tried to allocate %u bytes)", len_value);
1701 xwcstoutf(value, w_value, len_value);
1704 * We return `value` which is an allocated value and the caller is NOT
1705 * expecting to have to free it, so we keep a round-robin array,
1706 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1708 free(values[value_counter]);
1709 values[value_counter++] = value;
1710 if (value_counter >= ARRAY_SIZE(values))
1711 value_counter = 0;
1713 return value;
1716 int mingw_putenv(const char *namevalue)
1718 int size;
1719 wchar_t *wide, *equal;
1720 BOOL result;
1722 if (!namevalue || !*namevalue)
1723 return 0;
1725 size = strlen(namevalue) * 2 + 1;
1726 wide = calloc(size, sizeof(wchar_t));
1727 if (!wide)
1728 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1729 xutftowcs(wide, namevalue, size);
1730 equal = wcschr(wide, L'=');
1731 if (!equal)
1732 result = SetEnvironmentVariableW(wide, NULL);
1733 else {
1734 *equal = L'\0';
1735 result = SetEnvironmentVariableW(wide, equal + 1);
1737 free(wide);
1739 if (!result)
1740 errno = err_win_to_posix(GetLastError());
1742 return result ? 0 : -1;
1746 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1747 * that service contains a numerical port, or that it is null. It
1748 * does a simple search using gethostbyname, and returns one IPv4 host
1749 * if one was found.
1751 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1752 const struct addrinfo *hints,
1753 struct addrinfo **res)
1755 struct hostent *h = NULL;
1756 struct addrinfo *ai;
1757 struct sockaddr_in *sin;
1759 if (node) {
1760 h = gethostbyname(node);
1761 if (!h)
1762 return WSAGetLastError();
1765 ai = xmalloc(sizeof(struct addrinfo));
1766 *res = ai;
1767 ai->ai_flags = 0;
1768 ai->ai_family = AF_INET;
1769 ai->ai_socktype = hints ? hints->ai_socktype : 0;
1770 switch (ai->ai_socktype) {
1771 case SOCK_STREAM:
1772 ai->ai_protocol = IPPROTO_TCP;
1773 break;
1774 case SOCK_DGRAM:
1775 ai->ai_protocol = IPPROTO_UDP;
1776 break;
1777 default:
1778 ai->ai_protocol = 0;
1779 break;
1781 ai->ai_addrlen = sizeof(struct sockaddr_in);
1782 if (hints && (hints->ai_flags & AI_CANONNAME))
1783 ai->ai_canonname = h ? xstrdup(h->h_name) : NULL;
1784 else
1785 ai->ai_canonname = NULL;
1787 sin = xcalloc(1, ai->ai_addrlen);
1788 sin->sin_family = AF_INET;
1789 /* Note: getaddrinfo is supposed to allow service to be a string,
1790 * which should be looked up using getservbyname. This is
1791 * currently not implemented */
1792 if (service)
1793 sin->sin_port = htons(atoi(service));
1794 if (h)
1795 sin->sin_addr = *(struct in_addr *)h->h_addr;
1796 else if (hints && (hints->ai_flags & AI_PASSIVE))
1797 sin->sin_addr.s_addr = INADDR_ANY;
1798 else
1799 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1800 ai->ai_addr = (struct sockaddr *)sin;
1801 ai->ai_next = NULL;
1802 return 0;
1805 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1807 free(res->ai_canonname);
1808 free(res->ai_addr);
1809 free(res);
1812 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1813 char *host, DWORD hostlen,
1814 char *serv, DWORD servlen, int flags)
1816 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1817 if (sa->sa_family != AF_INET)
1818 return EAI_FAMILY;
1819 if (!host && !serv)
1820 return EAI_NONAME;
1822 if (host && hostlen > 0) {
1823 struct hostent *ent = NULL;
1824 if (!(flags & NI_NUMERICHOST))
1825 ent = gethostbyaddr((const char *)&sin->sin_addr,
1826 sizeof(sin->sin_addr), AF_INET);
1828 if (ent)
1829 snprintf(host, hostlen, "%s", ent->h_name);
1830 else if (flags & NI_NAMEREQD)
1831 return EAI_NONAME;
1832 else
1833 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1836 if (serv && servlen > 0) {
1837 struct servent *ent = NULL;
1838 if (!(flags & NI_NUMERICSERV))
1839 ent = getservbyport(sin->sin_port,
1840 flags & NI_DGRAM ? "udp" : "tcp");
1842 if (ent)
1843 snprintf(serv, servlen, "%s", ent->s_name);
1844 else
1845 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1848 return 0;
1851 static HMODULE ipv6_dll = NULL;
1852 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1853 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1854 const struct addrinfo *hints,
1855 struct addrinfo **res);
1856 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1857 char *host, DWORD hostlen,
1858 char *serv, DWORD servlen, int flags);
1860 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1861 * don't need to try to load that one dynamically.
1864 static void socket_cleanup(void)
1866 WSACleanup();
1867 if (ipv6_dll)
1868 FreeLibrary(ipv6_dll);
1869 ipv6_dll = NULL;
1870 ipv6_freeaddrinfo = freeaddrinfo_stub;
1871 ipv6_getaddrinfo = getaddrinfo_stub;
1872 ipv6_getnameinfo = getnameinfo_stub;
1875 static void ensure_socket_initialization(void)
1877 WSADATA wsa;
1878 static int initialized = 0;
1879 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1880 const char **name;
1882 if (initialized)
1883 return;
1885 if (WSAStartup(MAKEWORD(2,2), &wsa))
1886 die("unable to initialize winsock subsystem, error %d",
1887 WSAGetLastError());
1889 for (name = libraries; *name; name++) {
1890 ipv6_dll = LoadLibraryExA(*name, NULL,
1891 LOAD_LIBRARY_SEARCH_SYSTEM32);
1892 if (!ipv6_dll)
1893 continue;
1895 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1896 GetProcAddress(ipv6_dll, "freeaddrinfo");
1897 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1898 const struct addrinfo *,
1899 struct addrinfo **))
1900 GetProcAddress(ipv6_dll, "getaddrinfo");
1901 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1902 socklen_t, char *, DWORD,
1903 char *, DWORD, int))
1904 GetProcAddress(ipv6_dll, "getnameinfo");
1905 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1906 FreeLibrary(ipv6_dll);
1907 ipv6_dll = NULL;
1908 } else
1909 break;
1911 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1912 ipv6_freeaddrinfo = freeaddrinfo_stub;
1913 ipv6_getaddrinfo = getaddrinfo_stub;
1914 ipv6_getnameinfo = getnameinfo_stub;
1917 atexit(socket_cleanup);
1918 initialized = 1;
1921 #undef gethostname
1922 int mingw_gethostname(char *name, int namelen)
1924 ensure_socket_initialization();
1925 return gethostname(name, namelen);
1928 #undef gethostbyname
1929 struct hostent *mingw_gethostbyname(const char *host)
1931 ensure_socket_initialization();
1932 return gethostbyname(host);
1935 void mingw_freeaddrinfo(struct addrinfo *res)
1937 ipv6_freeaddrinfo(res);
1940 int mingw_getaddrinfo(const char *node, const char *service,
1941 const struct addrinfo *hints, struct addrinfo **res)
1943 ensure_socket_initialization();
1944 return ipv6_getaddrinfo(node, service, hints, res);
1947 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1948 char *host, DWORD hostlen, char *serv, DWORD servlen,
1949 int flags)
1951 ensure_socket_initialization();
1952 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1955 int mingw_socket(int domain, int type, int protocol)
1957 int sockfd;
1958 SOCKET s;
1960 ensure_socket_initialization();
1961 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1962 if (s == INVALID_SOCKET) {
1964 * WSAGetLastError() values are regular BSD error codes
1965 * biased by WSABASEERR.
1966 * However, strerror() does not know about networking
1967 * specific errors, which are values beginning at 38 or so.
1968 * Therefore, we choose to leave the biased error code
1969 * in errno so that _if_ someone looks up the code somewhere,
1970 * then it is at least the number that are usually listed.
1972 errno = WSAGetLastError();
1973 return -1;
1975 /* convert into a file descriptor */
1976 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1977 closesocket(s);
1978 return error("unable to make a socket file descriptor: %s",
1979 strerror(errno));
1981 return sockfd;
1984 #undef connect
1985 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1987 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1988 return connect(s, sa, sz);
1991 #undef bind
1992 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1994 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1995 return bind(s, sa, sz);
1998 #undef setsockopt
1999 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2001 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2002 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2005 #undef shutdown
2006 int mingw_shutdown(int sockfd, int how)
2008 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2009 return shutdown(s, how);
2012 #undef listen
2013 int mingw_listen(int sockfd, int backlog)
2015 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2016 return listen(s, backlog);
2019 #undef accept
2020 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2022 int sockfd2;
2024 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2025 SOCKET s2 = accept(s1, sa, sz);
2027 /* convert into a file descriptor */
2028 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2029 int err = errno;
2030 closesocket(s2);
2031 return error("unable to make a socket file descriptor: %s",
2032 strerror(err));
2034 return sockfd2;
2037 #undef rename
2038 int mingw_rename(const char *pold, const char *pnew)
2040 DWORD attrs, gle;
2041 int tries = 0;
2042 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2043 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2044 return -1;
2047 * Try native rename() first to get errno right.
2048 * It is based on MoveFile(), which cannot overwrite existing files.
2050 if (!_wrename(wpold, wpnew))
2051 return 0;
2052 if (errno != EEXIST)
2053 return -1;
2054 repeat:
2055 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2056 return 0;
2057 /* TODO: translate more errors */
2058 gle = GetLastError();
2059 if (gle == ERROR_ACCESS_DENIED &&
2060 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2061 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2062 DWORD attrsold = GetFileAttributesW(wpold);
2063 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2064 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2065 errno = EISDIR;
2066 else if (!_wrmdir(wpnew))
2067 goto repeat;
2068 return -1;
2070 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2071 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2072 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2073 return 0;
2074 gle = GetLastError();
2075 /* revert file attributes on failure */
2076 SetFileAttributesW(wpnew, attrs);
2079 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2081 * We assume that some other process had the source or
2082 * destination file open at the wrong moment and retry.
2083 * In order to give the other process a higher chance to
2084 * complete its operation, we give up our time slice now.
2085 * If we have to retry again, we do sleep a bit.
2087 Sleep(delay[tries]);
2088 tries++;
2089 goto repeat;
2091 if (gle == ERROR_ACCESS_DENIED &&
2092 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2093 "Should I try again?", pold, pnew))
2094 goto repeat;
2096 errno = EACCES;
2097 return -1;
2101 * Note that this doesn't return the actual pagesize, but
2102 * the allocation granularity. If future Windows specific git code
2103 * needs the real getpagesize function, we need to find another solution.
2105 int mingw_getpagesize(void)
2107 SYSTEM_INFO si;
2108 GetSystemInfo(&si);
2109 return si.dwAllocationGranularity;
2112 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2113 enum EXTENDED_NAME_FORMAT {
2114 NameDisplay = 3,
2115 NameUserPrincipal = 8
2118 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2120 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2121 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2122 static wchar_t wbuffer[1024];
2123 DWORD len;
2125 if (!INIT_PROC_ADDR(GetUserNameExW))
2126 return NULL;
2128 len = ARRAY_SIZE(wbuffer);
2129 if (GetUserNameExW(type, wbuffer, &len)) {
2130 char *converted = xmalloc((len *= 3));
2131 if (xwcstoutf(converted, wbuffer, len) >= 0)
2132 return converted;
2133 free(converted);
2136 return NULL;
2139 char *mingw_query_user_email(void)
2141 return get_extended_user_info(NameUserPrincipal);
2144 struct passwd *getpwuid(int uid)
2146 static unsigned initialized;
2147 static char user_name[100];
2148 static struct passwd *p;
2149 DWORD len;
2151 if (initialized)
2152 return p;
2154 len = sizeof(user_name);
2155 if (!GetUserName(user_name, &len)) {
2156 initialized = 1;
2157 return NULL;
2160 p = xmalloc(sizeof(*p));
2161 p->pw_name = user_name;
2162 p->pw_gecos = get_extended_user_info(NameDisplay);
2163 if (!p->pw_gecos)
2164 p->pw_gecos = "unknown";
2165 p->pw_dir = NULL;
2167 initialized = 1;
2168 return p;
2171 static HANDLE timer_event;
2172 static HANDLE timer_thread;
2173 static int timer_interval;
2174 static int one_shot;
2175 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2177 /* The timer works like this:
2178 * The thread, ticktack(), is a trivial routine that most of the time
2179 * only waits to receive the signal to terminate. The main thread tells
2180 * the thread to terminate by setting the timer_event to the signalled
2181 * state.
2182 * But ticktack() interrupts the wait state after the timer's interval
2183 * length to call the signal handler.
2186 static unsigned __stdcall ticktack(void *dummy)
2188 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2189 mingw_raise(SIGALRM);
2190 if (one_shot)
2191 break;
2193 return 0;
2196 static int start_timer_thread(void)
2198 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2199 if (timer_event) {
2200 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2201 if (!timer_thread )
2202 return errno = ENOMEM,
2203 error("cannot start timer thread");
2204 } else
2205 return errno = ENOMEM,
2206 error("cannot allocate resources for timer");
2207 return 0;
2210 static void stop_timer_thread(void)
2212 if (timer_event)
2213 SetEvent(timer_event); /* tell thread to terminate */
2214 if (timer_thread) {
2215 int rc = WaitForSingleObject(timer_thread, 10000);
2216 if (rc == WAIT_TIMEOUT)
2217 error("timer thread did not terminate timely");
2218 else if (rc != WAIT_OBJECT_0)
2219 error("waiting for timer thread failed: %lu",
2220 GetLastError());
2221 CloseHandle(timer_thread);
2223 if (timer_event)
2224 CloseHandle(timer_event);
2225 timer_event = NULL;
2226 timer_thread = NULL;
2229 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2231 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2234 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2236 static const struct timeval zero;
2237 static int atexit_done;
2239 if (out != NULL)
2240 return errno = EINVAL,
2241 error("setitimer param 3 != NULL not implemented");
2242 if (!is_timeval_eq(&in->it_interval, &zero) &&
2243 !is_timeval_eq(&in->it_interval, &in->it_value))
2244 return errno = EINVAL,
2245 error("setitimer: it_interval must be zero or eq it_value");
2247 if (timer_thread)
2248 stop_timer_thread();
2250 if (is_timeval_eq(&in->it_value, &zero) &&
2251 is_timeval_eq(&in->it_interval, &zero))
2252 return 0;
2254 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2255 one_shot = is_timeval_eq(&in->it_interval, &zero);
2256 if (!atexit_done) {
2257 atexit(stop_timer_thread);
2258 atexit_done = 1;
2260 return start_timer_thread();
2263 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2265 if (sig != SIGALRM)
2266 return errno = EINVAL,
2267 error("sigaction only implemented for SIGALRM");
2268 if (out != NULL)
2269 return errno = EINVAL,
2270 error("sigaction: param 3 != NULL not implemented");
2272 timer_fn = in->sa_handler;
2273 return 0;
2276 #undef signal
2277 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2279 sig_handler_t old;
2281 switch (sig) {
2282 case SIGALRM:
2283 old = timer_fn;
2284 timer_fn = handler;
2285 break;
2287 case SIGINT:
2288 old = sigint_fn;
2289 sigint_fn = handler;
2290 break;
2292 default:
2293 return signal(sig, handler);
2296 return old;
2299 #undef raise
2300 int mingw_raise(int sig)
2302 switch (sig) {
2303 case SIGALRM:
2304 if (timer_fn == SIG_DFL) {
2305 if (isatty(STDERR_FILENO))
2306 fputs("Alarm clock\n", stderr);
2307 exit(128 + SIGALRM);
2308 } else if (timer_fn != SIG_IGN)
2309 timer_fn(SIGALRM);
2310 return 0;
2312 case SIGINT:
2313 if (sigint_fn == SIG_DFL)
2314 exit(128 + SIGINT);
2315 else if (sigint_fn != SIG_IGN)
2316 sigint_fn(SIGINT);
2317 return 0;
2319 default:
2320 return raise(sig);
2324 int link(const char *oldpath, const char *newpath)
2326 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2327 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2328 xutftowcs_path(wnewpath, newpath) < 0)
2329 return -1;
2331 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2332 errno = err_win_to_posix(GetLastError());
2333 return -1;
2335 return 0;
2338 pid_t waitpid(pid_t pid, int *status, int options)
2340 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2341 FALSE, pid);
2342 if (!h) {
2343 errno = ECHILD;
2344 return -1;
2347 if (pid > 0 && options & WNOHANG) {
2348 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2349 CloseHandle(h);
2350 return 0;
2352 options &= ~WNOHANG;
2355 if (options == 0) {
2356 struct pinfo_t **ppinfo;
2357 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2358 CloseHandle(h);
2359 return 0;
2362 if (status)
2363 GetExitCodeProcess(h, (LPDWORD)status);
2365 EnterCriticalSection(&pinfo_cs);
2367 ppinfo = &pinfo;
2368 while (*ppinfo) {
2369 struct pinfo_t *info = *ppinfo;
2370 if (info->pid == pid) {
2371 CloseHandle(info->proc);
2372 *ppinfo = info->next;
2373 free(info);
2374 break;
2376 ppinfo = &info->next;
2379 LeaveCriticalSection(&pinfo_cs);
2381 CloseHandle(h);
2382 return pid;
2384 CloseHandle(h);
2386 errno = EINVAL;
2387 return -1;
2390 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2392 int upos = 0, wpos = 0;
2393 const unsigned char *utf = (const unsigned char*) utfs;
2394 if (!utf || !wcs || wcslen < 1) {
2395 errno = EINVAL;
2396 return -1;
2398 /* reserve space for \0 */
2399 wcslen--;
2400 if (utflen < 0)
2401 utflen = INT_MAX;
2403 while (upos < utflen) {
2404 int c = utf[upos++] & 0xff;
2405 if (utflen == INT_MAX && c == 0)
2406 break;
2408 if (wpos >= wcslen) {
2409 wcs[wpos] = 0;
2410 errno = ERANGE;
2411 return -1;
2414 if (c < 0x80) {
2415 /* ASCII */
2416 wcs[wpos++] = c;
2417 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2418 (utf[upos] & 0xc0) == 0x80) {
2419 /* 2-byte utf-8 */
2420 c = ((c & 0x1f) << 6);
2421 c |= (utf[upos++] & 0x3f);
2422 wcs[wpos++] = c;
2423 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2424 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2425 (utf[upos] & 0xc0) == 0x80 &&
2426 (utf[upos + 1] & 0xc0) == 0x80) {
2427 /* 3-byte utf-8 */
2428 c = ((c & 0x0f) << 12);
2429 c |= ((utf[upos++] & 0x3f) << 6);
2430 c |= (utf[upos++] & 0x3f);
2431 wcs[wpos++] = c;
2432 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2433 wpos + 1 < wcslen &&
2434 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2435 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2436 (utf[upos] & 0xc0) == 0x80 &&
2437 (utf[upos + 1] & 0xc0) == 0x80 &&
2438 (utf[upos + 2] & 0xc0) == 0x80) {
2439 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2440 c = ((c & 0x07) << 18);
2441 c |= ((utf[upos++] & 0x3f) << 12);
2442 c |= ((utf[upos++] & 0x3f) << 6);
2443 c |= (utf[upos++] & 0x3f);
2444 c -= 0x10000;
2445 wcs[wpos++] = 0xd800 | (c >> 10);
2446 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2447 } else if (c >= 0xa0) {
2448 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2449 wcs[wpos++] = c;
2450 } else {
2451 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2452 static const char *hex = "0123456789abcdef";
2453 wcs[wpos++] = hex[c >> 4];
2454 if (wpos < wcslen)
2455 wcs[wpos++] = hex[c & 0x0f];
2458 wcs[wpos] = 0;
2459 return wpos;
2462 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2464 if (!wcs || !utf || utflen < 1) {
2465 errno = EINVAL;
2466 return -1;
2468 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2469 if (utflen)
2470 return utflen - 1;
2471 errno = ERANGE;
2472 return -1;
2475 static void setup_windows_environment(void)
2477 char *tmp = getenv("TMPDIR");
2479 /* on Windows it is TMP and TEMP */
2480 if (!tmp) {
2481 if (!(tmp = getenv("TMP")))
2482 tmp = getenv("TEMP");
2483 if (tmp) {
2484 setenv("TMPDIR", tmp, 1);
2485 tmp = getenv("TMPDIR");
2489 if (tmp) {
2491 * Convert all dir separators to forward slashes,
2492 * to help shell commands called from the Git
2493 * executable (by not mistaking the dir separators
2494 * for escape characters).
2496 convert_slashes(tmp);
2499 /* simulate TERM to enable auto-color (see color.c) */
2500 if (!getenv("TERM"))
2501 setenv("TERM", "cygwin", 1);
2504 int is_valid_win32_path(const char *path)
2506 int preceding_space_or_period = 0, i = 0, periods = 0;
2508 if (!protect_ntfs)
2509 return 1;
2511 skip_dos_drive_prefix((char **)&path);
2513 for (;;) {
2514 char c = *(path++);
2515 switch (c) {
2516 case '\0':
2517 case '/': case '\\':
2518 /* cannot end in ` ` or `.`, except for `.` and `..` */
2519 if (preceding_space_or_period &&
2520 (i != periods || periods > 2))
2521 return 0;
2522 if (!c)
2523 return 1;
2525 i = periods = preceding_space_or_period = 0;
2526 continue;
2527 case '.':
2528 periods++;
2529 /* fallthru */
2530 case ' ':
2531 preceding_space_or_period = 1;
2532 i++;
2533 continue;
2534 case ':': /* DOS drive prefix was already skipped */
2535 case '<': case '>': case '"': case '|': case '?': case '*':
2536 /* illegal character */
2537 return 0;
2538 default:
2539 if (c > '\0' && c < '\x20')
2540 /* illegal character */
2541 return 0;
2543 preceding_space_or_period = 0;
2544 i++;
2549 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2550 * mingw startup code, see init.c in mingw runtime).
2552 int _CRT_glob = 0;
2554 typedef struct {
2555 int newmode;
2556 } _startupinfo;
2558 extern int __wgetmainargs(int *argc, wchar_t ***argv, wchar_t ***env, int glob,
2559 _startupinfo *si);
2561 static NORETURN void die_startup(void)
2563 fputs("fatal: not enough memory for initialization", stderr);
2564 exit(128);
2567 static void *malloc_startup(size_t size)
2569 void *result = malloc(size);
2570 if (!result)
2571 die_startup();
2572 return result;
2575 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2577 len = xwcstoutf(buffer, wcs, len) + 1;
2578 return memcpy(malloc_startup(len), buffer, len);
2581 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2582 DWORD desired_access, DWORD flags)
2584 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2585 wchar_t buf[MAX_PATH];
2586 DWORD max = ARRAY_SIZE(buf);
2587 HANDLE handle;
2588 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2590 if (!ret || ret >= max)
2591 return;
2593 /* make sure this does not leak into child processes */
2594 SetEnvironmentVariableW(key, NULL);
2595 if (!wcscmp(buf, L"off")) {
2596 close(fd);
2597 handle = GetStdHandle(std_id);
2598 if (handle != INVALID_HANDLE_VALUE)
2599 CloseHandle(handle);
2600 return;
2602 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2603 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2604 if (handle == INVALID_HANDLE_VALUE) {
2605 close(fd);
2606 handle = GetStdHandle(std_id);
2607 if (handle != INVALID_HANDLE_VALUE)
2608 CloseHandle(handle);
2609 } else {
2610 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2611 SetStdHandle(std_id, handle);
2612 dup2(new_fd, fd);
2613 /* do *not* close the new_fd: that would close stdout */
2615 return;
2617 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2618 flags, NULL);
2619 if (handle != INVALID_HANDLE_VALUE) {
2620 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2621 SetStdHandle(std_id, handle);
2622 dup2(new_fd, fd);
2623 close(new_fd);
2627 static void maybe_redirect_std_handles(void)
2629 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2630 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2631 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2632 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2633 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2634 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2637 void mingw_startup(void)
2639 int i, maxlen, argc;
2640 char *buffer;
2641 wchar_t **wenv, **wargv;
2642 _startupinfo si;
2644 maybe_redirect_std_handles();
2646 /* get wide char arguments and environment */
2647 si.newmode = 0;
2648 if (__wgetmainargs(&argc, &wargv, &wenv, _CRT_glob, &si) < 0)
2649 die_startup();
2651 /* determine size of argv and environ conversion buffer */
2652 maxlen = wcslen(wargv[0]);
2653 for (i = 1; i < argc; i++)
2654 maxlen = max(maxlen, wcslen(wargv[i]));
2656 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2657 maxlen = 3 * maxlen + 1;
2658 buffer = malloc_startup(maxlen);
2660 /* convert command line arguments and environment to UTF-8 */
2661 for (i = 0; i < argc; i++)
2662 __argv[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2663 free(buffer);
2665 /* fix Windows specific environment settings */
2666 setup_windows_environment();
2668 unset_environment_variables = xstrdup("PERL5LIB");
2670 /* initialize critical section for waitpid pinfo_t list */
2671 InitializeCriticalSection(&pinfo_cs);
2673 /* set up default file mode and file modes for stdin/out/err */
2674 _fmode = _O_BINARY;
2675 _setmode(_fileno(stdin), _O_BINARY);
2676 _setmode(_fileno(stdout), _O_BINARY);
2677 _setmode(_fileno(stderr), _O_BINARY);
2679 /* initialize Unicode console */
2680 winansi_init();
2683 int uname(struct utsname *buf)
2685 unsigned v = (unsigned)GetVersion();
2686 memset(buf, 0, sizeof(*buf));
2687 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2688 xsnprintf(buf->release, sizeof(buf->release),
2689 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2690 /* assuming NT variants only.. */
2691 xsnprintf(buf->version, sizeof(buf->version),
2692 "%u", (v >> 16) & 0x7fff);
2693 return 0;