Merge branch 'ma/windows-dynload-fix'
[git/debian.git] / compat / mingw.c
blob640dcb11de0dd6421c66a70a660a7fbc8bae4530
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 (xwcstoutf(pointer, wpointer, len) < 0)
1131 return NULL;
1132 convert_slashes(pointer);
1133 return pointer;
1137 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1138 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1140 static const char *quote_arg_msvc(const char *arg)
1142 /* count chars to quote */
1143 int len = 0, n = 0;
1144 int force_quotes = 0;
1145 char *q, *d;
1146 const char *p = arg;
1147 if (!*p) force_quotes = 1;
1148 while (*p) {
1149 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1150 force_quotes = 1;
1151 else if (*p == '"')
1152 n++;
1153 else if (*p == '\\') {
1154 int count = 0;
1155 while (*p == '\\') {
1156 count++;
1157 p++;
1158 len++;
1160 if (*p == '"' || !*p)
1161 n += count*2 + 1;
1162 continue;
1164 len++;
1165 p++;
1167 if (!force_quotes && n == 0)
1168 return arg;
1170 /* insert \ where necessary */
1171 d = q = xmalloc(st_add3(len, n, 3));
1172 *d++ = '"';
1173 while (*arg) {
1174 if (*arg == '"')
1175 *d++ = '\\';
1176 else if (*arg == '\\') {
1177 int count = 0;
1178 while (*arg == '\\') {
1179 count++;
1180 *d++ = *arg++;
1182 if (*arg == '"' || !*arg) {
1183 while (count-- > 0)
1184 *d++ = '\\';
1185 /* don't escape the surrounding end quote */
1186 if (!*arg)
1187 break;
1188 *d++ = '\\';
1191 *d++ = *arg++;
1193 *d++ = '"';
1194 *d++ = '\0';
1195 return q;
1198 #include "quote.h"
1200 static const char *quote_arg_msys2(const char *arg)
1202 struct strbuf buf = STRBUF_INIT;
1203 const char *p2 = arg, *p;
1205 for (p = arg; *p; p++) {
1206 int ws = isspace(*p);
1207 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1208 *p != '?' && *p != '*' && *p != '~')
1209 continue;
1210 if (!buf.len)
1211 strbuf_addch(&buf, '"');
1212 if (p != p2)
1213 strbuf_add(&buf, p2, p - p2);
1214 if (*p == '\\' || *p == '"')
1215 strbuf_addch(&buf, '\\');
1216 p2 = p;
1219 if (p == arg)
1220 strbuf_addch(&buf, '"');
1221 else if (!buf.len)
1222 return arg;
1223 else
1224 strbuf_add(&buf, p2, p - p2);
1226 strbuf_addch(&buf, '"');
1227 return strbuf_detach(&buf, 0);
1230 static const char *parse_interpreter(const char *cmd)
1232 static char buf[100];
1233 char *p, *opt;
1234 int n, fd;
1236 /* don't even try a .exe */
1237 n = strlen(cmd);
1238 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1239 return NULL;
1241 fd = open(cmd, O_RDONLY);
1242 if (fd < 0)
1243 return NULL;
1244 n = read(fd, buf, sizeof(buf)-1);
1245 close(fd);
1246 if (n < 4) /* at least '#!/x' and not error */
1247 return NULL;
1249 if (buf[0] != '#' || buf[1] != '!')
1250 return NULL;
1251 buf[n] = '\0';
1252 p = buf + strcspn(buf, "\r\n");
1253 if (!*p)
1254 return NULL;
1256 *p = '\0';
1257 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1258 return NULL;
1259 /* strip options */
1260 if ((opt = strchr(p+1, ' ')))
1261 *opt = '\0';
1262 return p+1;
1266 * exe_only means that we only want to detect .exe files, but not scripts
1267 * (which do not have an extension)
1269 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1270 int isexe, int exe_only)
1272 char path[MAX_PATH];
1273 wchar_t wpath[MAX_PATH];
1274 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1276 if (xutftowcs_path(wpath, path) < 0)
1277 return NULL;
1279 if (!isexe && _waccess(wpath, F_OK) == 0)
1280 return xstrdup(path);
1281 wpath[wcslen(wpath)-4] = '\0';
1282 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1283 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1284 path[strlen(path)-4] = '\0';
1285 return xstrdup(path);
1288 return NULL;
1292 * Determines the absolute path of cmd using the split path in path.
1293 * If cmd contains a slash or backslash, no lookup is performed.
1295 static char *path_lookup(const char *cmd, int exe_only)
1297 const char *path;
1298 char *prog = NULL;
1299 int len = strlen(cmd);
1300 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1302 if (strpbrk(cmd, "/\\"))
1303 return xstrdup(cmd);
1305 path = mingw_getenv("PATH");
1306 if (!path)
1307 return NULL;
1309 while (!prog) {
1310 const char *sep = strchrnul(path, ';');
1311 int dirlen = sep - path;
1312 if (dirlen)
1313 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1314 if (!*sep)
1315 break;
1316 path = sep + 1;
1319 return prog;
1322 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1324 while (*s && *s != c)
1325 s++;
1326 return s;
1329 /* Compare only keys */
1330 static int wenvcmp(const void *a, const void *b)
1332 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1333 size_t p_len, q_len;
1335 /* Find the keys */
1336 p_len = wcschrnul(p, L'=') - p;
1337 q_len = wcschrnul(q, L'=') - q;
1339 /* If the length differs, include the shorter key's NUL */
1340 if (p_len < q_len)
1341 p_len++;
1342 else if (p_len > q_len)
1343 p_len = q_len + 1;
1345 return _wcsnicmp(p, q, p_len);
1349 * Build an environment block combining the inherited environment
1350 * merged with the given list of settings.
1352 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1353 * Values of the form "KEY" in deltaenv delete inherited values.
1355 * Multiple entries in deltaenv for the same key are explicitly allowed.
1357 * We return a contiguous block of UNICODE strings with a final trailing
1358 * zero word.
1360 static wchar_t *make_environment_block(char **deltaenv)
1362 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1363 size_t wlen, s, delta_size, size;
1365 wchar_t **array = NULL;
1366 size_t alloc = 0, nr = 0, i;
1368 size = 1; /* for extra NUL at the end */
1370 /* If there is no deltaenv to apply, simply return a copy. */
1371 if (!deltaenv || !*deltaenv) {
1372 for (p = wenv; p && *p; ) {
1373 size_t s = wcslen(p) + 1;
1374 size += s;
1375 p += s;
1378 ALLOC_ARRAY(result, size);
1379 COPY_ARRAY(result, wenv, size);
1380 FreeEnvironmentStringsW(wenv);
1381 return result;
1385 * If there is a deltaenv, let's accumulate all keys into `array`,
1386 * sort them using the stable git_stable_qsort() and then copy,
1387 * skipping duplicate keys
1389 for (p = wenv; p && *p; ) {
1390 ALLOC_GROW(array, nr + 1, alloc);
1391 s = wcslen(p) + 1;
1392 array[nr++] = p;
1393 p += s;
1394 size += s;
1397 /* (over-)assess size needed for wchar version of deltaenv */
1398 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1399 delta_size += strlen(deltaenv[i]) * 2 + 1;
1400 ALLOC_ARRAY(wdeltaenv, delta_size);
1402 /* convert the deltaenv, appending to array */
1403 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1404 ALLOC_GROW(array, nr + 1, alloc);
1405 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1406 array[nr++] = p;
1407 p += wlen + 1;
1410 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1411 ALLOC_ARRAY(result, size + delta_size);
1413 for (p = result, i = 0; i < nr; i++) {
1414 /* Skip any duplicate keys; last one wins */
1415 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1416 i++;
1418 /* Skip "to delete" entry */
1419 if (!wcschr(array[i], L'='))
1420 continue;
1422 size = wcslen(array[i]) + 1;
1423 COPY_ARRAY(p, array[i], size);
1424 p += size;
1426 *p = L'\0';
1428 free(array);
1429 free(wdeltaenv);
1430 FreeEnvironmentStringsW(wenv);
1431 return result;
1434 static void do_unset_environment_variables(void)
1436 static int done;
1437 char *p = unset_environment_variables;
1439 if (done || !p)
1440 return;
1441 done = 1;
1443 for (;;) {
1444 char *comma = strchr(p, ',');
1446 if (comma)
1447 *comma = '\0';
1448 unsetenv(p);
1449 if (!comma)
1450 break;
1451 p = comma + 1;
1455 struct pinfo_t {
1456 struct pinfo_t *next;
1457 pid_t pid;
1458 HANDLE proc;
1460 static struct pinfo_t *pinfo = NULL;
1461 CRITICAL_SECTION pinfo_cs;
1463 /* Used to match and chomp off path components */
1464 static inline int match_last_path_component(const char *path, size_t *len,
1465 const char *component)
1467 size_t component_len = strlen(component);
1468 if (*len < component_len + 1 ||
1469 !is_dir_sep(path[*len - component_len - 1]) ||
1470 fspathncmp(path + *len - component_len, component, component_len))
1471 return 0;
1472 *len -= component_len + 1;
1473 /* chomp off repeated dir separators */
1474 while (*len > 0 && is_dir_sep(path[*len - 1]))
1475 (*len)--;
1476 return 1;
1479 static int is_msys2_sh(const char *cmd)
1481 if (!cmd)
1482 return 0;
1484 if (!strcmp(cmd, "sh")) {
1485 static int ret = -1;
1486 char *p;
1488 if (ret >= 0)
1489 return ret;
1491 p = path_lookup(cmd, 0);
1492 if (!p)
1493 ret = 0;
1494 else {
1495 size_t len = strlen(p);
1497 ret = match_last_path_component(p, &len, "sh.exe") &&
1498 match_last_path_component(p, &len, "bin") &&
1499 match_last_path_component(p, &len, "usr");
1500 free(p);
1502 return ret;
1505 if (ends_with(cmd, "\\sh.exe")) {
1506 static char *sh;
1508 if (!sh)
1509 sh = path_lookup("sh", 0);
1511 return !fspathcmp(cmd, sh);
1514 return 0;
1517 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1518 const char *dir,
1519 int prepend_cmd, int fhin, int fhout, int fherr)
1521 static int restrict_handle_inheritance = -1;
1522 STARTUPINFOEXW si;
1523 PROCESS_INFORMATION pi;
1524 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1525 HANDLE stdhandles[3];
1526 DWORD stdhandles_count = 0;
1527 SIZE_T size;
1528 struct strbuf args;
1529 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1530 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1531 BOOL ret;
1532 HANDLE cons;
1533 const char *(*quote_arg)(const char *arg) =
1534 is_msys2_sh(cmd ? cmd : *argv) ?
1535 quote_arg_msys2 : quote_arg_msvc;
1536 const char *strace_env;
1538 /* Make sure to override previous errors, if any */
1539 errno = 0;
1541 if (restrict_handle_inheritance < 0)
1542 restrict_handle_inheritance = core_restrict_inherited_handles;
1544 * The following code to restrict which handles are inherited seems
1545 * to work properly only on Windows 7 and later, so let's disable it
1546 * on Windows Vista and 2008.
1548 if (restrict_handle_inheritance < 0)
1549 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1551 do_unset_environment_variables();
1553 /* Determine whether or not we are associated to a console */
1554 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1555 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1556 FILE_ATTRIBUTE_NORMAL, NULL);
1557 if (cons == INVALID_HANDLE_VALUE) {
1558 /* There is no console associated with this process.
1559 * Since the child is a console process, Windows
1560 * would normally create a console window. But
1561 * since we'll be redirecting std streams, we do
1562 * not need the console.
1563 * It is necessary to use DETACHED_PROCESS
1564 * instead of CREATE_NO_WINDOW to make ssh
1565 * recognize that it has no console.
1567 flags |= DETACHED_PROCESS;
1568 } else {
1569 /* There is already a console. If we specified
1570 * DETACHED_PROCESS here, too, Windows would
1571 * disassociate the child from the console.
1572 * The same is true for CREATE_NO_WINDOW.
1573 * Go figure!
1575 CloseHandle(cons);
1577 memset(&si, 0, sizeof(si));
1578 si.StartupInfo.cb = sizeof(si);
1579 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1580 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1581 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1583 /* The list of handles cannot contain duplicates */
1584 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1585 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1586 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1587 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1588 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1589 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1590 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1591 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1592 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1593 if (stdhandles_count)
1594 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1596 if (*argv && !strcmp(cmd, *argv))
1597 wcmd[0] = L'\0';
1598 else if (xutftowcs_path(wcmd, cmd) < 0)
1599 return -1;
1600 if (dir && xutftowcs_path(wdir, dir) < 0)
1601 return -1;
1603 /* concatenate argv, quoting args as we go */
1604 strbuf_init(&args, 0);
1605 if (prepend_cmd) {
1606 char *quoted = (char *)quote_arg(cmd);
1607 strbuf_addstr(&args, quoted);
1608 if (quoted != cmd)
1609 free(quoted);
1611 for (; *argv; argv++) {
1612 char *quoted = (char *)quote_arg(*argv);
1613 if (*args.buf)
1614 strbuf_addch(&args, ' ');
1615 strbuf_addstr(&args, quoted);
1616 if (quoted != *argv)
1617 free(quoted);
1620 strace_env = getenv("GIT_STRACE_COMMANDS");
1621 if (strace_env) {
1622 char *p = path_lookup("strace.exe", 1);
1623 if (!p)
1624 return error("strace not found!");
1625 if (xutftowcs_path(wcmd, p) < 0) {
1626 free(p);
1627 return -1;
1629 free(p);
1630 if (!strcmp("1", strace_env) ||
1631 !strcasecmp("yes", strace_env) ||
1632 !strcasecmp("true", strace_env))
1633 strbuf_insert(&args, 0, "strace ", 7);
1634 else {
1635 const char *quoted = quote_arg(strace_env);
1636 struct strbuf buf = STRBUF_INIT;
1637 strbuf_addf(&buf, "strace -o %s ", quoted);
1638 if (quoted != strace_env)
1639 free((char *)quoted);
1640 strbuf_insert(&args, 0, buf.buf, buf.len);
1641 strbuf_release(&buf);
1645 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1646 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1647 strbuf_release(&args);
1649 wenvblk = make_environment_block(deltaenv);
1651 memset(&pi, 0, sizeof(pi));
1652 if (restrict_handle_inheritance && stdhandles_count &&
1653 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1654 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1655 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1656 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1657 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1658 UpdateProcThreadAttribute(attr_list, 0,
1659 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1660 stdhandles,
1661 stdhandles_count * sizeof(HANDLE),
1662 NULL, NULL)) {
1663 si.lpAttributeList = attr_list;
1664 flags |= EXTENDED_STARTUPINFO_PRESENT;
1667 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1668 stdhandles_count ? TRUE : FALSE,
1669 flags, wenvblk, dir ? wdir : NULL,
1670 &si.StartupInfo, &pi);
1673 * On Windows 2008 R2, it seems that specifying certain types of handles
1674 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1675 * error. Rather than playing finicky and fragile games, let's just try
1676 * to detect this situation and simply try again without restricting any
1677 * handle inheritance. This is still better than failing to create
1678 * processes.
1680 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1681 DWORD err = GetLastError();
1682 struct strbuf buf = STRBUF_INIT;
1684 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1686 * On Windows 7 and earlier, handles on pipes and character
1687 * devices are inherited automatically, and cannot be
1688 * specified in the thread handle list. Rather than trying
1689 * to catch each and every corner case (and running the
1690 * chance of *still* forgetting a few), let's just fall
1691 * back to creating the process without trying to limit the
1692 * handle inheritance.
1694 !(err == ERROR_INVALID_PARAMETER &&
1695 GetVersion() >> 16 < 9200) &&
1696 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1697 DWORD fl = 0;
1698 int i;
1700 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1702 for (i = 0; i < stdhandles_count; i++) {
1703 HANDLE h = stdhandles[i];
1704 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1705 "handle info (%d) %lx\n", i, h,
1706 GetFileType(h),
1707 GetHandleInformation(h, &fl),
1708 fl);
1710 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1711 "at\nhttps://github.com/git-for-windows/"
1712 "git/issues/new\n\n"
1713 "To suppress this warning, please set "
1714 "the environment variable\n\n"
1715 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1716 "\n");
1718 restrict_handle_inheritance = 0;
1719 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1720 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1721 TRUE, flags, wenvblk, dir ? wdir : NULL,
1722 &si.StartupInfo, &pi);
1723 if (!ret)
1724 errno = err_win_to_posix(GetLastError());
1725 if (ret && buf.len) {
1726 warning("failed to restrict file handles (%ld)\n\n%s",
1727 err, buf.buf);
1729 strbuf_release(&buf);
1730 } else if (!ret)
1731 errno = err_win_to_posix(GetLastError());
1733 if (si.lpAttributeList)
1734 DeleteProcThreadAttributeList(si.lpAttributeList);
1735 if (attr_list)
1736 HeapFree(GetProcessHeap(), 0, attr_list);
1738 free(wenvblk);
1739 free(wargs);
1741 if (!ret)
1742 return -1;
1744 CloseHandle(pi.hThread);
1747 * The process ID is the human-readable identifier of the process
1748 * that we want to present in log and error messages. The handle
1749 * is not useful for this purpose. But we cannot close it, either,
1750 * because it is not possible to turn a process ID into a process
1751 * handle after the process terminated.
1752 * Keep the handle in a list for waitpid.
1754 EnterCriticalSection(&pinfo_cs);
1756 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1757 info->pid = pi.dwProcessId;
1758 info->proc = pi.hProcess;
1759 info->next = pinfo;
1760 pinfo = info;
1762 LeaveCriticalSection(&pinfo_cs);
1764 return (pid_t)pi.dwProcessId;
1767 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1769 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1772 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1773 const char *dir,
1774 int fhin, int fhout, int fherr)
1776 pid_t pid;
1777 char *prog = path_lookup(cmd, 0);
1779 if (!prog) {
1780 errno = ENOENT;
1781 pid = -1;
1783 else {
1784 const char *interpr = parse_interpreter(prog);
1786 if (interpr) {
1787 const char *argv0 = argv[0];
1788 char *iprog = path_lookup(interpr, 1);
1789 argv[0] = prog;
1790 if (!iprog) {
1791 errno = ENOENT;
1792 pid = -1;
1794 else {
1795 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1796 fhin, fhout, fherr);
1797 free(iprog);
1799 argv[0] = argv0;
1801 else
1802 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1803 fhin, fhout, fherr);
1804 free(prog);
1806 return pid;
1809 static int try_shell_exec(const char *cmd, char *const *argv)
1811 const char *interpr = parse_interpreter(cmd);
1812 char *prog;
1813 int pid = 0;
1815 if (!interpr)
1816 return 0;
1817 prog = path_lookup(interpr, 1);
1818 if (prog) {
1819 int exec_id;
1820 int argc = 0;
1821 #ifndef _MSC_VER
1822 const
1823 #endif
1824 char **argv2;
1825 while (argv[argc]) argc++;
1826 ALLOC_ARRAY(argv2, argc + 1);
1827 argv2[0] = (char *)cmd; /* full path to the script file */
1828 COPY_ARRAY(&argv2[1], &argv[1], argc);
1829 exec_id = trace2_exec(prog, argv2);
1830 pid = mingw_spawnv(prog, argv2, 1);
1831 if (pid >= 0) {
1832 int status;
1833 if (waitpid(pid, &status, 0) < 0)
1834 status = 255;
1835 trace2_exec_result(exec_id, status);
1836 exit(status);
1838 trace2_exec_result(exec_id, -1);
1839 pid = 1; /* indicate that we tried but failed */
1840 free(prog);
1841 free(argv2);
1843 return pid;
1846 int mingw_execv(const char *cmd, char *const *argv)
1848 /* check if git_command is a shell script */
1849 if (!try_shell_exec(cmd, argv)) {
1850 int pid, status;
1851 int exec_id;
1853 exec_id = trace2_exec(cmd, (const char **)argv);
1854 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1855 if (pid < 0) {
1856 trace2_exec_result(exec_id, -1);
1857 return -1;
1859 if (waitpid(pid, &status, 0) < 0)
1860 status = 255;
1861 trace2_exec_result(exec_id, status);
1862 exit(status);
1864 return -1;
1867 int mingw_execvp(const char *cmd, char *const *argv)
1869 char *prog = path_lookup(cmd, 0);
1871 if (prog) {
1872 mingw_execv(prog, argv);
1873 free(prog);
1874 } else
1875 errno = ENOENT;
1877 return -1;
1880 int mingw_kill(pid_t pid, int sig)
1882 if (pid > 0 && sig == SIGTERM) {
1883 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1885 if (TerminateProcess(h, -1)) {
1886 CloseHandle(h);
1887 return 0;
1890 errno = err_win_to_posix(GetLastError());
1891 CloseHandle(h);
1892 return -1;
1893 } else if (pid > 0 && sig == 0) {
1894 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1895 if (h) {
1896 CloseHandle(h);
1897 return 0;
1901 errno = EINVAL;
1902 return -1;
1906 * UTF-8 versions of getenv(), putenv() and unsetenv().
1907 * Internally, they use the CRT's stock UNICODE routines
1908 * to avoid data loss.
1910 char *mingw_getenv(const char *name)
1912 #define GETENV_MAX_RETAIN 64
1913 static char *values[GETENV_MAX_RETAIN];
1914 static int value_counter;
1915 int len_key, len_value;
1916 wchar_t *w_key;
1917 char *value;
1918 wchar_t w_value[32768];
1920 if (!name || !*name)
1921 return NULL;
1923 len_key = strlen(name) + 1;
1924 /* We cannot use xcalloc() here because that uses getenv() itself */
1925 w_key = calloc(len_key, sizeof(wchar_t));
1926 if (!w_key)
1927 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1928 xutftowcs(w_key, name, len_key);
1929 /* GetEnvironmentVariableW() only sets the last error upon failure */
1930 SetLastError(ERROR_SUCCESS);
1931 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1932 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1933 free(w_key);
1934 return NULL;
1936 free(w_key);
1938 len_value = len_value * 3 + 1;
1939 /* We cannot use xcalloc() here because that uses getenv() itself */
1940 value = calloc(len_value, sizeof(char));
1941 if (!value)
1942 die("Out of memory, (tried to allocate %u bytes)", len_value);
1943 xwcstoutf(value, w_value, len_value);
1946 * We return `value` which is an allocated value and the caller is NOT
1947 * expecting to have to free it, so we keep a round-robin array,
1948 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1950 free(values[value_counter]);
1951 values[value_counter++] = value;
1952 if (value_counter >= ARRAY_SIZE(values))
1953 value_counter = 0;
1955 return value;
1958 int mingw_putenv(const char *namevalue)
1960 int size;
1961 wchar_t *wide, *equal;
1962 BOOL result;
1964 if (!namevalue || !*namevalue)
1965 return 0;
1967 size = strlen(namevalue) * 2 + 1;
1968 wide = calloc(size, sizeof(wchar_t));
1969 if (!wide)
1970 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1971 xutftowcs(wide, namevalue, size);
1972 equal = wcschr(wide, L'=');
1973 if (!equal)
1974 result = SetEnvironmentVariableW(wide, NULL);
1975 else {
1976 *equal = L'\0';
1977 result = SetEnvironmentVariableW(wide, equal + 1);
1979 free(wide);
1981 if (!result)
1982 errno = err_win_to_posix(GetLastError());
1984 return result ? 0 : -1;
1987 static void ensure_socket_initialization(void)
1989 WSADATA wsa;
1990 static int initialized = 0;
1992 if (initialized)
1993 return;
1995 if (WSAStartup(MAKEWORD(2,2), &wsa))
1996 die("unable to initialize winsock subsystem, error %d",
1997 WSAGetLastError());
1999 atexit((void(*)(void)) WSACleanup);
2000 initialized = 1;
2003 #undef gethostname
2004 int mingw_gethostname(char *name, int namelen)
2006 ensure_socket_initialization();
2007 return gethostname(name, namelen);
2010 #undef gethostbyname
2011 struct hostent *mingw_gethostbyname(const char *host)
2013 ensure_socket_initialization();
2014 return gethostbyname(host);
2017 #undef getaddrinfo
2018 int mingw_getaddrinfo(const char *node, const char *service,
2019 const struct addrinfo *hints, struct addrinfo **res)
2021 ensure_socket_initialization();
2022 return getaddrinfo(node, service, hints, res);
2025 int mingw_socket(int domain, int type, int protocol)
2027 int sockfd;
2028 SOCKET s;
2030 ensure_socket_initialization();
2031 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2032 if (s == INVALID_SOCKET) {
2034 * WSAGetLastError() values are regular BSD error codes
2035 * biased by WSABASEERR.
2036 * However, strerror() does not know about networking
2037 * specific errors, which are values beginning at 38 or so.
2038 * Therefore, we choose to leave the biased error code
2039 * in errno so that _if_ someone looks up the code somewhere,
2040 * then it is at least the number that are usually listed.
2042 errno = WSAGetLastError();
2043 return -1;
2045 /* convert into a file descriptor */
2046 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2047 closesocket(s);
2048 return error("unable to make a socket file descriptor: %s",
2049 strerror(errno));
2051 return sockfd;
2054 #undef connect
2055 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2057 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2058 return connect(s, sa, sz);
2061 #undef bind
2062 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2064 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2065 return bind(s, sa, sz);
2068 #undef setsockopt
2069 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2071 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2072 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2075 #undef shutdown
2076 int mingw_shutdown(int sockfd, int how)
2078 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2079 return shutdown(s, how);
2082 #undef listen
2083 int mingw_listen(int sockfd, int backlog)
2085 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2086 return listen(s, backlog);
2089 #undef accept
2090 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2092 int sockfd2;
2094 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2095 SOCKET s2 = accept(s1, sa, sz);
2097 /* convert into a file descriptor */
2098 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2099 int err = errno;
2100 closesocket(s2);
2101 return error("unable to make a socket file descriptor: %s",
2102 strerror(err));
2104 return sockfd2;
2107 #undef rename
2108 int mingw_rename(const char *pold, const char *pnew)
2110 DWORD attrs, gle;
2111 int tries = 0;
2112 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2113 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2114 return -1;
2117 * Try native rename() first to get errno right.
2118 * It is based on MoveFile(), which cannot overwrite existing files.
2120 if (!_wrename(wpold, wpnew))
2121 return 0;
2122 if (errno != EEXIST)
2123 return -1;
2124 repeat:
2125 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2126 return 0;
2127 /* TODO: translate more errors */
2128 gle = GetLastError();
2129 if (gle == ERROR_ACCESS_DENIED &&
2130 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2131 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2132 DWORD attrsold = GetFileAttributesW(wpold);
2133 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2134 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2135 errno = EISDIR;
2136 else if (!_wrmdir(wpnew))
2137 goto repeat;
2138 return -1;
2140 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2141 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2142 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2143 return 0;
2144 gle = GetLastError();
2145 /* revert file attributes on failure */
2146 SetFileAttributesW(wpnew, attrs);
2149 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2151 * We assume that some other process had the source or
2152 * destination file open at the wrong moment and retry.
2153 * In order to give the other process a higher chance to
2154 * complete its operation, we give up our time slice now.
2155 * If we have to retry again, we do sleep a bit.
2157 Sleep(delay[tries]);
2158 tries++;
2159 goto repeat;
2161 if (gle == ERROR_ACCESS_DENIED &&
2162 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2163 "Should I try again?", pold, pnew))
2164 goto repeat;
2166 errno = EACCES;
2167 return -1;
2171 * Note that this doesn't return the actual pagesize, but
2172 * the allocation granularity. If future Windows specific git code
2173 * needs the real getpagesize function, we need to find another solution.
2175 int mingw_getpagesize(void)
2177 SYSTEM_INFO si;
2178 GetSystemInfo(&si);
2179 return si.dwAllocationGranularity;
2182 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2183 enum EXTENDED_NAME_FORMAT {
2184 NameDisplay = 3,
2185 NameUserPrincipal = 8
2188 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2190 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2191 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2192 static wchar_t wbuffer[1024];
2193 DWORD len;
2195 if (!INIT_PROC_ADDR(GetUserNameExW))
2196 return NULL;
2198 len = ARRAY_SIZE(wbuffer);
2199 if (GetUserNameExW(type, wbuffer, &len)) {
2200 char *converted = xmalloc((len *= 3));
2201 if (xwcstoutf(converted, wbuffer, len) >= 0)
2202 return converted;
2203 free(converted);
2206 return NULL;
2209 char *mingw_query_user_email(void)
2211 return get_extended_user_info(NameUserPrincipal);
2214 struct passwd *getpwuid(int uid)
2216 static unsigned initialized;
2217 static char user_name[100];
2218 static struct passwd *p;
2219 wchar_t buf[100];
2220 DWORD len;
2222 if (initialized)
2223 return p;
2225 len = ARRAY_SIZE(buf);
2226 if (!GetUserNameW(buf, &len)) {
2227 initialized = 1;
2228 return NULL;
2231 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2232 initialized = 1;
2233 return NULL;
2236 p = xmalloc(sizeof(*p));
2237 p->pw_name = user_name;
2238 p->pw_gecos = get_extended_user_info(NameDisplay);
2239 if (!p->pw_gecos)
2240 p->pw_gecos = "unknown";
2241 p->pw_dir = NULL;
2243 initialized = 1;
2244 return p;
2247 static HANDLE timer_event;
2248 static HANDLE timer_thread;
2249 static int timer_interval;
2250 static int one_shot;
2251 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2253 /* The timer works like this:
2254 * The thread, ticktack(), is a trivial routine that most of the time
2255 * only waits to receive the signal to terminate. The main thread tells
2256 * the thread to terminate by setting the timer_event to the signalled
2257 * state.
2258 * But ticktack() interrupts the wait state after the timer's interval
2259 * length to call the signal handler.
2262 static unsigned __stdcall ticktack(void *dummy)
2264 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2265 mingw_raise(SIGALRM);
2266 if (one_shot)
2267 break;
2269 return 0;
2272 static int start_timer_thread(void)
2274 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2275 if (timer_event) {
2276 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2277 if (!timer_thread )
2278 return errno = ENOMEM,
2279 error("cannot start timer thread");
2280 } else
2281 return errno = ENOMEM,
2282 error("cannot allocate resources for timer");
2283 return 0;
2286 static void stop_timer_thread(void)
2288 if (timer_event)
2289 SetEvent(timer_event); /* tell thread to terminate */
2290 if (timer_thread) {
2291 int rc = WaitForSingleObject(timer_thread, 10000);
2292 if (rc == WAIT_TIMEOUT)
2293 error("timer thread did not terminate timely");
2294 else if (rc != WAIT_OBJECT_0)
2295 error("waiting for timer thread failed: %lu",
2296 GetLastError());
2297 CloseHandle(timer_thread);
2299 if (timer_event)
2300 CloseHandle(timer_event);
2301 timer_event = NULL;
2302 timer_thread = NULL;
2305 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2307 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2310 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2312 static const struct timeval zero;
2313 static int atexit_done;
2315 if (out != NULL)
2316 return errno = EINVAL,
2317 error("setitimer param 3 != NULL not implemented");
2318 if (!is_timeval_eq(&in->it_interval, &zero) &&
2319 !is_timeval_eq(&in->it_interval, &in->it_value))
2320 return errno = EINVAL,
2321 error("setitimer: it_interval must be zero or eq it_value");
2323 if (timer_thread)
2324 stop_timer_thread();
2326 if (is_timeval_eq(&in->it_value, &zero) &&
2327 is_timeval_eq(&in->it_interval, &zero))
2328 return 0;
2330 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2331 one_shot = is_timeval_eq(&in->it_interval, &zero);
2332 if (!atexit_done) {
2333 atexit(stop_timer_thread);
2334 atexit_done = 1;
2336 return start_timer_thread();
2339 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2341 if (sig != SIGALRM)
2342 return errno = EINVAL,
2343 error("sigaction only implemented for SIGALRM");
2344 if (out != NULL)
2345 return errno = EINVAL,
2346 error("sigaction: param 3 != NULL not implemented");
2348 timer_fn = in->sa_handler;
2349 return 0;
2352 #undef signal
2353 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2355 sig_handler_t old;
2357 switch (sig) {
2358 case SIGALRM:
2359 old = timer_fn;
2360 timer_fn = handler;
2361 break;
2363 case SIGINT:
2364 old = sigint_fn;
2365 sigint_fn = handler;
2366 break;
2368 default:
2369 return signal(sig, handler);
2372 return old;
2375 #undef raise
2376 int mingw_raise(int sig)
2378 switch (sig) {
2379 case SIGALRM:
2380 if (timer_fn == SIG_DFL) {
2381 if (isatty(STDERR_FILENO))
2382 fputs("Alarm clock\n", stderr);
2383 exit(128 + SIGALRM);
2384 } else if (timer_fn != SIG_IGN)
2385 timer_fn(SIGALRM);
2386 return 0;
2388 case SIGINT:
2389 if (sigint_fn == SIG_DFL)
2390 exit(128 + SIGINT);
2391 else if (sigint_fn != SIG_IGN)
2392 sigint_fn(SIGINT);
2393 return 0;
2395 #if defined(_MSC_VER)
2396 case SIGILL:
2397 case SIGFPE:
2398 case SIGSEGV:
2399 case SIGTERM:
2400 case SIGBREAK:
2401 case SIGABRT:
2402 case SIGABRT_COMPAT:
2404 * The <signal.h> header in the MS C Runtime defines 8 signals
2405 * as being supported on the platform. Anything else causes an
2406 * "Invalid signal or error" (which in DEBUG builds causes the
2407 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2408 * already know will fail.
2410 return raise(sig);
2411 default:
2412 errno = EINVAL;
2413 return -1;
2415 #else
2417 default:
2418 return raise(sig);
2420 #endif
2425 int link(const char *oldpath, const char *newpath)
2427 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2428 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2429 xutftowcs_path(wnewpath, newpath) < 0)
2430 return -1;
2432 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2433 errno = err_win_to_posix(GetLastError());
2434 return -1;
2436 return 0;
2439 pid_t waitpid(pid_t pid, int *status, int options)
2441 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2442 FALSE, pid);
2443 if (!h) {
2444 errno = ECHILD;
2445 return -1;
2448 if (pid > 0 && options & WNOHANG) {
2449 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2450 CloseHandle(h);
2451 return 0;
2453 options &= ~WNOHANG;
2456 if (options == 0) {
2457 struct pinfo_t **ppinfo;
2458 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2459 CloseHandle(h);
2460 return 0;
2463 if (status)
2464 GetExitCodeProcess(h, (LPDWORD)status);
2466 EnterCriticalSection(&pinfo_cs);
2468 ppinfo = &pinfo;
2469 while (*ppinfo) {
2470 struct pinfo_t *info = *ppinfo;
2471 if (info->pid == pid) {
2472 CloseHandle(info->proc);
2473 *ppinfo = info->next;
2474 free(info);
2475 break;
2477 ppinfo = &info->next;
2480 LeaveCriticalSection(&pinfo_cs);
2482 CloseHandle(h);
2483 return pid;
2485 CloseHandle(h);
2487 errno = EINVAL;
2488 return -1;
2491 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2493 int upos = 0, wpos = 0;
2494 const unsigned char *utf = (const unsigned char*) utfs;
2495 if (!utf || !wcs || wcslen < 1) {
2496 errno = EINVAL;
2497 return -1;
2499 /* reserve space for \0 */
2500 wcslen--;
2501 if (utflen < 0)
2502 utflen = INT_MAX;
2504 while (upos < utflen) {
2505 int c = utf[upos++] & 0xff;
2506 if (utflen == INT_MAX && c == 0)
2507 break;
2509 if (wpos >= wcslen) {
2510 wcs[wpos] = 0;
2511 errno = ERANGE;
2512 return -1;
2515 if (c < 0x80) {
2516 /* ASCII */
2517 wcs[wpos++] = c;
2518 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2519 (utf[upos] & 0xc0) == 0x80) {
2520 /* 2-byte utf-8 */
2521 c = ((c & 0x1f) << 6);
2522 c |= (utf[upos++] & 0x3f);
2523 wcs[wpos++] = c;
2524 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2525 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2526 (utf[upos] & 0xc0) == 0x80 &&
2527 (utf[upos + 1] & 0xc0) == 0x80) {
2528 /* 3-byte utf-8 */
2529 c = ((c & 0x0f) << 12);
2530 c |= ((utf[upos++] & 0x3f) << 6);
2531 c |= (utf[upos++] & 0x3f);
2532 wcs[wpos++] = c;
2533 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2534 wpos + 1 < wcslen &&
2535 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2536 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2537 (utf[upos] & 0xc0) == 0x80 &&
2538 (utf[upos + 1] & 0xc0) == 0x80 &&
2539 (utf[upos + 2] & 0xc0) == 0x80) {
2540 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2541 c = ((c & 0x07) << 18);
2542 c |= ((utf[upos++] & 0x3f) << 12);
2543 c |= ((utf[upos++] & 0x3f) << 6);
2544 c |= (utf[upos++] & 0x3f);
2545 c -= 0x10000;
2546 wcs[wpos++] = 0xd800 | (c >> 10);
2547 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2548 } else if (c >= 0xa0) {
2549 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2550 wcs[wpos++] = c;
2551 } else {
2552 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2553 static const char *hex = "0123456789abcdef";
2554 wcs[wpos++] = hex[c >> 4];
2555 if (wpos < wcslen)
2556 wcs[wpos++] = hex[c & 0x0f];
2559 wcs[wpos] = 0;
2560 return wpos;
2563 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2565 if (!wcs || !utf || utflen < 1) {
2566 errno = EINVAL;
2567 return -1;
2569 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2570 if (utflen)
2571 return utflen - 1;
2572 errno = ERANGE;
2573 return -1;
2576 static void setup_windows_environment(void)
2578 char *tmp = getenv("TMPDIR");
2580 /* on Windows it is TMP and TEMP */
2581 if (!tmp) {
2582 if (!(tmp = getenv("TMP")))
2583 tmp = getenv("TEMP");
2584 if (tmp) {
2585 setenv("TMPDIR", tmp, 1);
2586 tmp = getenv("TMPDIR");
2590 if (tmp) {
2592 * Convert all dir separators to forward slashes,
2593 * to help shell commands called from the Git
2594 * executable (by not mistaking the dir separators
2595 * for escape characters).
2597 convert_slashes(tmp);
2600 /* simulate TERM to enable auto-color (see color.c) */
2601 if (!getenv("TERM"))
2602 setenv("TERM", "cygwin", 1);
2604 /* calculate HOME if not set */
2605 if (!getenv("HOME")) {
2607 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2608 * location, thus also check if the path exists (i.e. is not
2609 * disconnected)
2611 if ((tmp = getenv("HOMEDRIVE"))) {
2612 struct strbuf buf = STRBUF_INIT;
2613 strbuf_addstr(&buf, tmp);
2614 if ((tmp = getenv("HOMEPATH"))) {
2615 strbuf_addstr(&buf, tmp);
2616 if (is_directory(buf.buf))
2617 setenv("HOME", buf.buf, 1);
2618 else
2619 tmp = NULL; /* use $USERPROFILE */
2621 strbuf_release(&buf);
2623 /* use $USERPROFILE if the home share is not available */
2624 if (!tmp && (tmp = getenv("USERPROFILE")))
2625 setenv("HOME", tmp, 1);
2629 int is_valid_win32_path(const char *path, int allow_literal_nul)
2631 const char *p = path;
2632 int preceding_space_or_period = 0, i = 0, periods = 0;
2634 if (!protect_ntfs)
2635 return 1;
2637 skip_dos_drive_prefix((char **)&path);
2638 goto segment_start;
2640 for (;;) {
2641 char c = *(path++);
2642 switch (c) {
2643 case '\0':
2644 case '/': case '\\':
2645 /* cannot end in ` ` or `.`, except for `.` and `..` */
2646 if (preceding_space_or_period &&
2647 (i != periods || periods > 2))
2648 return 0;
2649 if (!c)
2650 return 1;
2652 i = periods = preceding_space_or_period = 0;
2654 segment_start:
2655 switch (*path) {
2656 case 'a': case 'A': /* AUX */
2657 if (((c = path[++i]) != 'u' && c != 'U') ||
2658 ((c = path[++i]) != 'x' && c != 'X')) {
2659 not_a_reserved_name:
2660 path += i;
2661 continue;
2663 break;
2664 case 'c': case 'C':
2665 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2666 if ((c = path[++i]) != 'o' && c != 'O')
2667 goto not_a_reserved_name;
2668 c = path[++i];
2669 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2670 c = path[++i];
2671 if (c < '1' || c > '9')
2672 goto not_a_reserved_name;
2673 } else if (c == 'n' || c == 'N') { /* CON */
2674 c = path[i + 1];
2675 if ((c == 'i' || c == 'I') &&
2676 ((c = path[i + 2]) == 'n' ||
2677 c == 'N') &&
2678 path[i + 3] == '$')
2679 i += 3; /* CONIN$ */
2680 else if ((c == 'o' || c == 'O') &&
2681 ((c = path[i + 2]) == 'u' ||
2682 c == 'U') &&
2683 ((c = path[i + 3]) == 't' ||
2684 c == 'T') &&
2685 path[i + 4] == '$')
2686 i += 4; /* CONOUT$ */
2687 } else
2688 goto not_a_reserved_name;
2689 break;
2690 case 'l': case 'L': /* LPT<N> */
2691 if (((c = path[++i]) != 'p' && c != 'P') ||
2692 ((c = path[++i]) != 't' && c != 'T') ||
2693 !isdigit(path[++i]))
2694 goto not_a_reserved_name;
2695 break;
2696 case 'n': case 'N': /* NUL */
2697 if (((c = path[++i]) != 'u' && c != 'U') ||
2698 ((c = path[++i]) != 'l' && c != 'L') ||
2699 (allow_literal_nul &&
2700 !path[i + 1] && p == path))
2701 goto not_a_reserved_name;
2702 break;
2703 case 'p': case 'P': /* PRN */
2704 if (((c = path[++i]) != 'r' && c != 'R') ||
2705 ((c = path[++i]) != 'n' && c != 'N'))
2706 goto not_a_reserved_name;
2707 break;
2708 default:
2709 continue;
2713 * So far, this looks like a reserved name. Let's see
2714 * whether it actually is one: trailing spaces, a file
2715 * extension, or an NTFS Alternate Data Stream do not
2716 * matter, the name is still reserved if any of those
2717 * follow immediately after the actual name.
2719 i++;
2720 if (path[i] == ' ') {
2721 preceding_space_or_period = 1;
2722 while (path[++i] == ' ')
2723 ; /* skip all spaces */
2726 c = path[i];
2727 if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2728 goto not_a_reserved_name;
2730 /* contains reserved name */
2731 return 0;
2732 case '.':
2733 periods++;
2734 /* fallthru */
2735 case ' ':
2736 preceding_space_or_period = 1;
2737 i++;
2738 continue;
2739 case ':': /* DOS drive prefix was already skipped */
2740 case '<': case '>': case '"': case '|': case '?': case '*':
2741 /* illegal character */
2742 return 0;
2743 default:
2744 if (c > '\0' && c < '\x20')
2745 /* illegal character */
2746 return 0;
2748 preceding_space_or_period = 0;
2749 i++;
2753 #if !defined(_MSC_VER)
2755 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2756 * mingw startup code, see init.c in mingw runtime).
2758 int _CRT_glob = 0;
2759 #endif
2761 static NORETURN void die_startup(void)
2763 fputs("fatal: not enough memory for initialization", stderr);
2764 exit(128);
2767 static void *malloc_startup(size_t size)
2769 void *result = malloc(size);
2770 if (!result)
2771 die_startup();
2772 return result;
2775 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2777 len = xwcstoutf(buffer, wcs, len) + 1;
2778 return memcpy(malloc_startup(len), buffer, len);
2781 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2782 DWORD desired_access, DWORD flags)
2784 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2785 wchar_t buf[MAX_PATH];
2786 DWORD max = ARRAY_SIZE(buf);
2787 HANDLE handle;
2788 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2790 if (!ret || ret >= max)
2791 return;
2793 /* make sure this does not leak into child processes */
2794 SetEnvironmentVariableW(key, NULL);
2795 if (!wcscmp(buf, L"off")) {
2796 close(fd);
2797 handle = GetStdHandle(std_id);
2798 if (handle != INVALID_HANDLE_VALUE)
2799 CloseHandle(handle);
2800 return;
2802 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2803 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2804 if (handle == INVALID_HANDLE_VALUE) {
2805 close(fd);
2806 handle = GetStdHandle(std_id);
2807 if (handle != INVALID_HANDLE_VALUE)
2808 CloseHandle(handle);
2809 } else {
2810 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2811 SetStdHandle(std_id, handle);
2812 dup2(new_fd, fd);
2813 /* do *not* close the new_fd: that would close stdout */
2815 return;
2817 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2818 flags, NULL);
2819 if (handle != INVALID_HANDLE_VALUE) {
2820 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2821 SetStdHandle(std_id, handle);
2822 dup2(new_fd, fd);
2823 close(new_fd);
2827 static void maybe_redirect_std_handles(void)
2829 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2830 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2831 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2832 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2833 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2834 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2837 #ifdef _MSC_VER
2838 #ifdef _DEBUG
2839 #include <crtdbg.h>
2840 #endif
2841 #endif
2844 * We implement wmain() and compile with -municode, which would
2845 * normally ignore main(), but we call the latter from the former
2846 * so that we can handle non-ASCII command-line parameters
2847 * appropriately.
2849 * To be more compatible with the core git code, we convert
2850 * argv into UTF8 and pass them directly to main().
2852 int wmain(int argc, const wchar_t **wargv)
2854 int i, maxlen, exit_status;
2855 char *buffer, **save;
2856 const char **argv;
2858 trace2_initialize_clock();
2860 #ifdef _MSC_VER
2861 #ifdef _DEBUG
2862 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2863 #endif
2865 #ifdef USE_MSVC_CRTDBG
2866 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2867 #endif
2868 #endif
2870 maybe_redirect_std_handles();
2872 /* determine size of argv and environ conversion buffer */
2873 maxlen = wcslen(wargv[0]);
2874 for (i = 1; i < argc; i++)
2875 maxlen = max(maxlen, wcslen(wargv[i]));
2877 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2878 maxlen = 3 * maxlen + 1;
2879 buffer = malloc_startup(maxlen);
2882 * Create a UTF-8 version of w_argv. Also create a "save" copy
2883 * to remember all the string pointers because parse_options()
2884 * will remove claimed items from the argv that we pass down.
2886 ALLOC_ARRAY(argv, argc + 1);
2887 ALLOC_ARRAY(save, argc + 1);
2888 for (i = 0; i < argc; i++)
2889 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2890 argv[i] = save[i] = NULL;
2891 free(buffer);
2893 /* fix Windows specific environment settings */
2894 setup_windows_environment();
2896 unset_environment_variables = xstrdup("PERL5LIB");
2898 /* initialize critical section for waitpid pinfo_t list */
2899 InitializeCriticalSection(&pinfo_cs);
2901 /* set up default file mode and file modes for stdin/out/err */
2902 _fmode = _O_BINARY;
2903 _setmode(_fileno(stdin), _O_BINARY);
2904 _setmode(_fileno(stdout), _O_BINARY);
2905 _setmode(_fileno(stderr), _O_BINARY);
2907 /* initialize Unicode console */
2908 winansi_init();
2910 /* invoke the real main() using our utf8 version of argv. */
2911 exit_status = main(argc, argv);
2913 for (i = 0; i < argc; i++)
2914 free(save[i]);
2915 free(save);
2916 free(argv);
2918 return exit_status;
2921 int uname(struct utsname *buf)
2923 unsigned v = (unsigned)GetVersion();
2924 memset(buf, 0, sizeof(*buf));
2925 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2926 xsnprintf(buf->release, sizeof(buf->release),
2927 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2928 /* assuming NT variants only.. */
2929 xsnprintf(buf->version, sizeof(buf->version),
2930 "%u", (v >> 16) & 0x7fff);
2931 return 0;