notes.c: use designated initializers for clarity
[git/debian.git] / compat / mingw.c
blob94c5a1daa40cde53093b62f0c2c3c67da12ffd9e
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <aclapi.h>
4 #include <sddl.h>
5 #include <conio.h>
6 #include <wchar.h>
7 #include "../strbuf.h"
8 #include "../run-command.h"
9 #include "../cache.h"
10 #include "../abspath.h"
11 #include "../alloc.h"
12 #include "win32/lazyload.h"
13 #include "../config.h"
14 #include "../environment.h"
15 #include "../wrapper.h"
16 #include "dir.h"
17 #include "gettext.h"
18 #define SECURITY_WIN32
19 #include <sspi.h>
21 #define HCAST(type, handle) ((type)(intptr_t)handle)
23 static const int delay[] = { 0, 1, 10, 20, 40 };
25 void open_in_gdb(void)
27 static struct child_process cp = CHILD_PROCESS_INIT;
28 extern char *_pgmptr;
30 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
31 strvec_pushf(&cp.args, "--pid=%d", getpid());
32 cp.clean_on_exit = 1;
33 if (start_command(&cp) < 0)
34 die_errno("Could not start gdb");
35 sleep(1);
38 int err_win_to_posix(DWORD winerr)
40 int error = ENOSYS;
41 switch(winerr) {
42 case ERROR_ACCESS_DENIED: error = EACCES; break;
43 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
44 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
45 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
46 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
47 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
48 case ERROR_BAD_COMMAND: error = EIO; break;
49 case ERROR_BAD_DEVICE: error = ENODEV; break;
50 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
51 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
52 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
53 case ERROR_BAD_LENGTH: error = EINVAL; break;
54 case ERROR_BAD_PATHNAME: error = ENOENT; break;
55 case ERROR_BAD_PIPE: error = EPIPE; break;
56 case ERROR_BAD_UNIT: error = ENODEV; break;
57 case ERROR_BAD_USERNAME: error = EINVAL; break;
58 case ERROR_BROKEN_PIPE: error = EPIPE; break;
59 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
60 case ERROR_BUSY: error = EBUSY; break;
61 case ERROR_BUSY_DRIVE: error = EBUSY; break;
62 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
63 case ERROR_CANNOT_MAKE: error = EACCES; break;
64 case ERROR_CANTOPEN: error = EIO; break;
65 case ERROR_CANTREAD: error = EIO; break;
66 case ERROR_CANTWRITE: error = EIO; break;
67 case ERROR_CRC: error = EIO; break;
68 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
69 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
70 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
71 case ERROR_DIRECTORY: error = EINVAL; break;
72 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
73 case ERROR_DISK_CHANGE: error = EIO; break;
74 case ERROR_DISK_FULL: error = ENOSPC; break;
75 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
76 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
77 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
78 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
79 case ERROR_FILE_EXISTS: error = EEXIST; break;
80 case ERROR_FILE_INVALID: error = ENODEV; break;
81 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
82 case ERROR_GEN_FAILURE: error = EIO; break;
83 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
84 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
85 case ERROR_INVALID_ACCESS: error = EACCES; break;
86 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
87 case ERROR_INVALID_BLOCK: error = EFAULT; break;
88 case ERROR_INVALID_DATA: error = EINVAL; break;
89 case ERROR_INVALID_DRIVE: error = ENODEV; break;
90 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
91 case ERROR_INVALID_FLAGS: error = EINVAL; break;
92 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
93 case ERROR_INVALID_HANDLE: error = EBADF; break;
94 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
95 case ERROR_INVALID_NAME: error = EINVAL; break;
96 case ERROR_INVALID_OWNER: error = EINVAL; break;
97 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
98 case ERROR_INVALID_PASSWORD: error = EPERM; break;
99 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
100 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
101 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
102 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
103 case ERROR_IO_DEVICE: error = EIO; break;
104 case ERROR_IO_INCOMPLETE: error = EINTR; break;
105 case ERROR_LOCKED: error = EBUSY; break;
106 case ERROR_LOCK_VIOLATION: error = EACCES; break;
107 case ERROR_LOGON_FAILURE: error = EACCES; break;
108 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
109 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
110 case ERROR_MORE_DATA: error = EPIPE; break;
111 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
112 case ERROR_NOACCESS: error = EFAULT; break;
113 case ERROR_NONE_MAPPED: error = EINVAL; break;
114 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
115 case ERROR_NOT_READY: error = EAGAIN; break;
116 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
117 case ERROR_NO_DATA: error = EPIPE; break;
118 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
119 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
120 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
121 case ERROR_OPEN_FAILED: error = EIO; break;
122 case ERROR_OPEN_FILES: error = EBUSY; break;
123 case ERROR_OPERATION_ABORTED: error = EINTR; break;
124 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
125 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
126 case ERROR_PATH_BUSY: error = EBUSY; break;
127 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
128 case ERROR_PIPE_BUSY: error = EBUSY; break;
129 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
130 case ERROR_PIPE_LISTENING: error = EPIPE; break;
131 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
132 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
133 case ERROR_READ_FAULT: error = EIO; break;
134 case ERROR_SEEK: error = EIO; break;
135 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
136 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
137 case ERROR_SHARING_VIOLATION: error = EACCES; break;
138 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
139 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
140 case ERROR_SWAPERROR: error = ENOENT; break;
141 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
142 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
143 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
144 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
145 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
146 case ERROR_WRITE_FAULT: error = EIO; break;
147 case ERROR_WRITE_PROTECT: error = EROFS; break;
149 return error;
152 static inline int is_file_in_use_error(DWORD errcode)
154 switch (errcode) {
155 case ERROR_SHARING_VIOLATION:
156 case ERROR_ACCESS_DENIED:
157 return 1;
160 return 0;
163 static int read_yes_no_answer(void)
165 char answer[1024];
167 if (fgets(answer, sizeof(answer), stdin)) {
168 size_t answer_len = strlen(answer);
169 int got_full_line = 0, c;
171 /* remove the newline */
172 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
173 answer[answer_len-2] = '\0';
174 got_full_line = 1;
175 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
176 answer[answer_len-1] = '\0';
177 got_full_line = 1;
179 /* flush the buffer in case we did not get the full line */
180 if (!got_full_line)
181 while ((c = getchar()) != EOF && c != '\n')
183 } else
184 /* we could not read, return the
185 * default answer which is no */
186 return 0;
188 if (tolower(answer[0]) == 'y' && !answer[1])
189 return 1;
190 if (!strncasecmp(answer, "yes", sizeof(answer)))
191 return 1;
192 if (tolower(answer[0]) == 'n' && !answer[1])
193 return 0;
194 if (!strncasecmp(answer, "no", sizeof(answer)))
195 return 0;
197 /* did not find an answer we understand */
198 return -1;
201 static int ask_yes_no_if_possible(const char *format, ...)
203 char question[4096];
204 const char *retry_hook;
205 va_list args;
207 va_start(args, format);
208 vsnprintf(question, sizeof(question), format, args);
209 va_end(args);
211 retry_hook = mingw_getenv("GIT_ASK_YESNO");
212 if (retry_hook) {
213 struct child_process cmd = CHILD_PROCESS_INIT;
215 strvec_pushl(&cmd.args, retry_hook, question, NULL);
216 return !run_command(&cmd);
219 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
220 return 0;
222 while (1) {
223 int answer;
224 fprintf(stderr, "%s (y/n) ", question);
226 if ((answer = read_yes_no_answer()) >= 0)
227 return answer;
229 fprintf(stderr, "Sorry, I did not understand your answer. "
230 "Please type 'y' or 'n'\n");
234 /* Windows only */
235 enum hide_dotfiles_type {
236 HIDE_DOTFILES_FALSE = 0,
237 HIDE_DOTFILES_TRUE,
238 HIDE_DOTFILES_DOTGITONLY
241 static int core_restrict_inherited_handles = -1;
242 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
243 static char *unset_environment_variables;
245 int mingw_core_config(const char *var, const char *value, void *cb)
247 if (!strcmp(var, "core.hidedotfiles")) {
248 if (value && !strcasecmp(value, "dotgitonly"))
249 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
250 else
251 hide_dotfiles = git_config_bool(var, value);
252 return 0;
255 if (!strcmp(var, "core.unsetenvvars")) {
256 free(unset_environment_variables);
257 unset_environment_variables = xstrdup(value);
258 return 0;
261 if (!strcmp(var, "core.restrictinheritedhandles")) {
262 if (value && !strcasecmp(value, "auto"))
263 core_restrict_inherited_handles = -1;
264 else
265 core_restrict_inherited_handles =
266 git_config_bool(var, value);
267 return 0;
270 return 0;
273 /* Normalizes NT paths as returned by some low-level APIs. */
274 static wchar_t *normalize_ntpath(wchar_t *wbuf)
276 int i;
277 /* fix absolute path prefixes */
278 if (wbuf[0] == '\\') {
279 /* strip NT namespace prefixes */
280 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
281 !wcsncmp(wbuf, L"\\\\?\\", 4))
282 wbuf += 4;
283 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
284 wbuf += 12;
285 /* replace remaining '...UNC\' with '\\' */
286 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
287 wbuf += 2;
288 *wbuf = '\\';
291 /* convert backslashes to slashes */
292 for (i = 0; wbuf[i]; i++)
293 if (wbuf[i] == '\\')
294 wbuf[i] = '/';
295 return wbuf;
298 int mingw_unlink(const char *pathname)
300 int ret, tries = 0;
301 wchar_t wpathname[MAX_PATH];
302 if (xutftowcs_path(wpathname, pathname) < 0)
303 return -1;
305 if (DeleteFileW(wpathname))
306 return 0;
308 /* read-only files cannot be removed */
309 _wchmod(wpathname, 0666);
310 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
311 if (!is_file_in_use_error(GetLastError()))
312 break;
314 * We assume that some other process had the source or
315 * destination file open at the wrong moment and retry.
316 * In order to give the other process a higher chance to
317 * complete its operation, we give up our time slice now.
318 * If we have to retry again, we do sleep a bit.
320 Sleep(delay[tries]);
321 tries++;
323 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
324 ask_yes_no_if_possible("Unlink of file '%s' failed. "
325 "Should I try again?", pathname))
326 ret = _wunlink(wpathname);
327 return ret;
330 static int is_dir_empty(const wchar_t *wpath)
332 WIN32_FIND_DATAW findbuf;
333 HANDLE handle;
334 wchar_t wbuf[MAX_PATH + 2];
335 wcscpy(wbuf, wpath);
336 wcscat(wbuf, L"\\*");
337 handle = FindFirstFileW(wbuf, &findbuf);
338 if (handle == INVALID_HANDLE_VALUE)
339 return GetLastError() == ERROR_NO_MORE_FILES;
341 while (!wcscmp(findbuf.cFileName, L".") ||
342 !wcscmp(findbuf.cFileName, L".."))
343 if (!FindNextFileW(handle, &findbuf)) {
344 DWORD err = GetLastError();
345 FindClose(handle);
346 return err == ERROR_NO_MORE_FILES;
348 FindClose(handle);
349 return 0;
352 int mingw_rmdir(const char *pathname)
354 int ret, tries = 0;
355 wchar_t wpathname[MAX_PATH];
356 struct stat st;
359 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
360 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
361 * symbolic link (if it points to a directory).
363 * This behavior breaks the assumption of e.g. `remove_path()` which
364 * upon successful deletion of a file will attempt to remove its parent
365 * directories recursively until failure (which usually happens when
366 * the directory is not empty).
368 * Therefore, before calling `_wrmdir()`, we first check if the path is
369 * a symbolic link. If it is, we exit and return the same error as
370 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
372 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
373 errno = ENOTDIR;
374 return -1;
377 if (xutftowcs_path(wpathname, pathname) < 0)
378 return -1;
380 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
381 if (!is_file_in_use_error(GetLastError()))
382 errno = err_win_to_posix(GetLastError());
383 if (errno != EACCES)
384 break;
385 if (!is_dir_empty(wpathname)) {
386 errno = ENOTEMPTY;
387 break;
390 * We assume that some other process had the source or
391 * destination file open at the wrong moment and retry.
392 * In order to give the other process a higher chance to
393 * complete its operation, we give up our time slice now.
394 * If we have to retry again, we do sleep a bit.
396 Sleep(delay[tries]);
397 tries++;
399 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
400 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
401 "Should I try again?", pathname))
402 ret = _wrmdir(wpathname);
403 if (!ret)
404 invalidate_lstat_cache();
405 return ret;
408 static inline int needs_hiding(const char *path)
410 const char *basename;
412 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
413 return 0;
415 /* We cannot use basename(), as it would remove trailing slashes */
416 win32_skip_dos_drive_prefix((char **)&path);
417 if (!*path)
418 return 0;
420 for (basename = path; *path; path++)
421 if (is_dir_sep(*path)) {
422 do {
423 path++;
424 } while (is_dir_sep(*path));
425 /* ignore trailing slashes */
426 if (*path)
427 basename = path;
428 else
429 break;
432 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
433 return *basename == '.';
435 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
436 return !strncasecmp(".git", basename, 4) &&
437 (!basename[4] || is_dir_sep(basename[4]));
440 static int set_hidden_flag(const wchar_t *path, int set)
442 DWORD original = GetFileAttributesW(path), modified;
443 if (set)
444 modified = original | FILE_ATTRIBUTE_HIDDEN;
445 else
446 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
447 if (original == modified || SetFileAttributesW(path, modified))
448 return 0;
449 errno = err_win_to_posix(GetLastError());
450 return -1;
453 int mingw_mkdir(const char *path, int mode)
455 int ret;
456 wchar_t wpath[MAX_PATH];
458 if (!is_valid_win32_path(path, 0)) {
459 errno = EINVAL;
460 return -1;
463 if (xutftowcs_path(wpath, path) < 0)
464 return -1;
465 ret = _wmkdir(wpath);
466 if (!ret && needs_hiding(path))
467 return set_hidden_flag(wpath, 1);
468 return ret;
472 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
473 * is documented in [1] as opening a writable file handle in append mode.
474 * (It is believed that) this is atomic since it is maintained by the
475 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
477 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
479 * This trick does not appear to work for named pipes. Instead it creates
480 * a named pipe client handle that cannot be written to. Callers should
481 * just use the regular _wopen() for them. (And since client handle gets
482 * bound to a unique server handle, it isn't really an issue.)
484 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
486 HANDLE handle;
487 int fd;
488 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
490 /* only these flags are supported */
491 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
492 return errno = ENOSYS, -1;
495 * FILE_SHARE_WRITE is required to permit child processes
496 * to append to the file.
498 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
499 FILE_SHARE_WRITE | FILE_SHARE_READ,
500 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
501 if (handle == INVALID_HANDLE_VALUE) {
502 DWORD err = GetLastError();
505 * Some network storage solutions (e.g. Isilon) might return
506 * ERROR_INVALID_PARAMETER instead of expected error
507 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
508 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
510 if (err == ERROR_INVALID_PARAMETER)
511 err = ERROR_PATH_NOT_FOUND;
513 errno = err_win_to_posix(err);
514 return -1;
518 * No O_APPEND here, because the CRT uses it only to reset the
519 * file pointer to EOF before each write(); but that is not
520 * necessary (and may lead to races) for a file created with
521 * FILE_APPEND_DATA.
523 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
524 if (fd < 0)
525 CloseHandle(handle);
526 return fd;
530 * Does the pathname map to the local named pipe filesystem?
531 * That is, does it have a "//./pipe/" prefix?
533 static int is_local_named_pipe_path(const char *filename)
535 return (is_dir_sep(filename[0]) &&
536 is_dir_sep(filename[1]) &&
537 filename[2] == '.' &&
538 is_dir_sep(filename[3]) &&
539 !strncasecmp(filename+4, "pipe", 4) &&
540 is_dir_sep(filename[8]) &&
541 filename[9]);
544 int mingw_open (const char *filename, int oflags, ...)
546 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
547 va_list args;
548 unsigned mode;
549 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
550 wchar_t wfilename[MAX_PATH];
551 open_fn_t open_fn;
553 va_start(args, oflags);
554 mode = va_arg(args, int);
555 va_end(args);
557 if (!is_valid_win32_path(filename, !create)) {
558 errno = create ? EINVAL : ENOENT;
559 return -1;
562 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
563 open_fn = mingw_open_append;
564 else
565 open_fn = _wopen;
567 if (filename && !strcmp(filename, "/dev/null"))
568 wcscpy(wfilename, L"nul");
569 else if (xutftowcs_path(wfilename, filename) < 0)
570 return -1;
572 fd = open_fn(wfilename, oflags, mode);
574 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
575 DWORD attrs = GetFileAttributesW(wfilename);
576 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
577 errno = EISDIR;
579 if ((oflags & O_CREAT) && needs_hiding(filename)) {
581 * Internally, _wopen() uses the CreateFile() API which errors
582 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
583 * specified and an already existing file's attributes do not
584 * match *exactly*. As there is no mode or flag we can set that
585 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
586 * again *without* the O_CREAT flag (that corresponds to the
587 * CREATE_ALWAYS flag of CreateFile()).
589 if (fd < 0 && errno == EACCES)
590 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
591 if (fd >= 0 && set_hidden_flag(wfilename, 1))
592 warning("could not mark '%s' as hidden.", filename);
594 return fd;
597 static BOOL WINAPI ctrl_ignore(DWORD type)
599 return TRUE;
602 #undef fgetc
603 int mingw_fgetc(FILE *stream)
605 int ch;
606 if (!isatty(_fileno(stream)))
607 return fgetc(stream);
609 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
610 while (1) {
611 ch = fgetc(stream);
612 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
613 break;
615 /* Ctrl+C was pressed, simulate SIGINT and retry */
616 mingw_raise(SIGINT);
618 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
619 return ch;
622 #undef fopen
623 FILE *mingw_fopen (const char *filename, const char *otype)
625 int hide = needs_hiding(filename);
626 FILE *file;
627 wchar_t wfilename[MAX_PATH], wotype[4];
628 if (filename && !strcmp(filename, "/dev/null"))
629 wcscpy(wfilename, L"nul");
630 else if (!is_valid_win32_path(filename, 1)) {
631 int create = otype && strchr(otype, 'w');
632 errno = create ? EINVAL : ENOENT;
633 return NULL;
634 } else if (xutftowcs_path(wfilename, filename) < 0)
635 return NULL;
637 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
638 return NULL;
640 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
641 error("could not unhide %s", filename);
642 return NULL;
644 file = _wfopen(wfilename, wotype);
645 if (!file && GetLastError() == ERROR_INVALID_NAME)
646 errno = ENOENT;
647 if (file && hide && set_hidden_flag(wfilename, 1))
648 warning("could not mark '%s' as hidden.", filename);
649 return file;
652 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
654 int hide = needs_hiding(filename);
655 FILE *file;
656 wchar_t wfilename[MAX_PATH], wotype[4];
657 if (filename && !strcmp(filename, "/dev/null"))
658 wcscpy(wfilename, L"nul");
659 else if (!is_valid_win32_path(filename, 1)) {
660 int create = otype && strchr(otype, 'w');
661 errno = create ? EINVAL : ENOENT;
662 return NULL;
663 } else if (xutftowcs_path(wfilename, filename) < 0)
664 return NULL;
666 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
667 return NULL;
669 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
670 error("could not unhide %s", filename);
671 return NULL;
673 file = _wfreopen(wfilename, wotype, stream);
674 if (file && hide && set_hidden_flag(wfilename, 1))
675 warning("could not mark '%s' as hidden.", filename);
676 return file;
679 #undef fflush
680 int mingw_fflush(FILE *stream)
682 int ret = fflush(stream);
685 * write() is used behind the scenes of stdio output functions.
686 * Since git code does not check for errors after each stdio write
687 * operation, it can happen that write() is called by a later
688 * stdio function even if an earlier write() call failed. In the
689 * case of a pipe whose readable end was closed, only the first
690 * call to write() reports EPIPE on Windows. Subsequent write()
691 * calls report EINVAL. It is impossible to notice whether this
692 * fflush invocation triggered such a case, therefore, we have to
693 * catch all EINVAL errors whole-sale.
695 if (ret && errno == EINVAL)
696 errno = EPIPE;
698 return ret;
701 #undef write
702 ssize_t mingw_write(int fd, const void *buf, size_t len)
704 ssize_t result = write(fd, buf, len);
706 if (result < 0 && errno == EINVAL && buf) {
707 /* check if fd is a pipe */
708 HANDLE h = (HANDLE) _get_osfhandle(fd);
709 if (GetFileType(h) == FILE_TYPE_PIPE)
710 errno = EPIPE;
711 else
712 errno = EINVAL;
715 return result;
718 int mingw_access(const char *filename, int mode)
720 wchar_t wfilename[MAX_PATH];
721 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
722 return 0;
723 if (xutftowcs_path(wfilename, filename) < 0)
724 return -1;
725 /* X_OK is not supported by the MSVCRT version */
726 return _waccess(wfilename, mode & ~X_OK);
729 int mingw_chdir(const char *dirname)
731 wchar_t wdirname[MAX_PATH];
732 if (xutftowcs_path(wdirname, dirname) < 0)
733 return -1;
734 return _wchdir(wdirname);
737 int mingw_chmod(const char *filename, int mode)
739 wchar_t wfilename[MAX_PATH];
740 if (xutftowcs_path(wfilename, filename) < 0)
741 return -1;
742 return _wchmod(wfilename, mode);
746 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
747 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
749 static inline long long filetime_to_hnsec(const FILETIME *ft)
751 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
752 /* Windows to Unix Epoch conversion */
753 return winTime - 116444736000000000LL;
756 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
758 long long hnsec = filetime_to_hnsec(ft);
759 ts->tv_sec = (time_t)(hnsec / 10000000);
760 ts->tv_nsec = (hnsec % 10000000) * 100;
764 * Verifies that safe_create_leading_directories() would succeed.
766 static int has_valid_directory_prefix(wchar_t *wfilename)
768 int n = wcslen(wfilename);
770 while (n > 0) {
771 wchar_t c = wfilename[--n];
772 DWORD attributes;
774 if (!is_dir_sep(c))
775 continue;
777 wfilename[n] = L'\0';
778 attributes = GetFileAttributesW(wfilename);
779 wfilename[n] = c;
780 if (attributes &
781 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
782 return 1;
783 if (attributes == INVALID_FILE_ATTRIBUTES)
784 switch (GetLastError()) {
785 case ERROR_PATH_NOT_FOUND:
786 continue;
787 case ERROR_FILE_NOT_FOUND:
788 /* This implies parent directory exists. */
789 return 1;
791 return 0;
793 return 1;
796 /* We keep the do_lstat code in a separate function to avoid recursion.
797 * When a path ends with a slash, the stat will fail with ENOENT. In
798 * this case, we strip the trailing slashes and stat again.
800 * If follow is true then act like stat() and report on the link
801 * target. Otherwise report on the link itself.
803 static int do_lstat(int follow, const char *file_name, struct stat *buf)
805 WIN32_FILE_ATTRIBUTE_DATA fdata;
806 wchar_t wfilename[MAX_PATH];
807 if (xutftowcs_path(wfilename, file_name) < 0)
808 return -1;
810 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
811 buf->st_ino = 0;
812 buf->st_gid = 0;
813 buf->st_uid = 0;
814 buf->st_nlink = 1;
815 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
816 buf->st_size = fdata.nFileSizeLow |
817 (((off_t)fdata.nFileSizeHigh)<<32);
818 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
819 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
820 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
821 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
822 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
823 WIN32_FIND_DATAW findbuf;
824 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
825 if (handle != INVALID_HANDLE_VALUE) {
826 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
827 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
828 if (follow) {
829 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
830 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
831 } else {
832 buf->st_mode = S_IFLNK;
834 buf->st_mode |= S_IREAD;
835 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
836 buf->st_mode |= S_IWRITE;
838 FindClose(handle);
841 return 0;
843 switch (GetLastError()) {
844 case ERROR_ACCESS_DENIED:
845 case ERROR_SHARING_VIOLATION:
846 case ERROR_LOCK_VIOLATION:
847 case ERROR_SHARING_BUFFER_EXCEEDED:
848 errno = EACCES;
849 break;
850 case ERROR_BUFFER_OVERFLOW:
851 errno = ENAMETOOLONG;
852 break;
853 case ERROR_NOT_ENOUGH_MEMORY:
854 errno = ENOMEM;
855 break;
856 case ERROR_PATH_NOT_FOUND:
857 if (!has_valid_directory_prefix(wfilename)) {
858 errno = ENOTDIR;
859 break;
861 /* fallthru */
862 default:
863 errno = ENOENT;
864 break;
866 return -1;
869 /* We provide our own lstat/fstat functions, since the provided
870 * lstat/fstat functions are so slow. These stat functions are
871 * tailored for Git's usage (read: fast), and are not meant to be
872 * complete. Note that Git stat()s are redirected to mingw_lstat()
873 * too, since Windows doesn't really handle symlinks that well.
875 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
877 int namelen;
878 char alt_name[PATH_MAX];
880 if (!do_lstat(follow, file_name, buf))
881 return 0;
883 /* if file_name ended in a '/', Windows returned ENOENT;
884 * try again without trailing slashes
886 if (errno != ENOENT)
887 return -1;
889 namelen = strlen(file_name);
890 if (namelen && file_name[namelen-1] != '/')
891 return -1;
892 while (namelen && file_name[namelen-1] == '/')
893 --namelen;
894 if (!namelen || namelen >= PATH_MAX)
895 return -1;
897 memcpy(alt_name, file_name, namelen);
898 alt_name[namelen] = 0;
899 return do_lstat(follow, alt_name, buf);
902 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
904 BY_HANDLE_FILE_INFORMATION fdata;
906 if (!GetFileInformationByHandle(hnd, &fdata)) {
907 errno = err_win_to_posix(GetLastError());
908 return -1;
911 buf->st_ino = 0;
912 buf->st_gid = 0;
913 buf->st_uid = 0;
914 buf->st_nlink = 1;
915 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
916 buf->st_size = fdata.nFileSizeLow |
917 (((off_t)fdata.nFileSizeHigh)<<32);
918 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
919 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
920 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
921 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
922 return 0;
925 int mingw_lstat(const char *file_name, struct stat *buf)
927 return do_stat_internal(0, file_name, buf);
929 int mingw_stat(const char *file_name, struct stat *buf)
931 return do_stat_internal(1, file_name, buf);
934 int mingw_fstat(int fd, struct stat *buf)
936 HANDLE fh = (HANDLE)_get_osfhandle(fd);
937 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
939 switch (type) {
940 case FILE_TYPE_DISK:
941 return get_file_info_by_handle(fh, buf);
943 case FILE_TYPE_CHAR:
944 case FILE_TYPE_PIPE:
945 /* initialize stat fields */
946 memset(buf, 0, sizeof(*buf));
947 buf->st_nlink = 1;
949 if (type == FILE_TYPE_CHAR) {
950 buf->st_mode = _S_IFCHR;
951 } else {
952 buf->st_mode = _S_IFIFO;
953 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
954 buf->st_size = avail;
956 return 0;
958 default:
959 errno = EBADF;
960 return -1;
964 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
966 long long winTime = t * 10000000LL + 116444736000000000LL;
967 ft->dwLowDateTime = winTime;
968 ft->dwHighDateTime = winTime >> 32;
971 int mingw_utime (const char *file_name, const struct utimbuf *times)
973 FILETIME mft, aft;
974 int rc;
975 DWORD attrs;
976 wchar_t wfilename[MAX_PATH];
977 HANDLE osfilehandle;
979 if (xutftowcs_path(wfilename, file_name) < 0)
980 return -1;
982 /* must have write permission */
983 attrs = GetFileAttributesW(wfilename);
984 if (attrs != INVALID_FILE_ATTRIBUTES &&
985 (attrs & FILE_ATTRIBUTE_READONLY)) {
986 /* ignore errors here; open() will report them */
987 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
990 osfilehandle = CreateFileW(wfilename,
991 FILE_WRITE_ATTRIBUTES,
992 0 /*FileShare.None*/,
993 NULL,
994 OPEN_EXISTING,
995 (attrs != INVALID_FILE_ATTRIBUTES &&
996 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
997 FILE_FLAG_BACKUP_SEMANTICS : 0,
998 NULL);
999 if (osfilehandle == INVALID_HANDLE_VALUE) {
1000 errno = err_win_to_posix(GetLastError());
1001 rc = -1;
1002 goto revert_attrs;
1005 if (times) {
1006 time_t_to_filetime(times->modtime, &mft);
1007 time_t_to_filetime(times->actime, &aft);
1008 } else {
1009 GetSystemTimeAsFileTime(&mft);
1010 aft = mft;
1013 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
1014 errno = EINVAL;
1015 rc = -1;
1016 } else
1017 rc = 0;
1019 if (osfilehandle != INVALID_HANDLE_VALUE)
1020 CloseHandle(osfilehandle);
1022 revert_attrs:
1023 if (attrs != INVALID_FILE_ATTRIBUTES &&
1024 (attrs & FILE_ATTRIBUTE_READONLY)) {
1025 /* ignore errors again */
1026 SetFileAttributesW(wfilename, attrs);
1028 return rc;
1031 #undef strftime
1032 size_t mingw_strftime(char *s, size_t max,
1033 const char *format, const struct tm *tm)
1035 /* a pointer to the original strftime in case we can't find the UCRT version */
1036 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1037 size_t ret;
1038 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1039 const char *, const struct tm *);
1041 if (INIT_PROC_ADDR(strftime))
1042 ret = strftime(s, max, format, tm);
1043 else
1044 ret = fallback(s, max, format, tm);
1046 if (!ret && errno == EINVAL)
1047 die("invalid strftime format: '%s'", format);
1048 return ret;
1051 unsigned int sleep (unsigned int seconds)
1053 Sleep(seconds*1000);
1054 return 0;
1057 char *mingw_mktemp(char *template)
1059 wchar_t wtemplate[MAX_PATH];
1060 if (xutftowcs_path(wtemplate, template) < 0)
1061 return NULL;
1062 if (!_wmktemp(wtemplate))
1063 return NULL;
1064 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1065 return NULL;
1066 return template;
1069 int mkstemp(char *template)
1071 return git_mkstemp_mode(template, 0600);
1074 int gettimeofday(struct timeval *tv, void *tz)
1076 FILETIME ft;
1077 long long hnsec;
1079 GetSystemTimeAsFileTime(&ft);
1080 hnsec = filetime_to_hnsec(&ft);
1081 tv->tv_sec = hnsec / 10000000;
1082 tv->tv_usec = (hnsec % 10000000) / 10;
1083 return 0;
1086 int pipe(int filedes[2])
1088 HANDLE h[2];
1090 /* this creates non-inheritable handles */
1091 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1092 errno = err_win_to_posix(GetLastError());
1093 return -1;
1095 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1096 if (filedes[0] < 0) {
1097 CloseHandle(h[0]);
1098 CloseHandle(h[1]);
1099 return -1;
1101 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1102 if (filedes[1] < 0) {
1103 close(filedes[0]);
1104 CloseHandle(h[1]);
1105 return -1;
1107 return 0;
1110 #ifndef __MINGW64__
1111 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1113 if (gmtime_s(result, timep) == 0)
1114 return result;
1115 return NULL;
1118 struct tm *localtime_r(const time_t *timep, struct tm *result)
1120 if (localtime_s(result, timep) == 0)
1121 return result;
1122 return NULL;
1124 #endif
1126 char *mingw_getcwd(char *pointer, int len)
1128 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1129 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1131 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1132 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1133 return NULL;
1135 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1136 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1137 HANDLE hnd = CreateFileW(cwd, 0,
1138 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1139 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1140 if (hnd == INVALID_HANDLE_VALUE)
1141 return NULL;
1142 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1143 CloseHandle(hnd);
1144 if (!ret || ret >= ARRAY_SIZE(wpointer))
1145 return NULL;
1146 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1147 return NULL;
1148 return pointer;
1150 if (!ret || ret >= ARRAY_SIZE(wpointer))
1151 return NULL;
1152 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1153 errno = ENOENT;
1154 return NULL;
1156 if (xwcstoutf(pointer, wpointer, len) < 0)
1157 return NULL;
1158 convert_slashes(pointer);
1159 return pointer;
1163 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1164 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1166 static const char *quote_arg_msvc(const char *arg)
1168 /* count chars to quote */
1169 int len = 0, n = 0;
1170 int force_quotes = 0;
1171 char *q, *d;
1172 const char *p = arg;
1173 if (!*p) force_quotes = 1;
1174 while (*p) {
1175 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1176 force_quotes = 1;
1177 else if (*p == '"')
1178 n++;
1179 else if (*p == '\\') {
1180 int count = 0;
1181 while (*p == '\\') {
1182 count++;
1183 p++;
1184 len++;
1186 if (*p == '"' || !*p)
1187 n += count*2 + 1;
1188 continue;
1190 len++;
1191 p++;
1193 if (!force_quotes && n == 0)
1194 return arg;
1196 /* insert \ where necessary */
1197 d = q = xmalloc(st_add3(len, n, 3));
1198 *d++ = '"';
1199 while (*arg) {
1200 if (*arg == '"')
1201 *d++ = '\\';
1202 else if (*arg == '\\') {
1203 int count = 0;
1204 while (*arg == '\\') {
1205 count++;
1206 *d++ = *arg++;
1208 if (*arg == '"' || !*arg) {
1209 while (count-- > 0)
1210 *d++ = '\\';
1211 /* don't escape the surrounding end quote */
1212 if (!*arg)
1213 break;
1214 *d++ = '\\';
1217 *d++ = *arg++;
1219 *d++ = '"';
1220 *d++ = '\0';
1221 return q;
1224 #include "quote.h"
1226 static const char *quote_arg_msys2(const char *arg)
1228 struct strbuf buf = STRBUF_INIT;
1229 const char *p2 = arg, *p;
1231 for (p = arg; *p; p++) {
1232 int ws = isspace(*p);
1233 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1234 *p != '?' && *p != '*' && *p != '~')
1235 continue;
1236 if (!buf.len)
1237 strbuf_addch(&buf, '"');
1238 if (p != p2)
1239 strbuf_add(&buf, p2, p - p2);
1240 if (*p == '\\' || *p == '"')
1241 strbuf_addch(&buf, '\\');
1242 p2 = p;
1245 if (p == arg)
1246 strbuf_addch(&buf, '"');
1247 else if (!buf.len)
1248 return arg;
1249 else
1250 strbuf_add(&buf, p2, p - p2);
1252 strbuf_addch(&buf, '"');
1253 return strbuf_detach(&buf, 0);
1256 static const char *parse_interpreter(const char *cmd)
1258 static char buf[100];
1259 char *p, *opt;
1260 int n, fd;
1262 /* don't even try a .exe */
1263 n = strlen(cmd);
1264 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1265 return NULL;
1267 fd = open(cmd, O_RDONLY);
1268 if (fd < 0)
1269 return NULL;
1270 n = read(fd, buf, sizeof(buf)-1);
1271 close(fd);
1272 if (n < 4) /* at least '#!/x' and not error */
1273 return NULL;
1275 if (buf[0] != '#' || buf[1] != '!')
1276 return NULL;
1277 buf[n] = '\0';
1278 p = buf + strcspn(buf, "\r\n");
1279 if (!*p)
1280 return NULL;
1282 *p = '\0';
1283 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1284 return NULL;
1285 /* strip options */
1286 if ((opt = strchr(p+1, ' ')))
1287 *opt = '\0';
1288 return p+1;
1292 * exe_only means that we only want to detect .exe files, but not scripts
1293 * (which do not have an extension)
1295 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1296 int isexe, int exe_only)
1298 char path[MAX_PATH];
1299 wchar_t wpath[MAX_PATH];
1300 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1302 if (xutftowcs_path(wpath, path) < 0)
1303 return NULL;
1305 if (!isexe && _waccess(wpath, F_OK) == 0)
1306 return xstrdup(path);
1307 wpath[wcslen(wpath)-4] = '\0';
1308 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1309 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1310 path[strlen(path)-4] = '\0';
1311 return xstrdup(path);
1314 return NULL;
1318 * Determines the absolute path of cmd using the split path in path.
1319 * If cmd contains a slash or backslash, no lookup is performed.
1321 static char *path_lookup(const char *cmd, int exe_only)
1323 const char *path;
1324 char *prog = NULL;
1325 int len = strlen(cmd);
1326 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1328 if (strpbrk(cmd, "/\\"))
1329 return xstrdup(cmd);
1331 path = mingw_getenv("PATH");
1332 if (!path)
1333 return NULL;
1335 while (!prog) {
1336 const char *sep = strchrnul(path, ';');
1337 int dirlen = sep - path;
1338 if (dirlen)
1339 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1340 if (!*sep)
1341 break;
1342 path = sep + 1;
1345 return prog;
1348 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1350 while (*s && *s != c)
1351 s++;
1352 return s;
1355 /* Compare only keys */
1356 static int wenvcmp(const void *a, const void *b)
1358 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1359 size_t p_len, q_len;
1361 /* Find the keys */
1362 p_len = wcschrnul(p, L'=') - p;
1363 q_len = wcschrnul(q, L'=') - q;
1365 /* If the length differs, include the shorter key's NUL */
1366 if (p_len < q_len)
1367 p_len++;
1368 else if (p_len > q_len)
1369 p_len = q_len + 1;
1371 return _wcsnicmp(p, q, p_len);
1375 * Build an environment block combining the inherited environment
1376 * merged with the given list of settings.
1378 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1379 * Values of the form "KEY" in deltaenv delete inherited values.
1381 * Multiple entries in deltaenv for the same key are explicitly allowed.
1383 * We return a contiguous block of UNICODE strings with a final trailing
1384 * zero word.
1386 static wchar_t *make_environment_block(char **deltaenv)
1388 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1389 size_t wlen, s, delta_size, size;
1391 wchar_t **array = NULL;
1392 size_t alloc = 0, nr = 0, i;
1394 size = 1; /* for extra NUL at the end */
1396 /* If there is no deltaenv to apply, simply return a copy. */
1397 if (!deltaenv || !*deltaenv) {
1398 for (p = wenv; p && *p; ) {
1399 size_t s = wcslen(p) + 1;
1400 size += s;
1401 p += s;
1404 DUP_ARRAY(result, wenv, size);
1405 FreeEnvironmentStringsW(wenv);
1406 return result;
1410 * If there is a deltaenv, let's accumulate all keys into `array`,
1411 * sort them using the stable git_stable_qsort() and then copy,
1412 * skipping duplicate keys
1414 for (p = wenv; p && *p; ) {
1415 ALLOC_GROW(array, nr + 1, alloc);
1416 s = wcslen(p) + 1;
1417 array[nr++] = p;
1418 p += s;
1419 size += s;
1422 /* (over-)assess size needed for wchar version of deltaenv */
1423 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1424 delta_size += strlen(deltaenv[i]) * 2 + 1;
1425 ALLOC_ARRAY(wdeltaenv, delta_size);
1427 /* convert the deltaenv, appending to array */
1428 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1429 ALLOC_GROW(array, nr + 1, alloc);
1430 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1431 array[nr++] = p;
1432 p += wlen + 1;
1435 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1436 ALLOC_ARRAY(result, size + delta_size);
1438 for (p = result, i = 0; i < nr; i++) {
1439 /* Skip any duplicate keys; last one wins */
1440 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1441 i++;
1443 /* Skip "to delete" entry */
1444 if (!wcschr(array[i], L'='))
1445 continue;
1447 size = wcslen(array[i]) + 1;
1448 COPY_ARRAY(p, array[i], size);
1449 p += size;
1451 *p = L'\0';
1453 free(array);
1454 free(wdeltaenv);
1455 FreeEnvironmentStringsW(wenv);
1456 return result;
1459 static void do_unset_environment_variables(void)
1461 static int done;
1462 char *p = unset_environment_variables;
1464 if (done || !p)
1465 return;
1466 done = 1;
1468 for (;;) {
1469 char *comma = strchr(p, ',');
1471 if (comma)
1472 *comma = '\0';
1473 unsetenv(p);
1474 if (!comma)
1475 break;
1476 p = comma + 1;
1480 struct pinfo_t {
1481 struct pinfo_t *next;
1482 pid_t pid;
1483 HANDLE proc;
1485 static struct pinfo_t *pinfo = NULL;
1486 CRITICAL_SECTION pinfo_cs;
1488 /* Used to match and chomp off path components */
1489 static inline int match_last_path_component(const char *path, size_t *len,
1490 const char *component)
1492 size_t component_len = strlen(component);
1493 if (*len < component_len + 1 ||
1494 !is_dir_sep(path[*len - component_len - 1]) ||
1495 fspathncmp(path + *len - component_len, component, component_len))
1496 return 0;
1497 *len -= component_len + 1;
1498 /* chomp off repeated dir separators */
1499 while (*len > 0 && is_dir_sep(path[*len - 1]))
1500 (*len)--;
1501 return 1;
1504 static int is_msys2_sh(const char *cmd)
1506 if (!cmd)
1507 return 0;
1509 if (!strcmp(cmd, "sh")) {
1510 static int ret = -1;
1511 char *p;
1513 if (ret >= 0)
1514 return ret;
1516 p = path_lookup(cmd, 0);
1517 if (!p)
1518 ret = 0;
1519 else {
1520 size_t len = strlen(p);
1522 ret = match_last_path_component(p, &len, "sh.exe") &&
1523 match_last_path_component(p, &len, "bin") &&
1524 match_last_path_component(p, &len, "usr");
1525 free(p);
1527 return ret;
1530 if (ends_with(cmd, "\\sh.exe")) {
1531 static char *sh;
1533 if (!sh)
1534 sh = path_lookup("sh", 0);
1536 return !fspathcmp(cmd, sh);
1539 return 0;
1542 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1543 const char *dir,
1544 int prepend_cmd, int fhin, int fhout, int fherr)
1546 static int restrict_handle_inheritance = -1;
1547 STARTUPINFOEXW si;
1548 PROCESS_INFORMATION pi;
1549 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1550 HANDLE stdhandles[3];
1551 DWORD stdhandles_count = 0;
1552 SIZE_T size;
1553 struct strbuf args;
1554 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1555 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1556 BOOL ret;
1557 HANDLE cons;
1558 const char *(*quote_arg)(const char *arg) =
1559 is_msys2_sh(cmd ? cmd : *argv) ?
1560 quote_arg_msys2 : quote_arg_msvc;
1561 const char *strace_env;
1563 /* Make sure to override previous errors, if any */
1564 errno = 0;
1566 if (restrict_handle_inheritance < 0)
1567 restrict_handle_inheritance = core_restrict_inherited_handles;
1569 * The following code to restrict which handles are inherited seems
1570 * to work properly only on Windows 7 and later, so let's disable it
1571 * on Windows Vista and 2008.
1573 if (restrict_handle_inheritance < 0)
1574 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1576 do_unset_environment_variables();
1578 /* Determine whether or not we are associated to a console */
1579 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1580 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1581 FILE_ATTRIBUTE_NORMAL, NULL);
1582 if (cons == INVALID_HANDLE_VALUE) {
1583 /* There is no console associated with this process.
1584 * Since the child is a console process, Windows
1585 * would normally create a console window. But
1586 * since we'll be redirecting std streams, we do
1587 * not need the console.
1588 * It is necessary to use DETACHED_PROCESS
1589 * instead of CREATE_NO_WINDOW to make ssh
1590 * recognize that it has no console.
1592 flags |= DETACHED_PROCESS;
1593 } else {
1594 /* There is already a console. If we specified
1595 * DETACHED_PROCESS here, too, Windows would
1596 * disassociate the child from the console.
1597 * The same is true for CREATE_NO_WINDOW.
1598 * Go figure!
1600 CloseHandle(cons);
1602 memset(&si, 0, sizeof(si));
1603 si.StartupInfo.cb = sizeof(si);
1604 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1605 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1606 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1608 /* The list of handles cannot contain duplicates */
1609 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1610 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1611 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1612 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1613 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1614 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1615 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1616 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1617 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1618 if (stdhandles_count)
1619 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1621 if (*argv && !strcmp(cmd, *argv))
1622 wcmd[0] = L'\0';
1623 else if (xutftowcs_path(wcmd, cmd) < 0)
1624 return -1;
1625 if (dir && xutftowcs_path(wdir, dir) < 0)
1626 return -1;
1628 /* concatenate argv, quoting args as we go */
1629 strbuf_init(&args, 0);
1630 if (prepend_cmd) {
1631 char *quoted = (char *)quote_arg(cmd);
1632 strbuf_addstr(&args, quoted);
1633 if (quoted != cmd)
1634 free(quoted);
1636 for (; *argv; argv++) {
1637 char *quoted = (char *)quote_arg(*argv);
1638 if (*args.buf)
1639 strbuf_addch(&args, ' ');
1640 strbuf_addstr(&args, quoted);
1641 if (quoted != *argv)
1642 free(quoted);
1645 strace_env = getenv("GIT_STRACE_COMMANDS");
1646 if (strace_env) {
1647 char *p = path_lookup("strace.exe", 1);
1648 if (!p)
1649 return error("strace not found!");
1650 if (xutftowcs_path(wcmd, p) < 0) {
1651 free(p);
1652 return -1;
1654 free(p);
1655 if (!strcmp("1", strace_env) ||
1656 !strcasecmp("yes", strace_env) ||
1657 !strcasecmp("true", strace_env))
1658 strbuf_insert(&args, 0, "strace ", 7);
1659 else {
1660 const char *quoted = quote_arg(strace_env);
1661 struct strbuf buf = STRBUF_INIT;
1662 strbuf_addf(&buf, "strace -o %s ", quoted);
1663 if (quoted != strace_env)
1664 free((char *)quoted);
1665 strbuf_insert(&args, 0, buf.buf, buf.len);
1666 strbuf_release(&buf);
1670 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1671 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1672 strbuf_release(&args);
1674 wenvblk = make_environment_block(deltaenv);
1676 memset(&pi, 0, sizeof(pi));
1677 if (restrict_handle_inheritance && stdhandles_count &&
1678 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1679 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1680 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1681 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1682 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1683 UpdateProcThreadAttribute(attr_list, 0,
1684 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1685 stdhandles,
1686 stdhandles_count * sizeof(HANDLE),
1687 NULL, NULL)) {
1688 si.lpAttributeList = attr_list;
1689 flags |= EXTENDED_STARTUPINFO_PRESENT;
1692 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1693 stdhandles_count ? TRUE : FALSE,
1694 flags, wenvblk, dir ? wdir : NULL,
1695 &si.StartupInfo, &pi);
1698 * On Windows 2008 R2, it seems that specifying certain types of handles
1699 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1700 * error. Rather than playing finicky and fragile games, let's just try
1701 * to detect this situation and simply try again without restricting any
1702 * handle inheritance. This is still better than failing to create
1703 * processes.
1705 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1706 DWORD err = GetLastError();
1707 struct strbuf buf = STRBUF_INIT;
1709 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1711 * On Windows 7 and earlier, handles on pipes and character
1712 * devices are inherited automatically, and cannot be
1713 * specified in the thread handle list. Rather than trying
1714 * to catch each and every corner case (and running the
1715 * chance of *still* forgetting a few), let's just fall
1716 * back to creating the process without trying to limit the
1717 * handle inheritance.
1719 !(err == ERROR_INVALID_PARAMETER &&
1720 GetVersion() >> 16 < 9200) &&
1721 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1722 DWORD fl = 0;
1723 int i;
1725 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1727 for (i = 0; i < stdhandles_count; i++) {
1728 HANDLE h = stdhandles[i];
1729 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1730 "handle info (%d) %lx\n", i, h,
1731 GetFileType(h),
1732 GetHandleInformation(h, &fl),
1733 fl);
1735 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1736 "at\nhttps://github.com/git-for-windows/"
1737 "git/issues/new\n\n"
1738 "To suppress this warning, please set "
1739 "the environment variable\n\n"
1740 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1741 "\n");
1743 restrict_handle_inheritance = 0;
1744 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1745 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1746 TRUE, flags, wenvblk, dir ? wdir : NULL,
1747 &si.StartupInfo, &pi);
1748 if (!ret)
1749 errno = err_win_to_posix(GetLastError());
1750 if (ret && buf.len) {
1751 warning("failed to restrict file handles (%ld)\n\n%s",
1752 err, buf.buf);
1754 strbuf_release(&buf);
1755 } else if (!ret)
1756 errno = err_win_to_posix(GetLastError());
1758 if (si.lpAttributeList)
1759 DeleteProcThreadAttributeList(si.lpAttributeList);
1760 if (attr_list)
1761 HeapFree(GetProcessHeap(), 0, attr_list);
1763 free(wenvblk);
1764 free(wargs);
1766 if (!ret)
1767 return -1;
1769 CloseHandle(pi.hThread);
1772 * The process ID is the human-readable identifier of the process
1773 * that we want to present in log and error messages. The handle
1774 * is not useful for this purpose. But we cannot close it, either,
1775 * because it is not possible to turn a process ID into a process
1776 * handle after the process terminated.
1777 * Keep the handle in a list for waitpid.
1779 EnterCriticalSection(&pinfo_cs);
1781 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1782 info->pid = pi.dwProcessId;
1783 info->proc = pi.hProcess;
1784 info->next = pinfo;
1785 pinfo = info;
1787 LeaveCriticalSection(&pinfo_cs);
1789 return (pid_t)pi.dwProcessId;
1792 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1794 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1797 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1798 const char *dir,
1799 int fhin, int fhout, int fherr)
1801 pid_t pid;
1802 char *prog = path_lookup(cmd, 0);
1804 if (!prog) {
1805 errno = ENOENT;
1806 pid = -1;
1808 else {
1809 const char *interpr = parse_interpreter(prog);
1811 if (interpr) {
1812 const char *argv0 = argv[0];
1813 char *iprog = path_lookup(interpr, 1);
1814 argv[0] = prog;
1815 if (!iprog) {
1816 errno = ENOENT;
1817 pid = -1;
1819 else {
1820 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1821 fhin, fhout, fherr);
1822 free(iprog);
1824 argv[0] = argv0;
1826 else
1827 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1828 fhin, fhout, fherr);
1829 free(prog);
1831 return pid;
1834 static int try_shell_exec(const char *cmd, char *const *argv)
1836 const char *interpr = parse_interpreter(cmd);
1837 char *prog;
1838 int pid = 0;
1840 if (!interpr)
1841 return 0;
1842 prog = path_lookup(interpr, 1);
1843 if (prog) {
1844 int exec_id;
1845 int argc = 0;
1846 char **argv2;
1847 while (argv[argc]) argc++;
1848 ALLOC_ARRAY(argv2, argc + 1);
1849 argv2[0] = (char *)cmd; /* full path to the script file */
1850 COPY_ARRAY(&argv2[1], &argv[1], argc);
1851 exec_id = trace2_exec(prog, (const char **)argv2);
1852 pid = mingw_spawnv(prog, (const char **)argv2, 1);
1853 if (pid >= 0) {
1854 int status;
1855 if (waitpid(pid, &status, 0) < 0)
1856 status = 255;
1857 trace2_exec_result(exec_id, status);
1858 exit(status);
1860 trace2_exec_result(exec_id, -1);
1861 pid = 1; /* indicate that we tried but failed */
1862 free(prog);
1863 free(argv2);
1865 return pid;
1868 int mingw_execv(const char *cmd, char *const *argv)
1870 /* check if git_command is a shell script */
1871 if (!try_shell_exec(cmd, argv)) {
1872 int pid, status;
1873 int exec_id;
1875 exec_id = trace2_exec(cmd, (const char **)argv);
1876 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1877 if (pid < 0) {
1878 trace2_exec_result(exec_id, -1);
1879 return -1;
1881 if (waitpid(pid, &status, 0) < 0)
1882 status = 255;
1883 trace2_exec_result(exec_id, status);
1884 exit(status);
1886 return -1;
1889 int mingw_execvp(const char *cmd, char *const *argv)
1891 char *prog = path_lookup(cmd, 0);
1893 if (prog) {
1894 mingw_execv(prog, argv);
1895 free(prog);
1896 } else
1897 errno = ENOENT;
1899 return -1;
1902 int mingw_kill(pid_t pid, int sig)
1904 if (pid > 0 && sig == SIGTERM) {
1905 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1907 if (TerminateProcess(h, -1)) {
1908 CloseHandle(h);
1909 return 0;
1912 errno = err_win_to_posix(GetLastError());
1913 CloseHandle(h);
1914 return -1;
1915 } else if (pid > 0 && sig == 0) {
1916 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1917 if (h) {
1918 CloseHandle(h);
1919 return 0;
1923 errno = EINVAL;
1924 return -1;
1928 * UTF-8 versions of getenv(), putenv() and unsetenv().
1929 * Internally, they use the CRT's stock UNICODE routines
1930 * to avoid data loss.
1932 char *mingw_getenv(const char *name)
1934 #define GETENV_MAX_RETAIN 64
1935 static char *values[GETENV_MAX_RETAIN];
1936 static int value_counter;
1937 int len_key, len_value;
1938 wchar_t *w_key;
1939 char *value;
1940 wchar_t w_value[32768];
1942 if (!name || !*name)
1943 return NULL;
1945 len_key = strlen(name) + 1;
1946 /* We cannot use xcalloc() here because that uses getenv() itself */
1947 w_key = calloc(len_key, sizeof(wchar_t));
1948 if (!w_key)
1949 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1950 xutftowcs(w_key, name, len_key);
1951 /* GetEnvironmentVariableW() only sets the last error upon failure */
1952 SetLastError(ERROR_SUCCESS);
1953 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1954 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1955 free(w_key);
1956 return NULL;
1958 free(w_key);
1960 len_value = len_value * 3 + 1;
1961 /* We cannot use xcalloc() here because that uses getenv() itself */
1962 value = calloc(len_value, sizeof(char));
1963 if (!value)
1964 die("Out of memory, (tried to allocate %u bytes)", len_value);
1965 xwcstoutf(value, w_value, len_value);
1968 * We return `value` which is an allocated value and the caller is NOT
1969 * expecting to have to free it, so we keep a round-robin array,
1970 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1972 free(values[value_counter]);
1973 values[value_counter++] = value;
1974 if (value_counter >= ARRAY_SIZE(values))
1975 value_counter = 0;
1977 return value;
1980 int mingw_putenv(const char *namevalue)
1982 int size;
1983 wchar_t *wide, *equal;
1984 BOOL result;
1986 if (!namevalue || !*namevalue)
1987 return 0;
1989 size = strlen(namevalue) * 2 + 1;
1990 wide = calloc(size, sizeof(wchar_t));
1991 if (!wide)
1992 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1993 xutftowcs(wide, namevalue, size);
1994 equal = wcschr(wide, L'=');
1995 if (!equal)
1996 result = SetEnvironmentVariableW(wide, NULL);
1997 else {
1998 *equal = L'\0';
1999 result = SetEnvironmentVariableW(wide, equal + 1);
2001 free(wide);
2003 if (!result)
2004 errno = err_win_to_posix(GetLastError());
2006 return result ? 0 : -1;
2009 static void ensure_socket_initialization(void)
2011 WSADATA wsa;
2012 static int initialized = 0;
2014 if (initialized)
2015 return;
2017 if (WSAStartup(MAKEWORD(2,2), &wsa))
2018 die("unable to initialize winsock subsystem, error %d",
2019 WSAGetLastError());
2021 atexit((void(*)(void)) WSACleanup);
2022 initialized = 1;
2025 #undef gethostname
2026 int mingw_gethostname(char *name, int namelen)
2028 ensure_socket_initialization();
2029 return gethostname(name, namelen);
2032 #undef gethostbyname
2033 struct hostent *mingw_gethostbyname(const char *host)
2035 ensure_socket_initialization();
2036 return gethostbyname(host);
2039 #undef getaddrinfo
2040 int mingw_getaddrinfo(const char *node, const char *service,
2041 const struct addrinfo *hints, struct addrinfo **res)
2043 ensure_socket_initialization();
2044 return getaddrinfo(node, service, hints, res);
2047 int mingw_socket(int domain, int type, int protocol)
2049 int sockfd;
2050 SOCKET s;
2052 ensure_socket_initialization();
2053 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2054 if (s == INVALID_SOCKET) {
2056 * WSAGetLastError() values are regular BSD error codes
2057 * biased by WSABASEERR.
2058 * However, strerror() does not know about networking
2059 * specific errors, which are values beginning at 38 or so.
2060 * Therefore, we choose to leave the biased error code
2061 * in errno so that _if_ someone looks up the code somewhere,
2062 * then it is at least the number that are usually listed.
2064 errno = WSAGetLastError();
2065 return -1;
2067 /* convert into a file descriptor */
2068 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2069 closesocket(s);
2070 return error("unable to make a socket file descriptor: %s",
2071 strerror(errno));
2073 return sockfd;
2076 #undef connect
2077 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2079 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2080 return connect(s, sa, sz);
2083 #undef bind
2084 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2086 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2087 return bind(s, sa, sz);
2090 #undef setsockopt
2091 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2093 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2094 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2097 #undef shutdown
2098 int mingw_shutdown(int sockfd, int how)
2100 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2101 return shutdown(s, how);
2104 #undef listen
2105 int mingw_listen(int sockfd, int backlog)
2107 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2108 return listen(s, backlog);
2111 #undef accept
2112 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2114 int sockfd2;
2116 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2117 SOCKET s2 = accept(s1, sa, sz);
2119 /* convert into a file descriptor */
2120 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2121 int err = errno;
2122 closesocket(s2);
2123 return error("unable to make a socket file descriptor: %s",
2124 strerror(err));
2126 return sockfd2;
2129 #undef rename
2130 int mingw_rename(const char *pold, const char *pnew)
2132 DWORD attrs, gle;
2133 int tries = 0;
2134 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2135 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2136 return -1;
2139 * Try native rename() first to get errno right.
2140 * It is based on MoveFile(), which cannot overwrite existing files.
2142 if (!_wrename(wpold, wpnew))
2143 return 0;
2144 if (errno != EEXIST)
2145 return -1;
2146 repeat:
2147 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2148 return 0;
2149 /* TODO: translate more errors */
2150 gle = GetLastError();
2151 if (gle == ERROR_ACCESS_DENIED &&
2152 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2153 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2154 DWORD attrsold = GetFileAttributesW(wpold);
2155 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2156 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2157 errno = EISDIR;
2158 else if (!_wrmdir(wpnew))
2159 goto repeat;
2160 return -1;
2162 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2163 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2164 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2165 return 0;
2166 gle = GetLastError();
2167 /* revert file attributes on failure */
2168 SetFileAttributesW(wpnew, attrs);
2171 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2173 * We assume that some other process had the source or
2174 * destination file open at the wrong moment and retry.
2175 * In order to give the other process a higher chance to
2176 * complete its operation, we give up our time slice now.
2177 * If we have to retry again, we do sleep a bit.
2179 Sleep(delay[tries]);
2180 tries++;
2181 goto repeat;
2183 if (gle == ERROR_ACCESS_DENIED &&
2184 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2185 "Should I try again?", pold, pnew))
2186 goto repeat;
2188 errno = EACCES;
2189 return -1;
2193 * Note that this doesn't return the actual pagesize, but
2194 * the allocation granularity. If future Windows specific git code
2195 * needs the real getpagesize function, we need to find another solution.
2197 int mingw_getpagesize(void)
2199 SYSTEM_INFO si;
2200 GetSystemInfo(&si);
2201 return si.dwAllocationGranularity;
2204 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2205 enum EXTENDED_NAME_FORMAT {
2206 NameDisplay = 3,
2207 NameUserPrincipal = 8
2210 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2212 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2213 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2214 static wchar_t wbuffer[1024];
2215 DWORD len;
2217 if (!INIT_PROC_ADDR(GetUserNameExW))
2218 return NULL;
2220 len = ARRAY_SIZE(wbuffer);
2221 if (GetUserNameExW(type, wbuffer, &len)) {
2222 char *converted = xmalloc((len *= 3));
2223 if (xwcstoutf(converted, wbuffer, len) >= 0)
2224 return converted;
2225 free(converted);
2228 return NULL;
2231 char *mingw_query_user_email(void)
2233 return get_extended_user_info(NameUserPrincipal);
2236 struct passwd *getpwuid(int uid)
2238 static unsigned initialized;
2239 static char user_name[100];
2240 static struct passwd *p;
2241 wchar_t buf[100];
2242 DWORD len;
2244 if (initialized)
2245 return p;
2247 len = ARRAY_SIZE(buf);
2248 if (!GetUserNameW(buf, &len)) {
2249 initialized = 1;
2250 return NULL;
2253 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2254 initialized = 1;
2255 return NULL;
2258 p = xmalloc(sizeof(*p));
2259 p->pw_name = user_name;
2260 p->pw_gecos = get_extended_user_info(NameDisplay);
2261 if (!p->pw_gecos)
2262 p->pw_gecos = "unknown";
2263 p->pw_dir = NULL;
2265 initialized = 1;
2266 return p;
2269 static HANDLE timer_event;
2270 static HANDLE timer_thread;
2271 static int timer_interval;
2272 static int one_shot;
2273 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2275 /* The timer works like this:
2276 * The thread, ticktack(), is a trivial routine that most of the time
2277 * only waits to receive the signal to terminate. The main thread tells
2278 * the thread to terminate by setting the timer_event to the signalled
2279 * state.
2280 * But ticktack() interrupts the wait state after the timer's interval
2281 * length to call the signal handler.
2284 static unsigned __stdcall ticktack(void *dummy)
2286 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2287 mingw_raise(SIGALRM);
2288 if (one_shot)
2289 break;
2291 return 0;
2294 static int start_timer_thread(void)
2296 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2297 if (timer_event) {
2298 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2299 if (!timer_thread )
2300 return errno = ENOMEM,
2301 error("cannot start timer thread");
2302 } else
2303 return errno = ENOMEM,
2304 error("cannot allocate resources for timer");
2305 return 0;
2308 static void stop_timer_thread(void)
2310 if (timer_event)
2311 SetEvent(timer_event); /* tell thread to terminate */
2312 if (timer_thread) {
2313 int rc = WaitForSingleObject(timer_thread, 10000);
2314 if (rc == WAIT_TIMEOUT)
2315 error("timer thread did not terminate timely");
2316 else if (rc != WAIT_OBJECT_0)
2317 error("waiting for timer thread failed: %lu",
2318 GetLastError());
2319 CloseHandle(timer_thread);
2321 if (timer_event)
2322 CloseHandle(timer_event);
2323 timer_event = NULL;
2324 timer_thread = NULL;
2327 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2329 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2332 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2334 static const struct timeval zero;
2335 static int atexit_done;
2337 if (out)
2338 return errno = EINVAL,
2339 error("setitimer param 3 != NULL not implemented");
2340 if (!is_timeval_eq(&in->it_interval, &zero) &&
2341 !is_timeval_eq(&in->it_interval, &in->it_value))
2342 return errno = EINVAL,
2343 error("setitimer: it_interval must be zero or eq it_value");
2345 if (timer_thread)
2346 stop_timer_thread();
2348 if (is_timeval_eq(&in->it_value, &zero) &&
2349 is_timeval_eq(&in->it_interval, &zero))
2350 return 0;
2352 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2353 one_shot = is_timeval_eq(&in->it_interval, &zero);
2354 if (!atexit_done) {
2355 atexit(stop_timer_thread);
2356 atexit_done = 1;
2358 return start_timer_thread();
2361 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2363 if (sig != SIGALRM)
2364 return errno = EINVAL,
2365 error("sigaction only implemented for SIGALRM");
2366 if (out)
2367 return errno = EINVAL,
2368 error("sigaction: param 3 != NULL not implemented");
2370 timer_fn = in->sa_handler;
2371 return 0;
2374 #undef signal
2375 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2377 sig_handler_t old;
2379 switch (sig) {
2380 case SIGALRM:
2381 old = timer_fn;
2382 timer_fn = handler;
2383 break;
2385 case SIGINT:
2386 old = sigint_fn;
2387 sigint_fn = handler;
2388 break;
2390 default:
2391 return signal(sig, handler);
2394 return old;
2397 #undef raise
2398 int mingw_raise(int sig)
2400 switch (sig) {
2401 case SIGALRM:
2402 if (timer_fn == SIG_DFL) {
2403 if (isatty(STDERR_FILENO))
2404 fputs("Alarm clock\n", stderr);
2405 exit(128 + SIGALRM);
2406 } else if (timer_fn != SIG_IGN)
2407 timer_fn(SIGALRM);
2408 return 0;
2410 case SIGINT:
2411 if (sigint_fn == SIG_DFL)
2412 exit(128 + SIGINT);
2413 else if (sigint_fn != SIG_IGN)
2414 sigint_fn(SIGINT);
2415 return 0;
2417 #if defined(_MSC_VER)
2418 case SIGILL:
2419 case SIGFPE:
2420 case SIGSEGV:
2421 case SIGTERM:
2422 case SIGBREAK:
2423 case SIGABRT:
2424 case SIGABRT_COMPAT:
2426 * The <signal.h> header in the MS C Runtime defines 8 signals
2427 * as being supported on the platform. Anything else causes an
2428 * "Invalid signal or error" (which in DEBUG builds causes the
2429 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2430 * already know will fail.
2432 return raise(sig);
2433 default:
2434 errno = EINVAL;
2435 return -1;
2437 #else
2439 default:
2440 return raise(sig);
2442 #endif
2447 int link(const char *oldpath, const char *newpath)
2449 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2450 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2451 xutftowcs_path(wnewpath, newpath) < 0)
2452 return -1;
2454 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2455 errno = err_win_to_posix(GetLastError());
2456 return -1;
2458 return 0;
2461 pid_t waitpid(pid_t pid, int *status, int options)
2463 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2464 FALSE, pid);
2465 if (!h) {
2466 errno = ECHILD;
2467 return -1;
2470 if (pid > 0 && options & WNOHANG) {
2471 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2472 CloseHandle(h);
2473 return 0;
2475 options &= ~WNOHANG;
2478 if (options == 0) {
2479 struct pinfo_t **ppinfo;
2480 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2481 CloseHandle(h);
2482 return 0;
2485 if (status)
2486 GetExitCodeProcess(h, (LPDWORD)status);
2488 EnterCriticalSection(&pinfo_cs);
2490 ppinfo = &pinfo;
2491 while (*ppinfo) {
2492 struct pinfo_t *info = *ppinfo;
2493 if (info->pid == pid) {
2494 CloseHandle(info->proc);
2495 *ppinfo = info->next;
2496 free(info);
2497 break;
2499 ppinfo = &info->next;
2502 LeaveCriticalSection(&pinfo_cs);
2504 CloseHandle(h);
2505 return pid;
2507 CloseHandle(h);
2509 errno = EINVAL;
2510 return -1;
2513 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2515 int upos = 0, wpos = 0;
2516 const unsigned char *utf = (const unsigned char*) utfs;
2517 if (!utf || !wcs || wcslen < 1) {
2518 errno = EINVAL;
2519 return -1;
2521 /* reserve space for \0 */
2522 wcslen--;
2523 if (utflen < 0)
2524 utflen = INT_MAX;
2526 while (upos < utflen) {
2527 int c = utf[upos++] & 0xff;
2528 if (utflen == INT_MAX && c == 0)
2529 break;
2531 if (wpos >= wcslen) {
2532 wcs[wpos] = 0;
2533 errno = ERANGE;
2534 return -1;
2537 if (c < 0x80) {
2538 /* ASCII */
2539 wcs[wpos++] = c;
2540 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2541 (utf[upos] & 0xc0) == 0x80) {
2542 /* 2-byte utf-8 */
2543 c = ((c & 0x1f) << 6);
2544 c |= (utf[upos++] & 0x3f);
2545 wcs[wpos++] = c;
2546 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2547 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2548 (utf[upos] & 0xc0) == 0x80 &&
2549 (utf[upos + 1] & 0xc0) == 0x80) {
2550 /* 3-byte utf-8 */
2551 c = ((c & 0x0f) << 12);
2552 c |= ((utf[upos++] & 0x3f) << 6);
2553 c |= (utf[upos++] & 0x3f);
2554 wcs[wpos++] = c;
2555 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2556 wpos + 1 < wcslen &&
2557 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2558 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2559 (utf[upos] & 0xc0) == 0x80 &&
2560 (utf[upos + 1] & 0xc0) == 0x80 &&
2561 (utf[upos + 2] & 0xc0) == 0x80) {
2562 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2563 c = ((c & 0x07) << 18);
2564 c |= ((utf[upos++] & 0x3f) << 12);
2565 c |= ((utf[upos++] & 0x3f) << 6);
2566 c |= (utf[upos++] & 0x3f);
2567 c -= 0x10000;
2568 wcs[wpos++] = 0xd800 | (c >> 10);
2569 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2570 } else if (c >= 0xa0) {
2571 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2572 wcs[wpos++] = c;
2573 } else {
2574 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2575 static const char *hex = "0123456789abcdef";
2576 wcs[wpos++] = hex[c >> 4];
2577 if (wpos < wcslen)
2578 wcs[wpos++] = hex[c & 0x0f];
2581 wcs[wpos] = 0;
2582 return wpos;
2585 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2587 if (!wcs || !utf || utflen < 1) {
2588 errno = EINVAL;
2589 return -1;
2591 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2592 if (utflen)
2593 return utflen - 1;
2594 errno = ERANGE;
2595 return -1;
2598 static void setup_windows_environment(void)
2600 char *tmp = getenv("TMPDIR");
2602 /* on Windows it is TMP and TEMP */
2603 if (!tmp) {
2604 if (!(tmp = getenv("TMP")))
2605 tmp = getenv("TEMP");
2606 if (tmp) {
2607 setenv("TMPDIR", tmp, 1);
2608 tmp = getenv("TMPDIR");
2612 if (tmp) {
2614 * Convert all dir separators to forward slashes,
2615 * to help shell commands called from the Git
2616 * executable (by not mistaking the dir separators
2617 * for escape characters).
2619 convert_slashes(tmp);
2622 /* simulate TERM to enable auto-color (see color.c) */
2623 if (!getenv("TERM"))
2624 setenv("TERM", "cygwin", 1);
2626 /* calculate HOME if not set */
2627 if (!getenv("HOME")) {
2629 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2630 * location, thus also check if the path exists (i.e. is not
2631 * disconnected)
2633 if ((tmp = getenv("HOMEDRIVE"))) {
2634 struct strbuf buf = STRBUF_INIT;
2635 strbuf_addstr(&buf, tmp);
2636 if ((tmp = getenv("HOMEPATH"))) {
2637 strbuf_addstr(&buf, tmp);
2638 if (is_directory(buf.buf))
2639 setenv("HOME", buf.buf, 1);
2640 else
2641 tmp = NULL; /* use $USERPROFILE */
2643 strbuf_release(&buf);
2645 /* use $USERPROFILE if the home share is not available */
2646 if (!tmp && (tmp = getenv("USERPROFILE")))
2647 setenv("HOME", tmp, 1);
2651 static PSID get_current_user_sid(void)
2653 HANDLE token;
2654 DWORD len = 0;
2655 PSID result = NULL;
2657 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2658 return NULL;
2660 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2661 TOKEN_USER *info = xmalloc((size_t)len);
2662 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2663 len = GetLengthSid(info->User.Sid);
2664 result = xmalloc(len);
2665 if (!CopySid(len, result, info->User.Sid)) {
2666 error(_("failed to copy SID (%ld)"),
2667 GetLastError());
2668 FREE_AND_NULL(result);
2671 FREE_AND_NULL(info);
2673 CloseHandle(token);
2675 return result;
2678 static int acls_supported(const char *path)
2680 size_t offset = offset_1st_component(path);
2681 WCHAR wroot[MAX_PATH];
2682 DWORD file_system_flags;
2684 if (offset &&
2685 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2686 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2687 &file_system_flags, NULL, 0))
2688 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2690 return 0;
2693 int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
2695 WCHAR wpath[MAX_PATH];
2696 PSID sid = NULL;
2697 PSECURITY_DESCRIPTOR descriptor = NULL;
2698 DWORD err;
2700 static wchar_t home[MAX_PATH];
2702 int result = 0;
2704 if (xutftowcs_path(wpath, path) < 0)
2705 return 0;
2708 * On Windows, the home directory is owned by the administrator, but for
2709 * all practical purposes, it belongs to the user. Do pretend that it is
2710 * owned by the user.
2712 if (!*home) {
2713 DWORD size = ARRAY_SIZE(home);
2714 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2715 if (!len || len > size)
2716 wcscpy(home, L"::N/A::");
2718 if (!wcsicmp(wpath, home))
2719 return 1;
2721 /* Get the owner SID */
2722 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2723 OWNER_SECURITY_INFORMATION |
2724 DACL_SECURITY_INFORMATION,
2725 &sid, NULL, NULL, NULL, &descriptor);
2727 if (err != ERROR_SUCCESS)
2728 error(_("failed to get owner for '%s' (%ld)"), path, err);
2729 else if (sid && IsValidSid(sid)) {
2730 /* Now, verify that the SID matches the current user's */
2731 static PSID current_user_sid;
2732 BOOL is_member;
2734 if (!current_user_sid)
2735 current_user_sid = get_current_user_sid();
2737 if (current_user_sid &&
2738 IsValidSid(current_user_sid) &&
2739 EqualSid(sid, current_user_sid))
2740 result = 1;
2741 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
2742 CheckTokenMembership(NULL, sid, &is_member) &&
2743 is_member)
2745 * If owned by the Administrators group, and the
2746 * current user is an administrator, we consider that
2747 * okay, too.
2749 result = 1;
2750 else if (report &&
2751 IsWellKnownSid(sid, WinWorldSid) &&
2752 !acls_supported(path)) {
2754 * On FAT32 volumes, ownership is not actually recorded.
2756 strbuf_addf(report, "'%s' is on a file system that does "
2757 "not record ownership\n", path);
2758 } else if (report) {
2759 LPSTR str1, str2, to_free1 = NULL, to_free2 = NULL;
2761 if (ConvertSidToStringSidA(sid, &str1))
2762 to_free1 = str1;
2763 else
2764 str1 = "(inconvertible)";
2766 if (!current_user_sid)
2767 str2 = "(none)";
2768 else if (!IsValidSid(current_user_sid))
2769 str2 = "(invalid)";
2770 else if (ConvertSidToStringSidA(current_user_sid, &str2))
2771 to_free2 = str2;
2772 else
2773 str2 = "(inconvertible)";
2774 strbuf_addf(report,
2775 "'%s' is owned by:\n"
2776 "\t'%s'\nbut the current user is:\n"
2777 "\t'%s'\n", path, str1, str2);
2778 LocalFree(to_free1);
2779 LocalFree(to_free2);
2784 * We can release the security descriptor struct only now because `sid`
2785 * actually points into this struct.
2787 if (descriptor)
2788 LocalFree(descriptor);
2790 return result;
2793 int is_valid_win32_path(const char *path, int allow_literal_nul)
2795 const char *p = path;
2796 int preceding_space_or_period = 0, i = 0, periods = 0;
2798 if (!protect_ntfs)
2799 return 1;
2801 skip_dos_drive_prefix((char **)&path);
2802 goto segment_start;
2804 for (;;) {
2805 char c = *(path++);
2806 switch (c) {
2807 case '\0':
2808 case '/': case '\\':
2809 /* cannot end in ` ` or `.`, except for `.` and `..` */
2810 if (preceding_space_or_period &&
2811 (i != periods || periods > 2))
2812 return 0;
2813 if (!c)
2814 return 1;
2816 i = periods = preceding_space_or_period = 0;
2818 segment_start:
2819 switch (*path) {
2820 case 'a': case 'A': /* AUX */
2821 if (((c = path[++i]) != 'u' && c != 'U') ||
2822 ((c = path[++i]) != 'x' && c != 'X')) {
2823 not_a_reserved_name:
2824 path += i;
2825 continue;
2827 break;
2828 case 'c': case 'C':
2829 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2830 if ((c = path[++i]) != 'o' && c != 'O')
2831 goto not_a_reserved_name;
2832 c = path[++i];
2833 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2834 c = path[++i];
2835 if (c < '1' || c > '9')
2836 goto not_a_reserved_name;
2837 } else if (c == 'n' || c == 'N') { /* CON */
2838 c = path[i + 1];
2839 if ((c == 'i' || c == 'I') &&
2840 ((c = path[i + 2]) == 'n' ||
2841 c == 'N') &&
2842 path[i + 3] == '$')
2843 i += 3; /* CONIN$ */
2844 else if ((c == 'o' || c == 'O') &&
2845 ((c = path[i + 2]) == 'u' ||
2846 c == 'U') &&
2847 ((c = path[i + 3]) == 't' ||
2848 c == 'T') &&
2849 path[i + 4] == '$')
2850 i += 4; /* CONOUT$ */
2851 } else
2852 goto not_a_reserved_name;
2853 break;
2854 case 'l': case 'L': /* LPT<N> */
2855 if (((c = path[++i]) != 'p' && c != 'P') ||
2856 ((c = path[++i]) != 't' && c != 'T') ||
2857 !isdigit(path[++i]))
2858 goto not_a_reserved_name;
2859 break;
2860 case 'n': case 'N': /* NUL */
2861 if (((c = path[++i]) != 'u' && c != 'U') ||
2862 ((c = path[++i]) != 'l' && c != 'L') ||
2863 (allow_literal_nul &&
2864 !path[i + 1] && p == path))
2865 goto not_a_reserved_name;
2866 break;
2867 case 'p': case 'P': /* PRN */
2868 if (((c = path[++i]) != 'r' && c != 'R') ||
2869 ((c = path[++i]) != 'n' && c != 'N'))
2870 goto not_a_reserved_name;
2871 break;
2872 default:
2873 continue;
2877 * So far, this looks like a reserved name. Let's see
2878 * whether it actually is one: trailing spaces, a file
2879 * extension, or an NTFS Alternate Data Stream do not
2880 * matter, the name is still reserved if any of those
2881 * follow immediately after the actual name.
2883 i++;
2884 if (path[i] == ' ') {
2885 preceding_space_or_period = 1;
2886 while (path[++i] == ' ')
2887 ; /* skip all spaces */
2890 c = path[i];
2891 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
2892 goto not_a_reserved_name;
2894 /* contains reserved name */
2895 return 0;
2896 case '.':
2897 periods++;
2898 /* fallthru */
2899 case ' ':
2900 preceding_space_or_period = 1;
2901 i++;
2902 continue;
2903 case ':': /* DOS drive prefix was already skipped */
2904 case '<': case '>': case '"': case '|': case '?': case '*':
2905 /* illegal character */
2906 return 0;
2907 default:
2908 if (c > '\0' && c < '\x20')
2909 /* illegal character */
2910 return 0;
2912 preceding_space_or_period = 0;
2913 i++;
2917 #if !defined(_MSC_VER)
2919 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2920 * mingw startup code, see init.c in mingw runtime).
2922 int _CRT_glob = 0;
2923 #endif
2925 static NORETURN void die_startup(void)
2927 fputs("fatal: not enough memory for initialization", stderr);
2928 exit(128);
2931 static void *malloc_startup(size_t size)
2933 void *result = malloc(size);
2934 if (!result)
2935 die_startup();
2936 return result;
2939 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2941 len = xwcstoutf(buffer, wcs, len) + 1;
2942 return memcpy(malloc_startup(len), buffer, len);
2945 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2946 DWORD desired_access, DWORD flags)
2948 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2949 wchar_t buf[MAX_PATH];
2950 DWORD max = ARRAY_SIZE(buf);
2951 HANDLE handle;
2952 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2954 if (!ret || ret >= max)
2955 return;
2957 /* make sure this does not leak into child processes */
2958 SetEnvironmentVariableW(key, NULL);
2959 if (!wcscmp(buf, L"off")) {
2960 close(fd);
2961 handle = GetStdHandle(std_id);
2962 if (handle != INVALID_HANDLE_VALUE)
2963 CloseHandle(handle);
2964 return;
2966 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2967 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2968 if (handle == INVALID_HANDLE_VALUE) {
2969 close(fd);
2970 handle = GetStdHandle(std_id);
2971 if (handle != INVALID_HANDLE_VALUE)
2972 CloseHandle(handle);
2973 } else {
2974 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2975 SetStdHandle(std_id, handle);
2976 dup2(new_fd, fd);
2977 /* do *not* close the new_fd: that would close stdout */
2979 return;
2981 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2982 flags, NULL);
2983 if (handle != INVALID_HANDLE_VALUE) {
2984 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2985 SetStdHandle(std_id, handle);
2986 dup2(new_fd, fd);
2987 close(new_fd);
2991 static void maybe_redirect_std_handles(void)
2993 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2994 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2995 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2996 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2997 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2998 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
3001 #ifdef _MSC_VER
3002 #ifdef _DEBUG
3003 #include <crtdbg.h>
3004 #endif
3005 #endif
3008 * We implement wmain() and compile with -municode, which would
3009 * normally ignore main(), but we call the latter from the former
3010 * so that we can handle non-ASCII command-line parameters
3011 * appropriately.
3013 * To be more compatible with the core git code, we convert
3014 * argv into UTF8 and pass them directly to main().
3016 int wmain(int argc, const wchar_t **wargv)
3018 int i, maxlen, exit_status;
3019 char *buffer, **save;
3020 const char **argv;
3022 trace2_initialize_clock();
3024 #ifdef _MSC_VER
3025 #ifdef _DEBUG
3026 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3027 #endif
3029 #ifdef USE_MSVC_CRTDBG
3030 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3031 #endif
3032 #endif
3034 maybe_redirect_std_handles();
3036 /* determine size of argv and environ conversion buffer */
3037 maxlen = wcslen(wargv[0]);
3038 for (i = 1; i < argc; i++)
3039 maxlen = max(maxlen, wcslen(wargv[i]));
3041 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3042 maxlen = 3 * maxlen + 1;
3043 buffer = malloc_startup(maxlen);
3046 * Create a UTF-8 version of w_argv. Also create a "save" copy
3047 * to remember all the string pointers because parse_options()
3048 * will remove claimed items from the argv that we pass down.
3050 ALLOC_ARRAY(argv, argc + 1);
3051 ALLOC_ARRAY(save, argc + 1);
3052 for (i = 0; i < argc; i++)
3053 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3054 argv[i] = save[i] = NULL;
3055 free(buffer);
3057 /* fix Windows specific environment settings */
3058 setup_windows_environment();
3060 unset_environment_variables = xstrdup("PERL5LIB");
3062 /* initialize critical section for waitpid pinfo_t list */
3063 InitializeCriticalSection(&pinfo_cs);
3065 /* set up default file mode and file modes for stdin/out/err */
3066 _fmode = _O_BINARY;
3067 _setmode(_fileno(stdin), _O_BINARY);
3068 _setmode(_fileno(stdout), _O_BINARY);
3069 _setmode(_fileno(stderr), _O_BINARY);
3071 /* initialize Unicode console */
3072 winansi_init();
3074 /* invoke the real main() using our utf8 version of argv. */
3075 exit_status = main(argc, argv);
3077 for (i = 0; i < argc; i++)
3078 free(save[i]);
3079 free(save);
3080 free(argv);
3082 return exit_status;
3085 int uname(struct utsname *buf)
3087 unsigned v = (unsigned)GetVersion();
3088 memset(buf, 0, sizeof(*buf));
3089 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3090 xsnprintf(buf->release, sizeof(buf->release),
3091 "%u.%u", v & 0xff, (v >> 8) & 0xff);
3092 /* assuming NT variants only.. */
3093 xsnprintf(buf->version, sizeof(buf->version),
3094 "%u", (v >> 16) & 0x7fff);
3095 return 0;