log-tree: drop unused commit param in remerge_diff()
[git.git] / compat / mingw.c
blob901375d58415a3ae21f03a15e7b78da6f8b08efa
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 "win32/lazyload.h"
11 #include "../config.h"
12 #include "dir.h"
13 #define SECURITY_WIN32
14 #include <sspi.h>
16 #define HCAST(type, handle) ((type)(intptr_t)handle)
18 static const int delay[] = { 0, 1, 10, 20, 40 };
20 void open_in_gdb(void)
22 static struct child_process cp = CHILD_PROCESS_INIT;
23 extern char *_pgmptr;
25 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
26 strvec_pushf(&cp.args, "--pid=%d", getpid());
27 cp.clean_on_exit = 1;
28 if (start_command(&cp) < 0)
29 die_errno("Could not start gdb");
30 sleep(1);
33 int err_win_to_posix(DWORD winerr)
35 int error = ENOSYS;
36 switch(winerr) {
37 case ERROR_ACCESS_DENIED: error = EACCES; break;
38 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
39 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
40 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
41 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
42 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
43 case ERROR_BAD_COMMAND: error = EIO; break;
44 case ERROR_BAD_DEVICE: error = ENODEV; break;
45 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
46 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
47 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
48 case ERROR_BAD_LENGTH: error = EINVAL; break;
49 case ERROR_BAD_PATHNAME: error = ENOENT; break;
50 case ERROR_BAD_PIPE: error = EPIPE; break;
51 case ERROR_BAD_UNIT: error = ENODEV; break;
52 case ERROR_BAD_USERNAME: error = EINVAL; break;
53 case ERROR_BROKEN_PIPE: error = EPIPE; break;
54 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
55 case ERROR_BUSY: error = EBUSY; break;
56 case ERROR_BUSY_DRIVE: error = EBUSY; break;
57 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
58 case ERROR_CANNOT_MAKE: error = EACCES; break;
59 case ERROR_CANTOPEN: error = EIO; break;
60 case ERROR_CANTREAD: error = EIO; break;
61 case ERROR_CANTWRITE: error = EIO; break;
62 case ERROR_CRC: error = EIO; break;
63 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
64 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
65 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
66 case ERROR_DIRECTORY: error = EINVAL; break;
67 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
68 case ERROR_DISK_CHANGE: error = EIO; break;
69 case ERROR_DISK_FULL: error = ENOSPC; break;
70 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
71 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
72 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
73 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
74 case ERROR_FILE_EXISTS: error = EEXIST; break;
75 case ERROR_FILE_INVALID: error = ENODEV; break;
76 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
77 case ERROR_GEN_FAILURE: error = EIO; break;
78 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
79 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
80 case ERROR_INVALID_ACCESS: error = EACCES; break;
81 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
82 case ERROR_INVALID_BLOCK: error = EFAULT; break;
83 case ERROR_INVALID_DATA: error = EINVAL; break;
84 case ERROR_INVALID_DRIVE: error = ENODEV; break;
85 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
86 case ERROR_INVALID_FLAGS: error = EINVAL; break;
87 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
88 case ERROR_INVALID_HANDLE: error = EBADF; break;
89 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
90 case ERROR_INVALID_NAME: error = EINVAL; break;
91 case ERROR_INVALID_OWNER: error = EINVAL; break;
92 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
93 case ERROR_INVALID_PASSWORD: error = EPERM; break;
94 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
95 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
96 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
97 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
98 case ERROR_IO_DEVICE: error = EIO; break;
99 case ERROR_IO_INCOMPLETE: error = EINTR; break;
100 case ERROR_LOCKED: error = EBUSY; break;
101 case ERROR_LOCK_VIOLATION: error = EACCES; break;
102 case ERROR_LOGON_FAILURE: error = EACCES; break;
103 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
104 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
105 case ERROR_MORE_DATA: error = EPIPE; break;
106 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
107 case ERROR_NOACCESS: error = EFAULT; break;
108 case ERROR_NONE_MAPPED: error = EINVAL; break;
109 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
110 case ERROR_NOT_READY: error = EAGAIN; break;
111 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
112 case ERROR_NO_DATA: error = EPIPE; break;
113 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
114 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
115 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
116 case ERROR_OPEN_FAILED: error = EIO; break;
117 case ERROR_OPEN_FILES: error = EBUSY; break;
118 case ERROR_OPERATION_ABORTED: error = EINTR; break;
119 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
120 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
121 case ERROR_PATH_BUSY: error = EBUSY; break;
122 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
123 case ERROR_PIPE_BUSY: error = EBUSY; break;
124 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
125 case ERROR_PIPE_LISTENING: error = EPIPE; break;
126 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
127 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
128 case ERROR_READ_FAULT: error = EIO; break;
129 case ERROR_SEEK: error = EIO; break;
130 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
131 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
132 case ERROR_SHARING_VIOLATION: error = EACCES; break;
133 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
134 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
135 case ERROR_SWAPERROR: error = ENOENT; break;
136 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
137 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
138 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
139 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
140 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
141 case ERROR_WRITE_FAULT: error = EIO; break;
142 case ERROR_WRITE_PROTECT: error = EROFS; break;
144 return error;
147 static inline int is_file_in_use_error(DWORD errcode)
149 switch (errcode) {
150 case ERROR_SHARING_VIOLATION:
151 case ERROR_ACCESS_DENIED:
152 return 1;
155 return 0;
158 static int read_yes_no_answer(void)
160 char answer[1024];
162 if (fgets(answer, sizeof(answer), stdin)) {
163 size_t answer_len = strlen(answer);
164 int got_full_line = 0, c;
166 /* remove the newline */
167 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
168 answer[answer_len-2] = '\0';
169 got_full_line = 1;
170 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
171 answer[answer_len-1] = '\0';
172 got_full_line = 1;
174 /* flush the buffer in case we did not get the full line */
175 if (!got_full_line)
176 while ((c = getchar()) != EOF && c != '\n')
178 } else
179 /* we could not read, return the
180 * default answer which is no */
181 return 0;
183 if (tolower(answer[0]) == 'y' && !answer[1])
184 return 1;
185 if (!strncasecmp(answer, "yes", sizeof(answer)))
186 return 1;
187 if (tolower(answer[0]) == 'n' && !answer[1])
188 return 0;
189 if (!strncasecmp(answer, "no", sizeof(answer)))
190 return 0;
192 /* did not find an answer we understand */
193 return -1;
196 static int ask_yes_no_if_possible(const char *format, ...)
198 char question[4096];
199 const char *retry_hook[] = { NULL, NULL, NULL };
200 va_list args;
202 va_start(args, format);
203 vsnprintf(question, sizeof(question), format, args);
204 va_end(args);
206 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
207 retry_hook[1] = question;
208 return !run_command_v_opt(retry_hook, 0);
211 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
212 return 0;
214 while (1) {
215 int answer;
216 fprintf(stderr, "%s (y/n) ", question);
218 if ((answer = read_yes_no_answer()) >= 0)
219 return answer;
221 fprintf(stderr, "Sorry, I did not understand your answer. "
222 "Please type 'y' or 'n'\n");
226 /* Windows only */
227 enum hide_dotfiles_type {
228 HIDE_DOTFILES_FALSE = 0,
229 HIDE_DOTFILES_TRUE,
230 HIDE_DOTFILES_DOTGITONLY
233 static int core_restrict_inherited_handles = -1;
234 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
235 static char *unset_environment_variables;
237 int mingw_core_config(const char *var, const char *value, void *cb)
239 if (!strcmp(var, "core.hidedotfiles")) {
240 if (value && !strcasecmp(value, "dotgitonly"))
241 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
242 else
243 hide_dotfiles = git_config_bool(var, value);
244 return 0;
247 if (!strcmp(var, "core.unsetenvvars")) {
248 free(unset_environment_variables);
249 unset_environment_variables = xstrdup(value);
250 return 0;
253 if (!strcmp(var, "core.restrictinheritedhandles")) {
254 if (value && !strcasecmp(value, "auto"))
255 core_restrict_inherited_handles = -1;
256 else
257 core_restrict_inherited_handles =
258 git_config_bool(var, value);
259 return 0;
262 return 0;
265 /* Normalizes NT paths as returned by some low-level APIs. */
266 static wchar_t *normalize_ntpath(wchar_t *wbuf)
268 int i;
269 /* fix absolute path prefixes */
270 if (wbuf[0] == '\\') {
271 /* strip NT namespace prefixes */
272 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
273 !wcsncmp(wbuf, L"\\\\?\\", 4))
274 wbuf += 4;
275 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
276 wbuf += 12;
277 /* replace remaining '...UNC\' with '\\' */
278 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
279 wbuf += 2;
280 *wbuf = '\\';
283 /* convert backslashes to slashes */
284 for (i = 0; wbuf[i]; i++)
285 if (wbuf[i] == '\\')
286 wbuf[i] = '/';
287 return wbuf;
290 int mingw_unlink(const char *pathname)
292 int ret, tries = 0;
293 wchar_t wpathname[MAX_PATH];
294 if (xutftowcs_path(wpathname, pathname) < 0)
295 return -1;
297 if (DeleteFileW(wpathname))
298 return 0;
300 /* read-only files cannot be removed */
301 _wchmod(wpathname, 0666);
302 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
303 if (!is_file_in_use_error(GetLastError()))
304 break;
306 * We assume that some other process had the source or
307 * destination file open at the wrong moment and retry.
308 * In order to give the other process a higher chance to
309 * complete its operation, we give up our time slice now.
310 * If we have to retry again, we do sleep a bit.
312 Sleep(delay[tries]);
313 tries++;
315 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
316 ask_yes_no_if_possible("Unlink of file '%s' failed. "
317 "Should I try again?", pathname))
318 ret = _wunlink(wpathname);
319 return ret;
322 static int is_dir_empty(const wchar_t *wpath)
324 WIN32_FIND_DATAW findbuf;
325 HANDLE handle;
326 wchar_t wbuf[MAX_PATH + 2];
327 wcscpy(wbuf, wpath);
328 wcscat(wbuf, L"\\*");
329 handle = FindFirstFileW(wbuf, &findbuf);
330 if (handle == INVALID_HANDLE_VALUE)
331 return GetLastError() == ERROR_NO_MORE_FILES;
333 while (!wcscmp(findbuf.cFileName, L".") ||
334 !wcscmp(findbuf.cFileName, L".."))
335 if (!FindNextFileW(handle, &findbuf)) {
336 DWORD err = GetLastError();
337 FindClose(handle);
338 return err == ERROR_NO_MORE_FILES;
340 FindClose(handle);
341 return 0;
344 int mingw_rmdir(const char *pathname)
346 int ret, tries = 0;
347 wchar_t wpathname[MAX_PATH];
348 struct stat st;
351 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
352 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
353 * symbolic link (if it points to a directory).
355 * This behavior breaks the assumption of e.g. `remove_path()` which
356 * upon successful deletion of a file will attempt to remove its parent
357 * directories recursively until failure (which usually happens when
358 * the directory is not empty).
360 * Therefore, before calling `_wrmdir()`, we first check if the path is
361 * a symbolic link. If it is, we exit and return the same error as
362 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
364 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
365 errno = ENOTDIR;
366 return -1;
369 if (xutftowcs_path(wpathname, pathname) < 0)
370 return -1;
372 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
373 if (!is_file_in_use_error(GetLastError()))
374 errno = err_win_to_posix(GetLastError());
375 if (errno != EACCES)
376 break;
377 if (!is_dir_empty(wpathname)) {
378 errno = ENOTEMPTY;
379 break;
382 * We assume that some other process had the source or
383 * destination file open at the wrong moment and retry.
384 * In order to give the other process a higher chance to
385 * complete its operation, we give up our time slice now.
386 * If we have to retry again, we do sleep a bit.
388 Sleep(delay[tries]);
389 tries++;
391 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
392 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
393 "Should I try again?", pathname))
394 ret = _wrmdir(wpathname);
395 if (!ret)
396 invalidate_lstat_cache();
397 return ret;
400 static inline int needs_hiding(const char *path)
402 const char *basename;
404 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
405 return 0;
407 /* We cannot use basename(), as it would remove trailing slashes */
408 win32_skip_dos_drive_prefix((char **)&path);
409 if (!*path)
410 return 0;
412 for (basename = path; *path; path++)
413 if (is_dir_sep(*path)) {
414 do {
415 path++;
416 } while (is_dir_sep(*path));
417 /* ignore trailing slashes */
418 if (*path)
419 basename = path;
420 else
421 break;
424 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
425 return *basename == '.';
427 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
428 return !strncasecmp(".git", basename, 4) &&
429 (!basename[4] || is_dir_sep(basename[4]));
432 static int set_hidden_flag(const wchar_t *path, int set)
434 DWORD original = GetFileAttributesW(path), modified;
435 if (set)
436 modified = original | FILE_ATTRIBUTE_HIDDEN;
437 else
438 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
439 if (original == modified || SetFileAttributesW(path, modified))
440 return 0;
441 errno = err_win_to_posix(GetLastError());
442 return -1;
445 int mingw_mkdir(const char *path, int mode)
447 int ret;
448 wchar_t wpath[MAX_PATH];
450 if (!is_valid_win32_path(path, 0)) {
451 errno = EINVAL;
452 return -1;
455 if (xutftowcs_path(wpath, path) < 0)
456 return -1;
457 ret = _wmkdir(wpath);
458 if (!ret && needs_hiding(path))
459 return set_hidden_flag(wpath, 1);
460 return ret;
464 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
465 * is documented in [1] as opening a writable file handle in append mode.
466 * (It is believed that) this is atomic since it is maintained by the
467 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
469 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
471 * This trick does not appear to work for named pipes. Instead it creates
472 * a named pipe client handle that cannot be written to. Callers should
473 * just use the regular _wopen() for them. (And since client handle gets
474 * bound to a unique server handle, it isn't really an issue.)
476 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
478 HANDLE handle;
479 int fd;
480 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
482 /* only these flags are supported */
483 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
484 return errno = ENOSYS, -1;
487 * FILE_SHARE_WRITE is required to permit child processes
488 * to append to the file.
490 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
491 FILE_SHARE_WRITE | FILE_SHARE_READ,
492 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
493 if (handle == INVALID_HANDLE_VALUE) {
494 DWORD err = GetLastError();
497 * Some network storage solutions (e.g. Isilon) might return
498 * ERROR_INVALID_PARAMETER instead of expected error
499 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
500 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
502 if (err == ERROR_INVALID_PARAMETER)
503 err = ERROR_PATH_NOT_FOUND;
505 errno = err_win_to_posix(err);
506 return -1;
510 * No O_APPEND here, because the CRT uses it only to reset the
511 * file pointer to EOF before each write(); but that is not
512 * necessary (and may lead to races) for a file created with
513 * FILE_APPEND_DATA.
515 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
516 if (fd < 0)
517 CloseHandle(handle);
518 return fd;
522 * Does the pathname map to the local named pipe filesystem?
523 * That is, does it have a "//./pipe/" prefix?
525 static int is_local_named_pipe_path(const char *filename)
527 return (is_dir_sep(filename[0]) &&
528 is_dir_sep(filename[1]) &&
529 filename[2] == '.' &&
530 is_dir_sep(filename[3]) &&
531 !strncasecmp(filename+4, "pipe", 4) &&
532 is_dir_sep(filename[8]) &&
533 filename[9]);
536 int mingw_open (const char *filename, int oflags, ...)
538 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
539 va_list args;
540 unsigned mode;
541 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
542 wchar_t wfilename[MAX_PATH];
543 open_fn_t open_fn;
545 va_start(args, oflags);
546 mode = va_arg(args, int);
547 va_end(args);
549 if (!is_valid_win32_path(filename, !create)) {
550 errno = create ? EINVAL : ENOENT;
551 return -1;
554 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
555 open_fn = mingw_open_append;
556 else
557 open_fn = _wopen;
559 if (filename && !strcmp(filename, "/dev/null"))
560 wcscpy(wfilename, L"nul");
561 else if (xutftowcs_path(wfilename, filename) < 0)
562 return -1;
564 fd = open_fn(wfilename, oflags, mode);
566 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
567 DWORD attrs = GetFileAttributesW(wfilename);
568 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
569 errno = EISDIR;
571 if ((oflags & O_CREAT) && needs_hiding(filename)) {
573 * Internally, _wopen() uses the CreateFile() API which errors
574 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
575 * specified and an already existing file's attributes do not
576 * match *exactly*. As there is no mode or flag we can set that
577 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
578 * again *without* the O_CREAT flag (that corresponds to the
579 * CREATE_ALWAYS flag of CreateFile()).
581 if (fd < 0 && errno == EACCES)
582 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
583 if (fd >= 0 && set_hidden_flag(wfilename, 1))
584 warning("could not mark '%s' as hidden.", filename);
586 return fd;
589 static BOOL WINAPI ctrl_ignore(DWORD type)
591 return TRUE;
594 #undef fgetc
595 int mingw_fgetc(FILE *stream)
597 int ch;
598 if (!isatty(_fileno(stream)))
599 return fgetc(stream);
601 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
602 while (1) {
603 ch = fgetc(stream);
604 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
605 break;
607 /* Ctrl+C was pressed, simulate SIGINT and retry */
608 mingw_raise(SIGINT);
610 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
611 return ch;
614 #undef fopen
615 FILE *mingw_fopen (const char *filename, const char *otype)
617 int hide = needs_hiding(filename);
618 FILE *file;
619 wchar_t wfilename[MAX_PATH], wotype[4];
620 if (filename && !strcmp(filename, "/dev/null"))
621 wcscpy(wfilename, L"nul");
622 else if (!is_valid_win32_path(filename, 1)) {
623 int create = otype && strchr(otype, 'w');
624 errno = create ? EINVAL : ENOENT;
625 return NULL;
626 } else if (xutftowcs_path(wfilename, filename) < 0)
627 return NULL;
629 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
630 return NULL;
632 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
633 error("could not unhide %s", filename);
634 return NULL;
636 file = _wfopen(wfilename, wotype);
637 if (!file && GetLastError() == ERROR_INVALID_NAME)
638 errno = ENOENT;
639 if (file && hide && set_hidden_flag(wfilename, 1))
640 warning("could not mark '%s' as hidden.", filename);
641 return file;
644 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
646 int hide = needs_hiding(filename);
647 FILE *file;
648 wchar_t wfilename[MAX_PATH], wotype[4];
649 if (filename && !strcmp(filename, "/dev/null"))
650 wcscpy(wfilename, L"nul");
651 else if (!is_valid_win32_path(filename, 1)) {
652 int create = otype && strchr(otype, 'w');
653 errno = create ? EINVAL : ENOENT;
654 return NULL;
655 } else if (xutftowcs_path(wfilename, filename) < 0)
656 return NULL;
658 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
659 return NULL;
661 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
662 error("could not unhide %s", filename);
663 return NULL;
665 file = _wfreopen(wfilename, wotype, stream);
666 if (file && hide && set_hidden_flag(wfilename, 1))
667 warning("could not mark '%s' as hidden.", filename);
668 return file;
671 #undef fflush
672 int mingw_fflush(FILE *stream)
674 int ret = fflush(stream);
677 * write() is used behind the scenes of stdio output functions.
678 * Since git code does not check for errors after each stdio write
679 * operation, it can happen that write() is called by a later
680 * stdio function even if an earlier write() call failed. In the
681 * case of a pipe whose readable end was closed, only the first
682 * call to write() reports EPIPE on Windows. Subsequent write()
683 * calls report EINVAL. It is impossible to notice whether this
684 * fflush invocation triggered such a case, therefore, we have to
685 * catch all EINVAL errors whole-sale.
687 if (ret && errno == EINVAL)
688 errno = EPIPE;
690 return ret;
693 #undef write
694 ssize_t mingw_write(int fd, const void *buf, size_t len)
696 ssize_t result = write(fd, buf, len);
698 if (result < 0 && errno == EINVAL && buf) {
699 /* check if fd is a pipe */
700 HANDLE h = (HANDLE) _get_osfhandle(fd);
701 if (GetFileType(h) == FILE_TYPE_PIPE)
702 errno = EPIPE;
703 else
704 errno = EINVAL;
707 return result;
710 int mingw_access(const char *filename, int mode)
712 wchar_t wfilename[MAX_PATH];
713 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
714 return 0;
715 if (xutftowcs_path(wfilename, filename) < 0)
716 return -1;
717 /* X_OK is not supported by the MSVCRT version */
718 return _waccess(wfilename, mode & ~X_OK);
721 int mingw_chdir(const char *dirname)
723 wchar_t wdirname[MAX_PATH];
724 if (xutftowcs_path(wdirname, dirname) < 0)
725 return -1;
726 return _wchdir(wdirname);
729 int mingw_chmod(const char *filename, int mode)
731 wchar_t wfilename[MAX_PATH];
732 if (xutftowcs_path(wfilename, filename) < 0)
733 return -1;
734 return _wchmod(wfilename, mode);
738 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
739 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
741 static inline long long filetime_to_hnsec(const FILETIME *ft)
743 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
744 /* Windows to Unix Epoch conversion */
745 return winTime - 116444736000000000LL;
748 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
750 long long hnsec = filetime_to_hnsec(ft);
751 ts->tv_sec = (time_t)(hnsec / 10000000);
752 ts->tv_nsec = (hnsec % 10000000) * 100;
756 * Verifies that safe_create_leading_directories() would succeed.
758 static int has_valid_directory_prefix(wchar_t *wfilename)
760 int n = wcslen(wfilename);
762 while (n > 0) {
763 wchar_t c = wfilename[--n];
764 DWORD attributes;
766 if (!is_dir_sep(c))
767 continue;
769 wfilename[n] = L'\0';
770 attributes = GetFileAttributesW(wfilename);
771 wfilename[n] = c;
772 if (attributes &
773 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
774 return 1;
775 if (attributes == INVALID_FILE_ATTRIBUTES)
776 switch (GetLastError()) {
777 case ERROR_PATH_NOT_FOUND:
778 continue;
779 case ERROR_FILE_NOT_FOUND:
780 /* This implies parent directory exists. */
781 return 1;
783 return 0;
785 return 1;
788 /* We keep the do_lstat code in a separate function to avoid recursion.
789 * When a path ends with a slash, the stat will fail with ENOENT. In
790 * this case, we strip the trailing slashes and stat again.
792 * If follow is true then act like stat() and report on the link
793 * target. Otherwise report on the link itself.
795 static int do_lstat(int follow, const char *file_name, struct stat *buf)
797 WIN32_FILE_ATTRIBUTE_DATA fdata;
798 wchar_t wfilename[MAX_PATH];
799 if (xutftowcs_path(wfilename, file_name) < 0)
800 return -1;
802 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
803 buf->st_ino = 0;
804 buf->st_gid = 0;
805 buf->st_uid = 0;
806 buf->st_nlink = 1;
807 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
808 buf->st_size = fdata.nFileSizeLow |
809 (((off_t)fdata.nFileSizeHigh)<<32);
810 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
811 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
812 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
813 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
814 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
815 WIN32_FIND_DATAW findbuf;
816 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
817 if (handle != INVALID_HANDLE_VALUE) {
818 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
819 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
820 if (follow) {
821 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
822 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
823 } else {
824 buf->st_mode = S_IFLNK;
826 buf->st_mode |= S_IREAD;
827 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
828 buf->st_mode |= S_IWRITE;
830 FindClose(handle);
833 return 0;
835 switch (GetLastError()) {
836 case ERROR_ACCESS_DENIED:
837 case ERROR_SHARING_VIOLATION:
838 case ERROR_LOCK_VIOLATION:
839 case ERROR_SHARING_BUFFER_EXCEEDED:
840 errno = EACCES;
841 break;
842 case ERROR_BUFFER_OVERFLOW:
843 errno = ENAMETOOLONG;
844 break;
845 case ERROR_NOT_ENOUGH_MEMORY:
846 errno = ENOMEM;
847 break;
848 case ERROR_PATH_NOT_FOUND:
849 if (!has_valid_directory_prefix(wfilename)) {
850 errno = ENOTDIR;
851 break;
853 /* fallthru */
854 default:
855 errno = ENOENT;
856 break;
858 return -1;
861 /* We provide our own lstat/fstat functions, since the provided
862 * lstat/fstat functions are so slow. These stat functions are
863 * tailored for Git's usage (read: fast), and are not meant to be
864 * complete. Note that Git stat()s are redirected to mingw_lstat()
865 * too, since Windows doesn't really handle symlinks that well.
867 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
869 int namelen;
870 char alt_name[PATH_MAX];
872 if (!do_lstat(follow, file_name, buf))
873 return 0;
875 /* if file_name ended in a '/', Windows returned ENOENT;
876 * try again without trailing slashes
878 if (errno != ENOENT)
879 return -1;
881 namelen = strlen(file_name);
882 if (namelen && file_name[namelen-1] != '/')
883 return -1;
884 while (namelen && file_name[namelen-1] == '/')
885 --namelen;
886 if (!namelen || namelen >= PATH_MAX)
887 return -1;
889 memcpy(alt_name, file_name, namelen);
890 alt_name[namelen] = 0;
891 return do_lstat(follow, alt_name, buf);
894 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
896 BY_HANDLE_FILE_INFORMATION fdata;
898 if (!GetFileInformationByHandle(hnd, &fdata)) {
899 errno = err_win_to_posix(GetLastError());
900 return -1;
903 buf->st_ino = 0;
904 buf->st_gid = 0;
905 buf->st_uid = 0;
906 buf->st_nlink = 1;
907 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
908 buf->st_size = fdata.nFileSizeLow |
909 (((off_t)fdata.nFileSizeHigh)<<32);
910 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
911 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
912 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
913 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
914 return 0;
917 int mingw_lstat(const char *file_name, struct stat *buf)
919 return do_stat_internal(0, file_name, buf);
921 int mingw_stat(const char *file_name, struct stat *buf)
923 return do_stat_internal(1, file_name, buf);
926 int mingw_fstat(int fd, struct stat *buf)
928 HANDLE fh = (HANDLE)_get_osfhandle(fd);
929 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
931 switch (type) {
932 case FILE_TYPE_DISK:
933 return get_file_info_by_handle(fh, buf);
935 case FILE_TYPE_CHAR:
936 case FILE_TYPE_PIPE:
937 /* initialize stat fields */
938 memset(buf, 0, sizeof(*buf));
939 buf->st_nlink = 1;
941 if (type == FILE_TYPE_CHAR) {
942 buf->st_mode = _S_IFCHR;
943 } else {
944 buf->st_mode = _S_IFIFO;
945 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
946 buf->st_size = avail;
948 return 0;
950 default:
951 errno = EBADF;
952 return -1;
956 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
958 long long winTime = t * 10000000LL + 116444736000000000LL;
959 ft->dwLowDateTime = winTime;
960 ft->dwHighDateTime = winTime >> 32;
963 int mingw_utime (const char *file_name, const struct utimbuf *times)
965 FILETIME mft, aft;
966 int rc;
967 DWORD attrs;
968 wchar_t wfilename[MAX_PATH];
969 HANDLE osfilehandle;
971 if (xutftowcs_path(wfilename, file_name) < 0)
972 return -1;
974 /* must have write permission */
975 attrs = GetFileAttributesW(wfilename);
976 if (attrs != INVALID_FILE_ATTRIBUTES &&
977 (attrs & FILE_ATTRIBUTE_READONLY)) {
978 /* ignore errors here; open() will report them */
979 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
982 osfilehandle = CreateFileW(wfilename,
983 FILE_WRITE_ATTRIBUTES,
984 0 /*FileShare.None*/,
985 NULL,
986 OPEN_EXISTING,
987 (attrs != INVALID_FILE_ATTRIBUTES &&
988 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
989 FILE_FLAG_BACKUP_SEMANTICS : 0,
990 NULL);
991 if (osfilehandle == INVALID_HANDLE_VALUE) {
992 errno = err_win_to_posix(GetLastError());
993 rc = -1;
994 goto revert_attrs;
997 if (times) {
998 time_t_to_filetime(times->modtime, &mft);
999 time_t_to_filetime(times->actime, &aft);
1000 } else {
1001 GetSystemTimeAsFileTime(&mft);
1002 aft = mft;
1005 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
1006 errno = EINVAL;
1007 rc = -1;
1008 } else
1009 rc = 0;
1011 if (osfilehandle != INVALID_HANDLE_VALUE)
1012 CloseHandle(osfilehandle);
1014 revert_attrs:
1015 if (attrs != INVALID_FILE_ATTRIBUTES &&
1016 (attrs & FILE_ATTRIBUTE_READONLY)) {
1017 /* ignore errors again */
1018 SetFileAttributesW(wfilename, attrs);
1020 return rc;
1023 #undef strftime
1024 size_t mingw_strftime(char *s, size_t max,
1025 const char *format, const struct tm *tm)
1027 /* a pointer to the original strftime in case we can't find the UCRT version */
1028 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1029 size_t ret;
1030 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1031 const char *, const struct tm *);
1033 if (INIT_PROC_ADDR(strftime))
1034 ret = strftime(s, max, format, tm);
1035 else
1036 ret = fallback(s, max, format, tm);
1038 if (!ret && errno == EINVAL)
1039 die("invalid strftime format: '%s'", format);
1040 return ret;
1043 unsigned int sleep (unsigned int seconds)
1045 Sleep(seconds*1000);
1046 return 0;
1049 char *mingw_mktemp(char *template)
1051 wchar_t wtemplate[MAX_PATH];
1052 if (xutftowcs_path(wtemplate, template) < 0)
1053 return NULL;
1054 if (!_wmktemp(wtemplate))
1055 return NULL;
1056 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1057 return NULL;
1058 return template;
1061 int mkstemp(char *template)
1063 return git_mkstemp_mode(template, 0600);
1066 int gettimeofday(struct timeval *tv, void *tz)
1068 FILETIME ft;
1069 long long hnsec;
1071 GetSystemTimeAsFileTime(&ft);
1072 hnsec = filetime_to_hnsec(&ft);
1073 tv->tv_sec = hnsec / 10000000;
1074 tv->tv_usec = (hnsec % 10000000) / 10;
1075 return 0;
1078 int pipe(int filedes[2])
1080 HANDLE h[2];
1082 /* this creates non-inheritable handles */
1083 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1084 errno = err_win_to_posix(GetLastError());
1085 return -1;
1087 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1088 if (filedes[0] < 0) {
1089 CloseHandle(h[0]);
1090 CloseHandle(h[1]);
1091 return -1;
1093 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1094 if (filedes[1] < 0) {
1095 close(filedes[0]);
1096 CloseHandle(h[1]);
1097 return -1;
1099 return 0;
1102 #ifndef __MINGW64__
1103 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1105 if (gmtime_s(result, timep) == 0)
1106 return result;
1107 return NULL;
1110 struct tm *localtime_r(const time_t *timep, struct tm *result)
1112 if (localtime_s(result, timep) == 0)
1113 return result;
1114 return NULL;
1116 #endif
1118 char *mingw_getcwd(char *pointer, int len)
1120 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1121 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1123 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1124 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1125 return NULL;
1127 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1128 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1129 HANDLE hnd = CreateFileW(cwd, 0,
1130 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1131 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1132 if (hnd == INVALID_HANDLE_VALUE)
1133 return NULL;
1134 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1135 CloseHandle(hnd);
1136 if (!ret || ret >= ARRAY_SIZE(wpointer))
1137 return NULL;
1138 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1139 return NULL;
1140 return pointer;
1142 if (!ret || ret >= ARRAY_SIZE(wpointer))
1143 return NULL;
1144 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1145 errno = ENOENT;
1146 return NULL;
1148 if (xwcstoutf(pointer, wpointer, len) < 0)
1149 return NULL;
1150 convert_slashes(pointer);
1151 return pointer;
1155 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1156 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1158 static const char *quote_arg_msvc(const char *arg)
1160 /* count chars to quote */
1161 int len = 0, n = 0;
1162 int force_quotes = 0;
1163 char *q, *d;
1164 const char *p = arg;
1165 if (!*p) force_quotes = 1;
1166 while (*p) {
1167 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1168 force_quotes = 1;
1169 else if (*p == '"')
1170 n++;
1171 else if (*p == '\\') {
1172 int count = 0;
1173 while (*p == '\\') {
1174 count++;
1175 p++;
1176 len++;
1178 if (*p == '"' || !*p)
1179 n += count*2 + 1;
1180 continue;
1182 len++;
1183 p++;
1185 if (!force_quotes && n == 0)
1186 return arg;
1188 /* insert \ where necessary */
1189 d = q = xmalloc(st_add3(len, n, 3));
1190 *d++ = '"';
1191 while (*arg) {
1192 if (*arg == '"')
1193 *d++ = '\\';
1194 else if (*arg == '\\') {
1195 int count = 0;
1196 while (*arg == '\\') {
1197 count++;
1198 *d++ = *arg++;
1200 if (*arg == '"' || !*arg) {
1201 while (count-- > 0)
1202 *d++ = '\\';
1203 /* don't escape the surrounding end quote */
1204 if (!*arg)
1205 break;
1206 *d++ = '\\';
1209 *d++ = *arg++;
1211 *d++ = '"';
1212 *d++ = '\0';
1213 return q;
1216 #include "quote.h"
1218 static const char *quote_arg_msys2(const char *arg)
1220 struct strbuf buf = STRBUF_INIT;
1221 const char *p2 = arg, *p;
1223 for (p = arg; *p; p++) {
1224 int ws = isspace(*p);
1225 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1226 *p != '?' && *p != '*' && *p != '~')
1227 continue;
1228 if (!buf.len)
1229 strbuf_addch(&buf, '"');
1230 if (p != p2)
1231 strbuf_add(&buf, p2, p - p2);
1232 if (*p == '\\' || *p == '"')
1233 strbuf_addch(&buf, '\\');
1234 p2 = p;
1237 if (p == arg)
1238 strbuf_addch(&buf, '"');
1239 else if (!buf.len)
1240 return arg;
1241 else
1242 strbuf_add(&buf, p2, p - p2);
1244 strbuf_addch(&buf, '"');
1245 return strbuf_detach(&buf, 0);
1248 static const char *parse_interpreter(const char *cmd)
1250 static char buf[100];
1251 char *p, *opt;
1252 int n, fd;
1254 /* don't even try a .exe */
1255 n = strlen(cmd);
1256 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1257 return NULL;
1259 fd = open(cmd, O_RDONLY);
1260 if (fd < 0)
1261 return NULL;
1262 n = read(fd, buf, sizeof(buf)-1);
1263 close(fd);
1264 if (n < 4) /* at least '#!/x' and not error */
1265 return NULL;
1267 if (buf[0] != '#' || buf[1] != '!')
1268 return NULL;
1269 buf[n] = '\0';
1270 p = buf + strcspn(buf, "\r\n");
1271 if (!*p)
1272 return NULL;
1274 *p = '\0';
1275 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1276 return NULL;
1277 /* strip options */
1278 if ((opt = strchr(p+1, ' ')))
1279 *opt = '\0';
1280 return p+1;
1284 * exe_only means that we only want to detect .exe files, but not scripts
1285 * (which do not have an extension)
1287 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1288 int isexe, int exe_only)
1290 char path[MAX_PATH];
1291 wchar_t wpath[MAX_PATH];
1292 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1294 if (xutftowcs_path(wpath, path) < 0)
1295 return NULL;
1297 if (!isexe && _waccess(wpath, F_OK) == 0)
1298 return xstrdup(path);
1299 wpath[wcslen(wpath)-4] = '\0';
1300 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1301 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1302 path[strlen(path)-4] = '\0';
1303 return xstrdup(path);
1306 return NULL;
1310 * Determines the absolute path of cmd using the split path in path.
1311 * If cmd contains a slash or backslash, no lookup is performed.
1313 static char *path_lookup(const char *cmd, int exe_only)
1315 const char *path;
1316 char *prog = NULL;
1317 int len = strlen(cmd);
1318 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1320 if (strpbrk(cmd, "/\\"))
1321 return xstrdup(cmd);
1323 path = mingw_getenv("PATH");
1324 if (!path)
1325 return NULL;
1327 while (!prog) {
1328 const char *sep = strchrnul(path, ';');
1329 int dirlen = sep - path;
1330 if (dirlen)
1331 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1332 if (!*sep)
1333 break;
1334 path = sep + 1;
1337 return prog;
1340 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1342 while (*s && *s != c)
1343 s++;
1344 return s;
1347 /* Compare only keys */
1348 static int wenvcmp(const void *a, const void *b)
1350 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1351 size_t p_len, q_len;
1353 /* Find the keys */
1354 p_len = wcschrnul(p, L'=') - p;
1355 q_len = wcschrnul(q, L'=') - q;
1357 /* If the length differs, include the shorter key's NUL */
1358 if (p_len < q_len)
1359 p_len++;
1360 else if (p_len > q_len)
1361 p_len = q_len + 1;
1363 return _wcsnicmp(p, q, p_len);
1367 * Build an environment block combining the inherited environment
1368 * merged with the given list of settings.
1370 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1371 * Values of the form "KEY" in deltaenv delete inherited values.
1373 * Multiple entries in deltaenv for the same key are explicitly allowed.
1375 * We return a contiguous block of UNICODE strings with a final trailing
1376 * zero word.
1378 static wchar_t *make_environment_block(char **deltaenv)
1380 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1381 size_t wlen, s, delta_size, size;
1383 wchar_t **array = NULL;
1384 size_t alloc = 0, nr = 0, i;
1386 size = 1; /* for extra NUL at the end */
1388 /* If there is no deltaenv to apply, simply return a copy. */
1389 if (!deltaenv || !*deltaenv) {
1390 for (p = wenv; p && *p; ) {
1391 size_t s = wcslen(p) + 1;
1392 size += s;
1393 p += s;
1396 ALLOC_ARRAY(result, size);
1397 COPY_ARRAY(result, wenv, size);
1398 FreeEnvironmentStringsW(wenv);
1399 return result;
1403 * If there is a deltaenv, let's accumulate all keys into `array`,
1404 * sort them using the stable git_stable_qsort() and then copy,
1405 * skipping duplicate keys
1407 for (p = wenv; p && *p; ) {
1408 ALLOC_GROW(array, nr + 1, alloc);
1409 s = wcslen(p) + 1;
1410 array[nr++] = p;
1411 p += s;
1412 size += s;
1415 /* (over-)assess size needed for wchar version of deltaenv */
1416 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1417 delta_size += strlen(deltaenv[i]) * 2 + 1;
1418 ALLOC_ARRAY(wdeltaenv, delta_size);
1420 /* convert the deltaenv, appending to array */
1421 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1422 ALLOC_GROW(array, nr + 1, alloc);
1423 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1424 array[nr++] = p;
1425 p += wlen + 1;
1428 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1429 ALLOC_ARRAY(result, size + delta_size);
1431 for (p = result, i = 0; i < nr; i++) {
1432 /* Skip any duplicate keys; last one wins */
1433 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1434 i++;
1436 /* Skip "to delete" entry */
1437 if (!wcschr(array[i], L'='))
1438 continue;
1440 size = wcslen(array[i]) + 1;
1441 COPY_ARRAY(p, array[i], size);
1442 p += size;
1444 *p = L'\0';
1446 free(array);
1447 free(wdeltaenv);
1448 FreeEnvironmentStringsW(wenv);
1449 return result;
1452 static void do_unset_environment_variables(void)
1454 static int done;
1455 char *p = unset_environment_variables;
1457 if (done || !p)
1458 return;
1459 done = 1;
1461 for (;;) {
1462 char *comma = strchr(p, ',');
1464 if (comma)
1465 *comma = '\0';
1466 unsetenv(p);
1467 if (!comma)
1468 break;
1469 p = comma + 1;
1473 struct pinfo_t {
1474 struct pinfo_t *next;
1475 pid_t pid;
1476 HANDLE proc;
1478 static struct pinfo_t *pinfo = NULL;
1479 CRITICAL_SECTION pinfo_cs;
1481 /* Used to match and chomp off path components */
1482 static inline int match_last_path_component(const char *path, size_t *len,
1483 const char *component)
1485 size_t component_len = strlen(component);
1486 if (*len < component_len + 1 ||
1487 !is_dir_sep(path[*len - component_len - 1]) ||
1488 fspathncmp(path + *len - component_len, component, component_len))
1489 return 0;
1490 *len -= component_len + 1;
1491 /* chomp off repeated dir separators */
1492 while (*len > 0 && is_dir_sep(path[*len - 1]))
1493 (*len)--;
1494 return 1;
1497 static int is_msys2_sh(const char *cmd)
1499 if (!cmd)
1500 return 0;
1502 if (!strcmp(cmd, "sh")) {
1503 static int ret = -1;
1504 char *p;
1506 if (ret >= 0)
1507 return ret;
1509 p = path_lookup(cmd, 0);
1510 if (!p)
1511 ret = 0;
1512 else {
1513 size_t len = strlen(p);
1515 ret = match_last_path_component(p, &len, "sh.exe") &&
1516 match_last_path_component(p, &len, "bin") &&
1517 match_last_path_component(p, &len, "usr");
1518 free(p);
1520 return ret;
1523 if (ends_with(cmd, "\\sh.exe")) {
1524 static char *sh;
1526 if (!sh)
1527 sh = path_lookup("sh", 0);
1529 return !fspathcmp(cmd, sh);
1532 return 0;
1535 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1536 const char *dir,
1537 int prepend_cmd, int fhin, int fhout, int fherr)
1539 static int restrict_handle_inheritance = -1;
1540 STARTUPINFOEXW si;
1541 PROCESS_INFORMATION pi;
1542 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1543 HANDLE stdhandles[3];
1544 DWORD stdhandles_count = 0;
1545 SIZE_T size;
1546 struct strbuf args;
1547 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1548 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1549 BOOL ret;
1550 HANDLE cons;
1551 const char *(*quote_arg)(const char *arg) =
1552 is_msys2_sh(cmd ? cmd : *argv) ?
1553 quote_arg_msys2 : quote_arg_msvc;
1554 const char *strace_env;
1556 /* Make sure to override previous errors, if any */
1557 errno = 0;
1559 if (restrict_handle_inheritance < 0)
1560 restrict_handle_inheritance = core_restrict_inherited_handles;
1562 * The following code to restrict which handles are inherited seems
1563 * to work properly only on Windows 7 and later, so let's disable it
1564 * on Windows Vista and 2008.
1566 if (restrict_handle_inheritance < 0)
1567 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1569 do_unset_environment_variables();
1571 /* Determine whether or not we are associated to a console */
1572 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1573 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1574 FILE_ATTRIBUTE_NORMAL, NULL);
1575 if (cons == INVALID_HANDLE_VALUE) {
1576 /* There is no console associated with this process.
1577 * Since the child is a console process, Windows
1578 * would normally create a console window. But
1579 * since we'll be redirecting std streams, we do
1580 * not need the console.
1581 * It is necessary to use DETACHED_PROCESS
1582 * instead of CREATE_NO_WINDOW to make ssh
1583 * recognize that it has no console.
1585 flags |= DETACHED_PROCESS;
1586 } else {
1587 /* There is already a console. If we specified
1588 * DETACHED_PROCESS here, too, Windows would
1589 * disassociate the child from the console.
1590 * The same is true for CREATE_NO_WINDOW.
1591 * Go figure!
1593 CloseHandle(cons);
1595 memset(&si, 0, sizeof(si));
1596 si.StartupInfo.cb = sizeof(si);
1597 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1598 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1599 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1601 /* The list of handles cannot contain duplicates */
1602 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1603 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1604 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1605 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1606 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1607 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1608 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1609 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1610 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1611 if (stdhandles_count)
1612 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1614 if (*argv && !strcmp(cmd, *argv))
1615 wcmd[0] = L'\0';
1616 else if (xutftowcs_path(wcmd, cmd) < 0)
1617 return -1;
1618 if (dir && xutftowcs_path(wdir, dir) < 0)
1619 return -1;
1621 /* concatenate argv, quoting args as we go */
1622 strbuf_init(&args, 0);
1623 if (prepend_cmd) {
1624 char *quoted = (char *)quote_arg(cmd);
1625 strbuf_addstr(&args, quoted);
1626 if (quoted != cmd)
1627 free(quoted);
1629 for (; *argv; argv++) {
1630 char *quoted = (char *)quote_arg(*argv);
1631 if (*args.buf)
1632 strbuf_addch(&args, ' ');
1633 strbuf_addstr(&args, quoted);
1634 if (quoted != *argv)
1635 free(quoted);
1638 strace_env = getenv("GIT_STRACE_COMMANDS");
1639 if (strace_env) {
1640 char *p = path_lookup("strace.exe", 1);
1641 if (!p)
1642 return error("strace not found!");
1643 if (xutftowcs_path(wcmd, p) < 0) {
1644 free(p);
1645 return -1;
1647 free(p);
1648 if (!strcmp("1", strace_env) ||
1649 !strcasecmp("yes", strace_env) ||
1650 !strcasecmp("true", strace_env))
1651 strbuf_insert(&args, 0, "strace ", 7);
1652 else {
1653 const char *quoted = quote_arg(strace_env);
1654 struct strbuf buf = STRBUF_INIT;
1655 strbuf_addf(&buf, "strace -o %s ", quoted);
1656 if (quoted != strace_env)
1657 free((char *)quoted);
1658 strbuf_insert(&args, 0, buf.buf, buf.len);
1659 strbuf_release(&buf);
1663 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1664 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1665 strbuf_release(&args);
1667 wenvblk = make_environment_block(deltaenv);
1669 memset(&pi, 0, sizeof(pi));
1670 if (restrict_handle_inheritance && stdhandles_count &&
1671 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1672 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1673 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1674 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1675 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1676 UpdateProcThreadAttribute(attr_list, 0,
1677 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1678 stdhandles,
1679 stdhandles_count * sizeof(HANDLE),
1680 NULL, NULL)) {
1681 si.lpAttributeList = attr_list;
1682 flags |= EXTENDED_STARTUPINFO_PRESENT;
1685 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1686 stdhandles_count ? TRUE : FALSE,
1687 flags, wenvblk, dir ? wdir : NULL,
1688 &si.StartupInfo, &pi);
1691 * On Windows 2008 R2, it seems that specifying certain types of handles
1692 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1693 * error. Rather than playing finicky and fragile games, let's just try
1694 * to detect this situation and simply try again without restricting any
1695 * handle inheritance. This is still better than failing to create
1696 * processes.
1698 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1699 DWORD err = GetLastError();
1700 struct strbuf buf = STRBUF_INIT;
1702 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1704 * On Windows 7 and earlier, handles on pipes and character
1705 * devices are inherited automatically, and cannot be
1706 * specified in the thread handle list. Rather than trying
1707 * to catch each and every corner case (and running the
1708 * chance of *still* forgetting a few), let's just fall
1709 * back to creating the process without trying to limit the
1710 * handle inheritance.
1712 !(err == ERROR_INVALID_PARAMETER &&
1713 GetVersion() >> 16 < 9200) &&
1714 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1715 DWORD fl = 0;
1716 int i;
1718 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1720 for (i = 0; i < stdhandles_count; i++) {
1721 HANDLE h = stdhandles[i];
1722 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1723 "handle info (%d) %lx\n", i, h,
1724 GetFileType(h),
1725 GetHandleInformation(h, &fl),
1726 fl);
1728 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1729 "at\nhttps://github.com/git-for-windows/"
1730 "git/issues/new\n\n"
1731 "To suppress this warning, please set "
1732 "the environment variable\n\n"
1733 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1734 "\n");
1736 restrict_handle_inheritance = 0;
1737 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1738 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1739 TRUE, flags, wenvblk, dir ? wdir : NULL,
1740 &si.StartupInfo, &pi);
1741 if (!ret)
1742 errno = err_win_to_posix(GetLastError());
1743 if (ret && buf.len) {
1744 warning("failed to restrict file handles (%ld)\n\n%s",
1745 err, buf.buf);
1747 strbuf_release(&buf);
1748 } else if (!ret)
1749 errno = err_win_to_posix(GetLastError());
1751 if (si.lpAttributeList)
1752 DeleteProcThreadAttributeList(si.lpAttributeList);
1753 if (attr_list)
1754 HeapFree(GetProcessHeap(), 0, attr_list);
1756 free(wenvblk);
1757 free(wargs);
1759 if (!ret)
1760 return -1;
1762 CloseHandle(pi.hThread);
1765 * The process ID is the human-readable identifier of the process
1766 * that we want to present in log and error messages. The handle
1767 * is not useful for this purpose. But we cannot close it, either,
1768 * because it is not possible to turn a process ID into a process
1769 * handle after the process terminated.
1770 * Keep the handle in a list for waitpid.
1772 EnterCriticalSection(&pinfo_cs);
1774 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1775 info->pid = pi.dwProcessId;
1776 info->proc = pi.hProcess;
1777 info->next = pinfo;
1778 pinfo = info;
1780 LeaveCriticalSection(&pinfo_cs);
1782 return (pid_t)pi.dwProcessId;
1785 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1787 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1790 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1791 const char *dir,
1792 int fhin, int fhout, int fherr)
1794 pid_t pid;
1795 char *prog = path_lookup(cmd, 0);
1797 if (!prog) {
1798 errno = ENOENT;
1799 pid = -1;
1801 else {
1802 const char *interpr = parse_interpreter(prog);
1804 if (interpr) {
1805 const char *argv0 = argv[0];
1806 char *iprog = path_lookup(interpr, 1);
1807 argv[0] = prog;
1808 if (!iprog) {
1809 errno = ENOENT;
1810 pid = -1;
1812 else {
1813 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1814 fhin, fhout, fherr);
1815 free(iprog);
1817 argv[0] = argv0;
1819 else
1820 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1821 fhin, fhout, fherr);
1822 free(prog);
1824 return pid;
1827 static int try_shell_exec(const char *cmd, char *const *argv)
1829 const char *interpr = parse_interpreter(cmd);
1830 char *prog;
1831 int pid = 0;
1833 if (!interpr)
1834 return 0;
1835 prog = path_lookup(interpr, 1);
1836 if (prog) {
1837 int exec_id;
1838 int argc = 0;
1839 #ifndef _MSC_VER
1840 const
1841 #endif
1842 char **argv2;
1843 while (argv[argc]) argc++;
1844 ALLOC_ARRAY(argv2, argc + 1);
1845 argv2[0] = (char *)cmd; /* full path to the script file */
1846 COPY_ARRAY(&argv2[1], &argv[1], argc);
1847 exec_id = trace2_exec(prog, argv2);
1848 pid = mingw_spawnv(prog, argv2, 1);
1849 if (pid >= 0) {
1850 int status;
1851 if (waitpid(pid, &status, 0) < 0)
1852 status = 255;
1853 trace2_exec_result(exec_id, status);
1854 exit(status);
1856 trace2_exec_result(exec_id, -1);
1857 pid = 1; /* indicate that we tried but failed */
1858 free(prog);
1859 free(argv2);
1861 return pid;
1864 int mingw_execv(const char *cmd, char *const *argv)
1866 /* check if git_command is a shell script */
1867 if (!try_shell_exec(cmd, argv)) {
1868 int pid, status;
1869 int exec_id;
1871 exec_id = trace2_exec(cmd, (const char **)argv);
1872 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1873 if (pid < 0) {
1874 trace2_exec_result(exec_id, -1);
1875 return -1;
1877 if (waitpid(pid, &status, 0) < 0)
1878 status = 255;
1879 trace2_exec_result(exec_id, status);
1880 exit(status);
1882 return -1;
1885 int mingw_execvp(const char *cmd, char *const *argv)
1887 char *prog = path_lookup(cmd, 0);
1889 if (prog) {
1890 mingw_execv(prog, argv);
1891 free(prog);
1892 } else
1893 errno = ENOENT;
1895 return -1;
1898 int mingw_kill(pid_t pid, int sig)
1900 if (pid > 0 && sig == SIGTERM) {
1901 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1903 if (TerminateProcess(h, -1)) {
1904 CloseHandle(h);
1905 return 0;
1908 errno = err_win_to_posix(GetLastError());
1909 CloseHandle(h);
1910 return -1;
1911 } else if (pid > 0 && sig == 0) {
1912 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1913 if (h) {
1914 CloseHandle(h);
1915 return 0;
1919 errno = EINVAL;
1920 return -1;
1924 * UTF-8 versions of getenv(), putenv() and unsetenv().
1925 * Internally, they use the CRT's stock UNICODE routines
1926 * to avoid data loss.
1928 char *mingw_getenv(const char *name)
1930 #define GETENV_MAX_RETAIN 64
1931 static char *values[GETENV_MAX_RETAIN];
1932 static int value_counter;
1933 int len_key, len_value;
1934 wchar_t *w_key;
1935 char *value;
1936 wchar_t w_value[32768];
1938 if (!name || !*name)
1939 return NULL;
1941 len_key = strlen(name) + 1;
1942 /* We cannot use xcalloc() here because that uses getenv() itself */
1943 w_key = calloc(len_key, sizeof(wchar_t));
1944 if (!w_key)
1945 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1946 xutftowcs(w_key, name, len_key);
1947 /* GetEnvironmentVariableW() only sets the last error upon failure */
1948 SetLastError(ERROR_SUCCESS);
1949 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1950 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1951 free(w_key);
1952 return NULL;
1954 free(w_key);
1956 len_value = len_value * 3 + 1;
1957 /* We cannot use xcalloc() here because that uses getenv() itself */
1958 value = calloc(len_value, sizeof(char));
1959 if (!value)
1960 die("Out of memory, (tried to allocate %u bytes)", len_value);
1961 xwcstoutf(value, w_value, len_value);
1964 * We return `value` which is an allocated value and the caller is NOT
1965 * expecting to have to free it, so we keep a round-robin array,
1966 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1968 free(values[value_counter]);
1969 values[value_counter++] = value;
1970 if (value_counter >= ARRAY_SIZE(values))
1971 value_counter = 0;
1973 return value;
1976 int mingw_putenv(const char *namevalue)
1978 int size;
1979 wchar_t *wide, *equal;
1980 BOOL result;
1982 if (!namevalue || !*namevalue)
1983 return 0;
1985 size = strlen(namevalue) * 2 + 1;
1986 wide = calloc(size, sizeof(wchar_t));
1987 if (!wide)
1988 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1989 xutftowcs(wide, namevalue, size);
1990 equal = wcschr(wide, L'=');
1991 if (!equal)
1992 result = SetEnvironmentVariableW(wide, NULL);
1993 else {
1994 *equal = L'\0';
1995 result = SetEnvironmentVariableW(wide, equal + 1);
1997 free(wide);
1999 if (!result)
2000 errno = err_win_to_posix(GetLastError());
2002 return result ? 0 : -1;
2005 static void ensure_socket_initialization(void)
2007 WSADATA wsa;
2008 static int initialized = 0;
2010 if (initialized)
2011 return;
2013 if (WSAStartup(MAKEWORD(2,2), &wsa))
2014 die("unable to initialize winsock subsystem, error %d",
2015 WSAGetLastError());
2017 atexit((void(*)(void)) WSACleanup);
2018 initialized = 1;
2021 #undef gethostname
2022 int mingw_gethostname(char *name, int namelen)
2024 ensure_socket_initialization();
2025 return gethostname(name, namelen);
2028 #undef gethostbyname
2029 struct hostent *mingw_gethostbyname(const char *host)
2031 ensure_socket_initialization();
2032 return gethostbyname(host);
2035 #undef getaddrinfo
2036 int mingw_getaddrinfo(const char *node, const char *service,
2037 const struct addrinfo *hints, struct addrinfo **res)
2039 ensure_socket_initialization();
2040 return getaddrinfo(node, service, hints, res);
2043 int mingw_socket(int domain, int type, int protocol)
2045 int sockfd;
2046 SOCKET s;
2048 ensure_socket_initialization();
2049 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2050 if (s == INVALID_SOCKET) {
2052 * WSAGetLastError() values are regular BSD error codes
2053 * biased by WSABASEERR.
2054 * However, strerror() does not know about networking
2055 * specific errors, which are values beginning at 38 or so.
2056 * Therefore, we choose to leave the biased error code
2057 * in errno so that _if_ someone looks up the code somewhere,
2058 * then it is at least the number that are usually listed.
2060 errno = WSAGetLastError();
2061 return -1;
2063 /* convert into a file descriptor */
2064 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2065 closesocket(s);
2066 return error("unable to make a socket file descriptor: %s",
2067 strerror(errno));
2069 return sockfd;
2072 #undef connect
2073 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2075 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2076 return connect(s, sa, sz);
2079 #undef bind
2080 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2082 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2083 return bind(s, sa, sz);
2086 #undef setsockopt
2087 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2089 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2090 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2093 #undef shutdown
2094 int mingw_shutdown(int sockfd, int how)
2096 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2097 return shutdown(s, how);
2100 #undef listen
2101 int mingw_listen(int sockfd, int backlog)
2103 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2104 return listen(s, backlog);
2107 #undef accept
2108 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2110 int sockfd2;
2112 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2113 SOCKET s2 = accept(s1, sa, sz);
2115 /* convert into a file descriptor */
2116 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2117 int err = errno;
2118 closesocket(s2);
2119 return error("unable to make a socket file descriptor: %s",
2120 strerror(err));
2122 return sockfd2;
2125 #undef rename
2126 int mingw_rename(const char *pold, const char *pnew)
2128 DWORD attrs, gle;
2129 int tries = 0;
2130 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2131 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2132 return -1;
2135 * Try native rename() first to get errno right.
2136 * It is based on MoveFile(), which cannot overwrite existing files.
2138 if (!_wrename(wpold, wpnew))
2139 return 0;
2140 if (errno != EEXIST)
2141 return -1;
2142 repeat:
2143 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2144 return 0;
2145 /* TODO: translate more errors */
2146 gle = GetLastError();
2147 if (gle == ERROR_ACCESS_DENIED &&
2148 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2149 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2150 DWORD attrsold = GetFileAttributesW(wpold);
2151 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2152 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2153 errno = EISDIR;
2154 else if (!_wrmdir(wpnew))
2155 goto repeat;
2156 return -1;
2158 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2159 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2160 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2161 return 0;
2162 gle = GetLastError();
2163 /* revert file attributes on failure */
2164 SetFileAttributesW(wpnew, attrs);
2167 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2169 * We assume that some other process had the source or
2170 * destination file open at the wrong moment and retry.
2171 * In order to give the other process a higher chance to
2172 * complete its operation, we give up our time slice now.
2173 * If we have to retry again, we do sleep a bit.
2175 Sleep(delay[tries]);
2176 tries++;
2177 goto repeat;
2179 if (gle == ERROR_ACCESS_DENIED &&
2180 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2181 "Should I try again?", pold, pnew))
2182 goto repeat;
2184 errno = EACCES;
2185 return -1;
2189 * Note that this doesn't return the actual pagesize, but
2190 * the allocation granularity. If future Windows specific git code
2191 * needs the real getpagesize function, we need to find another solution.
2193 int mingw_getpagesize(void)
2195 SYSTEM_INFO si;
2196 GetSystemInfo(&si);
2197 return si.dwAllocationGranularity;
2200 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2201 enum EXTENDED_NAME_FORMAT {
2202 NameDisplay = 3,
2203 NameUserPrincipal = 8
2206 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2208 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2209 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2210 static wchar_t wbuffer[1024];
2211 DWORD len;
2213 if (!INIT_PROC_ADDR(GetUserNameExW))
2214 return NULL;
2216 len = ARRAY_SIZE(wbuffer);
2217 if (GetUserNameExW(type, wbuffer, &len)) {
2218 char *converted = xmalloc((len *= 3));
2219 if (xwcstoutf(converted, wbuffer, len) >= 0)
2220 return converted;
2221 free(converted);
2224 return NULL;
2227 char *mingw_query_user_email(void)
2229 return get_extended_user_info(NameUserPrincipal);
2232 struct passwd *getpwuid(int uid)
2234 static unsigned initialized;
2235 static char user_name[100];
2236 static struct passwd *p;
2237 wchar_t buf[100];
2238 DWORD len;
2240 if (initialized)
2241 return p;
2243 len = ARRAY_SIZE(buf);
2244 if (!GetUserNameW(buf, &len)) {
2245 initialized = 1;
2246 return NULL;
2249 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2250 initialized = 1;
2251 return NULL;
2254 p = xmalloc(sizeof(*p));
2255 p->pw_name = user_name;
2256 p->pw_gecos = get_extended_user_info(NameDisplay);
2257 if (!p->pw_gecos)
2258 p->pw_gecos = "unknown";
2259 p->pw_dir = NULL;
2261 initialized = 1;
2262 return p;
2265 static HANDLE timer_event;
2266 static HANDLE timer_thread;
2267 static int timer_interval;
2268 static int one_shot;
2269 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2271 /* The timer works like this:
2272 * The thread, ticktack(), is a trivial routine that most of the time
2273 * only waits to receive the signal to terminate. The main thread tells
2274 * the thread to terminate by setting the timer_event to the signalled
2275 * state.
2276 * But ticktack() interrupts the wait state after the timer's interval
2277 * length to call the signal handler.
2280 static unsigned __stdcall ticktack(void *dummy)
2282 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2283 mingw_raise(SIGALRM);
2284 if (one_shot)
2285 break;
2287 return 0;
2290 static int start_timer_thread(void)
2292 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2293 if (timer_event) {
2294 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2295 if (!timer_thread )
2296 return errno = ENOMEM,
2297 error("cannot start timer thread");
2298 } else
2299 return errno = ENOMEM,
2300 error("cannot allocate resources for timer");
2301 return 0;
2304 static void stop_timer_thread(void)
2306 if (timer_event)
2307 SetEvent(timer_event); /* tell thread to terminate */
2308 if (timer_thread) {
2309 int rc = WaitForSingleObject(timer_thread, 10000);
2310 if (rc == WAIT_TIMEOUT)
2311 error("timer thread did not terminate timely");
2312 else if (rc != WAIT_OBJECT_0)
2313 error("waiting for timer thread failed: %lu",
2314 GetLastError());
2315 CloseHandle(timer_thread);
2317 if (timer_event)
2318 CloseHandle(timer_event);
2319 timer_event = NULL;
2320 timer_thread = NULL;
2323 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2325 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2328 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2330 static const struct timeval zero;
2331 static int atexit_done;
2333 if (out)
2334 return errno = EINVAL,
2335 error("setitimer param 3 != NULL not implemented");
2336 if (!is_timeval_eq(&in->it_interval, &zero) &&
2337 !is_timeval_eq(&in->it_interval, &in->it_value))
2338 return errno = EINVAL,
2339 error("setitimer: it_interval must be zero or eq it_value");
2341 if (timer_thread)
2342 stop_timer_thread();
2344 if (is_timeval_eq(&in->it_value, &zero) &&
2345 is_timeval_eq(&in->it_interval, &zero))
2346 return 0;
2348 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2349 one_shot = is_timeval_eq(&in->it_interval, &zero);
2350 if (!atexit_done) {
2351 atexit(stop_timer_thread);
2352 atexit_done = 1;
2354 return start_timer_thread();
2357 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2359 if (sig != SIGALRM)
2360 return errno = EINVAL,
2361 error("sigaction only implemented for SIGALRM");
2362 if (out)
2363 return errno = EINVAL,
2364 error("sigaction: param 3 != NULL not implemented");
2366 timer_fn = in->sa_handler;
2367 return 0;
2370 #undef signal
2371 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2373 sig_handler_t old;
2375 switch (sig) {
2376 case SIGALRM:
2377 old = timer_fn;
2378 timer_fn = handler;
2379 break;
2381 case SIGINT:
2382 old = sigint_fn;
2383 sigint_fn = handler;
2384 break;
2386 default:
2387 return signal(sig, handler);
2390 return old;
2393 #undef raise
2394 int mingw_raise(int sig)
2396 switch (sig) {
2397 case SIGALRM:
2398 if (timer_fn == SIG_DFL) {
2399 if (isatty(STDERR_FILENO))
2400 fputs("Alarm clock\n", stderr);
2401 exit(128 + SIGALRM);
2402 } else if (timer_fn != SIG_IGN)
2403 timer_fn(SIGALRM);
2404 return 0;
2406 case SIGINT:
2407 if (sigint_fn == SIG_DFL)
2408 exit(128 + SIGINT);
2409 else if (sigint_fn != SIG_IGN)
2410 sigint_fn(SIGINT);
2411 return 0;
2413 #if defined(_MSC_VER)
2414 case SIGILL:
2415 case SIGFPE:
2416 case SIGSEGV:
2417 case SIGTERM:
2418 case SIGBREAK:
2419 case SIGABRT:
2420 case SIGABRT_COMPAT:
2422 * The <signal.h> header in the MS C Runtime defines 8 signals
2423 * as being supported on the platform. Anything else causes an
2424 * "Invalid signal or error" (which in DEBUG builds causes the
2425 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2426 * already know will fail.
2428 return raise(sig);
2429 default:
2430 errno = EINVAL;
2431 return -1;
2433 #else
2435 default:
2436 return raise(sig);
2438 #endif
2443 int link(const char *oldpath, const char *newpath)
2445 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2446 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2447 xutftowcs_path(wnewpath, newpath) < 0)
2448 return -1;
2450 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2451 errno = err_win_to_posix(GetLastError());
2452 return -1;
2454 return 0;
2457 pid_t waitpid(pid_t pid, int *status, int options)
2459 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2460 FALSE, pid);
2461 if (!h) {
2462 errno = ECHILD;
2463 return -1;
2466 if (pid > 0 && options & WNOHANG) {
2467 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2468 CloseHandle(h);
2469 return 0;
2471 options &= ~WNOHANG;
2474 if (options == 0) {
2475 struct pinfo_t **ppinfo;
2476 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2477 CloseHandle(h);
2478 return 0;
2481 if (status)
2482 GetExitCodeProcess(h, (LPDWORD)status);
2484 EnterCriticalSection(&pinfo_cs);
2486 ppinfo = &pinfo;
2487 while (*ppinfo) {
2488 struct pinfo_t *info = *ppinfo;
2489 if (info->pid == pid) {
2490 CloseHandle(info->proc);
2491 *ppinfo = info->next;
2492 free(info);
2493 break;
2495 ppinfo = &info->next;
2498 LeaveCriticalSection(&pinfo_cs);
2500 CloseHandle(h);
2501 return pid;
2503 CloseHandle(h);
2505 errno = EINVAL;
2506 return -1;
2509 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2511 int upos = 0, wpos = 0;
2512 const unsigned char *utf = (const unsigned char*) utfs;
2513 if (!utf || !wcs || wcslen < 1) {
2514 errno = EINVAL;
2515 return -1;
2517 /* reserve space for \0 */
2518 wcslen--;
2519 if (utflen < 0)
2520 utflen = INT_MAX;
2522 while (upos < utflen) {
2523 int c = utf[upos++] & 0xff;
2524 if (utflen == INT_MAX && c == 0)
2525 break;
2527 if (wpos >= wcslen) {
2528 wcs[wpos] = 0;
2529 errno = ERANGE;
2530 return -1;
2533 if (c < 0x80) {
2534 /* ASCII */
2535 wcs[wpos++] = c;
2536 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2537 (utf[upos] & 0xc0) == 0x80) {
2538 /* 2-byte utf-8 */
2539 c = ((c & 0x1f) << 6);
2540 c |= (utf[upos++] & 0x3f);
2541 wcs[wpos++] = c;
2542 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2543 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2544 (utf[upos] & 0xc0) == 0x80 &&
2545 (utf[upos + 1] & 0xc0) == 0x80) {
2546 /* 3-byte utf-8 */
2547 c = ((c & 0x0f) << 12);
2548 c |= ((utf[upos++] & 0x3f) << 6);
2549 c |= (utf[upos++] & 0x3f);
2550 wcs[wpos++] = c;
2551 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2552 wpos + 1 < wcslen &&
2553 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2554 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2555 (utf[upos] & 0xc0) == 0x80 &&
2556 (utf[upos + 1] & 0xc0) == 0x80 &&
2557 (utf[upos + 2] & 0xc0) == 0x80) {
2558 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2559 c = ((c & 0x07) << 18);
2560 c |= ((utf[upos++] & 0x3f) << 12);
2561 c |= ((utf[upos++] & 0x3f) << 6);
2562 c |= (utf[upos++] & 0x3f);
2563 c -= 0x10000;
2564 wcs[wpos++] = 0xd800 | (c >> 10);
2565 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2566 } else if (c >= 0xa0) {
2567 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2568 wcs[wpos++] = c;
2569 } else {
2570 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2571 static const char *hex = "0123456789abcdef";
2572 wcs[wpos++] = hex[c >> 4];
2573 if (wpos < wcslen)
2574 wcs[wpos++] = hex[c & 0x0f];
2577 wcs[wpos] = 0;
2578 return wpos;
2581 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2583 if (!wcs || !utf || utflen < 1) {
2584 errno = EINVAL;
2585 return -1;
2587 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2588 if (utflen)
2589 return utflen - 1;
2590 errno = ERANGE;
2591 return -1;
2594 static void setup_windows_environment(void)
2596 char *tmp = getenv("TMPDIR");
2598 /* on Windows it is TMP and TEMP */
2599 if (!tmp) {
2600 if (!(tmp = getenv("TMP")))
2601 tmp = getenv("TEMP");
2602 if (tmp) {
2603 setenv("TMPDIR", tmp, 1);
2604 tmp = getenv("TMPDIR");
2608 if (tmp) {
2610 * Convert all dir separators to forward slashes,
2611 * to help shell commands called from the Git
2612 * executable (by not mistaking the dir separators
2613 * for escape characters).
2615 convert_slashes(tmp);
2618 /* simulate TERM to enable auto-color (see color.c) */
2619 if (!getenv("TERM"))
2620 setenv("TERM", "cygwin", 1);
2622 /* calculate HOME if not set */
2623 if (!getenv("HOME")) {
2625 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2626 * location, thus also check if the path exists (i.e. is not
2627 * disconnected)
2629 if ((tmp = getenv("HOMEDRIVE"))) {
2630 struct strbuf buf = STRBUF_INIT;
2631 strbuf_addstr(&buf, tmp);
2632 if ((tmp = getenv("HOMEPATH"))) {
2633 strbuf_addstr(&buf, tmp);
2634 if (is_directory(buf.buf))
2635 setenv("HOME", buf.buf, 1);
2636 else
2637 tmp = NULL; /* use $USERPROFILE */
2639 strbuf_release(&buf);
2641 /* use $USERPROFILE if the home share is not available */
2642 if (!tmp && (tmp = getenv("USERPROFILE")))
2643 setenv("HOME", tmp, 1);
2647 static PSID get_current_user_sid(void)
2649 HANDLE token;
2650 DWORD len = 0;
2651 PSID result = NULL;
2653 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2654 return NULL;
2656 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2657 TOKEN_USER *info = xmalloc((size_t)len);
2658 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2659 len = GetLengthSid(info->User.Sid);
2660 result = xmalloc(len);
2661 if (!CopySid(len, result, info->User.Sid)) {
2662 error(_("failed to copy SID (%ld)"),
2663 GetLastError());
2664 FREE_AND_NULL(result);
2667 FREE_AND_NULL(info);
2669 CloseHandle(token);
2671 return result;
2674 static int acls_supported(const char *path)
2676 size_t offset = offset_1st_component(path);
2677 WCHAR wroot[MAX_PATH];
2678 DWORD file_system_flags;
2680 if (offset &&
2681 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2682 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2683 &file_system_flags, NULL, 0))
2684 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2686 return 0;
2689 int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
2691 WCHAR wpath[MAX_PATH];
2692 PSID sid = NULL;
2693 PSECURITY_DESCRIPTOR descriptor = NULL;
2694 DWORD err;
2696 static wchar_t home[MAX_PATH];
2698 int result = 0;
2700 if (xutftowcs_path(wpath, path) < 0)
2701 return 0;
2704 * On Windows, the home directory is owned by the administrator, but for
2705 * all practical purposes, it belongs to the user. Do pretend that it is
2706 * owned by the user.
2708 if (!*home) {
2709 DWORD size = ARRAY_SIZE(home);
2710 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2711 if (!len || len > size)
2712 wcscpy(home, L"::N/A::");
2714 if (!wcsicmp(wpath, home))
2715 return 1;
2717 /* Get the owner SID */
2718 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2719 OWNER_SECURITY_INFORMATION |
2720 DACL_SECURITY_INFORMATION,
2721 &sid, NULL, NULL, NULL, &descriptor);
2723 if (err != ERROR_SUCCESS)
2724 error(_("failed to get owner for '%s' (%ld)"), path, err);
2725 else if (sid && IsValidSid(sid)) {
2726 /* Now, verify that the SID matches the current user's */
2727 static PSID current_user_sid;
2728 BOOL is_member;
2730 if (!current_user_sid)
2731 current_user_sid = get_current_user_sid();
2733 if (current_user_sid &&
2734 IsValidSid(current_user_sid) &&
2735 EqualSid(sid, current_user_sid))
2736 result = 1;
2737 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
2738 CheckTokenMembership(NULL, sid, &is_member) &&
2739 is_member)
2741 * If owned by the Administrators group, and the
2742 * current user is an administrator, we consider that
2743 * okay, too.
2745 result = 1;
2746 else if (report &&
2747 IsWellKnownSid(sid, WinWorldSid) &&
2748 !acls_supported(path)) {
2750 * On FAT32 volumes, ownership is not actually recorded.
2752 strbuf_addf(report, "'%s' is on a file system that does"
2753 "not record ownership\n", path);
2754 } else if (report) {
2755 LPSTR str1, str2, to_free1 = NULL, to_free2 = NULL;
2757 if (ConvertSidToStringSidA(sid, &str1))
2758 to_free1 = str1;
2759 else
2760 str1 = "(inconvertible)";
2762 if (!current_user_sid)
2763 str2 = "(none)";
2764 else if (!IsValidSid(current_user_sid))
2765 str2 = "(invalid)";
2766 else if (ConvertSidToStringSidA(current_user_sid, &str2))
2767 to_free2 = str2;
2768 else
2769 str2 = "(inconvertible)";
2770 strbuf_addf(report,
2771 "'%s' is owned by:\n"
2772 "\t'%s'\nbut the current user is:\n"
2773 "\t'%s'\n", path, str1, str2);
2774 LocalFree(to_free1);
2775 LocalFree(to_free2);
2780 * We can release the security descriptor struct only now because `sid`
2781 * actually points into this struct.
2783 if (descriptor)
2784 LocalFree(descriptor);
2786 return result;
2789 int is_valid_win32_path(const char *path, int allow_literal_nul)
2791 const char *p = path;
2792 int preceding_space_or_period = 0, i = 0, periods = 0;
2794 if (!protect_ntfs)
2795 return 1;
2797 skip_dos_drive_prefix((char **)&path);
2798 goto segment_start;
2800 for (;;) {
2801 char c = *(path++);
2802 switch (c) {
2803 case '\0':
2804 case '/': case '\\':
2805 /* cannot end in ` ` or `.`, except for `.` and `..` */
2806 if (preceding_space_or_period &&
2807 (i != periods || periods > 2))
2808 return 0;
2809 if (!c)
2810 return 1;
2812 i = periods = preceding_space_or_period = 0;
2814 segment_start:
2815 switch (*path) {
2816 case 'a': case 'A': /* AUX */
2817 if (((c = path[++i]) != 'u' && c != 'U') ||
2818 ((c = path[++i]) != 'x' && c != 'X')) {
2819 not_a_reserved_name:
2820 path += i;
2821 continue;
2823 break;
2824 case 'c': case 'C':
2825 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2826 if ((c = path[++i]) != 'o' && c != 'O')
2827 goto not_a_reserved_name;
2828 c = path[++i];
2829 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2830 c = path[++i];
2831 if (c < '1' || c > '9')
2832 goto not_a_reserved_name;
2833 } else if (c == 'n' || c == 'N') { /* CON */
2834 c = path[i + 1];
2835 if ((c == 'i' || c == 'I') &&
2836 ((c = path[i + 2]) == 'n' ||
2837 c == 'N') &&
2838 path[i + 3] == '$')
2839 i += 3; /* CONIN$ */
2840 else if ((c == 'o' || c == 'O') &&
2841 ((c = path[i + 2]) == 'u' ||
2842 c == 'U') &&
2843 ((c = path[i + 3]) == 't' ||
2844 c == 'T') &&
2845 path[i + 4] == '$')
2846 i += 4; /* CONOUT$ */
2847 } else
2848 goto not_a_reserved_name;
2849 break;
2850 case 'l': case 'L': /* LPT<N> */
2851 if (((c = path[++i]) != 'p' && c != 'P') ||
2852 ((c = path[++i]) != 't' && c != 'T') ||
2853 !isdigit(path[++i]))
2854 goto not_a_reserved_name;
2855 break;
2856 case 'n': case 'N': /* NUL */
2857 if (((c = path[++i]) != 'u' && c != 'U') ||
2858 ((c = path[++i]) != 'l' && c != 'L') ||
2859 (allow_literal_nul &&
2860 !path[i + 1] && p == path))
2861 goto not_a_reserved_name;
2862 break;
2863 case 'p': case 'P': /* PRN */
2864 if (((c = path[++i]) != 'r' && c != 'R') ||
2865 ((c = path[++i]) != 'n' && c != 'N'))
2866 goto not_a_reserved_name;
2867 break;
2868 default:
2869 continue;
2873 * So far, this looks like a reserved name. Let's see
2874 * whether it actually is one: trailing spaces, a file
2875 * extension, or an NTFS Alternate Data Stream do not
2876 * matter, the name is still reserved if any of those
2877 * follow immediately after the actual name.
2879 i++;
2880 if (path[i] == ' ') {
2881 preceding_space_or_period = 1;
2882 while (path[++i] == ' ')
2883 ; /* skip all spaces */
2886 c = path[i];
2887 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
2888 goto not_a_reserved_name;
2890 /* contains reserved name */
2891 return 0;
2892 case '.':
2893 periods++;
2894 /* fallthru */
2895 case ' ':
2896 preceding_space_or_period = 1;
2897 i++;
2898 continue;
2899 case ':': /* DOS drive prefix was already skipped */
2900 case '<': case '>': case '"': case '|': case '?': case '*':
2901 /* illegal character */
2902 return 0;
2903 default:
2904 if (c > '\0' && c < '\x20')
2905 /* illegal character */
2906 return 0;
2908 preceding_space_or_period = 0;
2909 i++;
2913 #if !defined(_MSC_VER)
2915 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2916 * mingw startup code, see init.c in mingw runtime).
2918 int _CRT_glob = 0;
2919 #endif
2921 static NORETURN void die_startup(void)
2923 fputs("fatal: not enough memory for initialization", stderr);
2924 exit(128);
2927 static void *malloc_startup(size_t size)
2929 void *result = malloc(size);
2930 if (!result)
2931 die_startup();
2932 return result;
2935 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2937 len = xwcstoutf(buffer, wcs, len) + 1;
2938 return memcpy(malloc_startup(len), buffer, len);
2941 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2942 DWORD desired_access, DWORD flags)
2944 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2945 wchar_t buf[MAX_PATH];
2946 DWORD max = ARRAY_SIZE(buf);
2947 HANDLE handle;
2948 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2950 if (!ret || ret >= max)
2951 return;
2953 /* make sure this does not leak into child processes */
2954 SetEnvironmentVariableW(key, NULL);
2955 if (!wcscmp(buf, L"off")) {
2956 close(fd);
2957 handle = GetStdHandle(std_id);
2958 if (handle != INVALID_HANDLE_VALUE)
2959 CloseHandle(handle);
2960 return;
2962 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2963 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2964 if (handle == INVALID_HANDLE_VALUE) {
2965 close(fd);
2966 handle = GetStdHandle(std_id);
2967 if (handle != INVALID_HANDLE_VALUE)
2968 CloseHandle(handle);
2969 } else {
2970 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2971 SetStdHandle(std_id, handle);
2972 dup2(new_fd, fd);
2973 /* do *not* close the new_fd: that would close stdout */
2975 return;
2977 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2978 flags, NULL);
2979 if (handle != INVALID_HANDLE_VALUE) {
2980 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2981 SetStdHandle(std_id, handle);
2982 dup2(new_fd, fd);
2983 close(new_fd);
2987 static void maybe_redirect_std_handles(void)
2989 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2990 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2991 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2992 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2993 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2994 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2997 #ifdef _MSC_VER
2998 #ifdef _DEBUG
2999 #include <crtdbg.h>
3000 #endif
3001 #endif
3004 * We implement wmain() and compile with -municode, which would
3005 * normally ignore main(), but we call the latter from the former
3006 * so that we can handle non-ASCII command-line parameters
3007 * appropriately.
3009 * To be more compatible with the core git code, we convert
3010 * argv into UTF8 and pass them directly to main().
3012 int wmain(int argc, const wchar_t **wargv)
3014 int i, maxlen, exit_status;
3015 char *buffer, **save;
3016 const char **argv;
3018 trace2_initialize_clock();
3020 #ifdef _MSC_VER
3021 #ifdef _DEBUG
3022 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3023 #endif
3025 #ifdef USE_MSVC_CRTDBG
3026 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3027 #endif
3028 #endif
3030 maybe_redirect_std_handles();
3032 /* determine size of argv and environ conversion buffer */
3033 maxlen = wcslen(wargv[0]);
3034 for (i = 1; i < argc; i++)
3035 maxlen = max(maxlen, wcslen(wargv[i]));
3037 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3038 maxlen = 3 * maxlen + 1;
3039 buffer = malloc_startup(maxlen);
3042 * Create a UTF-8 version of w_argv. Also create a "save" copy
3043 * to remember all the string pointers because parse_options()
3044 * will remove claimed items from the argv that we pass down.
3046 ALLOC_ARRAY(argv, argc + 1);
3047 ALLOC_ARRAY(save, argc + 1);
3048 for (i = 0; i < argc; i++)
3049 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3050 argv[i] = save[i] = NULL;
3051 free(buffer);
3053 /* fix Windows specific environment settings */
3054 setup_windows_environment();
3056 unset_environment_variables = xstrdup("PERL5LIB");
3058 /* initialize critical section for waitpid pinfo_t list */
3059 InitializeCriticalSection(&pinfo_cs);
3061 /* set up default file mode and file modes for stdin/out/err */
3062 _fmode = _O_BINARY;
3063 _setmode(_fileno(stdin), _O_BINARY);
3064 _setmode(_fileno(stdout), _O_BINARY);
3065 _setmode(_fileno(stderr), _O_BINARY);
3067 /* initialize Unicode console */
3068 winansi_init();
3070 /* invoke the real main() using our utf8 version of argv. */
3071 exit_status = main(argc, argv);
3073 for (i = 0; i < argc; i++)
3074 free(save[i]);
3075 free(save);
3076 free(argv);
3078 return exit_status;
3081 int uname(struct utsname *buf)
3083 unsigned v = (unsigned)GetVersion();
3084 memset(buf, 0, sizeof(*buf));
3085 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3086 xsnprintf(buf->release, sizeof(buf->release),
3087 "%u.%u", v & 0xff, (v >> 8) & 0xff);
3088 /* assuming NT variants only.. */
3089 xsnprintf(buf->version, sizeof(buf->version),
3090 "%u", (v >> 16) & 0x7fff);
3091 return 0;