1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "../git-compat-util.h"
10 #include "../strbuf.h"
11 #include "../run-command.h"
12 #include "../abspath.h"
14 #include "win32/lazyload.h"
15 #include "../config.h"
16 #include "../environment.h"
17 #include "../trace2.h"
18 #include "../symlinks.h"
19 #include "../wrapper.h"
22 #define SECURITY_WIN32
26 #define STATUS_DELETE_PENDING ((NTSTATUS) 0xC0000056)
28 #define HCAST(type, handle) ((type)(intptr_t)handle)
30 static const int delay
[] = { 0, 1, 10, 20, 40 };
32 void open_in_gdb(void)
34 static struct child_process cp
= CHILD_PROCESS_INIT
;
36 strvec_pushl(&cp
.args
, "mintty", "gdb", NULL
);
37 strvec_pushf(&cp
.args
, "--pid=%d", getpid());
39 if (start_command(&cp
) < 0)
40 die_errno("Could not start gdb");
44 int err_win_to_posix(DWORD winerr
)
48 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
49 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
50 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
51 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
52 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
53 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
54 case ERROR_BAD_COMMAND
: error
= EIO
; break;
55 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
56 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
57 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
58 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
59 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
60 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
61 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
62 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
63 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
64 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
65 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
66 case ERROR_BUSY
: error
= EBUSY
; break;
67 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
68 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
69 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
70 case ERROR_CANTOPEN
: error
= EIO
; break;
71 case ERROR_CANTREAD
: error
= EIO
; break;
72 case ERROR_CANTWRITE
: error
= EIO
; break;
73 case ERROR_CRC
: error
= EIO
; break;
74 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
75 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
76 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
77 case ERROR_DIRECTORY
: error
= EINVAL
; break;
78 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
79 case ERROR_DISK_CHANGE
: error
= EIO
; break;
80 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
81 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
82 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
83 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
84 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
85 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
86 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
87 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
88 case ERROR_GEN_FAILURE
: error
= EIO
; break;
89 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
90 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
91 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
92 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
93 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
94 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
95 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
96 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
97 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
98 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
99 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
100 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
101 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
102 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
103 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
104 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
105 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
106 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
107 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
108 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
109 case ERROR_IO_DEVICE
: error
= EIO
; break;
110 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
111 case ERROR_LOCKED
: error
= EBUSY
; break;
112 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
113 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
114 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
115 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
116 case ERROR_MORE_DATA
: error
= EPIPE
; break;
117 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
118 case ERROR_NOACCESS
: error
= EFAULT
; break;
119 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
120 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
121 case ERROR_NOT_READY
: error
= EAGAIN
; break;
122 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
123 case ERROR_NO_DATA
: error
= EPIPE
; break;
124 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
125 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
126 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
127 case ERROR_OPEN_FAILED
: error
= EIO
; break;
128 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
129 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
130 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
131 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
132 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
133 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
134 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
135 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
136 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
137 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
138 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
139 case ERROR_READ_FAULT
: error
= EIO
; break;
140 case ERROR_SEEK
: error
= EIO
; break;
141 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
142 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
143 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
144 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
145 case ERROR_SUCCESS
: BUG("err_win_to_posix() called without an error!");
146 case ERROR_SWAPERROR
: error
= ENOENT
; break;
147 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
148 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
149 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
150 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
151 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
152 case ERROR_WRITE_FAULT
: error
= EIO
; break;
153 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
158 static inline int is_file_in_use_error(DWORD errcode
)
161 case ERROR_SHARING_VIOLATION
:
162 case ERROR_ACCESS_DENIED
:
169 static int read_yes_no_answer(void)
173 if (fgets(answer
, sizeof(answer
), stdin
)) {
174 size_t answer_len
= strlen(answer
);
175 int got_full_line
= 0, c
;
177 /* remove the newline */
178 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
179 answer
[answer_len
-2] = '\0';
181 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
182 answer
[answer_len
-1] = '\0';
185 /* flush the buffer in case we did not get the full line */
187 while ((c
= getchar()) != EOF
&& c
!= '\n')
190 /* we could not read, return the
191 * default answer which is no */
194 if (tolower(answer
[0]) == 'y' && !answer
[1])
196 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
198 if (tolower(answer
[0]) == 'n' && !answer
[1])
200 if (!strncasecmp(answer
, "no", sizeof(answer
)))
203 /* did not find an answer we understand */
207 static int ask_yes_no_if_possible(const char *format
, ...)
210 const char *retry_hook
;
213 va_start(args
, format
);
214 vsnprintf(question
, sizeof(question
), format
, args
);
217 retry_hook
= mingw_getenv("GIT_ASK_YESNO");
219 struct child_process cmd
= CHILD_PROCESS_INIT
;
221 strvec_pushl(&cmd
.args
, retry_hook
, question
, NULL
);
222 return !run_command(&cmd
);
225 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
230 fprintf(stderr
, "%s (y/n) ", question
);
232 if ((answer
= read_yes_no_answer()) >= 0)
235 fprintf(stderr
, "Sorry, I did not understand your answer. "
236 "Please type 'y' or 'n'\n");
241 enum hide_dotfiles_type
{
242 HIDE_DOTFILES_FALSE
= 0,
244 HIDE_DOTFILES_DOTGITONLY
247 static int core_restrict_inherited_handles
= -1;
248 static enum hide_dotfiles_type hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
249 static char *unset_environment_variables
;
251 int mingw_core_config(const char *var
, const char *value
,
252 const struct config_context
*ctx UNUSED
,
255 if (!strcmp(var
, "core.hidedotfiles")) {
256 if (value
&& !strcasecmp(value
, "dotgitonly"))
257 hide_dotfiles
= HIDE_DOTFILES_DOTGITONLY
;
259 hide_dotfiles
= git_config_bool(var
, value
);
263 if (!strcmp(var
, "core.unsetenvvars")) {
265 return config_error_nonbool(var
);
266 free(unset_environment_variables
);
267 unset_environment_variables
= xstrdup(value
);
271 if (!strcmp(var
, "core.restrictinheritedhandles")) {
272 if (value
&& !strcasecmp(value
, "auto"))
273 core_restrict_inherited_handles
= -1;
275 core_restrict_inherited_handles
=
276 git_config_bool(var
, value
);
283 /* Normalizes NT paths as returned by some low-level APIs. */
284 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
287 /* fix absolute path prefixes */
288 if (wbuf
[0] == '\\') {
289 /* strip NT namespace prefixes */
290 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
291 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
293 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
295 /* replace remaining '...UNC\' with '\\' */
296 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
301 /* convert backslashes to slashes */
302 for (i
= 0; wbuf
[i
]; i
++)
308 int mingw_unlink(const char *pathname
, int handle_in_use_error
)
311 wchar_t wpathname
[MAX_PATH
];
312 if (xutftowcs_path(wpathname
, pathname
) < 0)
315 if (DeleteFileW(wpathname
))
318 /* read-only files cannot be removed */
319 _wchmod(wpathname
, 0666);
320 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
321 if (!is_file_in_use_error(GetLastError()))
323 if (!handle_in_use_error
)
327 * We assume that some other process had the source or
328 * destination file open at the wrong moment and retry.
329 * In order to give the other process a higher chance to
330 * complete its operation, we give up our time slice now.
331 * If we have to retry again, we do sleep a bit.
336 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
337 ask_yes_no_if_possible("Unlink of file '%s' failed. "
338 "Should I try again?", pathname
))
339 ret
= _wunlink(wpathname
);
343 static int is_dir_empty(const wchar_t *wpath
)
345 WIN32_FIND_DATAW findbuf
;
347 wchar_t wbuf
[MAX_PATH
+ 2];
349 wcscat(wbuf
, L
"\\*");
350 handle
= FindFirstFileW(wbuf
, &findbuf
);
351 if (handle
== INVALID_HANDLE_VALUE
)
352 return GetLastError() == ERROR_NO_MORE_FILES
;
354 while (!wcscmp(findbuf
.cFileName
, L
".") ||
355 !wcscmp(findbuf
.cFileName
, L
".."))
356 if (!FindNextFileW(handle
, &findbuf
)) {
357 DWORD err
= GetLastError();
359 return err
== ERROR_NO_MORE_FILES
;
365 int mingw_rmdir(const char *pathname
)
368 wchar_t wpathname
[MAX_PATH
];
372 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
373 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
374 * symbolic link (if it points to a directory).
376 * This behavior breaks the assumption of e.g. `remove_path()` which
377 * upon successful deletion of a file will attempt to remove its parent
378 * directories recursively until failure (which usually happens when
379 * the directory is not empty).
381 * Therefore, before calling `_wrmdir()`, we first check if the path is
382 * a symbolic link. If it is, we exit and return the same error as
383 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
385 if (!mingw_lstat(pathname
, &st
) && S_ISLNK(st
.st_mode
)) {
390 if (xutftowcs_path(wpathname
, pathname
) < 0)
393 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
394 if (!is_file_in_use_error(GetLastError()))
395 errno
= err_win_to_posix(GetLastError());
398 if (!is_dir_empty(wpathname
)) {
403 * We assume that some other process had the source or
404 * destination file open at the wrong moment and retry.
405 * In order to give the other process a higher chance to
406 * complete its operation, we give up our time slice now.
407 * If we have to retry again, we do sleep a bit.
412 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
413 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
414 "Should I try again?", pathname
))
415 ret
= _wrmdir(wpathname
);
417 invalidate_lstat_cache();
421 static inline int needs_hiding(const char *path
)
423 const char *basename
;
425 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
428 /* We cannot use basename(), as it would remove trailing slashes */
429 win32_skip_dos_drive_prefix((char **)&path
);
433 for (basename
= path
; *path
; path
++)
434 if (is_dir_sep(*path
)) {
437 } while (is_dir_sep(*path
));
438 /* ignore trailing slashes */
445 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
446 return *basename
== '.';
448 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
449 return !strncasecmp(".git", basename
, 4) &&
450 (!basename
[4] || is_dir_sep(basename
[4]));
453 static int set_hidden_flag(const wchar_t *path
, int set
)
455 DWORD original
= GetFileAttributesW(path
), modified
;
457 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
459 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
460 if (original
== modified
|| SetFileAttributesW(path
, modified
))
462 errno
= err_win_to_posix(GetLastError());
466 int mingw_mkdir(const char *path
, int mode UNUSED
)
469 wchar_t wpath
[MAX_PATH
];
471 if (!is_valid_win32_path(path
, 0)) {
476 if (xutftowcs_path(wpath
, path
) < 0)
478 ret
= _wmkdir(wpath
);
479 if (!ret
&& needs_hiding(path
))
480 return set_hidden_flag(wpath
, 1);
485 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
486 * is documented in [1] as opening a writable file handle in append mode.
487 * (It is believed that) this is atomic since it is maintained by the
488 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
490 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
492 * This trick does not appear to work for named pipes. Instead it creates
493 * a named pipe client handle that cannot be written to. Callers should
494 * just use the regular _wopen() for them. (And since client handle gets
495 * bound to a unique server handle, it isn't really an issue.)
497 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
501 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
503 /* only these flags are supported */
504 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
505 return errno
= ENOSYS
, -1;
508 * FILE_SHARE_WRITE is required to permit child processes
509 * to append to the file.
511 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
512 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
513 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
514 if (handle
== INVALID_HANDLE_VALUE
) {
515 DWORD err
= GetLastError();
518 * Some network storage solutions (e.g. Isilon) might return
519 * ERROR_INVALID_PARAMETER instead of expected error
520 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
521 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
523 if (err
== ERROR_INVALID_PARAMETER
)
524 err
= ERROR_PATH_NOT_FOUND
;
526 errno
= err_win_to_posix(err
);
531 * No O_APPEND here, because the CRT uses it only to reset the
532 * file pointer to EOF before each write(); but that is not
533 * necessary (and may lead to races) for a file created with
536 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
543 * Ideally, we'd use `_wopen()` to implement this functionality so that we
544 * don't have to reimplement it, but unfortunately we do not have tight control
545 * over the share mode there. And while `_wsopen()` and friends exist that give
546 * us _some_ control over the share mode, this family of functions doesn't give
547 * us the ability to enable FILE_SHARE_DELETE, either. But this is a strict
548 * requirement for us though so that we can unlink or rename over files that
549 * are held open by another process.
551 * We are thus forced to implement our own emulation of `open()`. To make our
552 * life simpler we only implement basic support for this, namely opening
553 * existing files for reading and/or writing. This means that newly created
554 * files won't have their sharing mode set up correctly, but for now I couldn't
555 * find any case where this matters. We may have to revisit that in the future
556 * though based on our needs.
558 static int mingw_open_existing(const wchar_t *filename
, int oflags
, ...)
560 SECURITY_ATTRIBUTES security_attributes
= {
561 .nLength
= sizeof(security_attributes
),
562 .bInheritHandle
= !(oflags
& O_NOINHERIT
),
568 /* We only support basic flags. */
569 if (oflags
& ~(O_ACCMODE
| O_NOINHERIT
)) {
574 switch (oflags
& O_ACCMODE
) {
576 access
= GENERIC_READ
| GENERIC_WRITE
;
579 access
= GENERIC_WRITE
;
582 access
= GENERIC_READ
;
586 handle
= CreateFileW(filename
, access
,
587 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
588 &security_attributes
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
589 if (handle
== INVALID_HANDLE_VALUE
) {
590 DWORD err
= GetLastError();
592 /* See `mingw_open_append()` for why we have this conversion. */
593 if (err
== ERROR_INVALID_PARAMETER
)
594 err
= ERROR_PATH_NOT_FOUND
;
596 errno
= err_win_to_posix(err
);
600 fd
= _open_osfhandle((intptr_t)handle
, oflags
| O_BINARY
);
607 * Does the pathname map to the local named pipe filesystem?
608 * That is, does it have a "//./pipe/" prefix?
610 static int is_local_named_pipe_path(const char *filename
)
612 return (is_dir_sep(filename
[0]) &&
613 is_dir_sep(filename
[1]) &&
614 filename
[2] == '.' &&
615 is_dir_sep(filename
[3]) &&
616 !strncasecmp(filename
+4, "pipe", 4) &&
617 is_dir_sep(filename
[8]) &&
621 int mingw_open (const char *filename
, int oflags
, ...)
623 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
626 int fd
, create
= (oflags
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
);
627 wchar_t wfilename
[MAX_PATH
];
630 DECLARE_PROC_ADDR(ntdll
.dll
, NTSTATUS
, NTAPI
, RtlGetLastNtStatus
, void);
632 va_start(args
, oflags
);
633 mode
= va_arg(args
, int);
636 if (!is_valid_win32_path(filename
, !create
)) {
637 errno
= create
? EINVAL
: ENOENT
;
641 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
642 open_fn
= mingw_open_append
;
643 else if (!(oflags
& ~(O_ACCMODE
| O_NOINHERIT
)))
644 open_fn
= mingw_open_existing
;
648 if (filename
&& !strcmp(filename
, "/dev/null"))
649 wcscpy(wfilename
, L
"nul");
650 else if (xutftowcs_path(wfilename
, filename
) < 0)
653 fd
= open_fn(wfilename
, oflags
, mode
);
656 * Internally, `_wopen()` uses the `CreateFile()` API with CREATE_NEW,
657 * which may error out with ERROR_ACCESS_DENIED and an NtStatus of
658 * STATUS_DELETE_PENDING when the file is scheduled for deletion via
659 * `DeleteFileW()`. The file essentially exists, so we map errno to
660 * EEXIST instead of EACCESS so that callers don't have to special-case
663 * This fixes issues for example with the lockfile interface when one
664 * process has a lock that it is about to commit or release while
665 * another process wants to acquire it.
667 if (fd
< 0 && create
&& GetLastError() == ERROR_ACCESS_DENIED
&&
668 INIT_PROC_ADDR(RtlGetLastNtStatus
) && RtlGetLastNtStatus() == STATUS_DELETE_PENDING
)
670 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
671 DWORD attrs
= GetFileAttributesW(wfilename
);
672 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
675 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
677 * Internally, _wopen() uses the CreateFile() API which errors
678 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
679 * specified and an already existing file's attributes do not
680 * match *exactly*. As there is no mode or flag we can set that
681 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
682 * again *without* the O_CREAT flag (that corresponds to the
683 * CREATE_ALWAYS flag of CreateFile()).
685 if (fd
< 0 && errno
== EACCES
)
686 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
687 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
688 warning("could not mark '%s' as hidden.", filename
);
693 static BOOL WINAPI
ctrl_ignore(DWORD type UNUSED
)
699 int mingw_fgetc(FILE *stream
)
702 if (!isatty(_fileno(stream
)))
703 return fgetc(stream
);
705 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
708 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
711 /* Ctrl+C was pressed, simulate SIGINT and retry */
714 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
719 FILE *mingw_fopen (const char *filename
, const char *otype
)
721 int hide
= needs_hiding(filename
);
723 wchar_t wfilename
[MAX_PATH
], wotype
[4];
724 if (filename
&& !strcmp(filename
, "/dev/null"))
725 wcscpy(wfilename
, L
"nul");
726 else if (!is_valid_win32_path(filename
, 1)) {
727 int create
= otype
&& strchr(otype
, 'w');
728 errno
= create
? EINVAL
: ENOENT
;
730 } else if (xutftowcs_path(wfilename
, filename
) < 0)
733 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
736 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
737 error("could not unhide %s", filename
);
740 file
= _wfopen(wfilename
, wotype
);
741 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
743 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
744 warning("could not mark '%s' as hidden.", filename
);
748 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
750 int hide
= needs_hiding(filename
);
752 wchar_t wfilename
[MAX_PATH
], wotype
[4];
753 if (filename
&& !strcmp(filename
, "/dev/null"))
754 wcscpy(wfilename
, L
"nul");
755 else if (!is_valid_win32_path(filename
, 1)) {
756 int create
= otype
&& strchr(otype
, 'w');
757 errno
= create
? EINVAL
: ENOENT
;
759 } else if (xutftowcs_path(wfilename
, filename
) < 0)
762 if (xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
765 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
766 error("could not unhide %s", filename
);
769 file
= _wfreopen(wfilename
, wotype
, stream
);
770 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
771 warning("could not mark '%s' as hidden.", filename
);
776 int mingw_fflush(FILE *stream
)
778 int ret
= fflush(stream
);
781 * write() is used behind the scenes of stdio output functions.
782 * Since git code does not check for errors after each stdio write
783 * operation, it can happen that write() is called by a later
784 * stdio function even if an earlier write() call failed. In the
785 * case of a pipe whose readable end was closed, only the first
786 * call to write() reports EPIPE on Windows. Subsequent write()
787 * calls report EINVAL. It is impossible to notice whether this
788 * fflush invocation triggered such a case, therefore, we have to
789 * catch all EINVAL errors whole-sale.
791 if (ret
&& errno
== EINVAL
)
798 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
800 ssize_t result
= write(fd
, buf
, len
);
802 if (result
< 0 && (errno
== EINVAL
|| errno
== ENOSPC
) && buf
) {
805 /* check if fd is a pipe */
806 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
807 if (GetFileType(h
) != FILE_TYPE_PIPE
)
809 else if (orig
== EINVAL
)
814 if (!GetNamedPipeInfo(h
, NULL
, NULL
, &buf_size
, NULL
))
817 return write(fd
, buf
, buf_size
);
825 int mingw_access(const char *filename
, int mode
)
827 wchar_t wfilename
[MAX_PATH
];
828 if (!strcmp("nul", filename
) || !strcmp("/dev/null", filename
))
830 if (xutftowcs_path(wfilename
, filename
) < 0)
832 /* X_OK is not supported by the MSVCRT version */
833 return _waccess(wfilename
, mode
& ~X_OK
);
836 int mingw_chdir(const char *dirname
)
838 wchar_t wdirname
[MAX_PATH
];
839 if (xutftowcs_path(wdirname
, dirname
) < 0)
841 return _wchdir(wdirname
);
844 int mingw_chmod(const char *filename
, int mode
)
846 wchar_t wfilename
[MAX_PATH
];
847 if (xutftowcs_path(wfilename
, filename
) < 0)
849 return _wchmod(wfilename
, mode
);
853 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
854 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
856 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
858 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
859 /* Windows to Unix Epoch conversion */
860 return winTime
- 116444736000000000LL;
863 static inline void filetime_to_timespec(const FILETIME
*ft
, struct timespec
*ts
)
865 long long hnsec
= filetime_to_hnsec(ft
);
866 ts
->tv_sec
= (time_t)(hnsec
/ 10000000);
867 ts
->tv_nsec
= (hnsec
% 10000000) * 100;
871 * Verifies that safe_create_leading_directories() would succeed.
873 static int has_valid_directory_prefix(wchar_t *wfilename
)
875 size_t n
= wcslen(wfilename
);
878 wchar_t c
= wfilename
[--n
];
884 wfilename
[n
] = L
'\0';
885 attributes
= GetFileAttributesW(wfilename
);
888 (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
))
890 if (attributes
== INVALID_FILE_ATTRIBUTES
)
891 switch (GetLastError()) {
892 case ERROR_PATH_NOT_FOUND
:
894 case ERROR_FILE_NOT_FOUND
:
895 /* This implies parent directory exists. */
903 /* We keep the do_lstat code in a separate function to avoid recursion.
904 * When a path ends with a slash, the stat will fail with ENOENT. In
905 * this case, we strip the trailing slashes and stat again.
907 * If follow is true then act like stat() and report on the link
908 * target. Otherwise report on the link itself.
910 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
912 WIN32_FILE_ATTRIBUTE_DATA fdata
;
913 wchar_t wfilename
[MAX_PATH
];
914 if (xutftowcs_path(wfilename
, file_name
) < 0)
917 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
922 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
923 buf
->st_size
= fdata
.nFileSizeLow
|
924 (((off_t
)fdata
.nFileSizeHigh
)<<32);
925 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
926 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
927 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
928 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
929 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
930 WIN32_FIND_DATAW findbuf
;
931 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
932 if (handle
!= INVALID_HANDLE_VALUE
) {
933 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
934 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
936 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
937 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
939 buf
->st_mode
= S_IFLNK
;
941 buf
->st_mode
|= S_IREAD
;
942 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
943 buf
->st_mode
|= S_IWRITE
;
950 switch (GetLastError()) {
951 case ERROR_ACCESS_DENIED
:
952 case ERROR_SHARING_VIOLATION
:
953 case ERROR_LOCK_VIOLATION
:
954 case ERROR_SHARING_BUFFER_EXCEEDED
:
957 case ERROR_BUFFER_OVERFLOW
:
958 errno
= ENAMETOOLONG
;
960 case ERROR_NOT_ENOUGH_MEMORY
:
963 case ERROR_PATH_NOT_FOUND
:
964 if (!has_valid_directory_prefix(wfilename
)) {
976 /* We provide our own lstat/fstat functions, since the provided
977 * lstat/fstat functions are so slow. These stat functions are
978 * tailored for Git's usage (read: fast), and are not meant to be
979 * complete. Note that Git stat()s are redirected to mingw_lstat()
980 * too, since Windows doesn't really handle symlinks that well.
982 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
985 char alt_name
[PATH_MAX
];
987 if (!do_lstat(follow
, file_name
, buf
))
990 /* if file_name ended in a '/', Windows returned ENOENT;
991 * try again without trailing slashes
996 namelen
= strlen(file_name
);
997 if (namelen
&& file_name
[namelen
-1] != '/')
999 while (namelen
&& file_name
[namelen
-1] == '/')
1001 if (!namelen
|| namelen
>= PATH_MAX
)
1004 memcpy(alt_name
, file_name
, namelen
);
1005 alt_name
[namelen
] = 0;
1006 return do_lstat(follow
, alt_name
, buf
);
1009 static int get_file_info_by_handle(HANDLE hnd
, struct stat
*buf
)
1011 BY_HANDLE_FILE_INFORMATION fdata
;
1013 if (!GetFileInformationByHandle(hnd
, &fdata
)) {
1014 errno
= err_win_to_posix(GetLastError());
1022 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
1023 buf
->st_size
= fdata
.nFileSizeLow
|
1024 (((off_t
)fdata
.nFileSizeHigh
)<<32);
1025 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
1026 filetime_to_timespec(&(fdata
.ftLastAccessTime
), &(buf
->st_atim
));
1027 filetime_to_timespec(&(fdata
.ftLastWriteTime
), &(buf
->st_mtim
));
1028 filetime_to_timespec(&(fdata
.ftCreationTime
), &(buf
->st_ctim
));
1032 int mingw_lstat(const char *file_name
, struct stat
*buf
)
1034 return do_stat_internal(0, file_name
, buf
);
1036 int mingw_stat(const char *file_name
, struct stat
*buf
)
1038 return do_stat_internal(1, file_name
, buf
);
1041 int mingw_fstat(int fd
, struct stat
*buf
)
1043 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
1044 DWORD avail
, type
= GetFileType(fh
) & ~FILE_TYPE_REMOTE
;
1047 case FILE_TYPE_DISK
:
1048 return get_file_info_by_handle(fh
, buf
);
1050 case FILE_TYPE_CHAR
:
1051 case FILE_TYPE_PIPE
:
1052 /* initialize stat fields */
1053 memset(buf
, 0, sizeof(*buf
));
1056 if (type
== FILE_TYPE_CHAR
) {
1057 buf
->st_mode
= _S_IFCHR
;
1059 buf
->st_mode
= _S_IFIFO
;
1060 if (PeekNamedPipe(fh
, NULL
, 0, NULL
, &avail
, NULL
))
1061 buf
->st_size
= avail
;
1071 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
1073 long long winTime
= t
* 10000000LL + 116444736000000000LL;
1074 ft
->dwLowDateTime
= winTime
;
1075 ft
->dwHighDateTime
= winTime
>> 32;
1078 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
1083 wchar_t wfilename
[MAX_PATH
];
1084 HANDLE osfilehandle
;
1086 if (xutftowcs_path(wfilename
, file_name
) < 0)
1089 /* must have write permission */
1090 attrs
= GetFileAttributesW(wfilename
);
1091 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1092 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1093 /* ignore errors here; open() will report them */
1094 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
1097 osfilehandle
= CreateFileW(wfilename
,
1098 FILE_WRITE_ATTRIBUTES
,
1099 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1102 (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1103 (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) ?
1104 FILE_FLAG_BACKUP_SEMANTICS
: 0,
1106 if (osfilehandle
== INVALID_HANDLE_VALUE
) {
1107 errno
= err_win_to_posix(GetLastError());
1113 time_t_to_filetime(times
->modtime
, &mft
);
1114 time_t_to_filetime(times
->actime
, &aft
);
1116 GetSystemTimeAsFileTime(&mft
);
1120 if (!SetFileTime(osfilehandle
, NULL
, &aft
, &mft
)) {
1126 if (osfilehandle
!= INVALID_HANDLE_VALUE
)
1127 CloseHandle(osfilehandle
);
1130 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
1131 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
1132 /* ignore errors again */
1133 SetFileAttributesW(wfilename
, attrs
);
1139 size_t mingw_strftime(char *s
, size_t max
,
1140 const char *format
, const struct tm
*tm
)
1142 /* a pointer to the original strftime in case we can't find the UCRT version */
1143 static size_t (*fallback
)(char *, size_t, const char *, const struct tm
*) = strftime
;
1145 DECLARE_PROC_ADDR(ucrtbase
.dll
, size_t, __cdecl
, strftime
, char *, size_t,
1146 const char *, const struct tm
*);
1148 if (INIT_PROC_ADDR(strftime
))
1149 ret
= strftime(s
, max
, format
, tm
);
1151 ret
= fallback(s
, max
, format
, tm
);
1153 if (!ret
&& errno
== EINVAL
)
1154 die("invalid strftime format: '%s'", format
);
1158 unsigned int sleep (unsigned int seconds
)
1160 Sleep(seconds
*1000);
1164 char *mingw_mktemp(char *template)
1166 wchar_t wtemplate
[MAX_PATH
];
1167 if (xutftowcs_path(wtemplate
, template) < 0)
1169 if (!_wmktemp(wtemplate
))
1171 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
1176 int mkstemp(char *template)
1178 return git_mkstemp_mode(template, 0600);
1181 int gettimeofday(struct timeval
*tv
, void *tz UNUSED
)
1186 GetSystemTimeAsFileTime(&ft
);
1187 hnsec
= filetime_to_hnsec(&ft
);
1188 tv
->tv_sec
= hnsec
/ 10000000;
1189 tv
->tv_usec
= (hnsec
% 10000000) / 10;
1193 int pipe(int filedes
[2])
1197 /* this creates non-inheritable handles */
1198 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
1199 errno
= err_win_to_posix(GetLastError());
1202 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
1203 if (filedes
[0] < 0) {
1208 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
1209 if (filedes
[1] < 0) {
1218 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
1220 if (gmtime_s(result
, timep
) == 0)
1225 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
1227 if (localtime_s(result
, timep
) == 0)
1233 char *mingw_getcwd(char *pointer
, int len
)
1235 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
1236 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
1238 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
1239 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
1242 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
1243 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
1244 HANDLE hnd
= CreateFileW(cwd
, 0,
1245 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1246 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1247 if (hnd
== INVALID_HANDLE_VALUE
)
1249 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
1251 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1253 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
1257 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
1259 if (GetFileAttributesW(wpointer
) == INVALID_FILE_ATTRIBUTES
) {
1263 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
1265 convert_slashes(pointer
);
1270 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1271 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1273 static const char *quote_arg_msvc(const char *arg
)
1275 /* count chars to quote */
1277 int force_quotes
= 0;
1279 const char *p
= arg
;
1280 if (!*p
) force_quotes
= 1;
1282 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
1286 else if (*p
== '\\') {
1288 while (*p
== '\\') {
1293 if (*p
== '"' || !*p
)
1300 if (!force_quotes
&& n
== 0)
1303 /* insert \ where necessary */
1304 d
= q
= xmalloc(st_add3(len
, n
, 3));
1309 else if (*arg
== '\\') {
1311 while (*arg
== '\\') {
1315 if (*arg
== '"' || !*arg
) {
1318 /* don't escape the surrounding end quote */
1333 static const char *quote_arg_msys2(const char *arg
)
1335 struct strbuf buf
= STRBUF_INIT
;
1336 const char *p2
= arg
, *p
;
1338 for (p
= arg
; *p
; p
++) {
1339 int ws
= isspace(*p
);
1340 if (!ws
&& *p
!= '\\' && *p
!= '"' && *p
!= '{' && *p
!= '\'' &&
1341 *p
!= '?' && *p
!= '*' && *p
!= '~')
1344 strbuf_addch(&buf
, '"');
1346 strbuf_add(&buf
, p2
, p
- p2
);
1347 if (*p
== '\\' || *p
== '"')
1348 strbuf_addch(&buf
, '\\');
1353 strbuf_addch(&buf
, '"');
1357 strbuf_add(&buf
, p2
, p
- p2
);
1359 strbuf_addch(&buf
, '"');
1360 return strbuf_detach(&buf
, 0);
1363 static const char *parse_interpreter(const char *cmd
)
1365 static char buf
[100];
1367 ssize_t n
; /* read() can return negative values */
1370 /* don't even try a .exe */
1372 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1375 fd
= open(cmd
, O_RDONLY
);
1378 n
= read(fd
, buf
, sizeof(buf
)-1);
1380 if (n
< 4) /* at least '#!/x' and not error */
1383 if (buf
[0] != '#' || buf
[1] != '!')
1386 p
= buf
+ strcspn(buf
, "\r\n");
1391 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1394 if ((opt
= strchr(p
+1, ' ')))
1400 * exe_only means that we only want to detect .exe files, but not scripts
1401 * (which do not have an extension)
1403 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1404 int isexe
, int exe_only
)
1406 char path
[MAX_PATH
];
1407 wchar_t wpath
[MAX_PATH
];
1408 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1410 if (xutftowcs_path(wpath
, path
) < 0)
1413 if (!isexe
&& _waccess(wpath
, F_OK
) == 0)
1414 return xstrdup(path
);
1415 wpath
[wcslen(wpath
)-4] = '\0';
1416 if ((!exe_only
|| isexe
) && _waccess(wpath
, F_OK
) == 0) {
1417 if (!(GetFileAttributesW(wpath
) & FILE_ATTRIBUTE_DIRECTORY
)) {
1418 path
[strlen(path
)-4] = '\0';
1419 return xstrdup(path
);
1426 * Determines the absolute path of cmd using the split path in path.
1427 * If cmd contains a slash or backslash, no lookup is performed.
1429 static char *path_lookup(const char *cmd
, int exe_only
)
1433 size_t len
= strlen(cmd
);
1434 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1436 if (strpbrk(cmd
, "/\\"))
1437 return xstrdup(cmd
);
1439 path
= mingw_getenv("PATH");
1444 const char *sep
= strchrnul(path
, ';');
1445 int dirlen
= sep
- path
;
1447 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1456 char *mingw_locate_in_PATH(const char *cmd
)
1458 return path_lookup(cmd
, 0);
1461 static const wchar_t *wcschrnul(const wchar_t *s
, wchar_t c
)
1463 while (*s
&& *s
!= c
)
1468 /* Compare only keys */
1469 static int wenvcmp(const void *a
, const void *b
)
1471 wchar_t *p
= *(wchar_t **)a
, *q
= *(wchar_t **)b
;
1472 size_t p_len
, q_len
;
1475 p_len
= wcschrnul(p
, L
'=') - p
;
1476 q_len
= wcschrnul(q
, L
'=') - q
;
1478 /* If the length differs, include the shorter key's NUL */
1481 else if (p_len
> q_len
)
1484 return _wcsnicmp(p
, q
, p_len
);
1488 * Build an environment block combining the inherited environment
1489 * merged with the given list of settings.
1491 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1492 * Values of the form "KEY" in deltaenv delete inherited values.
1494 * Multiple entries in deltaenv for the same key are explicitly allowed.
1496 * We return a contiguous block of UNICODE strings with a final trailing
1499 static wchar_t *make_environment_block(char **deltaenv
)
1501 wchar_t *wenv
= GetEnvironmentStringsW(), *wdeltaenv
, *result
, *p
;
1502 size_t wlen
, s
, delta_size
, size
;
1504 wchar_t **array
= NULL
;
1505 size_t alloc
= 0, nr
= 0, i
;
1507 size
= 1; /* for extra NUL at the end */
1509 /* If there is no deltaenv to apply, simply return a copy. */
1510 if (!deltaenv
|| !*deltaenv
) {
1511 for (p
= wenv
; p
&& *p
; ) {
1512 size_t s
= wcslen(p
) + 1;
1517 DUP_ARRAY(result
, wenv
, size
);
1518 FreeEnvironmentStringsW(wenv
);
1523 * If there is a deltaenv, let's accumulate all keys into `array`,
1524 * sort them using the stable git_stable_qsort() and then copy,
1525 * skipping duplicate keys
1527 for (p
= wenv
; p
&& *p
; ) {
1528 ALLOC_GROW(array
, nr
+ 1, alloc
);
1535 /* (over-)assess size needed for wchar version of deltaenv */
1536 for (delta_size
= 0, i
= 0; deltaenv
[i
]; i
++)
1537 delta_size
+= strlen(deltaenv
[i
]) * 2 + 1;
1538 ALLOC_ARRAY(wdeltaenv
, delta_size
);
1540 /* convert the deltaenv, appending to array */
1541 for (i
= 0, p
= wdeltaenv
; deltaenv
[i
]; i
++) {
1542 ALLOC_GROW(array
, nr
+ 1, alloc
);
1543 wlen
= xutftowcs(p
, deltaenv
[i
], wdeltaenv
+ delta_size
- p
);
1548 git_stable_qsort(array
, nr
, sizeof(*array
), wenvcmp
);
1549 ALLOC_ARRAY(result
, size
+ delta_size
);
1551 for (p
= result
, i
= 0; i
< nr
; i
++) {
1552 /* Skip any duplicate keys; last one wins */
1553 while (i
+ 1 < nr
&& !wenvcmp(array
+ i
, array
+ i
+ 1))
1556 /* Skip "to delete" entry */
1557 if (!wcschr(array
[i
], L
'='))
1560 size
= wcslen(array
[i
]) + 1;
1561 COPY_ARRAY(p
, array
[i
], size
);
1568 FreeEnvironmentStringsW(wenv
);
1572 static void do_unset_environment_variables(void)
1575 char *p
= unset_environment_variables
;
1582 char *comma
= strchr(p
, ',');
1594 struct pinfo_t
*next
;
1598 static struct pinfo_t
*pinfo
= NULL
;
1599 CRITICAL_SECTION pinfo_cs
;
1601 /* Used to match and chomp off path components */
1602 static inline int match_last_path_component(const char *path
, size_t *len
,
1603 const char *component
)
1605 size_t component_len
= strlen(component
);
1606 if (*len
< component_len
+ 1 ||
1607 !is_dir_sep(path
[*len
- component_len
- 1]) ||
1608 fspathncmp(path
+ *len
- component_len
, component
, component_len
))
1610 *len
-= component_len
+ 1;
1611 /* chomp off repeated dir separators */
1612 while (*len
> 0 && is_dir_sep(path
[*len
- 1]))
1617 static int is_msys2_sh(const char *cmd
)
1622 if (!strcmp(cmd
, "sh")) {
1623 static int ret
= -1;
1629 p
= path_lookup(cmd
, 0);
1633 size_t len
= strlen(p
);
1635 ret
= match_last_path_component(p
, &len
, "sh.exe") &&
1636 match_last_path_component(p
, &len
, "bin") &&
1637 match_last_path_component(p
, &len
, "usr");
1643 if (ends_with(cmd
, "\\sh.exe") || ends_with(cmd
, "/sh.exe")) {
1647 sh
= path_lookup("sh", 0);
1649 return !fspathcmp(cmd
, sh
);
1655 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1657 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1659 static int restrict_handle_inheritance
= -1;
1661 PROCESS_INFORMATION pi
;
1662 LPPROC_THREAD_ATTRIBUTE_LIST attr_list
= NULL
;
1663 HANDLE stdhandles
[3];
1664 DWORD stdhandles_count
= 0;
1667 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1668 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1671 const char *(*quote_arg
)(const char *arg
) =
1672 is_msys2_sh(cmd
? cmd
: *argv
) ?
1673 quote_arg_msys2
: quote_arg_msvc
;
1674 const char *strace_env
;
1676 /* Make sure to override previous errors, if any */
1679 if (restrict_handle_inheritance
< 0)
1680 restrict_handle_inheritance
= core_restrict_inherited_handles
;
1682 * The following code to restrict which handles are inherited seems
1683 * to work properly only on Windows 7 and later, so let's disable it
1684 * on Windows Vista and 2008.
1686 if (restrict_handle_inheritance
< 0)
1687 restrict_handle_inheritance
= GetVersion() >> 16 >= 7601;
1689 do_unset_environment_variables();
1691 /* Determine whether or not we are associated to a console */
1692 cons
= CreateFileW(L
"CONOUT$", GENERIC_WRITE
,
1693 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1694 FILE_ATTRIBUTE_NORMAL
, NULL
);
1695 if (cons
== INVALID_HANDLE_VALUE
) {
1696 /* There is no console associated with this process.
1697 * Since the child is a console process, Windows
1698 * would normally create a console window. But
1699 * since we'll be redirecting std streams, we do
1700 * not need the console.
1701 * It is necessary to use DETACHED_PROCESS
1702 * instead of CREATE_NO_WINDOW to make ssh
1703 * recognize that it has no console.
1705 flags
|= DETACHED_PROCESS
;
1707 /* There is already a console. If we specified
1708 * DETACHED_PROCESS here, too, Windows would
1709 * disassociate the child from the console.
1710 * The same is true for CREATE_NO_WINDOW.
1715 memset(&si
, 0, sizeof(si
));
1716 si
.StartupInfo
.cb
= sizeof(si
);
1717 si
.StartupInfo
.hStdInput
= winansi_get_osfhandle(fhin
);
1718 si
.StartupInfo
.hStdOutput
= winansi_get_osfhandle(fhout
);
1719 si
.StartupInfo
.hStdError
= winansi_get_osfhandle(fherr
);
1721 /* The list of handles cannot contain duplicates */
1722 if (si
.StartupInfo
.hStdInput
!= INVALID_HANDLE_VALUE
)
1723 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdInput
;
1724 if (si
.StartupInfo
.hStdOutput
!= INVALID_HANDLE_VALUE
&&
1725 si
.StartupInfo
.hStdOutput
!= si
.StartupInfo
.hStdInput
)
1726 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdOutput
;
1727 if (si
.StartupInfo
.hStdError
!= INVALID_HANDLE_VALUE
&&
1728 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdInput
&&
1729 si
.StartupInfo
.hStdError
!= si
.StartupInfo
.hStdOutput
)
1730 stdhandles
[stdhandles_count
++] = si
.StartupInfo
.hStdError
;
1731 if (stdhandles_count
)
1732 si
.StartupInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1734 if (*argv
&& !strcmp(cmd
, *argv
))
1736 else if (xutftowcs_path(wcmd
, cmd
) < 0)
1738 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1741 /* concatenate argv, quoting args as we go */
1742 strbuf_init(&args
, 0);
1744 char *quoted
= (char *)quote_arg(cmd
);
1745 strbuf_addstr(&args
, quoted
);
1749 for (; *argv
; argv
++) {
1750 char *quoted
= (char *)quote_arg(*argv
);
1752 strbuf_addch(&args
, ' ');
1753 strbuf_addstr(&args
, quoted
);
1754 if (quoted
!= *argv
)
1758 strace_env
= getenv("GIT_STRACE_COMMANDS");
1760 char *p
= path_lookup("strace.exe", 1);
1762 return error("strace not found!");
1763 if (xutftowcs_path(wcmd
, p
) < 0) {
1768 if (!strcmp("1", strace_env
) ||
1769 !strcasecmp("yes", strace_env
) ||
1770 !strcasecmp("true", strace_env
))
1771 strbuf_insert(&args
, 0, "strace ", 7);
1773 const char *quoted
= quote_arg(strace_env
);
1774 struct strbuf buf
= STRBUF_INIT
;
1775 strbuf_addf(&buf
, "strace -o %s ", quoted
);
1776 if (quoted
!= strace_env
)
1777 free((char *)quoted
);
1778 strbuf_insert(&args
, 0, buf
.buf
, buf
.len
);
1779 strbuf_release(&buf
);
1783 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1784 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1785 strbuf_release(&args
);
1787 wenvblk
= make_environment_block(deltaenv
);
1789 memset(&pi
, 0, sizeof(pi
));
1790 if (restrict_handle_inheritance
&& stdhandles_count
&&
1791 (InitializeProcThreadAttributeList(NULL
, 1, 0, &size
) ||
1792 GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1793 (attr_list
= (LPPROC_THREAD_ATTRIBUTE_LIST
)
1794 (HeapAlloc(GetProcessHeap(), 0, size
))) &&
1795 InitializeProcThreadAttributeList(attr_list
, 1, 0, &size
) &&
1796 UpdateProcThreadAttribute(attr_list
, 0,
1797 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
1799 stdhandles_count
* sizeof(HANDLE
),
1801 si
.lpAttributeList
= attr_list
;
1802 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
1805 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1806 stdhandles_count
? TRUE
: FALSE
,
1807 flags
, wenvblk
, dir
? wdir
: NULL
,
1808 &si
.StartupInfo
, &pi
);
1811 * On Windows 2008 R2, it seems that specifying certain types of handles
1812 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1813 * error. Rather than playing finicky and fragile games, let's just try
1814 * to detect this situation and simply try again without restricting any
1815 * handle inheritance. This is still better than failing to create
1818 if (!ret
&& restrict_handle_inheritance
&& stdhandles_count
) {
1819 DWORD err
= GetLastError();
1820 struct strbuf buf
= STRBUF_INIT
;
1822 if (err
!= ERROR_NO_SYSTEM_RESOURCES
&&
1824 * On Windows 7 and earlier, handles on pipes and character
1825 * devices are inherited automatically, and cannot be
1826 * specified in the thread handle list. Rather than trying
1827 * to catch each and every corner case (and running the
1828 * chance of *still* forgetting a few), let's just fall
1829 * back to creating the process without trying to limit the
1830 * handle inheritance.
1832 !(err
== ERROR_INVALID_PARAMETER
&&
1833 GetVersion() >> 16 < 9200) &&
1834 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1838 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1840 for (i
= 0; i
< stdhandles_count
; i
++) {
1841 HANDLE h
= stdhandles
[i
];
1842 strbuf_addf(&buf
, "handle #%d: %p (type %lx, "
1843 "handle info (%d) %lx\n", i
, h
,
1845 GetHandleInformation(h
, &fl
),
1848 strbuf_addstr(&buf
, "\nThis is a bug; please report it "
1849 "at\nhttps://github.com/git-for-windows/"
1850 "git/issues/new\n\n"
1851 "To suppress this warning, please set "
1852 "the environment variable\n\n"
1853 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1856 restrict_handle_inheritance
= 0;
1857 flags
&= ~EXTENDED_STARTUPINFO_PRESENT
;
1858 ret
= CreateProcessW(*wcmd
? wcmd
: NULL
, wargs
, NULL
, NULL
,
1859 TRUE
, flags
, wenvblk
, dir
? wdir
: NULL
,
1860 &si
.StartupInfo
, &pi
);
1862 errno
= err_win_to_posix(GetLastError());
1863 if (ret
&& buf
.len
) {
1864 warning("failed to restrict file handles (%ld)\n\n%s",
1867 strbuf_release(&buf
);
1869 errno
= err_win_to_posix(GetLastError());
1871 if (si
.lpAttributeList
)
1872 DeleteProcThreadAttributeList(si
.lpAttributeList
);
1874 HeapFree(GetProcessHeap(), 0, attr_list
);
1882 CloseHandle(pi
.hThread
);
1885 * The process ID is the human-readable identifier of the process
1886 * that we want to present in log and error messages. The handle
1887 * is not useful for this purpose. But we cannot close it, either,
1888 * because it is not possible to turn a process ID into a process
1889 * handle after the process terminated.
1890 * Keep the handle in a list for waitpid.
1892 EnterCriticalSection(&pinfo_cs
);
1894 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1895 info
->pid
= pi
.dwProcessId
;
1896 info
->proc
= pi
.hProcess
;
1900 LeaveCriticalSection(&pinfo_cs
);
1902 return (pid_t
)pi
.dwProcessId
;
1905 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1907 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1910 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1912 int fhin
, int fhout
, int fherr
)
1915 char *prog
= path_lookup(cmd
, 0);
1922 const char *interpr
= parse_interpreter(prog
);
1925 const char *argv0
= argv
[0];
1926 char *iprog
= path_lookup(interpr
, 1);
1933 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1934 fhin
, fhout
, fherr
);
1940 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1941 fhin
, fhout
, fherr
);
1947 static int try_shell_exec(const char *cmd
, char *const *argv
)
1949 const char *interpr
= parse_interpreter(cmd
);
1955 prog
= path_lookup(interpr
, 1);
1960 while (argv
[argc
]) argc
++;
1961 ALLOC_ARRAY(argv2
, argc
+ 1);
1962 argv2
[0] = (char *)cmd
; /* full path to the script file */
1963 COPY_ARRAY(&argv2
[1], &argv
[1], argc
);
1964 exec_id
= trace2_exec(prog
, (const char **)argv2
);
1965 pid
= mingw_spawnv(prog
, (const char **)argv2
, 1);
1968 if (waitpid(pid
, &status
, 0) < 0)
1970 trace2_exec_result(exec_id
, status
);
1973 trace2_exec_result(exec_id
, -1);
1974 pid
= 1; /* indicate that we tried but failed */
1981 int mingw_execv(const char *cmd
, char *const *argv
)
1983 /* check if git_command is a shell script */
1984 if (!try_shell_exec(cmd
, argv
)) {
1988 exec_id
= trace2_exec(cmd
, (const char **)argv
);
1989 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1991 trace2_exec_result(exec_id
, -1);
1994 if (waitpid(pid
, &status
, 0) < 0)
1996 trace2_exec_result(exec_id
, status
);
2002 int mingw_execvp(const char *cmd
, char *const *argv
)
2004 char *prog
= path_lookup(cmd
, 0);
2007 mingw_execv(prog
, argv
);
2015 int mingw_kill(pid_t pid
, int sig
)
2017 if (pid
> 0 && sig
== SIGTERM
) {
2018 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
2020 if (TerminateProcess(h
, -1)) {
2025 errno
= err_win_to_posix(GetLastError());
2028 } else if (pid
> 0 && sig
== 0) {
2029 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
2041 * UTF-8 versions of getenv(), putenv() and unsetenv().
2042 * Internally, they use the CRT's stock UNICODE routines
2043 * to avoid data loss.
2045 char *mingw_getenv(const char *name
)
2047 #define GETENV_MAX_RETAIN 64
2048 static char *values
[GETENV_MAX_RETAIN
];
2049 static int value_counter
;
2050 size_t len_key
, len_value
;
2053 wchar_t w_value
[32768];
2055 if (!name
|| !*name
)
2058 len_key
= strlen(name
) + 1;
2059 /* We cannot use xcalloc() here because that uses getenv() itself */
2060 w_key
= calloc(len_key
, sizeof(wchar_t));
2062 die("Out of memory, (tried to allocate %"PRIuMAX
" wchar_t's)",
2063 (uintmax_t)len_key
);
2064 xutftowcs(w_key
, name
, len_key
);
2065 /* GetEnvironmentVariableW() only sets the last error upon failure */
2066 SetLastError(ERROR_SUCCESS
);
2067 len_value
= GetEnvironmentVariableW(w_key
, w_value
, ARRAY_SIZE(w_value
));
2068 if (!len_value
&& GetLastError() == ERROR_ENVVAR_NOT_FOUND
) {
2074 len_value
= len_value
* 3 + 1;
2075 /* We cannot use xcalloc() here because that uses getenv() itself */
2076 value
= calloc(len_value
, sizeof(char));
2078 die("Out of memory, (tried to allocate %"PRIuMAX
" bytes)",
2079 (uintmax_t)len_value
);
2080 xwcstoutf(value
, w_value
, len_value
);
2083 * We return `value` which is an allocated value and the caller is NOT
2084 * expecting to have to free it, so we keep a round-robin array,
2085 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
2087 free(values
[value_counter
]);
2088 values
[value_counter
++] = value
;
2089 if (value_counter
>= ARRAY_SIZE(values
))
2095 int mingw_putenv(const char *namevalue
)
2098 wchar_t *wide
, *equal
;
2101 if (!namevalue
|| !*namevalue
)
2104 size
= strlen(namevalue
) * 2 + 1;
2105 wide
= calloc(size
, sizeof(wchar_t));
2107 die("Out of memory, (tried to allocate %" PRIuMAX
" wchar_t's)",
2109 xutftowcs(wide
, namevalue
, size
);
2110 equal
= wcschr(wide
, L
'=');
2112 result
= SetEnvironmentVariableW(wide
, NULL
);
2115 result
= SetEnvironmentVariableW(wide
, equal
+ 1);
2120 errno
= err_win_to_posix(GetLastError());
2122 return result
? 0 : -1;
2125 static void ensure_socket_initialization(void)
2128 static int initialized
= 0;
2133 if (WSAStartup(MAKEWORD(2,2), &wsa
))
2134 die("unable to initialize winsock subsystem, error %d",
2137 atexit((void(*)(void)) WSACleanup
);
2142 int mingw_gethostname(char *name
, int namelen
)
2144 ensure_socket_initialization();
2145 return gethostname(name
, namelen
);
2148 #undef gethostbyname
2149 struct hostent
*mingw_gethostbyname(const char *host
)
2151 ensure_socket_initialization();
2152 return gethostbyname(host
);
2156 int mingw_getaddrinfo(const char *node
, const char *service
,
2157 const struct addrinfo
*hints
, struct addrinfo
**res
)
2159 ensure_socket_initialization();
2160 return getaddrinfo(node
, service
, hints
, res
);
2163 int mingw_socket(int domain
, int type
, int protocol
)
2168 ensure_socket_initialization();
2169 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
2170 if (s
== INVALID_SOCKET
) {
2172 * WSAGetLastError() values are regular BSD error codes
2173 * biased by WSABASEERR.
2174 * However, strerror() does not know about networking
2175 * specific errors, which are values beginning at 38 or so.
2176 * Therefore, we choose to leave the biased error code
2177 * in errno so that _if_ someone looks up the code somewhere,
2178 * then it is at least the number that are usually listed.
2180 errno
= WSAGetLastError();
2183 /* convert into a file descriptor */
2184 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
2186 return error("unable to make a socket file descriptor: %s",
2193 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2195 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2196 return connect(s
, sa
, sz
);
2200 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
2202 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2203 return bind(s
, sa
, sz
);
2207 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
2209 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2210 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
2214 int mingw_shutdown(int sockfd
, int how
)
2216 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2217 return shutdown(s
, how
);
2221 int mingw_listen(int sockfd
, int backlog
)
2223 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
2224 return listen(s
, backlog
);
2228 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
2232 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
2233 SOCKET s2
= accept(s1
, sa
, sz
);
2235 /* convert into a file descriptor */
2236 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
2239 return error("unable to make a socket file descriptor: %s",
2246 int mingw_rename(const char *pold
, const char *pnew
)
2248 static int supports_file_rename_info_ex
= 1;
2251 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
2254 if (xutftowcs_path(wpold
, pold
) < 0)
2256 wpnew_len
= xutftowcs_path(wpnew
, pnew
);
2261 * Try native rename() first to get errno right.
2262 * It is based on MoveFile(), which cannot overwrite existing files.
2264 if (!_wrename(wpold
, wpnew
))
2266 if (errno
!= EEXIST
)
2270 if (supports_file_rename_info_ex
) {
2272 * Our minimum required Windows version is still set to Windows
2273 * Vista. We thus have to declare required infrastructure for
2274 * FileRenameInfoEx ourselves until we bump _WIN32_WINNT to
2275 * 0x0A00. Furthermore, we have to handle cases where the
2276 * FileRenameInfoEx call isn't supported yet.
2278 #define FILE_RENAME_FLAG_REPLACE_IF_EXISTS 0x00000001
2279 #define FILE_RENAME_FLAG_POSIX_SEMANTICS 0x00000002
2280 FILE_INFO_BY_HANDLE_CLASS FileRenameInfoEx
= 22;
2283 * This is usually an unnamed union, but that is not
2284 * part of ISO C99. We thus inline the field, as we
2285 * really only care for the Flags field anyway.
2288 HANDLE RootDirectory
;
2289 DWORD FileNameLength
;
2291 * The actual structure is defined with a single-character
2292 * flex array so that the structure has to be allocated on
2293 * the heap. As we declare this structure ourselves though
2294 * we can avoid the allocation and define FileName to have
2297 WCHAR FileName
[MAX_PATH
];
2298 } rename_info
= { 0 };
2299 HANDLE old_handle
= INVALID_HANDLE_VALUE
;
2302 old_handle
= CreateFileW(wpold
, DELETE
,
2303 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2304 NULL
, OPEN_EXISTING
,
2305 FILE_FLAG_BACKUP_SEMANTICS
| FILE_FLAG_OPEN_REPARSE_POINT
,
2307 if (old_handle
== INVALID_HANDLE_VALUE
) {
2308 errno
= err_win_to_posix(GetLastError());
2312 rename_info
.Flags
= FILE_RENAME_FLAG_REPLACE_IF_EXISTS
|
2313 FILE_RENAME_FLAG_POSIX_SEMANTICS
;
2314 rename_info
.FileNameLength
= wpnew_len
* sizeof(WCHAR
);
2315 memcpy(rename_info
.FileName
, wpnew
, wpnew_len
* sizeof(WCHAR
));
2317 success
= SetFileInformationByHandle(old_handle
, FileRenameInfoEx
,
2318 &rename_info
, sizeof(rename_info
));
2319 gle
= GetLastError();
2320 CloseHandle(old_handle
);
2325 * When we see ERROR_INVALID_PARAMETER we can assume that the
2326 * current system doesn't support FileRenameInfoEx. Keep us
2327 * from using it in future calls and retry.
2329 if (gle
== ERROR_INVALID_PARAMETER
) {
2330 supports_file_rename_info_ex
= 0;
2335 * In theory, we shouldn't get ERROR_ACCESS_DENIED because we
2336 * always open files with FILE_SHARE_DELETE But in practice we
2337 * cannot assume that Git is the only one accessing files, and
2338 * other applications may not set FILE_SHARE_DELETE. So we have
2342 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2344 gle
= GetLastError();
2347 /* TODO: translate more errors */
2348 if (gle
== ERROR_ACCESS_DENIED
&&
2349 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
2350 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
2351 DWORD attrsold
= GetFileAttributesW(wpold
);
2352 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
2353 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
2355 else if (!_wrmdir(wpnew
))
2359 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
2360 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
2361 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
2363 gle
= GetLastError();
2364 /* revert file attributes on failure */
2365 SetFileAttributesW(wpnew
, attrs
);
2368 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
2370 * We assume that some other process had the source or
2371 * destination file open at the wrong moment and retry.
2372 * In order to give the other process a higher chance to
2373 * complete its operation, we give up our time slice now.
2374 * If we have to retry again, we do sleep a bit.
2376 Sleep(delay
[tries
]);
2380 if (gle
== ERROR_ACCESS_DENIED
&&
2381 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2382 "Should I try again?", pold
, pnew
))
2390 * Note that this doesn't return the actual pagesize, but
2391 * the allocation granularity. If future Windows specific git code
2392 * needs the real getpagesize function, we need to find another solution.
2394 int mingw_getpagesize(void)
2398 return si
.dwAllocationGranularity
;
2401 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2402 enum EXTENDED_NAME_FORMAT
{
2404 NameUserPrincipal
= 8
2407 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
2409 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, SEC_ENTRY
, GetUserNameExW
,
2410 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
2411 static wchar_t wbuffer
[1024];
2414 if (!INIT_PROC_ADDR(GetUserNameExW
))
2417 len
= ARRAY_SIZE(wbuffer
);
2418 if (GetUserNameExW(type
, wbuffer
, &len
)) {
2419 char *converted
= xmalloc((len
*= 3));
2420 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
2428 char *mingw_query_user_email(void)
2430 return get_extended_user_info(NameUserPrincipal
);
2433 struct passwd
*getpwuid(int uid UNUSED
)
2435 static unsigned initialized
;
2436 static char user_name
[100];
2437 static struct passwd
*p
;
2444 len
= ARRAY_SIZE(buf
);
2445 if (!GetUserNameW(buf
, &len
)) {
2450 if (xwcstoutf(user_name
, buf
, sizeof(user_name
)) < 0) {
2455 p
= xmalloc(sizeof(*p
));
2456 p
->pw_name
= user_name
;
2457 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
2460 * Data returned by getpwuid(3P) is treated as internal and
2461 * must never be written to or freed.
2463 p
->pw_gecos
= (char *) "unknown";
2470 static HANDLE timer_event
;
2471 static HANDLE timer_thread
;
2472 static int timer_interval
;
2473 static int one_shot
;
2474 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
2476 /* The timer works like this:
2477 * The thread, ticktack(), is a trivial routine that most of the time
2478 * only waits to receive the signal to terminate. The main thread tells
2479 * the thread to terminate by setting the timer_event to the signalled
2481 * But ticktack() interrupts the wait state after the timer's interval
2482 * length to call the signal handler.
2485 static unsigned __stdcall
ticktack(void *dummy UNUSED
)
2487 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
2488 mingw_raise(SIGALRM
);
2495 static int start_timer_thread(void)
2497 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2499 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
2501 return errno
= ENOMEM
,
2502 error("cannot start timer thread");
2504 return errno
= ENOMEM
,
2505 error("cannot allocate resources for timer");
2509 static void stop_timer_thread(void)
2512 SetEvent(timer_event
); /* tell thread to terminate */
2514 int rc
= WaitForSingleObject(timer_thread
, 10000);
2515 if (rc
== WAIT_TIMEOUT
)
2516 error("timer thread did not terminate timely");
2517 else if (rc
!= WAIT_OBJECT_0
)
2518 error("waiting for timer thread failed: %lu",
2520 CloseHandle(timer_thread
);
2523 CloseHandle(timer_event
);
2525 timer_thread
= NULL
;
2528 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
2530 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
2533 int setitimer(int type UNUSED
, struct itimerval
*in
, struct itimerval
*out
)
2535 static const struct timeval zero
;
2536 static int atexit_done
;
2539 return errno
= EINVAL
,
2540 error("setitimer param 3 != NULL not implemented");
2541 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
2542 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
2543 return errno
= EINVAL
,
2544 error("setitimer: it_interval must be zero or eq it_value");
2547 stop_timer_thread();
2549 if (is_timeval_eq(&in
->it_value
, &zero
) &&
2550 is_timeval_eq(&in
->it_interval
, &zero
))
2553 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
2554 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
2556 atexit(stop_timer_thread
);
2559 return start_timer_thread();
2562 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2565 return errno
= EINVAL
,
2566 error("sigaction only implemented for SIGALRM");
2568 return errno
= EINVAL
,
2569 error("sigaction: param 3 != NULL not implemented");
2571 timer_fn
= in
->sa_handler
;
2576 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2588 sigint_fn
= handler
;
2592 return signal(sig
, handler
);
2599 int mingw_raise(int sig
)
2603 if (timer_fn
== SIG_DFL
) {
2604 if (isatty(STDERR_FILENO
))
2605 fputs("Alarm clock\n", stderr
);
2606 exit(128 + SIGALRM
);
2607 } else if (timer_fn
!= SIG_IGN
)
2612 if (sigint_fn
== SIG_DFL
)
2614 else if (sigint_fn
!= SIG_IGN
)
2618 #if defined(_MSC_VER)
2625 case SIGABRT_COMPAT
:
2627 * The <signal.h> header in the MS C Runtime defines 8 signals
2628 * as being supported on the platform. Anything else causes an
2629 * "Invalid signal or error" (which in DEBUG builds causes the
2630 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2631 * already know will fail.
2648 int link(const char *oldpath
, const char *newpath
)
2650 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2651 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2652 xutftowcs_path(wnewpath
, newpath
) < 0)
2655 if (!CreateHardLinkW(wnewpath
, woldpath
, NULL
)) {
2656 errno
= err_win_to_posix(GetLastError());
2662 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2664 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2671 if (pid
> 0 && options
& WNOHANG
) {
2672 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2676 options
&= ~WNOHANG
;
2680 struct pinfo_t
**ppinfo
;
2681 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2687 GetExitCodeProcess(h
, (LPDWORD
)status
);
2689 EnterCriticalSection(&pinfo_cs
);
2693 struct pinfo_t
*info
= *ppinfo
;
2694 if (info
->pid
== pid
) {
2695 CloseHandle(info
->proc
);
2696 *ppinfo
= info
->next
;
2700 ppinfo
= &info
->next
;
2703 LeaveCriticalSection(&pinfo_cs
);
2714 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2716 int upos
= 0, wpos
= 0;
2717 const unsigned char *utf
= (const unsigned char*) utfs
;
2718 if (!utf
|| !wcs
|| wcslen
< 1) {
2722 /* reserve space for \0 */
2727 while (upos
< utflen
) {
2728 int c
= utf
[upos
++] & 0xff;
2729 if (utflen
== INT_MAX
&& c
== 0)
2732 if (wpos
>= wcslen
) {
2741 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2742 (utf
[upos
] & 0xc0) == 0x80) {
2744 c
= ((c
& 0x1f) << 6);
2745 c
|= (utf
[upos
++] & 0x3f);
2747 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2748 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2749 (utf
[upos
] & 0xc0) == 0x80 &&
2750 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2752 c
= ((c
& 0x0f) << 12);
2753 c
|= ((utf
[upos
++] & 0x3f) << 6);
2754 c
|= (utf
[upos
++] & 0x3f);
2756 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2757 wpos
+ 1 < wcslen
&&
2758 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2759 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2760 (utf
[upos
] & 0xc0) == 0x80 &&
2761 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2762 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2763 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2764 c
= ((c
& 0x07) << 18);
2765 c
|= ((utf
[upos
++] & 0x3f) << 12);
2766 c
|= ((utf
[upos
++] & 0x3f) << 6);
2767 c
|= (utf
[upos
++] & 0x3f);
2769 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2770 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2771 } else if (c
>= 0xa0) {
2772 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2775 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2776 static const char *hex
= "0123456789abcdef";
2777 wcs
[wpos
++] = hex
[c
>> 4];
2779 wcs
[wpos
++] = hex
[c
& 0x0f];
2786 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2788 if (!wcs
|| !utf
|| utflen
< 1) {
2792 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2799 static void setup_windows_environment(void)
2801 char *tmp
= getenv("TMPDIR");
2803 /* on Windows it is TMP and TEMP */
2805 if (!(tmp
= getenv("TMP")))
2806 tmp
= getenv("TEMP");
2808 setenv("TMPDIR", tmp
, 1);
2809 tmp
= getenv("TMPDIR");
2815 * Convert all dir separators to forward slashes,
2816 * to help shell commands called from the Git
2817 * executable (by not mistaking the dir separators
2818 * for escape characters).
2820 convert_slashes(tmp
);
2823 /* simulate TERM to enable auto-color (see color.c) */
2824 if (!getenv("TERM"))
2825 setenv("TERM", "cygwin", 1);
2827 /* calculate HOME if not set */
2828 if (!getenv("HOME")) {
2830 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2831 * location, thus also check if the path exists (i.e. is not
2834 if ((tmp
= getenv("HOMEDRIVE"))) {
2835 struct strbuf buf
= STRBUF_INIT
;
2836 strbuf_addstr(&buf
, tmp
);
2837 if ((tmp
= getenv("HOMEPATH"))) {
2838 strbuf_addstr(&buf
, tmp
);
2839 if (is_directory(buf
.buf
))
2840 setenv("HOME", buf
.buf
, 1);
2842 tmp
= NULL
; /* use $USERPROFILE */
2844 strbuf_release(&buf
);
2846 /* use $USERPROFILE if the home share is not available */
2847 if (!tmp
&& (tmp
= getenv("USERPROFILE")))
2848 setenv("HOME", tmp
, 1);
2852 static void get_current_user_sid(PSID
*sid
, HANDLE
*linked_token
)
2856 TOKEN_ELEVATION_TYPE elevationType
;
2860 *linked_token
= NULL
;
2862 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &token
))
2865 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &len
)) {
2866 TOKEN_USER
*info
= xmalloc((size_t)len
);
2867 if (GetTokenInformation(token
, TokenUser
, info
, len
, &len
)) {
2868 len
= GetLengthSid(info
->User
.Sid
);
2869 *sid
= xmalloc(len
);
2870 if (!CopySid(len
, *sid
, info
->User
.Sid
)) {
2871 error(_("failed to copy SID (%ld)"),
2873 FREE_AND_NULL(*sid
);
2876 FREE_AND_NULL(info
);
2879 if (GetTokenInformation(token
, TokenElevationType
, &elevationType
, sizeof(elevationType
), &size
) &&
2880 elevationType
== TokenElevationTypeLimited
) {
2882 * The current process is run by a member of the Administrators
2883 * group, but is not running elevated.
2885 if (!GetTokenInformation(token
, TokenLinkedToken
, linked_token
, sizeof(*linked_token
), &size
))
2886 linked_token
= NULL
; /* there is no linked token */
2892 static BOOL
user_sid_to_user_name(PSID sid
, LPSTR
*str
)
2894 SID_NAME_USE pe_use
;
2895 DWORD len_user
= 0, len_domain
= 0;
2896 BOOL translate_sid_to_user
;
2899 * returns only FALSE, because the string pointers are NULL
2901 LookupAccountSidA(NULL
, sid
, NULL
, &len_user
, NULL
, &len_domain
,
2904 * Alloc needed space of the strings
2906 ALLOC_ARRAY((*str
), (size_t)len_domain
+ (size_t)len_user
);
2907 translate_sid_to_user
= LookupAccountSidA(NULL
, sid
,
2908 (*str
) + len_domain
, &len_user
, *str
, &len_domain
, &pe_use
);
2909 if (!translate_sid_to_user
)
2910 FREE_AND_NULL(*str
);
2912 (*str
)[len_domain
] = '/';
2913 return translate_sid_to_user
;
2916 static int acls_supported(const char *path
)
2918 size_t offset
= offset_1st_component(path
);
2919 WCHAR wroot
[MAX_PATH
];
2920 DWORD file_system_flags
;
2923 xutftowcsn(wroot
, path
, MAX_PATH
, offset
) > 0 &&
2924 GetVolumeInformationW(wroot
, NULL
, 0, NULL
, NULL
,
2925 &file_system_flags
, NULL
, 0))
2926 return !!(file_system_flags
& FILE_PERSISTENT_ACLS
);
2931 int is_path_owned_by_current_sid(const char *path
, struct strbuf
*report
)
2933 WCHAR wpath
[MAX_PATH
];
2935 PSECURITY_DESCRIPTOR descriptor
= NULL
;
2938 static wchar_t home
[MAX_PATH
];
2942 if (xutftowcs_path(wpath
, path
) < 0)
2946 * On Windows, the home directory is owned by the administrator, but for
2947 * all practical purposes, it belongs to the user. Do pretend that it is
2948 * owned by the user.
2951 DWORD size
= ARRAY_SIZE(home
);
2952 DWORD len
= GetEnvironmentVariableW(L
"HOME", home
, size
);
2953 if (!len
|| len
> size
)
2954 wcscpy(home
, L
"::N/A::");
2956 if (!wcsicmp(wpath
, home
))
2959 /* Get the owner SID */
2960 err
= GetNamedSecurityInfoW(wpath
, SE_FILE_OBJECT
,
2961 OWNER_SECURITY_INFORMATION
|
2962 DACL_SECURITY_INFORMATION
,
2963 &sid
, NULL
, NULL
, NULL
, &descriptor
);
2965 if (err
!= ERROR_SUCCESS
)
2966 error(_("failed to get owner for '%s' (%ld)"), path
, err
);
2967 else if (sid
&& IsValidSid(sid
)) {
2968 /* Now, verify that the SID matches the current user's */
2969 static PSID current_user_sid
;
2970 static HANDLE linked_token
;
2973 if (!current_user_sid
)
2974 get_current_user_sid(¤t_user_sid
, &linked_token
);
2976 if (current_user_sid
&&
2977 IsValidSid(current_user_sid
) &&
2978 EqualSid(sid
, current_user_sid
))
2980 else if (IsWellKnownSid(sid
, WinBuiltinAdministratorsSid
) &&
2981 ((CheckTokenMembership(NULL
, sid
, &is_member
) &&
2984 CheckTokenMembership(linked_token
, sid
, &is_member
) &&
2987 * If owned by the Administrators group, and the
2988 * current user is an administrator, we consider that
2993 IsWellKnownSid(sid
, WinWorldSid
) &&
2994 !acls_supported(path
)) {
2996 * On FAT32 volumes, ownership is not actually recorded.
2998 strbuf_addf(report
, "'%s' is on a file system that does "
2999 "not record ownership\n", path
);
3000 } else if (report
) {
3001 PCSTR str1
, str2
, str3
, str4
;
3002 LPSTR to_free1
= NULL
, to_free3
= NULL
,
3003 to_local_free2
= NULL
, to_local_free4
= NULL
;
3005 if (user_sid_to_user_name(sid
, &to_free1
))
3008 str1
= "(inconvertible)";
3009 if (ConvertSidToStringSidA(sid
, &to_local_free2
))
3010 str2
= to_local_free2
;
3012 str2
= "(inconvertible)";
3014 if (!current_user_sid
) {
3018 else if (!IsValidSid(current_user_sid
)) {
3022 if (user_sid_to_user_name(current_user_sid
,
3026 str3
= "(inconvertible)";
3027 if (ConvertSidToStringSidA(current_user_sid
,
3029 str4
= to_local_free4
;
3031 str4
= "(inconvertible)";
3034 "'%s' is owned by:\n"
3035 "\t%s (%s)\nbut the current user is:\n"
3037 path
, str1
, str2
, str3
, str4
);
3039 LocalFree(to_local_free2
);
3041 LocalFree(to_local_free4
);
3046 * We can release the security descriptor struct only now because `sid`
3047 * actually points into this struct.
3050 LocalFree(descriptor
);
3055 int is_valid_win32_path(const char *path
, int allow_literal_nul
)
3057 const char *p
= path
;
3058 int preceding_space_or_period
= 0, i
= 0, periods
= 0;
3063 skip_dos_drive_prefix((char **)&path
);
3070 case '/': case '\\':
3071 /* cannot end in ` ` or `.`, except for `.` and `..` */
3072 if (preceding_space_or_period
&&
3073 (i
!= periods
|| periods
> 2))
3078 i
= periods
= preceding_space_or_period
= 0;
3082 case 'a': case 'A': /* AUX */
3083 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
3084 ((c
= path
[++i
]) != 'x' && c
!= 'X')) {
3085 not_a_reserved_name
:
3091 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
3092 if ((c
= path
[++i
]) != 'o' && c
!= 'O')
3093 goto not_a_reserved_name
;
3095 if (c
== 'm' || c
== 'M') { /* COM1 ... COM9 */
3097 if (c
< '1' || c
> '9')
3098 goto not_a_reserved_name
;
3099 } else if (c
== 'n' || c
== 'N') { /* CON */
3101 if ((c
== 'i' || c
== 'I') &&
3102 ((c
= path
[i
+ 2]) == 'n' ||
3105 i
+= 3; /* CONIN$ */
3106 else if ((c
== 'o' || c
== 'O') &&
3107 ((c
= path
[i
+ 2]) == 'u' ||
3109 ((c
= path
[i
+ 3]) == 't' ||
3112 i
+= 4; /* CONOUT$ */
3114 goto not_a_reserved_name
;
3116 case 'l': case 'L': /* LPT<N> */
3117 if (((c
= path
[++i
]) != 'p' && c
!= 'P') ||
3118 ((c
= path
[++i
]) != 't' && c
!= 'T') ||
3119 !isdigit(path
[++i
]))
3120 goto not_a_reserved_name
;
3122 case 'n': case 'N': /* NUL */
3123 if (((c
= path
[++i
]) != 'u' && c
!= 'U') ||
3124 ((c
= path
[++i
]) != 'l' && c
!= 'L') ||
3125 (allow_literal_nul
&&
3126 !path
[i
+ 1] && p
== path
))
3127 goto not_a_reserved_name
;
3129 case 'p': case 'P': /* PRN */
3130 if (((c
= path
[++i
]) != 'r' && c
!= 'R') ||
3131 ((c
= path
[++i
]) != 'n' && c
!= 'N'))
3132 goto not_a_reserved_name
;
3139 * So far, this looks like a reserved name. Let's see
3140 * whether it actually is one: trailing spaces, a file
3141 * extension, or an NTFS Alternate Data Stream do not
3142 * matter, the name is still reserved if any of those
3143 * follow immediately after the actual name.
3146 if (path
[i
] == ' ') {
3147 preceding_space_or_period
= 1;
3148 while (path
[++i
] == ' ')
3149 ; /* skip all spaces */
3153 if (c
&& c
!= '.' && c
!= ':' && !is_xplatform_dir_sep(c
))
3154 goto not_a_reserved_name
;
3156 /* contains reserved name */
3162 preceding_space_or_period
= 1;
3165 case ':': /* DOS drive prefix was already skipped */
3166 case '<': case '>': case '"': case '|': case '?': case '*':
3167 /* illegal character */
3170 if (c
> '\0' && c
< '\x20')
3171 /* illegal character */
3174 preceding_space_or_period
= 0;
3179 #if !defined(_MSC_VER)
3181 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
3182 * mingw startup code, see init.c in mingw runtime).
3187 static NORETURN
void die_startup(void)
3189 fputs("fatal: not enough memory for initialization", stderr
);
3193 static void *malloc_startup(size_t size
)
3195 void *result
= malloc(size
);
3201 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
3203 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
3204 return memcpy(malloc_startup(len
), buffer
, len
);
3207 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
3208 DWORD desired_access
, DWORD flags
)
3210 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
3211 wchar_t buf
[MAX_PATH
];
3212 DWORD max
= ARRAY_SIZE(buf
);
3214 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
3216 if (!ret
|| ret
>= max
)
3219 /* make sure this does not leak into child processes */
3220 SetEnvironmentVariableW(key
, NULL
);
3221 if (!wcscmp(buf
, L
"off")) {
3223 handle
= GetStdHandle(std_id
);
3224 if (handle
!= INVALID_HANDLE_VALUE
)
3225 CloseHandle(handle
);
3228 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
3229 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
3230 if (handle
== INVALID_HANDLE_VALUE
) {
3232 handle
= GetStdHandle(std_id
);
3233 if (handle
!= INVALID_HANDLE_VALUE
)
3234 CloseHandle(handle
);
3236 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
3237 SetStdHandle(std_id
, handle
);
3239 /* do *not* close the new_fd: that would close stdout */
3243 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
3245 if (handle
!= INVALID_HANDLE_VALUE
) {
3246 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
3247 SetStdHandle(std_id
, handle
);
3253 static void maybe_redirect_std_handles(void)
3255 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
3256 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
3257 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
3258 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
3259 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
3260 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
3270 * We implement wmain() and compile with -municode, which would
3271 * normally ignore main(), but we call the latter from the former
3272 * so that we can handle non-ASCII command-line parameters
3275 * To be more compatible with the core git code, we convert
3276 * argv into UTF8 and pass them directly to main().
3278 int wmain(int argc
, const wchar_t **wargv
)
3282 char *buffer
, **save
;
3285 trace2_initialize_clock();
3289 _CrtSetReportMode(_CRT_ASSERT
, _CRTDBG_MODE_DEBUG
);
3292 #ifdef USE_MSVC_CRTDBG
3293 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF
| _CRTDBG_LEAK_CHECK_DF
);
3297 maybe_redirect_std_handles();
3299 /* determine size of argv and environ conversion buffer */
3300 maxlen
= wcslen(wargv
[0]);
3301 for (i
= 1; i
< argc
; i
++)
3302 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
3304 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3305 maxlen
= 3 * maxlen
+ 1;
3306 buffer
= malloc_startup(maxlen
);
3309 * Create a UTF-8 version of w_argv. Also create a "save" copy
3310 * to remember all the string pointers because parse_options()
3311 * will remove claimed items from the argv that we pass down.
3313 ALLOC_ARRAY(argv
, argc
+ 1);
3314 ALLOC_ARRAY(save
, argc
+ 1);
3315 for (i
= 0; i
< argc
; i
++)
3316 argv
[i
] = save
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
3317 argv
[i
] = save
[i
] = NULL
;
3320 /* fix Windows specific environment settings */
3321 setup_windows_environment();
3323 unset_environment_variables
= xstrdup("PERL5LIB");
3325 /* initialize critical section for waitpid pinfo_t list */
3326 InitializeCriticalSection(&pinfo_cs
);
3328 /* set up default file mode and file modes for stdin/out/err */
3330 _setmode(_fileno(stdin
), _O_BINARY
);
3331 _setmode(_fileno(stdout
), _O_BINARY
);
3332 _setmode(_fileno(stderr
), _O_BINARY
);
3334 /* initialize Unicode console */
3337 /* invoke the real main() using our utf8 version of argv. */
3338 exit_status
= main(argc
, argv
);
3340 for (i
= 0; i
< argc
; i
++)
3348 int uname(struct utsname
*buf
)
3350 unsigned v
= (unsigned)GetVersion();
3351 memset(buf
, 0, sizeof(*buf
));
3352 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
3353 xsnprintf(buf
->release
, sizeof(buf
->release
),
3354 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
3355 /* assuming NT variants only.. */
3356 xsnprintf(buf
->version
, sizeof(buf
->version
),
3357 "%u", (v
>> 16) & 0x7fff);
3361 #ifndef NO_UNIX_SOCKETS
3362 int mingw_have_unix_sockets(void)
3364 SC_HANDLE scm
, srvc
;
3365 SERVICE_STATUS_PROCESS status
;
3368 scm
= OpenSCManagerA(NULL
, NULL
, SC_MANAGER_CONNECT
);
3370 srvc
= OpenServiceA(scm
, "afunix", SERVICE_QUERY_STATUS
);
3372 if(QueryServiceStatusEx(srvc
, SC_STATUS_PROCESS_INFO
, (LPBYTE
)&status
, sizeof(SERVICE_STATUS_PROCESS
), &bytes
))
3373 ret
= status
.dwCurrentState
== SERVICE_RUNNING
;
3374 CloseServiceHandle(srvc
);
3376 CloseServiceHandle(scm
);