compat/fsmonitor/fsm-listen-darwin: add MacOS header files for FSEvent
[git.git] / compat / mingw.c
blob03af369b2b972fdce2476b256ef3679ec88e025e
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include <wchar.h>
5 #include "../strbuf.h"
6 #include "../run-command.h"
7 #include "../cache.h"
8 #include "win32/lazyload.h"
9 #include "../config.h"
10 #include "dir.h"
11 #define SECURITY_WIN32
12 #include <sspi.h>
14 #define HCAST(type, handle) ((type)(intptr_t)handle)
16 static const int delay[] = { 0, 1, 10, 20, 40 };
18 void open_in_gdb(void)
20 static struct child_process cp = CHILD_PROCESS_INIT;
21 extern char *_pgmptr;
23 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
24 strvec_pushf(&cp.args, "--pid=%d", getpid());
25 cp.clean_on_exit = 1;
26 if (start_command(&cp) < 0)
27 die_errno("Could not start gdb");
28 sleep(1);
31 int err_win_to_posix(DWORD winerr)
33 int error = ENOSYS;
34 switch(winerr) {
35 case ERROR_ACCESS_DENIED: error = EACCES; break;
36 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
37 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
38 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
39 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
40 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
41 case ERROR_BAD_COMMAND: error = EIO; break;
42 case ERROR_BAD_DEVICE: error = ENODEV; break;
43 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
44 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
45 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
46 case ERROR_BAD_LENGTH: error = EINVAL; break;
47 case ERROR_BAD_PATHNAME: error = ENOENT; break;
48 case ERROR_BAD_PIPE: error = EPIPE; break;
49 case ERROR_BAD_UNIT: error = ENODEV; break;
50 case ERROR_BAD_USERNAME: error = EINVAL; break;
51 case ERROR_BROKEN_PIPE: error = EPIPE; break;
52 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
53 case ERROR_BUSY: error = EBUSY; break;
54 case ERROR_BUSY_DRIVE: error = EBUSY; break;
55 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
56 case ERROR_CANNOT_MAKE: error = EACCES; break;
57 case ERROR_CANTOPEN: error = EIO; break;
58 case ERROR_CANTREAD: error = EIO; break;
59 case ERROR_CANTWRITE: error = EIO; break;
60 case ERROR_CRC: error = EIO; break;
61 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
62 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
63 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
64 case ERROR_DIRECTORY: error = EINVAL; break;
65 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
66 case ERROR_DISK_CHANGE: error = EIO; break;
67 case ERROR_DISK_FULL: error = ENOSPC; break;
68 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
69 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
70 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
71 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
72 case ERROR_FILE_EXISTS: error = EEXIST; break;
73 case ERROR_FILE_INVALID: error = ENODEV; break;
74 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
75 case ERROR_GEN_FAILURE: error = EIO; break;
76 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
77 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
78 case ERROR_INVALID_ACCESS: error = EACCES; break;
79 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
80 case ERROR_INVALID_BLOCK: error = EFAULT; break;
81 case ERROR_INVALID_DATA: error = EINVAL; break;
82 case ERROR_INVALID_DRIVE: error = ENODEV; break;
83 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
84 case ERROR_INVALID_FLAGS: error = EINVAL; break;
85 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
86 case ERROR_INVALID_HANDLE: error = EBADF; break;
87 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
88 case ERROR_INVALID_NAME: error = EINVAL; break;
89 case ERROR_INVALID_OWNER: error = EINVAL; break;
90 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
91 case ERROR_INVALID_PASSWORD: error = EPERM; break;
92 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
93 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
94 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
95 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
96 case ERROR_IO_DEVICE: error = EIO; break;
97 case ERROR_IO_INCOMPLETE: error = EINTR; break;
98 case ERROR_LOCKED: error = EBUSY; break;
99 case ERROR_LOCK_VIOLATION: error = EACCES; break;
100 case ERROR_LOGON_FAILURE: error = EACCES; break;
101 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
102 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
103 case ERROR_MORE_DATA: error = EPIPE; break;
104 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
105 case ERROR_NOACCESS: error = EFAULT; break;
106 case ERROR_NONE_MAPPED: error = EINVAL; break;
107 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
108 case ERROR_NOT_READY: error = EAGAIN; break;
109 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
110 case ERROR_NO_DATA: error = EPIPE; break;
111 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
112 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
113 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
114 case ERROR_OPEN_FAILED: error = EIO; break;
115 case ERROR_OPEN_FILES: error = EBUSY; break;
116 case ERROR_OPERATION_ABORTED: error = EINTR; break;
117 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
118 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
119 case ERROR_PATH_BUSY: error = EBUSY; break;
120 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
121 case ERROR_PIPE_BUSY: error = EBUSY; break;
122 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
123 case ERROR_PIPE_LISTENING: error = EPIPE; break;
124 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
125 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
126 case ERROR_READ_FAULT: error = EIO; break;
127 case ERROR_SEEK: error = EIO; break;
128 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
129 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
130 case ERROR_SHARING_VIOLATION: error = EACCES; break;
131 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
132 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
133 case ERROR_SWAPERROR: error = ENOENT; break;
134 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
135 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
136 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
137 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
138 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
139 case ERROR_WRITE_FAULT: error = EIO; break;
140 case ERROR_WRITE_PROTECT: error = EROFS; break;
142 return error;
145 static inline int is_file_in_use_error(DWORD errcode)
147 switch (errcode) {
148 case ERROR_SHARING_VIOLATION:
149 case ERROR_ACCESS_DENIED:
150 return 1;
153 return 0;
156 static int read_yes_no_answer(void)
158 char answer[1024];
160 if (fgets(answer, sizeof(answer), stdin)) {
161 size_t answer_len = strlen(answer);
162 int got_full_line = 0, c;
164 /* remove the newline */
165 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
166 answer[answer_len-2] = '\0';
167 got_full_line = 1;
168 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
169 answer[answer_len-1] = '\0';
170 got_full_line = 1;
172 /* flush the buffer in case we did not get the full line */
173 if (!got_full_line)
174 while ((c = getchar()) != EOF && c != '\n')
176 } else
177 /* we could not read, return the
178 * default answer which is no */
179 return 0;
181 if (tolower(answer[0]) == 'y' && !answer[1])
182 return 1;
183 if (!strncasecmp(answer, "yes", sizeof(answer)))
184 return 1;
185 if (tolower(answer[0]) == 'n' && !answer[1])
186 return 0;
187 if (!strncasecmp(answer, "no", sizeof(answer)))
188 return 0;
190 /* did not find an answer we understand */
191 return -1;
194 static int ask_yes_no_if_possible(const char *format, ...)
196 char question[4096];
197 const char *retry_hook[] = { NULL, NULL, NULL };
198 va_list args;
200 va_start(args, format);
201 vsnprintf(question, sizeof(question), format, args);
202 va_end(args);
204 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
205 retry_hook[1] = question;
206 return !run_command_v_opt(retry_hook, 0);
209 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
210 return 0;
212 while (1) {
213 int answer;
214 fprintf(stderr, "%s (y/n) ", question);
216 if ((answer = read_yes_no_answer()) >= 0)
217 return answer;
219 fprintf(stderr, "Sorry, I did not understand your answer. "
220 "Please type 'y' or 'n'\n");
224 /* Windows only */
225 enum hide_dotfiles_type {
226 HIDE_DOTFILES_FALSE = 0,
227 HIDE_DOTFILES_TRUE,
228 HIDE_DOTFILES_DOTGITONLY
231 static int core_restrict_inherited_handles = -1;
232 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
233 static char *unset_environment_variables;
235 int mingw_core_config(const char *var, const char *value, void *cb)
237 if (!strcmp(var, "core.hidedotfiles")) {
238 if (value && !strcasecmp(value, "dotgitonly"))
239 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
240 else
241 hide_dotfiles = git_config_bool(var, value);
242 return 0;
245 if (!strcmp(var, "core.unsetenvvars")) {
246 free(unset_environment_variables);
247 unset_environment_variables = xstrdup(value);
248 return 0;
251 if (!strcmp(var, "core.restrictinheritedhandles")) {
252 if (value && !strcasecmp(value, "auto"))
253 core_restrict_inherited_handles = -1;
254 else
255 core_restrict_inherited_handles =
256 git_config_bool(var, value);
257 return 0;
260 return 0;
263 /* Normalizes NT paths as returned by some low-level APIs. */
264 static wchar_t *normalize_ntpath(wchar_t *wbuf)
266 int i;
267 /* fix absolute path prefixes */
268 if (wbuf[0] == '\\') {
269 /* strip NT namespace prefixes */
270 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
271 !wcsncmp(wbuf, L"\\\\?\\", 4))
272 wbuf += 4;
273 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
274 wbuf += 12;
275 /* replace remaining '...UNC\' with '\\' */
276 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
277 wbuf += 2;
278 *wbuf = '\\';
281 /* convert backslashes to slashes */
282 for (i = 0; wbuf[i]; i++)
283 if (wbuf[i] == '\\')
284 wbuf[i] = '/';
285 return wbuf;
288 int mingw_unlink(const char *pathname)
290 int ret, tries = 0;
291 wchar_t wpathname[MAX_PATH];
292 if (xutftowcs_path(wpathname, pathname) < 0)
293 return -1;
295 if (DeleteFileW(wpathname))
296 return 0;
298 /* read-only files cannot be removed */
299 _wchmod(wpathname, 0666);
300 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
301 if (!is_file_in_use_error(GetLastError()))
302 break;
304 * We assume that some other process had the source or
305 * destination file open at the wrong moment and retry.
306 * In order to give the other process a higher chance to
307 * complete its operation, we give up our time slice now.
308 * If we have to retry again, we do sleep a bit.
310 Sleep(delay[tries]);
311 tries++;
313 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
314 ask_yes_no_if_possible("Unlink of file '%s' failed. "
315 "Should I try again?", pathname))
316 ret = _wunlink(wpathname);
317 return ret;
320 static int is_dir_empty(const wchar_t *wpath)
322 WIN32_FIND_DATAW findbuf;
323 HANDLE handle;
324 wchar_t wbuf[MAX_PATH + 2];
325 wcscpy(wbuf, wpath);
326 wcscat(wbuf, L"\\*");
327 handle = FindFirstFileW(wbuf, &findbuf);
328 if (handle == INVALID_HANDLE_VALUE)
329 return GetLastError() == ERROR_NO_MORE_FILES;
331 while (!wcscmp(findbuf.cFileName, L".") ||
332 !wcscmp(findbuf.cFileName, L".."))
333 if (!FindNextFileW(handle, &findbuf)) {
334 DWORD err = GetLastError();
335 FindClose(handle);
336 return err == ERROR_NO_MORE_FILES;
338 FindClose(handle);
339 return 0;
342 int mingw_rmdir(const char *pathname)
344 int ret, tries = 0;
345 wchar_t wpathname[MAX_PATH];
346 struct stat st;
349 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
350 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
351 * symbolic link (if it points to a directory).
353 * This behavior breaks the assumption of e.g. `remove_path()` which
354 * upon successful deletion of a file will attempt to remove its parent
355 * directories recursively until failure (which usually happens when
356 * the directory is not empty).
358 * Therefore, before calling `_wrmdir()`, we first check if the path is
359 * a symbolic link. If it is, we exit and return the same error as
360 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
362 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
363 errno = ENOTDIR;
364 return -1;
367 if (xutftowcs_path(wpathname, pathname) < 0)
368 return -1;
370 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
371 if (!is_file_in_use_error(GetLastError()))
372 errno = err_win_to_posix(GetLastError());
373 if (errno != EACCES)
374 break;
375 if (!is_dir_empty(wpathname)) {
376 errno = ENOTEMPTY;
377 break;
380 * We assume that some other process had the source or
381 * destination file open at the wrong moment and retry.
382 * In order to give the other process a higher chance to
383 * complete its operation, we give up our time slice now.
384 * If we have to retry again, we do sleep a bit.
386 Sleep(delay[tries]);
387 tries++;
389 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
390 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
391 "Should I try again?", pathname))
392 ret = _wrmdir(wpathname);
393 if (!ret)
394 invalidate_lstat_cache();
395 return ret;
398 static inline int needs_hiding(const char *path)
400 const char *basename;
402 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
403 return 0;
405 /* We cannot use basename(), as it would remove trailing slashes */
406 win32_skip_dos_drive_prefix((char **)&path);
407 if (!*path)
408 return 0;
410 for (basename = path; *path; path++)
411 if (is_dir_sep(*path)) {
412 do {
413 path++;
414 } while (is_dir_sep(*path));
415 /* ignore trailing slashes */
416 if (*path)
417 basename = path;
418 else
419 break;
422 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
423 return *basename == '.';
425 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
426 return !strncasecmp(".git", basename, 4) &&
427 (!basename[4] || is_dir_sep(basename[4]));
430 static int set_hidden_flag(const wchar_t *path, int set)
432 DWORD original = GetFileAttributesW(path), modified;
433 if (set)
434 modified = original | FILE_ATTRIBUTE_HIDDEN;
435 else
436 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
437 if (original == modified || SetFileAttributesW(path, modified))
438 return 0;
439 errno = err_win_to_posix(GetLastError());
440 return -1;
443 int mingw_mkdir(const char *path, int mode)
445 int ret;
446 wchar_t wpath[MAX_PATH];
448 if (!is_valid_win32_path(path, 0)) {
449 errno = EINVAL;
450 return -1;
453 if (xutftowcs_path(wpath, path) < 0)
454 return -1;
455 ret = _wmkdir(wpath);
456 if (!ret && needs_hiding(path))
457 return set_hidden_flag(wpath, 1);
458 return ret;
462 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
463 * is documented in [1] as opening a writable file handle in append mode.
464 * (It is believed that) this is atomic since it is maintained by the
465 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
467 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
469 * This trick does not appear to work for named pipes. Instead it creates
470 * a named pipe client handle that cannot be written to. Callers should
471 * just use the regular _wopen() for them. (And since client handle gets
472 * bound to a unique server handle, it isn't really an issue.)
474 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
476 HANDLE handle;
477 int fd;
478 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
480 /* only these flags are supported */
481 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
482 return errno = ENOSYS, -1;
485 * FILE_SHARE_WRITE is required to permit child processes
486 * to append to the file.
488 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
489 FILE_SHARE_WRITE | FILE_SHARE_READ,
490 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
491 if (handle == INVALID_HANDLE_VALUE) {
492 DWORD err = GetLastError();
495 * Some network storage solutions (e.g. Isilon) might return
496 * ERROR_INVALID_PARAMETER instead of expected error
497 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
498 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
500 if (err == ERROR_INVALID_PARAMETER)
501 err = ERROR_PATH_NOT_FOUND;
503 errno = err_win_to_posix(err);
504 return -1;
508 * No O_APPEND here, because the CRT uses it only to reset the
509 * file pointer to EOF before each write(); but that is not
510 * necessary (and may lead to races) for a file created with
511 * FILE_APPEND_DATA.
513 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
514 if (fd < 0)
515 CloseHandle(handle);
516 return fd;
520 * Does the pathname map to the local named pipe filesystem?
521 * That is, does it have a "//./pipe/" prefix?
523 static int is_local_named_pipe_path(const char *filename)
525 return (is_dir_sep(filename[0]) &&
526 is_dir_sep(filename[1]) &&
527 filename[2] == '.' &&
528 is_dir_sep(filename[3]) &&
529 !strncasecmp(filename+4, "pipe", 4) &&
530 is_dir_sep(filename[8]) &&
531 filename[9]);
534 int mingw_open (const char *filename, int oflags, ...)
536 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
537 va_list args;
538 unsigned mode;
539 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
540 wchar_t wfilename[MAX_PATH];
541 open_fn_t open_fn;
543 va_start(args, oflags);
544 mode = va_arg(args, int);
545 va_end(args);
547 if (!is_valid_win32_path(filename, !create)) {
548 errno = create ? EINVAL : ENOENT;
549 return -1;
552 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
553 open_fn = mingw_open_append;
554 else
555 open_fn = _wopen;
557 if (filename && !strcmp(filename, "/dev/null"))
558 wcscpy(wfilename, L"nul");
559 else if (xutftowcs_path(wfilename, filename) < 0)
560 return -1;
562 fd = open_fn(wfilename, oflags, mode);
564 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
565 DWORD attrs = GetFileAttributesW(wfilename);
566 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
567 errno = EISDIR;
569 if ((oflags & O_CREAT) && needs_hiding(filename)) {
571 * Internally, _wopen() uses the CreateFile() API which errors
572 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
573 * specified and an already existing file's attributes do not
574 * match *exactly*. As there is no mode or flag we can set that
575 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
576 * again *without* the O_CREAT flag (that corresponds to the
577 * CREATE_ALWAYS flag of CreateFile()).
579 if (fd < 0 && errno == EACCES)
580 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
581 if (fd >= 0 && set_hidden_flag(wfilename, 1))
582 warning("could not mark '%s' as hidden.", filename);
584 return fd;
587 static BOOL WINAPI ctrl_ignore(DWORD type)
589 return TRUE;
592 #undef fgetc
593 int mingw_fgetc(FILE *stream)
595 int ch;
596 if (!isatty(_fileno(stream)))
597 return fgetc(stream);
599 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
600 while (1) {
601 ch = fgetc(stream);
602 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
603 break;
605 /* Ctrl+C was pressed, simulate SIGINT and retry */
606 mingw_raise(SIGINT);
608 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
609 return ch;
612 #undef fopen
613 FILE *mingw_fopen (const char *filename, const char *otype)
615 int hide = needs_hiding(filename);
616 FILE *file;
617 wchar_t wfilename[MAX_PATH], wotype[4];
618 if (filename && !strcmp(filename, "/dev/null"))
619 wcscpy(wfilename, L"nul");
620 else if (!is_valid_win32_path(filename, 1)) {
621 int create = otype && strchr(otype, 'w');
622 errno = create ? EINVAL : ENOENT;
623 return NULL;
624 } else if (xutftowcs_path(wfilename, filename) < 0)
625 return NULL;
627 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
628 return NULL;
630 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
631 error("could not unhide %s", filename);
632 return NULL;
634 file = _wfopen(wfilename, wotype);
635 if (!file && GetLastError() == ERROR_INVALID_NAME)
636 errno = ENOENT;
637 if (file && hide && set_hidden_flag(wfilename, 1))
638 warning("could not mark '%s' as hidden.", filename);
639 return file;
642 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
644 int hide = needs_hiding(filename);
645 FILE *file;
646 wchar_t wfilename[MAX_PATH], wotype[4];
647 if (filename && !strcmp(filename, "/dev/null"))
648 wcscpy(wfilename, L"nul");
649 else if (!is_valid_win32_path(filename, 1)) {
650 int create = otype && strchr(otype, 'w');
651 errno = create ? EINVAL : ENOENT;
652 return NULL;
653 } else if (xutftowcs_path(wfilename, filename) < 0)
654 return NULL;
656 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
657 return NULL;
659 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
660 error("could not unhide %s", filename);
661 return NULL;
663 file = _wfreopen(wfilename, wotype, stream);
664 if (file && hide && set_hidden_flag(wfilename, 1))
665 warning("could not mark '%s' as hidden.", filename);
666 return file;
669 #undef fflush
670 int mingw_fflush(FILE *stream)
672 int ret = fflush(stream);
675 * write() is used behind the scenes of stdio output functions.
676 * Since git code does not check for errors after each stdio write
677 * operation, it can happen that write() is called by a later
678 * stdio function even if an earlier write() call failed. In the
679 * case of a pipe whose readable end was closed, only the first
680 * call to write() reports EPIPE on Windows. Subsequent write()
681 * calls report EINVAL. It is impossible to notice whether this
682 * fflush invocation triggered such a case, therefore, we have to
683 * catch all EINVAL errors whole-sale.
685 if (ret && errno == EINVAL)
686 errno = EPIPE;
688 return ret;
691 #undef write
692 ssize_t mingw_write(int fd, const void *buf, size_t len)
694 ssize_t result = write(fd, buf, len);
696 if (result < 0 && errno == EINVAL && buf) {
697 /* check if fd is a pipe */
698 HANDLE h = (HANDLE) _get_osfhandle(fd);
699 if (GetFileType(h) == FILE_TYPE_PIPE)
700 errno = EPIPE;
701 else
702 errno = EINVAL;
705 return result;
708 int mingw_access(const char *filename, int mode)
710 wchar_t wfilename[MAX_PATH];
711 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
712 return 0;
713 if (xutftowcs_path(wfilename, filename) < 0)
714 return -1;
715 /* X_OK is not supported by the MSVCRT version */
716 return _waccess(wfilename, mode & ~X_OK);
719 int mingw_chdir(const char *dirname)
721 wchar_t wdirname[MAX_PATH];
722 if (xutftowcs_path(wdirname, dirname) < 0)
723 return -1;
724 return _wchdir(wdirname);
727 int mingw_chmod(const char *filename, int mode)
729 wchar_t wfilename[MAX_PATH];
730 if (xutftowcs_path(wfilename, filename) < 0)
731 return -1;
732 return _wchmod(wfilename, mode);
736 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
737 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
739 static inline long long filetime_to_hnsec(const FILETIME *ft)
741 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
742 /* Windows to Unix Epoch conversion */
743 return winTime - 116444736000000000LL;
746 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
748 long long hnsec = filetime_to_hnsec(ft);
749 ts->tv_sec = (time_t)(hnsec / 10000000);
750 ts->tv_nsec = (hnsec % 10000000) * 100;
754 * Verifies that safe_create_leading_directories() would succeed.
756 static int has_valid_directory_prefix(wchar_t *wfilename)
758 int n = wcslen(wfilename);
760 while (n > 0) {
761 wchar_t c = wfilename[--n];
762 DWORD attributes;
764 if (!is_dir_sep(c))
765 continue;
767 wfilename[n] = L'\0';
768 attributes = GetFileAttributesW(wfilename);
769 wfilename[n] = c;
770 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
771 attributes == FILE_ATTRIBUTE_DEVICE)
772 return 1;
773 if (attributes == INVALID_FILE_ATTRIBUTES)
774 switch (GetLastError()) {
775 case ERROR_PATH_NOT_FOUND:
776 continue;
777 case ERROR_FILE_NOT_FOUND:
778 /* This implies parent directory exists. */
779 return 1;
781 return 0;
783 return 1;
786 /* We keep the do_lstat code in a separate function to avoid recursion.
787 * When a path ends with a slash, the stat will fail with ENOENT. In
788 * this case, we strip the trailing slashes and stat again.
790 * If follow is true then act like stat() and report on the link
791 * target. Otherwise report on the link itself.
793 static int do_lstat(int follow, const char *file_name, struct stat *buf)
795 WIN32_FILE_ATTRIBUTE_DATA fdata;
796 wchar_t wfilename[MAX_PATH];
797 if (xutftowcs_path(wfilename, file_name) < 0)
798 return -1;
800 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
801 buf->st_ino = 0;
802 buf->st_gid = 0;
803 buf->st_uid = 0;
804 buf->st_nlink = 1;
805 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
806 buf->st_size = fdata.nFileSizeLow |
807 (((off_t)fdata.nFileSizeHigh)<<32);
808 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
809 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
810 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
811 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
812 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
813 WIN32_FIND_DATAW findbuf;
814 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
815 if (handle != INVALID_HANDLE_VALUE) {
816 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
817 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
818 if (follow) {
819 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
820 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
821 } else {
822 buf->st_mode = S_IFLNK;
824 buf->st_mode |= S_IREAD;
825 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
826 buf->st_mode |= S_IWRITE;
828 FindClose(handle);
831 return 0;
833 switch (GetLastError()) {
834 case ERROR_ACCESS_DENIED:
835 case ERROR_SHARING_VIOLATION:
836 case ERROR_LOCK_VIOLATION:
837 case ERROR_SHARING_BUFFER_EXCEEDED:
838 errno = EACCES;
839 break;
840 case ERROR_BUFFER_OVERFLOW:
841 errno = ENAMETOOLONG;
842 break;
843 case ERROR_NOT_ENOUGH_MEMORY:
844 errno = ENOMEM;
845 break;
846 case ERROR_PATH_NOT_FOUND:
847 if (!has_valid_directory_prefix(wfilename)) {
848 errno = ENOTDIR;
849 break;
851 /* fallthru */
852 default:
853 errno = ENOENT;
854 break;
856 return -1;
859 /* We provide our own lstat/fstat functions, since the provided
860 * lstat/fstat functions are so slow. These stat functions are
861 * tailored for Git's usage (read: fast), and are not meant to be
862 * complete. Note that Git stat()s are redirected to mingw_lstat()
863 * too, since Windows doesn't really handle symlinks that well.
865 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
867 int namelen;
868 char alt_name[PATH_MAX];
870 if (!do_lstat(follow, file_name, buf))
871 return 0;
873 /* if file_name ended in a '/', Windows returned ENOENT;
874 * try again without trailing slashes
876 if (errno != ENOENT)
877 return -1;
879 namelen = strlen(file_name);
880 if (namelen && file_name[namelen-1] != '/')
881 return -1;
882 while (namelen && file_name[namelen-1] == '/')
883 --namelen;
884 if (!namelen || namelen >= PATH_MAX)
885 return -1;
887 memcpy(alt_name, file_name, namelen);
888 alt_name[namelen] = 0;
889 return do_lstat(follow, alt_name, buf);
892 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
894 BY_HANDLE_FILE_INFORMATION fdata;
896 if (!GetFileInformationByHandle(hnd, &fdata)) {
897 errno = err_win_to_posix(GetLastError());
898 return -1;
901 buf->st_ino = 0;
902 buf->st_gid = 0;
903 buf->st_uid = 0;
904 buf->st_nlink = 1;
905 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
906 buf->st_size = fdata.nFileSizeLow |
907 (((off_t)fdata.nFileSizeHigh)<<32);
908 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
909 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
910 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
911 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
912 return 0;
915 int mingw_lstat(const char *file_name, struct stat *buf)
917 return do_stat_internal(0, file_name, buf);
919 int mingw_stat(const char *file_name, struct stat *buf)
921 return do_stat_internal(1, file_name, buf);
924 int mingw_fstat(int fd, struct stat *buf)
926 HANDLE fh = (HANDLE)_get_osfhandle(fd);
927 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
929 switch (type) {
930 case FILE_TYPE_DISK:
931 return get_file_info_by_handle(fh, buf);
933 case FILE_TYPE_CHAR:
934 case FILE_TYPE_PIPE:
935 /* initialize stat fields */
936 memset(buf, 0, sizeof(*buf));
937 buf->st_nlink = 1;
939 if (type == FILE_TYPE_CHAR) {
940 buf->st_mode = _S_IFCHR;
941 } else {
942 buf->st_mode = _S_IFIFO;
943 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
944 buf->st_size = avail;
946 return 0;
948 default:
949 errno = EBADF;
950 return -1;
954 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
956 long long winTime = t * 10000000LL + 116444736000000000LL;
957 ft->dwLowDateTime = winTime;
958 ft->dwHighDateTime = winTime >> 32;
961 int mingw_utime (const char *file_name, const struct utimbuf *times)
963 FILETIME mft, aft;
964 int fh, rc;
965 DWORD attrs;
966 wchar_t wfilename[MAX_PATH];
967 if (xutftowcs_path(wfilename, file_name) < 0)
968 return -1;
970 /* must have write permission */
971 attrs = GetFileAttributesW(wfilename);
972 if (attrs != INVALID_FILE_ATTRIBUTES &&
973 (attrs & FILE_ATTRIBUTE_READONLY)) {
974 /* ignore errors here; open() will report them */
975 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
978 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
979 rc = -1;
980 goto revert_attrs;
983 if (times) {
984 time_t_to_filetime(times->modtime, &mft);
985 time_t_to_filetime(times->actime, &aft);
986 } else {
987 GetSystemTimeAsFileTime(&mft);
988 aft = mft;
990 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
991 errno = EINVAL;
992 rc = -1;
993 } else
994 rc = 0;
995 close(fh);
997 revert_attrs:
998 if (attrs != INVALID_FILE_ATTRIBUTES &&
999 (attrs & FILE_ATTRIBUTE_READONLY)) {
1000 /* ignore errors again */
1001 SetFileAttributesW(wfilename, attrs);
1003 return rc;
1006 #undef strftime
1007 size_t mingw_strftime(char *s, size_t max,
1008 const char *format, const struct tm *tm)
1010 /* a pointer to the original strftime in case we can't find the UCRT version */
1011 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1012 size_t ret;
1013 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1014 const char *, const struct tm *);
1016 if (INIT_PROC_ADDR(strftime))
1017 ret = strftime(s, max, format, tm);
1018 else
1019 ret = fallback(s, max, format, tm);
1021 if (!ret && errno == EINVAL)
1022 die("invalid strftime format: '%s'", format);
1023 return ret;
1026 unsigned int sleep (unsigned int seconds)
1028 Sleep(seconds*1000);
1029 return 0;
1032 char *mingw_mktemp(char *template)
1034 wchar_t wtemplate[MAX_PATH];
1035 if (xutftowcs_path(wtemplate, template) < 0)
1036 return NULL;
1037 if (!_wmktemp(wtemplate))
1038 return NULL;
1039 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1040 return NULL;
1041 return template;
1044 int mkstemp(char *template)
1046 char *filename = mktemp(template);
1047 if (filename == NULL)
1048 return -1;
1049 return open(filename, O_RDWR | O_CREAT, 0600);
1052 int gettimeofday(struct timeval *tv, void *tz)
1054 FILETIME ft;
1055 long long hnsec;
1057 GetSystemTimeAsFileTime(&ft);
1058 hnsec = filetime_to_hnsec(&ft);
1059 tv->tv_sec = hnsec / 10000000;
1060 tv->tv_usec = (hnsec % 10000000) / 10;
1061 return 0;
1064 int pipe(int filedes[2])
1066 HANDLE h[2];
1068 /* this creates non-inheritable handles */
1069 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1070 errno = err_win_to_posix(GetLastError());
1071 return -1;
1073 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1074 if (filedes[0] < 0) {
1075 CloseHandle(h[0]);
1076 CloseHandle(h[1]);
1077 return -1;
1079 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1080 if (filedes[1] < 0) {
1081 close(filedes[0]);
1082 CloseHandle(h[1]);
1083 return -1;
1085 return 0;
1088 #ifndef __MINGW64__
1089 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1091 if (gmtime_s(result, timep) == 0)
1092 return result;
1093 return NULL;
1096 struct tm *localtime_r(const time_t *timep, struct tm *result)
1098 if (localtime_s(result, timep) == 0)
1099 return result;
1100 return NULL;
1102 #endif
1104 char *mingw_getcwd(char *pointer, int len)
1106 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1107 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1109 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1110 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1111 return NULL;
1113 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1114 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1115 HANDLE hnd = CreateFileW(cwd, 0,
1116 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1117 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1118 if (hnd == INVALID_HANDLE_VALUE)
1119 return NULL;
1120 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1121 CloseHandle(hnd);
1122 if (!ret || ret >= ARRAY_SIZE(wpointer))
1123 return NULL;
1124 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1125 return NULL;
1126 return pointer;
1128 if (!ret || ret >= ARRAY_SIZE(wpointer))
1129 return NULL;
1130 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1131 errno = ENOENT;
1132 return NULL;
1134 if (xwcstoutf(pointer, wpointer, len) < 0)
1135 return NULL;
1136 convert_slashes(pointer);
1137 return pointer;
1141 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1142 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1144 static const char *quote_arg_msvc(const char *arg)
1146 /* count chars to quote */
1147 int len = 0, n = 0;
1148 int force_quotes = 0;
1149 char *q, *d;
1150 const char *p = arg;
1151 if (!*p) force_quotes = 1;
1152 while (*p) {
1153 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1154 force_quotes = 1;
1155 else if (*p == '"')
1156 n++;
1157 else if (*p == '\\') {
1158 int count = 0;
1159 while (*p == '\\') {
1160 count++;
1161 p++;
1162 len++;
1164 if (*p == '"' || !*p)
1165 n += count*2 + 1;
1166 continue;
1168 len++;
1169 p++;
1171 if (!force_quotes && n == 0)
1172 return arg;
1174 /* insert \ where necessary */
1175 d = q = xmalloc(st_add3(len, n, 3));
1176 *d++ = '"';
1177 while (*arg) {
1178 if (*arg == '"')
1179 *d++ = '\\';
1180 else if (*arg == '\\') {
1181 int count = 0;
1182 while (*arg == '\\') {
1183 count++;
1184 *d++ = *arg++;
1186 if (*arg == '"' || !*arg) {
1187 while (count-- > 0)
1188 *d++ = '\\';
1189 /* don't escape the surrounding end quote */
1190 if (!*arg)
1191 break;
1192 *d++ = '\\';
1195 *d++ = *arg++;
1197 *d++ = '"';
1198 *d++ = '\0';
1199 return q;
1202 #include "quote.h"
1204 static const char *quote_arg_msys2(const char *arg)
1206 struct strbuf buf = STRBUF_INIT;
1207 const char *p2 = arg, *p;
1209 for (p = arg; *p; p++) {
1210 int ws = isspace(*p);
1211 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1212 *p != '?' && *p != '*' && *p != '~')
1213 continue;
1214 if (!buf.len)
1215 strbuf_addch(&buf, '"');
1216 if (p != p2)
1217 strbuf_add(&buf, p2, p - p2);
1218 if (*p == '\\' || *p == '"')
1219 strbuf_addch(&buf, '\\');
1220 p2 = p;
1223 if (p == arg)
1224 strbuf_addch(&buf, '"');
1225 else if (!buf.len)
1226 return arg;
1227 else
1228 strbuf_add(&buf, p2, p - p2);
1230 strbuf_addch(&buf, '"');
1231 return strbuf_detach(&buf, 0);
1234 static const char *parse_interpreter(const char *cmd)
1236 static char buf[100];
1237 char *p, *opt;
1238 int n, fd;
1240 /* don't even try a .exe */
1241 n = strlen(cmd);
1242 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1243 return NULL;
1245 fd = open(cmd, O_RDONLY);
1246 if (fd < 0)
1247 return NULL;
1248 n = read(fd, buf, sizeof(buf)-1);
1249 close(fd);
1250 if (n < 4) /* at least '#!/x' and not error */
1251 return NULL;
1253 if (buf[0] != '#' || buf[1] != '!')
1254 return NULL;
1255 buf[n] = '\0';
1256 p = buf + strcspn(buf, "\r\n");
1257 if (!*p)
1258 return NULL;
1260 *p = '\0';
1261 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1262 return NULL;
1263 /* strip options */
1264 if ((opt = strchr(p+1, ' ')))
1265 *opt = '\0';
1266 return p+1;
1270 * exe_only means that we only want to detect .exe files, but not scripts
1271 * (which do not have an extension)
1273 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1274 int isexe, int exe_only)
1276 char path[MAX_PATH];
1277 wchar_t wpath[MAX_PATH];
1278 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1280 if (xutftowcs_path(wpath, path) < 0)
1281 return NULL;
1283 if (!isexe && _waccess(wpath, F_OK) == 0)
1284 return xstrdup(path);
1285 wpath[wcslen(wpath)-4] = '\0';
1286 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1287 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1288 path[strlen(path)-4] = '\0';
1289 return xstrdup(path);
1292 return NULL;
1296 * Determines the absolute path of cmd using the split path in path.
1297 * If cmd contains a slash or backslash, no lookup is performed.
1299 static char *path_lookup(const char *cmd, int exe_only)
1301 const char *path;
1302 char *prog = NULL;
1303 int len = strlen(cmd);
1304 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1306 if (strpbrk(cmd, "/\\"))
1307 return xstrdup(cmd);
1309 path = mingw_getenv("PATH");
1310 if (!path)
1311 return NULL;
1313 while (!prog) {
1314 const char *sep = strchrnul(path, ';');
1315 int dirlen = sep - path;
1316 if (dirlen)
1317 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1318 if (!*sep)
1319 break;
1320 path = sep + 1;
1323 return prog;
1326 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1328 while (*s && *s != c)
1329 s++;
1330 return s;
1333 /* Compare only keys */
1334 static int wenvcmp(const void *a, const void *b)
1336 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1337 size_t p_len, q_len;
1339 /* Find the keys */
1340 p_len = wcschrnul(p, L'=') - p;
1341 q_len = wcschrnul(q, L'=') - q;
1343 /* If the length differs, include the shorter key's NUL */
1344 if (p_len < q_len)
1345 p_len++;
1346 else if (p_len > q_len)
1347 p_len = q_len + 1;
1349 return _wcsnicmp(p, q, p_len);
1353 * Build an environment block combining the inherited environment
1354 * merged with the given list of settings.
1356 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1357 * Values of the form "KEY" in deltaenv delete inherited values.
1359 * Multiple entries in deltaenv for the same key are explicitly allowed.
1361 * We return a contiguous block of UNICODE strings with a final trailing
1362 * zero word.
1364 static wchar_t *make_environment_block(char **deltaenv)
1366 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1367 size_t wlen, s, delta_size, size;
1369 wchar_t **array = NULL;
1370 size_t alloc = 0, nr = 0, i;
1372 size = 1; /* for extra NUL at the end */
1374 /* If there is no deltaenv to apply, simply return a copy. */
1375 if (!deltaenv || !*deltaenv) {
1376 for (p = wenv; p && *p; ) {
1377 size_t s = wcslen(p) + 1;
1378 size += s;
1379 p += s;
1382 ALLOC_ARRAY(result, size);
1383 COPY_ARRAY(result, wenv, size);
1384 FreeEnvironmentStringsW(wenv);
1385 return result;
1389 * If there is a deltaenv, let's accumulate all keys into `array`,
1390 * sort them using the stable git_stable_qsort() and then copy,
1391 * skipping duplicate keys
1393 for (p = wenv; p && *p; ) {
1394 ALLOC_GROW(array, nr + 1, alloc);
1395 s = wcslen(p) + 1;
1396 array[nr++] = p;
1397 p += s;
1398 size += s;
1401 /* (over-)assess size needed for wchar version of deltaenv */
1402 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1403 delta_size += strlen(deltaenv[i]) * 2 + 1;
1404 ALLOC_ARRAY(wdeltaenv, delta_size);
1406 /* convert the deltaenv, appending to array */
1407 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1408 ALLOC_GROW(array, nr + 1, alloc);
1409 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1410 array[nr++] = p;
1411 p += wlen + 1;
1414 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1415 ALLOC_ARRAY(result, size + delta_size);
1417 for (p = result, i = 0; i < nr; i++) {
1418 /* Skip any duplicate keys; last one wins */
1419 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1420 i++;
1422 /* Skip "to delete" entry */
1423 if (!wcschr(array[i], L'='))
1424 continue;
1426 size = wcslen(array[i]) + 1;
1427 COPY_ARRAY(p, array[i], size);
1428 p += size;
1430 *p = L'\0';
1432 free(array);
1433 free(wdeltaenv);
1434 FreeEnvironmentStringsW(wenv);
1435 return result;
1438 static void do_unset_environment_variables(void)
1440 static int done;
1441 char *p = unset_environment_variables;
1443 if (done || !p)
1444 return;
1445 done = 1;
1447 for (;;) {
1448 char *comma = strchr(p, ',');
1450 if (comma)
1451 *comma = '\0';
1452 unsetenv(p);
1453 if (!comma)
1454 break;
1455 p = comma + 1;
1459 struct pinfo_t {
1460 struct pinfo_t *next;
1461 pid_t pid;
1462 HANDLE proc;
1464 static struct pinfo_t *pinfo = NULL;
1465 CRITICAL_SECTION pinfo_cs;
1467 /* Used to match and chomp off path components */
1468 static inline int match_last_path_component(const char *path, size_t *len,
1469 const char *component)
1471 size_t component_len = strlen(component);
1472 if (*len < component_len + 1 ||
1473 !is_dir_sep(path[*len - component_len - 1]) ||
1474 fspathncmp(path + *len - component_len, component, component_len))
1475 return 0;
1476 *len -= component_len + 1;
1477 /* chomp off repeated dir separators */
1478 while (*len > 0 && is_dir_sep(path[*len - 1]))
1479 (*len)--;
1480 return 1;
1483 static int is_msys2_sh(const char *cmd)
1485 if (!cmd)
1486 return 0;
1488 if (!strcmp(cmd, "sh")) {
1489 static int ret = -1;
1490 char *p;
1492 if (ret >= 0)
1493 return ret;
1495 p = path_lookup(cmd, 0);
1496 if (!p)
1497 ret = 0;
1498 else {
1499 size_t len = strlen(p);
1501 ret = match_last_path_component(p, &len, "sh.exe") &&
1502 match_last_path_component(p, &len, "bin") &&
1503 match_last_path_component(p, &len, "usr");
1504 free(p);
1506 return ret;
1509 if (ends_with(cmd, "\\sh.exe")) {
1510 static char *sh;
1512 if (!sh)
1513 sh = path_lookup("sh", 0);
1515 return !fspathcmp(cmd, sh);
1518 return 0;
1521 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1522 const char *dir,
1523 int prepend_cmd, int fhin, int fhout, int fherr)
1525 static int restrict_handle_inheritance = -1;
1526 STARTUPINFOEXW si;
1527 PROCESS_INFORMATION pi;
1528 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1529 HANDLE stdhandles[3];
1530 DWORD stdhandles_count = 0;
1531 SIZE_T size;
1532 struct strbuf args;
1533 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1534 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1535 BOOL ret;
1536 HANDLE cons;
1537 const char *(*quote_arg)(const char *arg) =
1538 is_msys2_sh(cmd ? cmd : *argv) ?
1539 quote_arg_msys2 : quote_arg_msvc;
1540 const char *strace_env;
1542 /* Make sure to override previous errors, if any */
1543 errno = 0;
1545 if (restrict_handle_inheritance < 0)
1546 restrict_handle_inheritance = core_restrict_inherited_handles;
1548 * The following code to restrict which handles are inherited seems
1549 * to work properly only on Windows 7 and later, so let's disable it
1550 * on Windows Vista and 2008.
1552 if (restrict_handle_inheritance < 0)
1553 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1555 do_unset_environment_variables();
1557 /* Determine whether or not we are associated to a console */
1558 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1559 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1560 FILE_ATTRIBUTE_NORMAL, NULL);
1561 if (cons == INVALID_HANDLE_VALUE) {
1562 /* There is no console associated with this process.
1563 * Since the child is a console process, Windows
1564 * would normally create a console window. But
1565 * since we'll be redirecting std streams, we do
1566 * not need the console.
1567 * It is necessary to use DETACHED_PROCESS
1568 * instead of CREATE_NO_WINDOW to make ssh
1569 * recognize that it has no console.
1571 flags |= DETACHED_PROCESS;
1572 } else {
1573 /* There is already a console. If we specified
1574 * DETACHED_PROCESS here, too, Windows would
1575 * disassociate the child from the console.
1576 * The same is true for CREATE_NO_WINDOW.
1577 * Go figure!
1579 CloseHandle(cons);
1581 memset(&si, 0, sizeof(si));
1582 si.StartupInfo.cb = sizeof(si);
1583 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1584 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1585 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1587 /* The list of handles cannot contain duplicates */
1588 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1589 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1590 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1591 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1592 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1593 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1594 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1595 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1596 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1597 if (stdhandles_count)
1598 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1600 if (*argv && !strcmp(cmd, *argv))
1601 wcmd[0] = L'\0';
1602 else if (xutftowcs_path(wcmd, cmd) < 0)
1603 return -1;
1604 if (dir && xutftowcs_path(wdir, dir) < 0)
1605 return -1;
1607 /* concatenate argv, quoting args as we go */
1608 strbuf_init(&args, 0);
1609 if (prepend_cmd) {
1610 char *quoted = (char *)quote_arg(cmd);
1611 strbuf_addstr(&args, quoted);
1612 if (quoted != cmd)
1613 free(quoted);
1615 for (; *argv; argv++) {
1616 char *quoted = (char *)quote_arg(*argv);
1617 if (*args.buf)
1618 strbuf_addch(&args, ' ');
1619 strbuf_addstr(&args, quoted);
1620 if (quoted != *argv)
1621 free(quoted);
1624 strace_env = getenv("GIT_STRACE_COMMANDS");
1625 if (strace_env) {
1626 char *p = path_lookup("strace.exe", 1);
1627 if (!p)
1628 return error("strace not found!");
1629 if (xutftowcs_path(wcmd, p) < 0) {
1630 free(p);
1631 return -1;
1633 free(p);
1634 if (!strcmp("1", strace_env) ||
1635 !strcasecmp("yes", strace_env) ||
1636 !strcasecmp("true", strace_env))
1637 strbuf_insert(&args, 0, "strace ", 7);
1638 else {
1639 const char *quoted = quote_arg(strace_env);
1640 struct strbuf buf = STRBUF_INIT;
1641 strbuf_addf(&buf, "strace -o %s ", quoted);
1642 if (quoted != strace_env)
1643 free((char *)quoted);
1644 strbuf_insert(&args, 0, buf.buf, buf.len);
1645 strbuf_release(&buf);
1649 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1650 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1651 strbuf_release(&args);
1653 wenvblk = make_environment_block(deltaenv);
1655 memset(&pi, 0, sizeof(pi));
1656 if (restrict_handle_inheritance && stdhandles_count &&
1657 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1658 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1659 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1660 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1661 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1662 UpdateProcThreadAttribute(attr_list, 0,
1663 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1664 stdhandles,
1665 stdhandles_count * sizeof(HANDLE),
1666 NULL, NULL)) {
1667 si.lpAttributeList = attr_list;
1668 flags |= EXTENDED_STARTUPINFO_PRESENT;
1671 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1672 stdhandles_count ? TRUE : FALSE,
1673 flags, wenvblk, dir ? wdir : NULL,
1674 &si.StartupInfo, &pi);
1677 * On Windows 2008 R2, it seems that specifying certain types of handles
1678 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1679 * error. Rather than playing finicky and fragile games, let's just try
1680 * to detect this situation and simply try again without restricting any
1681 * handle inheritance. This is still better than failing to create
1682 * processes.
1684 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1685 DWORD err = GetLastError();
1686 struct strbuf buf = STRBUF_INIT;
1688 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1690 * On Windows 7 and earlier, handles on pipes and character
1691 * devices are inherited automatically, and cannot be
1692 * specified in the thread handle list. Rather than trying
1693 * to catch each and every corner case (and running the
1694 * chance of *still* forgetting a few), let's just fall
1695 * back to creating the process without trying to limit the
1696 * handle inheritance.
1698 !(err == ERROR_INVALID_PARAMETER &&
1699 GetVersion() >> 16 < 9200) &&
1700 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1701 DWORD fl = 0;
1702 int i;
1704 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1706 for (i = 0; i < stdhandles_count; i++) {
1707 HANDLE h = stdhandles[i];
1708 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1709 "handle info (%d) %lx\n", i, h,
1710 GetFileType(h),
1711 GetHandleInformation(h, &fl),
1712 fl);
1714 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1715 "at\nhttps://github.com/git-for-windows/"
1716 "git/issues/new\n\n"
1717 "To suppress this warning, please set "
1718 "the environment variable\n\n"
1719 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1720 "\n");
1722 restrict_handle_inheritance = 0;
1723 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1724 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1725 TRUE, flags, wenvblk, dir ? wdir : NULL,
1726 &si.StartupInfo, &pi);
1727 if (!ret)
1728 errno = err_win_to_posix(GetLastError());
1729 if (ret && buf.len) {
1730 warning("failed to restrict file handles (%ld)\n\n%s",
1731 err, buf.buf);
1733 strbuf_release(&buf);
1734 } else if (!ret)
1735 errno = err_win_to_posix(GetLastError());
1737 if (si.lpAttributeList)
1738 DeleteProcThreadAttributeList(si.lpAttributeList);
1739 if (attr_list)
1740 HeapFree(GetProcessHeap(), 0, attr_list);
1742 free(wenvblk);
1743 free(wargs);
1745 if (!ret)
1746 return -1;
1748 CloseHandle(pi.hThread);
1751 * The process ID is the human-readable identifier of the process
1752 * that we want to present in log and error messages. The handle
1753 * is not useful for this purpose. But we cannot close it, either,
1754 * because it is not possible to turn a process ID into a process
1755 * handle after the process terminated.
1756 * Keep the handle in a list for waitpid.
1758 EnterCriticalSection(&pinfo_cs);
1760 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1761 info->pid = pi.dwProcessId;
1762 info->proc = pi.hProcess;
1763 info->next = pinfo;
1764 pinfo = info;
1766 LeaveCriticalSection(&pinfo_cs);
1768 return (pid_t)pi.dwProcessId;
1771 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1773 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1776 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1777 const char *dir,
1778 int fhin, int fhout, int fherr)
1780 pid_t pid;
1781 char *prog = path_lookup(cmd, 0);
1783 if (!prog) {
1784 errno = ENOENT;
1785 pid = -1;
1787 else {
1788 const char *interpr = parse_interpreter(prog);
1790 if (interpr) {
1791 const char *argv0 = argv[0];
1792 char *iprog = path_lookup(interpr, 1);
1793 argv[0] = prog;
1794 if (!iprog) {
1795 errno = ENOENT;
1796 pid = -1;
1798 else {
1799 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1800 fhin, fhout, fherr);
1801 free(iprog);
1803 argv[0] = argv0;
1805 else
1806 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1807 fhin, fhout, fherr);
1808 free(prog);
1810 return pid;
1813 static int try_shell_exec(const char *cmd, char *const *argv)
1815 const char *interpr = parse_interpreter(cmd);
1816 char *prog;
1817 int pid = 0;
1819 if (!interpr)
1820 return 0;
1821 prog = path_lookup(interpr, 1);
1822 if (prog) {
1823 int exec_id;
1824 int argc = 0;
1825 #ifndef _MSC_VER
1826 const
1827 #endif
1828 char **argv2;
1829 while (argv[argc]) argc++;
1830 ALLOC_ARRAY(argv2, argc + 1);
1831 argv2[0] = (char *)cmd; /* full path to the script file */
1832 COPY_ARRAY(&argv2[1], &argv[1], argc);
1833 exec_id = trace2_exec(prog, argv2);
1834 pid = mingw_spawnv(prog, argv2, 1);
1835 if (pid >= 0) {
1836 int status;
1837 if (waitpid(pid, &status, 0) < 0)
1838 status = 255;
1839 trace2_exec_result(exec_id, status);
1840 exit(status);
1842 trace2_exec_result(exec_id, -1);
1843 pid = 1; /* indicate that we tried but failed */
1844 free(prog);
1845 free(argv2);
1847 return pid;
1850 int mingw_execv(const char *cmd, char *const *argv)
1852 /* check if git_command is a shell script */
1853 if (!try_shell_exec(cmd, argv)) {
1854 int pid, status;
1855 int exec_id;
1857 exec_id = trace2_exec(cmd, (const char **)argv);
1858 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1859 if (pid < 0) {
1860 trace2_exec_result(exec_id, -1);
1861 return -1;
1863 if (waitpid(pid, &status, 0) < 0)
1864 status = 255;
1865 trace2_exec_result(exec_id, status);
1866 exit(status);
1868 return -1;
1871 int mingw_execvp(const char *cmd, char *const *argv)
1873 char *prog = path_lookup(cmd, 0);
1875 if (prog) {
1876 mingw_execv(prog, argv);
1877 free(prog);
1878 } else
1879 errno = ENOENT;
1881 return -1;
1884 int mingw_kill(pid_t pid, int sig)
1886 if (pid > 0 && sig == SIGTERM) {
1887 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1889 if (TerminateProcess(h, -1)) {
1890 CloseHandle(h);
1891 return 0;
1894 errno = err_win_to_posix(GetLastError());
1895 CloseHandle(h);
1896 return -1;
1897 } else if (pid > 0 && sig == 0) {
1898 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1899 if (h) {
1900 CloseHandle(h);
1901 return 0;
1905 errno = EINVAL;
1906 return -1;
1910 * UTF-8 versions of getenv(), putenv() and unsetenv().
1911 * Internally, they use the CRT's stock UNICODE routines
1912 * to avoid data loss.
1914 char *mingw_getenv(const char *name)
1916 #define GETENV_MAX_RETAIN 64
1917 static char *values[GETENV_MAX_RETAIN];
1918 static int value_counter;
1919 int len_key, len_value;
1920 wchar_t *w_key;
1921 char *value;
1922 wchar_t w_value[32768];
1924 if (!name || !*name)
1925 return NULL;
1927 len_key = strlen(name) + 1;
1928 /* We cannot use xcalloc() here because that uses getenv() itself */
1929 w_key = calloc(len_key, sizeof(wchar_t));
1930 if (!w_key)
1931 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1932 xutftowcs(w_key, name, len_key);
1933 /* GetEnvironmentVariableW() only sets the last error upon failure */
1934 SetLastError(ERROR_SUCCESS);
1935 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1936 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1937 free(w_key);
1938 return NULL;
1940 free(w_key);
1942 len_value = len_value * 3 + 1;
1943 /* We cannot use xcalloc() here because that uses getenv() itself */
1944 value = calloc(len_value, sizeof(char));
1945 if (!value)
1946 die("Out of memory, (tried to allocate %u bytes)", len_value);
1947 xwcstoutf(value, w_value, len_value);
1950 * We return `value` which is an allocated value and the caller is NOT
1951 * expecting to have to free it, so we keep a round-robin array,
1952 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1954 free(values[value_counter]);
1955 values[value_counter++] = value;
1956 if (value_counter >= ARRAY_SIZE(values))
1957 value_counter = 0;
1959 return value;
1962 int mingw_putenv(const char *namevalue)
1964 int size;
1965 wchar_t *wide, *equal;
1966 BOOL result;
1968 if (!namevalue || !*namevalue)
1969 return 0;
1971 size = strlen(namevalue) * 2 + 1;
1972 wide = calloc(size, sizeof(wchar_t));
1973 if (!wide)
1974 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1975 xutftowcs(wide, namevalue, size);
1976 equal = wcschr(wide, L'=');
1977 if (!equal)
1978 result = SetEnvironmentVariableW(wide, NULL);
1979 else {
1980 *equal = L'\0';
1981 result = SetEnvironmentVariableW(wide, equal + 1);
1983 free(wide);
1985 if (!result)
1986 errno = err_win_to_posix(GetLastError());
1988 return result ? 0 : -1;
1991 static void ensure_socket_initialization(void)
1993 WSADATA wsa;
1994 static int initialized = 0;
1996 if (initialized)
1997 return;
1999 if (WSAStartup(MAKEWORD(2,2), &wsa))
2000 die("unable to initialize winsock subsystem, error %d",
2001 WSAGetLastError());
2003 atexit((void(*)(void)) WSACleanup);
2004 initialized = 1;
2007 #undef gethostname
2008 int mingw_gethostname(char *name, int namelen)
2010 ensure_socket_initialization();
2011 return gethostname(name, namelen);
2014 #undef gethostbyname
2015 struct hostent *mingw_gethostbyname(const char *host)
2017 ensure_socket_initialization();
2018 return gethostbyname(host);
2021 #undef getaddrinfo
2022 int mingw_getaddrinfo(const char *node, const char *service,
2023 const struct addrinfo *hints, struct addrinfo **res)
2025 ensure_socket_initialization();
2026 return getaddrinfo(node, service, hints, res);
2029 int mingw_socket(int domain, int type, int protocol)
2031 int sockfd;
2032 SOCKET s;
2034 ensure_socket_initialization();
2035 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2036 if (s == INVALID_SOCKET) {
2038 * WSAGetLastError() values are regular BSD error codes
2039 * biased by WSABASEERR.
2040 * However, strerror() does not know about networking
2041 * specific errors, which are values beginning at 38 or so.
2042 * Therefore, we choose to leave the biased error code
2043 * in errno so that _if_ someone looks up the code somewhere,
2044 * then it is at least the number that are usually listed.
2046 errno = WSAGetLastError();
2047 return -1;
2049 /* convert into a file descriptor */
2050 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2051 closesocket(s);
2052 return error("unable to make a socket file descriptor: %s",
2053 strerror(errno));
2055 return sockfd;
2058 #undef connect
2059 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2061 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2062 return connect(s, sa, sz);
2065 #undef bind
2066 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2068 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2069 return bind(s, sa, sz);
2072 #undef setsockopt
2073 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2075 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2076 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2079 #undef shutdown
2080 int mingw_shutdown(int sockfd, int how)
2082 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2083 return shutdown(s, how);
2086 #undef listen
2087 int mingw_listen(int sockfd, int backlog)
2089 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2090 return listen(s, backlog);
2093 #undef accept
2094 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2096 int sockfd2;
2098 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2099 SOCKET s2 = accept(s1, sa, sz);
2101 /* convert into a file descriptor */
2102 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2103 int err = errno;
2104 closesocket(s2);
2105 return error("unable to make a socket file descriptor: %s",
2106 strerror(err));
2108 return sockfd2;
2111 #undef rename
2112 int mingw_rename(const char *pold, const char *pnew)
2114 DWORD attrs, gle;
2115 int tries = 0;
2116 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2117 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2118 return -1;
2121 * Try native rename() first to get errno right.
2122 * It is based on MoveFile(), which cannot overwrite existing files.
2124 if (!_wrename(wpold, wpnew))
2125 return 0;
2126 if (errno != EEXIST)
2127 return -1;
2128 repeat:
2129 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2130 return 0;
2131 /* TODO: translate more errors */
2132 gle = GetLastError();
2133 if (gle == ERROR_ACCESS_DENIED &&
2134 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2135 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2136 DWORD attrsold = GetFileAttributesW(wpold);
2137 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2138 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2139 errno = EISDIR;
2140 else if (!_wrmdir(wpnew))
2141 goto repeat;
2142 return -1;
2144 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2145 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2146 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2147 return 0;
2148 gle = GetLastError();
2149 /* revert file attributes on failure */
2150 SetFileAttributesW(wpnew, attrs);
2153 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2155 * We assume that some other process had the source or
2156 * destination file open at the wrong moment and retry.
2157 * In order to give the other process a higher chance to
2158 * complete its operation, we give up our time slice now.
2159 * If we have to retry again, we do sleep a bit.
2161 Sleep(delay[tries]);
2162 tries++;
2163 goto repeat;
2165 if (gle == ERROR_ACCESS_DENIED &&
2166 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2167 "Should I try again?", pold, pnew))
2168 goto repeat;
2170 errno = EACCES;
2171 return -1;
2175 * Note that this doesn't return the actual pagesize, but
2176 * the allocation granularity. If future Windows specific git code
2177 * needs the real getpagesize function, we need to find another solution.
2179 int mingw_getpagesize(void)
2181 SYSTEM_INFO si;
2182 GetSystemInfo(&si);
2183 return si.dwAllocationGranularity;
2186 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2187 enum EXTENDED_NAME_FORMAT {
2188 NameDisplay = 3,
2189 NameUserPrincipal = 8
2192 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2194 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2195 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2196 static wchar_t wbuffer[1024];
2197 DWORD len;
2199 if (!INIT_PROC_ADDR(GetUserNameExW))
2200 return NULL;
2202 len = ARRAY_SIZE(wbuffer);
2203 if (GetUserNameExW(type, wbuffer, &len)) {
2204 char *converted = xmalloc((len *= 3));
2205 if (xwcstoutf(converted, wbuffer, len) >= 0)
2206 return converted;
2207 free(converted);
2210 return NULL;
2213 char *mingw_query_user_email(void)
2215 return get_extended_user_info(NameUserPrincipal);
2218 struct passwd *getpwuid(int uid)
2220 static unsigned initialized;
2221 static char user_name[100];
2222 static struct passwd *p;
2223 wchar_t buf[100];
2224 DWORD len;
2226 if (initialized)
2227 return p;
2229 len = ARRAY_SIZE(buf);
2230 if (!GetUserNameW(buf, &len)) {
2231 initialized = 1;
2232 return NULL;
2235 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2236 initialized = 1;
2237 return NULL;
2240 p = xmalloc(sizeof(*p));
2241 p->pw_name = user_name;
2242 p->pw_gecos = get_extended_user_info(NameDisplay);
2243 if (!p->pw_gecos)
2244 p->pw_gecos = "unknown";
2245 p->pw_dir = NULL;
2247 initialized = 1;
2248 return p;
2251 static HANDLE timer_event;
2252 static HANDLE timer_thread;
2253 static int timer_interval;
2254 static int one_shot;
2255 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2257 /* The timer works like this:
2258 * The thread, ticktack(), is a trivial routine that most of the time
2259 * only waits to receive the signal to terminate. The main thread tells
2260 * the thread to terminate by setting the timer_event to the signalled
2261 * state.
2262 * But ticktack() interrupts the wait state after the timer's interval
2263 * length to call the signal handler.
2266 static unsigned __stdcall ticktack(void *dummy)
2268 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2269 mingw_raise(SIGALRM);
2270 if (one_shot)
2271 break;
2273 return 0;
2276 static int start_timer_thread(void)
2278 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2279 if (timer_event) {
2280 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2281 if (!timer_thread )
2282 return errno = ENOMEM,
2283 error("cannot start timer thread");
2284 } else
2285 return errno = ENOMEM,
2286 error("cannot allocate resources for timer");
2287 return 0;
2290 static void stop_timer_thread(void)
2292 if (timer_event)
2293 SetEvent(timer_event); /* tell thread to terminate */
2294 if (timer_thread) {
2295 int rc = WaitForSingleObject(timer_thread, 10000);
2296 if (rc == WAIT_TIMEOUT)
2297 error("timer thread did not terminate timely");
2298 else if (rc != WAIT_OBJECT_0)
2299 error("waiting for timer thread failed: %lu",
2300 GetLastError());
2301 CloseHandle(timer_thread);
2303 if (timer_event)
2304 CloseHandle(timer_event);
2305 timer_event = NULL;
2306 timer_thread = NULL;
2309 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2311 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2314 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2316 static const struct timeval zero;
2317 static int atexit_done;
2319 if (out != NULL)
2320 return errno = EINVAL,
2321 error("setitimer param 3 != NULL not implemented");
2322 if (!is_timeval_eq(&in->it_interval, &zero) &&
2323 !is_timeval_eq(&in->it_interval, &in->it_value))
2324 return errno = EINVAL,
2325 error("setitimer: it_interval must be zero or eq it_value");
2327 if (timer_thread)
2328 stop_timer_thread();
2330 if (is_timeval_eq(&in->it_value, &zero) &&
2331 is_timeval_eq(&in->it_interval, &zero))
2332 return 0;
2334 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2335 one_shot = is_timeval_eq(&in->it_interval, &zero);
2336 if (!atexit_done) {
2337 atexit(stop_timer_thread);
2338 atexit_done = 1;
2340 return start_timer_thread();
2343 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2345 if (sig != SIGALRM)
2346 return errno = EINVAL,
2347 error("sigaction only implemented for SIGALRM");
2348 if (out != NULL)
2349 return errno = EINVAL,
2350 error("sigaction: param 3 != NULL not implemented");
2352 timer_fn = in->sa_handler;
2353 return 0;
2356 #undef signal
2357 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2359 sig_handler_t old;
2361 switch (sig) {
2362 case SIGALRM:
2363 old = timer_fn;
2364 timer_fn = handler;
2365 break;
2367 case SIGINT:
2368 old = sigint_fn;
2369 sigint_fn = handler;
2370 break;
2372 default:
2373 return signal(sig, handler);
2376 return old;
2379 #undef raise
2380 int mingw_raise(int sig)
2382 switch (sig) {
2383 case SIGALRM:
2384 if (timer_fn == SIG_DFL) {
2385 if (isatty(STDERR_FILENO))
2386 fputs("Alarm clock\n", stderr);
2387 exit(128 + SIGALRM);
2388 } else if (timer_fn != SIG_IGN)
2389 timer_fn(SIGALRM);
2390 return 0;
2392 case SIGINT:
2393 if (sigint_fn == SIG_DFL)
2394 exit(128 + SIGINT);
2395 else if (sigint_fn != SIG_IGN)
2396 sigint_fn(SIGINT);
2397 return 0;
2399 #if defined(_MSC_VER)
2400 case SIGILL:
2401 case SIGFPE:
2402 case SIGSEGV:
2403 case SIGTERM:
2404 case SIGBREAK:
2405 case SIGABRT:
2406 case SIGABRT_COMPAT:
2408 * The <signal.h> header in the MS C Runtime defines 8 signals
2409 * as being supported on the platform. Anything else causes an
2410 * "Invalid signal or error" (which in DEBUG builds causes the
2411 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2412 * already know will fail.
2414 return raise(sig);
2415 default:
2416 errno = EINVAL;
2417 return -1;
2419 #else
2421 default:
2422 return raise(sig);
2424 #endif
2429 int link(const char *oldpath, const char *newpath)
2431 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2432 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2433 xutftowcs_path(wnewpath, newpath) < 0)
2434 return -1;
2436 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2437 errno = err_win_to_posix(GetLastError());
2438 return -1;
2440 return 0;
2443 pid_t waitpid(pid_t pid, int *status, int options)
2445 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2446 FALSE, pid);
2447 if (!h) {
2448 errno = ECHILD;
2449 return -1;
2452 if (pid > 0 && options & WNOHANG) {
2453 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2454 CloseHandle(h);
2455 return 0;
2457 options &= ~WNOHANG;
2460 if (options == 0) {
2461 struct pinfo_t **ppinfo;
2462 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2463 CloseHandle(h);
2464 return 0;
2467 if (status)
2468 GetExitCodeProcess(h, (LPDWORD)status);
2470 EnterCriticalSection(&pinfo_cs);
2472 ppinfo = &pinfo;
2473 while (*ppinfo) {
2474 struct pinfo_t *info = *ppinfo;
2475 if (info->pid == pid) {
2476 CloseHandle(info->proc);
2477 *ppinfo = info->next;
2478 free(info);
2479 break;
2481 ppinfo = &info->next;
2484 LeaveCriticalSection(&pinfo_cs);
2486 CloseHandle(h);
2487 return pid;
2489 CloseHandle(h);
2491 errno = EINVAL;
2492 return -1;
2495 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2497 int upos = 0, wpos = 0;
2498 const unsigned char *utf = (const unsigned char*) utfs;
2499 if (!utf || !wcs || wcslen < 1) {
2500 errno = EINVAL;
2501 return -1;
2503 /* reserve space for \0 */
2504 wcslen--;
2505 if (utflen < 0)
2506 utflen = INT_MAX;
2508 while (upos < utflen) {
2509 int c = utf[upos++] & 0xff;
2510 if (utflen == INT_MAX && c == 0)
2511 break;
2513 if (wpos >= wcslen) {
2514 wcs[wpos] = 0;
2515 errno = ERANGE;
2516 return -1;
2519 if (c < 0x80) {
2520 /* ASCII */
2521 wcs[wpos++] = c;
2522 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2523 (utf[upos] & 0xc0) == 0x80) {
2524 /* 2-byte utf-8 */
2525 c = ((c & 0x1f) << 6);
2526 c |= (utf[upos++] & 0x3f);
2527 wcs[wpos++] = c;
2528 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2529 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2530 (utf[upos] & 0xc0) == 0x80 &&
2531 (utf[upos + 1] & 0xc0) == 0x80) {
2532 /* 3-byte utf-8 */
2533 c = ((c & 0x0f) << 12);
2534 c |= ((utf[upos++] & 0x3f) << 6);
2535 c |= (utf[upos++] & 0x3f);
2536 wcs[wpos++] = c;
2537 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2538 wpos + 1 < wcslen &&
2539 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2540 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2541 (utf[upos] & 0xc0) == 0x80 &&
2542 (utf[upos + 1] & 0xc0) == 0x80 &&
2543 (utf[upos + 2] & 0xc0) == 0x80) {
2544 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2545 c = ((c & 0x07) << 18);
2546 c |= ((utf[upos++] & 0x3f) << 12);
2547 c |= ((utf[upos++] & 0x3f) << 6);
2548 c |= (utf[upos++] & 0x3f);
2549 c -= 0x10000;
2550 wcs[wpos++] = 0xd800 | (c >> 10);
2551 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2552 } else if (c >= 0xa0) {
2553 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2554 wcs[wpos++] = c;
2555 } else {
2556 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2557 static const char *hex = "0123456789abcdef";
2558 wcs[wpos++] = hex[c >> 4];
2559 if (wpos < wcslen)
2560 wcs[wpos++] = hex[c & 0x0f];
2563 wcs[wpos] = 0;
2564 return wpos;
2567 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2569 if (!wcs || !utf || utflen < 1) {
2570 errno = EINVAL;
2571 return -1;
2573 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2574 if (utflen)
2575 return utflen - 1;
2576 errno = ERANGE;
2577 return -1;
2580 static void setup_windows_environment(void)
2582 char *tmp = getenv("TMPDIR");
2584 /* on Windows it is TMP and TEMP */
2585 if (!tmp) {
2586 if (!(tmp = getenv("TMP")))
2587 tmp = getenv("TEMP");
2588 if (tmp) {
2589 setenv("TMPDIR", tmp, 1);
2590 tmp = getenv("TMPDIR");
2594 if (tmp) {
2596 * Convert all dir separators to forward slashes,
2597 * to help shell commands called from the Git
2598 * executable (by not mistaking the dir separators
2599 * for escape characters).
2601 convert_slashes(tmp);
2604 /* simulate TERM to enable auto-color (see color.c) */
2605 if (!getenv("TERM"))
2606 setenv("TERM", "cygwin", 1);
2608 /* calculate HOME if not set */
2609 if (!getenv("HOME")) {
2611 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2612 * location, thus also check if the path exists (i.e. is not
2613 * disconnected)
2615 if ((tmp = getenv("HOMEDRIVE"))) {
2616 struct strbuf buf = STRBUF_INIT;
2617 strbuf_addstr(&buf, tmp);
2618 if ((tmp = getenv("HOMEPATH"))) {
2619 strbuf_addstr(&buf, tmp);
2620 if (is_directory(buf.buf))
2621 setenv("HOME", buf.buf, 1);
2622 else
2623 tmp = NULL; /* use $USERPROFILE */
2625 strbuf_release(&buf);
2627 /* use $USERPROFILE if the home share is not available */
2628 if (!tmp && (tmp = getenv("USERPROFILE")))
2629 setenv("HOME", tmp, 1);
2633 int is_valid_win32_path(const char *path, int allow_literal_nul)
2635 const char *p = path;
2636 int preceding_space_or_period = 0, i = 0, periods = 0;
2638 if (!protect_ntfs)
2639 return 1;
2641 skip_dos_drive_prefix((char **)&path);
2642 goto segment_start;
2644 for (;;) {
2645 char c = *(path++);
2646 switch (c) {
2647 case '\0':
2648 case '/': case '\\':
2649 /* cannot end in ` ` or `.`, except for `.` and `..` */
2650 if (preceding_space_or_period &&
2651 (i != periods || periods > 2))
2652 return 0;
2653 if (!c)
2654 return 1;
2656 i = periods = preceding_space_or_period = 0;
2658 segment_start:
2659 switch (*path) {
2660 case 'a': case 'A': /* AUX */
2661 if (((c = path[++i]) != 'u' && c != 'U') ||
2662 ((c = path[++i]) != 'x' && c != 'X')) {
2663 not_a_reserved_name:
2664 path += i;
2665 continue;
2667 break;
2668 case 'c': case 'C':
2669 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2670 if ((c = path[++i]) != 'o' && c != 'O')
2671 goto not_a_reserved_name;
2672 c = path[++i];
2673 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2674 c = path[++i];
2675 if (c < '1' || c > '9')
2676 goto not_a_reserved_name;
2677 } else if (c == 'n' || c == 'N') { /* CON */
2678 c = path[i + 1];
2679 if ((c == 'i' || c == 'I') &&
2680 ((c = path[i + 2]) == 'n' ||
2681 c == 'N') &&
2682 path[i + 3] == '$')
2683 i += 3; /* CONIN$ */
2684 else if ((c == 'o' || c == 'O') &&
2685 ((c = path[i + 2]) == 'u' ||
2686 c == 'U') &&
2687 ((c = path[i + 3]) == 't' ||
2688 c == 'T') &&
2689 path[i + 4] == '$')
2690 i += 4; /* CONOUT$ */
2691 } else
2692 goto not_a_reserved_name;
2693 break;
2694 case 'l': case 'L': /* LPT<N> */
2695 if (((c = path[++i]) != 'p' && c != 'P') ||
2696 ((c = path[++i]) != 't' && c != 'T') ||
2697 !isdigit(path[++i]))
2698 goto not_a_reserved_name;
2699 break;
2700 case 'n': case 'N': /* NUL */
2701 if (((c = path[++i]) != 'u' && c != 'U') ||
2702 ((c = path[++i]) != 'l' && c != 'L') ||
2703 (allow_literal_nul &&
2704 !path[i + 1] && p == path))
2705 goto not_a_reserved_name;
2706 break;
2707 case 'p': case 'P': /* PRN */
2708 if (((c = path[++i]) != 'r' && c != 'R') ||
2709 ((c = path[++i]) != 'n' && c != 'N'))
2710 goto not_a_reserved_name;
2711 break;
2712 default:
2713 continue;
2717 * So far, this looks like a reserved name. Let's see
2718 * whether it actually is one: trailing spaces, a file
2719 * extension, or an NTFS Alternate Data Stream do not
2720 * matter, the name is still reserved if any of those
2721 * follow immediately after the actual name.
2723 i++;
2724 if (path[i] == ' ') {
2725 preceding_space_or_period = 1;
2726 while (path[++i] == ' ')
2727 ; /* skip all spaces */
2730 c = path[i];
2731 if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2732 goto not_a_reserved_name;
2734 /* contains reserved name */
2735 return 0;
2736 case '.':
2737 periods++;
2738 /* fallthru */
2739 case ' ':
2740 preceding_space_or_period = 1;
2741 i++;
2742 continue;
2743 case ':': /* DOS drive prefix was already skipped */
2744 case '<': case '>': case '"': case '|': case '?': case '*':
2745 /* illegal character */
2746 return 0;
2747 default:
2748 if (c > '\0' && c < '\x20')
2749 /* illegal character */
2750 return 0;
2752 preceding_space_or_period = 0;
2753 i++;
2757 #if !defined(_MSC_VER)
2759 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2760 * mingw startup code, see init.c in mingw runtime).
2762 int _CRT_glob = 0;
2763 #endif
2765 static NORETURN void die_startup(void)
2767 fputs("fatal: not enough memory for initialization", stderr);
2768 exit(128);
2771 static void *malloc_startup(size_t size)
2773 void *result = malloc(size);
2774 if (!result)
2775 die_startup();
2776 return result;
2779 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2781 len = xwcstoutf(buffer, wcs, len) + 1;
2782 return memcpy(malloc_startup(len), buffer, len);
2785 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2786 DWORD desired_access, DWORD flags)
2788 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2789 wchar_t buf[MAX_PATH];
2790 DWORD max = ARRAY_SIZE(buf);
2791 HANDLE handle;
2792 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2794 if (!ret || ret >= max)
2795 return;
2797 /* make sure this does not leak into child processes */
2798 SetEnvironmentVariableW(key, NULL);
2799 if (!wcscmp(buf, L"off")) {
2800 close(fd);
2801 handle = GetStdHandle(std_id);
2802 if (handle != INVALID_HANDLE_VALUE)
2803 CloseHandle(handle);
2804 return;
2806 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2807 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2808 if (handle == INVALID_HANDLE_VALUE) {
2809 close(fd);
2810 handle = GetStdHandle(std_id);
2811 if (handle != INVALID_HANDLE_VALUE)
2812 CloseHandle(handle);
2813 } else {
2814 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2815 SetStdHandle(std_id, handle);
2816 dup2(new_fd, fd);
2817 /* do *not* close the new_fd: that would close stdout */
2819 return;
2821 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2822 flags, NULL);
2823 if (handle != INVALID_HANDLE_VALUE) {
2824 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2825 SetStdHandle(std_id, handle);
2826 dup2(new_fd, fd);
2827 close(new_fd);
2831 static void maybe_redirect_std_handles(void)
2833 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2834 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2835 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2836 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2837 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2838 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2841 #ifdef _MSC_VER
2842 #ifdef _DEBUG
2843 #include <crtdbg.h>
2844 #endif
2845 #endif
2848 * We implement wmain() and compile with -municode, which would
2849 * normally ignore main(), but we call the latter from the former
2850 * so that we can handle non-ASCII command-line parameters
2851 * appropriately.
2853 * To be more compatible with the core git code, we convert
2854 * argv into UTF8 and pass them directly to main().
2856 int wmain(int argc, const wchar_t **wargv)
2858 int i, maxlen, exit_status;
2859 char *buffer, **save;
2860 const char **argv;
2862 trace2_initialize_clock();
2864 #ifdef _MSC_VER
2865 #ifdef _DEBUG
2866 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2867 #endif
2869 #ifdef USE_MSVC_CRTDBG
2870 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2871 #endif
2872 #endif
2874 maybe_redirect_std_handles();
2876 /* determine size of argv and environ conversion buffer */
2877 maxlen = wcslen(wargv[0]);
2878 for (i = 1; i < argc; i++)
2879 maxlen = max(maxlen, wcslen(wargv[i]));
2881 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2882 maxlen = 3 * maxlen + 1;
2883 buffer = malloc_startup(maxlen);
2886 * Create a UTF-8 version of w_argv. Also create a "save" copy
2887 * to remember all the string pointers because parse_options()
2888 * will remove claimed items from the argv that we pass down.
2890 ALLOC_ARRAY(argv, argc + 1);
2891 ALLOC_ARRAY(save, argc + 1);
2892 for (i = 0; i < argc; i++)
2893 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2894 argv[i] = save[i] = NULL;
2895 free(buffer);
2897 /* fix Windows specific environment settings */
2898 setup_windows_environment();
2900 unset_environment_variables = xstrdup("PERL5LIB");
2902 /* initialize critical section for waitpid pinfo_t list */
2903 InitializeCriticalSection(&pinfo_cs);
2905 /* set up default file mode and file modes for stdin/out/err */
2906 _fmode = _O_BINARY;
2907 _setmode(_fileno(stdin), _O_BINARY);
2908 _setmode(_fileno(stdout), _O_BINARY);
2909 _setmode(_fileno(stderr), _O_BINARY);
2911 /* initialize Unicode console */
2912 winansi_init();
2914 /* invoke the real main() using our utf8 version of argv. */
2915 exit_status = main(argc, argv);
2917 for (i = 0; i < argc; i++)
2918 free(save[i]);
2919 free(save);
2920 free(argv);
2922 return exit_status;
2925 int uname(struct utsname *buf)
2927 unsigned v = (unsigned)GetVersion();
2928 memset(buf, 0, sizeof(*buf));
2929 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2930 xsnprintf(buf->release, sizeof(buf->release),
2931 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2932 /* assuming NT variants only.. */
2933 xsnprintf(buf->version, sizeof(buf->version),
2934 "%u", (v >> 16) & 0x7fff);
2935 return 0;