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 */
370 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
371 return *basename == '.';
373 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
374 return !strncasecmp(".git", basename, 4) &&
375 (!basename[4] || is_dir_sep(basename[4]));
378 static int set_hidden_flag(const wchar_t *path, int set)
380 DWORD original = GetFileAttributesW(path), modified;
382 modified = original | FILE_ATTRIBUTE_HIDDEN;
384 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
385 if (original == modified || SetFileAttributesW(path, modified))
387 errno = err_win_to_posix(GetLastError());
391 int mingw_mkdir(const char *path, int mode)
394 wchar_t wpath[MAX_PATH];
396 if (!is_valid_win32_path(path)) {
401 if (xutftowcs_path(wpath, path) < 0)
403 ret = _wmkdir(wpath);
404 if (!ret && needs_hiding(path))
405 return set_hidden_flag(wpath, 1);
410 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
411 * is documented in [1] as opening a writable file handle in append mode.
412 * (It is believed that) this is atomic since it is maintained by the
413 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
415 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
417 * This trick does not appear to work for named pipes. Instead it creates
418 * a named pipe client handle that cannot be written to. Callers should
419 * just use the regular _wopen() for them. (And since client handle gets
420 * bound to a unique server handle, it isn't really an issue.)
422 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
426 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
428 /* only these flags are supported */
429 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
430 return errno = ENOSYS, -1;
433 * FILE_SHARE_WRITE is required to permit child processes
434 * to append to the file.
436 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
437 FILE_SHARE_WRITE | FILE_SHARE_READ,
438 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
439 if (handle == INVALID_HANDLE_VALUE)
440 return errno = err_win_to_posix(GetLastError()), -1;
443 * No O_APPEND here, because the CRT uses it only to reset the
444 * file pointer to EOF before each write(); but that is not
445 * necessary (and may lead to races) for a file created with
448 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
455 * Does the pathname map to the local named pipe filesystem?
456 * That is, does it have a "//./pipe/" prefix?
458 static int is_local_named_pipe_path(const char *filename)
460 return (is_dir_sep(filename[0]) &&
461 is_dir_sep(filename[1]) &&
462 filename[2] == '.' &&
463 is_dir_sep(filename[3]) &&
464 !strncasecmp(filename+4, "pipe", 4) &&
465 is_dir_sep(filename[8]) &&
469 int mingw_open (const char *filename, int oflags, ...)
471 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
474 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
475 wchar_t wfilename[MAX_PATH];
478 va_start(args, oflags);
479 mode = va_arg(args, int);
482 if (!is_valid_win32_path(filename)) {
483 errno = create ? EINVAL : ENOENT;
487 if (filename && !strcmp(filename, "/dev/null"))
490 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
491 open_fn = mingw_open_append;
495 if (xutftowcs_path(wfilename, filename) < 0)
497 fd = open_fn(wfilename, oflags, mode);
499 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
500 DWORD attrs = GetFileAttributesW(wfilename);
501 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
504 if ((oflags & O_CREAT) && needs_hiding(filename)) {
506 * Internally, _wopen() uses the CreateFile() API which errors
507 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
508 * specified and an already existing file's attributes do not
509 * match *exactly*. As there is no mode or flag we can set that
510 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
511 * again *without* the O_CREAT flag (that corresponds to the
512 * CREATE_ALWAYS flag of CreateFile()).
514 if (fd < 0 && errno == EACCES)
515 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
516 if (fd >= 0 && set_hidden_flag(wfilename, 1))
517 warning("could not mark '%s' as hidden.", filename);
522 static BOOL WINAPI ctrl_ignore(DWORD type)
528 int mingw_fgetc(FILE *stream)
531 if (!isatty(_fileno(stream)))
532 return fgetc(stream);
534 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
537 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
540 /* Ctrl+C was pressed, simulate SIGINT and retry */
543 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
548 FILE *mingw_fopen (const char *filename, const char *otype)
550 int hide = needs_hiding(filename);
552 wchar_t wfilename[MAX_PATH], wotype[4];
553 if (!is_valid_win32_path(filename)) {
554 int create = otype && strchr(otype, 'w');
555 errno = create ? EINVAL : ENOENT;
558 if (filename && !strcmp(filename, "/dev/null"))
560 if (xutftowcs_path(wfilename, filename) < 0 ||
561 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
563 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
564 error("could not unhide %s", filename);
567 file = _wfopen(wfilename, wotype);
568 if (!file && GetLastError() == ERROR_INVALID_NAME)
570 if (file && hide && set_hidden_flag(wfilename, 1))
571 warning("could not mark '%s' as hidden.", filename);
575 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
577 int hide = needs_hiding(filename);
579 wchar_t wfilename[MAX_PATH], wotype[4];
580 if (!is_valid_win32_path(filename)) {
581 int create = otype && strchr(otype, 'w');
582 errno = create ? EINVAL : ENOENT;
585 if (filename && !strcmp(filename, "/dev/null"))
587 if (xutftowcs_path(wfilename, filename) < 0 ||
588 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
590 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
591 error("could not unhide %s", filename);
594 file = _wfreopen(wfilename, wotype, stream);
595 if (file && hide && set_hidden_flag(wfilename, 1))
596 warning("could not mark '%s' as hidden.", filename);
601 int mingw_fflush(FILE *stream)
603 int ret = fflush(stream);
606 * write() is used behind the scenes of stdio output functions.
607 * Since git code does not check for errors after each stdio write
608 * operation, it can happen that write() is called by a later
609 * stdio function even if an earlier write() call failed. In the
610 * case of a pipe whose readable end was closed, only the first
611 * call to write() reports EPIPE on Windows. Subsequent write()
612 * calls report EINVAL. It is impossible to notice whether this
613 * fflush invocation triggered such a case, therefore, we have to
614 * catch all EINVAL errors whole-sale.
616 if (ret && errno == EINVAL)
623 ssize_t mingw_write(int fd, const void *buf, size_t len)
625 ssize_t result = write(fd, buf, len);
627 if (result < 0 && errno == EINVAL && buf) {
628 /* check if fd is a pipe */
629 HANDLE h = (HANDLE) _get_osfhandle(fd);
630 if (GetFileType(h) == FILE_TYPE_PIPE)
639 int mingw_access(const char *filename, int mode)
641 wchar_t wfilename[MAX_PATH];
642 if (xutftowcs_path(wfilename, filename) < 0)
644 /* X_OK is not supported by the MSVCRT version */
645 return _waccess(wfilename, mode & ~X_OK);
648 int mingw_chdir(const char *dirname)
650 wchar_t wdirname[MAX_PATH];
651 if (xutftowcs_path(wdirname, dirname) < 0)
653 return _wchdir(wdirname);
656 int mingw_chmod(const char *filename, int mode)
658 wchar_t wfilename[MAX_PATH];
659 if (xutftowcs_path(wfilename, filename) < 0)
661 return _wchmod(wfilename, mode);
665 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
666 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
668 static inline long long filetime_to_hnsec(const FILETIME *ft)
670 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
671 /* Windows to Unix Epoch conversion */
672 return winTime - 116444736000000000LL;
675 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
677 long long hnsec = filetime_to_hnsec(ft);
678 ts->tv_sec = (time_t)(hnsec / 10000000);
679 ts->tv_nsec = (hnsec % 10000000) * 100;
683 * Verifies that safe_create_leading_directories() would succeed.
685 static int has_valid_directory_prefix(wchar_t *wfilename)
687 int n = wcslen(wfilename);
690 wchar_t c = wfilename[--n];
696 wfilename[n] = L'\0';
697 attributes = GetFileAttributesW(wfilename);
699 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
700 attributes == FILE_ATTRIBUTE_DEVICE)
702 if (attributes == INVALID_FILE_ATTRIBUTES)
703 switch (GetLastError()) {
704 case ERROR_PATH_NOT_FOUND:
706 case ERROR_FILE_NOT_FOUND:
707 /* This implies parent directory exists. */
715 /* We keep the do_lstat code in a separate function to avoid recursion.
716 * When a path ends with a slash, the stat will fail with ENOENT. In
717 * this case, we strip the trailing slashes and stat again.
719 * If follow is true then act like stat() and report on the link
720 * target. Otherwise report on the link itself.
722 static int do_lstat(int follow, const char *file_name, struct stat *buf)
724 WIN32_FILE_ATTRIBUTE_DATA fdata;
725 wchar_t wfilename[MAX_PATH];
726 if (xutftowcs_path(wfilename, file_name) < 0)
729 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
734 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
735 buf->st_size = fdata.nFileSizeLow |
736 (((off_t)fdata.nFileSizeHigh)<<32);
737 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
738 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
739 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
740 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
741 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
742 WIN32_FIND_DATAW findbuf;
743 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
744 if (handle != INVALID_HANDLE_VALUE) {
745 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
746 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
748 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
749 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
751 buf->st_mode = S_IFLNK;
753 buf->st_mode |= S_IREAD;
754 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
755 buf->st_mode |= S_IWRITE;
762 switch (GetLastError()) {
763 case ERROR_ACCESS_DENIED:
764 case ERROR_SHARING_VIOLATION:
765 case ERROR_LOCK_VIOLATION:
766 case ERROR_SHARING_BUFFER_EXCEEDED:
769 case ERROR_BUFFER_OVERFLOW:
770 errno = ENAMETOOLONG;
772 case ERROR_NOT_ENOUGH_MEMORY:
775 case ERROR_PATH_NOT_FOUND:
776 if (!has_valid_directory_prefix(wfilename)) {
788 /* We provide our own lstat/fstat functions, since the provided
789 * lstat/fstat functions are so slow. These stat functions are
790 * tailored for Git's usage (read: fast), and are not meant to be
791 * complete. Note that Git stat()s are redirected to mingw_lstat()
792 * too, since Windows doesn't really handle symlinks that well.
794 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
797 char alt_name[PATH_MAX];
799 if (!do_lstat(follow, file_name, buf))
802 /* if file_name ended in a '/', Windows returned ENOENT;
803 * try again without trailing slashes
808 namelen = strlen(file_name);
809 if (namelen && file_name[namelen-1] != '/')
811 while (namelen && file_name[namelen-1] == '/')
813 if (!namelen || namelen >= PATH_MAX)
816 memcpy(alt_name, file_name, namelen);
817 alt_name[namelen] = 0;
818 return do_lstat(follow, alt_name, buf);
821 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
823 BY_HANDLE_FILE_INFORMATION fdata;
825 if (!GetFileInformationByHandle(hnd, &fdata)) {
826 errno = err_win_to_posix(GetLastError());
834 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
835 buf->st_size = fdata.nFileSizeLow |
836 (((off_t)fdata.nFileSizeHigh)<<32);
837 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
838 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
839 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
840 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
844 int mingw_lstat(const char *file_name, struct stat *buf)
846 return do_stat_internal(0, file_name, buf);
848 int mingw_stat(const char *file_name, struct stat *buf)
850 return do_stat_internal(1, file_name, buf);
853 int mingw_fstat(int fd, struct stat *buf)
855 HANDLE fh = (HANDLE)_get_osfhandle(fd);
856 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
860 return get_file_info_by_handle(fh, buf);
864 /* initialize stat fields */
865 memset(buf, 0, sizeof(*buf));
868 if (type == FILE_TYPE_CHAR) {
869 buf->st_mode = _S_IFCHR;
871 buf->st_mode = _S_IFIFO;
872 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
873 buf->st_size = avail;
883 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
885 long long winTime = t * 10000000LL + 116444736000000000LL;
886 ft->dwLowDateTime = winTime;
887 ft->dwHighDateTime = winTime >> 32;
890 int mingw_utime (const char *file_name, const struct utimbuf *times)
895 wchar_t wfilename[MAX_PATH];
896 if (xutftowcs_path(wfilename, file_name) < 0)
899 /* must have write permission */
900 attrs = GetFileAttributesW(wfilename);
901 if (attrs != INVALID_FILE_ATTRIBUTES &&
902 (attrs & FILE_ATTRIBUTE_READONLY)) {
903 /* ignore errors here; open() will report them */
904 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
907 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
913 time_t_to_filetime(times->modtime, &mft);
914 time_t_to_filetime(times->actime, &aft);
916 GetSystemTimeAsFileTime(&mft);
919 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
927 if (attrs != INVALID_FILE_ATTRIBUTES &&
928 (attrs & FILE_ATTRIBUTE_READONLY)) {
929 /* ignore errors again */
930 SetFileAttributesW(wfilename, attrs);
936 size_t mingw_strftime(char *s, size_t max,
937 const char *format, const struct tm *tm)
939 size_t ret = strftime(s, max, format, tm);
941 if (!ret && errno == EINVAL)
942 die("invalid strftime format: '%s'", format);
946 unsigned int sleep (unsigned int seconds)
952 char *mingw_mktemp(char *template)
954 wchar_t wtemplate[MAX_PATH];
955 if (xutftowcs_path(wtemplate, template) < 0)
957 if (!_wmktemp(wtemplate))
959 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
964 int mkstemp(char *template)
966 char *filename = mktemp(template);
967 if (filename == NULL)
969 return open(filename, O_RDWR | O_CREAT, 0600);
972 int gettimeofday(struct timeval *tv, void *tz)
977 GetSystemTimeAsFileTime(&ft);
978 hnsec = filetime_to_hnsec(&ft);
979 tv->tv_sec = hnsec / 10000000;
980 tv->tv_usec = (hnsec % 10000000) / 10;
984 int pipe(int filedes[2])
988 /* this creates non-inheritable handles */
989 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
990 errno = err_win_to_posix(GetLastError());
993 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
994 if (filedes[0] < 0) {
999 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1000 if (filedes[1] < 0) {
1008 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1010 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
1011 memcpy(result, gmtime(timep), sizeof(struct tm));
1015 struct tm *localtime_r(const time_t *timep, struct tm *result)
1017 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
1018 memcpy(result, localtime(timep), sizeof(struct tm));
1022 char *mingw_getcwd(char *pointer, int len)
1024 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1025 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1027 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1028 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1031 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1032 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1033 HANDLE hnd = CreateFileW(cwd, 0,
1034 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1035 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1036 if (hnd == INVALID_HANDLE_VALUE)
1038 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1040 if (!ret || ret >= ARRAY_SIZE(wpointer))
1042 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1046 if (!ret || ret >= ARRAY_SIZE(wpointer))
1048 if (xwcstoutf(pointer, wpointer, len) < 0)
1050 convert_slashes(pointer);
1055 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1056 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1058 static const char *quote_arg_msvc(const char *arg)
1060 /* count chars to quote */
1062 int force_quotes = 0;
1064 const char *p = arg;
1065 if (!*p) force_quotes = 1;
1067 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1071 else if (*p == '\\') {
1073 while (*p == '\\') {
1078 if (*p == '"' || !*p)
1085 if (!force_quotes && n == 0)
1088 /* insert \ where necessary */
1089 d = q = xmalloc(st_add3(len, n, 3));
1094 else if (*arg == '\\') {
1096 while (*arg == '\\') {
1100 if (*arg == '"' || !*arg) {
1103 /* don't escape the surrounding end quote */
1118 static const char *quote_arg_msys2(const char *arg)
1120 struct strbuf buf = STRBUF_INIT;
1121 const char *p2 = arg, *p;
1123 for (p = arg; *p; p++) {
1124 int ws = isspace(*p);
1125 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1126 *p != '?' && *p != '*' && *p != '~')
1129 strbuf_addch(&buf, '"');
1131 strbuf_add(&buf, p2, p - p2);
1132 if (*p == '\\' || *p == '"')
1133 strbuf_addch(&buf, '\\');
1138 strbuf_addch(&buf, '"');
1142 strbuf_add(&buf, p2, p - p2);
1144 strbuf_addch(&buf, '"');
1145 return strbuf_detach(&buf, 0);
1148 static const char *parse_interpreter(const char *cmd)
1150 static char buf[100];
1154 /* don't even try a .exe */
1156 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1159 fd = open(cmd, O_RDONLY);
1162 n = read(fd, buf, sizeof(buf)-1);
1164 if (n < 4) /* at least '#!/x' and not error */
1167 if (buf[0] != '#' || buf[1] != '!')
1170 p = buf + strcspn(buf, "\r\n");
1175 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1178 if ((opt = strchr(p+1, ' ')))
1184 * exe_only means that we only want to detect .exe files, but not scripts
1185 * (which do not have an extension)
1187 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1188 int isexe, int exe_only)
1190 char path[MAX_PATH];
1191 wchar_t wpath[MAX_PATH];
1192 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1194 if (xutftowcs_path(wpath, path) < 0)
1197 if (!isexe && _waccess(wpath, F_OK) == 0)
1198 return xstrdup(path);
1199 wpath[wcslen(wpath)-4] = '\0';
1200 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1201 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1202 path[strlen(path)-4] = '\0';
1203 return xstrdup(path);
1210 * Determines the absolute path of cmd using the split path in path.
1211 * If cmd contains a slash or backslash, no lookup is performed.
1213 static char *path_lookup(const char *cmd, int exe_only)
1217 int len = strlen(cmd);
1218 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1220 if (strchr(cmd, '/') || strchr(cmd, '\\'))
1221 return xstrdup(cmd);
1223 path = mingw_getenv("PATH");
1228 const char *sep = strchrnul(path, ';');
1229 int dirlen = sep - path;
1231 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1240 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1242 while (*s && *s != c)
1247 /* Compare only keys */
1248 static int wenvcmp(const void *a, const void *b)
1250 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1251 size_t p_len, q_len;
1254 p_len = wcschrnul(p, L'=') - p;
1255 q_len = wcschrnul(q, L'=') - q;
1257 /* If the length differs, include the shorter key's NUL */
1260 else if (p_len > q_len)
1263 return _wcsnicmp(p, q, p_len);
1267 * Build an environment block combining the inherited environment
1268 * merged with the given list of settings.
1270 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1271 * Values of the form "KEY" in deltaenv delete inherited values.
1273 * Multiple entries in deltaenv for the same key are explicitly allowed.
1275 * We return a contiguous block of UNICODE strings with a final trailing
1278 static wchar_t *make_environment_block(char **deltaenv)
1280 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1281 size_t wlen, s, delta_size, size;
1283 wchar_t **array = NULL;
1284 size_t alloc = 0, nr = 0, i;
1286 size = 1; /* for extra NUL at the end */
1288 /* If there is no deltaenv to apply, simply return a copy. */
1289 if (!deltaenv || !*deltaenv) {
1290 for (p = wenv; p && *p; ) {
1291 size_t s = wcslen(p) + 1;
1296 ALLOC_ARRAY(result, size);
1297 COPY_ARRAY(result, wenv, size);
1298 FreeEnvironmentStringsW(wenv);
1303 * If there is a deltaenv, let's accumulate all keys into `array`,
1304 * sort them using the stable git_stable_qsort() and then copy,
1305 * skipping duplicate keys
1307 for (p = wenv; p && *p; ) {
1308 ALLOC_GROW(array, nr + 1, alloc);
1315 /* (over-)assess size needed for wchar version of deltaenv */
1316 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1317 delta_size += strlen(deltaenv[i]) * 2 + 1;
1318 ALLOC_ARRAY(wdeltaenv, delta_size);
1320 /* convert the deltaenv, appending to array */
1321 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1322 ALLOC_GROW(array, nr + 1, alloc);
1323 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1328 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1329 ALLOC_ARRAY(result, size + delta_size);
1331 for (p = result, i = 0; i < nr; i++) {
1332 /* Skip any duplicate keys; last one wins */
1333 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1336 /* Skip "to delete" entry */
1337 if (!wcschr(array[i], L'='))
1340 size = wcslen(array[i]) + 1;
1341 COPY_ARRAY(p, array[i], size);
1348 FreeEnvironmentStringsW(wenv);
1352 static void do_unset_environment_variables(void)
1355 char *p = unset_environment_variables;
1362 char *comma = strchr(p, ',');
1374 struct pinfo_t *next;
1378 static struct pinfo_t *pinfo = NULL;
1379 CRITICAL_SECTION pinfo_cs;
1381 /* Used to match and chomp off path components */
1382 static inline int match_last_path_component(const char *path, size_t *len,
1383 const char *component)
1385 size_t component_len = strlen(component);
1386 if (*len < component_len + 1 ||
1387 !is_dir_sep(path[*len - component_len - 1]) ||
1388 fspathncmp(path + *len - component_len, component, component_len))
1390 *len -= component_len + 1;
1391 /* chomp off repeated dir separators */
1392 while (*len > 0 && is_dir_sep(path[*len - 1]))
1397 static int is_msys2_sh(const char *cmd)
1402 if (!strcmp(cmd, "sh")) {
1403 static int ret = -1;
1409 p = path_lookup(cmd, 0);
1413 size_t len = strlen(p);
1415 ret = match_last_path_component(p, &len, "sh.exe") &&
1416 match_last_path_component(p, &len, "bin") &&
1417 match_last_path_component(p, &len, "usr");
1423 if (ends_with(cmd, "\\sh.exe")) {
1427 sh = path_lookup("sh", 0);
1429 return !fspathcmp(cmd, sh);
1435 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1437 int prepend_cmd, int fhin, int fhout, int fherr)
1440 PROCESS_INFORMATION pi;
1442 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1443 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1446 const char *(*quote_arg)(const char *arg) =
1447 is_msys2_sh(cmd ? cmd : *argv) ?
1448 quote_arg_msys2 : quote_arg_msvc;
1450 do_unset_environment_variables();
1452 /* Determine whether or not we are associated to a console */
1453 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1454 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1455 FILE_ATTRIBUTE_NORMAL, NULL);
1456 if (cons == INVALID_HANDLE_VALUE) {
1457 /* There is no console associated with this process.
1458 * Since the child is a console process, Windows
1459 * would normally create a console window. But
1460 * since we'll be redirecting std streams, we do
1461 * not need the console.
1462 * It is necessary to use DETACHED_PROCESS
1463 * instead of CREATE_NO_WINDOW to make ssh
1464 * recognize that it has no console.
1466 flags |= DETACHED_PROCESS;
1468 /* There is already a console. If we specified
1469 * DETACHED_PROCESS here, too, Windows would
1470 * disassociate the child from the console.
1471 * The same is true for CREATE_NO_WINDOW.
1476 memset(&si, 0, sizeof(si));
1478 si.dwFlags = STARTF_USESTDHANDLES;
1479 si.hStdInput = winansi_get_osfhandle(fhin);
1480 si.hStdOutput = winansi_get_osfhandle(fhout);
1481 si.hStdError = winansi_get_osfhandle(fherr);
1483 if (*argv && !strcmp(cmd, *argv))
1485 else if (xutftowcs_path(wcmd, cmd) < 0)
1487 if (dir && xutftowcs_path(wdir, dir) < 0)
1490 /* concatenate argv, quoting args as we go */
1491 strbuf_init(&args, 0);
1493 char *quoted = (char *)quote_arg(cmd);
1494 strbuf_addstr(&args, quoted);
1498 for (; *argv; argv++) {
1499 char *quoted = (char *)quote_arg(*argv);
1501 strbuf_addch(&args, ' ');
1502 strbuf_addstr(&args, quoted);
1503 if (quoted != *argv)
1507 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1508 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1509 strbuf_release(&args);
1511 wenvblk = make_environment_block(deltaenv);
1513 memset(&pi, 0, sizeof(pi));
1514 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL, TRUE,
1515 flags, wenvblk, dir ? wdir : NULL, &si, &pi);
1524 CloseHandle(pi.hThread);
1527 * The process ID is the human-readable identifier of the process
1528 * that we want to present in log and error messages. The handle
1529 * is not useful for this purpose. But we cannot close it, either,
1530 * because it is not possible to turn a process ID into a process
1531 * handle after the process terminated.
1532 * Keep the handle in a list for waitpid.
1534 EnterCriticalSection(&pinfo_cs);
1536 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1537 info->pid = pi.dwProcessId;
1538 info->proc = pi.hProcess;
1542 LeaveCriticalSection(&pinfo_cs);
1544 return (pid_t)pi.dwProcessId;
1547 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1549 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1552 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1554 int fhin, int fhout, int fherr)
1557 char *prog = path_lookup(cmd, 0);
1564 const char *interpr = parse_interpreter(prog);
1567 const char *argv0 = argv[0];
1568 char *iprog = path_lookup(interpr, 1);
1575 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1576 fhin, fhout, fherr);
1582 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1583 fhin, fhout, fherr);
1589 static int try_shell_exec(const char *cmd, char *const *argv)
1591 const char *interpr = parse_interpreter(cmd);
1597 prog = path_lookup(interpr, 1);
1605 while (argv[argc]) argc++;
1606 ALLOC_ARRAY(argv2, argc + 1);
1607 argv2[0] = (char *)cmd; /* full path to the script file */
1608 COPY_ARRAY(&argv2[1], &argv[1], argc);
1609 exec_id = trace2_exec(prog, argv2);
1610 pid = mingw_spawnv(prog, argv2, 1);
1613 if (waitpid(pid, &status, 0) < 0)
1615 trace2_exec_result(exec_id, status);
1618 trace2_exec_result(exec_id, -1);
1619 pid = 1; /* indicate that we tried but failed */
1626 int mingw_execv(const char *cmd, char *const *argv)
1628 /* check if git_command is a shell script */
1629 if (!try_shell_exec(cmd, argv)) {
1633 exec_id = trace2_exec(cmd, (const char **)argv);
1634 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1636 trace2_exec_result(exec_id, -1);
1639 if (waitpid(pid, &status, 0) < 0)
1641 trace2_exec_result(exec_id, status);
1647 int mingw_execvp(const char *cmd, char *const *argv)
1649 char *prog = path_lookup(cmd, 0);
1652 mingw_execv(prog, argv);
1660 int mingw_kill(pid_t pid, int sig)
1662 if (pid > 0 && sig == SIGTERM) {
1663 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1665 if (TerminateProcess(h, -1)) {
1670 errno = err_win_to_posix(GetLastError());
1673 } else if (pid > 0 && sig == 0) {
1674 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1686 * UTF-8 versions of getenv(), putenv() and unsetenv().
1687 * Internally, they use the CRT's stock UNICODE routines
1688 * to avoid data loss.
1690 char *mingw_getenv(const char *name)
1692 #define GETENV_MAX_RETAIN 64
1693 static char *values[GETENV_MAX_RETAIN];
1694 static int value_counter;
1695 int len_key, len_value;
1698 wchar_t w_value[32768];
1700 if (!name || !*name)
1703 len_key = strlen(name) + 1;
1704 /* We cannot use xcalloc() here because that uses getenv() itself */
1705 w_key = calloc(len_key, sizeof(wchar_t));
1707 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1708 xutftowcs(w_key, name, len_key);
1709 /* GetEnvironmentVariableW() only sets the last error upon failure */
1710 SetLastError(ERROR_SUCCESS);
1711 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1712 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1718 len_value = len_value * 3 + 1;
1719 /* We cannot use xcalloc() here because that uses getenv() itself */
1720 value = calloc(len_value, sizeof(char));
1722 die("Out of memory, (tried to allocate %u bytes)", len_value);
1723 xwcstoutf(value, w_value, len_value);
1726 * We return `value` which is an allocated value and the caller is NOT
1727 * expecting to have to free it, so we keep a round-robin array,
1728 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1730 free(values[value_counter]);
1731 values[value_counter++] = value;
1732 if (value_counter >= ARRAY_SIZE(values))
1738 int mingw_putenv(const char *namevalue)
1741 wchar_t *wide, *equal;
1744 if (!namevalue || !*namevalue)
1747 size = strlen(namevalue) * 2 + 1;
1748 wide = calloc(size, sizeof(wchar_t));
1750 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1751 xutftowcs(wide, namevalue, size);
1752 equal = wcschr(wide, L'=');
1754 result = SetEnvironmentVariableW(wide, NULL);
1757 result = SetEnvironmentVariableW(wide, equal + 1);
1762 errno = err_win_to_posix(GetLastError());
1764 return result ? 0 : -1;
1767 static void ensure_socket_initialization(void)
1770 static int initialized = 0;
1775 if (WSAStartup(MAKEWORD(2,2), &wsa))
1776 die("unable to initialize winsock subsystem, error %d",
1779 atexit((void(*)(void)) WSACleanup);
1784 int mingw_gethostname(char *name, int namelen)
1786 ensure_socket_initialization();
1787 return gethostname(name, namelen);
1790 #undef gethostbyname
1791 struct hostent *mingw_gethostbyname(const char *host)
1793 ensure_socket_initialization();
1794 return gethostbyname(host);
1798 int mingw_getaddrinfo(const char *node, const char *service,
1799 const struct addrinfo *hints, struct addrinfo **res)
1801 ensure_socket_initialization();
1802 return getaddrinfo(node, service, hints, res);
1805 int mingw_socket(int domain, int type, int protocol)
1810 ensure_socket_initialization();
1811 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1812 if (s == INVALID_SOCKET) {
1814 * WSAGetLastError() values are regular BSD error codes
1815 * biased by WSABASEERR.
1816 * However, strerror() does not know about networking
1817 * specific errors, which are values beginning at 38 or so.
1818 * Therefore, we choose to leave the biased error code
1819 * in errno so that _if_ someone looks up the code somewhere,
1820 * then it is at least the number that are usually listed.
1822 errno = WSAGetLastError();
1825 /* convert into a file descriptor */
1826 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1828 return error("unable to make a socket file descriptor: %s",
1835 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1837 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1838 return connect(s, sa, sz);
1842 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1844 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1845 return bind(s, sa, sz);
1849 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1851 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1852 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1856 int mingw_shutdown(int sockfd, int how)
1858 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1859 return shutdown(s, how);
1863 int mingw_listen(int sockfd, int backlog)
1865 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1866 return listen(s, backlog);
1870 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1874 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1875 SOCKET s2 = accept(s1, sa, sz);
1877 /* convert into a file descriptor */
1878 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1881 return error("unable to make a socket file descriptor: %s",
1888 int mingw_rename(const char *pold, const char *pnew)
1892 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1893 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1897 * Try native rename() first to get errno right.
1898 * It is based on MoveFile(), which cannot overwrite existing files.
1900 if (!_wrename(wpold, wpnew))
1902 if (errno != EEXIST)
1905 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1907 /* TODO: translate more errors */
1908 gle = GetLastError();
1909 if (gle == ERROR_ACCESS_DENIED &&
1910 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
1911 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1912 DWORD attrsold = GetFileAttributesW(wpold);
1913 if (attrsold == INVALID_FILE_ATTRIBUTES ||
1914 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
1916 else if (!_wrmdir(wpnew))
1920 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1921 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1922 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1924 gle = GetLastError();
1925 /* revert file attributes on failure */
1926 SetFileAttributesW(wpnew, attrs);
1929 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1931 * We assume that some other process had the source or
1932 * destination file open at the wrong moment and retry.
1933 * In order to give the other process a higher chance to
1934 * complete its operation, we give up our time slice now.
1935 * If we have to retry again, we do sleep a bit.
1937 Sleep(delay[tries]);
1941 if (gle == ERROR_ACCESS_DENIED &&
1942 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1943 "Should I try again?", pold, pnew))
1951 * Note that this doesn't return the actual pagesize, but
1952 * the allocation granularity. If future Windows specific git code
1953 * needs the real getpagesize function, we need to find another solution.
1955 int mingw_getpagesize(void)
1959 return si.dwAllocationGranularity;
1962 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1963 enum EXTENDED_NAME_FORMAT {
1965 NameUserPrincipal = 8
1968 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
1970 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
1971 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
1972 static wchar_t wbuffer[1024];
1975 if (!INIT_PROC_ADDR(GetUserNameExW))
1978 len = ARRAY_SIZE(wbuffer);
1979 if (GetUserNameExW(type, wbuffer, &len)) {
1980 char *converted = xmalloc((len *= 3));
1981 if (xwcstoutf(converted, wbuffer, len) >= 0)
1989 char *mingw_query_user_email(void)
1991 return get_extended_user_info(NameUserPrincipal);
1994 struct passwd *getpwuid(int uid)
1996 static unsigned initialized;
1997 static char user_name[100];
1998 static struct passwd *p;
2005 len = ARRAY_SIZE(buf);
2006 if (!GetUserNameW(buf, &len)) {
2011 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2016 p = xmalloc(sizeof(*p));
2017 p->pw_name = user_name;
2018 p->pw_gecos = get_extended_user_info(NameDisplay);
2020 p->pw_gecos = "unknown";
2027 static HANDLE timer_event;
2028 static HANDLE timer_thread;
2029 static int timer_interval;
2030 static int one_shot;
2031 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2033 /* The timer works like this:
2034 * The thread, ticktack(), is a trivial routine that most of the time
2035 * only waits to receive the signal to terminate. The main thread tells
2036 * the thread to terminate by setting the timer_event to the signalled
2038 * But ticktack() interrupts the wait state after the timer's interval
2039 * length to call the signal handler.
2042 static unsigned __stdcall ticktack(void *dummy)
2044 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2045 mingw_raise(SIGALRM);
2052 static int start_timer_thread(void)
2054 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2056 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2058 return errno = ENOMEM,
2059 error("cannot start timer thread");
2061 return errno = ENOMEM,
2062 error("cannot allocate resources for timer");
2066 static void stop_timer_thread(void)
2069 SetEvent(timer_event); /* tell thread to terminate */
2071 int rc = WaitForSingleObject(timer_thread, 10000);
2072 if (rc == WAIT_TIMEOUT)
2073 error("timer thread did not terminate timely");
2074 else if (rc != WAIT_OBJECT_0)
2075 error("waiting for timer thread failed: %lu",
2077 CloseHandle(timer_thread);
2080 CloseHandle(timer_event);
2082 timer_thread = NULL;
2085 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2087 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2090 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2092 static const struct timeval zero;
2093 static int atexit_done;
2096 return errno = EINVAL,
2097 error("setitimer param 3 != NULL not implemented");
2098 if (!is_timeval_eq(&in->it_interval, &zero) &&
2099 !is_timeval_eq(&in->it_interval, &in->it_value))
2100 return errno = EINVAL,
2101 error("setitimer: it_interval must be zero or eq it_value");
2104 stop_timer_thread();
2106 if (is_timeval_eq(&in->it_value, &zero) &&
2107 is_timeval_eq(&in->it_interval, &zero))
2110 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2111 one_shot = is_timeval_eq(&in->it_interval, &zero);
2113 atexit(stop_timer_thread);
2116 return start_timer_thread();
2119 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2122 return errno = EINVAL,
2123 error("sigaction only implemented for SIGALRM");
2125 return errno = EINVAL,
2126 error("sigaction: param 3 != NULL not implemented");
2128 timer_fn = in->sa_handler;
2133 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2145 sigint_fn = handler;
2149 return signal(sig, handler);
2156 int mingw_raise(int sig)
2160 if (timer_fn == SIG_DFL) {
2161 if (isatty(STDERR_FILENO))
2162 fputs("Alarm clock\n", stderr);
2163 exit(128 + SIGALRM);
2164 } else if (timer_fn != SIG_IGN)
2169 if (sigint_fn == SIG_DFL)
2171 else if (sigint_fn != SIG_IGN)
2175 #if defined(_MSC_VER)
2182 case SIGABRT_COMPAT:
2184 * The <signal.h> header in the MS C Runtime defines 8 signals
2185 * as being supported on the platform. Anything else causes an
2186 * "Invalid signal or error" (which in DEBUG builds causes the
2187 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2188 * already know will fail.
2205 int link(const char *oldpath, const char *newpath)
2207 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2208 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2209 xutftowcs_path(wnewpath, newpath) < 0)
2212 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2213 errno = err_win_to_posix(GetLastError());
2219 pid_t waitpid(pid_t pid, int *status, int options)
2221 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2228 if (pid > 0 && options & WNOHANG) {
2229 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2233 options &= ~WNOHANG;
2237 struct pinfo_t **ppinfo;
2238 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2244 GetExitCodeProcess(h, (LPDWORD)status);
2246 EnterCriticalSection(&pinfo_cs);
2250 struct pinfo_t *info = *ppinfo;
2251 if (info->pid == pid) {
2252 CloseHandle(info->proc);
2253 *ppinfo = info->next;
2257 ppinfo = &info->next;
2260 LeaveCriticalSection(&pinfo_cs);
2271 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2273 int upos = 0, wpos = 0;
2274 const unsigned char *utf = (const unsigned char*) utfs;
2275 if (!utf || !wcs || wcslen < 1) {
2279 /* reserve space for \0 */
2284 while (upos < utflen) {
2285 int c = utf[upos++] & 0xff;
2286 if (utflen == INT_MAX && c == 0)
2289 if (wpos >= wcslen) {
2298 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2299 (utf[upos] & 0xc0) == 0x80) {
2301 c = ((c & 0x1f) << 6);
2302 c |= (utf[upos++] & 0x3f);
2304 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2305 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2306 (utf[upos] & 0xc0) == 0x80 &&
2307 (utf[upos + 1] & 0xc0) == 0x80) {
2309 c = ((c & 0x0f) << 12);
2310 c |= ((utf[upos++] & 0x3f) << 6);
2311 c |= (utf[upos++] & 0x3f);
2313 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2314 wpos + 1 < wcslen &&
2315 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2316 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2317 (utf[upos] & 0xc0) == 0x80 &&
2318 (utf[upos + 1] & 0xc0) == 0x80 &&
2319 (utf[upos + 2] & 0xc0) == 0x80) {
2320 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2321 c = ((c & 0x07) << 18);
2322 c |= ((utf[upos++] & 0x3f) << 12);
2323 c |= ((utf[upos++] & 0x3f) << 6);
2324 c |= (utf[upos++] & 0x3f);
2326 wcs[wpos++] = 0xd800 | (c >> 10);
2327 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2328 } else if (c >= 0xa0) {
2329 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2332 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2333 static const char *hex = "0123456789abcdef";
2334 wcs[wpos++] = hex[c >> 4];
2336 wcs[wpos++] = hex[c & 0x0f];
2343 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2345 if (!wcs || !utf || utflen < 1) {
2349 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2356 static void setup_windows_environment(void)
2358 char *tmp = getenv("TMPDIR");
2360 /* on Windows it is TMP and TEMP */
2362 if (!(tmp = getenv("TMP")))
2363 tmp = getenv("TEMP");
2365 setenv("TMPDIR", tmp, 1);
2366 tmp = getenv("TMPDIR");
2372 * Convert all dir separators to forward slashes,
2373 * to help shell commands called from the Git
2374 * executable (by not mistaking the dir separators
2375 * for escape characters).
2377 convert_slashes(tmp);
2380 /* simulate TERM to enable auto-color (see color.c) */
2381 if (!getenv("TERM"))
2382 setenv("TERM", "cygwin", 1);
2384 /* calculate HOME if not set */
2385 if (!getenv("HOME")) {
2387 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2388 * location, thus also check if the path exists (i.e. is not
2391 if ((tmp = getenv("HOMEDRIVE"))) {
2392 struct strbuf buf = STRBUF_INIT;
2393 strbuf_addstr(&buf, tmp);
2394 if ((tmp = getenv("HOMEPATH"))) {
2395 strbuf_addstr(&buf, tmp);
2396 if (is_directory(buf.buf))
2397 setenv("HOME", buf.buf, 1);
2399 tmp = NULL; /* use $USERPROFILE */
2401 strbuf_release(&buf);
2403 /* use $USERPROFILE if the home share is not available */
2404 if (!tmp && (tmp = getenv("USERPROFILE")))
2405 setenv("HOME", tmp, 1);
2409 int is_valid_win32_path(const char *path)
2411 int preceding_space_or_period = 0, i = 0, periods = 0;
2416 skip_dos_drive_prefix((char **)&path);
2422 case '/': case '\\':
2423 /* cannot end in ` ` or `.`, except for `.` and `..` */
2424 if (preceding_space_or_period &&
2425 (i != periods || periods > 2))
2430 i = periods = preceding_space_or_period = 0;
2436 preceding_space_or_period = 1;
2439 case ':': /* DOS drive prefix was already skipped */
2440 case '<': case '>': case '"': case '|': case '?': case '*':
2441 /* illegal character */
2444 if (c > '\0' && c < '\x20')
2445 /* illegal character */
2448 preceding_space_or_period = 0;
2453 #if !defined(_MSC_VER)
2455 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2456 * mingw startup code, see init.c in mingw runtime).
2461 static NORETURN void die_startup(void)
2463 fputs("fatal: not enough memory for initialization", stderr);
2467 static void *malloc_startup(size_t size)
2469 void *result = malloc(size);
2475 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2477 len = xwcstoutf(buffer, wcs, len) + 1;
2478 return memcpy(malloc_startup(len), buffer, len);
2481 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2482 DWORD desired_access, DWORD flags)
2484 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2485 wchar_t buf[MAX_PATH];
2486 DWORD max = ARRAY_SIZE(buf);
2488 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2490 if (!ret || ret >= max)
2493 /* make sure this does not leak into child processes */
2494 SetEnvironmentVariableW(key, NULL);
2495 if (!wcscmp(buf, L"off")) {
2497 handle = GetStdHandle(std_id);
2498 if (handle != INVALID_HANDLE_VALUE)
2499 CloseHandle(handle);
2502 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2503 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2504 if (handle == INVALID_HANDLE_VALUE) {
2506 handle = GetStdHandle(std_id);
2507 if (handle != INVALID_HANDLE_VALUE)
2508 CloseHandle(handle);
2510 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2511 SetStdHandle(std_id, handle);
2513 /* do *not* close the new_fd: that would close stdout */
2517 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2519 if (handle != INVALID_HANDLE_VALUE) {
2520 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2521 SetStdHandle(std_id, handle);
2527 static void maybe_redirect_std_handles(void)
2529 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2530 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2531 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2532 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2533 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2534 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2544 * We implement wmain() and compile with -municode, which would
2545 * normally ignore main(), but we call the latter from the former
2546 * so that we can handle non-ASCII command-line parameters
2549 * To be more compatible with the core git code, we convert
2550 * argv into UTF8 and pass them directly to main().
2552 int wmain(int argc, const wchar_t **wargv)
2554 int i, maxlen, exit_status;
2555 char *buffer, **save;
2558 trace2_initialize_clock();
2562 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2565 #ifdef USE_MSVC_CRTDBG
2566 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2570 maybe_redirect_std_handles();
2572 /* determine size of argv and environ conversion buffer */
2573 maxlen = wcslen(wargv[0]);
2574 for (i = 1; i < argc; i++)
2575 maxlen = max(maxlen, wcslen(wargv[i]));
2577 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2578 maxlen = 3 * maxlen + 1;
2579 buffer = malloc_startup(maxlen);
2582 * Create a UTF-8 version of w_argv. Also create a "save" copy
2583 * to remember all the string pointers because parse_options()
2584 * will remove claimed items from the argv that we pass down.
2586 ALLOC_ARRAY(argv, argc + 1);
2587 ALLOC_ARRAY(save, argc + 1);
2588 for (i = 0; i < argc; i++)
2589 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2590 argv[i] = save[i] = NULL;
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 */
2610 /* invoke the real main() using our utf8 version of argv. */
2611 exit_status = main(argc, argv);
2613 for (i = 0; i < argc; i++)
2621 int uname(struct utsname *buf)
2623 unsigned v = (unsigned)GetVersion();
2624 memset(buf, 0, sizeof(*buf));
2625 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2626 xsnprintf(buf->release, sizeof(buf->release),
2627 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2628 /* assuming NT variants only.. */
2629 xsnprintf(buf->version, sizeof(buf->version),
2630 "%u", (v >> 16) & 0x7fff);