1 #include "../git-compat-util.h"
8 #include "../run-command.h"
10 #include "../abspath.h"
12 #include "win32/lazyload.h"
13 #include "../config.h"
14 #include "../environment.h"
15 #include "../wrapper.h"
18 #define SECURITY_WIN32
21 #define HCAST(type, handle) ((type)(intptr_t)handle)
23 static const int delay
[] = { 0, 1, 10, 20, 40 };
25 void open_in_gdb(void)
27 static struct child_process cp
= CHILD_PROCESS_INIT
;
30 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
31 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
33 if (start_command(&cp
) < 0)
34 die_errno("Could not start gdb");
38 int err_win_to_posix(DWORD winerr
)
42 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
43 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
44 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
45 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
46 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
47 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
48 case ERROR_BAD_COMMAND
: error
= EIO
; break;
49 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
50 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
51 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
52 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
53 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
54 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
55 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
56 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
57 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
58 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
59 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
60 case ERROR_BUSY
: error
= EBUSY
; break;
61 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
62 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
63 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
64 case ERROR_CANTOPEN
: error
= EIO
; break;
65 case ERROR_CANTREAD
: error
= EIO
; break;
66 case ERROR_CANTWRITE
: error
= EIO
; break;
67 case ERROR_CRC
: error
= EIO
; break;
68 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
69 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
70 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
71 case ERROR_DIRECTORY
: error
= EINVAL
; break;
72 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
73 case ERROR_DISK_CHANGE
: error
= EIO
; break;
74 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
75 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
76 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
77 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
78 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
79 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
80 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
81 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
82 case ERROR_GEN_FAILURE
: error
= EIO
; break;
83 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
84 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
85 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
86 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
87 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
88 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
89 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
90 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
91 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
92 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
93 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
94 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
95 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
96 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
97 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
98 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
99 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
100 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
101 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
102 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
103 case ERROR_IO_DEVICE
: error
= EIO
; break;
104 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
105 case ERROR_LOCKED
: error
= EBUSY
; break;
106 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
107 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
108 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
109 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
110 case ERROR_MORE_DATA
: error
= EPIPE
; break;
111 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
112 case ERROR_NOACCESS
: error
= EFAULT
; break;
113 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
114 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
115 case ERROR_NOT_READY
: error
= EAGAIN
; break;
116 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
117 case ERROR_NO_DATA
: error
= EPIPE
; break;
118 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
119 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
120 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
121 case ERROR_OPEN_FAILED
: error
= EIO
; break;
122 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
123 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
124 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
125 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
126 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
127 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
128 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
129 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
130 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
131 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
132 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
133 case ERROR_READ_FAULT
: error
= EIO
; break;
134 case ERROR_SEEK
: error
= EIO
; break;
135 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
136 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
137 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
138 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
139 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
140 case ERROR_SWAPERROR
: error
= ENOENT
; break;
141 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
142 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
143 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
144 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
145 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
146 case ERROR_WRITE_FAULT
: error
= EIO
; break;
147 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
152 static inline int is_file_in_use_error(DWORD errcode
)
155 case ERROR_SHARING_VIOLATION
:
156 case ERROR_ACCESS_DENIED
:
163 static int read_yes_no_answer(void)
167 if (fgets(answer
, sizeof(answer
), stdin
)) {
168 size_t answer_len
= strlen(answer
);
169 int got_full_line
= 0, c
;
171 /* remove the newline */
172 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
173 answer
[answer_len
-2] = '\0';
175 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
176 answer
[answer_len
-1] = '\0';
179 /* flush the buffer in case we did not get the full line */
181 while ((c
= getchar()) != EOF
&& c
!= '\n')
184 /* we could not read, return the
185 * default answer which is no */
188 if (tolower(answer
[0]) == 'y' && !answer
[1])
190 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
192 if (tolower(answer
[0]) == 'n' && !answer
[1])
194 if (!strncasecmp(answer
, "no", sizeof(answer
)))
197 /* did not find an answer we understand */
201 static int ask_yes_no_if_possible(const char *format
, ...)
204 const char *retry_hook
;
207 va_start(args
, format
);
208 vsnprintf(question
, sizeof(question
), format
, args
);
211 retry_hook
= mingw_getenv("GIT_ASK_YESNO");
213 struct child_process cmd
= CHILD_PROCESS_INIT
;
215 strvec_pushl(&cmd
.args
, retry_hook
, question
, NULL
);
216 return !run_command(&cmd
);
219 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
224 fprintf(stderr
, "%s (y/n) ", question
);
226 if ((answer
= read_yes_no_answer()) >= 0)
229 fprintf(stderr
, "Sorry, I did not understand your answer. "
230 "Please type 'y' or 'n'\n");
235 enum hide_dotfiles_type
{
236 HIDE_DOTFILES_FALSE
= 0,
238 HIDE_DOTFILES_DOTGITONLY
241 static int core_restrict_inherited_handles
= -1;
242 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
243 static char *unset_environment_variables
;
245 int mingw_core_config(const char *var
, const char *value
, void *cb
)
247 if (!strcmp(var
, "core.hidedotfiles")) {
248 if (value
&& !strcasecmp(value
, "dotgitonly"))
249 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
251 hide_dotfiles
= git_config_bool(var
, value
);
255 if (!strcmp(var
, "core.unsetenvvars")) {
256 free(unset_environment_variables
);
257 unset_environment_variables
= xstrdup(value
);
261 if (!strcmp(var
, "core.restrictinheritedhandles")) {
262 if (value
&& !strcasecmp(value
, "auto"))
263 core_restrict_inherited_handles
= -1;
265 core_restrict_inherited_handles
=
266 git_config_bool(var
, value
);
273 /* Normalizes NT paths as returned by some low-level APIs. */
274 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
277 /* fix absolute path prefixes */
278 if (wbuf
[0] == '\\') {
279 /* strip NT namespace prefixes */
280 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
281 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
283 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
285 /* replace remaining '...UNC\' with '\\' */
286 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
291 /* convert backslashes to slashes */
292 for (i
= 0; wbuf
[i
]; i
++)
298 int mingw_unlink(const char *pathname
)
301 wchar_t wpathname
[MAX_PATH
];
302 if (xutftowcs_path(wpathname
, pathname
) < 0)
305 if (DeleteFileW(wpathname
))
308 /* read-only files cannot be removed */
309 _wchmod(wpathname
, 0666);
310 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
311 if (!is_file_in_use_error(GetLastError()))
314 * We assume that some other process had the source or
315 * destination file open at the wrong moment and retry.
316 * In order to give the other process a higher chance to
317 * complete its operation, we give up our time slice now.
318 * If we have to retry again, we do sleep a bit.
323 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
324 ask_yes_no_if_possible("Unlink of file '%s' failed. "
325 "Should I try again?", pathname
))
326 ret
= _wunlink(wpathname
);
330 static int is_dir_empty(const wchar_t *wpath
)
332 WIN32_FIND_DATAW findbuf
;
334 wchar_t wbuf
[MAX_PATH
+ 2];
336 wcscat(wbuf
, L
"\\*");
337 handle
= FindFirstFileW(wbuf
, &findbuf
);
338 if (handle
== INVALID_HANDLE_VALUE
)
339 return GetLastError() == ERROR_NO_MORE_FILES
;
341 while (!wcscmp(findbuf
.cFileName
, L
".") ||
342 !wcscmp(findbuf
.cFileName
, L
".."))
343 if (!FindNextFileW(handle
, &findbuf
)) {
344 DWORD err
= GetLastError();
346 return err
== ERROR_NO_MORE_FILES
;
352 int mingw_rmdir(const char *pathname
)
355 wchar_t wpathname
[MAX_PATH
];
359 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
360 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
361 * symbolic link (if it points to a directory).
363 * This behavior breaks the assumption of e.g. `remove_path()` which
364 * upon successful deletion of a file will attempt to remove its parent
365 * directories recursively until failure (which usually happens when
366 * the directory is not empty).
368 * Therefore, before calling `_wrmdir()`, we first check if the path is
369 * a symbolic link. If it is, we exit and return the same error as
370 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
372 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
377 if (xutftowcs_path(wpathname
, pathname
) < 0)
380 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
381 if (!is_file_in_use_error(GetLastError()))
382 errno
= err_win_to_posix(GetLastError());
385 if (!is_dir_empty(wpathname
)) {
390 * We assume that some other process had the source or
391 * destination file open at the wrong moment and retry.
392 * In order to give the other process a higher chance to
393 * complete its operation, we give up our time slice now.
394 * If we have to retry again, we do sleep a bit.
399 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
400 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
401 "Should I try again?", pathname
))
402 ret
= _wrmdir(wpathname
);
404 invalidate_lstat_cache();
408 static inline int needs_hiding(const char *path
)
410 const char *basename
;
412 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
415 /* We cannot use basename(), as it would remove trailing slashes */
416 win32_skip_dos_drive_prefix((char **)&path
);
420 for (basename
= path
; *path
; path
++)
421 if (is_dir_sep(*path
)) {
424 } while (is_dir_sep(*path
));
425 /* ignore trailing slashes */
432 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
433 return *basename
== '.';
435 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
436 return !strncasecmp(".git", basename
, 4) &&
437 (!basename
[4] || is_dir_sep(basename
[4]));
440 static int set_hidden_flag(const wchar_t *path
, int set
)
442 DWORD original
= GetFileAttributesW(path
), modified
;
444 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
446 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
447 if (original
== modified
|| SetFileAttributesW(path
, modified
))
449 errno
= err_win_to_posix(GetLastError());
453 int mingw_mkdir(const char *path
, int mode
)
456 wchar_t wpath
[MAX_PATH
];
458 if (!is_valid_win32_path(path
, 0)) {
463 if (xutftowcs_path(wpath
, path
) < 0)
465 ret
= _wmkdir(wpath
);
466 if (!ret
&& needs_hiding(path
))
467 return set_hidden_flag(wpath
, 1);
472 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
473 * is documented in [1] as opening a writable file handle in append mode.
474 * (It is believed that) this is atomic since it is maintained by the
475 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
477 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
479 * This trick does not appear to work for named pipes. Instead it creates
480 * a named pipe client handle that cannot be written to. Callers should
481 * just use the regular _wopen() for them. (And since client handle gets
482 * bound to a unique server handle, it isn't really an issue.)
484 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
488 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
490 /* only these flags are supported */
491 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
492 return errno
= ENOSYS
, -1;
495 * FILE_SHARE_WRITE is required to permit child processes
496 * to append to the file.
498 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
499 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
500 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
501 if (handle
== INVALID_HANDLE_VALUE
) {
502 DWORD err
= GetLastError();
505 * Some network storage solutions (e.g. Isilon) might return
506 * ERROR_INVALID_PARAMETER instead of expected error
507 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
508 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
510 if (err
== ERROR_INVALID_PARAMETER
)
511 err
= ERROR_PATH_NOT_FOUND
;
513 errno
= err_win_to_posix(err
);
518 * No O_APPEND here, because the CRT uses it only to reset the
519 * file pointer to EOF before each write(); but that is not
520 * necessary (and may lead to races) for a file created with
523 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
530 * Does the pathname map to the local named pipe filesystem?
531 * That is, does it have a "//./pipe/" prefix?
533 static int is_local_named_pipe_path(const char *filename
)
535 return (is_dir_sep(filename
[0]) &&
536 is_dir_sep(filename
[1]) &&
537 filename
[2] == '.' &&
538 is_dir_sep(filename
[3]) &&
539 !strncasecmp(filename
+4, "pipe", 4) &&
540 is_dir_sep(filename
[8]) &&
544 int mingw_open (const char *filename
, int oflags
, ...)
546 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
549 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
550 wchar_t wfilename
[MAX_PATH
];
553 va_start(args
, oflags
);
554 mode
= va_arg(args
, int);
557 if (!is_valid_win32_path(filename
, !create
)) {
558 errno
= create
? EINVAL
: ENOENT
;
562 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
563 open_fn
= mingw_open_append
;
567 if (filename
&& !strcmp(filename
, "/dev/null"))
568 wcscpy(wfilename
, L
"nul");
569 else if (xutftowcs_path(wfilename
, filename
) < 0)
572 fd
= open_fn(wfilename
, oflags
, mode
);
574 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
575 DWORD attrs
= GetFileAttributesW(wfilename
);
576 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
579 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
581 * Internally, _wopen() uses the CreateFile() API which errors
582 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
583 * specified and an already existing file's attributes do not
584 * match *exactly*. As there is no mode or flag we can set that
585 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
586 * again *without* the O_CREAT flag (that corresponds to the
587 * CREATE_ALWAYS flag of CreateFile()).
589 if (fd
< 0 && errno
== EACCES
)
590 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
591 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
592 warning("could not mark '%s' as hidden.", filename
);
597 static BOOL WINAPI
ctrl_ignore(DWORD type
)
603 int mingw_fgetc(FILE *stream
)
606 if (!isatty(_fileno(stream
)))
607 return fgetc(stream
);
609 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
612 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
615 /* Ctrl+C was pressed, simulate SIGINT and retry */
618 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
623 FILE *mingw_fopen (const char *filename
, const char *otype
)
625 int hide
= needs_hiding(filename
);
627 wchar_t wfilename
[MAX_PATH
], wotype
[4];
628 if (filename
&& !strcmp(filename
, "/dev/null"))
629 wcscpy(wfilename
, L
"nul");
630 else if (!is_valid_win32_path(filename
, 1)) {
631 int create
= otype
&& strchr(otype
, 'w');
632 errno
= create
? EINVAL
: ENOENT
;
634 } else if (xutftowcs_path(wfilename
, filename
) < 0)
637 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
640 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
641 error("could not unhide %s", filename
);
644 file
= _wfopen(wfilename
, wotype
);
645 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
647 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
648 warning("could not mark '%s' as hidden.", filename
);
652 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
654 int hide
= needs_hiding(filename
);
656 wchar_t wfilename
[MAX_PATH
], wotype
[4];
657 if (filename
&& !strcmp(filename
, "/dev/null"))
658 wcscpy(wfilename
, L
"nul");
659 else if (!is_valid_win32_path(filename
, 1)) {
660 int create
= otype
&& strchr(otype
, 'w');
661 errno
= create
? EINVAL
: ENOENT
;
663 } else if (xutftowcs_path(wfilename
, filename
) < 0)
666 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
669 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
670 error("could not unhide %s", filename
);
673 file
= _wfreopen(wfilename
, wotype
, stream
);
674 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
675 warning("could not mark '%s' as hidden.", filename
);
680 int mingw_fflush(FILE *stream
)
682 int ret
= fflush(stream
);
685 * write() is used behind the scenes of stdio output functions.
686 * Since git code does not check for errors after each stdio write
687 * operation, it can happen that write() is called by a later
688 * stdio function even if an earlier write() call failed. In the
689 * case of a pipe whose readable end was closed, only the first
690 * call to write() reports EPIPE on Windows. Subsequent write()
691 * calls report EINVAL. It is impossible to notice whether this
692 * fflush invocation triggered such a case, therefore, we have to
693 * catch all EINVAL errors whole-sale.
695 if (ret
&& errno
== EINVAL
)
702 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
704 ssize_t result
= write(fd
, buf
, len
);
706 if (result
< 0 && errno
== EINVAL
&& buf
) {
707 /* check if fd is a pipe */
708 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
709 if (GetFileType(h
) == FILE_TYPE_PIPE
)
718 int mingw_access(const char *filename
, int mode
)
720 wchar_t wfilename
[MAX_PATH
];
721 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
723 if (xutftowcs_path(wfilename
, filename
) < 0)
725 /* X_OK is not supported by the MSVCRT version */
726 return _waccess(wfilename
, mode
& ~X_OK
);
729 int mingw_chdir(const char *dirname
)
731 wchar_t wdirname
[MAX_PATH
];
732 if (xutftowcs_path(wdirname
, dirname
) < 0)
734 return _wchdir(wdirname
);
737 int mingw_chmod(const char *filename
, int mode
)
739 wchar_t wfilename
[MAX_PATH
];
740 if (xutftowcs_path(wfilename
, filename
) < 0)
742 return _wchmod(wfilename
, mode
);
746 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
747 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
749 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
751 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
752 /* Windows to Unix Epoch conversion */
753 return winTime
- 116444736000000000LL;
756 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
758 long long hnsec
= filetime_to_hnsec(ft
);
759 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
760 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
764 * Verifies that safe_create_leading_directories() would succeed.
766 static int has_valid_directory_prefix(wchar_t *wfilename
)
768 int n
= wcslen(wfilename
);
771 wchar_t c
= wfilename
[--n
];
777 wfilename
[n
] = L
'\0';
778 attributes
= GetFileAttributesW(wfilename
);
781 (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
))
783 if (attributes
== INVALID_FILE_ATTRIBUTES
)
784 switch (GetLastError()) {
785 case ERROR_PATH_NOT_FOUND
:
787 case ERROR_FILE_NOT_FOUND
:
788 /* This implies parent directory exists. */
796 /* We keep the do_lstat code in a separate function to avoid recursion.
797 * When a path ends with a slash, the stat will fail with ENOENT. In
798 * this case, we strip the trailing slashes and stat again.
800 * If follow is true then act like stat() and report on the link
801 * target. Otherwise report on the link itself.
803 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
805 WIN32_FILE_ATTRIBUTE_DATA fdata
;
806 wchar_t wfilename
[MAX_PATH
];
807 if (xutftowcs_path(wfilename
, file_name
) < 0)
810 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
815 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
816 buf
->st_size
= fdata
.nFileSizeLow
|
817 (((off_t
)fdata
.nFileSizeHigh
)<<32);
818 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
819 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
820 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
821 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
822 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
823 WIN32_FIND_DATAW findbuf
;
824 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
825 if (handle
!= INVALID_HANDLE_VALUE
) {
826 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
827 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
829 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
830 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
832 buf
->st_mode
= S_IFLNK
;
834 buf
->st_mode
|= S_IREAD
;
835 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
836 buf
->st_mode
|= S_IWRITE
;
843 switch (GetLastError()) {
844 case ERROR_ACCESS_DENIED
:
845 case ERROR_SHARING_VIOLATION
:
846 case ERROR_LOCK_VIOLATION
:
847 case ERROR_SHARING_BUFFER_EXCEEDED
:
850 case ERROR_BUFFER_OVERFLOW
:
851 errno
= ENAMETOOLONG
;
853 case ERROR_NOT_ENOUGH_MEMORY
:
856 case ERROR_PATH_NOT_FOUND
:
857 if (!has_valid_directory_prefix(wfilename
)) {
869 /* We provide our own lstat/fstat functions, since the provided
870 * lstat/fstat functions are so slow. These stat functions are
871 * tailored for Git's usage (read: fast), and are not meant to be
872 * complete. Note that Git stat()s are redirected to mingw_lstat()
873 * too, since Windows doesn't really handle symlinks that well.
875 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
878 char alt_name
[PATH_MAX
];
880 if (!do_lstat(follow
, file_name
, buf
))
883 /* if file_name ended in a '/', Windows returned ENOENT;
884 * try again without trailing slashes
889 namelen
= strlen(file_name
);
890 if (namelen
&& file_name
[namelen
-1] != '/')
892 while (namelen
&& file_name
[namelen
-1] == '/')
894 if (!namelen
|| namelen
>= PATH_MAX
)
897 memcpy(alt_name
, file_name
, namelen
);
898 alt_name
[namelen
] = 0;
899 return do_lstat(follow
, alt_name
, buf
);
902 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
904 BY_HANDLE_FILE_INFORMATION fdata
;
906 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
907 errno
= err_win_to_posix(GetLastError());
915 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
916 buf
->st_size
= fdata
.nFileSizeLow
|
917 (((off_t
)fdata
.nFileSizeHigh
)<<32);
918 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
919 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
920 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
921 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
925 int mingw_lstat(const char *file_name
, struct stat
*buf
)
927 return do_stat_internal(0, file_name
, buf
);
929 int mingw_stat(const char *file_name
, struct stat
*buf
)
931 return do_stat_internal(1, file_name
, buf
);
934 int mingw_fstat(int fd
, struct stat
*buf
)
936 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
937 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
941 return get_file_info_by_handle(fh
, buf
);
945 /* initialize stat fields */
946 memset(buf
, 0, sizeof(*buf
));
949 if (type
== FILE_TYPE_CHAR
) {
950 buf
->st_mode
= _S_IFCHR
;
952 buf
->st_mode
= _S_IFIFO
;
953 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
954 buf
->st_size
= avail
;
964 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
966 long long winTime
= t
* 10000000LL + 116444736000000000LL;
967 ft
->dwLowDateTime
= winTime
;
968 ft
->dwHighDateTime
= winTime
>> 32;
971 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
976 wchar_t wfilename
[MAX_PATH
];
979 if (xutftowcs_path(wfilename
, file_name
) < 0)
982 /* must have write permission */
983 attrs
= GetFileAttributesW(wfilename
);
984 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
985 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
986 /* ignore errors here; open() will report them */
987 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
990 osfilehandle
= CreateFileW(wfilename
,
991 FILE_WRITE_ATTRIBUTES
,
992 0 /*FileShare.None*/,
995 (attrs
!= INVALID_FILE_ATTRIBUTES
&&
996 (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) ?
997 FILE_FLAG_BACKUP_SEMANTICS
: 0,
999 if (osfilehandle
== INVALID_HANDLE_VALUE
) {
1000 errno
= err_win_to_posix(GetLastError());
1006 time_t_to_filetime(times
->modtime
, &mft
);
1007 time_t_to_filetime(times
->actime
, &aft
);
1009 GetSystemTimeAsFileTime(&mft
);
1013 if (!SetFileTime(osfilehandle
, NULL
, &aft
, &mft
)) {
1019 if (osfilehandle
!= INVALID_HANDLE_VALUE
)
1020 CloseHandle(osfilehandle
);
1023 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1024 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1025 /* ignore errors again */
1026 SetFileAttributesW(wfilename
, attrs
);
1032 size_t mingw_strftime(char *s
, size_t max
,
1033 const char *format
, const struct tm
*tm
)
1035 /* a pointer to the original strftime in case we can't find the UCRT version */
1036 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1038 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1039 const char *, const struct tm
*);
1041 if (INIT_PROC_ADDR(strftime
))
1042 ret
= strftime(s
, max
, format
, tm
);
1044 ret
= fallback(s
, max
, format
, tm
);
1046 if (!ret
&& errno
== EINVAL
)
1047 die("invalid strftime format: '%s'", format
);
1051 unsigned int sleep (unsigned int seconds
)
1053 Sleep(seconds
*1000);
1057 char *mingw_mktemp(char *template)
1059 wchar_t wtemplate
[MAX_PATH
];
1060 if (xutftowcs_path(wtemplate
, template) < 0)
1062 if (!_wmktemp(wtemplate
))
1064 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1069 int mkstemp(char *template)
1071 return git_mkstemp_mode(template, 0600);
1074 int gettimeofday(struct timeval
*tv
, void *tz
)
1079 GetSystemTimeAsFileTime(&ft
);
1080 hnsec
= filetime_to_hnsec(&ft
);
1081 tv
->tv_sec
= hnsec
/ 10000000;
1082 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1086 int pipe(int filedes
[2])
1090 /* this creates non-inheritable handles */
1091 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1092 errno
= err_win_to_posix(GetLastError());
1095 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1096 if (filedes
[0] < 0) {
1101 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1102 if (filedes
[1] < 0) {
1111 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1113 if (gmtime_s(result
, timep
) == 0)
1118 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1120 if (localtime_s(result
, timep
) == 0)
1126 char *mingw_getcwd(char *pointer
, int len
)
1128 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1129 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1131 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1132 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1135 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1136 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1137 HANDLE hnd
= CreateFileW(cwd
, 0,
1138 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1139 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1140 if (hnd
== INVALID_HANDLE_VALUE
)
1142 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1144 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1146 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1150 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1152 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1156 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1158 convert_slashes(pointer
);
1163 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1164 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1166 static const char *quote_arg_msvc(const char *arg
)
1168 /* count chars to quote */
1170 int force_quotes
= 0;
1172 const char *p
= arg
;
1173 if (!*p
) force_quotes
= 1;
1175 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1179 else if (*p
== '\\') {
1181 while (*p
== '\\') {
1186 if (*p
== '"' || !*p
)
1193 if (!force_quotes
&& n
== 0)
1196 /* insert \ where necessary */
1197 d
= q
= xmalloc(st_add3(len
, n
, 3));
1202 else if (*arg
== '\\') {
1204 while (*arg
== '\\') {
1208 if (*arg
== '"' || !*arg
) {
1211 /* don't escape the surrounding end quote */
1226 static const char *quote_arg_msys2(const char *arg
)
1228 struct strbuf buf
= STRBUF_INIT
;
1229 const char *p2
= arg
, *p
;
1231 for (p
= arg
; *p
; p
++) {
1232 int ws
= isspace(*p
);
1233 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1234 *p
!= '?' && *p
!= '*' && *p
!= '~')
1237 strbuf_addch(&buf
, '"');
1239 strbuf_add(&buf
, p2
, p
- p2
);
1240 if (*p
== '\\' || *p
== '"')
1241 strbuf_addch(&buf
, '\\');
1246 strbuf_addch(&buf
, '"');
1250 strbuf_add(&buf
, p2
, p
- p2
);
1252 strbuf_addch(&buf
, '"');
1253 return strbuf_detach(&buf
, 0);
1256 static const char *parse_interpreter(const char *cmd
)
1258 static char buf
[100];
1262 /* don't even try a .exe */
1264 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1267 fd
= open(cmd
, O_RDONLY
);
1270 n
= read(fd
, buf
, sizeof(buf
)-1);
1272 if (n
< 4) /* at least '#!/x' and not error */
1275 if (buf
[0] != '#' || buf
[1] != '!')
1278 p
= buf
+ strcspn(buf
, "\r\n");
1283 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1286 if ((opt
= strchr(p
+1, ' ')))
1292 * exe_only means that we only want to detect .exe files, but not scripts
1293 * (which do not have an extension)
1295 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1296 int isexe
, int exe_only
)
1298 char path
[MAX_PATH
];
1299 wchar_t wpath
[MAX_PATH
];
1300 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1302 if (xutftowcs_path(wpath
, path
) < 0)
1305 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1306 return xstrdup(path
);
1307 wpath
[wcslen(wpath
)-4] = '\0';
1308 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1309 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1310 path
[strlen(path
)-4] = '\0';
1311 return xstrdup(path
);
1318 * Determines the absolute path of cmd using the split path in path.
1319 * If cmd contains a slash or backslash, no lookup is performed.
1321 static char *path_lookup(const char *cmd
, int exe_only
)
1325 int len
= strlen(cmd
);
1326 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1328 if (strpbrk(cmd
, "/\\"))
1329 return xstrdup(cmd
);
1331 path
= mingw_getenv("PATH");
1336 const char *sep
= strchrnul(path
, ';');
1337 int dirlen
= sep
- path
;
1339 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1348 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1350 while (*s
&& *s
!= c
)
1355 /* Compare only keys */
1356 static int wenvcmp(const void *a
, const void *b
)
1358 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1359 size_t p_len
, q_len
;
1362 p_len
= wcschrnul(p
, L
'=') - p
;
1363 q_len
= wcschrnul(q
, L
'=') - q
;
1365 /* If the length differs, include the shorter key's NUL */
1368 else if (p_len
> q_len
)
1371 return _wcsnicmp(p
, q
, p_len
);
1375 * Build an environment block combining the inherited environment
1376 * merged with the given list of settings.
1378 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1379 * Values of the form "KEY" in deltaenv delete inherited values.
1381 * Multiple entries in deltaenv for the same key are explicitly allowed.
1383 * We return a contiguous block of UNICODE strings with a final trailing
1386 static wchar_t *make_environment_block(char **deltaenv
)
1388 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1389 size_t wlen
, s
, delta_size
, size
;
1391 wchar_t **array
= NULL
;
1392 size_t alloc
= 0, nr
= 0, i
;
1394 size
= 1; /* for extra NUL at the end */
1396 /* If there is no deltaenv to apply, simply return a copy. */
1397 if (!deltaenv
|| !*deltaenv
) {
1398 for (p
= wenv
; p
&& *p
; ) {
1399 size_t s
= wcslen(p
) + 1;
1404 DUP_ARRAY(result
, wenv
, size
);
1405 FreeEnvironmentStringsW(wenv
);
1410 * If there is a deltaenv, let's accumulate all keys into `array`,
1411 * sort them using the stable git_stable_qsort() and then copy,
1412 * skipping duplicate keys
1414 for (p
= wenv
; p
&& *p
; ) {
1415 ALLOC_GROW(array
, nr
+ 1, alloc
);
1422 /* (over-)assess size needed for wchar version of deltaenv */
1423 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1424 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1425 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1427 /* convert the deltaenv, appending to array */
1428 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1429 ALLOC_GROW(array
, nr
+ 1, alloc
);
1430 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1435 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1436 ALLOC_ARRAY(result
, size
+ delta_size
);
1438 for (p
= result
, i
= 0; i
< nr
; i
++) {
1439 /* Skip any duplicate keys; last one wins */
1440 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1443 /* Skip "to delete" entry */
1444 if (!wcschr(array
[i
], L
'='))
1447 size
= wcslen(array
[i
]) + 1;
1448 COPY_ARRAY(p
, array
[i
], size
);
1455 FreeEnvironmentStringsW(wenv
);
1459 static void do_unset_environment_variables(void)
1462 char *p
= unset_environment_variables
;
1469 char *comma
= strchr(p
, ',');
1481 struct pinfo_t
*next
;
1485 static struct pinfo_t
*pinfo
= NULL
;
1486 CRITICAL_SECTION pinfo_cs
;
1488 /* Used to match and chomp off path components */
1489 static inline int match_last_path_component(const char *path
, size_t *len
,
1490 const char *component
)
1492 size_t component_len
= strlen(component
);
1493 if (*len
< component_len
+ 1 ||
1494 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1495 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1497 *len
-= component_len
+ 1;
1498 /* chomp off repeated dir separators */
1499 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1504 static int is_msys2_sh(const char *cmd
)
1509 if (!strcmp(cmd
, "sh")) {
1510 static int ret
= -1;
1516 p
= path_lookup(cmd
, 0);
1520 size_t len
= strlen(p
);
1522 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1523 match_last_path_component(p
, &len
, "bin") &&
1524 match_last_path_component(p
, &len
, "usr");
1530 if (ends_with(cmd
, "\\sh.exe")) {
1534 sh
= path_lookup("sh", 0);
1536 return !fspathcmp(cmd
, sh
);
1542 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1544 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1546 static int restrict_handle_inheritance
= -1;
1548 PROCESS_INFORMATION pi
;
1549 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1550 HANDLE stdhandles
[3];
1551 DWORD stdhandles_count
= 0;
1554 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1555 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1558 const char *(*quote_arg
)(const char *arg
) =
1559 is_msys2_sh(cmd
? cmd
: *argv
) ?
1560 quote_arg_msys2
: quote_arg_msvc
;
1561 const char *strace_env
;
1563 /* Make sure to override previous errors, if any */
1566 if (restrict_handle_inheritance
< 0)
1567 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1569 * The following code to restrict which handles are inherited seems
1570 * to work properly only on Windows 7 and later, so let's disable it
1571 * on Windows Vista and 2008.
1573 if (restrict_handle_inheritance
< 0)
1574 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1576 do_unset_environment_variables();
1578 /* Determine whether or not we are associated to a console */
1579 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1580 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1581 FILE_ATTRIBUTE_NORMAL
, NULL
);
1582 if (cons
== INVALID_HANDLE_VALUE
) {
1583 /* There is no console associated with this process.
1584 * Since the child is a console process, Windows
1585 * would normally create a console window. But
1586 * since we'll be redirecting std streams, we do
1587 * not need the console.
1588 * It is necessary to use DETACHED_PROCESS
1589 * instead of CREATE_NO_WINDOW to make ssh
1590 * recognize that it has no console.
1592 flags
|= DETACHED_PROCESS
;
1594 /* There is already a console. If we specified
1595 * DETACHED_PROCESS here, too, Windows would
1596 * disassociate the child from the console.
1597 * The same is true for CREATE_NO_WINDOW.
1602 memset(&si
, 0, sizeof(si
));
1603 si
.StartupInfo
.cb
= sizeof(si
);
1604 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1605 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1606 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1608 /* The list of handles cannot contain duplicates */
1609 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1610 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1611 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1612 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1613 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1614 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1615 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1616 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1617 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1618 if (stdhandles_count
)
1619 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1621 if (*argv
&& !strcmp(cmd
, *argv
))
1623 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1625 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1628 /* concatenate argv, quoting args as we go */
1629 strbuf_init(&args
, 0);
1631 char *quoted
= (char *)quote_arg(cmd
);
1632 strbuf_addstr(&args
, quoted
);
1636 for (; *argv
; argv
++) {
1637 char *quoted
= (char *)quote_arg(*argv
);
1639 strbuf_addch(&args
, ' ');
1640 strbuf_addstr(&args
, quoted
);
1641 if (quoted
!= *argv
)
1645 strace_env
= getenv("GIT_STRACE_COMMANDS");
1647 char *p
= path_lookup("strace.exe", 1);
1649 return error("strace not found!");
1650 if (xutftowcs_path(wcmd
, p
) < 0) {
1655 if (!strcmp("1", strace_env
) ||
1656 !strcasecmp("yes", strace_env
) ||
1657 !strcasecmp("true", strace_env
))
1658 strbuf_insert(&args
, 0, "strace ", 7);
1660 const char *quoted
= quote_arg(strace_env
);
1661 struct strbuf buf
= STRBUF_INIT
;
1662 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1663 if (quoted
!= strace_env
)
1664 free((char *)quoted
);
1665 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1666 strbuf_release(&buf
);
1670 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1671 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1672 strbuf_release(&args
);
1674 wenvblk
= make_environment_block(deltaenv
);
1676 memset(&pi
, 0, sizeof(pi
));
1677 if (restrict_handle_inheritance
&& stdhandles_count
&&
1678 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1679 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1680 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1681 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1682 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1683 UpdateProcThreadAttribute(attr_list
, 0,
1684 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1686 stdhandles_count
* sizeof(HANDLE
),
1688 si
.lpAttributeList
= attr_list
;
1689 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1692 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1693 stdhandles_count
? TRUE
: FALSE
,
1694 flags
, wenvblk
, dir
? wdir
: NULL
,
1695 &si
.StartupInfo
, &pi
);
1698 * On Windows 2008 R2, it seems that specifying certain types of handles
1699 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1700 * error. Rather than playing finicky and fragile games, let's just try
1701 * to detect this situation and simply try again without restricting any
1702 * handle inheritance. This is still better than failing to create
1705 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1706 DWORD err
= GetLastError();
1707 struct strbuf buf
= STRBUF_INIT
;
1709 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1711 * On Windows 7 and earlier, handles on pipes and character
1712 * devices are inherited automatically, and cannot be
1713 * specified in the thread handle list. Rather than trying
1714 * to catch each and every corner case (and running the
1715 * chance of *still* forgetting a few), let's just fall
1716 * back to creating the process without trying to limit the
1717 * handle inheritance.
1719 !(err
== ERROR_INVALID_PARAMETER
&&
1720 GetVersion() >> 16 < 9200) &&
1721 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1725 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1727 for (i
= 0; i
< stdhandles_count
; i
++) {
1728 HANDLE h
= stdhandles
[i
];
1729 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1730 "handle info (%d) %lx\n", i
, h
,
1732 GetHandleInformation(h
, &fl
),
1735 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1736 "at\nhttps://github.com/git-for-windows/"
1737 "git/issues/new\n\n"
1738 "To suppress this warning, please set "
1739 "the environment variable\n\n"
1740 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1743 restrict_handle_inheritance
= 0;
1744 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1745 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1746 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1747 &si
.StartupInfo
, &pi
);
1749 errno
= err_win_to_posix(GetLastError());
1750 if (ret
&& buf
.len
) {
1751 warning("failed to restrict file handles (%ld)\n\n%s",
1754 strbuf_release(&buf
);
1756 errno
= err_win_to_posix(GetLastError());
1758 if (si
.lpAttributeList
)
1759 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1761 HeapFree(GetProcessHeap(), 0, attr_list
);
1769 CloseHandle(pi
.hThread
);
1772 * The process ID is the human-readable identifier of the process
1773 * that we want to present in log and error messages. The handle
1774 * is not useful for this purpose. But we cannot close it, either,
1775 * because it is not possible to turn a process ID into a process
1776 * handle after the process terminated.
1777 * Keep the handle in a list for waitpid.
1779 EnterCriticalSection(&pinfo_cs
);
1781 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1782 info
->pid
= pi
.dwProcessId
;
1783 info
->proc
= pi
.hProcess
;
1787 LeaveCriticalSection(&pinfo_cs
);
1789 return (pid_t
)pi
.dwProcessId
;
1792 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1794 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1797 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1799 int fhin
, int fhout
, int fherr
)
1802 char *prog
= path_lookup(cmd
, 0);
1809 const char *interpr
= parse_interpreter(prog
);
1812 const char *argv0
= argv
[0];
1813 char *iprog
= path_lookup(interpr
, 1);
1820 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1821 fhin
, fhout
, fherr
);
1827 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1828 fhin
, fhout
, fherr
);
1834 static int try_shell_exec(const char *cmd
, char *const *argv
)
1836 const char *interpr
= parse_interpreter(cmd
);
1842 prog
= path_lookup(interpr
, 1);
1847 while (argv
[argc
]) argc
++;
1848 ALLOC_ARRAY(argv2
, argc
+ 1);
1849 argv2
[0] = (char *)cmd
; /* full path to the script file */
1850 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1851 exec_id
= trace2_exec(prog
, (const char **)argv2
);
1852 pid
= mingw_spawnv(prog
, (const char **)argv2
, 1);
1855 if (waitpid(pid
, &status
, 0) < 0)
1857 trace2_exec_result(exec_id
, status
);
1860 trace2_exec_result(exec_id
, -1);
1861 pid
= 1; /* indicate that we tried but failed */
1868 int mingw_execv(const char *cmd
, char *const *argv
)
1870 /* check if git_command is a shell script */
1871 if (!try_shell_exec(cmd
, argv
)) {
1875 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1876 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1878 trace2_exec_result(exec_id
, -1);
1881 if (waitpid(pid
, &status
, 0) < 0)
1883 trace2_exec_result(exec_id
, status
);
1889 int mingw_execvp(const char *cmd
, char *const *argv
)
1891 char *prog
= path_lookup(cmd
, 0);
1894 mingw_execv(prog
, argv
);
1902 int mingw_kill(pid_t pid
, int sig
)
1904 if (pid
> 0 && sig
== SIGTERM
) {
1905 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1907 if (TerminateProcess(h
, -1)) {
1912 errno
= err_win_to_posix(GetLastError());
1915 } else if (pid
> 0 && sig
== 0) {
1916 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1928 * UTF-8 versions of getenv(), putenv() and unsetenv().
1929 * Internally, they use the CRT's stock UNICODE routines
1930 * to avoid data loss.
1932 char *mingw_getenv(const char *name
)
1934 #define GETENV_MAX_RETAIN 64
1935 static char *values
[GETENV_MAX_RETAIN
];
1936 static int value_counter
;
1937 int len_key
, len_value
;
1940 wchar_t w_value
[32768];
1942 if (!name
|| !*name
)
1945 len_key
= strlen(name
) + 1;
1946 /* We cannot use xcalloc() here because that uses getenv() itself */
1947 w_key
= calloc(len_key
, sizeof(wchar_t));
1949 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1950 xutftowcs(w_key
, name
, len_key
);
1951 /* GetEnvironmentVariableW() only sets the last error upon failure */
1952 SetLastError(ERROR_SUCCESS
);
1953 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1954 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1960 len_value
= len_value
* 3 + 1;
1961 /* We cannot use xcalloc() here because that uses getenv() itself */
1962 value
= calloc(len_value
, sizeof(char));
1964 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1965 xwcstoutf(value
, w_value
, len_value
);
1968 * We return `value` which is an allocated value and the caller is NOT
1969 * expecting to have to free it, so we keep a round-robin array,
1970 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1972 free(values
[value_counter
]);
1973 values
[value_counter
++] = value
;
1974 if (value_counter
>= ARRAY_SIZE(values
))
1980 int mingw_putenv(const char *namevalue
)
1983 wchar_t *wide
, *equal
;
1986 if (!namevalue
|| !*namevalue
)
1989 size
= strlen(namevalue
) * 2 + 1;
1990 wide
= calloc(size
, sizeof(wchar_t));
1992 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1993 xutftowcs(wide
, namevalue
, size
);
1994 equal
= wcschr(wide
, L
'=');
1996 result
= SetEnvironmentVariableW(wide
, NULL
);
1999 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
2004 errno
= err_win_to_posix(GetLastError());
2006 return result
? 0 : -1;
2009 static void ensure_socket_initialization(void)
2012 static int initialized
= 0;
2017 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2018 die("unable to initialize winsock subsystem, error %d",
2021 atexit((void(*)(void)) WSACleanup
);
2026 int mingw_gethostname(char *name
, int namelen
)
2028 ensure_socket_initialization();
2029 return gethostname(name
, namelen
);
2032 #undef gethostbyname
2033 struct hostent
*mingw_gethostbyname(const char *host
)
2035 ensure_socket_initialization();
2036 return gethostbyname(host
);
2040 int mingw_getaddrinfo(const char *node
, const char *service
,
2041 const struct addrinfo
*hints
, struct addrinfo
**res
)
2043 ensure_socket_initialization();
2044 return getaddrinfo(node
, service
, hints
, res
);
2047 int mingw_socket(int domain
, int type
, int protocol
)
2052 ensure_socket_initialization();
2053 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2054 if (s
== INVALID_SOCKET
) {
2056 * WSAGetLastError() values are regular BSD error codes
2057 * biased by WSABASEERR.
2058 * However, strerror() does not know about networking
2059 * specific errors, which are values beginning at 38 or so.
2060 * Therefore, we choose to leave the biased error code
2061 * in errno so that _if_ someone looks up the code somewhere,
2062 * then it is at least the number that are usually listed.
2064 errno
= WSAGetLastError();
2067 /* convert into a file descriptor */
2068 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2070 return error("unable to make a socket file descriptor: %s",
2077 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2079 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2080 return connect(s
, sa
, sz
);
2084 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2086 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2087 return bind(s
, sa
, sz
);
2091 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2093 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2094 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2098 int mingw_shutdown(int sockfd
, int how
)
2100 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2101 return shutdown(s
, how
);
2105 int mingw_listen(int sockfd
, int backlog
)
2107 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2108 return listen(s
, backlog
);
2112 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2116 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2117 SOCKET s2
= accept(s1
, sa
, sz
);
2119 /* convert into a file descriptor */
2120 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2123 return error("unable to make a socket file descriptor: %s",
2130 int mingw_rename(const char *pold
, const char *pnew
)
2134 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2135 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2139 * Try native rename() first to get errno right.
2140 * It is based on MoveFile(), which cannot overwrite existing files.
2142 if (!_wrename(wpold
, wpnew
))
2144 if (errno
!= EEXIST
)
2147 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2149 /* TODO: translate more errors */
2150 gle
= GetLastError();
2151 if (gle
== ERROR_ACCESS_DENIED
&&
2152 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2153 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2154 DWORD attrsold
= GetFileAttributesW(wpold
);
2155 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2156 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2158 else if (!_wrmdir(wpnew
))
2162 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2163 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2164 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2166 gle
= GetLastError();
2167 /* revert file attributes on failure */
2168 SetFileAttributesW(wpnew
, attrs
);
2171 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2173 * We assume that some other process had the source or
2174 * destination file open at the wrong moment and retry.
2175 * In order to give the other process a higher chance to
2176 * complete its operation, we give up our time slice now.
2177 * If we have to retry again, we do sleep a bit.
2179 Sleep(delay
[tries
]);
2183 if (gle
== ERROR_ACCESS_DENIED
&&
2184 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2185 "Should I try again?", pold
, pnew
))
2193 * Note that this doesn't return the actual pagesize, but
2194 * the allocation granularity. If future Windows specific git code
2195 * needs the real getpagesize function, we need to find another solution.
2197 int mingw_getpagesize(void)
2201 return si
.dwAllocationGranularity
;
2204 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2205 enum EXTENDED_NAME_FORMAT
{
2207 NameUserPrincipal
= 8
2210 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2212 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2213 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2214 static wchar_t wbuffer
[1024];
2217 if (!INIT_PROC_ADDR(GetUserNameExW
))
2220 len
= ARRAY_SIZE(wbuffer
);
2221 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2222 char *converted
= xmalloc((len
*= 3));
2223 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2231 char *mingw_query_user_email(void)
2233 return get_extended_user_info(NameUserPrincipal
);
2236 struct passwd
*getpwuid(int uid
)
2238 static unsigned initialized
;
2239 static char user_name
[100];
2240 static struct passwd
*p
;
2247 len
= ARRAY_SIZE(buf
);
2248 if (!GetUserNameW(buf
, &len
)) {
2253 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2258 p
= xmalloc(sizeof(*p
));
2259 p
->pw_name
= user_name
;
2260 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2262 p
->pw_gecos
= "unknown";
2269 static HANDLE timer_event
;
2270 static HANDLE timer_thread
;
2271 static int timer_interval
;
2272 static int one_shot
;
2273 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2275 /* The timer works like this:
2276 * The thread, ticktack(), is a trivial routine that most of the time
2277 * only waits to receive the signal to terminate. The main thread tells
2278 * the thread to terminate by setting the timer_event to the signalled
2280 * But ticktack() interrupts the wait state after the timer's interval
2281 * length to call the signal handler.
2284 static unsigned __stdcall
ticktack(void *dummy
)
2286 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2287 mingw_raise(SIGALRM
);
2294 static int start_timer_thread(void)
2296 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2298 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2300 return errno
= ENOMEM
,
2301 error("cannot start timer thread");
2303 return errno
= ENOMEM
,
2304 error("cannot allocate resources for timer");
2308 static void stop_timer_thread(void)
2311 SetEvent(timer_event
); /* tell thread to terminate */
2313 int rc
= WaitForSingleObject(timer_thread
, 10000);
2314 if (rc
== WAIT_TIMEOUT
)
2315 error("timer thread did not terminate timely");
2316 else if (rc
!= WAIT_OBJECT_0
)
2317 error("waiting for timer thread failed: %lu",
2319 CloseHandle(timer_thread
);
2322 CloseHandle(timer_event
);
2324 timer_thread
= NULL
;
2327 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2329 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2332 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2334 static const struct timeval zero
;
2335 static int atexit_done
;
2338 return errno
= EINVAL
,
2339 error("setitimer param 3 != NULL not implemented");
2340 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2341 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2342 return errno
= EINVAL
,
2343 error("setitimer: it_interval must be zero or eq it_value");
2346 stop_timer_thread();
2348 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2349 is_timeval_eq(&in
->it_interval
, &zero
))
2352 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2353 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2355 atexit(stop_timer_thread
);
2358 return start_timer_thread();
2361 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2364 return errno
= EINVAL
,
2365 error("sigaction only implemented for SIGALRM");
2367 return errno
= EINVAL
,
2368 error("sigaction: param 3 != NULL not implemented");
2370 timer_fn
= in
->sa_handler
;
2375 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2387 sigint_fn
= handler
;
2391 return signal(sig
, handler
);
2398 int mingw_raise(int sig
)
2402 if (timer_fn
== SIG_DFL
) {
2403 if (isatty(STDERR_FILENO
))
2404 fputs("Alarm clock\n", stderr
);
2405 exit(128 + SIGALRM
);
2406 } else if (timer_fn
!= SIG_IGN
)
2411 if (sigint_fn
== SIG_DFL
)
2413 else if (sigint_fn
!= SIG_IGN
)
2417 #if defined(_MSC_VER)
2424 case SIGABRT_COMPAT
:
2426 * The <signal.h> header in the MS C Runtime defines 8 signals
2427 * as being supported on the platform. Anything else causes an
2428 * "Invalid signal or error" (which in DEBUG builds causes the
2429 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2430 * already know will fail.
2447 int link(const char *oldpath
, const char *newpath
)
2449 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2450 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2451 xutftowcs_path(wnewpath
, newpath
) < 0)
2454 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2455 errno
= err_win_to_posix(GetLastError());
2461 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2463 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2470 if (pid
> 0 && options
& WNOHANG
) {
2471 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2475 options
&= ~WNOHANG
;
2479 struct pinfo_t
**ppinfo
;
2480 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2486 GetExitCodeProcess(h
, (LPDWORD
)status
);
2488 EnterCriticalSection(&pinfo_cs
);
2492 struct pinfo_t
*info
= *ppinfo
;
2493 if (info
->pid
== pid
) {
2494 CloseHandle(info
->proc
);
2495 *ppinfo
= info
->next
;
2499 ppinfo
= &info
->next
;
2502 LeaveCriticalSection(&pinfo_cs
);
2513 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2515 int upos
= 0, wpos
= 0;
2516 const unsigned char *utf
= (const unsigned char*) utfs
;
2517 if (!utf
|| !wcs
|| wcslen
< 1) {
2521 /* reserve space for \0 */
2526 while (upos
< utflen
) {
2527 int c
= utf
[upos
++] & 0xff;
2528 if (utflen
== INT_MAX
&& c
== 0)
2531 if (wpos
>= wcslen
) {
2540 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2541 (utf
[upos
] & 0xc0) == 0x80) {
2543 c
= ((c
& 0x1f) << 6);
2544 c
|= (utf
[upos
++] & 0x3f);
2546 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2547 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2548 (utf
[upos
] & 0xc0) == 0x80 &&
2549 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2551 c
= ((c
& 0x0f) << 12);
2552 c
|= ((utf
[upos
++] & 0x3f) << 6);
2553 c
|= (utf
[upos
++] & 0x3f);
2555 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2556 wpos
+ 1 < wcslen
&&
2557 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2558 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2559 (utf
[upos
] & 0xc0) == 0x80 &&
2560 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2561 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2562 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2563 c
= ((c
& 0x07) << 18);
2564 c
|= ((utf
[upos
++] & 0x3f) << 12);
2565 c
|= ((utf
[upos
++] & 0x3f) << 6);
2566 c
|= (utf
[upos
++] & 0x3f);
2568 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2569 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2570 } else if (c
>= 0xa0) {
2571 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2574 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2575 static const char *hex
= "0123456789abcdef";
2576 wcs
[wpos
++] = hex
[c
>> 4];
2578 wcs
[wpos
++] = hex
[c
& 0x0f];
2585 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2587 if (!wcs
|| !utf
|| utflen
< 1) {
2591 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2598 static void setup_windows_environment(void)
2600 char *tmp
= getenv("TMPDIR");
2602 /* on Windows it is TMP and TEMP */
2604 if (!(tmp
= getenv("TMP")))
2605 tmp
= getenv("TEMP");
2607 setenv("TMPDIR", tmp
, 1);
2608 tmp
= getenv("TMPDIR");
2614 * Convert all dir separators to forward slashes,
2615 * to help shell commands called from the Git
2616 * executable (by not mistaking the dir separators
2617 * for escape characters).
2619 convert_slashes(tmp
);
2622 /* simulate TERM to enable auto-color (see color.c) */
2623 if (!getenv("TERM"))
2624 setenv("TERM", "cygwin", 1);
2626 /* calculate HOME if not set */
2627 if (!getenv("HOME")) {
2629 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2630 * location, thus also check if the path exists (i.e. is not
2633 if ((tmp
= getenv("HOMEDRIVE"))) {
2634 struct strbuf buf
= STRBUF_INIT
;
2635 strbuf_addstr(&buf
, tmp
);
2636 if ((tmp
= getenv("HOMEPATH"))) {
2637 strbuf_addstr(&buf
, tmp
);
2638 if (is_directory(buf
.buf
))
2639 setenv("HOME", buf
.buf
, 1);
2641 tmp
= NULL
; /* use $USERPROFILE */
2643 strbuf_release(&buf
);
2645 /* use $USERPROFILE if the home share is not available */
2646 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2647 setenv("HOME", tmp
, 1);
2651 static PSID
get_current_user_sid(void)
2657 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2660 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2661 TOKEN_USER
*info
= xmalloc((size_t)len
);
2662 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2663 len
= GetLengthSid(info
->User
.Sid
);
2664 result
= xmalloc(len
);
2665 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2666 error(_("failed to copy SID (%ld)"),
2668 FREE_AND_NULL(result
);
2671 FREE_AND_NULL(info
);
2678 static int acls_supported(const char *path
)
2680 size_t offset
= offset_1st_component(path
);
2681 WCHAR wroot
[MAX_PATH
];
2682 DWORD file_system_flags
;
2685 xutftowcsn(wroot
, path
, MAX_PATH
, offset
) > 0 &&
2686 GetVolumeInformationW(wroot
, NULL
, 0, NULL
, NULL
,
2687 &file_system_flags
, NULL
, 0))
2688 return !!(file_system_flags
& FILE_PERSISTENT_ACLS
);
2693 int is_path_owned_by_current_sid(const char *path
, struct strbuf
*report
)
2695 WCHAR wpath
[MAX_PATH
];
2697 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2700 static wchar_t home
[MAX_PATH
];
2704 if (xutftowcs_path(wpath
, path
) < 0)
2708 * On Windows, the home directory is owned by the administrator, but for
2709 * all practical purposes, it belongs to the user. Do pretend that it is
2710 * owned by the user.
2713 DWORD size
= ARRAY_SIZE(home
);
2714 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2715 if (!len
|| len
> size
)
2716 wcscpy(home
, L
"::N/A::");
2718 if (!wcsicmp(wpath
, home
))
2721 /* Get the owner SID */
2722 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2723 OWNER_SECURITY_INFORMATION
|
2724 DACL_SECURITY_INFORMATION
,
2725 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2727 if (err
!= ERROR_SUCCESS
)
2728 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2729 else if (sid
&& IsValidSid(sid
)) {
2730 /* Now, verify that the SID matches the current user's */
2731 static PSID current_user_sid
;
2734 if (!current_user_sid
)
2735 current_user_sid
= get_current_user_sid();
2737 if (current_user_sid
&&
2738 IsValidSid(current_user_sid
) &&
2739 EqualSid(sid
, current_user_sid
))
2741 else if (IsWellKnownSid(sid
, WinBuiltinAdministratorsSid
) &&
2742 CheckTokenMembership(NULL
, sid
, &is_member
) &&
2745 * If owned by the Administrators group, and the
2746 * current user is an administrator, we consider that
2751 IsWellKnownSid(sid
, WinWorldSid
) &&
2752 !acls_supported(path
)) {
2754 * On FAT32 volumes, ownership is not actually recorded.
2756 strbuf_addf(report
, "'%s' is on a file system that does "
2757 "not record ownership\n", path
);
2758 } else if (report
) {
2759 LPSTR str1
, str2
, to_free1
= NULL
, to_free2
= NULL
;
2761 if (ConvertSidToStringSidA(sid
, &str1
))
2764 str1
= "(inconvertible)";
2766 if (!current_user_sid
)
2768 else if (!IsValidSid(current_user_sid
))
2770 else if (ConvertSidToStringSidA(current_user_sid
, &str2
))
2773 str2
= "(inconvertible)";
2775 "'%s' is owned by:\n"
2776 "\t'%s'\nbut the current user is:\n"
2777 "\t'%s'\n", path
, str1
, str2
);
2778 LocalFree(to_free1
);
2779 LocalFree(to_free2
);
2784 * We can release the security descriptor struct only now because `sid`
2785 * actually points into this struct.
2788 LocalFree(descriptor
);
2793 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2795 const char *p
= path
;
2796 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2801 skip_dos_drive_prefix((char **)&path
);
2808 case '/': case '\\':
2809 /* cannot end in ` ` or `.`, except for `.` and `..` */
2810 if (preceding_space_or_period
&&
2811 (i
!= periods
|| periods
> 2))
2816 i
= periods
= preceding_space_or_period
= 0;
2820 case 'a': case 'A': /* AUX */
2821 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2822 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2823 not_a_reserved_name
:
2829 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2830 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2831 goto not_a_reserved_name
;
2833 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2835 if (c
< '1' || c
> '9')
2836 goto not_a_reserved_name
;
2837 } else if (c
== 'n' || c
== 'N') { /* CON */
2839 if ((c
== 'i' || c
== 'I') &&
2840 ((c
= path
[i
+ 2]) == 'n' ||
2843 i
+= 3; /* CONIN$ */
2844 else if ((c
== 'o' || c
== 'O') &&
2845 ((c
= path
[i
+ 2]) == 'u' ||
2847 ((c
= path
[i
+ 3]) == 't' ||
2850 i
+= 4; /* CONOUT$ */
2852 goto not_a_reserved_name
;
2854 case 'l': case 'L': /* LPT<N> */
2855 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2856 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2857 !isdigit(path
[++i
]))
2858 goto not_a_reserved_name
;
2860 case 'n': case 'N': /* NUL */
2861 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2862 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2863 (allow_literal_nul
&&
2864 !path
[i
+ 1] && p
== path
))
2865 goto not_a_reserved_name
;
2867 case 'p': case 'P': /* PRN */
2868 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2869 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2870 goto not_a_reserved_name
;
2877 * So far, this looks like a reserved name. Let's see
2878 * whether it actually is one: trailing spaces, a file
2879 * extension, or an NTFS Alternate Data Stream do not
2880 * matter, the name is still reserved if any of those
2881 * follow immediately after the actual name.
2884 if (path
[i
] == ' ') {
2885 preceding_space_or_period
= 1;
2886 while (path
[++i
] == ' ')
2887 ; /* skip all spaces */
2891 if (c
&& c
!= '.' && c
!= ':' && !is_xplatform_dir_sep(c
))
2892 goto not_a_reserved_name
;
2894 /* contains reserved name */
2900 preceding_space_or_period
= 1;
2903 case ':': /* DOS drive prefix was already skipped */
2904 case '<': case '>': case '"': case '|': case '?': case '*':
2905 /* illegal character */
2908 if (c
> '\0' && c
< '\x20')
2909 /* illegal character */
2912 preceding_space_or_period
= 0;
2917 #if !defined(_MSC_VER)
2919 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2920 * mingw startup code, see init.c in mingw runtime).
2925 static NORETURN
void die_startup(void)
2927 fputs("fatal: not enough memory for initialization", stderr
);
2931 static void *malloc_startup(size_t size
)
2933 void *result
= malloc(size
);
2939 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2941 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2942 return memcpy(malloc_startup(len
), buffer
, len
);
2945 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2946 DWORD desired_access
, DWORD flags
)
2948 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2949 wchar_t buf
[MAX_PATH
];
2950 DWORD max
= ARRAY_SIZE(buf
);
2952 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2954 if (!ret
|| ret
>= max
)
2957 /* make sure this does not leak into child processes */
2958 SetEnvironmentVariableW(key
, NULL
);
2959 if (!wcscmp(buf
, L
"off")) {
2961 handle
= GetStdHandle(std_id
);
2962 if (handle
!= INVALID_HANDLE_VALUE
)
2963 CloseHandle(handle
);
2966 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2967 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2968 if (handle
== INVALID_HANDLE_VALUE
) {
2970 handle
= GetStdHandle(std_id
);
2971 if (handle
!= INVALID_HANDLE_VALUE
)
2972 CloseHandle(handle
);
2974 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2975 SetStdHandle(std_id
, handle
);
2977 /* do *not* close the new_fd: that would close stdout */
2981 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2983 if (handle
!= INVALID_HANDLE_VALUE
) {
2984 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2985 SetStdHandle(std_id
, handle
);
2991 static void maybe_redirect_std_handles(void)
2993 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2994 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2995 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2996 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2997 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2998 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
3008 * We implement wmain() and compile with -municode, which would
3009 * normally ignore main(), but we call the latter from the former
3010 * so that we can handle non-ASCII command-line parameters
3013 * To be more compatible with the core git code, we convert
3014 * argv into UTF8 and pass them directly to main().
3016 int wmain(int argc
, const wchar_t **wargv
)
3018 int i
, maxlen
, exit_status
;
3019 char *buffer
, **save
;
3022 trace2_initialize_clock();
3026 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
3029 #ifdef USE_MSVC_CRTDBG
3030 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
3034 maybe_redirect_std_handles();
3036 /* determine size of argv and environ conversion buffer */
3037 maxlen
= wcslen(wargv
[0]);
3038 for (i
= 1; i
< argc
; i
++)
3039 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
3041 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3042 maxlen
= 3 * maxlen
+ 1;
3043 buffer
= malloc_startup(maxlen
);
3046 * Create a UTF-8 version of w_argv. Also create a "save" copy
3047 * to remember all the string pointers because parse_options()
3048 * will remove claimed items from the argv that we pass down.
3050 ALLOC_ARRAY(argv
, argc
+ 1);
3051 ALLOC_ARRAY(save
, argc
+ 1);
3052 for (i
= 0; i
< argc
; i
++)
3053 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
3054 argv
[i
] = save
[i
] = NULL
;
3057 /* fix Windows specific environment settings */
3058 setup_windows_environment();
3060 unset_environment_variables
= xstrdup("PERL5LIB");
3062 /* initialize critical section for waitpid pinfo_t list */
3063 InitializeCriticalSection(&pinfo_cs
);
3065 /* set up default file mode and file modes for stdin/out/err */
3067 _setmode(_fileno(stdin
), _O_BINARY
);
3068 _setmode(_fileno(stdout
), _O_BINARY
);
3069 _setmode(_fileno(stderr
), _O_BINARY
);
3071 /* initialize Unicode console */
3074 /* invoke the real main() using our utf8 version of argv. */
3075 exit_status
= main(argc
, argv
);
3077 for (i
= 0; i
< argc
; i
++)
3085 int uname(struct utsname
*buf
)
3087 unsigned v
= (unsigned)GetVersion();
3088 memset(buf
, 0, sizeof(*buf
));
3089 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3090 xsnprintf(buf
->release
, sizeof(buf
->release
),
3091 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3092 /* assuming NT variants only.. */
3093 xsnprintf(buf
->version
, sizeof(buf
->version
),
3094 "%u", (v
>> 16) & 0x7fff);