1 #include "../git-compat-util.h"
7 #include "../run-command.h"
9 #include "win32/lazyload.h"
10 #include "../config.h"
13 #define HCAST(type, handle) ((type)(intptr_t)handle)
15 static const int delay
[] = { 0, 1, 10, 20, 40 };
17 void open_in_gdb(void)
19 static struct child_process cp
= CHILD_PROCESS_INIT
;
22 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
23 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
25 if (start_command(&cp
) < 0)
26 die_errno("Could not start gdb");
30 int err_win_to_posix(DWORD winerr
)
34 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
35 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
36 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
37 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
38 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
39 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
40 case ERROR_BAD_COMMAND
: error
= EIO
; break;
41 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
42 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
43 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
44 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
45 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
46 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
47 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
48 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
49 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
50 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
51 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
52 case ERROR_BUSY
: error
= EBUSY
; break;
53 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
54 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
55 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
56 case ERROR_CANTOPEN
: error
= EIO
; break;
57 case ERROR_CANTREAD
: error
= EIO
; break;
58 case ERROR_CANTWRITE
: error
= EIO
; break;
59 case ERROR_CRC
: error
= EIO
; break;
60 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
61 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
62 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
63 case ERROR_DIRECTORY
: error
= EINVAL
; break;
64 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
65 case ERROR_DISK_CHANGE
: error
= EIO
; break;
66 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
67 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
68 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
69 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
70 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
71 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
72 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
73 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
74 case ERROR_GEN_FAILURE
: error
= EIO
; break;
75 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
76 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
77 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
78 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
79 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
80 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
81 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
82 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
83 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
84 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
85 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
86 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
87 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
88 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
89 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
90 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
91 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
92 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
93 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
94 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
95 case ERROR_IO_DEVICE
: error
= EIO
; break;
96 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
97 case ERROR_LOCKED
: error
= EBUSY
; break;
98 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
99 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
100 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
101 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
102 case ERROR_MORE_DATA
: error
= EPIPE
; break;
103 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
104 case ERROR_NOACCESS
: error
= EFAULT
; break;
105 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
106 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
107 case ERROR_NOT_READY
: error
= EAGAIN
; break;
108 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
109 case ERROR_NO_DATA
: error
= EPIPE
; break;
110 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
111 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
112 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
113 case ERROR_OPEN_FAILED
: error
= EIO
; break;
114 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
115 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
116 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
117 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
118 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
119 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
120 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
121 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
122 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
123 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
124 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
125 case ERROR_READ_FAULT
: error
= EIO
; break;
126 case ERROR_SEEK
: error
= EIO
; break;
127 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
128 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
129 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
130 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
131 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
132 case ERROR_SWAPERROR
: error
= ENOENT
; break;
133 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
134 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
135 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
136 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
137 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
138 case ERROR_WRITE_FAULT
: error
= EIO
; break;
139 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
144 static inline int is_file_in_use_error(DWORD errcode
)
147 case ERROR_SHARING_VIOLATION
:
148 case ERROR_ACCESS_DENIED
:
155 static int read_yes_no_answer(void)
159 if (fgets(answer
, sizeof(answer
), stdin
)) {
160 size_t answer_len
= strlen(answer
);
161 int got_full_line
= 0, c
;
163 /* remove the newline */
164 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
165 answer
[answer_len
-2] = '\0';
167 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
168 answer
[answer_len
-1] = '\0';
171 /* flush the buffer in case we did not get the full line */
173 while ((c
= getchar()) != EOF
&& c
!= '\n')
176 /* we could not read, return the
177 * default answer which is no */
180 if (tolower(answer
[0]) == 'y' && !answer
[1])
182 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
184 if (tolower(answer
[0]) == 'n' && !answer
[1])
186 if (!strncasecmp(answer
, "no", sizeof(answer
)))
189 /* did not find an answer we understand */
193 static int ask_yes_no_if_possible(const char *format
, ...)
196 const char *retry_hook
[] = { NULL
, NULL
, NULL
};
199 va_start(args
, format
);
200 vsnprintf(question
, sizeof(question
), format
, args
);
203 if ((retry_hook
[0] = mingw_getenv("GIT_ASK_YESNO"))) {
204 retry_hook
[1] = question
;
205 return !run_command_v_opt(retry_hook
, 0);
208 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
213 fprintf(stderr
, "%s (y/n) ", question
);
215 if ((answer
= read_yes_no_answer()) >= 0)
218 fprintf(stderr
, "Sorry, I did not understand your answer. "
219 "Please type 'y' or 'n'\n");
224 enum hide_dotfiles_type
{
225 HIDE_DOTFILES_FALSE
= 0,
227 HIDE_DOTFILES_DOTGITONLY
230 static int core_restrict_inherited_handles
= -1;
231 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
232 static char *unset_environment_variables
;
234 int mingw_core_config(const char *var
, const char *value
, void *cb
)
236 if (!strcmp(var
, "core.hidedotfiles")) {
237 if (value
&& !strcasecmp(value
, "dotgitonly"))
238 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
240 hide_dotfiles
= git_config_bool(var
, value
);
244 if (!strcmp(var
, "core.unsetenvvars")) {
245 free(unset_environment_variables
);
246 unset_environment_variables
= xstrdup(value
);
250 if (!strcmp(var
, "core.restrictinheritedhandles")) {
251 if (value
&& !strcasecmp(value
, "auto"))
252 core_restrict_inherited_handles
= -1;
254 core_restrict_inherited_handles
=
255 git_config_bool(var
, value
);
262 /* Normalizes NT paths as returned by some low-level APIs. */
263 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
266 /* fix absolute path prefixes */
267 if (wbuf
[0] == '\\') {
268 /* strip NT namespace prefixes */
269 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
270 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
272 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
274 /* replace remaining '...UNC\' with '\\' */
275 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
280 /* convert backslashes to slashes */
281 for (i
= 0; wbuf
[i
]; i
++)
287 int mingw_unlink(const char *pathname
)
290 wchar_t wpathname
[MAX_PATH
];
291 if (xutftowcs_path(wpathname
, pathname
) < 0)
294 if (DeleteFileW(wpathname
))
297 /* read-only files cannot be removed */
298 _wchmod(wpathname
, 0666);
299 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
300 if (!is_file_in_use_error(GetLastError()))
303 * We assume that some other process had the source or
304 * destination file open at the wrong moment and retry.
305 * In order to give the other process a higher chance to
306 * complete its operation, we give up our time slice now.
307 * If we have to retry again, we do sleep a bit.
312 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
313 ask_yes_no_if_possible("Unlink of file '%s' failed. "
314 "Should I try again?", pathname
))
315 ret
= _wunlink(wpathname
);
319 static int is_dir_empty(const wchar_t *wpath
)
321 WIN32_FIND_DATAW findbuf
;
323 wchar_t wbuf
[MAX_PATH
+ 2];
325 wcscat(wbuf
, L
"\\*");
326 handle
= FindFirstFileW(wbuf
, &findbuf
);
327 if (handle
== INVALID_HANDLE_VALUE
)
328 return GetLastError() == ERROR_NO_MORE_FILES
;
330 while (!wcscmp(findbuf
.cFileName
, L
".") ||
331 !wcscmp(findbuf
.cFileName
, L
".."))
332 if (!FindNextFileW(handle
, &findbuf
)) {
333 DWORD err
= GetLastError();
335 return err
== ERROR_NO_MORE_FILES
;
341 int mingw_rmdir(const char *pathname
)
344 wchar_t wpathname
[MAX_PATH
];
345 if (xutftowcs_path(wpathname
, pathname
) < 0)
348 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
349 if (!is_file_in_use_error(GetLastError()))
350 errno
= err_win_to_posix(GetLastError());
353 if (!is_dir_empty(wpathname
)) {
358 * We assume that some other process had the source or
359 * destination file open at the wrong moment and retry.
360 * In order to give the other process a higher chance to
361 * complete its operation, we give up our time slice now.
362 * If we have to retry again, we do sleep a bit.
367 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
368 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
369 "Should I try again?", pathname
))
370 ret
= _wrmdir(wpathname
);
372 invalidate_lstat_cache();
376 static inline int needs_hiding(const char *path
)
378 const char *basename
;
380 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
383 /* We cannot use basename(), as it would remove trailing slashes */
384 win32_skip_dos_drive_prefix((char **)&path
);
388 for (basename
= path
; *path
; path
++)
389 if (is_dir_sep(*path
)) {
392 } while (is_dir_sep(*path
));
393 /* ignore trailing slashes */
400 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
401 return *basename
== '.';
403 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
404 return !strncasecmp(".git", basename
, 4) &&
405 (!basename
[4] || is_dir_sep(basename
[4]));
408 static int set_hidden_flag(const wchar_t *path
, int set
)
410 DWORD original
= GetFileAttributesW(path
), modified
;
412 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
414 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
415 if (original
== modified
|| SetFileAttributesW(path
, modified
))
417 errno
= err_win_to_posix(GetLastError());
421 int mingw_mkdir(const char *path
, int mode
)
424 wchar_t wpath
[MAX_PATH
];
426 if (!is_valid_win32_path(path
, 0)) {
431 if (xutftowcs_path(wpath
, path
) < 0)
433 ret
= _wmkdir(wpath
);
434 if (!ret
&& needs_hiding(path
))
435 return set_hidden_flag(wpath
, 1);
440 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
441 * is documented in [1] as opening a writable file handle in append mode.
442 * (It is believed that) this is atomic since it is maintained by the
443 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
445 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
447 * This trick does not appear to work for named pipes. Instead it creates
448 * a named pipe client handle that cannot be written to. Callers should
449 * just use the regular _wopen() for them. (And since client handle gets
450 * bound to a unique server handle, it isn't really an issue.)
452 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
456 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
458 /* only these flags are supported */
459 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
460 return errno
= ENOSYS
, -1;
463 * FILE_SHARE_WRITE is required to permit child processes
464 * to append to the file.
466 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
467 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
468 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
469 if (handle
== INVALID_HANDLE_VALUE
) {
470 DWORD err
= GetLastError();
473 * Some network storage solutions (e.g. Isilon) might return
474 * ERROR_INVALID_PARAMETER instead of expected error
475 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
476 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
478 if (err
== ERROR_INVALID_PARAMETER
)
479 err
= ERROR_PATH_NOT_FOUND
;
481 errno
= err_win_to_posix(err
);
486 * No O_APPEND here, because the CRT uses it only to reset the
487 * file pointer to EOF before each write(); but that is not
488 * necessary (and may lead to races) for a file created with
491 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
498 * Does the pathname map to the local named pipe filesystem?
499 * That is, does it have a "//./pipe/" prefix?
501 static int is_local_named_pipe_path(const char *filename
)
503 return (is_dir_sep(filename
[0]) &&
504 is_dir_sep(filename
[1]) &&
505 filename
[2] == '.' &&
506 is_dir_sep(filename
[3]) &&
507 !strncasecmp(filename
+4, "pipe", 4) &&
508 is_dir_sep(filename
[8]) &&
512 int mingw_open (const char *filename
, int oflags
, ...)
514 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
517 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
518 wchar_t wfilename
[MAX_PATH
];
521 va_start(args
, oflags
);
522 mode
= va_arg(args
, int);
525 if (!is_valid_win32_path(filename
, !create
)) {
526 errno
= create
? EINVAL
: ENOENT
;
530 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
531 open_fn
= mingw_open_append
;
535 if (filename
&& !strcmp(filename
, "/dev/null"))
536 wcscpy(wfilename
, L
"nul");
537 else if (xutftowcs_path(wfilename
, filename
) < 0)
540 fd
= open_fn(wfilename
, oflags
, mode
);
542 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
543 DWORD attrs
= GetFileAttributesW(wfilename
);
544 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
547 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
549 * Internally, _wopen() uses the CreateFile() API which errors
550 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
551 * specified and an already existing file's attributes do not
552 * match *exactly*. As there is no mode or flag we can set that
553 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
554 * again *without* the O_CREAT flag (that corresponds to the
555 * CREATE_ALWAYS flag of CreateFile()).
557 if (fd
< 0 && errno
== EACCES
)
558 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
559 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
560 warning("could not mark '%s' as hidden.", filename
);
565 static BOOL WINAPI
ctrl_ignore(DWORD type
)
571 int mingw_fgetc(FILE *stream
)
574 if (!isatty(_fileno(stream
)))
575 return fgetc(stream
);
577 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
580 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
583 /* Ctrl+C was pressed, simulate SIGINT and retry */
586 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
591 FILE *mingw_fopen (const char *filename
, const char *otype
)
593 int hide
= needs_hiding(filename
);
595 wchar_t wfilename
[MAX_PATH
], wotype
[4];
596 if (filename
&& !strcmp(filename
, "/dev/null"))
597 wcscpy(wfilename
, L
"nul");
598 else if (!is_valid_win32_path(filename
, 1)) {
599 int create
= otype
&& strchr(otype
, 'w');
600 errno
= create
? EINVAL
: ENOENT
;
602 } else if (xutftowcs_path(wfilename
, filename
) < 0)
605 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
608 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
609 error("could not unhide %s", filename
);
612 file
= _wfopen(wfilename
, wotype
);
613 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
615 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
616 warning("could not mark '%s' as hidden.", filename
);
620 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
622 int hide
= needs_hiding(filename
);
624 wchar_t wfilename
[MAX_PATH
], wotype
[4];
625 if (filename
&& !strcmp(filename
, "/dev/null"))
626 wcscpy(wfilename
, L
"nul");
627 else if (!is_valid_win32_path(filename
, 1)) {
628 int create
= otype
&& strchr(otype
, 'w');
629 errno
= create
? EINVAL
: ENOENT
;
631 } else if (xutftowcs_path(wfilename
, filename
) < 0)
634 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
637 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
638 error("could not unhide %s", filename
);
641 file
= _wfreopen(wfilename
, wotype
, stream
);
642 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
643 warning("could not mark '%s' as hidden.", filename
);
648 int mingw_fflush(FILE *stream
)
650 int ret
= fflush(stream
);
653 * write() is used behind the scenes of stdio output functions.
654 * Since git code does not check for errors after each stdio write
655 * operation, it can happen that write() is called by a later
656 * stdio function even if an earlier write() call failed. In the
657 * case of a pipe whose readable end was closed, only the first
658 * call to write() reports EPIPE on Windows. Subsequent write()
659 * calls report EINVAL. It is impossible to notice whether this
660 * fflush invocation triggered such a case, therefore, we have to
661 * catch all EINVAL errors whole-sale.
663 if (ret
&& errno
== EINVAL
)
670 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
672 ssize_t result
= write(fd
, buf
, len
);
674 if (result
< 0 && errno
== EINVAL
&& buf
) {
675 /* check if fd is a pipe */
676 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
677 if (GetFileType(h
) == FILE_TYPE_PIPE
)
686 int mingw_access(const char *filename
, int mode
)
688 wchar_t wfilename
[MAX_PATH
];
689 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
691 if (xutftowcs_path(wfilename
, filename
) < 0)
693 /* X_OK is not supported by the MSVCRT version */
694 return _waccess(wfilename
, mode
& ~X_OK
);
697 int mingw_chdir(const char *dirname
)
699 wchar_t wdirname
[MAX_PATH
];
700 if (xutftowcs_path(wdirname
, dirname
) < 0)
702 return _wchdir(wdirname
);
705 int mingw_chmod(const char *filename
, int mode
)
707 wchar_t wfilename
[MAX_PATH
];
708 if (xutftowcs_path(wfilename
, filename
) < 0)
710 return _wchmod(wfilename
, mode
);
714 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
715 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
717 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
719 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
720 /* Windows to Unix Epoch conversion */
721 return winTime
- 116444736000000000LL;
724 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
726 long long hnsec
= filetime_to_hnsec(ft
);
727 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
728 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
732 * Verifies that safe_create_leading_directories() would succeed.
734 static int has_valid_directory_prefix(wchar_t *wfilename
)
736 int n
= wcslen(wfilename
);
739 wchar_t c
= wfilename
[--n
];
745 wfilename
[n
] = L
'\0';
746 attributes
= GetFileAttributesW(wfilename
);
748 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
749 attributes
== FILE_ATTRIBUTE_DEVICE
)
751 if (attributes
== INVALID_FILE_ATTRIBUTES
)
752 switch (GetLastError()) {
753 case ERROR_PATH_NOT_FOUND
:
755 case ERROR_FILE_NOT_FOUND
:
756 /* This implies parent directory exists. */
764 /* We keep the do_lstat code in a separate function to avoid recursion.
765 * When a path ends with a slash, the stat will fail with ENOENT. In
766 * this case, we strip the trailing slashes and stat again.
768 * If follow is true then act like stat() and report on the link
769 * target. Otherwise report on the link itself.
771 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
773 WIN32_FILE_ATTRIBUTE_DATA fdata
;
774 wchar_t wfilename
[MAX_PATH
];
775 if (xutftowcs_path(wfilename
, file_name
) < 0)
778 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
783 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
784 buf
->st_size
= fdata
.nFileSizeLow
|
785 (((off_t
)fdata
.nFileSizeHigh
)<<32);
786 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
787 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
788 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
789 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
790 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
791 WIN32_FIND_DATAW findbuf
;
792 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
793 if (handle
!= INVALID_HANDLE_VALUE
) {
794 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
795 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
797 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
798 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
800 buf
->st_mode
= S_IFLNK
;
802 buf
->st_mode
|= S_IREAD
;
803 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
804 buf
->st_mode
|= S_IWRITE
;
811 switch (GetLastError()) {
812 case ERROR_ACCESS_DENIED
:
813 case ERROR_SHARING_VIOLATION
:
814 case ERROR_LOCK_VIOLATION
:
815 case ERROR_SHARING_BUFFER_EXCEEDED
:
818 case ERROR_BUFFER_OVERFLOW
:
819 errno
= ENAMETOOLONG
;
821 case ERROR_NOT_ENOUGH_MEMORY
:
824 case ERROR_PATH_NOT_FOUND
:
825 if (!has_valid_directory_prefix(wfilename
)) {
837 /* We provide our own lstat/fstat functions, since the provided
838 * lstat/fstat functions are so slow. These stat functions are
839 * tailored for Git's usage (read: fast), and are not meant to be
840 * complete. Note that Git stat()s are redirected to mingw_lstat()
841 * too, since Windows doesn't really handle symlinks that well.
843 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
846 char alt_name
[PATH_MAX
];
848 if (!do_lstat(follow
, file_name
, buf
))
851 /* if file_name ended in a '/', Windows returned ENOENT;
852 * try again without trailing slashes
857 namelen
= strlen(file_name
);
858 if (namelen
&& file_name
[namelen
-1] != '/')
860 while (namelen
&& file_name
[namelen
-1] == '/')
862 if (!namelen
|| namelen
>= PATH_MAX
)
865 memcpy(alt_name
, file_name
, namelen
);
866 alt_name
[namelen
] = 0;
867 return do_lstat(follow
, alt_name
, buf
);
870 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
872 BY_HANDLE_FILE_INFORMATION fdata
;
874 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
875 errno
= err_win_to_posix(GetLastError());
883 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
884 buf
->st_size
= fdata
.nFileSizeLow
|
885 (((off_t
)fdata
.nFileSizeHigh
)<<32);
886 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
887 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
888 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
889 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
893 int mingw_lstat(const char *file_name
, struct stat
*buf
)
895 return do_stat_internal(0, file_name
, buf
);
897 int mingw_stat(const char *file_name
, struct stat
*buf
)
899 return do_stat_internal(1, file_name
, buf
);
902 int mingw_fstat(int fd
, struct stat
*buf
)
904 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
905 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
909 return get_file_info_by_handle(fh
, buf
);
913 /* initialize stat fields */
914 memset(buf
, 0, sizeof(*buf
));
917 if (type
== FILE_TYPE_CHAR
) {
918 buf
->st_mode
= _S_IFCHR
;
920 buf
->st_mode
= _S_IFIFO
;
921 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
922 buf
->st_size
= avail
;
932 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
934 long long winTime
= t
* 10000000LL + 116444736000000000LL;
935 ft
->dwLowDateTime
= winTime
;
936 ft
->dwHighDateTime
= winTime
>> 32;
939 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
944 wchar_t wfilename
[MAX_PATH
];
945 if (xutftowcs_path(wfilename
, file_name
) < 0)
948 /* must have write permission */
949 attrs
= GetFileAttributesW(wfilename
);
950 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
951 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
952 /* ignore errors here; open() will report them */
953 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
956 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
962 time_t_to_filetime(times
->modtime
, &mft
);
963 time_t_to_filetime(times
->actime
, &aft
);
965 GetSystemTimeAsFileTime(&mft
);
968 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
976 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
977 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
978 /* ignore errors again */
979 SetFileAttributesW(wfilename
, attrs
);
985 size_t mingw_strftime(char *s
, size_t max
,
986 const char *format
, const struct tm
*tm
)
988 /* a pointer to the original strftime in case we can't find the UCRT version */
989 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
991 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, strftime
, char *, size_t,
992 const char *, const struct tm
*);
994 if (INIT_PROC_ADDR(strftime
))
995 ret
= strftime(s
, max
, format
, tm
);
997 ret
= fallback(s
, max
, format
, tm
);
999 if (!ret
&& errno
== EINVAL
)
1000 die("invalid strftime format: '%s'", format
);
1004 unsigned int sleep (unsigned int seconds
)
1006 Sleep(seconds
*1000);
1010 char *mingw_mktemp(char *template)
1012 wchar_t wtemplate
[MAX_PATH
];
1013 if (xutftowcs_path(wtemplate
, template) < 0)
1015 if (!_wmktemp(wtemplate
))
1017 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1022 int mkstemp(char *template)
1024 char *filename
= mktemp(template);
1025 if (filename
== NULL
)
1027 return open(filename
, O_RDWR
| O_CREAT
, 0600);
1030 int gettimeofday(struct timeval
*tv
, void *tz
)
1035 GetSystemTimeAsFileTime(&ft
);
1036 hnsec
= filetime_to_hnsec(&ft
);
1037 tv
->tv_sec
= hnsec
/ 10000000;
1038 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1042 int pipe(int filedes
[2])
1046 /* this creates non-inheritable handles */
1047 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1048 errno
= err_win_to_posix(GetLastError());
1051 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1052 if (filedes
[0] < 0) {
1057 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1058 if (filedes
[1] < 0) {
1067 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1069 if (gmtime_s(result
, timep
) == 0)
1074 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1076 if (localtime_s(result
, timep
) == 0)
1082 char *mingw_getcwd(char *pointer
, int len
)
1084 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1085 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1087 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1088 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1091 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1092 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1093 HANDLE hnd
= CreateFileW(cwd
, 0,
1094 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1095 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1096 if (hnd
== INVALID_HANDLE_VALUE
)
1098 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1100 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1102 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1106 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1108 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1110 convert_slashes(pointer
);
1115 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1116 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1118 static const char *quote_arg_msvc(const char *arg
)
1120 /* count chars to quote */
1122 int force_quotes
= 0;
1124 const char *p
= arg
;
1125 if (!*p
) force_quotes
= 1;
1127 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1131 else if (*p
== '\\') {
1133 while (*p
== '\\') {
1138 if (*p
== '"' || !*p
)
1145 if (!force_quotes
&& n
== 0)
1148 /* insert \ where necessary */
1149 d
= q
= xmalloc(st_add3(len
, n
, 3));
1154 else if (*arg
== '\\') {
1156 while (*arg
== '\\') {
1160 if (*arg
== '"' || !*arg
) {
1163 /* don't escape the surrounding end quote */
1178 static const char *quote_arg_msys2(const char *arg
)
1180 struct strbuf buf
= STRBUF_INIT
;
1181 const char *p2
= arg
, *p
;
1183 for (p
= arg
; *p
; p
++) {
1184 int ws
= isspace(*p
);
1185 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1186 *p
!= '?' && *p
!= '*' && *p
!= '~')
1189 strbuf_addch(&buf
, '"');
1191 strbuf_add(&buf
, p2
, p
- p2
);
1192 if (*p
== '\\' || *p
== '"')
1193 strbuf_addch(&buf
, '\\');
1198 strbuf_addch(&buf
, '"');
1202 strbuf_add(&buf
, p2
, p
- p2
);
1204 strbuf_addch(&buf
, '"');
1205 return strbuf_detach(&buf
, 0);
1208 static const char *parse_interpreter(const char *cmd
)
1210 static char buf
[100];
1214 /* don't even try a .exe */
1216 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1219 fd
= open(cmd
, O_RDONLY
);
1222 n
= read(fd
, buf
, sizeof(buf
)-1);
1224 if (n
< 4) /* at least '#!/x' and not error */
1227 if (buf
[0] != '#' || buf
[1] != '!')
1230 p
= buf
+ strcspn(buf
, "\r\n");
1235 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1238 if ((opt
= strchr(p
+1, ' ')))
1244 * exe_only means that we only want to detect .exe files, but not scripts
1245 * (which do not have an extension)
1247 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1248 int isexe
, int exe_only
)
1250 char path
[MAX_PATH
];
1251 wchar_t wpath
[MAX_PATH
];
1252 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1254 if (xutftowcs_path(wpath
, path
) < 0)
1257 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1258 return xstrdup(path
);
1259 wpath
[wcslen(wpath
)-4] = '\0';
1260 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1261 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1262 path
[strlen(path
)-4] = '\0';
1263 return xstrdup(path
);
1270 * Determines the absolute path of cmd using the split path in path.
1271 * If cmd contains a slash or backslash, no lookup is performed.
1273 static char *path_lookup(const char *cmd
, int exe_only
)
1277 int len
= strlen(cmd
);
1278 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1280 if (strpbrk(cmd
, "/\\"))
1281 return xstrdup(cmd
);
1283 path
= mingw_getenv("PATH");
1288 const char *sep
= strchrnul(path
, ';');
1289 int dirlen
= sep
- path
;
1291 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1300 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1302 while (*s
&& *s
!= c
)
1307 /* Compare only keys */
1308 static int wenvcmp(const void *a
, const void *b
)
1310 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1311 size_t p_len
, q_len
;
1314 p_len
= wcschrnul(p
, L
'=') - p
;
1315 q_len
= wcschrnul(q
, L
'=') - q
;
1317 /* If the length differs, include the shorter key's NUL */
1320 else if (p_len
> q_len
)
1323 return _wcsnicmp(p
, q
, p_len
);
1327 * Build an environment block combining the inherited environment
1328 * merged with the given list of settings.
1330 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1331 * Values of the form "KEY" in deltaenv delete inherited values.
1333 * Multiple entries in deltaenv for the same key are explicitly allowed.
1335 * We return a contiguous block of UNICODE strings with a final trailing
1338 static wchar_t *make_environment_block(char **deltaenv
)
1340 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1341 size_t wlen
, s
, delta_size
, size
;
1343 wchar_t **array
= NULL
;
1344 size_t alloc
= 0, nr
= 0, i
;
1346 size
= 1; /* for extra NUL at the end */
1348 /* If there is no deltaenv to apply, simply return a copy. */
1349 if (!deltaenv
|| !*deltaenv
) {
1350 for (p
= wenv
; p
&& *p
; ) {
1351 size_t s
= wcslen(p
) + 1;
1356 ALLOC_ARRAY(result
, size
);
1357 COPY_ARRAY(result
, wenv
, size
);
1358 FreeEnvironmentStringsW(wenv
);
1363 * If there is a deltaenv, let's accumulate all keys into `array`,
1364 * sort them using the stable git_stable_qsort() and then copy,
1365 * skipping duplicate keys
1367 for (p
= wenv
; p
&& *p
; ) {
1368 ALLOC_GROW(array
, nr
+ 1, alloc
);
1375 /* (over-)assess size needed for wchar version of deltaenv */
1376 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1377 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1378 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1380 /* convert the deltaenv, appending to array */
1381 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1382 ALLOC_GROW(array
, nr
+ 1, alloc
);
1383 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1388 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1389 ALLOC_ARRAY(result
, size
+ delta_size
);
1391 for (p
= result
, i
= 0; i
< nr
; i
++) {
1392 /* Skip any duplicate keys; last one wins */
1393 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1396 /* Skip "to delete" entry */
1397 if (!wcschr(array
[i
], L
'='))
1400 size
= wcslen(array
[i
]) + 1;
1401 COPY_ARRAY(p
, array
[i
], size
);
1408 FreeEnvironmentStringsW(wenv
);
1412 static void do_unset_environment_variables(void)
1415 char *p
= unset_environment_variables
;
1422 char *comma
= strchr(p
, ',');
1434 struct pinfo_t
*next
;
1438 static struct pinfo_t
*pinfo
= NULL
;
1439 CRITICAL_SECTION pinfo_cs
;
1441 /* Used to match and chomp off path components */
1442 static inline int match_last_path_component(const char *path
, size_t *len
,
1443 const char *component
)
1445 size_t component_len
= strlen(component
);
1446 if (*len
< component_len
+ 1 ||
1447 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1448 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1450 *len
-= component_len
+ 1;
1451 /* chomp off repeated dir separators */
1452 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1457 static int is_msys2_sh(const char *cmd
)
1462 if (!strcmp(cmd
, "sh")) {
1463 static int ret
= -1;
1469 p
= path_lookup(cmd
, 0);
1473 size_t len
= strlen(p
);
1475 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1476 match_last_path_component(p
, &len
, "bin") &&
1477 match_last_path_component(p
, &len
, "usr");
1483 if (ends_with(cmd
, "\\sh.exe")) {
1487 sh
= path_lookup("sh", 0);
1489 return !fspathcmp(cmd
, sh
);
1495 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1497 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1499 static int restrict_handle_inheritance
= -1;
1501 PROCESS_INFORMATION pi
;
1502 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1503 HANDLE stdhandles
[3];
1504 DWORD stdhandles_count
= 0;
1507 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1508 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1511 const char *(*quote_arg
)(const char *arg
) =
1512 is_msys2_sh(cmd
? cmd
: *argv
) ?
1513 quote_arg_msys2
: quote_arg_msvc
;
1514 const char *strace_env
;
1516 /* Make sure to override previous errors, if any */
1519 if (restrict_handle_inheritance
< 0)
1520 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1522 * The following code to restrict which handles are inherited seems
1523 * to work properly only on Windows 7 and later, so let's disable it
1524 * on Windows Vista and 2008.
1526 if (restrict_handle_inheritance
< 0)
1527 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1529 do_unset_environment_variables();
1531 /* Determine whether or not we are associated to a console */
1532 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1533 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1534 FILE_ATTRIBUTE_NORMAL
, NULL
);
1535 if (cons
== INVALID_HANDLE_VALUE
) {
1536 /* There is no console associated with this process.
1537 * Since the child is a console process, Windows
1538 * would normally create a console window. But
1539 * since we'll be redirecting std streams, we do
1540 * not need the console.
1541 * It is necessary to use DETACHED_PROCESS
1542 * instead of CREATE_NO_WINDOW to make ssh
1543 * recognize that it has no console.
1545 flags
|= DETACHED_PROCESS
;
1547 /* There is already a console. If we specified
1548 * DETACHED_PROCESS here, too, Windows would
1549 * disassociate the child from the console.
1550 * The same is true for CREATE_NO_WINDOW.
1555 memset(&si
, 0, sizeof(si
));
1556 si
.StartupInfo
.cb
= sizeof(si
);
1557 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1558 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1559 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1561 /* The list of handles cannot contain duplicates */
1562 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1563 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1564 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1565 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1566 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1567 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1568 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1569 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1570 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1571 if (stdhandles_count
)
1572 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1574 if (*argv
&& !strcmp(cmd
, *argv
))
1576 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1578 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1581 /* concatenate argv, quoting args as we go */
1582 strbuf_init(&args
, 0);
1584 char *quoted
= (char *)quote_arg(cmd
);
1585 strbuf_addstr(&args
, quoted
);
1589 for (; *argv
; argv
++) {
1590 char *quoted
= (char *)quote_arg(*argv
);
1592 strbuf_addch(&args
, ' ');
1593 strbuf_addstr(&args
, quoted
);
1594 if (quoted
!= *argv
)
1598 strace_env
= getenv("GIT_STRACE_COMMANDS");
1600 char *p
= path_lookup("strace.exe", 1);
1602 return error("strace not found!");
1603 if (xutftowcs_path(wcmd
, p
) < 0) {
1608 if (!strcmp("1", strace_env
) ||
1609 !strcasecmp("yes", strace_env
) ||
1610 !strcasecmp("true", strace_env
))
1611 strbuf_insert(&args
, 0, "strace ", 7);
1613 const char *quoted
= quote_arg(strace_env
);
1614 struct strbuf buf
= STRBUF_INIT
;
1615 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1616 if (quoted
!= strace_env
)
1617 free((char *)quoted
);
1618 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1619 strbuf_release(&buf
);
1623 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1624 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1625 strbuf_release(&args
);
1627 wenvblk
= make_environment_block(deltaenv
);
1629 memset(&pi
, 0, sizeof(pi
));
1630 if (restrict_handle_inheritance
&& stdhandles_count
&&
1631 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1632 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1633 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1634 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1635 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1636 UpdateProcThreadAttribute(attr_list
, 0,
1637 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1639 stdhandles_count
* sizeof(HANDLE
),
1641 si
.lpAttributeList
= attr_list
;
1642 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1645 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1646 stdhandles_count
? TRUE
: FALSE
,
1647 flags
, wenvblk
, dir
? wdir
: NULL
,
1648 &si
.StartupInfo
, &pi
);
1651 * On Windows 2008 R2, it seems that specifying certain types of handles
1652 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1653 * error. Rather than playing finicky and fragile games, let's just try
1654 * to detect this situation and simply try again without restricting any
1655 * handle inheritance. This is still better than failing to create
1658 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1659 DWORD err
= GetLastError();
1660 struct strbuf buf
= STRBUF_INIT
;
1662 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1664 * On Windows 7 and earlier, handles on pipes and character
1665 * devices are inherited automatically, and cannot be
1666 * specified in the thread handle list. Rather than trying
1667 * to catch each and every corner case (and running the
1668 * chance of *still* forgetting a few), let's just fall
1669 * back to creating the process without trying to limit the
1670 * handle inheritance.
1672 !(err
== ERROR_INVALID_PARAMETER
&&
1673 GetVersion() >> 16 < 9200) &&
1674 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1678 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1680 for (i
= 0; i
< stdhandles_count
; i
++) {
1681 HANDLE h
= stdhandles
[i
];
1682 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1683 "handle info (%d) %lx\n", i
, h
,
1685 GetHandleInformation(h
, &fl
),
1688 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1689 "at\nhttps://github.com/git-for-windows/"
1690 "git/issues/new\n\n"
1691 "To suppress this warning, please set "
1692 "the environment variable\n\n"
1693 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1696 restrict_handle_inheritance
= 0;
1697 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1698 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1699 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1700 &si
.StartupInfo
, &pi
);
1702 errno
= err_win_to_posix(GetLastError());
1703 if (ret
&& buf
.len
) {
1704 warning("failed to restrict file handles (%ld)\n\n%s",
1707 strbuf_release(&buf
);
1709 errno
= err_win_to_posix(GetLastError());
1711 if (si
.lpAttributeList
)
1712 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1714 HeapFree(GetProcessHeap(), 0, attr_list
);
1722 CloseHandle(pi
.hThread
);
1725 * The process ID is the human-readable identifier of the process
1726 * that we want to present in log and error messages. The handle
1727 * is not useful for this purpose. But we cannot close it, either,
1728 * because it is not possible to turn a process ID into a process
1729 * handle after the process terminated.
1730 * Keep the handle in a list for waitpid.
1732 EnterCriticalSection(&pinfo_cs
);
1734 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1735 info
->pid
= pi
.dwProcessId
;
1736 info
->proc
= pi
.hProcess
;
1740 LeaveCriticalSection(&pinfo_cs
);
1742 return (pid_t
)pi
.dwProcessId
;
1745 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1747 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1750 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1752 int fhin
, int fhout
, int fherr
)
1755 char *prog
= path_lookup(cmd
, 0);
1762 const char *interpr
= parse_interpreter(prog
);
1765 const char *argv0
= argv
[0];
1766 char *iprog
= path_lookup(interpr
, 1);
1773 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1774 fhin
, fhout
, fherr
);
1780 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1781 fhin
, fhout
, fherr
);
1787 static int try_shell_exec(const char *cmd
, char *const *argv
)
1789 const char *interpr
= parse_interpreter(cmd
);
1795 prog
= path_lookup(interpr
, 1);
1803 while (argv
[argc
]) argc
++;
1804 ALLOC_ARRAY(argv2
, argc
+ 1);
1805 argv2
[0] = (char *)cmd
; /* full path to the script file */
1806 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1807 exec_id
= trace2_exec(prog
, argv2
);
1808 pid
= mingw_spawnv(prog
, argv2
, 1);
1811 if (waitpid(pid
, &status
, 0) < 0)
1813 trace2_exec_result(exec_id
, status
);
1816 trace2_exec_result(exec_id
, -1);
1817 pid
= 1; /* indicate that we tried but failed */
1824 int mingw_execv(const char *cmd
, char *const *argv
)
1826 /* check if git_command is a shell script */
1827 if (!try_shell_exec(cmd
, argv
)) {
1831 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1832 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1834 trace2_exec_result(exec_id
, -1);
1837 if (waitpid(pid
, &status
, 0) < 0)
1839 trace2_exec_result(exec_id
, status
);
1845 int mingw_execvp(const char *cmd
, char *const *argv
)
1847 char *prog
= path_lookup(cmd
, 0);
1850 mingw_execv(prog
, argv
);
1858 int mingw_kill(pid_t pid
, int sig
)
1860 if (pid
> 0 && sig
== SIGTERM
) {
1861 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1863 if (TerminateProcess(h
, -1)) {
1868 errno
= err_win_to_posix(GetLastError());
1871 } else if (pid
> 0 && sig
== 0) {
1872 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1884 * UTF-8 versions of getenv(), putenv() and unsetenv().
1885 * Internally, they use the CRT's stock UNICODE routines
1886 * to avoid data loss.
1888 char *mingw_getenv(const char *name
)
1890 #define GETENV_MAX_RETAIN 64
1891 static char *values
[GETENV_MAX_RETAIN
];
1892 static int value_counter
;
1893 int len_key
, len_value
;
1896 wchar_t w_value
[32768];
1898 if (!name
|| !*name
)
1901 len_key
= strlen(name
) + 1;
1902 /* We cannot use xcalloc() here because that uses getenv() itself */
1903 w_key
= calloc(len_key
, sizeof(wchar_t));
1905 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1906 xutftowcs(w_key
, name
, len_key
);
1907 /* GetEnvironmentVariableW() only sets the last error upon failure */
1908 SetLastError(ERROR_SUCCESS
);
1909 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1910 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1916 len_value
= len_value
* 3 + 1;
1917 /* We cannot use xcalloc() here because that uses getenv() itself */
1918 value
= calloc(len_value
, sizeof(char));
1920 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1921 xwcstoutf(value
, w_value
, len_value
);
1924 * We return `value` which is an allocated value and the caller is NOT
1925 * expecting to have to free it, so we keep a round-robin array,
1926 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1928 free(values
[value_counter
]);
1929 values
[value_counter
++] = value
;
1930 if (value_counter
>= ARRAY_SIZE(values
))
1936 int mingw_putenv(const char *namevalue
)
1939 wchar_t *wide
, *equal
;
1942 if (!namevalue
|| !*namevalue
)
1945 size
= strlen(namevalue
) * 2 + 1;
1946 wide
= calloc(size
, sizeof(wchar_t));
1948 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1949 xutftowcs(wide
, namevalue
, size
);
1950 equal
= wcschr(wide
, L
'=');
1952 result
= SetEnvironmentVariableW(wide
, NULL
);
1955 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
1960 errno
= err_win_to_posix(GetLastError());
1962 return result
? 0 : -1;
1965 static void ensure_socket_initialization(void)
1968 static int initialized
= 0;
1973 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1974 die("unable to initialize winsock subsystem, error %d",
1977 atexit((void(*)(void)) WSACleanup
);
1982 int mingw_gethostname(char *name
, int namelen
)
1984 ensure_socket_initialization();
1985 return gethostname(name
, namelen
);
1988 #undef gethostbyname
1989 struct hostent
*mingw_gethostbyname(const char *host
)
1991 ensure_socket_initialization();
1992 return gethostbyname(host
);
1996 int mingw_getaddrinfo(const char *node
, const char *service
,
1997 const struct addrinfo
*hints
, struct addrinfo
**res
)
1999 ensure_socket_initialization();
2000 return getaddrinfo(node
, service
, hints
, res
);
2003 int mingw_socket(int domain
, int type
, int protocol
)
2008 ensure_socket_initialization();
2009 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2010 if (s
== INVALID_SOCKET
) {
2012 * WSAGetLastError() values are regular BSD error codes
2013 * biased by WSABASEERR.
2014 * However, strerror() does not know about networking
2015 * specific errors, which are values beginning at 38 or so.
2016 * Therefore, we choose to leave the biased error code
2017 * in errno so that _if_ someone looks up the code somewhere,
2018 * then it is at least the number that are usually listed.
2020 errno
= WSAGetLastError();
2023 /* convert into a file descriptor */
2024 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2026 return error("unable to make a socket file descriptor: %s",
2033 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2035 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2036 return connect(s
, sa
, sz
);
2040 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2042 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2043 return bind(s
, sa
, sz
);
2047 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2049 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2050 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2054 int mingw_shutdown(int sockfd
, int how
)
2056 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2057 return shutdown(s
, how
);
2061 int mingw_listen(int sockfd
, int backlog
)
2063 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2064 return listen(s
, backlog
);
2068 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2072 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2073 SOCKET s2
= accept(s1
, sa
, sz
);
2075 /* convert into a file descriptor */
2076 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2079 return error("unable to make a socket file descriptor: %s",
2086 int mingw_rename(const char *pold
, const char *pnew
)
2090 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2091 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2095 * Try native rename() first to get errno right.
2096 * It is based on MoveFile(), which cannot overwrite existing files.
2098 if (!_wrename(wpold
, wpnew
))
2100 if (errno
!= EEXIST
)
2103 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2105 /* TODO: translate more errors */
2106 gle
= GetLastError();
2107 if (gle
== ERROR_ACCESS_DENIED
&&
2108 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2109 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2110 DWORD attrsold
= GetFileAttributesW(wpold
);
2111 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2112 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2114 else if (!_wrmdir(wpnew
))
2118 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2119 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2120 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2122 gle
= GetLastError();
2123 /* revert file attributes on failure */
2124 SetFileAttributesW(wpnew
, attrs
);
2127 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2129 * We assume that some other process had the source or
2130 * destination file open at the wrong moment and retry.
2131 * In order to give the other process a higher chance to
2132 * complete its operation, we give up our time slice now.
2133 * If we have to retry again, we do sleep a bit.
2135 Sleep(delay
[tries
]);
2139 if (gle
== ERROR_ACCESS_DENIED
&&
2140 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2141 "Should I try again?", pold
, pnew
))
2149 * Note that this doesn't return the actual pagesize, but
2150 * the allocation granularity. If future Windows specific git code
2151 * needs the real getpagesize function, we need to find another solution.
2153 int mingw_getpagesize(void)
2157 return si
.dwAllocationGranularity
;
2160 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2161 enum EXTENDED_NAME_FORMAT
{
2163 NameUserPrincipal
= 8
2166 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2168 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, GetUserNameExW
,
2169 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2170 static wchar_t wbuffer
[1024];
2173 if (!INIT_PROC_ADDR(GetUserNameExW
))
2176 len
= ARRAY_SIZE(wbuffer
);
2177 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2178 char *converted
= xmalloc((len
*= 3));
2179 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2187 char *mingw_query_user_email(void)
2189 return get_extended_user_info(NameUserPrincipal
);
2192 struct passwd
*getpwuid(int uid
)
2194 static unsigned initialized
;
2195 static char user_name
[100];
2196 static struct passwd
*p
;
2203 len
= ARRAY_SIZE(buf
);
2204 if (!GetUserNameW(buf
, &len
)) {
2209 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2214 p
= xmalloc(sizeof(*p
));
2215 p
->pw_name
= user_name
;
2216 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2218 p
->pw_gecos
= "unknown";
2225 static HANDLE timer_event
;
2226 static HANDLE timer_thread
;
2227 static int timer_interval
;
2228 static int one_shot
;
2229 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2231 /* The timer works like this:
2232 * The thread, ticktack(), is a trivial routine that most of the time
2233 * only waits to receive the signal to terminate. The main thread tells
2234 * the thread to terminate by setting the timer_event to the signalled
2236 * But ticktack() interrupts the wait state after the timer's interval
2237 * length to call the signal handler.
2240 static unsigned __stdcall
ticktack(void *dummy
)
2242 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2243 mingw_raise(SIGALRM
);
2250 static int start_timer_thread(void)
2252 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2254 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2256 return errno
= ENOMEM
,
2257 error("cannot start timer thread");
2259 return errno
= ENOMEM
,
2260 error("cannot allocate resources for timer");
2264 static void stop_timer_thread(void)
2267 SetEvent(timer_event
); /* tell thread to terminate */
2269 int rc
= WaitForSingleObject(timer_thread
, 10000);
2270 if (rc
== WAIT_TIMEOUT
)
2271 error("timer thread did not terminate timely");
2272 else if (rc
!= WAIT_OBJECT_0
)
2273 error("waiting for timer thread failed: %lu",
2275 CloseHandle(timer_thread
);
2278 CloseHandle(timer_event
);
2280 timer_thread
= NULL
;
2283 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2285 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2288 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2290 static const struct timeval zero
;
2291 static int atexit_done
;
2294 return errno
= EINVAL
,
2295 error("setitimer param 3 != NULL not implemented");
2296 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2297 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2298 return errno
= EINVAL
,
2299 error("setitimer: it_interval must be zero or eq it_value");
2302 stop_timer_thread();
2304 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2305 is_timeval_eq(&in
->it_interval
, &zero
))
2308 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2309 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2311 atexit(stop_timer_thread
);
2314 return start_timer_thread();
2317 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2320 return errno
= EINVAL
,
2321 error("sigaction only implemented for SIGALRM");
2323 return errno
= EINVAL
,
2324 error("sigaction: param 3 != NULL not implemented");
2326 timer_fn
= in
->sa_handler
;
2331 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2343 sigint_fn
= handler
;
2347 return signal(sig
, handler
);
2354 int mingw_raise(int sig
)
2358 if (timer_fn
== SIG_DFL
) {
2359 if (isatty(STDERR_FILENO
))
2360 fputs("Alarm clock\n", stderr
);
2361 exit(128 + SIGALRM
);
2362 } else if (timer_fn
!= SIG_IGN
)
2367 if (sigint_fn
== SIG_DFL
)
2369 else if (sigint_fn
!= SIG_IGN
)
2373 #if defined(_MSC_VER)
2380 case SIGABRT_COMPAT
:
2382 * The <signal.h> header in the MS C Runtime defines 8 signals
2383 * as being supported on the platform. Anything else causes an
2384 * "Invalid signal or error" (which in DEBUG builds causes the
2385 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2386 * already know will fail.
2403 int link(const char *oldpath
, const char *newpath
)
2405 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2406 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2407 xutftowcs_path(wnewpath
, newpath
) < 0)
2410 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2411 errno
= err_win_to_posix(GetLastError());
2417 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2419 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2426 if (pid
> 0 && options
& WNOHANG
) {
2427 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2431 options
&= ~WNOHANG
;
2435 struct pinfo_t
**ppinfo
;
2436 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2442 GetExitCodeProcess(h
, (LPDWORD
)status
);
2444 EnterCriticalSection(&pinfo_cs
);
2448 struct pinfo_t
*info
= *ppinfo
;
2449 if (info
->pid
== pid
) {
2450 CloseHandle(info
->proc
);
2451 *ppinfo
= info
->next
;
2455 ppinfo
= &info
->next
;
2458 LeaveCriticalSection(&pinfo_cs
);
2469 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2471 int upos
= 0, wpos
= 0;
2472 const unsigned char *utf
= (const unsigned char*) utfs
;
2473 if (!utf
|| !wcs
|| wcslen
< 1) {
2477 /* reserve space for \0 */
2482 while (upos
< utflen
) {
2483 int c
= utf
[upos
++] & 0xff;
2484 if (utflen
== INT_MAX
&& c
== 0)
2487 if (wpos
>= wcslen
) {
2496 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2497 (utf
[upos
] & 0xc0) == 0x80) {
2499 c
= ((c
& 0x1f) << 6);
2500 c
|= (utf
[upos
++] & 0x3f);
2502 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2503 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2504 (utf
[upos
] & 0xc0) == 0x80 &&
2505 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2507 c
= ((c
& 0x0f) << 12);
2508 c
|= ((utf
[upos
++] & 0x3f) << 6);
2509 c
|= (utf
[upos
++] & 0x3f);
2511 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2512 wpos
+ 1 < wcslen
&&
2513 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2514 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2515 (utf
[upos
] & 0xc0) == 0x80 &&
2516 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2517 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2518 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2519 c
= ((c
& 0x07) << 18);
2520 c
|= ((utf
[upos
++] & 0x3f) << 12);
2521 c
|= ((utf
[upos
++] & 0x3f) << 6);
2522 c
|= (utf
[upos
++] & 0x3f);
2524 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2525 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2526 } else if (c
>= 0xa0) {
2527 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2530 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2531 static const char *hex
= "0123456789abcdef";
2532 wcs
[wpos
++] = hex
[c
>> 4];
2534 wcs
[wpos
++] = hex
[c
& 0x0f];
2541 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2543 if (!wcs
|| !utf
|| utflen
< 1) {
2547 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2554 static void setup_windows_environment(void)
2556 char *tmp
= getenv("TMPDIR");
2558 /* on Windows it is TMP and TEMP */
2560 if (!(tmp
= getenv("TMP")))
2561 tmp
= getenv("TEMP");
2563 setenv("TMPDIR", tmp
, 1);
2564 tmp
= getenv("TMPDIR");
2570 * Convert all dir separators to forward slashes,
2571 * to help shell commands called from the Git
2572 * executable (by not mistaking the dir separators
2573 * for escape characters).
2575 convert_slashes(tmp
);
2578 /* simulate TERM to enable auto-color (see color.c) */
2579 if (!getenv("TERM"))
2580 setenv("TERM", "cygwin", 1);
2582 /* calculate HOME if not set */
2583 if (!getenv("HOME")) {
2585 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2586 * location, thus also check if the path exists (i.e. is not
2589 if ((tmp
= getenv("HOMEDRIVE"))) {
2590 struct strbuf buf
= STRBUF_INIT
;
2591 strbuf_addstr(&buf
, tmp
);
2592 if ((tmp
= getenv("HOMEPATH"))) {
2593 strbuf_addstr(&buf
, tmp
);
2594 if (is_directory(buf
.buf
))
2595 setenv("HOME", buf
.buf
, 1);
2597 tmp
= NULL
; /* use $USERPROFILE */
2599 strbuf_release(&buf
);
2601 /* use $USERPROFILE if the home share is not available */
2602 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2603 setenv("HOME", tmp
, 1);
2607 static PSID
get_current_user_sid(void)
2613 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2616 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2617 TOKEN_USER
*info
= xmalloc((size_t)len
);
2618 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2619 len
= GetLengthSid(info
->User
.Sid
);
2620 result
= xmalloc(len
);
2621 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2622 error(_("failed to copy SID (%ld)"),
2624 FREE_AND_NULL(result
);
2627 FREE_AND_NULL(info
);
2634 int is_path_owned_by_current_sid(const char *path
)
2636 WCHAR wpath
[MAX_PATH
];
2638 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2641 static wchar_t home
[MAX_PATH
];
2645 if (xutftowcs_path(wpath
, path
) < 0)
2649 * On Windows, the home directory is owned by the administrator, but for
2650 * all practical purposes, it belongs to the user. Do pretend that it is
2651 * owned by the user.
2654 DWORD size
= ARRAY_SIZE(home
);
2655 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2656 if (!len
|| len
> size
)
2657 wcscpy(home
, L
"::N/A::");
2659 if (!wcsicmp(wpath
, home
))
2662 /* Get the owner SID */
2663 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2664 OWNER_SECURITY_INFORMATION
|
2665 DACL_SECURITY_INFORMATION
,
2666 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2668 if (err
!= ERROR_SUCCESS
)
2669 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2670 else if (sid
&& IsValidSid(sid
)) {
2671 /* Now, verify that the SID matches the current user's */
2672 static PSID current_user_sid
;
2674 if (!current_user_sid
)
2675 current_user_sid
= get_current_user_sid();
2677 if (current_user_sid
&&
2678 IsValidSid(current_user_sid
) &&
2679 EqualSid(sid
, current_user_sid
))
2684 * We can release the security descriptor struct only now because `sid`
2685 * actually points into this struct.
2688 LocalFree(descriptor
);
2693 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2695 const char *p
= path
;
2696 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2701 skip_dos_drive_prefix((char **)&path
);
2708 case '/': case '\\':
2709 /* cannot end in ` ` or `.`, except for `.` and `..` */
2710 if (preceding_space_or_period
&&
2711 (i
!= periods
|| periods
> 2))
2716 i
= periods
= preceding_space_or_period
= 0;
2720 case 'a': case 'A': /* AUX */
2721 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2722 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2723 not_a_reserved_name
:
2729 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2730 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2731 goto not_a_reserved_name
;
2733 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2735 if (c
< '1' || c
> '9')
2736 goto not_a_reserved_name
;
2737 } else if (c
== 'n' || c
== 'N') { /* CON */
2739 if ((c
== 'i' || c
== 'I') &&
2740 ((c
= path
[i
+ 2]) == 'n' ||
2743 i
+= 3; /* CONIN$ */
2744 else if ((c
== 'o' || c
== 'O') &&
2745 ((c
= path
[i
+ 2]) == 'u' ||
2747 ((c
= path
[i
+ 3]) == 't' ||
2750 i
+= 4; /* CONOUT$ */
2752 goto not_a_reserved_name
;
2754 case 'l': case 'L': /* LPT<N> */
2755 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2756 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2757 !isdigit(path
[++i
]))
2758 goto not_a_reserved_name
;
2760 case 'n': case 'N': /* NUL */
2761 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2762 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2763 (allow_literal_nul
&&
2764 !path
[i
+ 1] && p
== path
))
2765 goto not_a_reserved_name
;
2767 case 'p': case 'P': /* PRN */
2768 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2769 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2770 goto not_a_reserved_name
;
2777 * So far, this looks like a reserved name. Let's see
2778 * whether it actually is one: trailing spaces, a file
2779 * extension, or an NTFS Alternate Data Stream do not
2780 * matter, the name is still reserved if any of those
2781 * follow immediately after the actual name.
2784 if (path
[i
] == ' ') {
2785 preceding_space_or_period
= 1;
2786 while (path
[++i
] == ' ')
2787 ; /* skip all spaces */
2791 if (c
&& c
!= '.' && c
!= ':' && c
!= '/' && c
!= '\\')
2792 goto not_a_reserved_name
;
2794 /* contains reserved name */
2800 preceding_space_or_period
= 1;
2803 case ':': /* DOS drive prefix was already skipped */
2804 case '<': case '>': case '"': case '|': case '?': case '*':
2805 /* illegal character */
2808 if (c
> '\0' && c
< '\x20')
2809 /* illegal character */
2812 preceding_space_or_period
= 0;
2817 #if !defined(_MSC_VER)
2819 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2820 * mingw startup code, see init.c in mingw runtime).
2825 static NORETURN
void die_startup(void)
2827 fputs("fatal: not enough memory for initialization", stderr
);
2831 static void *malloc_startup(size_t size
)
2833 void *result
= malloc(size
);
2839 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2841 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2842 return memcpy(malloc_startup(len
), buffer
, len
);
2845 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2846 DWORD desired_access
, DWORD flags
)
2848 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2849 wchar_t buf
[MAX_PATH
];
2850 DWORD max
= ARRAY_SIZE(buf
);
2852 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2854 if (!ret
|| ret
>= max
)
2857 /* make sure this does not leak into child processes */
2858 SetEnvironmentVariableW(key
, NULL
);
2859 if (!wcscmp(buf
, L
"off")) {
2861 handle
= GetStdHandle(std_id
);
2862 if (handle
!= INVALID_HANDLE_VALUE
)
2863 CloseHandle(handle
);
2866 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2867 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2868 if (handle
== INVALID_HANDLE_VALUE
) {
2870 handle
= GetStdHandle(std_id
);
2871 if (handle
!= INVALID_HANDLE_VALUE
)
2872 CloseHandle(handle
);
2874 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2875 SetStdHandle(std_id
, handle
);
2877 /* do *not* close the new_fd: that would close stdout */
2881 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2883 if (handle
!= INVALID_HANDLE_VALUE
) {
2884 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2885 SetStdHandle(std_id
, handle
);
2891 static void maybe_redirect_std_handles(void)
2893 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2894 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2895 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2896 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2897 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2898 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2908 * We implement wmain() and compile with -municode, which would
2909 * normally ignore main(), but we call the latter from the former
2910 * so that we can handle non-ASCII command-line parameters
2913 * To be more compatible with the core git code, we convert
2914 * argv into UTF8 and pass them directly to main().
2916 int wmain(int argc
, const wchar_t **wargv
)
2918 int i
, maxlen
, exit_status
;
2919 char *buffer
, **save
;
2922 trace2_initialize_clock();
2926 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
2929 #ifdef USE_MSVC_CRTDBG
2930 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
2934 maybe_redirect_std_handles();
2936 /* determine size of argv and environ conversion buffer */
2937 maxlen
= wcslen(wargv
[0]);
2938 for (i
= 1; i
< argc
; i
++)
2939 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2941 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2942 maxlen
= 3 * maxlen
+ 1;
2943 buffer
= malloc_startup(maxlen
);
2946 * Create a UTF-8 version of w_argv. Also create a "save" copy
2947 * to remember all the string pointers because parse_options()
2948 * will remove claimed items from the argv that we pass down.
2950 ALLOC_ARRAY(argv
, argc
+ 1);
2951 ALLOC_ARRAY(save
, argc
+ 1);
2952 for (i
= 0; i
< argc
; i
++)
2953 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2954 argv
[i
] = save
[i
] = NULL
;
2957 /* fix Windows specific environment settings */
2958 setup_windows_environment();
2960 unset_environment_variables
= xstrdup("PERL5LIB");
2962 /* initialize critical section for waitpid pinfo_t list */
2963 InitializeCriticalSection(&pinfo_cs
);
2965 /* set up default file mode and file modes for stdin/out/err */
2967 _setmode(_fileno(stdin
), _O_BINARY
);
2968 _setmode(_fileno(stdout
), _O_BINARY
);
2969 _setmode(_fileno(stderr
), _O_BINARY
);
2971 /* initialize Unicode console */
2974 /* invoke the real main() using our utf8 version of argv. */
2975 exit_status
= main(argc
, argv
);
2977 for (i
= 0; i
< argc
; i
++)
2985 int uname(struct utsname
*buf
)
2987 unsigned v
= (unsigned)GetVersion();
2988 memset(buf
, 0, sizeof(*buf
));
2989 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
2990 xsnprintf(buf
->release
, sizeof(buf
->release
),
2991 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
2992 /* assuming NT variants only.. */
2993 xsnprintf(buf
->version
, sizeof(buf
->version
),
2994 "%u", (v
>> 16) & 0x7fff);