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
];
347 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
348 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
349 * symbolic link (if it points to a directory).
351 * This behavior breaks the assumption of e.g. `remove_path()` which
352 * upon successful deletion of a file will attempt to remove its parent
353 * directories recursively until failure (which usually happens when
354 * the directory is not empty).
356 * Therefore, before calling `_wrmdir()`, we first check if the path is
357 * a symbolic link. If it is, we exit and return the same error as
358 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
360 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
365 if (xutftowcs_path(wpathname
, pathname
) < 0)
368 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
369 if (!is_file_in_use_error(GetLastError()))
370 errno
= err_win_to_posix(GetLastError());
373 if (!is_dir_empty(wpathname
)) {
378 * We assume that some other process had the source or
379 * destination file open at the wrong moment and retry.
380 * In order to give the other process a higher chance to
381 * complete its operation, we give up our time slice now.
382 * If we have to retry again, we do sleep a bit.
387 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
388 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
389 "Should I try again?", pathname
))
390 ret
= _wrmdir(wpathname
);
392 invalidate_lstat_cache();
396 static inline int needs_hiding(const char *path
)
398 const char *basename
;
400 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
403 /* We cannot use basename(), as it would remove trailing slashes */
404 win32_skip_dos_drive_prefix((char **)&path
);
408 for (basename
= path
; *path
; path
++)
409 if (is_dir_sep(*path
)) {
412 } while (is_dir_sep(*path
));
413 /* ignore trailing slashes */
420 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
421 return *basename
== '.';
423 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
424 return !strncasecmp(".git", basename
, 4) &&
425 (!basename
[4] || is_dir_sep(basename
[4]));
428 static int set_hidden_flag(const wchar_t *path
, int set
)
430 DWORD original
= GetFileAttributesW(path
), modified
;
432 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
434 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
435 if (original
== modified
|| SetFileAttributesW(path
, modified
))
437 errno
= err_win_to_posix(GetLastError());
441 int mingw_mkdir(const char *path
, int mode
)
444 wchar_t wpath
[MAX_PATH
];
446 if (!is_valid_win32_path(path
, 0)) {
451 if (xutftowcs_path(wpath
, path
) < 0)
453 ret
= _wmkdir(wpath
);
454 if (!ret
&& needs_hiding(path
))
455 return set_hidden_flag(wpath
, 1);
460 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
461 * is documented in [1] as opening a writable file handle in append mode.
462 * (It is believed that) this is atomic since it is maintained by the
463 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
465 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
467 * This trick does not appear to work for named pipes. Instead it creates
468 * a named pipe client handle that cannot be written to. Callers should
469 * just use the regular _wopen() for them. (And since client handle gets
470 * bound to a unique server handle, it isn't really an issue.)
472 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
476 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
478 /* only these flags are supported */
479 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
480 return errno
= ENOSYS
, -1;
483 * FILE_SHARE_WRITE is required to permit child processes
484 * to append to the file.
486 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
487 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
488 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
489 if (handle
== INVALID_HANDLE_VALUE
) {
490 DWORD err
= GetLastError();
493 * Some network storage solutions (e.g. Isilon) might return
494 * ERROR_INVALID_PARAMETER instead of expected error
495 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
496 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
498 if (err
== ERROR_INVALID_PARAMETER
)
499 err
= ERROR_PATH_NOT_FOUND
;
501 errno
= err_win_to_posix(err
);
506 * No O_APPEND here, because the CRT uses it only to reset the
507 * file pointer to EOF before each write(); but that is not
508 * necessary (and may lead to races) for a file created with
511 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
518 * Does the pathname map to the local named pipe filesystem?
519 * That is, does it have a "//./pipe/" prefix?
521 static int is_local_named_pipe_path(const char *filename
)
523 return (is_dir_sep(filename
[0]) &&
524 is_dir_sep(filename
[1]) &&
525 filename
[2] == '.' &&
526 is_dir_sep(filename
[3]) &&
527 !strncasecmp(filename
+4, "pipe", 4) &&
528 is_dir_sep(filename
[8]) &&
532 int mingw_open (const char *filename
, int oflags
, ...)
534 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
537 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
538 wchar_t wfilename
[MAX_PATH
];
541 va_start(args
, oflags
);
542 mode
= va_arg(args
, int);
545 if (!is_valid_win32_path(filename
, !create
)) {
546 errno
= create
? EINVAL
: ENOENT
;
550 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
551 open_fn
= mingw_open_append
;
555 if (filename
&& !strcmp(filename
, "/dev/null"))
556 wcscpy(wfilename
, L
"nul");
557 else if (xutftowcs_path(wfilename
, filename
) < 0)
560 fd
= open_fn(wfilename
, oflags
, mode
);
562 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
563 DWORD attrs
= GetFileAttributesW(wfilename
);
564 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
567 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
569 * Internally, _wopen() uses the CreateFile() API which errors
570 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
571 * specified and an already existing file's attributes do not
572 * match *exactly*. As there is no mode or flag we can set that
573 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
574 * again *without* the O_CREAT flag (that corresponds to the
575 * CREATE_ALWAYS flag of CreateFile()).
577 if (fd
< 0 && errno
== EACCES
)
578 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
579 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
580 warning("could not mark '%s' as hidden.", filename
);
585 static BOOL WINAPI
ctrl_ignore(DWORD type
)
591 int mingw_fgetc(FILE *stream
)
594 if (!isatty(_fileno(stream
)))
595 return fgetc(stream
);
597 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
600 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
603 /* Ctrl+C was pressed, simulate SIGINT and retry */
606 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
611 FILE *mingw_fopen (const char *filename
, const char *otype
)
613 int hide
= needs_hiding(filename
);
615 wchar_t wfilename
[MAX_PATH
], wotype
[4];
616 if (filename
&& !strcmp(filename
, "/dev/null"))
617 wcscpy(wfilename
, L
"nul");
618 else if (!is_valid_win32_path(filename
, 1)) {
619 int create
= otype
&& strchr(otype
, 'w');
620 errno
= create
? EINVAL
: ENOENT
;
622 } else if (xutftowcs_path(wfilename
, filename
) < 0)
625 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
628 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
629 error("could not unhide %s", filename
);
632 file
= _wfopen(wfilename
, wotype
);
633 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
635 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
636 warning("could not mark '%s' as hidden.", filename
);
640 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
642 int hide
= needs_hiding(filename
);
644 wchar_t wfilename
[MAX_PATH
], wotype
[4];
645 if (filename
&& !strcmp(filename
, "/dev/null"))
646 wcscpy(wfilename
, L
"nul");
647 else if (!is_valid_win32_path(filename
, 1)) {
648 int create
= otype
&& strchr(otype
, 'w');
649 errno
= create
? EINVAL
: ENOENT
;
651 } else if (xutftowcs_path(wfilename
, filename
) < 0)
654 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
657 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
658 error("could not unhide %s", filename
);
661 file
= _wfreopen(wfilename
, wotype
, stream
);
662 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
663 warning("could not mark '%s' as hidden.", filename
);
668 int mingw_fflush(FILE *stream
)
670 int ret
= fflush(stream
);
673 * write() is used behind the scenes of stdio output functions.
674 * Since git code does not check for errors after each stdio write
675 * operation, it can happen that write() is called by a later
676 * stdio function even if an earlier write() call failed. In the
677 * case of a pipe whose readable end was closed, only the first
678 * call to write() reports EPIPE on Windows. Subsequent write()
679 * calls report EINVAL. It is impossible to notice whether this
680 * fflush invocation triggered such a case, therefore, we have to
681 * catch all EINVAL errors whole-sale.
683 if (ret
&& errno
== EINVAL
)
690 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
692 ssize_t result
= write(fd
, buf
, len
);
694 if (result
< 0 && errno
== EINVAL
&& buf
) {
695 /* check if fd is a pipe */
696 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
697 if (GetFileType(h
) == FILE_TYPE_PIPE
)
706 int mingw_access(const char *filename
, int mode
)
708 wchar_t wfilename
[MAX_PATH
];
709 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
711 if (xutftowcs_path(wfilename
, filename
) < 0)
713 /* X_OK is not supported by the MSVCRT version */
714 return _waccess(wfilename
, mode
& ~X_OK
);
717 int mingw_chdir(const char *dirname
)
719 wchar_t wdirname
[MAX_PATH
];
720 if (xutftowcs_path(wdirname
, dirname
) < 0)
722 return _wchdir(wdirname
);
725 int mingw_chmod(const char *filename
, int mode
)
727 wchar_t wfilename
[MAX_PATH
];
728 if (xutftowcs_path(wfilename
, filename
) < 0)
730 return _wchmod(wfilename
, mode
);
734 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
735 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
737 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
739 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
740 /* Windows to Unix Epoch conversion */
741 return winTime
- 116444736000000000LL;
744 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
746 long long hnsec
= filetime_to_hnsec(ft
);
747 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
748 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
752 * Verifies that safe_create_leading_directories() would succeed.
754 static int has_valid_directory_prefix(wchar_t *wfilename
)
756 int n
= wcslen(wfilename
);
759 wchar_t c
= wfilename
[--n
];
765 wfilename
[n
] = L
'\0';
766 attributes
= GetFileAttributesW(wfilename
);
768 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
769 attributes
== FILE_ATTRIBUTE_DEVICE
)
771 if (attributes
== INVALID_FILE_ATTRIBUTES
)
772 switch (GetLastError()) {
773 case ERROR_PATH_NOT_FOUND
:
775 case ERROR_FILE_NOT_FOUND
:
776 /* This implies parent directory exists. */
784 /* We keep the do_lstat code in a separate function to avoid recursion.
785 * When a path ends with a slash, the stat will fail with ENOENT. In
786 * this case, we strip the trailing slashes and stat again.
788 * If follow is true then act like stat() and report on the link
789 * target. Otherwise report on the link itself.
791 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
793 WIN32_FILE_ATTRIBUTE_DATA fdata
;
794 wchar_t wfilename
[MAX_PATH
];
795 if (xutftowcs_path(wfilename
, file_name
) < 0)
798 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
803 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
804 buf
->st_size
= fdata
.nFileSizeLow
|
805 (((off_t
)fdata
.nFileSizeHigh
)<<32);
806 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
807 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
808 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
809 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
810 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
811 WIN32_FIND_DATAW findbuf
;
812 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
813 if (handle
!= INVALID_HANDLE_VALUE
) {
814 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
815 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
817 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
818 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
820 buf
->st_mode
= S_IFLNK
;
822 buf
->st_mode
|= S_IREAD
;
823 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
824 buf
->st_mode
|= S_IWRITE
;
831 switch (GetLastError()) {
832 case ERROR_ACCESS_DENIED
:
833 case ERROR_SHARING_VIOLATION
:
834 case ERROR_LOCK_VIOLATION
:
835 case ERROR_SHARING_BUFFER_EXCEEDED
:
838 case ERROR_BUFFER_OVERFLOW
:
839 errno
= ENAMETOOLONG
;
841 case ERROR_NOT_ENOUGH_MEMORY
:
844 case ERROR_PATH_NOT_FOUND
:
845 if (!has_valid_directory_prefix(wfilename
)) {
857 /* We provide our own lstat/fstat functions, since the provided
858 * lstat/fstat functions are so slow. These stat functions are
859 * tailored for Git's usage (read: fast), and are not meant to be
860 * complete. Note that Git stat()s are redirected to mingw_lstat()
861 * too, since Windows doesn't really handle symlinks that well.
863 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
866 char alt_name
[PATH_MAX
];
868 if (!do_lstat(follow
, file_name
, buf
))
871 /* if file_name ended in a '/', Windows returned ENOENT;
872 * try again without trailing slashes
877 namelen
= strlen(file_name
);
878 if (namelen
&& file_name
[namelen
-1] != '/')
880 while (namelen
&& file_name
[namelen
-1] == '/')
882 if (!namelen
|| namelen
>= PATH_MAX
)
885 memcpy(alt_name
, file_name
, namelen
);
886 alt_name
[namelen
] = 0;
887 return do_lstat(follow
, alt_name
, buf
);
890 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
892 BY_HANDLE_FILE_INFORMATION fdata
;
894 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
895 errno
= err_win_to_posix(GetLastError());
903 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
904 buf
->st_size
= fdata
.nFileSizeLow
|
905 (((off_t
)fdata
.nFileSizeHigh
)<<32);
906 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
907 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
908 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
909 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
913 int mingw_lstat(const char *file_name
, struct stat
*buf
)
915 return do_stat_internal(0, file_name
, buf
);
917 int mingw_stat(const char *file_name
, struct stat
*buf
)
919 return do_stat_internal(1, file_name
, buf
);
922 int mingw_fstat(int fd
, struct stat
*buf
)
924 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
925 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
929 return get_file_info_by_handle(fh
, buf
);
933 /* initialize stat fields */
934 memset(buf
, 0, sizeof(*buf
));
937 if (type
== FILE_TYPE_CHAR
) {
938 buf
->st_mode
= _S_IFCHR
;
940 buf
->st_mode
= _S_IFIFO
;
941 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
942 buf
->st_size
= avail
;
952 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
954 long long winTime
= t
* 10000000LL + 116444736000000000LL;
955 ft
->dwLowDateTime
= winTime
;
956 ft
->dwHighDateTime
= winTime
>> 32;
959 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
964 wchar_t wfilename
[MAX_PATH
];
965 if (xutftowcs_path(wfilename
, file_name
) < 0)
968 /* must have write permission */
969 attrs
= GetFileAttributesW(wfilename
);
970 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
971 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
972 /* ignore errors here; open() will report them */
973 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
976 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
982 time_t_to_filetime(times
->modtime
, &mft
);
983 time_t_to_filetime(times
->actime
, &aft
);
985 GetSystemTimeAsFileTime(&mft
);
988 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
996 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
997 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
998 /* ignore errors again */
999 SetFileAttributesW(wfilename
, attrs
);
1005 size_t mingw_strftime(char *s
, size_t max
,
1006 const char *format
, const struct tm
*tm
)
1008 /* a pointer to the original strftime in case we can't find the UCRT version */
1009 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1011 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, strftime
, char *, size_t,
1012 const char *, const struct tm
*);
1014 if (INIT_PROC_ADDR(strftime
))
1015 ret
= strftime(s
, max
, format
, tm
);
1017 ret
= fallback(s
, max
, format
, tm
);
1019 if (!ret
&& errno
== EINVAL
)
1020 die("invalid strftime format: '%s'", format
);
1024 unsigned int sleep (unsigned int seconds
)
1026 Sleep(seconds
*1000);
1030 char *mingw_mktemp(char *template)
1032 wchar_t wtemplate
[MAX_PATH
];
1033 if (xutftowcs_path(wtemplate
, template) < 0)
1035 if (!_wmktemp(wtemplate
))
1037 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1042 int mkstemp(char *template)
1044 char *filename
= mktemp(template);
1045 if (filename
== NULL
)
1047 return open(filename
, O_RDWR
| O_CREAT
, 0600);
1050 int gettimeofday(struct timeval
*tv
, void *tz
)
1055 GetSystemTimeAsFileTime(&ft
);
1056 hnsec
= filetime_to_hnsec(&ft
);
1057 tv
->tv_sec
= hnsec
/ 10000000;
1058 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1062 int pipe(int filedes
[2])
1066 /* this creates non-inheritable handles */
1067 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1068 errno
= err_win_to_posix(GetLastError());
1071 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1072 if (filedes
[0] < 0) {
1077 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1078 if (filedes
[1] < 0) {
1086 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1088 if (gmtime_s(result
, timep
) == 0)
1093 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1095 if (localtime_s(result
, timep
) == 0)
1100 char *mingw_getcwd(char *pointer
, int len
)
1102 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1103 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1105 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1106 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1109 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1110 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1111 HANDLE hnd
= CreateFileW(cwd
, 0,
1112 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1113 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1114 if (hnd
== INVALID_HANDLE_VALUE
)
1116 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1118 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1120 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1124 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1126 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1128 convert_slashes(pointer
);
1133 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1134 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1136 static const char *quote_arg_msvc(const char *arg
)
1138 /* count chars to quote */
1140 int force_quotes
= 0;
1142 const char *p
= arg
;
1143 if (!*p
) force_quotes
= 1;
1145 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1149 else if (*p
== '\\') {
1151 while (*p
== '\\') {
1156 if (*p
== '"' || !*p
)
1163 if (!force_quotes
&& n
== 0)
1166 /* insert \ where necessary */
1167 d
= q
= xmalloc(st_add3(len
, n
, 3));
1172 else if (*arg
== '\\') {
1174 while (*arg
== '\\') {
1178 if (*arg
== '"' || !*arg
) {
1181 /* don't escape the surrounding end quote */
1196 static const char *quote_arg_msys2(const char *arg
)
1198 struct strbuf buf
= STRBUF_INIT
;
1199 const char *p2
= arg
, *p
;
1201 for (p
= arg
; *p
; p
++) {
1202 int ws
= isspace(*p
);
1203 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1204 *p
!= '?' && *p
!= '*' && *p
!= '~')
1207 strbuf_addch(&buf
, '"');
1209 strbuf_add(&buf
, p2
, p
- p2
);
1210 if (*p
== '\\' || *p
== '"')
1211 strbuf_addch(&buf
, '\\');
1216 strbuf_addch(&buf
, '"');
1220 strbuf_add(&buf
, p2
, p
- p2
);
1222 strbuf_addch(&buf
, '"');
1223 return strbuf_detach(&buf
, 0);
1226 static const char *parse_interpreter(const char *cmd
)
1228 static char buf
[100];
1232 /* don't even try a .exe */
1234 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1237 fd
= open(cmd
, O_RDONLY
);
1240 n
= read(fd
, buf
, sizeof(buf
)-1);
1242 if (n
< 4) /* at least '#!/x' and not error */
1245 if (buf
[0] != '#' || buf
[1] != '!')
1248 p
= buf
+ strcspn(buf
, "\r\n");
1253 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1256 if ((opt
= strchr(p
+1, ' ')))
1262 * exe_only means that we only want to detect .exe files, but not scripts
1263 * (which do not have an extension)
1265 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1266 int isexe
, int exe_only
)
1268 char path
[MAX_PATH
];
1269 wchar_t wpath
[MAX_PATH
];
1270 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1272 if (xutftowcs_path(wpath
, path
) < 0)
1275 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1276 return xstrdup(path
);
1277 wpath
[wcslen(wpath
)-4] = '\0';
1278 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1279 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1280 path
[strlen(path
)-4] = '\0';
1281 return xstrdup(path
);
1288 * Determines the absolute path of cmd using the split path in path.
1289 * If cmd contains a slash or backslash, no lookup is performed.
1291 static char *path_lookup(const char *cmd
, int exe_only
)
1295 int len
= strlen(cmd
);
1296 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1298 if (strpbrk(cmd
, "/\\"))
1299 return xstrdup(cmd
);
1301 path
= mingw_getenv("PATH");
1306 const char *sep
= strchrnul(path
, ';');
1307 int dirlen
= sep
- path
;
1309 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1318 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1320 while (*s
&& *s
!= c
)
1325 /* Compare only keys */
1326 static int wenvcmp(const void *a
, const void *b
)
1328 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1329 size_t p_len
, q_len
;
1332 p_len
= wcschrnul(p
, L
'=') - p
;
1333 q_len
= wcschrnul(q
, L
'=') - q
;
1335 /* If the length differs, include the shorter key's NUL */
1338 else if (p_len
> q_len
)
1341 return _wcsnicmp(p
, q
, p_len
);
1345 * Build an environment block combining the inherited environment
1346 * merged with the given list of settings.
1348 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1349 * Values of the form "KEY" in deltaenv delete inherited values.
1351 * Multiple entries in deltaenv for the same key are explicitly allowed.
1353 * We return a contiguous block of UNICODE strings with a final trailing
1356 static wchar_t *make_environment_block(char **deltaenv
)
1358 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1359 size_t wlen
, s
, delta_size
, size
;
1361 wchar_t **array
= NULL
;
1362 size_t alloc
= 0, nr
= 0, i
;
1364 size
= 1; /* for extra NUL at the end */
1366 /* If there is no deltaenv to apply, simply return a copy. */
1367 if (!deltaenv
|| !*deltaenv
) {
1368 for (p
= wenv
; p
&& *p
; ) {
1369 size_t s
= wcslen(p
) + 1;
1374 ALLOC_ARRAY(result
, size
);
1375 COPY_ARRAY(result
, wenv
, size
);
1376 FreeEnvironmentStringsW(wenv
);
1381 * If there is a deltaenv, let's accumulate all keys into `array`,
1382 * sort them using the stable git_stable_qsort() and then copy,
1383 * skipping duplicate keys
1385 for (p
= wenv
; p
&& *p
; ) {
1386 ALLOC_GROW(array
, nr
+ 1, alloc
);
1393 /* (over-)assess size needed for wchar version of deltaenv */
1394 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1395 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1396 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1398 /* convert the deltaenv, appending to array */
1399 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1400 ALLOC_GROW(array
, nr
+ 1, alloc
);
1401 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1406 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1407 ALLOC_ARRAY(result
, size
+ delta_size
);
1409 for (p
= result
, i
= 0; i
< nr
; i
++) {
1410 /* Skip any duplicate keys; last one wins */
1411 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1414 /* Skip "to delete" entry */
1415 if (!wcschr(array
[i
], L
'='))
1418 size
= wcslen(array
[i
]) + 1;
1419 COPY_ARRAY(p
, array
[i
], size
);
1426 FreeEnvironmentStringsW(wenv
);
1430 static void do_unset_environment_variables(void)
1433 char *p
= unset_environment_variables
;
1440 char *comma
= strchr(p
, ',');
1452 struct pinfo_t
*next
;
1456 static struct pinfo_t
*pinfo
= NULL
;
1457 CRITICAL_SECTION pinfo_cs
;
1459 /* Used to match and chomp off path components */
1460 static inline int match_last_path_component(const char *path
, size_t *len
,
1461 const char *component
)
1463 size_t component_len
= strlen(component
);
1464 if (*len
< component_len
+ 1 ||
1465 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1466 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1468 *len
-= component_len
+ 1;
1469 /* chomp off repeated dir separators */
1470 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1475 static int is_msys2_sh(const char *cmd
)
1480 if (!strcmp(cmd
, "sh")) {
1481 static int ret
= -1;
1487 p
= path_lookup(cmd
, 0);
1491 size_t len
= strlen(p
);
1493 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1494 match_last_path_component(p
, &len
, "bin") &&
1495 match_last_path_component(p
, &len
, "usr");
1501 if (ends_with(cmd
, "\\sh.exe")) {
1505 sh
= path_lookup("sh", 0);
1507 return !fspathcmp(cmd
, sh
);
1513 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1515 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1517 static int restrict_handle_inheritance
= -1;
1519 PROCESS_INFORMATION pi
;
1520 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1521 HANDLE stdhandles
[3];
1522 DWORD stdhandles_count
= 0;
1525 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1526 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1529 const char *(*quote_arg
)(const char *arg
) =
1530 is_msys2_sh(cmd
? cmd
: *argv
) ?
1531 quote_arg_msys2
: quote_arg_msvc
;
1532 const char *strace_env
;
1534 /* Make sure to override previous errors, if any */
1537 if (restrict_handle_inheritance
< 0)
1538 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1540 * The following code to restrict which handles are inherited seems
1541 * to work properly only on Windows 7 and later, so let's disable it
1542 * on Windows Vista and 2008.
1544 if (restrict_handle_inheritance
< 0)
1545 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1547 do_unset_environment_variables();
1549 /* Determine whether or not we are associated to a console */
1550 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1551 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1552 FILE_ATTRIBUTE_NORMAL
, NULL
);
1553 if (cons
== INVALID_HANDLE_VALUE
) {
1554 /* There is no console associated with this process.
1555 * Since the child is a console process, Windows
1556 * would normally create a console window. But
1557 * since we'll be redirecting std streams, we do
1558 * not need the console.
1559 * It is necessary to use DETACHED_PROCESS
1560 * instead of CREATE_NO_WINDOW to make ssh
1561 * recognize that it has no console.
1563 flags
|= DETACHED_PROCESS
;
1565 /* There is already a console. If we specified
1566 * DETACHED_PROCESS here, too, Windows would
1567 * disassociate the child from the console.
1568 * The same is true for CREATE_NO_WINDOW.
1573 memset(&si
, 0, sizeof(si
));
1574 si
.StartupInfo
.cb
= sizeof(si
);
1575 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1576 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1577 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1579 /* The list of handles cannot contain duplicates */
1580 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1581 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1582 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1583 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1584 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1585 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1586 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1587 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1588 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1589 if (stdhandles_count
)
1590 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1592 if (*argv
&& !strcmp(cmd
, *argv
))
1594 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1596 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1599 /* concatenate argv, quoting args as we go */
1600 strbuf_init(&args
, 0);
1602 char *quoted
= (char *)quote_arg(cmd
);
1603 strbuf_addstr(&args
, quoted
);
1607 for (; *argv
; argv
++) {
1608 char *quoted
= (char *)quote_arg(*argv
);
1610 strbuf_addch(&args
, ' ');
1611 strbuf_addstr(&args
, quoted
);
1612 if (quoted
!= *argv
)
1616 strace_env
= getenv("GIT_STRACE_COMMANDS");
1618 char *p
= path_lookup("strace.exe", 1);
1620 return error("strace not found!");
1621 if (xutftowcs_path(wcmd
, p
) < 0) {
1626 if (!strcmp("1", strace_env
) ||
1627 !strcasecmp("yes", strace_env
) ||
1628 !strcasecmp("true", strace_env
))
1629 strbuf_insert(&args
, 0, "strace ", 7);
1631 const char *quoted
= quote_arg(strace_env
);
1632 struct strbuf buf
= STRBUF_INIT
;
1633 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1634 if (quoted
!= strace_env
)
1635 free((char *)quoted
);
1636 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1637 strbuf_release(&buf
);
1641 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1642 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1643 strbuf_release(&args
);
1645 wenvblk
= make_environment_block(deltaenv
);
1647 memset(&pi
, 0, sizeof(pi
));
1648 if (restrict_handle_inheritance
&& stdhandles_count
&&
1649 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1650 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1651 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1652 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1653 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1654 UpdateProcThreadAttribute(attr_list
, 0,
1655 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1657 stdhandles_count
* sizeof(HANDLE
),
1659 si
.lpAttributeList
= attr_list
;
1660 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1663 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1664 stdhandles_count
? TRUE
: FALSE
,
1665 flags
, wenvblk
, dir
? wdir
: NULL
,
1666 &si
.StartupInfo
, &pi
);
1669 * On Windows 2008 R2, it seems that specifying certain types of handles
1670 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1671 * error. Rather than playing finicky and fragile games, let's just try
1672 * to detect this situation and simply try again without restricting any
1673 * handle inheritance. This is still better than failing to create
1676 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1677 DWORD err
= GetLastError();
1678 struct strbuf buf
= STRBUF_INIT
;
1680 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1682 * On Windows 7 and earlier, handles on pipes and character
1683 * devices are inherited automatically, and cannot be
1684 * specified in the thread handle list. Rather than trying
1685 * to catch each and every corner case (and running the
1686 * chance of *still* forgetting a few), let's just fall
1687 * back to creating the process without trying to limit the
1688 * handle inheritance.
1690 !(err
== ERROR_INVALID_PARAMETER
&&
1691 GetVersion() >> 16 < 9200) &&
1692 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1696 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1698 for (i
= 0; i
< stdhandles_count
; i
++) {
1699 HANDLE h
= stdhandles
[i
];
1700 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1701 "handle info (%d) %lx\n", i
, h
,
1703 GetHandleInformation(h
, &fl
),
1706 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1707 "at\nhttps://github.com/git-for-windows/"
1708 "git/issues/new\n\n"
1709 "To suppress this warning, please set "
1710 "the environment variable\n\n"
1711 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1714 restrict_handle_inheritance
= 0;
1715 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1716 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1717 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1718 &si
.StartupInfo
, &pi
);
1720 errno
= err_win_to_posix(GetLastError());
1721 if (ret
&& buf
.len
) {
1722 warning("failed to restrict file handles (%ld)\n\n%s",
1725 strbuf_release(&buf
);
1727 errno
= err_win_to_posix(GetLastError());
1729 if (si
.lpAttributeList
)
1730 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1732 HeapFree(GetProcessHeap(), 0, attr_list
);
1740 CloseHandle(pi
.hThread
);
1743 * The process ID is the human-readable identifier of the process
1744 * that we want to present in log and error messages. The handle
1745 * is not useful for this purpose. But we cannot close it, either,
1746 * because it is not possible to turn a process ID into a process
1747 * handle after the process terminated.
1748 * Keep the handle in a list for waitpid.
1750 EnterCriticalSection(&pinfo_cs
);
1752 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1753 info
->pid
= pi
.dwProcessId
;
1754 info
->proc
= pi
.hProcess
;
1758 LeaveCriticalSection(&pinfo_cs
);
1760 return (pid_t
)pi
.dwProcessId
;
1763 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1765 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1768 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1770 int fhin
, int fhout
, int fherr
)
1773 char *prog
= path_lookup(cmd
, 0);
1780 const char *interpr
= parse_interpreter(prog
);
1783 const char *argv0
= argv
[0];
1784 char *iprog
= path_lookup(interpr
, 1);
1791 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1792 fhin
, fhout
, fherr
);
1798 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1799 fhin
, fhout
, fherr
);
1805 static int try_shell_exec(const char *cmd
, char *const *argv
)
1807 const char *interpr
= parse_interpreter(cmd
);
1813 prog
= path_lookup(interpr
, 1);
1821 while (argv
[argc
]) argc
++;
1822 ALLOC_ARRAY(argv2
, argc
+ 1);
1823 argv2
[0] = (char *)cmd
; /* full path to the script file */
1824 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1825 exec_id
= trace2_exec(prog
, argv2
);
1826 pid
= mingw_spawnv(prog
, argv2
, 1);
1829 if (waitpid(pid
, &status
, 0) < 0)
1831 trace2_exec_result(exec_id
, status
);
1834 trace2_exec_result(exec_id
, -1);
1835 pid
= 1; /* indicate that we tried but failed */
1842 int mingw_execv(const char *cmd
, char *const *argv
)
1844 /* check if git_command is a shell script */
1845 if (!try_shell_exec(cmd
, argv
)) {
1849 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1850 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1852 trace2_exec_result(exec_id
, -1);
1855 if (waitpid(pid
, &status
, 0) < 0)
1857 trace2_exec_result(exec_id
, status
);
1863 int mingw_execvp(const char *cmd
, char *const *argv
)
1865 char *prog
= path_lookup(cmd
, 0);
1868 mingw_execv(prog
, argv
);
1876 int mingw_kill(pid_t pid
, int sig
)
1878 if (pid
> 0 && sig
== SIGTERM
) {
1879 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1881 if (TerminateProcess(h
, -1)) {
1886 errno
= err_win_to_posix(GetLastError());
1889 } else if (pid
> 0 && sig
== 0) {
1890 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1902 * UTF-8 versions of getenv(), putenv() and unsetenv().
1903 * Internally, they use the CRT's stock UNICODE routines
1904 * to avoid data loss.
1906 char *mingw_getenv(const char *name
)
1908 #define GETENV_MAX_RETAIN 64
1909 static char *values
[GETENV_MAX_RETAIN
];
1910 static int value_counter
;
1911 int len_key
, len_value
;
1914 wchar_t w_value
[32768];
1916 if (!name
|| !*name
)
1919 len_key
= strlen(name
) + 1;
1920 /* We cannot use xcalloc() here because that uses getenv() itself */
1921 w_key
= calloc(len_key
, sizeof(wchar_t));
1923 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1924 xutftowcs(w_key
, name
, len_key
);
1925 /* GetEnvironmentVariableW() only sets the last error upon failure */
1926 SetLastError(ERROR_SUCCESS
);
1927 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1928 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1934 len_value
= len_value
* 3 + 1;
1935 /* We cannot use xcalloc() here because that uses getenv() itself */
1936 value
= calloc(len_value
, sizeof(char));
1938 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1939 xwcstoutf(value
, w_value
, len_value
);
1942 * We return `value` which is an allocated value and the caller is NOT
1943 * expecting to have to free it, so we keep a round-robin array,
1944 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1946 free(values
[value_counter
]);
1947 values
[value_counter
++] = value
;
1948 if (value_counter
>= ARRAY_SIZE(values
))
1954 int mingw_putenv(const char *namevalue
)
1957 wchar_t *wide
, *equal
;
1960 if (!namevalue
|| !*namevalue
)
1963 size
= strlen(namevalue
) * 2 + 1;
1964 wide
= calloc(size
, sizeof(wchar_t));
1966 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1967 xutftowcs(wide
, namevalue
, size
);
1968 equal
= wcschr(wide
, L
'=');
1970 result
= SetEnvironmentVariableW(wide
, NULL
);
1973 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
1978 errno
= err_win_to_posix(GetLastError());
1980 return result
? 0 : -1;
1983 static void ensure_socket_initialization(void)
1986 static int initialized
= 0;
1991 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1992 die("unable to initialize winsock subsystem, error %d",
1995 atexit((void(*)(void)) WSACleanup
);
2000 int mingw_gethostname(char *name
, int namelen
)
2002 ensure_socket_initialization();
2003 return gethostname(name
, namelen
);
2006 #undef gethostbyname
2007 struct hostent
*mingw_gethostbyname(const char *host
)
2009 ensure_socket_initialization();
2010 return gethostbyname(host
);
2014 int mingw_getaddrinfo(const char *node
, const char *service
,
2015 const struct addrinfo
*hints
, struct addrinfo
**res
)
2017 ensure_socket_initialization();
2018 return getaddrinfo(node
, service
, hints
, res
);
2021 int mingw_socket(int domain
, int type
, int protocol
)
2026 ensure_socket_initialization();
2027 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2028 if (s
== INVALID_SOCKET
) {
2030 * WSAGetLastError() values are regular BSD error codes
2031 * biased by WSABASEERR.
2032 * However, strerror() does not know about networking
2033 * specific errors, which are values beginning at 38 or so.
2034 * Therefore, we choose to leave the biased error code
2035 * in errno so that _if_ someone looks up the code somewhere,
2036 * then it is at least the number that are usually listed.
2038 errno
= WSAGetLastError();
2041 /* convert into a file descriptor */
2042 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2044 return error("unable to make a socket file descriptor: %s",
2051 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2053 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2054 return connect(s
, sa
, sz
);
2058 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2060 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2061 return bind(s
, sa
, sz
);
2065 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2067 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2068 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2072 int mingw_shutdown(int sockfd
, int how
)
2074 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2075 return shutdown(s
, how
);
2079 int mingw_listen(int sockfd
, int backlog
)
2081 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2082 return listen(s
, backlog
);
2086 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2090 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2091 SOCKET s2
= accept(s1
, sa
, sz
);
2093 /* convert into a file descriptor */
2094 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2097 return error("unable to make a socket file descriptor: %s",
2104 int mingw_rename(const char *pold
, const char *pnew
)
2108 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2109 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2113 * Try native rename() first to get errno right.
2114 * It is based on MoveFile(), which cannot overwrite existing files.
2116 if (!_wrename(wpold
, wpnew
))
2118 if (errno
!= EEXIST
)
2121 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2123 /* TODO: translate more errors */
2124 gle
= GetLastError();
2125 if (gle
== ERROR_ACCESS_DENIED
&&
2126 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2127 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2128 DWORD attrsold
= GetFileAttributesW(wpold
);
2129 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2130 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2132 else if (!_wrmdir(wpnew
))
2136 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2137 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2138 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2140 gle
= GetLastError();
2141 /* revert file attributes on failure */
2142 SetFileAttributesW(wpnew
, attrs
);
2145 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2147 * We assume that some other process had the source or
2148 * destination file open at the wrong moment and retry.
2149 * In order to give the other process a higher chance to
2150 * complete its operation, we give up our time slice now.
2151 * If we have to retry again, we do sleep a bit.
2153 Sleep(delay
[tries
]);
2157 if (gle
== ERROR_ACCESS_DENIED
&&
2158 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2159 "Should I try again?", pold
, pnew
))
2167 * Note that this doesn't return the actual pagesize, but
2168 * the allocation granularity. If future Windows specific git code
2169 * needs the real getpagesize function, we need to find another solution.
2171 int mingw_getpagesize(void)
2175 return si
.dwAllocationGranularity
;
2178 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2179 enum EXTENDED_NAME_FORMAT
{
2181 NameUserPrincipal
= 8
2184 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2186 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, GetUserNameExW
,
2187 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2188 static wchar_t wbuffer
[1024];
2191 if (!INIT_PROC_ADDR(GetUserNameExW
))
2194 len
= ARRAY_SIZE(wbuffer
);
2195 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2196 char *converted
= xmalloc((len
*= 3));
2197 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2205 char *mingw_query_user_email(void)
2207 return get_extended_user_info(NameUserPrincipal
);
2210 struct passwd
*getpwuid(int uid
)
2212 static unsigned initialized
;
2213 static char user_name
[100];
2214 static struct passwd
*p
;
2221 len
= ARRAY_SIZE(buf
);
2222 if (!GetUserNameW(buf
, &len
)) {
2227 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2232 p
= xmalloc(sizeof(*p
));
2233 p
->pw_name
= user_name
;
2234 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2236 p
->pw_gecos
= "unknown";
2243 static HANDLE timer_event
;
2244 static HANDLE timer_thread
;
2245 static int timer_interval
;
2246 static int one_shot
;
2247 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2249 /* The timer works like this:
2250 * The thread, ticktack(), is a trivial routine that most of the time
2251 * only waits to receive the signal to terminate. The main thread tells
2252 * the thread to terminate by setting the timer_event to the signalled
2254 * But ticktack() interrupts the wait state after the timer's interval
2255 * length to call the signal handler.
2258 static unsigned __stdcall
ticktack(void *dummy
)
2260 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2261 mingw_raise(SIGALRM
);
2268 static int start_timer_thread(void)
2270 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2272 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2274 return errno
= ENOMEM
,
2275 error("cannot start timer thread");
2277 return errno
= ENOMEM
,
2278 error("cannot allocate resources for timer");
2282 static void stop_timer_thread(void)
2285 SetEvent(timer_event
); /* tell thread to terminate */
2287 int rc
= WaitForSingleObject(timer_thread
, 10000);
2288 if (rc
== WAIT_TIMEOUT
)
2289 error("timer thread did not terminate timely");
2290 else if (rc
!= WAIT_OBJECT_0
)
2291 error("waiting for timer thread failed: %lu",
2293 CloseHandle(timer_thread
);
2296 CloseHandle(timer_event
);
2298 timer_thread
= NULL
;
2301 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2303 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2306 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2308 static const struct timeval zero
;
2309 static int atexit_done
;
2312 return errno
= EINVAL
,
2313 error("setitimer param 3 != NULL not implemented");
2314 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2315 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2316 return errno
= EINVAL
,
2317 error("setitimer: it_interval must be zero or eq it_value");
2320 stop_timer_thread();
2322 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2323 is_timeval_eq(&in
->it_interval
, &zero
))
2326 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2327 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2329 atexit(stop_timer_thread
);
2332 return start_timer_thread();
2335 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2338 return errno
= EINVAL
,
2339 error("sigaction only implemented for SIGALRM");
2341 return errno
= EINVAL
,
2342 error("sigaction: param 3 != NULL not implemented");
2344 timer_fn
= in
->sa_handler
;
2349 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2361 sigint_fn
= handler
;
2365 return signal(sig
, handler
);
2372 int mingw_raise(int sig
)
2376 if (timer_fn
== SIG_DFL
) {
2377 if (isatty(STDERR_FILENO
))
2378 fputs("Alarm clock\n", stderr
);
2379 exit(128 + SIGALRM
);
2380 } else if (timer_fn
!= SIG_IGN
)
2385 if (sigint_fn
== SIG_DFL
)
2387 else if (sigint_fn
!= SIG_IGN
)
2391 #if defined(_MSC_VER)
2398 case SIGABRT_COMPAT
:
2400 * The <signal.h> header in the MS C Runtime defines 8 signals
2401 * as being supported on the platform. Anything else causes an
2402 * "Invalid signal or error" (which in DEBUG builds causes the
2403 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2404 * already know will fail.
2421 int link(const char *oldpath
, const char *newpath
)
2423 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2424 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2425 xutftowcs_path(wnewpath
, newpath
) < 0)
2428 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2429 errno
= err_win_to_posix(GetLastError());
2435 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2437 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2444 if (pid
> 0 && options
& WNOHANG
) {
2445 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2449 options
&= ~WNOHANG
;
2453 struct pinfo_t
**ppinfo
;
2454 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2460 GetExitCodeProcess(h
, (LPDWORD
)status
);
2462 EnterCriticalSection(&pinfo_cs
);
2466 struct pinfo_t
*info
= *ppinfo
;
2467 if (info
->pid
== pid
) {
2468 CloseHandle(info
->proc
);
2469 *ppinfo
= info
->next
;
2473 ppinfo
= &info
->next
;
2476 LeaveCriticalSection(&pinfo_cs
);
2487 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2489 int upos
= 0, wpos
= 0;
2490 const unsigned char *utf
= (const unsigned char*) utfs
;
2491 if (!utf
|| !wcs
|| wcslen
< 1) {
2495 /* reserve space for \0 */
2500 while (upos
< utflen
) {
2501 int c
= utf
[upos
++] & 0xff;
2502 if (utflen
== INT_MAX
&& c
== 0)
2505 if (wpos
>= wcslen
) {
2514 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2515 (utf
[upos
] & 0xc0) == 0x80) {
2517 c
= ((c
& 0x1f) << 6);
2518 c
|= (utf
[upos
++] & 0x3f);
2520 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2521 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2522 (utf
[upos
] & 0xc0) == 0x80 &&
2523 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2525 c
= ((c
& 0x0f) << 12);
2526 c
|= ((utf
[upos
++] & 0x3f) << 6);
2527 c
|= (utf
[upos
++] & 0x3f);
2529 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2530 wpos
+ 1 < wcslen
&&
2531 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2532 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2533 (utf
[upos
] & 0xc0) == 0x80 &&
2534 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2535 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2536 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2537 c
= ((c
& 0x07) << 18);
2538 c
|= ((utf
[upos
++] & 0x3f) << 12);
2539 c
|= ((utf
[upos
++] & 0x3f) << 6);
2540 c
|= (utf
[upos
++] & 0x3f);
2542 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2543 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2544 } else if (c
>= 0xa0) {
2545 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2548 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2549 static const char *hex
= "0123456789abcdef";
2550 wcs
[wpos
++] = hex
[c
>> 4];
2552 wcs
[wpos
++] = hex
[c
& 0x0f];
2559 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2561 if (!wcs
|| !utf
|| utflen
< 1) {
2565 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2572 static void setup_windows_environment(void)
2574 char *tmp
= getenv("TMPDIR");
2576 /* on Windows it is TMP and TEMP */
2578 if (!(tmp
= getenv("TMP")))
2579 tmp
= getenv("TEMP");
2581 setenv("TMPDIR", tmp
, 1);
2582 tmp
= getenv("TMPDIR");
2588 * Convert all dir separators to forward slashes,
2589 * to help shell commands called from the Git
2590 * executable (by not mistaking the dir separators
2591 * for escape characters).
2593 convert_slashes(tmp
);
2596 /* simulate TERM to enable auto-color (see color.c) */
2597 if (!getenv("TERM"))
2598 setenv("TERM", "cygwin", 1);
2600 /* calculate HOME if not set */
2601 if (!getenv("HOME")) {
2603 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2604 * location, thus also check if the path exists (i.e. is not
2607 if ((tmp
= getenv("HOMEDRIVE"))) {
2608 struct strbuf buf
= STRBUF_INIT
;
2609 strbuf_addstr(&buf
, tmp
);
2610 if ((tmp
= getenv("HOMEPATH"))) {
2611 strbuf_addstr(&buf
, tmp
);
2612 if (is_directory(buf
.buf
))
2613 setenv("HOME", buf
.buf
, 1);
2615 tmp
= NULL
; /* use $USERPROFILE */
2617 strbuf_release(&buf
);
2619 /* use $USERPROFILE if the home share is not available */
2620 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2621 setenv("HOME", tmp
, 1);
2625 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2627 const char *p
= path
;
2628 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2633 skip_dos_drive_prefix((char **)&path
);
2640 case '/': case '\\':
2641 /* cannot end in ` ` or `.`, except for `.` and `..` */
2642 if (preceding_space_or_period
&&
2643 (i
!= periods
|| periods
> 2))
2648 i
= periods
= preceding_space_or_period
= 0;
2652 case 'a': case 'A': /* AUX */
2653 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2654 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2655 not_a_reserved_name
:
2661 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2662 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2663 goto not_a_reserved_name
;
2665 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2667 if (c
< '1' || c
> '9')
2668 goto not_a_reserved_name
;
2669 } else if (c
== 'n' || c
== 'N') { /* CON */
2671 if ((c
== 'i' || c
== 'I') &&
2672 ((c
= path
[i
+ 2]) == 'n' ||
2675 i
+= 3; /* CONIN$ */
2676 else if ((c
== 'o' || c
== 'O') &&
2677 ((c
= path
[i
+ 2]) == 'u' ||
2679 ((c
= path
[i
+ 3]) == 't' ||
2682 i
+= 4; /* CONOUT$ */
2684 goto not_a_reserved_name
;
2686 case 'l': case 'L': /* LPT<N> */
2687 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2688 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2689 !isdigit(path
[++i
]))
2690 goto not_a_reserved_name
;
2692 case 'n': case 'N': /* NUL */
2693 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2694 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2695 (allow_literal_nul
&&
2696 !path
[i
+ 1] && p
== path
))
2697 goto not_a_reserved_name
;
2699 case 'p': case 'P': /* PRN */
2700 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2701 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2702 goto not_a_reserved_name
;
2709 * So far, this looks like a reserved name. Let's see
2710 * whether it actually is one: trailing spaces, a file
2711 * extension, or an NTFS Alternate Data Stream do not
2712 * matter, the name is still reserved if any of those
2713 * follow immediately after the actual name.
2716 if (path
[i
] == ' ') {
2717 preceding_space_or_period
= 1;
2718 while (path
[++i
] == ' ')
2719 ; /* skip all spaces */
2723 if (c
&& c
!= '.' && c
!= ':' && c
!= '/' && c
!= '\\')
2724 goto not_a_reserved_name
;
2726 /* contains reserved name */
2732 preceding_space_or_period
= 1;
2735 case ':': /* DOS drive prefix was already skipped */
2736 case '<': case '>': case '"': case '|': case '?': case '*':
2737 /* illegal character */
2740 if (c
> '\0' && c
< '\x20')
2741 /* illegal character */
2744 preceding_space_or_period
= 0;
2749 #if !defined(_MSC_VER)
2751 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2752 * mingw startup code, see init.c in mingw runtime).
2757 static NORETURN
void die_startup(void)
2759 fputs("fatal: not enough memory for initialization", stderr
);
2763 static void *malloc_startup(size_t size
)
2765 void *result
= malloc(size
);
2771 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2773 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2774 return memcpy(malloc_startup(len
), buffer
, len
);
2777 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2778 DWORD desired_access
, DWORD flags
)
2780 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2781 wchar_t buf
[MAX_PATH
];
2782 DWORD max
= ARRAY_SIZE(buf
);
2784 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2786 if (!ret
|| ret
>= max
)
2789 /* make sure this does not leak into child processes */
2790 SetEnvironmentVariableW(key
, NULL
);
2791 if (!wcscmp(buf
, L
"off")) {
2793 handle
= GetStdHandle(std_id
);
2794 if (handle
!= INVALID_HANDLE_VALUE
)
2795 CloseHandle(handle
);
2798 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2799 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2800 if (handle
== INVALID_HANDLE_VALUE
) {
2802 handle
= GetStdHandle(std_id
);
2803 if (handle
!= INVALID_HANDLE_VALUE
)
2804 CloseHandle(handle
);
2806 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2807 SetStdHandle(std_id
, handle
);
2809 /* do *not* close the new_fd: that would close stdout */
2813 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2815 if (handle
!= INVALID_HANDLE_VALUE
) {
2816 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2817 SetStdHandle(std_id
, handle
);
2823 static void maybe_redirect_std_handles(void)
2825 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2826 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2827 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2828 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2829 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2830 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2840 * We implement wmain() and compile with -municode, which would
2841 * normally ignore main(), but we call the latter from the former
2842 * so that we can handle non-ASCII command-line parameters
2845 * To be more compatible with the core git code, we convert
2846 * argv into UTF8 and pass them directly to main().
2848 int wmain(int argc
, const wchar_t **wargv
)
2850 int i
, maxlen
, exit_status
;
2851 char *buffer
, **save
;
2854 trace2_initialize_clock();
2858 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
2861 #ifdef USE_MSVC_CRTDBG
2862 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
2866 maybe_redirect_std_handles();
2868 /* determine size of argv and environ conversion buffer */
2869 maxlen
= wcslen(wargv
[0]);
2870 for (i
= 1; i
< argc
; i
++)
2871 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2873 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2874 maxlen
= 3 * maxlen
+ 1;
2875 buffer
= malloc_startup(maxlen
);
2878 * Create a UTF-8 version of w_argv. Also create a "save" copy
2879 * to remember all the string pointers because parse_options()
2880 * will remove claimed items from the argv that we pass down.
2882 ALLOC_ARRAY(argv
, argc
+ 1);
2883 ALLOC_ARRAY(save
, argc
+ 1);
2884 for (i
= 0; i
< argc
; i
++)
2885 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2886 argv
[i
] = save
[i
] = NULL
;
2889 /* fix Windows specific environment settings */
2890 setup_windows_environment();
2892 unset_environment_variables
= xstrdup("PERL5LIB");
2894 /* initialize critical section for waitpid pinfo_t list */
2895 InitializeCriticalSection(&pinfo_cs
);
2897 /* set up default file mode and file modes for stdin/out/err */
2899 _setmode(_fileno(stdin
), _O_BINARY
);
2900 _setmode(_fileno(stdout
), _O_BINARY
);
2901 _setmode(_fileno(stderr
), _O_BINARY
);
2903 /* initialize Unicode console */
2906 /* invoke the real main() using our utf8 version of argv. */
2907 exit_status
= main(argc
, argv
);
2909 for (i
= 0; i
< argc
; i
++)
2917 int uname(struct utsname
*buf
)
2919 unsigned v
= (unsigned)GetVersion();
2920 memset(buf
, 0, sizeof(*buf
));
2921 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
2922 xsnprintf(buf
->release
, sizeof(buf
->release
),
2923 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
2924 /* assuming NT variants only.. */
2925 xsnprintf(buf
->version
, sizeof(buf
->version
),
2926 "%u", (v
>> 16) & 0x7fff);