1 #include "../git-compat-util.h"
8 #include "../run-command.h"
10 #include "win32/lazyload.h"
11 #include "../config.h"
13 #define SECURITY_WIN32
16 #define HCAST(type, handle) ((type)(intptr_t)handle)
18 static const int delay
[] = { 0, 1, 10, 20, 40 };
20 void open_in_gdb(void)
22 static struct child_process cp
= CHILD_PROCESS_INIT
;
25 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
26 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
28 if (start_command(&cp
) < 0)
29 die_errno("Could not start gdb");
33 int err_win_to_posix(DWORD winerr
)
37 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
38 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
39 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
40 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
41 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
42 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
43 case ERROR_BAD_COMMAND
: error
= EIO
; break;
44 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
45 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
46 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
47 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
48 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
49 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
50 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
51 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
52 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
53 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
54 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
55 case ERROR_BUSY
: error
= EBUSY
; break;
56 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
57 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
58 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
59 case ERROR_CANTOPEN
: error
= EIO
; break;
60 case ERROR_CANTREAD
: error
= EIO
; break;
61 case ERROR_CANTWRITE
: error
= EIO
; break;
62 case ERROR_CRC
: error
= EIO
; break;
63 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
64 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
65 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
66 case ERROR_DIRECTORY
: error
= EINVAL
; break;
67 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
68 case ERROR_DISK_CHANGE
: error
= EIO
; break;
69 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
70 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
71 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
72 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
73 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
74 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
75 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
76 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
77 case ERROR_GEN_FAILURE
: error
= EIO
; break;
78 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
79 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
80 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
81 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
82 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
83 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
84 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
85 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
86 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
87 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
88 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
89 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
90 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
91 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
92 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
93 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
94 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
95 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
96 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
97 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
98 case ERROR_IO_DEVICE
: error
= EIO
; break;
99 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
100 case ERROR_LOCKED
: error
= EBUSY
; break;
101 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
102 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
103 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
104 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
105 case ERROR_MORE_DATA
: error
= EPIPE
; break;
106 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
107 case ERROR_NOACCESS
: error
= EFAULT
; break;
108 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
109 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
110 case ERROR_NOT_READY
: error
= EAGAIN
; break;
111 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
112 case ERROR_NO_DATA
: error
= EPIPE
; break;
113 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
114 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
115 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
116 case ERROR_OPEN_FAILED
: error
= EIO
; break;
117 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
118 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
119 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
120 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
121 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
122 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
123 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
124 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
125 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
126 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
127 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
128 case ERROR_READ_FAULT
: error
= EIO
; break;
129 case ERROR_SEEK
: error
= EIO
; break;
130 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
131 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
132 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
133 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
134 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
135 case ERROR_SWAPERROR
: error
= ENOENT
; break;
136 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
137 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
138 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
139 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
140 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
141 case ERROR_WRITE_FAULT
: error
= EIO
; break;
142 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
147 static inline int is_file_in_use_error(DWORD errcode
)
150 case ERROR_SHARING_VIOLATION
:
151 case ERROR_ACCESS_DENIED
:
158 static int read_yes_no_answer(void)
162 if (fgets(answer
, sizeof(answer
), stdin
)) {
163 size_t answer_len
= strlen(answer
);
164 int got_full_line
= 0, c
;
166 /* remove the newline */
167 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
168 answer
[answer_len
-2] = '\0';
170 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
171 answer
[answer_len
-1] = '\0';
174 /* flush the buffer in case we did not get the full line */
176 while ((c
= getchar()) != EOF
&& c
!= '\n')
179 /* we could not read, return the
180 * default answer which is no */
183 if (tolower(answer
[0]) == 'y' && !answer
[1])
185 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
187 if (tolower(answer
[0]) == 'n' && !answer
[1])
189 if (!strncasecmp(answer
, "no", sizeof(answer
)))
192 /* did not find an answer we understand */
196 static int ask_yes_no_if_possible(const char *format
, ...)
199 const char *retry_hook
;
202 va_start(args
, format
);
203 vsnprintf(question
, sizeof(question
), format
, args
);
206 retry_hook
= mingw_getenv("GIT_ASK_YESNO");
208 struct child_process cmd
= CHILD_PROCESS_INIT
;
210 strvec_pushl(&cmd
.args
, retry_hook
, question
, NULL
);
211 return !run_command(&cmd
);
214 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
219 fprintf(stderr
, "%s (y/n) ", question
);
221 if ((answer
= read_yes_no_answer()) >= 0)
224 fprintf(stderr
, "Sorry, I did not understand your answer. "
225 "Please type 'y' or 'n'\n");
230 enum hide_dotfiles_type
{
231 HIDE_DOTFILES_FALSE
= 0,
233 HIDE_DOTFILES_DOTGITONLY
236 static int core_restrict_inherited_handles
= -1;
237 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
238 static char *unset_environment_variables
;
240 int mingw_core_config(const char *var
, const char *value
, void *cb
)
242 if (!strcmp(var
, "core.hidedotfiles")) {
243 if (value
&& !strcasecmp(value
, "dotgitonly"))
244 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
246 hide_dotfiles
= git_config_bool(var
, value
);
250 if (!strcmp(var
, "core.unsetenvvars")) {
251 free(unset_environment_variables
);
252 unset_environment_variables
= xstrdup(value
);
256 if (!strcmp(var
, "core.restrictinheritedhandles")) {
257 if (value
&& !strcasecmp(value
, "auto"))
258 core_restrict_inherited_handles
= -1;
260 core_restrict_inherited_handles
=
261 git_config_bool(var
, value
);
268 /* Normalizes NT paths as returned by some low-level APIs. */
269 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
272 /* fix absolute path prefixes */
273 if (wbuf
[0] == '\\') {
274 /* strip NT namespace prefixes */
275 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
276 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
278 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
280 /* replace remaining '...UNC\' with '\\' */
281 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
286 /* convert backslashes to slashes */
287 for (i
= 0; wbuf
[i
]; i
++)
293 int mingw_unlink(const char *pathname
)
296 wchar_t wpathname
[MAX_PATH
];
297 if (xutftowcs_path(wpathname
, pathname
) < 0)
300 if (DeleteFileW(wpathname
))
303 /* read-only files cannot be removed */
304 _wchmod(wpathname
, 0666);
305 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
306 if (!is_file_in_use_error(GetLastError()))
309 * We assume that some other process had the source or
310 * destination file open at the wrong moment and retry.
311 * In order to give the other process a higher chance to
312 * complete its operation, we give up our time slice now.
313 * If we have to retry again, we do sleep a bit.
318 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
319 ask_yes_no_if_possible("Unlink of file '%s' failed. "
320 "Should I try again?", pathname
))
321 ret
= _wunlink(wpathname
);
325 static int is_dir_empty(const wchar_t *wpath
)
327 WIN32_FIND_DATAW findbuf
;
329 wchar_t wbuf
[MAX_PATH
+ 2];
331 wcscat(wbuf
, L
"\\*");
332 handle
= FindFirstFileW(wbuf
, &findbuf
);
333 if (handle
== INVALID_HANDLE_VALUE
)
334 return GetLastError() == ERROR_NO_MORE_FILES
;
336 while (!wcscmp(findbuf
.cFileName
, L
".") ||
337 !wcscmp(findbuf
.cFileName
, L
".."))
338 if (!FindNextFileW(handle
, &findbuf
)) {
339 DWORD err
= GetLastError();
341 return err
== ERROR_NO_MORE_FILES
;
347 int mingw_rmdir(const char *pathname
)
350 wchar_t wpathname
[MAX_PATH
];
354 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
355 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
356 * symbolic link (if it points to a directory).
358 * This behavior breaks the assumption of e.g. `remove_path()` which
359 * upon successful deletion of a file will attempt to remove its parent
360 * directories recursively until failure (which usually happens when
361 * the directory is not empty).
363 * Therefore, before calling `_wrmdir()`, we first check if the path is
364 * a symbolic link. If it is, we exit and return the same error as
365 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
367 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
372 if (xutftowcs_path(wpathname
, pathname
) < 0)
375 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
376 if (!is_file_in_use_error(GetLastError()))
377 errno
= err_win_to_posix(GetLastError());
380 if (!is_dir_empty(wpathname
)) {
385 * We assume that some other process had the source or
386 * destination file open at the wrong moment and retry.
387 * In order to give the other process a higher chance to
388 * complete its operation, we give up our time slice now.
389 * If we have to retry again, we do sleep a bit.
394 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
395 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
396 "Should I try again?", pathname
))
397 ret
= _wrmdir(wpathname
);
399 invalidate_lstat_cache();
403 static inline int needs_hiding(const char *path
)
405 const char *basename
;
407 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
410 /* We cannot use basename(), as it would remove trailing slashes */
411 win32_skip_dos_drive_prefix((char **)&path
);
415 for (basename
= path
; *path
; path
++)
416 if (is_dir_sep(*path
)) {
419 } while (is_dir_sep(*path
));
420 /* ignore trailing slashes */
427 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
428 return *basename
== '.';
430 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
431 return !strncasecmp(".git", basename
, 4) &&
432 (!basename
[4] || is_dir_sep(basename
[4]));
435 static int set_hidden_flag(const wchar_t *path
, int set
)
437 DWORD original
= GetFileAttributesW(path
), modified
;
439 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
441 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
442 if (original
== modified
|| SetFileAttributesW(path
, modified
))
444 errno
= err_win_to_posix(GetLastError());
448 int mingw_mkdir(const char *path
, int mode
)
451 wchar_t wpath
[MAX_PATH
];
453 if (!is_valid_win32_path(path
, 0)) {
458 if (xutftowcs_path(wpath
, path
) < 0)
460 ret
= _wmkdir(wpath
);
461 if (!ret
&& needs_hiding(path
))
462 return set_hidden_flag(wpath
, 1);
467 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
468 * is documented in [1] as opening a writable file handle in append mode.
469 * (It is believed that) this is atomic since it is maintained by the
470 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
472 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
474 * This trick does not appear to work for named pipes. Instead it creates
475 * a named pipe client handle that cannot be written to. Callers should
476 * just use the regular _wopen() for them. (And since client handle gets
477 * bound to a unique server handle, it isn't really an issue.)
479 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
483 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
485 /* only these flags are supported */
486 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
487 return errno
= ENOSYS
, -1;
490 * FILE_SHARE_WRITE is required to permit child processes
491 * to append to the file.
493 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
494 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
495 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
496 if (handle
== INVALID_HANDLE_VALUE
) {
497 DWORD err
= GetLastError();
500 * Some network storage solutions (e.g. Isilon) might return
501 * ERROR_INVALID_PARAMETER instead of expected error
502 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
503 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
505 if (err
== ERROR_INVALID_PARAMETER
)
506 err
= ERROR_PATH_NOT_FOUND
;
508 errno
= err_win_to_posix(err
);
513 * No O_APPEND here, because the CRT uses it only to reset the
514 * file pointer to EOF before each write(); but that is not
515 * necessary (and may lead to races) for a file created with
518 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
525 * Does the pathname map to the local named pipe filesystem?
526 * That is, does it have a "//./pipe/" prefix?
528 static int is_local_named_pipe_path(const char *filename
)
530 return (is_dir_sep(filename
[0]) &&
531 is_dir_sep(filename
[1]) &&
532 filename
[2] == '.' &&
533 is_dir_sep(filename
[3]) &&
534 !strncasecmp(filename
+4, "pipe", 4) &&
535 is_dir_sep(filename
[8]) &&
539 int mingw_open (const char *filename
, int oflags
, ...)
541 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
544 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
545 wchar_t wfilename
[MAX_PATH
];
548 va_start(args
, oflags
);
549 mode
= va_arg(args
, int);
552 if (!is_valid_win32_path(filename
, !create
)) {
553 errno
= create
? EINVAL
: ENOENT
;
557 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
558 open_fn
= mingw_open_append
;
562 if (filename
&& !strcmp(filename
, "/dev/null"))
563 wcscpy(wfilename
, L
"nul");
564 else if (xutftowcs_path(wfilename
, filename
) < 0)
567 fd
= open_fn(wfilename
, oflags
, mode
);
569 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
570 DWORD attrs
= GetFileAttributesW(wfilename
);
571 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
574 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
576 * Internally, _wopen() uses the CreateFile() API which errors
577 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
578 * specified and an already existing file's attributes do not
579 * match *exactly*. As there is no mode or flag we can set that
580 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
581 * again *without* the O_CREAT flag (that corresponds to the
582 * CREATE_ALWAYS flag of CreateFile()).
584 if (fd
< 0 && errno
== EACCES
)
585 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
586 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
587 warning("could not mark '%s' as hidden.", filename
);
592 static BOOL WINAPI
ctrl_ignore(DWORD type
)
598 int mingw_fgetc(FILE *stream
)
601 if (!isatty(_fileno(stream
)))
602 return fgetc(stream
);
604 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
607 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
610 /* Ctrl+C was pressed, simulate SIGINT and retry */
613 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
618 FILE *mingw_fopen (const char *filename
, const char *otype
)
620 int hide
= needs_hiding(filename
);
622 wchar_t wfilename
[MAX_PATH
], wotype
[4];
623 if (filename
&& !strcmp(filename
, "/dev/null"))
624 wcscpy(wfilename
, L
"nul");
625 else if (!is_valid_win32_path(filename
, 1)) {
626 int create
= otype
&& strchr(otype
, 'w');
627 errno
= create
? EINVAL
: ENOENT
;
629 } else if (xutftowcs_path(wfilename
, filename
) < 0)
632 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
635 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
636 error("could not unhide %s", filename
);
639 file
= _wfopen(wfilename
, wotype
);
640 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
642 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
643 warning("could not mark '%s' as hidden.", filename
);
647 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
649 int hide
= needs_hiding(filename
);
651 wchar_t wfilename
[MAX_PATH
], wotype
[4];
652 if (filename
&& !strcmp(filename
, "/dev/null"))
653 wcscpy(wfilename
, L
"nul");
654 else if (!is_valid_win32_path(filename
, 1)) {
655 int create
= otype
&& strchr(otype
, 'w');
656 errno
= create
? EINVAL
: ENOENT
;
658 } else if (xutftowcs_path(wfilename
, filename
) < 0)
661 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
664 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
665 error("could not unhide %s", filename
);
668 file
= _wfreopen(wfilename
, wotype
, stream
);
669 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
670 warning("could not mark '%s' as hidden.", filename
);
675 int mingw_fflush(FILE *stream
)
677 int ret
= fflush(stream
);
680 * write() is used behind the scenes of stdio output functions.
681 * Since git code does not check for errors after each stdio write
682 * operation, it can happen that write() is called by a later
683 * stdio function even if an earlier write() call failed. In the
684 * case of a pipe whose readable end was closed, only the first
685 * call to write() reports EPIPE on Windows. Subsequent write()
686 * calls report EINVAL. It is impossible to notice whether this
687 * fflush invocation triggered such a case, therefore, we have to
688 * catch all EINVAL errors whole-sale.
690 if (ret
&& errno
== EINVAL
)
697 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
699 ssize_t result
= write(fd
, buf
, len
);
701 if (result
< 0 && errno
== EINVAL
&& buf
) {
702 /* check if fd is a pipe */
703 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
704 if (GetFileType(h
) == FILE_TYPE_PIPE
)
713 int mingw_access(const char *filename
, int mode
)
715 wchar_t wfilename
[MAX_PATH
];
716 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
718 if (xutftowcs_path(wfilename
, filename
) < 0)
720 /* X_OK is not supported by the MSVCRT version */
721 return _waccess(wfilename
, mode
& ~X_OK
);
724 int mingw_chdir(const char *dirname
)
726 wchar_t wdirname
[MAX_PATH
];
727 if (xutftowcs_path(wdirname
, dirname
) < 0)
729 return _wchdir(wdirname
);
732 int mingw_chmod(const char *filename
, int mode
)
734 wchar_t wfilename
[MAX_PATH
];
735 if (xutftowcs_path(wfilename
, filename
) < 0)
737 return _wchmod(wfilename
, mode
);
741 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
742 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
744 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
746 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
747 /* Windows to Unix Epoch conversion */
748 return winTime
- 116444736000000000LL;
751 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
753 long long hnsec
= filetime_to_hnsec(ft
);
754 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
755 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
759 * Verifies that safe_create_leading_directories() would succeed.
761 static int has_valid_directory_prefix(wchar_t *wfilename
)
763 int n
= wcslen(wfilename
);
766 wchar_t c
= wfilename
[--n
];
772 wfilename
[n
] = L
'\0';
773 attributes
= GetFileAttributesW(wfilename
);
776 (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
))
778 if (attributes
== INVALID_FILE_ATTRIBUTES
)
779 switch (GetLastError()) {
780 case ERROR_PATH_NOT_FOUND
:
782 case ERROR_FILE_NOT_FOUND
:
783 /* This implies parent directory exists. */
791 /* We keep the do_lstat code in a separate function to avoid recursion.
792 * When a path ends with a slash, the stat will fail with ENOENT. In
793 * this case, we strip the trailing slashes and stat again.
795 * If follow is true then act like stat() and report on the link
796 * target. Otherwise report on the link itself.
798 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
800 WIN32_FILE_ATTRIBUTE_DATA fdata
;
801 wchar_t wfilename
[MAX_PATH
];
802 if (xutftowcs_path(wfilename
, file_name
) < 0)
805 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
810 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
811 buf
->st_size
= fdata
.nFileSizeLow
|
812 (((off_t
)fdata
.nFileSizeHigh
)<<32);
813 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
814 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
815 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
816 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
817 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
818 WIN32_FIND_DATAW findbuf
;
819 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
820 if (handle
!= INVALID_HANDLE_VALUE
) {
821 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
822 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
824 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
825 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
827 buf
->st_mode
= S_IFLNK
;
829 buf
->st_mode
|= S_IREAD
;
830 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
831 buf
->st_mode
|= S_IWRITE
;
838 switch (GetLastError()) {
839 case ERROR_ACCESS_DENIED
:
840 case ERROR_SHARING_VIOLATION
:
841 case ERROR_LOCK_VIOLATION
:
842 case ERROR_SHARING_BUFFER_EXCEEDED
:
845 case ERROR_BUFFER_OVERFLOW
:
846 errno
= ENAMETOOLONG
;
848 case ERROR_NOT_ENOUGH_MEMORY
:
851 case ERROR_PATH_NOT_FOUND
:
852 if (!has_valid_directory_prefix(wfilename
)) {
864 /* We provide our own lstat/fstat functions, since the provided
865 * lstat/fstat functions are so slow. These stat functions are
866 * tailored for Git's usage (read: fast), and are not meant to be
867 * complete. Note that Git stat()s are redirected to mingw_lstat()
868 * too, since Windows doesn't really handle symlinks that well.
870 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
873 char alt_name
[PATH_MAX
];
875 if (!do_lstat(follow
, file_name
, buf
))
878 /* if file_name ended in a '/', Windows returned ENOENT;
879 * try again without trailing slashes
884 namelen
= strlen(file_name
);
885 if (namelen
&& file_name
[namelen
-1] != '/')
887 while (namelen
&& file_name
[namelen
-1] == '/')
889 if (!namelen
|| namelen
>= PATH_MAX
)
892 memcpy(alt_name
, file_name
, namelen
);
893 alt_name
[namelen
] = 0;
894 return do_lstat(follow
, alt_name
, buf
);
897 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
899 BY_HANDLE_FILE_INFORMATION fdata
;
901 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
902 errno
= err_win_to_posix(GetLastError());
910 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
911 buf
->st_size
= fdata
.nFileSizeLow
|
912 (((off_t
)fdata
.nFileSizeHigh
)<<32);
913 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
914 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
915 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
916 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
920 int mingw_lstat(const char *file_name
, struct stat
*buf
)
922 return do_stat_internal(0, file_name
, buf
);
924 int mingw_stat(const char *file_name
, struct stat
*buf
)
926 return do_stat_internal(1, file_name
, buf
);
929 int mingw_fstat(int fd
, struct stat
*buf
)
931 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
932 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
936 return get_file_info_by_handle(fh
, buf
);
940 /* initialize stat fields */
941 memset(buf
, 0, sizeof(*buf
));
944 if (type
== FILE_TYPE_CHAR
) {
945 buf
->st_mode
= _S_IFCHR
;
947 buf
->st_mode
= _S_IFIFO
;
948 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
949 buf
->st_size
= avail
;
959 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
961 long long winTime
= t
* 10000000LL + 116444736000000000LL;
962 ft
->dwLowDateTime
= winTime
;
963 ft
->dwHighDateTime
= winTime
>> 32;
966 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
971 wchar_t wfilename
[MAX_PATH
];
974 if (xutftowcs_path(wfilename
, file_name
) < 0)
977 /* must have write permission */
978 attrs
= GetFileAttributesW(wfilename
);
979 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
980 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
981 /* ignore errors here; open() will report them */
982 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
985 osfilehandle
= CreateFileW(wfilename
,
986 FILE_WRITE_ATTRIBUTES
,
987 0 /*FileShare.None*/,
990 (attrs
!= INVALID_FILE_ATTRIBUTES
&&
991 (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) ?
992 FILE_FLAG_BACKUP_SEMANTICS
: 0,
994 if (osfilehandle
== INVALID_HANDLE_VALUE
) {
995 errno
= err_win_to_posix(GetLastError());
1001 time_t_to_filetime(times
->modtime
, &mft
);
1002 time_t_to_filetime(times
->actime
, &aft
);
1004 GetSystemTimeAsFileTime(&mft
);
1008 if (!SetFileTime(osfilehandle
, NULL
, &aft
, &mft
)) {
1014 if (osfilehandle
!= INVALID_HANDLE_VALUE
)
1015 CloseHandle(osfilehandle
);
1018 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1019 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1020 /* ignore errors again */
1021 SetFileAttributesW(wfilename
, attrs
);
1027 size_t mingw_strftime(char *s
, size_t max
,
1028 const char *format
, const struct tm
*tm
)
1030 /* a pointer to the original strftime in case we can't find the UCRT version */
1031 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1033 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1034 const char *, const struct tm
*);
1036 if (INIT_PROC_ADDR(strftime
))
1037 ret
= strftime(s
, max
, format
, tm
);
1039 ret
= fallback(s
, max
, format
, tm
);
1041 if (!ret
&& errno
== EINVAL
)
1042 die("invalid strftime format: '%s'", format
);
1046 unsigned int sleep (unsigned int seconds
)
1048 Sleep(seconds
*1000);
1052 char *mingw_mktemp(char *template)
1054 wchar_t wtemplate
[MAX_PATH
];
1055 if (xutftowcs_path(wtemplate
, template) < 0)
1057 if (!_wmktemp(wtemplate
))
1059 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1064 int mkstemp(char *template)
1066 return git_mkstemp_mode(template, 0600);
1069 int gettimeofday(struct timeval
*tv
, void *tz
)
1074 GetSystemTimeAsFileTime(&ft
);
1075 hnsec
= filetime_to_hnsec(&ft
);
1076 tv
->tv_sec
= hnsec
/ 10000000;
1077 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1081 int pipe(int filedes
[2])
1085 /* this creates non-inheritable handles */
1086 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1087 errno
= err_win_to_posix(GetLastError());
1090 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1091 if (filedes
[0] < 0) {
1096 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1097 if (filedes
[1] < 0) {
1106 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1108 if (gmtime_s(result
, timep
) == 0)
1113 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1115 if (localtime_s(result
, timep
) == 0)
1121 char *mingw_getcwd(char *pointer
, int len
)
1123 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1124 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1126 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1127 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1130 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1131 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1132 HANDLE hnd
= CreateFileW(cwd
, 0,
1133 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1134 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1135 if (hnd
== INVALID_HANDLE_VALUE
)
1137 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1139 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1141 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1145 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1147 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1151 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1153 convert_slashes(pointer
);
1158 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1159 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1161 static const char *quote_arg_msvc(const char *arg
)
1163 /* count chars to quote */
1165 int force_quotes
= 0;
1167 const char *p
= arg
;
1168 if (!*p
) force_quotes
= 1;
1170 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1174 else if (*p
== '\\') {
1176 while (*p
== '\\') {
1181 if (*p
== '"' || !*p
)
1188 if (!force_quotes
&& n
== 0)
1191 /* insert \ where necessary */
1192 d
= q
= xmalloc(st_add3(len
, n
, 3));
1197 else if (*arg
== '\\') {
1199 while (*arg
== '\\') {
1203 if (*arg
== '"' || !*arg
) {
1206 /* don't escape the surrounding end quote */
1221 static const char *quote_arg_msys2(const char *arg
)
1223 struct strbuf buf
= STRBUF_INIT
;
1224 const char *p2
= arg
, *p
;
1226 for (p
= arg
; *p
; p
++) {
1227 int ws
= isspace(*p
);
1228 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1229 *p
!= '?' && *p
!= '*' && *p
!= '~')
1232 strbuf_addch(&buf
, '"');
1234 strbuf_add(&buf
, p2
, p
- p2
);
1235 if (*p
== '\\' || *p
== '"')
1236 strbuf_addch(&buf
, '\\');
1241 strbuf_addch(&buf
, '"');
1245 strbuf_add(&buf
, p2
, p
- p2
);
1247 strbuf_addch(&buf
, '"');
1248 return strbuf_detach(&buf
, 0);
1251 static const char *parse_interpreter(const char *cmd
)
1253 static char buf
[100];
1257 /* don't even try a .exe */
1259 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1262 fd
= open(cmd
, O_RDONLY
);
1265 n
= read(fd
, buf
, sizeof(buf
)-1);
1267 if (n
< 4) /* at least '#!/x' and not error */
1270 if (buf
[0] != '#' || buf
[1] != '!')
1273 p
= buf
+ strcspn(buf
, "\r\n");
1278 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1281 if ((opt
= strchr(p
+1, ' ')))
1287 * exe_only means that we only want to detect .exe files, but not scripts
1288 * (which do not have an extension)
1290 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1291 int isexe
, int exe_only
)
1293 char path
[MAX_PATH
];
1294 wchar_t wpath
[MAX_PATH
];
1295 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1297 if (xutftowcs_path(wpath
, path
) < 0)
1300 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1301 return xstrdup(path
);
1302 wpath
[wcslen(wpath
)-4] = '\0';
1303 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1304 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1305 path
[strlen(path
)-4] = '\0';
1306 return xstrdup(path
);
1313 * Determines the absolute path of cmd using the split path in path.
1314 * If cmd contains a slash or backslash, no lookup is performed.
1316 static char *path_lookup(const char *cmd
, int exe_only
)
1320 int len
= strlen(cmd
);
1321 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1323 if (strpbrk(cmd
, "/\\"))
1324 return xstrdup(cmd
);
1326 path
= mingw_getenv("PATH");
1331 const char *sep
= strchrnul(path
, ';');
1332 int dirlen
= sep
- path
;
1334 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1343 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1345 while (*s
&& *s
!= c
)
1350 /* Compare only keys */
1351 static int wenvcmp(const void *a
, const void *b
)
1353 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1354 size_t p_len
, q_len
;
1357 p_len
= wcschrnul(p
, L
'=') - p
;
1358 q_len
= wcschrnul(q
, L
'=') - q
;
1360 /* If the length differs, include the shorter key's NUL */
1363 else if (p_len
> q_len
)
1366 return _wcsnicmp(p
, q
, p_len
);
1370 * Build an environment block combining the inherited environment
1371 * merged with the given list of settings.
1373 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1374 * Values of the form "KEY" in deltaenv delete inherited values.
1376 * Multiple entries in deltaenv for the same key are explicitly allowed.
1378 * We return a contiguous block of UNICODE strings with a final trailing
1381 static wchar_t *make_environment_block(char **deltaenv
)
1383 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1384 size_t wlen
, s
, delta_size
, size
;
1386 wchar_t **array
= NULL
;
1387 size_t alloc
= 0, nr
= 0, i
;
1389 size
= 1; /* for extra NUL at the end */
1391 /* If there is no deltaenv to apply, simply return a copy. */
1392 if (!deltaenv
|| !*deltaenv
) {
1393 for (p
= wenv
; p
&& *p
; ) {
1394 size_t s
= wcslen(p
) + 1;
1399 ALLOC_ARRAY(result
, size
);
1400 COPY_ARRAY(result
, wenv
, size
);
1401 FreeEnvironmentStringsW(wenv
);
1406 * If there is a deltaenv, let's accumulate all keys into `array`,
1407 * sort them using the stable git_stable_qsort() and then copy,
1408 * skipping duplicate keys
1410 for (p
= wenv
; p
&& *p
; ) {
1411 ALLOC_GROW(array
, nr
+ 1, alloc
);
1418 /* (over-)assess size needed for wchar version of deltaenv */
1419 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1420 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1421 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1423 /* convert the deltaenv, appending to array */
1424 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1425 ALLOC_GROW(array
, nr
+ 1, alloc
);
1426 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1431 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1432 ALLOC_ARRAY(result
, size
+ delta_size
);
1434 for (p
= result
, i
= 0; i
< nr
; i
++) {
1435 /* Skip any duplicate keys; last one wins */
1436 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1439 /* Skip "to delete" entry */
1440 if (!wcschr(array
[i
], L
'='))
1443 size
= wcslen(array
[i
]) + 1;
1444 COPY_ARRAY(p
, array
[i
], size
);
1451 FreeEnvironmentStringsW(wenv
);
1455 static void do_unset_environment_variables(void)
1458 char *p
= unset_environment_variables
;
1465 char *comma
= strchr(p
, ',');
1477 struct pinfo_t
*next
;
1481 static struct pinfo_t
*pinfo
= NULL
;
1482 CRITICAL_SECTION pinfo_cs
;
1484 /* Used to match and chomp off path components */
1485 static inline int match_last_path_component(const char *path
, size_t *len
,
1486 const char *component
)
1488 size_t component_len
= strlen(component
);
1489 if (*len
< component_len
+ 1 ||
1490 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1491 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1493 *len
-= component_len
+ 1;
1494 /* chomp off repeated dir separators */
1495 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1500 static int is_msys2_sh(const char *cmd
)
1505 if (!strcmp(cmd
, "sh")) {
1506 static int ret
= -1;
1512 p
= path_lookup(cmd
, 0);
1516 size_t len
= strlen(p
);
1518 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1519 match_last_path_component(p
, &len
, "bin") &&
1520 match_last_path_component(p
, &len
, "usr");
1526 if (ends_with(cmd
, "\\sh.exe")) {
1530 sh
= path_lookup("sh", 0);
1532 return !fspathcmp(cmd
, sh
);
1538 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1540 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1542 static int restrict_handle_inheritance
= -1;
1544 PROCESS_INFORMATION pi
;
1545 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1546 HANDLE stdhandles
[3];
1547 DWORD stdhandles_count
= 0;
1550 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1551 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1554 const char *(*quote_arg
)(const char *arg
) =
1555 is_msys2_sh(cmd
? cmd
: *argv
) ?
1556 quote_arg_msys2
: quote_arg_msvc
;
1557 const char *strace_env
;
1559 /* Make sure to override previous errors, if any */
1562 if (restrict_handle_inheritance
< 0)
1563 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1565 * The following code to restrict which handles are inherited seems
1566 * to work properly only on Windows 7 and later, so let's disable it
1567 * on Windows Vista and 2008.
1569 if (restrict_handle_inheritance
< 0)
1570 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1572 do_unset_environment_variables();
1574 /* Determine whether or not we are associated to a console */
1575 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1576 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1577 FILE_ATTRIBUTE_NORMAL
, NULL
);
1578 if (cons
== INVALID_HANDLE_VALUE
) {
1579 /* There is no console associated with this process.
1580 * Since the child is a console process, Windows
1581 * would normally create a console window. But
1582 * since we'll be redirecting std streams, we do
1583 * not need the console.
1584 * It is necessary to use DETACHED_PROCESS
1585 * instead of CREATE_NO_WINDOW to make ssh
1586 * recognize that it has no console.
1588 flags
|= DETACHED_PROCESS
;
1590 /* There is already a console. If we specified
1591 * DETACHED_PROCESS here, too, Windows would
1592 * disassociate the child from the console.
1593 * The same is true for CREATE_NO_WINDOW.
1598 memset(&si
, 0, sizeof(si
));
1599 si
.StartupInfo
.cb
= sizeof(si
);
1600 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1601 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1602 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1604 /* The list of handles cannot contain duplicates */
1605 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1606 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1607 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1608 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1609 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1610 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1611 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1612 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1613 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1614 if (stdhandles_count
)
1615 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1617 if (*argv
&& !strcmp(cmd
, *argv
))
1619 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1621 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1624 /* concatenate argv, quoting args as we go */
1625 strbuf_init(&args
, 0);
1627 char *quoted
= (char *)quote_arg(cmd
);
1628 strbuf_addstr(&args
, quoted
);
1632 for (; *argv
; argv
++) {
1633 char *quoted
= (char *)quote_arg(*argv
);
1635 strbuf_addch(&args
, ' ');
1636 strbuf_addstr(&args
, quoted
);
1637 if (quoted
!= *argv
)
1641 strace_env
= getenv("GIT_STRACE_COMMANDS");
1643 char *p
= path_lookup("strace.exe", 1);
1645 return error("strace not found!");
1646 if (xutftowcs_path(wcmd
, p
) < 0) {
1651 if (!strcmp("1", strace_env
) ||
1652 !strcasecmp("yes", strace_env
) ||
1653 !strcasecmp("true", strace_env
))
1654 strbuf_insert(&args
, 0, "strace ", 7);
1656 const char *quoted
= quote_arg(strace_env
);
1657 struct strbuf buf
= STRBUF_INIT
;
1658 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1659 if (quoted
!= strace_env
)
1660 free((char *)quoted
);
1661 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1662 strbuf_release(&buf
);
1666 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1667 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1668 strbuf_release(&args
);
1670 wenvblk
= make_environment_block(deltaenv
);
1672 memset(&pi
, 0, sizeof(pi
));
1673 if (restrict_handle_inheritance
&& stdhandles_count
&&
1674 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1675 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1676 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1677 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1678 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1679 UpdateProcThreadAttribute(attr_list
, 0,
1680 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1682 stdhandles_count
* sizeof(HANDLE
),
1684 si
.lpAttributeList
= attr_list
;
1685 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1688 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1689 stdhandles_count
? TRUE
: FALSE
,
1690 flags
, wenvblk
, dir
? wdir
: NULL
,
1691 &si
.StartupInfo
, &pi
);
1694 * On Windows 2008 R2, it seems that specifying certain types of handles
1695 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1696 * error. Rather than playing finicky and fragile games, let's just try
1697 * to detect this situation and simply try again without restricting any
1698 * handle inheritance. This is still better than failing to create
1701 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1702 DWORD err
= GetLastError();
1703 struct strbuf buf
= STRBUF_INIT
;
1705 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1707 * On Windows 7 and earlier, handles on pipes and character
1708 * devices are inherited automatically, and cannot be
1709 * specified in the thread handle list. Rather than trying
1710 * to catch each and every corner case (and running the
1711 * chance of *still* forgetting a few), let's just fall
1712 * back to creating the process without trying to limit the
1713 * handle inheritance.
1715 !(err
== ERROR_INVALID_PARAMETER
&&
1716 GetVersion() >> 16 < 9200) &&
1717 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1721 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1723 for (i
= 0; i
< stdhandles_count
; i
++) {
1724 HANDLE h
= stdhandles
[i
];
1725 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1726 "handle info (%d) %lx\n", i
, h
,
1728 GetHandleInformation(h
, &fl
),
1731 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1732 "at\nhttps://github.com/git-for-windows/"
1733 "git/issues/new\n\n"
1734 "To suppress this warning, please set "
1735 "the environment variable\n\n"
1736 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1739 restrict_handle_inheritance
= 0;
1740 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1741 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1742 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1743 &si
.StartupInfo
, &pi
);
1745 errno
= err_win_to_posix(GetLastError());
1746 if (ret
&& buf
.len
) {
1747 warning("failed to restrict file handles (%ld)\n\n%s",
1750 strbuf_release(&buf
);
1752 errno
= err_win_to_posix(GetLastError());
1754 if (si
.lpAttributeList
)
1755 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1757 HeapFree(GetProcessHeap(), 0, attr_list
);
1765 CloseHandle(pi
.hThread
);
1768 * The process ID is the human-readable identifier of the process
1769 * that we want to present in log and error messages. The handle
1770 * is not useful for this purpose. But we cannot close it, either,
1771 * because it is not possible to turn a process ID into a process
1772 * handle after the process terminated.
1773 * Keep the handle in a list for waitpid.
1775 EnterCriticalSection(&pinfo_cs
);
1777 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1778 info
->pid
= pi
.dwProcessId
;
1779 info
->proc
= pi
.hProcess
;
1783 LeaveCriticalSection(&pinfo_cs
);
1785 return (pid_t
)pi
.dwProcessId
;
1788 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1790 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1793 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1795 int fhin
, int fhout
, int fherr
)
1798 char *prog
= path_lookup(cmd
, 0);
1805 const char *interpr
= parse_interpreter(prog
);
1808 const char *argv0
= argv
[0];
1809 char *iprog
= path_lookup(interpr
, 1);
1816 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1817 fhin
, fhout
, fherr
);
1823 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1824 fhin
, fhout
, fherr
);
1830 static int try_shell_exec(const char *cmd
, char *const *argv
)
1832 const char *interpr
= parse_interpreter(cmd
);
1838 prog
= path_lookup(interpr
, 1);
1846 while (argv
[argc
]) argc
++;
1847 ALLOC_ARRAY(argv2
, argc
+ 1);
1848 argv2
[0] = (char *)cmd
; /* full path to the script file */
1849 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1850 exec_id
= trace2_exec(prog
, argv2
);
1851 pid
= mingw_spawnv(prog
, argv2
, 1);
1854 if (waitpid(pid
, &status
, 0) < 0)
1856 trace2_exec_result(exec_id
, status
);
1859 trace2_exec_result(exec_id
, -1);
1860 pid
= 1; /* indicate that we tried but failed */
1867 int mingw_execv(const char *cmd
, char *const *argv
)
1869 /* check if git_command is a shell script */
1870 if (!try_shell_exec(cmd
, argv
)) {
1874 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1875 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1877 trace2_exec_result(exec_id
, -1);
1880 if (waitpid(pid
, &status
, 0) < 0)
1882 trace2_exec_result(exec_id
, status
);
1888 int mingw_execvp(const char *cmd
, char *const *argv
)
1890 char *prog
= path_lookup(cmd
, 0);
1893 mingw_execv(prog
, argv
);
1901 int mingw_kill(pid_t pid
, int sig
)
1903 if (pid
> 0 && sig
== SIGTERM
) {
1904 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1906 if (TerminateProcess(h
, -1)) {
1911 errno
= err_win_to_posix(GetLastError());
1914 } else if (pid
> 0 && sig
== 0) {
1915 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1927 * UTF-8 versions of getenv(), putenv() and unsetenv().
1928 * Internally, they use the CRT's stock UNICODE routines
1929 * to avoid data loss.
1931 char *mingw_getenv(const char *name
)
1933 #define GETENV_MAX_RETAIN 64
1934 static char *values
[GETENV_MAX_RETAIN
];
1935 static int value_counter
;
1936 int len_key
, len_value
;
1939 wchar_t w_value
[32768];
1941 if (!name
|| !*name
)
1944 len_key
= strlen(name
) + 1;
1945 /* We cannot use xcalloc() here because that uses getenv() itself */
1946 w_key
= calloc(len_key
, sizeof(wchar_t));
1948 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1949 xutftowcs(w_key
, name
, len_key
);
1950 /* GetEnvironmentVariableW() only sets the last error upon failure */
1951 SetLastError(ERROR_SUCCESS
);
1952 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1953 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1959 len_value
= len_value
* 3 + 1;
1960 /* We cannot use xcalloc() here because that uses getenv() itself */
1961 value
= calloc(len_value
, sizeof(char));
1963 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1964 xwcstoutf(value
, w_value
, len_value
);
1967 * We return `value` which is an allocated value and the caller is NOT
1968 * expecting to have to free it, so we keep a round-robin array,
1969 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1971 free(values
[value_counter
]);
1972 values
[value_counter
++] = value
;
1973 if (value_counter
>= ARRAY_SIZE(values
))
1979 int mingw_putenv(const char *namevalue
)
1982 wchar_t *wide
, *equal
;
1985 if (!namevalue
|| !*namevalue
)
1988 size
= strlen(namevalue
) * 2 + 1;
1989 wide
= calloc(size
, sizeof(wchar_t));
1991 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1992 xutftowcs(wide
, namevalue
, size
);
1993 equal
= wcschr(wide
, L
'=');
1995 result
= SetEnvironmentVariableW(wide
, NULL
);
1998 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
2003 errno
= err_win_to_posix(GetLastError());
2005 return result
? 0 : -1;
2008 static void ensure_socket_initialization(void)
2011 static int initialized
= 0;
2016 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2017 die("unable to initialize winsock subsystem, error %d",
2020 atexit((void(*)(void)) WSACleanup
);
2025 int mingw_gethostname(char *name
, int namelen
)
2027 ensure_socket_initialization();
2028 return gethostname(name
, namelen
);
2031 #undef gethostbyname
2032 struct hostent
*mingw_gethostbyname(const char *host
)
2034 ensure_socket_initialization();
2035 return gethostbyname(host
);
2039 int mingw_getaddrinfo(const char *node
, const char *service
,
2040 const struct addrinfo
*hints
, struct addrinfo
**res
)
2042 ensure_socket_initialization();
2043 return getaddrinfo(node
, service
, hints
, res
);
2046 int mingw_socket(int domain
, int type
, int protocol
)
2051 ensure_socket_initialization();
2052 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2053 if (s
== INVALID_SOCKET
) {
2055 * WSAGetLastError() values are regular BSD error codes
2056 * biased by WSABASEERR.
2057 * However, strerror() does not know about networking
2058 * specific errors, which are values beginning at 38 or so.
2059 * Therefore, we choose to leave the biased error code
2060 * in errno so that _if_ someone looks up the code somewhere,
2061 * then it is at least the number that are usually listed.
2063 errno
= WSAGetLastError();
2066 /* convert into a file descriptor */
2067 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2069 return error("unable to make a socket file descriptor: %s",
2076 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2078 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2079 return connect(s
, sa
, sz
);
2083 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2085 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2086 return bind(s
, sa
, sz
);
2090 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2092 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2093 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2097 int mingw_shutdown(int sockfd
, int how
)
2099 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2100 return shutdown(s
, how
);
2104 int mingw_listen(int sockfd
, int backlog
)
2106 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2107 return listen(s
, backlog
);
2111 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2115 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2116 SOCKET s2
= accept(s1
, sa
, sz
);
2118 /* convert into a file descriptor */
2119 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2122 return error("unable to make a socket file descriptor: %s",
2129 int mingw_rename(const char *pold
, const char *pnew
)
2133 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2134 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2138 * Try native rename() first to get errno right.
2139 * It is based on MoveFile(), which cannot overwrite existing files.
2141 if (!_wrename(wpold
, wpnew
))
2143 if (errno
!= EEXIST
)
2146 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2148 /* TODO: translate more errors */
2149 gle
= GetLastError();
2150 if (gle
== ERROR_ACCESS_DENIED
&&
2151 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2152 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2153 DWORD attrsold
= GetFileAttributesW(wpold
);
2154 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2155 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2157 else if (!_wrmdir(wpnew
))
2161 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2162 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2163 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2165 gle
= GetLastError();
2166 /* revert file attributes on failure */
2167 SetFileAttributesW(wpnew
, attrs
);
2170 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2172 * We assume that some other process had the source or
2173 * destination file open at the wrong moment and retry.
2174 * In order to give the other process a higher chance to
2175 * complete its operation, we give up our time slice now.
2176 * If we have to retry again, we do sleep a bit.
2178 Sleep(delay
[tries
]);
2182 if (gle
== ERROR_ACCESS_DENIED
&&
2183 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2184 "Should I try again?", pold
, pnew
))
2192 * Note that this doesn't return the actual pagesize, but
2193 * the allocation granularity. If future Windows specific git code
2194 * needs the real getpagesize function, we need to find another solution.
2196 int mingw_getpagesize(void)
2200 return si
.dwAllocationGranularity
;
2203 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2204 enum EXTENDED_NAME_FORMAT
{
2206 NameUserPrincipal
= 8
2209 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2211 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2212 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2213 static wchar_t wbuffer
[1024];
2216 if (!INIT_PROC_ADDR(GetUserNameExW
))
2219 len
= ARRAY_SIZE(wbuffer
);
2220 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2221 char *converted
= xmalloc((len
*= 3));
2222 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2230 char *mingw_query_user_email(void)
2232 return get_extended_user_info(NameUserPrincipal
);
2235 struct passwd
*getpwuid(int uid
)
2237 static unsigned initialized
;
2238 static char user_name
[100];
2239 static struct passwd
*p
;
2246 len
= ARRAY_SIZE(buf
);
2247 if (!GetUserNameW(buf
, &len
)) {
2252 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2257 p
= xmalloc(sizeof(*p
));
2258 p
->pw_name
= user_name
;
2259 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2261 p
->pw_gecos
= "unknown";
2268 static HANDLE timer_event
;
2269 static HANDLE timer_thread
;
2270 static int timer_interval
;
2271 static int one_shot
;
2272 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2274 /* The timer works like this:
2275 * The thread, ticktack(), is a trivial routine that most of the time
2276 * only waits to receive the signal to terminate. The main thread tells
2277 * the thread to terminate by setting the timer_event to the signalled
2279 * But ticktack() interrupts the wait state after the timer's interval
2280 * length to call the signal handler.
2283 static unsigned __stdcall
ticktack(void *dummy
)
2285 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2286 mingw_raise(SIGALRM
);
2293 static int start_timer_thread(void)
2295 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2297 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2299 return errno
= ENOMEM
,
2300 error("cannot start timer thread");
2302 return errno
= ENOMEM
,
2303 error("cannot allocate resources for timer");
2307 static void stop_timer_thread(void)
2310 SetEvent(timer_event
); /* tell thread to terminate */
2312 int rc
= WaitForSingleObject(timer_thread
, 10000);
2313 if (rc
== WAIT_TIMEOUT
)
2314 error("timer thread did not terminate timely");
2315 else if (rc
!= WAIT_OBJECT_0
)
2316 error("waiting for timer thread failed: %lu",
2318 CloseHandle(timer_thread
);
2321 CloseHandle(timer_event
);
2323 timer_thread
= NULL
;
2326 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2328 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2331 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2333 static const struct timeval zero
;
2334 static int atexit_done
;
2337 return errno
= EINVAL
,
2338 error("setitimer param 3 != NULL not implemented");
2339 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2340 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2341 return errno
= EINVAL
,
2342 error("setitimer: it_interval must be zero or eq it_value");
2345 stop_timer_thread();
2347 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2348 is_timeval_eq(&in
->it_interval
, &zero
))
2351 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2352 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2354 atexit(stop_timer_thread
);
2357 return start_timer_thread();
2360 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2363 return errno
= EINVAL
,
2364 error("sigaction only implemented for SIGALRM");
2366 return errno
= EINVAL
,
2367 error("sigaction: param 3 != NULL not implemented");
2369 timer_fn
= in
->sa_handler
;
2374 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2386 sigint_fn
= handler
;
2390 return signal(sig
, handler
);
2397 int mingw_raise(int sig
)
2401 if (timer_fn
== SIG_DFL
) {
2402 if (isatty(STDERR_FILENO
))
2403 fputs("Alarm clock\n", stderr
);
2404 exit(128 + SIGALRM
);
2405 } else if (timer_fn
!= SIG_IGN
)
2410 if (sigint_fn
== SIG_DFL
)
2412 else if (sigint_fn
!= SIG_IGN
)
2416 #if defined(_MSC_VER)
2423 case SIGABRT_COMPAT
:
2425 * The <signal.h> header in the MS C Runtime defines 8 signals
2426 * as being supported on the platform. Anything else causes an
2427 * "Invalid signal or error" (which in DEBUG builds causes the
2428 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2429 * already know will fail.
2446 int link(const char *oldpath
, const char *newpath
)
2448 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2449 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2450 xutftowcs_path(wnewpath
, newpath
) < 0)
2453 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2454 errno
= err_win_to_posix(GetLastError());
2460 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2462 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2469 if (pid
> 0 && options
& WNOHANG
) {
2470 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2474 options
&= ~WNOHANG
;
2478 struct pinfo_t
**ppinfo
;
2479 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2485 GetExitCodeProcess(h
, (LPDWORD
)status
);
2487 EnterCriticalSection(&pinfo_cs
);
2491 struct pinfo_t
*info
= *ppinfo
;
2492 if (info
->pid
== pid
) {
2493 CloseHandle(info
->proc
);
2494 *ppinfo
= info
->next
;
2498 ppinfo
= &info
->next
;
2501 LeaveCriticalSection(&pinfo_cs
);
2512 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2514 int upos
= 0, wpos
= 0;
2515 const unsigned char *utf
= (const unsigned char*) utfs
;
2516 if (!utf
|| !wcs
|| wcslen
< 1) {
2520 /* reserve space for \0 */
2525 while (upos
< utflen
) {
2526 int c
= utf
[upos
++] & 0xff;
2527 if (utflen
== INT_MAX
&& c
== 0)
2530 if (wpos
>= wcslen
) {
2539 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2540 (utf
[upos
] & 0xc0) == 0x80) {
2542 c
= ((c
& 0x1f) << 6);
2543 c
|= (utf
[upos
++] & 0x3f);
2545 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2546 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2547 (utf
[upos
] & 0xc0) == 0x80 &&
2548 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2550 c
= ((c
& 0x0f) << 12);
2551 c
|= ((utf
[upos
++] & 0x3f) << 6);
2552 c
|= (utf
[upos
++] & 0x3f);
2554 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2555 wpos
+ 1 < wcslen
&&
2556 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2557 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2558 (utf
[upos
] & 0xc0) == 0x80 &&
2559 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2560 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2561 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2562 c
= ((c
& 0x07) << 18);
2563 c
|= ((utf
[upos
++] & 0x3f) << 12);
2564 c
|= ((utf
[upos
++] & 0x3f) << 6);
2565 c
|= (utf
[upos
++] & 0x3f);
2567 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2568 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2569 } else if (c
>= 0xa0) {
2570 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2573 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2574 static const char *hex
= "0123456789abcdef";
2575 wcs
[wpos
++] = hex
[c
>> 4];
2577 wcs
[wpos
++] = hex
[c
& 0x0f];
2584 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2586 if (!wcs
|| !utf
|| utflen
< 1) {
2590 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2597 static void setup_windows_environment(void)
2599 char *tmp
= getenv("TMPDIR");
2601 /* on Windows it is TMP and TEMP */
2603 if (!(tmp
= getenv("TMP")))
2604 tmp
= getenv("TEMP");
2606 setenv("TMPDIR", tmp
, 1);
2607 tmp
= getenv("TMPDIR");
2613 * Convert all dir separators to forward slashes,
2614 * to help shell commands called from the Git
2615 * executable (by not mistaking the dir separators
2616 * for escape characters).
2618 convert_slashes(tmp
);
2621 /* simulate TERM to enable auto-color (see color.c) */
2622 if (!getenv("TERM"))
2623 setenv("TERM", "cygwin", 1);
2625 /* calculate HOME if not set */
2626 if (!getenv("HOME")) {
2628 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2629 * location, thus also check if the path exists (i.e. is not
2632 if ((tmp
= getenv("HOMEDRIVE"))) {
2633 struct strbuf buf
= STRBUF_INIT
;
2634 strbuf_addstr(&buf
, tmp
);
2635 if ((tmp
= getenv("HOMEPATH"))) {
2636 strbuf_addstr(&buf
, tmp
);
2637 if (is_directory(buf
.buf
))
2638 setenv("HOME", buf
.buf
, 1);
2640 tmp
= NULL
; /* use $USERPROFILE */
2642 strbuf_release(&buf
);
2644 /* use $USERPROFILE if the home share is not available */
2645 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2646 setenv("HOME", tmp
, 1);
2650 static PSID
get_current_user_sid(void)
2656 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2659 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2660 TOKEN_USER
*info
= xmalloc((size_t)len
);
2661 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2662 len
= GetLengthSid(info
->User
.Sid
);
2663 result
= xmalloc(len
);
2664 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2665 error(_("failed to copy SID (%ld)"),
2667 FREE_AND_NULL(result
);
2670 FREE_AND_NULL(info
);
2677 static int acls_supported(const char *path
)
2679 size_t offset
= offset_1st_component(path
);
2680 WCHAR wroot
[MAX_PATH
];
2681 DWORD file_system_flags
;
2684 xutftowcsn(wroot
, path
, MAX_PATH
, offset
) > 0 &&
2685 GetVolumeInformationW(wroot
, NULL
, 0, NULL
, NULL
,
2686 &file_system_flags
, NULL
, 0))
2687 return !!(file_system_flags
& FILE_PERSISTENT_ACLS
);
2692 int is_path_owned_by_current_sid(const char *path
, struct strbuf
*report
)
2694 WCHAR wpath
[MAX_PATH
];
2696 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2699 static wchar_t home
[MAX_PATH
];
2703 if (xutftowcs_path(wpath
, path
) < 0)
2707 * On Windows, the home directory is owned by the administrator, but for
2708 * all practical purposes, it belongs to the user. Do pretend that it is
2709 * owned by the user.
2712 DWORD size
= ARRAY_SIZE(home
);
2713 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2714 if (!len
|| len
> size
)
2715 wcscpy(home
, L
"::N/A::");
2717 if (!wcsicmp(wpath
, home
))
2720 /* Get the owner SID */
2721 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2722 OWNER_SECURITY_INFORMATION
|
2723 DACL_SECURITY_INFORMATION
,
2724 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2726 if (err
!= ERROR_SUCCESS
)
2727 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2728 else if (sid
&& IsValidSid(sid
)) {
2729 /* Now, verify that the SID matches the current user's */
2730 static PSID current_user_sid
;
2733 if (!current_user_sid
)
2734 current_user_sid
= get_current_user_sid();
2736 if (current_user_sid
&&
2737 IsValidSid(current_user_sid
) &&
2738 EqualSid(sid
, current_user_sid
))
2740 else if (IsWellKnownSid(sid
, WinBuiltinAdministratorsSid
) &&
2741 CheckTokenMembership(NULL
, sid
, &is_member
) &&
2744 * If owned by the Administrators group, and the
2745 * current user is an administrator, we consider that
2750 IsWellKnownSid(sid
, WinWorldSid
) &&
2751 !acls_supported(path
)) {
2753 * On FAT32 volumes, ownership is not actually recorded.
2755 strbuf_addf(report
, "'%s' is on a file system that does"
2756 "not record ownership\n", path
);
2757 } else if (report
) {
2758 LPSTR str1
, str2
, to_free1
= NULL
, to_free2
= NULL
;
2760 if (ConvertSidToStringSidA(sid
, &str1
))
2763 str1
= "(inconvertible)";
2765 if (!current_user_sid
)
2767 else if (!IsValidSid(current_user_sid
))
2769 else if (ConvertSidToStringSidA(current_user_sid
, &str2
))
2772 str2
= "(inconvertible)";
2774 "'%s' is owned by:\n"
2775 "\t'%s'\nbut the current user is:\n"
2776 "\t'%s'\n", path
, str1
, str2
);
2777 LocalFree(to_free1
);
2778 LocalFree(to_free2
);
2783 * We can release the security descriptor struct only now because `sid`
2784 * actually points into this struct.
2787 LocalFree(descriptor
);
2792 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2794 const char *p
= path
;
2795 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2800 skip_dos_drive_prefix((char **)&path
);
2807 case '/': case '\\':
2808 /* cannot end in ` ` or `.`, except for `.` and `..` */
2809 if (preceding_space_or_period
&&
2810 (i
!= periods
|| periods
> 2))
2815 i
= periods
= preceding_space_or_period
= 0;
2819 case 'a': case 'A': /* AUX */
2820 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2821 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2822 not_a_reserved_name
:
2828 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2829 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2830 goto not_a_reserved_name
;
2832 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2834 if (c
< '1' || c
> '9')
2835 goto not_a_reserved_name
;
2836 } else if (c
== 'n' || c
== 'N') { /* CON */
2838 if ((c
== 'i' || c
== 'I') &&
2839 ((c
= path
[i
+ 2]) == 'n' ||
2842 i
+= 3; /* CONIN$ */
2843 else if ((c
== 'o' || c
== 'O') &&
2844 ((c
= path
[i
+ 2]) == 'u' ||
2846 ((c
= path
[i
+ 3]) == 't' ||
2849 i
+= 4; /* CONOUT$ */
2851 goto not_a_reserved_name
;
2853 case 'l': case 'L': /* LPT<N> */
2854 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2855 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2856 !isdigit(path
[++i
]))
2857 goto not_a_reserved_name
;
2859 case 'n': case 'N': /* NUL */
2860 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2861 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2862 (allow_literal_nul
&&
2863 !path
[i
+ 1] && p
== path
))
2864 goto not_a_reserved_name
;
2866 case 'p': case 'P': /* PRN */
2867 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2868 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2869 goto not_a_reserved_name
;
2876 * So far, this looks like a reserved name. Let's see
2877 * whether it actually is one: trailing spaces, a file
2878 * extension, or an NTFS Alternate Data Stream do not
2879 * matter, the name is still reserved if any of those
2880 * follow immediately after the actual name.
2883 if (path
[i
] == ' ') {
2884 preceding_space_or_period
= 1;
2885 while (path
[++i
] == ' ')
2886 ; /* skip all spaces */
2890 if (c
&& c
!= '.' && c
!= ':' && !is_xplatform_dir_sep(c
))
2891 goto not_a_reserved_name
;
2893 /* contains reserved name */
2899 preceding_space_or_period
= 1;
2902 case ':': /* DOS drive prefix was already skipped */
2903 case '<': case '>': case '"': case '|': case '?': case '*':
2904 /* illegal character */
2907 if (c
> '\0' && c
< '\x20')
2908 /* illegal character */
2911 preceding_space_or_period
= 0;
2916 #if !defined(_MSC_VER)
2918 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2919 * mingw startup code, see init.c in mingw runtime).
2924 static NORETURN
void die_startup(void)
2926 fputs("fatal: not enough memory for initialization", stderr
);
2930 static void *malloc_startup(size_t size
)
2932 void *result
= malloc(size
);
2938 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2940 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2941 return memcpy(malloc_startup(len
), buffer
, len
);
2944 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2945 DWORD desired_access
, DWORD flags
)
2947 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2948 wchar_t buf
[MAX_PATH
];
2949 DWORD max
= ARRAY_SIZE(buf
);
2951 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2953 if (!ret
|| ret
>= max
)
2956 /* make sure this does not leak into child processes */
2957 SetEnvironmentVariableW(key
, NULL
);
2958 if (!wcscmp(buf
, L
"off")) {
2960 handle
= GetStdHandle(std_id
);
2961 if (handle
!= INVALID_HANDLE_VALUE
)
2962 CloseHandle(handle
);
2965 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2966 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2967 if (handle
== INVALID_HANDLE_VALUE
) {
2969 handle
= GetStdHandle(std_id
);
2970 if (handle
!= INVALID_HANDLE_VALUE
)
2971 CloseHandle(handle
);
2973 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2974 SetStdHandle(std_id
, handle
);
2976 /* do *not* close the new_fd: that would close stdout */
2980 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2982 if (handle
!= INVALID_HANDLE_VALUE
) {
2983 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2984 SetStdHandle(std_id
, handle
);
2990 static void maybe_redirect_std_handles(void)
2992 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2993 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2994 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2995 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2996 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2997 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
3007 * We implement wmain() and compile with -municode, which would
3008 * normally ignore main(), but we call the latter from the former
3009 * so that we can handle non-ASCII command-line parameters
3012 * To be more compatible with the core git code, we convert
3013 * argv into UTF8 and pass them directly to main().
3015 int wmain(int argc
, const wchar_t **wargv
)
3017 int i
, maxlen
, exit_status
;
3018 char *buffer
, **save
;
3021 trace2_initialize_clock();
3025 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
3028 #ifdef USE_MSVC_CRTDBG
3029 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
3033 maybe_redirect_std_handles();
3035 /* determine size of argv and environ conversion buffer */
3036 maxlen
= wcslen(wargv
[0]);
3037 for (i
= 1; i
< argc
; i
++)
3038 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
3040 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3041 maxlen
= 3 * maxlen
+ 1;
3042 buffer
= malloc_startup(maxlen
);
3045 * Create a UTF-8 version of w_argv. Also create a "save" copy
3046 * to remember all the string pointers because parse_options()
3047 * will remove claimed items from the argv that we pass down.
3049 ALLOC_ARRAY(argv
, argc
+ 1);
3050 ALLOC_ARRAY(save
, argc
+ 1);
3051 for (i
= 0; i
< argc
; i
++)
3052 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
3053 argv
[i
] = save
[i
] = NULL
;
3056 /* fix Windows specific environment settings */
3057 setup_windows_environment();
3059 unset_environment_variables
= xstrdup("PERL5LIB");
3061 /* initialize critical section for waitpid pinfo_t list */
3062 InitializeCriticalSection(&pinfo_cs
);
3064 /* set up default file mode and file modes for stdin/out/err */
3066 _setmode(_fileno(stdin
), _O_BINARY
);
3067 _setmode(_fileno(stdout
), _O_BINARY
);
3068 _setmode(_fileno(stderr
), _O_BINARY
);
3070 /* initialize Unicode console */
3073 /* invoke the real main() using our utf8 version of argv. */
3074 exit_status
= main(argc
, argv
);
3076 for (i
= 0; i
< argc
; i
++)
3084 int uname(struct utsname
*buf
)
3086 unsigned v
= (unsigned)GetVersion();
3087 memset(buf
, 0, sizeof(*buf
));
3088 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3089 xsnprintf(buf
->release
, sizeof(buf
->release
),
3090 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3091 /* assuming NT variants only.. */
3092 xsnprintf(buf
->version
, sizeof(buf
->version
),
3093 "%u", (v
>> 16) & 0x7fff);