Merge branch 'sg/index-format-doc-update' into maint
[git/debian.git] / compat / mingw.c
blobb5502997e2dce6f98890e790733b7d387ccaf25c
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <aclapi.h>
4 #include <conio.h>
5 #include <wchar.h>
6 #include "../strbuf.h"
7 #include "../run-command.h"
8 #include "../cache.h"
9 #include "win32/lazyload.h"
10 #include "../config.h"
11 #include "dir.h"
12 #define SECURITY_WIN32
13 #include <sspi.h>
15 #define HCAST(type, handle) ((type)(intptr_t)handle)
17 static const int delay[] = { 0, 1, 10, 20, 40 };
19 void open_in_gdb(void)
21 static struct child_process cp = CHILD_PROCESS_INIT;
22 extern char *_pgmptr;
24 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
25 strvec_pushf(&cp.args, "--pid=%d", getpid());
26 cp.clean_on_exit = 1;
27 if (start_command(&cp) < 0)
28 die_errno("Could not start gdb");
29 sleep(1);
32 int err_win_to_posix(DWORD winerr)
34 int error = ENOSYS;
35 switch(winerr) {
36 case ERROR_ACCESS_DENIED: error = EACCES; break;
37 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
38 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
39 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
40 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
41 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
42 case ERROR_BAD_COMMAND: error = EIO; break;
43 case ERROR_BAD_DEVICE: error = ENODEV; break;
44 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
45 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
46 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
47 case ERROR_BAD_LENGTH: error = EINVAL; break;
48 case ERROR_BAD_PATHNAME: error = ENOENT; break;
49 case ERROR_BAD_PIPE: error = EPIPE; break;
50 case ERROR_BAD_UNIT: error = ENODEV; break;
51 case ERROR_BAD_USERNAME: error = EINVAL; break;
52 case ERROR_BROKEN_PIPE: error = EPIPE; break;
53 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
54 case ERROR_BUSY: error = EBUSY; break;
55 case ERROR_BUSY_DRIVE: error = EBUSY; break;
56 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
57 case ERROR_CANNOT_MAKE: error = EACCES; break;
58 case ERROR_CANTOPEN: error = EIO; break;
59 case ERROR_CANTREAD: error = EIO; break;
60 case ERROR_CANTWRITE: error = EIO; break;
61 case ERROR_CRC: error = EIO; break;
62 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
63 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
64 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
65 case ERROR_DIRECTORY: error = EINVAL; break;
66 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
67 case ERROR_DISK_CHANGE: error = EIO; break;
68 case ERROR_DISK_FULL: error = ENOSPC; break;
69 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
70 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
71 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
72 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
73 case ERROR_FILE_EXISTS: error = EEXIST; break;
74 case ERROR_FILE_INVALID: error = ENODEV; break;
75 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
76 case ERROR_GEN_FAILURE: error = EIO; break;
77 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
78 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
79 case ERROR_INVALID_ACCESS: error = EACCES; break;
80 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
81 case ERROR_INVALID_BLOCK: error = EFAULT; break;
82 case ERROR_INVALID_DATA: error = EINVAL; break;
83 case ERROR_INVALID_DRIVE: error = ENODEV; break;
84 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
85 case ERROR_INVALID_FLAGS: error = EINVAL; break;
86 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
87 case ERROR_INVALID_HANDLE: error = EBADF; break;
88 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
89 case ERROR_INVALID_NAME: error = EINVAL; break;
90 case ERROR_INVALID_OWNER: error = EINVAL; break;
91 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
92 case ERROR_INVALID_PASSWORD: error = EPERM; break;
93 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
94 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
95 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
96 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
97 case ERROR_IO_DEVICE: error = EIO; break;
98 case ERROR_IO_INCOMPLETE: error = EINTR; break;
99 case ERROR_LOCKED: error = EBUSY; break;
100 case ERROR_LOCK_VIOLATION: error = EACCES; break;
101 case ERROR_LOGON_FAILURE: error = EACCES; break;
102 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
103 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
104 case ERROR_MORE_DATA: error = EPIPE; break;
105 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
106 case ERROR_NOACCESS: error = EFAULT; break;
107 case ERROR_NONE_MAPPED: error = EINVAL; break;
108 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
109 case ERROR_NOT_READY: error = EAGAIN; break;
110 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
111 case ERROR_NO_DATA: error = EPIPE; break;
112 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
113 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
114 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
115 case ERROR_OPEN_FAILED: error = EIO; break;
116 case ERROR_OPEN_FILES: error = EBUSY; break;
117 case ERROR_OPERATION_ABORTED: error = EINTR; break;
118 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
119 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
120 case ERROR_PATH_BUSY: error = EBUSY; break;
121 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
122 case ERROR_PIPE_BUSY: error = EBUSY; break;
123 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
124 case ERROR_PIPE_LISTENING: error = EPIPE; break;
125 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
126 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
127 case ERROR_READ_FAULT: error = EIO; break;
128 case ERROR_SEEK: error = EIO; break;
129 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
130 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
131 case ERROR_SHARING_VIOLATION: error = EACCES; break;
132 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
133 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
134 case ERROR_SWAPERROR: error = ENOENT; break;
135 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
136 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
137 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
138 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
139 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
140 case ERROR_WRITE_FAULT: error = EIO; break;
141 case ERROR_WRITE_PROTECT: error = EROFS; break;
143 return error;
146 static inline int is_file_in_use_error(DWORD errcode)
148 switch (errcode) {
149 case ERROR_SHARING_VIOLATION:
150 case ERROR_ACCESS_DENIED:
151 return 1;
154 return 0;
157 static int read_yes_no_answer(void)
159 char answer[1024];
161 if (fgets(answer, sizeof(answer), stdin)) {
162 size_t answer_len = strlen(answer);
163 int got_full_line = 0, c;
165 /* remove the newline */
166 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
167 answer[answer_len-2] = '\0';
168 got_full_line = 1;
169 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
170 answer[answer_len-1] = '\0';
171 got_full_line = 1;
173 /* flush the buffer in case we did not get the full line */
174 if (!got_full_line)
175 while ((c = getchar()) != EOF && c != '\n')
177 } else
178 /* we could not read, return the
179 * default answer which is no */
180 return 0;
182 if (tolower(answer[0]) == 'y' && !answer[1])
183 return 1;
184 if (!strncasecmp(answer, "yes", sizeof(answer)))
185 return 1;
186 if (tolower(answer[0]) == 'n' && !answer[1])
187 return 0;
188 if (!strncasecmp(answer, "no", sizeof(answer)))
189 return 0;
191 /* did not find an answer we understand */
192 return -1;
195 static int ask_yes_no_if_possible(const char *format, ...)
197 char question[4096];
198 const char *retry_hook[] = { NULL, NULL, NULL };
199 va_list args;
201 va_start(args, format);
202 vsnprintf(question, sizeof(question), format, args);
203 va_end(args);
205 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
206 retry_hook[1] = question;
207 return !run_command_v_opt(retry_hook, 0);
210 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
211 return 0;
213 while (1) {
214 int answer;
215 fprintf(stderr, "%s (y/n) ", question);
217 if ((answer = read_yes_no_answer()) >= 0)
218 return answer;
220 fprintf(stderr, "Sorry, I did not understand your answer. "
221 "Please type 'y' or 'n'\n");
225 /* Windows only */
226 enum hide_dotfiles_type {
227 HIDE_DOTFILES_FALSE = 0,
228 HIDE_DOTFILES_TRUE,
229 HIDE_DOTFILES_DOTGITONLY
232 static int core_restrict_inherited_handles = -1;
233 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
234 static char *unset_environment_variables;
236 int mingw_core_config(const char *var, const char *value, void *cb)
238 if (!strcmp(var, "core.hidedotfiles")) {
239 if (value && !strcasecmp(value, "dotgitonly"))
240 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
241 else
242 hide_dotfiles = git_config_bool(var, value);
243 return 0;
246 if (!strcmp(var, "core.unsetenvvars")) {
247 free(unset_environment_variables);
248 unset_environment_variables = xstrdup(value);
249 return 0;
252 if (!strcmp(var, "core.restrictinheritedhandles")) {
253 if (value && !strcasecmp(value, "auto"))
254 core_restrict_inherited_handles = -1;
255 else
256 core_restrict_inherited_handles =
257 git_config_bool(var, value);
258 return 0;
261 return 0;
264 /* Normalizes NT paths as returned by some low-level APIs. */
265 static wchar_t *normalize_ntpath(wchar_t *wbuf)
267 int i;
268 /* fix absolute path prefixes */
269 if (wbuf[0] == '\\') {
270 /* strip NT namespace prefixes */
271 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
272 !wcsncmp(wbuf, L"\\\\?\\", 4))
273 wbuf += 4;
274 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
275 wbuf += 12;
276 /* replace remaining '...UNC\' with '\\' */
277 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
278 wbuf += 2;
279 *wbuf = '\\';
282 /* convert backslashes to slashes */
283 for (i = 0; wbuf[i]; i++)
284 if (wbuf[i] == '\\')
285 wbuf[i] = '/';
286 return wbuf;
289 int mingw_unlink(const char *pathname)
291 int ret, tries = 0;
292 wchar_t wpathname[MAX_PATH];
293 if (xutftowcs_path(wpathname, pathname) < 0)
294 return -1;
296 if (DeleteFileW(wpathname))
297 return 0;
299 /* read-only files cannot be removed */
300 _wchmod(wpathname, 0666);
301 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
302 if (!is_file_in_use_error(GetLastError()))
303 break;
305 * We assume that some other process had the source or
306 * destination file open at the wrong moment and retry.
307 * In order to give the other process a higher chance to
308 * complete its operation, we give up our time slice now.
309 * If we have to retry again, we do sleep a bit.
311 Sleep(delay[tries]);
312 tries++;
314 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
315 ask_yes_no_if_possible("Unlink of file '%s' failed. "
316 "Should I try again?", pathname))
317 ret = _wunlink(wpathname);
318 return ret;
321 static int is_dir_empty(const wchar_t *wpath)
323 WIN32_FIND_DATAW findbuf;
324 HANDLE handle;
325 wchar_t wbuf[MAX_PATH + 2];
326 wcscpy(wbuf, wpath);
327 wcscat(wbuf, L"\\*");
328 handle = FindFirstFileW(wbuf, &findbuf);
329 if (handle == INVALID_HANDLE_VALUE)
330 return GetLastError() == ERROR_NO_MORE_FILES;
332 while (!wcscmp(findbuf.cFileName, L".") ||
333 !wcscmp(findbuf.cFileName, L".."))
334 if (!FindNextFileW(handle, &findbuf)) {
335 DWORD err = GetLastError();
336 FindClose(handle);
337 return err == ERROR_NO_MORE_FILES;
339 FindClose(handle);
340 return 0;
343 int mingw_rmdir(const char *pathname)
345 int ret, tries = 0;
346 wchar_t wpathname[MAX_PATH];
347 struct stat st;
350 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
351 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
352 * symbolic link (if it points to a directory).
354 * This behavior breaks the assumption of e.g. `remove_path()` which
355 * upon successful deletion of a file will attempt to remove its parent
356 * directories recursively until failure (which usually happens when
357 * the directory is not empty).
359 * Therefore, before calling `_wrmdir()`, we first check if the path is
360 * a symbolic link. If it is, we exit and return the same error as
361 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
363 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
364 errno = ENOTDIR;
365 return -1;
368 if (xutftowcs_path(wpathname, pathname) < 0)
369 return -1;
371 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
372 if (!is_file_in_use_error(GetLastError()))
373 errno = err_win_to_posix(GetLastError());
374 if (errno != EACCES)
375 break;
376 if (!is_dir_empty(wpathname)) {
377 errno = ENOTEMPTY;
378 break;
381 * We assume that some other process had the source or
382 * destination file open at the wrong moment and retry.
383 * In order to give the other process a higher chance to
384 * complete its operation, we give up our time slice now.
385 * If we have to retry again, we do sleep a bit.
387 Sleep(delay[tries]);
388 tries++;
390 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
391 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
392 "Should I try again?", pathname))
393 ret = _wrmdir(wpathname);
394 if (!ret)
395 invalidate_lstat_cache();
396 return ret;
399 static inline int needs_hiding(const char *path)
401 const char *basename;
403 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
404 return 0;
406 /* We cannot use basename(), as it would remove trailing slashes */
407 win32_skip_dos_drive_prefix((char **)&path);
408 if (!*path)
409 return 0;
411 for (basename = path; *path; path++)
412 if (is_dir_sep(*path)) {
413 do {
414 path++;
415 } while (is_dir_sep(*path));
416 /* ignore trailing slashes */
417 if (*path)
418 basename = path;
419 else
420 break;
423 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
424 return *basename == '.';
426 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
427 return !strncasecmp(".git", basename, 4) &&
428 (!basename[4] || is_dir_sep(basename[4]));
431 static int set_hidden_flag(const wchar_t *path, int set)
433 DWORD original = GetFileAttributesW(path), modified;
434 if (set)
435 modified = original | FILE_ATTRIBUTE_HIDDEN;
436 else
437 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
438 if (original == modified || SetFileAttributesW(path, modified))
439 return 0;
440 errno = err_win_to_posix(GetLastError());
441 return -1;
444 int mingw_mkdir(const char *path, int mode)
446 int ret;
447 wchar_t wpath[MAX_PATH];
449 if (!is_valid_win32_path(path, 0)) {
450 errno = EINVAL;
451 return -1;
454 if (xutftowcs_path(wpath, path) < 0)
455 return -1;
456 ret = _wmkdir(wpath);
457 if (!ret && needs_hiding(path))
458 return set_hidden_flag(wpath, 1);
459 return ret;
463 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
464 * is documented in [1] as opening a writable file handle in append mode.
465 * (It is believed that) this is atomic since it is maintained by the
466 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
468 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
470 * This trick does not appear to work for named pipes. Instead it creates
471 * a named pipe client handle that cannot be written to. Callers should
472 * just use the regular _wopen() for them. (And since client handle gets
473 * bound to a unique server handle, it isn't really an issue.)
475 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
477 HANDLE handle;
478 int fd;
479 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
481 /* only these flags are supported */
482 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
483 return errno = ENOSYS, -1;
486 * FILE_SHARE_WRITE is required to permit child processes
487 * to append to the file.
489 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
490 FILE_SHARE_WRITE | FILE_SHARE_READ,
491 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
492 if (handle == INVALID_HANDLE_VALUE) {
493 DWORD err = GetLastError();
496 * Some network storage solutions (e.g. Isilon) might return
497 * ERROR_INVALID_PARAMETER instead of expected error
498 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
499 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
501 if (err == ERROR_INVALID_PARAMETER)
502 err = ERROR_PATH_NOT_FOUND;
504 errno = err_win_to_posix(err);
505 return -1;
509 * No O_APPEND here, because the CRT uses it only to reset the
510 * file pointer to EOF before each write(); but that is not
511 * necessary (and may lead to races) for a file created with
512 * FILE_APPEND_DATA.
514 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
515 if (fd < 0)
516 CloseHandle(handle);
517 return fd;
521 * Does the pathname map to the local named pipe filesystem?
522 * That is, does it have a "//./pipe/" prefix?
524 static int is_local_named_pipe_path(const char *filename)
526 return (is_dir_sep(filename[0]) &&
527 is_dir_sep(filename[1]) &&
528 filename[2] == '.' &&
529 is_dir_sep(filename[3]) &&
530 !strncasecmp(filename+4, "pipe", 4) &&
531 is_dir_sep(filename[8]) &&
532 filename[9]);
535 int mingw_open (const char *filename, int oflags, ...)
537 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
538 va_list args;
539 unsigned mode;
540 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
541 wchar_t wfilename[MAX_PATH];
542 open_fn_t open_fn;
544 va_start(args, oflags);
545 mode = va_arg(args, int);
546 va_end(args);
548 if (!is_valid_win32_path(filename, !create)) {
549 errno = create ? EINVAL : ENOENT;
550 return -1;
553 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
554 open_fn = mingw_open_append;
555 else
556 open_fn = _wopen;
558 if (filename && !strcmp(filename, "/dev/null"))
559 wcscpy(wfilename, L"nul");
560 else if (xutftowcs_path(wfilename, filename) < 0)
561 return -1;
563 fd = open_fn(wfilename, oflags, mode);
565 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
566 DWORD attrs = GetFileAttributesW(wfilename);
567 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
568 errno = EISDIR;
570 if ((oflags & O_CREAT) && needs_hiding(filename)) {
572 * Internally, _wopen() uses the CreateFile() API which errors
573 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
574 * specified and an already existing file's attributes do not
575 * match *exactly*. As there is no mode or flag we can set that
576 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
577 * again *without* the O_CREAT flag (that corresponds to the
578 * CREATE_ALWAYS flag of CreateFile()).
580 if (fd < 0 && errno == EACCES)
581 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
582 if (fd >= 0 && set_hidden_flag(wfilename, 1))
583 warning("could not mark '%s' as hidden.", filename);
585 return fd;
588 static BOOL WINAPI ctrl_ignore(DWORD type)
590 return TRUE;
593 #undef fgetc
594 int mingw_fgetc(FILE *stream)
596 int ch;
597 if (!isatty(_fileno(stream)))
598 return fgetc(stream);
600 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
601 while (1) {
602 ch = fgetc(stream);
603 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
604 break;
606 /* Ctrl+C was pressed, simulate SIGINT and retry */
607 mingw_raise(SIGINT);
609 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
610 return ch;
613 #undef fopen
614 FILE *mingw_fopen (const char *filename, const char *otype)
616 int hide = needs_hiding(filename);
617 FILE *file;
618 wchar_t wfilename[MAX_PATH], wotype[4];
619 if (filename && !strcmp(filename, "/dev/null"))
620 wcscpy(wfilename, L"nul");
621 else if (!is_valid_win32_path(filename, 1)) {
622 int create = otype && strchr(otype, 'w');
623 errno = create ? EINVAL : ENOENT;
624 return NULL;
625 } else if (xutftowcs_path(wfilename, filename) < 0)
626 return NULL;
628 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
629 return NULL;
631 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
632 error("could not unhide %s", filename);
633 return NULL;
635 file = _wfopen(wfilename, wotype);
636 if (!file && GetLastError() == ERROR_INVALID_NAME)
637 errno = ENOENT;
638 if (file && hide && set_hidden_flag(wfilename, 1))
639 warning("could not mark '%s' as hidden.", filename);
640 return file;
643 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
645 int hide = needs_hiding(filename);
646 FILE *file;
647 wchar_t wfilename[MAX_PATH], wotype[4];
648 if (filename && !strcmp(filename, "/dev/null"))
649 wcscpy(wfilename, L"nul");
650 else if (!is_valid_win32_path(filename, 1)) {
651 int create = otype && strchr(otype, 'w');
652 errno = create ? EINVAL : ENOENT;
653 return NULL;
654 } else if (xutftowcs_path(wfilename, filename) < 0)
655 return NULL;
657 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
658 return NULL;
660 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
661 error("could not unhide %s", filename);
662 return NULL;
664 file = _wfreopen(wfilename, wotype, stream);
665 if (file && hide && set_hidden_flag(wfilename, 1))
666 warning("could not mark '%s' as hidden.", filename);
667 return file;
670 #undef fflush
671 int mingw_fflush(FILE *stream)
673 int ret = fflush(stream);
676 * write() is used behind the scenes of stdio output functions.
677 * Since git code does not check for errors after each stdio write
678 * operation, it can happen that write() is called by a later
679 * stdio function even if an earlier write() call failed. In the
680 * case of a pipe whose readable end was closed, only the first
681 * call to write() reports EPIPE on Windows. Subsequent write()
682 * calls report EINVAL. It is impossible to notice whether this
683 * fflush invocation triggered such a case, therefore, we have to
684 * catch all EINVAL errors whole-sale.
686 if (ret && errno == EINVAL)
687 errno = EPIPE;
689 return ret;
692 #undef write
693 ssize_t mingw_write(int fd, const void *buf, size_t len)
695 ssize_t result = write(fd, buf, len);
697 if (result < 0 && errno == EINVAL && buf) {
698 /* check if fd is a pipe */
699 HANDLE h = (HANDLE) _get_osfhandle(fd);
700 if (GetFileType(h) == FILE_TYPE_PIPE)
701 errno = EPIPE;
702 else
703 errno = EINVAL;
706 return result;
709 int mingw_access(const char *filename, int mode)
711 wchar_t wfilename[MAX_PATH];
712 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
713 return 0;
714 if (xutftowcs_path(wfilename, filename) < 0)
715 return -1;
716 /* X_OK is not supported by the MSVCRT version */
717 return _waccess(wfilename, mode & ~X_OK);
720 int mingw_chdir(const char *dirname)
722 wchar_t wdirname[MAX_PATH];
723 if (xutftowcs_path(wdirname, dirname) < 0)
724 return -1;
725 return _wchdir(wdirname);
728 int mingw_chmod(const char *filename, int mode)
730 wchar_t wfilename[MAX_PATH];
731 if (xutftowcs_path(wfilename, filename) < 0)
732 return -1;
733 return _wchmod(wfilename, mode);
737 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
738 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
740 static inline long long filetime_to_hnsec(const FILETIME *ft)
742 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
743 /* Windows to Unix Epoch conversion */
744 return winTime - 116444736000000000LL;
747 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
749 long long hnsec = filetime_to_hnsec(ft);
750 ts->tv_sec = (time_t)(hnsec / 10000000);
751 ts->tv_nsec = (hnsec % 10000000) * 100;
755 * Verifies that safe_create_leading_directories() would succeed.
757 static int has_valid_directory_prefix(wchar_t *wfilename)
759 int n = wcslen(wfilename);
761 while (n > 0) {
762 wchar_t c = wfilename[--n];
763 DWORD attributes;
765 if (!is_dir_sep(c))
766 continue;
768 wfilename[n] = L'\0';
769 attributes = GetFileAttributesW(wfilename);
770 wfilename[n] = c;
771 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
772 attributes == FILE_ATTRIBUTE_DEVICE)
773 return 1;
774 if (attributes == INVALID_FILE_ATTRIBUTES)
775 switch (GetLastError()) {
776 case ERROR_PATH_NOT_FOUND:
777 continue;
778 case ERROR_FILE_NOT_FOUND:
779 /* This implies parent directory exists. */
780 return 1;
782 return 0;
784 return 1;
787 /* We keep the do_lstat code in a separate function to avoid recursion.
788 * When a path ends with a slash, the stat will fail with ENOENT. In
789 * this case, we strip the trailing slashes and stat again.
791 * If follow is true then act like stat() and report on the link
792 * target. Otherwise report on the link itself.
794 static int do_lstat(int follow, const char *file_name, struct stat *buf)
796 WIN32_FILE_ATTRIBUTE_DATA fdata;
797 wchar_t wfilename[MAX_PATH];
798 if (xutftowcs_path(wfilename, file_name) < 0)
799 return -1;
801 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
802 buf->st_ino = 0;
803 buf->st_gid = 0;
804 buf->st_uid = 0;
805 buf->st_nlink = 1;
806 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
807 buf->st_size = fdata.nFileSizeLow |
808 (((off_t)fdata.nFileSizeHigh)<<32);
809 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
810 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
811 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
812 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
813 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
814 WIN32_FIND_DATAW findbuf;
815 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
816 if (handle != INVALID_HANDLE_VALUE) {
817 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
818 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
819 if (follow) {
820 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
821 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
822 } else {
823 buf->st_mode = S_IFLNK;
825 buf->st_mode |= S_IREAD;
826 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
827 buf->st_mode |= S_IWRITE;
829 FindClose(handle);
832 return 0;
834 switch (GetLastError()) {
835 case ERROR_ACCESS_DENIED:
836 case ERROR_SHARING_VIOLATION:
837 case ERROR_LOCK_VIOLATION:
838 case ERROR_SHARING_BUFFER_EXCEEDED:
839 errno = EACCES;
840 break;
841 case ERROR_BUFFER_OVERFLOW:
842 errno = ENAMETOOLONG;
843 break;
844 case ERROR_NOT_ENOUGH_MEMORY:
845 errno = ENOMEM;
846 break;
847 case ERROR_PATH_NOT_FOUND:
848 if (!has_valid_directory_prefix(wfilename)) {
849 errno = ENOTDIR;
850 break;
852 /* fallthru */
853 default:
854 errno = ENOENT;
855 break;
857 return -1;
860 /* We provide our own lstat/fstat functions, since the provided
861 * lstat/fstat functions are so slow. These stat functions are
862 * tailored for Git's usage (read: fast), and are not meant to be
863 * complete. Note that Git stat()s are redirected to mingw_lstat()
864 * too, since Windows doesn't really handle symlinks that well.
866 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
868 int namelen;
869 char alt_name[PATH_MAX];
871 if (!do_lstat(follow, file_name, buf))
872 return 0;
874 /* if file_name ended in a '/', Windows returned ENOENT;
875 * try again without trailing slashes
877 if (errno != ENOENT)
878 return -1;
880 namelen = strlen(file_name);
881 if (namelen && file_name[namelen-1] != '/')
882 return -1;
883 while (namelen && file_name[namelen-1] == '/')
884 --namelen;
885 if (!namelen || namelen >= PATH_MAX)
886 return -1;
888 memcpy(alt_name, file_name, namelen);
889 alt_name[namelen] = 0;
890 return do_lstat(follow, alt_name, buf);
893 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
895 BY_HANDLE_FILE_INFORMATION fdata;
897 if (!GetFileInformationByHandle(hnd, &fdata)) {
898 errno = err_win_to_posix(GetLastError());
899 return -1;
902 buf->st_ino = 0;
903 buf->st_gid = 0;
904 buf->st_uid = 0;
905 buf->st_nlink = 1;
906 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
907 buf->st_size = fdata.nFileSizeLow |
908 (((off_t)fdata.nFileSizeHigh)<<32);
909 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
910 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
911 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
912 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
913 return 0;
916 int mingw_lstat(const char *file_name, struct stat *buf)
918 return do_stat_internal(0, file_name, buf);
920 int mingw_stat(const char *file_name, struct stat *buf)
922 return do_stat_internal(1, file_name, buf);
925 int mingw_fstat(int fd, struct stat *buf)
927 HANDLE fh = (HANDLE)_get_osfhandle(fd);
928 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
930 switch (type) {
931 case FILE_TYPE_DISK:
932 return get_file_info_by_handle(fh, buf);
934 case FILE_TYPE_CHAR:
935 case FILE_TYPE_PIPE:
936 /* initialize stat fields */
937 memset(buf, 0, sizeof(*buf));
938 buf->st_nlink = 1;
940 if (type == FILE_TYPE_CHAR) {
941 buf->st_mode = _S_IFCHR;
942 } else {
943 buf->st_mode = _S_IFIFO;
944 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
945 buf->st_size = avail;
947 return 0;
949 default:
950 errno = EBADF;
951 return -1;
955 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
957 long long winTime = t * 10000000LL + 116444736000000000LL;
958 ft->dwLowDateTime = winTime;
959 ft->dwHighDateTime = winTime >> 32;
962 int mingw_utime (const char *file_name, const struct utimbuf *times)
964 FILETIME mft, aft;
965 int rc;
966 DWORD attrs;
967 wchar_t wfilename[MAX_PATH];
968 HANDLE osfilehandle;
970 if (xutftowcs_path(wfilename, file_name) < 0)
971 return -1;
973 /* must have write permission */
974 attrs = GetFileAttributesW(wfilename);
975 if (attrs != INVALID_FILE_ATTRIBUTES &&
976 (attrs & FILE_ATTRIBUTE_READONLY)) {
977 /* ignore errors here; open() will report them */
978 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
981 osfilehandle = CreateFileW(wfilename,
982 FILE_WRITE_ATTRIBUTES,
983 0 /*FileShare.None*/,
984 NULL,
985 OPEN_EXISTING,
986 (attrs != INVALID_FILE_ATTRIBUTES &&
987 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
988 FILE_FLAG_BACKUP_SEMANTICS : 0,
989 NULL);
990 if (osfilehandle == INVALID_HANDLE_VALUE) {
991 errno = err_win_to_posix(GetLastError());
992 rc = -1;
993 goto revert_attrs;
996 if (times) {
997 time_t_to_filetime(times->modtime, &mft);
998 time_t_to_filetime(times->actime, &aft);
999 } else {
1000 GetSystemTimeAsFileTime(&mft);
1001 aft = mft;
1004 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
1005 errno = EINVAL;
1006 rc = -1;
1007 } else
1008 rc = 0;
1010 if (osfilehandle != INVALID_HANDLE_VALUE)
1011 CloseHandle(osfilehandle);
1013 revert_attrs:
1014 if (attrs != INVALID_FILE_ATTRIBUTES &&
1015 (attrs & FILE_ATTRIBUTE_READONLY)) {
1016 /* ignore errors again */
1017 SetFileAttributesW(wfilename, attrs);
1019 return rc;
1022 #undef strftime
1023 size_t mingw_strftime(char *s, size_t max,
1024 const char *format, const struct tm *tm)
1026 /* a pointer to the original strftime in case we can't find the UCRT version */
1027 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1028 size_t ret;
1029 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1030 const char *, const struct tm *);
1032 if (INIT_PROC_ADDR(strftime))
1033 ret = strftime(s, max, format, tm);
1034 else
1035 ret = fallback(s, max, format, tm);
1037 if (!ret && errno == EINVAL)
1038 die("invalid strftime format: '%s'", format);
1039 return ret;
1042 unsigned int sleep (unsigned int seconds)
1044 Sleep(seconds*1000);
1045 return 0;
1048 char *mingw_mktemp(char *template)
1050 wchar_t wtemplate[MAX_PATH];
1051 if (xutftowcs_path(wtemplate, template) < 0)
1052 return NULL;
1053 if (!_wmktemp(wtemplate))
1054 return NULL;
1055 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1056 return NULL;
1057 return template;
1060 int mkstemp(char *template)
1062 return git_mkstemp_mode(template, 0600);
1065 int gettimeofday(struct timeval *tv, void *tz)
1067 FILETIME ft;
1068 long long hnsec;
1070 GetSystemTimeAsFileTime(&ft);
1071 hnsec = filetime_to_hnsec(&ft);
1072 tv->tv_sec = hnsec / 10000000;
1073 tv->tv_usec = (hnsec % 10000000) / 10;
1074 return 0;
1077 int pipe(int filedes[2])
1079 HANDLE h[2];
1081 /* this creates non-inheritable handles */
1082 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1083 errno = err_win_to_posix(GetLastError());
1084 return -1;
1086 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1087 if (filedes[0] < 0) {
1088 CloseHandle(h[0]);
1089 CloseHandle(h[1]);
1090 return -1;
1092 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1093 if (filedes[1] < 0) {
1094 close(filedes[0]);
1095 CloseHandle(h[1]);
1096 return -1;
1098 return 0;
1101 #ifndef __MINGW64__
1102 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1104 if (gmtime_s(result, timep) == 0)
1105 return result;
1106 return NULL;
1109 struct tm *localtime_r(const time_t *timep, struct tm *result)
1111 if (localtime_s(result, timep) == 0)
1112 return result;
1113 return NULL;
1115 #endif
1117 char *mingw_getcwd(char *pointer, int len)
1119 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1120 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1122 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1123 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1124 return NULL;
1126 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1127 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1128 HANDLE hnd = CreateFileW(cwd, 0,
1129 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1130 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1131 if (hnd == INVALID_HANDLE_VALUE)
1132 return NULL;
1133 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1134 CloseHandle(hnd);
1135 if (!ret || ret >= ARRAY_SIZE(wpointer))
1136 return NULL;
1137 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1138 return NULL;
1139 return pointer;
1141 if (!ret || ret >= ARRAY_SIZE(wpointer))
1142 return NULL;
1143 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1144 errno = ENOENT;
1145 return NULL;
1147 if (xwcstoutf(pointer, wpointer, len) < 0)
1148 return NULL;
1149 convert_slashes(pointer);
1150 return pointer;
1154 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1155 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1157 static const char *quote_arg_msvc(const char *arg)
1159 /* count chars to quote */
1160 int len = 0, n = 0;
1161 int force_quotes = 0;
1162 char *q, *d;
1163 const char *p = arg;
1164 if (!*p) force_quotes = 1;
1165 while (*p) {
1166 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1167 force_quotes = 1;
1168 else if (*p == '"')
1169 n++;
1170 else if (*p == '\\') {
1171 int count = 0;
1172 while (*p == '\\') {
1173 count++;
1174 p++;
1175 len++;
1177 if (*p == '"' || !*p)
1178 n += count*2 + 1;
1179 continue;
1181 len++;
1182 p++;
1184 if (!force_quotes && n == 0)
1185 return arg;
1187 /* insert \ where necessary */
1188 d = q = xmalloc(st_add3(len, n, 3));
1189 *d++ = '"';
1190 while (*arg) {
1191 if (*arg == '"')
1192 *d++ = '\\';
1193 else if (*arg == '\\') {
1194 int count = 0;
1195 while (*arg == '\\') {
1196 count++;
1197 *d++ = *arg++;
1199 if (*arg == '"' || !*arg) {
1200 while (count-- > 0)
1201 *d++ = '\\';
1202 /* don't escape the surrounding end quote */
1203 if (!*arg)
1204 break;
1205 *d++ = '\\';
1208 *d++ = *arg++;
1210 *d++ = '"';
1211 *d++ = '\0';
1212 return q;
1215 #include "quote.h"
1217 static const char *quote_arg_msys2(const char *arg)
1219 struct strbuf buf = STRBUF_INIT;
1220 const char *p2 = arg, *p;
1222 for (p = arg; *p; p++) {
1223 int ws = isspace(*p);
1224 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1225 *p != '?' && *p != '*' && *p != '~')
1226 continue;
1227 if (!buf.len)
1228 strbuf_addch(&buf, '"');
1229 if (p != p2)
1230 strbuf_add(&buf, p2, p - p2);
1231 if (*p == '\\' || *p == '"')
1232 strbuf_addch(&buf, '\\');
1233 p2 = p;
1236 if (p == arg)
1237 strbuf_addch(&buf, '"');
1238 else if (!buf.len)
1239 return arg;
1240 else
1241 strbuf_add(&buf, p2, p - p2);
1243 strbuf_addch(&buf, '"');
1244 return strbuf_detach(&buf, 0);
1247 static const char *parse_interpreter(const char *cmd)
1249 static char buf[100];
1250 char *p, *opt;
1251 int n, fd;
1253 /* don't even try a .exe */
1254 n = strlen(cmd);
1255 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1256 return NULL;
1258 fd = open(cmd, O_RDONLY);
1259 if (fd < 0)
1260 return NULL;
1261 n = read(fd, buf, sizeof(buf)-1);
1262 close(fd);
1263 if (n < 4) /* at least '#!/x' and not error */
1264 return NULL;
1266 if (buf[0] != '#' || buf[1] != '!')
1267 return NULL;
1268 buf[n] = '\0';
1269 p = buf + strcspn(buf, "\r\n");
1270 if (!*p)
1271 return NULL;
1273 *p = '\0';
1274 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1275 return NULL;
1276 /* strip options */
1277 if ((opt = strchr(p+1, ' ')))
1278 *opt = '\0';
1279 return p+1;
1283 * exe_only means that we only want to detect .exe files, but not scripts
1284 * (which do not have an extension)
1286 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1287 int isexe, int exe_only)
1289 char path[MAX_PATH];
1290 wchar_t wpath[MAX_PATH];
1291 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1293 if (xutftowcs_path(wpath, path) < 0)
1294 return NULL;
1296 if (!isexe && _waccess(wpath, F_OK) == 0)
1297 return xstrdup(path);
1298 wpath[wcslen(wpath)-4] = '\0';
1299 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1300 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1301 path[strlen(path)-4] = '\0';
1302 return xstrdup(path);
1305 return NULL;
1309 * Determines the absolute path of cmd using the split path in path.
1310 * If cmd contains a slash or backslash, no lookup is performed.
1312 static char *path_lookup(const char *cmd, int exe_only)
1314 const char *path;
1315 char *prog = NULL;
1316 int len = strlen(cmd);
1317 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1319 if (strpbrk(cmd, "/\\"))
1320 return xstrdup(cmd);
1322 path = mingw_getenv("PATH");
1323 if (!path)
1324 return NULL;
1326 while (!prog) {
1327 const char *sep = strchrnul(path, ';');
1328 int dirlen = sep - path;
1329 if (dirlen)
1330 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1331 if (!*sep)
1332 break;
1333 path = sep + 1;
1336 return prog;
1339 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1341 while (*s && *s != c)
1342 s++;
1343 return s;
1346 /* Compare only keys */
1347 static int wenvcmp(const void *a, const void *b)
1349 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1350 size_t p_len, q_len;
1352 /* Find the keys */
1353 p_len = wcschrnul(p, L'=') - p;
1354 q_len = wcschrnul(q, L'=') - q;
1356 /* If the length differs, include the shorter key's NUL */
1357 if (p_len < q_len)
1358 p_len++;
1359 else if (p_len > q_len)
1360 p_len = q_len + 1;
1362 return _wcsnicmp(p, q, p_len);
1366 * Build an environment block combining the inherited environment
1367 * merged with the given list of settings.
1369 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1370 * Values of the form "KEY" in deltaenv delete inherited values.
1372 * Multiple entries in deltaenv for the same key are explicitly allowed.
1374 * We return a contiguous block of UNICODE strings with a final trailing
1375 * zero word.
1377 static wchar_t *make_environment_block(char **deltaenv)
1379 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1380 size_t wlen, s, delta_size, size;
1382 wchar_t **array = NULL;
1383 size_t alloc = 0, nr = 0, i;
1385 size = 1; /* for extra NUL at the end */
1387 /* If there is no deltaenv to apply, simply return a copy. */
1388 if (!deltaenv || !*deltaenv) {
1389 for (p = wenv; p && *p; ) {
1390 size_t s = wcslen(p) + 1;
1391 size += s;
1392 p += s;
1395 ALLOC_ARRAY(result, size);
1396 COPY_ARRAY(result, wenv, size);
1397 FreeEnvironmentStringsW(wenv);
1398 return result;
1402 * If there is a deltaenv, let's accumulate all keys into `array`,
1403 * sort them using the stable git_stable_qsort() and then copy,
1404 * skipping duplicate keys
1406 for (p = wenv; p && *p; ) {
1407 ALLOC_GROW(array, nr + 1, alloc);
1408 s = wcslen(p) + 1;
1409 array[nr++] = p;
1410 p += s;
1411 size += s;
1414 /* (over-)assess size needed for wchar version of deltaenv */
1415 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1416 delta_size += strlen(deltaenv[i]) * 2 + 1;
1417 ALLOC_ARRAY(wdeltaenv, delta_size);
1419 /* convert the deltaenv, appending to array */
1420 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1421 ALLOC_GROW(array, nr + 1, alloc);
1422 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1423 array[nr++] = p;
1424 p += wlen + 1;
1427 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1428 ALLOC_ARRAY(result, size + delta_size);
1430 for (p = result, i = 0; i < nr; i++) {
1431 /* Skip any duplicate keys; last one wins */
1432 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1433 i++;
1435 /* Skip "to delete" entry */
1436 if (!wcschr(array[i], L'='))
1437 continue;
1439 size = wcslen(array[i]) + 1;
1440 COPY_ARRAY(p, array[i], size);
1441 p += size;
1443 *p = L'\0';
1445 free(array);
1446 free(wdeltaenv);
1447 FreeEnvironmentStringsW(wenv);
1448 return result;
1451 static void do_unset_environment_variables(void)
1453 static int done;
1454 char *p = unset_environment_variables;
1456 if (done || !p)
1457 return;
1458 done = 1;
1460 for (;;) {
1461 char *comma = strchr(p, ',');
1463 if (comma)
1464 *comma = '\0';
1465 unsetenv(p);
1466 if (!comma)
1467 break;
1468 p = comma + 1;
1472 struct pinfo_t {
1473 struct pinfo_t *next;
1474 pid_t pid;
1475 HANDLE proc;
1477 static struct pinfo_t *pinfo = NULL;
1478 CRITICAL_SECTION pinfo_cs;
1480 /* Used to match and chomp off path components */
1481 static inline int match_last_path_component(const char *path, size_t *len,
1482 const char *component)
1484 size_t component_len = strlen(component);
1485 if (*len < component_len + 1 ||
1486 !is_dir_sep(path[*len - component_len - 1]) ||
1487 fspathncmp(path + *len - component_len, component, component_len))
1488 return 0;
1489 *len -= component_len + 1;
1490 /* chomp off repeated dir separators */
1491 while (*len > 0 && is_dir_sep(path[*len - 1]))
1492 (*len)--;
1493 return 1;
1496 static int is_msys2_sh(const char *cmd)
1498 if (!cmd)
1499 return 0;
1501 if (!strcmp(cmd, "sh")) {
1502 static int ret = -1;
1503 char *p;
1505 if (ret >= 0)
1506 return ret;
1508 p = path_lookup(cmd, 0);
1509 if (!p)
1510 ret = 0;
1511 else {
1512 size_t len = strlen(p);
1514 ret = match_last_path_component(p, &len, "sh.exe") &&
1515 match_last_path_component(p, &len, "bin") &&
1516 match_last_path_component(p, &len, "usr");
1517 free(p);
1519 return ret;
1522 if (ends_with(cmd, "\\sh.exe")) {
1523 static char *sh;
1525 if (!sh)
1526 sh = path_lookup("sh", 0);
1528 return !fspathcmp(cmd, sh);
1531 return 0;
1534 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1535 const char *dir,
1536 int prepend_cmd, int fhin, int fhout, int fherr)
1538 static int restrict_handle_inheritance = -1;
1539 STARTUPINFOEXW si;
1540 PROCESS_INFORMATION pi;
1541 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1542 HANDLE stdhandles[3];
1543 DWORD stdhandles_count = 0;
1544 SIZE_T size;
1545 struct strbuf args;
1546 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1547 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1548 BOOL ret;
1549 HANDLE cons;
1550 const char *(*quote_arg)(const char *arg) =
1551 is_msys2_sh(cmd ? cmd : *argv) ?
1552 quote_arg_msys2 : quote_arg_msvc;
1553 const char *strace_env;
1555 /* Make sure to override previous errors, if any */
1556 errno = 0;
1558 if (restrict_handle_inheritance < 0)
1559 restrict_handle_inheritance = core_restrict_inherited_handles;
1561 * The following code to restrict which handles are inherited seems
1562 * to work properly only on Windows 7 and later, so let's disable it
1563 * on Windows Vista and 2008.
1565 if (restrict_handle_inheritance < 0)
1566 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1568 do_unset_environment_variables();
1570 /* Determine whether or not we are associated to a console */
1571 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1572 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1573 FILE_ATTRIBUTE_NORMAL, NULL);
1574 if (cons == INVALID_HANDLE_VALUE) {
1575 /* There is no console associated with this process.
1576 * Since the child is a console process, Windows
1577 * would normally create a console window. But
1578 * since we'll be redirecting std streams, we do
1579 * not need the console.
1580 * It is necessary to use DETACHED_PROCESS
1581 * instead of CREATE_NO_WINDOW to make ssh
1582 * recognize that it has no console.
1584 flags |= DETACHED_PROCESS;
1585 } else {
1586 /* There is already a console. If we specified
1587 * DETACHED_PROCESS here, too, Windows would
1588 * disassociate the child from the console.
1589 * The same is true for CREATE_NO_WINDOW.
1590 * Go figure!
1592 CloseHandle(cons);
1594 memset(&si, 0, sizeof(si));
1595 si.StartupInfo.cb = sizeof(si);
1596 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1597 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1598 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1600 /* The list of handles cannot contain duplicates */
1601 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1602 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1603 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1604 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1605 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1606 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1607 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1608 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1609 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1610 if (stdhandles_count)
1611 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1613 if (*argv && !strcmp(cmd, *argv))
1614 wcmd[0] = L'\0';
1615 else if (xutftowcs_path(wcmd, cmd) < 0)
1616 return -1;
1617 if (dir && xutftowcs_path(wdir, dir) < 0)
1618 return -1;
1620 /* concatenate argv, quoting args as we go */
1621 strbuf_init(&args, 0);
1622 if (prepend_cmd) {
1623 char *quoted = (char *)quote_arg(cmd);
1624 strbuf_addstr(&args, quoted);
1625 if (quoted != cmd)
1626 free(quoted);
1628 for (; *argv; argv++) {
1629 char *quoted = (char *)quote_arg(*argv);
1630 if (*args.buf)
1631 strbuf_addch(&args, ' ');
1632 strbuf_addstr(&args, quoted);
1633 if (quoted != *argv)
1634 free(quoted);
1637 strace_env = getenv("GIT_STRACE_COMMANDS");
1638 if (strace_env) {
1639 char *p = path_lookup("strace.exe", 1);
1640 if (!p)
1641 return error("strace not found!");
1642 if (xutftowcs_path(wcmd, p) < 0) {
1643 free(p);
1644 return -1;
1646 free(p);
1647 if (!strcmp("1", strace_env) ||
1648 !strcasecmp("yes", strace_env) ||
1649 !strcasecmp("true", strace_env))
1650 strbuf_insert(&args, 0, "strace ", 7);
1651 else {
1652 const char *quoted = quote_arg(strace_env);
1653 struct strbuf buf = STRBUF_INIT;
1654 strbuf_addf(&buf, "strace -o %s ", quoted);
1655 if (quoted != strace_env)
1656 free((char *)quoted);
1657 strbuf_insert(&args, 0, buf.buf, buf.len);
1658 strbuf_release(&buf);
1662 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1663 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1664 strbuf_release(&args);
1666 wenvblk = make_environment_block(deltaenv);
1668 memset(&pi, 0, sizeof(pi));
1669 if (restrict_handle_inheritance && stdhandles_count &&
1670 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1671 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1672 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1673 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1674 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1675 UpdateProcThreadAttribute(attr_list, 0,
1676 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1677 stdhandles,
1678 stdhandles_count * sizeof(HANDLE),
1679 NULL, NULL)) {
1680 si.lpAttributeList = attr_list;
1681 flags |= EXTENDED_STARTUPINFO_PRESENT;
1684 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1685 stdhandles_count ? TRUE : FALSE,
1686 flags, wenvblk, dir ? wdir : NULL,
1687 &si.StartupInfo, &pi);
1690 * On Windows 2008 R2, it seems that specifying certain types of handles
1691 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1692 * error. Rather than playing finicky and fragile games, let's just try
1693 * to detect this situation and simply try again without restricting any
1694 * handle inheritance. This is still better than failing to create
1695 * processes.
1697 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1698 DWORD err = GetLastError();
1699 struct strbuf buf = STRBUF_INIT;
1701 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1703 * On Windows 7 and earlier, handles on pipes and character
1704 * devices are inherited automatically, and cannot be
1705 * specified in the thread handle list. Rather than trying
1706 * to catch each and every corner case (and running the
1707 * chance of *still* forgetting a few), let's just fall
1708 * back to creating the process without trying to limit the
1709 * handle inheritance.
1711 !(err == ERROR_INVALID_PARAMETER &&
1712 GetVersion() >> 16 < 9200) &&
1713 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1714 DWORD fl = 0;
1715 int i;
1717 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1719 for (i = 0; i < stdhandles_count; i++) {
1720 HANDLE h = stdhandles[i];
1721 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1722 "handle info (%d) %lx\n", i, h,
1723 GetFileType(h),
1724 GetHandleInformation(h, &fl),
1725 fl);
1727 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1728 "at\nhttps://github.com/git-for-windows/"
1729 "git/issues/new\n\n"
1730 "To suppress this warning, please set "
1731 "the environment variable\n\n"
1732 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1733 "\n");
1735 restrict_handle_inheritance = 0;
1736 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1737 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1738 TRUE, flags, wenvblk, dir ? wdir : NULL,
1739 &si.StartupInfo, &pi);
1740 if (!ret)
1741 errno = err_win_to_posix(GetLastError());
1742 if (ret && buf.len) {
1743 warning("failed to restrict file handles (%ld)\n\n%s",
1744 err, buf.buf);
1746 strbuf_release(&buf);
1747 } else if (!ret)
1748 errno = err_win_to_posix(GetLastError());
1750 if (si.lpAttributeList)
1751 DeleteProcThreadAttributeList(si.lpAttributeList);
1752 if (attr_list)
1753 HeapFree(GetProcessHeap(), 0, attr_list);
1755 free(wenvblk);
1756 free(wargs);
1758 if (!ret)
1759 return -1;
1761 CloseHandle(pi.hThread);
1764 * The process ID is the human-readable identifier of the process
1765 * that we want to present in log and error messages. The handle
1766 * is not useful for this purpose. But we cannot close it, either,
1767 * because it is not possible to turn a process ID into a process
1768 * handle after the process terminated.
1769 * Keep the handle in a list for waitpid.
1771 EnterCriticalSection(&pinfo_cs);
1773 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1774 info->pid = pi.dwProcessId;
1775 info->proc = pi.hProcess;
1776 info->next = pinfo;
1777 pinfo = info;
1779 LeaveCriticalSection(&pinfo_cs);
1781 return (pid_t)pi.dwProcessId;
1784 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1786 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1789 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1790 const char *dir,
1791 int fhin, int fhout, int fherr)
1793 pid_t pid;
1794 char *prog = path_lookup(cmd, 0);
1796 if (!prog) {
1797 errno = ENOENT;
1798 pid = -1;
1800 else {
1801 const char *interpr = parse_interpreter(prog);
1803 if (interpr) {
1804 const char *argv0 = argv[0];
1805 char *iprog = path_lookup(interpr, 1);
1806 argv[0] = prog;
1807 if (!iprog) {
1808 errno = ENOENT;
1809 pid = -1;
1811 else {
1812 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1813 fhin, fhout, fherr);
1814 free(iprog);
1816 argv[0] = argv0;
1818 else
1819 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1820 fhin, fhout, fherr);
1821 free(prog);
1823 return pid;
1826 static int try_shell_exec(const char *cmd, char *const *argv)
1828 const char *interpr = parse_interpreter(cmd);
1829 char *prog;
1830 int pid = 0;
1832 if (!interpr)
1833 return 0;
1834 prog = path_lookup(interpr, 1);
1835 if (prog) {
1836 int exec_id;
1837 int argc = 0;
1838 #ifndef _MSC_VER
1839 const
1840 #endif
1841 char **argv2;
1842 while (argv[argc]) argc++;
1843 ALLOC_ARRAY(argv2, argc + 1);
1844 argv2[0] = (char *)cmd; /* full path to the script file */
1845 COPY_ARRAY(&argv2[1], &argv[1], argc);
1846 exec_id = trace2_exec(prog, argv2);
1847 pid = mingw_spawnv(prog, argv2, 1);
1848 if (pid >= 0) {
1849 int status;
1850 if (waitpid(pid, &status, 0) < 0)
1851 status = 255;
1852 trace2_exec_result(exec_id, status);
1853 exit(status);
1855 trace2_exec_result(exec_id, -1);
1856 pid = 1; /* indicate that we tried but failed */
1857 free(prog);
1858 free(argv2);
1860 return pid;
1863 int mingw_execv(const char *cmd, char *const *argv)
1865 /* check if git_command is a shell script */
1866 if (!try_shell_exec(cmd, argv)) {
1867 int pid, status;
1868 int exec_id;
1870 exec_id = trace2_exec(cmd, (const char **)argv);
1871 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1872 if (pid < 0) {
1873 trace2_exec_result(exec_id, -1);
1874 return -1;
1876 if (waitpid(pid, &status, 0) < 0)
1877 status = 255;
1878 trace2_exec_result(exec_id, status);
1879 exit(status);
1881 return -1;
1884 int mingw_execvp(const char *cmd, char *const *argv)
1886 char *prog = path_lookup(cmd, 0);
1888 if (prog) {
1889 mingw_execv(prog, argv);
1890 free(prog);
1891 } else
1892 errno = ENOENT;
1894 return -1;
1897 int mingw_kill(pid_t pid, int sig)
1899 if (pid > 0 && sig == SIGTERM) {
1900 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1902 if (TerminateProcess(h, -1)) {
1903 CloseHandle(h);
1904 return 0;
1907 errno = err_win_to_posix(GetLastError());
1908 CloseHandle(h);
1909 return -1;
1910 } else if (pid > 0 && sig == 0) {
1911 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1912 if (h) {
1913 CloseHandle(h);
1914 return 0;
1918 errno = EINVAL;
1919 return -1;
1923 * UTF-8 versions of getenv(), putenv() and unsetenv().
1924 * Internally, they use the CRT's stock UNICODE routines
1925 * to avoid data loss.
1927 char *mingw_getenv(const char *name)
1929 #define GETENV_MAX_RETAIN 64
1930 static char *values[GETENV_MAX_RETAIN];
1931 static int value_counter;
1932 int len_key, len_value;
1933 wchar_t *w_key;
1934 char *value;
1935 wchar_t w_value[32768];
1937 if (!name || !*name)
1938 return NULL;
1940 len_key = strlen(name) + 1;
1941 /* We cannot use xcalloc() here because that uses getenv() itself */
1942 w_key = calloc(len_key, sizeof(wchar_t));
1943 if (!w_key)
1944 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1945 xutftowcs(w_key, name, len_key);
1946 /* GetEnvironmentVariableW() only sets the last error upon failure */
1947 SetLastError(ERROR_SUCCESS);
1948 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1949 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1950 free(w_key);
1951 return NULL;
1953 free(w_key);
1955 len_value = len_value * 3 + 1;
1956 /* We cannot use xcalloc() here because that uses getenv() itself */
1957 value = calloc(len_value, sizeof(char));
1958 if (!value)
1959 die("Out of memory, (tried to allocate %u bytes)", len_value);
1960 xwcstoutf(value, w_value, len_value);
1963 * We return `value` which is an allocated value and the caller is NOT
1964 * expecting to have to free it, so we keep a round-robin array,
1965 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1967 free(values[value_counter]);
1968 values[value_counter++] = value;
1969 if (value_counter >= ARRAY_SIZE(values))
1970 value_counter = 0;
1972 return value;
1975 int mingw_putenv(const char *namevalue)
1977 int size;
1978 wchar_t *wide, *equal;
1979 BOOL result;
1981 if (!namevalue || !*namevalue)
1982 return 0;
1984 size = strlen(namevalue) * 2 + 1;
1985 wide = calloc(size, sizeof(wchar_t));
1986 if (!wide)
1987 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1988 xutftowcs(wide, namevalue, size);
1989 equal = wcschr(wide, L'=');
1990 if (!equal)
1991 result = SetEnvironmentVariableW(wide, NULL);
1992 else {
1993 *equal = L'\0';
1994 result = SetEnvironmentVariableW(wide, equal + 1);
1996 free(wide);
1998 if (!result)
1999 errno = err_win_to_posix(GetLastError());
2001 return result ? 0 : -1;
2004 static void ensure_socket_initialization(void)
2006 WSADATA wsa;
2007 static int initialized = 0;
2009 if (initialized)
2010 return;
2012 if (WSAStartup(MAKEWORD(2,2), &wsa))
2013 die("unable to initialize winsock subsystem, error %d",
2014 WSAGetLastError());
2016 atexit((void(*)(void)) WSACleanup);
2017 initialized = 1;
2020 #undef gethostname
2021 int mingw_gethostname(char *name, int namelen)
2023 ensure_socket_initialization();
2024 return gethostname(name, namelen);
2027 #undef gethostbyname
2028 struct hostent *mingw_gethostbyname(const char *host)
2030 ensure_socket_initialization();
2031 return gethostbyname(host);
2034 #undef getaddrinfo
2035 int mingw_getaddrinfo(const char *node, const char *service,
2036 const struct addrinfo *hints, struct addrinfo **res)
2038 ensure_socket_initialization();
2039 return getaddrinfo(node, service, hints, res);
2042 int mingw_socket(int domain, int type, int protocol)
2044 int sockfd;
2045 SOCKET s;
2047 ensure_socket_initialization();
2048 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2049 if (s == INVALID_SOCKET) {
2051 * WSAGetLastError() values are regular BSD error codes
2052 * biased by WSABASEERR.
2053 * However, strerror() does not know about networking
2054 * specific errors, which are values beginning at 38 or so.
2055 * Therefore, we choose to leave the biased error code
2056 * in errno so that _if_ someone looks up the code somewhere,
2057 * then it is at least the number that are usually listed.
2059 errno = WSAGetLastError();
2060 return -1;
2062 /* convert into a file descriptor */
2063 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2064 closesocket(s);
2065 return error("unable to make a socket file descriptor: %s",
2066 strerror(errno));
2068 return sockfd;
2071 #undef connect
2072 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2074 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2075 return connect(s, sa, sz);
2078 #undef bind
2079 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2081 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2082 return bind(s, sa, sz);
2085 #undef setsockopt
2086 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2088 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2089 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2092 #undef shutdown
2093 int mingw_shutdown(int sockfd, int how)
2095 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2096 return shutdown(s, how);
2099 #undef listen
2100 int mingw_listen(int sockfd, int backlog)
2102 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2103 return listen(s, backlog);
2106 #undef accept
2107 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2109 int sockfd2;
2111 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2112 SOCKET s2 = accept(s1, sa, sz);
2114 /* convert into a file descriptor */
2115 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2116 int err = errno;
2117 closesocket(s2);
2118 return error("unable to make a socket file descriptor: %s",
2119 strerror(err));
2121 return sockfd2;
2124 #undef rename
2125 int mingw_rename(const char *pold, const char *pnew)
2127 DWORD attrs, gle;
2128 int tries = 0;
2129 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2130 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2131 return -1;
2134 * Try native rename() first to get errno right.
2135 * It is based on MoveFile(), which cannot overwrite existing files.
2137 if (!_wrename(wpold, wpnew))
2138 return 0;
2139 if (errno != EEXIST)
2140 return -1;
2141 repeat:
2142 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2143 return 0;
2144 /* TODO: translate more errors */
2145 gle = GetLastError();
2146 if (gle == ERROR_ACCESS_DENIED &&
2147 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2148 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2149 DWORD attrsold = GetFileAttributesW(wpold);
2150 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2151 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2152 errno = EISDIR;
2153 else if (!_wrmdir(wpnew))
2154 goto repeat;
2155 return -1;
2157 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2158 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2159 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2160 return 0;
2161 gle = GetLastError();
2162 /* revert file attributes on failure */
2163 SetFileAttributesW(wpnew, attrs);
2166 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2168 * We assume that some other process had the source or
2169 * destination file open at the wrong moment and retry.
2170 * In order to give the other process a higher chance to
2171 * complete its operation, we give up our time slice now.
2172 * If we have to retry again, we do sleep a bit.
2174 Sleep(delay[tries]);
2175 tries++;
2176 goto repeat;
2178 if (gle == ERROR_ACCESS_DENIED &&
2179 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2180 "Should I try again?", pold, pnew))
2181 goto repeat;
2183 errno = EACCES;
2184 return -1;
2188 * Note that this doesn't return the actual pagesize, but
2189 * the allocation granularity. If future Windows specific git code
2190 * needs the real getpagesize function, we need to find another solution.
2192 int mingw_getpagesize(void)
2194 SYSTEM_INFO si;
2195 GetSystemInfo(&si);
2196 return si.dwAllocationGranularity;
2199 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2200 enum EXTENDED_NAME_FORMAT {
2201 NameDisplay = 3,
2202 NameUserPrincipal = 8
2205 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2207 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2208 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2209 static wchar_t wbuffer[1024];
2210 DWORD len;
2212 if (!INIT_PROC_ADDR(GetUserNameExW))
2213 return NULL;
2215 len = ARRAY_SIZE(wbuffer);
2216 if (GetUserNameExW(type, wbuffer, &len)) {
2217 char *converted = xmalloc((len *= 3));
2218 if (xwcstoutf(converted, wbuffer, len) >= 0)
2219 return converted;
2220 free(converted);
2223 return NULL;
2226 char *mingw_query_user_email(void)
2228 return get_extended_user_info(NameUserPrincipal);
2231 struct passwd *getpwuid(int uid)
2233 static unsigned initialized;
2234 static char user_name[100];
2235 static struct passwd *p;
2236 wchar_t buf[100];
2237 DWORD len;
2239 if (initialized)
2240 return p;
2242 len = ARRAY_SIZE(buf);
2243 if (!GetUserNameW(buf, &len)) {
2244 initialized = 1;
2245 return NULL;
2248 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2249 initialized = 1;
2250 return NULL;
2253 p = xmalloc(sizeof(*p));
2254 p->pw_name = user_name;
2255 p->pw_gecos = get_extended_user_info(NameDisplay);
2256 if (!p->pw_gecos)
2257 p->pw_gecos = "unknown";
2258 p->pw_dir = NULL;
2260 initialized = 1;
2261 return p;
2264 static HANDLE timer_event;
2265 static HANDLE timer_thread;
2266 static int timer_interval;
2267 static int one_shot;
2268 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2270 /* The timer works like this:
2271 * The thread, ticktack(), is a trivial routine that most of the time
2272 * only waits to receive the signal to terminate. The main thread tells
2273 * the thread to terminate by setting the timer_event to the signalled
2274 * state.
2275 * But ticktack() interrupts the wait state after the timer's interval
2276 * length to call the signal handler.
2279 static unsigned __stdcall ticktack(void *dummy)
2281 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2282 mingw_raise(SIGALRM);
2283 if (one_shot)
2284 break;
2286 return 0;
2289 static int start_timer_thread(void)
2291 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2292 if (timer_event) {
2293 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2294 if (!timer_thread )
2295 return errno = ENOMEM,
2296 error("cannot start timer thread");
2297 } else
2298 return errno = ENOMEM,
2299 error("cannot allocate resources for timer");
2300 return 0;
2303 static void stop_timer_thread(void)
2305 if (timer_event)
2306 SetEvent(timer_event); /* tell thread to terminate */
2307 if (timer_thread) {
2308 int rc = WaitForSingleObject(timer_thread, 10000);
2309 if (rc == WAIT_TIMEOUT)
2310 error("timer thread did not terminate timely");
2311 else if (rc != WAIT_OBJECT_0)
2312 error("waiting for timer thread failed: %lu",
2313 GetLastError());
2314 CloseHandle(timer_thread);
2316 if (timer_event)
2317 CloseHandle(timer_event);
2318 timer_event = NULL;
2319 timer_thread = NULL;
2322 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2324 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2327 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2329 static const struct timeval zero;
2330 static int atexit_done;
2332 if (out)
2333 return errno = EINVAL,
2334 error("setitimer param 3 != NULL not implemented");
2335 if (!is_timeval_eq(&in->it_interval, &zero) &&
2336 !is_timeval_eq(&in->it_interval, &in->it_value))
2337 return errno = EINVAL,
2338 error("setitimer: it_interval must be zero or eq it_value");
2340 if (timer_thread)
2341 stop_timer_thread();
2343 if (is_timeval_eq(&in->it_value, &zero) &&
2344 is_timeval_eq(&in->it_interval, &zero))
2345 return 0;
2347 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2348 one_shot = is_timeval_eq(&in->it_interval, &zero);
2349 if (!atexit_done) {
2350 atexit(stop_timer_thread);
2351 atexit_done = 1;
2353 return start_timer_thread();
2356 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2358 if (sig != SIGALRM)
2359 return errno = EINVAL,
2360 error("sigaction only implemented for SIGALRM");
2361 if (out)
2362 return errno = EINVAL,
2363 error("sigaction: param 3 != NULL not implemented");
2365 timer_fn = in->sa_handler;
2366 return 0;
2369 #undef signal
2370 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2372 sig_handler_t old;
2374 switch (sig) {
2375 case SIGALRM:
2376 old = timer_fn;
2377 timer_fn = handler;
2378 break;
2380 case SIGINT:
2381 old = sigint_fn;
2382 sigint_fn = handler;
2383 break;
2385 default:
2386 return signal(sig, handler);
2389 return old;
2392 #undef raise
2393 int mingw_raise(int sig)
2395 switch (sig) {
2396 case SIGALRM:
2397 if (timer_fn == SIG_DFL) {
2398 if (isatty(STDERR_FILENO))
2399 fputs("Alarm clock\n", stderr);
2400 exit(128 + SIGALRM);
2401 } else if (timer_fn != SIG_IGN)
2402 timer_fn(SIGALRM);
2403 return 0;
2405 case SIGINT:
2406 if (sigint_fn == SIG_DFL)
2407 exit(128 + SIGINT);
2408 else if (sigint_fn != SIG_IGN)
2409 sigint_fn(SIGINT);
2410 return 0;
2412 #if defined(_MSC_VER)
2413 case SIGILL:
2414 case SIGFPE:
2415 case SIGSEGV:
2416 case SIGTERM:
2417 case SIGBREAK:
2418 case SIGABRT:
2419 case SIGABRT_COMPAT:
2421 * The <signal.h> header in the MS C Runtime defines 8 signals
2422 * as being supported on the platform. Anything else causes an
2423 * "Invalid signal or error" (which in DEBUG builds causes the
2424 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2425 * already know will fail.
2427 return raise(sig);
2428 default:
2429 errno = EINVAL;
2430 return -1;
2432 #else
2434 default:
2435 return raise(sig);
2437 #endif
2442 int link(const char *oldpath, const char *newpath)
2444 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2445 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2446 xutftowcs_path(wnewpath, newpath) < 0)
2447 return -1;
2449 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2450 errno = err_win_to_posix(GetLastError());
2451 return -1;
2453 return 0;
2456 pid_t waitpid(pid_t pid, int *status, int options)
2458 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2459 FALSE, pid);
2460 if (!h) {
2461 errno = ECHILD;
2462 return -1;
2465 if (pid > 0 && options & WNOHANG) {
2466 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2467 CloseHandle(h);
2468 return 0;
2470 options &= ~WNOHANG;
2473 if (options == 0) {
2474 struct pinfo_t **ppinfo;
2475 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2476 CloseHandle(h);
2477 return 0;
2480 if (status)
2481 GetExitCodeProcess(h, (LPDWORD)status);
2483 EnterCriticalSection(&pinfo_cs);
2485 ppinfo = &pinfo;
2486 while (*ppinfo) {
2487 struct pinfo_t *info = *ppinfo;
2488 if (info->pid == pid) {
2489 CloseHandle(info->proc);
2490 *ppinfo = info->next;
2491 free(info);
2492 break;
2494 ppinfo = &info->next;
2497 LeaveCriticalSection(&pinfo_cs);
2499 CloseHandle(h);
2500 return pid;
2502 CloseHandle(h);
2504 errno = EINVAL;
2505 return -1;
2508 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2510 int upos = 0, wpos = 0;
2511 const unsigned char *utf = (const unsigned char*) utfs;
2512 if (!utf || !wcs || wcslen < 1) {
2513 errno = EINVAL;
2514 return -1;
2516 /* reserve space for \0 */
2517 wcslen--;
2518 if (utflen < 0)
2519 utflen = INT_MAX;
2521 while (upos < utflen) {
2522 int c = utf[upos++] & 0xff;
2523 if (utflen == INT_MAX && c == 0)
2524 break;
2526 if (wpos >= wcslen) {
2527 wcs[wpos] = 0;
2528 errno = ERANGE;
2529 return -1;
2532 if (c < 0x80) {
2533 /* ASCII */
2534 wcs[wpos++] = c;
2535 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2536 (utf[upos] & 0xc0) == 0x80) {
2537 /* 2-byte utf-8 */
2538 c = ((c & 0x1f) << 6);
2539 c |= (utf[upos++] & 0x3f);
2540 wcs[wpos++] = c;
2541 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2542 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2543 (utf[upos] & 0xc0) == 0x80 &&
2544 (utf[upos + 1] & 0xc0) == 0x80) {
2545 /* 3-byte utf-8 */
2546 c = ((c & 0x0f) << 12);
2547 c |= ((utf[upos++] & 0x3f) << 6);
2548 c |= (utf[upos++] & 0x3f);
2549 wcs[wpos++] = c;
2550 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2551 wpos + 1 < wcslen &&
2552 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2553 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2554 (utf[upos] & 0xc0) == 0x80 &&
2555 (utf[upos + 1] & 0xc0) == 0x80 &&
2556 (utf[upos + 2] & 0xc0) == 0x80) {
2557 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2558 c = ((c & 0x07) << 18);
2559 c |= ((utf[upos++] & 0x3f) << 12);
2560 c |= ((utf[upos++] & 0x3f) << 6);
2561 c |= (utf[upos++] & 0x3f);
2562 c -= 0x10000;
2563 wcs[wpos++] = 0xd800 | (c >> 10);
2564 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2565 } else if (c >= 0xa0) {
2566 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2567 wcs[wpos++] = c;
2568 } else {
2569 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2570 static const char *hex = "0123456789abcdef";
2571 wcs[wpos++] = hex[c >> 4];
2572 if (wpos < wcslen)
2573 wcs[wpos++] = hex[c & 0x0f];
2576 wcs[wpos] = 0;
2577 return wpos;
2580 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2582 if (!wcs || !utf || utflen < 1) {
2583 errno = EINVAL;
2584 return -1;
2586 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2587 if (utflen)
2588 return utflen - 1;
2589 errno = ERANGE;
2590 return -1;
2593 static void setup_windows_environment(void)
2595 char *tmp = getenv("TMPDIR");
2597 /* on Windows it is TMP and TEMP */
2598 if (!tmp) {
2599 if (!(tmp = getenv("TMP")))
2600 tmp = getenv("TEMP");
2601 if (tmp) {
2602 setenv("TMPDIR", tmp, 1);
2603 tmp = getenv("TMPDIR");
2607 if (tmp) {
2609 * Convert all dir separators to forward slashes,
2610 * to help shell commands called from the Git
2611 * executable (by not mistaking the dir separators
2612 * for escape characters).
2614 convert_slashes(tmp);
2617 /* simulate TERM to enable auto-color (see color.c) */
2618 if (!getenv("TERM"))
2619 setenv("TERM", "cygwin", 1);
2621 /* calculate HOME if not set */
2622 if (!getenv("HOME")) {
2624 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2625 * location, thus also check if the path exists (i.e. is not
2626 * disconnected)
2628 if ((tmp = getenv("HOMEDRIVE"))) {
2629 struct strbuf buf = STRBUF_INIT;
2630 strbuf_addstr(&buf, tmp);
2631 if ((tmp = getenv("HOMEPATH"))) {
2632 strbuf_addstr(&buf, tmp);
2633 if (is_directory(buf.buf))
2634 setenv("HOME", buf.buf, 1);
2635 else
2636 tmp = NULL; /* use $USERPROFILE */
2638 strbuf_release(&buf);
2640 /* use $USERPROFILE if the home share is not available */
2641 if (!tmp && (tmp = getenv("USERPROFILE")))
2642 setenv("HOME", tmp, 1);
2646 static PSID get_current_user_sid(void)
2648 HANDLE token;
2649 DWORD len = 0;
2650 PSID result = NULL;
2652 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2653 return NULL;
2655 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2656 TOKEN_USER *info = xmalloc((size_t)len);
2657 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2658 len = GetLengthSid(info->User.Sid);
2659 result = xmalloc(len);
2660 if (!CopySid(len, result, info->User.Sid)) {
2661 error(_("failed to copy SID (%ld)"),
2662 GetLastError());
2663 FREE_AND_NULL(result);
2666 FREE_AND_NULL(info);
2668 CloseHandle(token);
2670 return result;
2673 int is_path_owned_by_current_sid(const char *path)
2675 WCHAR wpath[MAX_PATH];
2676 PSID sid = NULL;
2677 PSECURITY_DESCRIPTOR descriptor = NULL;
2678 DWORD err;
2680 static wchar_t home[MAX_PATH];
2682 int result = 0;
2684 if (xutftowcs_path(wpath, path) < 0)
2685 return 0;
2688 * On Windows, the home directory is owned by the administrator, but for
2689 * all practical purposes, it belongs to the user. Do pretend that it is
2690 * owned by the user.
2692 if (!*home) {
2693 DWORD size = ARRAY_SIZE(home);
2694 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2695 if (!len || len > size)
2696 wcscpy(home, L"::N/A::");
2698 if (!wcsicmp(wpath, home))
2699 return 1;
2701 /* Get the owner SID */
2702 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2703 OWNER_SECURITY_INFORMATION |
2704 DACL_SECURITY_INFORMATION,
2705 &sid, NULL, NULL, NULL, &descriptor);
2707 if (err != ERROR_SUCCESS)
2708 error(_("failed to get owner for '%s' (%ld)"), path, err);
2709 else if (sid && IsValidSid(sid)) {
2710 /* Now, verify that the SID matches the current user's */
2711 static PSID current_user_sid;
2713 if (!current_user_sid)
2714 current_user_sid = get_current_user_sid();
2716 if (current_user_sid &&
2717 IsValidSid(current_user_sid) &&
2718 EqualSid(sid, current_user_sid))
2719 result = 1;
2723 * We can release the security descriptor struct only now because `sid`
2724 * actually points into this struct.
2726 if (descriptor)
2727 LocalFree(descriptor);
2729 return result;
2732 int is_valid_win32_path(const char *path, int allow_literal_nul)
2734 const char *p = path;
2735 int preceding_space_or_period = 0, i = 0, periods = 0;
2737 if (!protect_ntfs)
2738 return 1;
2740 skip_dos_drive_prefix((char **)&path);
2741 goto segment_start;
2743 for (;;) {
2744 char c = *(path++);
2745 switch (c) {
2746 case '\0':
2747 case '/': case '\\':
2748 /* cannot end in ` ` or `.`, except for `.` and `..` */
2749 if (preceding_space_or_period &&
2750 (i != periods || periods > 2))
2751 return 0;
2752 if (!c)
2753 return 1;
2755 i = periods = preceding_space_or_period = 0;
2757 segment_start:
2758 switch (*path) {
2759 case 'a': case 'A': /* AUX */
2760 if (((c = path[++i]) != 'u' && c != 'U') ||
2761 ((c = path[++i]) != 'x' && c != 'X')) {
2762 not_a_reserved_name:
2763 path += i;
2764 continue;
2766 break;
2767 case 'c': case 'C':
2768 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2769 if ((c = path[++i]) != 'o' && c != 'O')
2770 goto not_a_reserved_name;
2771 c = path[++i];
2772 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2773 c = path[++i];
2774 if (c < '1' || c > '9')
2775 goto not_a_reserved_name;
2776 } else if (c == 'n' || c == 'N') { /* CON */
2777 c = path[i + 1];
2778 if ((c == 'i' || c == 'I') &&
2779 ((c = path[i + 2]) == 'n' ||
2780 c == 'N') &&
2781 path[i + 3] == '$')
2782 i += 3; /* CONIN$ */
2783 else if ((c == 'o' || c == 'O') &&
2784 ((c = path[i + 2]) == 'u' ||
2785 c == 'U') &&
2786 ((c = path[i + 3]) == 't' ||
2787 c == 'T') &&
2788 path[i + 4] == '$')
2789 i += 4; /* CONOUT$ */
2790 } else
2791 goto not_a_reserved_name;
2792 break;
2793 case 'l': case 'L': /* LPT<N> */
2794 if (((c = path[++i]) != 'p' && c != 'P') ||
2795 ((c = path[++i]) != 't' && c != 'T') ||
2796 !isdigit(path[++i]))
2797 goto not_a_reserved_name;
2798 break;
2799 case 'n': case 'N': /* NUL */
2800 if (((c = path[++i]) != 'u' && c != 'U') ||
2801 ((c = path[++i]) != 'l' && c != 'L') ||
2802 (allow_literal_nul &&
2803 !path[i + 1] && p == path))
2804 goto not_a_reserved_name;
2805 break;
2806 case 'p': case 'P': /* PRN */
2807 if (((c = path[++i]) != 'r' && c != 'R') ||
2808 ((c = path[++i]) != 'n' && c != 'N'))
2809 goto not_a_reserved_name;
2810 break;
2811 default:
2812 continue;
2816 * So far, this looks like a reserved name. Let's see
2817 * whether it actually is one: trailing spaces, a file
2818 * extension, or an NTFS Alternate Data Stream do not
2819 * matter, the name is still reserved if any of those
2820 * follow immediately after the actual name.
2822 i++;
2823 if (path[i] == ' ') {
2824 preceding_space_or_period = 1;
2825 while (path[++i] == ' ')
2826 ; /* skip all spaces */
2829 c = path[i];
2830 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
2831 goto not_a_reserved_name;
2833 /* contains reserved name */
2834 return 0;
2835 case '.':
2836 periods++;
2837 /* fallthru */
2838 case ' ':
2839 preceding_space_or_period = 1;
2840 i++;
2841 continue;
2842 case ':': /* DOS drive prefix was already skipped */
2843 case '<': case '>': case '"': case '|': case '?': case '*':
2844 /* illegal character */
2845 return 0;
2846 default:
2847 if (c > '\0' && c < '\x20')
2848 /* illegal character */
2849 return 0;
2851 preceding_space_or_period = 0;
2852 i++;
2856 #if !defined(_MSC_VER)
2858 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2859 * mingw startup code, see init.c in mingw runtime).
2861 int _CRT_glob = 0;
2862 #endif
2864 static NORETURN void die_startup(void)
2866 fputs("fatal: not enough memory for initialization", stderr);
2867 exit(128);
2870 static void *malloc_startup(size_t size)
2872 void *result = malloc(size);
2873 if (!result)
2874 die_startup();
2875 return result;
2878 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2880 len = xwcstoutf(buffer, wcs, len) + 1;
2881 return memcpy(malloc_startup(len), buffer, len);
2884 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2885 DWORD desired_access, DWORD flags)
2887 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2888 wchar_t buf[MAX_PATH];
2889 DWORD max = ARRAY_SIZE(buf);
2890 HANDLE handle;
2891 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2893 if (!ret || ret >= max)
2894 return;
2896 /* make sure this does not leak into child processes */
2897 SetEnvironmentVariableW(key, NULL);
2898 if (!wcscmp(buf, L"off")) {
2899 close(fd);
2900 handle = GetStdHandle(std_id);
2901 if (handle != INVALID_HANDLE_VALUE)
2902 CloseHandle(handle);
2903 return;
2905 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2906 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2907 if (handle == INVALID_HANDLE_VALUE) {
2908 close(fd);
2909 handle = GetStdHandle(std_id);
2910 if (handle != INVALID_HANDLE_VALUE)
2911 CloseHandle(handle);
2912 } else {
2913 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2914 SetStdHandle(std_id, handle);
2915 dup2(new_fd, fd);
2916 /* do *not* close the new_fd: that would close stdout */
2918 return;
2920 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2921 flags, NULL);
2922 if (handle != INVALID_HANDLE_VALUE) {
2923 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2924 SetStdHandle(std_id, handle);
2925 dup2(new_fd, fd);
2926 close(new_fd);
2930 static void maybe_redirect_std_handles(void)
2932 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2933 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2934 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2935 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2936 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2937 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2940 #ifdef _MSC_VER
2941 #ifdef _DEBUG
2942 #include <crtdbg.h>
2943 #endif
2944 #endif
2947 * We implement wmain() and compile with -municode, which would
2948 * normally ignore main(), but we call the latter from the former
2949 * so that we can handle non-ASCII command-line parameters
2950 * appropriately.
2952 * To be more compatible with the core git code, we convert
2953 * argv into UTF8 and pass them directly to main().
2955 int wmain(int argc, const wchar_t **wargv)
2957 int i, maxlen, exit_status;
2958 char *buffer, **save;
2959 const char **argv;
2961 trace2_initialize_clock();
2963 #ifdef _MSC_VER
2964 #ifdef _DEBUG
2965 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2966 #endif
2968 #ifdef USE_MSVC_CRTDBG
2969 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2970 #endif
2971 #endif
2973 maybe_redirect_std_handles();
2975 /* determine size of argv and environ conversion buffer */
2976 maxlen = wcslen(wargv[0]);
2977 for (i = 1; i < argc; i++)
2978 maxlen = max(maxlen, wcslen(wargv[i]));
2980 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2981 maxlen = 3 * maxlen + 1;
2982 buffer = malloc_startup(maxlen);
2985 * Create a UTF-8 version of w_argv. Also create a "save" copy
2986 * to remember all the string pointers because parse_options()
2987 * will remove claimed items from the argv that we pass down.
2989 ALLOC_ARRAY(argv, argc + 1);
2990 ALLOC_ARRAY(save, argc + 1);
2991 for (i = 0; i < argc; i++)
2992 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2993 argv[i] = save[i] = NULL;
2994 free(buffer);
2996 /* fix Windows specific environment settings */
2997 setup_windows_environment();
2999 unset_environment_variables = xstrdup("PERL5LIB");
3001 /* initialize critical section for waitpid pinfo_t list */
3002 InitializeCriticalSection(&pinfo_cs);
3004 /* set up default file mode and file modes for stdin/out/err */
3005 _fmode = _O_BINARY;
3006 _setmode(_fileno(stdin), _O_BINARY);
3007 _setmode(_fileno(stdout), _O_BINARY);
3008 _setmode(_fileno(stderr), _O_BINARY);
3010 /* initialize Unicode console */
3011 winansi_init();
3013 /* invoke the real main() using our utf8 version of argv. */
3014 exit_status = main(argc, argv);
3016 for (i = 0; i < argc; i++)
3017 free(save[i]);
3018 free(save);
3019 free(argv);
3021 return exit_status;
3024 int uname(struct utsname *buf)
3026 unsigned v = (unsigned)GetVersion();
3027 memset(buf, 0, sizeof(*buf));
3028 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3029 xsnprintf(buf->release, sizeof(buf->release),
3030 "%u.%u", v & 0xff, (v >> 8) & 0xff);
3031 /* assuming NT variants only.. */
3032 xsnprintf(buf->version, sizeof(buf->version),
3033 "%u", (v >> 16) & 0x7fff);
3034 return 0;