mingw: short-circuit the conversion of `/dev/null` to UTF-16
[git.git] / compat / mingw.c
blob03c4538ec886aebb8e5c25c370f25aa64e0c637b
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;
366 else
367 break;
370 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
371 return *basename == '.';
373 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
374 return !strncasecmp(".git", basename, 4) &&
375 (!basename[4] || is_dir_sep(basename[4]));
378 static int set_hidden_flag(const wchar_t *path, int set)
380 DWORD original = GetFileAttributesW(path), modified;
381 if (set)
382 modified = original | FILE_ATTRIBUTE_HIDDEN;
383 else
384 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
385 if (original == modified || SetFileAttributesW(path, modified))
386 return 0;
387 errno = err_win_to_posix(GetLastError());
388 return -1;
391 int mingw_mkdir(const char *path, int mode)
393 int ret;
394 wchar_t wpath[MAX_PATH];
396 if (!is_valid_win32_path(path)) {
397 errno = EINVAL;
398 return -1;
401 if (xutftowcs_path(wpath, path) < 0)
402 return -1;
403 ret = _wmkdir(wpath);
404 if (!ret && needs_hiding(path))
405 return set_hidden_flag(wpath, 1);
406 return ret;
410 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
411 * is documented in [1] as opening a writable file handle in append mode.
412 * (It is believed that) this is atomic since it is maintained by the
413 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
415 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
417 * This trick does not appear to work for named pipes. Instead it creates
418 * a named pipe client handle that cannot be written to. Callers should
419 * just use the regular _wopen() for them. (And since client handle gets
420 * bound to a unique server handle, it isn't really an issue.)
422 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
424 HANDLE handle;
425 int fd;
426 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
428 /* only these flags are supported */
429 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
430 return errno = ENOSYS, -1;
433 * FILE_SHARE_WRITE is required to permit child processes
434 * to append to the file.
436 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
437 FILE_SHARE_WRITE | FILE_SHARE_READ,
438 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
439 if (handle == INVALID_HANDLE_VALUE)
440 return errno = err_win_to_posix(GetLastError()), -1;
443 * No O_APPEND here, because the CRT uses it only to reset the
444 * file pointer to EOF before each write(); but that is not
445 * necessary (and may lead to races) for a file created with
446 * FILE_APPEND_DATA.
448 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
449 if (fd < 0)
450 CloseHandle(handle);
451 return fd;
455 * Does the pathname map to the local named pipe filesystem?
456 * That is, does it have a "//./pipe/" prefix?
458 static int is_local_named_pipe_path(const char *filename)
460 return (is_dir_sep(filename[0]) &&
461 is_dir_sep(filename[1]) &&
462 filename[2] == '.' &&
463 is_dir_sep(filename[3]) &&
464 !strncasecmp(filename+4, "pipe", 4) &&
465 is_dir_sep(filename[8]) &&
466 filename[9]);
469 int mingw_open (const char *filename, int oflags, ...)
471 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
472 va_list args;
473 unsigned mode;
474 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
475 wchar_t wfilename[MAX_PATH];
476 open_fn_t open_fn;
478 va_start(args, oflags);
479 mode = va_arg(args, int);
480 va_end(args);
482 if (!is_valid_win32_path(filename)) {
483 errno = create ? EINVAL : ENOENT;
484 return -1;
487 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
488 open_fn = mingw_open_append;
489 else
490 open_fn = _wopen;
492 if (filename && !strcmp(filename, "/dev/null"))
493 wcscpy(wfilename, L"nul");
494 else if (xutftowcs_path(wfilename, filename) < 0)
495 return -1;
497 fd = open_fn(wfilename, oflags, mode);
499 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
500 DWORD attrs = GetFileAttributesW(wfilename);
501 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
502 errno = EISDIR;
504 if ((oflags & O_CREAT) && needs_hiding(filename)) {
506 * Internally, _wopen() uses the CreateFile() API which errors
507 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
508 * specified and an already existing file's attributes do not
509 * match *exactly*. As there is no mode or flag we can set that
510 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
511 * again *without* the O_CREAT flag (that corresponds to the
512 * CREATE_ALWAYS flag of CreateFile()).
514 if (fd < 0 && errno == EACCES)
515 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
516 if (fd >= 0 && set_hidden_flag(wfilename, 1))
517 warning("could not mark '%s' as hidden.", filename);
519 return fd;
522 static BOOL WINAPI ctrl_ignore(DWORD type)
524 return TRUE;
527 #undef fgetc
528 int mingw_fgetc(FILE *stream)
530 int ch;
531 if (!isatty(_fileno(stream)))
532 return fgetc(stream);
534 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
535 while (1) {
536 ch = fgetc(stream);
537 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
538 break;
540 /* Ctrl+C was pressed, simulate SIGINT and retry */
541 mingw_raise(SIGINT);
543 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
544 return ch;
547 #undef fopen
548 FILE *mingw_fopen (const char *filename, const char *otype)
550 int hide = needs_hiding(filename);
551 FILE *file;
552 wchar_t wfilename[MAX_PATH], wotype[4];
553 if (!is_valid_win32_path(filename)) {
554 int create = otype && strchr(otype, 'w');
555 errno = create ? EINVAL : ENOENT;
556 return NULL;
558 if (filename && !strcmp(filename, "/dev/null"))
559 wcscpy(wfilename, L"nul");
560 else if (xutftowcs_path(wfilename, filename) < 0)
561 return NULL;
563 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
564 return NULL;
566 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
567 error("could not unhide %s", filename);
568 return NULL;
570 file = _wfopen(wfilename, wotype);
571 if (!file && GetLastError() == ERROR_INVALID_NAME)
572 errno = ENOENT;
573 if (file && hide && set_hidden_flag(wfilename, 1))
574 warning("could not mark '%s' as hidden.", filename);
575 return file;
578 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
580 int hide = needs_hiding(filename);
581 FILE *file;
582 wchar_t wfilename[MAX_PATH], wotype[4];
583 if (!is_valid_win32_path(filename)) {
584 int create = otype && strchr(otype, 'w');
585 errno = create ? EINVAL : ENOENT;
586 return NULL;
588 if (filename && !strcmp(filename, "/dev/null"))
589 wcscpy(wfilename, L"nul");
590 else if (xutftowcs_path(wfilename, filename) < 0)
591 return NULL;
593 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
594 return NULL;
596 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
597 error("could not unhide %s", filename);
598 return NULL;
600 file = _wfreopen(wfilename, wotype, stream);
601 if (file && hide && set_hidden_flag(wfilename, 1))
602 warning("could not mark '%s' as hidden.", filename);
603 return file;
606 #undef fflush
607 int mingw_fflush(FILE *stream)
609 int ret = fflush(stream);
612 * write() is used behind the scenes of stdio output functions.
613 * Since git code does not check for errors after each stdio write
614 * operation, it can happen that write() is called by a later
615 * stdio function even if an earlier write() call failed. In the
616 * case of a pipe whose readable end was closed, only the first
617 * call to write() reports EPIPE on Windows. Subsequent write()
618 * calls report EINVAL. It is impossible to notice whether this
619 * fflush invocation triggered such a case, therefore, we have to
620 * catch all EINVAL errors whole-sale.
622 if (ret && errno == EINVAL)
623 errno = EPIPE;
625 return ret;
628 #undef write
629 ssize_t mingw_write(int fd, const void *buf, size_t len)
631 ssize_t result = write(fd, buf, len);
633 if (result < 0 && errno == EINVAL && buf) {
634 /* check if fd is a pipe */
635 HANDLE h = (HANDLE) _get_osfhandle(fd);
636 if (GetFileType(h) == FILE_TYPE_PIPE)
637 errno = EPIPE;
638 else
639 errno = EINVAL;
642 return result;
645 int mingw_access(const char *filename, int mode)
647 wchar_t wfilename[MAX_PATH];
648 if (xutftowcs_path(wfilename, filename) < 0)
649 return -1;
650 /* X_OK is not supported by the MSVCRT version */
651 return _waccess(wfilename, mode & ~X_OK);
654 int mingw_chdir(const char *dirname)
656 wchar_t wdirname[MAX_PATH];
657 if (xutftowcs_path(wdirname, dirname) < 0)
658 return -1;
659 return _wchdir(wdirname);
662 int mingw_chmod(const char *filename, int mode)
664 wchar_t wfilename[MAX_PATH];
665 if (xutftowcs_path(wfilename, filename) < 0)
666 return -1;
667 return _wchmod(wfilename, mode);
671 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
672 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
674 static inline long long filetime_to_hnsec(const FILETIME *ft)
676 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
677 /* Windows to Unix Epoch conversion */
678 return winTime - 116444736000000000LL;
681 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
683 long long hnsec = filetime_to_hnsec(ft);
684 ts->tv_sec = (time_t)(hnsec / 10000000);
685 ts->tv_nsec = (hnsec % 10000000) * 100;
689 * Verifies that safe_create_leading_directories() would succeed.
691 static int has_valid_directory_prefix(wchar_t *wfilename)
693 int n = wcslen(wfilename);
695 while (n > 0) {
696 wchar_t c = wfilename[--n];
697 DWORD attributes;
699 if (!is_dir_sep(c))
700 continue;
702 wfilename[n] = L'\0';
703 attributes = GetFileAttributesW(wfilename);
704 wfilename[n] = c;
705 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
706 attributes == FILE_ATTRIBUTE_DEVICE)
707 return 1;
708 if (attributes == INVALID_FILE_ATTRIBUTES)
709 switch (GetLastError()) {
710 case ERROR_PATH_NOT_FOUND:
711 continue;
712 case ERROR_FILE_NOT_FOUND:
713 /* This implies parent directory exists. */
714 return 1;
716 return 0;
718 return 1;
721 /* We keep the do_lstat code in a separate function to avoid recursion.
722 * When a path ends with a slash, the stat will fail with ENOENT. In
723 * this case, we strip the trailing slashes and stat again.
725 * If follow is true then act like stat() and report on the link
726 * target. Otherwise report on the link itself.
728 static int do_lstat(int follow, const char *file_name, struct stat *buf)
730 WIN32_FILE_ATTRIBUTE_DATA fdata;
731 wchar_t wfilename[MAX_PATH];
732 if (xutftowcs_path(wfilename, file_name) < 0)
733 return -1;
735 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
736 buf->st_ino = 0;
737 buf->st_gid = 0;
738 buf->st_uid = 0;
739 buf->st_nlink = 1;
740 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
741 buf->st_size = fdata.nFileSizeLow |
742 (((off_t)fdata.nFileSizeHigh)<<32);
743 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
744 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
745 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
746 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
747 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
748 WIN32_FIND_DATAW findbuf;
749 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
750 if (handle != INVALID_HANDLE_VALUE) {
751 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
752 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
753 if (follow) {
754 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
755 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
756 } else {
757 buf->st_mode = S_IFLNK;
759 buf->st_mode |= S_IREAD;
760 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
761 buf->st_mode |= S_IWRITE;
763 FindClose(handle);
766 return 0;
768 switch (GetLastError()) {
769 case ERROR_ACCESS_DENIED:
770 case ERROR_SHARING_VIOLATION:
771 case ERROR_LOCK_VIOLATION:
772 case ERROR_SHARING_BUFFER_EXCEEDED:
773 errno = EACCES;
774 break;
775 case ERROR_BUFFER_OVERFLOW:
776 errno = ENAMETOOLONG;
777 break;
778 case ERROR_NOT_ENOUGH_MEMORY:
779 errno = ENOMEM;
780 break;
781 case ERROR_PATH_NOT_FOUND:
782 if (!has_valid_directory_prefix(wfilename)) {
783 errno = ENOTDIR;
784 break;
786 /* fallthru */
787 default:
788 errno = ENOENT;
789 break;
791 return -1;
794 /* We provide our own lstat/fstat functions, since the provided
795 * lstat/fstat functions are so slow. These stat functions are
796 * tailored for Git's usage (read: fast), and are not meant to be
797 * complete. Note that Git stat()s are redirected to mingw_lstat()
798 * too, since Windows doesn't really handle symlinks that well.
800 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
802 int namelen;
803 char alt_name[PATH_MAX];
805 if (!do_lstat(follow, file_name, buf))
806 return 0;
808 /* if file_name ended in a '/', Windows returned ENOENT;
809 * try again without trailing slashes
811 if (errno != ENOENT)
812 return -1;
814 namelen = strlen(file_name);
815 if (namelen && file_name[namelen-1] != '/')
816 return -1;
817 while (namelen && file_name[namelen-1] == '/')
818 --namelen;
819 if (!namelen || namelen >= PATH_MAX)
820 return -1;
822 memcpy(alt_name, file_name, namelen);
823 alt_name[namelen] = 0;
824 return do_lstat(follow, alt_name, buf);
827 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
829 BY_HANDLE_FILE_INFORMATION fdata;
831 if (!GetFileInformationByHandle(hnd, &fdata)) {
832 errno = err_win_to_posix(GetLastError());
833 return -1;
836 buf->st_ino = 0;
837 buf->st_gid = 0;
838 buf->st_uid = 0;
839 buf->st_nlink = 1;
840 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
841 buf->st_size = fdata.nFileSizeLow |
842 (((off_t)fdata.nFileSizeHigh)<<32);
843 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
844 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
845 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
846 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
847 return 0;
850 int mingw_lstat(const char *file_name, struct stat *buf)
852 return do_stat_internal(0, file_name, buf);
854 int mingw_stat(const char *file_name, struct stat *buf)
856 return do_stat_internal(1, file_name, buf);
859 int mingw_fstat(int fd, struct stat *buf)
861 HANDLE fh = (HANDLE)_get_osfhandle(fd);
862 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
864 switch (type) {
865 case FILE_TYPE_DISK:
866 return get_file_info_by_handle(fh, buf);
868 case FILE_TYPE_CHAR:
869 case FILE_TYPE_PIPE:
870 /* initialize stat fields */
871 memset(buf, 0, sizeof(*buf));
872 buf->st_nlink = 1;
874 if (type == FILE_TYPE_CHAR) {
875 buf->st_mode = _S_IFCHR;
876 } else {
877 buf->st_mode = _S_IFIFO;
878 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
879 buf->st_size = avail;
881 return 0;
883 default:
884 errno = EBADF;
885 return -1;
889 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
891 long long winTime = t * 10000000LL + 116444736000000000LL;
892 ft->dwLowDateTime = winTime;
893 ft->dwHighDateTime = winTime >> 32;
896 int mingw_utime (const char *file_name, const struct utimbuf *times)
898 FILETIME mft, aft;
899 int fh, rc;
900 DWORD attrs;
901 wchar_t wfilename[MAX_PATH];
902 if (xutftowcs_path(wfilename, file_name) < 0)
903 return -1;
905 /* must have write permission */
906 attrs = GetFileAttributesW(wfilename);
907 if (attrs != INVALID_FILE_ATTRIBUTES &&
908 (attrs & FILE_ATTRIBUTE_READONLY)) {
909 /* ignore errors here; open() will report them */
910 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
913 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
914 rc = -1;
915 goto revert_attrs;
918 if (times) {
919 time_t_to_filetime(times->modtime, &mft);
920 time_t_to_filetime(times->actime, &aft);
921 } else {
922 GetSystemTimeAsFileTime(&mft);
923 aft = mft;
925 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
926 errno = EINVAL;
927 rc = -1;
928 } else
929 rc = 0;
930 close(fh);
932 revert_attrs:
933 if (attrs != INVALID_FILE_ATTRIBUTES &&
934 (attrs & FILE_ATTRIBUTE_READONLY)) {
935 /* ignore errors again */
936 SetFileAttributesW(wfilename, attrs);
938 return rc;
941 #undef strftime
942 size_t mingw_strftime(char *s, size_t max,
943 const char *format, const struct tm *tm)
945 size_t ret = strftime(s, max, format, tm);
947 if (!ret && errno == EINVAL)
948 die("invalid strftime format: '%s'", format);
949 return ret;
952 unsigned int sleep (unsigned int seconds)
954 Sleep(seconds*1000);
955 return 0;
958 char *mingw_mktemp(char *template)
960 wchar_t wtemplate[MAX_PATH];
961 if (xutftowcs_path(wtemplate, template) < 0)
962 return NULL;
963 if (!_wmktemp(wtemplate))
964 return NULL;
965 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
966 return NULL;
967 return template;
970 int mkstemp(char *template)
972 char *filename = mktemp(template);
973 if (filename == NULL)
974 return -1;
975 return open(filename, O_RDWR | O_CREAT, 0600);
978 int gettimeofday(struct timeval *tv, void *tz)
980 FILETIME ft;
981 long long hnsec;
983 GetSystemTimeAsFileTime(&ft);
984 hnsec = filetime_to_hnsec(&ft);
985 tv->tv_sec = hnsec / 10000000;
986 tv->tv_usec = (hnsec % 10000000) / 10;
987 return 0;
990 int pipe(int filedes[2])
992 HANDLE h[2];
994 /* this creates non-inheritable handles */
995 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
996 errno = err_win_to_posix(GetLastError());
997 return -1;
999 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1000 if (filedes[0] < 0) {
1001 CloseHandle(h[0]);
1002 CloseHandle(h[1]);
1003 return -1;
1005 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1006 if (filedes[1] < 0) {
1007 close(filedes[0]);
1008 CloseHandle(h[1]);
1009 return -1;
1011 return 0;
1014 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1016 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
1017 memcpy(result, gmtime(timep), sizeof(struct tm));
1018 return result;
1021 struct tm *localtime_r(const time_t *timep, struct tm *result)
1023 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
1024 memcpy(result, localtime(timep), sizeof(struct tm));
1025 return result;
1028 char *mingw_getcwd(char *pointer, int len)
1030 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1031 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1033 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1034 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1035 return NULL;
1037 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1038 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1039 HANDLE hnd = CreateFileW(cwd, 0,
1040 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1041 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1042 if (hnd == INVALID_HANDLE_VALUE)
1043 return NULL;
1044 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1045 CloseHandle(hnd);
1046 if (!ret || ret >= ARRAY_SIZE(wpointer))
1047 return NULL;
1048 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1049 return NULL;
1050 return pointer;
1052 if (!ret || ret >= ARRAY_SIZE(wpointer))
1053 return NULL;
1054 if (xwcstoutf(pointer, wpointer, len) < 0)
1055 return NULL;
1056 convert_slashes(pointer);
1057 return pointer;
1061 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1062 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1064 static const char *quote_arg_msvc(const char *arg)
1066 /* count chars to quote */
1067 int len = 0, n = 0;
1068 int force_quotes = 0;
1069 char *q, *d;
1070 const char *p = arg;
1071 if (!*p) force_quotes = 1;
1072 while (*p) {
1073 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1074 force_quotes = 1;
1075 else if (*p == '"')
1076 n++;
1077 else if (*p == '\\') {
1078 int count = 0;
1079 while (*p == '\\') {
1080 count++;
1081 p++;
1082 len++;
1084 if (*p == '"' || !*p)
1085 n += count*2 + 1;
1086 continue;
1088 len++;
1089 p++;
1091 if (!force_quotes && n == 0)
1092 return arg;
1094 /* insert \ where necessary */
1095 d = q = xmalloc(st_add3(len, n, 3));
1096 *d++ = '"';
1097 while (*arg) {
1098 if (*arg == '"')
1099 *d++ = '\\';
1100 else if (*arg == '\\') {
1101 int count = 0;
1102 while (*arg == '\\') {
1103 count++;
1104 *d++ = *arg++;
1106 if (*arg == '"' || !*arg) {
1107 while (count-- > 0)
1108 *d++ = '\\';
1109 /* don't escape the surrounding end quote */
1110 if (!*arg)
1111 break;
1112 *d++ = '\\';
1115 *d++ = *arg++;
1117 *d++ = '"';
1118 *d++ = '\0';
1119 return q;
1122 #include "quote.h"
1124 static const char *quote_arg_msys2(const char *arg)
1126 struct strbuf buf = STRBUF_INIT;
1127 const char *p2 = arg, *p;
1129 for (p = arg; *p; p++) {
1130 int ws = isspace(*p);
1131 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1132 *p != '?' && *p != '*' && *p != '~')
1133 continue;
1134 if (!buf.len)
1135 strbuf_addch(&buf, '"');
1136 if (p != p2)
1137 strbuf_add(&buf, p2, p - p2);
1138 if (*p == '\\' || *p == '"')
1139 strbuf_addch(&buf, '\\');
1140 p2 = p;
1143 if (p == arg)
1144 strbuf_addch(&buf, '"');
1145 else if (!buf.len)
1146 return arg;
1147 else
1148 strbuf_add(&buf, p2, p - p2);
1150 strbuf_addch(&buf, '"');
1151 return strbuf_detach(&buf, 0);
1154 static const char *parse_interpreter(const char *cmd)
1156 static char buf[100];
1157 char *p, *opt;
1158 int n, fd;
1160 /* don't even try a .exe */
1161 n = strlen(cmd);
1162 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1163 return NULL;
1165 fd = open(cmd, O_RDONLY);
1166 if (fd < 0)
1167 return NULL;
1168 n = read(fd, buf, sizeof(buf)-1);
1169 close(fd);
1170 if (n < 4) /* at least '#!/x' and not error */
1171 return NULL;
1173 if (buf[0] != '#' || buf[1] != '!')
1174 return NULL;
1175 buf[n] = '\0';
1176 p = buf + strcspn(buf, "\r\n");
1177 if (!*p)
1178 return NULL;
1180 *p = '\0';
1181 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1182 return NULL;
1183 /* strip options */
1184 if ((opt = strchr(p+1, ' ')))
1185 *opt = '\0';
1186 return p+1;
1190 * exe_only means that we only want to detect .exe files, but not scripts
1191 * (which do not have an extension)
1193 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1194 int isexe, int exe_only)
1196 char path[MAX_PATH];
1197 wchar_t wpath[MAX_PATH];
1198 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1200 if (xutftowcs_path(wpath, path) < 0)
1201 return NULL;
1203 if (!isexe && _waccess(wpath, F_OK) == 0)
1204 return xstrdup(path);
1205 wpath[wcslen(wpath)-4] = '\0';
1206 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1207 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1208 path[strlen(path)-4] = '\0';
1209 return xstrdup(path);
1212 return NULL;
1216 * Determines the absolute path of cmd using the split path in path.
1217 * If cmd contains a slash or backslash, no lookup is performed.
1219 static char *path_lookup(const char *cmd, int exe_only)
1221 const char *path;
1222 char *prog = NULL;
1223 int len = strlen(cmd);
1224 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1226 if (strchr(cmd, '/') || strchr(cmd, '\\'))
1227 return xstrdup(cmd);
1229 path = mingw_getenv("PATH");
1230 if (!path)
1231 return NULL;
1233 while (!prog) {
1234 const char *sep = strchrnul(path, ';');
1235 int dirlen = sep - path;
1236 if (dirlen)
1237 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1238 if (!*sep)
1239 break;
1240 path = sep + 1;
1243 return prog;
1246 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1248 while (*s && *s != c)
1249 s++;
1250 return s;
1253 /* Compare only keys */
1254 static int wenvcmp(const void *a, const void *b)
1256 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1257 size_t p_len, q_len;
1259 /* Find the keys */
1260 p_len = wcschrnul(p, L'=') - p;
1261 q_len = wcschrnul(q, L'=') - q;
1263 /* If the length differs, include the shorter key's NUL */
1264 if (p_len < q_len)
1265 p_len++;
1266 else if (p_len > q_len)
1267 p_len = q_len + 1;
1269 return _wcsnicmp(p, q, p_len);
1273 * Build an environment block combining the inherited environment
1274 * merged with the given list of settings.
1276 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1277 * Values of the form "KEY" in deltaenv delete inherited values.
1279 * Multiple entries in deltaenv for the same key are explicitly allowed.
1281 * We return a contiguous block of UNICODE strings with a final trailing
1282 * zero word.
1284 static wchar_t *make_environment_block(char **deltaenv)
1286 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1287 size_t wlen, s, delta_size, size;
1289 wchar_t **array = NULL;
1290 size_t alloc = 0, nr = 0, i;
1292 size = 1; /* for extra NUL at the end */
1294 /* If there is no deltaenv to apply, simply return a copy. */
1295 if (!deltaenv || !*deltaenv) {
1296 for (p = wenv; p && *p; ) {
1297 size_t s = wcslen(p) + 1;
1298 size += s;
1299 p += s;
1302 ALLOC_ARRAY(result, size);
1303 COPY_ARRAY(result, wenv, size);
1304 FreeEnvironmentStringsW(wenv);
1305 return result;
1309 * If there is a deltaenv, let's accumulate all keys into `array`,
1310 * sort them using the stable git_stable_qsort() and then copy,
1311 * skipping duplicate keys
1313 for (p = wenv; p && *p; ) {
1314 ALLOC_GROW(array, nr + 1, alloc);
1315 s = wcslen(p) + 1;
1316 array[nr++] = p;
1317 p += s;
1318 size += s;
1321 /* (over-)assess size needed for wchar version of deltaenv */
1322 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1323 delta_size += strlen(deltaenv[i]) * 2 + 1;
1324 ALLOC_ARRAY(wdeltaenv, delta_size);
1326 /* convert the deltaenv, appending to array */
1327 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1328 ALLOC_GROW(array, nr + 1, alloc);
1329 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1330 array[nr++] = p;
1331 p += wlen + 1;
1334 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1335 ALLOC_ARRAY(result, size + delta_size);
1337 for (p = result, i = 0; i < nr; i++) {
1338 /* Skip any duplicate keys; last one wins */
1339 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1340 i++;
1342 /* Skip "to delete" entry */
1343 if (!wcschr(array[i], L'='))
1344 continue;
1346 size = wcslen(array[i]) + 1;
1347 COPY_ARRAY(p, array[i], size);
1348 p += size;
1350 *p = L'\0';
1352 free(array);
1353 free(wdeltaenv);
1354 FreeEnvironmentStringsW(wenv);
1355 return result;
1358 static void do_unset_environment_variables(void)
1360 static int done;
1361 char *p = unset_environment_variables;
1363 if (done || !p)
1364 return;
1365 done = 1;
1367 for (;;) {
1368 char *comma = strchr(p, ',');
1370 if (comma)
1371 *comma = '\0';
1372 unsetenv(p);
1373 if (!comma)
1374 break;
1375 p = comma + 1;
1379 struct pinfo_t {
1380 struct pinfo_t *next;
1381 pid_t pid;
1382 HANDLE proc;
1384 static struct pinfo_t *pinfo = NULL;
1385 CRITICAL_SECTION pinfo_cs;
1387 /* Used to match and chomp off path components */
1388 static inline int match_last_path_component(const char *path, size_t *len,
1389 const char *component)
1391 size_t component_len = strlen(component);
1392 if (*len < component_len + 1 ||
1393 !is_dir_sep(path[*len - component_len - 1]) ||
1394 fspathncmp(path + *len - component_len, component, component_len))
1395 return 0;
1396 *len -= component_len + 1;
1397 /* chomp off repeated dir separators */
1398 while (*len > 0 && is_dir_sep(path[*len - 1]))
1399 (*len)--;
1400 return 1;
1403 static int is_msys2_sh(const char *cmd)
1405 if (!cmd)
1406 return 0;
1408 if (!strcmp(cmd, "sh")) {
1409 static int ret = -1;
1410 char *p;
1412 if (ret >= 0)
1413 return ret;
1415 p = path_lookup(cmd, 0);
1416 if (!p)
1417 ret = 0;
1418 else {
1419 size_t len = strlen(p);
1421 ret = match_last_path_component(p, &len, "sh.exe") &&
1422 match_last_path_component(p, &len, "bin") &&
1423 match_last_path_component(p, &len, "usr");
1424 free(p);
1426 return ret;
1429 if (ends_with(cmd, "\\sh.exe")) {
1430 static char *sh;
1432 if (!sh)
1433 sh = path_lookup("sh", 0);
1435 return !fspathcmp(cmd, sh);
1438 return 0;
1441 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1442 const char *dir,
1443 int prepend_cmd, int fhin, int fhout, int fherr)
1445 STARTUPINFOW si;
1446 PROCESS_INFORMATION pi;
1447 struct strbuf args;
1448 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1449 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1450 BOOL ret;
1451 HANDLE cons;
1452 const char *(*quote_arg)(const char *arg) =
1453 is_msys2_sh(cmd ? cmd : *argv) ?
1454 quote_arg_msys2 : quote_arg_msvc;
1456 do_unset_environment_variables();
1458 /* Determine whether or not we are associated to a console */
1459 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1460 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1461 FILE_ATTRIBUTE_NORMAL, NULL);
1462 if (cons == INVALID_HANDLE_VALUE) {
1463 /* There is no console associated with this process.
1464 * Since the child is a console process, Windows
1465 * would normally create a console window. But
1466 * since we'll be redirecting std streams, we do
1467 * not need the console.
1468 * It is necessary to use DETACHED_PROCESS
1469 * instead of CREATE_NO_WINDOW to make ssh
1470 * recognize that it has no console.
1472 flags |= DETACHED_PROCESS;
1473 } else {
1474 /* There is already a console. If we specified
1475 * DETACHED_PROCESS here, too, Windows would
1476 * disassociate the child from the console.
1477 * The same is true for CREATE_NO_WINDOW.
1478 * Go figure!
1480 CloseHandle(cons);
1482 memset(&si, 0, sizeof(si));
1483 si.cb = sizeof(si);
1484 si.dwFlags = STARTF_USESTDHANDLES;
1485 si.hStdInput = winansi_get_osfhandle(fhin);
1486 si.hStdOutput = winansi_get_osfhandle(fhout);
1487 si.hStdError = winansi_get_osfhandle(fherr);
1489 if (*argv && !strcmp(cmd, *argv))
1490 wcmd[0] = L'\0';
1491 else if (xutftowcs_path(wcmd, cmd) < 0)
1492 return -1;
1493 if (dir && xutftowcs_path(wdir, dir) < 0)
1494 return -1;
1496 /* concatenate argv, quoting args as we go */
1497 strbuf_init(&args, 0);
1498 if (prepend_cmd) {
1499 char *quoted = (char *)quote_arg(cmd);
1500 strbuf_addstr(&args, quoted);
1501 if (quoted != cmd)
1502 free(quoted);
1504 for (; *argv; argv++) {
1505 char *quoted = (char *)quote_arg(*argv);
1506 if (*args.buf)
1507 strbuf_addch(&args, ' ');
1508 strbuf_addstr(&args, quoted);
1509 if (quoted != *argv)
1510 free(quoted);
1513 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1514 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1515 strbuf_release(&args);
1517 wenvblk = make_environment_block(deltaenv);
1519 memset(&pi, 0, sizeof(pi));
1520 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL, TRUE,
1521 flags, wenvblk, dir ? wdir : NULL, &si, &pi);
1523 free(wenvblk);
1524 free(wargs);
1526 if (!ret) {
1527 errno = ENOENT;
1528 return -1;
1530 CloseHandle(pi.hThread);
1533 * The process ID is the human-readable identifier of the process
1534 * that we want to present in log and error messages. The handle
1535 * is not useful for this purpose. But we cannot close it, either,
1536 * because it is not possible to turn a process ID into a process
1537 * handle after the process terminated.
1538 * Keep the handle in a list for waitpid.
1540 EnterCriticalSection(&pinfo_cs);
1542 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1543 info->pid = pi.dwProcessId;
1544 info->proc = pi.hProcess;
1545 info->next = pinfo;
1546 pinfo = info;
1548 LeaveCriticalSection(&pinfo_cs);
1550 return (pid_t)pi.dwProcessId;
1553 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1555 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1558 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1559 const char *dir,
1560 int fhin, int fhout, int fherr)
1562 pid_t pid;
1563 char *prog = path_lookup(cmd, 0);
1565 if (!prog) {
1566 errno = ENOENT;
1567 pid = -1;
1569 else {
1570 const char *interpr = parse_interpreter(prog);
1572 if (interpr) {
1573 const char *argv0 = argv[0];
1574 char *iprog = path_lookup(interpr, 1);
1575 argv[0] = prog;
1576 if (!iprog) {
1577 errno = ENOENT;
1578 pid = -1;
1580 else {
1581 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1582 fhin, fhout, fherr);
1583 free(iprog);
1585 argv[0] = argv0;
1587 else
1588 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1589 fhin, fhout, fherr);
1590 free(prog);
1592 return pid;
1595 static int try_shell_exec(const char *cmd, char *const *argv)
1597 const char *interpr = parse_interpreter(cmd);
1598 char *prog;
1599 int pid = 0;
1601 if (!interpr)
1602 return 0;
1603 prog = path_lookup(interpr, 1);
1604 if (prog) {
1605 int exec_id;
1606 int argc = 0;
1607 #ifndef _MSC_VER
1608 const
1609 #endif
1610 char **argv2;
1611 while (argv[argc]) argc++;
1612 ALLOC_ARRAY(argv2, argc + 1);
1613 argv2[0] = (char *)cmd; /* full path to the script file */
1614 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1615 exec_id = trace2_exec(prog, argv2);
1616 pid = mingw_spawnv(prog, argv2, 1);
1617 if (pid >= 0) {
1618 int status;
1619 if (waitpid(pid, &status, 0) < 0)
1620 status = 255;
1621 trace2_exec_result(exec_id, status);
1622 exit(status);
1624 trace2_exec_result(exec_id, -1);
1625 pid = 1; /* indicate that we tried but failed */
1626 free(prog);
1627 free(argv2);
1629 return pid;
1632 int mingw_execv(const char *cmd, char *const *argv)
1634 /* check if git_command is a shell script */
1635 if (!try_shell_exec(cmd, argv)) {
1636 int pid, status;
1637 int exec_id;
1639 exec_id = trace2_exec(cmd, (const char **)argv);
1640 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1641 if (pid < 0) {
1642 trace2_exec_result(exec_id, -1);
1643 return -1;
1645 if (waitpid(pid, &status, 0) < 0)
1646 status = 255;
1647 trace2_exec_result(exec_id, status);
1648 exit(status);
1650 return -1;
1653 int mingw_execvp(const char *cmd, char *const *argv)
1655 char *prog = path_lookup(cmd, 0);
1657 if (prog) {
1658 mingw_execv(prog, argv);
1659 free(prog);
1660 } else
1661 errno = ENOENT;
1663 return -1;
1666 int mingw_kill(pid_t pid, int sig)
1668 if (pid > 0 && sig == SIGTERM) {
1669 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1671 if (TerminateProcess(h, -1)) {
1672 CloseHandle(h);
1673 return 0;
1676 errno = err_win_to_posix(GetLastError());
1677 CloseHandle(h);
1678 return -1;
1679 } else if (pid > 0 && sig == 0) {
1680 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1681 if (h) {
1682 CloseHandle(h);
1683 return 0;
1687 errno = EINVAL;
1688 return -1;
1692 * UTF-8 versions of getenv(), putenv() and unsetenv().
1693 * Internally, they use the CRT's stock UNICODE routines
1694 * to avoid data loss.
1696 char *mingw_getenv(const char *name)
1698 #define GETENV_MAX_RETAIN 64
1699 static char *values[GETENV_MAX_RETAIN];
1700 static int value_counter;
1701 int len_key, len_value;
1702 wchar_t *w_key;
1703 char *value;
1704 wchar_t w_value[32768];
1706 if (!name || !*name)
1707 return NULL;
1709 len_key = strlen(name) + 1;
1710 /* We cannot use xcalloc() here because that uses getenv() itself */
1711 w_key = calloc(len_key, sizeof(wchar_t));
1712 if (!w_key)
1713 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1714 xutftowcs(w_key, name, len_key);
1715 /* GetEnvironmentVariableW() only sets the last error upon failure */
1716 SetLastError(ERROR_SUCCESS);
1717 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1718 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1719 free(w_key);
1720 return NULL;
1722 free(w_key);
1724 len_value = len_value * 3 + 1;
1725 /* We cannot use xcalloc() here because that uses getenv() itself */
1726 value = calloc(len_value, sizeof(char));
1727 if (!value)
1728 die("Out of memory, (tried to allocate %u bytes)", len_value);
1729 xwcstoutf(value, w_value, len_value);
1732 * We return `value` which is an allocated value and the caller is NOT
1733 * expecting to have to free it, so we keep a round-robin array,
1734 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1736 free(values[value_counter]);
1737 values[value_counter++] = value;
1738 if (value_counter >= ARRAY_SIZE(values))
1739 value_counter = 0;
1741 return value;
1744 int mingw_putenv(const char *namevalue)
1746 int size;
1747 wchar_t *wide, *equal;
1748 BOOL result;
1750 if (!namevalue || !*namevalue)
1751 return 0;
1753 size = strlen(namevalue) * 2 + 1;
1754 wide = calloc(size, sizeof(wchar_t));
1755 if (!wide)
1756 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1757 xutftowcs(wide, namevalue, size);
1758 equal = wcschr(wide, L'=');
1759 if (!equal)
1760 result = SetEnvironmentVariableW(wide, NULL);
1761 else {
1762 *equal = L'\0';
1763 result = SetEnvironmentVariableW(wide, equal + 1);
1765 free(wide);
1767 if (!result)
1768 errno = err_win_to_posix(GetLastError());
1770 return result ? 0 : -1;
1773 static void ensure_socket_initialization(void)
1775 WSADATA wsa;
1776 static int initialized = 0;
1778 if (initialized)
1779 return;
1781 if (WSAStartup(MAKEWORD(2,2), &wsa))
1782 die("unable to initialize winsock subsystem, error %d",
1783 WSAGetLastError());
1785 atexit((void(*)(void)) WSACleanup);
1786 initialized = 1;
1789 #undef gethostname
1790 int mingw_gethostname(char *name, int namelen)
1792 ensure_socket_initialization();
1793 return gethostname(name, namelen);
1796 #undef gethostbyname
1797 struct hostent *mingw_gethostbyname(const char *host)
1799 ensure_socket_initialization();
1800 return gethostbyname(host);
1803 #undef getaddrinfo
1804 int mingw_getaddrinfo(const char *node, const char *service,
1805 const struct addrinfo *hints, struct addrinfo **res)
1807 ensure_socket_initialization();
1808 return getaddrinfo(node, service, hints, res);
1811 int mingw_socket(int domain, int type, int protocol)
1813 int sockfd;
1814 SOCKET s;
1816 ensure_socket_initialization();
1817 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1818 if (s == INVALID_SOCKET) {
1820 * WSAGetLastError() values are regular BSD error codes
1821 * biased by WSABASEERR.
1822 * However, strerror() does not know about networking
1823 * specific errors, which are values beginning at 38 or so.
1824 * Therefore, we choose to leave the biased error code
1825 * in errno so that _if_ someone looks up the code somewhere,
1826 * then it is at least the number that are usually listed.
1828 errno = WSAGetLastError();
1829 return -1;
1831 /* convert into a file descriptor */
1832 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1833 closesocket(s);
1834 return error("unable to make a socket file descriptor: %s",
1835 strerror(errno));
1837 return sockfd;
1840 #undef connect
1841 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1843 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1844 return connect(s, sa, sz);
1847 #undef bind
1848 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1850 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1851 return bind(s, sa, sz);
1854 #undef setsockopt
1855 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1857 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1858 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1861 #undef shutdown
1862 int mingw_shutdown(int sockfd, int how)
1864 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1865 return shutdown(s, how);
1868 #undef listen
1869 int mingw_listen(int sockfd, int backlog)
1871 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1872 return listen(s, backlog);
1875 #undef accept
1876 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1878 int sockfd2;
1880 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1881 SOCKET s2 = accept(s1, sa, sz);
1883 /* convert into a file descriptor */
1884 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1885 int err = errno;
1886 closesocket(s2);
1887 return error("unable to make a socket file descriptor: %s",
1888 strerror(err));
1890 return sockfd2;
1893 #undef rename
1894 int mingw_rename(const char *pold, const char *pnew)
1896 DWORD attrs, gle;
1897 int tries = 0;
1898 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1899 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1900 return -1;
1903 * Try native rename() first to get errno right.
1904 * It is based on MoveFile(), which cannot overwrite existing files.
1906 if (!_wrename(wpold, wpnew))
1907 return 0;
1908 if (errno != EEXIST)
1909 return -1;
1910 repeat:
1911 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1912 return 0;
1913 /* TODO: translate more errors */
1914 gle = GetLastError();
1915 if (gle == ERROR_ACCESS_DENIED &&
1916 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
1917 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1918 DWORD attrsold = GetFileAttributesW(wpold);
1919 if (attrsold == INVALID_FILE_ATTRIBUTES ||
1920 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
1921 errno = EISDIR;
1922 else if (!_wrmdir(wpnew))
1923 goto repeat;
1924 return -1;
1926 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1927 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1928 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1929 return 0;
1930 gle = GetLastError();
1931 /* revert file attributes on failure */
1932 SetFileAttributesW(wpnew, attrs);
1935 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1937 * We assume that some other process had the source or
1938 * destination file open at the wrong moment and retry.
1939 * In order to give the other process a higher chance to
1940 * complete its operation, we give up our time slice now.
1941 * If we have to retry again, we do sleep a bit.
1943 Sleep(delay[tries]);
1944 tries++;
1945 goto repeat;
1947 if (gle == ERROR_ACCESS_DENIED &&
1948 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1949 "Should I try again?", pold, pnew))
1950 goto repeat;
1952 errno = EACCES;
1953 return -1;
1957 * Note that this doesn't return the actual pagesize, but
1958 * the allocation granularity. If future Windows specific git code
1959 * needs the real getpagesize function, we need to find another solution.
1961 int mingw_getpagesize(void)
1963 SYSTEM_INFO si;
1964 GetSystemInfo(&si);
1965 return si.dwAllocationGranularity;
1968 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1969 enum EXTENDED_NAME_FORMAT {
1970 NameDisplay = 3,
1971 NameUserPrincipal = 8
1974 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
1976 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
1977 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
1978 static wchar_t wbuffer[1024];
1979 DWORD len;
1981 if (!INIT_PROC_ADDR(GetUserNameExW))
1982 return NULL;
1984 len = ARRAY_SIZE(wbuffer);
1985 if (GetUserNameExW(type, wbuffer, &len)) {
1986 char *converted = xmalloc((len *= 3));
1987 if (xwcstoutf(converted, wbuffer, len) >= 0)
1988 return converted;
1989 free(converted);
1992 return NULL;
1995 char *mingw_query_user_email(void)
1997 return get_extended_user_info(NameUserPrincipal);
2000 struct passwd *getpwuid(int uid)
2002 static unsigned initialized;
2003 static char user_name[100];
2004 static struct passwd *p;
2005 wchar_t buf[100];
2006 DWORD len;
2008 if (initialized)
2009 return p;
2011 len = ARRAY_SIZE(buf);
2012 if (!GetUserNameW(buf, &len)) {
2013 initialized = 1;
2014 return NULL;
2017 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2018 initialized = 1;
2019 return NULL;
2022 p = xmalloc(sizeof(*p));
2023 p->pw_name = user_name;
2024 p->pw_gecos = get_extended_user_info(NameDisplay);
2025 if (!p->pw_gecos)
2026 p->pw_gecos = "unknown";
2027 p->pw_dir = NULL;
2029 initialized = 1;
2030 return p;
2033 static HANDLE timer_event;
2034 static HANDLE timer_thread;
2035 static int timer_interval;
2036 static int one_shot;
2037 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2039 /* The timer works like this:
2040 * The thread, ticktack(), is a trivial routine that most of the time
2041 * only waits to receive the signal to terminate. The main thread tells
2042 * the thread to terminate by setting the timer_event to the signalled
2043 * state.
2044 * But ticktack() interrupts the wait state after the timer's interval
2045 * length to call the signal handler.
2048 static unsigned __stdcall ticktack(void *dummy)
2050 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2051 mingw_raise(SIGALRM);
2052 if (one_shot)
2053 break;
2055 return 0;
2058 static int start_timer_thread(void)
2060 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2061 if (timer_event) {
2062 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2063 if (!timer_thread )
2064 return errno = ENOMEM,
2065 error("cannot start timer thread");
2066 } else
2067 return errno = ENOMEM,
2068 error("cannot allocate resources for timer");
2069 return 0;
2072 static void stop_timer_thread(void)
2074 if (timer_event)
2075 SetEvent(timer_event); /* tell thread to terminate */
2076 if (timer_thread) {
2077 int rc = WaitForSingleObject(timer_thread, 10000);
2078 if (rc == WAIT_TIMEOUT)
2079 error("timer thread did not terminate timely");
2080 else if (rc != WAIT_OBJECT_0)
2081 error("waiting for timer thread failed: %lu",
2082 GetLastError());
2083 CloseHandle(timer_thread);
2085 if (timer_event)
2086 CloseHandle(timer_event);
2087 timer_event = NULL;
2088 timer_thread = NULL;
2091 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2093 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2096 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2098 static const struct timeval zero;
2099 static int atexit_done;
2101 if (out != NULL)
2102 return errno = EINVAL,
2103 error("setitimer param 3 != NULL not implemented");
2104 if (!is_timeval_eq(&in->it_interval, &zero) &&
2105 !is_timeval_eq(&in->it_interval, &in->it_value))
2106 return errno = EINVAL,
2107 error("setitimer: it_interval must be zero or eq it_value");
2109 if (timer_thread)
2110 stop_timer_thread();
2112 if (is_timeval_eq(&in->it_value, &zero) &&
2113 is_timeval_eq(&in->it_interval, &zero))
2114 return 0;
2116 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2117 one_shot = is_timeval_eq(&in->it_interval, &zero);
2118 if (!atexit_done) {
2119 atexit(stop_timer_thread);
2120 atexit_done = 1;
2122 return start_timer_thread();
2125 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2127 if (sig != SIGALRM)
2128 return errno = EINVAL,
2129 error("sigaction only implemented for SIGALRM");
2130 if (out != NULL)
2131 return errno = EINVAL,
2132 error("sigaction: param 3 != NULL not implemented");
2134 timer_fn = in->sa_handler;
2135 return 0;
2138 #undef signal
2139 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2141 sig_handler_t old;
2143 switch (sig) {
2144 case SIGALRM:
2145 old = timer_fn;
2146 timer_fn = handler;
2147 break;
2149 case SIGINT:
2150 old = sigint_fn;
2151 sigint_fn = handler;
2152 break;
2154 default:
2155 return signal(sig, handler);
2158 return old;
2161 #undef raise
2162 int mingw_raise(int sig)
2164 switch (sig) {
2165 case SIGALRM:
2166 if (timer_fn == SIG_DFL) {
2167 if (isatty(STDERR_FILENO))
2168 fputs("Alarm clock\n", stderr);
2169 exit(128 + SIGALRM);
2170 } else if (timer_fn != SIG_IGN)
2171 timer_fn(SIGALRM);
2172 return 0;
2174 case SIGINT:
2175 if (sigint_fn == SIG_DFL)
2176 exit(128 + SIGINT);
2177 else if (sigint_fn != SIG_IGN)
2178 sigint_fn(SIGINT);
2179 return 0;
2181 #if defined(_MSC_VER)
2182 case SIGILL:
2183 case SIGFPE:
2184 case SIGSEGV:
2185 case SIGTERM:
2186 case SIGBREAK:
2187 case SIGABRT:
2188 case SIGABRT_COMPAT:
2190 * The <signal.h> header in the MS C Runtime defines 8 signals
2191 * as being supported on the platform. Anything else causes an
2192 * "Invalid signal or error" (which in DEBUG builds causes the
2193 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2194 * already know will fail.
2196 return raise(sig);
2197 default:
2198 errno = EINVAL;
2199 return -1;
2201 #else
2203 default:
2204 return raise(sig);
2206 #endif
2211 int link(const char *oldpath, const char *newpath)
2213 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2214 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2215 xutftowcs_path(wnewpath, newpath) < 0)
2216 return -1;
2218 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2219 errno = err_win_to_posix(GetLastError());
2220 return -1;
2222 return 0;
2225 pid_t waitpid(pid_t pid, int *status, int options)
2227 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2228 FALSE, pid);
2229 if (!h) {
2230 errno = ECHILD;
2231 return -1;
2234 if (pid > 0 && options & WNOHANG) {
2235 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2236 CloseHandle(h);
2237 return 0;
2239 options &= ~WNOHANG;
2242 if (options == 0) {
2243 struct pinfo_t **ppinfo;
2244 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2245 CloseHandle(h);
2246 return 0;
2249 if (status)
2250 GetExitCodeProcess(h, (LPDWORD)status);
2252 EnterCriticalSection(&pinfo_cs);
2254 ppinfo = &pinfo;
2255 while (*ppinfo) {
2256 struct pinfo_t *info = *ppinfo;
2257 if (info->pid == pid) {
2258 CloseHandle(info->proc);
2259 *ppinfo = info->next;
2260 free(info);
2261 break;
2263 ppinfo = &info->next;
2266 LeaveCriticalSection(&pinfo_cs);
2268 CloseHandle(h);
2269 return pid;
2271 CloseHandle(h);
2273 errno = EINVAL;
2274 return -1;
2277 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2279 int upos = 0, wpos = 0;
2280 const unsigned char *utf = (const unsigned char*) utfs;
2281 if (!utf || !wcs || wcslen < 1) {
2282 errno = EINVAL;
2283 return -1;
2285 /* reserve space for \0 */
2286 wcslen--;
2287 if (utflen < 0)
2288 utflen = INT_MAX;
2290 while (upos < utflen) {
2291 int c = utf[upos++] & 0xff;
2292 if (utflen == INT_MAX && c == 0)
2293 break;
2295 if (wpos >= wcslen) {
2296 wcs[wpos] = 0;
2297 errno = ERANGE;
2298 return -1;
2301 if (c < 0x80) {
2302 /* ASCII */
2303 wcs[wpos++] = c;
2304 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2305 (utf[upos] & 0xc0) == 0x80) {
2306 /* 2-byte utf-8 */
2307 c = ((c & 0x1f) << 6);
2308 c |= (utf[upos++] & 0x3f);
2309 wcs[wpos++] = c;
2310 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2311 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2312 (utf[upos] & 0xc0) == 0x80 &&
2313 (utf[upos + 1] & 0xc0) == 0x80) {
2314 /* 3-byte utf-8 */
2315 c = ((c & 0x0f) << 12);
2316 c |= ((utf[upos++] & 0x3f) << 6);
2317 c |= (utf[upos++] & 0x3f);
2318 wcs[wpos++] = c;
2319 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2320 wpos + 1 < wcslen &&
2321 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2322 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2323 (utf[upos] & 0xc0) == 0x80 &&
2324 (utf[upos + 1] & 0xc0) == 0x80 &&
2325 (utf[upos + 2] & 0xc0) == 0x80) {
2326 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2327 c = ((c & 0x07) << 18);
2328 c |= ((utf[upos++] & 0x3f) << 12);
2329 c |= ((utf[upos++] & 0x3f) << 6);
2330 c |= (utf[upos++] & 0x3f);
2331 c -= 0x10000;
2332 wcs[wpos++] = 0xd800 | (c >> 10);
2333 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2334 } else if (c >= 0xa0) {
2335 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2336 wcs[wpos++] = c;
2337 } else {
2338 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2339 static const char *hex = "0123456789abcdef";
2340 wcs[wpos++] = hex[c >> 4];
2341 if (wpos < wcslen)
2342 wcs[wpos++] = hex[c & 0x0f];
2345 wcs[wpos] = 0;
2346 return wpos;
2349 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2351 if (!wcs || !utf || utflen < 1) {
2352 errno = EINVAL;
2353 return -1;
2355 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2356 if (utflen)
2357 return utflen - 1;
2358 errno = ERANGE;
2359 return -1;
2362 static void setup_windows_environment(void)
2364 char *tmp = getenv("TMPDIR");
2366 /* on Windows it is TMP and TEMP */
2367 if (!tmp) {
2368 if (!(tmp = getenv("TMP")))
2369 tmp = getenv("TEMP");
2370 if (tmp) {
2371 setenv("TMPDIR", tmp, 1);
2372 tmp = getenv("TMPDIR");
2376 if (tmp) {
2378 * Convert all dir separators to forward slashes,
2379 * to help shell commands called from the Git
2380 * executable (by not mistaking the dir separators
2381 * for escape characters).
2383 convert_slashes(tmp);
2386 /* simulate TERM to enable auto-color (see color.c) */
2387 if (!getenv("TERM"))
2388 setenv("TERM", "cygwin", 1);
2390 /* calculate HOME if not set */
2391 if (!getenv("HOME")) {
2393 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2394 * location, thus also check if the path exists (i.e. is not
2395 * disconnected)
2397 if ((tmp = getenv("HOMEDRIVE"))) {
2398 struct strbuf buf = STRBUF_INIT;
2399 strbuf_addstr(&buf, tmp);
2400 if ((tmp = getenv("HOMEPATH"))) {
2401 strbuf_addstr(&buf, tmp);
2402 if (is_directory(buf.buf))
2403 setenv("HOME", buf.buf, 1);
2404 else
2405 tmp = NULL; /* use $USERPROFILE */
2407 strbuf_release(&buf);
2409 /* use $USERPROFILE if the home share is not available */
2410 if (!tmp && (tmp = getenv("USERPROFILE")))
2411 setenv("HOME", tmp, 1);
2415 int is_valid_win32_path(const char *path)
2417 int preceding_space_or_period = 0, i = 0, periods = 0;
2419 if (!protect_ntfs)
2420 return 1;
2422 skip_dos_drive_prefix((char **)&path);
2424 for (;;) {
2425 char c = *(path++);
2426 switch (c) {
2427 case '\0':
2428 case '/': case '\\':
2429 /* cannot end in ` ` or `.`, except for `.` and `..` */
2430 if (preceding_space_or_period &&
2431 (i != periods || periods > 2))
2432 return 0;
2433 if (!c)
2434 return 1;
2436 i = periods = preceding_space_or_period = 0;
2437 continue;
2438 case '.':
2439 periods++;
2440 /* fallthru */
2441 case ' ':
2442 preceding_space_or_period = 1;
2443 i++;
2444 continue;
2445 case ':': /* DOS drive prefix was already skipped */
2446 case '<': case '>': case '"': case '|': case '?': case '*':
2447 /* illegal character */
2448 return 0;
2449 default:
2450 if (c > '\0' && c < '\x20')
2451 /* illegal character */
2452 return 0;
2454 preceding_space_or_period = 0;
2455 i++;
2459 #if !defined(_MSC_VER)
2461 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2462 * mingw startup code, see init.c in mingw runtime).
2464 int _CRT_glob = 0;
2465 #endif
2467 static NORETURN void die_startup(void)
2469 fputs("fatal: not enough memory for initialization", stderr);
2470 exit(128);
2473 static void *malloc_startup(size_t size)
2475 void *result = malloc(size);
2476 if (!result)
2477 die_startup();
2478 return result;
2481 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2483 len = xwcstoutf(buffer, wcs, len) + 1;
2484 return memcpy(malloc_startup(len), buffer, len);
2487 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2488 DWORD desired_access, DWORD flags)
2490 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2491 wchar_t buf[MAX_PATH];
2492 DWORD max = ARRAY_SIZE(buf);
2493 HANDLE handle;
2494 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2496 if (!ret || ret >= max)
2497 return;
2499 /* make sure this does not leak into child processes */
2500 SetEnvironmentVariableW(key, NULL);
2501 if (!wcscmp(buf, L"off")) {
2502 close(fd);
2503 handle = GetStdHandle(std_id);
2504 if (handle != INVALID_HANDLE_VALUE)
2505 CloseHandle(handle);
2506 return;
2508 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2509 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2510 if (handle == INVALID_HANDLE_VALUE) {
2511 close(fd);
2512 handle = GetStdHandle(std_id);
2513 if (handle != INVALID_HANDLE_VALUE)
2514 CloseHandle(handle);
2515 } else {
2516 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2517 SetStdHandle(std_id, handle);
2518 dup2(new_fd, fd);
2519 /* do *not* close the new_fd: that would close stdout */
2521 return;
2523 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2524 flags, NULL);
2525 if (handle != INVALID_HANDLE_VALUE) {
2526 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2527 SetStdHandle(std_id, handle);
2528 dup2(new_fd, fd);
2529 close(new_fd);
2533 static void maybe_redirect_std_handles(void)
2535 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2536 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2537 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2538 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2539 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2540 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2543 #ifdef _MSC_VER
2544 #ifdef _DEBUG
2545 #include <crtdbg.h>
2546 #endif
2547 #endif
2550 * We implement wmain() and compile with -municode, which would
2551 * normally ignore main(), but we call the latter from the former
2552 * so that we can handle non-ASCII command-line parameters
2553 * appropriately.
2555 * To be more compatible with the core git code, we convert
2556 * argv into UTF8 and pass them directly to main().
2558 int wmain(int argc, const wchar_t **wargv)
2560 int i, maxlen, exit_status;
2561 char *buffer, **save;
2562 const char **argv;
2564 trace2_initialize_clock();
2566 #ifdef _MSC_VER
2567 #ifdef _DEBUG
2568 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2569 #endif
2571 #ifdef USE_MSVC_CRTDBG
2572 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2573 #endif
2574 #endif
2576 maybe_redirect_std_handles();
2578 /* determine size of argv and environ conversion buffer */
2579 maxlen = wcslen(wargv[0]);
2580 for (i = 1; i < argc; i++)
2581 maxlen = max(maxlen, wcslen(wargv[i]));
2583 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2584 maxlen = 3 * maxlen + 1;
2585 buffer = malloc_startup(maxlen);
2588 * Create a UTF-8 version of w_argv. Also create a "save" copy
2589 * to remember all the string pointers because parse_options()
2590 * will remove claimed items from the argv that we pass down.
2592 ALLOC_ARRAY(argv, argc + 1);
2593 ALLOC_ARRAY(save, argc + 1);
2594 for (i = 0; i < argc; i++)
2595 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2596 argv[i] = save[i] = NULL;
2597 free(buffer);
2599 /* fix Windows specific environment settings */
2600 setup_windows_environment();
2602 unset_environment_variables = xstrdup("PERL5LIB");
2604 /* initialize critical section for waitpid pinfo_t list */
2605 InitializeCriticalSection(&pinfo_cs);
2607 /* set up default file mode and file modes for stdin/out/err */
2608 _fmode = _O_BINARY;
2609 _setmode(_fileno(stdin), _O_BINARY);
2610 _setmode(_fileno(stdout), _O_BINARY);
2611 _setmode(_fileno(stderr), _O_BINARY);
2613 /* initialize Unicode console */
2614 winansi_init();
2616 /* invoke the real main() using our utf8 version of argv. */
2617 exit_status = main(argc, argv);
2619 for (i = 0; i < argc; i++)
2620 free(save[i]);
2621 free(save);
2622 free(argv);
2624 return exit_status;
2627 int uname(struct utsname *buf)
2629 unsigned v = (unsigned)GetVersion();
2630 memset(buf, 0, sizeof(*buf));
2631 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2632 xsnprintf(buf->release, sizeof(buf->release),
2633 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2634 /* assuming NT variants only.. */
2635 xsnprintf(buf->version, sizeof(buf->version),
2636 "%u", (v >> 16) & 0x7fff);
2637 return 0;