1 #include "../git-compat-util.h"
9 static int err_win_to_posix(DWORD winerr
)
13 case ERROR_ACCESS_DENIED
: error
= EACCES
; break;
14 case ERROR_ACCOUNT_DISABLED
: error
= EACCES
; break;
15 case ERROR_ACCOUNT_RESTRICTION
: error
= EACCES
; break;
16 case ERROR_ALREADY_ASSIGNED
: error
= EBUSY
; break;
17 case ERROR_ALREADY_EXISTS
: error
= EEXIST
; break;
18 case ERROR_ARITHMETIC_OVERFLOW
: error
= ERANGE
; break;
19 case ERROR_BAD_COMMAND
: error
= EIO
; break;
20 case ERROR_BAD_DEVICE
: error
= ENODEV
; break;
21 case ERROR_BAD_DRIVER_LEVEL
: error
= ENXIO
; break;
22 case ERROR_BAD_EXE_FORMAT
: error
= ENOEXEC
; break;
23 case ERROR_BAD_FORMAT
: error
= ENOEXEC
; break;
24 case ERROR_BAD_LENGTH
: error
= EINVAL
; break;
25 case ERROR_BAD_PATHNAME
: error
= ENOENT
; break;
26 case ERROR_BAD_PIPE
: error
= EPIPE
; break;
27 case ERROR_BAD_UNIT
: error
= ENODEV
; break;
28 case ERROR_BAD_USERNAME
: error
= EINVAL
; break;
29 case ERROR_BROKEN_PIPE
: error
= EPIPE
; break;
30 case ERROR_BUFFER_OVERFLOW
: error
= ENAMETOOLONG
; break;
31 case ERROR_BUSY
: error
= EBUSY
; break;
32 case ERROR_BUSY_DRIVE
: error
= EBUSY
; break;
33 case ERROR_CALL_NOT_IMPLEMENTED
: error
= ENOSYS
; break;
34 case ERROR_CANNOT_MAKE
: error
= EACCES
; break;
35 case ERROR_CANTOPEN
: error
= EIO
; break;
36 case ERROR_CANTREAD
: error
= EIO
; break;
37 case ERROR_CANTWRITE
: error
= EIO
; break;
38 case ERROR_CRC
: error
= EIO
; break;
39 case ERROR_CURRENT_DIRECTORY
: error
= EACCES
; break;
40 case ERROR_DEVICE_IN_USE
: error
= EBUSY
; break;
41 case ERROR_DEV_NOT_EXIST
: error
= ENODEV
; break;
42 case ERROR_DIRECTORY
: error
= EINVAL
; break;
43 case ERROR_DIR_NOT_EMPTY
: error
= ENOTEMPTY
; break;
44 case ERROR_DISK_CHANGE
: error
= EIO
; break;
45 case ERROR_DISK_FULL
: error
= ENOSPC
; break;
46 case ERROR_DRIVE_LOCKED
: error
= EBUSY
; break;
47 case ERROR_ENVVAR_NOT_FOUND
: error
= EINVAL
; break;
48 case ERROR_EXE_MARKED_INVALID
: error
= ENOEXEC
; break;
49 case ERROR_FILENAME_EXCED_RANGE
: error
= ENAMETOOLONG
; break;
50 case ERROR_FILE_EXISTS
: error
= EEXIST
; break;
51 case ERROR_FILE_INVALID
: error
= ENODEV
; break;
52 case ERROR_FILE_NOT_FOUND
: error
= ENOENT
; break;
53 case ERROR_GEN_FAILURE
: error
= EIO
; break;
54 case ERROR_HANDLE_DISK_FULL
: error
= ENOSPC
; break;
55 case ERROR_INSUFFICIENT_BUFFER
: error
= ENOMEM
; break;
56 case ERROR_INVALID_ACCESS
: error
= EACCES
; break;
57 case ERROR_INVALID_ADDRESS
: error
= EFAULT
; break;
58 case ERROR_INVALID_BLOCK
: error
= EFAULT
; break;
59 case ERROR_INVALID_DATA
: error
= EINVAL
; break;
60 case ERROR_INVALID_DRIVE
: error
= ENODEV
; break;
61 case ERROR_INVALID_EXE_SIGNATURE
: error
= ENOEXEC
; break;
62 case ERROR_INVALID_FLAGS
: error
= EINVAL
; break;
63 case ERROR_INVALID_FUNCTION
: error
= ENOSYS
; break;
64 case ERROR_INVALID_HANDLE
: error
= EBADF
; break;
65 case ERROR_INVALID_LOGON_HOURS
: error
= EACCES
; break;
66 case ERROR_INVALID_NAME
: error
= EINVAL
; break;
67 case ERROR_INVALID_OWNER
: error
= EINVAL
; break;
68 case ERROR_INVALID_PARAMETER
: error
= EINVAL
; break;
69 case ERROR_INVALID_PASSWORD
: error
= EPERM
; break;
70 case ERROR_INVALID_PRIMARY_GROUP
: error
= EINVAL
; break;
71 case ERROR_INVALID_SIGNAL_NUMBER
: error
= EINVAL
; break;
72 case ERROR_INVALID_TARGET_HANDLE
: error
= EIO
; break;
73 case ERROR_INVALID_WORKSTATION
: error
= EACCES
; break;
74 case ERROR_IO_DEVICE
: error
= EIO
; break;
75 case ERROR_IO_INCOMPLETE
: error
= EINTR
; break;
76 case ERROR_LOCKED
: error
= EBUSY
; break;
77 case ERROR_LOCK_VIOLATION
: error
= EACCES
; break;
78 case ERROR_LOGON_FAILURE
: error
= EACCES
; break;
79 case ERROR_MAPPED_ALIGNMENT
: error
= EINVAL
; break;
80 case ERROR_META_EXPANSION_TOO_LONG
: error
= E2BIG
; break;
81 case ERROR_MORE_DATA
: error
= EPIPE
; break;
82 case ERROR_NEGATIVE_SEEK
: error
= ESPIPE
; break;
83 case ERROR_NOACCESS
: error
= EFAULT
; break;
84 case ERROR_NONE_MAPPED
: error
= EINVAL
; break;
85 case ERROR_NOT_ENOUGH_MEMORY
: error
= ENOMEM
; break;
86 case ERROR_NOT_READY
: error
= EAGAIN
; break;
87 case ERROR_NOT_SAME_DEVICE
: error
= EXDEV
; break;
88 case ERROR_NO_DATA
: error
= EPIPE
; break;
89 case ERROR_NO_MORE_SEARCH_HANDLES
: error
= EIO
; break;
90 case ERROR_NO_PROC_SLOTS
: error
= EAGAIN
; break;
91 case ERROR_NO_SUCH_PRIVILEGE
: error
= EACCES
; break;
92 case ERROR_OPEN_FAILED
: error
= EIO
; break;
93 case ERROR_OPEN_FILES
: error
= EBUSY
; break;
94 case ERROR_OPERATION_ABORTED
: error
= EINTR
; break;
95 case ERROR_OUTOFMEMORY
: error
= ENOMEM
; break;
96 case ERROR_PASSWORD_EXPIRED
: error
= EACCES
; break;
97 case ERROR_PATH_BUSY
: error
= EBUSY
; break;
98 case ERROR_PATH_NOT_FOUND
: error
= ENOENT
; break;
99 case ERROR_PIPE_BUSY
: error
= EBUSY
; break;
100 case ERROR_PIPE_CONNECTED
: error
= EPIPE
; break;
101 case ERROR_PIPE_LISTENING
: error
= EPIPE
; break;
102 case ERROR_PIPE_NOT_CONNECTED
: error
= EPIPE
; break;
103 case ERROR_PRIVILEGE_NOT_HELD
: error
= EACCES
; break;
104 case ERROR_READ_FAULT
: error
= EIO
; break;
105 case ERROR_SEEK
: error
= EIO
; break;
106 case ERROR_SEEK_ON_DEVICE
: error
= ESPIPE
; break;
107 case ERROR_SHARING_BUFFER_EXCEEDED
: error
= ENFILE
; break;
108 case ERROR_SHARING_VIOLATION
: error
= EACCES
; break;
109 case ERROR_STACK_OVERFLOW
: error
= ENOMEM
; break;
110 case ERROR_SWAPERROR
: error
= ENOENT
; break;
111 case ERROR_TOO_MANY_MODULES
: error
= EMFILE
; break;
112 case ERROR_TOO_MANY_OPEN_FILES
: error
= EMFILE
; break;
113 case ERROR_UNRECOGNIZED_MEDIA
: error
= ENXIO
; break;
114 case ERROR_UNRECOGNIZED_VOLUME
: error
= ENODEV
; break;
115 case ERROR_WAIT_NO_CHILDREN
: error
= ECHILD
; break;
116 case ERROR_WRITE_FAULT
: error
= EIO
; break;
117 case ERROR_WRITE_PROTECT
: error
= EROFS
; break;
123 int mingw_open (const char *filename
, int oflags
, ...)
129 va_start(args
, oflags
);
130 mode
= va_arg(args
, int);
133 if (!strcmp(filename
, "/dev/null"))
136 fd
= open(filename
, oflags
, mode
);
138 if (fd
< 0 && (oflags
& O_CREAT
) && errno
== EACCES
) {
139 DWORD attrs
= GetFileAttributes(filename
);
140 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
146 static inline time_t filetime_to_time_t(const FILETIME
*ft
)
148 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
149 winTime
-= 116444736000000000LL; /* Windows to Unix Epoch conversion */
150 winTime
/= 10000000; /* Nano to seconds resolution */
151 return (time_t)winTime
;
155 * We keep the do_lstat code in a separate function to avoid recursion.
156 * When a path ends with a slash, the stat will fail with ENOENT. In
157 * this case, we strip the trailing slashes and stat again.
159 static int do_lstat(const char *file_name
, struct stat
*buf
)
161 WIN32_FILE_ATTRIBUTE_DATA fdata
;
163 if (!(errno
= get_file_attr(file_name
, &fdata
))) {
168 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
169 buf
->st_size
= fdata
.nFileSizeLow
|
170 (((off_t
)fdata
.nFileSizeHigh
)<<32);
171 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
172 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
173 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
174 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
175 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
176 WIN32_FIND_DATAA findbuf
;
177 HANDLE handle
= FindFirstFileA(file_name
, &findbuf
);
178 if (handle
!= INVALID_HANDLE_VALUE
) {
179 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
180 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
181 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
182 buf
->st_mode
= S_IREAD
| S_IFLNK
;
183 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
184 buf
->st_mode
|= S_IWRITE
;
185 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
196 * We provide our own lstat/fstat functions, since the provided
197 * lstat/fstat functions are so slow. These stat functions are
198 * tailored for Git's usage (read: fast), and are not meant to be
199 * complete. Note that Git stat()s are redirected to mingw_lstat()
200 * too, since Windows doesn't really handle symlinks that well.
202 int mingw_lstat(const char *file_name
, struct stat
*buf
)
205 static char alt_name
[PATH_MAX
];
207 if (!do_lstat(file_name
, buf
))
211 * if file_name ended in a '/', Windows returned ENOENT;
212 * try again without trailing slashes
217 namelen
= strlen(file_name
);
218 if (namelen
&& file_name
[namelen
-1] != '/')
220 while (namelen
&& file_name
[namelen
-1] == '/')
222 if (!namelen
|| namelen
>= PATH_MAX
)
225 memcpy(alt_name
, file_name
, namelen
);
226 alt_name
[namelen
] = 0;
227 return do_lstat(alt_name
, buf
);
231 int mingw_fstat(int fd
, struct stat
*buf
)
233 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
234 BY_HANDLE_FILE_INFORMATION fdata
;
236 if (fh
== INVALID_HANDLE_VALUE
) {
240 /* direct non-file handles to MS's fstat() */
241 if (GetFileType(fh
) != FILE_TYPE_DISK
)
242 return _fstati64(fd
, buf
);
244 if (GetFileInformationByHandle(fh
, &fdata
)) {
249 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
250 buf
->st_size
= fdata
.nFileSizeLow
|
251 (((off_t
)fdata
.nFileSizeHigh
)<<32);
252 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
253 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
254 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
255 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
262 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
264 long long winTime
= t
* 10000000LL + 116444736000000000LL;
265 ft
->dwLowDateTime
= winTime
;
266 ft
->dwHighDateTime
= winTime
>> 32;
269 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
274 /* must have write permission */
275 if ((fh
= open(file_name
, O_RDWR
| O_BINARY
)) < 0)
278 time_t_to_filetime(times
->modtime
, &mft
);
279 time_t_to_filetime(times
->actime
, &aft
);
280 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
289 unsigned int sleep (unsigned int seconds
)
295 int mkstemp(char *template)
297 char *filename
= mktemp(template);
298 if (filename
== NULL
)
300 return open(filename
, O_RDWR
| O_CREAT
, 0600);
303 int gettimeofday(struct timeval
*tv
, void *tz
)
308 tm
.tm_year
= st
.wYear
-1900;
309 tm
.tm_mon
= st
.wMonth
-1;
310 tm
.tm_mday
= st
.wDay
;
311 tm
.tm_hour
= st
.wHour
;
312 tm
.tm_min
= st
.wMinute
;
313 tm
.tm_sec
= st
.wSecond
;
314 tv
->tv_sec
= tm_to_time_t(&tm
);
317 tv
->tv_usec
= st
.wMilliseconds
*1000;
321 int pipe(int filedes
[2])
326 if (_pipe(filedes
, 8192, 0) < 0)
329 parent
= GetCurrentProcess();
331 if (!DuplicateHandle (parent
, (HANDLE
)_get_osfhandle(filedes
[0]),
332 parent
, &h
[0], 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
337 if (!DuplicateHandle (parent
, (HANDLE
)_get_osfhandle(filedes
[1]),
338 parent
, &h
[1], 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
344 fd
= _open_osfhandle((int)h
[0], O_NOINHERIT
);
354 fd
= _open_osfhandle((int)h
[1], O_NOINHERIT
);
366 int poll(struct pollfd
*ufds
, unsigned int nfds
, int timeout
)
375 return errno
= EINVAL
, error("poll timeout not supported");
379 * When there is only one fd to wait for, then we pretend that
380 * input is available and let the actual wait happen when the
381 * caller invokes read().
384 if (!(ufds
[0].events
& POLLIN
))
385 return errno
= EINVAL
, error("POLLIN not set");
386 ufds
[0].revents
= POLLIN
;
392 for (i
= 0; i
< nfds
; i
++) {
394 HANDLE h
= (HANDLE
) _get_osfhandle(ufds
[i
].fd
);
395 if (h
== INVALID_HANDLE_VALUE
)
396 return -1; /* errno was set */
398 if (!(ufds
[i
].events
& POLLIN
))
399 return errno
= EINVAL
, error("POLLIN not set");
401 /* this emulation works only for pipes */
402 if (!PeekNamedPipe(h
, NULL
, 0, NULL
, &avail
, NULL
)) {
403 int err
= GetLastError();
404 if (err
== ERROR_BROKEN_PIPE
) {
405 ufds
[i
].revents
= POLLHUP
;
409 return error("PeekNamedPipe failed,"
410 " GetLastError: %u", err
);
413 ufds
[i
].revents
= POLLIN
;
420 * The only times that we spin here is when the process
421 * that is connected through the pipes is waiting for
422 * its own input data to become available. But since
423 * the process (pack-objects) is itself CPU intensive,
424 * it will happily pick up the time slice that we are
425 * relinquishing here.
433 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
435 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
436 memcpy(result
, gmtime(timep
), sizeof(struct tm
));
440 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
442 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
443 memcpy(result
, localtime(timep
), sizeof(struct tm
));
448 char *mingw_getcwd(char *pointer
, int len
)
451 char *ret
= getcwd(pointer
, len
);
454 for (i
= 0; pointer
[i
]; i
++)
455 if (pointer
[i
] == '\\')
461 char *mingw_getenv(const char *name
)
463 char *result
= getenv(name
);
464 if (!result
&& !strcmp(name
, "TMPDIR")) {
465 /* on Windows it is TMP and TEMP */
466 result
= getenv("TMP");
468 result
= getenv("TEMP");
474 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
475 * (Parsing C++ Command-Line Arguments)
477 static const char *quote_arg(const char *arg
)
479 /* count chars to quote */
481 int force_quotes
= 0;
484 if (!*p
) force_quotes
= 1;
486 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
490 else if (*p
== '\\') {
504 if (!force_quotes
&& n
== 0)
507 /* insert \ where necessary */
508 d
= q
= xmalloc(len
+n
+3);
513 else if (*arg
== '\\') {
515 while (*arg
== '\\') {
532 static const char *parse_interpreter(const char *cmd
)
534 static char buf
[100];
538 /* don't even try a .exe */
540 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
543 fd
= open(cmd
, O_RDONLY
);
546 n
= read(fd
, buf
, sizeof(buf
)-1);
548 if (n
< 4) /* at least '#!/x' and not error */
551 if (buf
[0] != '#' || buf
[1] != '!')
554 p
= buf
+ strcspn(buf
, "\r\n");
559 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
562 if ((opt
= strchr(p
+1, ' ')))
568 * Splits the PATH into parts.
570 static char **get_path_split(void)
572 char *p
, **path
, *envpath
= getenv("PATH");
575 if (!envpath
|| !*envpath
)
578 envpath
= xstrdup(envpath
);
584 if (*dir
) { /* not earlier, catches series of ; */
591 path
= xmalloc((n
+1)*sizeof(char *));
596 path
[i
++] = xstrdup(p
);
606 static void free_path_split(char **path
)
619 * exe_only means that we only want to detect .exe files, but not scripts
620 * (which do not have an extension)
622 static char *lookup_prog(const char *dir
, const char *cmd
, int isexe
, int exe_only
)
625 snprintf(path
, sizeof(path
), "%s/%s.exe", dir
, cmd
);
627 if (!isexe
&& access(path
, F_OK
) == 0)
628 return xstrdup(path
);
629 path
[strlen(path
)-4] = '\0';
630 if ((!exe_only
|| isexe
) && access(path
, F_OK
) == 0)
631 if (!(GetFileAttributes(path
) & FILE_ATTRIBUTE_DIRECTORY
))
632 return xstrdup(path
);
637 * Determines the absolute path of cmd using the the split path in path.
638 * If cmd contains a slash or backslash, no lookup is performed.
640 static char *path_lookup(const char *cmd
, char **path
, int exe_only
)
643 int len
= strlen(cmd
);
644 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
646 if (strchr(cmd
, '/') || strchr(cmd
, '\\'))
649 while (!prog
&& *path
)
650 prog
= lookup_prog(*path
++, cmd
, isexe
, exe_only
);
655 static int env_compare(const void *a
, const void *b
)
659 return strcasecmp(*ea
, *eb
);
662 static pid_t
mingw_spawnve(const char *cmd
, const char **argv
, char **env
,
666 PROCESS_INFORMATION pi
;
667 struct strbuf envblk
, args
;
671 /* Determine whether or not we are associated to a console */
672 HANDLE cons
= CreateFile("CONOUT$", GENERIC_WRITE
,
673 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
674 FILE_ATTRIBUTE_NORMAL
, NULL
);
675 if (cons
== INVALID_HANDLE_VALUE
) {
677 * There is no console associated with this process.
678 * Since the child is a console process, Windows
679 * would normally create a console window. But
680 * since we'll be redirecting std streams, we do
681 * not need the console.
682 * It is necessary to use DETACHED_PROCESS
683 * instead of CREATE_NO_WINDOW to make ssh
684 * recognize that it has no console.
686 flags
= DETACHED_PROCESS
;
689 * There is already a console. If we specified
690 * DETACHED_PROCESS here, too, Windows would
691 * disassociate the child from the console.
692 * The same is true for CREATE_NO_WINDOW.
698 memset(&si
, 0, sizeof(si
));
700 si
.dwFlags
= STARTF_USESTDHANDLES
;
701 si
.hStdInput
= (HANDLE
) _get_osfhandle(0);
702 si
.hStdOutput
= (HANDLE
) _get_osfhandle(1);
703 si
.hStdError
= (HANDLE
) _get_osfhandle(2);
705 /* concatenate argv, quoting args as we go */
706 strbuf_init(&args
, 0);
708 char *quoted
= (char *)quote_arg(cmd
);
709 strbuf_addstr(&args
, quoted
);
713 for (; *argv
; argv
++) {
714 char *quoted
= (char *)quote_arg(*argv
);
716 strbuf_addch(&args
, ' ');
717 strbuf_addstr(&args
, quoted
);
724 char **e
, **sorted_env
;
726 for (e
= env
; *e
; e
++)
729 /* environment must be sorted */
730 sorted_env
= xmalloc(sizeof(*sorted_env
) * (count
+ 1));
731 memcpy(sorted_env
, env
, sizeof(*sorted_env
) * (count
+ 1));
732 qsort(sorted_env
, count
, sizeof(*sorted_env
), env_compare
);
734 strbuf_init(&envblk
, 0);
735 for (e
= sorted_env
; *e
; e
++) {
736 strbuf_addstr(&envblk
, *e
);
737 strbuf_addch(&envblk
, '\0');
742 memset(&pi
, 0, sizeof(pi
));
743 ret
= CreateProcess(cmd
, args
.buf
, NULL
, NULL
, TRUE
, flags
,
744 env
? envblk
.buf
: NULL
, NULL
, &si
, &pi
);
747 strbuf_release(&envblk
);
748 strbuf_release(&args
);
754 CloseHandle(pi
.hThread
);
755 return (pid_t
)pi
.hProcess
;
758 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **env
)
761 char **path
= get_path_split();
762 char *prog
= path_lookup(cmd
, path
, 0);
769 const char *interpr
= parse_interpreter(prog
);
772 const char *argv0
= argv
[0];
773 char *iprog
= path_lookup(interpr
, path
, 1);
780 pid
= mingw_spawnve(iprog
, argv
, env
, 1);
786 pid
= mingw_spawnve(prog
, argv
, env
, 0);
789 free_path_split(path
);
793 static int try_shell_exec(const char *cmd
, char *const *argv
, char **env
)
795 const char *interpr
= parse_interpreter(cmd
);
802 path
= get_path_split();
803 prog
= path_lookup(interpr
, path
, 1);
807 while (argv
[argc
]) argc
++;
808 argv2
= xmalloc(sizeof(*argv
) * (argc
+1));
809 argv2
[0] = (char *)cmd
; /* full path to the script file */
810 memcpy(&argv2
[1], &argv
[1], sizeof(*argv
) * argc
);
811 pid
= mingw_spawnve(prog
, argv2
, env
, 1);
814 if (waitpid(pid
, &status
, 0) < 0)
818 pid
= 1; /* indicate that we tried but failed */
822 free_path_split(path
);
826 static void mingw_execve(const char *cmd
, char *const *argv
, char *const *env
)
828 /* check if git_command is a shell script */
829 if (!try_shell_exec(cmd
, argv
, (char **)env
)) {
832 pid
= mingw_spawnve(cmd
, (const char **)argv
, (char **)env
, 0);
835 if (waitpid(pid
, &status
, 0) < 0)
841 void mingw_execvp(const char *cmd
, char *const *argv
)
843 char **path
= get_path_split();
844 char *prog
= path_lookup(cmd
, path
, 0);
847 mingw_execve(prog
, argv
, environ
);
852 free_path_split(path
);
855 static char **copy_environ(void)
861 env
= xmalloc((i
+1)*sizeof(*env
));
862 for (i
= 0; environ
[i
]; i
++)
863 env
[i
] = xstrdup(environ
[i
]);
868 void free_environ(char **env
)
871 for (i
= 0; env
[i
]; i
++)
876 static int lookup_env(char **env
, const char *name
, size_t nmln
)
880 for (i
= 0; env
[i
]; i
++) {
881 if (0 == strncmp(env
[i
], name
, nmln
)
882 && '=' == env
[i
][nmln
])
890 * If name contains '=', then sets the variable, otherwise it unsets it
892 static char **env_setenv(char **env
, const char *name
)
894 char *eq
= strchrnul(name
, '=');
895 int i
= lookup_env(env
, name
, eq
-name
);
899 for (i
= 0; env
[i
]; i
++)
901 env
= xrealloc(env
, (i
+2)*sizeof(*env
));
902 env
[i
] = xstrdup(name
);
909 env
[i
] = xstrdup(name
);
918 * Copies global environ and adjusts variables as specified by vars.
920 char **make_augmented_environ(const char *const *vars
)
922 char **env
= copy_environ();
925 env
= env_setenv(env
, *vars
++);
929 /* this is the first function to call into WS_32; initialize it */
931 struct hostent
*mingw_gethostbyname(const char *host
)
935 if (WSAStartup(MAKEWORD(2,2), &wsa
))
936 die("unable to initialize winsock subsystem, error %d",
938 atexit((void(*)(void)) WSACleanup
);
939 return gethostbyname(host
);
942 int mingw_socket(int domain
, int type
, int protocol
)
945 SOCKET s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
946 if (s
== INVALID_SOCKET
) {
948 * WSAGetLastError() values are regular BSD error codes
949 * biased by WSABASEERR.
950 * However, strerror() does not know about networking
951 * specific errors, which are values beginning at 38 or so.
952 * Therefore, we choose to leave the biased error code
953 * in errno so that _if_ someone looks up the code somewhere,
954 * then it is at least the number that are usually listed.
956 errno
= WSAGetLastError();
959 /* convert into a file descriptor */
960 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
962 return error("unable to make a socket file descriptor: %s",
969 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
971 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
972 return connect(s
, sa
, sz
);
976 int mingw_rename(const char *pold
, const char *pnew
)
980 static const int delay
[] = { 0, 1, 10, 20, 40 };
983 * Try native rename() first to get errno right.
984 * It is based on MoveFile(), which cannot overwrite existing files.
986 if (!rename(pold
, pnew
))
991 if (MoveFileEx(pold
, pnew
, MOVEFILE_REPLACE_EXISTING
))
993 /* TODO: translate more errors */
994 gle
= GetLastError();
995 if (gle
== ERROR_ACCESS_DENIED
&&
996 (attrs
= GetFileAttributes(pnew
)) != INVALID_FILE_ATTRIBUTES
) {
997 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
1001 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
1002 SetFileAttributes(pnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
1003 if (MoveFileEx(pold
, pnew
, MOVEFILE_REPLACE_EXISTING
))
1005 gle
= GetLastError();
1006 /* revert file attributes on failure */
1007 SetFileAttributes(pnew
, attrs
);
1010 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
1012 * We assume that some other process had the source or
1013 * destination file open at the wrong moment and retry.
1014 * In order to give the other process a higher chance to
1015 * complete its operation, we give up our time slice now.
1016 * If we have to retry again, we do sleep a bit.
1018 Sleep(delay
[tries
]);
1026 struct passwd
*getpwuid(int uid
)
1028 static char user_name
[100];
1029 static struct passwd p
;
1031 DWORD len
= sizeof(user_name
);
1032 if (!GetUserName(user_name
, &len
))
1034 p
.pw_name
= user_name
;
1035 p
.pw_gecos
= "unknown";
1040 static HANDLE timer_event
;
1041 static HANDLE timer_thread
;
1042 static int timer_interval
;
1043 static int one_shot
;
1044 static sig_handler_t timer_fn
= SIG_DFL
;
1047 * The timer works like this:
1048 * The thread, ticktack(), is a trivial routine that most of the time
1049 * only waits to receive the signal to terminate. The main thread tells
1050 * the thread to terminate by setting the timer_event to the signalled
1052 * But ticktack() interrupts the wait state after the timer's interval
1053 * length to call the signal handler.
1056 static unsigned __stdcall
ticktack(void *dummy
)
1058 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
1059 if (timer_fn
== SIG_DFL
)
1061 if (timer_fn
!= SIG_IGN
)
1069 static int start_timer_thread(void)
1071 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1073 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
1075 return errno
= ENOMEM
,
1076 error("cannot start timer thread");
1078 return errno
= ENOMEM
,
1079 error("cannot allocate resources for timer");
1083 static void stop_timer_thread(void)
1086 SetEvent(timer_event
); /* tell thread to terminate */
1088 int rc
= WaitForSingleObject(timer_thread
, 1000);
1089 if (rc
== WAIT_TIMEOUT
)
1090 error("timer thread did not terminate timely");
1091 else if (rc
!= WAIT_OBJECT_0
)
1092 error("waiting for timer thread failed: %lu",
1094 CloseHandle(timer_thread
);
1097 CloseHandle(timer_event
);
1099 timer_thread
= NULL
;
1102 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
1104 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
1107 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
1109 static const struct timeval zero
;
1110 static int atexit_done
;
1113 return errno
= EINVAL
,
1114 error("setitimer param 3 != NULL not implemented");
1115 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
1116 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
1117 return errno
= EINVAL
,
1118 error("setitimer: it_interval must be zero or eq it_value");
1121 stop_timer_thread();
1123 if (is_timeval_eq(&in
->it_value
, &zero
) &&
1124 is_timeval_eq(&in
->it_interval
, &zero
))
1127 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
1128 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
1130 atexit(stop_timer_thread
);
1133 return start_timer_thread();
1136 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
1139 return errno
= EINVAL
,
1140 error("sigaction only implemented for SIGALRM");
1142 return errno
= EINVAL
,
1143 error("sigaction: param 3 != NULL not implemented");
1145 timer_fn
= in
->sa_handler
;
1150 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
1152 sig_handler_t old
= timer_fn
;
1154 return signal(sig
, handler
);
1159 static const char *make_backslash_path(const char *path
)
1161 static char buf
[PATH_MAX
+ 1];
1164 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
1165 die("Too long path: %.*s", 60, path
);
1167 for (c
= buf
; *c
; c
++) {
1174 void mingw_open_html(const char *unixpath
)
1176 const char *htmlpath
= make_backslash_path(unixpath
);
1177 printf("Launching default browser to display HTML ...\n");
1178 ShellExecute(NULL
, "open", htmlpath
, NULL
, "\\", 0);
1181 int link(const char *oldpath
, const char *newpath
)
1183 typedef BOOL (WINAPI
*T
)(const char*, const char*, LPSECURITY_ATTRIBUTES
);
1184 static T create_hard_link
= NULL
;
1185 if (!create_hard_link
) {
1186 create_hard_link
= (T
) GetProcAddress(
1187 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1188 if (!create_hard_link
)
1189 create_hard_link
= (T
)-1;
1191 if (create_hard_link
== (T
)-1) {
1195 if (!create_hard_link(newpath
, oldpath
, NULL
)) {
1196 errno
= err_win_to_posix(GetLastError());
1202 int symlink(const char *oldpath
, const char *newpath
)
1204 typedef BOOL
WINAPI (*symlink_fn
)(const char*, const char*, DWORD
);
1205 static symlink_fn create_symbolic_link
= NULL
;
1206 if (!create_symbolic_link
) {
1207 create_symbolic_link
= (symlink_fn
) GetProcAddress(
1208 GetModuleHandle("kernel32.dll"), "CreateSymbolicLinkA");
1209 if (!create_symbolic_link
)
1210 create_symbolic_link
= (symlink_fn
)-1;
1212 if (create_symbolic_link
== (symlink_fn
)-1) {
1217 if (!create_symbolic_link(newpath
, oldpath
, 0)) {
1218 errno
= err_win_to_posix(GetLastError());
1224 int readlink(const char *path
, char *buf
, size_t bufsiz
)
1226 HANDLE handle
= CreateFile(path
, GENERIC_READ
,
1227 FILE_SHARE_READ
|FILE_SHARE_WRITE
|FILE_SHARE_DELETE
,
1228 NULL
, OPEN_EXISTING
,
1229 FILE_FLAG_BACKUP_SEMANTICS
| FILE_FLAG_OPEN_REPARSE_POINT
,
1232 if (handle
!= INVALID_HANDLE_VALUE
) {
1233 unsigned char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
1235 if (DeviceIoControl(handle
, FSCTL_GET_REPARSE_POINT
, NULL
, 0, buffer
,
1236 MAXIMUM_REPARSE_DATA_BUFFER_SIZE
, &dummy
, NULL
)) {
1237 REPARSE_DATA_BUFFER
*b
= (REPARSE_DATA_BUFFER
*) buffer
;
1238 if (b
->ReparseTag
== IO_REPARSE_TAG_SYMLINK
) {
1239 int len
= b
->SymbolicLinkReparseBuffer
.SubstituteNameLength
/ sizeof(wchar_t);
1240 int offset
= b
->SymbolicLinkReparseBuffer
.SubstituteNameOffset
/ sizeof(wchar_t);
1241 snprintf(buf
, bufsiz
, "%*ls", len
, & b
->SymbolicLinkReparseBuffer
.PathBuffer
[offset
]);
1242 CloseHandle(handle
);
1247 CloseHandle(handle
);
1254 char *getpass(const char *prompt
)
1256 struct strbuf buf
= STRBUF_INIT
;
1258 fputs(prompt
, stderr
);
1261 if (c
== '\r' || c
== '\n')
1263 strbuf_addch(&buf
, c
);
1265 fputs("\n", stderr
);
1266 return strbuf_detach(&buf
, NULL
);
1269 #ifndef NO_MINGW_REPLACE_READDIR
1270 /* MinGW readdir implementation to avoid extra lstats for Git */
1273 struct _finddata_t dd_dta
; /* disk transfer area for this dir */
1274 struct mingw_dirent dd_dir
; /* Our own implementation, including d_type */
1275 long dd_handle
; /* _findnext handle */
1276 int dd_stat
; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1277 char dd_name
[1]; /* given path for dir with search pattern (struct is extended) */
1280 struct dirent
*mingw_readdir(DIR *dir
)
1282 WIN32_FIND_DATAA buf
;
1284 struct mingw_DIR
*mdir
= (struct mingw_DIR
*)dir
;
1286 if (!dir
->dd_handle
) {
1287 errno
= EBADF
; /* No set_errno for mingw */
1291 if (dir
->dd_handle
== (long)INVALID_HANDLE_VALUE
&& dir
->dd_stat
== 0)
1294 handle
= FindFirstFileA(dir
->dd_name
, &buf
);
1295 lasterr
= GetLastError();
1296 dir
->dd_handle
= (long)handle
;
1297 if (handle
== INVALID_HANDLE_VALUE
&& (lasterr
!= ERROR_NO_MORE_FILES
)) {
1298 errno
= err_win_to_posix(lasterr
);
1301 } else if (dir
->dd_handle
== (long)INVALID_HANDLE_VALUE
) {
1303 } else if (!FindNextFileA((HANDLE
)dir
->dd_handle
, &buf
)) {
1304 DWORD lasterr
= GetLastError();
1305 FindClose((HANDLE
)dir
->dd_handle
);
1306 dir
->dd_handle
= (long)INVALID_HANDLE_VALUE
;
1308 * POSIX says you shouldn't set errno when readdir can't
1309 * find any more files; so, if another error we leave it set.
1311 if (lasterr
!= ERROR_NO_MORE_FILES
)
1312 errno
= err_win_to_posix(lasterr
);
1316 /* We get here if `buf' contains valid data. */
1317 strcpy(dir
->dd_dir
.d_name
, buf
.cFileName
);
1320 /* Set file type, based on WIN32_FIND_DATA */
1321 mdir
->dd_dir
.d_type
= 0;
1322 if ((buf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
1323 (buf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
))
1324 mdir
->dd_dir
.d_type
|= DT_LNK
;
1325 else if (buf
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1326 mdir
->dd_dir
.d_type
|= DT_DIR
;
1328 mdir
->dd_dir
.d_type
|= DT_REG
;
1330 return (struct dirent
*)&dir
->dd_dir
;
1332 #endif // !NO_MINGW_REPLACE_READDIR