1 #include "../git-compat-util.h"
7 #include "../run-command.h"
9 #include "win32/lazyload.h"
10 #include "../config.h"
13 #define HCAST(type, handle) ((type)(intptr_t)handle)
15 static const int delay
[] = { 0, 1, 10, 20, 40 };
17 void open_in_gdb(void)
19 static struct child_process cp
= CHILD_PROCESS_INIT
;
22 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
23 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
25 if (start_command(&cp
) < 0)
26 die_errno("Could not start gdb");
30 int err_win_to_posix(DWORD winerr
)
34 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
35 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
36 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
37 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
38 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
39 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
40 case ERROR_BAD_COMMAND
: error
= EIO
; break;
41 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
42 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
43 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
44 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
45 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
46 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
47 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
48 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
49 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
50 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
51 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
52 case ERROR_BUSY
: error
= EBUSY
; break;
53 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
54 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
55 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
56 case ERROR_CANTOPEN
: error
= EIO
; break;
57 case ERROR_CANTREAD
: error
= EIO
; break;
58 case ERROR_CANTWRITE
: error
= EIO
; break;
59 case ERROR_CRC
: error
= EIO
; break;
60 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
61 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
62 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
63 case ERROR_DIRECTORY
: error
= EINVAL
; break;
64 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
65 case ERROR_DISK_CHANGE
: error
= EIO
; break;
66 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
67 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
68 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
69 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
70 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
71 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
72 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
73 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
74 case ERROR_GEN_FAILURE
: error
= EIO
; break;
75 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
76 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
77 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
78 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
79 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
80 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
81 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
82 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
83 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
84 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
85 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
86 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
87 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
88 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
89 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
90 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
91 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
92 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
93 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
94 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
95 case ERROR_IO_DEVICE
: error
= EIO
; break;
96 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
97 case ERROR_LOCKED
: error
= EBUSY
; break;
98 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
99 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
100 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
101 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
102 case ERROR_MORE_DATA
: error
= EPIPE
; break;
103 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
104 case ERROR_NOACCESS
: error
= EFAULT
; break;
105 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
106 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
107 case ERROR_NOT_READY
: error
= EAGAIN
; break;
108 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
109 case ERROR_NO_DATA
: error
= EPIPE
; break;
110 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
111 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
112 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
113 case ERROR_OPEN_FAILED
: error
= EIO
; break;
114 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
115 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
116 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
117 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
118 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
119 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
120 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
121 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
122 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
123 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
124 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
125 case ERROR_READ_FAULT
: error
= EIO
; break;
126 case ERROR_SEEK
: error
= EIO
; break;
127 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
128 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
129 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
130 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
131 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
132 case ERROR_SWAPERROR
: error
= ENOENT
; break;
133 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
134 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
135 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
136 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
137 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
138 case ERROR_WRITE_FAULT
: error
= EIO
; break;
139 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
144 static inline int is_file_in_use_error(DWORD errcode
)
147 case ERROR_SHARING_VIOLATION
:
148 case ERROR_ACCESS_DENIED
:
155 static int read_yes_no_answer(void)
159 if (fgets(answer
, sizeof(answer
), stdin
)) {
160 size_t answer_len
= strlen(answer
);
161 int got_full_line
= 0, c
;
163 /* remove the newline */
164 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
165 answer
[answer_len
-2] = '\0';
167 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
168 answer
[answer_len
-1] = '\0';
171 /* flush the buffer in case we did not get the full line */
173 while ((c
= getchar()) != EOF
&& c
!= '\n')
176 /* we could not read, return the
177 * default answer which is no */
180 if (tolower(answer
[0]) == 'y' && !answer
[1])
182 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
184 if (tolower(answer
[0]) == 'n' && !answer
[1])
186 if (!strncasecmp(answer
, "no", sizeof(answer
)))
189 /* did not find an answer we understand */
193 static int ask_yes_no_if_possible(const char *format
, ...)
196 const char *retry_hook
[] = { NULL
, NULL
, NULL
};
199 va_start(args
, format
);
200 vsnprintf(question
, sizeof(question
), format
, args
);
203 if ((retry_hook
[0] = mingw_getenv("GIT_ASK_YESNO"))) {
204 retry_hook
[1] = question
;
205 return !run_command_v_opt(retry_hook
, 0);
208 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
213 fprintf(stderr
, "%s (y/n) ", question
);
215 if ((answer
= read_yes_no_answer()) >= 0)
218 fprintf(stderr
, "Sorry, I did not understand your answer. "
219 "Please type 'y' or 'n'\n");
224 enum hide_dotfiles_type
{
225 HIDE_DOTFILES_FALSE
= 0,
227 HIDE_DOTFILES_DOTGITONLY
230 static int core_restrict_inherited_handles
= -1;
231 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
232 static char *unset_environment_variables
;
234 int mingw_core_config(const char *var
, const char *value
, void *cb
)
236 if (!strcmp(var
, "core.hidedotfiles")) {
237 if (value
&& !strcasecmp(value
, "dotgitonly"))
238 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
240 hide_dotfiles
= git_config_bool(var
, value
);
244 if (!strcmp(var
, "core.unsetenvvars")) {
245 free(unset_environment_variables
);
246 unset_environment_variables
= xstrdup(value
);
250 if (!strcmp(var
, "core.restrictinheritedhandles")) {
251 if (value
&& !strcasecmp(value
, "auto"))
252 core_restrict_inherited_handles
= -1;
254 core_restrict_inherited_handles
=
255 git_config_bool(var
, value
);
262 /* Normalizes NT paths as returned by some low-level APIs. */
263 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
266 /* fix absolute path prefixes */
267 if (wbuf
[0] == '\\') {
268 /* strip NT namespace prefixes */
269 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
270 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
272 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
274 /* replace remaining '...UNC\' with '\\' */
275 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
280 /* convert backslashes to slashes */
281 for (i
= 0; wbuf
[i
]; i
++)
287 int mingw_unlink(const char *pathname
)
290 wchar_t wpathname
[MAX_PATH
];
291 if (xutftowcs_path(wpathname
, pathname
) < 0)
294 if (DeleteFileW(wpathname
))
297 /* read-only files cannot be removed */
298 _wchmod(wpathname
, 0666);
299 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
300 if (!is_file_in_use_error(GetLastError()))
303 * We assume that some other process had the source or
304 * destination file open at the wrong moment and retry.
305 * In order to give the other process a higher chance to
306 * complete its operation, we give up our time slice now.
307 * If we have to retry again, we do sleep a bit.
312 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
313 ask_yes_no_if_possible("Unlink of file '%s' failed. "
314 "Should I try again?", pathname
))
315 ret
= _wunlink(wpathname
);
319 static int is_dir_empty(const wchar_t *wpath
)
321 WIN32_FIND_DATAW findbuf
;
323 wchar_t wbuf
[MAX_PATH
+ 2];
325 wcscat(wbuf
, L
"\\*");
326 handle
= FindFirstFileW(wbuf
, &findbuf
);
327 if (handle
== INVALID_HANDLE_VALUE
)
328 return GetLastError() == ERROR_NO_MORE_FILES
;
330 while (!wcscmp(findbuf
.cFileName
, L
".") ||
331 !wcscmp(findbuf
.cFileName
, L
".."))
332 if (!FindNextFileW(handle
, &findbuf
)) {
333 DWORD err
= GetLastError();
335 return err
== ERROR_NO_MORE_FILES
;
341 int mingw_rmdir(const char *pathname
)
344 wchar_t wpathname
[MAX_PATH
];
348 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
349 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
350 * symbolic link (if it points to a directory).
352 * This behavior breaks the assumption of e.g. `remove_path()` which
353 * upon successful deletion of a file will attempt to remove its parent
354 * directories recursively until failure (which usually happens when
355 * the directory is not empty).
357 * Therefore, before calling `_wrmdir()`, we first check if the path is
358 * a symbolic link. If it is, we exit and return the same error as
359 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
361 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
366 if (xutftowcs_path(wpathname
, pathname
) < 0)
369 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
370 if (!is_file_in_use_error(GetLastError()))
371 errno
= err_win_to_posix(GetLastError());
374 if (!is_dir_empty(wpathname
)) {
379 * We assume that some other process had the source or
380 * destination file open at the wrong moment and retry.
381 * In order to give the other process a higher chance to
382 * complete its operation, we give up our time slice now.
383 * If we have to retry again, we do sleep a bit.
388 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
389 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
390 "Should I try again?", pathname
))
391 ret
= _wrmdir(wpathname
);
393 invalidate_lstat_cache();
397 static inline int needs_hiding(const char *path
)
399 const char *basename
;
401 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
404 /* We cannot use basename(), as it would remove trailing slashes */
405 win32_skip_dos_drive_prefix((char **)&path
);
409 for (basename
= path
; *path
; path
++)
410 if (is_dir_sep(*path
)) {
413 } while (is_dir_sep(*path
));
414 /* ignore trailing slashes */
421 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
422 return *basename
== '.';
424 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
425 return !strncasecmp(".git", basename
, 4) &&
426 (!basename
[4] || is_dir_sep(basename
[4]));
429 static int set_hidden_flag(const wchar_t *path
, int set
)
431 DWORD original
= GetFileAttributesW(path
), modified
;
433 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
435 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
436 if (original
== modified
|| SetFileAttributesW(path
, modified
))
438 errno
= err_win_to_posix(GetLastError());
442 int mingw_mkdir(const char *path
, int mode
)
445 wchar_t wpath
[MAX_PATH
];
447 if (!is_valid_win32_path(path
, 0)) {
452 if (xutftowcs_path(wpath
, path
) < 0)
454 ret
= _wmkdir(wpath
);
455 if (!ret
&& needs_hiding(path
))
456 return set_hidden_flag(wpath
, 1);
461 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
462 * is documented in [1] as opening a writable file handle in append mode.
463 * (It is believed that) this is atomic since it is maintained by the
464 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
466 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
468 * This trick does not appear to work for named pipes. Instead it creates
469 * a named pipe client handle that cannot be written to. Callers should
470 * just use the regular _wopen() for them. (And since client handle gets
471 * bound to a unique server handle, it isn't really an issue.)
473 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
477 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
479 /* only these flags are supported */
480 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
481 return errno
= ENOSYS
, -1;
484 * FILE_SHARE_WRITE is required to permit child processes
485 * to append to the file.
487 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
488 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
489 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
490 if (handle
== INVALID_HANDLE_VALUE
) {
491 DWORD err
= GetLastError();
494 * Some network storage solutions (e.g. Isilon) might return
495 * ERROR_INVALID_PARAMETER instead of expected error
496 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
497 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
499 if (err
== ERROR_INVALID_PARAMETER
)
500 err
= ERROR_PATH_NOT_FOUND
;
502 errno
= err_win_to_posix(err
);
507 * No O_APPEND here, because the CRT uses it only to reset the
508 * file pointer to EOF before each write(); but that is not
509 * necessary (and may lead to races) for a file created with
512 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
519 * Does the pathname map to the local named pipe filesystem?
520 * That is, does it have a "//./pipe/" prefix?
522 static int is_local_named_pipe_path(const char *filename
)
524 return (is_dir_sep(filename
[0]) &&
525 is_dir_sep(filename
[1]) &&
526 filename
[2] == '.' &&
527 is_dir_sep(filename
[3]) &&
528 !strncasecmp(filename
+4, "pipe", 4) &&
529 is_dir_sep(filename
[8]) &&
533 int mingw_open (const char *filename
, int oflags
, ...)
535 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
538 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
539 wchar_t wfilename
[MAX_PATH
];
542 va_start(args
, oflags
);
543 mode
= va_arg(args
, int);
546 if (!is_valid_win32_path(filename
, !create
)) {
547 errno
= create
? EINVAL
: ENOENT
;
551 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
552 open_fn
= mingw_open_append
;
556 if (filename
&& !strcmp(filename
, "/dev/null"))
557 wcscpy(wfilename
, L
"nul");
558 else if (xutftowcs_path(wfilename
, filename
) < 0)
561 fd
= open_fn(wfilename
, oflags
, mode
);
563 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
564 DWORD attrs
= GetFileAttributesW(wfilename
);
565 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
568 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
570 * Internally, _wopen() uses the CreateFile() API which errors
571 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
572 * specified and an already existing file's attributes do not
573 * match *exactly*. As there is no mode or flag we can set that
574 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
575 * again *without* the O_CREAT flag (that corresponds to the
576 * CREATE_ALWAYS flag of CreateFile()).
578 if (fd
< 0 && errno
== EACCES
)
579 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
580 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
581 warning("could not mark '%s' as hidden.", filename
);
586 static BOOL WINAPI
ctrl_ignore(DWORD type
)
592 int mingw_fgetc(FILE *stream
)
595 if (!isatty(_fileno(stream
)))
596 return fgetc(stream
);
598 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
601 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
604 /* Ctrl+C was pressed, simulate SIGINT and retry */
607 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
612 FILE *mingw_fopen (const char *filename
, const char *otype
)
614 int hide
= needs_hiding(filename
);
616 wchar_t wfilename
[MAX_PATH
], wotype
[4];
617 if (filename
&& !strcmp(filename
, "/dev/null"))
618 wcscpy(wfilename
, L
"nul");
619 else if (!is_valid_win32_path(filename
, 1)) {
620 int create
= otype
&& strchr(otype
, 'w');
621 errno
= create
? EINVAL
: ENOENT
;
623 } else if (xutftowcs_path(wfilename
, filename
) < 0)
626 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
629 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
630 error("could not unhide %s", filename
);
633 file
= _wfopen(wfilename
, wotype
);
634 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
636 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
637 warning("could not mark '%s' as hidden.", filename
);
641 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
643 int hide
= needs_hiding(filename
);
645 wchar_t wfilename
[MAX_PATH
], wotype
[4];
646 if (filename
&& !strcmp(filename
, "/dev/null"))
647 wcscpy(wfilename
, L
"nul");
648 else if (!is_valid_win32_path(filename
, 1)) {
649 int create
= otype
&& strchr(otype
, 'w');
650 errno
= create
? EINVAL
: ENOENT
;
652 } else if (xutftowcs_path(wfilename
, filename
) < 0)
655 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
658 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
659 error("could not unhide %s", filename
);
662 file
= _wfreopen(wfilename
, wotype
, stream
);
663 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
664 warning("could not mark '%s' as hidden.", filename
);
669 int mingw_fflush(FILE *stream
)
671 int ret
= fflush(stream
);
674 * write() is used behind the scenes of stdio output functions.
675 * Since git code does not check for errors after each stdio write
676 * operation, it can happen that write() is called by a later
677 * stdio function even if an earlier write() call failed. In the
678 * case of a pipe whose readable end was closed, only the first
679 * call to write() reports EPIPE on Windows. Subsequent write()
680 * calls report EINVAL. It is impossible to notice whether this
681 * fflush invocation triggered such a case, therefore, we have to
682 * catch all EINVAL errors whole-sale.
684 if (ret
&& errno
== EINVAL
)
691 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
693 ssize_t result
= write(fd
, buf
, len
);
695 if (result
< 0 && errno
== EINVAL
&& buf
) {
696 /* check if fd is a pipe */
697 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
698 if (GetFileType(h
) == FILE_TYPE_PIPE
)
707 int mingw_access(const char *filename
, int mode
)
709 wchar_t wfilename
[MAX_PATH
];
710 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
712 if (xutftowcs_path(wfilename
, filename
) < 0)
714 /* X_OK is not supported by the MSVCRT version */
715 return _waccess(wfilename
, mode
& ~X_OK
);
718 int mingw_chdir(const char *dirname
)
720 wchar_t wdirname
[MAX_PATH
];
721 if (xutftowcs_path(wdirname
, dirname
) < 0)
723 return _wchdir(wdirname
);
726 int mingw_chmod(const char *filename
, int mode
)
728 wchar_t wfilename
[MAX_PATH
];
729 if (xutftowcs_path(wfilename
, filename
) < 0)
731 return _wchmod(wfilename
, mode
);
735 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
736 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
738 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
740 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
741 /* Windows to Unix Epoch conversion */
742 return winTime
- 116444736000000000LL;
745 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
747 long long hnsec
= filetime_to_hnsec(ft
);
748 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
749 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
753 * Verifies that safe_create_leading_directories() would succeed.
755 static int has_valid_directory_prefix(wchar_t *wfilename
)
757 int n
= wcslen(wfilename
);
760 wchar_t c
= wfilename
[--n
];
766 wfilename
[n
] = L
'\0';
767 attributes
= GetFileAttributesW(wfilename
);
769 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
770 attributes
== FILE_ATTRIBUTE_DEVICE
)
772 if (attributes
== INVALID_FILE_ATTRIBUTES
)
773 switch (GetLastError()) {
774 case ERROR_PATH_NOT_FOUND
:
776 case ERROR_FILE_NOT_FOUND
:
777 /* This implies parent directory exists. */
785 /* We keep the do_lstat code in a separate function to avoid recursion.
786 * When a path ends with a slash, the stat will fail with ENOENT. In
787 * this case, we strip the trailing slashes and stat again.
789 * If follow is true then act like stat() and report on the link
790 * target. Otherwise report on the link itself.
792 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
794 WIN32_FILE_ATTRIBUTE_DATA fdata
;
795 wchar_t wfilename
[MAX_PATH
];
796 if (xutftowcs_path(wfilename
, file_name
) < 0)
799 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
804 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
805 buf
->st_size
= fdata
.nFileSizeLow
|
806 (((off_t
)fdata
.nFileSizeHigh
)<<32);
807 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
808 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
809 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
810 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
811 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
812 WIN32_FIND_DATAW findbuf
;
813 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
814 if (handle
!= INVALID_HANDLE_VALUE
) {
815 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
816 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
818 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
819 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
821 buf
->st_mode
= S_IFLNK
;
823 buf
->st_mode
|= S_IREAD
;
824 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
825 buf
->st_mode
|= S_IWRITE
;
832 switch (GetLastError()) {
833 case ERROR_ACCESS_DENIED
:
834 case ERROR_SHARING_VIOLATION
:
835 case ERROR_LOCK_VIOLATION
:
836 case ERROR_SHARING_BUFFER_EXCEEDED
:
839 case ERROR_BUFFER_OVERFLOW
:
840 errno
= ENAMETOOLONG
;
842 case ERROR_NOT_ENOUGH_MEMORY
:
845 case ERROR_PATH_NOT_FOUND
:
846 if (!has_valid_directory_prefix(wfilename
)) {
858 /* We provide our own lstat/fstat functions, since the provided
859 * lstat/fstat functions are so slow. These stat functions are
860 * tailored for Git's usage (read: fast), and are not meant to be
861 * complete. Note that Git stat()s are redirected to mingw_lstat()
862 * too, since Windows doesn't really handle symlinks that well.
864 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
867 char alt_name
[PATH_MAX
];
869 if (!do_lstat(follow
, file_name
, buf
))
872 /* if file_name ended in a '/', Windows returned ENOENT;
873 * try again without trailing slashes
878 namelen
= strlen(file_name
);
879 if (namelen
&& file_name
[namelen
-1] != '/')
881 while (namelen
&& file_name
[namelen
-1] == '/')
883 if (!namelen
|| namelen
>= PATH_MAX
)
886 memcpy(alt_name
, file_name
, namelen
);
887 alt_name
[namelen
] = 0;
888 return do_lstat(follow
, alt_name
, buf
);
891 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
893 BY_HANDLE_FILE_INFORMATION fdata
;
895 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
896 errno
= err_win_to_posix(GetLastError());
904 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
905 buf
->st_size
= fdata
.nFileSizeLow
|
906 (((off_t
)fdata
.nFileSizeHigh
)<<32);
907 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
908 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
909 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
910 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
914 int mingw_lstat(const char *file_name
, struct stat
*buf
)
916 return do_stat_internal(0, file_name
, buf
);
918 int mingw_stat(const char *file_name
, struct stat
*buf
)
920 return do_stat_internal(1, file_name
, buf
);
923 int mingw_fstat(int fd
, struct stat
*buf
)
925 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
926 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
930 return get_file_info_by_handle(fh
, buf
);
934 /* initialize stat fields */
935 memset(buf
, 0, sizeof(*buf
));
938 if (type
== FILE_TYPE_CHAR
) {
939 buf
->st_mode
= _S_IFCHR
;
941 buf
->st_mode
= _S_IFIFO
;
942 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
943 buf
->st_size
= avail
;
953 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
955 long long winTime
= t
* 10000000LL + 116444736000000000LL;
956 ft
->dwLowDateTime
= winTime
;
957 ft
->dwHighDateTime
= winTime
>> 32;
960 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
965 wchar_t wfilename
[MAX_PATH
];
966 if (xutftowcs_path(wfilename
, file_name
) < 0)
969 /* must have write permission */
970 attrs
= GetFileAttributesW(wfilename
);
971 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
972 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
973 /* ignore errors here; open() will report them */
974 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
977 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
983 time_t_to_filetime(times
->modtime
, &mft
);
984 time_t_to_filetime(times
->actime
, &aft
);
986 GetSystemTimeAsFileTime(&mft
);
989 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
997 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
998 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
999 /* ignore errors again */
1000 SetFileAttributesW(wfilename
, attrs
);
1006 size_t mingw_strftime(char *s
, size_t max
,
1007 const char *format
, const struct tm
*tm
)
1009 /* a pointer to the original strftime in case we can't find the UCRT version */
1010 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1012 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, strftime
, char *, size_t,
1013 const char *, const struct tm
*);
1015 if (INIT_PROC_ADDR(strftime
))
1016 ret
= strftime(s
, max
, format
, tm
);
1018 ret
= fallback(s
, max
, format
, tm
);
1020 if (!ret
&& errno
== EINVAL
)
1021 die("invalid strftime format: '%s'", format
);
1025 unsigned int sleep (unsigned int seconds
)
1027 Sleep(seconds
*1000);
1031 char *mingw_mktemp(char *template)
1033 wchar_t wtemplate
[MAX_PATH
];
1034 if (xutftowcs_path(wtemplate
, template) < 0)
1036 if (!_wmktemp(wtemplate
))
1038 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1043 int mkstemp(char *template)
1045 char *filename
= mktemp(template);
1046 if (filename
== NULL
)
1048 return open(filename
, O_RDWR
| O_CREAT
, 0600);
1051 int gettimeofday(struct timeval
*tv
, void *tz
)
1056 GetSystemTimeAsFileTime(&ft
);
1057 hnsec
= filetime_to_hnsec(&ft
);
1058 tv
->tv_sec
= hnsec
/ 10000000;
1059 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1063 int pipe(int filedes
[2])
1067 /* this creates non-inheritable handles */
1068 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1069 errno
= err_win_to_posix(GetLastError());
1072 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1073 if (filedes
[0] < 0) {
1078 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1079 if (filedes
[1] < 0) {
1088 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1090 if (gmtime_s(result
, timep
) == 0)
1095 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1097 if (localtime_s(result
, timep
) == 0)
1103 char *mingw_getcwd(char *pointer
, int len
)
1105 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1106 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1108 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1109 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1112 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1113 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1114 HANDLE hnd
= CreateFileW(cwd
, 0,
1115 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1116 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1117 if (hnd
== INVALID_HANDLE_VALUE
)
1119 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1121 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1123 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1127 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1129 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1131 convert_slashes(pointer
);
1136 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1137 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1139 static const char *quote_arg_msvc(const char *arg
)
1141 /* count chars to quote */
1143 int force_quotes
= 0;
1145 const char *p
= arg
;
1146 if (!*p
) force_quotes
= 1;
1148 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1152 else if (*p
== '\\') {
1154 while (*p
== '\\') {
1159 if (*p
== '"' || !*p
)
1166 if (!force_quotes
&& n
== 0)
1169 /* insert \ where necessary */
1170 d
= q
= xmalloc(st_add3(len
, n
, 3));
1175 else if (*arg
== '\\') {
1177 while (*arg
== '\\') {
1181 if (*arg
== '"' || !*arg
) {
1184 /* don't escape the surrounding end quote */
1199 static const char *quote_arg_msys2(const char *arg
)
1201 struct strbuf buf
= STRBUF_INIT
;
1202 const char *p2
= arg
, *p
;
1204 for (p
= arg
; *p
; p
++) {
1205 int ws
= isspace(*p
);
1206 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1207 *p
!= '?' && *p
!= '*' && *p
!= '~')
1210 strbuf_addch(&buf
, '"');
1212 strbuf_add(&buf
, p2
, p
- p2
);
1213 if (*p
== '\\' || *p
== '"')
1214 strbuf_addch(&buf
, '\\');
1219 strbuf_addch(&buf
, '"');
1223 strbuf_add(&buf
, p2
, p
- p2
);
1225 strbuf_addch(&buf
, '"');
1226 return strbuf_detach(&buf
, 0);
1229 static const char *parse_interpreter(const char *cmd
)
1231 static char buf
[100];
1235 /* don't even try a .exe */
1237 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1240 fd
= open(cmd
, O_RDONLY
);
1243 n
= read(fd
, buf
, sizeof(buf
)-1);
1245 if (n
< 4) /* at least '#!/x' and not error */
1248 if (buf
[0] != '#' || buf
[1] != '!')
1251 p
= buf
+ strcspn(buf
, "\r\n");
1256 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1259 if ((opt
= strchr(p
+1, ' ')))
1265 * exe_only means that we only want to detect .exe files, but not scripts
1266 * (which do not have an extension)
1268 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1269 int isexe
, int exe_only
)
1271 char path
[MAX_PATH
];
1272 wchar_t wpath
[MAX_PATH
];
1273 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1275 if (xutftowcs_path(wpath
, path
) < 0)
1278 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1279 return xstrdup(path
);
1280 wpath
[wcslen(wpath
)-4] = '\0';
1281 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1282 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1283 path
[strlen(path
)-4] = '\0';
1284 return xstrdup(path
);
1291 * Determines the absolute path of cmd using the split path in path.
1292 * If cmd contains a slash or backslash, no lookup is performed.
1294 static char *path_lookup(const char *cmd
, int exe_only
)
1298 int len
= strlen(cmd
);
1299 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1301 if (strpbrk(cmd
, "/\\"))
1302 return xstrdup(cmd
);
1304 path
= mingw_getenv("PATH");
1309 const char *sep
= strchrnul(path
, ';');
1310 int dirlen
= sep
- path
;
1312 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1321 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1323 while (*s
&& *s
!= c
)
1328 /* Compare only keys */
1329 static int wenvcmp(const void *a
, const void *b
)
1331 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1332 size_t p_len
, q_len
;
1335 p_len
= wcschrnul(p
, L
'=') - p
;
1336 q_len
= wcschrnul(q
, L
'=') - q
;
1338 /* If the length differs, include the shorter key's NUL */
1341 else if (p_len
> q_len
)
1344 return _wcsnicmp(p
, q
, p_len
);
1348 * Build an environment block combining the inherited environment
1349 * merged with the given list of settings.
1351 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1352 * Values of the form "KEY" in deltaenv delete inherited values.
1354 * Multiple entries in deltaenv for the same key are explicitly allowed.
1356 * We return a contiguous block of UNICODE strings with a final trailing
1359 static wchar_t *make_environment_block(char **deltaenv
)
1361 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1362 size_t wlen
, s
, delta_size
, size
;
1364 wchar_t **array
= NULL
;
1365 size_t alloc
= 0, nr
= 0, i
;
1367 size
= 1; /* for extra NUL at the end */
1369 /* If there is no deltaenv to apply, simply return a copy. */
1370 if (!deltaenv
|| !*deltaenv
) {
1371 for (p
= wenv
; p
&& *p
; ) {
1372 size_t s
= wcslen(p
) + 1;
1377 ALLOC_ARRAY(result
, size
);
1378 COPY_ARRAY(result
, wenv
, size
);
1379 FreeEnvironmentStringsW(wenv
);
1384 * If there is a deltaenv, let's accumulate all keys into `array`,
1385 * sort them using the stable git_stable_qsort() and then copy,
1386 * skipping duplicate keys
1388 for (p
= wenv
; p
&& *p
; ) {
1389 ALLOC_GROW(array
, nr
+ 1, alloc
);
1396 /* (over-)assess size needed for wchar version of deltaenv */
1397 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1398 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1399 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1401 /* convert the deltaenv, appending to array */
1402 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1403 ALLOC_GROW(array
, nr
+ 1, alloc
);
1404 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1409 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1410 ALLOC_ARRAY(result
, size
+ delta_size
);
1412 for (p
= result
, i
= 0; i
< nr
; i
++) {
1413 /* Skip any duplicate keys; last one wins */
1414 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1417 /* Skip "to delete" entry */
1418 if (!wcschr(array
[i
], L
'='))
1421 size
= wcslen(array
[i
]) + 1;
1422 COPY_ARRAY(p
, array
[i
], size
);
1429 FreeEnvironmentStringsW(wenv
);
1433 static void do_unset_environment_variables(void)
1436 char *p
= unset_environment_variables
;
1443 char *comma
= strchr(p
, ',');
1455 struct pinfo_t
*next
;
1459 static struct pinfo_t
*pinfo
= NULL
;
1460 CRITICAL_SECTION pinfo_cs
;
1462 /* Used to match and chomp off path components */
1463 static inline int match_last_path_component(const char *path
, size_t *len
,
1464 const char *component
)
1466 size_t component_len
= strlen(component
);
1467 if (*len
< component_len
+ 1 ||
1468 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1469 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1471 *len
-= component_len
+ 1;
1472 /* chomp off repeated dir separators */
1473 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1478 static int is_msys2_sh(const char *cmd
)
1483 if (!strcmp(cmd
, "sh")) {
1484 static int ret
= -1;
1490 p
= path_lookup(cmd
, 0);
1494 size_t len
= strlen(p
);
1496 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1497 match_last_path_component(p
, &len
, "bin") &&
1498 match_last_path_component(p
, &len
, "usr");
1504 if (ends_with(cmd
, "\\sh.exe")) {
1508 sh
= path_lookup("sh", 0);
1510 return !fspathcmp(cmd
, sh
);
1516 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1518 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1520 static int restrict_handle_inheritance
= -1;
1522 PROCESS_INFORMATION pi
;
1523 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1524 HANDLE stdhandles
[3];
1525 DWORD stdhandles_count
= 0;
1528 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1529 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1532 const char *(*quote_arg
)(const char *arg
) =
1533 is_msys2_sh(cmd
? cmd
: *argv
) ?
1534 quote_arg_msys2
: quote_arg_msvc
;
1535 const char *strace_env
;
1537 /* Make sure to override previous errors, if any */
1540 if (restrict_handle_inheritance
< 0)
1541 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1543 * The following code to restrict which handles are inherited seems
1544 * to work properly only on Windows 7 and later, so let's disable it
1545 * on Windows Vista and 2008.
1547 if (restrict_handle_inheritance
< 0)
1548 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1550 do_unset_environment_variables();
1552 /* Determine whether or not we are associated to a console */
1553 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1554 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1555 FILE_ATTRIBUTE_NORMAL
, NULL
);
1556 if (cons
== INVALID_HANDLE_VALUE
) {
1557 /* There is no console associated with this process.
1558 * Since the child is a console process, Windows
1559 * would normally create a console window. But
1560 * since we'll be redirecting std streams, we do
1561 * not need the console.
1562 * It is necessary to use DETACHED_PROCESS
1563 * instead of CREATE_NO_WINDOW to make ssh
1564 * recognize that it has no console.
1566 flags
|= DETACHED_PROCESS
;
1568 /* There is already a console. If we specified
1569 * DETACHED_PROCESS here, too, Windows would
1570 * disassociate the child from the console.
1571 * The same is true for CREATE_NO_WINDOW.
1576 memset(&si
, 0, sizeof(si
));
1577 si
.StartupInfo
.cb
= sizeof(si
);
1578 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1579 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1580 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1582 /* The list of handles cannot contain duplicates */
1583 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1584 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1585 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1586 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1587 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1588 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1589 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1590 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1591 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1592 if (stdhandles_count
)
1593 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1595 if (*argv
&& !strcmp(cmd
, *argv
))
1597 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1599 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1602 /* concatenate argv, quoting args as we go */
1603 strbuf_init(&args
, 0);
1605 char *quoted
= (char *)quote_arg(cmd
);
1606 strbuf_addstr(&args
, quoted
);
1610 for (; *argv
; argv
++) {
1611 char *quoted
= (char *)quote_arg(*argv
);
1613 strbuf_addch(&args
, ' ');
1614 strbuf_addstr(&args
, quoted
);
1615 if (quoted
!= *argv
)
1619 strace_env
= getenv("GIT_STRACE_COMMANDS");
1621 char *p
= path_lookup("strace.exe", 1);
1623 return error("strace not found!");
1624 if (xutftowcs_path(wcmd
, p
) < 0) {
1629 if (!strcmp("1", strace_env
) ||
1630 !strcasecmp("yes", strace_env
) ||
1631 !strcasecmp("true", strace_env
))
1632 strbuf_insert(&args
, 0, "strace ", 7);
1634 const char *quoted
= quote_arg(strace_env
);
1635 struct strbuf buf
= STRBUF_INIT
;
1636 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1637 if (quoted
!= strace_env
)
1638 free((char *)quoted
);
1639 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1640 strbuf_release(&buf
);
1644 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1645 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1646 strbuf_release(&args
);
1648 wenvblk
= make_environment_block(deltaenv
);
1650 memset(&pi
, 0, sizeof(pi
));
1651 if (restrict_handle_inheritance
&& stdhandles_count
&&
1652 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1653 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1654 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1655 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1656 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1657 UpdateProcThreadAttribute(attr_list
, 0,
1658 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1660 stdhandles_count
* sizeof(HANDLE
),
1662 si
.lpAttributeList
= attr_list
;
1663 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1666 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1667 stdhandles_count
? TRUE
: FALSE
,
1668 flags
, wenvblk
, dir
? wdir
: NULL
,
1669 &si
.StartupInfo
, &pi
);
1672 * On Windows 2008 R2, it seems that specifying certain types of handles
1673 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1674 * error. Rather than playing finicky and fragile games, let's just try
1675 * to detect this situation and simply try again without restricting any
1676 * handle inheritance. This is still better than failing to create
1679 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1680 DWORD err
= GetLastError();
1681 struct strbuf buf
= STRBUF_INIT
;
1683 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1685 * On Windows 7 and earlier, handles on pipes and character
1686 * devices are inherited automatically, and cannot be
1687 * specified in the thread handle list. Rather than trying
1688 * to catch each and every corner case (and running the
1689 * chance of *still* forgetting a few), let's just fall
1690 * back to creating the process without trying to limit the
1691 * handle inheritance.
1693 !(err
== ERROR_INVALID_PARAMETER
&&
1694 GetVersion() >> 16 < 9200) &&
1695 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1699 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1701 for (i
= 0; i
< stdhandles_count
; i
++) {
1702 HANDLE h
= stdhandles
[i
];
1703 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1704 "handle info (%d) %lx\n", i
, h
,
1706 GetHandleInformation(h
, &fl
),
1709 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1710 "at\nhttps://github.com/git-for-windows/"
1711 "git/issues/new\n\n"
1712 "To suppress this warning, please set "
1713 "the environment variable\n\n"
1714 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1717 restrict_handle_inheritance
= 0;
1718 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1719 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1720 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1721 &si
.StartupInfo
, &pi
);
1723 errno
= err_win_to_posix(GetLastError());
1724 if (ret
&& buf
.len
) {
1725 warning("failed to restrict file handles (%ld)\n\n%s",
1728 strbuf_release(&buf
);
1730 errno
= err_win_to_posix(GetLastError());
1732 if (si
.lpAttributeList
)
1733 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1735 HeapFree(GetProcessHeap(), 0, attr_list
);
1743 CloseHandle(pi
.hThread
);
1746 * The process ID is the human-readable identifier of the process
1747 * that we want to present in log and error messages. The handle
1748 * is not useful for this purpose. But we cannot close it, either,
1749 * because it is not possible to turn a process ID into a process
1750 * handle after the process terminated.
1751 * Keep the handle in a list for waitpid.
1753 EnterCriticalSection(&pinfo_cs
);
1755 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1756 info
->pid
= pi
.dwProcessId
;
1757 info
->proc
= pi
.hProcess
;
1761 LeaveCriticalSection(&pinfo_cs
);
1763 return (pid_t
)pi
.dwProcessId
;
1766 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1768 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1771 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1773 int fhin
, int fhout
, int fherr
)
1776 char *prog
= path_lookup(cmd
, 0);
1783 const char *interpr
= parse_interpreter(prog
);
1786 const char *argv0
= argv
[0];
1787 char *iprog
= path_lookup(interpr
, 1);
1794 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1795 fhin
, fhout
, fherr
);
1801 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1802 fhin
, fhout
, fherr
);
1808 static int try_shell_exec(const char *cmd
, char *const *argv
)
1810 const char *interpr
= parse_interpreter(cmd
);
1816 prog
= path_lookup(interpr
, 1);
1824 while (argv
[argc
]) argc
++;
1825 ALLOC_ARRAY(argv2
, argc
+ 1);
1826 argv2
[0] = (char *)cmd
; /* full path to the script file */
1827 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1828 exec_id
= trace2_exec(prog
, argv2
);
1829 pid
= mingw_spawnv(prog
, argv2
, 1);
1832 if (waitpid(pid
, &status
, 0) < 0)
1834 trace2_exec_result(exec_id
, status
);
1837 trace2_exec_result(exec_id
, -1);
1838 pid
= 1; /* indicate that we tried but failed */
1845 int mingw_execv(const char *cmd
, char *const *argv
)
1847 /* check if git_command is a shell script */
1848 if (!try_shell_exec(cmd
, argv
)) {
1852 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1853 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1855 trace2_exec_result(exec_id
, -1);
1858 if (waitpid(pid
, &status
, 0) < 0)
1860 trace2_exec_result(exec_id
, status
);
1866 int mingw_execvp(const char *cmd
, char *const *argv
)
1868 char *prog
= path_lookup(cmd
, 0);
1871 mingw_execv(prog
, argv
);
1879 int mingw_kill(pid_t pid
, int sig
)
1881 if (pid
> 0 && sig
== SIGTERM
) {
1882 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1884 if (TerminateProcess(h
, -1)) {
1889 errno
= err_win_to_posix(GetLastError());
1892 } else if (pid
> 0 && sig
== 0) {
1893 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1905 * UTF-8 versions of getenv(), putenv() and unsetenv().
1906 * Internally, they use the CRT's stock UNICODE routines
1907 * to avoid data loss.
1909 char *mingw_getenv(const char *name
)
1911 #define GETENV_MAX_RETAIN 64
1912 static char *values
[GETENV_MAX_RETAIN
];
1913 static int value_counter
;
1914 int len_key
, len_value
;
1917 wchar_t w_value
[32768];
1919 if (!name
|| !*name
)
1922 len_key
= strlen(name
) + 1;
1923 /* We cannot use xcalloc() here because that uses getenv() itself */
1924 w_key
= calloc(len_key
, sizeof(wchar_t));
1926 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1927 xutftowcs(w_key
, name
, len_key
);
1928 /* GetEnvironmentVariableW() only sets the last error upon failure */
1929 SetLastError(ERROR_SUCCESS
);
1930 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1931 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1937 len_value
= len_value
* 3 + 1;
1938 /* We cannot use xcalloc() here because that uses getenv() itself */
1939 value
= calloc(len_value
, sizeof(char));
1941 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1942 xwcstoutf(value
, w_value
, len_value
);
1945 * We return `value` which is an allocated value and the caller is NOT
1946 * expecting to have to free it, so we keep a round-robin array,
1947 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1949 free(values
[value_counter
]);
1950 values
[value_counter
++] = value
;
1951 if (value_counter
>= ARRAY_SIZE(values
))
1957 int mingw_putenv(const char *namevalue
)
1960 wchar_t *wide
, *equal
;
1963 if (!namevalue
|| !*namevalue
)
1966 size
= strlen(namevalue
) * 2 + 1;
1967 wide
= calloc(size
, sizeof(wchar_t));
1969 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1970 xutftowcs(wide
, namevalue
, size
);
1971 equal
= wcschr(wide
, L
'=');
1973 result
= SetEnvironmentVariableW(wide
, NULL
);
1976 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
1981 errno
= err_win_to_posix(GetLastError());
1983 return result
? 0 : -1;
1986 static void ensure_socket_initialization(void)
1989 static int initialized
= 0;
1994 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1995 die("unable to initialize winsock subsystem, error %d",
1998 atexit((void(*)(void)) WSACleanup
);
2003 int mingw_gethostname(char *name
, int namelen
)
2005 ensure_socket_initialization();
2006 return gethostname(name
, namelen
);
2009 #undef gethostbyname
2010 struct hostent
*mingw_gethostbyname(const char *host
)
2012 ensure_socket_initialization();
2013 return gethostbyname(host
);
2017 int mingw_getaddrinfo(const char *node
, const char *service
,
2018 const struct addrinfo
*hints
, struct addrinfo
**res
)
2020 ensure_socket_initialization();
2021 return getaddrinfo(node
, service
, hints
, res
);
2024 int mingw_socket(int domain
, int type
, int protocol
)
2029 ensure_socket_initialization();
2030 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2031 if (s
== INVALID_SOCKET
) {
2033 * WSAGetLastError() values are regular BSD error codes
2034 * biased by WSABASEERR.
2035 * However, strerror() does not know about networking
2036 * specific errors, which are values beginning at 38 or so.
2037 * Therefore, we choose to leave the biased error code
2038 * in errno so that _if_ someone looks up the code somewhere,
2039 * then it is at least the number that are usually listed.
2041 errno
= WSAGetLastError();
2044 /* convert into a file descriptor */
2045 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2047 return error("unable to make a socket file descriptor: %s",
2054 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2056 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2057 return connect(s
, sa
, sz
);
2061 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2063 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2064 return bind(s
, sa
, sz
);
2068 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2070 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2071 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2075 int mingw_shutdown(int sockfd
, int how
)
2077 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2078 return shutdown(s
, how
);
2082 int mingw_listen(int sockfd
, int backlog
)
2084 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2085 return listen(s
, backlog
);
2089 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2093 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2094 SOCKET s2
= accept(s1
, sa
, sz
);
2096 /* convert into a file descriptor */
2097 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2100 return error("unable to make a socket file descriptor: %s",
2107 int mingw_rename(const char *pold
, const char *pnew
)
2111 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2112 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2116 * Try native rename() first to get errno right.
2117 * It is based on MoveFile(), which cannot overwrite existing files.
2119 if (!_wrename(wpold
, wpnew
))
2121 if (errno
!= EEXIST
)
2124 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2126 /* TODO: translate more errors */
2127 gle
= GetLastError();
2128 if (gle
== ERROR_ACCESS_DENIED
&&
2129 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2130 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2131 DWORD attrsold
= GetFileAttributesW(wpold
);
2132 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2133 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2135 else if (!_wrmdir(wpnew
))
2139 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2140 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2141 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2143 gle
= GetLastError();
2144 /* revert file attributes on failure */
2145 SetFileAttributesW(wpnew
, attrs
);
2148 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2150 * We assume that some other process had the source or
2151 * destination file open at the wrong moment and retry.
2152 * In order to give the other process a higher chance to
2153 * complete its operation, we give up our time slice now.
2154 * If we have to retry again, we do sleep a bit.
2156 Sleep(delay
[tries
]);
2160 if (gle
== ERROR_ACCESS_DENIED
&&
2161 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2162 "Should I try again?", pold
, pnew
))
2170 * Note that this doesn't return the actual pagesize, but
2171 * the allocation granularity. If future Windows specific git code
2172 * needs the real getpagesize function, we need to find another solution.
2174 int mingw_getpagesize(void)
2178 return si
.dwAllocationGranularity
;
2181 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2182 enum EXTENDED_NAME_FORMAT
{
2184 NameUserPrincipal
= 8
2187 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2189 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, GetUserNameExW
,
2190 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2191 static wchar_t wbuffer
[1024];
2194 if (!INIT_PROC_ADDR(GetUserNameExW
))
2197 len
= ARRAY_SIZE(wbuffer
);
2198 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2199 char *converted
= xmalloc((len
*= 3));
2200 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2208 char *mingw_query_user_email(void)
2210 return get_extended_user_info(NameUserPrincipal
);
2213 struct passwd
*getpwuid(int uid
)
2215 static unsigned initialized
;
2216 static char user_name
[100];
2217 static struct passwd
*p
;
2224 len
= ARRAY_SIZE(buf
);
2225 if (!GetUserNameW(buf
, &len
)) {
2230 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2235 p
= xmalloc(sizeof(*p
));
2236 p
->pw_name
= user_name
;
2237 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2239 p
->pw_gecos
= "unknown";
2246 static HANDLE timer_event
;
2247 static HANDLE timer_thread
;
2248 static int timer_interval
;
2249 static int one_shot
;
2250 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2252 /* The timer works like this:
2253 * The thread, ticktack(), is a trivial routine that most of the time
2254 * only waits to receive the signal to terminate. The main thread tells
2255 * the thread to terminate by setting the timer_event to the signalled
2257 * But ticktack() interrupts the wait state after the timer's interval
2258 * length to call the signal handler.
2261 static unsigned __stdcall
ticktack(void *dummy
)
2263 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2264 mingw_raise(SIGALRM
);
2271 static int start_timer_thread(void)
2273 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2275 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2277 return errno
= ENOMEM
,
2278 error("cannot start timer thread");
2280 return errno
= ENOMEM
,
2281 error("cannot allocate resources for timer");
2285 static void stop_timer_thread(void)
2288 SetEvent(timer_event
); /* tell thread to terminate */
2290 int rc
= WaitForSingleObject(timer_thread
, 10000);
2291 if (rc
== WAIT_TIMEOUT
)
2292 error("timer thread did not terminate timely");
2293 else if (rc
!= WAIT_OBJECT_0
)
2294 error("waiting for timer thread failed: %lu",
2296 CloseHandle(timer_thread
);
2299 CloseHandle(timer_event
);
2301 timer_thread
= NULL
;
2304 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2306 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2309 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2311 static const struct timeval zero
;
2312 static int atexit_done
;
2315 return errno
= EINVAL
,
2316 error("setitimer param 3 != NULL not implemented");
2317 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2318 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2319 return errno
= EINVAL
,
2320 error("setitimer: it_interval must be zero or eq it_value");
2323 stop_timer_thread();
2325 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2326 is_timeval_eq(&in
->it_interval
, &zero
))
2329 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2330 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2332 atexit(stop_timer_thread
);
2335 return start_timer_thread();
2338 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2341 return errno
= EINVAL
,
2342 error("sigaction only implemented for SIGALRM");
2344 return errno
= EINVAL
,
2345 error("sigaction: param 3 != NULL not implemented");
2347 timer_fn
= in
->sa_handler
;
2352 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2364 sigint_fn
= handler
;
2368 return signal(sig
, handler
);
2375 int mingw_raise(int sig
)
2379 if (timer_fn
== SIG_DFL
) {
2380 if (isatty(STDERR_FILENO
))
2381 fputs("Alarm clock\n", stderr
);
2382 exit(128 + SIGALRM
);
2383 } else if (timer_fn
!= SIG_IGN
)
2388 if (sigint_fn
== SIG_DFL
)
2390 else if (sigint_fn
!= SIG_IGN
)
2394 #if defined(_MSC_VER)
2401 case SIGABRT_COMPAT
:
2403 * The <signal.h> header in the MS C Runtime defines 8 signals
2404 * as being supported on the platform. Anything else causes an
2405 * "Invalid signal or error" (which in DEBUG builds causes the
2406 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2407 * already know will fail.
2424 int link(const char *oldpath
, const char *newpath
)
2426 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2427 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2428 xutftowcs_path(wnewpath
, newpath
) < 0)
2431 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2432 errno
= err_win_to_posix(GetLastError());
2438 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2440 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2447 if (pid
> 0 && options
& WNOHANG
) {
2448 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2452 options
&= ~WNOHANG
;
2456 struct pinfo_t
**ppinfo
;
2457 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2463 GetExitCodeProcess(h
, (LPDWORD
)status
);
2465 EnterCriticalSection(&pinfo_cs
);
2469 struct pinfo_t
*info
= *ppinfo
;
2470 if (info
->pid
== pid
) {
2471 CloseHandle(info
->proc
);
2472 *ppinfo
= info
->next
;
2476 ppinfo
= &info
->next
;
2479 LeaveCriticalSection(&pinfo_cs
);
2490 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2492 int upos
= 0, wpos
= 0;
2493 const unsigned char *utf
= (const unsigned char*) utfs
;
2494 if (!utf
|| !wcs
|| wcslen
< 1) {
2498 /* reserve space for \0 */
2503 while (upos
< utflen
) {
2504 int c
= utf
[upos
++] & 0xff;
2505 if (utflen
== INT_MAX
&& c
== 0)
2508 if (wpos
>= wcslen
) {
2517 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2518 (utf
[upos
] & 0xc0) == 0x80) {
2520 c
= ((c
& 0x1f) << 6);
2521 c
|= (utf
[upos
++] & 0x3f);
2523 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2524 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2525 (utf
[upos
] & 0xc0) == 0x80 &&
2526 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2528 c
= ((c
& 0x0f) << 12);
2529 c
|= ((utf
[upos
++] & 0x3f) << 6);
2530 c
|= (utf
[upos
++] & 0x3f);
2532 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2533 wpos
+ 1 < wcslen
&&
2534 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2535 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2536 (utf
[upos
] & 0xc0) == 0x80 &&
2537 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2538 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2539 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2540 c
= ((c
& 0x07) << 18);
2541 c
|= ((utf
[upos
++] & 0x3f) << 12);
2542 c
|= ((utf
[upos
++] & 0x3f) << 6);
2543 c
|= (utf
[upos
++] & 0x3f);
2545 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2546 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2547 } else if (c
>= 0xa0) {
2548 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2551 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2552 static const char *hex
= "0123456789abcdef";
2553 wcs
[wpos
++] = hex
[c
>> 4];
2555 wcs
[wpos
++] = hex
[c
& 0x0f];
2562 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2564 if (!wcs
|| !utf
|| utflen
< 1) {
2568 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2575 static void setup_windows_environment(void)
2577 char *tmp
= getenv("TMPDIR");
2579 /* on Windows it is TMP and TEMP */
2581 if (!(tmp
= getenv("TMP")))
2582 tmp
= getenv("TEMP");
2584 setenv("TMPDIR", tmp
, 1);
2585 tmp
= getenv("TMPDIR");
2591 * Convert all dir separators to forward slashes,
2592 * to help shell commands called from the Git
2593 * executable (by not mistaking the dir separators
2594 * for escape characters).
2596 convert_slashes(tmp
);
2599 /* simulate TERM to enable auto-color (see color.c) */
2600 if (!getenv("TERM"))
2601 setenv("TERM", "cygwin", 1);
2603 /* calculate HOME if not set */
2604 if (!getenv("HOME")) {
2606 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2607 * location, thus also check if the path exists (i.e. is not
2610 if ((tmp
= getenv("HOMEDRIVE"))) {
2611 struct strbuf buf
= STRBUF_INIT
;
2612 strbuf_addstr(&buf
, tmp
);
2613 if ((tmp
= getenv("HOMEPATH"))) {
2614 strbuf_addstr(&buf
, tmp
);
2615 if (is_directory(buf
.buf
))
2616 setenv("HOME", buf
.buf
, 1);
2618 tmp
= NULL
; /* use $USERPROFILE */
2620 strbuf_release(&buf
);
2622 /* use $USERPROFILE if the home share is not available */
2623 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2624 setenv("HOME", tmp
, 1);
2628 static PSID
get_current_user_sid(void)
2634 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2637 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2638 TOKEN_USER
*info
= xmalloc((size_t)len
);
2639 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2640 len
= GetLengthSid(info
->User
.Sid
);
2641 result
= xmalloc(len
);
2642 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2643 error(_("failed to copy SID (%ld)"),
2645 FREE_AND_NULL(result
);
2648 FREE_AND_NULL(info
);
2655 int is_path_owned_by_current_sid(const char *path
)
2657 WCHAR wpath
[MAX_PATH
];
2659 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2662 static wchar_t home
[MAX_PATH
];
2666 if (xutftowcs_path(wpath
, path
) < 0)
2670 * On Windows, the home directory is owned by the administrator, but for
2671 * all practical purposes, it belongs to the user. Do pretend that it is
2672 * owned by the user.
2675 DWORD size
= ARRAY_SIZE(home
);
2676 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2677 if (!len
|| len
> size
)
2678 wcscpy(home
, L
"::N/A::");
2680 if (!wcsicmp(wpath
, home
))
2683 /* Get the owner SID */
2684 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2685 OWNER_SECURITY_INFORMATION
|
2686 DACL_SECURITY_INFORMATION
,
2687 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2689 if (err
!= ERROR_SUCCESS
)
2690 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2691 else if (sid
&& IsValidSid(sid
)) {
2692 /* Now, verify that the SID matches the current user's */
2693 static PSID current_user_sid
;
2695 if (!current_user_sid
)
2696 current_user_sid
= get_current_user_sid();
2698 if (current_user_sid
&&
2699 IsValidSid(current_user_sid
) &&
2700 EqualSid(sid
, current_user_sid
))
2705 * We can release the security descriptor struct only now because `sid`
2706 * actually points into this struct.
2709 LocalFree(descriptor
);
2714 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2716 const char *p
= path
;
2717 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2722 skip_dos_drive_prefix((char **)&path
);
2729 case '/': case '\\':
2730 /* cannot end in ` ` or `.`, except for `.` and `..` */
2731 if (preceding_space_or_period
&&
2732 (i
!= periods
|| periods
> 2))
2737 i
= periods
= preceding_space_or_period
= 0;
2741 case 'a': case 'A': /* AUX */
2742 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2743 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2744 not_a_reserved_name
:
2750 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2751 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2752 goto not_a_reserved_name
;
2754 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2756 if (c
< '1' || c
> '9')
2757 goto not_a_reserved_name
;
2758 } else if (c
== 'n' || c
== 'N') { /* CON */
2760 if ((c
== 'i' || c
== 'I') &&
2761 ((c
= path
[i
+ 2]) == 'n' ||
2764 i
+= 3; /* CONIN$ */
2765 else if ((c
== 'o' || c
== 'O') &&
2766 ((c
= path
[i
+ 2]) == 'u' ||
2768 ((c
= path
[i
+ 3]) == 't' ||
2771 i
+= 4; /* CONOUT$ */
2773 goto not_a_reserved_name
;
2775 case 'l': case 'L': /* LPT<N> */
2776 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2777 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2778 !isdigit(path
[++i
]))
2779 goto not_a_reserved_name
;
2781 case 'n': case 'N': /* NUL */
2782 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2783 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2784 (allow_literal_nul
&&
2785 !path
[i
+ 1] && p
== path
))
2786 goto not_a_reserved_name
;
2788 case 'p': case 'P': /* PRN */
2789 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2790 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2791 goto not_a_reserved_name
;
2798 * So far, this looks like a reserved name. Let's see
2799 * whether it actually is one: trailing spaces, a file
2800 * extension, or an NTFS Alternate Data Stream do not
2801 * matter, the name is still reserved if any of those
2802 * follow immediately after the actual name.
2805 if (path
[i
] == ' ') {
2806 preceding_space_or_period
= 1;
2807 while (path
[++i
] == ' ')
2808 ; /* skip all spaces */
2812 if (c
&& c
!= '.' && c
!= ':' && c
!= '/' && c
!= '\\')
2813 goto not_a_reserved_name
;
2815 /* contains reserved name */
2821 preceding_space_or_period
= 1;
2824 case ':': /* DOS drive prefix was already skipped */
2825 case '<': case '>': case '"': case '|': case '?': case '*':
2826 /* illegal character */
2829 if (c
> '\0' && c
< '\x20')
2830 /* illegal character */
2833 preceding_space_or_period
= 0;
2838 #if !defined(_MSC_VER)
2840 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2841 * mingw startup code, see init.c in mingw runtime).
2846 static NORETURN
void die_startup(void)
2848 fputs("fatal: not enough memory for initialization", stderr
);
2852 static void *malloc_startup(size_t size
)
2854 void *result
= malloc(size
);
2860 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2862 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2863 return memcpy(malloc_startup(len
), buffer
, len
);
2866 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2867 DWORD desired_access
, DWORD flags
)
2869 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2870 wchar_t buf
[MAX_PATH
];
2871 DWORD max
= ARRAY_SIZE(buf
);
2873 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2875 if (!ret
|| ret
>= max
)
2878 /* make sure this does not leak into child processes */
2879 SetEnvironmentVariableW(key
, NULL
);
2880 if (!wcscmp(buf
, L
"off")) {
2882 handle
= GetStdHandle(std_id
);
2883 if (handle
!= INVALID_HANDLE_VALUE
)
2884 CloseHandle(handle
);
2887 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2888 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2889 if (handle
== INVALID_HANDLE_VALUE
) {
2891 handle
= GetStdHandle(std_id
);
2892 if (handle
!= INVALID_HANDLE_VALUE
)
2893 CloseHandle(handle
);
2895 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2896 SetStdHandle(std_id
, handle
);
2898 /* do *not* close the new_fd: that would close stdout */
2902 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2904 if (handle
!= INVALID_HANDLE_VALUE
) {
2905 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2906 SetStdHandle(std_id
, handle
);
2912 static void maybe_redirect_std_handles(void)
2914 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2915 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2916 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2917 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2918 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2919 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2929 * We implement wmain() and compile with -municode, which would
2930 * normally ignore main(), but we call the latter from the former
2931 * so that we can handle non-ASCII command-line parameters
2934 * To be more compatible with the core git code, we convert
2935 * argv into UTF8 and pass them directly to main().
2937 int wmain(int argc
, const wchar_t **wargv
)
2939 int i
, maxlen
, exit_status
;
2940 char *buffer
, **save
;
2943 trace2_initialize_clock();
2947 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
2950 #ifdef USE_MSVC_CRTDBG
2951 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
2955 maybe_redirect_std_handles();
2957 /* determine size of argv and environ conversion buffer */
2958 maxlen
= wcslen(wargv
[0]);
2959 for (i
= 1; i
< argc
; i
++)
2960 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2962 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2963 maxlen
= 3 * maxlen
+ 1;
2964 buffer
= malloc_startup(maxlen
);
2967 * Create a UTF-8 version of w_argv. Also create a "save" copy
2968 * to remember all the string pointers because parse_options()
2969 * will remove claimed items from the argv that we pass down.
2971 ALLOC_ARRAY(argv
, argc
+ 1);
2972 ALLOC_ARRAY(save
, argc
+ 1);
2973 for (i
= 0; i
< argc
; i
++)
2974 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2975 argv
[i
] = save
[i
] = NULL
;
2978 /* fix Windows specific environment settings */
2979 setup_windows_environment();
2981 unset_environment_variables
= xstrdup("PERL5LIB");
2983 /* initialize critical section for waitpid pinfo_t list */
2984 InitializeCriticalSection(&pinfo_cs
);
2986 /* set up default file mode and file modes for stdin/out/err */
2988 _setmode(_fileno(stdin
), _O_BINARY
);
2989 _setmode(_fileno(stdout
), _O_BINARY
);
2990 _setmode(_fileno(stderr
), _O_BINARY
);
2992 /* initialize Unicode console */
2995 /* invoke the real main() using our utf8 version of argv. */
2996 exit_status
= main(argc
, argv
);
2998 for (i
= 0; i
< argc
; i
++)
3006 int uname(struct utsname
*buf
)
3008 unsigned v
= (unsigned)GetVersion();
3009 memset(buf
, 0, sizeof(*buf
));
3010 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3011 xsnprintf(buf
->release
, sizeof(buf
->release
),
3012 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3013 /* assuming NT variants only.. */
3014 xsnprintf(buf
->version
, sizeof(buf
->version
),
3015 "%u", (v
>> 16) & 0x7fff);