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")) {
259 return config_error_nonbool(var
);
260 free(unset_environment_variables
);
261 unset_environment_variables
= xstrdup(value
);
265 if (!strcmp(var
, "core.restrictinheritedhandles")) {
266 if (value
&& !strcasecmp(value
, "auto"))
267 core_restrict_inherited_handles
= -1;
269 core_restrict_inherited_handles
=
270 git_config_bool(var
, value
);
277 /* Normalizes NT paths as returned by some low-level APIs. */
278 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
281 /* fix absolute path prefixes */
282 if (wbuf
[0] == '\\') {
283 /* strip NT namespace prefixes */
284 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
285 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
287 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
289 /* replace remaining '...UNC\' with '\\' */
290 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
295 /* convert backslashes to slashes */
296 for (i
= 0; wbuf
[i
]; i
++)
302 int mingw_unlink(const char *pathname
)
305 wchar_t wpathname
[MAX_PATH
];
306 if (xutftowcs_path(wpathname
, pathname
) < 0)
309 if (DeleteFileW(wpathname
))
312 /* read-only files cannot be removed */
313 _wchmod(wpathname
, 0666);
314 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
315 if (!is_file_in_use_error(GetLastError()))
318 * We assume that some other process had the source or
319 * destination file open at the wrong moment and retry.
320 * In order to give the other process a higher chance to
321 * complete its operation, we give up our time slice now.
322 * If we have to retry again, we do sleep a bit.
327 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
328 ask_yes_no_if_possible("Unlink of file '%s' failed. "
329 "Should I try again?", pathname
))
330 ret
= _wunlink(wpathname
);
334 static int is_dir_empty(const wchar_t *wpath
)
336 WIN32_FIND_DATAW findbuf
;
338 wchar_t wbuf
[MAX_PATH
+ 2];
340 wcscat(wbuf
, L
"\\*");
341 handle
= FindFirstFileW(wbuf
, &findbuf
);
342 if (handle
== INVALID_HANDLE_VALUE
)
343 return GetLastError() == ERROR_NO_MORE_FILES
;
345 while (!wcscmp(findbuf
.cFileName
, L
".") ||
346 !wcscmp(findbuf
.cFileName
, L
".."))
347 if (!FindNextFileW(handle
, &findbuf
)) {
348 DWORD err
= GetLastError();
350 return err
== ERROR_NO_MORE_FILES
;
356 int mingw_rmdir(const char *pathname
)
359 wchar_t wpathname
[MAX_PATH
];
363 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
364 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
365 * symbolic link (if it points to a directory).
367 * This behavior breaks the assumption of e.g. `remove_path()` which
368 * upon successful deletion of a file will attempt to remove its parent
369 * directories recursively until failure (which usually happens when
370 * the directory is not empty).
372 * Therefore, before calling `_wrmdir()`, we first check if the path is
373 * a symbolic link. If it is, we exit and return the same error as
374 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
376 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
381 if (xutftowcs_path(wpathname
, pathname
) < 0)
384 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
385 if (!is_file_in_use_error(GetLastError()))
386 errno
= err_win_to_posix(GetLastError());
389 if (!is_dir_empty(wpathname
)) {
394 * We assume that some other process had the source or
395 * destination file open at the wrong moment and retry.
396 * In order to give the other process a higher chance to
397 * complete its operation, we give up our time slice now.
398 * If we have to retry again, we do sleep a bit.
403 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
404 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
405 "Should I try again?", pathname
))
406 ret
= _wrmdir(wpathname
);
408 invalidate_lstat_cache();
412 static inline int needs_hiding(const char *path
)
414 const char *basename
;
416 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
419 /* We cannot use basename(), as it would remove trailing slashes */
420 win32_skip_dos_drive_prefix((char **)&path
);
424 for (basename
= path
; *path
; path
++)
425 if (is_dir_sep(*path
)) {
428 } while (is_dir_sep(*path
));
429 /* ignore trailing slashes */
436 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
437 return *basename
== '.';
439 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
440 return !strncasecmp(".git", basename
, 4) &&
441 (!basename
[4] || is_dir_sep(basename
[4]));
444 static int set_hidden_flag(const wchar_t *path
, int set
)
446 DWORD original
= GetFileAttributesW(path
), modified
;
448 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
450 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
451 if (original
== modified
|| SetFileAttributesW(path
, modified
))
453 errno
= err_win_to_posix(GetLastError());
457 int mingw_mkdir(const char *path
, int mode
)
460 wchar_t wpath
[MAX_PATH
];
462 if (!is_valid_win32_path(path
, 0)) {
467 if (xutftowcs_path(wpath
, path
) < 0)
469 ret
= _wmkdir(wpath
);
470 if (!ret
&& needs_hiding(path
))
471 return set_hidden_flag(wpath
, 1);
476 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
477 * is documented in [1] as opening a writable file handle in append mode.
478 * (It is believed that) this is atomic since it is maintained by the
479 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
481 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
483 * This trick does not appear to work for named pipes. Instead it creates
484 * a named pipe client handle that cannot be written to. Callers should
485 * just use the regular _wopen() for them. (And since client handle gets
486 * bound to a unique server handle, it isn't really an issue.)
488 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
492 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
494 /* only these flags are supported */
495 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
496 return errno
= ENOSYS
, -1;
499 * FILE_SHARE_WRITE is required to permit child processes
500 * to append to the file.
502 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
503 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
504 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
505 if (handle
== INVALID_HANDLE_VALUE
) {
506 DWORD err
= GetLastError();
509 * Some network storage solutions (e.g. Isilon) might return
510 * ERROR_INVALID_PARAMETER instead of expected error
511 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
512 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
514 if (err
== ERROR_INVALID_PARAMETER
)
515 err
= ERROR_PATH_NOT_FOUND
;
517 errno
= err_win_to_posix(err
);
522 * No O_APPEND here, because the CRT uses it only to reset the
523 * file pointer to EOF before each write(); but that is not
524 * necessary (and may lead to races) for a file created with
527 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
534 * Does the pathname map to the local named pipe filesystem?
535 * That is, does it have a "//./pipe/" prefix?
537 static int is_local_named_pipe_path(const char *filename
)
539 return (is_dir_sep(filename
[0]) &&
540 is_dir_sep(filename
[1]) &&
541 filename
[2] == '.' &&
542 is_dir_sep(filename
[3]) &&
543 !strncasecmp(filename
+4, "pipe", 4) &&
544 is_dir_sep(filename
[8]) &&
548 int mingw_open (const char *filename
, int oflags
, ...)
550 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
553 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
554 wchar_t wfilename
[MAX_PATH
];
557 va_start(args
, oflags
);
558 mode
= va_arg(args
, int);
561 if (!is_valid_win32_path(filename
, !create
)) {
562 errno
= create
? EINVAL
: ENOENT
;
566 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
567 open_fn
= mingw_open_append
;
571 if (filename
&& !strcmp(filename
, "/dev/null"))
572 wcscpy(wfilename
, L
"nul");
573 else if (xutftowcs_path(wfilename
, filename
) < 0)
576 fd
= open_fn(wfilename
, oflags
, mode
);
578 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
579 DWORD attrs
= GetFileAttributesW(wfilename
);
580 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
583 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
585 * Internally, _wopen() uses the CreateFile() API which errors
586 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
587 * specified and an already existing file's attributes do not
588 * match *exactly*. As there is no mode or flag we can set that
589 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
590 * again *without* the O_CREAT flag (that corresponds to the
591 * CREATE_ALWAYS flag of CreateFile()).
593 if (fd
< 0 && errno
== EACCES
)
594 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
595 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
596 warning("could not mark '%s' as hidden.", filename
);
601 static BOOL WINAPI
ctrl_ignore(DWORD type
)
607 int mingw_fgetc(FILE *stream
)
610 if (!isatty(_fileno(stream
)))
611 return fgetc(stream
);
613 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
616 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
619 /* Ctrl+C was pressed, simulate SIGINT and retry */
622 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
627 FILE *mingw_fopen (const char *filename
, const char *otype
)
629 int hide
= needs_hiding(filename
);
631 wchar_t wfilename
[MAX_PATH
], wotype
[4];
632 if (filename
&& !strcmp(filename
, "/dev/null"))
633 wcscpy(wfilename
, L
"nul");
634 else if (!is_valid_win32_path(filename
, 1)) {
635 int create
= otype
&& strchr(otype
, 'w');
636 errno
= create
? EINVAL
: ENOENT
;
638 } else if (xutftowcs_path(wfilename
, filename
) < 0)
641 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
644 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
645 error("could not unhide %s", filename
);
648 file
= _wfopen(wfilename
, wotype
);
649 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
651 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
652 warning("could not mark '%s' as hidden.", filename
);
656 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
658 int hide
= needs_hiding(filename
);
660 wchar_t wfilename
[MAX_PATH
], wotype
[4];
661 if (filename
&& !strcmp(filename
, "/dev/null"))
662 wcscpy(wfilename
, L
"nul");
663 else if (!is_valid_win32_path(filename
, 1)) {
664 int create
= otype
&& strchr(otype
, 'w');
665 errno
= create
? EINVAL
: ENOENT
;
667 } else if (xutftowcs_path(wfilename
, filename
) < 0)
670 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
673 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
674 error("could not unhide %s", filename
);
677 file
= _wfreopen(wfilename
, wotype
, stream
);
678 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
679 warning("could not mark '%s' as hidden.", filename
);
684 int mingw_fflush(FILE *stream
)
686 int ret
= fflush(stream
);
689 * write() is used behind the scenes of stdio output functions.
690 * Since git code does not check for errors after each stdio write
691 * operation, it can happen that write() is called by a later
692 * stdio function even if an earlier write() call failed. In the
693 * case of a pipe whose readable end was closed, only the first
694 * call to write() reports EPIPE on Windows. Subsequent write()
695 * calls report EINVAL. It is impossible to notice whether this
696 * fflush invocation triggered such a case, therefore, we have to
697 * catch all EINVAL errors whole-sale.
699 if (ret
&& errno
== EINVAL
)
706 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
708 ssize_t result
= write(fd
, buf
, len
);
710 if (result
< 0 && errno
== EINVAL
&& buf
) {
711 /* check if fd is a pipe */
712 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
713 if (GetFileType(h
) == FILE_TYPE_PIPE
)
722 int mingw_access(const char *filename
, int mode
)
724 wchar_t wfilename
[MAX_PATH
];
725 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
727 if (xutftowcs_path(wfilename
, filename
) < 0)
729 /* X_OK is not supported by the MSVCRT version */
730 return _waccess(wfilename
, mode
& ~X_OK
);
733 int mingw_chdir(const char *dirname
)
735 wchar_t wdirname
[MAX_PATH
];
736 if (xutftowcs_path(wdirname
, dirname
) < 0)
738 return _wchdir(wdirname
);
741 int mingw_chmod(const char *filename
, int mode
)
743 wchar_t wfilename
[MAX_PATH
];
744 if (xutftowcs_path(wfilename
, filename
) < 0)
746 return _wchmod(wfilename
, mode
);
750 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
751 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
753 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
755 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
756 /* Windows to Unix Epoch conversion */
757 return winTime
- 116444736000000000LL;
760 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
762 long long hnsec
= filetime_to_hnsec(ft
);
763 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
764 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
768 * Verifies that safe_create_leading_directories() would succeed.
770 static int has_valid_directory_prefix(wchar_t *wfilename
)
772 int n
= wcslen(wfilename
);
775 wchar_t c
= wfilename
[--n
];
781 wfilename
[n
] = L
'\0';
782 attributes
= GetFileAttributesW(wfilename
);
785 (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
))
787 if (attributes
== INVALID_FILE_ATTRIBUTES
)
788 switch (GetLastError()) {
789 case ERROR_PATH_NOT_FOUND
:
791 case ERROR_FILE_NOT_FOUND
:
792 /* This implies parent directory exists. */
800 /* We keep the do_lstat code in a separate function to avoid recursion.
801 * When a path ends with a slash, the stat will fail with ENOENT. In
802 * this case, we strip the trailing slashes and stat again.
804 * If follow is true then act like stat() and report on the link
805 * target. Otherwise report on the link itself.
807 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
809 WIN32_FILE_ATTRIBUTE_DATA fdata
;
810 wchar_t wfilename
[MAX_PATH
];
811 if (xutftowcs_path(wfilename
, file_name
) < 0)
814 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
819 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
820 buf
->st_size
= fdata
.nFileSizeLow
|
821 (((off_t
)fdata
.nFileSizeHigh
)<<32);
822 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
823 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
824 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
825 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
826 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
827 WIN32_FIND_DATAW findbuf
;
828 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
829 if (handle
!= INVALID_HANDLE_VALUE
) {
830 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
831 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
833 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
834 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
836 buf
->st_mode
= S_IFLNK
;
838 buf
->st_mode
|= S_IREAD
;
839 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
840 buf
->st_mode
|= S_IWRITE
;
847 switch (GetLastError()) {
848 case ERROR_ACCESS_DENIED
:
849 case ERROR_SHARING_VIOLATION
:
850 case ERROR_LOCK_VIOLATION
:
851 case ERROR_SHARING_BUFFER_EXCEEDED
:
854 case ERROR_BUFFER_OVERFLOW
:
855 errno
= ENAMETOOLONG
;
857 case ERROR_NOT_ENOUGH_MEMORY
:
860 case ERROR_PATH_NOT_FOUND
:
861 if (!has_valid_directory_prefix(wfilename
)) {
873 /* We provide our own lstat/fstat functions, since the provided
874 * lstat/fstat functions are so slow. These stat functions are
875 * tailored for Git's usage (read: fast), and are not meant to be
876 * complete. Note that Git stat()s are redirected to mingw_lstat()
877 * too, since Windows doesn't really handle symlinks that well.
879 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
882 char alt_name
[PATH_MAX
];
884 if (!do_lstat(follow
, file_name
, buf
))
887 /* if file_name ended in a '/', Windows returned ENOENT;
888 * try again without trailing slashes
893 namelen
= strlen(file_name
);
894 if (namelen
&& file_name
[namelen
-1] != '/')
896 while (namelen
&& file_name
[namelen
-1] == '/')
898 if (!namelen
|| namelen
>= PATH_MAX
)
901 memcpy(alt_name
, file_name
, namelen
);
902 alt_name
[namelen
] = 0;
903 return do_lstat(follow
, alt_name
, buf
);
906 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
908 BY_HANDLE_FILE_INFORMATION fdata
;
910 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
911 errno
= err_win_to_posix(GetLastError());
919 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
920 buf
->st_size
= fdata
.nFileSizeLow
|
921 (((off_t
)fdata
.nFileSizeHigh
)<<32);
922 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
923 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
924 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
925 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
929 int mingw_lstat(const char *file_name
, struct stat
*buf
)
931 return do_stat_internal(0, file_name
, buf
);
933 int mingw_stat(const char *file_name
, struct stat
*buf
)
935 return do_stat_internal(1, file_name
, buf
);
938 int mingw_fstat(int fd
, struct stat
*buf
)
940 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
941 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
945 return get_file_info_by_handle(fh
, buf
);
949 /* initialize stat fields */
950 memset(buf
, 0, sizeof(*buf
));
953 if (type
== FILE_TYPE_CHAR
) {
954 buf
->st_mode
= _S_IFCHR
;
956 buf
->st_mode
= _S_IFIFO
;
957 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
958 buf
->st_size
= avail
;
968 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
970 long long winTime
= t
* 10000000LL + 116444736000000000LL;
971 ft
->dwLowDateTime
= winTime
;
972 ft
->dwHighDateTime
= winTime
>> 32;
975 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
980 wchar_t wfilename
[MAX_PATH
];
983 if (xutftowcs_path(wfilename
, file_name
) < 0)
986 /* must have write permission */
987 attrs
= GetFileAttributesW(wfilename
);
988 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
989 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
990 /* ignore errors here; open() will report them */
991 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
994 osfilehandle
= CreateFileW(wfilename
,
995 FILE_WRITE_ATTRIBUTES
,
996 0 /*FileShare.None*/,
999 (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1000 (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) ?
1001 FILE_FLAG_BACKUP_SEMANTICS
: 0,
1003 if (osfilehandle
== INVALID_HANDLE_VALUE
) {
1004 errno
= err_win_to_posix(GetLastError());
1010 time_t_to_filetime(times
->modtime
, &mft
);
1011 time_t_to_filetime(times
->actime
, &aft
);
1013 GetSystemTimeAsFileTime(&mft
);
1017 if (!SetFileTime(osfilehandle
, NULL
, &aft
, &mft
)) {
1023 if (osfilehandle
!= INVALID_HANDLE_VALUE
)
1024 CloseHandle(osfilehandle
);
1027 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1028 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1029 /* ignore errors again */
1030 SetFileAttributesW(wfilename
, attrs
);
1036 size_t mingw_strftime(char *s
, size_t max
,
1037 const char *format
, const struct tm
*tm
)
1039 /* a pointer to the original strftime in case we can't find the UCRT version */
1040 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1042 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1043 const char *, const struct tm
*);
1045 if (INIT_PROC_ADDR(strftime
))
1046 ret
= strftime(s
, max
, format
, tm
);
1048 ret
= fallback(s
, max
, format
, tm
);
1050 if (!ret
&& errno
== EINVAL
)
1051 die("invalid strftime format: '%s'", format
);
1055 unsigned int sleep (unsigned int seconds
)
1057 Sleep(seconds
*1000);
1061 char *mingw_mktemp(char *template)
1063 wchar_t wtemplate
[MAX_PATH
];
1064 if (xutftowcs_path(wtemplate
, template) < 0)
1066 if (!_wmktemp(wtemplate
))
1068 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1073 int mkstemp(char *template)
1075 return git_mkstemp_mode(template, 0600);
1078 int gettimeofday(struct timeval
*tv
, void *tz
)
1083 GetSystemTimeAsFileTime(&ft
);
1084 hnsec
= filetime_to_hnsec(&ft
);
1085 tv
->tv_sec
= hnsec
/ 10000000;
1086 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1090 int pipe(int filedes
[2])
1094 /* this creates non-inheritable handles */
1095 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1096 errno
= err_win_to_posix(GetLastError());
1099 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1100 if (filedes
[0] < 0) {
1105 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1106 if (filedes
[1] < 0) {
1115 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1117 if (gmtime_s(result
, timep
) == 0)
1122 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1124 if (localtime_s(result
, timep
) == 0)
1130 char *mingw_getcwd(char *pointer
, int len
)
1132 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1133 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1135 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1136 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1139 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1140 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1141 HANDLE hnd
= CreateFileW(cwd
, 0,
1142 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1143 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1144 if (hnd
== INVALID_HANDLE_VALUE
)
1146 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1148 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1150 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1154 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1156 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1160 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1162 convert_slashes(pointer
);
1167 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1168 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1170 static const char *quote_arg_msvc(const char *arg
)
1172 /* count chars to quote */
1174 int force_quotes
= 0;
1176 const char *p
= arg
;
1177 if (!*p
) force_quotes
= 1;
1179 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1183 else if (*p
== '\\') {
1185 while (*p
== '\\') {
1190 if (*p
== '"' || !*p
)
1197 if (!force_quotes
&& n
== 0)
1200 /* insert \ where necessary */
1201 d
= q
= xmalloc(st_add3(len
, n
, 3));
1206 else if (*arg
== '\\') {
1208 while (*arg
== '\\') {
1212 if (*arg
== '"' || !*arg
) {
1215 /* don't escape the surrounding end quote */
1230 static const char *quote_arg_msys2(const char *arg
)
1232 struct strbuf buf
= STRBUF_INIT
;
1233 const char *p2
= arg
, *p
;
1235 for (p
= arg
; *p
; p
++) {
1236 int ws
= isspace(*p
);
1237 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1238 *p
!= '?' && *p
!= '*' && *p
!= '~')
1241 strbuf_addch(&buf
, '"');
1243 strbuf_add(&buf
, p2
, p
- p2
);
1244 if (*p
== '\\' || *p
== '"')
1245 strbuf_addch(&buf
, '\\');
1250 strbuf_addch(&buf
, '"');
1254 strbuf_add(&buf
, p2
, p
- p2
);
1256 strbuf_addch(&buf
, '"');
1257 return strbuf_detach(&buf
, 0);
1260 static const char *parse_interpreter(const char *cmd
)
1262 static char buf
[100];
1266 /* don't even try a .exe */
1268 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1271 fd
= open(cmd
, O_RDONLY
);
1274 n
= read(fd
, buf
, sizeof(buf
)-1);
1276 if (n
< 4) /* at least '#!/x' and not error */
1279 if (buf
[0] != '#' || buf
[1] != '!')
1282 p
= buf
+ strcspn(buf
, "\r\n");
1287 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1290 if ((opt
= strchr(p
+1, ' ')))
1296 * exe_only means that we only want to detect .exe files, but not scripts
1297 * (which do not have an extension)
1299 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1300 int isexe
, int exe_only
)
1302 char path
[MAX_PATH
];
1303 wchar_t wpath
[MAX_PATH
];
1304 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1306 if (xutftowcs_path(wpath
, path
) < 0)
1309 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1310 return xstrdup(path
);
1311 wpath
[wcslen(wpath
)-4] = '\0';
1312 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1313 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1314 path
[strlen(path
)-4] = '\0';
1315 return xstrdup(path
);
1322 * Determines the absolute path of cmd using the split path in path.
1323 * If cmd contains a slash or backslash, no lookup is performed.
1325 static char *path_lookup(const char *cmd
, int exe_only
)
1329 int len
= strlen(cmd
);
1330 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1332 if (strpbrk(cmd
, "/\\"))
1333 return xstrdup(cmd
);
1335 path
= mingw_getenv("PATH");
1340 const char *sep
= strchrnul(path
, ';');
1341 int dirlen
= sep
- path
;
1343 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1352 char *mingw_locate_in_PATH(const char *cmd
)
1354 return path_lookup(cmd
, 0);
1357 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1359 while (*s
&& *s
!= c
)
1364 /* Compare only keys */
1365 static int wenvcmp(const void *a
, const void *b
)
1367 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1368 size_t p_len
, q_len
;
1371 p_len
= wcschrnul(p
, L
'=') - p
;
1372 q_len
= wcschrnul(q
, L
'=') - q
;
1374 /* If the length differs, include the shorter key's NUL */
1377 else if (p_len
> q_len
)
1380 return _wcsnicmp(p
, q
, p_len
);
1384 * Build an environment block combining the inherited environment
1385 * merged with the given list of settings.
1387 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1388 * Values of the form "KEY" in deltaenv delete inherited values.
1390 * Multiple entries in deltaenv for the same key are explicitly allowed.
1392 * We return a contiguous block of UNICODE strings with a final trailing
1395 static wchar_t *make_environment_block(char **deltaenv
)
1397 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1398 size_t wlen
, s
, delta_size
, size
;
1400 wchar_t **array
= NULL
;
1401 size_t alloc
= 0, nr
= 0, i
;
1403 size
= 1; /* for extra NUL at the end */
1405 /* If there is no deltaenv to apply, simply return a copy. */
1406 if (!deltaenv
|| !*deltaenv
) {
1407 for (p
= wenv
; p
&& *p
; ) {
1408 size_t s
= wcslen(p
) + 1;
1413 DUP_ARRAY(result
, wenv
, size
);
1414 FreeEnvironmentStringsW(wenv
);
1419 * If there is a deltaenv, let's accumulate all keys into `array`,
1420 * sort them using the stable git_stable_qsort() and then copy,
1421 * skipping duplicate keys
1423 for (p
= wenv
; p
&& *p
; ) {
1424 ALLOC_GROW(array
, nr
+ 1, alloc
);
1431 /* (over-)assess size needed for wchar version of deltaenv */
1432 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1433 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1434 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1436 /* convert the deltaenv, appending to array */
1437 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1438 ALLOC_GROW(array
, nr
+ 1, alloc
);
1439 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1444 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1445 ALLOC_ARRAY(result
, size
+ delta_size
);
1447 for (p
= result
, i
= 0; i
< nr
; i
++) {
1448 /* Skip any duplicate keys; last one wins */
1449 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1452 /* Skip "to delete" entry */
1453 if (!wcschr(array
[i
], L
'='))
1456 size
= wcslen(array
[i
]) + 1;
1457 COPY_ARRAY(p
, array
[i
], size
);
1464 FreeEnvironmentStringsW(wenv
);
1468 static void do_unset_environment_variables(void)
1471 char *p
= unset_environment_variables
;
1478 char *comma
= strchr(p
, ',');
1490 struct pinfo_t
*next
;
1494 static struct pinfo_t
*pinfo
= NULL
;
1495 CRITICAL_SECTION pinfo_cs
;
1497 /* Used to match and chomp off path components */
1498 static inline int match_last_path_component(const char *path
, size_t *len
,
1499 const char *component
)
1501 size_t component_len
= strlen(component
);
1502 if (*len
< component_len
+ 1 ||
1503 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1504 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1506 *len
-= component_len
+ 1;
1507 /* chomp off repeated dir separators */
1508 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1513 static int is_msys2_sh(const char *cmd
)
1518 if (!strcmp(cmd
, "sh")) {
1519 static int ret
= -1;
1525 p
= path_lookup(cmd
, 0);
1529 size_t len
= strlen(p
);
1531 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1532 match_last_path_component(p
, &len
, "bin") &&
1533 match_last_path_component(p
, &len
, "usr");
1539 if (ends_with(cmd
, "\\sh.exe")) {
1543 sh
= path_lookup("sh", 0);
1545 return !fspathcmp(cmd
, sh
);
1551 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1553 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1555 static int restrict_handle_inheritance
= -1;
1557 PROCESS_INFORMATION pi
;
1558 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1559 HANDLE stdhandles
[3];
1560 DWORD stdhandles_count
= 0;
1563 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1564 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1567 const char *(*quote_arg
)(const char *arg
) =
1568 is_msys2_sh(cmd
? cmd
: *argv
) ?
1569 quote_arg_msys2
: quote_arg_msvc
;
1570 const char *strace_env
;
1572 /* Make sure to override previous errors, if any */
1575 if (restrict_handle_inheritance
< 0)
1576 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1578 * The following code to restrict which handles are inherited seems
1579 * to work properly only on Windows 7 and later, so let's disable it
1580 * on Windows Vista and 2008.
1582 if (restrict_handle_inheritance
< 0)
1583 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1585 do_unset_environment_variables();
1587 /* Determine whether or not we are associated to a console */
1588 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1589 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1590 FILE_ATTRIBUTE_NORMAL
, NULL
);
1591 if (cons
== INVALID_HANDLE_VALUE
) {
1592 /* There is no console associated with this process.
1593 * Since the child is a console process, Windows
1594 * would normally create a console window. But
1595 * since we'll be redirecting std streams, we do
1596 * not need the console.
1597 * It is necessary to use DETACHED_PROCESS
1598 * instead of CREATE_NO_WINDOW to make ssh
1599 * recognize that it has no console.
1601 flags
|= DETACHED_PROCESS
;
1603 /* There is already a console. If we specified
1604 * DETACHED_PROCESS here, too, Windows would
1605 * disassociate the child from the console.
1606 * The same is true for CREATE_NO_WINDOW.
1611 memset(&si
, 0, sizeof(si
));
1612 si
.StartupInfo
.cb
= sizeof(si
);
1613 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1614 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1615 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1617 /* The list of handles cannot contain duplicates */
1618 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1619 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1620 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1621 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1622 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1623 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1624 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1625 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1626 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1627 if (stdhandles_count
)
1628 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1630 if (*argv
&& !strcmp(cmd
, *argv
))
1632 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1634 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1637 /* concatenate argv, quoting args as we go */
1638 strbuf_init(&args
, 0);
1640 char *quoted
= (char *)quote_arg(cmd
);
1641 strbuf_addstr(&args
, quoted
);
1645 for (; *argv
; argv
++) {
1646 char *quoted
= (char *)quote_arg(*argv
);
1648 strbuf_addch(&args
, ' ');
1649 strbuf_addstr(&args
, quoted
);
1650 if (quoted
!= *argv
)
1654 strace_env
= getenv("GIT_STRACE_COMMANDS");
1656 char *p
= path_lookup("strace.exe", 1);
1658 return error("strace not found!");
1659 if (xutftowcs_path(wcmd
, p
) < 0) {
1664 if (!strcmp("1", strace_env
) ||
1665 !strcasecmp("yes", strace_env
) ||
1666 !strcasecmp("true", strace_env
))
1667 strbuf_insert(&args
, 0, "strace ", 7);
1669 const char *quoted
= quote_arg(strace_env
);
1670 struct strbuf buf
= STRBUF_INIT
;
1671 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1672 if (quoted
!= strace_env
)
1673 free((char *)quoted
);
1674 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1675 strbuf_release(&buf
);
1679 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1680 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1681 strbuf_release(&args
);
1683 wenvblk
= make_environment_block(deltaenv
);
1685 memset(&pi
, 0, sizeof(pi
));
1686 if (restrict_handle_inheritance
&& stdhandles_count
&&
1687 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1688 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1689 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1690 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1691 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1692 UpdateProcThreadAttribute(attr_list
, 0,
1693 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1695 stdhandles_count
* sizeof(HANDLE
),
1697 si
.lpAttributeList
= attr_list
;
1698 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1701 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1702 stdhandles_count
? TRUE
: FALSE
,
1703 flags
, wenvblk
, dir
? wdir
: NULL
,
1704 &si
.StartupInfo
, &pi
);
1707 * On Windows 2008 R2, it seems that specifying certain types of handles
1708 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1709 * error. Rather than playing finicky and fragile games, let's just try
1710 * to detect this situation and simply try again without restricting any
1711 * handle inheritance. This is still better than failing to create
1714 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1715 DWORD err
= GetLastError();
1716 struct strbuf buf
= STRBUF_INIT
;
1718 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1720 * On Windows 7 and earlier, handles on pipes and character
1721 * devices are inherited automatically, and cannot be
1722 * specified in the thread handle list. Rather than trying
1723 * to catch each and every corner case (and running the
1724 * chance of *still* forgetting a few), let's just fall
1725 * back to creating the process without trying to limit the
1726 * handle inheritance.
1728 !(err
== ERROR_INVALID_PARAMETER
&&
1729 GetVersion() >> 16 < 9200) &&
1730 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1734 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1736 for (i
= 0; i
< stdhandles_count
; i
++) {
1737 HANDLE h
= stdhandles
[i
];
1738 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1739 "handle info (%d) %lx\n", i
, h
,
1741 GetHandleInformation(h
, &fl
),
1744 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1745 "at\nhttps://github.com/git-for-windows/"
1746 "git/issues/new\n\n"
1747 "To suppress this warning, please set "
1748 "the environment variable\n\n"
1749 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1752 restrict_handle_inheritance
= 0;
1753 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1754 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1755 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1756 &si
.StartupInfo
, &pi
);
1758 errno
= err_win_to_posix(GetLastError());
1759 if (ret
&& buf
.len
) {
1760 warning("failed to restrict file handles (%ld)\n\n%s",
1763 strbuf_release(&buf
);
1765 errno
= err_win_to_posix(GetLastError());
1767 if (si
.lpAttributeList
)
1768 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1770 HeapFree(GetProcessHeap(), 0, attr_list
);
1778 CloseHandle(pi
.hThread
);
1781 * The process ID is the human-readable identifier of the process
1782 * that we want to present in log and error messages. The handle
1783 * is not useful for this purpose. But we cannot close it, either,
1784 * because it is not possible to turn a process ID into a process
1785 * handle after the process terminated.
1786 * Keep the handle in a list for waitpid.
1788 EnterCriticalSection(&pinfo_cs
);
1790 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1791 info
->pid
= pi
.dwProcessId
;
1792 info
->proc
= pi
.hProcess
;
1796 LeaveCriticalSection(&pinfo_cs
);
1798 return (pid_t
)pi
.dwProcessId
;
1801 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1803 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1806 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1808 int fhin
, int fhout
, int fherr
)
1811 char *prog
= path_lookup(cmd
, 0);
1818 const char *interpr
= parse_interpreter(prog
);
1821 const char *argv0
= argv
[0];
1822 char *iprog
= path_lookup(interpr
, 1);
1829 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1830 fhin
, fhout
, fherr
);
1836 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1837 fhin
, fhout
, fherr
);
1843 static int try_shell_exec(const char *cmd
, char *const *argv
)
1845 const char *interpr
= parse_interpreter(cmd
);
1851 prog
= path_lookup(interpr
, 1);
1856 while (argv
[argc
]) argc
++;
1857 ALLOC_ARRAY(argv2
, argc
+ 1);
1858 argv2
[0] = (char *)cmd
; /* full path to the script file */
1859 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1860 exec_id
= trace2_exec(prog
, (const char **)argv2
);
1861 pid
= mingw_spawnv(prog
, (const char **)argv2
, 1);
1864 if (waitpid(pid
, &status
, 0) < 0)
1866 trace2_exec_result(exec_id
, status
);
1869 trace2_exec_result(exec_id
, -1);
1870 pid
= 1; /* indicate that we tried but failed */
1877 int mingw_execv(const char *cmd
, char *const *argv
)
1879 /* check if git_command is a shell script */
1880 if (!try_shell_exec(cmd
, argv
)) {
1884 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1885 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1887 trace2_exec_result(exec_id
, -1);
1890 if (waitpid(pid
, &status
, 0) < 0)
1892 trace2_exec_result(exec_id
, status
);
1898 int mingw_execvp(const char *cmd
, char *const *argv
)
1900 char *prog
= path_lookup(cmd
, 0);
1903 mingw_execv(prog
, argv
);
1911 int mingw_kill(pid_t pid
, int sig
)
1913 if (pid
> 0 && sig
== SIGTERM
) {
1914 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1916 if (TerminateProcess(h
, -1)) {
1921 errno
= err_win_to_posix(GetLastError());
1924 } else if (pid
> 0 && sig
== 0) {
1925 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1937 * UTF-8 versions of getenv(), putenv() and unsetenv().
1938 * Internally, they use the CRT's stock UNICODE routines
1939 * to avoid data loss.
1941 char *mingw_getenv(const char *name
)
1943 #define GETENV_MAX_RETAIN 64
1944 static char *values
[GETENV_MAX_RETAIN
];
1945 static int value_counter
;
1946 int len_key
, len_value
;
1949 wchar_t w_value
[32768];
1951 if (!name
|| !*name
)
1954 len_key
= strlen(name
) + 1;
1955 /* We cannot use xcalloc() here because that uses getenv() itself */
1956 w_key
= calloc(len_key
, sizeof(wchar_t));
1958 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1959 xutftowcs(w_key
, name
, len_key
);
1960 /* GetEnvironmentVariableW() only sets the last error upon failure */
1961 SetLastError(ERROR_SUCCESS
);
1962 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1963 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1969 len_value
= len_value
* 3 + 1;
1970 /* We cannot use xcalloc() here because that uses getenv() itself */
1971 value
= calloc(len_value
, sizeof(char));
1973 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1974 xwcstoutf(value
, w_value
, len_value
);
1977 * We return `value` which is an allocated value and the caller is NOT
1978 * expecting to have to free it, so we keep a round-robin array,
1979 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1981 free(values
[value_counter
]);
1982 values
[value_counter
++] = value
;
1983 if (value_counter
>= ARRAY_SIZE(values
))
1989 int mingw_putenv(const char *namevalue
)
1992 wchar_t *wide
, *equal
;
1995 if (!namevalue
|| !*namevalue
)
1998 size
= strlen(namevalue
) * 2 + 1;
1999 wide
= calloc(size
, sizeof(wchar_t));
2001 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
2002 xutftowcs(wide
, namevalue
, size
);
2003 equal
= wcschr(wide
, L
'=');
2005 result
= SetEnvironmentVariableW(wide
, NULL
);
2008 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
2013 errno
= err_win_to_posix(GetLastError());
2015 return result
? 0 : -1;
2018 static void ensure_socket_initialization(void)
2021 static int initialized
= 0;
2026 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2027 die("unable to initialize winsock subsystem, error %d",
2030 atexit((void(*)(void)) WSACleanup
);
2035 int mingw_gethostname(char *name
, int namelen
)
2037 ensure_socket_initialization();
2038 return gethostname(name
, namelen
);
2041 #undef gethostbyname
2042 struct hostent
*mingw_gethostbyname(const char *host
)
2044 ensure_socket_initialization();
2045 return gethostbyname(host
);
2049 int mingw_getaddrinfo(const char *node
, const char *service
,
2050 const struct addrinfo
*hints
, struct addrinfo
**res
)
2052 ensure_socket_initialization();
2053 return getaddrinfo(node
, service
, hints
, res
);
2056 int mingw_socket(int domain
, int type
, int protocol
)
2061 ensure_socket_initialization();
2062 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2063 if (s
== INVALID_SOCKET
) {
2065 * WSAGetLastError() values are regular BSD error codes
2066 * biased by WSABASEERR.
2067 * However, strerror() does not know about networking
2068 * specific errors, which are values beginning at 38 or so.
2069 * Therefore, we choose to leave the biased error code
2070 * in errno so that _if_ someone looks up the code somewhere,
2071 * then it is at least the number that are usually listed.
2073 errno
= WSAGetLastError();
2076 /* convert into a file descriptor */
2077 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2079 return error("unable to make a socket file descriptor: %s",
2086 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2088 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2089 return connect(s
, sa
, sz
);
2093 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2095 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2096 return bind(s
, sa
, sz
);
2100 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2102 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2103 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2107 int mingw_shutdown(int sockfd
, int how
)
2109 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2110 return shutdown(s
, how
);
2114 int mingw_listen(int sockfd
, int backlog
)
2116 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2117 return listen(s
, backlog
);
2121 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2125 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2126 SOCKET s2
= accept(s1
, sa
, sz
);
2128 /* convert into a file descriptor */
2129 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2132 return error("unable to make a socket file descriptor: %s",
2139 int mingw_rename(const char *pold
, const char *pnew
)
2143 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2144 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2148 * Try native rename() first to get errno right.
2149 * It is based on MoveFile(), which cannot overwrite existing files.
2151 if (!_wrename(wpold
, wpnew
))
2153 if (errno
!= EEXIST
)
2156 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2158 /* TODO: translate more errors */
2159 gle
= GetLastError();
2160 if (gle
== ERROR_ACCESS_DENIED
&&
2161 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2162 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2163 DWORD attrsold
= GetFileAttributesW(wpold
);
2164 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2165 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2167 else if (!_wrmdir(wpnew
))
2171 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2172 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2173 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2175 gle
= GetLastError();
2176 /* revert file attributes on failure */
2177 SetFileAttributesW(wpnew
, attrs
);
2180 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2182 * We assume that some other process had the source or
2183 * destination file open at the wrong moment and retry.
2184 * In order to give the other process a higher chance to
2185 * complete its operation, we give up our time slice now.
2186 * If we have to retry again, we do sleep a bit.
2188 Sleep(delay
[tries
]);
2192 if (gle
== ERROR_ACCESS_DENIED
&&
2193 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2194 "Should I try again?", pold
, pnew
))
2202 * Note that this doesn't return the actual pagesize, but
2203 * the allocation granularity. If future Windows specific git code
2204 * needs the real getpagesize function, we need to find another solution.
2206 int mingw_getpagesize(void)
2210 return si
.dwAllocationGranularity
;
2213 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2214 enum EXTENDED_NAME_FORMAT
{
2216 NameUserPrincipal
= 8
2219 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2221 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2222 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2223 static wchar_t wbuffer
[1024];
2226 if (!INIT_PROC_ADDR(GetUserNameExW
))
2229 len
= ARRAY_SIZE(wbuffer
);
2230 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2231 char *converted
= xmalloc((len
*= 3));
2232 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2240 char *mingw_query_user_email(void)
2242 return get_extended_user_info(NameUserPrincipal
);
2245 struct passwd
*getpwuid(int uid
)
2247 static unsigned initialized
;
2248 static char user_name
[100];
2249 static struct passwd
*p
;
2256 len
= ARRAY_SIZE(buf
);
2257 if (!GetUserNameW(buf
, &len
)) {
2262 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2267 p
= xmalloc(sizeof(*p
));
2268 p
->pw_name
= user_name
;
2269 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2271 p
->pw_gecos
= "unknown";
2278 static HANDLE timer_event
;
2279 static HANDLE timer_thread
;
2280 static int timer_interval
;
2281 static int one_shot
;
2282 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2284 /* The timer works like this:
2285 * The thread, ticktack(), is a trivial routine that most of the time
2286 * only waits to receive the signal to terminate. The main thread tells
2287 * the thread to terminate by setting the timer_event to the signalled
2289 * But ticktack() interrupts the wait state after the timer's interval
2290 * length to call the signal handler.
2293 static unsigned __stdcall
ticktack(void *dummy
)
2295 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2296 mingw_raise(SIGALRM
);
2303 static int start_timer_thread(void)
2305 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2307 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2309 return errno
= ENOMEM
,
2310 error("cannot start timer thread");
2312 return errno
= ENOMEM
,
2313 error("cannot allocate resources for timer");
2317 static void stop_timer_thread(void)
2320 SetEvent(timer_event
); /* tell thread to terminate */
2322 int rc
= WaitForSingleObject(timer_thread
, 10000);
2323 if (rc
== WAIT_TIMEOUT
)
2324 error("timer thread did not terminate timely");
2325 else if (rc
!= WAIT_OBJECT_0
)
2326 error("waiting for timer thread failed: %lu",
2328 CloseHandle(timer_thread
);
2331 CloseHandle(timer_event
);
2333 timer_thread
= NULL
;
2336 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2338 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2341 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2343 static const struct timeval zero
;
2344 static int atexit_done
;
2347 return errno
= EINVAL
,
2348 error("setitimer param 3 != NULL not implemented");
2349 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2350 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2351 return errno
= EINVAL
,
2352 error("setitimer: it_interval must be zero or eq it_value");
2355 stop_timer_thread();
2357 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2358 is_timeval_eq(&in
->it_interval
, &zero
))
2361 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2362 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2364 atexit(stop_timer_thread
);
2367 return start_timer_thread();
2370 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2373 return errno
= EINVAL
,
2374 error("sigaction only implemented for SIGALRM");
2376 return errno
= EINVAL
,
2377 error("sigaction: param 3 != NULL not implemented");
2379 timer_fn
= in
->sa_handler
;
2384 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2396 sigint_fn
= handler
;
2400 return signal(sig
, handler
);
2407 int mingw_raise(int sig
)
2411 if (timer_fn
== SIG_DFL
) {
2412 if (isatty(STDERR_FILENO
))
2413 fputs("Alarm clock\n", stderr
);
2414 exit(128 + SIGALRM
);
2415 } else if (timer_fn
!= SIG_IGN
)
2420 if (sigint_fn
== SIG_DFL
)
2422 else if (sigint_fn
!= SIG_IGN
)
2426 #if defined(_MSC_VER)
2433 case SIGABRT_COMPAT
:
2435 * The <signal.h> header in the MS C Runtime defines 8 signals
2436 * as being supported on the platform. Anything else causes an
2437 * "Invalid signal or error" (which in DEBUG builds causes the
2438 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2439 * already know will fail.
2456 int link(const char *oldpath
, const char *newpath
)
2458 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2459 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2460 xutftowcs_path(wnewpath
, newpath
) < 0)
2463 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2464 errno
= err_win_to_posix(GetLastError());
2470 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2472 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2479 if (pid
> 0 && options
& WNOHANG
) {
2480 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2484 options
&= ~WNOHANG
;
2488 struct pinfo_t
**ppinfo
;
2489 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2495 GetExitCodeProcess(h
, (LPDWORD
)status
);
2497 EnterCriticalSection(&pinfo_cs
);
2501 struct pinfo_t
*info
= *ppinfo
;
2502 if (info
->pid
== pid
) {
2503 CloseHandle(info
->proc
);
2504 *ppinfo
= info
->next
;
2508 ppinfo
= &info
->next
;
2511 LeaveCriticalSection(&pinfo_cs
);
2522 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2524 int upos
= 0, wpos
= 0;
2525 const unsigned char *utf
= (const unsigned char*) utfs
;
2526 if (!utf
|| !wcs
|| wcslen
< 1) {
2530 /* reserve space for \0 */
2535 while (upos
< utflen
) {
2536 int c
= utf
[upos
++] & 0xff;
2537 if (utflen
== INT_MAX
&& c
== 0)
2540 if (wpos
>= wcslen
) {
2549 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2550 (utf
[upos
] & 0xc0) == 0x80) {
2552 c
= ((c
& 0x1f) << 6);
2553 c
|= (utf
[upos
++] & 0x3f);
2555 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2556 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2557 (utf
[upos
] & 0xc0) == 0x80 &&
2558 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2560 c
= ((c
& 0x0f) << 12);
2561 c
|= ((utf
[upos
++] & 0x3f) << 6);
2562 c
|= (utf
[upos
++] & 0x3f);
2564 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2565 wpos
+ 1 < wcslen
&&
2566 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2567 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2568 (utf
[upos
] & 0xc0) == 0x80 &&
2569 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2570 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2571 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2572 c
= ((c
& 0x07) << 18);
2573 c
|= ((utf
[upos
++] & 0x3f) << 12);
2574 c
|= ((utf
[upos
++] & 0x3f) << 6);
2575 c
|= (utf
[upos
++] & 0x3f);
2577 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2578 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2579 } else if (c
>= 0xa0) {
2580 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2583 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2584 static const char *hex
= "0123456789abcdef";
2585 wcs
[wpos
++] = hex
[c
>> 4];
2587 wcs
[wpos
++] = hex
[c
& 0x0f];
2594 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2596 if (!wcs
|| !utf
|| utflen
< 1) {
2600 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2607 static void setup_windows_environment(void)
2609 char *tmp
= getenv("TMPDIR");
2611 /* on Windows it is TMP and TEMP */
2613 if (!(tmp
= getenv("TMP")))
2614 tmp
= getenv("TEMP");
2616 setenv("TMPDIR", tmp
, 1);
2617 tmp
= getenv("TMPDIR");
2623 * Convert all dir separators to forward slashes,
2624 * to help shell commands called from the Git
2625 * executable (by not mistaking the dir separators
2626 * for escape characters).
2628 convert_slashes(tmp
);
2631 /* simulate TERM to enable auto-color (see color.c) */
2632 if (!getenv("TERM"))
2633 setenv("TERM", "cygwin", 1);
2635 /* calculate HOME if not set */
2636 if (!getenv("HOME")) {
2638 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2639 * location, thus also check if the path exists (i.e. is not
2642 if ((tmp
= getenv("HOMEDRIVE"))) {
2643 struct strbuf buf
= STRBUF_INIT
;
2644 strbuf_addstr(&buf
, tmp
);
2645 if ((tmp
= getenv("HOMEPATH"))) {
2646 strbuf_addstr(&buf
, tmp
);
2647 if (is_directory(buf
.buf
))
2648 setenv("HOME", buf
.buf
, 1);
2650 tmp
= NULL
; /* use $USERPROFILE */
2652 strbuf_release(&buf
);
2654 /* use $USERPROFILE if the home share is not available */
2655 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2656 setenv("HOME", tmp
, 1);
2660 static PSID
get_current_user_sid(void)
2666 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2669 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2670 TOKEN_USER
*info
= xmalloc((size_t)len
);
2671 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2672 len
= GetLengthSid(info
->User
.Sid
);
2673 result
= xmalloc(len
);
2674 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2675 error(_("failed to copy SID (%ld)"),
2677 FREE_AND_NULL(result
);
2680 FREE_AND_NULL(info
);
2687 static BOOL
user_sid_to_user_name(PSID sid
, LPSTR
*str
)
2689 SID_NAME_USE pe_use
;
2690 DWORD len_user
= 0, len_domain
= 0;
2691 BOOL translate_sid_to_user
;
2694 * returns only FALSE, because the string pointers are NULL
2696 LookupAccountSidA(NULL
, sid
, NULL
, &len_user
, NULL
, &len_domain
,
2699 * Alloc needed space of the strings
2701 ALLOC_ARRAY((*str
), (size_t)len_domain
+ (size_t)len_user
);
2702 translate_sid_to_user
= LookupAccountSidA(NULL
, sid
,
2703 (*str
) + len_domain
, &len_user
, *str
, &len_domain
, &pe_use
);
2704 if (!translate_sid_to_user
)
2705 FREE_AND_NULL(*str
);
2707 (*str
)[len_domain
] = '/';
2708 return translate_sid_to_user
;
2711 static int acls_supported(const char *path
)
2713 size_t offset
= offset_1st_component(path
);
2714 WCHAR wroot
[MAX_PATH
];
2715 DWORD file_system_flags
;
2718 xutftowcsn(wroot
, path
, MAX_PATH
, offset
) > 0 &&
2719 GetVolumeInformationW(wroot
, NULL
, 0, NULL
, NULL
,
2720 &file_system_flags
, NULL
, 0))
2721 return !!(file_system_flags
& FILE_PERSISTENT_ACLS
);
2726 int is_path_owned_by_current_sid(const char *path
, struct strbuf
*report
)
2728 WCHAR wpath
[MAX_PATH
];
2730 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2733 static wchar_t home
[MAX_PATH
];
2737 if (xutftowcs_path(wpath
, path
) < 0)
2741 * On Windows, the home directory is owned by the administrator, but for
2742 * all practical purposes, it belongs to the user. Do pretend that it is
2743 * owned by the user.
2746 DWORD size
= ARRAY_SIZE(home
);
2747 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2748 if (!len
|| len
> size
)
2749 wcscpy(home
, L
"::N/A::");
2751 if (!wcsicmp(wpath
, home
))
2754 /* Get the owner SID */
2755 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2756 OWNER_SECURITY_INFORMATION
|
2757 DACL_SECURITY_INFORMATION
,
2758 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2760 if (err
!= ERROR_SUCCESS
)
2761 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2762 else if (sid
&& IsValidSid(sid
)) {
2763 /* Now, verify that the SID matches the current user's */
2764 static PSID current_user_sid
;
2767 if (!current_user_sid
)
2768 current_user_sid
= get_current_user_sid();
2770 if (current_user_sid
&&
2771 IsValidSid(current_user_sid
) &&
2772 EqualSid(sid
, current_user_sid
))
2774 else if (IsWellKnownSid(sid
, WinBuiltinAdministratorsSid
) &&
2775 CheckTokenMembership(NULL
, sid
, &is_member
) &&
2778 * If owned by the Administrators group, and the
2779 * current user is an administrator, we consider that
2784 IsWellKnownSid(sid
, WinWorldSid
) &&
2785 !acls_supported(path
)) {
2787 * On FAT32 volumes, ownership is not actually recorded.
2789 strbuf_addf(report
, "'%s' is on a file system that does "
2790 "not record ownership\n", path
);
2791 } else if (report
) {
2792 LPSTR str1
, str2
, str3
, str4
, to_free1
= NULL
,
2793 to_free3
= NULL
, to_local_free2
= NULL
,
2794 to_local_free4
= NULL
;
2796 if (user_sid_to_user_name(sid
, &str1
))
2799 str1
= "(inconvertible)";
2800 if (ConvertSidToStringSidA(sid
, &str2
))
2801 to_local_free2
= str2
;
2803 str2
= "(inconvertible)";
2805 if (!current_user_sid
) {
2809 else if (!IsValidSid(current_user_sid
)) {
2813 if (user_sid_to_user_name(current_user_sid
,
2817 str3
= "(inconvertible)";
2818 if (ConvertSidToStringSidA(current_user_sid
,
2820 to_local_free4
= str4
;
2822 str4
= "(inconvertible)";
2825 "'%s' is owned by:\n"
2826 "\t%s (%s)\nbut the current user is:\n"
2828 path
, str1
, str2
, str3
, str4
);
2830 LocalFree(to_local_free2
);
2832 LocalFree(to_local_free4
);
2837 * We can release the security descriptor struct only now because `sid`
2838 * actually points into this struct.
2841 LocalFree(descriptor
);
2846 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2848 const char *p
= path
;
2849 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2854 skip_dos_drive_prefix((char **)&path
);
2861 case '/': case '\\':
2862 /* cannot end in ` ` or `.`, except for `.` and `..` */
2863 if (preceding_space_or_period
&&
2864 (i
!= periods
|| periods
> 2))
2869 i
= periods
= preceding_space_or_period
= 0;
2873 case 'a': case 'A': /* AUX */
2874 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2875 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2876 not_a_reserved_name
:
2882 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2883 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2884 goto not_a_reserved_name
;
2886 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2888 if (c
< '1' || c
> '9')
2889 goto not_a_reserved_name
;
2890 } else if (c
== 'n' || c
== 'N') { /* CON */
2892 if ((c
== 'i' || c
== 'I') &&
2893 ((c
= path
[i
+ 2]) == 'n' ||
2896 i
+= 3; /* CONIN$ */
2897 else if ((c
== 'o' || c
== 'O') &&
2898 ((c
= path
[i
+ 2]) == 'u' ||
2900 ((c
= path
[i
+ 3]) == 't' ||
2903 i
+= 4; /* CONOUT$ */
2905 goto not_a_reserved_name
;
2907 case 'l': case 'L': /* LPT<N> */
2908 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2909 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2910 !isdigit(path
[++i
]))
2911 goto not_a_reserved_name
;
2913 case 'n': case 'N': /* NUL */
2914 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2915 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2916 (allow_literal_nul
&&
2917 !path
[i
+ 1] && p
== path
))
2918 goto not_a_reserved_name
;
2920 case 'p': case 'P': /* PRN */
2921 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2922 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2923 goto not_a_reserved_name
;
2930 * So far, this looks like a reserved name. Let's see
2931 * whether it actually is one: trailing spaces, a file
2932 * extension, or an NTFS Alternate Data Stream do not
2933 * matter, the name is still reserved if any of those
2934 * follow immediately after the actual name.
2937 if (path
[i
] == ' ') {
2938 preceding_space_or_period
= 1;
2939 while (path
[++i
] == ' ')
2940 ; /* skip all spaces */
2944 if (c
&& c
!= '.' && c
!= ':' && !is_xplatform_dir_sep(c
))
2945 goto not_a_reserved_name
;
2947 /* contains reserved name */
2953 preceding_space_or_period
= 1;
2956 case ':': /* DOS drive prefix was already skipped */
2957 case '<': case '>': case '"': case '|': case '?': case '*':
2958 /* illegal character */
2961 if (c
> '\0' && c
< '\x20')
2962 /* illegal character */
2965 preceding_space_or_period
= 0;
2970 #if !defined(_MSC_VER)
2972 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2973 * mingw startup code, see init.c in mingw runtime).
2978 static NORETURN
void die_startup(void)
2980 fputs("fatal: not enough memory for initialization", stderr
);
2984 static void *malloc_startup(size_t size
)
2986 void *result
= malloc(size
);
2992 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2994 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2995 return memcpy(malloc_startup(len
), buffer
, len
);
2998 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2999 DWORD desired_access
, DWORD flags
)
3001 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
3002 wchar_t buf
[MAX_PATH
];
3003 DWORD max
= ARRAY_SIZE(buf
);
3005 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
3007 if (!ret
|| ret
>= max
)
3010 /* make sure this does not leak into child processes */
3011 SetEnvironmentVariableW(key
, NULL
);
3012 if (!wcscmp(buf
, L
"off")) {
3014 handle
= GetStdHandle(std_id
);
3015 if (handle
!= INVALID_HANDLE_VALUE
)
3016 CloseHandle(handle
);
3019 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
3020 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
3021 if (handle
== INVALID_HANDLE_VALUE
) {
3023 handle
= GetStdHandle(std_id
);
3024 if (handle
!= INVALID_HANDLE_VALUE
)
3025 CloseHandle(handle
);
3027 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
3028 SetStdHandle(std_id
, handle
);
3030 /* do *not* close the new_fd: that would close stdout */
3034 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
3036 if (handle
!= INVALID_HANDLE_VALUE
) {
3037 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
3038 SetStdHandle(std_id
, handle
);
3044 static void maybe_redirect_std_handles(void)
3046 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
3047 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
3048 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
3049 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
3050 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
3051 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
3061 * We implement wmain() and compile with -municode, which would
3062 * normally ignore main(), but we call the latter from the former
3063 * so that we can handle non-ASCII command-line parameters
3066 * To be more compatible with the core git code, we convert
3067 * argv into UTF8 and pass them directly to main().
3069 int wmain(int argc
, const wchar_t **wargv
)
3071 int i
, maxlen
, exit_status
;
3072 char *buffer
, **save
;
3075 trace2_initialize_clock();
3079 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
3082 #ifdef USE_MSVC_CRTDBG
3083 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
3087 maybe_redirect_std_handles();
3089 /* determine size of argv and environ conversion buffer */
3090 maxlen
= wcslen(wargv
[0]);
3091 for (i
= 1; i
< argc
; i
++)
3092 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
3094 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3095 maxlen
= 3 * maxlen
+ 1;
3096 buffer
= malloc_startup(maxlen
);
3099 * Create a UTF-8 version of w_argv. Also create a "save" copy
3100 * to remember all the string pointers because parse_options()
3101 * will remove claimed items from the argv that we pass down.
3103 ALLOC_ARRAY(argv
, argc
+ 1);
3104 ALLOC_ARRAY(save
, argc
+ 1);
3105 for (i
= 0; i
< argc
; i
++)
3106 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
3107 argv
[i
] = save
[i
] = NULL
;
3110 /* fix Windows specific environment settings */
3111 setup_windows_environment();
3113 unset_environment_variables
= xstrdup("PERL5LIB");
3115 /* initialize critical section for waitpid pinfo_t list */
3116 InitializeCriticalSection(&pinfo_cs
);
3118 /* set up default file mode and file modes for stdin/out/err */
3120 _setmode(_fileno(stdin
), _O_BINARY
);
3121 _setmode(_fileno(stdout
), _O_BINARY
);
3122 _setmode(_fileno(stderr
), _O_BINARY
);
3124 /* initialize Unicode console */
3127 /* invoke the real main() using our utf8 version of argv. */
3128 exit_status
= main(argc
, argv
);
3130 for (i
= 0; i
< argc
; i
++)
3138 int uname(struct utsname
*buf
)
3140 unsigned v
= (unsigned)GetVersion();
3141 memset(buf
, 0, sizeof(*buf
));
3142 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3143 xsnprintf(buf
->release
, sizeof(buf
->release
),
3144 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3145 /* assuming NT variants only.. */
3146 xsnprintf(buf
->version
, sizeof(buf
->version
),
3147 "%u", (v
>> 16) & 0x7fff);