1 #include "../git-compat-util.h"
8 #include "../run-command.h"
9 #include "../abspath.h"
11 #include "win32/lazyload.h"
12 #include "../config.h"
13 #include "../environment.h"
14 #include "../trace2.h"
15 #include "../symlinks.h"
16 #include "../wrapper.h"
19 #define SECURITY_WIN32
22 #define HCAST(type, handle) ((type)(intptr_t)handle)
24 static const int delay
[] = { 0, 1, 10, 20, 40 };
26 void open_in_gdb(void)
28 static struct child_process cp
= CHILD_PROCESS_INIT
;
31 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
32 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
34 if (start_command(&cp
) < 0)
35 die_errno("Could not start gdb");
39 int err_win_to_posix(DWORD winerr
)
43 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
44 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
45 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
46 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
47 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
48 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
49 case ERROR_BAD_COMMAND
: error
= EIO
; break;
50 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
51 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
52 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
53 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
54 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
55 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
56 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
57 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
58 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
59 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
60 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
61 case ERROR_BUSY
: error
= EBUSY
; break;
62 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
63 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
64 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
65 case ERROR_CANTOPEN
: error
= EIO
; break;
66 case ERROR_CANTREAD
: error
= EIO
; break;
67 case ERROR_CANTWRITE
: error
= EIO
; break;
68 case ERROR_CRC
: error
= EIO
; break;
69 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
70 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
71 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
72 case ERROR_DIRECTORY
: error
= EINVAL
; break;
73 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
74 case ERROR_DISK_CHANGE
: error
= EIO
; break;
75 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
76 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
77 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
78 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
79 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
80 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
81 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
82 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
83 case ERROR_GEN_FAILURE
: error
= EIO
; break;
84 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
85 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
86 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
87 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
88 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
89 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
90 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
91 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
92 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
93 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
94 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
95 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
96 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
97 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
98 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
99 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
100 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
101 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
102 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
103 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
104 case ERROR_IO_DEVICE
: error
= EIO
; break;
105 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
106 case ERROR_LOCKED
: error
= EBUSY
; break;
107 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
108 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
109 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
110 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
111 case ERROR_MORE_DATA
: error
= EPIPE
; break;
112 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
113 case ERROR_NOACCESS
: error
= EFAULT
; break;
114 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
115 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
116 case ERROR_NOT_READY
: error
= EAGAIN
; break;
117 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
118 case ERROR_NO_DATA
: error
= EPIPE
; break;
119 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
120 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
121 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
122 case ERROR_OPEN_FAILED
: error
= EIO
; break;
123 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
124 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
125 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
126 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
127 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
128 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
129 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
130 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
131 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
132 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
133 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
134 case ERROR_READ_FAULT
: error
= EIO
; break;
135 case ERROR_SEEK
: error
= EIO
; break;
136 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
137 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
138 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
139 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
140 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
141 case ERROR_SWAPERROR
: error
= ENOENT
; break;
142 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
143 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
144 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
145 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
146 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
147 case ERROR_WRITE_FAULT
: error
= EIO
; break;
148 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
153 static inline int is_file_in_use_error(DWORD errcode
)
156 case ERROR_SHARING_VIOLATION
:
157 case ERROR_ACCESS_DENIED
:
164 static int read_yes_no_answer(void)
168 if (fgets(answer
, sizeof(answer
), stdin
)) {
169 size_t answer_len
= strlen(answer
);
170 int got_full_line
= 0, c
;
172 /* remove the newline */
173 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
174 answer
[answer_len
-2] = '\0';
176 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
177 answer
[answer_len
-1] = '\0';
180 /* flush the buffer in case we did not get the full line */
182 while ((c
= getchar()) != EOF
&& c
!= '\n')
185 /* we could not read, return the
186 * default answer which is no */
189 if (tolower(answer
[0]) == 'y' && !answer
[1])
191 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
193 if (tolower(answer
[0]) == 'n' && !answer
[1])
195 if (!strncasecmp(answer
, "no", sizeof(answer
)))
198 /* did not find an answer we understand */
202 static int ask_yes_no_if_possible(const char *format
, ...)
205 const char *retry_hook
;
208 va_start(args
, format
);
209 vsnprintf(question
, sizeof(question
), format
, args
);
212 retry_hook
= mingw_getenv("GIT_ASK_YESNO");
214 struct child_process cmd
= CHILD_PROCESS_INIT
;
216 strvec_pushl(&cmd
.args
, retry_hook
, question
, NULL
);
217 return !run_command(&cmd
);
220 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
225 fprintf(stderr
, "%s (y/n) ", question
);
227 if ((answer
= read_yes_no_answer()) >= 0)
230 fprintf(stderr
, "Sorry, I did not understand your answer. "
231 "Please type 'y' or 'n'\n");
236 enum hide_dotfiles_type
{
237 HIDE_DOTFILES_FALSE
= 0,
239 HIDE_DOTFILES_DOTGITONLY
242 static int core_restrict_inherited_handles
= -1;
243 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
244 static char *unset_environment_variables
;
246 int mingw_core_config(const char *var
, const char *value
,
247 const struct config_context
*ctx
, void *cb
)
249 if (!strcmp(var
, "core.hidedotfiles")) {
250 if (value
&& !strcasecmp(value
, "dotgitonly"))
251 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
253 hide_dotfiles
= git_config_bool(var
, value
);
257 if (!strcmp(var
, "core.unsetenvvars")) {
258 free(unset_environment_variables
);
259 unset_environment_variables
= xstrdup(value
);
263 if (!strcmp(var
, "core.restrictinheritedhandles")) {
264 if (value
&& !strcasecmp(value
, "auto"))
265 core_restrict_inherited_handles
= -1;
267 core_restrict_inherited_handles
=
268 git_config_bool(var
, value
);
275 /* Normalizes NT paths as returned by some low-level APIs. */
276 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
279 /* fix absolute path prefixes */
280 if (wbuf
[0] == '\\') {
281 /* strip NT namespace prefixes */
282 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
283 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
285 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
287 /* replace remaining '...UNC\' with '\\' */
288 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
293 /* convert backslashes to slashes */
294 for (i
= 0; wbuf
[i
]; i
++)
300 int mingw_unlink(const char *pathname
)
303 wchar_t wpathname
[MAX_PATH
];
304 if (xutftowcs_path(wpathname
, pathname
) < 0)
307 if (DeleteFileW(wpathname
))
310 /* read-only files cannot be removed */
311 _wchmod(wpathname
, 0666);
312 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
313 if (!is_file_in_use_error(GetLastError()))
316 * We assume that some other process had the source or
317 * destination file open at the wrong moment and retry.
318 * In order to give the other process a higher chance to
319 * complete its operation, we give up our time slice now.
320 * If we have to retry again, we do sleep a bit.
325 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
326 ask_yes_no_if_possible("Unlink of file '%s' failed. "
327 "Should I try again?", pathname
))
328 ret
= _wunlink(wpathname
);
332 static int is_dir_empty(const wchar_t *wpath
)
334 WIN32_FIND_DATAW findbuf
;
336 wchar_t wbuf
[MAX_PATH
+ 2];
338 wcscat(wbuf
, L
"\\*");
339 handle
= FindFirstFileW(wbuf
, &findbuf
);
340 if (handle
== INVALID_HANDLE_VALUE
)
341 return GetLastError() == ERROR_NO_MORE_FILES
;
343 while (!wcscmp(findbuf
.cFileName
, L
".") ||
344 !wcscmp(findbuf
.cFileName
, L
".."))
345 if (!FindNextFileW(handle
, &findbuf
)) {
346 DWORD err
= GetLastError();
348 return err
== ERROR_NO_MORE_FILES
;
354 int mingw_rmdir(const char *pathname
)
357 wchar_t wpathname
[MAX_PATH
];
361 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
362 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
363 * symbolic link (if it points to a directory).
365 * This behavior breaks the assumption of e.g. `remove_path()` which
366 * upon successful deletion of a file will attempt to remove its parent
367 * directories recursively until failure (which usually happens when
368 * the directory is not empty).
370 * Therefore, before calling `_wrmdir()`, we first check if the path is
371 * a symbolic link. If it is, we exit and return the same error as
372 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
374 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
379 if (xutftowcs_path(wpathname
, pathname
) < 0)
382 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
383 if (!is_file_in_use_error(GetLastError()))
384 errno
= err_win_to_posix(GetLastError());
387 if (!is_dir_empty(wpathname
)) {
392 * We assume that some other process had the source or
393 * destination file open at the wrong moment and retry.
394 * In order to give the other process a higher chance to
395 * complete its operation, we give up our time slice now.
396 * If we have to retry again, we do sleep a bit.
401 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
402 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
403 "Should I try again?", pathname
))
404 ret
= _wrmdir(wpathname
);
406 invalidate_lstat_cache();
410 static inline int needs_hiding(const char *path
)
412 const char *basename
;
414 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
417 /* We cannot use basename(), as it would remove trailing slashes */
418 win32_skip_dos_drive_prefix((char **)&path
);
422 for (basename
= path
; *path
; path
++)
423 if (is_dir_sep(*path
)) {
426 } while (is_dir_sep(*path
));
427 /* ignore trailing slashes */
434 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
435 return *basename
== '.';
437 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
438 return !strncasecmp(".git", basename
, 4) &&
439 (!basename
[4] || is_dir_sep(basename
[4]));
442 static int set_hidden_flag(const wchar_t *path
, int set
)
444 DWORD original
= GetFileAttributesW(path
), modified
;
446 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
448 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
449 if (original
== modified
|| SetFileAttributesW(path
, modified
))
451 errno
= err_win_to_posix(GetLastError());
455 int mingw_mkdir(const char *path
, int mode
)
458 wchar_t wpath
[MAX_PATH
];
460 if (!is_valid_win32_path(path
, 0)) {
465 if (xutftowcs_path(wpath
, path
) < 0)
467 ret
= _wmkdir(wpath
);
468 if (!ret
&& needs_hiding(path
))
469 return set_hidden_flag(wpath
, 1);
474 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
475 * is documented in [1] as opening a writable file handle in append mode.
476 * (It is believed that) this is atomic since it is maintained by the
477 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
479 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
481 * This trick does not appear to work for named pipes. Instead it creates
482 * a named pipe client handle that cannot be written to. Callers should
483 * just use the regular _wopen() for them. (And since client handle gets
484 * bound to a unique server handle, it isn't really an issue.)
486 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
490 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
492 /* only these flags are supported */
493 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
494 return errno
= ENOSYS
, -1;
497 * FILE_SHARE_WRITE is required to permit child processes
498 * to append to the file.
500 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
501 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
502 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
503 if (handle
== INVALID_HANDLE_VALUE
) {
504 DWORD err
= GetLastError();
507 * Some network storage solutions (e.g. Isilon) might return
508 * ERROR_INVALID_PARAMETER instead of expected error
509 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
510 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
512 if (err
== ERROR_INVALID_PARAMETER
)
513 err
= ERROR_PATH_NOT_FOUND
;
515 errno
= err_win_to_posix(err
);
520 * No O_APPEND here, because the CRT uses it only to reset the
521 * file pointer to EOF before each write(); but that is not
522 * necessary (and may lead to races) for a file created with
525 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
532 * Does the pathname map to the local named pipe filesystem?
533 * That is, does it have a "//./pipe/" prefix?
535 static int is_local_named_pipe_path(const char *filename
)
537 return (is_dir_sep(filename
[0]) &&
538 is_dir_sep(filename
[1]) &&
539 filename
[2] == '.' &&
540 is_dir_sep(filename
[3]) &&
541 !strncasecmp(filename
+4, "pipe", 4) &&
542 is_dir_sep(filename
[8]) &&
546 int mingw_open (const char *filename
, int oflags
, ...)
548 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
551 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
552 wchar_t wfilename
[MAX_PATH
];
555 va_start(args
, oflags
);
556 mode
= va_arg(args
, int);
559 if (!is_valid_win32_path(filename
, !create
)) {
560 errno
= create
? EINVAL
: ENOENT
;
564 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
565 open_fn
= mingw_open_append
;
569 if (filename
&& !strcmp(filename
, "/dev/null"))
570 wcscpy(wfilename
, L
"nul");
571 else if (xutftowcs_path(wfilename
, filename
) < 0)
574 fd
= open_fn(wfilename
, oflags
, mode
);
576 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
577 DWORD attrs
= GetFileAttributesW(wfilename
);
578 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
581 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
583 * Internally, _wopen() uses the CreateFile() API which errors
584 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
585 * specified and an already existing file's attributes do not
586 * match *exactly*. As there is no mode or flag we can set that
587 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
588 * again *without* the O_CREAT flag (that corresponds to the
589 * CREATE_ALWAYS flag of CreateFile()).
591 if (fd
< 0 && errno
== EACCES
)
592 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
593 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
594 warning("could not mark '%s' as hidden.", filename
);
599 static BOOL WINAPI
ctrl_ignore(DWORD type
)
605 int mingw_fgetc(FILE *stream
)
608 if (!isatty(_fileno(stream
)))
609 return fgetc(stream
);
611 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
614 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
617 /* Ctrl+C was pressed, simulate SIGINT and retry */
620 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
625 FILE *mingw_fopen (const char *filename
, const char *otype
)
627 int hide
= needs_hiding(filename
);
629 wchar_t wfilename
[MAX_PATH
], wotype
[4];
630 if (filename
&& !strcmp(filename
, "/dev/null"))
631 wcscpy(wfilename
, L
"nul");
632 else if (!is_valid_win32_path(filename
, 1)) {
633 int create
= otype
&& strchr(otype
, 'w');
634 errno
= create
? EINVAL
: ENOENT
;
636 } else if (xutftowcs_path(wfilename
, filename
) < 0)
639 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
642 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
643 error("could not unhide %s", filename
);
646 file
= _wfopen(wfilename
, wotype
);
647 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
649 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
650 warning("could not mark '%s' as hidden.", filename
);
654 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
656 int hide
= needs_hiding(filename
);
658 wchar_t wfilename
[MAX_PATH
], wotype
[4];
659 if (filename
&& !strcmp(filename
, "/dev/null"))
660 wcscpy(wfilename
, L
"nul");
661 else if (!is_valid_win32_path(filename
, 1)) {
662 int create
= otype
&& strchr(otype
, 'w');
663 errno
= create
? EINVAL
: ENOENT
;
665 } else if (xutftowcs_path(wfilename
, filename
) < 0)
668 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
671 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
672 error("could not unhide %s", filename
);
675 file
= _wfreopen(wfilename
, wotype
, stream
);
676 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
677 warning("could not mark '%s' as hidden.", filename
);
682 int mingw_fflush(FILE *stream
)
684 int ret
= fflush(stream
);
687 * write() is used behind the scenes of stdio output functions.
688 * Since git code does not check for errors after each stdio write
689 * operation, it can happen that write() is called by a later
690 * stdio function even if an earlier write() call failed. In the
691 * case of a pipe whose readable end was closed, only the first
692 * call to write() reports EPIPE on Windows. Subsequent write()
693 * calls report EINVAL. It is impossible to notice whether this
694 * fflush invocation triggered such a case, therefore, we have to
695 * catch all EINVAL errors whole-sale.
697 if (ret
&& errno
== EINVAL
)
704 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
706 ssize_t result
= write(fd
, buf
, len
);
708 if (result
< 0 && errno
== EINVAL
&& buf
) {
709 /* check if fd is a pipe */
710 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
711 if (GetFileType(h
) == FILE_TYPE_PIPE
)
720 int mingw_access(const char *filename
, int mode
)
722 wchar_t wfilename
[MAX_PATH
];
723 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
725 if (xutftowcs_path(wfilename
, filename
) < 0)
727 /* X_OK is not supported by the MSVCRT version */
728 return _waccess(wfilename
, mode
& ~X_OK
);
731 int mingw_chdir(const char *dirname
)
733 wchar_t wdirname
[MAX_PATH
];
734 if (xutftowcs_path(wdirname
, dirname
) < 0)
736 return _wchdir(wdirname
);
739 int mingw_chmod(const char *filename
, int mode
)
741 wchar_t wfilename
[MAX_PATH
];
742 if (xutftowcs_path(wfilename
, filename
) < 0)
744 return _wchmod(wfilename
, mode
);
748 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
749 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
751 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
753 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
754 /* Windows to Unix Epoch conversion */
755 return winTime
- 116444736000000000LL;
758 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
760 long long hnsec
= filetime_to_hnsec(ft
);
761 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
762 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
766 * Verifies that safe_create_leading_directories() would succeed.
768 static int has_valid_directory_prefix(wchar_t *wfilename
)
770 int n
= wcslen(wfilename
);
773 wchar_t c
= wfilename
[--n
];
779 wfilename
[n
] = L
'\0';
780 attributes
= GetFileAttributesW(wfilename
);
783 (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
))
785 if (attributes
== INVALID_FILE_ATTRIBUTES
)
786 switch (GetLastError()) {
787 case ERROR_PATH_NOT_FOUND
:
789 case ERROR_FILE_NOT_FOUND
:
790 /* This implies parent directory exists. */
798 /* We keep the do_lstat code in a separate function to avoid recursion.
799 * When a path ends with a slash, the stat will fail with ENOENT. In
800 * this case, we strip the trailing slashes and stat again.
802 * If follow is true then act like stat() and report on the link
803 * target. Otherwise report on the link itself.
805 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
807 WIN32_FILE_ATTRIBUTE_DATA fdata
;
808 wchar_t wfilename
[MAX_PATH
];
809 if (xutftowcs_path(wfilename
, file_name
) < 0)
812 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
817 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
818 buf
->st_size
= fdata
.nFileSizeLow
|
819 (((off_t
)fdata
.nFileSizeHigh
)<<32);
820 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
821 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
822 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
823 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
824 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
825 WIN32_FIND_DATAW findbuf
;
826 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
827 if (handle
!= INVALID_HANDLE_VALUE
) {
828 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
829 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
831 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
832 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
834 buf
->st_mode
= S_IFLNK
;
836 buf
->st_mode
|= S_IREAD
;
837 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
838 buf
->st_mode
|= S_IWRITE
;
845 switch (GetLastError()) {
846 case ERROR_ACCESS_DENIED
:
847 case ERROR_SHARING_VIOLATION
:
848 case ERROR_LOCK_VIOLATION
:
849 case ERROR_SHARING_BUFFER_EXCEEDED
:
852 case ERROR_BUFFER_OVERFLOW
:
853 errno
= ENAMETOOLONG
;
855 case ERROR_NOT_ENOUGH_MEMORY
:
858 case ERROR_PATH_NOT_FOUND
:
859 if (!has_valid_directory_prefix(wfilename
)) {
871 /* We provide our own lstat/fstat functions, since the provided
872 * lstat/fstat functions are so slow. These stat functions are
873 * tailored for Git's usage (read: fast), and are not meant to be
874 * complete. Note that Git stat()s are redirected to mingw_lstat()
875 * too, since Windows doesn't really handle symlinks that well.
877 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
880 char alt_name
[PATH_MAX
];
882 if (!do_lstat(follow
, file_name
, buf
))
885 /* if file_name ended in a '/', Windows returned ENOENT;
886 * try again without trailing slashes
891 namelen
= strlen(file_name
);
892 if (namelen
&& file_name
[namelen
-1] != '/')
894 while (namelen
&& file_name
[namelen
-1] == '/')
896 if (!namelen
|| namelen
>= PATH_MAX
)
899 memcpy(alt_name
, file_name
, namelen
);
900 alt_name
[namelen
] = 0;
901 return do_lstat(follow
, alt_name
, buf
);
904 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
906 BY_HANDLE_FILE_INFORMATION fdata
;
908 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
909 errno
= err_win_to_posix(GetLastError());
917 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
918 buf
->st_size
= fdata
.nFileSizeLow
|
919 (((off_t
)fdata
.nFileSizeHigh
)<<32);
920 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
921 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
922 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
923 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
927 int mingw_lstat(const char *file_name
, struct stat
*buf
)
929 return do_stat_internal(0, file_name
, buf
);
931 int mingw_stat(const char *file_name
, struct stat
*buf
)
933 return do_stat_internal(1, file_name
, buf
);
936 int mingw_fstat(int fd
, struct stat
*buf
)
938 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
939 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
943 return get_file_info_by_handle(fh
, buf
);
947 /* initialize stat fields */
948 memset(buf
, 0, sizeof(*buf
));
951 if (type
== FILE_TYPE_CHAR
) {
952 buf
->st_mode
= _S_IFCHR
;
954 buf
->st_mode
= _S_IFIFO
;
955 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
956 buf
->st_size
= avail
;
966 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
968 long long winTime
= t
* 10000000LL + 116444736000000000LL;
969 ft
->dwLowDateTime
= winTime
;
970 ft
->dwHighDateTime
= winTime
>> 32;
973 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
978 wchar_t wfilename
[MAX_PATH
];
981 if (xutftowcs_path(wfilename
, file_name
) < 0)
984 /* must have write permission */
985 attrs
= GetFileAttributesW(wfilename
);
986 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
987 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
988 /* ignore errors here; open() will report them */
989 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
992 osfilehandle
= CreateFileW(wfilename
,
993 FILE_WRITE_ATTRIBUTES
,
994 0 /*FileShare.None*/,
997 (attrs
!= INVALID_FILE_ATTRIBUTES
&&
998 (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) ?
999 FILE_FLAG_BACKUP_SEMANTICS
: 0,
1001 if (osfilehandle
== INVALID_HANDLE_VALUE
) {
1002 errno
= err_win_to_posix(GetLastError());
1008 time_t_to_filetime(times
->modtime
, &mft
);
1009 time_t_to_filetime(times
->actime
, &aft
);
1011 GetSystemTimeAsFileTime(&mft
);
1015 if (!SetFileTime(osfilehandle
, NULL
, &aft
, &mft
)) {
1021 if (osfilehandle
!= INVALID_HANDLE_VALUE
)
1022 CloseHandle(osfilehandle
);
1025 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1026 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1027 /* ignore errors again */
1028 SetFileAttributesW(wfilename
, attrs
);
1034 size_t mingw_strftime(char *s
, size_t max
,
1035 const char *format
, const struct tm
*tm
)
1037 /* a pointer to the original strftime in case we can't find the UCRT version */
1038 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1040 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1041 const char *, const struct tm
*);
1043 if (INIT_PROC_ADDR(strftime
))
1044 ret
= strftime(s
, max
, format
, tm
);
1046 ret
= fallback(s
, max
, format
, tm
);
1048 if (!ret
&& errno
== EINVAL
)
1049 die("invalid strftime format: '%s'", format
);
1053 unsigned int sleep (unsigned int seconds
)
1055 Sleep(seconds
*1000);
1059 char *mingw_mktemp(char *template)
1061 wchar_t wtemplate
[MAX_PATH
];
1062 if (xutftowcs_path(wtemplate
, template) < 0)
1064 if (!_wmktemp(wtemplate
))
1066 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1071 int mkstemp(char *template)
1073 return git_mkstemp_mode(template, 0600);
1076 int gettimeofday(struct timeval
*tv
, void *tz
)
1081 GetSystemTimeAsFileTime(&ft
);
1082 hnsec
= filetime_to_hnsec(&ft
);
1083 tv
->tv_sec
= hnsec
/ 10000000;
1084 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1088 int pipe(int filedes
[2])
1092 /* this creates non-inheritable handles */
1093 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1094 errno
= err_win_to_posix(GetLastError());
1097 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1098 if (filedes
[0] < 0) {
1103 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1104 if (filedes
[1] < 0) {
1113 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1115 if (gmtime_s(result
, timep
) == 0)
1120 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1122 if (localtime_s(result
, timep
) == 0)
1128 char *mingw_getcwd(char *pointer
, int len
)
1130 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1131 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1133 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1134 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1137 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1138 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1139 HANDLE hnd
= CreateFileW(cwd
, 0,
1140 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1141 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1142 if (hnd
== INVALID_HANDLE_VALUE
)
1144 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1146 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1148 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1152 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1154 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1158 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1160 convert_slashes(pointer
);
1165 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1166 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1168 static const char *quote_arg_msvc(const char *arg
)
1170 /* count chars to quote */
1172 int force_quotes
= 0;
1174 const char *p
= arg
;
1175 if (!*p
) force_quotes
= 1;
1177 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1181 else if (*p
== '\\') {
1183 while (*p
== '\\') {
1188 if (*p
== '"' || !*p
)
1195 if (!force_quotes
&& n
== 0)
1198 /* insert \ where necessary */
1199 d
= q
= xmalloc(st_add3(len
, n
, 3));
1204 else if (*arg
== '\\') {
1206 while (*arg
== '\\') {
1210 if (*arg
== '"' || !*arg
) {
1213 /* don't escape the surrounding end quote */
1228 static const char *quote_arg_msys2(const char *arg
)
1230 struct strbuf buf
= STRBUF_INIT
;
1231 const char *p2
= arg
, *p
;
1233 for (p
= arg
; *p
; p
++) {
1234 int ws
= isspace(*p
);
1235 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1236 *p
!= '?' && *p
!= '*' && *p
!= '~')
1239 strbuf_addch(&buf
, '"');
1241 strbuf_add(&buf
, p2
, p
- p2
);
1242 if (*p
== '\\' || *p
== '"')
1243 strbuf_addch(&buf
, '\\');
1248 strbuf_addch(&buf
, '"');
1252 strbuf_add(&buf
, p2
, p
- p2
);
1254 strbuf_addch(&buf
, '"');
1255 return strbuf_detach(&buf
, 0);
1258 static const char *parse_interpreter(const char *cmd
)
1260 static char buf
[100];
1264 /* don't even try a .exe */
1266 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1269 fd
= open(cmd
, O_RDONLY
);
1272 n
= read(fd
, buf
, sizeof(buf
)-1);
1274 if (n
< 4) /* at least '#!/x' and not error */
1277 if (buf
[0] != '#' || buf
[1] != '!')
1280 p
= buf
+ strcspn(buf
, "\r\n");
1285 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1288 if ((opt
= strchr(p
+1, ' ')))
1294 * exe_only means that we only want to detect .exe files, but not scripts
1295 * (which do not have an extension)
1297 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1298 int isexe
, int exe_only
)
1300 char path
[MAX_PATH
];
1301 wchar_t wpath
[MAX_PATH
];
1302 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1304 if (xutftowcs_path(wpath
, path
) < 0)
1307 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1308 return xstrdup(path
);
1309 wpath
[wcslen(wpath
)-4] = '\0';
1310 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1311 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1312 path
[strlen(path
)-4] = '\0';
1313 return xstrdup(path
);
1320 * Determines the absolute path of cmd using the split path in path.
1321 * If cmd contains a slash or backslash, no lookup is performed.
1323 static char *path_lookup(const char *cmd
, int exe_only
)
1327 int len
= strlen(cmd
);
1328 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1330 if (strpbrk(cmd
, "/\\"))
1331 return xstrdup(cmd
);
1333 path
= mingw_getenv("PATH");
1338 const char *sep
= strchrnul(path
, ';');
1339 int dirlen
= sep
- path
;
1341 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1350 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1352 while (*s
&& *s
!= c
)
1357 /* Compare only keys */
1358 static int wenvcmp(const void *a
, const void *b
)
1360 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1361 size_t p_len
, q_len
;
1364 p_len
= wcschrnul(p
, L
'=') - p
;
1365 q_len
= wcschrnul(q
, L
'=') - q
;
1367 /* If the length differs, include the shorter key's NUL */
1370 else if (p_len
> q_len
)
1373 return _wcsnicmp(p
, q
, p_len
);
1377 * Build an environment block combining the inherited environment
1378 * merged with the given list of settings.
1380 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1381 * Values of the form "KEY" in deltaenv delete inherited values.
1383 * Multiple entries in deltaenv for the same key are explicitly allowed.
1385 * We return a contiguous block of UNICODE strings with a final trailing
1388 static wchar_t *make_environment_block(char **deltaenv
)
1390 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1391 size_t wlen
, s
, delta_size
, size
;
1393 wchar_t **array
= NULL
;
1394 size_t alloc
= 0, nr
= 0, i
;
1396 size
= 1; /* for extra NUL at the end */
1398 /* If there is no deltaenv to apply, simply return a copy. */
1399 if (!deltaenv
|| !*deltaenv
) {
1400 for (p
= wenv
; p
&& *p
; ) {
1401 size_t s
= wcslen(p
) + 1;
1406 DUP_ARRAY(result
, wenv
, size
);
1407 FreeEnvironmentStringsW(wenv
);
1412 * If there is a deltaenv, let's accumulate all keys into `array`,
1413 * sort them using the stable git_stable_qsort() and then copy,
1414 * skipping duplicate keys
1416 for (p
= wenv
; p
&& *p
; ) {
1417 ALLOC_GROW(array
, nr
+ 1, alloc
);
1424 /* (over-)assess size needed for wchar version of deltaenv */
1425 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1426 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1427 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1429 /* convert the deltaenv, appending to array */
1430 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1431 ALLOC_GROW(array
, nr
+ 1, alloc
);
1432 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1437 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1438 ALLOC_ARRAY(result
, size
+ delta_size
);
1440 for (p
= result
, i
= 0; i
< nr
; i
++) {
1441 /* Skip any duplicate keys; last one wins */
1442 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1445 /* Skip "to delete" entry */
1446 if (!wcschr(array
[i
], L
'='))
1449 size
= wcslen(array
[i
]) + 1;
1450 COPY_ARRAY(p
, array
[i
], size
);
1457 FreeEnvironmentStringsW(wenv
);
1461 static void do_unset_environment_variables(void)
1464 char *p
= unset_environment_variables
;
1471 char *comma
= strchr(p
, ',');
1483 struct pinfo_t
*next
;
1487 static struct pinfo_t
*pinfo
= NULL
;
1488 CRITICAL_SECTION pinfo_cs
;
1490 /* Used to match and chomp off path components */
1491 static inline int match_last_path_component(const char *path
, size_t *len
,
1492 const char *component
)
1494 size_t component_len
= strlen(component
);
1495 if (*len
< component_len
+ 1 ||
1496 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1497 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1499 *len
-= component_len
+ 1;
1500 /* chomp off repeated dir separators */
1501 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1506 static int is_msys2_sh(const char *cmd
)
1511 if (!strcmp(cmd
, "sh")) {
1512 static int ret
= -1;
1518 p
= path_lookup(cmd
, 0);
1522 size_t len
= strlen(p
);
1524 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1525 match_last_path_component(p
, &len
, "bin") &&
1526 match_last_path_component(p
, &len
, "usr");
1532 if (ends_with(cmd
, "\\sh.exe")) {
1536 sh
= path_lookup("sh", 0);
1538 return !fspathcmp(cmd
, sh
);
1544 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1546 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1548 static int restrict_handle_inheritance
= -1;
1550 PROCESS_INFORMATION pi
;
1551 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1552 HANDLE stdhandles
[3];
1553 DWORD stdhandles_count
= 0;
1556 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1557 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1560 const char *(*quote_arg
)(const char *arg
) =
1561 is_msys2_sh(cmd
? cmd
: *argv
) ?
1562 quote_arg_msys2
: quote_arg_msvc
;
1563 const char *strace_env
;
1565 /* Make sure to override previous errors, if any */
1568 if (restrict_handle_inheritance
< 0)
1569 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1571 * The following code to restrict which handles are inherited seems
1572 * to work properly only on Windows 7 and later, so let's disable it
1573 * on Windows Vista and 2008.
1575 if (restrict_handle_inheritance
< 0)
1576 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1578 do_unset_environment_variables();
1580 /* Determine whether or not we are associated to a console */
1581 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1582 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1583 FILE_ATTRIBUTE_NORMAL
, NULL
);
1584 if (cons
== INVALID_HANDLE_VALUE
) {
1585 /* There is no console associated with this process.
1586 * Since the child is a console process, Windows
1587 * would normally create a console window. But
1588 * since we'll be redirecting std streams, we do
1589 * not need the console.
1590 * It is necessary to use DETACHED_PROCESS
1591 * instead of CREATE_NO_WINDOW to make ssh
1592 * recognize that it has no console.
1594 flags
|= DETACHED_PROCESS
;
1596 /* There is already a console. If we specified
1597 * DETACHED_PROCESS here, too, Windows would
1598 * disassociate the child from the console.
1599 * The same is true for CREATE_NO_WINDOW.
1604 memset(&si
, 0, sizeof(si
));
1605 si
.StartupInfo
.cb
= sizeof(si
);
1606 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1607 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1608 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1610 /* The list of handles cannot contain duplicates */
1611 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1612 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1613 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1614 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1615 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1616 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1617 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1618 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1619 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1620 if (stdhandles_count
)
1621 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1623 if (*argv
&& !strcmp(cmd
, *argv
))
1625 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1627 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1630 /* concatenate argv, quoting args as we go */
1631 strbuf_init(&args
, 0);
1633 char *quoted
= (char *)quote_arg(cmd
);
1634 strbuf_addstr(&args
, quoted
);
1638 for (; *argv
; argv
++) {
1639 char *quoted
= (char *)quote_arg(*argv
);
1641 strbuf_addch(&args
, ' ');
1642 strbuf_addstr(&args
, quoted
);
1643 if (quoted
!= *argv
)
1647 strace_env
= getenv("GIT_STRACE_COMMANDS");
1649 char *p
= path_lookup("strace.exe", 1);
1651 return error("strace not found!");
1652 if (xutftowcs_path(wcmd
, p
) < 0) {
1657 if (!strcmp("1", strace_env
) ||
1658 !strcasecmp("yes", strace_env
) ||
1659 !strcasecmp("true", strace_env
))
1660 strbuf_insert(&args
, 0, "strace ", 7);
1662 const char *quoted
= quote_arg(strace_env
);
1663 struct strbuf buf
= STRBUF_INIT
;
1664 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1665 if (quoted
!= strace_env
)
1666 free((char *)quoted
);
1667 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1668 strbuf_release(&buf
);
1672 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1673 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1674 strbuf_release(&args
);
1676 wenvblk
= make_environment_block(deltaenv
);
1678 memset(&pi
, 0, sizeof(pi
));
1679 if (restrict_handle_inheritance
&& stdhandles_count
&&
1680 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1681 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1682 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1683 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1684 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1685 UpdateProcThreadAttribute(attr_list
, 0,
1686 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1688 stdhandles_count
* sizeof(HANDLE
),
1690 si
.lpAttributeList
= attr_list
;
1691 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1694 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1695 stdhandles_count
? TRUE
: FALSE
,
1696 flags
, wenvblk
, dir
? wdir
: NULL
,
1697 &si
.StartupInfo
, &pi
);
1700 * On Windows 2008 R2, it seems that specifying certain types of handles
1701 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1702 * error. Rather than playing finicky and fragile games, let's just try
1703 * to detect this situation and simply try again without restricting any
1704 * handle inheritance. This is still better than failing to create
1707 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1708 DWORD err
= GetLastError();
1709 struct strbuf buf
= STRBUF_INIT
;
1711 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1713 * On Windows 7 and earlier, handles on pipes and character
1714 * devices are inherited automatically, and cannot be
1715 * specified in the thread handle list. Rather than trying
1716 * to catch each and every corner case (and running the
1717 * chance of *still* forgetting a few), let's just fall
1718 * back to creating the process without trying to limit the
1719 * handle inheritance.
1721 !(err
== ERROR_INVALID_PARAMETER
&&
1722 GetVersion() >> 16 < 9200) &&
1723 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1727 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1729 for (i
= 0; i
< stdhandles_count
; i
++) {
1730 HANDLE h
= stdhandles
[i
];
1731 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1732 "handle info (%d) %lx\n", i
, h
,
1734 GetHandleInformation(h
, &fl
),
1737 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1738 "at\nhttps://github.com/git-for-windows/"
1739 "git/issues/new\n\n"
1740 "To suppress this warning, please set "
1741 "the environment variable\n\n"
1742 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1745 restrict_handle_inheritance
= 0;
1746 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1747 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1748 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1749 &si
.StartupInfo
, &pi
);
1751 errno
= err_win_to_posix(GetLastError());
1752 if (ret
&& buf
.len
) {
1753 warning("failed to restrict file handles (%ld)\n\n%s",
1756 strbuf_release(&buf
);
1758 errno
= err_win_to_posix(GetLastError());
1760 if (si
.lpAttributeList
)
1761 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1763 HeapFree(GetProcessHeap(), 0, attr_list
);
1771 CloseHandle(pi
.hThread
);
1774 * The process ID is the human-readable identifier of the process
1775 * that we want to present in log and error messages. The handle
1776 * is not useful for this purpose. But we cannot close it, either,
1777 * because it is not possible to turn a process ID into a process
1778 * handle after the process terminated.
1779 * Keep the handle in a list for waitpid.
1781 EnterCriticalSection(&pinfo_cs
);
1783 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1784 info
->pid
= pi
.dwProcessId
;
1785 info
->proc
= pi
.hProcess
;
1789 LeaveCriticalSection(&pinfo_cs
);
1791 return (pid_t
)pi
.dwProcessId
;
1794 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1796 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1799 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1801 int fhin
, int fhout
, int fherr
)
1804 char *prog
= path_lookup(cmd
, 0);
1811 const char *interpr
= parse_interpreter(prog
);
1814 const char *argv0
= argv
[0];
1815 char *iprog
= path_lookup(interpr
, 1);
1822 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1823 fhin
, fhout
, fherr
);
1829 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1830 fhin
, fhout
, fherr
);
1836 static int try_shell_exec(const char *cmd
, char *const *argv
)
1838 const char *interpr
= parse_interpreter(cmd
);
1844 prog
= path_lookup(interpr
, 1);
1849 while (argv
[argc
]) argc
++;
1850 ALLOC_ARRAY(argv2
, argc
+ 1);
1851 argv2
[0] = (char *)cmd
; /* full path to the script file */
1852 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1853 exec_id
= trace2_exec(prog
, (const char **)argv2
);
1854 pid
= mingw_spawnv(prog
, (const char **)argv2
, 1);
1857 if (waitpid(pid
, &status
, 0) < 0)
1859 trace2_exec_result(exec_id
, status
);
1862 trace2_exec_result(exec_id
, -1);
1863 pid
= 1; /* indicate that we tried but failed */
1870 int mingw_execv(const char *cmd
, char *const *argv
)
1872 /* check if git_command is a shell script */
1873 if (!try_shell_exec(cmd
, argv
)) {
1877 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1878 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1880 trace2_exec_result(exec_id
, -1);
1883 if (waitpid(pid
, &status
, 0) < 0)
1885 trace2_exec_result(exec_id
, status
);
1891 int mingw_execvp(const char *cmd
, char *const *argv
)
1893 char *prog
= path_lookup(cmd
, 0);
1896 mingw_execv(prog
, argv
);
1904 int mingw_kill(pid_t pid
, int sig
)
1906 if (pid
> 0 && sig
== SIGTERM
) {
1907 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1909 if (TerminateProcess(h
, -1)) {
1914 errno
= err_win_to_posix(GetLastError());
1917 } else if (pid
> 0 && sig
== 0) {
1918 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1930 * UTF-8 versions of getenv(), putenv() and unsetenv().
1931 * Internally, they use the CRT's stock UNICODE routines
1932 * to avoid data loss.
1934 char *mingw_getenv(const char *name
)
1936 #define GETENV_MAX_RETAIN 64
1937 static char *values
[GETENV_MAX_RETAIN
];
1938 static int value_counter
;
1939 int len_key
, len_value
;
1942 wchar_t w_value
[32768];
1944 if (!name
|| !*name
)
1947 len_key
= strlen(name
) + 1;
1948 /* We cannot use xcalloc() here because that uses getenv() itself */
1949 w_key
= calloc(len_key
, sizeof(wchar_t));
1951 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1952 xutftowcs(w_key
, name
, len_key
);
1953 /* GetEnvironmentVariableW() only sets the last error upon failure */
1954 SetLastError(ERROR_SUCCESS
);
1955 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1956 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1962 len_value
= len_value
* 3 + 1;
1963 /* We cannot use xcalloc() here because that uses getenv() itself */
1964 value
= calloc(len_value
, sizeof(char));
1966 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1967 xwcstoutf(value
, w_value
, len_value
);
1970 * We return `value` which is an allocated value and the caller is NOT
1971 * expecting to have to free it, so we keep a round-robin array,
1972 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1974 free(values
[value_counter
]);
1975 values
[value_counter
++] = value
;
1976 if (value_counter
>= ARRAY_SIZE(values
))
1982 int mingw_putenv(const char *namevalue
)
1985 wchar_t *wide
, *equal
;
1988 if (!namevalue
|| !*namevalue
)
1991 size
= strlen(namevalue
) * 2 + 1;
1992 wide
= calloc(size
, sizeof(wchar_t));
1994 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1995 xutftowcs(wide
, namevalue
, size
);
1996 equal
= wcschr(wide
, L
'=');
1998 result
= SetEnvironmentVariableW(wide
, NULL
);
2001 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
2006 errno
= err_win_to_posix(GetLastError());
2008 return result
? 0 : -1;
2011 static void ensure_socket_initialization(void)
2014 static int initialized
= 0;
2019 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2020 die("unable to initialize winsock subsystem, error %d",
2023 atexit((void(*)(void)) WSACleanup
);
2028 int mingw_gethostname(char *name
, int namelen
)
2030 ensure_socket_initialization();
2031 return gethostname(name
, namelen
);
2034 #undef gethostbyname
2035 struct hostent
*mingw_gethostbyname(const char *host
)
2037 ensure_socket_initialization();
2038 return gethostbyname(host
);
2042 int mingw_getaddrinfo(const char *node
, const char *service
,
2043 const struct addrinfo
*hints
, struct addrinfo
**res
)
2045 ensure_socket_initialization();
2046 return getaddrinfo(node
, service
, hints
, res
);
2049 int mingw_socket(int domain
, int type
, int protocol
)
2054 ensure_socket_initialization();
2055 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2056 if (s
== INVALID_SOCKET
) {
2058 * WSAGetLastError() values are regular BSD error codes
2059 * biased by WSABASEERR.
2060 * However, strerror() does not know about networking
2061 * specific errors, which are values beginning at 38 or so.
2062 * Therefore, we choose to leave the biased error code
2063 * in errno so that _if_ someone looks up the code somewhere,
2064 * then it is at least the number that are usually listed.
2066 errno
= WSAGetLastError();
2069 /* convert into a file descriptor */
2070 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2072 return error("unable to make a socket file descriptor: %s",
2079 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2081 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2082 return connect(s
, sa
, sz
);
2086 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2088 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2089 return bind(s
, sa
, sz
);
2093 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2095 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2096 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2100 int mingw_shutdown(int sockfd
, int how
)
2102 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2103 return shutdown(s
, how
);
2107 int mingw_listen(int sockfd
, int backlog
)
2109 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2110 return listen(s
, backlog
);
2114 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2118 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2119 SOCKET s2
= accept(s1
, sa
, sz
);
2121 /* convert into a file descriptor */
2122 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2125 return error("unable to make a socket file descriptor: %s",
2132 int mingw_rename(const char *pold
, const char *pnew
)
2136 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2137 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2141 * Try native rename() first to get errno right.
2142 * It is based on MoveFile(), which cannot overwrite existing files.
2144 if (!_wrename(wpold
, wpnew
))
2146 if (errno
!= EEXIST
)
2149 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2151 /* TODO: translate more errors */
2152 gle
= GetLastError();
2153 if (gle
== ERROR_ACCESS_DENIED
&&
2154 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2155 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2156 DWORD attrsold
= GetFileAttributesW(wpold
);
2157 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2158 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2160 else if (!_wrmdir(wpnew
))
2164 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2165 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2166 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2168 gle
= GetLastError();
2169 /* revert file attributes on failure */
2170 SetFileAttributesW(wpnew
, attrs
);
2173 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2175 * We assume that some other process had the source or
2176 * destination file open at the wrong moment and retry.
2177 * In order to give the other process a higher chance to
2178 * complete its operation, we give up our time slice now.
2179 * If we have to retry again, we do sleep a bit.
2181 Sleep(delay
[tries
]);
2185 if (gle
== ERROR_ACCESS_DENIED
&&
2186 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2187 "Should I try again?", pold
, pnew
))
2195 * Note that this doesn't return the actual pagesize, but
2196 * the allocation granularity. If future Windows specific git code
2197 * needs the real getpagesize function, we need to find another solution.
2199 int mingw_getpagesize(void)
2203 return si
.dwAllocationGranularity
;
2206 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2207 enum EXTENDED_NAME_FORMAT
{
2209 NameUserPrincipal
= 8
2212 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2214 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2215 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2216 static wchar_t wbuffer
[1024];
2219 if (!INIT_PROC_ADDR(GetUserNameExW
))
2222 len
= ARRAY_SIZE(wbuffer
);
2223 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2224 char *converted
= xmalloc((len
*= 3));
2225 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2233 char *mingw_query_user_email(void)
2235 return get_extended_user_info(NameUserPrincipal
);
2238 struct passwd
*getpwuid(int uid
)
2240 static unsigned initialized
;
2241 static char user_name
[100];
2242 static struct passwd
*p
;
2249 len
= ARRAY_SIZE(buf
);
2250 if (!GetUserNameW(buf
, &len
)) {
2255 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2260 p
= xmalloc(sizeof(*p
));
2261 p
->pw_name
= user_name
;
2262 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2264 p
->pw_gecos
= "unknown";
2271 static HANDLE timer_event
;
2272 static HANDLE timer_thread
;
2273 static int timer_interval
;
2274 static int one_shot
;
2275 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2277 /* The timer works like this:
2278 * The thread, ticktack(), is a trivial routine that most of the time
2279 * only waits to receive the signal to terminate. The main thread tells
2280 * the thread to terminate by setting the timer_event to the signalled
2282 * But ticktack() interrupts the wait state after the timer's interval
2283 * length to call the signal handler.
2286 static unsigned __stdcall
ticktack(void *dummy
)
2288 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2289 mingw_raise(SIGALRM
);
2296 static int start_timer_thread(void)
2298 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2300 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2302 return errno
= ENOMEM
,
2303 error("cannot start timer thread");
2305 return errno
= ENOMEM
,
2306 error("cannot allocate resources for timer");
2310 static void stop_timer_thread(void)
2313 SetEvent(timer_event
); /* tell thread to terminate */
2315 int rc
= WaitForSingleObject(timer_thread
, 10000);
2316 if (rc
== WAIT_TIMEOUT
)
2317 error("timer thread did not terminate timely");
2318 else if (rc
!= WAIT_OBJECT_0
)
2319 error("waiting for timer thread failed: %lu",
2321 CloseHandle(timer_thread
);
2324 CloseHandle(timer_event
);
2326 timer_thread
= NULL
;
2329 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2331 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2334 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2336 static const struct timeval zero
;
2337 static int atexit_done
;
2340 return errno
= EINVAL
,
2341 error("setitimer param 3 != NULL not implemented");
2342 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2343 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2344 return errno
= EINVAL
,
2345 error("setitimer: it_interval must be zero or eq it_value");
2348 stop_timer_thread();
2350 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2351 is_timeval_eq(&in
->it_interval
, &zero
))
2354 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2355 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2357 atexit(stop_timer_thread
);
2360 return start_timer_thread();
2363 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2366 return errno
= EINVAL
,
2367 error("sigaction only implemented for SIGALRM");
2369 return errno
= EINVAL
,
2370 error("sigaction: param 3 != NULL not implemented");
2372 timer_fn
= in
->sa_handler
;
2377 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2389 sigint_fn
= handler
;
2393 return signal(sig
, handler
);
2400 int mingw_raise(int sig
)
2404 if (timer_fn
== SIG_DFL
) {
2405 if (isatty(STDERR_FILENO
))
2406 fputs("Alarm clock\n", stderr
);
2407 exit(128 + SIGALRM
);
2408 } else if (timer_fn
!= SIG_IGN
)
2413 if (sigint_fn
== SIG_DFL
)
2415 else if (sigint_fn
!= SIG_IGN
)
2419 #if defined(_MSC_VER)
2426 case SIGABRT_COMPAT
:
2428 * The <signal.h> header in the MS C Runtime defines 8 signals
2429 * as being supported on the platform. Anything else causes an
2430 * "Invalid signal or error" (which in DEBUG builds causes the
2431 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2432 * already know will fail.
2449 int link(const char *oldpath
, const char *newpath
)
2451 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2452 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2453 xutftowcs_path(wnewpath
, newpath
) < 0)
2456 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2457 errno
= err_win_to_posix(GetLastError());
2463 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2465 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2472 if (pid
> 0 && options
& WNOHANG
) {
2473 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2477 options
&= ~WNOHANG
;
2481 struct pinfo_t
**ppinfo
;
2482 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2488 GetExitCodeProcess(h
, (LPDWORD
)status
);
2490 EnterCriticalSection(&pinfo_cs
);
2494 struct pinfo_t
*info
= *ppinfo
;
2495 if (info
->pid
== pid
) {
2496 CloseHandle(info
->proc
);
2497 *ppinfo
= info
->next
;
2501 ppinfo
= &info
->next
;
2504 LeaveCriticalSection(&pinfo_cs
);
2515 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2517 int upos
= 0, wpos
= 0;
2518 const unsigned char *utf
= (const unsigned char*) utfs
;
2519 if (!utf
|| !wcs
|| wcslen
< 1) {
2523 /* reserve space for \0 */
2528 while (upos
< utflen
) {
2529 int c
= utf
[upos
++] & 0xff;
2530 if (utflen
== INT_MAX
&& c
== 0)
2533 if (wpos
>= wcslen
) {
2542 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2543 (utf
[upos
] & 0xc0) == 0x80) {
2545 c
= ((c
& 0x1f) << 6);
2546 c
|= (utf
[upos
++] & 0x3f);
2548 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2549 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2550 (utf
[upos
] & 0xc0) == 0x80 &&
2551 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2553 c
= ((c
& 0x0f) << 12);
2554 c
|= ((utf
[upos
++] & 0x3f) << 6);
2555 c
|= (utf
[upos
++] & 0x3f);
2557 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2558 wpos
+ 1 < wcslen
&&
2559 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2560 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2561 (utf
[upos
] & 0xc0) == 0x80 &&
2562 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2563 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2564 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2565 c
= ((c
& 0x07) << 18);
2566 c
|= ((utf
[upos
++] & 0x3f) << 12);
2567 c
|= ((utf
[upos
++] & 0x3f) << 6);
2568 c
|= (utf
[upos
++] & 0x3f);
2570 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2571 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2572 } else if (c
>= 0xa0) {
2573 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2576 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2577 static const char *hex
= "0123456789abcdef";
2578 wcs
[wpos
++] = hex
[c
>> 4];
2580 wcs
[wpos
++] = hex
[c
& 0x0f];
2587 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2589 if (!wcs
|| !utf
|| utflen
< 1) {
2593 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2600 static void setup_windows_environment(void)
2602 char *tmp
= getenv("TMPDIR");
2604 /* on Windows it is TMP and TEMP */
2606 if (!(tmp
= getenv("TMP")))
2607 tmp
= getenv("TEMP");
2609 setenv("TMPDIR", tmp
, 1);
2610 tmp
= getenv("TMPDIR");
2616 * Convert all dir separators to forward slashes,
2617 * to help shell commands called from the Git
2618 * executable (by not mistaking the dir separators
2619 * for escape characters).
2621 convert_slashes(tmp
);
2624 /* simulate TERM to enable auto-color (see color.c) */
2625 if (!getenv("TERM"))
2626 setenv("TERM", "cygwin", 1);
2628 /* calculate HOME if not set */
2629 if (!getenv("HOME")) {
2631 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2632 * location, thus also check if the path exists (i.e. is not
2635 if ((tmp
= getenv("HOMEDRIVE"))) {
2636 struct strbuf buf
= STRBUF_INIT
;
2637 strbuf_addstr(&buf
, tmp
);
2638 if ((tmp
= getenv("HOMEPATH"))) {
2639 strbuf_addstr(&buf
, tmp
);
2640 if (is_directory(buf
.buf
))
2641 setenv("HOME", buf
.buf
, 1);
2643 tmp
= NULL
; /* use $USERPROFILE */
2645 strbuf_release(&buf
);
2647 /* use $USERPROFILE if the home share is not available */
2648 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2649 setenv("HOME", tmp
, 1);
2653 static PSID
get_current_user_sid(void)
2659 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2662 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2663 TOKEN_USER
*info
= xmalloc((size_t)len
);
2664 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2665 len
= GetLengthSid(info
->User
.Sid
);
2666 result
= xmalloc(len
);
2667 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2668 error(_("failed to copy SID (%ld)"),
2670 FREE_AND_NULL(result
);
2673 FREE_AND_NULL(info
);
2680 static int acls_supported(const char *path
)
2682 size_t offset
= offset_1st_component(path
);
2683 WCHAR wroot
[MAX_PATH
];
2684 DWORD file_system_flags
;
2687 xutftowcsn(wroot
, path
, MAX_PATH
, offset
) > 0 &&
2688 GetVolumeInformationW(wroot
, NULL
, 0, NULL
, NULL
,
2689 &file_system_flags
, NULL
, 0))
2690 return !!(file_system_flags
& FILE_PERSISTENT_ACLS
);
2695 int is_path_owned_by_current_sid(const char *path
, struct strbuf
*report
)
2697 WCHAR wpath
[MAX_PATH
];
2699 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2702 static wchar_t home
[MAX_PATH
];
2706 if (xutftowcs_path(wpath
, path
) < 0)
2710 * On Windows, the home directory is owned by the administrator, but for
2711 * all practical purposes, it belongs to the user. Do pretend that it is
2712 * owned by the user.
2715 DWORD size
= ARRAY_SIZE(home
);
2716 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2717 if (!len
|| len
> size
)
2718 wcscpy(home
, L
"::N/A::");
2720 if (!wcsicmp(wpath
, home
))
2723 /* Get the owner SID */
2724 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2725 OWNER_SECURITY_INFORMATION
|
2726 DACL_SECURITY_INFORMATION
,
2727 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2729 if (err
!= ERROR_SUCCESS
)
2730 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2731 else if (sid
&& IsValidSid(sid
)) {
2732 /* Now, verify that the SID matches the current user's */
2733 static PSID current_user_sid
;
2736 if (!current_user_sid
)
2737 current_user_sid
= get_current_user_sid();
2739 if (current_user_sid
&&
2740 IsValidSid(current_user_sid
) &&
2741 EqualSid(sid
, current_user_sid
))
2743 else if (IsWellKnownSid(sid
, WinBuiltinAdministratorsSid
) &&
2744 CheckTokenMembership(NULL
, sid
, &is_member
) &&
2747 * If owned by the Administrators group, and the
2748 * current user is an administrator, we consider that
2753 IsWellKnownSid(sid
, WinWorldSid
) &&
2754 !acls_supported(path
)) {
2756 * On FAT32 volumes, ownership is not actually recorded.
2758 strbuf_addf(report
, "'%s' is on a file system that does "
2759 "not record ownership\n", path
);
2760 } else if (report
) {
2761 LPSTR str1
, str2
, to_free1
= NULL
, to_free2
= NULL
;
2763 if (ConvertSidToStringSidA(sid
, &str1
))
2766 str1
= "(inconvertible)";
2768 if (!current_user_sid
)
2770 else if (!IsValidSid(current_user_sid
))
2772 else if (ConvertSidToStringSidA(current_user_sid
, &str2
))
2775 str2
= "(inconvertible)";
2777 "'%s' is owned by:\n"
2778 "\t'%s'\nbut the current user is:\n"
2779 "\t'%s'\n", path
, str1
, str2
);
2780 LocalFree(to_free1
);
2781 LocalFree(to_free2
);
2786 * We can release the security descriptor struct only now because `sid`
2787 * actually points into this struct.
2790 LocalFree(descriptor
);
2795 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2797 const char *p
= path
;
2798 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2803 skip_dos_drive_prefix((char **)&path
);
2810 case '/': case '\\':
2811 /* cannot end in ` ` or `.`, except for `.` and `..` */
2812 if (preceding_space_or_period
&&
2813 (i
!= periods
|| periods
> 2))
2818 i
= periods
= preceding_space_or_period
= 0;
2822 case 'a': case 'A': /* AUX */
2823 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2824 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2825 not_a_reserved_name
:
2831 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2832 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2833 goto not_a_reserved_name
;
2835 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2837 if (c
< '1' || c
> '9')
2838 goto not_a_reserved_name
;
2839 } else if (c
== 'n' || c
== 'N') { /* CON */
2841 if ((c
== 'i' || c
== 'I') &&
2842 ((c
= path
[i
+ 2]) == 'n' ||
2845 i
+= 3; /* CONIN$ */
2846 else if ((c
== 'o' || c
== 'O') &&
2847 ((c
= path
[i
+ 2]) == 'u' ||
2849 ((c
= path
[i
+ 3]) == 't' ||
2852 i
+= 4; /* CONOUT$ */
2854 goto not_a_reserved_name
;
2856 case 'l': case 'L': /* LPT<N> */
2857 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2858 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2859 !isdigit(path
[++i
]))
2860 goto not_a_reserved_name
;
2862 case 'n': case 'N': /* NUL */
2863 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2864 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2865 (allow_literal_nul
&&
2866 !path
[i
+ 1] && p
== path
))
2867 goto not_a_reserved_name
;
2869 case 'p': case 'P': /* PRN */
2870 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2871 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2872 goto not_a_reserved_name
;
2879 * So far, this looks like a reserved name. Let's see
2880 * whether it actually is one: trailing spaces, a file
2881 * extension, or an NTFS Alternate Data Stream do not
2882 * matter, the name is still reserved if any of those
2883 * follow immediately after the actual name.
2886 if (path
[i
] == ' ') {
2887 preceding_space_or_period
= 1;
2888 while (path
[++i
] == ' ')
2889 ; /* skip all spaces */
2893 if (c
&& c
!= '.' && c
!= ':' && !is_xplatform_dir_sep(c
))
2894 goto not_a_reserved_name
;
2896 /* contains reserved name */
2902 preceding_space_or_period
= 1;
2905 case ':': /* DOS drive prefix was already skipped */
2906 case '<': case '>': case '"': case '|': case '?': case '*':
2907 /* illegal character */
2910 if (c
> '\0' && c
< '\x20')
2911 /* illegal character */
2914 preceding_space_or_period
= 0;
2919 #if !defined(_MSC_VER)
2921 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2922 * mingw startup code, see init.c in mingw runtime).
2927 static NORETURN
void die_startup(void)
2929 fputs("fatal: not enough memory for initialization", stderr
);
2933 static void *malloc_startup(size_t size
)
2935 void *result
= malloc(size
);
2941 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2943 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2944 return memcpy(malloc_startup(len
), buffer
, len
);
2947 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2948 DWORD desired_access
, DWORD flags
)
2950 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2951 wchar_t buf
[MAX_PATH
];
2952 DWORD max
= ARRAY_SIZE(buf
);
2954 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2956 if (!ret
|| ret
>= max
)
2959 /* make sure this does not leak into child processes */
2960 SetEnvironmentVariableW(key
, NULL
);
2961 if (!wcscmp(buf
, L
"off")) {
2963 handle
= GetStdHandle(std_id
);
2964 if (handle
!= INVALID_HANDLE_VALUE
)
2965 CloseHandle(handle
);
2968 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2969 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2970 if (handle
== INVALID_HANDLE_VALUE
) {
2972 handle
= GetStdHandle(std_id
);
2973 if (handle
!= INVALID_HANDLE_VALUE
)
2974 CloseHandle(handle
);
2976 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2977 SetStdHandle(std_id
, handle
);
2979 /* do *not* close the new_fd: that would close stdout */
2983 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2985 if (handle
!= INVALID_HANDLE_VALUE
) {
2986 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2987 SetStdHandle(std_id
, handle
);
2993 static void maybe_redirect_std_handles(void)
2995 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2996 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2997 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2998 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2999 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
3000 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
3010 * We implement wmain() and compile with -municode, which would
3011 * normally ignore main(), but we call the latter from the former
3012 * so that we can handle non-ASCII command-line parameters
3015 * To be more compatible with the core git code, we convert
3016 * argv into UTF8 and pass them directly to main().
3018 int wmain(int argc
, const wchar_t **wargv
)
3020 int i
, maxlen
, exit_status
;
3021 char *buffer
, **save
;
3024 trace2_initialize_clock();
3028 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
3031 #ifdef USE_MSVC_CRTDBG
3032 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
3036 maybe_redirect_std_handles();
3038 /* determine size of argv and environ conversion buffer */
3039 maxlen
= wcslen(wargv
[0]);
3040 for (i
= 1; i
< argc
; i
++)
3041 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
3043 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3044 maxlen
= 3 * maxlen
+ 1;
3045 buffer
= malloc_startup(maxlen
);
3048 * Create a UTF-8 version of w_argv. Also create a "save" copy
3049 * to remember all the string pointers because parse_options()
3050 * will remove claimed items from the argv that we pass down.
3052 ALLOC_ARRAY(argv
, argc
+ 1);
3053 ALLOC_ARRAY(save
, argc
+ 1);
3054 for (i
= 0; i
< argc
; i
++)
3055 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
3056 argv
[i
] = save
[i
] = NULL
;
3059 /* fix Windows specific environment settings */
3060 setup_windows_environment();
3062 unset_environment_variables
= xstrdup("PERL5LIB");
3064 /* initialize critical section for waitpid pinfo_t list */
3065 InitializeCriticalSection(&pinfo_cs
);
3067 /* set up default file mode and file modes for stdin/out/err */
3069 _setmode(_fileno(stdin
), _O_BINARY
);
3070 _setmode(_fileno(stdout
), _O_BINARY
);
3071 _setmode(_fileno(stderr
), _O_BINARY
);
3073 /* initialize Unicode console */
3076 /* invoke the real main() using our utf8 version of argv. */
3077 exit_status
= main(argc
, argv
);
3079 for (i
= 0; i
< argc
; i
++)
3087 int uname(struct utsname
*buf
)
3089 unsigned v
= (unsigned)GetVersion();
3090 memset(buf
, 0, sizeof(*buf
));
3091 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3092 xsnprintf(buf
->release
, sizeof(buf
->release
),
3093 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3094 /* assuming NT variants only.. */
3095 xsnprintf(buf
->version
, sizeof(buf
->version
),
3096 "%u", (v
>> 16) & 0x7fff);