1 #include "../git-compat-util.h"
6 #include "../run-command.h"
8 #include "win32/lazyload.h"
12 #define HCAST(type, handle) ((type)(intptr_t)handle)
14 static const int delay
[] = { 0, 1, 10, 20, 40 };
16 void open_in_gdb(void)
18 static struct child_process cp
= CHILD_PROCESS_INIT
;
21 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
22 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
24 if (start_command(&cp
) < 0)
25 die_errno("Could not start gdb");
29 int err_win_to_posix(DWORD winerr
)
33 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
34 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
35 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
36 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
37 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
38 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
39 case ERROR_BAD_COMMAND
: error
= EIO
; break;
40 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
41 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
42 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
43 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
44 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
45 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
46 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
47 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
48 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
49 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
50 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
51 case ERROR_BUSY
: error
= EBUSY
; break;
52 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
53 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
54 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
55 case ERROR_CANTOPEN
: error
= EIO
; break;
56 case ERROR_CANTREAD
: error
= EIO
; break;
57 case ERROR_CANTWRITE
: error
= EIO
; break;
58 case ERROR_CRC
: error
= EIO
; break;
59 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
60 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
61 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
62 case ERROR_DIRECTORY
: error
= EINVAL
; break;
63 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
64 case ERROR_DISK_CHANGE
: error
= EIO
; break;
65 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
66 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
67 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
68 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
69 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
70 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
71 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
72 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
73 case ERROR_GEN_FAILURE
: error
= EIO
; break;
74 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
75 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
76 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
77 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
78 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
79 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
80 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
81 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
82 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
83 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
84 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
85 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
86 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
87 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
88 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
89 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
90 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
91 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
92 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
93 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
94 case ERROR_IO_DEVICE
: error
= EIO
; break;
95 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
96 case ERROR_LOCKED
: error
= EBUSY
; break;
97 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
98 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
99 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
100 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
101 case ERROR_MORE_DATA
: error
= EPIPE
; break;
102 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
103 case ERROR_NOACCESS
: error
= EFAULT
; break;
104 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
105 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
106 case ERROR_NOT_READY
: error
= EAGAIN
; break;
107 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
108 case ERROR_NO_DATA
: error
= EPIPE
; break;
109 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
110 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
111 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
112 case ERROR_OPEN_FAILED
: error
= EIO
; break;
113 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
114 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
115 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
116 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
117 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
118 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
119 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
120 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
121 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
122 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
123 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
124 case ERROR_READ_FAULT
: error
= EIO
; break;
125 case ERROR_SEEK
: error
= EIO
; break;
126 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
127 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
128 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
129 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
130 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
131 case ERROR_SWAPERROR
: error
= ENOENT
; break;
132 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
133 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
134 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
135 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
136 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
137 case ERROR_WRITE_FAULT
: error
= EIO
; break;
138 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
143 static inline int is_file_in_use_error(DWORD errcode
)
146 case ERROR_SHARING_VIOLATION
:
147 case ERROR_ACCESS_DENIED
:
154 static int read_yes_no_answer(void)
158 if (fgets(answer
, sizeof(answer
), stdin
)) {
159 size_t answer_len
= strlen(answer
);
160 int got_full_line
= 0, c
;
162 /* remove the newline */
163 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
164 answer
[answer_len
-2] = '\0';
166 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
167 answer
[answer_len
-1] = '\0';
170 /* flush the buffer in case we did not get the full line */
172 while ((c
= getchar()) != EOF
&& c
!= '\n')
175 /* we could not read, return the
176 * default answer which is no */
179 if (tolower(answer
[0]) == 'y' && !answer
[1])
181 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
183 if (tolower(answer
[0]) == 'n' && !answer
[1])
185 if (!strncasecmp(answer
, "no", sizeof(answer
)))
188 /* did not find an answer we understand */
192 static int ask_yes_no_if_possible(const char *format
, ...)
195 const char *retry_hook
[] = { NULL
, NULL
, NULL
};
198 va_start(args
, format
);
199 vsnprintf(question
, sizeof(question
), format
, args
);
202 if ((retry_hook
[0] = mingw_getenv("GIT_ASK_YESNO"))) {
203 retry_hook
[1] = question
;
204 return !run_command_v_opt(retry_hook
, 0);
207 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
212 fprintf(stderr
, "%s (y/n) ", question
);
214 if ((answer
= read_yes_no_answer()) >= 0)
217 fprintf(stderr
, "Sorry, I did not understand your answer. "
218 "Please type 'y' or 'n'\n");
223 enum hide_dotfiles_type
{
224 HIDE_DOTFILES_FALSE
= 0,
226 HIDE_DOTFILES_DOTGITONLY
229 static int core_restrict_inherited_handles
= -1;
230 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
231 static char *unset_environment_variables
;
233 int mingw_core_config(const char *var
, const char *value
, void *cb
)
235 if (!strcmp(var
, "core.hidedotfiles")) {
236 if (value
&& !strcasecmp(value
, "dotgitonly"))
237 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
239 hide_dotfiles
= git_config_bool(var
, value
);
243 if (!strcmp(var
, "core.unsetenvvars")) {
244 free(unset_environment_variables
);
245 unset_environment_variables
= xstrdup(value
);
249 if (!strcmp(var
, "core.restrictinheritedhandles")) {
250 if (value
&& !strcasecmp(value
, "auto"))
251 core_restrict_inherited_handles
= -1;
253 core_restrict_inherited_handles
=
254 git_config_bool(var
, value
);
261 /* Normalizes NT paths as returned by some low-level APIs. */
262 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
265 /* fix absolute path prefixes */
266 if (wbuf
[0] == '\\') {
267 /* strip NT namespace prefixes */
268 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
269 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
271 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
273 /* replace remaining '...UNC\' with '\\' */
274 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
279 /* convert backslashes to slashes */
280 for (i
= 0; wbuf
[i
]; i
++)
286 int mingw_unlink(const char *pathname
)
289 wchar_t wpathname
[MAX_PATH
];
290 if (xutftowcs_path(wpathname
, pathname
) < 0)
293 if (DeleteFileW(wpathname
))
296 /* read-only files cannot be removed */
297 _wchmod(wpathname
, 0666);
298 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
299 if (!is_file_in_use_error(GetLastError()))
302 * We assume that some other process had the source or
303 * destination file open at the wrong moment and retry.
304 * In order to give the other process a higher chance to
305 * complete its operation, we give up our time slice now.
306 * If we have to retry again, we do sleep a bit.
311 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
312 ask_yes_no_if_possible("Unlink of file '%s' failed. "
313 "Should I try again?", pathname
))
314 ret
= _wunlink(wpathname
);
318 static int is_dir_empty(const wchar_t *wpath
)
320 WIN32_FIND_DATAW findbuf
;
322 wchar_t wbuf
[MAX_PATH
+ 2];
324 wcscat(wbuf
, L
"\\*");
325 handle
= FindFirstFileW(wbuf
, &findbuf
);
326 if (handle
== INVALID_HANDLE_VALUE
)
327 return GetLastError() == ERROR_NO_MORE_FILES
;
329 while (!wcscmp(findbuf
.cFileName
, L
".") ||
330 !wcscmp(findbuf
.cFileName
, L
".."))
331 if (!FindNextFileW(handle
, &findbuf
)) {
332 DWORD err
= GetLastError();
334 return err
== ERROR_NO_MORE_FILES
;
340 int mingw_rmdir(const char *pathname
)
343 wchar_t wpathname
[MAX_PATH
];
344 if (xutftowcs_path(wpathname
, pathname
) < 0)
347 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
348 if (!is_file_in_use_error(GetLastError()))
349 errno
= err_win_to_posix(GetLastError());
352 if (!is_dir_empty(wpathname
)) {
357 * We assume that some other process had the source or
358 * destination file open at the wrong moment and retry.
359 * In order to give the other process a higher chance to
360 * complete its operation, we give up our time slice now.
361 * If we have to retry again, we do sleep a bit.
366 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
367 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
368 "Should I try again?", pathname
))
369 ret
= _wrmdir(wpathname
);
371 invalidate_lstat_cache();
375 static inline int needs_hiding(const char *path
)
377 const char *basename
;
379 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
382 /* We cannot use basename(), as it would remove trailing slashes */
383 win32_skip_dos_drive_prefix((char **)&path
);
387 for (basename
= path
; *path
; path
++)
388 if (is_dir_sep(*path
)) {
391 } while (is_dir_sep(*path
));
392 /* ignore trailing slashes */
399 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
400 return *basename
== '.';
402 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
403 return !strncasecmp(".git", basename
, 4) &&
404 (!basename
[4] || is_dir_sep(basename
[4]));
407 static int set_hidden_flag(const wchar_t *path
, int set
)
409 DWORD original
= GetFileAttributesW(path
), modified
;
411 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
413 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
414 if (original
== modified
|| SetFileAttributesW(path
, modified
))
416 errno
= err_win_to_posix(GetLastError());
420 int mingw_mkdir(const char *path
, int mode
)
423 wchar_t wpath
[MAX_PATH
];
425 if (!is_valid_win32_path(path
, 0)) {
430 if (xutftowcs_path(wpath
, path
) < 0)
432 ret
= _wmkdir(wpath
);
433 if (!ret
&& needs_hiding(path
))
434 return set_hidden_flag(wpath
, 1);
439 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
440 * is documented in [1] as opening a writable file handle in append mode.
441 * (It is believed that) this is atomic since it is maintained by the
442 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
444 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
446 * This trick does not appear to work for named pipes. Instead it creates
447 * a named pipe client handle that cannot be written to. Callers should
448 * just use the regular _wopen() for them. (And since client handle gets
449 * bound to a unique server handle, it isn't really an issue.)
451 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
455 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
457 /* only these flags are supported */
458 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
459 return errno
= ENOSYS
, -1;
462 * FILE_SHARE_WRITE is required to permit child processes
463 * to append to the file.
465 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
466 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
467 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
468 if (handle
== INVALID_HANDLE_VALUE
) {
469 DWORD err
= GetLastError();
472 * Some network storage solutions (e.g. Isilon) might return
473 * ERROR_INVALID_PARAMETER instead of expected error
474 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
475 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
477 if (err
== ERROR_INVALID_PARAMETER
)
478 err
= ERROR_PATH_NOT_FOUND
;
480 errno
= err_win_to_posix(err
);
485 * No O_APPEND here, because the CRT uses it only to reset the
486 * file pointer to EOF before each write(); but that is not
487 * necessary (and may lead to races) for a file created with
490 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
497 * Does the pathname map to the local named pipe filesystem?
498 * That is, does it have a "//./pipe/" prefix?
500 static int is_local_named_pipe_path(const char *filename
)
502 return (is_dir_sep(filename
[0]) &&
503 is_dir_sep(filename
[1]) &&
504 filename
[2] == '.' &&
505 is_dir_sep(filename
[3]) &&
506 !strncasecmp(filename
+4, "pipe", 4) &&
507 is_dir_sep(filename
[8]) &&
511 int mingw_open (const char *filename
, int oflags
, ...)
513 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
516 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
517 wchar_t wfilename
[MAX_PATH
];
520 va_start(args
, oflags
);
521 mode
= va_arg(args
, int);
524 if (!is_valid_win32_path(filename
, !create
)) {
525 errno
= create
? EINVAL
: ENOENT
;
529 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
530 open_fn
= mingw_open_append
;
534 if (filename
&& !strcmp(filename
, "/dev/null"))
535 wcscpy(wfilename
, L
"nul");
536 else if (xutftowcs_path(wfilename
, filename
) < 0)
539 fd
= open_fn(wfilename
, oflags
, mode
);
541 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
542 DWORD attrs
= GetFileAttributesW(wfilename
);
543 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
546 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
548 * Internally, _wopen() uses the CreateFile() API which errors
549 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
550 * specified and an already existing file's attributes do not
551 * match *exactly*. As there is no mode or flag we can set that
552 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
553 * again *without* the O_CREAT flag (that corresponds to the
554 * CREATE_ALWAYS flag of CreateFile()).
556 if (fd
< 0 && errno
== EACCES
)
557 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
558 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
559 warning("could not mark '%s' as hidden.", filename
);
564 static BOOL WINAPI
ctrl_ignore(DWORD type
)
570 int mingw_fgetc(FILE *stream
)
573 if (!isatty(_fileno(stream
)))
574 return fgetc(stream
);
576 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
579 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
582 /* Ctrl+C was pressed, simulate SIGINT and retry */
585 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
590 FILE *mingw_fopen (const char *filename
, const char *otype
)
592 int hide
= needs_hiding(filename
);
594 wchar_t wfilename
[MAX_PATH
], wotype
[4];
595 if (filename
&& !strcmp(filename
, "/dev/null"))
596 wcscpy(wfilename
, L
"nul");
597 else if (!is_valid_win32_path(filename
, 1)) {
598 int create
= otype
&& strchr(otype
, 'w');
599 errno
= create
? EINVAL
: ENOENT
;
601 } else if (xutftowcs_path(wfilename
, filename
) < 0)
604 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
607 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
608 error("could not unhide %s", filename
);
611 file
= _wfopen(wfilename
, wotype
);
612 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
614 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
615 warning("could not mark '%s' as hidden.", filename
);
619 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
621 int hide
= needs_hiding(filename
);
623 wchar_t wfilename
[MAX_PATH
], wotype
[4];
624 if (filename
&& !strcmp(filename
, "/dev/null"))
625 wcscpy(wfilename
, L
"nul");
626 else if (!is_valid_win32_path(filename
, 1)) {
627 int create
= otype
&& strchr(otype
, 'w');
628 errno
= create
? EINVAL
: ENOENT
;
630 } else if (xutftowcs_path(wfilename
, filename
) < 0)
633 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
636 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
637 error("could not unhide %s", filename
);
640 file
= _wfreopen(wfilename
, wotype
, stream
);
641 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
642 warning("could not mark '%s' as hidden.", filename
);
647 int mingw_fflush(FILE *stream
)
649 int ret
= fflush(stream
);
652 * write() is used behind the scenes of stdio output functions.
653 * Since git code does not check for errors after each stdio write
654 * operation, it can happen that write() is called by a later
655 * stdio function even if an earlier write() call failed. In the
656 * case of a pipe whose readable end was closed, only the first
657 * call to write() reports EPIPE on Windows. Subsequent write()
658 * calls report EINVAL. It is impossible to notice whether this
659 * fflush invocation triggered such a case, therefore, we have to
660 * catch all EINVAL errors whole-sale.
662 if (ret
&& errno
== EINVAL
)
669 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
671 ssize_t result
= write(fd
, buf
, len
);
673 if (result
< 0 && errno
== EINVAL
&& buf
) {
674 /* check if fd is a pipe */
675 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
676 if (GetFileType(h
) == FILE_TYPE_PIPE
)
685 int mingw_access(const char *filename
, int mode
)
687 wchar_t wfilename
[MAX_PATH
];
688 if (xutftowcs_path(wfilename
, filename
) < 0)
690 /* X_OK is not supported by the MSVCRT version */
691 return _waccess(wfilename
, mode
& ~X_OK
);
694 int mingw_chdir(const char *dirname
)
696 wchar_t wdirname
[MAX_PATH
];
697 if (xutftowcs_path(wdirname
, dirname
) < 0)
699 return _wchdir(wdirname
);
702 int mingw_chmod(const char *filename
, int mode
)
704 wchar_t wfilename
[MAX_PATH
];
705 if (xutftowcs_path(wfilename
, filename
) < 0)
707 return _wchmod(wfilename
, mode
);
711 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
712 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
714 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
716 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
717 /* Windows to Unix Epoch conversion */
718 return winTime
- 116444736000000000LL;
721 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
723 long long hnsec
= filetime_to_hnsec(ft
);
724 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
725 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
729 * Verifies that safe_create_leading_directories() would succeed.
731 static int has_valid_directory_prefix(wchar_t *wfilename
)
733 int n
= wcslen(wfilename
);
736 wchar_t c
= wfilename
[--n
];
742 wfilename
[n
] = L
'\0';
743 attributes
= GetFileAttributesW(wfilename
);
745 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
746 attributes
== FILE_ATTRIBUTE_DEVICE
)
748 if (attributes
== INVALID_FILE_ATTRIBUTES
)
749 switch (GetLastError()) {
750 case ERROR_PATH_NOT_FOUND
:
752 case ERROR_FILE_NOT_FOUND
:
753 /* This implies parent directory exists. */
761 /* We keep the do_lstat code in a separate function to avoid recursion.
762 * When a path ends with a slash, the stat will fail with ENOENT. In
763 * this case, we strip the trailing slashes and stat again.
765 * If follow is true then act like stat() and report on the link
766 * target. Otherwise report on the link itself.
768 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
770 WIN32_FILE_ATTRIBUTE_DATA fdata
;
771 wchar_t wfilename
[MAX_PATH
];
772 if (xutftowcs_path(wfilename
, file_name
) < 0)
775 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
780 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
781 buf
->st_size
= fdata
.nFileSizeLow
|
782 (((off_t
)fdata
.nFileSizeHigh
)<<32);
783 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
784 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
785 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
786 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
787 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
788 WIN32_FIND_DATAW findbuf
;
789 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
790 if (handle
!= INVALID_HANDLE_VALUE
) {
791 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
792 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
794 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
795 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
797 buf
->st_mode
= S_IFLNK
;
799 buf
->st_mode
|= S_IREAD
;
800 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
801 buf
->st_mode
|= S_IWRITE
;
808 switch (GetLastError()) {
809 case ERROR_ACCESS_DENIED
:
810 case ERROR_SHARING_VIOLATION
:
811 case ERROR_LOCK_VIOLATION
:
812 case ERROR_SHARING_BUFFER_EXCEEDED
:
815 case ERROR_BUFFER_OVERFLOW
:
816 errno
= ENAMETOOLONG
;
818 case ERROR_NOT_ENOUGH_MEMORY
:
821 case ERROR_PATH_NOT_FOUND
:
822 if (!has_valid_directory_prefix(wfilename
)) {
834 /* We provide our own lstat/fstat functions, since the provided
835 * lstat/fstat functions are so slow. These stat functions are
836 * tailored for Git's usage (read: fast), and are not meant to be
837 * complete. Note that Git stat()s are redirected to mingw_lstat()
838 * too, since Windows doesn't really handle symlinks that well.
840 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
843 char alt_name
[PATH_MAX
];
845 if (!do_lstat(follow
, file_name
, buf
))
848 /* if file_name ended in a '/', Windows returned ENOENT;
849 * try again without trailing slashes
854 namelen
= strlen(file_name
);
855 if (namelen
&& file_name
[namelen
-1] != '/')
857 while (namelen
&& file_name
[namelen
-1] == '/')
859 if (!namelen
|| namelen
>= PATH_MAX
)
862 memcpy(alt_name
, file_name
, namelen
);
863 alt_name
[namelen
] = 0;
864 return do_lstat(follow
, alt_name
, buf
);
867 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
869 BY_HANDLE_FILE_INFORMATION fdata
;
871 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
872 errno
= err_win_to_posix(GetLastError());
880 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
881 buf
->st_size
= fdata
.nFileSizeLow
|
882 (((off_t
)fdata
.nFileSizeHigh
)<<32);
883 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
884 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
885 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
886 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
890 int mingw_lstat(const char *file_name
, struct stat
*buf
)
892 return do_stat_internal(0, file_name
, buf
);
894 int mingw_stat(const char *file_name
, struct stat
*buf
)
896 return do_stat_internal(1, file_name
, buf
);
899 int mingw_fstat(int fd
, struct stat
*buf
)
901 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
902 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
906 return get_file_info_by_handle(fh
, buf
);
910 /* initialize stat fields */
911 memset(buf
, 0, sizeof(*buf
));
914 if (type
== FILE_TYPE_CHAR
) {
915 buf
->st_mode
= _S_IFCHR
;
917 buf
->st_mode
= _S_IFIFO
;
918 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
919 buf
->st_size
= avail
;
929 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
931 long long winTime
= t
* 10000000LL + 116444736000000000LL;
932 ft
->dwLowDateTime
= winTime
;
933 ft
->dwHighDateTime
= winTime
>> 32;
936 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
941 wchar_t wfilename
[MAX_PATH
];
942 if (xutftowcs_path(wfilename
, file_name
) < 0)
945 /* must have write permission */
946 attrs
= GetFileAttributesW(wfilename
);
947 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
948 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
949 /* ignore errors here; open() will report them */
950 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
953 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
959 time_t_to_filetime(times
->modtime
, &mft
);
960 time_t_to_filetime(times
->actime
, &aft
);
962 GetSystemTimeAsFileTime(&mft
);
965 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
973 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
974 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
975 /* ignore errors again */
976 SetFileAttributesW(wfilename
, attrs
);
982 size_t mingw_strftime(char *s
, size_t max
,
983 const char *format
, const struct tm
*tm
)
985 /* a pointer to the original strftime in case we can't find the UCRT version */
986 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
988 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, strftime
, char *, size_t,
989 const char *, const struct tm
*);
991 if (INIT_PROC_ADDR(strftime
))
992 ret
= strftime(s
, max
, format
, tm
);
994 ret
= fallback(s
, max
, format
, tm
);
996 if (!ret
&& errno
== EINVAL
)
997 die("invalid strftime format: '%s'", format
);
1001 unsigned int sleep (unsigned int seconds
)
1003 Sleep(seconds
*1000);
1007 char *mingw_mktemp(char *template)
1009 wchar_t wtemplate
[MAX_PATH
];
1010 if (xutftowcs_path(wtemplate
, template) < 0)
1012 if (!_wmktemp(wtemplate
))
1014 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1019 int mkstemp(char *template)
1021 char *filename
= mktemp(template);
1022 if (filename
== NULL
)
1024 return open(filename
, O_RDWR
| O_CREAT
, 0600);
1027 int gettimeofday(struct timeval
*tv
, void *tz
)
1032 GetSystemTimeAsFileTime(&ft
);
1033 hnsec
= filetime_to_hnsec(&ft
);
1034 tv
->tv_sec
= hnsec
/ 10000000;
1035 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1039 int pipe(int filedes
[2])
1043 /* this creates non-inheritable handles */
1044 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1045 errno
= err_win_to_posix(GetLastError());
1048 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1049 if (filedes
[0] < 0) {
1054 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1055 if (filedes
[1] < 0) {
1063 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1065 if (gmtime_s(result
, timep
) == 0)
1070 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1072 if (localtime_s(result
, timep
) == 0)
1077 char *mingw_getcwd(char *pointer
, int len
)
1079 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1080 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1082 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1083 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1086 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1087 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1088 HANDLE hnd
= CreateFileW(cwd
, 0,
1089 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1090 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1091 if (hnd
== INVALID_HANDLE_VALUE
)
1093 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1095 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1097 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1101 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1103 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1105 convert_slashes(pointer
);
1110 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1111 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1113 static const char *quote_arg_msvc(const char *arg
)
1115 /* count chars to quote */
1117 int force_quotes
= 0;
1119 const char *p
= arg
;
1120 if (!*p
) force_quotes
= 1;
1122 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1126 else if (*p
== '\\') {
1128 while (*p
== '\\') {
1133 if (*p
== '"' || !*p
)
1140 if (!force_quotes
&& n
== 0)
1143 /* insert \ where necessary */
1144 d
= q
= xmalloc(st_add3(len
, n
, 3));
1149 else if (*arg
== '\\') {
1151 while (*arg
== '\\') {
1155 if (*arg
== '"' || !*arg
) {
1158 /* don't escape the surrounding end quote */
1173 static const char *quote_arg_msys2(const char *arg
)
1175 struct strbuf buf
= STRBUF_INIT
;
1176 const char *p2
= arg
, *p
;
1178 for (p
= arg
; *p
; p
++) {
1179 int ws
= isspace(*p
);
1180 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1181 *p
!= '?' && *p
!= '*' && *p
!= '~')
1184 strbuf_addch(&buf
, '"');
1186 strbuf_add(&buf
, p2
, p
- p2
);
1187 if (*p
== '\\' || *p
== '"')
1188 strbuf_addch(&buf
, '\\');
1193 strbuf_addch(&buf
, '"');
1197 strbuf_add(&buf
, p2
, p
- p2
);
1199 strbuf_addch(&buf
, '"');
1200 return strbuf_detach(&buf
, 0);
1203 static const char *parse_interpreter(const char *cmd
)
1205 static char buf
[100];
1209 /* don't even try a .exe */
1211 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1214 fd
= open(cmd
, O_RDONLY
);
1217 n
= read(fd
, buf
, sizeof(buf
)-1);
1219 if (n
< 4) /* at least '#!/x' and not error */
1222 if (buf
[0] != '#' || buf
[1] != '!')
1225 p
= buf
+ strcspn(buf
, "\r\n");
1230 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1233 if ((opt
= strchr(p
+1, ' ')))
1239 * exe_only means that we only want to detect .exe files, but not scripts
1240 * (which do not have an extension)
1242 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1243 int isexe
, int exe_only
)
1245 char path
[MAX_PATH
];
1246 wchar_t wpath
[MAX_PATH
];
1247 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1249 if (xutftowcs_path(wpath
, path
) < 0)
1252 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1253 return xstrdup(path
);
1254 wpath
[wcslen(wpath
)-4] = '\0';
1255 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1256 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1257 path
[strlen(path
)-4] = '\0';
1258 return xstrdup(path
);
1265 * Determines the absolute path of cmd using the split path in path.
1266 * If cmd contains a slash or backslash, no lookup is performed.
1268 static char *path_lookup(const char *cmd
, int exe_only
)
1272 int len
= strlen(cmd
);
1273 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1275 if (strpbrk(cmd
, "/\\"))
1276 return xstrdup(cmd
);
1278 path
= mingw_getenv("PATH");
1283 const char *sep
= strchrnul(path
, ';');
1284 int dirlen
= sep
- path
;
1286 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1295 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1297 while (*s
&& *s
!= c
)
1302 /* Compare only keys */
1303 static int wenvcmp(const void *a
, const void *b
)
1305 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1306 size_t p_len
, q_len
;
1309 p_len
= wcschrnul(p
, L
'=') - p
;
1310 q_len
= wcschrnul(q
, L
'=') - q
;
1312 /* If the length differs, include the shorter key's NUL */
1315 else if (p_len
> q_len
)
1318 return _wcsnicmp(p
, q
, p_len
);
1322 * Build an environment block combining the inherited environment
1323 * merged with the given list of settings.
1325 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1326 * Values of the form "KEY" in deltaenv delete inherited values.
1328 * Multiple entries in deltaenv for the same key are explicitly allowed.
1330 * We return a contiguous block of UNICODE strings with a final trailing
1333 static wchar_t *make_environment_block(char **deltaenv
)
1335 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1336 size_t wlen
, s
, delta_size
, size
;
1338 wchar_t **array
= NULL
;
1339 size_t alloc
= 0, nr
= 0, i
;
1341 size
= 1; /* for extra NUL at the end */
1343 /* If there is no deltaenv to apply, simply return a copy. */
1344 if (!deltaenv
|| !*deltaenv
) {
1345 for (p
= wenv
; p
&& *p
; ) {
1346 size_t s
= wcslen(p
) + 1;
1351 ALLOC_ARRAY(result
, size
);
1352 COPY_ARRAY(result
, wenv
, size
);
1353 FreeEnvironmentStringsW(wenv
);
1358 * If there is a deltaenv, let's accumulate all keys into `array`,
1359 * sort them using the stable git_stable_qsort() and then copy,
1360 * skipping duplicate keys
1362 for (p
= wenv
; p
&& *p
; ) {
1363 ALLOC_GROW(array
, nr
+ 1, alloc
);
1370 /* (over-)assess size needed for wchar version of deltaenv */
1371 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1372 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1373 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1375 /* convert the deltaenv, appending to array */
1376 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1377 ALLOC_GROW(array
, nr
+ 1, alloc
);
1378 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1383 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1384 ALLOC_ARRAY(result
, size
+ delta_size
);
1386 for (p
= result
, i
= 0; i
< nr
; i
++) {
1387 /* Skip any duplicate keys; last one wins */
1388 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1391 /* Skip "to delete" entry */
1392 if (!wcschr(array
[i
], L
'='))
1395 size
= wcslen(array
[i
]) + 1;
1396 COPY_ARRAY(p
, array
[i
], size
);
1403 FreeEnvironmentStringsW(wenv
);
1407 static void do_unset_environment_variables(void)
1410 char *p
= unset_environment_variables
;
1417 char *comma
= strchr(p
, ',');
1429 struct pinfo_t
*next
;
1433 static struct pinfo_t
*pinfo
= NULL
;
1434 CRITICAL_SECTION pinfo_cs
;
1436 /* Used to match and chomp off path components */
1437 static inline int match_last_path_component(const char *path
, size_t *len
,
1438 const char *component
)
1440 size_t component_len
= strlen(component
);
1441 if (*len
< component_len
+ 1 ||
1442 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1443 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1445 *len
-= component_len
+ 1;
1446 /* chomp off repeated dir separators */
1447 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1452 static int is_msys2_sh(const char *cmd
)
1457 if (!strcmp(cmd
, "sh")) {
1458 static int ret
= -1;
1464 p
= path_lookup(cmd
, 0);
1468 size_t len
= strlen(p
);
1470 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1471 match_last_path_component(p
, &len
, "bin") &&
1472 match_last_path_component(p
, &len
, "usr");
1478 if (ends_with(cmd
, "\\sh.exe")) {
1482 sh
= path_lookup("sh", 0);
1484 return !fspathcmp(cmd
, sh
);
1490 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1492 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1494 static int restrict_handle_inheritance
= -1;
1496 PROCESS_INFORMATION pi
;
1497 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1498 HANDLE stdhandles
[3];
1499 DWORD stdhandles_count
= 0;
1502 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1503 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1506 const char *(*quote_arg
)(const char *arg
) =
1507 is_msys2_sh(cmd
? cmd
: *argv
) ?
1508 quote_arg_msys2
: quote_arg_msvc
;
1509 const char *strace_env
;
1511 /* Make sure to override previous errors, if any */
1514 if (restrict_handle_inheritance
< 0)
1515 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1517 * The following code to restrict which handles are inherited seems
1518 * to work properly only on Windows 7 and later, so let's disable it
1519 * on Windows Vista and 2008.
1521 if (restrict_handle_inheritance
< 0)
1522 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1524 do_unset_environment_variables();
1526 /* Determine whether or not we are associated to a console */
1527 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1528 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1529 FILE_ATTRIBUTE_NORMAL
, NULL
);
1530 if (cons
== INVALID_HANDLE_VALUE
) {
1531 /* There is no console associated with this process.
1532 * Since the child is a console process, Windows
1533 * would normally create a console window. But
1534 * since we'll be redirecting std streams, we do
1535 * not need the console.
1536 * It is necessary to use DETACHED_PROCESS
1537 * instead of CREATE_NO_WINDOW to make ssh
1538 * recognize that it has no console.
1540 flags
|= DETACHED_PROCESS
;
1542 /* There is already a console. If we specified
1543 * DETACHED_PROCESS here, too, Windows would
1544 * disassociate the child from the console.
1545 * The same is true for CREATE_NO_WINDOW.
1550 memset(&si
, 0, sizeof(si
));
1551 si
.StartupInfo
.cb
= sizeof(si
);
1552 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1553 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1554 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1556 /* The list of handles cannot contain duplicates */
1557 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1558 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1559 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1560 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1561 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1562 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1563 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1564 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1565 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1566 if (stdhandles_count
)
1567 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1569 if (*argv
&& !strcmp(cmd
, *argv
))
1571 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1573 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1576 /* concatenate argv, quoting args as we go */
1577 strbuf_init(&args
, 0);
1579 char *quoted
= (char *)quote_arg(cmd
);
1580 strbuf_addstr(&args
, quoted
);
1584 for (; *argv
; argv
++) {
1585 char *quoted
= (char *)quote_arg(*argv
);
1587 strbuf_addch(&args
, ' ');
1588 strbuf_addstr(&args
, quoted
);
1589 if (quoted
!= *argv
)
1593 strace_env
= getenv("GIT_STRACE_COMMANDS");
1595 char *p
= path_lookup("strace.exe", 1);
1597 return error("strace not found!");
1598 if (xutftowcs_path(wcmd
, p
) < 0) {
1603 if (!strcmp("1", strace_env
) ||
1604 !strcasecmp("yes", strace_env
) ||
1605 !strcasecmp("true", strace_env
))
1606 strbuf_insert(&args
, 0, "strace ", 7);
1608 const char *quoted
= quote_arg(strace_env
);
1609 struct strbuf buf
= STRBUF_INIT
;
1610 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1611 if (quoted
!= strace_env
)
1612 free((char *)quoted
);
1613 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1614 strbuf_release(&buf
);
1618 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1619 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1620 strbuf_release(&args
);
1622 wenvblk
= make_environment_block(deltaenv
);
1624 memset(&pi
, 0, sizeof(pi
));
1625 if (restrict_handle_inheritance
&& stdhandles_count
&&
1626 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1627 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1628 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1629 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1630 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1631 UpdateProcThreadAttribute(attr_list
, 0,
1632 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1634 stdhandles_count
* sizeof(HANDLE
),
1636 si
.lpAttributeList
= attr_list
;
1637 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1640 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1641 stdhandles_count
? TRUE
: FALSE
,
1642 flags
, wenvblk
, dir
? wdir
: NULL
,
1643 &si
.StartupInfo
, &pi
);
1646 * On Windows 2008 R2, it seems that specifying certain types of handles
1647 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1648 * error. Rather than playing finicky and fragile games, let's just try
1649 * to detect this situation and simply try again without restricting any
1650 * handle inheritance. This is still better than failing to create
1653 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1654 DWORD err
= GetLastError();
1655 struct strbuf buf
= STRBUF_INIT
;
1657 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1659 * On Windows 7 and earlier, handles on pipes and character
1660 * devices are inherited automatically, and cannot be
1661 * specified in the thread handle list. Rather than trying
1662 * to catch each and every corner case (and running the
1663 * chance of *still* forgetting a few), let's just fall
1664 * back to creating the process without trying to limit the
1665 * handle inheritance.
1667 !(err
== ERROR_INVALID_PARAMETER
&&
1668 GetVersion() >> 16 < 9200) &&
1669 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1673 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1675 for (i
= 0; i
< stdhandles_count
; i
++) {
1676 HANDLE h
= stdhandles
[i
];
1677 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1678 "handle info (%d) %lx\n", i
, h
,
1680 GetHandleInformation(h
, &fl
),
1683 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1684 "at\nhttps://github.com/git-for-windows/"
1685 "git/issues/new\n\n"
1686 "To suppress this warning, please set "
1687 "the environment variable\n\n"
1688 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1691 restrict_handle_inheritance
= 0;
1692 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1693 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1694 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1695 &si
.StartupInfo
, &pi
);
1697 errno
= err_win_to_posix(GetLastError());
1698 if (ret
&& buf
.len
) {
1699 warning("failed to restrict file handles (%ld)\n\n%s",
1702 strbuf_release(&buf
);
1704 errno
= err_win_to_posix(GetLastError());
1706 if (si
.lpAttributeList
)
1707 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1709 HeapFree(GetProcessHeap(), 0, attr_list
);
1717 CloseHandle(pi
.hThread
);
1720 * The process ID is the human-readable identifier of the process
1721 * that we want to present in log and error messages. The handle
1722 * is not useful for this purpose. But we cannot close it, either,
1723 * because it is not possible to turn a process ID into a process
1724 * handle after the process terminated.
1725 * Keep the handle in a list for waitpid.
1727 EnterCriticalSection(&pinfo_cs
);
1729 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1730 info
->pid
= pi
.dwProcessId
;
1731 info
->proc
= pi
.hProcess
;
1735 LeaveCriticalSection(&pinfo_cs
);
1737 return (pid_t
)pi
.dwProcessId
;
1740 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1742 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1745 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1747 int fhin
, int fhout
, int fherr
)
1750 char *prog
= path_lookup(cmd
, 0);
1757 const char *interpr
= parse_interpreter(prog
);
1760 const char *argv0
= argv
[0];
1761 char *iprog
= path_lookup(interpr
, 1);
1768 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1769 fhin
, fhout
, fherr
);
1775 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1776 fhin
, fhout
, fherr
);
1782 static int try_shell_exec(const char *cmd
, char *const *argv
)
1784 const char *interpr
= parse_interpreter(cmd
);
1790 prog
= path_lookup(interpr
, 1);
1798 while (argv
[argc
]) argc
++;
1799 ALLOC_ARRAY(argv2
, argc
+ 1);
1800 argv2
[0] = (char *)cmd
; /* full path to the script file */
1801 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1802 exec_id
= trace2_exec(prog
, argv2
);
1803 pid
= mingw_spawnv(prog
, argv2
, 1);
1806 if (waitpid(pid
, &status
, 0) < 0)
1808 trace2_exec_result(exec_id
, status
);
1811 trace2_exec_result(exec_id
, -1);
1812 pid
= 1; /* indicate that we tried but failed */
1819 int mingw_execv(const char *cmd
, char *const *argv
)
1821 /* check if git_command is a shell script */
1822 if (!try_shell_exec(cmd
, argv
)) {
1826 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1827 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1829 trace2_exec_result(exec_id
, -1);
1832 if (waitpid(pid
, &status
, 0) < 0)
1834 trace2_exec_result(exec_id
, status
);
1840 int mingw_execvp(const char *cmd
, char *const *argv
)
1842 char *prog
= path_lookup(cmd
, 0);
1845 mingw_execv(prog
, argv
);
1853 int mingw_kill(pid_t pid
, int sig
)
1855 if (pid
> 0 && sig
== SIGTERM
) {
1856 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1858 if (TerminateProcess(h
, -1)) {
1863 errno
= err_win_to_posix(GetLastError());
1866 } else if (pid
> 0 && sig
== 0) {
1867 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1879 * UTF-8 versions of getenv(), putenv() and unsetenv().
1880 * Internally, they use the CRT's stock UNICODE routines
1881 * to avoid data loss.
1883 char *mingw_getenv(const char *name
)
1885 #define GETENV_MAX_RETAIN 64
1886 static char *values
[GETENV_MAX_RETAIN
];
1887 static int value_counter
;
1888 int len_key
, len_value
;
1891 wchar_t w_value
[32768];
1893 if (!name
|| !*name
)
1896 len_key
= strlen(name
) + 1;
1897 /* We cannot use xcalloc() here because that uses getenv() itself */
1898 w_key
= calloc(len_key
, sizeof(wchar_t));
1900 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1901 xutftowcs(w_key
, name
, len_key
);
1902 /* GetEnvironmentVariableW() only sets the last error upon failure */
1903 SetLastError(ERROR_SUCCESS
);
1904 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1905 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1911 len_value
= len_value
* 3 + 1;
1912 /* We cannot use xcalloc() here because that uses getenv() itself */
1913 value
= calloc(len_value
, sizeof(char));
1915 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1916 xwcstoutf(value
, w_value
, len_value
);
1919 * We return `value` which is an allocated value and the caller is NOT
1920 * expecting to have to free it, so we keep a round-robin array,
1921 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1923 free(values
[value_counter
]);
1924 values
[value_counter
++] = value
;
1925 if (value_counter
>= ARRAY_SIZE(values
))
1931 int mingw_putenv(const char *namevalue
)
1934 wchar_t *wide
, *equal
;
1937 if (!namevalue
|| !*namevalue
)
1940 size
= strlen(namevalue
) * 2 + 1;
1941 wide
= calloc(size
, sizeof(wchar_t));
1943 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1944 xutftowcs(wide
, namevalue
, size
);
1945 equal
= wcschr(wide
, L
'=');
1947 result
= SetEnvironmentVariableW(wide
, NULL
);
1950 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
1955 errno
= err_win_to_posix(GetLastError());
1957 return result
? 0 : -1;
1960 static void ensure_socket_initialization(void)
1963 static int initialized
= 0;
1968 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1969 die("unable to initialize winsock subsystem, error %d",
1972 atexit((void(*)(void)) WSACleanup
);
1977 int mingw_gethostname(char *name
, int namelen
)
1979 ensure_socket_initialization();
1980 return gethostname(name
, namelen
);
1983 #undef gethostbyname
1984 struct hostent
*mingw_gethostbyname(const char *host
)
1986 ensure_socket_initialization();
1987 return gethostbyname(host
);
1991 int mingw_getaddrinfo(const char *node
, const char *service
,
1992 const struct addrinfo
*hints
, struct addrinfo
**res
)
1994 ensure_socket_initialization();
1995 return getaddrinfo(node
, service
, hints
, res
);
1998 int mingw_socket(int domain
, int type
, int protocol
)
2003 ensure_socket_initialization();
2004 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2005 if (s
== INVALID_SOCKET
) {
2007 * WSAGetLastError() values are regular BSD error codes
2008 * biased by WSABASEERR.
2009 * However, strerror() does not know about networking
2010 * specific errors, which are values beginning at 38 or so.
2011 * Therefore, we choose to leave the biased error code
2012 * in errno so that _if_ someone looks up the code somewhere,
2013 * then it is at least the number that are usually listed.
2015 errno
= WSAGetLastError();
2018 /* convert into a file descriptor */
2019 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2021 return error("unable to make a socket file descriptor: %s",
2028 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2030 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2031 return connect(s
, sa
, sz
);
2035 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2037 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2038 return bind(s
, sa
, sz
);
2042 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2044 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2045 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2049 int mingw_shutdown(int sockfd
, int how
)
2051 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2052 return shutdown(s
, how
);
2056 int mingw_listen(int sockfd
, int backlog
)
2058 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2059 return listen(s
, backlog
);
2063 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2067 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2068 SOCKET s2
= accept(s1
, sa
, sz
);
2070 /* convert into a file descriptor */
2071 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2074 return error("unable to make a socket file descriptor: %s",
2081 int mingw_rename(const char *pold
, const char *pnew
)
2085 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2086 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2090 * Try native rename() first to get errno right.
2091 * It is based on MoveFile(), which cannot overwrite existing files.
2093 if (!_wrename(wpold
, wpnew
))
2095 if (errno
!= EEXIST
)
2098 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2100 /* TODO: translate more errors */
2101 gle
= GetLastError();
2102 if (gle
== ERROR_ACCESS_DENIED
&&
2103 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2104 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2105 DWORD attrsold
= GetFileAttributesW(wpold
);
2106 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2107 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2109 else if (!_wrmdir(wpnew
))
2113 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2114 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2115 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2117 gle
= GetLastError();
2118 /* revert file attributes on failure */
2119 SetFileAttributesW(wpnew
, attrs
);
2122 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2124 * We assume that some other process had the source or
2125 * destination file open at the wrong moment and retry.
2126 * In order to give the other process a higher chance to
2127 * complete its operation, we give up our time slice now.
2128 * If we have to retry again, we do sleep a bit.
2130 Sleep(delay
[tries
]);
2134 if (gle
== ERROR_ACCESS_DENIED
&&
2135 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2136 "Should I try again?", pold
, pnew
))
2144 * Note that this doesn't return the actual pagesize, but
2145 * the allocation granularity. If future Windows specific git code
2146 * needs the real getpagesize function, we need to find another solution.
2148 int mingw_getpagesize(void)
2152 return si
.dwAllocationGranularity
;
2155 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2156 enum EXTENDED_NAME_FORMAT
{
2158 NameUserPrincipal
= 8
2161 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2163 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, GetUserNameExW
,
2164 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2165 static wchar_t wbuffer
[1024];
2168 if (!INIT_PROC_ADDR(GetUserNameExW
))
2171 len
= ARRAY_SIZE(wbuffer
);
2172 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2173 char *converted
= xmalloc((len
*= 3));
2174 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2182 char *mingw_query_user_email(void)
2184 return get_extended_user_info(NameUserPrincipal
);
2187 struct passwd
*getpwuid(int uid
)
2189 static unsigned initialized
;
2190 static char user_name
[100];
2191 static struct passwd
*p
;
2198 len
= ARRAY_SIZE(buf
);
2199 if (!GetUserNameW(buf
, &len
)) {
2204 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2209 p
= xmalloc(sizeof(*p
));
2210 p
->pw_name
= user_name
;
2211 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2213 p
->pw_gecos
= "unknown";
2220 static HANDLE timer_event
;
2221 static HANDLE timer_thread
;
2222 static int timer_interval
;
2223 static int one_shot
;
2224 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2226 /* The timer works like this:
2227 * The thread, ticktack(), is a trivial routine that most of the time
2228 * only waits to receive the signal to terminate. The main thread tells
2229 * the thread to terminate by setting the timer_event to the signalled
2231 * But ticktack() interrupts the wait state after the timer's interval
2232 * length to call the signal handler.
2235 static unsigned __stdcall
ticktack(void *dummy
)
2237 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2238 mingw_raise(SIGALRM
);
2245 static int start_timer_thread(void)
2247 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2249 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2251 return errno
= ENOMEM
,
2252 error("cannot start timer thread");
2254 return errno
= ENOMEM
,
2255 error("cannot allocate resources for timer");
2259 static void stop_timer_thread(void)
2262 SetEvent(timer_event
); /* tell thread to terminate */
2264 int rc
= WaitForSingleObject(timer_thread
, 10000);
2265 if (rc
== WAIT_TIMEOUT
)
2266 error("timer thread did not terminate timely");
2267 else if (rc
!= WAIT_OBJECT_0
)
2268 error("waiting for timer thread failed: %lu",
2270 CloseHandle(timer_thread
);
2273 CloseHandle(timer_event
);
2275 timer_thread
= NULL
;
2278 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2280 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2283 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2285 static const struct timeval zero
;
2286 static int atexit_done
;
2289 return errno
= EINVAL
,
2290 error("setitimer param 3 != NULL not implemented");
2291 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2292 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2293 return errno
= EINVAL
,
2294 error("setitimer: it_interval must be zero or eq it_value");
2297 stop_timer_thread();
2299 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2300 is_timeval_eq(&in
->it_interval
, &zero
))
2303 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2304 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2306 atexit(stop_timer_thread
);
2309 return start_timer_thread();
2312 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2315 return errno
= EINVAL
,
2316 error("sigaction only implemented for SIGALRM");
2318 return errno
= EINVAL
,
2319 error("sigaction: param 3 != NULL not implemented");
2321 timer_fn
= in
->sa_handler
;
2326 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2338 sigint_fn
= handler
;
2342 return signal(sig
, handler
);
2349 int mingw_raise(int sig
)
2353 if (timer_fn
== SIG_DFL
) {
2354 if (isatty(STDERR_FILENO
))
2355 fputs("Alarm clock\n", stderr
);
2356 exit(128 + SIGALRM
);
2357 } else if (timer_fn
!= SIG_IGN
)
2362 if (sigint_fn
== SIG_DFL
)
2364 else if (sigint_fn
!= SIG_IGN
)
2368 #if defined(_MSC_VER)
2375 case SIGABRT_COMPAT
:
2377 * The <signal.h> header in the MS C Runtime defines 8 signals
2378 * as being supported on the platform. Anything else causes an
2379 * "Invalid signal or error" (which in DEBUG builds causes the
2380 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2381 * already know will fail.
2398 int link(const char *oldpath
, const char *newpath
)
2400 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2401 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2402 xutftowcs_path(wnewpath
, newpath
) < 0)
2405 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2406 errno
= err_win_to_posix(GetLastError());
2412 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2414 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2421 if (pid
> 0 && options
& WNOHANG
) {
2422 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2426 options
&= ~WNOHANG
;
2430 struct pinfo_t
**ppinfo
;
2431 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2437 GetExitCodeProcess(h
, (LPDWORD
)status
);
2439 EnterCriticalSection(&pinfo_cs
);
2443 struct pinfo_t
*info
= *ppinfo
;
2444 if (info
->pid
== pid
) {
2445 CloseHandle(info
->proc
);
2446 *ppinfo
= info
->next
;
2450 ppinfo
= &info
->next
;
2453 LeaveCriticalSection(&pinfo_cs
);
2464 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2466 int upos
= 0, wpos
= 0;
2467 const unsigned char *utf
= (const unsigned char*) utfs
;
2468 if (!utf
|| !wcs
|| wcslen
< 1) {
2472 /* reserve space for \0 */
2477 while (upos
< utflen
) {
2478 int c
= utf
[upos
++] & 0xff;
2479 if (utflen
== INT_MAX
&& c
== 0)
2482 if (wpos
>= wcslen
) {
2491 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2492 (utf
[upos
] & 0xc0) == 0x80) {
2494 c
= ((c
& 0x1f) << 6);
2495 c
|= (utf
[upos
++] & 0x3f);
2497 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2498 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2499 (utf
[upos
] & 0xc0) == 0x80 &&
2500 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2502 c
= ((c
& 0x0f) << 12);
2503 c
|= ((utf
[upos
++] & 0x3f) << 6);
2504 c
|= (utf
[upos
++] & 0x3f);
2506 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2507 wpos
+ 1 < wcslen
&&
2508 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2509 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2510 (utf
[upos
] & 0xc0) == 0x80 &&
2511 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2512 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2513 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2514 c
= ((c
& 0x07) << 18);
2515 c
|= ((utf
[upos
++] & 0x3f) << 12);
2516 c
|= ((utf
[upos
++] & 0x3f) << 6);
2517 c
|= (utf
[upos
++] & 0x3f);
2519 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2520 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2521 } else if (c
>= 0xa0) {
2522 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2525 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2526 static const char *hex
= "0123456789abcdef";
2527 wcs
[wpos
++] = hex
[c
>> 4];
2529 wcs
[wpos
++] = hex
[c
& 0x0f];
2536 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2538 if (!wcs
|| !utf
|| utflen
< 1) {
2542 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2549 static void setup_windows_environment(void)
2551 char *tmp
= getenv("TMPDIR");
2553 /* on Windows it is TMP and TEMP */
2555 if (!(tmp
= getenv("TMP")))
2556 tmp
= getenv("TEMP");
2558 setenv("TMPDIR", tmp
, 1);
2559 tmp
= getenv("TMPDIR");
2565 * Convert all dir separators to forward slashes,
2566 * to help shell commands called from the Git
2567 * executable (by not mistaking the dir separators
2568 * for escape characters).
2570 convert_slashes(tmp
);
2573 /* simulate TERM to enable auto-color (see color.c) */
2574 if (!getenv("TERM"))
2575 setenv("TERM", "cygwin", 1);
2577 /* calculate HOME if not set */
2578 if (!getenv("HOME")) {
2580 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2581 * location, thus also check if the path exists (i.e. is not
2584 if ((tmp
= getenv("HOMEDRIVE"))) {
2585 struct strbuf buf
= STRBUF_INIT
;
2586 strbuf_addstr(&buf
, tmp
);
2587 if ((tmp
= getenv("HOMEPATH"))) {
2588 strbuf_addstr(&buf
, tmp
);
2589 if (is_directory(buf
.buf
))
2590 setenv("HOME", buf
.buf
, 1);
2592 tmp
= NULL
; /* use $USERPROFILE */
2594 strbuf_release(&buf
);
2596 /* use $USERPROFILE if the home share is not available */
2597 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2598 setenv("HOME", tmp
, 1);
2602 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2604 const char *p
= path
;
2605 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2610 skip_dos_drive_prefix((char **)&path
);
2617 case '/': case '\\':
2618 /* cannot end in ` ` or `.`, except for `.` and `..` */
2619 if (preceding_space_or_period
&&
2620 (i
!= periods
|| periods
> 2))
2625 i
= periods
= preceding_space_or_period
= 0;
2629 case 'a': case 'A': /* AUX */
2630 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2631 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2632 not_a_reserved_name
:
2638 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2639 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2640 goto not_a_reserved_name
;
2642 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2644 if (c
< '1' || c
> '9')
2645 goto not_a_reserved_name
;
2646 } else if (c
== 'n' || c
== 'N') { /* CON */
2648 if ((c
== 'i' || c
== 'I') &&
2649 ((c
= path
[i
+ 2]) == 'n' ||
2652 i
+= 3; /* CONIN$ */
2653 else if ((c
== 'o' || c
== 'O') &&
2654 ((c
= path
[i
+ 2]) == 'u' ||
2656 ((c
= path
[i
+ 3]) == 't' ||
2659 i
+= 4; /* CONOUT$ */
2661 goto not_a_reserved_name
;
2663 case 'l': case 'L': /* LPT<N> */
2664 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2665 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2666 !isdigit(path
[++i
]))
2667 goto not_a_reserved_name
;
2669 case 'n': case 'N': /* NUL */
2670 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2671 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2672 (allow_literal_nul
&&
2673 !path
[i
+ 1] && p
== path
))
2674 goto not_a_reserved_name
;
2676 case 'p': case 'P': /* PRN */
2677 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2678 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2679 goto not_a_reserved_name
;
2686 * So far, this looks like a reserved name. Let's see
2687 * whether it actually is one: trailing spaces, a file
2688 * extension, or an NTFS Alternate Data Stream do not
2689 * matter, the name is still reserved if any of those
2690 * follow immediately after the actual name.
2693 if (path
[i
] == ' ') {
2694 preceding_space_or_period
= 1;
2695 while (path
[++i
] == ' ')
2696 ; /* skip all spaces */
2700 if (c
&& c
!= '.' && c
!= ':' && c
!= '/' && c
!= '\\')
2701 goto not_a_reserved_name
;
2703 /* contains reserved name */
2709 preceding_space_or_period
= 1;
2712 case ':': /* DOS drive prefix was already skipped */
2713 case '<': case '>': case '"': case '|': case '?': case '*':
2714 /* illegal character */
2717 if (c
> '\0' && c
< '\x20')
2718 /* illegal character */
2721 preceding_space_or_period
= 0;
2726 #if !defined(_MSC_VER)
2728 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2729 * mingw startup code, see init.c in mingw runtime).
2734 static NORETURN
void die_startup(void)
2736 fputs("fatal: not enough memory for initialization", stderr
);
2740 static void *malloc_startup(size_t size
)
2742 void *result
= malloc(size
);
2748 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2750 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2751 return memcpy(malloc_startup(len
), buffer
, len
);
2754 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2755 DWORD desired_access
, DWORD flags
)
2757 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2758 wchar_t buf
[MAX_PATH
];
2759 DWORD max
= ARRAY_SIZE(buf
);
2761 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2763 if (!ret
|| ret
>= max
)
2766 /* make sure this does not leak into child processes */
2767 SetEnvironmentVariableW(key
, NULL
);
2768 if (!wcscmp(buf
, L
"off")) {
2770 handle
= GetStdHandle(std_id
);
2771 if (handle
!= INVALID_HANDLE_VALUE
)
2772 CloseHandle(handle
);
2775 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2776 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2777 if (handle
== INVALID_HANDLE_VALUE
) {
2779 handle
= GetStdHandle(std_id
);
2780 if (handle
!= INVALID_HANDLE_VALUE
)
2781 CloseHandle(handle
);
2783 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2784 SetStdHandle(std_id
, handle
);
2786 /* do *not* close the new_fd: that would close stdout */
2790 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2792 if (handle
!= INVALID_HANDLE_VALUE
) {
2793 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2794 SetStdHandle(std_id
, handle
);
2800 static void maybe_redirect_std_handles(void)
2802 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2803 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2804 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2805 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2806 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2807 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2817 * We implement wmain() and compile with -municode, which would
2818 * normally ignore main(), but we call the latter from the former
2819 * so that we can handle non-ASCII command-line parameters
2822 * To be more compatible with the core git code, we convert
2823 * argv into UTF8 and pass them directly to main().
2825 int wmain(int argc
, const wchar_t **wargv
)
2827 int i
, maxlen
, exit_status
;
2828 char *buffer
, **save
;
2831 trace2_initialize_clock();
2835 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
2838 #ifdef USE_MSVC_CRTDBG
2839 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
2843 maybe_redirect_std_handles();
2845 /* determine size of argv and environ conversion buffer */
2846 maxlen
= wcslen(wargv
[0]);
2847 for (i
= 1; i
< argc
; i
++)
2848 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2850 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2851 maxlen
= 3 * maxlen
+ 1;
2852 buffer
= malloc_startup(maxlen
);
2855 * Create a UTF-8 version of w_argv. Also create a "save" copy
2856 * to remember all the string pointers because parse_options()
2857 * will remove claimed items from the argv that we pass down.
2859 ALLOC_ARRAY(argv
, argc
+ 1);
2860 ALLOC_ARRAY(save
, argc
+ 1);
2861 for (i
= 0; i
< argc
; i
++)
2862 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2863 argv
[i
] = save
[i
] = NULL
;
2866 /* fix Windows specific environment settings */
2867 setup_windows_environment();
2869 unset_environment_variables
= xstrdup("PERL5LIB");
2871 /* initialize critical section for waitpid pinfo_t list */
2872 InitializeCriticalSection(&pinfo_cs
);
2874 /* set up default file mode and file modes for stdin/out/err */
2876 _setmode(_fileno(stdin
), _O_BINARY
);
2877 _setmode(_fileno(stdout
), _O_BINARY
);
2878 _setmode(_fileno(stderr
), _O_BINARY
);
2880 /* initialize Unicode console */
2883 /* invoke the real main() using our utf8 version of argv. */
2884 exit_status
= main(argc
, argv
);
2886 for (i
= 0; i
< argc
; i
++)
2894 int uname(struct utsname
*buf
)
2896 unsigned v
= (unsigned)GetVersion();
2897 memset(buf
, 0, sizeof(*buf
));
2898 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
2899 xsnprintf(buf
->release
, sizeof(buf
->release
),
2900 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
2901 /* assuming NT variants only.. */
2902 xsnprintf(buf
->version
, sizeof(buf
->version
),
2903 "%u", (v
>> 16) & 0x7fff);