1 #include "../git-compat-util.h"
6 #include "../run-command.h"
8 #include "win32/lazyload.h"
10 #define HCAST(type, handle) ((type)(intptr_t)handle)
12 static const int delay
[] = { 0, 1, 10, 20, 40 };
14 int err_win_to_posix(DWORD winerr
)
18 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
19 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
20 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
21 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
22 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
23 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
24 case ERROR_BAD_COMMAND
: error
= EIO
; break;
25 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
26 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
27 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
28 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
29 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
30 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
31 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
32 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
33 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
34 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
35 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
36 case ERROR_BUSY
: error
= EBUSY
; break;
37 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
38 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
39 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
40 case ERROR_CANTOPEN
: error
= EIO
; break;
41 case ERROR_CANTREAD
: error
= EIO
; break;
42 case ERROR_CANTWRITE
: error
= EIO
; break;
43 case ERROR_CRC
: error
= EIO
; break;
44 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
45 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
46 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
47 case ERROR_DIRECTORY
: error
= EINVAL
; break;
48 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
49 case ERROR_DISK_CHANGE
: error
= EIO
; break;
50 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
51 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
52 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
53 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
54 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
55 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
56 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
57 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
58 case ERROR_GEN_FAILURE
: error
= EIO
; break;
59 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
60 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
61 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
62 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
63 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
64 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
65 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
66 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
67 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
68 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
69 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
70 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
71 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
72 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
73 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
74 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
75 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
76 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
77 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
78 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
79 case ERROR_IO_DEVICE
: error
= EIO
; break;
80 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
81 case ERROR_LOCKED
: error
= EBUSY
; break;
82 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
83 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
84 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
85 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
86 case ERROR_MORE_DATA
: error
= EPIPE
; break;
87 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
88 case ERROR_NOACCESS
: error
= EFAULT
; break;
89 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
90 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
91 case ERROR_NOT_READY
: error
= EAGAIN
; break;
92 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
93 case ERROR_NO_DATA
: error
= EPIPE
; break;
94 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
95 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
96 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
97 case ERROR_OPEN_FAILED
: error
= EIO
; break;
98 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
99 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
100 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
101 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
102 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
103 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
104 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
105 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
106 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
107 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
108 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
109 case ERROR_READ_FAULT
: error
= EIO
; break;
110 case ERROR_SEEK
: error
= EIO
; break;
111 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
112 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
113 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
114 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
115 case ERROR_SWAPERROR
: error
= ENOENT
; break;
116 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
117 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
118 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
119 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
120 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
121 case ERROR_WRITE_FAULT
: error
= EIO
; break;
122 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
127 static inline int is_file_in_use_error(DWORD errcode
)
130 case ERROR_SHARING_VIOLATION
:
131 case ERROR_ACCESS_DENIED
:
138 static int read_yes_no_answer(void)
142 if (fgets(answer
, sizeof(answer
), stdin
)) {
143 size_t answer_len
= strlen(answer
);
144 int got_full_line
= 0, c
;
146 /* remove the newline */
147 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
148 answer
[answer_len
-2] = '\0';
150 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
151 answer
[answer_len
-1] = '\0';
154 /* flush the buffer in case we did not get the full line */
156 while ((c
= getchar()) != EOF
&& c
!= '\n')
159 /* we could not read, return the
160 * default answer which is no */
163 if (tolower(answer
[0]) == 'y' && !answer
[1])
165 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
167 if (tolower(answer
[0]) == 'n' && !answer
[1])
169 if (!strncasecmp(answer
, "no", sizeof(answer
)))
172 /* did not find an answer we understand */
176 static int ask_yes_no_if_possible(const char *format
, ...)
179 const char *retry_hook
[] = { NULL
, NULL
, NULL
};
182 va_start(args
, format
);
183 vsnprintf(question
, sizeof(question
), format
, args
);
186 if ((retry_hook
[0] = mingw_getenv("GIT_ASK_YESNO"))) {
187 retry_hook
[1] = question
;
188 return !run_command_v_opt(retry_hook
, 0);
191 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
196 fprintf(stderr
, "%s (y/n) ", question
);
198 if ((answer
= read_yes_no_answer()) >= 0)
201 fprintf(stderr
, "Sorry, I did not understand your answer. "
202 "Please type 'y' or 'n'\n");
206 int mingw_core_config(const char *var
, const char *value
, void *cb
)
211 /* Normalizes NT paths as returned by some low-level APIs. */
212 static wchar_t *normalize_ntpath(wchar_t *wbuf
)
215 /* fix absolute path prefixes */
216 if (wbuf
[0] == '\\') {
217 /* strip NT namespace prefixes */
218 if (!wcsncmp(wbuf
, L
"\\??\\", 4) ||
219 !wcsncmp(wbuf
, L
"\\\\?\\", 4))
221 else if (!wcsnicmp(wbuf
, L
"\\DosDevices\\", 12))
223 /* replace remaining '...UNC\' with '\\' */
224 if (!wcsnicmp(wbuf
, L
"UNC\\", 4)) {
229 /* convert backslashes to slashes */
230 for (i
= 0; wbuf
[i
]; i
++)
236 int mingw_unlink(const char *pathname
)
239 wchar_t wpathname
[MAX_PATH
];
240 if (xutftowcs_path(wpathname
, pathname
) < 0)
243 /* read-only files cannot be removed */
244 _wchmod(wpathname
, 0666);
245 while ((ret
= _wunlink(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
246 if (!is_file_in_use_error(GetLastError()))
249 * We assume that some other process had the source or
250 * destination file open at the wrong moment and retry.
251 * In order to give the other process a higher chance to
252 * complete its operation, we give up our time slice now.
253 * If we have to retry again, we do sleep a bit.
258 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
259 ask_yes_no_if_possible("Unlink of file '%s' failed. "
260 "Should I try again?", pathname
))
261 ret
= _wunlink(wpathname
);
265 static int is_dir_empty(const wchar_t *wpath
)
267 WIN32_FIND_DATAW findbuf
;
269 wchar_t wbuf
[MAX_PATH
+ 2];
271 wcscat(wbuf
, L
"\\*");
272 handle
= FindFirstFileW(wbuf
, &findbuf
);
273 if (handle
== INVALID_HANDLE_VALUE
)
274 return GetLastError() == ERROR_NO_MORE_FILES
;
276 while (!wcscmp(findbuf
.cFileName
, L
".") ||
277 !wcscmp(findbuf
.cFileName
, L
".."))
278 if (!FindNextFileW(handle
, &findbuf
)) {
279 DWORD err
= GetLastError();
281 return err
== ERROR_NO_MORE_FILES
;
287 int mingw_rmdir(const char *pathname
)
290 wchar_t wpathname
[MAX_PATH
];
291 if (xutftowcs_path(wpathname
, pathname
) < 0)
294 while ((ret
= _wrmdir(wpathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
295 if (!is_file_in_use_error(GetLastError()))
296 errno
= err_win_to_posix(GetLastError());
299 if (!is_dir_empty(wpathname
)) {
304 * We assume that some other process had the source or
305 * destination file open at the wrong moment and retry.
306 * In order to give the other process a higher chance to
307 * complete its operation, we give up our time slice now.
308 * If we have to retry again, we do sleep a bit.
313 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
314 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
315 "Should I try again?", pathname
))
316 ret
= _wrmdir(wpathname
);
320 static inline int needs_hiding(const char *path
)
322 const char *basename
;
324 if (hide_dotfiles
== HIDE_DOTFILES_FALSE
)
327 /* We cannot use basename(), as it would remove trailing slashes */
328 mingw_skip_dos_drive_prefix((char **)&path
);
332 for (basename
= path
; *path
; path
++)
333 if (is_dir_sep(*path
)) {
336 } while (is_dir_sep(*path
));
337 /* ignore trailing slashes */
342 if (hide_dotfiles
== HIDE_DOTFILES_TRUE
)
343 return *basename
== '.';
345 assert(hide_dotfiles
== HIDE_DOTFILES_DOTGITONLY
);
346 return !strncasecmp(".git", basename
, 4) &&
347 (!basename
[4] || is_dir_sep(basename
[4]));
350 static int set_hidden_flag(const wchar_t *path
, int set
)
352 DWORD original
= GetFileAttributesW(path
), modified
;
354 modified
= original
| FILE_ATTRIBUTE_HIDDEN
;
356 modified
= original
& ~FILE_ATTRIBUTE_HIDDEN
;
357 if (original
== modified
|| SetFileAttributesW(path
, modified
))
359 errno
= err_win_to_posix(GetLastError());
363 int mingw_mkdir(const char *path
, int mode
)
366 wchar_t wpath
[MAX_PATH
];
367 if (xutftowcs_path(wpath
, path
) < 0)
369 ret
= _wmkdir(wpath
);
370 if (!ret
&& needs_hiding(path
))
371 return set_hidden_flag(wpath
, 1);
376 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
377 * is documented in [1] as opening a writable file handle in append mode.
378 * (It is believed that) this is atomic since it is maintained by the
379 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
381 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
383 * This trick does not appear to work for named pipes. Instead it creates
384 * a named pipe client handle that cannot be written to. Callers should
385 * just use the regular _wopen() for them. (And since client handle gets
386 * bound to a unique server handle, it isn't really an issue.)
388 static int mingw_open_append(wchar_t const *wfilename
, int oflags
, ...)
392 DWORD create
= (oflags
& O_CREAT
) ? OPEN_ALWAYS
: OPEN_EXISTING
;
394 /* only these flags are supported */
395 if ((oflags
& ~O_CREAT
) != (O_WRONLY
| O_APPEND
))
396 return errno
= ENOSYS
, -1;
399 * FILE_SHARE_WRITE is required to permit child processes
400 * to append to the file.
402 handle
= CreateFileW(wfilename
, FILE_APPEND_DATA
,
403 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
404 NULL
, create
, FILE_ATTRIBUTE_NORMAL
, NULL
);
405 if (handle
== INVALID_HANDLE_VALUE
)
406 return errno
= err_win_to_posix(GetLastError()), -1;
409 * No O_APPEND here, because the CRT uses it only to reset the
410 * file pointer to EOF before each write(); but that is not
411 * necessary (and may lead to races) for a file created with
414 fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
421 * Does the pathname map to the local named pipe filesystem?
422 * That is, does it have a "//./pipe/" prefix?
424 static int is_local_named_pipe_path(const char *filename
)
426 return (is_dir_sep(filename
[0]) &&
427 is_dir_sep(filename
[1]) &&
428 filename
[2] == '.' &&
429 is_dir_sep(filename
[3]) &&
430 !strncasecmp(filename
+4, "pipe", 4) &&
431 is_dir_sep(filename
[8]) &&
435 int mingw_open (const char *filename
, int oflags
, ...)
437 typedef int (*open_fn_t
)(wchar_t const *wfilename
, int oflags
, ...);
441 wchar_t wfilename
[MAX_PATH
];
444 va_start(args
, oflags
);
445 mode
= va_arg(args
, int);
448 if (filename
&& !strcmp(filename
, "/dev/null"))
451 if ((oflags
& O_APPEND
) && !is_local_named_pipe_path(filename
))
452 open_fn
= mingw_open_append
;
456 if (xutftowcs_path(wfilename
, filename
) < 0)
458 fd
= open_fn(wfilename
, oflags
, mode
);
460 if (fd
< 0 && (oflags
& O_ACCMODE
) != O_RDONLY
&& errno
== EACCES
) {
461 DWORD attrs
= GetFileAttributesW(wfilename
);
462 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
465 if ((oflags
& O_CREAT
) && needs_hiding(filename
)) {
467 * Internally, _wopen() uses the CreateFile() API which errors
468 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
469 * specified and an already existing file's attributes do not
470 * match *exactly*. As there is no mode or flag we can set that
471 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
472 * again *without* the O_CREAT flag (that corresponds to the
473 * CREATE_ALWAYS flag of CreateFile()).
475 if (fd
< 0 && errno
== EACCES
)
476 fd
= open_fn(wfilename
, oflags
& ~O_CREAT
, mode
);
477 if (fd
>= 0 && set_hidden_flag(wfilename
, 1))
478 warning("could not mark '%s' as hidden.", filename
);
483 static BOOL WINAPI
ctrl_ignore(DWORD type
)
489 int mingw_fgetc(FILE *stream
)
492 if (!isatty(_fileno(stream
)))
493 return fgetc(stream
);
495 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
498 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
501 /* Ctrl+C was pressed, simulate SIGINT and retry */
504 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
509 FILE *mingw_fopen (const char *filename
, const char *otype
)
511 int hide
= needs_hiding(filename
);
513 wchar_t wfilename
[MAX_PATH
], wotype
[4];
514 if (filename
&& !strcmp(filename
, "/dev/null"))
516 if (xutftowcs_path(wfilename
, filename
) < 0 ||
517 xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
519 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
520 error("could not unhide %s", filename
);
523 file
= _wfopen(wfilename
, wotype
);
524 if (!file
&& GetLastError() == ERROR_INVALID_NAME
)
526 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
527 warning("could not mark '%s' as hidden.", filename
);
531 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
533 int hide
= needs_hiding(filename
);
535 wchar_t wfilename
[MAX_PATH
], wotype
[4];
536 if (filename
&& !strcmp(filename
, "/dev/null"))
538 if (xutftowcs_path(wfilename
, filename
) < 0 ||
539 xutftowcs(wotype
, otype
, ARRAY_SIZE(wotype
)) < 0)
541 if (hide
&& !access(filename
, F_OK
) && set_hidden_flag(wfilename
, 0)) {
542 error("could not unhide %s", filename
);
545 file
= _wfreopen(wfilename
, wotype
, stream
);
546 if (file
&& hide
&& set_hidden_flag(wfilename
, 1))
547 warning("could not mark '%s' as hidden.", filename
);
552 int mingw_fflush(FILE *stream
)
554 int ret
= fflush(stream
);
557 * write() is used behind the scenes of stdio output functions.
558 * Since git code does not check for errors after each stdio write
559 * operation, it can happen that write() is called by a later
560 * stdio function even if an earlier write() call failed. In the
561 * case of a pipe whose readable end was closed, only the first
562 * call to write() reports EPIPE on Windows. Subsequent write()
563 * calls report EINVAL. It is impossible to notice whether this
564 * fflush invocation triggered such a case, therefore, we have to
565 * catch all EINVAL errors whole-sale.
567 if (ret
&& errno
== EINVAL
)
574 ssize_t
mingw_write(int fd
, const void *buf
, size_t len
)
576 ssize_t result
= write(fd
, buf
, len
);
578 if (result
< 0 && errno
== EINVAL
&& buf
) {
579 /* check if fd is a pipe */
580 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
581 if (GetFileType(h
) == FILE_TYPE_PIPE
)
590 int mingw_access(const char *filename
, int mode
)
592 wchar_t wfilename
[MAX_PATH
];
593 if (xutftowcs_path(wfilename
, filename
) < 0)
595 /* X_OK is not supported by the MSVCRT version */
596 return _waccess(wfilename
, mode
& ~X_OK
);
599 int mingw_chdir(const char *dirname
)
601 wchar_t wdirname
[MAX_PATH
];
602 if (xutftowcs_path(wdirname
, dirname
) < 0)
604 return _wchdir(wdirname
);
607 int mingw_chmod(const char *filename
, int mode
)
609 wchar_t wfilename
[MAX_PATH
];
610 if (xutftowcs_path(wfilename
, filename
) < 0)
612 return _wchmod(wfilename
, mode
);
616 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
617 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
619 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
621 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
622 /* Windows to Unix Epoch conversion */
623 return winTime
- 116444736000000000LL;
626 static inline time_t filetime_to_time_t(const FILETIME
*ft
)
628 return (time_t)(filetime_to_hnsec(ft
) / 10000000);
632 * Verifies that safe_create_leading_directories() would succeed.
634 static int has_valid_directory_prefix(wchar_t *wfilename
)
636 int n
= wcslen(wfilename
);
639 wchar_t c
= wfilename
[--n
];
645 wfilename
[n
] = L
'\0';
646 attributes
= GetFileAttributesW(wfilename
);
648 if (attributes
== FILE_ATTRIBUTE_DIRECTORY
||
649 attributes
== FILE_ATTRIBUTE_DEVICE
)
651 if (attributes
== INVALID_FILE_ATTRIBUTES
)
652 switch (GetLastError()) {
653 case ERROR_PATH_NOT_FOUND
:
655 case ERROR_FILE_NOT_FOUND
:
656 /* This implies parent directory exists. */
664 /* We keep the do_lstat code in a separate function to avoid recursion.
665 * When a path ends with a slash, the stat will fail with ENOENT. In
666 * this case, we strip the trailing slashes and stat again.
668 * If follow is true then act like stat() and report on the link
669 * target. Otherwise report on the link itself.
671 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
673 WIN32_FILE_ATTRIBUTE_DATA fdata
;
674 wchar_t wfilename
[MAX_PATH
];
675 if (xutftowcs_path(wfilename
, file_name
) < 0)
678 if (GetFileAttributesExW(wfilename
, GetFileExInfoStandard
, &fdata
)) {
683 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
684 buf
->st_size
= fdata
.nFileSizeLow
|
685 (((off_t
)fdata
.nFileSizeHigh
)<<32);
686 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
687 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
688 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
689 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
690 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
691 WIN32_FIND_DATAW findbuf
;
692 HANDLE handle
= FindFirstFileW(wfilename
, &findbuf
);
693 if (handle
!= INVALID_HANDLE_VALUE
) {
694 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
695 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
697 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
698 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
700 buf
->st_mode
= S_IFLNK
;
702 buf
->st_mode
|= S_IREAD
;
703 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
704 buf
->st_mode
|= S_IWRITE
;
711 switch (GetLastError()) {
712 case ERROR_ACCESS_DENIED
:
713 case ERROR_SHARING_VIOLATION
:
714 case ERROR_LOCK_VIOLATION
:
715 case ERROR_SHARING_BUFFER_EXCEEDED
:
718 case ERROR_BUFFER_OVERFLOW
:
719 errno
= ENAMETOOLONG
;
721 case ERROR_NOT_ENOUGH_MEMORY
:
724 case ERROR_PATH_NOT_FOUND
:
725 if (!has_valid_directory_prefix(wfilename
)) {
737 /* We provide our own lstat/fstat functions, since the provided
738 * lstat/fstat functions are so slow. These stat functions are
739 * tailored for Git's usage (read: fast), and are not meant to be
740 * complete. Note that Git stat()s are redirected to mingw_lstat()
741 * too, since Windows doesn't really handle symlinks that well.
743 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
746 char alt_name
[PATH_MAX
];
748 if (!do_lstat(follow
, file_name
, buf
))
751 /* if file_name ended in a '/', Windows returned ENOENT;
752 * try again without trailing slashes
757 namelen
= strlen(file_name
);
758 if (namelen
&& file_name
[namelen
-1] != '/')
760 while (namelen
&& file_name
[namelen
-1] == '/')
762 if (!namelen
|| namelen
>= PATH_MAX
)
765 memcpy(alt_name
, file_name
, namelen
);
766 alt_name
[namelen
] = 0;
767 return do_lstat(follow
, alt_name
, buf
);
770 int mingw_lstat(const char *file_name
, struct stat
*buf
)
772 return do_stat_internal(0, file_name
, buf
);
774 int mingw_stat(const char *file_name
, struct stat
*buf
)
776 return do_stat_internal(1, file_name
, buf
);
779 int mingw_fstat(int fd
, struct stat
*buf
)
781 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
782 BY_HANDLE_FILE_INFORMATION fdata
;
784 if (fh
== INVALID_HANDLE_VALUE
) {
788 /* direct non-file handles to MS's fstat() */
789 if (GetFileType(fh
) != FILE_TYPE_DISK
)
790 return _fstati64(fd
, buf
);
792 if (GetFileInformationByHandle(fh
, &fdata
)) {
797 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
798 buf
->st_size
= fdata
.nFileSizeLow
|
799 (((off_t
)fdata
.nFileSizeHigh
)<<32);
800 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
801 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
802 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
803 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
810 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
812 long long winTime
= t
* 10000000LL + 116444736000000000LL;
813 ft
->dwLowDateTime
= winTime
;
814 ft
->dwHighDateTime
= winTime
>> 32;
817 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
822 wchar_t wfilename
[MAX_PATH
];
823 if (xutftowcs_path(wfilename
, file_name
) < 0)
826 /* must have write permission */
827 attrs
= GetFileAttributesW(wfilename
);
828 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
829 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
830 /* ignore errors here; open() will report them */
831 SetFileAttributesW(wfilename
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
834 if ((fh
= _wopen(wfilename
, O_RDWR
| O_BINARY
)) < 0) {
840 time_t_to_filetime(times
->modtime
, &mft
);
841 time_t_to_filetime(times
->actime
, &aft
);
843 GetSystemTimeAsFileTime(&mft
);
846 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
854 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
855 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
856 /* ignore errors again */
857 SetFileAttributesW(wfilename
, attrs
);
863 size_t mingw_strftime(char *s
, size_t max
,
864 const char *format
, const struct tm
*tm
)
866 size_t ret
= strftime(s
, max
, format
, tm
);
868 if (!ret
&& errno
== EINVAL
)
869 die("invalid strftime format: '%s'", format
);
873 unsigned int sleep (unsigned int seconds
)
879 char *mingw_mktemp(char *template)
881 wchar_t wtemplate
[MAX_PATH
];
882 if (xutftowcs_path(wtemplate
, template) < 0)
884 if (!_wmktemp(wtemplate
))
886 if (xwcstoutf(template, wtemplate
, strlen(template) + 1) < 0)
891 int mkstemp(char *template)
893 char *filename
= mktemp(template);
894 if (filename
== NULL
)
896 return open(filename
, O_RDWR
| O_CREAT
, 0600);
899 int gettimeofday(struct timeval
*tv
, void *tz
)
904 GetSystemTimeAsFileTime(&ft
);
905 hnsec
= filetime_to_hnsec(&ft
);
906 tv
->tv_sec
= hnsec
/ 10000000;
907 tv
->tv_usec
= (hnsec
% 10000000) / 10;
911 int pipe(int filedes
[2])
915 /* this creates non-inheritable handles */
916 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
917 errno
= err_win_to_posix(GetLastError());
920 filedes
[0] = _open_osfhandle(HCAST(int, h
[0]), O_NOINHERIT
);
921 if (filedes
[0] < 0) {
926 filedes
[1] = _open_osfhandle(HCAST(int, h
[1]), O_NOINHERIT
);
927 if (filedes
[1] < 0) {
935 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
937 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
938 memcpy(result
, gmtime(timep
), sizeof(struct tm
));
942 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
944 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
945 memcpy(result
, localtime(timep
), sizeof(struct tm
));
949 char *mingw_getcwd(char *pointer
, int len
)
951 wchar_t cwd
[MAX_PATH
], wpointer
[MAX_PATH
];
952 DWORD ret
= GetCurrentDirectoryW(ARRAY_SIZE(cwd
), cwd
);
954 if (!ret
|| ret
>= ARRAY_SIZE(cwd
)) {
955 errno
= ret
? ENAMETOOLONG
: err_win_to_posix(GetLastError());
958 ret
= GetLongPathNameW(cwd
, wpointer
, ARRAY_SIZE(wpointer
));
959 if (!ret
&& GetLastError() == ERROR_ACCESS_DENIED
) {
960 HANDLE hnd
= CreateFileW(cwd
, 0,
961 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
962 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
963 if (hnd
== INVALID_HANDLE_VALUE
)
965 ret
= GetFinalPathNameByHandleW(hnd
, wpointer
, ARRAY_SIZE(wpointer
), 0);
967 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
969 if (xwcstoutf(pointer
, normalize_ntpath(wpointer
), len
) < 0)
973 if (!ret
|| ret
>= ARRAY_SIZE(wpointer
))
975 if (xwcstoutf(pointer
, wpointer
, len
) < 0)
977 convert_slashes(pointer
);
982 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
983 * (Parsing C++ Command-Line Arguments)
985 static const char *quote_arg(const char *arg
)
987 /* count chars to quote */
989 int force_quotes
= 0;
992 if (!*p
) force_quotes
= 1;
994 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
998 else if (*p
== '\\') {
1000 while (*p
== '\\') {
1012 if (!force_quotes
&& n
== 0)
1015 /* insert \ where necessary */
1016 d
= q
= xmalloc(st_add3(len
, n
, 3));
1021 else if (*arg
== '\\') {
1023 while (*arg
== '\\') {
1040 static const char *parse_interpreter(const char *cmd
)
1042 static char buf
[100];
1046 /* don't even try a .exe */
1048 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
1051 fd
= open(cmd
, O_RDONLY
);
1054 n
= read(fd
, buf
, sizeof(buf
)-1);
1056 if (n
< 4) /* at least '#!/x' and not error */
1059 if (buf
[0] != '#' || buf
[1] != '!')
1062 p
= buf
+ strcspn(buf
, "\r\n");
1067 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
1070 if ((opt
= strchr(p
+1, ' ')))
1076 * exe_only means that we only want to detect .exe files, but not scripts
1077 * (which do not have an extension)
1079 static char *lookup_prog(const char *dir
, int dirlen
, const char *cmd
,
1080 int isexe
, int exe_only
)
1082 char path
[MAX_PATH
];
1083 snprintf(path
, sizeof(path
), "%.*s\\%s.exe", dirlen
, dir
, cmd
);
1085 if (!isexe
&& access(path
, F_OK
) == 0)
1086 return xstrdup(path
);
1087 path
[strlen(path
)-4] = '\0';
1088 if ((!exe_only
|| isexe
) && access(path
, F_OK
) == 0)
1089 if (!(GetFileAttributes(path
) & FILE_ATTRIBUTE_DIRECTORY
))
1090 return xstrdup(path
);
1095 * Determines the absolute path of cmd using the split path in path.
1096 * If cmd contains a slash or backslash, no lookup is performed.
1098 static char *path_lookup(const char *cmd
, int exe_only
)
1102 int len
= strlen(cmd
);
1103 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
1105 if (strchr(cmd
, '/') || strchr(cmd
, '\\'))
1106 return xstrdup(cmd
);
1108 path
= mingw_getenv("PATH");
1113 const char *sep
= strchrnul(path
, ';');
1114 int dirlen
= sep
- path
;
1116 prog
= lookup_prog(path
, dirlen
, cmd
, isexe
, exe_only
);
1125 static int do_putenv(char **env
, const char *name
, int size
, int free_old
);
1127 /* used number of elements of environ array, including terminating NULL */
1128 static int environ_size
= 0;
1129 /* allocated size of environ array, in bytes */
1130 static int environ_alloc
= 0;
1133 * Create environment block suitable for CreateProcess. Merges current
1134 * process environment and the supplied environment changes.
1136 static wchar_t *make_environment_block(char **deltaenv
)
1138 wchar_t *wenvblk
= NULL
;
1140 int i
= 0, size
= environ_size
, wenvsz
= 0, wenvpos
= 0;
1142 while (deltaenv
&& deltaenv
[i
])
1145 /* copy the environment, leaving space for changes */
1146 ALLOC_ARRAY(tmpenv
, size
+ i
);
1147 memcpy(tmpenv
, environ
, size
* sizeof(char*));
1149 /* merge supplied environment changes into the temporary environment */
1150 for (i
= 0; deltaenv
&& deltaenv
[i
]; i
++)
1151 size
= do_putenv(tmpenv
, deltaenv
[i
], size
, 0);
1153 /* create environment block from temporary environment */
1154 for (i
= 0; tmpenv
[i
]; i
++) {
1155 size
= 2 * strlen(tmpenv
[i
]) + 2; /* +2 for final \0 */
1156 ALLOC_GROW(wenvblk
, (wenvpos
+ size
) * sizeof(wchar_t), wenvsz
);
1157 wenvpos
+= xutftowcs(&wenvblk
[wenvpos
], tmpenv
[i
], size
) + 1;
1159 /* add final \0 terminator */
1160 wenvblk
[wenvpos
] = 0;
1166 struct pinfo_t
*next
;
1170 static struct pinfo_t
*pinfo
= NULL
;
1171 CRITICAL_SECTION pinfo_cs
;
1173 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **deltaenv
,
1175 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
1178 PROCESS_INFORMATION pi
;
1180 wchar_t wcmd
[MAX_PATH
], wdir
[MAX_PATH
], *wargs
, *wenvblk
= NULL
;
1181 unsigned flags
= CREATE_UNICODE_ENVIRONMENT
;
1184 /* Determine whether or not we are associated to a console */
1185 HANDLE cons
= CreateFile("CONOUT$", GENERIC_WRITE
,
1186 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
1187 FILE_ATTRIBUTE_NORMAL
, NULL
);
1188 if (cons
== INVALID_HANDLE_VALUE
) {
1189 /* There is no console associated with this process.
1190 * Since the child is a console process, Windows
1191 * would normally create a console window. But
1192 * since we'll be redirecting std streams, we do
1193 * not need the console.
1194 * It is necessary to use DETACHED_PROCESS
1195 * instead of CREATE_NO_WINDOW to make ssh
1196 * recognize that it has no console.
1198 flags
|= DETACHED_PROCESS
;
1200 /* There is already a console. If we specified
1201 * DETACHED_PROCESS here, too, Windows would
1202 * disassociate the child from the console.
1203 * The same is true for CREATE_NO_WINDOW.
1208 memset(&si
, 0, sizeof(si
));
1210 si
.dwFlags
= STARTF_USESTDHANDLES
;
1211 si
.hStdInput
= winansi_get_osfhandle(fhin
);
1212 si
.hStdOutput
= winansi_get_osfhandle(fhout
);
1213 si
.hStdError
= winansi_get_osfhandle(fherr
);
1215 if (xutftowcs_path(wcmd
, cmd
) < 0)
1217 if (dir
&& xutftowcs_path(wdir
, dir
) < 0)
1220 /* concatenate argv, quoting args as we go */
1221 strbuf_init(&args
, 0);
1223 char *quoted
= (char *)quote_arg(cmd
);
1224 strbuf_addstr(&args
, quoted
);
1228 for (; *argv
; argv
++) {
1229 char *quoted
= (char *)quote_arg(*argv
);
1231 strbuf_addch(&args
, ' ');
1232 strbuf_addstr(&args
, quoted
);
1233 if (quoted
!= *argv
)
1237 ALLOC_ARRAY(wargs
, st_add(st_mult(2, args
.len
), 1));
1238 xutftowcs(wargs
, args
.buf
, 2 * args
.len
+ 1);
1239 strbuf_release(&args
);
1241 wenvblk
= make_environment_block(deltaenv
);
1243 memset(&pi
, 0, sizeof(pi
));
1244 ret
= CreateProcessW(wcmd
, wargs
, NULL
, NULL
, TRUE
, flags
,
1245 wenvblk
, dir
? wdir
: NULL
, &si
, &pi
);
1254 CloseHandle(pi
.hThread
);
1257 * The process ID is the human-readable identifier of the process
1258 * that we want to present in log and error messages. The handle
1259 * is not useful for this purpose. But we cannot close it, either,
1260 * because it is not possible to turn a process ID into a process
1261 * handle after the process terminated.
1262 * Keep the handle in a list for waitpid.
1264 EnterCriticalSection(&pinfo_cs
);
1266 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
1267 info
->pid
= pi
.dwProcessId
;
1268 info
->proc
= pi
.hProcess
;
1272 LeaveCriticalSection(&pinfo_cs
);
1274 return (pid_t
)pi
.dwProcessId
;
1277 static pid_t
mingw_spawnv(const char *cmd
, const char **argv
, int prepend_cmd
)
1279 return mingw_spawnve_fd(cmd
, argv
, NULL
, NULL
, prepend_cmd
, 0, 1, 2);
1282 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **deltaenv
,
1284 int fhin
, int fhout
, int fherr
)
1287 char *prog
= path_lookup(cmd
, 0);
1294 const char *interpr
= parse_interpreter(prog
);
1297 const char *argv0
= argv
[0];
1298 char *iprog
= path_lookup(interpr
, 1);
1305 pid
= mingw_spawnve_fd(iprog
, argv
, deltaenv
, dir
, 1,
1306 fhin
, fhout
, fherr
);
1312 pid
= mingw_spawnve_fd(prog
, argv
, deltaenv
, dir
, 0,
1313 fhin
, fhout
, fherr
);
1319 static int try_shell_exec(const char *cmd
, char *const *argv
)
1321 const char *interpr
= parse_interpreter(cmd
);
1327 prog
= path_lookup(interpr
, 1);
1331 while (argv
[argc
]) argc
++;
1332 ALLOC_ARRAY(argv2
, argc
+ 1);
1333 argv2
[0] = (char *)cmd
; /* full path to the script file */
1334 memcpy(&argv2
[1], &argv
[1], sizeof(*argv
) * argc
);
1335 pid
= mingw_spawnv(prog
, argv2
, 1);
1338 if (waitpid(pid
, &status
, 0) < 0)
1342 pid
= 1; /* indicate that we tried but failed */
1349 int mingw_execv(const char *cmd
, char *const *argv
)
1351 /* check if git_command is a shell script */
1352 if (!try_shell_exec(cmd
, argv
)) {
1355 pid
= mingw_spawnv(cmd
, (const char **)argv
, 0);
1358 if (waitpid(pid
, &status
, 0) < 0)
1365 int mingw_execvp(const char *cmd
, char *const *argv
)
1367 char *prog
= path_lookup(cmd
, 0);
1370 mingw_execv(prog
, argv
);
1378 int mingw_kill(pid_t pid
, int sig
)
1380 if (pid
> 0 && sig
== SIGTERM
) {
1381 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1383 if (TerminateProcess(h
, -1)) {
1388 errno
= err_win_to_posix(GetLastError());
1391 } else if (pid
> 0 && sig
== 0) {
1392 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1404 * Compare environment entries by key (i.e. stopping at '=' or '\0').
1406 static int compareenv(const void *v1
, const void *v2
)
1408 const char *e1
= *(const char**)v1
;
1409 const char *e2
= *(const char**)v2
;
1414 c1
= (c1
== '=') ? 0 : tolower(c1
);
1415 c2
= (c2
== '=') ? 0 : tolower(c2
);
1425 static int bsearchenv(char **env
, const char *name
, size_t size
)
1427 unsigned low
= 0, high
= size
;
1428 while (low
< high
) {
1429 unsigned mid
= low
+ ((high
- low
) >> 1);
1430 int cmp
= compareenv(&env
[mid
], &name
);
1438 return ~low
; /* not found, return 1's complement of insert position */
1442 * If name contains '=', then sets the variable, otherwise it unsets it
1443 * Size includes the terminating NULL. Env must have room for size + 1 entries
1444 * (in case of insert). Returns the new size. Optionally frees removed entries.
1446 static int do_putenv(char **env
, const char *name
, int size
, int free_old
)
1448 int i
= bsearchenv(env
, name
, size
- 1);
1450 /* optionally free removed / replaced entry */
1451 if (i
>= 0 && free_old
)
1454 if (strchr(name
, '=')) {
1455 /* if new value ('key=value') is specified, insert or replace entry */
1458 memmove(&env
[i
+ 1], &env
[i
], (size
- i
) * sizeof(char*));
1461 env
[i
] = (char*) name
;
1462 } else if (i
>= 0) {
1463 /* otherwise ('key') remove existing entry */
1465 memmove(&env
[i
], &env
[i
+ 1], (size
- i
) * sizeof(char*));
1470 char *mingw_getenv(const char *name
)
1473 int pos
= bsearchenv(environ
, name
, environ_size
- 1);
1476 value
= strchr(environ
[pos
], '=');
1477 return value
? &value
[1] : NULL
;
1480 int mingw_putenv(const char *namevalue
)
1482 ALLOC_GROW(environ
, (environ_size
+ 1) * sizeof(char*), environ_alloc
);
1483 environ_size
= do_putenv(environ
, namevalue
, environ_size
, 1);
1488 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1489 * that service contains a numerical port, or that it is null. It
1490 * does a simple search using gethostbyname, and returns one IPv4 host
1493 static int WSAAPI
getaddrinfo_stub(const char *node
, const char *service
,
1494 const struct addrinfo
*hints
,
1495 struct addrinfo
**res
)
1497 struct hostent
*h
= NULL
;
1498 struct addrinfo
*ai
;
1499 struct sockaddr_in
*sin
;
1502 h
= gethostbyname(node
);
1504 return WSAGetLastError();
1507 ai
= xmalloc(sizeof(struct addrinfo
));
1510 ai
->ai_family
= AF_INET
;
1511 ai
->ai_socktype
= hints
? hints
->ai_socktype
: 0;
1512 switch (ai
->ai_socktype
) {
1514 ai
->ai_protocol
= IPPROTO_TCP
;
1517 ai
->ai_protocol
= IPPROTO_UDP
;
1520 ai
->ai_protocol
= 0;
1523 ai
->ai_addrlen
= sizeof(struct sockaddr_in
);
1524 if (hints
&& (hints
->ai_flags
& AI_CANONNAME
))
1525 ai
->ai_canonname
= h
? xstrdup(h
->h_name
) : NULL
;
1527 ai
->ai_canonname
= NULL
;
1529 sin
= xcalloc(1, ai
->ai_addrlen
);
1530 sin
->sin_family
= AF_INET
;
1531 /* Note: getaddrinfo is supposed to allow service to be a string,
1532 * which should be looked up using getservbyname. This is
1533 * currently not implemented */
1535 sin
->sin_port
= htons(atoi(service
));
1537 sin
->sin_addr
= *(struct in_addr
*)h
->h_addr
;
1538 else if (hints
&& (hints
->ai_flags
& AI_PASSIVE
))
1539 sin
->sin_addr
.s_addr
= INADDR_ANY
;
1541 sin
->sin_addr
.s_addr
= INADDR_LOOPBACK
;
1542 ai
->ai_addr
= (struct sockaddr
*)sin
;
1547 static void WSAAPI
freeaddrinfo_stub(struct addrinfo
*res
)
1549 free(res
->ai_canonname
);
1554 static int WSAAPI
getnameinfo_stub(const struct sockaddr
*sa
, socklen_t salen
,
1555 char *host
, DWORD hostlen
,
1556 char *serv
, DWORD servlen
, int flags
)
1558 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)sa
;
1559 if (sa
->sa_family
!= AF_INET
)
1564 if (host
&& hostlen
> 0) {
1565 struct hostent
*ent
= NULL
;
1566 if (!(flags
& NI_NUMERICHOST
))
1567 ent
= gethostbyaddr((const char *)&sin
->sin_addr
,
1568 sizeof(sin
->sin_addr
), AF_INET
);
1571 snprintf(host
, hostlen
, "%s", ent
->h_name
);
1572 else if (flags
& NI_NAMEREQD
)
1575 snprintf(host
, hostlen
, "%s", inet_ntoa(sin
->sin_addr
));
1578 if (serv
&& servlen
> 0) {
1579 struct servent
*ent
= NULL
;
1580 if (!(flags
& NI_NUMERICSERV
))
1581 ent
= getservbyport(sin
->sin_port
,
1582 flags
& NI_DGRAM
? "udp" : "tcp");
1585 snprintf(serv
, servlen
, "%s", ent
->s_name
);
1587 snprintf(serv
, servlen
, "%d", ntohs(sin
->sin_port
));
1593 static HMODULE ipv6_dll
= NULL
;
1594 static void (WSAAPI
*ipv6_freeaddrinfo
)(struct addrinfo
*res
);
1595 static int (WSAAPI
*ipv6_getaddrinfo
)(const char *node
, const char *service
,
1596 const struct addrinfo
*hints
,
1597 struct addrinfo
**res
);
1598 static int (WSAAPI
*ipv6_getnameinfo
)(const struct sockaddr
*sa
, socklen_t salen
,
1599 char *host
, DWORD hostlen
,
1600 char *serv
, DWORD servlen
, int flags
);
1602 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1603 * don't need to try to load that one dynamically.
1606 static void socket_cleanup(void)
1610 FreeLibrary(ipv6_dll
);
1612 ipv6_freeaddrinfo
= freeaddrinfo_stub
;
1613 ipv6_getaddrinfo
= getaddrinfo_stub
;
1614 ipv6_getnameinfo
= getnameinfo_stub
;
1617 static void ensure_socket_initialization(void)
1620 static int initialized
= 0;
1621 const char *libraries
[] = { "ws2_32.dll", "wship6.dll", NULL
};
1627 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1628 die("unable to initialize winsock subsystem, error %d",
1631 for (name
= libraries
; *name
; name
++) {
1632 ipv6_dll
= LoadLibraryExA(*name
, NULL
,
1633 LOAD_LIBRARY_SEARCH_SYSTEM32
);
1637 ipv6_freeaddrinfo
= (void (WSAAPI
*)(struct addrinfo
*))
1638 GetProcAddress(ipv6_dll
, "freeaddrinfo");
1639 ipv6_getaddrinfo
= (int (WSAAPI
*)(const char *, const char *,
1640 const struct addrinfo
*,
1641 struct addrinfo
**))
1642 GetProcAddress(ipv6_dll
, "getaddrinfo");
1643 ipv6_getnameinfo
= (int (WSAAPI
*)(const struct sockaddr
*,
1644 socklen_t
, char *, DWORD
,
1645 char *, DWORD
, int))
1646 GetProcAddress(ipv6_dll
, "getnameinfo");
1647 if (!ipv6_freeaddrinfo
|| !ipv6_getaddrinfo
|| !ipv6_getnameinfo
) {
1648 FreeLibrary(ipv6_dll
);
1653 if (!ipv6_freeaddrinfo
|| !ipv6_getaddrinfo
|| !ipv6_getnameinfo
) {
1654 ipv6_freeaddrinfo
= freeaddrinfo_stub
;
1655 ipv6_getaddrinfo
= getaddrinfo_stub
;
1656 ipv6_getnameinfo
= getnameinfo_stub
;
1659 atexit(socket_cleanup
);
1664 int mingw_gethostname(char *name
, int namelen
)
1666 ensure_socket_initialization();
1667 return gethostname(name
, namelen
);
1670 #undef gethostbyname
1671 struct hostent
*mingw_gethostbyname(const char *host
)
1673 ensure_socket_initialization();
1674 return gethostbyname(host
);
1677 void mingw_freeaddrinfo(struct addrinfo
*res
)
1679 ipv6_freeaddrinfo(res
);
1682 int mingw_getaddrinfo(const char *node
, const char *service
,
1683 const struct addrinfo
*hints
, struct addrinfo
**res
)
1685 ensure_socket_initialization();
1686 return ipv6_getaddrinfo(node
, service
, hints
, res
);
1689 int mingw_getnameinfo(const struct sockaddr
*sa
, socklen_t salen
,
1690 char *host
, DWORD hostlen
, char *serv
, DWORD servlen
,
1693 ensure_socket_initialization();
1694 return ipv6_getnameinfo(sa
, salen
, host
, hostlen
, serv
, servlen
, flags
);
1697 int mingw_socket(int domain
, int type
, int protocol
)
1702 ensure_socket_initialization();
1703 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
1704 if (s
== INVALID_SOCKET
) {
1706 * WSAGetLastError() values are regular BSD error codes
1707 * biased by WSABASEERR.
1708 * However, strerror() does not know about networking
1709 * specific errors, which are values beginning at 38 or so.
1710 * Therefore, we choose to leave the biased error code
1711 * in errno so that _if_ someone looks up the code somewhere,
1712 * then it is at least the number that are usually listed.
1714 errno
= WSAGetLastError();
1717 /* convert into a file descriptor */
1718 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
1720 return error("unable to make a socket file descriptor: %s",
1727 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
1729 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1730 return connect(s
, sa
, sz
);
1734 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
1736 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1737 return bind(s
, sa
, sz
);
1741 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
1743 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1744 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
1748 int mingw_shutdown(int sockfd
, int how
)
1750 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1751 return shutdown(s
, how
);
1755 int mingw_listen(int sockfd
, int backlog
)
1757 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1758 return listen(s
, backlog
);
1762 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
1766 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
1767 SOCKET s2
= accept(s1
, sa
, sz
);
1769 /* convert into a file descriptor */
1770 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
1773 return error("unable to make a socket file descriptor: %s",
1780 int mingw_rename(const char *pold
, const char *pnew
)
1784 wchar_t wpold
[MAX_PATH
], wpnew
[MAX_PATH
];
1785 if (xutftowcs_path(wpold
, pold
) < 0 || xutftowcs_path(wpnew
, pnew
) < 0)
1789 * Try native rename() first to get errno right.
1790 * It is based on MoveFile(), which cannot overwrite existing files.
1792 if (!_wrename(wpold
, wpnew
))
1794 if (errno
!= EEXIST
)
1797 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
1799 /* TODO: translate more errors */
1800 gle
= GetLastError();
1801 if (gle
== ERROR_ACCESS_DENIED
&&
1802 (attrs
= GetFileAttributesW(wpnew
)) != INVALID_FILE_ATTRIBUTES
) {
1803 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
1804 DWORD attrsold
= GetFileAttributesW(wpold
);
1805 if (attrsold
== INVALID_FILE_ATTRIBUTES
||
1806 !(attrsold
& FILE_ATTRIBUTE_DIRECTORY
))
1808 else if (!_wrmdir(wpnew
))
1812 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
1813 SetFileAttributesW(wpnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
1814 if (MoveFileExW(wpold
, wpnew
, MOVEFILE_REPLACE_EXISTING
))
1816 gle
= GetLastError();
1817 /* revert file attributes on failure */
1818 SetFileAttributesW(wpnew
, attrs
);
1821 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
1823 * We assume that some other process had the source or
1824 * destination file open at the wrong moment and retry.
1825 * In order to give the other process a higher chance to
1826 * complete its operation, we give up our time slice now.
1827 * If we have to retry again, we do sleep a bit.
1829 Sleep(delay
[tries
]);
1833 if (gle
== ERROR_ACCESS_DENIED
&&
1834 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1835 "Should I try again?", pold
, pnew
))
1843 * Note that this doesn't return the actual pagesize, but
1844 * the allocation granularity. If future Windows specific git code
1845 * needs the real getpagesize function, we need to find another solution.
1847 int mingw_getpagesize(void)
1851 return si
.dwAllocationGranularity
;
1854 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1855 enum EXTENDED_NAME_FORMAT
{
1857 NameUserPrincipal
= 8
1860 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type
)
1862 DECLARE_PROC_ADDR(secur32
.dll
, BOOL
, GetUserNameExW
,
1863 enum EXTENDED_NAME_FORMAT
, LPCWSTR
, PULONG
);
1864 static wchar_t wbuffer
[1024];
1867 if (!INIT_PROC_ADDR(GetUserNameExW
))
1870 len
= ARRAY_SIZE(wbuffer
);
1871 if (GetUserNameExW(type
, wbuffer
, &len
)) {
1872 char *converted
= xmalloc((len
*= 3));
1873 if (xwcstoutf(converted
, wbuffer
, len
) >= 0)
1881 char *mingw_query_user_email(void)
1883 return get_extended_user_info(NameUserPrincipal
);
1886 struct passwd
*getpwuid(int uid
)
1888 static unsigned initialized
;
1889 static char user_name
[100];
1890 static struct passwd
*p
;
1896 len
= sizeof(user_name
);
1897 if (!GetUserName(user_name
, &len
)) {
1902 p
= xmalloc(sizeof(*p
));
1903 p
->pw_name
= user_name
;
1904 p
->pw_gecos
= get_extended_user_info(NameDisplay
);
1906 p
->pw_gecos
= "unknown";
1913 static HANDLE timer_event
;
1914 static HANDLE timer_thread
;
1915 static int timer_interval
;
1916 static int one_shot
;
1917 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
1919 /* The timer works like this:
1920 * The thread, ticktack(), is a trivial routine that most of the time
1921 * only waits to receive the signal to terminate. The main thread tells
1922 * the thread to terminate by setting the timer_event to the signalled
1924 * But ticktack() interrupts the wait state after the timer's interval
1925 * length to call the signal handler.
1928 static unsigned __stdcall
ticktack(void *dummy
)
1930 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
1931 mingw_raise(SIGALRM
);
1938 static int start_timer_thread(void)
1940 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1942 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
1944 return errno
= ENOMEM
,
1945 error("cannot start timer thread");
1947 return errno
= ENOMEM
,
1948 error("cannot allocate resources for timer");
1952 static void stop_timer_thread(void)
1955 SetEvent(timer_event
); /* tell thread to terminate */
1957 int rc
= WaitForSingleObject(timer_thread
, 1000);
1958 if (rc
== WAIT_TIMEOUT
)
1959 error("timer thread did not terminate timely");
1960 else if (rc
!= WAIT_OBJECT_0
)
1961 error("waiting for timer thread failed: %lu",
1963 CloseHandle(timer_thread
);
1966 CloseHandle(timer_event
);
1968 timer_thread
= NULL
;
1971 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
1973 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
1976 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
1978 static const struct timeval zero
;
1979 static int atexit_done
;
1982 return errno
= EINVAL
,
1983 error("setitimer param 3 != NULL not implemented");
1984 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
1985 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
1986 return errno
= EINVAL
,
1987 error("setitimer: it_interval must be zero or eq it_value");
1990 stop_timer_thread();
1992 if (is_timeval_eq(&in
->it_value
, &zero
) &&
1993 is_timeval_eq(&in
->it_interval
, &zero
))
1996 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
1997 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
1999 atexit(stop_timer_thread
);
2002 return start_timer_thread();
2005 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
2008 return errno
= EINVAL
,
2009 error("sigaction only implemented for SIGALRM");
2011 return errno
= EINVAL
,
2012 error("sigaction: param 3 != NULL not implemented");
2014 timer_fn
= in
->sa_handler
;
2019 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
2031 sigint_fn
= handler
;
2035 return signal(sig
, handler
);
2042 int mingw_raise(int sig
)
2046 if (timer_fn
== SIG_DFL
) {
2047 if (isatty(STDERR_FILENO
))
2048 fputs("Alarm clock\n", stderr
);
2049 exit(128 + SIGALRM
);
2050 } else if (timer_fn
!= SIG_IGN
)
2055 if (sigint_fn
== SIG_DFL
)
2057 else if (sigint_fn
!= SIG_IGN
)
2066 int link(const char *oldpath
, const char *newpath
)
2068 typedef BOOL (WINAPI
*T
)(LPCWSTR
, LPCWSTR
, LPSECURITY_ATTRIBUTES
);
2069 static T create_hard_link
= NULL
;
2070 wchar_t woldpath
[MAX_PATH
], wnewpath
[MAX_PATH
];
2071 if (xutftowcs_path(woldpath
, oldpath
) < 0 ||
2072 xutftowcs_path(wnewpath
, newpath
) < 0)
2075 if (!create_hard_link
) {
2076 create_hard_link
= (T
) GetProcAddress(
2077 GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2078 if (!create_hard_link
)
2079 create_hard_link
= (T
)-1;
2081 if (create_hard_link
== (T
)-1) {
2085 if (!create_hard_link(wnewpath
, woldpath
, NULL
)) {
2086 errno
= err_win_to_posix(GetLastError());
2092 pid_t
waitpid(pid_t pid
, int *status
, int options
)
2094 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
2101 if (pid
> 0 && options
& WNOHANG
) {
2102 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
2106 options
&= ~WNOHANG
;
2110 struct pinfo_t
**ppinfo
;
2111 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
2117 GetExitCodeProcess(h
, (LPDWORD
)status
);
2119 EnterCriticalSection(&pinfo_cs
);
2123 struct pinfo_t
*info
= *ppinfo
;
2124 if (info
->pid
== pid
) {
2125 CloseHandle(info
->proc
);
2126 *ppinfo
= info
->next
;
2130 ppinfo
= &info
->next
;
2133 LeaveCriticalSection(&pinfo_cs
);
2144 int mingw_skip_dos_drive_prefix(char **path
)
2146 int ret
= has_dos_drive_prefix(*path
);
2151 int mingw_offset_1st_component(const char *path
)
2153 char *pos
= (char *)path
;
2156 if (!skip_dos_drive_prefix(&pos
) &&
2157 is_dir_sep(pos
[0]) && is_dir_sep(pos
[1])) {
2158 /* skip server name */
2159 pos
= strpbrk(pos
+ 2, "\\/");
2161 return 0; /* Error: malformed unc path */
2165 } while (*pos
&& !is_dir_sep(*pos
));
2168 return pos
+ is_dir_sep(*pos
) - path
;
2171 int xutftowcsn(wchar_t *wcs
, const char *utfs
, size_t wcslen
, int utflen
)
2173 int upos
= 0, wpos
= 0;
2174 const unsigned char *utf
= (const unsigned char*) utfs
;
2175 if (!utf
|| !wcs
|| wcslen
< 1) {
2179 /* reserve space for \0 */
2184 while (upos
< utflen
) {
2185 int c
= utf
[upos
++] & 0xff;
2186 if (utflen
== INT_MAX
&& c
== 0)
2189 if (wpos
>= wcslen
) {
2198 } else if (c
>= 0xc2 && c
< 0xe0 && upos
< utflen
&&
2199 (utf
[upos
] & 0xc0) == 0x80) {
2201 c
= ((c
& 0x1f) << 6);
2202 c
|= (utf
[upos
++] & 0x3f);
2204 } else if (c
>= 0xe0 && c
< 0xf0 && upos
+ 1 < utflen
&&
2205 !(c
== 0xe0 && utf
[upos
] < 0xa0) && /* over-long encoding */
2206 (utf
[upos
] & 0xc0) == 0x80 &&
2207 (utf
[upos
+ 1] & 0xc0) == 0x80) {
2209 c
= ((c
& 0x0f) << 12);
2210 c
|= ((utf
[upos
++] & 0x3f) << 6);
2211 c
|= (utf
[upos
++] & 0x3f);
2213 } else if (c
>= 0xf0 && c
< 0xf5 && upos
+ 2 < utflen
&&
2214 wpos
+ 1 < wcslen
&&
2215 !(c
== 0xf0 && utf
[upos
] < 0x90) && /* over-long encoding */
2216 !(c
== 0xf4 && utf
[upos
] >= 0x90) && /* > \u10ffff */
2217 (utf
[upos
] & 0xc0) == 0x80 &&
2218 (utf
[upos
+ 1] & 0xc0) == 0x80 &&
2219 (utf
[upos
+ 2] & 0xc0) == 0x80) {
2220 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2221 c
= ((c
& 0x07) << 18);
2222 c
|= ((utf
[upos
++] & 0x3f) << 12);
2223 c
|= ((utf
[upos
++] & 0x3f) << 6);
2224 c
|= (utf
[upos
++] & 0x3f);
2226 wcs
[wpos
++] = 0xd800 | (c
>> 10);
2227 wcs
[wpos
++] = 0xdc00 | (c
& 0x3ff);
2228 } else if (c
>= 0xa0) {
2229 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2232 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2233 static const char *hex
= "0123456789abcdef";
2234 wcs
[wpos
++] = hex
[c
>> 4];
2236 wcs
[wpos
++] = hex
[c
& 0x0f];
2243 int xwcstoutf(char *utf
, const wchar_t *wcs
, size_t utflen
)
2245 if (!wcs
|| !utf
|| utflen
< 1) {
2249 utflen
= WideCharToMultiByte(CP_UTF8
, 0, wcs
, -1, utf
, utflen
, NULL
, NULL
);
2256 static void setup_windows_environment(void)
2258 char *tmp
= getenv("TMPDIR");
2260 /* on Windows it is TMP and TEMP */
2262 if (!(tmp
= getenv("TMP")))
2263 tmp
= getenv("TEMP");
2265 setenv("TMPDIR", tmp
, 1);
2266 tmp
= getenv("TMPDIR");
2272 * Convert all dir separators to forward slashes,
2273 * to help shell commands called from the Git
2274 * executable (by not mistaking the dir separators
2275 * for escape characters).
2277 convert_slashes(tmp
);
2280 /* simulate TERM to enable auto-color (see color.c) */
2281 if (!getenv("TERM"))
2282 setenv("TERM", "cygwin", 1);
2286 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2287 * mingw startup code, see init.c in mingw runtime).
2295 extern int __wgetmainargs(int *argc
, wchar_t ***argv
, wchar_t ***env
, int glob
,
2298 static NORETURN
void die_startup(void)
2300 fputs("fatal: not enough memory for initialization", stderr
);
2304 static void *malloc_startup(size_t size
)
2306 void *result
= malloc(size
);
2312 static char *wcstoutfdup_startup(char *buffer
, const wchar_t *wcs
, size_t len
)
2314 len
= xwcstoutf(buffer
, wcs
, len
) + 1;
2315 return memcpy(malloc_startup(len
), buffer
, len
);
2318 static void maybe_redirect_std_handle(const wchar_t *key
, DWORD std_id
, int fd
,
2319 DWORD desired_access
, DWORD flags
)
2321 DWORD create_flag
= fd
? OPEN_ALWAYS
: OPEN_EXISTING
;
2322 wchar_t buf
[MAX_PATH
];
2323 DWORD max
= ARRAY_SIZE(buf
);
2325 DWORD ret
= GetEnvironmentVariableW(key
, buf
, max
);
2327 if (!ret
|| ret
>= max
)
2330 /* make sure this does not leak into child processes */
2331 SetEnvironmentVariableW(key
, NULL
);
2332 if (!wcscmp(buf
, L
"off")) {
2334 handle
= GetStdHandle(std_id
);
2335 if (handle
!= INVALID_HANDLE_VALUE
)
2336 CloseHandle(handle
);
2339 if (std_id
== STD_ERROR_HANDLE
&& !wcscmp(buf
, L
"2>&1")) {
2340 handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2341 if (handle
== INVALID_HANDLE_VALUE
) {
2343 handle
= GetStdHandle(std_id
);
2344 if (handle
!= INVALID_HANDLE_VALUE
)
2345 CloseHandle(handle
);
2347 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2348 SetStdHandle(std_id
, handle
);
2350 /* do *not* close the new_fd: that would close stdout */
2354 handle
= CreateFileW(buf
, desired_access
, 0, NULL
, create_flag
,
2356 if (handle
!= INVALID_HANDLE_VALUE
) {
2357 int new_fd
= _open_osfhandle((intptr_t)handle
, O_BINARY
);
2358 SetStdHandle(std_id
, handle
);
2364 static void maybe_redirect_std_handles(void)
2366 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE
, 0,
2367 GENERIC_READ
, FILE_ATTRIBUTE_NORMAL
);
2368 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE
, 1,
2369 GENERIC_WRITE
, FILE_ATTRIBUTE_NORMAL
);
2370 maybe_redirect_std_handle(L
"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE
, 2,
2371 GENERIC_WRITE
, FILE_FLAG_NO_BUFFERING
);
2374 void mingw_startup(void)
2376 int i
, maxlen
, argc
;
2378 wchar_t **wenv
, **wargv
;
2381 maybe_redirect_std_handles();
2383 /* get wide char arguments and environment */
2385 if (__wgetmainargs(&argc
, &wargv
, &wenv
, _CRT_glob
, &si
) < 0)
2388 /* determine size of argv and environ conversion buffer */
2389 maxlen
= wcslen(wargv
[0]);
2390 for (i
= 1; i
< argc
; i
++)
2391 maxlen
= max(maxlen
, wcslen(wargv
[i
]));
2392 for (i
= 0; wenv
[i
]; i
++)
2393 maxlen
= max(maxlen
, wcslen(wenv
[i
]));
2396 * nedmalloc can't free CRT memory, allocate resizable environment
2397 * list. Note that xmalloc / xmemdupz etc. call getenv, so we cannot
2398 * use it while initializing the environment itself.
2400 environ_size
= i
+ 1;
2401 environ_alloc
= alloc_nr(environ_size
* sizeof(char*));
2402 environ
= malloc_startup(environ_alloc
);
2404 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2405 maxlen
= 3 * maxlen
+ 1;
2406 buffer
= malloc_startup(maxlen
);
2408 /* convert command line arguments and environment to UTF-8 */
2409 for (i
= 0; i
< argc
; i
++)
2410 __argv
[i
] = wcstoutfdup_startup(buffer
, wargv
[i
], maxlen
);
2411 for (i
= 0; wenv
[i
]; i
++)
2412 environ
[i
] = wcstoutfdup_startup(buffer
, wenv
[i
], maxlen
);
2416 /* sort environment for O(log n) getenv / putenv */
2417 qsort(environ
, i
, sizeof(char*), compareenv
);
2419 /* fix Windows specific environment settings */
2420 setup_windows_environment();
2422 /* initialize critical section for waitpid pinfo_t list */
2423 InitializeCriticalSection(&pinfo_cs
);
2425 /* set up default file mode and file modes for stdin/out/err */
2427 _setmode(_fileno(stdin
), _O_BINARY
);
2428 _setmode(_fileno(stdout
), _O_BINARY
);
2429 _setmode(_fileno(stderr
), _O_BINARY
);
2431 /* initialize Unicode console */
2435 int uname(struct utsname
*buf
)
2437 unsigned v
= (unsigned)GetVersion();
2438 memset(buf
, 0, sizeof(*buf
));
2439 xsnprintf(buf
->sysname
, sizeof(buf
->sysname
), "Windows");
2440 xsnprintf(buf
->release
, sizeof(buf
->release
),
2441 "%u.%u", v
& 0xff, (v
>> 8) & 0xff);
2442 /* assuming NT variants only.. */
2443 xsnprintf(buf
->version
, sizeof(buf
->version
),
2444 "%u", (v
>> 16) & 0x7fff);