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
];
345 if (xutftowcs_path(wpathname
, pathname
) < 0)
348 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
349 if (!is_file_in_use_error(GetLastError()))
350 errno
= err_win_to_posix(GetLastError());
353 if (!is_dir_empty(wpathname
)) {
358 * We assume that some other process had the source or
359 * destination file open at the wrong moment and retry.
360 * In order to give the other process a higher chance to
361 * complete its operation, we give up our time slice now.
362 * If we have to retry again, we do sleep a bit.
367 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
368 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
369 "Should I try again?", pathname
))
370 ret
= _wrmdir(wpathname
);
372 invalidate_lstat_cache();
376 static inline int needs_hiding(const char *path
)
378 const char *basename
;
380 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
383 /* We cannot use basename(), as it would remove trailing slashes */
384 win32_skip_dos_drive_prefix((char **)&path
);
388 for (basename
= path
; *path
; path
++)
389 if (is_dir_sep(*path
)) {
392 } while (is_dir_sep(*path
));
393 /* ignore trailing slashes */
400 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
401 return *basename
== '.';
403 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
404 return !strncasecmp(".git", basename
, 4) &&
405 (!basename
[4] || is_dir_sep(basename
[4]));
408 static int set_hidden_flag(const wchar_t *path
, int set
)
410 DWORD original
= GetFileAttributesW(path
), modified
;
412 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
414 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
415 if (original
== modified
|| SetFileAttributesW(path
, modified
))
417 errno
= err_win_to_posix(GetLastError());
421 int mingw_mkdir(const char *path
, int mode
)
424 wchar_t wpath
[MAX_PATH
];
426 if (!is_valid_win32_path(path
, 0)) {
431 if (xutftowcs_path(wpath
, path
) < 0)
433 ret
= _wmkdir(wpath
);
434 if (!ret
&& needs_hiding(path
))
435 return set_hidden_flag(wpath
, 1);
440 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
441 * is documented in [1] as opening a writable file handle in append mode.
442 * (It is believed that) this is atomic since it is maintained by the
443 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
445 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
447 * This trick does not appear to work for named pipes. Instead it creates
448 * a named pipe client handle that cannot be written to. Callers should
449 * just use the regular _wopen() for them. (And since client handle gets
450 * bound to a unique server handle, it isn't really an issue.)
452 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
456 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
458 /* only these flags are supported */
459 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
460 return errno
= ENOSYS
, -1;
463 * FILE_SHARE_WRITE is required to permit child processes
464 * to append to the file.
466 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
467 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
468 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
469 if (handle
== INVALID_HANDLE_VALUE
) {
470 DWORD err
= GetLastError();
473 * Some network storage solutions (e.g. Isilon) might return
474 * ERROR_INVALID_PARAMETER instead of expected error
475 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
476 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
478 if (err
== ERROR_INVALID_PARAMETER
)
479 err
= ERROR_PATH_NOT_FOUND
;
481 errno
= err_win_to_posix(err
);
486 * No O_APPEND here, because the CRT uses it only to reset the
487 * file pointer to EOF before each write(); but that is not
488 * necessary (and may lead to races) for a file created with
491 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
498 * Does the pathname map to the local named pipe filesystem?
499 * That is, does it have a "//./pipe/" prefix?
501 static int is_local_named_pipe_path(const char *filename
)
503 return (is_dir_sep(filename
[0]) &&
504 is_dir_sep(filename
[1]) &&
505 filename
[2] == '.' &&
506 is_dir_sep(filename
[3]) &&
507 !strncasecmp(filename
+4, "pipe", 4) &&
508 is_dir_sep(filename
[8]) &&
512 int mingw_open (const char *filename
, int oflags
, ...)
514 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
517 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
518 wchar_t wfilename
[MAX_PATH
];
521 va_start(args
, oflags
);
522 mode
= va_arg(args
, int);
525 if (!is_valid_win32_path(filename
, !create
)) {
526 errno
= create
? EINVAL
: ENOENT
;
530 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
531 open_fn
= mingw_open_append
;
535 if (filename
&& !strcmp(filename
, "/dev/null"))
536 wcscpy(wfilename
, L
"nul");
537 else if (xutftowcs_path(wfilename
, filename
) < 0)
540 fd
= open_fn(wfilename
, oflags
, mode
);
542 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
543 DWORD attrs
= GetFileAttributesW(wfilename
);
544 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
547 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
549 * Internally, _wopen() uses the CreateFile() API which errors
550 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
551 * specified and an already existing file's attributes do not
552 * match *exactly*. As there is no mode or flag we can set that
553 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
554 * again *without* the O_CREAT flag (that corresponds to the
555 * CREATE_ALWAYS flag of CreateFile()).
557 if (fd
< 0 && errno
== EACCES
)
558 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
559 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
560 warning("could not mark '%s' as hidden.", filename
);
565 static BOOL WINAPI
ctrl_ignore(DWORD type
)
571 int mingw_fgetc(FILE *stream
)
574 if (!isatty(_fileno(stream
)))
575 return fgetc(stream
);
577 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
580 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
583 /* Ctrl+C was pressed, simulate SIGINT and retry */
586 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
591 FILE *mingw_fopen (const char *filename
, const char *otype
)
593 int hide
= needs_hiding(filename
);
595 wchar_t wfilename
[MAX_PATH
], wotype
[4];
596 if (filename
&& !strcmp(filename
, "/dev/null"))
597 wcscpy(wfilename
, L
"nul");
598 else if (!is_valid_win32_path(filename
, 1)) {
599 int create
= otype
&& strchr(otype
, 'w');
600 errno
= create
? EINVAL
: ENOENT
;
602 } else if (xutftowcs_path(wfilename
, filename
) < 0)
605 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
608 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
609 error("could not unhide %s", filename
);
612 file
= _wfopen(wfilename
, wotype
);
613 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
615 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
616 warning("could not mark '%s' as hidden.", filename
);
620 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
622 int hide
= needs_hiding(filename
);
624 wchar_t wfilename
[MAX_PATH
], wotype
[4];
625 if (filename
&& !strcmp(filename
, "/dev/null"))
626 wcscpy(wfilename
, L
"nul");
627 else if (!is_valid_win32_path(filename
, 1)) {
628 int create
= otype
&& strchr(otype
, 'w');
629 errno
= create
? EINVAL
: ENOENT
;
631 } else if (xutftowcs_path(wfilename
, filename
) < 0)
634 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
637 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
638 error("could not unhide %s", filename
);
641 file
= _wfreopen(wfilename
, wotype
, stream
);
642 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
643 warning("could not mark '%s' as hidden.", filename
);
648 int mingw_fflush(FILE *stream
)
650 int ret
= fflush(stream
);
653 * write() is used behind the scenes of stdio output functions.
654 * Since git code does not check for errors after each stdio write
655 * operation, it can happen that write() is called by a later
656 * stdio function even if an earlier write() call failed. In the
657 * case of a pipe whose readable end was closed, only the first
658 * call to write() reports EPIPE on Windows. Subsequent write()
659 * calls report EINVAL. It is impossible to notice whether this
660 * fflush invocation triggered such a case, therefore, we have to
661 * catch all EINVAL errors whole-sale.
663 if (ret
&& errno
== EINVAL
)
670 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
672 ssize_t result
= write(fd
, buf
, len
);
674 if (result
< 0 && errno
== EINVAL
&& buf
) {
675 /* check if fd is a pipe */
676 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
677 if (GetFileType(h
) == FILE_TYPE_PIPE
)
686 int mingw_access(const char *filename
, int mode
)
688 wchar_t wfilename
[MAX_PATH
];
689 if (xutftowcs_path(wfilename
, filename
) < 0)
691 /* X_OK is not supported by the MSVCRT version */
692 return _waccess(wfilename
, mode
& ~X_OK
);
695 int mingw_chdir(const char *dirname
)
697 wchar_t wdirname
[MAX_PATH
];
698 if (xutftowcs_path(wdirname
, dirname
) < 0)
700 return _wchdir(wdirname
);
703 int mingw_chmod(const char *filename
, int mode
)
705 wchar_t wfilename
[MAX_PATH
];
706 if (xutftowcs_path(wfilename
, filename
) < 0)
708 return _wchmod(wfilename
, mode
);
712 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
713 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
715 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
717 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
718 /* Windows to Unix Epoch conversion */
719 return winTime
- 116444736000000000LL;
722 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
724 long long hnsec
= filetime_to_hnsec(ft
);
725 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
726 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
730 * Verifies that safe_create_leading_directories() would succeed.
732 static int has_valid_directory_prefix(wchar_t *wfilename
)
734 int n
= wcslen(wfilename
);
737 wchar_t c
= wfilename
[--n
];
743 wfilename
[n
] = L
'\0';
744 attributes
= GetFileAttributesW(wfilename
);
746 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
747 attributes
== FILE_ATTRIBUTE_DEVICE
)
749 if (attributes
== INVALID_FILE_ATTRIBUTES
)
750 switch (GetLastError()) {
751 case ERROR_PATH_NOT_FOUND
:
753 case ERROR_FILE_NOT_FOUND
:
754 /* This implies parent directory exists. */
762 /* We keep the do_lstat code in a separate function to avoid recursion.
763 * When a path ends with a slash, the stat will fail with ENOENT. In
764 * this case, we strip the trailing slashes and stat again.
766 * If follow is true then act like stat() and report on the link
767 * target. Otherwise report on the link itself.
769 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
771 WIN32_FILE_ATTRIBUTE_DATA fdata
;
772 wchar_t wfilename
[MAX_PATH
];
773 if (xutftowcs_path(wfilename
, file_name
) < 0)
776 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
781 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
782 buf
->st_size
= fdata
.nFileSizeLow
|
783 (((off_t
)fdata
.nFileSizeHigh
)<<32);
784 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
785 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
786 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
787 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
788 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
789 WIN32_FIND_DATAW findbuf
;
790 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
791 if (handle
!= INVALID_HANDLE_VALUE
) {
792 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
793 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
795 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
796 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
798 buf
->st_mode
= S_IFLNK
;
800 buf
->st_mode
|= S_IREAD
;
801 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
802 buf
->st_mode
|= S_IWRITE
;
809 switch (GetLastError()) {
810 case ERROR_ACCESS_DENIED
:
811 case ERROR_SHARING_VIOLATION
:
812 case ERROR_LOCK_VIOLATION
:
813 case ERROR_SHARING_BUFFER_EXCEEDED
:
816 case ERROR_BUFFER_OVERFLOW
:
817 errno
= ENAMETOOLONG
;
819 case ERROR_NOT_ENOUGH_MEMORY
:
822 case ERROR_PATH_NOT_FOUND
:
823 if (!has_valid_directory_prefix(wfilename
)) {
835 /* We provide our own lstat/fstat functions, since the provided
836 * lstat/fstat functions are so slow. These stat functions are
837 * tailored for Git's usage (read: fast), and are not meant to be
838 * complete. Note that Git stat()s are redirected to mingw_lstat()
839 * too, since Windows doesn't really handle symlinks that well.
841 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
844 char alt_name
[PATH_MAX
];
846 if (!do_lstat(follow
, file_name
, buf
))
849 /* if file_name ended in a '/', Windows returned ENOENT;
850 * try again without trailing slashes
855 namelen
= strlen(file_name
);
856 if (namelen
&& file_name
[namelen
-1] != '/')
858 while (namelen
&& file_name
[namelen
-1] == '/')
860 if (!namelen
|| namelen
>= PATH_MAX
)
863 memcpy(alt_name
, file_name
, namelen
);
864 alt_name
[namelen
] = 0;
865 return do_lstat(follow
, alt_name
, buf
);
868 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
870 BY_HANDLE_FILE_INFORMATION fdata
;
872 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
873 errno
= err_win_to_posix(GetLastError());
881 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
882 buf
->st_size
= fdata
.nFileSizeLow
|
883 (((off_t
)fdata
.nFileSizeHigh
)<<32);
884 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
885 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
886 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
887 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
891 int mingw_lstat(const char *file_name
, struct stat
*buf
)
893 return do_stat_internal(0, file_name
, buf
);
895 int mingw_stat(const char *file_name
, struct stat
*buf
)
897 return do_stat_internal(1, file_name
, buf
);
900 int mingw_fstat(int fd
, struct stat
*buf
)
902 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
903 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
907 return get_file_info_by_handle(fh
, buf
);
911 /* initialize stat fields */
912 memset(buf
, 0, sizeof(*buf
));
915 if (type
== FILE_TYPE_CHAR
) {
916 buf
->st_mode
= _S_IFCHR
;
918 buf
->st_mode
= _S_IFIFO
;
919 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
920 buf
->st_size
= avail
;
930 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
932 long long winTime
= t
* 10000000LL + 116444736000000000LL;
933 ft
->dwLowDateTime
= winTime
;
934 ft
->dwHighDateTime
= winTime
>> 32;
937 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
942 wchar_t wfilename
[MAX_PATH
];
943 if (xutftowcs_path(wfilename
, file_name
) < 0)
946 /* must have write permission */
947 attrs
= GetFileAttributesW(wfilename
);
948 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
949 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
950 /* ignore errors here; open() will report them */
951 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
954 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
960 time_t_to_filetime(times
->modtime
, &mft
);
961 time_t_to_filetime(times
->actime
, &aft
);
963 GetSystemTimeAsFileTime(&mft
);
966 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
974 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
975 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
976 /* ignore errors again */
977 SetFileAttributesW(wfilename
, attrs
);
983 size_t mingw_strftime(char *s
, size_t max
,
984 const char *format
, const struct tm
*tm
)
986 /* a pointer to the original strftime in case we can't find the UCRT version */
987 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
989 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, strftime
, char *, size_t,
990 const char *, const struct tm
*);
992 if (INIT_PROC_ADDR(strftime
))
993 ret
= strftime(s
, max
, format
, tm
);
995 ret
= fallback(s
, max
, format
, tm
);
997 if (!ret
&& errno
== EINVAL
)
998 die("invalid strftime format: '%s'", format
);
1002 unsigned int sleep (unsigned int seconds
)
1004 Sleep(seconds
*1000);
1008 char *mingw_mktemp(char *template)
1010 wchar_t wtemplate
[MAX_PATH
];
1011 if (xutftowcs_path(wtemplate
, template) < 0)
1013 if (!_wmktemp(wtemplate
))
1015 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1020 int mkstemp(char *template)
1022 char *filename
= mktemp(template);
1023 if (filename
== NULL
)
1025 return open(filename
, O_RDWR
| O_CREAT
, 0600);
1028 int gettimeofday(struct timeval
*tv
, void *tz
)
1033 GetSystemTimeAsFileTime(&ft
);
1034 hnsec
= filetime_to_hnsec(&ft
);
1035 tv
->tv_sec
= hnsec
/ 10000000;
1036 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1040 int pipe(int filedes
[2])
1044 /* this creates non-inheritable handles */
1045 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1046 errno
= err_win_to_posix(GetLastError());
1049 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1050 if (filedes
[0] < 0) {
1055 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1056 if (filedes
[1] < 0) {
1065 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1067 if (gmtime_s(result
, timep
) == 0)
1072 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1074 if (localtime_s(result
, timep
) == 0)
1080 char *mingw_getcwd(char *pointer
, int len
)
1082 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1083 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1085 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1086 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1089 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1090 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1091 HANDLE hnd
= CreateFileW(cwd
, 0,
1092 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1093 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1094 if (hnd
== INVALID_HANDLE_VALUE
)
1096 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1098 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1100 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1104 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1106 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1108 convert_slashes(pointer
);
1113 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1114 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1116 static const char *quote_arg_msvc(const char *arg
)
1118 /* count chars to quote */
1120 int force_quotes
= 0;
1122 const char *p
= arg
;
1123 if (!*p
) force_quotes
= 1;
1125 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1129 else if (*p
== '\\') {
1131 while (*p
== '\\') {
1136 if (*p
== '"' || !*p
)
1143 if (!force_quotes
&& n
== 0)
1146 /* insert \ where necessary */
1147 d
= q
= xmalloc(st_add3(len
, n
, 3));
1152 else if (*arg
== '\\') {
1154 while (*arg
== '\\') {
1158 if (*arg
== '"' || !*arg
) {
1161 /* don't escape the surrounding end quote */
1176 static const char *quote_arg_msys2(const char *arg
)
1178 struct strbuf buf
= STRBUF_INIT
;
1179 const char *p2
= arg
, *p
;
1181 for (p
= arg
; *p
; p
++) {
1182 int ws
= isspace(*p
);
1183 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1184 *p
!= '?' && *p
!= '*' && *p
!= '~')
1187 strbuf_addch(&buf
, '"');
1189 strbuf_add(&buf
, p2
, p
- p2
);
1190 if (*p
== '\\' || *p
== '"')
1191 strbuf_addch(&buf
, '\\');
1196 strbuf_addch(&buf
, '"');
1200 strbuf_add(&buf
, p2
, p
- p2
);
1202 strbuf_addch(&buf
, '"');
1203 return strbuf_detach(&buf
, 0);
1206 static const char *parse_interpreter(const char *cmd
)
1208 static char buf
[100];
1212 /* don't even try a .exe */
1214 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1217 fd
= open(cmd
, O_RDONLY
);
1220 n
= read(fd
, buf
, sizeof(buf
)-1);
1222 if (n
< 4) /* at least '#!/x' and not error */
1225 if (buf
[0] != '#' || buf
[1] != '!')
1228 p
= buf
+ strcspn(buf
, "\r\n");
1233 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1236 if ((opt
= strchr(p
+1, ' ')))
1242 * exe_only means that we only want to detect .exe files, but not scripts
1243 * (which do not have an extension)
1245 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1246 int isexe
, int exe_only
)
1248 char path
[MAX_PATH
];
1249 wchar_t wpath
[MAX_PATH
];
1250 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1252 if (xutftowcs_path(wpath
, path
) < 0)
1255 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1256 return xstrdup(path
);
1257 wpath
[wcslen(wpath
)-4] = '\0';
1258 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1259 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1260 path
[strlen(path
)-4] = '\0';
1261 return xstrdup(path
);
1268 * Determines the absolute path of cmd using the split path in path.
1269 * If cmd contains a slash or backslash, no lookup is performed.
1271 static char *path_lookup(const char *cmd
, int exe_only
)
1275 int len
= strlen(cmd
);
1276 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1278 if (strpbrk(cmd
, "/\\"))
1279 return xstrdup(cmd
);
1281 path
= mingw_getenv("PATH");
1286 const char *sep
= strchrnul(path
, ';');
1287 int dirlen
= sep
- path
;
1289 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1298 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1300 while (*s
&& *s
!= c
)
1305 /* Compare only keys */
1306 static int wenvcmp(const void *a
, const void *b
)
1308 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1309 size_t p_len
, q_len
;
1312 p_len
= wcschrnul(p
, L
'=') - p
;
1313 q_len
= wcschrnul(q
, L
'=') - q
;
1315 /* If the length differs, include the shorter key's NUL */
1318 else if (p_len
> q_len
)
1321 return _wcsnicmp(p
, q
, p_len
);
1325 * Build an environment block combining the inherited environment
1326 * merged with the given list of settings.
1328 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1329 * Values of the form "KEY" in deltaenv delete inherited values.
1331 * Multiple entries in deltaenv for the same key are explicitly allowed.
1333 * We return a contiguous block of UNICODE strings with a final trailing
1336 static wchar_t *make_environment_block(char **deltaenv
)
1338 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1339 size_t wlen
, s
, delta_size
, size
;
1341 wchar_t **array
= NULL
;
1342 size_t alloc
= 0, nr
= 0, i
;
1344 size
= 1; /* for extra NUL at the end */
1346 /* If there is no deltaenv to apply, simply return a copy. */
1347 if (!deltaenv
|| !*deltaenv
) {
1348 for (p
= wenv
; p
&& *p
; ) {
1349 size_t s
= wcslen(p
) + 1;
1354 ALLOC_ARRAY(result
, size
);
1355 COPY_ARRAY(result
, wenv
, size
);
1356 FreeEnvironmentStringsW(wenv
);
1361 * If there is a deltaenv, let's accumulate all keys into `array`,
1362 * sort them using the stable git_stable_qsort() and then copy,
1363 * skipping duplicate keys
1365 for (p
= wenv
; p
&& *p
; ) {
1366 ALLOC_GROW(array
, nr
+ 1, alloc
);
1373 /* (over-)assess size needed for wchar version of deltaenv */
1374 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1375 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1376 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1378 /* convert the deltaenv, appending to array */
1379 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1380 ALLOC_GROW(array
, nr
+ 1, alloc
);
1381 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1386 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1387 ALLOC_ARRAY(result
, size
+ delta_size
);
1389 for (p
= result
, i
= 0; i
< nr
; i
++) {
1390 /* Skip any duplicate keys; last one wins */
1391 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1394 /* Skip "to delete" entry */
1395 if (!wcschr(array
[i
], L
'='))
1398 size
= wcslen(array
[i
]) + 1;
1399 COPY_ARRAY(p
, array
[i
], size
);
1406 FreeEnvironmentStringsW(wenv
);
1410 static void do_unset_environment_variables(void)
1413 char *p
= unset_environment_variables
;
1420 char *comma
= strchr(p
, ',');
1432 struct pinfo_t
*next
;
1436 static struct pinfo_t
*pinfo
= NULL
;
1437 CRITICAL_SECTION pinfo_cs
;
1439 /* Used to match and chomp off path components */
1440 static inline int match_last_path_component(const char *path
, size_t *len
,
1441 const char *component
)
1443 size_t component_len
= strlen(component
);
1444 if (*len
< component_len
+ 1 ||
1445 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1446 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1448 *len
-= component_len
+ 1;
1449 /* chomp off repeated dir separators */
1450 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1455 static int is_msys2_sh(const char *cmd
)
1460 if (!strcmp(cmd
, "sh")) {
1461 static int ret
= -1;
1467 p
= path_lookup(cmd
, 0);
1471 size_t len
= strlen(p
);
1473 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1474 match_last_path_component(p
, &len
, "bin") &&
1475 match_last_path_component(p
, &len
, "usr");
1481 if (ends_with(cmd
, "\\sh.exe")) {
1485 sh
= path_lookup("sh", 0);
1487 return !fspathcmp(cmd
, sh
);
1493 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1495 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1497 static int restrict_handle_inheritance
= -1;
1499 PROCESS_INFORMATION pi
;
1500 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1501 HANDLE stdhandles
[3];
1502 DWORD stdhandles_count
= 0;
1505 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1506 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1509 const char *(*quote_arg
)(const char *arg
) =
1510 is_msys2_sh(cmd
? cmd
: *argv
) ?
1511 quote_arg_msys2
: quote_arg_msvc
;
1512 const char *strace_env
;
1514 /* Make sure to override previous errors, if any */
1517 if (restrict_handle_inheritance
< 0)
1518 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1520 * The following code to restrict which handles are inherited seems
1521 * to work properly only on Windows 7 and later, so let's disable it
1522 * on Windows Vista and 2008.
1524 if (restrict_handle_inheritance
< 0)
1525 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1527 do_unset_environment_variables();
1529 /* Determine whether or not we are associated to a console */
1530 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1531 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1532 FILE_ATTRIBUTE_NORMAL
, NULL
);
1533 if (cons
== INVALID_HANDLE_VALUE
) {
1534 /* There is no console associated with this process.
1535 * Since the child is a console process, Windows
1536 * would normally create a console window. But
1537 * since we'll be redirecting std streams, we do
1538 * not need the console.
1539 * It is necessary to use DETACHED_PROCESS
1540 * instead of CREATE_NO_WINDOW to make ssh
1541 * recognize that it has no console.
1543 flags
|= DETACHED_PROCESS
;
1545 /* There is already a console. If we specified
1546 * DETACHED_PROCESS here, too, Windows would
1547 * disassociate the child from the console.
1548 * The same is true for CREATE_NO_WINDOW.
1553 memset(&si
, 0, sizeof(si
));
1554 si
.StartupInfo
.cb
= sizeof(si
);
1555 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1556 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1557 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1559 /* The list of handles cannot contain duplicates */
1560 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1561 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1562 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1563 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1564 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1565 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1566 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1567 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1568 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1569 if (stdhandles_count
)
1570 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1572 if (*argv
&& !strcmp(cmd
, *argv
))
1574 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1576 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1579 /* concatenate argv, quoting args as we go */
1580 strbuf_init(&args
, 0);
1582 char *quoted
= (char *)quote_arg(cmd
);
1583 strbuf_addstr(&args
, quoted
);
1587 for (; *argv
; argv
++) {
1588 char *quoted
= (char *)quote_arg(*argv
);
1590 strbuf_addch(&args
, ' ');
1591 strbuf_addstr(&args
, quoted
);
1592 if (quoted
!= *argv
)
1596 strace_env
= getenv("GIT_STRACE_COMMANDS");
1598 char *p
= path_lookup("strace.exe", 1);
1600 return error("strace not found!");
1601 if (xutftowcs_path(wcmd
, p
) < 0) {
1606 if (!strcmp("1", strace_env
) ||
1607 !strcasecmp("yes", strace_env
) ||
1608 !strcasecmp("true", strace_env
))
1609 strbuf_insert(&args
, 0, "strace ", 7);
1611 const char *quoted
= quote_arg(strace_env
);
1612 struct strbuf buf
= STRBUF_INIT
;
1613 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1614 if (quoted
!= strace_env
)
1615 free((char *)quoted
);
1616 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1617 strbuf_release(&buf
);
1621 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1622 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1623 strbuf_release(&args
);
1625 wenvblk
= make_environment_block(deltaenv
);
1627 memset(&pi
, 0, sizeof(pi
));
1628 if (restrict_handle_inheritance
&& stdhandles_count
&&
1629 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1630 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1631 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1632 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1633 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1634 UpdateProcThreadAttribute(attr_list
, 0,
1635 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1637 stdhandles_count
* sizeof(HANDLE
),
1639 si
.lpAttributeList
= attr_list
;
1640 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1643 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1644 stdhandles_count
? TRUE
: FALSE
,
1645 flags
, wenvblk
, dir
? wdir
: NULL
,
1646 &si
.StartupInfo
, &pi
);
1649 * On Windows 2008 R2, it seems that specifying certain types of handles
1650 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1651 * error. Rather than playing finicky and fragile games, let's just try
1652 * to detect this situation and simply try again without restricting any
1653 * handle inheritance. This is still better than failing to create
1656 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1657 DWORD err
= GetLastError();
1658 struct strbuf buf
= STRBUF_INIT
;
1660 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1662 * On Windows 7 and earlier, handles on pipes and character
1663 * devices are inherited automatically, and cannot be
1664 * specified in the thread handle list. Rather than trying
1665 * to catch each and every corner case (and running the
1666 * chance of *still* forgetting a few), let's just fall
1667 * back to creating the process without trying to limit the
1668 * handle inheritance.
1670 !(err
== ERROR_INVALID_PARAMETER
&&
1671 GetVersion() >> 16 < 9200) &&
1672 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1676 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1678 for (i
= 0; i
< stdhandles_count
; i
++) {
1679 HANDLE h
= stdhandles
[i
];
1680 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1681 "handle info (%d) %lx\n", i
, h
,
1683 GetHandleInformation(h
, &fl
),
1686 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1687 "at\nhttps://github.com/git-for-windows/"
1688 "git/issues/new\n\n"
1689 "To suppress this warning, please set "
1690 "the environment variable\n\n"
1691 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1694 restrict_handle_inheritance
= 0;
1695 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1696 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1697 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1698 &si
.StartupInfo
, &pi
);
1700 errno
= err_win_to_posix(GetLastError());
1701 if (ret
&& buf
.len
) {
1702 warning("failed to restrict file handles (%ld)\n\n%s",
1705 strbuf_release(&buf
);
1707 errno
= err_win_to_posix(GetLastError());
1709 if (si
.lpAttributeList
)
1710 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1712 HeapFree(GetProcessHeap(), 0, attr_list
);
1720 CloseHandle(pi
.hThread
);
1723 * The process ID is the human-readable identifier of the process
1724 * that we want to present in log and error messages. The handle
1725 * is not useful for this purpose. But we cannot close it, either,
1726 * because it is not possible to turn a process ID into a process
1727 * handle after the process terminated.
1728 * Keep the handle in a list for waitpid.
1730 EnterCriticalSection(&pinfo_cs
);
1732 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1733 info
->pid
= pi
.dwProcessId
;
1734 info
->proc
= pi
.hProcess
;
1738 LeaveCriticalSection(&pinfo_cs
);
1740 return (pid_t
)pi
.dwProcessId
;
1743 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1745 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1748 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1750 int fhin
, int fhout
, int fherr
)
1753 char *prog
= path_lookup(cmd
, 0);
1760 const char *interpr
= parse_interpreter(prog
);
1763 const char *argv0
= argv
[0];
1764 char *iprog
= path_lookup(interpr
, 1);
1771 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1772 fhin
, fhout
, fherr
);
1778 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1779 fhin
, fhout
, fherr
);
1785 static int try_shell_exec(const char *cmd
, char *const *argv
)
1787 const char *interpr
= parse_interpreter(cmd
);
1793 prog
= path_lookup(interpr
, 1);
1801 while (argv
[argc
]) argc
++;
1802 ALLOC_ARRAY(argv2
, argc
+ 1);
1803 argv2
[0] = (char *)cmd
; /* full path to the script file */
1804 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1805 exec_id
= trace2_exec(prog
, argv2
);
1806 pid
= mingw_spawnv(prog
, argv2
, 1);
1809 if (waitpid(pid
, &status
, 0) < 0)
1811 trace2_exec_result(exec_id
, status
);
1814 trace2_exec_result(exec_id
, -1);
1815 pid
= 1; /* indicate that we tried but failed */
1822 int mingw_execv(const char *cmd
, char *const *argv
)
1824 /* check if git_command is a shell script */
1825 if (!try_shell_exec(cmd
, argv
)) {
1829 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1830 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1832 trace2_exec_result(exec_id
, -1);
1835 if (waitpid(pid
, &status
, 0) < 0)
1837 trace2_exec_result(exec_id
, status
);
1843 int mingw_execvp(const char *cmd
, char *const *argv
)
1845 char *prog
= path_lookup(cmd
, 0);
1848 mingw_execv(prog
, argv
);
1856 int mingw_kill(pid_t pid
, int sig
)
1858 if (pid
> 0 && sig
== SIGTERM
) {
1859 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1861 if (TerminateProcess(h
, -1)) {
1866 errno
= err_win_to_posix(GetLastError());
1869 } else if (pid
> 0 && sig
== 0) {
1870 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1882 * UTF-8 versions of getenv(), putenv() and unsetenv().
1883 * Internally, they use the CRT's stock UNICODE routines
1884 * to avoid data loss.
1886 char *mingw_getenv(const char *name
)
1888 #define GETENV_MAX_RETAIN 64
1889 static char *values
[GETENV_MAX_RETAIN
];
1890 static int value_counter
;
1891 int len_key
, len_value
;
1894 wchar_t w_value
[32768];
1896 if (!name
|| !*name
)
1899 len_key
= strlen(name
) + 1;
1900 /* We cannot use xcalloc() here because that uses getenv() itself */
1901 w_key
= calloc(len_key
, sizeof(wchar_t));
1903 die("Out of memory, (tried to allocate %u wchar_t's)", len_key
);
1904 xutftowcs(w_key
, name
, len_key
);
1905 /* GetEnvironmentVariableW() only sets the last error upon failure */
1906 SetLastError(ERROR_SUCCESS
);
1907 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
1908 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
1914 len_value
= len_value
* 3 + 1;
1915 /* We cannot use xcalloc() here because that uses getenv() itself */
1916 value
= calloc(len_value
, sizeof(char));
1918 die("Out of memory, (tried to allocate %u bytes)", len_value
);
1919 xwcstoutf(value
, w_value
, len_value
);
1922 * We return `value` which is an allocated value and the caller is NOT
1923 * expecting to have to free it, so we keep a round-robin array,
1924 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1926 free(values
[value_counter
]);
1927 values
[value_counter
++] = value
;
1928 if (value_counter
>= ARRAY_SIZE(values
))
1934 int mingw_putenv(const char *namevalue
)
1937 wchar_t *wide
, *equal
;
1940 if (!namevalue
|| !*namevalue
)
1943 size
= strlen(namevalue
) * 2 + 1;
1944 wide
= calloc(size
, sizeof(wchar_t));
1946 die("Out of memory, (tried to allocate %u wchar_t's)", size
);
1947 xutftowcs(wide
, namevalue
, size
);
1948 equal
= wcschr(wide
, L
'=');
1950 result
= SetEnvironmentVariableW(wide
, NULL
);
1953 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
1958 errno
= err_win_to_posix(GetLastError());
1960 return result
? 0 : -1;
1963 static void ensure_socket_initialization(void)
1966 static int initialized
= 0;
1971 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1972 die("unable to initialize winsock subsystem, error %d",
1975 atexit((void(*)(void)) WSACleanup
);
1980 int mingw_gethostname(char *name
, int namelen
)
1982 ensure_socket_initialization();
1983 return gethostname(name
, namelen
);
1986 #undef gethostbyname
1987 struct hostent
*mingw_gethostbyname(const char *host
)
1989 ensure_socket_initialization();
1990 return gethostbyname(host
);
1994 int mingw_getaddrinfo(const char *node
, const char *service
,
1995 const struct addrinfo
*hints
, struct addrinfo
**res
)
1997 ensure_socket_initialization();
1998 return getaddrinfo(node
, service
, hints
, res
);
2001 int mingw_socket(int domain
, int type
, int protocol
)
2006 ensure_socket_initialization();
2007 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2008 if (s
== INVALID_SOCKET
) {
2010 * WSAGetLastError() values are regular BSD error codes
2011 * biased by WSABASEERR.
2012 * However, strerror() does not know about networking
2013 * specific errors, which are values beginning at 38 or so.
2014 * Therefore, we choose to leave the biased error code
2015 * in errno so that _if_ someone looks up the code somewhere,
2016 * then it is at least the number that are usually listed.
2018 errno
= WSAGetLastError();
2021 /* convert into a file descriptor */
2022 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2024 return error("unable to make a socket file descriptor: %s",
2031 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2033 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2034 return connect(s
, sa
, sz
);
2038 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2040 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2041 return bind(s
, sa
, sz
);
2045 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2047 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2048 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2052 int mingw_shutdown(int sockfd
, int how
)
2054 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2055 return shutdown(s
, how
);
2059 int mingw_listen(int sockfd
, int backlog
)
2061 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2062 return listen(s
, backlog
);
2066 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2070 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2071 SOCKET s2
= accept(s1
, sa
, sz
);
2073 /* convert into a file descriptor */
2074 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2077 return error("unable to make a socket file descriptor: %s",
2084 int mingw_rename(const char *pold
, const char *pnew
)
2088 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2089 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
2093 * Try native rename() first to get errno right.
2094 * It is based on MoveFile(), which cannot overwrite existing files.
2096 if (!_wrename(wpold
, wpnew
))
2098 if (errno
!= EEXIST
)
2101 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2103 /* TODO: translate more errors */
2104 gle
= GetLastError();
2105 if (gle
== ERROR_ACCESS_DENIED
&&
2106 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2107 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2108 DWORD attrsold
= GetFileAttributesW(wpold
);
2109 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2110 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2112 else if (!_wrmdir(wpnew
))
2116 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2117 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2118 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2120 gle
= GetLastError();
2121 /* revert file attributes on failure */
2122 SetFileAttributesW(wpnew
, attrs
);
2125 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2127 * We assume that some other process had the source or
2128 * destination file open at the wrong moment and retry.
2129 * In order to give the other process a higher chance to
2130 * complete its operation, we give up our time slice now.
2131 * If we have to retry again, we do sleep a bit.
2133 Sleep(delay
[tries
]);
2137 if (gle
== ERROR_ACCESS_DENIED
&&
2138 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2139 "Should I try again?", pold
, pnew
))
2147 * Note that this doesn't return the actual pagesize, but
2148 * the allocation granularity. If future Windows specific git code
2149 * needs the real getpagesize function, we need to find another solution.
2151 int mingw_getpagesize(void)
2155 return si
.dwAllocationGranularity
;
2158 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2159 enum EXTENDED_NAME_FORMAT
{
2161 NameUserPrincipal
= 8
2164 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2166 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, GetUserNameExW
,
2167 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2168 static wchar_t wbuffer
[1024];
2171 if (!INIT_PROC_ADDR(GetUserNameExW
))
2174 len
= ARRAY_SIZE(wbuffer
);
2175 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2176 char *converted
= xmalloc((len
*= 3));
2177 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2185 char *mingw_query_user_email(void)
2187 return get_extended_user_info(NameUserPrincipal
);
2190 struct passwd
*getpwuid(int uid
)
2192 static unsigned initialized
;
2193 static char user_name
[100];
2194 static struct passwd
*p
;
2201 len
= ARRAY_SIZE(buf
);
2202 if (!GetUserNameW(buf
, &len
)) {
2207 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2212 p
= xmalloc(sizeof(*p
));
2213 p
->pw_name
= user_name
;
2214 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2216 p
->pw_gecos
= "unknown";
2223 static HANDLE timer_event
;
2224 static HANDLE timer_thread
;
2225 static int timer_interval
;
2226 static int one_shot
;
2227 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2229 /* The timer works like this:
2230 * The thread, ticktack(), is a trivial routine that most of the time
2231 * only waits to receive the signal to terminate. The main thread tells
2232 * the thread to terminate by setting the timer_event to the signalled
2234 * But ticktack() interrupts the wait state after the timer's interval
2235 * length to call the signal handler.
2238 static unsigned __stdcall
ticktack(void *dummy
)
2240 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2241 mingw_raise(SIGALRM
);
2248 static int start_timer_thread(void)
2250 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2252 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2254 return errno
= ENOMEM
,
2255 error("cannot start timer thread");
2257 return errno
= ENOMEM
,
2258 error("cannot allocate resources for timer");
2262 static void stop_timer_thread(void)
2265 SetEvent(timer_event
); /* tell thread to terminate */
2267 int rc
= WaitForSingleObject(timer_thread
, 10000);
2268 if (rc
== WAIT_TIMEOUT
)
2269 error("timer thread did not terminate timely");
2270 else if (rc
!= WAIT_OBJECT_0
)
2271 error("waiting for timer thread failed: %lu",
2273 CloseHandle(timer_thread
);
2276 CloseHandle(timer_event
);
2278 timer_thread
= NULL
;
2281 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2283 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2286 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
2288 static const struct timeval zero
;
2289 static int atexit_done
;
2292 return errno
= EINVAL
,
2293 error("setitimer param 3 != NULL not implemented");
2294 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2295 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2296 return errno
= EINVAL
,
2297 error("setitimer: it_interval must be zero or eq it_value");
2300 stop_timer_thread();
2302 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2303 is_timeval_eq(&in
->it_interval
, &zero
))
2306 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2307 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2309 atexit(stop_timer_thread
);
2312 return start_timer_thread();
2315 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2318 return errno
= EINVAL
,
2319 error("sigaction only implemented for SIGALRM");
2321 return errno
= EINVAL
,
2322 error("sigaction: param 3 != NULL not implemented");
2324 timer_fn
= in
->sa_handler
;
2329 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2341 sigint_fn
= handler
;
2345 return signal(sig
, handler
);
2352 int mingw_raise(int sig
)
2356 if (timer_fn
== SIG_DFL
) {
2357 if (isatty(STDERR_FILENO
))
2358 fputs("Alarm clock\n", stderr
);
2359 exit(128 + SIGALRM
);
2360 } else if (timer_fn
!= SIG_IGN
)
2365 if (sigint_fn
== SIG_DFL
)
2367 else if (sigint_fn
!= SIG_IGN
)
2371 #if defined(_MSC_VER)
2378 case SIGABRT_COMPAT
:
2380 * The <signal.h> header in the MS C Runtime defines 8 signals
2381 * as being supported on the platform. Anything else causes an
2382 * "Invalid signal or error" (which in DEBUG builds causes the
2383 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2384 * already know will fail.
2401 int link(const char *oldpath
, const char *newpath
)
2403 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2404 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2405 xutftowcs_path(wnewpath
, newpath
) < 0)
2408 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2409 errno
= err_win_to_posix(GetLastError());
2415 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2417 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2424 if (pid
> 0 && options
& WNOHANG
) {
2425 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2429 options
&= ~WNOHANG
;
2433 struct pinfo_t
**ppinfo
;
2434 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2440 GetExitCodeProcess(h
, (LPDWORD
)status
);
2442 EnterCriticalSection(&pinfo_cs
);
2446 struct pinfo_t
*info
= *ppinfo
;
2447 if (info
->pid
== pid
) {
2448 CloseHandle(info
->proc
);
2449 *ppinfo
= info
->next
;
2453 ppinfo
= &info
->next
;
2456 LeaveCriticalSection(&pinfo_cs
);
2467 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2469 int upos
= 0, wpos
= 0;
2470 const unsigned char *utf
= (const unsigned char*) utfs
;
2471 if (!utf
|| !wcs
|| wcslen
< 1) {
2475 /* reserve space for \0 */
2480 while (upos
< utflen
) {
2481 int c
= utf
[upos
++] & 0xff;
2482 if (utflen
== INT_MAX
&& c
== 0)
2485 if (wpos
>= wcslen
) {
2494 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2495 (utf
[upos
] & 0xc0) == 0x80) {
2497 c
= ((c
& 0x1f) << 6);
2498 c
|= (utf
[upos
++] & 0x3f);
2500 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2501 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2502 (utf
[upos
] & 0xc0) == 0x80 &&
2503 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2505 c
= ((c
& 0x0f) << 12);
2506 c
|= ((utf
[upos
++] & 0x3f) << 6);
2507 c
|= (utf
[upos
++] & 0x3f);
2509 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2510 wpos
+ 1 < wcslen
&&
2511 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2512 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2513 (utf
[upos
] & 0xc0) == 0x80 &&
2514 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2515 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2516 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2517 c
= ((c
& 0x07) << 18);
2518 c
|= ((utf
[upos
++] & 0x3f) << 12);
2519 c
|= ((utf
[upos
++] & 0x3f) << 6);
2520 c
|= (utf
[upos
++] & 0x3f);
2522 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2523 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2524 } else if (c
>= 0xa0) {
2525 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2528 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2529 static const char *hex
= "0123456789abcdef";
2530 wcs
[wpos
++] = hex
[c
>> 4];
2532 wcs
[wpos
++] = hex
[c
& 0x0f];
2539 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2541 if (!wcs
|| !utf
|| utflen
< 1) {
2545 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2552 static void setup_windows_environment(void)
2554 char *tmp
= getenv("TMPDIR");
2556 /* on Windows it is TMP and TEMP */
2558 if (!(tmp
= getenv("TMP")))
2559 tmp
= getenv("TEMP");
2561 setenv("TMPDIR", tmp
, 1);
2562 tmp
= getenv("TMPDIR");
2568 * Convert all dir separators to forward slashes,
2569 * to help shell commands called from the Git
2570 * executable (by not mistaking the dir separators
2571 * for escape characters).
2573 convert_slashes(tmp
);
2576 /* simulate TERM to enable auto-color (see color.c) */
2577 if (!getenv("TERM"))
2578 setenv("TERM", "cygwin", 1);
2580 /* calculate HOME if not set */
2581 if (!getenv("HOME")) {
2583 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2584 * location, thus also check if the path exists (i.e. is not
2587 if ((tmp
= getenv("HOMEDRIVE"))) {
2588 struct strbuf buf
= STRBUF_INIT
;
2589 strbuf_addstr(&buf
, tmp
);
2590 if ((tmp
= getenv("HOMEPATH"))) {
2591 strbuf_addstr(&buf
, tmp
);
2592 if (is_directory(buf
.buf
))
2593 setenv("HOME", buf
.buf
, 1);
2595 tmp
= NULL
; /* use $USERPROFILE */
2597 strbuf_release(&buf
);
2599 /* use $USERPROFILE if the home share is not available */
2600 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2601 setenv("HOME", tmp
, 1);
2605 static PSID
get_current_user_sid(void)
2611 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2614 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2615 TOKEN_USER
*info
= xmalloc((size_t)len
);
2616 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2617 len
= GetLengthSid(info
->User
.Sid
);
2618 result
= xmalloc(len
);
2619 if (!CopySid(len
, result
, info
->User
.Sid
)) {
2620 error(_("failed to copy SID (%ld)"),
2622 FREE_AND_NULL(result
);
2625 FREE_AND_NULL(info
);
2632 int is_path_owned_by_current_sid(const char *path
)
2634 WCHAR wpath
[MAX_PATH
];
2636 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2639 static wchar_t home
[MAX_PATH
];
2643 if (xutftowcs_path(wpath
, path
) < 0)
2647 * On Windows, the home directory is owned by the administrator, but for
2648 * all practical purposes, it belongs to the user. Do pretend that it is
2649 * owned by the user.
2652 DWORD size
= ARRAY_SIZE(home
);
2653 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2654 if (!len
|| len
> size
)
2655 wcscpy(home
, L
"::N/A::");
2657 if (!wcsicmp(wpath
, home
))
2660 /* Get the owner SID */
2661 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2662 OWNER_SECURITY_INFORMATION
|
2663 DACL_SECURITY_INFORMATION
,
2664 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2666 if (err
!= ERROR_SUCCESS
)
2667 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2668 else if (sid
&& IsValidSid(sid
)) {
2669 /* Now, verify that the SID matches the current user's */
2670 static PSID current_user_sid
;
2672 if (!current_user_sid
)
2673 current_user_sid
= get_current_user_sid();
2675 if (current_user_sid
&&
2676 IsValidSid(current_user_sid
) &&
2677 EqualSid(sid
, current_user_sid
))
2682 * We can release the security descriptor struct only now because `sid`
2683 * actually points into this struct.
2686 LocalFree(descriptor
);
2691 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
2693 const char *p
= path
;
2694 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
2699 skip_dos_drive_prefix((char **)&path
);
2706 case '/': case '\\':
2707 /* cannot end in ` ` or `.`, except for `.` and `..` */
2708 if (preceding_space_or_period
&&
2709 (i
!= periods
|| periods
> 2))
2714 i
= periods
= preceding_space_or_period
= 0;
2718 case 'a': case 'A': /* AUX */
2719 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2720 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
2721 not_a_reserved_name
:
2727 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2728 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
2729 goto not_a_reserved_name
;
2731 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
2733 if (c
< '1' || c
> '9')
2734 goto not_a_reserved_name
;
2735 } else if (c
== 'n' || c
== 'N') { /* CON */
2737 if ((c
== 'i' || c
== 'I') &&
2738 ((c
= path
[i
+ 2]) == 'n' ||
2741 i
+= 3; /* CONIN$ */
2742 else if ((c
== 'o' || c
== 'O') &&
2743 ((c
= path
[i
+ 2]) == 'u' ||
2745 ((c
= path
[i
+ 3]) == 't' ||
2748 i
+= 4; /* CONOUT$ */
2750 goto not_a_reserved_name
;
2752 case 'l': case 'L': /* LPT<N> */
2753 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
2754 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
2755 !isdigit(path
[++i
]))
2756 goto not_a_reserved_name
;
2758 case 'n': case 'N': /* NUL */
2759 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
2760 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
2761 (allow_literal_nul
&&
2762 !path
[i
+ 1] && p
== path
))
2763 goto not_a_reserved_name
;
2765 case 'p': case 'P': /* PRN */
2766 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
2767 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
2768 goto not_a_reserved_name
;
2775 * So far, this looks like a reserved name. Let's see
2776 * whether it actually is one: trailing spaces, a file
2777 * extension, or an NTFS Alternate Data Stream do not
2778 * matter, the name is still reserved if any of those
2779 * follow immediately after the actual name.
2782 if (path
[i
] == ' ') {
2783 preceding_space_or_period
= 1;
2784 while (path
[++i
] == ' ')
2785 ; /* skip all spaces */
2789 if (c
&& c
!= '.' && c
!= ':' && c
!= '/' && c
!= '\\')
2790 goto not_a_reserved_name
;
2792 /* contains reserved name */
2798 preceding_space_or_period
= 1;
2801 case ':': /* DOS drive prefix was already skipped */
2802 case '<': case '>': case '"': case '|': case '?': case '*':
2803 /* illegal character */
2806 if (c
> '\0' && c
< '\x20')
2807 /* illegal character */
2810 preceding_space_or_period
= 0;
2815 #if !defined(_MSC_VER)
2817 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2818 * mingw startup code, see init.c in mingw runtime).
2823 static NORETURN
void die_startup(void)
2825 fputs("fatal: not enough memory for initialization", stderr
);
2829 static void *malloc_startup(size_t size
)
2831 void *result
= malloc(size
);
2837 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2839 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2840 return memcpy(malloc_startup(len
), buffer
, len
);
2843 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2844 DWORD desired_access
, DWORD flags
)
2846 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2847 wchar_t buf
[MAX_PATH
];
2848 DWORD max
= ARRAY_SIZE(buf
);
2850 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2852 if (!ret
|| ret
>= max
)
2855 /* make sure this does not leak into child processes */
2856 SetEnvironmentVariableW(key
, NULL
);
2857 if (!wcscmp(buf
, L
"off")) {
2859 handle
= GetStdHandle(std_id
);
2860 if (handle
!= INVALID_HANDLE_VALUE
)
2861 CloseHandle(handle
);
2864 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2865 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2866 if (handle
== INVALID_HANDLE_VALUE
) {
2868 handle
= GetStdHandle(std_id
);
2869 if (handle
!= INVALID_HANDLE_VALUE
)
2870 CloseHandle(handle
);
2872 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2873 SetStdHandle(std_id
, handle
);
2875 /* do *not* close the new_fd: that would close stdout */
2879 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2881 if (handle
!= INVALID_HANDLE_VALUE
) {
2882 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2883 SetStdHandle(std_id
, handle
);
2889 static void maybe_redirect_std_handles(void)
2891 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2892 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2893 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2894 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2895 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2896 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2906 * We implement wmain() and compile with -municode, which would
2907 * normally ignore main(), but we call the latter from the former
2908 * so that we can handle non-ASCII command-line parameters
2911 * To be more compatible with the core git code, we convert
2912 * argv into UTF8 and pass them directly to main().
2914 int wmain(int argc
, const wchar_t **wargv
)
2916 int i
, maxlen
, exit_status
;
2917 char *buffer
, **save
;
2920 trace2_initialize_clock();
2924 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
2927 #ifdef USE_MSVC_CRTDBG
2928 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
2932 maybe_redirect_std_handles();
2934 /* determine size of argv and environ conversion buffer */
2935 maxlen
= wcslen(wargv
[0]);
2936 for (i
= 1; i
< argc
; i
++)
2937 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2939 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2940 maxlen
= 3 * maxlen
+ 1;
2941 buffer
= malloc_startup(maxlen
);
2944 * Create a UTF-8 version of w_argv. Also create a "save" copy
2945 * to remember all the string pointers because parse_options()
2946 * will remove claimed items from the argv that we pass down.
2948 ALLOC_ARRAY(argv
, argc
+ 1);
2949 ALLOC_ARRAY(save
, argc
+ 1);
2950 for (i
= 0; i
< argc
; i
++)
2951 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2952 argv
[i
] = save
[i
] = NULL
;
2955 /* fix Windows specific environment settings */
2956 setup_windows_environment();
2958 unset_environment_variables
= xstrdup("PERL5LIB");
2960 /* initialize critical section for waitpid pinfo_t list */
2961 InitializeCriticalSection(&pinfo_cs
);
2963 /* set up default file mode and file modes for stdin/out/err */
2965 _setmode(_fileno(stdin
), _O_BINARY
);
2966 _setmode(_fileno(stdout
), _O_BINARY
);
2967 _setmode(_fileno(stderr
), _O_BINARY
);
2969 /* initialize Unicode console */
2972 /* invoke the real main() using our utf8 version of argv. */
2973 exit_status
= main(argc
, argv
);
2975 for (i
= 0; i
< argc
; i
++)
2983 int uname(struct utsname
*buf
)
2985 unsigned v
= (unsigned)GetVersion();
2986 memset(buf
, 0, sizeof(*buf
));
2987 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
2988 xsnprintf(buf
->release
, sizeof(buf
->release
),
2989 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
2990 /* assuming NT variants only.. */
2991 xsnprintf(buf
->version
, sizeof(buf
->version
),
2992 "%u", (v
>> 16) & 0x7fff);