1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "../git-compat-util.h"
10 #include "../run-command.h"
11 #include "../abspath.h"
13 #include "win32/lazyload.h"
14 #include "../config.h"
15 #include "../environment.h"
16 #include "../trace2.h"
17 #include "../symlinks.h"
18 #include "../wrapper.h"
21 #define SECURITY_WIN32
24 #define HCAST(type, handle) ((type)(intptr_t)handle)
26 static const int delay
[] = { 0, 1, 10, 20, 40 };
28 void open_in_gdb(void)
30 static struct child_process cp
= CHILD_PROCESS_INIT
;
32 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
33 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
35 if (start_command(&cp
) < 0)
36 die_errno("Could not start gdb");
40 int err_win_to_posix(DWORD winerr
)
44 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
45 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
46 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
47 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
48 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
49 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
50 case ERROR_BAD_COMMAND
: error
= EIO
; break;
51 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
52 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
53 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
54 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
55 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
56 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
57 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
58 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
59 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
60 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
61 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
62 case ERROR_BUSY
: error
= EBUSY
; break;
63 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
64 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
65 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
66 case ERROR_CANTOPEN
: error
= EIO
; break;
67 case ERROR_CANTREAD
: error
= EIO
; break;
68 case ERROR_CANTWRITE
: error
= EIO
; break;
69 case ERROR_CRC
: error
= EIO
; break;
70 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
71 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
72 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
73 case ERROR_DIRECTORY
: error
= EINVAL
; break;
74 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
75 case ERROR_DISK_CHANGE
: error
= EIO
; break;
76 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
77 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
78 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
79 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
80 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
81 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
82 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
83 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
84 case ERROR_GEN_FAILURE
: error
= EIO
; break;
85 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
86 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
87 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
88 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
89 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
90 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
91 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
92 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
93 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
94 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
95 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
96 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
97 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
98 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
99 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
100 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
101 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
102 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
103 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
104 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
105 case ERROR_IO_DEVICE
: error
= EIO
; break;
106 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
107 case ERROR_LOCKED
: error
= EBUSY
; break;
108 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
109 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
110 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
111 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
112 case ERROR_MORE_DATA
: error
= EPIPE
; break;
113 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
114 case ERROR_NOACCESS
: error
= EFAULT
; break;
115 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
116 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
117 case ERROR_NOT_READY
: error
= EAGAIN
; break;
118 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
119 case ERROR_NO_DATA
: error
= EPIPE
; break;
120 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
121 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
122 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
123 case ERROR_OPEN_FAILED
: error
= EIO
; break;
124 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
125 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
126 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
127 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
128 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
129 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
130 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
131 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
132 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
133 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
134 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
135 case ERROR_READ_FAULT
: error
= EIO
; break;
136 case ERROR_SEEK
: error
= EIO
; break;
137 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
138 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
139 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
140 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
141 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
142 case ERROR_SWAPERROR
: error
= ENOENT
; break;
143 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
144 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
145 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
146 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
147 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
148 case ERROR_WRITE_FAULT
: error
= EIO
; break;
149 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
154 static inline int is_file_in_use_error(DWORD errcode
)
157 case ERROR_SHARING_VIOLATION
:
158 case ERROR_ACCESS_DENIED
:
165 static int read_yes_no_answer(void)
169 if (fgets(answer
, sizeof(answer
), stdin
)) {
170 size_t answer_len
= strlen(answer
);
171 int got_full_line
= 0, c
;
173 /* remove the newline */
174 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
175 answer
[answer_len
-2] = '\0';
177 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
178 answer
[answer_len
-1] = '\0';
181 /* flush the buffer in case we did not get the full line */
183 while ((c
= getchar()) != EOF
&& c
!= '\n')
186 /* we could not read, return the
187 * default answer which is no */
190 if (tolower(answer
[0]) == 'y' && !answer
[1])
192 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
194 if (tolower(answer
[0]) == 'n' && !answer
[1])
196 if (!strncasecmp(answer
, "no", sizeof(answer
)))
199 /* did not find an answer we understand */
203 static int ask_yes_no_if_possible(const char *format
, ...)
206 const char *retry_hook
;
209 va_start(args
, format
);
210 vsnprintf(question
, sizeof(question
), format
, args
);
213 retry_hook
= mingw_getenv("GIT_ASK_YESNO");
215 struct child_process cmd
= CHILD_PROCESS_INIT
;
217 strvec_pushl(&cmd
.args
, retry_hook
, question
, NULL
);
218 return !run_command(&cmd
);
221 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
226 fprintf(stderr
, "%s (y/n) ", question
);
228 if ((answer
= read_yes_no_answer()) >= 0)
231 fprintf(stderr
, "Sorry, I did not understand your answer. "
232 "Please type 'y' or 'n'\n");
237 enum hide_dotfiles_type
{
238 HIDE_DOTFILES_FALSE
= 0,
240 HIDE_DOTFILES_DOTGITONLY
243 static int core_restrict_inherited_handles
= -1;
244 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
245 static char *unset_environment_variables
;
247 int mingw_core_config(const char *var
, const char *value
,
248 const struct config_context
*ctx UNUSED
,
251 if (!strcmp(var
, "core.hidedotfiles")) {
252 if (value
&& !strcasecmp(value
, "dotgitonly"))
253 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
255 hide_dotfiles
= git_config_bool(var
, value
);
259 if (!strcmp(var
, "core.unsetenvvars")) {
261 return config_error_nonbool(var
);
262 free(unset_environment_variables
);
263 unset_environment_variables
= xstrdup(value
);
267 if (!strcmp(var
, "core.restrictinheritedhandles")) {
268 if (value
&& !strcasecmp(value
, "auto"))
269 core_restrict_inherited_handles
= -1;
271 core_restrict_inherited_handles
=
272 git_config_bool(var
, value
);
279 /* Normalizes NT paths as returned by some low-level APIs. */
280 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
283 /* fix absolute path prefixes */
284 if (wbuf
[0] == '\\') {
285 /* strip NT namespace prefixes */
286 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
287 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
289 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
291 /* replace remaining '...UNC\' with '\\' */
292 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
297 /* convert backslashes to slashes */
298 for (i
= 0; wbuf
[i
]; i
++)
304 int mingw_unlink(const char *pathname
)
307 wchar_t wpathname
[MAX_PATH
];
308 if (xutftowcs_path(wpathname
, pathname
) < 0)
311 if (DeleteFileW(wpathname
))
314 /* read-only files cannot be removed */
315 _wchmod(wpathname
, 0666);
316 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
317 if (!is_file_in_use_error(GetLastError()))
320 * We assume that some other process had the source or
321 * destination file open at the wrong moment and retry.
322 * In order to give the other process a higher chance to
323 * complete its operation, we give up our time slice now.
324 * If we have to retry again, we do sleep a bit.
329 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
330 ask_yes_no_if_possible("Unlink of file '%s' failed. "
331 "Should I try again?", pathname
))
332 ret
= _wunlink(wpathname
);
336 static int is_dir_empty(const wchar_t *wpath
)
338 WIN32_FIND_DATAW findbuf
;
340 wchar_t wbuf
[MAX_PATH
+ 2];
342 wcscat(wbuf
, L
"\\*");
343 handle
= FindFirstFileW(wbuf
, &findbuf
);
344 if (handle
== INVALID_HANDLE_VALUE
)
345 return GetLastError() == ERROR_NO_MORE_FILES
;
347 while (!wcscmp(findbuf
.cFileName
, L
".") ||
348 !wcscmp(findbuf
.cFileName
, L
".."))
349 if (!FindNextFileW(handle
, &findbuf
)) {
350 DWORD err
= GetLastError();
352 return err
== ERROR_NO_MORE_FILES
;
358 int mingw_rmdir(const char *pathname
)
361 wchar_t wpathname
[MAX_PATH
];
365 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
366 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
367 * symbolic link (if it points to a directory).
369 * This behavior breaks the assumption of e.g. `remove_path()` which
370 * upon successful deletion of a file will attempt to remove its parent
371 * directories recursively until failure (which usually happens when
372 * the directory is not empty).
374 * Therefore, before calling `_wrmdir()`, we first check if the path is
375 * a symbolic link. If it is, we exit and return the same error as
376 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
378 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
383 if (xutftowcs_path(wpathname
, pathname
) < 0)
386 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
387 if (!is_file_in_use_error(GetLastError()))
388 errno
= err_win_to_posix(GetLastError());
391 if (!is_dir_empty(wpathname
)) {
396 * We assume that some other process had the source or
397 * destination file open at the wrong moment and retry.
398 * In order to give the other process a higher chance to
399 * complete its operation, we give up our time slice now.
400 * If we have to retry again, we do sleep a bit.
405 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
406 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
407 "Should I try again?", pathname
))
408 ret
= _wrmdir(wpathname
);
410 invalidate_lstat_cache();
414 static inline int needs_hiding(const char *path
)
416 const char *basename
;
418 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
421 /* We cannot use basename(), as it would remove trailing slashes */
422 win32_skip_dos_drive_prefix((char **)&path
);
426 for (basename
= path
; *path
; path
++)
427 if (is_dir_sep(*path
)) {
430 } while (is_dir_sep(*path
));
431 /* ignore trailing slashes */
438 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
439 return *basename
== '.';
441 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
442 return !strncasecmp(".git", basename
, 4) &&
443 (!basename
[4] || is_dir_sep(basename
[4]));
446 static int set_hidden_flag(const wchar_t *path
, int set
)
448 DWORD original
= GetFileAttributesW(path
), modified
;
450 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
452 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
453 if (original
== modified
|| SetFileAttributesW(path
, modified
))
455 errno
= err_win_to_posix(GetLastError());
459 int mingw_mkdir(const char *path
, int mode UNUSED
)
462 wchar_t wpath
[MAX_PATH
];
464 if (!is_valid_win32_path(path
, 0)) {
469 if (xutftowcs_path(wpath
, path
) < 0)
471 ret
= _wmkdir(wpath
);
472 if (!ret
&& needs_hiding(path
))
473 return set_hidden_flag(wpath
, 1);
478 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
479 * is documented in [1] as opening a writable file handle in append mode.
480 * (It is believed that) this is atomic since it is maintained by the
481 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
483 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
485 * This trick does not appear to work for named pipes. Instead it creates
486 * a named pipe client handle that cannot be written to. Callers should
487 * just use the regular _wopen() for them. (And since client handle gets
488 * bound to a unique server handle, it isn't really an issue.)
490 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
494 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
496 /* only these flags are supported */
497 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
498 return errno
= ENOSYS
, -1;
501 * FILE_SHARE_WRITE is required to permit child processes
502 * to append to the file.
504 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
505 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
506 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
507 if (handle
== INVALID_HANDLE_VALUE
) {
508 DWORD err
= GetLastError();
511 * Some network storage solutions (e.g. Isilon) might return
512 * ERROR_INVALID_PARAMETER instead of expected error
513 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
514 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
516 if (err
== ERROR_INVALID_PARAMETER
)
517 err
= ERROR_PATH_NOT_FOUND
;
519 errno
= err_win_to_posix(err
);
524 * No O_APPEND here, because the CRT uses it only to reset the
525 * file pointer to EOF before each write(); but that is not
526 * necessary (and may lead to races) for a file created with
529 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
536 * Does the pathname map to the local named pipe filesystem?
537 * That is, does it have a "//./pipe/" prefix?
539 static int is_local_named_pipe_path(const char *filename
)
541 return (is_dir_sep(filename
[0]) &&
542 is_dir_sep(filename
[1]) &&
543 filename
[2] == '.' &&
544 is_dir_sep(filename
[3]) &&
545 !strncasecmp(filename
+4, "pipe", 4) &&
546 is_dir_sep(filename
[8]) &&
550 int mingw_open (const char *filename
, int oflags
, ...)
552 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
555 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
556 wchar_t wfilename
[MAX_PATH
];
559 va_start(args
, oflags
);
560 mode
= va_arg(args
, int);
563 if (!is_valid_win32_path(filename
, !create
)) {
564 errno
= create
? EINVAL
: ENOENT
;
568 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
569 open_fn
= mingw_open_append
;
573 if (filename
&& !strcmp(filename
, "/dev/null"))
574 wcscpy(wfilename
, L
"nul");
575 else if (xutftowcs_path(wfilename
, filename
) < 0)
578 fd
= open_fn(wfilename
, oflags
, mode
);
580 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
581 DWORD attrs
= GetFileAttributesW(wfilename
);
582 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
585 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
587 * Internally, _wopen() uses the CreateFile() API which errors
588 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
589 * specified and an already existing file's attributes do not
590 * match *exactly*. As there is no mode or flag we can set that
591 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
592 * again *without* the O_CREAT flag (that corresponds to the
593 * CREATE_ALWAYS flag of CreateFile()).
595 if (fd
< 0 && errno
== EACCES
)
596 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
597 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
598 warning("could not mark '%s' as hidden.", filename
);
603 static BOOL WINAPI
ctrl_ignore(DWORD type UNUSED
)
609 int mingw_fgetc(FILE *stream
)
612 if (!isatty(_fileno(stream
)))
613 return fgetc(stream
);
615 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
618 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
621 /* Ctrl+C was pressed, simulate SIGINT and retry */
624 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
629 FILE *mingw_fopen (const char *filename
, const char *otype
)
631 int hide
= needs_hiding(filename
);
633 wchar_t wfilename
[MAX_PATH
], wotype
[4];
634 if (filename
&& !strcmp(filename
, "/dev/null"))
635 wcscpy(wfilename
, L
"nul");
636 else if (!is_valid_win32_path(filename
, 1)) {
637 int create
= otype
&& strchr(otype
, 'w');
638 errno
= create
? EINVAL
: ENOENT
;
640 } else if (xutftowcs_path(wfilename
, filename
) < 0)
643 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
646 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
647 error("could not unhide %s", filename
);
650 file
= _wfopen(wfilename
, wotype
);
651 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
653 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
654 warning("could not mark '%s' as hidden.", filename
);
658 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
660 int hide
= needs_hiding(filename
);
662 wchar_t wfilename
[MAX_PATH
], wotype
[4];
663 if (filename
&& !strcmp(filename
, "/dev/null"))
664 wcscpy(wfilename
, L
"nul");
665 else if (!is_valid_win32_path(filename
, 1)) {
666 int create
= otype
&& strchr(otype
, 'w');
667 errno
= create
? EINVAL
: ENOENT
;
669 } else if (xutftowcs_path(wfilename
, filename
) < 0)
672 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
675 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
676 error("could not unhide %s", filename
);
679 file
= _wfreopen(wfilename
, wotype
, stream
);
680 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
681 warning("could not mark '%s' as hidden.", filename
);
686 int mingw_fflush(FILE *stream
)
688 int ret
= fflush(stream
);
691 * write() is used behind the scenes of stdio output functions.
692 * Since git code does not check for errors after each stdio write
693 * operation, it can happen that write() is called by a later
694 * stdio function even if an earlier write() call failed. In the
695 * case of a pipe whose readable end was closed, only the first
696 * call to write() reports EPIPE on Windows. Subsequent write()
697 * calls report EINVAL. It is impossible to notice whether this
698 * fflush invocation triggered such a case, therefore, we have to
699 * catch all EINVAL errors whole-sale.
701 if (ret
&& errno
== EINVAL
)
708 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
710 ssize_t result
= write(fd
, buf
, len
);
712 if (result
< 0 && (errno
== EINVAL
|| errno
== ENOSPC
) && buf
) {
715 /* check if fd is a pipe */
716 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
717 if (GetFileType(h
) != FILE_TYPE_PIPE
)
719 else if (orig
== EINVAL
)
724 if (!GetNamedPipeInfo(h
, NULL
, NULL
, &buf_size
, NULL
))
727 return write(fd
, buf
, buf_size
);
735 int mingw_access(const char *filename
, int mode
)
737 wchar_t wfilename
[MAX_PATH
];
738 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
740 if (xutftowcs_path(wfilename
, filename
) < 0)
742 /* X_OK is not supported by the MSVCRT version */
743 return _waccess(wfilename
, mode
& ~X_OK
);
746 int mingw_chdir(const char *dirname
)
748 wchar_t wdirname
[MAX_PATH
];
749 if (xutftowcs_path(wdirname
, dirname
) < 0)
751 return _wchdir(wdirname
);
754 int mingw_chmod(const char *filename
, int mode
)
756 wchar_t wfilename
[MAX_PATH
];
757 if (xutftowcs_path(wfilename
, filename
) < 0)
759 return _wchmod(wfilename
, mode
);
763 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
764 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
766 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
768 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
769 /* Windows to Unix Epoch conversion */
770 return winTime
- 116444736000000000LL;
773 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
775 long long hnsec
= filetime_to_hnsec(ft
);
776 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
777 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
781 * Verifies that safe_create_leading_directories() would succeed.
783 static int has_valid_directory_prefix(wchar_t *wfilename
)
785 int n
= wcslen(wfilename
);
788 wchar_t c
= wfilename
[--n
];
794 wfilename
[n
] = L
'\0';
795 attributes
= GetFileAttributesW(wfilename
);
798 (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
))
800 if (attributes
== INVALID_FILE_ATTRIBUTES
)
801 switch (GetLastError()) {
802 case ERROR_PATH_NOT_FOUND
:
804 case ERROR_FILE_NOT_FOUND
:
805 /* This implies parent directory exists. */
813 /* We keep the do_lstat code in a separate function to avoid recursion.
814 * When a path ends with a slash, the stat will fail with ENOENT. In
815 * this case, we strip the trailing slashes and stat again.
817 * If follow is true then act like stat() and report on the link
818 * target. Otherwise report on the link itself.
820 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
822 WIN32_FILE_ATTRIBUTE_DATA fdata
;
823 wchar_t wfilename
[MAX_PATH
];
824 if (xutftowcs_path(wfilename
, file_name
) < 0)
827 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
832 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
833 buf
->st_size
= fdata
.nFileSizeLow
|
834 (((off_t
)fdata
.nFileSizeHigh
)<<32);
835 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
836 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
837 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
838 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
839 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
840 WIN32_FIND_DATAW findbuf
;
841 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
842 if (handle
!= INVALID_HANDLE_VALUE
) {
843 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
844 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
846 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
847 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
849 buf
->st_mode
= S_IFLNK
;
851 buf
->st_mode
|= S_IREAD
;
852 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
853 buf
->st_mode
|= S_IWRITE
;
860 switch (GetLastError()) {
861 case ERROR_ACCESS_DENIED
:
862 case ERROR_SHARING_VIOLATION
:
863 case ERROR_LOCK_VIOLATION
:
864 case ERROR_SHARING_BUFFER_EXCEEDED
:
867 case ERROR_BUFFER_OVERFLOW
:
868 errno
= ENAMETOOLONG
;
870 case ERROR_NOT_ENOUGH_MEMORY
:
873 case ERROR_PATH_NOT_FOUND
:
874 if (!has_valid_directory_prefix(wfilename
)) {
886 /* We provide our own lstat/fstat functions, since the provided
887 * lstat/fstat functions are so slow. These stat functions are
888 * tailored for Git's usage (read: fast), and are not meant to be
889 * complete. Note that Git stat()s are redirected to mingw_lstat()
890 * too, since Windows doesn't really handle symlinks that well.
892 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
895 char alt_name
[PATH_MAX
];
897 if (!do_lstat(follow
, file_name
, buf
))
900 /* if file_name ended in a '/', Windows returned ENOENT;
901 * try again without trailing slashes
906 namelen
= strlen(file_name
);
907 if (namelen
&& file_name
[namelen
-1] != '/')
909 while (namelen
&& file_name
[namelen
-1] == '/')
911 if (!namelen
|| namelen
>= PATH_MAX
)
914 memcpy(alt_name
, file_name
, namelen
);
915 alt_name
[namelen
] = 0;
916 return do_lstat(follow
, alt_name
, buf
);
919 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
921 BY_HANDLE_FILE_INFORMATION fdata
;
923 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
924 errno
= err_win_to_posix(GetLastError());
932 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
933 buf
->st_size
= fdata
.nFileSizeLow
|
934 (((off_t
)fdata
.nFileSizeHigh
)<<32);
935 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
936 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
937 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
938 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
942 int mingw_lstat(const char *file_name
, struct stat
*buf
)
944 return do_stat_internal(0, file_name
, buf
);
946 int mingw_stat(const char *file_name
, struct stat
*buf
)
948 return do_stat_internal(1, file_name
, buf
);
951 int mingw_fstat(int fd
, struct stat
*buf
)
953 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
954 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
958 return get_file_info_by_handle(fh
, buf
);
962 /* initialize stat fields */
963 memset(buf
, 0, sizeof(*buf
));
966 if (type
== FILE_TYPE_CHAR
) {
967 buf
->st_mode
= _S_IFCHR
;
969 buf
->st_mode
= _S_IFIFO
;
970 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
971 buf
->st_size
= avail
;
981 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
983 long long winTime
= t
* 10000000LL + 116444736000000000LL;
984 ft
->dwLowDateTime
= winTime
;
985 ft
->dwHighDateTime
= winTime
>> 32;
988 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
993 wchar_t wfilename
[MAX_PATH
];
996 if (xutftowcs_path(wfilename
, file_name
) < 0)
999 /* must have write permission */
1000 attrs
= GetFileAttributesW(wfilename
);
1001 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1002 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1003 /* ignore errors here; open() will report them */
1004 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
1007 osfilehandle
= CreateFileW(wfilename
,
1008 FILE_WRITE_ATTRIBUTES
,
1009 0 /*FileShare.None*/,
1012 (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1013 (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) ?
1014 FILE_FLAG_BACKUP_SEMANTICS
: 0,
1016 if (osfilehandle
== INVALID_HANDLE_VALUE
) {
1017 errno
= err_win_to_posix(GetLastError());
1023 time_t_to_filetime(times
->modtime
, &mft
);
1024 time_t_to_filetime(times
->actime
, &aft
);
1026 GetSystemTimeAsFileTime(&mft
);
1030 if (!SetFileTime(osfilehandle
, NULL
, &aft
, &mft
)) {
1036 if (osfilehandle
!= INVALID_HANDLE_VALUE
)
1037 CloseHandle(osfilehandle
);
1040 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1041 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1042 /* ignore errors again */
1043 SetFileAttributesW(wfilename
, attrs
);
1049 size_t mingw_strftime(char *s
, size_t max
,
1050 const char *format
, const struct tm
*tm
)
1052 /* a pointer to the original strftime in case we can't find the UCRT version */
1053 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1055 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1056 const char *, const struct tm
*);
1058 if (INIT_PROC_ADDR(strftime
))
1059 ret
= strftime(s
, max
, format
, tm
);
1061 ret
= fallback(s
, max
, format
, tm
);
1063 if (!ret
&& errno
== EINVAL
)
1064 die("invalid strftime format: '%s'", format
);
1068 unsigned int sleep (unsigned int seconds
)
1070 Sleep(seconds
*1000);
1074 char *mingw_mktemp(char *template)
1076 wchar_t wtemplate
[MAX_PATH
];
1077 if (xutftowcs_path(wtemplate
, template) < 0)
1079 if (!_wmktemp(wtemplate
))
1081 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1086 int mkstemp(char *template)
1088 return git_mkstemp_mode(template, 0600);
1091 int gettimeofday(struct timeval
*tv
, void *tz UNUSED
)
1096 GetSystemTimeAsFileTime(&ft
);
1097 hnsec
= filetime_to_hnsec(&ft
);
1098 tv
->tv_sec
= hnsec
/ 10000000;
1099 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1103 int pipe(int filedes
[2])
1107 /* this creates non-inheritable handles */
1108 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1109 errno
= err_win_to_posix(GetLastError());
1112 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1113 if (filedes
[0] < 0) {
1118 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1119 if (filedes
[1] < 0) {
1128 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1130 if (gmtime_s(result
, timep
) == 0)
1135 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1137 if (localtime_s(result
, timep
) == 0)
1143 char *mingw_getcwd(char *pointer
, int len
)
1145 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1146 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1148 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1149 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1152 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1153 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1154 HANDLE hnd
= CreateFileW(cwd
, 0,
1155 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1156 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1157 if (hnd
== INVALID_HANDLE_VALUE
)
1159 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1161 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1163 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1167 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1169 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1173 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1175 convert_slashes(pointer
);
1180 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1181 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1183 static const char *quote_arg_msvc(const char *arg
)
1185 /* count chars to quote */
1187 int force_quotes
= 0;
1189 const char *p
= arg
;
1190 if (!*p
) force_quotes
= 1;
1192 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1196 else if (*p
== '\\') {
1198 while (*p
== '\\') {
1203 if (*p
== '"' || !*p
)
1210 if (!force_quotes
&& n
== 0)
1213 /* insert \ where necessary */
1214 d
= q
= xmalloc(st_add3(len
, n
, 3));
1219 else if (*arg
== '\\') {
1221 while (*arg
== '\\') {
1225 if (*arg
== '"' || !*arg
) {
1228 /* don't escape the surrounding end quote */
1243 static const char *quote_arg_msys2(const char *arg
)
1245 struct strbuf buf
= STRBUF_INIT
;
1246 const char *p2
= arg
, *p
;
1248 for (p
= arg
; *p
; p
++) {
1249 int ws
= isspace(*p
);
1250 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1251 *p
!= '?' && *p
!= '*' && *p
!= '~')
1254 strbuf_addch(&buf
, '"');
1256 strbuf_add(&buf
, p2
, p
- p2
);
1257 if (*p
== '\\' || *p
== '"')
1258 strbuf_addch(&buf
, '\\');
1263 strbuf_addch(&buf
, '"');
1267 strbuf_add(&buf
, p2
, p
- p2
);
1269 strbuf_addch(&buf
, '"');
1270 return strbuf_detach(&buf
, 0);
1273 static const char *parse_interpreter(const char *cmd
)
1275 static char buf
[100];
1279 /* don't even try a .exe */
1281 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1284 fd
= open(cmd
, O_RDONLY
);
1287 n
= read(fd
, buf
, sizeof(buf
)-1);
1289 if (n
< 4) /* at least '#!/x' and not error */
1292 if (buf
[0] != '#' || buf
[1] != '!')
1295 p
= buf
+ strcspn(buf
, "\r\n");
1300 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1303 if ((opt
= strchr(p
+1, ' ')))
1309 * exe_only means that we only want to detect .exe files, but not scripts
1310 * (which do not have an extension)
1312 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1313 int isexe
, int exe_only
)
1315 char path
[MAX_PATH
];
1316 wchar_t wpath
[MAX_PATH
];
1317 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1319 if (xutftowcs_path(wpath
, path
) < 0)
1322 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1323 return xstrdup(path
);
1324 wpath
[wcslen(wpath
)-4] = '\0';
1325 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1326 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1327 path
[strlen(path
)-4] = '\0';
1328 return xstrdup(path
);
1335 * Determines the absolute path of cmd using the split path in path.
1336 * If cmd contains a slash or backslash, no lookup is performed.
1338 static char *path_lookup(const char *cmd
, int exe_only
)
1342 int len
= strlen(cmd
);
1343 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1345 if (strpbrk(cmd
, "/\\"))
1346 return xstrdup(cmd
);
1348 path
= mingw_getenv("PATH");
1353 const char *sep
= strchrnul(path
, ';');
1354 int dirlen
= sep
- path
;
1356 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1365 char *mingw_locate_in_PATH(const char *cmd
)
1367 return path_lookup(cmd
, 0);
1370 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1372 while (*s
&& *s
!= c
)
1377 /* Compare only keys */
1378 static int wenvcmp(const void *a
, const void *b
)
1380 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1381 size_t p_len
, q_len
;
1384 p_len
= wcschrnul(p
, L
'=') - p
;
1385 q_len
= wcschrnul(q
, L
'=') - q
;
1387 /* If the length differs, include the shorter key's NUL */
1390 else if (p_len
> q_len
)
1393 return _wcsnicmp(p
, q
, p_len
);
1397 * Build an environment block combining the inherited environment
1398 * merged with the given list of settings.
1400 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1401 * Values of the form "KEY" in deltaenv delete inherited values.
1403 * Multiple entries in deltaenv for the same key are explicitly allowed.
1405 * We return a contiguous block of UNICODE strings with a final trailing
1408 static wchar_t *make_environment_block(char **deltaenv
)
1410 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1411 size_t wlen
, s
, delta_size
, size
;
1413 wchar_t **array
= NULL
;
1414 size_t alloc
= 0, nr
= 0, i
;
1416 size
= 1; /* for extra NUL at the end */
1418 /* If there is no deltaenv to apply, simply return a copy. */
1419 if (!deltaenv
|| !*deltaenv
) {
1420 for (p
= wenv
; p
&& *p
; ) {
1421 size_t s
= wcslen(p
) + 1;
1426 DUP_ARRAY(result
, wenv
, size
);
1427 FreeEnvironmentStringsW(wenv
);
1432 * If there is a deltaenv, let's accumulate all keys into `array`,
1433 * sort them using the stable git_stable_qsort() and then copy,
1434 * skipping duplicate keys
1436 for (p
= wenv
; p
&& *p
; ) {
1437 ALLOC_GROW(array
, nr
+ 1, alloc
);
1444 /* (over-)assess size needed for wchar version of deltaenv */
1445 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1446 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1447 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1449 /* convert the deltaenv, appending to array */
1450 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1451 ALLOC_GROW(array
, nr
+ 1, alloc
);
1452 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1457 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1458 ALLOC_ARRAY(result
, size
+ delta_size
);
1460 for (p
= result
, i
= 0; i
< nr
; i
++) {
1461 /* Skip any duplicate keys; last one wins */
1462 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1465 /* Skip "to delete" entry */
1466 if (!wcschr(array
[i
], L
'='))
1469 size
= wcslen(array
[i
]) + 1;
1470 COPY_ARRAY(p
, array
[i
], size
);
1477 FreeEnvironmentStringsW(wenv
);
1481 static void do_unset_environment_variables(void)
1484 char *p
= unset_environment_variables
;
1491 char *comma
= strchr(p
, ',');
1503 struct pinfo_t
*next
;
1507 static struct pinfo_t
*pinfo
= NULL
;
1508 CRITICAL_SECTION pinfo_cs
;
1510 /* Used to match and chomp off path components */
1511 static inline int match_last_path_component(const char *path
, size_t *len
,
1512 const char *component
)
1514 size_t component_len
= strlen(component
);
1515 if (*len
< component_len
+ 1 ||
1516 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1517 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1519 *len
-= component_len
+ 1;
1520 /* chomp off repeated dir separators */
1521 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1526 static int is_msys2_sh(const char *cmd
)
1531 if (!strcmp(cmd
, "sh")) {
1532 static int ret
= -1;
1538 p
= path_lookup(cmd
, 0);
1542 size_t len
= strlen(p
);
1544 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1545 match_last_path_component(p
, &len
, "bin") &&
1546 match_last_path_component(p
, &len
, "usr");
1552 if (ends_with(cmd
, "\\sh.exe") || ends_with(cmd
, "/sh.exe")) {
1556 sh
= path_lookup("sh", 0);
1558 return !fspathcmp(cmd
, sh
);
1564 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1566 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1568 static int restrict_handle_inheritance
= -1;
1570 PROCESS_INFORMATION pi
;
1571 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1572 HANDLE stdhandles
[3];
1573 DWORD stdhandles_count
= 0;
1576 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1577 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1580 const char *(*quote_arg
)(const char *arg
) =
1581 is_msys2_sh(cmd
? cmd
: *argv
) ?
1582 quote_arg_msys2
: quote_arg_msvc
;
1583 const char *strace_env
;
1585 /* Make sure to override previous errors, if any */
1588 if (restrict_handle_inheritance
< 0)
1589 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1591 * The following code to restrict which handles are inherited seems
1592 * to work properly only on Windows 7 and later, so let's disable it
1593 * on Windows Vista and 2008.
1595 if (restrict_handle_inheritance
< 0)
1596 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1598 do_unset_environment_variables();
1600 /* Determine whether or not we are associated to a console */
1601 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1602 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1603 FILE_ATTRIBUTE_NORMAL
, NULL
);
1604 if (cons
== INVALID_HANDLE_VALUE
) {
1605 /* There is no console associated with this process.
1606 * Since the child is a console process, Windows
1607 * would normally create a console window. But
1608 * since we'll be redirecting std streams, we do
1609 * not need the console.
1610 * It is necessary to use DETACHED_PROCESS
1611 * instead of CREATE_NO_WINDOW to make ssh
1612 * recognize that it has no console.
1614 flags
|= DETACHED_PROCESS
;
1616 /* There is already a console. If we specified
1617 * DETACHED_PROCESS here, too, Windows would
1618 * disassociate the child from the console.
1619 * The same is true for CREATE_NO_WINDOW.
1624 memset(&si
, 0, sizeof(si
));
1625 si
.StartupInfo
.cb
= sizeof(si
);
1626 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1627 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1628 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1630 /* The list of handles cannot contain duplicates */
1631 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1632 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1633 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1634 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1635 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1636 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1637 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1638 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1639 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1640 if (stdhandles_count
)
1641 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1643 if (*argv
&& !strcmp(cmd
, *argv
))
1645 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1647 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1650 /* concatenate argv, quoting args as we go */
1651 strbuf_init(&args
, 0);
1653 char *quoted
= (char *)quote_arg(cmd
);
1654 strbuf_addstr(&args
, quoted
);
1658 for (; *argv
; argv
++) {
1659 char *quoted
= (char *)quote_arg(*argv
);
1661 strbuf_addch(&args
, ' ');
1662 strbuf_addstr(&args
, quoted
);
1663 if (quoted
!= *argv
)
1667 strace_env
= getenv("GIT_STRACE_COMMANDS");
1669 char *p
= path_lookup("strace.exe", 1);
1671 return error("strace not found!");
1672 if (xutftowcs_path(wcmd
, p
) < 0) {
1677 if (!strcmp("1", strace_env
) ||
1678 !strcasecmp("yes", strace_env
) ||
1679 !strcasecmp("true", strace_env
))
1680 strbuf_insert(&args
, 0, "strace ", 7);
1682 const char *quoted
= quote_arg(strace_env
);
1683 struct strbuf buf
= STRBUF_INIT
;
1684 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1685 if (quoted
!= strace_env
)
1686 free((char *)quoted
);
1687 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1688 strbuf_release(&buf
);
1692 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1693 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1694 strbuf_release(&args
);
1696 wenvblk
= make_environment_block(deltaenv
);
1698 memset(&pi
, 0, sizeof(pi
));
1699 if (restrict_handle_inheritance
&& stdhandles_count
&&
1700 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1701 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1702 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1703 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1704 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1705 UpdateProcThreadAttribute(attr_list
, 0,
1706 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1708 stdhandles_count
* sizeof(HANDLE
),
1710 si
.lpAttributeList
= attr_list
;
1711 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1714 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1715 stdhandles_count
? TRUE
: FALSE
,
1716 flags
, wenvblk
, dir
? wdir
: NULL
,
1717 &si
.StartupInfo
, &pi
);
1720 * On Windows 2008 R2, it seems that specifying certain types of handles
1721 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1722 * error. Rather than playing finicky and fragile games, let's just try
1723 * to detect this situation and simply try again without restricting any
1724 * handle inheritance. This is still better than failing to create
1727 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1728 DWORD err
= GetLastError();
1729 struct strbuf buf
= STRBUF_INIT
;
1731 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1733 * On Windows 7 and earlier, handles on pipes and character
1734 * devices are inherited automatically, and cannot be
1735 * specified in the thread handle list. Rather than trying
1736 * to catch each and every corner case (and running the
1737 * chance of *still* forgetting a few), let's just fall
1738 * back to creating the process without trying to limit the
1739 * handle inheritance.
1741 !(err
== ERROR_INVALID_PARAMETER
&&
1742 GetVersion() >> 16 < 9200) &&
1743 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1747 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1749 for (i
= 0; i
< stdhandles_count
; i
++) {
1750 HANDLE h
= stdhandles
[i
];
1751 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1752 "handle info (%d) %lx\n", i
, h
,
1754 GetHandleInformation(h
, &fl
),
1757 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1758 "at\nhttps://github.com/git-for-windows/"
1759 "git/issues/new\n\n"
1760 "To suppress this warning, please set "
1761 "the environment variable\n\n"
1762 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1765 restrict_handle_inheritance
= 0;
1766 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1767 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1768 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1769 &si
.StartupInfo
, &pi
);
1771 errno
= err_win_to_posix(GetLastError());
1772 if (ret
&& buf
.len
) {
1773 warning("failed to restrict file handles (%ld)\n\n%s",
1776 strbuf_release(&buf
);
1778 errno
= err_win_to_posix(GetLastError());
1780 if (si
.lpAttributeList
)
1781 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1783 HeapFree(GetProcessHeap(), 0, attr_list
);
1791 CloseHandle(pi
.hThread
);
1794 * The process ID is the human-readable identifier of the process
1795 * that we want to present in log and error messages. The handle
1796 * is not useful for this purpose. But we cannot close it, either,
1797 * because it is not possible to turn a process ID into a process
1798 * handle after the process terminated.
1799 * Keep the handle in a list for waitpid.
1801 EnterCriticalSection(&pinfo_cs
);
1803 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1804 info
->pid
= pi
.dwProcessId
;
1805 info
->proc
= pi
.hProcess
;
1809 LeaveCriticalSection(&pinfo_cs
);
1811 return (pid_t
)pi
.dwProcessId
;
1814 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1816 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1819 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1821 int fhin
, int fhout
, int fherr
)
1824 char *prog
= path_lookup(cmd
, 0);
1831 const char *interpr
= parse_interpreter(prog
);
1834 const char *argv0
= argv
[0];
1835 char *iprog
= path_lookup(interpr
, 1);
1842 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1843 fhin
, fhout
, fherr
);
1849 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1850 fhin
, fhout
, fherr
);
1856 static int try_shell_exec(const char *cmd
, char *const *argv
)
1858 const char *interpr
= parse_interpreter(cmd
);
1864 prog
= path_lookup(interpr
, 1);
1869 while (argv
[argc
]) argc
++;
1870 ALLOC_ARRAY(argv2
, argc
+ 1);
1871 argv2
[0] = (char *)cmd
; /* full path to the script file */
1872 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1873 exec_id
= trace2_exec(prog
, (const char **)argv2
);
1874 pid
= mingw_spawnv(prog
, (const char **)argv2
, 1);
1877 if (waitpid(pid
, &status
, 0) < 0)
1879 trace2_exec_result(exec_id
, status
);
1882 trace2_exec_result(exec_id
, -1);
1883 pid
= 1; /* indicate that we tried but failed */
1890 int mingw_execv(const char *cmd
, char *const *argv
)
1892 /* check if git_command is a shell script */
1893 if (!try_shell_exec(cmd
, argv
)) {
1897 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1898 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1900 trace2_exec_result(exec_id
, -1);
1903 if (waitpid(pid
, &status
, 0) < 0)
1905 trace2_exec_result(exec_id
, status
);
1911 int mingw_execvp(const char *cmd
, char *const *argv
)
1913 char *prog
= path_lookup(cmd
, 0);
1916 mingw_execv(prog
, argv
);
1924 int mingw_kill(pid_t pid
, int sig
)
1926 if (pid
> 0 && sig
== SIGTERM
) {
1927 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1929 if (TerminateProcess(h
, -1)) {
1934 errno
= err_win_to_posix(GetLastError());
1937 } else if (pid
> 0 && sig
== 0) {
1938 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1950 * UTF-8 versions of getenv(), putenv() and unsetenv().
1951 * Internally, they use the CRT's stock UNICODE routines
1952 * to avoid data loss.
1954 char *mingw_getenv(const char *name
)
1956 #define GETENV_MAX_RETAIN 64
1957 static char *values
[GETENV_MAX_RETAIN
];
1958 static int value_counter
;
1959 int len_key
, len_value
;
1962 wchar_t w_value
[32768];
1964 if (!name
|| !*name
)
1967 len_key
= strlen(name
) + 1;
1968 /* We cannot use xcalloc() here because that uses getenv() itself */
1969 w_key
= calloc(len_key
, sizeof(wchar_t));
1971 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1972 xutftowcs(w_key
, name
, len_key
);
1973 /* GetEnvironmentVariableW() only sets the last error upon failure */
1974 SetLastError(ERROR_SUCCESS
);
1975 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1976 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1982 len_value
= len_value
* 3 + 1;
1983 /* We cannot use xcalloc() here because that uses getenv() itself */
1984 value
= calloc(len_value
, sizeof(char));
1986 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1987 xwcstoutf(value
, w_value
, len_value
);
1990 * We return `value` which is an allocated value and the caller is NOT
1991 * expecting to have to free it, so we keep a round-robin array,
1992 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1994 free(values
[value_counter
]);
1995 values
[value_counter
++] = value
;
1996 if (value_counter
>= ARRAY_SIZE(values
))
2002 int mingw_putenv(const char *namevalue
)
2005 wchar_t *wide
, *equal
;
2008 if (!namevalue
|| !*namevalue
)
2011 size
= strlen(namevalue
) * 2 + 1;
2012 wide
= calloc(size
, sizeof(wchar_t));
2014 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
2015 xutftowcs(wide
, namevalue
, size
);
2016 equal
= wcschr(wide
, L
'=');
2018 result
= SetEnvironmentVariableW(wide
, NULL
);
2021 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
2026 errno
= err_win_to_posix(GetLastError());
2028 return result
? 0 : -1;
2031 static void ensure_socket_initialization(void)
2034 static int initialized
= 0;
2039 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2040 die("unable to initialize winsock subsystem, error %d",
2043 atexit((void(*)(void)) WSACleanup
);
2048 int mingw_gethostname(char *name
, int namelen
)
2050 ensure_socket_initialization();
2051 return gethostname(name
, namelen
);
2054 #undef gethostbyname
2055 struct hostent
*mingw_gethostbyname(const char *host
)
2057 ensure_socket_initialization();
2058 return gethostbyname(host
);
2062 int mingw_getaddrinfo(const char *node
, const char *service
,
2063 const struct addrinfo
*hints
, struct addrinfo
**res
)
2065 ensure_socket_initialization();
2066 return getaddrinfo(node
, service
, hints
, res
);
2069 int mingw_socket(int domain
, int type
, int protocol
)
2074 ensure_socket_initialization();
2075 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2076 if (s
== INVALID_SOCKET
) {
2078 * WSAGetLastError() values are regular BSD error codes
2079 * biased by WSABASEERR.
2080 * However, strerror() does not know about networking
2081 * specific errors, which are values beginning at 38 or so.
2082 * Therefore, we choose to leave the biased error code
2083 * in errno so that _if_ someone looks up the code somewhere,
2084 * then it is at least the number that are usually listed.
2086 errno
= WSAGetLastError();
2089 /* convert into a file descriptor */
2090 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2092 return error("unable to make a socket file descriptor: %s",
2099 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2101 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2102 return connect(s
, sa
, sz
);
2106 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2108 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2109 return bind(s
, sa
, sz
);
2113 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2115 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2116 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2120 int mingw_shutdown(int sockfd
, int how
)
2122 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2123 return shutdown(s
, how
);
2127 int mingw_listen(int sockfd
, int backlog
)
2129 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2130 return listen(s
, backlog
);
2134 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2138 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2139 SOCKET s2
= accept(s1
, sa
, sz
);
2141 /* convert into a file descriptor */
2142 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2145 return error("unable to make a socket file descriptor: %s",
2152 int mingw_rename(const char *pold
, const char *pnew
)
2156 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2157 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2161 * Try native rename() first to get errno right.
2162 * It is based on MoveFile(), which cannot overwrite existing files.
2164 if (!_wrename(wpold
, wpnew
))
2166 if (errno
!= EEXIST
)
2169 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2171 /* TODO: translate more errors */
2172 gle
= GetLastError();
2173 if (gle
== ERROR_ACCESS_DENIED
&&
2174 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2175 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2176 DWORD attrsold
= GetFileAttributesW(wpold
);
2177 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2178 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2180 else if (!_wrmdir(wpnew
))
2184 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2185 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2186 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2188 gle
= GetLastError();
2189 /* revert file attributes on failure */
2190 SetFileAttributesW(wpnew
, attrs
);
2193 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2195 * We assume that some other process had the source or
2196 * destination file open at the wrong moment and retry.
2197 * In order to give the other process a higher chance to
2198 * complete its operation, we give up our time slice now.
2199 * If we have to retry again, we do sleep a bit.
2201 Sleep(delay
[tries
]);
2205 if (gle
== ERROR_ACCESS_DENIED
&&
2206 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2207 "Should I try again?", pold
, pnew
))
2215 * Note that this doesn't return the actual pagesize, but
2216 * the allocation granularity. If future Windows specific git code
2217 * needs the real getpagesize function, we need to find another solution.
2219 int mingw_getpagesize(void)
2223 return si
.dwAllocationGranularity
;
2226 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2227 enum EXTENDED_NAME_FORMAT
{
2229 NameUserPrincipal
= 8
2232 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2234 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2235 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2236 static wchar_t wbuffer
[1024];
2239 if (!INIT_PROC_ADDR(GetUserNameExW
))
2242 len
= ARRAY_SIZE(wbuffer
);
2243 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2244 char *converted
= xmalloc((len
*= 3));
2245 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2253 char *mingw_query_user_email(void)
2255 return get_extended_user_info(NameUserPrincipal
);
2258 struct passwd
*getpwuid(int uid UNUSED
)
2260 static unsigned initialized
;
2261 static char user_name
[100];
2262 static struct passwd
*p
;
2269 len
= ARRAY_SIZE(buf
);
2270 if (!GetUserNameW(buf
, &len
)) {
2275 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2280 p
= xmalloc(sizeof(*p
));
2281 p
->pw_name
= user_name
;
2282 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2285 * Data returned by getpwuid(3P) is treated as internal and
2286 * must never be written to or freed.
2288 p
->pw_gecos
= (char *) "unknown";
2295 static HANDLE timer_event
;
2296 static HANDLE timer_thread
;
2297 static int timer_interval
;
2298 static int one_shot
;
2299 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2301 /* The timer works like this:
2302 * The thread, ticktack(), is a trivial routine that most of the time
2303 * only waits to receive the signal to terminate. The main thread tells
2304 * the thread to terminate by setting the timer_event to the signalled
2306 * But ticktack() interrupts the wait state after the timer's interval
2307 * length to call the signal handler.
2310 static unsigned __stdcall
ticktack(void *dummy UNUSED
)
2312 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2313 mingw_raise(SIGALRM
);
2320 static int start_timer_thread(void)
2322 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2324 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2326 return errno
= ENOMEM
,
2327 error("cannot start timer thread");
2329 return errno
= ENOMEM
,
2330 error("cannot allocate resources for timer");
2334 static void stop_timer_thread(void)
2337 SetEvent(timer_event
); /* tell thread to terminate */
2339 int rc
= WaitForSingleObject(timer_thread
, 10000);
2340 if (rc
== WAIT_TIMEOUT
)
2341 error("timer thread did not terminate timely");
2342 else if (rc
!= WAIT_OBJECT_0
)
2343 error("waiting for timer thread failed: %lu",
2345 CloseHandle(timer_thread
);
2348 CloseHandle(timer_event
);
2350 timer_thread
= NULL
;
2353 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2355 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2358 int setitimer(int type UNUSED
, struct itimerval
*in
, struct itimerval
*out
)
2360 static const struct timeval zero
;
2361 static int atexit_done
;
2364 return errno
= EINVAL
,
2365 error("setitimer param 3 != NULL not implemented");
2366 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2367 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2368 return errno
= EINVAL
,
2369 error("setitimer: it_interval must be zero or eq it_value");
2372 stop_timer_thread();
2374 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2375 is_timeval_eq(&in
->it_interval
, &zero
))
2378 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2379 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2381 atexit(stop_timer_thread
);
2384 return start_timer_thread();
2387 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2390 return errno
= EINVAL
,
2391 error("sigaction only implemented for SIGALRM");
2393 return errno
= EINVAL
,
2394 error("sigaction: param 3 != NULL not implemented");
2396 timer_fn
= in
->sa_handler
;
2401 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2413 sigint_fn
= handler
;
2417 return signal(sig
, handler
);
2424 int mingw_raise(int sig
)
2428 if (timer_fn
== SIG_DFL
) {
2429 if (isatty(STDERR_FILENO
))
2430 fputs("Alarm clock\n", stderr
);
2431 exit(128 + SIGALRM
);
2432 } else if (timer_fn
!= SIG_IGN
)
2437 if (sigint_fn
== SIG_DFL
)
2439 else if (sigint_fn
!= SIG_IGN
)
2443 #if defined(_MSC_VER)
2450 case SIGABRT_COMPAT
:
2452 * The <signal.h> header in the MS C Runtime defines 8 signals
2453 * as being supported on the platform. Anything else causes an
2454 * "Invalid signal or error" (which in DEBUG builds causes the
2455 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2456 * already know will fail.
2473 int link(const char *oldpath
, const char *newpath
)
2475 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2476 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2477 xutftowcs_path(wnewpath
, newpath
) < 0)
2480 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2481 errno
= err_win_to_posix(GetLastError());
2487 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2489 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2496 if (pid
> 0 && options
& WNOHANG
) {
2497 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2501 options
&= ~WNOHANG
;
2505 struct pinfo_t
**ppinfo
;
2506 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2512 GetExitCodeProcess(h
, (LPDWORD
)status
);
2514 EnterCriticalSection(&pinfo_cs
);
2518 struct pinfo_t
*info
= *ppinfo
;
2519 if (info
->pid
== pid
) {
2520 CloseHandle(info
->proc
);
2521 *ppinfo
= info
->next
;
2525 ppinfo
= &info
->next
;
2528 LeaveCriticalSection(&pinfo_cs
);
2539 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2541 int upos
= 0, wpos
= 0;
2542 const unsigned char *utf
= (const unsigned char*) utfs
;
2543 if (!utf
|| !wcs
|| wcslen
< 1) {
2547 /* reserve space for \0 */
2552 while (upos
< utflen
) {
2553 int c
= utf
[upos
++] & 0xff;
2554 if (utflen
== INT_MAX
&& c
== 0)
2557 if (wpos
>= wcslen
) {
2566 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2567 (utf
[upos
] & 0xc0) == 0x80) {
2569 c
= ((c
& 0x1f) << 6);
2570 c
|= (utf
[upos
++] & 0x3f);
2572 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2573 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2574 (utf
[upos
] & 0xc0) == 0x80 &&
2575 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2577 c
= ((c
& 0x0f) << 12);
2578 c
|= ((utf
[upos
++] & 0x3f) << 6);
2579 c
|= (utf
[upos
++] & 0x3f);
2581 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2582 wpos
+ 1 < wcslen
&&
2583 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2584 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2585 (utf
[upos
] & 0xc0) == 0x80 &&
2586 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2587 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2588 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2589 c
= ((c
& 0x07) << 18);
2590 c
|= ((utf
[upos
++] & 0x3f) << 12);
2591 c
|= ((utf
[upos
++] & 0x3f) << 6);
2592 c
|= (utf
[upos
++] & 0x3f);
2594 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2595 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2596 } else if (c
>= 0xa0) {
2597 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2600 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2601 static const char *hex
= "0123456789abcdef";
2602 wcs
[wpos
++] = hex
[c
>> 4];
2604 wcs
[wpos
++] = hex
[c
& 0x0f];
2611 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2613 if (!wcs
|| !utf
|| utflen
< 1) {
2617 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2624 static void setup_windows_environment(void)
2626 char *tmp
= getenv("TMPDIR");
2628 /* on Windows it is TMP and TEMP */
2630 if (!(tmp
= getenv("TMP")))
2631 tmp
= getenv("TEMP");
2633 setenv("TMPDIR", tmp
, 1);
2634 tmp
= getenv("TMPDIR");
2640 * Convert all dir separators to forward slashes,
2641 * to help shell commands called from the Git
2642 * executable (by not mistaking the dir separators
2643 * for escape characters).
2645 convert_slashes(tmp
);
2648 /* simulate TERM to enable auto-color (see color.c) */
2649 if (!getenv("TERM"))
2650 setenv("TERM", "cygwin", 1);
2652 /* calculate HOME if not set */
2653 if (!getenv("HOME")) {
2655 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2656 * location, thus also check if the path exists (i.e. is not
2659 if ((tmp
= getenv("HOMEDRIVE"))) {
2660 struct strbuf buf
= STRBUF_INIT
;
2661 strbuf_addstr(&buf
, tmp
);
2662 if ((tmp
= getenv("HOMEPATH"))) {
2663 strbuf_addstr(&buf
, tmp
);
2664 if (is_directory(buf
.buf
))
2665 setenv("HOME", buf
.buf
, 1);
2667 tmp
= NULL
; /* use $USERPROFILE */
2669 strbuf_release(&buf
);
2671 /* use $USERPROFILE if the home share is not available */
2672 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2673 setenv("HOME", tmp
, 1);
2677 static PSID
get_current_user_sid(void)
2683 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2686 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2687 TOKEN_USER
*info
= xmalloc((size_t)len
);
2688 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2689 len
= GetLengthSid(info
->User
.Sid
);
2690 result
= xmalloc(len
);
2691 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2692 error(_("failed to copy SID (%ld)"),
2694 FREE_AND_NULL(result
);
2697 FREE_AND_NULL(info
);
2704 static BOOL
user_sid_to_user_name(PSID sid
, LPSTR
*str
)
2706 SID_NAME_USE pe_use
;
2707 DWORD len_user
= 0, len_domain
= 0;
2708 BOOL translate_sid_to_user
;
2711 * returns only FALSE, because the string pointers are NULL
2713 LookupAccountSidA(NULL
, sid
, NULL
, &len_user
, NULL
, &len_domain
,
2716 * Alloc needed space of the strings
2718 ALLOC_ARRAY((*str
), (size_t)len_domain
+ (size_t)len_user
);
2719 translate_sid_to_user
= LookupAccountSidA(NULL
, sid
,
2720 (*str
) + len_domain
, &len_user
, *str
, &len_domain
, &pe_use
);
2721 if (!translate_sid_to_user
)
2722 FREE_AND_NULL(*str
);
2724 (*str
)[len_domain
] = '/';
2725 return translate_sid_to_user
;
2728 static int acls_supported(const char *path
)
2730 size_t offset
= offset_1st_component(path
);
2731 WCHAR wroot
[MAX_PATH
];
2732 DWORD file_system_flags
;
2735 xutftowcsn(wroot
, path
, MAX_PATH
, offset
) > 0 &&
2736 GetVolumeInformationW(wroot
, NULL
, 0, NULL
, NULL
,
2737 &file_system_flags
, NULL
, 0))
2738 return !!(file_system_flags
& FILE_PERSISTENT_ACLS
);
2743 int is_path_owned_by_current_sid(const char *path
, struct strbuf
*report
)
2745 WCHAR wpath
[MAX_PATH
];
2747 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2750 static wchar_t home
[MAX_PATH
];
2754 if (xutftowcs_path(wpath
, path
) < 0)
2758 * On Windows, the home directory is owned by the administrator, but for
2759 * all practical purposes, it belongs to the user. Do pretend that it is
2760 * owned by the user.
2763 DWORD size
= ARRAY_SIZE(home
);
2764 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2765 if (!len
|| len
> size
)
2766 wcscpy(home
, L
"::N/A::");
2768 if (!wcsicmp(wpath
, home
))
2771 /* Get the owner SID */
2772 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2773 OWNER_SECURITY_INFORMATION
|
2774 DACL_SECURITY_INFORMATION
,
2775 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2777 if (err
!= ERROR_SUCCESS
)
2778 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2779 else if (sid
&& IsValidSid(sid
)) {
2780 /* Now, verify that the SID matches the current user's */
2781 static PSID current_user_sid
;
2784 if (!current_user_sid
)
2785 current_user_sid
= get_current_user_sid();
2787 if (current_user_sid
&&
2788 IsValidSid(current_user_sid
) &&
2789 EqualSid(sid
, current_user_sid
))
2791 else if (IsWellKnownSid(sid
, WinBuiltinAdministratorsSid
) &&
2792 CheckTokenMembership(NULL
, sid
, &is_member
) &&
2795 * If owned by the Administrators group, and the
2796 * current user is an administrator, we consider that
2801 IsWellKnownSid(sid
, WinWorldSid
) &&
2802 !acls_supported(path
)) {
2804 * On FAT32 volumes, ownership is not actually recorded.
2806 strbuf_addf(report
, "'%s' is on a file system that does "
2807 "not record ownership\n", path
);
2808 } else if (report
) {
2809 PCSTR str1
, str2
, str3
, str4
;
2810 LPSTR to_free1
= NULL
, to_free3
= NULL
,
2811 to_local_free2
= NULL
, to_local_free4
= NULL
;
2813 if (user_sid_to_user_name(sid
, &to_free1
))
2816 str1
= "(inconvertible)";
2817 if (ConvertSidToStringSidA(sid
, &to_local_free2
))
2818 str2
= to_local_free2
;
2820 str2
= "(inconvertible)";
2822 if (!current_user_sid
) {
2826 else if (!IsValidSid(current_user_sid
)) {
2830 if (user_sid_to_user_name(current_user_sid
,
2834 str3
= "(inconvertible)";
2835 if (ConvertSidToStringSidA(current_user_sid
,
2837 str4
= to_local_free4
;
2839 str4
= "(inconvertible)";
2842 "'%s' is owned by:\n"
2843 "\t%s (%s)\nbut the current user is:\n"
2845 path
, str1
, str2
, str3
, str4
);
2847 LocalFree(to_local_free2
);
2849 LocalFree(to_local_free4
);
2854 * We can release the security descriptor struct only now because `sid`
2855 * actually points into this struct.
2858 LocalFree(descriptor
);
2863 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2865 const char *p
= path
;
2866 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2871 skip_dos_drive_prefix((char **)&path
);
2878 case '/': case '\\':
2879 /* cannot end in ` ` or `.`, except for `.` and `..` */
2880 if (preceding_space_or_period
&&
2881 (i
!= periods
|| periods
> 2))
2886 i
= periods
= preceding_space_or_period
= 0;
2890 case 'a': case 'A': /* AUX */
2891 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2892 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2893 not_a_reserved_name
:
2899 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2900 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2901 goto not_a_reserved_name
;
2903 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2905 if (c
< '1' || c
> '9')
2906 goto not_a_reserved_name
;
2907 } else if (c
== 'n' || c
== 'N') { /* CON */
2909 if ((c
== 'i' || c
== 'I') &&
2910 ((c
= path
[i
+ 2]) == 'n' ||
2913 i
+= 3; /* CONIN$ */
2914 else if ((c
== 'o' || c
== 'O') &&
2915 ((c
= path
[i
+ 2]) == 'u' ||
2917 ((c
= path
[i
+ 3]) == 't' ||
2920 i
+= 4; /* CONOUT$ */
2922 goto not_a_reserved_name
;
2924 case 'l': case 'L': /* LPT<N> */
2925 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2926 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2927 !isdigit(path
[++i
]))
2928 goto not_a_reserved_name
;
2930 case 'n': case 'N': /* NUL */
2931 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2932 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2933 (allow_literal_nul
&&
2934 !path
[i
+ 1] && p
== path
))
2935 goto not_a_reserved_name
;
2937 case 'p': case 'P': /* PRN */
2938 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2939 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2940 goto not_a_reserved_name
;
2947 * So far, this looks like a reserved name. Let's see
2948 * whether it actually is one: trailing spaces, a file
2949 * extension, or an NTFS Alternate Data Stream do not
2950 * matter, the name is still reserved if any of those
2951 * follow immediately after the actual name.
2954 if (path
[i
] == ' ') {
2955 preceding_space_or_period
= 1;
2956 while (path
[++i
] == ' ')
2957 ; /* skip all spaces */
2961 if (c
&& c
!= '.' && c
!= ':' && !is_xplatform_dir_sep(c
))
2962 goto not_a_reserved_name
;
2964 /* contains reserved name */
2970 preceding_space_or_period
= 1;
2973 case ':': /* DOS drive prefix was already skipped */
2974 case '<': case '>': case '"': case '|': case '?': case '*':
2975 /* illegal character */
2978 if (c
> '\0' && c
< '\x20')
2979 /* illegal character */
2982 preceding_space_or_period
= 0;
2987 #if !defined(_MSC_VER)
2989 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2990 * mingw startup code, see init.c in mingw runtime).
2995 static NORETURN
void die_startup(void)
2997 fputs("fatal: not enough memory for initialization", stderr
);
3001 static void *malloc_startup(size_t size
)
3003 void *result
= malloc(size
);
3009 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
3011 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
3012 return memcpy(malloc_startup(len
), buffer
, len
);
3015 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
3016 DWORD desired_access
, DWORD flags
)
3018 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
3019 wchar_t buf
[MAX_PATH
];
3020 DWORD max
= ARRAY_SIZE(buf
);
3022 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
3024 if (!ret
|| ret
>= max
)
3027 /* make sure this does not leak into child processes */
3028 SetEnvironmentVariableW(key
, NULL
);
3029 if (!wcscmp(buf
, L
"off")) {
3031 handle
= GetStdHandle(std_id
);
3032 if (handle
!= INVALID_HANDLE_VALUE
)
3033 CloseHandle(handle
);
3036 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
3037 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
3038 if (handle
== INVALID_HANDLE_VALUE
) {
3040 handle
= GetStdHandle(std_id
);
3041 if (handle
!= INVALID_HANDLE_VALUE
)
3042 CloseHandle(handle
);
3044 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
3045 SetStdHandle(std_id
, handle
);
3047 /* do *not* close the new_fd: that would close stdout */
3051 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
3053 if (handle
!= INVALID_HANDLE_VALUE
) {
3054 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
3055 SetStdHandle(std_id
, handle
);
3061 static void maybe_redirect_std_handles(void)
3063 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
3064 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
3065 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
3066 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
3067 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
3068 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
3078 * We implement wmain() and compile with -municode, which would
3079 * normally ignore main(), but we call the latter from the former
3080 * so that we can handle non-ASCII command-line parameters
3083 * To be more compatible with the core git code, we convert
3084 * argv into UTF8 and pass them directly to main().
3086 int wmain(int argc
, const wchar_t **wargv
)
3088 int i
, maxlen
, exit_status
;
3089 char *buffer
, **save
;
3092 trace2_initialize_clock();
3096 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
3099 #ifdef USE_MSVC_CRTDBG
3100 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
3104 maybe_redirect_std_handles();
3106 /* determine size of argv and environ conversion buffer */
3107 maxlen
= wcslen(wargv
[0]);
3108 for (i
= 1; i
< argc
; i
++)
3109 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
3111 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3112 maxlen
= 3 * maxlen
+ 1;
3113 buffer
= malloc_startup(maxlen
);
3116 * Create a UTF-8 version of w_argv. Also create a "save" copy
3117 * to remember all the string pointers because parse_options()
3118 * will remove claimed items from the argv that we pass down.
3120 ALLOC_ARRAY(argv
, argc
+ 1);
3121 ALLOC_ARRAY(save
, argc
+ 1);
3122 for (i
= 0; i
< argc
; i
++)
3123 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
3124 argv
[i
] = save
[i
] = NULL
;
3127 /* fix Windows specific environment settings */
3128 setup_windows_environment();
3130 unset_environment_variables
= xstrdup("PERL5LIB");
3132 /* initialize critical section for waitpid pinfo_t list */
3133 InitializeCriticalSection(&pinfo_cs
);
3135 /* set up default file mode and file modes for stdin/out/err */
3137 _setmode(_fileno(stdin
), _O_BINARY
);
3138 _setmode(_fileno(stdout
), _O_BINARY
);
3139 _setmode(_fileno(stderr
), _O_BINARY
);
3141 /* initialize Unicode console */
3144 /* invoke the real main() using our utf8 version of argv. */
3145 exit_status
= main(argc
, argv
);
3147 for (i
= 0; i
< argc
; i
++)
3155 int uname(struct utsname
*buf
)
3157 unsigned v
= (unsigned)GetVersion();
3158 memset(buf
, 0, sizeof(*buf
));
3159 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3160 xsnprintf(buf
->release
, sizeof(buf
->release
),
3161 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3162 /* assuming NT variants only.. */
3163 xsnprintf(buf
->version
, sizeof(buf
->version
),
3164 "%u", (v
>> 16) & 0x7fff);
3168 #ifndef NO_UNIX_SOCKETS
3169 int mingw_have_unix_sockets(void)
3171 SC_HANDLE scm
, srvc
;
3172 SERVICE_STATUS_PROCESS status
;
3175 scm
= OpenSCManagerA(NULL
, NULL
, SC_MANAGER_CONNECT
);
3177 srvc
= OpenServiceA(scm
, "afunix", SERVICE_QUERY_STATUS
);
3179 if(QueryServiceStatusEx(srvc
, SC_STATUS_PROCESS_INFO
, (LPBYTE
)&status
, sizeof(SERVICE_STATUS_PROCESS
), &bytes
))
3180 ret
= status
.dwCurrentState
== SERVICE_RUNNING
;
3181 CloseServiceHandle(srvc
);
3183 CloseServiceHandle(scm
);