1 #include "../git-compat-util.h"
6 #include "../run-command.h"
8 #include "win32/lazyload.h"
12 #define HCAST(type, handle) ((type)(intptr_t)handle)
14 static const int delay[] = { 0, 1, 10, 20, 40 };
16 int err_win_to_posix(DWORD winerr)
20 case ERROR_ACCESS_DENIED: error = EACCES; break;
21 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
22 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
23 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
24 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
25 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
26 case ERROR_BAD_COMMAND: error = EIO; break;
27 case ERROR_BAD_DEVICE: error = ENODEV; break;
28 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
29 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
30 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
31 case ERROR_BAD_LENGTH: error = EINVAL; break;
32 case ERROR_BAD_PATHNAME: error = ENOENT; break;
33 case ERROR_BAD_PIPE: error = EPIPE; break;
34 case ERROR_BAD_UNIT: error = ENODEV; break;
35 case ERROR_BAD_USERNAME: error = EINVAL; break;
36 case ERROR_BROKEN_PIPE: error = EPIPE; break;
37 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
38 case ERROR_BUSY: error = EBUSY; break;
39 case ERROR_BUSY_DRIVE: error = EBUSY; break;
40 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
41 case ERROR_CANNOT_MAKE: error = EACCES; break;
42 case ERROR_CANTOPEN: error = EIO; break;
43 case ERROR_CANTREAD: error = EIO; break;
44 case ERROR_CANTWRITE: error = EIO; break;
45 case ERROR_CRC: error = EIO; break;
46 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
47 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
48 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
49 case ERROR_DIRECTORY: error = EINVAL; break;
50 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
51 case ERROR_DISK_CHANGE: error = EIO; break;
52 case ERROR_DISK_FULL: error = ENOSPC; break;
53 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
54 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
55 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
56 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
57 case ERROR_FILE_EXISTS: error = EEXIST; break;
58 case ERROR_FILE_INVALID: error = ENODEV; break;
59 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
60 case ERROR_GEN_FAILURE: error = EIO; break;
61 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
62 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
63 case ERROR_INVALID_ACCESS: error = EACCES; break;
64 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
65 case ERROR_INVALID_BLOCK: error = EFAULT; break;
66 case ERROR_INVALID_DATA: error = EINVAL; break;
67 case ERROR_INVALID_DRIVE: error = ENODEV; break;
68 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
69 case ERROR_INVALID_FLAGS: error = EINVAL; break;
70 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
71 case ERROR_INVALID_HANDLE: error = EBADF; break;
72 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
73 case ERROR_INVALID_NAME: error = EINVAL; break;
74 case ERROR_INVALID_OWNER: error = EINVAL; break;
75 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
76 case ERROR_INVALID_PASSWORD: error = EPERM; break;
77 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
78 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
79 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
80 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
81 case ERROR_IO_DEVICE: error = EIO; break;
82 case ERROR_IO_INCOMPLETE: error = EINTR; break;
83 case ERROR_LOCKED: error = EBUSY; break;
84 case ERROR_LOCK_VIOLATION: error = EACCES; break;
85 case ERROR_LOGON_FAILURE: error = EACCES; break;
86 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
87 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
88 case ERROR_MORE_DATA: error = EPIPE; break;
89 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
90 case ERROR_NOACCESS: error = EFAULT; break;
91 case ERROR_NONE_MAPPED: error = EINVAL; break;
92 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
93 case ERROR_NOT_READY: error = EAGAIN; break;
94 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
95 case ERROR_NO_DATA: error = EPIPE; break;
96 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
97 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
98 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
99 case ERROR_OPEN_FAILED: error = EIO; break;
100 case ERROR_OPEN_FILES: error = EBUSY; break;
101 case ERROR_OPERATION_ABORTED: error = EINTR; break;
102 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
103 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
104 case ERROR_PATH_BUSY: error = EBUSY; break;
105 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
106 case ERROR_PIPE_BUSY: error = EBUSY; break;
107 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
108 case ERROR_PIPE_LISTENING: error = EPIPE; break;
109 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
110 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
111 case ERROR_READ_FAULT: error = EIO; break;
112 case ERROR_SEEK: error = EIO; break;
113 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
114 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
115 case ERROR_SHARING_VIOLATION: error = EACCES; break;
116 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
117 case ERROR_SWAPERROR: error = ENOENT; break;
118 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
119 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
120 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
121 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
122 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
123 case ERROR_WRITE_FAULT: error = EIO; break;
124 case ERROR_WRITE_PROTECT: error = EROFS; break;
129 static inline int is_file_in_use_error(DWORD errcode)
132 case ERROR_SHARING_VIOLATION:
133 case ERROR_ACCESS_DENIED:
140 static int read_yes_no_answer(void)
144 if (fgets(answer, sizeof(answer), stdin)) {
145 size_t answer_len = strlen(answer);
146 int got_full_line = 0, c;
148 /* remove the newline */
149 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
150 answer[answer_len-2] = '\0';
152 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
153 answer[answer_len-1] = '\0';
156 /* flush the buffer in case we did not get the full line */
158 while ((c = getchar()) != EOF && c != '\n')
161 /* we could not read, return the
162 * default answer which is no */
165 if (tolower(answer[0]) == 'y' && !answer[1])
167 if (!strncasecmp(answer, "yes", sizeof(answer)))
169 if (tolower(answer[0]) == 'n' && !answer[1])
171 if (!strncasecmp(answer, "no", sizeof(answer)))
174 /* did not find an answer we understand */
178 static int ask_yes_no_if_possible(const char *format, ...)
181 const char *retry_hook[] = { NULL, NULL, NULL };
184 va_start(args, format);
185 vsnprintf(question, sizeof(question), format, args);
188 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
189 retry_hook[1] = question;
190 return !run_command_v_opt(retry_hook, 0);
193 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
198 fprintf(stderr, "%s (y/n) ", question);
200 if ((answer = read_yes_no_answer()) >= 0)
203 fprintf(stderr, "Sorry, I did not understand your answer. "
204 "Please type 'y' or 'n'\n");
209 enum hide_dotfiles_type {
210 HIDE_DOTFILES_FALSE = 0,
212 HIDE_DOTFILES_DOTGITONLY
215 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
216 static char *unset_environment_variables;
218 int mingw_core_config(const char *var, const char *value, void *cb)
220 if (!strcmp(var, "core.hidedotfiles")) {
221 if (value && !strcasecmp(value, "dotgitonly"))
222 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
224 hide_dotfiles = git_config_bool(var, value);
228 if (!strcmp(var, "core.unsetenvvars")) {
229 free(unset_environment_variables);
230 unset_environment_variables = xstrdup(value);
237 /* Normalizes NT paths as returned by some low-level APIs. */
238 static wchar_t *normalize_ntpath(wchar_t *wbuf)
241 /* fix absolute path prefixes */
242 if (wbuf[0] == '\\') {
243 /* strip NT namespace prefixes */
244 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
245 !wcsncmp(wbuf, L"\\\\?\\", 4))
247 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
249 /* replace remaining '...UNC\' with '\\' */
250 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
255 /* convert backslashes to slashes */
256 for (i = 0; wbuf[i]; i++)
262 int mingw_unlink(const char *pathname)
265 wchar_t wpathname[MAX_PATH];
266 if (xutftowcs_path(wpathname, pathname) < 0)
269 /* read-only files cannot be removed */
270 _wchmod(wpathname, 0666);
271 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
272 if (!is_file_in_use_error(GetLastError()))
275 * We assume that some other process had the source or
276 * destination file open at the wrong moment and retry.
277 * In order to give the other process a higher chance to
278 * complete its operation, we give up our time slice now.
279 * If we have to retry again, we do sleep a bit.
284 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
285 ask_yes_no_if_possible("Unlink of file '%s' failed. "
286 "Should I try again?", pathname))
287 ret = _wunlink(wpathname);
291 static int is_dir_empty(const wchar_t *wpath)
293 WIN32_FIND_DATAW findbuf;
295 wchar_t wbuf[MAX_PATH + 2];
297 wcscat(wbuf, L"\\*");
298 handle = FindFirstFileW(wbuf, &findbuf);
299 if (handle == INVALID_HANDLE_VALUE)
300 return GetLastError() == ERROR_NO_MORE_FILES;
302 while (!wcscmp(findbuf.cFileName, L".") ||
303 !wcscmp(findbuf.cFileName, L".."))
304 if (!FindNextFileW(handle, &findbuf)) {
305 DWORD err = GetLastError();
307 return err == ERROR_NO_MORE_FILES;
313 int mingw_rmdir(const char *pathname)
316 wchar_t wpathname[MAX_PATH];
317 if (xutftowcs_path(wpathname, pathname) < 0)
320 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
321 if (!is_file_in_use_error(GetLastError()))
322 errno = err_win_to_posix(GetLastError());
325 if (!is_dir_empty(wpathname)) {
330 * We assume that some other process had the source or
331 * destination file open at the wrong moment and retry.
332 * In order to give the other process a higher chance to
333 * complete its operation, we give up our time slice now.
334 * If we have to retry again, we do sleep a bit.
339 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
340 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
341 "Should I try again?", pathname))
342 ret = _wrmdir(wpathname);
346 static inline int needs_hiding(const char *path)
348 const char *basename;
350 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
353 /* We cannot use basename(), as it would remove trailing slashes */
354 win32_skip_dos_drive_prefix((char **)&path);
358 for (basename = path; *path; path++)
359 if (is_dir_sep(*path)) {
362 } while (is_dir_sep(*path));
363 /* ignore trailing slashes */
368 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
369 return *basename == '.';
371 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
372 return !strncasecmp(".git", basename, 4) &&
373 (!basename[4] || is_dir_sep(basename[4]));
376 static int set_hidden_flag(const wchar_t *path, int set)
378 DWORD original = GetFileAttributesW(path), modified;
380 modified = original | FILE_ATTRIBUTE_HIDDEN;
382 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
383 if (original == modified || SetFileAttributesW(path, modified))
385 errno = err_win_to_posix(GetLastError());
389 int mingw_mkdir(const char *path, int mode)
392 wchar_t wpath[MAX_PATH];
393 if (xutftowcs_path(wpath, path) < 0)
395 ret = _wmkdir(wpath);
396 if (!ret && needs_hiding(path))
397 return set_hidden_flag(wpath, 1);
402 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
403 * is documented in [1] as opening a writable file handle in append mode.
404 * (It is believed that) this is atomic since it is maintained by the
405 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
407 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
409 * This trick does not appear to work for named pipes. Instead it creates
410 * a named pipe client handle that cannot be written to. Callers should
411 * just use the regular _wopen() for them. (And since client handle gets
412 * bound to a unique server handle, it isn't really an issue.)
414 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
418 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
420 /* only these flags are supported */
421 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
422 return errno = ENOSYS, -1;
425 * FILE_SHARE_WRITE is required to permit child processes
426 * to append to the file.
428 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
429 FILE_SHARE_WRITE | FILE_SHARE_READ,
430 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
431 if (handle == INVALID_HANDLE_VALUE)
432 return errno = err_win_to_posix(GetLastError()), -1;
435 * No O_APPEND here, because the CRT uses it only to reset the
436 * file pointer to EOF before each write(); but that is not
437 * necessary (and may lead to races) for a file created with
440 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
447 * Does the pathname map to the local named pipe filesystem?
448 * That is, does it have a "//./pipe/" prefix?
450 static int is_local_named_pipe_path(const char *filename)
452 return (is_dir_sep(filename[0]) &&
453 is_dir_sep(filename[1]) &&
454 filename[2] == '.' &&
455 is_dir_sep(filename[3]) &&
456 !strncasecmp(filename+4, "pipe", 4) &&
457 is_dir_sep(filename[8]) &&
461 int mingw_open (const char *filename, int oflags, ...)
463 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
467 wchar_t wfilename[MAX_PATH];
470 va_start(args, oflags);
471 mode = va_arg(args, int);
474 if (filename && !strcmp(filename, "/dev/null"))
477 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
478 open_fn = mingw_open_append;
482 if (xutftowcs_path(wfilename, filename) < 0)
484 fd = open_fn(wfilename, oflags, mode);
486 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
487 DWORD attrs = GetFileAttributesW(wfilename);
488 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
491 if ((oflags & O_CREAT) && needs_hiding(filename)) {
493 * Internally, _wopen() uses the CreateFile() API which errors
494 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
495 * specified and an already existing file's attributes do not
496 * match *exactly*. As there is no mode or flag we can set that
497 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
498 * again *without* the O_CREAT flag (that corresponds to the
499 * CREATE_ALWAYS flag of CreateFile()).
501 if (fd < 0 && errno == EACCES)
502 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
503 if (fd >= 0 && set_hidden_flag(wfilename, 1))
504 warning("could not mark '%s' as hidden.", filename);
509 static BOOL WINAPI ctrl_ignore(DWORD type)
515 int mingw_fgetc(FILE *stream)
518 if (!isatty(_fileno(stream)))
519 return fgetc(stream);
521 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
524 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
527 /* Ctrl+C was pressed, simulate SIGINT and retry */
530 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
535 FILE *mingw_fopen (const char *filename, const char *otype)
537 int hide = needs_hiding(filename);
539 wchar_t wfilename[MAX_PATH], wotype[4];
540 if (filename && !strcmp(filename, "/dev/null"))
542 if (xutftowcs_path(wfilename, filename) < 0 ||
543 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
545 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
546 error("could not unhide %s", filename);
549 file = _wfopen(wfilename, wotype);
550 if (!file && GetLastError() == ERROR_INVALID_NAME)
552 if (file && hide && set_hidden_flag(wfilename, 1))
553 warning("could not mark '%s' as hidden.", filename);
557 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
559 int hide = needs_hiding(filename);
561 wchar_t wfilename[MAX_PATH], wotype[4];
562 if (filename && !strcmp(filename, "/dev/null"))
564 if (xutftowcs_path(wfilename, filename) < 0 ||
565 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
567 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
568 error("could not unhide %s", filename);
571 file = _wfreopen(wfilename, wotype, stream);
572 if (file && hide && set_hidden_flag(wfilename, 1))
573 warning("could not mark '%s' as hidden.", filename);
578 int mingw_fflush(FILE *stream)
580 int ret = fflush(stream);
583 * write() is used behind the scenes of stdio output functions.
584 * Since git code does not check for errors after each stdio write
585 * operation, it can happen that write() is called by a later
586 * stdio function even if an earlier write() call failed. In the
587 * case of a pipe whose readable end was closed, only the first
588 * call to write() reports EPIPE on Windows. Subsequent write()
589 * calls report EINVAL. It is impossible to notice whether this
590 * fflush invocation triggered such a case, therefore, we have to
591 * catch all EINVAL errors whole-sale.
593 if (ret && errno == EINVAL)
600 ssize_t mingw_write(int fd, const void *buf, size_t len)
602 ssize_t result = write(fd, buf, len);
604 if (result < 0 && errno == EINVAL && buf) {
605 /* check if fd is a pipe */
606 HANDLE h = (HANDLE) _get_osfhandle(fd);
607 if (GetFileType(h) == FILE_TYPE_PIPE)
616 int mingw_access(const char *filename, int mode)
618 wchar_t wfilename[MAX_PATH];
619 if (xutftowcs_path(wfilename, filename) < 0)
621 /* X_OK is not supported by the MSVCRT version */
622 return _waccess(wfilename, mode & ~X_OK);
625 int mingw_chdir(const char *dirname)
627 wchar_t wdirname[MAX_PATH];
628 if (xutftowcs_path(wdirname, dirname) < 0)
630 return _wchdir(wdirname);
633 int mingw_chmod(const char *filename, int mode)
635 wchar_t wfilename[MAX_PATH];
636 if (xutftowcs_path(wfilename, filename) < 0)
638 return _wchmod(wfilename, mode);
642 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
643 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
645 static inline long long filetime_to_hnsec(const FILETIME *ft)
647 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
648 /* Windows to Unix Epoch conversion */
649 return winTime - 116444736000000000LL;
652 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
654 long long hnsec = filetime_to_hnsec(ft);
655 ts->tv_sec = (time_t)(hnsec / 10000000);
656 ts->tv_nsec = (hnsec % 10000000) * 100;
660 * Verifies that safe_create_leading_directories() would succeed.
662 static int has_valid_directory_prefix(wchar_t *wfilename)
664 int n = wcslen(wfilename);
667 wchar_t c = wfilename[--n];
673 wfilename[n] = L'\0';
674 attributes = GetFileAttributesW(wfilename);
676 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
677 attributes == FILE_ATTRIBUTE_DEVICE)
679 if (attributes == INVALID_FILE_ATTRIBUTES)
680 switch (GetLastError()) {
681 case ERROR_PATH_NOT_FOUND:
683 case ERROR_FILE_NOT_FOUND:
684 /* This implies parent directory exists. */
692 /* We keep the do_lstat code in a separate function to avoid recursion.
693 * When a path ends with a slash, the stat will fail with ENOENT. In
694 * this case, we strip the trailing slashes and stat again.
696 * If follow is true then act like stat() and report on the link
697 * target. Otherwise report on the link itself.
699 static int do_lstat(int follow, const char *file_name, struct stat *buf)
701 WIN32_FILE_ATTRIBUTE_DATA fdata;
702 wchar_t wfilename[MAX_PATH];
703 if (xutftowcs_path(wfilename, file_name) < 0)
706 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
711 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
712 buf->st_size = fdata.nFileSizeLow |
713 (((off_t)fdata.nFileSizeHigh)<<32);
714 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
715 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
716 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
717 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
718 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
719 WIN32_FIND_DATAW findbuf;
720 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
721 if (handle != INVALID_HANDLE_VALUE) {
722 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
723 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
725 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
726 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
728 buf->st_mode = S_IFLNK;
730 buf->st_mode |= S_IREAD;
731 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
732 buf->st_mode |= S_IWRITE;
739 switch (GetLastError()) {
740 case ERROR_ACCESS_DENIED:
741 case ERROR_SHARING_VIOLATION:
742 case ERROR_LOCK_VIOLATION:
743 case ERROR_SHARING_BUFFER_EXCEEDED:
746 case ERROR_BUFFER_OVERFLOW:
747 errno = ENAMETOOLONG;
749 case ERROR_NOT_ENOUGH_MEMORY:
752 case ERROR_PATH_NOT_FOUND:
753 if (!has_valid_directory_prefix(wfilename)) {
765 /* We provide our own lstat/fstat functions, since the provided
766 * lstat/fstat functions are so slow. These stat functions are
767 * tailored for Git's usage (read: fast), and are not meant to be
768 * complete. Note that Git stat()s are redirected to mingw_lstat()
769 * too, since Windows doesn't really handle symlinks that well.
771 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
774 char alt_name[PATH_MAX];
776 if (!do_lstat(follow, file_name, buf))
779 /* if file_name ended in a '/', Windows returned ENOENT;
780 * try again without trailing slashes
785 namelen = strlen(file_name);
786 if (namelen && file_name[namelen-1] != '/')
788 while (namelen && file_name[namelen-1] == '/')
790 if (!namelen || namelen >= PATH_MAX)
793 memcpy(alt_name, file_name, namelen);
794 alt_name[namelen] = 0;
795 return do_lstat(follow, alt_name, buf);
798 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
800 BY_HANDLE_FILE_INFORMATION fdata;
802 if (!GetFileInformationByHandle(hnd, &fdata)) {
803 errno = err_win_to_posix(GetLastError());
811 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
812 buf->st_size = fdata.nFileSizeLow |
813 (((off_t)fdata.nFileSizeHigh)<<32);
814 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
815 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
816 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
817 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
821 int mingw_lstat(const char *file_name, struct stat *buf)
823 return do_stat_internal(0, file_name, buf);
825 int mingw_stat(const char *file_name, struct stat *buf)
827 return do_stat_internal(1, file_name, buf);
830 int mingw_fstat(int fd, struct stat *buf)
832 HANDLE fh = (HANDLE)_get_osfhandle(fd);
833 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
837 return get_file_info_by_handle(fh, buf);
841 /* initialize stat fields */
842 memset(buf, 0, sizeof(*buf));
845 if (type == FILE_TYPE_CHAR) {
846 buf->st_mode = _S_IFCHR;
848 buf->st_mode = _S_IFIFO;
849 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
850 buf->st_size = avail;
860 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
862 long long winTime = t * 10000000LL + 116444736000000000LL;
863 ft->dwLowDateTime = winTime;
864 ft->dwHighDateTime = winTime >> 32;
867 int mingw_utime (const char *file_name, const struct utimbuf *times)
872 wchar_t wfilename[MAX_PATH];
873 if (xutftowcs_path(wfilename, file_name) < 0)
876 /* must have write permission */
877 attrs = GetFileAttributesW(wfilename);
878 if (attrs != INVALID_FILE_ATTRIBUTES &&
879 (attrs & FILE_ATTRIBUTE_READONLY)) {
880 /* ignore errors here; open() will report them */
881 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
884 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
890 time_t_to_filetime(times->modtime, &mft);
891 time_t_to_filetime(times->actime, &aft);
893 GetSystemTimeAsFileTime(&mft);
896 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
904 if (attrs != INVALID_FILE_ATTRIBUTES &&
905 (attrs & FILE_ATTRIBUTE_READONLY)) {
906 /* ignore errors again */
907 SetFileAttributesW(wfilename, attrs);
913 size_t mingw_strftime(char *s, size_t max,
914 const char *format, const struct tm *tm)
916 size_t ret = strftime(s, max, format, tm);
918 if (!ret && errno == EINVAL)
919 die("invalid strftime format: '%s'", format);
923 unsigned int sleep (unsigned int seconds)
929 char *mingw_mktemp(char *template)
931 wchar_t wtemplate[MAX_PATH];
932 if (xutftowcs_path(wtemplate, template) < 0)
934 if (!_wmktemp(wtemplate))
936 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
941 int mkstemp(char *template)
943 char *filename = mktemp(template);
944 if (filename == NULL)
946 return open(filename, O_RDWR | O_CREAT, 0600);
949 int gettimeofday(struct timeval *tv, void *tz)
954 GetSystemTimeAsFileTime(&ft);
955 hnsec = filetime_to_hnsec(&ft);
956 tv->tv_sec = hnsec / 10000000;
957 tv->tv_usec = (hnsec % 10000000) / 10;
961 int pipe(int filedes[2])
965 /* this creates non-inheritable handles */
966 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
967 errno = err_win_to_posix(GetLastError());
970 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
971 if (filedes[0] < 0) {
976 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
977 if (filedes[1] < 0) {
985 struct tm *gmtime_r(const time_t *timep, struct tm *result)
987 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
988 memcpy(result, gmtime(timep), sizeof(struct tm));
992 struct tm *localtime_r(const time_t *timep, struct tm *result)
994 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
995 memcpy(result, localtime(timep), sizeof(struct tm));
999 char *mingw_getcwd(char *pointer, int len)
1001 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1002 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1004 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1005 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1008 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1009 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1010 HANDLE hnd = CreateFileW(cwd, 0,
1011 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1012 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1013 if (hnd == INVALID_HANDLE_VALUE)
1015 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1017 if (!ret || ret >= ARRAY_SIZE(wpointer))
1019 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1023 if (!ret || ret >= ARRAY_SIZE(wpointer))
1025 if (xwcstoutf(pointer, wpointer, len) < 0)
1027 convert_slashes(pointer);
1032 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1033 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1035 static const char *quote_arg_msvc(const char *arg)
1037 /* count chars to quote */
1039 int force_quotes = 0;
1041 const char *p = arg;
1042 if (!*p) force_quotes = 1;
1044 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1048 else if (*p == '\\') {
1050 while (*p == '\\') {
1062 if (!force_quotes && n == 0)
1065 /* insert \ where necessary */
1066 d = q = xmalloc(st_add3(len, n, 3));
1071 else if (*arg == '\\') {
1073 while (*arg == '\\') {
1092 static const char *quote_arg_msys2(const char *arg)
1094 struct strbuf buf = STRBUF_INIT;
1095 const char *p2 = arg, *p;
1097 for (p = arg; *p; p++) {
1098 int ws = isspace(*p);
1099 if (!ws && *p != '\\' && *p != '"' && *p != '{')
1102 strbuf_addch(&buf, '"');
1104 strbuf_add(&buf, p2, p - p2);
1105 if (!ws && *p != '{')
1106 strbuf_addch(&buf, '\\');
1111 strbuf_addch(&buf, '"');
1115 strbuf_add(&buf, p2, p - p2),
1117 strbuf_addch(&buf, '"');
1118 return strbuf_detach(&buf, 0);
1121 static const char *parse_interpreter(const char *cmd)
1123 static char buf[100];
1127 /* don't even try a .exe */
1129 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1132 fd = open(cmd, O_RDONLY);
1135 n = read(fd, buf, sizeof(buf)-1);
1137 if (n < 4) /* at least '#!/x' and not error */
1140 if (buf[0] != '#' || buf[1] != '!')
1143 p = buf + strcspn(buf, "\r\n");
1148 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1151 if ((opt = strchr(p+1, ' ')))
1157 * exe_only means that we only want to detect .exe files, but not scripts
1158 * (which do not have an extension)
1160 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1161 int isexe, int exe_only)
1163 char path[MAX_PATH];
1164 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1166 if (!isexe && access(path, F_OK) == 0)
1167 return xstrdup(path);
1168 path[strlen(path)-4] = '\0';
1169 if ((!exe_only || isexe) && access(path, F_OK) == 0)
1170 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
1171 return xstrdup(path);
1176 * Determines the absolute path of cmd using the split path in path.
1177 * If cmd contains a slash or backslash, no lookup is performed.
1179 static char *path_lookup(const char *cmd, int exe_only)
1183 int len = strlen(cmd);
1184 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1186 if (strchr(cmd, '/') || strchr(cmd, '\\'))
1187 return xstrdup(cmd);
1189 path = mingw_getenv("PATH");
1194 const char *sep = strchrnul(path, ';');
1195 int dirlen = sep - path;
1197 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1206 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1208 while (*s && *s != c)
1213 /* Compare only keys */
1214 static int wenvcmp(const void *a, const void *b)
1216 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1217 size_t p_len, q_len;
1220 p_len = wcschrnul(p, L'=') - p;
1221 q_len = wcschrnul(q, L'=') - q;
1223 /* If the length differs, include the shorter key's NUL */
1226 else if (p_len > q_len)
1229 return _wcsnicmp(p, q, p_len);
1232 /* We need a stable sort to convert the environment between UTF-16 <-> UTF-8 */
1233 #ifndef INTERNAL_QSORT
1238 * Build an environment block combining the inherited environment
1239 * merged with the given list of settings.
1241 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1242 * Values of the form "KEY" in deltaenv delete inherited values.
1244 * Multiple entries in deltaenv for the same key are explicitly allowed.
1246 * We return a contiguous block of UNICODE strings with a final trailing
1249 static wchar_t *make_environment_block(char **deltaenv)
1251 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1252 size_t wlen, s, delta_size, size;
1254 wchar_t **array = NULL;
1255 size_t alloc = 0, nr = 0, i;
1257 size = 1; /* for extra NUL at the end */
1259 /* If there is no deltaenv to apply, simply return a copy. */
1260 if (!deltaenv || !*deltaenv) {
1261 for (p = wenv; p && *p; ) {
1262 size_t s = wcslen(p) + 1;
1267 ALLOC_ARRAY(result, size);
1268 memcpy(result, wenv, size * sizeof(*wenv));
1269 FreeEnvironmentStringsW(wenv);
1274 * If there is a deltaenv, let's accumulate all keys into `array`,
1275 * sort them using the stable git_qsort() and then copy, skipping
1278 for (p = wenv; p && *p; ) {
1279 ALLOC_GROW(array, nr + 1, alloc);
1286 /* (over-)assess size needed for wchar version of deltaenv */
1287 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1288 delta_size += strlen(deltaenv[i]) * 2 + 1;
1289 ALLOC_ARRAY(wdeltaenv, delta_size);
1291 /* convert the deltaenv, appending to array */
1292 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1293 ALLOC_GROW(array, nr + 1, alloc);
1294 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1299 git_qsort(array, nr, sizeof(*array), wenvcmp);
1300 ALLOC_ARRAY(result, size + delta_size);
1302 for (p = result, i = 0; i < nr; i++) {
1303 /* Skip any duplicate keys; last one wins */
1304 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1307 /* Skip "to delete" entry */
1308 if (!wcschr(array[i], L'='))
1311 size = wcslen(array[i]) + 1;
1312 memcpy(p, array[i], size * sizeof(*p));
1319 FreeEnvironmentStringsW(wenv);
1323 static void do_unset_environment_variables(void)
1326 char *p = unset_environment_variables;
1333 char *comma = strchr(p, ',');
1345 struct pinfo_t *next;
1349 static struct pinfo_t *pinfo = NULL;
1350 CRITICAL_SECTION pinfo_cs;
1352 /* Used to match and chomp off path components */
1353 static inline int match_last_path_component(const char *path, size_t *len,
1354 const char *component)
1356 size_t component_len = strlen(component);
1357 if (*len < component_len + 1 ||
1358 !is_dir_sep(path[*len - component_len - 1]) ||
1359 fspathncmp(path + *len - component_len, component, component_len))
1361 *len -= component_len + 1;
1362 /* chomp off repeated dir separators */
1363 while (*len > 0 && is_dir_sep(path[*len - 1]))
1368 static int is_msys2_sh(const char *cmd)
1370 if (cmd && !strcmp(cmd, "sh")) {
1371 static int ret = -1;
1377 p = path_lookup(cmd, 0);
1381 size_t len = strlen(p);
1383 ret = match_last_path_component(p, &len, "sh.exe") &&
1384 match_last_path_component(p, &len, "bin") &&
1385 match_last_path_component(p, &len, "usr");
1393 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1395 int prepend_cmd, int fhin, int fhout, int fherr)
1398 PROCESS_INFORMATION pi;
1400 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1401 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1404 const char *(*quote_arg)(const char *arg) =
1405 is_msys2_sh(*argv) ? quote_arg_msys2 : quote_arg_msvc;
1407 do_unset_environment_variables();
1409 /* Determine whether or not we are associated to a console */
1410 cons = CreateFile("CONOUT$", GENERIC_WRITE,
1411 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1412 FILE_ATTRIBUTE_NORMAL, NULL);
1413 if (cons == INVALID_HANDLE_VALUE) {
1414 /* There is no console associated with this process.
1415 * Since the child is a console process, Windows
1416 * would normally create a console window. But
1417 * since we'll be redirecting std streams, we do
1418 * not need the console.
1419 * It is necessary to use DETACHED_PROCESS
1420 * instead of CREATE_NO_WINDOW to make ssh
1421 * recognize that it has no console.
1423 flags |= DETACHED_PROCESS;
1425 /* There is already a console. If we specified
1426 * DETACHED_PROCESS here, too, Windows would
1427 * disassociate the child from the console.
1428 * The same is true for CREATE_NO_WINDOW.
1433 memset(&si, 0, sizeof(si));
1435 si.dwFlags = STARTF_USESTDHANDLES;
1436 si.hStdInput = winansi_get_osfhandle(fhin);
1437 si.hStdOutput = winansi_get_osfhandle(fhout);
1438 si.hStdError = winansi_get_osfhandle(fherr);
1440 if (xutftowcs_path(wcmd, cmd) < 0)
1442 if (dir && xutftowcs_path(wdir, dir) < 0)
1445 /* concatenate argv, quoting args as we go */
1446 strbuf_init(&args, 0);
1448 char *quoted = (char *)quote_arg(cmd);
1449 strbuf_addstr(&args, quoted);
1453 for (; *argv; argv++) {
1454 char *quoted = (char *)quote_arg(*argv);
1456 strbuf_addch(&args, ' ');
1457 strbuf_addstr(&args, quoted);
1458 if (quoted != *argv)
1462 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1463 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1464 strbuf_release(&args);
1466 wenvblk = make_environment_block(deltaenv);
1468 memset(&pi, 0, sizeof(pi));
1469 ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,
1470 wenvblk, dir ? wdir : NULL, &si, &pi);
1479 CloseHandle(pi.hThread);
1482 * The process ID is the human-readable identifier of the process
1483 * that we want to present in log and error messages. The handle
1484 * is not useful for this purpose. But we cannot close it, either,
1485 * because it is not possible to turn a process ID into a process
1486 * handle after the process terminated.
1487 * Keep the handle in a list for waitpid.
1489 EnterCriticalSection(&pinfo_cs);
1491 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1492 info->pid = pi.dwProcessId;
1493 info->proc = pi.hProcess;
1497 LeaveCriticalSection(&pinfo_cs);
1499 return (pid_t)pi.dwProcessId;
1502 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1504 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1507 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1509 int fhin, int fhout, int fherr)
1512 char *prog = path_lookup(cmd, 0);
1519 const char *interpr = parse_interpreter(prog);
1522 const char *argv0 = argv[0];
1523 char *iprog = path_lookup(interpr, 1);
1530 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1531 fhin, fhout, fherr);
1537 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1538 fhin, fhout, fherr);
1544 static int try_shell_exec(const char *cmd, char *const *argv)
1546 const char *interpr = parse_interpreter(cmd);
1552 prog = path_lookup(interpr, 1);
1557 while (argv[argc]) argc++;
1558 ALLOC_ARRAY(argv2, argc + 1);
1559 argv2[0] = (char *)cmd; /* full path to the script file */
1560 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1561 exec_id = trace2_exec(prog, argv2);
1562 pid = mingw_spawnv(prog, argv2, 1);
1565 if (waitpid(pid, &status, 0) < 0)
1567 trace2_exec_result(exec_id, status);
1570 trace2_exec_result(exec_id, -1);
1571 pid = 1; /* indicate that we tried but failed */
1578 int mingw_execv(const char *cmd, char *const *argv)
1580 /* check if git_command is a shell script */
1581 if (!try_shell_exec(cmd, argv)) {
1585 exec_id = trace2_exec(cmd, (const char **)argv);
1586 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1588 trace2_exec_result(exec_id, -1);
1591 if (waitpid(pid, &status, 0) < 0)
1593 trace2_exec_result(exec_id, status);
1599 int mingw_execvp(const char *cmd, char *const *argv)
1601 char *prog = path_lookup(cmd, 0);
1604 mingw_execv(prog, argv);
1612 int mingw_kill(pid_t pid, int sig)
1614 if (pid > 0 && sig == SIGTERM) {
1615 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1617 if (TerminateProcess(h, -1)) {
1622 errno = err_win_to_posix(GetLastError());
1625 } else if (pid > 0 && sig == 0) {
1626 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1638 * UTF-8 versions of getenv(), putenv() and unsetenv().
1639 * Internally, they use the CRT's stock UNICODE routines
1640 * to avoid data loss.
1642 char *mingw_getenv(const char *name)
1644 #define GETENV_MAX_RETAIN 64
1645 static char *values[GETENV_MAX_RETAIN];
1646 static int value_counter;
1647 int len_key, len_value;
1650 wchar_t w_value[32768];
1652 if (!name || !*name)
1655 len_key = strlen(name) + 1;
1656 /* We cannot use xcalloc() here because that uses getenv() itself */
1657 w_key = calloc(len_key, sizeof(wchar_t));
1659 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1660 xutftowcs(w_key, name, len_key);
1661 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1662 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1668 len_value = len_value * 3 + 1;
1669 /* We cannot use xcalloc() here because that uses getenv() itself */
1670 value = calloc(len_value, sizeof(char));
1672 die("Out of memory, (tried to allocate %u bytes)", len_value);
1673 xwcstoutf(value, w_value, len_value);
1676 * We return `value` which is an allocated value and the caller is NOT
1677 * expecting to have to free it, so we keep a round-robin array,
1678 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1680 free(values[value_counter]);
1681 values[value_counter++] = value;
1682 if (value_counter >= ARRAY_SIZE(values))
1688 int mingw_putenv(const char *namevalue)
1691 wchar_t *wide, *equal;
1694 if (!namevalue || !*namevalue)
1697 size = strlen(namevalue) * 2 + 1;
1698 wide = calloc(size, sizeof(wchar_t));
1700 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1701 xutftowcs(wide, namevalue, size);
1702 equal = wcschr(wide, L'=');
1704 result = SetEnvironmentVariableW(wide, NULL);
1707 result = SetEnvironmentVariableW(wide, equal + 1);
1712 errno = err_win_to_posix(GetLastError());
1714 return result ? 0 : -1;
1718 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1719 * that service contains a numerical port, or that it is null. It
1720 * does a simple search using gethostbyname, and returns one IPv4 host
1723 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1724 const struct addrinfo *hints,
1725 struct addrinfo **res)
1727 struct hostent *h = NULL;
1728 struct addrinfo *ai;
1729 struct sockaddr_in *sin;
1732 h = gethostbyname(node);
1734 return WSAGetLastError();
1737 ai = xmalloc(sizeof(struct addrinfo));
1740 ai->ai_family = AF_INET;
1741 ai->ai_socktype = hints ? hints->ai_socktype : 0;
1742 switch (ai->ai_socktype) {
1744 ai->ai_protocol = IPPROTO_TCP;
1747 ai->ai_protocol = IPPROTO_UDP;
1750 ai->ai_protocol = 0;
1753 ai->ai_addrlen = sizeof(struct sockaddr_in);
1754 if (hints && (hints->ai_flags & AI_CANONNAME))
1755 ai->ai_canonname = h ? xstrdup(h->h_name) : NULL;
1757 ai->ai_canonname = NULL;
1759 sin = xcalloc(1, ai->ai_addrlen);
1760 sin->sin_family = AF_INET;
1761 /* Note: getaddrinfo is supposed to allow service to be a string,
1762 * which should be looked up using getservbyname. This is
1763 * currently not implemented */
1765 sin->sin_port = htons(atoi(service));
1767 sin->sin_addr = *(struct in_addr *)h->h_addr;
1768 else if (hints && (hints->ai_flags & AI_PASSIVE))
1769 sin->sin_addr.s_addr = INADDR_ANY;
1771 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1772 ai->ai_addr = (struct sockaddr *)sin;
1777 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1779 free(res->ai_canonname);
1784 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1785 char *host, DWORD hostlen,
1786 char *serv, DWORD servlen, int flags)
1788 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1789 if (sa->sa_family != AF_INET)
1794 if (host && hostlen > 0) {
1795 struct hostent *ent = NULL;
1796 if (!(flags & NI_NUMERICHOST))
1797 ent = gethostbyaddr((const char *)&sin->sin_addr,
1798 sizeof(sin->sin_addr), AF_INET);
1801 snprintf(host, hostlen, "%s", ent->h_name);
1802 else if (flags & NI_NAMEREQD)
1805 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1808 if (serv && servlen > 0) {
1809 struct servent *ent = NULL;
1810 if (!(flags & NI_NUMERICSERV))
1811 ent = getservbyport(sin->sin_port,
1812 flags & NI_DGRAM ? "udp" : "tcp");
1815 snprintf(serv, servlen, "%s", ent->s_name);
1817 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1823 static HMODULE ipv6_dll = NULL;
1824 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1825 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1826 const struct addrinfo *hints,
1827 struct addrinfo **res);
1828 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1829 char *host, DWORD hostlen,
1830 char *serv, DWORD servlen, int flags);
1832 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1833 * don't need to try to load that one dynamically.
1836 static void socket_cleanup(void)
1840 FreeLibrary(ipv6_dll);
1842 ipv6_freeaddrinfo = freeaddrinfo_stub;
1843 ipv6_getaddrinfo = getaddrinfo_stub;
1844 ipv6_getnameinfo = getnameinfo_stub;
1847 static void ensure_socket_initialization(void)
1850 static int initialized = 0;
1851 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1857 if (WSAStartup(MAKEWORD(2,2), &wsa))
1858 die("unable to initialize winsock subsystem, error %d",
1861 for (name = libraries; *name; name++) {
1862 ipv6_dll = LoadLibraryExA(*name, NULL,
1863 LOAD_LIBRARY_SEARCH_SYSTEM32);
1867 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1868 GetProcAddress(ipv6_dll, "freeaddrinfo");
1869 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1870 const struct addrinfo *,
1871 struct addrinfo **))
1872 GetProcAddress(ipv6_dll, "getaddrinfo");
1873 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1874 socklen_t, char *, DWORD,
1875 char *, DWORD, int))
1876 GetProcAddress(ipv6_dll, "getnameinfo");
1877 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1878 FreeLibrary(ipv6_dll);
1883 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1884 ipv6_freeaddrinfo = freeaddrinfo_stub;
1885 ipv6_getaddrinfo = getaddrinfo_stub;
1886 ipv6_getnameinfo = getnameinfo_stub;
1889 atexit(socket_cleanup);
1894 int mingw_gethostname(char *name, int namelen)
1896 ensure_socket_initialization();
1897 return gethostname(name, namelen);
1900 #undef gethostbyname
1901 struct hostent *mingw_gethostbyname(const char *host)
1903 ensure_socket_initialization();
1904 return gethostbyname(host);
1907 void mingw_freeaddrinfo(struct addrinfo *res)
1909 ipv6_freeaddrinfo(res);
1912 int mingw_getaddrinfo(const char *node, const char *service,
1913 const struct addrinfo *hints, struct addrinfo **res)
1915 ensure_socket_initialization();
1916 return ipv6_getaddrinfo(node, service, hints, res);
1919 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1920 char *host, DWORD hostlen, char *serv, DWORD servlen,
1923 ensure_socket_initialization();
1924 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1927 int mingw_socket(int domain, int type, int protocol)
1932 ensure_socket_initialization();
1933 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1934 if (s == INVALID_SOCKET) {
1936 * WSAGetLastError() values are regular BSD error codes
1937 * biased by WSABASEERR.
1938 * However, strerror() does not know about networking
1939 * specific errors, which are values beginning at 38 or so.
1940 * Therefore, we choose to leave the biased error code
1941 * in errno so that _if_ someone looks up the code somewhere,
1942 * then it is at least the number that are usually listed.
1944 errno = WSAGetLastError();
1947 /* convert into a file descriptor */
1948 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1950 return error("unable to make a socket file descriptor: %s",
1957 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1959 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1960 return connect(s, sa, sz);
1964 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1966 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1967 return bind(s, sa, sz);
1971 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1973 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1974 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1978 int mingw_shutdown(int sockfd, int how)
1980 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1981 return shutdown(s, how);
1985 int mingw_listen(int sockfd, int backlog)
1987 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1988 return listen(s, backlog);
1992 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1996 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1997 SOCKET s2 = accept(s1, sa, sz);
1999 /* convert into a file descriptor */
2000 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2003 return error("unable to make a socket file descriptor: %s",
2010 int mingw_rename(const char *pold, const char *pnew)
2014 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2015 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2019 * Try native rename() first to get errno right.
2020 * It is based on MoveFile(), which cannot overwrite existing files.
2022 if (!_wrename(wpold, wpnew))
2024 if (errno != EEXIST)
2027 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2029 /* TODO: translate more errors */
2030 gle = GetLastError();
2031 if (gle == ERROR_ACCESS_DENIED &&
2032 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2033 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2034 DWORD attrsold = GetFileAttributesW(wpold);
2035 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2036 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2038 else if (!_wrmdir(wpnew))
2042 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2043 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2044 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2046 gle = GetLastError();
2047 /* revert file attributes on failure */
2048 SetFileAttributesW(wpnew, attrs);
2051 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2053 * We assume that some other process had the source or
2054 * destination file open at the wrong moment and retry.
2055 * In order to give the other process a higher chance to
2056 * complete its operation, we give up our time slice now.
2057 * If we have to retry again, we do sleep a bit.
2059 Sleep(delay[tries]);
2063 if (gle == ERROR_ACCESS_DENIED &&
2064 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2065 "Should I try again?", pold, pnew))
2073 * Note that this doesn't return the actual pagesize, but
2074 * the allocation granularity. If future Windows specific git code
2075 * needs the real getpagesize function, we need to find another solution.
2077 int mingw_getpagesize(void)
2081 return si.dwAllocationGranularity;
2084 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2085 enum EXTENDED_NAME_FORMAT {
2087 NameUserPrincipal = 8
2090 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2092 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2093 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2094 static wchar_t wbuffer[1024];
2097 if (!INIT_PROC_ADDR(GetUserNameExW))
2100 len = ARRAY_SIZE(wbuffer);
2101 if (GetUserNameExW(type, wbuffer, &len)) {
2102 char *converted = xmalloc((len *= 3));
2103 if (xwcstoutf(converted, wbuffer, len) >= 0)
2111 char *mingw_query_user_email(void)
2113 return get_extended_user_info(NameUserPrincipal);
2116 struct passwd *getpwuid(int uid)
2118 static unsigned initialized;
2119 static char user_name[100];
2120 static struct passwd *p;
2126 len = sizeof(user_name);
2127 if (!GetUserName(user_name, &len)) {
2132 p = xmalloc(sizeof(*p));
2133 p->pw_name = user_name;
2134 p->pw_gecos = get_extended_user_info(NameDisplay);
2136 p->pw_gecos = "unknown";
2143 static HANDLE timer_event;
2144 static HANDLE timer_thread;
2145 static int timer_interval;
2146 static int one_shot;
2147 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2149 /* The timer works like this:
2150 * The thread, ticktack(), is a trivial routine that most of the time
2151 * only waits to receive the signal to terminate. The main thread tells
2152 * the thread to terminate by setting the timer_event to the signalled
2154 * But ticktack() interrupts the wait state after the timer's interval
2155 * length to call the signal handler.
2158 static unsigned __stdcall ticktack(void *dummy)
2160 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2161 mingw_raise(SIGALRM);
2168 static int start_timer_thread(void)
2170 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2172 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2174 return errno = ENOMEM,
2175 error("cannot start timer thread");
2177 return errno = ENOMEM,
2178 error("cannot allocate resources for timer");
2182 static void stop_timer_thread(void)
2185 SetEvent(timer_event); /* tell thread to terminate */
2187 int rc = WaitForSingleObject(timer_thread, 10000);
2188 if (rc == WAIT_TIMEOUT)
2189 error("timer thread did not terminate timely");
2190 else if (rc != WAIT_OBJECT_0)
2191 error("waiting for timer thread failed: %lu",
2193 CloseHandle(timer_thread);
2196 CloseHandle(timer_event);
2198 timer_thread = NULL;
2201 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2203 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2206 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2208 static const struct timeval zero;
2209 static int atexit_done;
2212 return errno = EINVAL,
2213 error("setitimer param 3 != NULL not implemented");
2214 if (!is_timeval_eq(&in->it_interval, &zero) &&
2215 !is_timeval_eq(&in->it_interval, &in->it_value))
2216 return errno = EINVAL,
2217 error("setitimer: it_interval must be zero or eq it_value");
2220 stop_timer_thread();
2222 if (is_timeval_eq(&in->it_value, &zero) &&
2223 is_timeval_eq(&in->it_interval, &zero))
2226 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2227 one_shot = is_timeval_eq(&in->it_interval, &zero);
2229 atexit(stop_timer_thread);
2232 return start_timer_thread();
2235 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2238 return errno = EINVAL,
2239 error("sigaction only implemented for SIGALRM");
2241 return errno = EINVAL,
2242 error("sigaction: param 3 != NULL not implemented");
2244 timer_fn = in->sa_handler;
2249 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2261 sigint_fn = handler;
2265 return signal(sig, handler);
2272 int mingw_raise(int sig)
2276 if (timer_fn == SIG_DFL) {
2277 if (isatty(STDERR_FILENO))
2278 fputs("Alarm clock\n", stderr);
2279 exit(128 + SIGALRM);
2280 } else if (timer_fn != SIG_IGN)
2285 if (sigint_fn == SIG_DFL)
2287 else if (sigint_fn != SIG_IGN)
2296 int link(const char *oldpath, const char *newpath)
2298 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2299 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2300 xutftowcs_path(wnewpath, newpath) < 0)
2303 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2304 errno = err_win_to_posix(GetLastError());
2310 pid_t waitpid(pid_t pid, int *status, int options)
2312 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2319 if (pid > 0 && options & WNOHANG) {
2320 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2324 options &= ~WNOHANG;
2328 struct pinfo_t **ppinfo;
2329 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2335 GetExitCodeProcess(h, (LPDWORD)status);
2337 EnterCriticalSection(&pinfo_cs);
2341 struct pinfo_t *info = *ppinfo;
2342 if (info->pid == pid) {
2343 CloseHandle(info->proc);
2344 *ppinfo = info->next;
2348 ppinfo = &info->next;
2351 LeaveCriticalSection(&pinfo_cs);
2362 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2364 int upos = 0, wpos = 0;
2365 const unsigned char *utf = (const unsigned char*) utfs;
2366 if (!utf || !wcs || wcslen < 1) {
2370 /* reserve space for \0 */
2375 while (upos < utflen) {
2376 int c = utf[upos++] & 0xff;
2377 if (utflen == INT_MAX && c == 0)
2380 if (wpos >= wcslen) {
2389 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2390 (utf[upos] & 0xc0) == 0x80) {
2392 c = ((c & 0x1f) << 6);
2393 c |= (utf[upos++] & 0x3f);
2395 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2396 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2397 (utf[upos] & 0xc0) == 0x80 &&
2398 (utf[upos + 1] & 0xc0) == 0x80) {
2400 c = ((c & 0x0f) << 12);
2401 c |= ((utf[upos++] & 0x3f) << 6);
2402 c |= (utf[upos++] & 0x3f);
2404 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2405 wpos + 1 < wcslen &&
2406 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2407 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2408 (utf[upos] & 0xc0) == 0x80 &&
2409 (utf[upos + 1] & 0xc0) == 0x80 &&
2410 (utf[upos + 2] & 0xc0) == 0x80) {
2411 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2412 c = ((c & 0x07) << 18);
2413 c |= ((utf[upos++] & 0x3f) << 12);
2414 c |= ((utf[upos++] & 0x3f) << 6);
2415 c |= (utf[upos++] & 0x3f);
2417 wcs[wpos++] = 0xd800 | (c >> 10);
2418 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2419 } else if (c >= 0xa0) {
2420 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2423 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2424 static const char *hex = "0123456789abcdef";
2425 wcs[wpos++] = hex[c >> 4];
2427 wcs[wpos++] = hex[c & 0x0f];
2434 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2436 if (!wcs || !utf || utflen < 1) {
2440 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2447 static void setup_windows_environment(void)
2449 char *tmp = getenv("TMPDIR");
2451 /* on Windows it is TMP and TEMP */
2453 if (!(tmp = getenv("TMP")))
2454 tmp = getenv("TEMP");
2456 setenv("TMPDIR", tmp, 1);
2457 tmp = getenv("TMPDIR");
2463 * Convert all dir separators to forward slashes,
2464 * to help shell commands called from the Git
2465 * executable (by not mistaking the dir separators
2466 * for escape characters).
2468 convert_slashes(tmp);
2471 /* simulate TERM to enable auto-color (see color.c) */
2472 if (!getenv("TERM"))
2473 setenv("TERM", "cygwin", 1);
2477 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2478 * mingw startup code, see init.c in mingw runtime).
2486 extern int __wgetmainargs(int *argc, wchar_t ***argv, wchar_t ***env, int glob,
2489 static NORETURN void die_startup(void)
2491 fputs("fatal: not enough memory for initialization", stderr);
2495 static void *malloc_startup(size_t size)
2497 void *result = malloc(size);
2503 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2505 len = xwcstoutf(buffer, wcs, len) + 1;
2506 return memcpy(malloc_startup(len), buffer, len);
2509 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2510 DWORD desired_access, DWORD flags)
2512 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2513 wchar_t buf[MAX_PATH];
2514 DWORD max = ARRAY_SIZE(buf);
2516 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2518 if (!ret || ret >= max)
2521 /* make sure this does not leak into child processes */
2522 SetEnvironmentVariableW(key, NULL);
2523 if (!wcscmp(buf, L"off")) {
2525 handle = GetStdHandle(std_id);
2526 if (handle != INVALID_HANDLE_VALUE)
2527 CloseHandle(handle);
2530 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2531 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2532 if (handle == INVALID_HANDLE_VALUE) {
2534 handle = GetStdHandle(std_id);
2535 if (handle != INVALID_HANDLE_VALUE)
2536 CloseHandle(handle);
2538 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2539 SetStdHandle(std_id, handle);
2541 /* do *not* close the new_fd: that would close stdout */
2545 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2547 if (handle != INVALID_HANDLE_VALUE) {
2548 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2549 SetStdHandle(std_id, handle);
2555 static void maybe_redirect_std_handles(void)
2557 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2558 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2559 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2560 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2561 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2562 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2565 void mingw_startup(void)
2567 int i, maxlen, argc;
2569 wchar_t **wenv, **wargv;
2572 maybe_redirect_std_handles();
2574 /* get wide char arguments and environment */
2576 if (__wgetmainargs(&argc, &wargv, &wenv, _CRT_glob, &si) < 0)
2579 /* determine size of argv and environ conversion buffer */
2580 maxlen = wcslen(wargv[0]);
2581 for (i = 1; i < argc; i++)
2582 maxlen = max(maxlen, wcslen(wargv[i]));
2584 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2585 maxlen = 3 * maxlen + 1;
2586 buffer = malloc_startup(maxlen);
2588 /* convert command line arguments and environment to UTF-8 */
2589 for (i = 0; i < argc; i++)
2590 __argv[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2593 /* fix Windows specific environment settings */
2594 setup_windows_environment();
2596 unset_environment_variables = xstrdup("PERL5LIB");
2598 /* initialize critical section for waitpid pinfo_t list */
2599 InitializeCriticalSection(&pinfo_cs);
2601 /* set up default file mode and file modes for stdin/out/err */
2603 _setmode(_fileno(stdin), _O_BINARY);
2604 _setmode(_fileno(stdout), _O_BINARY);
2605 _setmode(_fileno(stderr), _O_BINARY);
2607 /* initialize Unicode console */
2611 int uname(struct utsname *buf)
2613 unsigned v = (unsigned)GetVersion();
2614 memset(buf, 0, sizeof(*buf));
2615 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2616 xsnprintf(buf->release, sizeof(buf->release),
2617 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2618 /* assuming NT variants only.. */
2619 xsnprintf(buf->version, sizeof(buf->version),
2620 "%u", (v >> 16) & 0x7fff);