1 #include "../git-compat-util.h"
6 #include "../run-command.h"
8 #include "win32/lazyload.h"
11 #define SECURITY_WIN32
14 #define HCAST(type, handle) ((type)(intptr_t)handle)
16 static const int delay
[] = { 0, 1, 10, 20, 40 };
18 void open_in_gdb(void)
20 static struct child_process cp
= CHILD_PROCESS_INIT
;
23 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
24 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
26 if (start_command(&cp
) < 0)
27 die_errno("Could not start gdb");
31 int err_win_to_posix(DWORD winerr
)
35 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
36 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
37 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
38 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
39 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
40 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
41 case ERROR_BAD_COMMAND
: error
= EIO
; break;
42 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
43 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
44 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
45 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
46 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
47 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
48 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
49 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
50 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
51 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
52 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
53 case ERROR_BUSY
: error
= EBUSY
; break;
54 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
55 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
56 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
57 case ERROR_CANTOPEN
: error
= EIO
; break;
58 case ERROR_CANTREAD
: error
= EIO
; break;
59 case ERROR_CANTWRITE
: error
= EIO
; break;
60 case ERROR_CRC
: error
= EIO
; break;
61 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
62 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
63 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
64 case ERROR_DIRECTORY
: error
= EINVAL
; break;
65 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
66 case ERROR_DISK_CHANGE
: error
= EIO
; break;
67 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
68 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
69 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
70 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
71 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
72 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
73 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
74 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
75 case ERROR_GEN_FAILURE
: error
= EIO
; break;
76 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
77 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
78 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
79 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
80 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
81 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
82 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
83 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
84 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
85 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
86 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
87 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
88 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
89 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
90 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
91 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
92 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
93 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
94 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
95 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
96 case ERROR_IO_DEVICE
: error
= EIO
; break;
97 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
98 case ERROR_LOCKED
: error
= EBUSY
; break;
99 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
100 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
101 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
102 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
103 case ERROR_MORE_DATA
: error
= EPIPE
; break;
104 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
105 case ERROR_NOACCESS
: error
= EFAULT
; break;
106 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
107 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
108 case ERROR_NOT_READY
: error
= EAGAIN
; break;
109 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
110 case ERROR_NO_DATA
: error
= EPIPE
; break;
111 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
112 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
113 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
114 case ERROR_OPEN_FAILED
: error
= EIO
; break;
115 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
116 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
117 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
118 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
119 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
120 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
121 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
122 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
123 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
124 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
125 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
126 case ERROR_READ_FAULT
: error
= EIO
; break;
127 case ERROR_SEEK
: error
= EIO
; break;
128 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
129 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
130 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
131 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
132 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
133 case ERROR_SWAPERROR
: error
= ENOENT
; break;
134 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
135 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
136 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
137 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
138 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
139 case ERROR_WRITE_FAULT
: error
= EIO
; break;
140 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
145 static inline int is_file_in_use_error(DWORD errcode
)
148 case ERROR_SHARING_VIOLATION
:
149 case ERROR_ACCESS_DENIED
:
156 static int read_yes_no_answer(void)
160 if (fgets(answer
, sizeof(answer
), stdin
)) {
161 size_t answer_len
= strlen(answer
);
162 int got_full_line
= 0, c
;
164 /* remove the newline */
165 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
166 answer
[answer_len
-2] = '\0';
168 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
169 answer
[answer_len
-1] = '\0';
172 /* flush the buffer in case we did not get the full line */
174 while ((c
= getchar()) != EOF
&& c
!= '\n')
177 /* we could not read, return the
178 * default answer which is no */
181 if (tolower(answer
[0]) == 'y' && !answer
[1])
183 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
185 if (tolower(answer
[0]) == 'n' && !answer
[1])
187 if (!strncasecmp(answer
, "no", sizeof(answer
)))
190 /* did not find an answer we understand */
194 static int ask_yes_no_if_possible(const char *format
, ...)
197 const char *retry_hook
[] = { NULL
, NULL
, NULL
};
200 va_start(args
, format
);
201 vsnprintf(question
, sizeof(question
), format
, args
);
204 if ((retry_hook
[0] = mingw_getenv("GIT_ASK_YESNO"))) {
205 retry_hook
[1] = question
;
206 return !run_command_v_opt(retry_hook
, 0);
209 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
214 fprintf(stderr
, "%s (y/n) ", question
);
216 if ((answer
= read_yes_no_answer()) >= 0)
219 fprintf(stderr
, "Sorry, I did not understand your answer. "
220 "Please type 'y' or 'n'\n");
225 enum hide_dotfiles_type
{
226 HIDE_DOTFILES_FALSE
= 0,
228 HIDE_DOTFILES_DOTGITONLY
231 static int core_restrict_inherited_handles
= -1;
232 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
233 static char *unset_environment_variables
;
235 int mingw_core_config(const char *var
, const char *value
, void *cb
)
237 if (!strcmp(var
, "core.hidedotfiles")) {
238 if (value
&& !strcasecmp(value
, "dotgitonly"))
239 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
241 hide_dotfiles
= git_config_bool(var
, value
);
245 if (!strcmp(var
, "core.unsetenvvars")) {
246 free(unset_environment_variables
);
247 unset_environment_variables
= xstrdup(value
);
251 if (!strcmp(var
, "core.restrictinheritedhandles")) {
252 if (value
&& !strcasecmp(value
, "auto"))
253 core_restrict_inherited_handles
= -1;
255 core_restrict_inherited_handles
=
256 git_config_bool(var
, value
);
263 /* Normalizes NT paths as returned by some low-level APIs. */
264 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
267 /* fix absolute path prefixes */
268 if (wbuf
[0] == '\\') {
269 /* strip NT namespace prefixes */
270 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
271 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
273 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
275 /* replace remaining '...UNC\' with '\\' */
276 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
281 /* convert backslashes to slashes */
282 for (i
= 0; wbuf
[i
]; i
++)
288 int mingw_unlink(const char *pathname
)
291 wchar_t wpathname
[MAX_PATH
];
292 if (xutftowcs_path(wpathname
, pathname
) < 0)
295 if (DeleteFileW(wpathname
))
298 /* read-only files cannot be removed */
299 _wchmod(wpathname
, 0666);
300 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
301 if (!is_file_in_use_error(GetLastError()))
304 * We assume that some other process had the source or
305 * destination file open at the wrong moment and retry.
306 * In order to give the other process a higher chance to
307 * complete its operation, we give up our time slice now.
308 * If we have to retry again, we do sleep a bit.
313 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
314 ask_yes_no_if_possible("Unlink of file '%s' failed. "
315 "Should I try again?", pathname
))
316 ret
= _wunlink(wpathname
);
320 static int is_dir_empty(const wchar_t *wpath
)
322 WIN32_FIND_DATAW findbuf
;
324 wchar_t wbuf
[MAX_PATH
+ 2];
326 wcscat(wbuf
, L
"\\*");
327 handle
= FindFirstFileW(wbuf
, &findbuf
);
328 if (handle
== INVALID_HANDLE_VALUE
)
329 return GetLastError() == ERROR_NO_MORE_FILES
;
331 while (!wcscmp(findbuf
.cFileName
, L
".") ||
332 !wcscmp(findbuf
.cFileName
, L
".."))
333 if (!FindNextFileW(handle
, &findbuf
)) {
334 DWORD err
= GetLastError();
336 return err
== ERROR_NO_MORE_FILES
;
342 int mingw_rmdir(const char *pathname
)
345 wchar_t wpathname
[MAX_PATH
];
349 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
350 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
351 * symbolic link (if it points to a directory).
353 * This behavior breaks the assumption of e.g. `remove_path()` which
354 * upon successful deletion of a file will attempt to remove its parent
355 * directories recursively until failure (which usually happens when
356 * the directory is not empty).
358 * Therefore, before calling `_wrmdir()`, we first check if the path is
359 * a symbolic link. If it is, we exit and return the same error as
360 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
362 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
367 if (xutftowcs_path(wpathname
, pathname
) < 0)
370 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
371 if (!is_file_in_use_error(GetLastError()))
372 errno
= err_win_to_posix(GetLastError());
375 if (!is_dir_empty(wpathname
)) {
380 * We assume that some other process had the source or
381 * destination file open at the wrong moment and retry.
382 * In order to give the other process a higher chance to
383 * complete its operation, we give up our time slice now.
384 * If we have to retry again, we do sleep a bit.
389 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
390 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
391 "Should I try again?", pathname
))
392 ret
= _wrmdir(wpathname
);
394 invalidate_lstat_cache();
398 static inline int needs_hiding(const char *path
)
400 const char *basename
;
402 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
405 /* We cannot use basename(), as it would remove trailing slashes */
406 win32_skip_dos_drive_prefix((char **)&path
);
410 for (basename
= path
; *path
; path
++)
411 if (is_dir_sep(*path
)) {
414 } while (is_dir_sep(*path
));
415 /* ignore trailing slashes */
422 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
423 return *basename
== '.';
425 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
426 return !strncasecmp(".git", basename
, 4) &&
427 (!basename
[4] || is_dir_sep(basename
[4]));
430 static int set_hidden_flag(const wchar_t *path
, int set
)
432 DWORD original
= GetFileAttributesW(path
), modified
;
434 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
436 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
437 if (original
== modified
|| SetFileAttributesW(path
, modified
))
439 errno
= err_win_to_posix(GetLastError());
443 int mingw_mkdir(const char *path
, int mode
)
446 wchar_t wpath
[MAX_PATH
];
448 if (!is_valid_win32_path(path
, 0)) {
453 if (xutftowcs_path(wpath
, path
) < 0)
455 ret
= _wmkdir(wpath
);
456 if (!ret
&& needs_hiding(path
))
457 return set_hidden_flag(wpath
, 1);
462 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
463 * is documented in [1] as opening a writable file handle in append mode.
464 * (It is believed that) this is atomic since it is maintained by the
465 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
467 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
469 * This trick does not appear to work for named pipes. Instead it creates
470 * a named pipe client handle that cannot be written to. Callers should
471 * just use the regular _wopen() for them. (And since client handle gets
472 * bound to a unique server handle, it isn't really an issue.)
474 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
478 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
480 /* only these flags are supported */
481 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
482 return errno
= ENOSYS
, -1;
485 * FILE_SHARE_WRITE is required to permit child processes
486 * to append to the file.
488 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
489 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
490 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
491 if (handle
== INVALID_HANDLE_VALUE
) {
492 DWORD err
= GetLastError();
495 * Some network storage solutions (e.g. Isilon) might return
496 * ERROR_INVALID_PARAMETER instead of expected error
497 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
498 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
500 if (err
== ERROR_INVALID_PARAMETER
)
501 err
= ERROR_PATH_NOT_FOUND
;
503 errno
= err_win_to_posix(err
);
508 * No O_APPEND here, because the CRT uses it only to reset the
509 * file pointer to EOF before each write(); but that is not
510 * necessary (and may lead to races) for a file created with
513 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
520 * Does the pathname map to the local named pipe filesystem?
521 * That is, does it have a "//./pipe/" prefix?
523 static int is_local_named_pipe_path(const char *filename
)
525 return (is_dir_sep(filename
[0]) &&
526 is_dir_sep(filename
[1]) &&
527 filename
[2] == '.' &&
528 is_dir_sep(filename
[3]) &&
529 !strncasecmp(filename
+4, "pipe", 4) &&
530 is_dir_sep(filename
[8]) &&
534 int mingw_open (const char *filename
, int oflags
, ...)
536 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
539 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
540 wchar_t wfilename
[MAX_PATH
];
543 va_start(args
, oflags
);
544 mode
= va_arg(args
, int);
547 if (!is_valid_win32_path(filename
, !create
)) {
548 errno
= create
? EINVAL
: ENOENT
;
552 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
553 open_fn
= mingw_open_append
;
557 if (filename
&& !strcmp(filename
, "/dev/null"))
558 wcscpy(wfilename
, L
"nul");
559 else if (xutftowcs_path(wfilename
, filename
) < 0)
562 fd
= open_fn(wfilename
, oflags
, mode
);
564 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
565 DWORD attrs
= GetFileAttributesW(wfilename
);
566 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
569 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
571 * Internally, _wopen() uses the CreateFile() API which errors
572 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
573 * specified and an already existing file's attributes do not
574 * match *exactly*. As there is no mode or flag we can set that
575 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
576 * again *without* the O_CREAT flag (that corresponds to the
577 * CREATE_ALWAYS flag of CreateFile()).
579 if (fd
< 0 && errno
== EACCES
)
580 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
581 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
582 warning("could not mark '%s' as hidden.", filename
);
587 static BOOL WINAPI
ctrl_ignore(DWORD type
)
593 int mingw_fgetc(FILE *stream
)
596 if (!isatty(_fileno(stream
)))
597 return fgetc(stream
);
599 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
602 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
605 /* Ctrl+C was pressed, simulate SIGINT and retry */
608 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
613 FILE *mingw_fopen (const char *filename
, const char *otype
)
615 int hide
= needs_hiding(filename
);
617 wchar_t wfilename
[MAX_PATH
], wotype
[4];
618 if (filename
&& !strcmp(filename
, "/dev/null"))
619 wcscpy(wfilename
, L
"nul");
620 else if (!is_valid_win32_path(filename
, 1)) {
621 int create
= otype
&& strchr(otype
, 'w');
622 errno
= create
? EINVAL
: ENOENT
;
624 } else if (xutftowcs_path(wfilename
, filename
) < 0)
627 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
630 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
631 error("could not unhide %s", filename
);
634 file
= _wfopen(wfilename
, wotype
);
635 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
637 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
638 warning("could not mark '%s' as hidden.", filename
);
642 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
644 int hide
= needs_hiding(filename
);
646 wchar_t wfilename
[MAX_PATH
], wotype
[4];
647 if (filename
&& !strcmp(filename
, "/dev/null"))
648 wcscpy(wfilename
, L
"nul");
649 else if (!is_valid_win32_path(filename
, 1)) {
650 int create
= otype
&& strchr(otype
, 'w');
651 errno
= create
? EINVAL
: ENOENT
;
653 } else if (xutftowcs_path(wfilename
, filename
) < 0)
656 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
659 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
660 error("could not unhide %s", filename
);
663 file
= _wfreopen(wfilename
, wotype
, stream
);
664 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
665 warning("could not mark '%s' as hidden.", filename
);
670 int mingw_fflush(FILE *stream
)
672 int ret
= fflush(stream
);
675 * write() is used behind the scenes of stdio output functions.
676 * Since git code does not check for errors after each stdio write
677 * operation, it can happen that write() is called by a later
678 * stdio function even if an earlier write() call failed. In the
679 * case of a pipe whose readable end was closed, only the first
680 * call to write() reports EPIPE on Windows. Subsequent write()
681 * calls report EINVAL. It is impossible to notice whether this
682 * fflush invocation triggered such a case, therefore, we have to
683 * catch all EINVAL errors whole-sale.
685 if (ret
&& errno
== EINVAL
)
692 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
694 ssize_t result
= write(fd
, buf
, len
);
696 if (result
< 0 && errno
== EINVAL
&& buf
) {
697 /* check if fd is a pipe */
698 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
699 if (GetFileType(h
) == FILE_TYPE_PIPE
)
708 int mingw_access(const char *filename
, int mode
)
710 wchar_t wfilename
[MAX_PATH
];
711 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
713 if (xutftowcs_path(wfilename
, filename
) < 0)
715 /* X_OK is not supported by the MSVCRT version */
716 return _waccess(wfilename
, mode
& ~X_OK
);
719 int mingw_chdir(const char *dirname
)
721 wchar_t wdirname
[MAX_PATH
];
722 if (xutftowcs_path(wdirname
, dirname
) < 0)
724 return _wchdir(wdirname
);
727 int mingw_chmod(const char *filename
, int mode
)
729 wchar_t wfilename
[MAX_PATH
];
730 if (xutftowcs_path(wfilename
, filename
) < 0)
732 return _wchmod(wfilename
, mode
);
736 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
737 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
739 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
741 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
742 /* Windows to Unix Epoch conversion */
743 return winTime
- 116444736000000000LL;
746 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
748 long long hnsec
= filetime_to_hnsec(ft
);
749 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
750 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
754 * Verifies that safe_create_leading_directories() would succeed.
756 static int has_valid_directory_prefix(wchar_t *wfilename
)
758 int n
= wcslen(wfilename
);
761 wchar_t c
= wfilename
[--n
];
767 wfilename
[n
] = L
'\0';
768 attributes
= GetFileAttributesW(wfilename
);
770 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
771 attributes
== FILE_ATTRIBUTE_DEVICE
)
773 if (attributes
== INVALID_FILE_ATTRIBUTES
)
774 switch (GetLastError()) {
775 case ERROR_PATH_NOT_FOUND
:
777 case ERROR_FILE_NOT_FOUND
:
778 /* This implies parent directory exists. */
786 /* We keep the do_lstat code in a separate function to avoid recursion.
787 * When a path ends with a slash, the stat will fail with ENOENT. In
788 * this case, we strip the trailing slashes and stat again.
790 * If follow is true then act like stat() and report on the link
791 * target. Otherwise report on the link itself.
793 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
795 WIN32_FILE_ATTRIBUTE_DATA fdata
;
796 wchar_t wfilename
[MAX_PATH
];
797 if (xutftowcs_path(wfilename
, file_name
) < 0)
800 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
805 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
806 buf
->st_size
= fdata
.nFileSizeLow
|
807 (((off_t
)fdata
.nFileSizeHigh
)<<32);
808 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
809 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
810 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
811 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
812 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
813 WIN32_FIND_DATAW findbuf
;
814 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
815 if (handle
!= INVALID_HANDLE_VALUE
) {
816 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
817 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
819 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
820 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
822 buf
->st_mode
= S_IFLNK
;
824 buf
->st_mode
|= S_IREAD
;
825 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
826 buf
->st_mode
|= S_IWRITE
;
833 switch (GetLastError()) {
834 case ERROR_ACCESS_DENIED
:
835 case ERROR_SHARING_VIOLATION
:
836 case ERROR_LOCK_VIOLATION
:
837 case ERROR_SHARING_BUFFER_EXCEEDED
:
840 case ERROR_BUFFER_OVERFLOW
:
841 errno
= ENAMETOOLONG
;
843 case ERROR_NOT_ENOUGH_MEMORY
:
846 case ERROR_PATH_NOT_FOUND
:
847 if (!has_valid_directory_prefix(wfilename
)) {
859 /* We provide our own lstat/fstat functions, since the provided
860 * lstat/fstat functions are so slow. These stat functions are
861 * tailored for Git's usage (read: fast), and are not meant to be
862 * complete. Note that Git stat()s are redirected to mingw_lstat()
863 * too, since Windows doesn't really handle symlinks that well.
865 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
868 char alt_name
[PATH_MAX
];
870 if (!do_lstat(follow
, file_name
, buf
))
873 /* if file_name ended in a '/', Windows returned ENOENT;
874 * try again without trailing slashes
879 namelen
= strlen(file_name
);
880 if (namelen
&& file_name
[namelen
-1] != '/')
882 while (namelen
&& file_name
[namelen
-1] == '/')
884 if (!namelen
|| namelen
>= PATH_MAX
)
887 memcpy(alt_name
, file_name
, namelen
);
888 alt_name
[namelen
] = 0;
889 return do_lstat(follow
, alt_name
, buf
);
892 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
894 BY_HANDLE_FILE_INFORMATION fdata
;
896 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
897 errno
= err_win_to_posix(GetLastError());
905 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
906 buf
->st_size
= fdata
.nFileSizeLow
|
907 (((off_t
)fdata
.nFileSizeHigh
)<<32);
908 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
909 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
910 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
911 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
915 int mingw_lstat(const char *file_name
, struct stat
*buf
)
917 return do_stat_internal(0, file_name
, buf
);
919 int mingw_stat(const char *file_name
, struct stat
*buf
)
921 return do_stat_internal(1, file_name
, buf
);
924 int mingw_fstat(int fd
, struct stat
*buf
)
926 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
927 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
931 return get_file_info_by_handle(fh
, buf
);
935 /* initialize stat fields */
936 memset(buf
, 0, sizeof(*buf
));
939 if (type
== FILE_TYPE_CHAR
) {
940 buf
->st_mode
= _S_IFCHR
;
942 buf
->st_mode
= _S_IFIFO
;
943 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
944 buf
->st_size
= avail
;
954 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
956 long long winTime
= t
* 10000000LL + 116444736000000000LL;
957 ft
->dwLowDateTime
= winTime
;
958 ft
->dwHighDateTime
= winTime
>> 32;
961 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
966 wchar_t wfilename
[MAX_PATH
];
967 if (xutftowcs_path(wfilename
, file_name
) < 0)
970 /* must have write permission */
971 attrs
= GetFileAttributesW(wfilename
);
972 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
973 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
974 /* ignore errors here; open() will report them */
975 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
978 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
984 time_t_to_filetime(times
->modtime
, &mft
);
985 time_t_to_filetime(times
->actime
, &aft
);
987 GetSystemTimeAsFileTime(&mft
);
990 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
998 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
999 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1000 /* ignore errors again */
1001 SetFileAttributesW(wfilename
, attrs
);
1007 size_t mingw_strftime(char *s
, size_t max
,
1008 const char *format
, const struct tm
*tm
)
1010 /* a pointer to the original strftime in case we can't find the UCRT version */
1011 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1013 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1014 const char *, const struct tm
*);
1016 if (INIT_PROC_ADDR(strftime
))
1017 ret
= strftime(s
, max
, format
, tm
);
1019 ret
= fallback(s
, max
, format
, tm
);
1021 if (!ret
&& errno
== EINVAL
)
1022 die("invalid strftime format: '%s'", format
);
1026 unsigned int sleep (unsigned int seconds
)
1028 Sleep(seconds
*1000);
1032 char *mingw_mktemp(char *template)
1034 wchar_t wtemplate
[MAX_PATH
];
1035 if (xutftowcs_path(wtemplate
, template) < 0)
1037 if (!_wmktemp(wtemplate
))
1039 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1044 int mkstemp(char *template)
1046 char *filename
= mktemp(template);
1047 if (filename
== NULL
)
1049 return open(filename
, O_RDWR
| O_CREAT
, 0600);
1052 int gettimeofday(struct timeval
*tv
, void *tz
)
1057 GetSystemTimeAsFileTime(&ft
);
1058 hnsec
= filetime_to_hnsec(&ft
);
1059 tv
->tv_sec
= hnsec
/ 10000000;
1060 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1064 int pipe(int filedes
[2])
1068 /* this creates non-inheritable handles */
1069 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1070 errno
= err_win_to_posix(GetLastError());
1073 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1074 if (filedes
[0] < 0) {
1079 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1080 if (filedes
[1] < 0) {
1089 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1091 if (gmtime_s(result
, timep
) == 0)
1096 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1098 if (localtime_s(result
, timep
) == 0)
1104 char *mingw_getcwd(char *pointer
, int len
)
1106 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1107 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1109 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1110 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1113 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1114 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1115 HANDLE hnd
= CreateFileW(cwd
, 0,
1116 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1117 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1118 if (hnd
== INVALID_HANDLE_VALUE
)
1120 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1122 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1124 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1128 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1130 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1134 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1136 convert_slashes(pointer
);
1141 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1142 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1144 static const char *quote_arg_msvc(const char *arg
)
1146 /* count chars to quote */
1148 int force_quotes
= 0;
1150 const char *p
= arg
;
1151 if (!*p
) force_quotes
= 1;
1153 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1157 else if (*p
== '\\') {
1159 while (*p
== '\\') {
1164 if (*p
== '"' || !*p
)
1171 if (!force_quotes
&& n
== 0)
1174 /* insert \ where necessary */
1175 d
= q
= xmalloc(st_add3(len
, n
, 3));
1180 else if (*arg
== '\\') {
1182 while (*arg
== '\\') {
1186 if (*arg
== '"' || !*arg
) {
1189 /* don't escape the surrounding end quote */
1204 static const char *quote_arg_msys2(const char *arg
)
1206 struct strbuf buf
= STRBUF_INIT
;
1207 const char *p2
= arg
, *p
;
1209 for (p
= arg
; *p
; p
++) {
1210 int ws
= isspace(*p
);
1211 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1212 *p
!= '?' && *p
!= '*' && *p
!= '~')
1215 strbuf_addch(&buf
, '"');
1217 strbuf_add(&buf
, p2
, p
- p2
);
1218 if (*p
== '\\' || *p
== '"')
1219 strbuf_addch(&buf
, '\\');
1224 strbuf_addch(&buf
, '"');
1228 strbuf_add(&buf
, p2
, p
- p2
);
1230 strbuf_addch(&buf
, '"');
1231 return strbuf_detach(&buf
, 0);
1234 static const char *parse_interpreter(const char *cmd
)
1236 static char buf
[100];
1240 /* don't even try a .exe */
1242 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1245 fd
= open(cmd
, O_RDONLY
);
1248 n
= read(fd
, buf
, sizeof(buf
)-1);
1250 if (n
< 4) /* at least '#!/x' and not error */
1253 if (buf
[0] != '#' || buf
[1] != '!')
1256 p
= buf
+ strcspn(buf
, "\r\n");
1261 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1264 if ((opt
= strchr(p
+1, ' ')))
1270 * exe_only means that we only want to detect .exe files, but not scripts
1271 * (which do not have an extension)
1273 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1274 int isexe
, int exe_only
)
1276 char path
[MAX_PATH
];
1277 wchar_t wpath
[MAX_PATH
];
1278 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1280 if (xutftowcs_path(wpath
, path
) < 0)
1283 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1284 return xstrdup(path
);
1285 wpath
[wcslen(wpath
)-4] = '\0';
1286 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1287 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1288 path
[strlen(path
)-4] = '\0';
1289 return xstrdup(path
);
1296 * Determines the absolute path of cmd using the split path in path.
1297 * If cmd contains a slash or backslash, no lookup is performed.
1299 static char *path_lookup(const char *cmd
, int exe_only
)
1303 int len
= strlen(cmd
);
1304 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1306 if (strpbrk(cmd
, "/\\"))
1307 return xstrdup(cmd
);
1309 path
= mingw_getenv("PATH");
1314 const char *sep
= strchrnul(path
, ';');
1315 int dirlen
= sep
- path
;
1317 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1326 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1328 while (*s
&& *s
!= c
)
1333 /* Compare only keys */
1334 static int wenvcmp(const void *a
, const void *b
)
1336 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1337 size_t p_len
, q_len
;
1340 p_len
= wcschrnul(p
, L
'=') - p
;
1341 q_len
= wcschrnul(q
, L
'=') - q
;
1343 /* If the length differs, include the shorter key's NUL */
1346 else if (p_len
> q_len
)
1349 return _wcsnicmp(p
, q
, p_len
);
1353 * Build an environment block combining the inherited environment
1354 * merged with the given list of settings.
1356 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1357 * Values of the form "KEY" in deltaenv delete inherited values.
1359 * Multiple entries in deltaenv for the same key are explicitly allowed.
1361 * We return a contiguous block of UNICODE strings with a final trailing
1364 static wchar_t *make_environment_block(char **deltaenv
)
1366 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1367 size_t wlen
, s
, delta_size
, size
;
1369 wchar_t **array
= NULL
;
1370 size_t alloc
= 0, nr
= 0, i
;
1372 size
= 1; /* for extra NUL at the end */
1374 /* If there is no deltaenv to apply, simply return a copy. */
1375 if (!deltaenv
|| !*deltaenv
) {
1376 for (p
= wenv
; p
&& *p
; ) {
1377 size_t s
= wcslen(p
) + 1;
1382 ALLOC_ARRAY(result
, size
);
1383 COPY_ARRAY(result
, wenv
, size
);
1384 FreeEnvironmentStringsW(wenv
);
1389 * If there is a deltaenv, let's accumulate all keys into `array`,
1390 * sort them using the stable git_stable_qsort() and then copy,
1391 * skipping duplicate keys
1393 for (p
= wenv
; p
&& *p
; ) {
1394 ALLOC_GROW(array
, nr
+ 1, alloc
);
1401 /* (over-)assess size needed for wchar version of deltaenv */
1402 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1403 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1404 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1406 /* convert the deltaenv, appending to array */
1407 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1408 ALLOC_GROW(array
, nr
+ 1, alloc
);
1409 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1414 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1415 ALLOC_ARRAY(result
, size
+ delta_size
);
1417 for (p
= result
, i
= 0; i
< nr
; i
++) {
1418 /* Skip any duplicate keys; last one wins */
1419 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1422 /* Skip "to delete" entry */
1423 if (!wcschr(array
[i
], L
'='))
1426 size
= wcslen(array
[i
]) + 1;
1427 COPY_ARRAY(p
, array
[i
], size
);
1434 FreeEnvironmentStringsW(wenv
);
1438 static void do_unset_environment_variables(void)
1441 char *p
= unset_environment_variables
;
1448 char *comma
= strchr(p
, ',');
1460 struct pinfo_t
*next
;
1464 static struct pinfo_t
*pinfo
= NULL
;
1465 CRITICAL_SECTION pinfo_cs
;
1467 /* Used to match and chomp off path components */
1468 static inline int match_last_path_component(const char *path
, size_t *len
,
1469 const char *component
)
1471 size_t component_len
= strlen(component
);
1472 if (*len
< component_len
+ 1 ||
1473 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1474 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1476 *len
-= component_len
+ 1;
1477 /* chomp off repeated dir separators */
1478 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1483 static int is_msys2_sh(const char *cmd
)
1488 if (!strcmp(cmd
, "sh")) {
1489 static int ret
= -1;
1495 p
= path_lookup(cmd
, 0);
1499 size_t len
= strlen(p
);
1501 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1502 match_last_path_component(p
, &len
, "bin") &&
1503 match_last_path_component(p
, &len
, "usr");
1509 if (ends_with(cmd
, "\\sh.exe")) {
1513 sh
= path_lookup("sh", 0);
1515 return !fspathcmp(cmd
, sh
);
1521 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1523 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1525 static int restrict_handle_inheritance
= -1;
1527 PROCESS_INFORMATION pi
;
1528 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1529 HANDLE stdhandles
[3];
1530 DWORD stdhandles_count
= 0;
1533 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1534 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1537 const char *(*quote_arg
)(const char *arg
) =
1538 is_msys2_sh(cmd
? cmd
: *argv
) ?
1539 quote_arg_msys2
: quote_arg_msvc
;
1540 const char *strace_env
;
1542 /* Make sure to override previous errors, if any */
1545 if (restrict_handle_inheritance
< 0)
1546 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1548 * The following code to restrict which handles are inherited seems
1549 * to work properly only on Windows 7 and later, so let's disable it
1550 * on Windows Vista and 2008.
1552 if (restrict_handle_inheritance
< 0)
1553 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1555 do_unset_environment_variables();
1557 /* Determine whether or not we are associated to a console */
1558 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1559 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1560 FILE_ATTRIBUTE_NORMAL
, NULL
);
1561 if (cons
== INVALID_HANDLE_VALUE
) {
1562 /* There is no console associated with this process.
1563 * Since the child is a console process, Windows
1564 * would normally create a console window. But
1565 * since we'll be redirecting std streams, we do
1566 * not need the console.
1567 * It is necessary to use DETACHED_PROCESS
1568 * instead of CREATE_NO_WINDOW to make ssh
1569 * recognize that it has no console.
1571 flags
|= DETACHED_PROCESS
;
1573 /* There is already a console. If we specified
1574 * DETACHED_PROCESS here, too, Windows would
1575 * disassociate the child from the console.
1576 * The same is true for CREATE_NO_WINDOW.
1581 memset(&si
, 0, sizeof(si
));
1582 si
.StartupInfo
.cb
= sizeof(si
);
1583 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1584 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1585 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1587 /* The list of handles cannot contain duplicates */
1588 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1589 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1590 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1591 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1592 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1593 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1594 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1595 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1596 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1597 if (stdhandles_count
)
1598 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1600 if (*argv
&& !strcmp(cmd
, *argv
))
1602 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1604 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1607 /* concatenate argv, quoting args as we go */
1608 strbuf_init(&args
, 0);
1610 char *quoted
= (char *)quote_arg(cmd
);
1611 strbuf_addstr(&args
, quoted
);
1615 for (; *argv
; argv
++) {
1616 char *quoted
= (char *)quote_arg(*argv
);
1618 strbuf_addch(&args
, ' ');
1619 strbuf_addstr(&args
, quoted
);
1620 if (quoted
!= *argv
)
1624 strace_env
= getenv("GIT_STRACE_COMMANDS");
1626 char *p
= path_lookup("strace.exe", 1);
1628 return error("strace not found!");
1629 if (xutftowcs_path(wcmd
, p
) < 0) {
1634 if (!strcmp("1", strace_env
) ||
1635 !strcasecmp("yes", strace_env
) ||
1636 !strcasecmp("true", strace_env
))
1637 strbuf_insert(&args
, 0, "strace ", 7);
1639 const char *quoted
= quote_arg(strace_env
);
1640 struct strbuf buf
= STRBUF_INIT
;
1641 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1642 if (quoted
!= strace_env
)
1643 free((char *)quoted
);
1644 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1645 strbuf_release(&buf
);
1649 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1650 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1651 strbuf_release(&args
);
1653 wenvblk
= make_environment_block(deltaenv
);
1655 memset(&pi
, 0, sizeof(pi
));
1656 if (restrict_handle_inheritance
&& stdhandles_count
&&
1657 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1658 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1659 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1660 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1661 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1662 UpdateProcThreadAttribute(attr_list
, 0,
1663 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1665 stdhandles_count
* sizeof(HANDLE
),
1667 si
.lpAttributeList
= attr_list
;
1668 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1671 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1672 stdhandles_count
? TRUE
: FALSE
,
1673 flags
, wenvblk
, dir
? wdir
: NULL
,
1674 &si
.StartupInfo
, &pi
);
1677 * On Windows 2008 R2, it seems that specifying certain types of handles
1678 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1679 * error. Rather than playing finicky and fragile games, let's just try
1680 * to detect this situation and simply try again without restricting any
1681 * handle inheritance. This is still better than failing to create
1684 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1685 DWORD err
= GetLastError();
1686 struct strbuf buf
= STRBUF_INIT
;
1688 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1690 * On Windows 7 and earlier, handles on pipes and character
1691 * devices are inherited automatically, and cannot be
1692 * specified in the thread handle list. Rather than trying
1693 * to catch each and every corner case (and running the
1694 * chance of *still* forgetting a few), let's just fall
1695 * back to creating the process without trying to limit the
1696 * handle inheritance.
1698 !(err
== ERROR_INVALID_PARAMETER
&&
1699 GetVersion() >> 16 < 9200) &&
1700 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1704 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1706 for (i
= 0; i
< stdhandles_count
; i
++) {
1707 HANDLE h
= stdhandles
[i
];
1708 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1709 "handle info (%d) %lx\n", i
, h
,
1711 GetHandleInformation(h
, &fl
),
1714 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1715 "at\nhttps://github.com/git-for-windows/"
1716 "git/issues/new\n\n"
1717 "To suppress this warning, please set "
1718 "the environment variable\n\n"
1719 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1722 restrict_handle_inheritance
= 0;
1723 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1724 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1725 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1726 &si
.StartupInfo
, &pi
);
1728 errno
= err_win_to_posix(GetLastError());
1729 if (ret
&& buf
.len
) {
1730 warning("failed to restrict file handles (%ld)\n\n%s",
1733 strbuf_release(&buf
);
1735 errno
= err_win_to_posix(GetLastError());
1737 if (si
.lpAttributeList
)
1738 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1740 HeapFree(GetProcessHeap(), 0, attr_list
);
1748 CloseHandle(pi
.hThread
);
1751 * The process ID is the human-readable identifier of the process
1752 * that we want to present in log and error messages. The handle
1753 * is not useful for this purpose. But we cannot close it, either,
1754 * because it is not possible to turn a process ID into a process
1755 * handle after the process terminated.
1756 * Keep the handle in a list for waitpid.
1758 EnterCriticalSection(&pinfo_cs
);
1760 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1761 info
->pid
= pi
.dwProcessId
;
1762 info
->proc
= pi
.hProcess
;
1766 LeaveCriticalSection(&pinfo_cs
);
1768 return (pid_t
)pi
.dwProcessId
;
1771 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1773 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1776 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1778 int fhin
, int fhout
, int fherr
)
1781 char *prog
= path_lookup(cmd
, 0);
1788 const char *interpr
= parse_interpreter(prog
);
1791 const char *argv0
= argv
[0];
1792 char *iprog
= path_lookup(interpr
, 1);
1799 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1800 fhin
, fhout
, fherr
);
1806 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1807 fhin
, fhout
, fherr
);
1813 static int try_shell_exec(const char *cmd
, char *const *argv
)
1815 const char *interpr
= parse_interpreter(cmd
);
1821 prog
= path_lookup(interpr
, 1);
1829 while (argv
[argc
]) argc
++;
1830 ALLOC_ARRAY(argv2
, argc
+ 1);
1831 argv2
[0] = (char *)cmd
; /* full path to the script file */
1832 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1833 exec_id
= trace2_exec(prog
, argv2
);
1834 pid
= mingw_spawnv(prog
, argv2
, 1);
1837 if (waitpid(pid
, &status
, 0) < 0)
1839 trace2_exec_result(exec_id
, status
);
1842 trace2_exec_result(exec_id
, -1);
1843 pid
= 1; /* indicate that we tried but failed */
1850 int mingw_execv(const char *cmd
, char *const *argv
)
1852 /* check if git_command is a shell script */
1853 if (!try_shell_exec(cmd
, argv
)) {
1857 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1858 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1860 trace2_exec_result(exec_id
, -1);
1863 if (waitpid(pid
, &status
, 0) < 0)
1865 trace2_exec_result(exec_id
, status
);
1871 int mingw_execvp(const char *cmd
, char *const *argv
)
1873 char *prog
= path_lookup(cmd
, 0);
1876 mingw_execv(prog
, argv
);
1884 int mingw_kill(pid_t pid
, int sig
)
1886 if (pid
> 0 && sig
== SIGTERM
) {
1887 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1889 if (TerminateProcess(h
, -1)) {
1894 errno
= err_win_to_posix(GetLastError());
1897 } else if (pid
> 0 && sig
== 0) {
1898 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1910 * UTF-8 versions of getenv(), putenv() and unsetenv().
1911 * Internally, they use the CRT's stock UNICODE routines
1912 * to avoid data loss.
1914 char *mingw_getenv(const char *name
)
1916 #define GETENV_MAX_RETAIN 64
1917 static char *values
[GETENV_MAX_RETAIN
];
1918 static int value_counter
;
1919 int len_key
, len_value
;
1922 wchar_t w_value
[32768];
1924 if (!name
|| !*name
)
1927 len_key
= strlen(name
) + 1;
1928 /* We cannot use xcalloc() here because that uses getenv() itself */
1929 w_key
= calloc(len_key
, sizeof(wchar_t));
1931 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1932 xutftowcs(w_key
, name
, len_key
);
1933 /* GetEnvironmentVariableW() only sets the last error upon failure */
1934 SetLastError(ERROR_SUCCESS
);
1935 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1936 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1942 len_value
= len_value
* 3 + 1;
1943 /* We cannot use xcalloc() here because that uses getenv() itself */
1944 value
= calloc(len_value
, sizeof(char));
1946 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1947 xwcstoutf(value
, w_value
, len_value
);
1950 * We return `value` which is an allocated value and the caller is NOT
1951 * expecting to have to free it, so we keep a round-robin array,
1952 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1954 free(values
[value_counter
]);
1955 values
[value_counter
++] = value
;
1956 if (value_counter
>= ARRAY_SIZE(values
))
1962 int mingw_putenv(const char *namevalue
)
1965 wchar_t *wide
, *equal
;
1968 if (!namevalue
|| !*namevalue
)
1971 size
= strlen(namevalue
) * 2 + 1;
1972 wide
= calloc(size
, sizeof(wchar_t));
1974 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1975 xutftowcs(wide
, namevalue
, size
);
1976 equal
= wcschr(wide
, L
'=');
1978 result
= SetEnvironmentVariableW(wide
, NULL
);
1981 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
1986 errno
= err_win_to_posix(GetLastError());
1988 return result
? 0 : -1;
1991 static void ensure_socket_initialization(void)
1994 static int initialized
= 0;
1999 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2000 die("unable to initialize winsock subsystem, error %d",
2003 atexit((void(*)(void)) WSACleanup
);
2008 int mingw_gethostname(char *name
, int namelen
)
2010 ensure_socket_initialization();
2011 return gethostname(name
, namelen
);
2014 #undef gethostbyname
2015 struct hostent
*mingw_gethostbyname(const char *host
)
2017 ensure_socket_initialization();
2018 return gethostbyname(host
);
2022 int mingw_getaddrinfo(const char *node
, const char *service
,
2023 const struct addrinfo
*hints
, struct addrinfo
**res
)
2025 ensure_socket_initialization();
2026 return getaddrinfo(node
, service
, hints
, res
);
2029 int mingw_socket(int domain
, int type
, int protocol
)
2034 ensure_socket_initialization();
2035 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2036 if (s
== INVALID_SOCKET
) {
2038 * WSAGetLastError() values are regular BSD error codes
2039 * biased by WSABASEERR.
2040 * However, strerror() does not know about networking
2041 * specific errors, which are values beginning at 38 or so.
2042 * Therefore, we choose to leave the biased error code
2043 * in errno so that _if_ someone looks up the code somewhere,
2044 * then it is at least the number that are usually listed.
2046 errno
= WSAGetLastError();
2049 /* convert into a file descriptor */
2050 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2052 return error("unable to make a socket file descriptor: %s",
2059 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2061 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2062 return connect(s
, sa
, sz
);
2066 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2068 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2069 return bind(s
, sa
, sz
);
2073 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2075 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2076 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2080 int mingw_shutdown(int sockfd
, int how
)
2082 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2083 return shutdown(s
, how
);
2087 int mingw_listen(int sockfd
, int backlog
)
2089 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2090 return listen(s
, backlog
);
2094 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2098 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2099 SOCKET s2
= accept(s1
, sa
, sz
);
2101 /* convert into a file descriptor */
2102 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2105 return error("unable to make a socket file descriptor: %s",
2112 int mingw_rename(const char *pold
, const char *pnew
)
2116 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2117 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2121 * Try native rename() first to get errno right.
2122 * It is based on MoveFile(), which cannot overwrite existing files.
2124 if (!_wrename(wpold
, wpnew
))
2126 if (errno
!= EEXIST
)
2129 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2131 /* TODO: translate more errors */
2132 gle
= GetLastError();
2133 if (gle
== ERROR_ACCESS_DENIED
&&
2134 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2135 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2136 DWORD attrsold
= GetFileAttributesW(wpold
);
2137 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2138 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2140 else if (!_wrmdir(wpnew
))
2144 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2145 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2146 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2148 gle
= GetLastError();
2149 /* revert file attributes on failure */
2150 SetFileAttributesW(wpnew
, attrs
);
2153 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2155 * We assume that some other process had the source or
2156 * destination file open at the wrong moment and retry.
2157 * In order to give the other process a higher chance to
2158 * complete its operation, we give up our time slice now.
2159 * If we have to retry again, we do sleep a bit.
2161 Sleep(delay
[tries
]);
2165 if (gle
== ERROR_ACCESS_DENIED
&&
2166 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2167 "Should I try again?", pold
, pnew
))
2175 * Note that this doesn't return the actual pagesize, but
2176 * the allocation granularity. If future Windows specific git code
2177 * needs the real getpagesize function, we need to find another solution.
2179 int mingw_getpagesize(void)
2183 return si
.dwAllocationGranularity
;
2186 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2187 enum EXTENDED_NAME_FORMAT
{
2189 NameUserPrincipal
= 8
2192 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2194 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2195 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2196 static wchar_t wbuffer
[1024];
2199 if (!INIT_PROC_ADDR(GetUserNameExW
))
2202 len
= ARRAY_SIZE(wbuffer
);
2203 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2204 char *converted
= xmalloc((len
*= 3));
2205 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2213 char *mingw_query_user_email(void)
2215 return get_extended_user_info(NameUserPrincipal
);
2218 struct passwd
*getpwuid(int uid
)
2220 static unsigned initialized
;
2221 static char user_name
[100];
2222 static struct passwd
*p
;
2229 len
= ARRAY_SIZE(buf
);
2230 if (!GetUserNameW(buf
, &len
)) {
2235 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2240 p
= xmalloc(sizeof(*p
));
2241 p
->pw_name
= user_name
;
2242 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2244 p
->pw_gecos
= "unknown";
2251 static HANDLE timer_event
;
2252 static HANDLE timer_thread
;
2253 static int timer_interval
;
2254 static int one_shot
;
2255 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2257 /* The timer works like this:
2258 * The thread, ticktack(), is a trivial routine that most of the time
2259 * only waits to receive the signal to terminate. The main thread tells
2260 * the thread to terminate by setting the timer_event to the signalled
2262 * But ticktack() interrupts the wait state after the timer's interval
2263 * length to call the signal handler.
2266 static unsigned __stdcall
ticktack(void *dummy
)
2268 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2269 mingw_raise(SIGALRM
);
2276 static int start_timer_thread(void)
2278 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2280 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2282 return errno
= ENOMEM
,
2283 error("cannot start timer thread");
2285 return errno
= ENOMEM
,
2286 error("cannot allocate resources for timer");
2290 static void stop_timer_thread(void)
2293 SetEvent(timer_event
); /* tell thread to terminate */
2295 int rc
= WaitForSingleObject(timer_thread
, 10000);
2296 if (rc
== WAIT_TIMEOUT
)
2297 error("timer thread did not terminate timely");
2298 else if (rc
!= WAIT_OBJECT_0
)
2299 error("waiting for timer thread failed: %lu",
2301 CloseHandle(timer_thread
);
2304 CloseHandle(timer_event
);
2306 timer_thread
= NULL
;
2309 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2311 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2314 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2316 static const struct timeval zero
;
2317 static int atexit_done
;
2320 return errno
= EINVAL
,
2321 error("setitimer param 3 != NULL not implemented");
2322 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2323 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2324 return errno
= EINVAL
,
2325 error("setitimer: it_interval must be zero or eq it_value");
2328 stop_timer_thread();
2330 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2331 is_timeval_eq(&in
->it_interval
, &zero
))
2334 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2335 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2337 atexit(stop_timer_thread
);
2340 return start_timer_thread();
2343 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2346 return errno
= EINVAL
,
2347 error("sigaction only implemented for SIGALRM");
2349 return errno
= EINVAL
,
2350 error("sigaction: param 3 != NULL not implemented");
2352 timer_fn
= in
->sa_handler
;
2357 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2369 sigint_fn
= handler
;
2373 return signal(sig
, handler
);
2380 int mingw_raise(int sig
)
2384 if (timer_fn
== SIG_DFL
) {
2385 if (isatty(STDERR_FILENO
))
2386 fputs("Alarm clock\n", stderr
);
2387 exit(128 + SIGALRM
);
2388 } else if (timer_fn
!= SIG_IGN
)
2393 if (sigint_fn
== SIG_DFL
)
2395 else if (sigint_fn
!= SIG_IGN
)
2399 #if defined(_MSC_VER)
2406 case SIGABRT_COMPAT
:
2408 * The <signal.h> header in the MS C Runtime defines 8 signals
2409 * as being supported on the platform. Anything else causes an
2410 * "Invalid signal or error" (which in DEBUG builds causes the
2411 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2412 * already know will fail.
2429 int link(const char *oldpath
, const char *newpath
)
2431 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2432 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2433 xutftowcs_path(wnewpath
, newpath
) < 0)
2436 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2437 errno
= err_win_to_posix(GetLastError());
2443 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2445 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2452 if (pid
> 0 && options
& WNOHANG
) {
2453 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2457 options
&= ~WNOHANG
;
2461 struct pinfo_t
**ppinfo
;
2462 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2468 GetExitCodeProcess(h
, (LPDWORD
)status
);
2470 EnterCriticalSection(&pinfo_cs
);
2474 struct pinfo_t
*info
= *ppinfo
;
2475 if (info
->pid
== pid
) {
2476 CloseHandle(info
->proc
);
2477 *ppinfo
= info
->next
;
2481 ppinfo
= &info
->next
;
2484 LeaveCriticalSection(&pinfo_cs
);
2495 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2497 int upos
= 0, wpos
= 0;
2498 const unsigned char *utf
= (const unsigned char*) utfs
;
2499 if (!utf
|| !wcs
|| wcslen
< 1) {
2503 /* reserve space for \0 */
2508 while (upos
< utflen
) {
2509 int c
= utf
[upos
++] & 0xff;
2510 if (utflen
== INT_MAX
&& c
== 0)
2513 if (wpos
>= wcslen
) {
2522 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2523 (utf
[upos
] & 0xc0) == 0x80) {
2525 c
= ((c
& 0x1f) << 6);
2526 c
|= (utf
[upos
++] & 0x3f);
2528 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2529 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2530 (utf
[upos
] & 0xc0) == 0x80 &&
2531 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2533 c
= ((c
& 0x0f) << 12);
2534 c
|= ((utf
[upos
++] & 0x3f) << 6);
2535 c
|= (utf
[upos
++] & 0x3f);
2537 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2538 wpos
+ 1 < wcslen
&&
2539 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2540 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2541 (utf
[upos
] & 0xc0) == 0x80 &&
2542 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2543 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2544 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2545 c
= ((c
& 0x07) << 18);
2546 c
|= ((utf
[upos
++] & 0x3f) << 12);
2547 c
|= ((utf
[upos
++] & 0x3f) << 6);
2548 c
|= (utf
[upos
++] & 0x3f);
2550 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2551 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2552 } else if (c
>= 0xa0) {
2553 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2556 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2557 static const char *hex
= "0123456789abcdef";
2558 wcs
[wpos
++] = hex
[c
>> 4];
2560 wcs
[wpos
++] = hex
[c
& 0x0f];
2567 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2569 if (!wcs
|| !utf
|| utflen
< 1) {
2573 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2580 static void setup_windows_environment(void)
2582 char *tmp
= getenv("TMPDIR");
2584 /* on Windows it is TMP and TEMP */
2586 if (!(tmp
= getenv("TMP")))
2587 tmp
= getenv("TEMP");
2589 setenv("TMPDIR", tmp
, 1);
2590 tmp
= getenv("TMPDIR");
2596 * Convert all dir separators to forward slashes,
2597 * to help shell commands called from the Git
2598 * executable (by not mistaking the dir separators
2599 * for escape characters).
2601 convert_slashes(tmp
);
2604 /* simulate TERM to enable auto-color (see color.c) */
2605 if (!getenv("TERM"))
2606 setenv("TERM", "cygwin", 1);
2608 /* calculate HOME if not set */
2609 if (!getenv("HOME")) {
2611 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2612 * location, thus also check if the path exists (i.e. is not
2615 if ((tmp
= getenv("HOMEDRIVE"))) {
2616 struct strbuf buf
= STRBUF_INIT
;
2617 strbuf_addstr(&buf
, tmp
);
2618 if ((tmp
= getenv("HOMEPATH"))) {
2619 strbuf_addstr(&buf
, tmp
);
2620 if (is_directory(buf
.buf
))
2621 setenv("HOME", buf
.buf
, 1);
2623 tmp
= NULL
; /* use $USERPROFILE */
2625 strbuf_release(&buf
);
2627 /* use $USERPROFILE if the home share is not available */
2628 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2629 setenv("HOME", tmp
, 1);
2633 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2635 const char *p
= path
;
2636 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2641 skip_dos_drive_prefix((char **)&path
);
2648 case '/': case '\\':
2649 /* cannot end in ` ` or `.`, except for `.` and `..` */
2650 if (preceding_space_or_period
&&
2651 (i
!= periods
|| periods
> 2))
2656 i
= periods
= preceding_space_or_period
= 0;
2660 case 'a': case 'A': /* AUX */
2661 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2662 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2663 not_a_reserved_name
:
2669 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2670 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2671 goto not_a_reserved_name
;
2673 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2675 if (c
< '1' || c
> '9')
2676 goto not_a_reserved_name
;
2677 } else if (c
== 'n' || c
== 'N') { /* CON */
2679 if ((c
== 'i' || c
== 'I') &&
2680 ((c
= path
[i
+ 2]) == 'n' ||
2683 i
+= 3; /* CONIN$ */
2684 else if ((c
== 'o' || c
== 'O') &&
2685 ((c
= path
[i
+ 2]) == 'u' ||
2687 ((c
= path
[i
+ 3]) == 't' ||
2690 i
+= 4; /* CONOUT$ */
2692 goto not_a_reserved_name
;
2694 case 'l': case 'L': /* LPT<N> */
2695 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2696 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2697 !isdigit(path
[++i
]))
2698 goto not_a_reserved_name
;
2700 case 'n': case 'N': /* NUL */
2701 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2702 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2703 (allow_literal_nul
&&
2704 !path
[i
+ 1] && p
== path
))
2705 goto not_a_reserved_name
;
2707 case 'p': case 'P': /* PRN */
2708 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2709 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2710 goto not_a_reserved_name
;
2717 * So far, this looks like a reserved name. Let's see
2718 * whether it actually is one: trailing spaces, a file
2719 * extension, or an NTFS Alternate Data Stream do not
2720 * matter, the name is still reserved if any of those
2721 * follow immediately after the actual name.
2724 if (path
[i
] == ' ') {
2725 preceding_space_or_period
= 1;
2726 while (path
[++i
] == ' ')
2727 ; /* skip all spaces */
2731 if (c
&& c
!= '.' && c
!= ':' && c
!= '/' && c
!= '\\')
2732 goto not_a_reserved_name
;
2734 /* contains reserved name */
2740 preceding_space_or_period
= 1;
2743 case ':': /* DOS drive prefix was already skipped */
2744 case '<': case '>': case '"': case '|': case '?': case '*':
2745 /* illegal character */
2748 if (c
> '\0' && c
< '\x20')
2749 /* illegal character */
2752 preceding_space_or_period
= 0;
2757 #if !defined(_MSC_VER)
2759 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2760 * mingw startup code, see init.c in mingw runtime).
2765 static NORETURN
void die_startup(void)
2767 fputs("fatal: not enough memory for initialization", stderr
);
2771 static void *malloc_startup(size_t size
)
2773 void *result
= malloc(size
);
2779 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2781 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2782 return memcpy(malloc_startup(len
), buffer
, len
);
2785 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2786 DWORD desired_access
, DWORD flags
)
2788 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2789 wchar_t buf
[MAX_PATH
];
2790 DWORD max
= ARRAY_SIZE(buf
);
2792 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2794 if (!ret
|| ret
>= max
)
2797 /* make sure this does not leak into child processes */
2798 SetEnvironmentVariableW(key
, NULL
);
2799 if (!wcscmp(buf
, L
"off")) {
2801 handle
= GetStdHandle(std_id
);
2802 if (handle
!= INVALID_HANDLE_VALUE
)
2803 CloseHandle(handle
);
2806 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2807 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2808 if (handle
== INVALID_HANDLE_VALUE
) {
2810 handle
= GetStdHandle(std_id
);
2811 if (handle
!= INVALID_HANDLE_VALUE
)
2812 CloseHandle(handle
);
2814 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2815 SetStdHandle(std_id
, handle
);
2817 /* do *not* close the new_fd: that would close stdout */
2821 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2823 if (handle
!= INVALID_HANDLE_VALUE
) {
2824 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2825 SetStdHandle(std_id
, handle
);
2831 static void maybe_redirect_std_handles(void)
2833 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2834 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2835 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2836 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2837 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2838 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2848 * We implement wmain() and compile with -municode, which would
2849 * normally ignore main(), but we call the latter from the former
2850 * so that we can handle non-ASCII command-line parameters
2853 * To be more compatible with the core git code, we convert
2854 * argv into UTF8 and pass them directly to main().
2856 int wmain(int argc
, const wchar_t **wargv
)
2858 int i
, maxlen
, exit_status
;
2859 char *buffer
, **save
;
2862 trace2_initialize_clock();
2866 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
2869 #ifdef USE_MSVC_CRTDBG
2870 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
2874 maybe_redirect_std_handles();
2876 /* determine size of argv and environ conversion buffer */
2877 maxlen
= wcslen(wargv
[0]);
2878 for (i
= 1; i
< argc
; i
++)
2879 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2881 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2882 maxlen
= 3 * maxlen
+ 1;
2883 buffer
= malloc_startup(maxlen
);
2886 * Create a UTF-8 version of w_argv. Also create a "save" copy
2887 * to remember all the string pointers because parse_options()
2888 * will remove claimed items from the argv that we pass down.
2890 ALLOC_ARRAY(argv
, argc
+ 1);
2891 ALLOC_ARRAY(save
, argc
+ 1);
2892 for (i
= 0; i
< argc
; i
++)
2893 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2894 argv
[i
] = save
[i
] = NULL
;
2897 /* fix Windows specific environment settings */
2898 setup_windows_environment();
2900 unset_environment_variables
= xstrdup("PERL5LIB");
2902 /* initialize critical section for waitpid pinfo_t list */
2903 InitializeCriticalSection(&pinfo_cs
);
2905 /* set up default file mode and file modes for stdin/out/err */
2907 _setmode(_fileno(stdin
), _O_BINARY
);
2908 _setmode(_fileno(stdout
), _O_BINARY
);
2909 _setmode(_fileno(stderr
), _O_BINARY
);
2911 /* initialize Unicode console */
2914 /* invoke the real main() using our utf8 version of argv. */
2915 exit_status
= main(argc
, argv
);
2917 for (i
= 0; i
< argc
; i
++)
2925 int uname(struct utsname
*buf
)
2927 unsigned v
= (unsigned)GetVersion();
2928 memset(buf
, 0, sizeof(*buf
));
2929 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
2930 xsnprintf(buf
->release
, sizeof(buf
->release
),
2931 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
2932 /* assuming NT variants only.. */
2933 xsnprintf(buf
->version
, sizeof(buf
->version
),
2934 "%u", (v
>> 16) & 0x7fff);