1 #include "../git-compat-util.h"
5 #include "../run-command.h"
7 static const int delay
[] = { 0, 1, 10, 20, 40 };
9 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;
122 static inline int is_file_in_use_error(DWORD errcode
)
125 case ERROR_SHARING_VIOLATION
:
126 case ERROR_ACCESS_DENIED
:
133 static int read_yes_no_answer(void)
137 if (fgets(answer
, sizeof(answer
), stdin
)) {
138 size_t answer_len
= strlen(answer
);
139 int got_full_line
= 0, c
;
141 /* remove the newline */
142 if (answer_len
>= 2 && answer
[answer_len
-2] == '\r') {
143 answer
[answer_len
-2] = '\0';
145 } else if (answer_len
>= 1 && answer
[answer_len
-1] == '\n') {
146 answer
[answer_len
-1] = '\0';
149 /* flush the buffer in case we did not get the full line */
151 while ((c
= getchar()) != EOF
&& c
!= '\n')
154 /* we could not read, return the
155 * default answer which is no */
158 if (tolower(answer
[0]) == 'y' && !answer
[1])
160 if (!strncasecmp(answer
, "yes", sizeof(answer
)))
162 if (tolower(answer
[0]) == 'n' && !answer
[1])
164 if (!strncasecmp(answer
, "no", sizeof(answer
)))
167 /* did not find an answer we understand */
171 static int ask_yes_no_if_possible(const char *format
, ...)
174 const char *retry_hook
[] = { NULL
, NULL
, NULL
};
177 va_start(args
, format
);
178 vsnprintf(question
, sizeof(question
), format
, args
);
181 if ((retry_hook
[0] = mingw_getenv("GIT_ASK_YESNO"))) {
182 retry_hook
[1] = question
;
183 return !run_command_v_opt(retry_hook
, 0);
186 if (!isatty(_fileno(stdin
)) || !isatty(_fileno(stderr
)))
191 fprintf(stderr
, "%s (y/n) ", question
);
193 if ((answer
= read_yes_no_answer()) >= 0)
196 fprintf(stderr
, "Sorry, I did not understand your answer. "
197 "Please type 'y' or 'n'\n");
202 int mingw_unlink(const char *pathname
)
206 /* read-only files cannot be removed */
207 chmod(pathname
, 0666);
208 while ((ret
= unlink(pathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
209 if (!is_file_in_use_error(GetLastError()))
212 * We assume that some other process had the source or
213 * destination file open at the wrong moment and retry.
214 * In order to give the other process a higher chance to
215 * complete its operation, we give up our time slice now.
216 * If we have to retry again, we do sleep a bit.
221 while (ret
== -1 && is_file_in_use_error(GetLastError()) &&
222 ask_yes_no_if_possible("Unlink of file '%s' failed. "
223 "Should I try again?", pathname
))
224 ret
= unlink(pathname
);
228 static int is_dir_empty(const char *path
)
230 struct strbuf buf
= STRBUF_INIT
;
231 WIN32_FIND_DATAA findbuf
;
234 strbuf_addf(&buf
, "%s\\*", path
);
235 handle
= FindFirstFileA(buf
.buf
, &findbuf
);
236 if (handle
== INVALID_HANDLE_VALUE
) {
237 strbuf_release(&buf
);
238 return GetLastError() == ERROR_NO_MORE_FILES
;
241 while (!strcmp(findbuf
.cFileName
, ".") ||
242 !strcmp(findbuf
.cFileName
, ".."))
243 if (!FindNextFile(handle
, &findbuf
)) {
244 strbuf_release(&buf
);
245 return GetLastError() == ERROR_NO_MORE_FILES
;
248 strbuf_release(&buf
);
253 int mingw_rmdir(const char *pathname
)
257 while ((ret
= rmdir(pathname
)) == -1 && tries
< ARRAY_SIZE(delay
)) {
258 if (!is_file_in_use_error(GetLastError()))
259 errno
= err_win_to_posix(GetLastError());
262 if (!is_dir_empty(pathname
)) {
267 * We assume that some other process had the source or
268 * destination file open at the wrong moment and retry.
269 * In order to give the other process a higher chance to
270 * complete its operation, we give up our time slice now.
271 * If we have to retry again, we do sleep a bit.
276 while (ret
== -1 && errno
== EACCES
&& is_file_in_use_error(GetLastError()) &&
277 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
278 "Should I try again?", pathname
))
279 ret
= rmdir(pathname
);
284 int mingw_open (const char *filename
, int oflags
, ...)
290 va_start(args
, oflags
);
291 mode
= va_arg(args
, int);
294 if (filename
&& !strcmp(filename
, "/dev/null"))
297 fd
= open(filename
, oflags
, mode
);
299 if (fd
< 0 && (oflags
& O_CREAT
) && errno
== EACCES
) {
300 DWORD attrs
= GetFileAttributes(filename
);
301 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
308 ssize_t
mingw_write(int fd
, const void *buf
, size_t count
)
311 * While write() calls to a file on a local disk are translated
312 * into WriteFile() calls with a maximum size of 64KB on Windows
313 * XP and 256KB on Vista, no such cap is placed on writes to
314 * files over the network on Windows XP. Unfortunately, there
315 * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
316 * bigger writes fail on Windows XP.
317 * So we cap to a nice 31MB here to avoid write failures over
318 * the net without changing the number of WriteFile() calls in
321 return write(fd
, buf
, min(count
, 31 * 1024 * 1024));
324 static BOOL WINAPI
ctrl_ignore(DWORD type
)
330 int mingw_fgetc(FILE *stream
)
333 if (!isatty(_fileno(stream
)))
334 return fgetc(stream
);
336 SetConsoleCtrlHandler(ctrl_ignore
, TRUE
);
339 if (ch
!= EOF
|| GetLastError() != ERROR_OPERATION_ABORTED
)
342 /* Ctrl+C was pressed, simulate SIGINT and retry */
345 SetConsoleCtrlHandler(ctrl_ignore
, FALSE
);
350 FILE *mingw_fopen (const char *filename
, const char *otype
)
352 if (filename
&& !strcmp(filename
, "/dev/null"))
354 return fopen(filename
, otype
);
358 FILE *mingw_freopen (const char *filename
, const char *otype
, FILE *stream
)
360 if (filename
&& !strcmp(filename
, "/dev/null"))
362 return freopen(filename
, otype
, stream
);
366 int mingw_fflush(FILE *stream
)
368 int ret
= fflush(stream
);
371 * write() is used behind the scenes of stdio output functions.
372 * Since git code does not check for errors after each stdio write
373 * operation, it can happen that write() is called by a later
374 * stdio function even if an earlier write() call failed. In the
375 * case of a pipe whose readable end was closed, only the first
376 * call to write() reports EPIPE on Windows. Subsequent write()
377 * calls report EINVAL. It is impossible to notice whether this
378 * fflush invocation triggered such a case, therefore, we have to
379 * catch all EINVAL errors whole-sale.
381 if (ret
&& errno
== EINVAL
)
388 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
389 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
391 static inline long long filetime_to_hnsec(const FILETIME
*ft
)
393 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
394 /* Windows to Unix Epoch conversion */
395 return winTime
- 116444736000000000LL;
398 static inline time_t filetime_to_time_t(const FILETIME
*ft
)
400 return (time_t)(filetime_to_hnsec(ft
) / 10000000);
403 /* We keep the do_lstat code in a separate function to avoid recursion.
404 * When a path ends with a slash, the stat will fail with ENOENT. In
405 * this case, we strip the trailing slashes and stat again.
407 * If follow is true then act like stat() and report on the link
408 * target. Otherwise report on the link itself.
410 static int do_lstat(int follow
, const char *file_name
, struct stat
*buf
)
413 WIN32_FILE_ATTRIBUTE_DATA fdata
;
415 if (!(err
= get_file_attr(file_name
, &fdata
))) {
420 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
421 buf
->st_size
= fdata
.nFileSizeLow
|
422 (((off_t
)fdata
.nFileSizeHigh
)<<32);
423 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
424 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
425 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
426 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
427 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
428 WIN32_FIND_DATAA findbuf
;
429 HANDLE handle
= FindFirstFileA(file_name
, &findbuf
);
430 if (handle
!= INVALID_HANDLE_VALUE
) {
431 if ((findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) &&
432 (findbuf
.dwReserved0
== IO_REPARSE_TAG_SYMLINK
)) {
434 char buffer
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
435 buf
->st_size
= readlink(file_name
, buffer
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
);
437 buf
->st_mode
= S_IFLNK
;
439 buf
->st_mode
|= S_IREAD
;
440 if (!(findbuf
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
441 buf
->st_mode
|= S_IWRITE
;
452 /* We provide our own lstat/fstat functions, since the provided
453 * lstat/fstat functions are so slow. These stat functions are
454 * tailored for Git's usage (read: fast), and are not meant to be
455 * complete. Note that Git stat()s are redirected to mingw_lstat()
456 * too, since Windows doesn't really handle symlinks that well.
458 static int do_stat_internal(int follow
, const char *file_name
, struct stat
*buf
)
461 static char alt_name
[PATH_MAX
];
463 if (!do_lstat(follow
, file_name
, buf
))
466 /* if file_name ended in a '/', Windows returned ENOENT;
467 * try again without trailing slashes
472 namelen
= strlen(file_name
);
473 if (namelen
&& file_name
[namelen
-1] != '/')
475 while (namelen
&& file_name
[namelen
-1] == '/')
477 if (!namelen
|| namelen
>= PATH_MAX
)
480 memcpy(alt_name
, file_name
, namelen
);
481 alt_name
[namelen
] = 0;
482 return do_lstat(follow
, alt_name
, buf
);
485 int mingw_lstat(const char *file_name
, struct stat
*buf
)
487 return do_stat_internal(0, file_name
, buf
);
489 int mingw_stat(const char *file_name
, struct stat
*buf
)
491 return do_stat_internal(1, file_name
, buf
);
494 int mingw_fstat(int fd
, struct stat
*buf
)
496 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
497 BY_HANDLE_FILE_INFORMATION fdata
;
499 if (fh
== INVALID_HANDLE_VALUE
) {
503 /* direct non-file handles to MS's fstat() */
504 if (GetFileType(fh
) != FILE_TYPE_DISK
)
505 return _fstati64(fd
, buf
);
507 if (GetFileInformationByHandle(fh
, &fdata
)) {
512 buf
->st_mode
= file_attr_to_st_mode(fdata
.dwFileAttributes
);
513 buf
->st_size
= fdata
.nFileSizeLow
|
514 (((off_t
)fdata
.nFileSizeHigh
)<<32);
515 buf
->st_dev
= buf
->st_rdev
= 0; /* not used by Git */
516 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
517 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
518 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
525 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
527 long long winTime
= t
* 10000000LL + 116444736000000000LL;
528 ft
->dwLowDateTime
= winTime
;
529 ft
->dwHighDateTime
= winTime
>> 32;
532 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
537 /* must have write permission */
538 DWORD attrs
= GetFileAttributes(file_name
);
539 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
540 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
541 /* ignore errors here; open() will report them */
542 SetFileAttributes(file_name
, attrs
& ~FILE_ATTRIBUTE_READONLY
);
545 if ((fh
= open(file_name
, O_RDWR
| O_BINARY
)) < 0) {
551 time_t_to_filetime(times
->modtime
, &mft
);
552 time_t_to_filetime(times
->actime
, &aft
);
554 GetSystemTimeAsFileTime(&mft
);
557 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
565 if (attrs
!= INVALID_FILE_ATTRIBUTES
&&
566 (attrs
& FILE_ATTRIBUTE_READONLY
)) {
567 /* ignore errors again */
568 SetFileAttributes(file_name
, attrs
);
573 unsigned int sleep (unsigned int seconds
)
579 int mkstemp(char *template)
581 char *filename
= mktemp(template);
582 if (filename
== NULL
)
584 return open(filename
, O_RDWR
| O_CREAT
, 0600);
587 int gettimeofday(struct timeval
*tv
, void *tz
)
592 GetSystemTimeAsFileTime(&ft
);
593 hnsec
= filetime_to_hnsec(&ft
);
594 tv
->tv_sec
= hnsec
/ 10000000;
595 tv
->tv_usec
= (hnsec
% 10000000) / 10;
599 int pipe(int filedes
[2])
603 /* this creates non-inheritable handles */
604 if (!CreatePipe(&h
[0], &h
[1], NULL
, 8192)) {
605 errno
= err_win_to_posix(GetLastError());
608 filedes
[0] = _open_osfhandle((int)h
[0], O_NOINHERIT
);
609 if (filedes
[0] < 0) {
614 filedes
[1] = _open_osfhandle((int)h
[1], O_NOINHERIT
);
615 if (filedes
[0] < 0) {
623 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
625 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
626 memcpy(result
, gmtime(timep
), sizeof(struct tm
));
630 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
632 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
633 memcpy(result
, localtime(timep
), sizeof(struct tm
));
638 char *mingw_getcwd(char *pointer
, int len
)
641 char *ret
= getcwd(pointer
, len
);
644 for (i
= 0; pointer
[i
]; i
++)
645 if (pointer
[i
] == '\\')
651 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
652 * (Parsing C++ Command-Line Arguments)
654 static const char *quote_arg(const char *arg
)
656 /* count chars to quote */
658 int force_quotes
= 0;
661 if (!*p
) force_quotes
= 1;
663 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{' || *p
== '\'')
667 else if (*p
== '\\') {
681 if (!force_quotes
&& n
== 0)
684 /* insert \ where necessary */
685 d
= q
= xmalloc(len
+n
+3);
690 else if (*arg
== '\\') {
692 while (*arg
== '\\') {
709 static const char *parse_interpreter(const char *cmd
)
711 static char buf
[100];
715 /* don't even try a .exe */
717 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
720 fd
= open(cmd
, O_RDONLY
);
723 n
= read(fd
, buf
, sizeof(buf
)-1);
725 if (n
< 4) /* at least '#!/x' and not error */
728 if (buf
[0] != '#' || buf
[1] != '!')
731 p
= buf
+ strcspn(buf
, "\r\n");
736 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
739 if ((opt
= strchr(p
+1, ' ')))
745 * Splits the PATH into parts.
747 static char **get_path_split(void)
749 char *p
, **path
, *envpath
= mingw_getenv("PATH");
752 if (!envpath
|| !*envpath
)
755 envpath
= xstrdup(envpath
);
761 if (*dir
) { /* not earlier, catches series of ; */
768 path
= xmalloc((n
+1)*sizeof(char *));
773 path
[i
++] = xstrdup(p
);
783 static void free_path_split(char **path
)
796 * exe_only means that we only want to detect .exe files, but not scripts
797 * (which do not have an extension)
799 static char *lookup_prog(const char *dir
, const char *cmd
, int isexe
, int exe_only
)
802 snprintf(path
, sizeof(path
), "%s/%s.exe", dir
, cmd
);
804 if (!isexe
&& access(path
, F_OK
) == 0)
805 return xstrdup(path
);
806 path
[strlen(path
)-4] = '\0';
807 if ((!exe_only
|| isexe
) && access(path
, F_OK
) == 0)
808 if (!(GetFileAttributes(path
) & FILE_ATTRIBUTE_DIRECTORY
))
809 return xstrdup(path
);
814 * Determines the absolute path of cmd using the split path in path.
815 * If cmd contains a slash or backslash, no lookup is performed.
817 static char *path_lookup(const char *cmd
, char **path
, int exe_only
)
820 int len
= strlen(cmd
);
821 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
823 if (strchr(cmd
, '/') || strchr(cmd
, '\\'))
826 while (!prog
&& *path
)
827 prog
= lookup_prog(*path
++, cmd
, isexe
, exe_only
);
832 static int env_compare(const void *a
, const void *b
)
836 return strcasecmp(*ea
, *eb
);
840 struct pinfo_t
*next
;
844 static struct pinfo_t
*pinfo
= NULL
;
845 CRITICAL_SECTION pinfo_cs
;
847 static pid_t
mingw_spawnve_fd(const char *cmd
, const char **argv
, char **env
,
849 int prepend_cmd
, int fhin
, int fhout
, int fherr
)
852 PROCESS_INFORMATION pi
;
853 struct strbuf envblk
, args
;
857 /* Determine whether or not we are associated to a console */
858 HANDLE cons
= CreateFile("CONOUT$", GENERIC_WRITE
,
859 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
860 FILE_ATTRIBUTE_NORMAL
, NULL
);
861 if (cons
== INVALID_HANDLE_VALUE
) {
862 /* There is no console associated with this process.
863 * Since the child is a console process, Windows
864 * would normally create a console window. But
865 * since we'll be redirecting std streams, we do
866 * not need the console.
867 * It is necessary to use DETACHED_PROCESS
868 * instead of CREATE_NO_WINDOW to make ssh
869 * recognize that it has no console.
871 flags
= DETACHED_PROCESS
;
873 /* There is already a console. If we specified
874 * DETACHED_PROCESS here, too, Windows would
875 * disassociate the child from the console.
876 * The same is true for CREATE_NO_WINDOW.
882 memset(&si
, 0, sizeof(si
));
884 si
.dwFlags
= STARTF_USESTDHANDLES
;
885 si
.hStdInput
= (HANDLE
) _get_osfhandle(fhin
);
886 si
.hStdOutput
= (HANDLE
) _get_osfhandle(fhout
);
887 si
.hStdError
= (HANDLE
) _get_osfhandle(fherr
);
889 /* concatenate argv, quoting args as we go */
890 strbuf_init(&args
, 0);
892 char *quoted
= (char *)quote_arg(cmd
);
893 strbuf_addstr(&args
, quoted
);
897 for (; *argv
; argv
++) {
898 char *quoted
= (char *)quote_arg(*argv
);
900 strbuf_addch(&args
, ' ');
901 strbuf_addstr(&args
, quoted
);
908 char **e
, **sorted_env
;
910 for (e
= env
; *e
; e
++)
913 /* environment must be sorted */
914 sorted_env
= xmalloc(sizeof(*sorted_env
) * (count
+ 1));
915 memcpy(sorted_env
, env
, sizeof(*sorted_env
) * (count
+ 1));
916 qsort(sorted_env
, count
, sizeof(*sorted_env
), env_compare
);
918 strbuf_init(&envblk
, 0);
919 for (e
= sorted_env
; *e
; e
++) {
920 strbuf_addstr(&envblk
, *e
);
921 strbuf_addch(&envblk
, '\0');
926 memset(&pi
, 0, sizeof(pi
));
927 ret
= CreateProcess(cmd
, args
.buf
, NULL
, NULL
, TRUE
, flags
,
928 env
? envblk
.buf
: NULL
, dir
, &si
, &pi
);
931 strbuf_release(&envblk
);
932 strbuf_release(&args
);
938 CloseHandle(pi
.hThread
);
941 * The process ID is the human-readable identifier of the process
942 * that we want to present in log and error messages. The handle
943 * is not useful for this purpose. But we cannot close it, either,
944 * because it is not possible to turn a process ID into a process
945 * handle after the process terminated.
946 * Keep the handle in a list for waitpid.
948 EnterCriticalSection(&pinfo_cs
);
950 struct pinfo_t
*info
= xmalloc(sizeof(struct pinfo_t
));
951 info
->pid
= pi
.dwProcessId
;
952 info
->proc
= pi
.hProcess
;
956 LeaveCriticalSection(&pinfo_cs
);
958 return (pid_t
)pi
.dwProcessId
;
961 static pid_t
mingw_spawnve(const char *cmd
, const char **argv
, char **env
,
964 return mingw_spawnve_fd(cmd
, argv
, env
, NULL
, prepend_cmd
, 0, 1, 2);
967 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **env
,
969 int fhin
, int fhout
, int fherr
)
972 char **path
= get_path_split();
973 char *prog
= path_lookup(cmd
, path
, 0);
980 const char *interpr
= parse_interpreter(prog
);
983 const char *argv0
= argv
[0];
984 char *iprog
= path_lookup(interpr
, path
, 1);
991 pid
= mingw_spawnve_fd(iprog
, argv
, env
, dir
, 1,
998 pid
= mingw_spawnve_fd(prog
, argv
, env
, dir
, 0,
1002 free_path_split(path
);
1006 static int try_shell_exec(const char *cmd
, char *const *argv
, char **env
)
1008 const char *interpr
= parse_interpreter(cmd
);
1015 path
= get_path_split();
1016 prog
= path_lookup(interpr
, path
, 1);
1020 while (argv
[argc
]) argc
++;
1021 argv2
= xmalloc(sizeof(*argv
) * (argc
+1));
1022 argv2
[0] = (char *)cmd
; /* full path to the script file */
1023 memcpy(&argv2
[1], &argv
[1], sizeof(*argv
) * argc
);
1024 pid
= mingw_spawnve(prog
, argv2
, env
, 1);
1027 if (waitpid(pid
, &status
, 0) < 0)
1031 pid
= 1; /* indicate that we tried but failed */
1035 free_path_split(path
);
1039 static void mingw_execve(const char *cmd
, char *const *argv
, char *const *env
)
1041 /* check if git_command is a shell script */
1042 if (!try_shell_exec(cmd
, argv
, (char **)env
)) {
1045 pid
= mingw_spawnve(cmd
, (const char **)argv
, (char **)env
, 0);
1048 if (waitpid(pid
, &status
, 0) < 0)
1054 int mingw_execvp(const char *cmd
, char *const *argv
)
1056 char **path
= get_path_split();
1057 char *prog
= path_lookup(cmd
, path
, 0);
1060 mingw_execve(prog
, argv
, environ
);
1065 free_path_split(path
);
1069 int mingw_execv(const char *cmd
, char *const *argv
)
1071 mingw_execve(cmd
, argv
, environ
);
1075 int mingw_kill(pid_t pid
, int sig
)
1077 if (pid
> 0 && sig
== SIGTERM
) {
1078 HANDLE h
= OpenProcess(PROCESS_TERMINATE
, FALSE
, pid
);
1080 if (TerminateProcess(h
, -1)) {
1085 errno
= err_win_to_posix(GetLastError());
1088 } else if (pid
> 0 && sig
== 0) {
1089 HANDLE h
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
1100 static char **copy_environ(void)
1106 env
= xmalloc((i
+1)*sizeof(*env
));
1107 for (i
= 0; environ
[i
]; i
++)
1108 env
[i
] = xstrdup(environ
[i
]);
1113 void free_environ(char **env
)
1116 for (i
= 0; env
[i
]; i
++)
1121 static int lookup_env(char **env
, const char *name
, size_t nmln
)
1125 for (i
= 0; env
[i
]; i
++) {
1126 if (0 == strncmp(env
[i
], name
, nmln
)
1127 && '=' == env
[i
][nmln
])
1135 * If name contains '=', then sets the variable, otherwise it unsets it
1137 static char **env_setenv(char **env
, const char *name
)
1139 char *eq
= strchrnul(name
, '=');
1140 int i
= lookup_env(env
, name
, eq
-name
);
1144 for (i
= 0; env
[i
]; i
++)
1146 env
= xrealloc(env
, (i
+2)*sizeof(*env
));
1147 env
[i
] = xstrdup(name
);
1154 env
[i
] = xstrdup(name
);
1163 * Copies global environ and adjusts variables as specified by vars.
1165 char **make_augmented_environ(const char *const *vars
)
1167 char **env
= copy_environ();
1170 env
= env_setenv(env
, *vars
++);
1177 * The system's getenv looks up the name in a case-insensitive manner.
1178 * This version tries a case-sensitive lookup and falls back to
1179 * case-insensitive if nothing was found. This is necessary because,
1180 * as a prominent example, CMD sets 'Path', but not 'PATH'.
1181 * Warning: not thread-safe.
1183 static char *getenv_cs(const char *name
)
1185 size_t len
= strlen(name
);
1186 int i
= lookup_env(environ
, name
, len
);
1188 return environ
[i
] + len
+ 1; /* skip past name and '=' */
1189 return getenv(name
);
1192 char *mingw_getenv(const char *name
)
1194 char *result
= getenv_cs(name
);
1195 if (!result
&& !strcmp(name
, "TMPDIR")) {
1196 /* on Windows it is TMP and TEMP */
1197 result
= getenv_cs("TMP");
1199 result
= getenv_cs("TEMP");
1205 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1206 * that service contains a numerical port, or that it is null. It
1207 * does a simple search using gethostbyname, and returns one IPv4 host
1210 static int WSAAPI
getaddrinfo_stub(const char *node
, const char *service
,
1211 const struct addrinfo
*hints
,
1212 struct addrinfo
**res
)
1214 struct hostent
*h
= NULL
;
1215 struct addrinfo
*ai
;
1216 struct sockaddr_in
*sin
;
1219 h
= gethostbyname(node
);
1221 return WSAGetLastError();
1224 ai
= xmalloc(sizeof(struct addrinfo
));
1227 ai
->ai_family
= AF_INET
;
1228 ai
->ai_socktype
= hints
? hints
->ai_socktype
: 0;
1229 switch (ai
->ai_socktype
) {
1231 ai
->ai_protocol
= IPPROTO_TCP
;
1234 ai
->ai_protocol
= IPPROTO_UDP
;
1237 ai
->ai_protocol
= 0;
1240 ai
->ai_addrlen
= sizeof(struct sockaddr_in
);
1241 if (hints
&& (hints
->ai_flags
& AI_CANONNAME
))
1242 ai
->ai_canonname
= h
? xstrdup(h
->h_name
) : NULL
;
1244 ai
->ai_canonname
= NULL
;
1246 sin
= xmalloc(ai
->ai_addrlen
);
1247 memset(sin
, 0, ai
->ai_addrlen
);
1248 sin
->sin_family
= AF_INET
;
1249 /* Note: getaddrinfo is supposed to allow service to be a string,
1250 * which should be looked up using getservbyname. This is
1251 * currently not implemented */
1253 sin
->sin_port
= htons(atoi(service
));
1255 sin
->sin_addr
= *(struct in_addr
*)h
->h_addr
;
1256 else if (hints
&& (hints
->ai_flags
& AI_PASSIVE
))
1257 sin
->sin_addr
.s_addr
= INADDR_ANY
;
1259 sin
->sin_addr
.s_addr
= INADDR_LOOPBACK
;
1260 ai
->ai_addr
= (struct sockaddr
*)sin
;
1265 static void WSAAPI
freeaddrinfo_stub(struct addrinfo
*res
)
1267 free(res
->ai_canonname
);
1272 static int WSAAPI
getnameinfo_stub(const struct sockaddr
*sa
, socklen_t salen
,
1273 char *host
, DWORD hostlen
,
1274 char *serv
, DWORD servlen
, int flags
)
1276 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)sa
;
1277 if (sa
->sa_family
!= AF_INET
)
1282 if (host
&& hostlen
> 0) {
1283 struct hostent
*ent
= NULL
;
1284 if (!(flags
& NI_NUMERICHOST
))
1285 ent
= gethostbyaddr((const char *)&sin
->sin_addr
,
1286 sizeof(sin
->sin_addr
), AF_INET
);
1289 snprintf(host
, hostlen
, "%s", ent
->h_name
);
1290 else if (flags
& NI_NAMEREQD
)
1293 snprintf(host
, hostlen
, "%s", inet_ntoa(sin
->sin_addr
));
1296 if (serv
&& servlen
> 0) {
1297 struct servent
*ent
= NULL
;
1298 if (!(flags
& NI_NUMERICSERV
))
1299 ent
= getservbyport(sin
->sin_port
,
1300 flags
& NI_DGRAM
? "udp" : "tcp");
1303 snprintf(serv
, servlen
, "%s", ent
->s_name
);
1305 snprintf(serv
, servlen
, "%d", ntohs(sin
->sin_port
));
1311 static HMODULE ipv6_dll
= NULL
;
1312 static void (WSAAPI
*ipv6_freeaddrinfo
)(struct addrinfo
*res
);
1313 static int (WSAAPI
*ipv6_getaddrinfo
)(const char *node
, const char *service
,
1314 const struct addrinfo
*hints
,
1315 struct addrinfo
**res
);
1316 static int (WSAAPI
*ipv6_getnameinfo
)(const struct sockaddr
*sa
, socklen_t salen
,
1317 char *host
, DWORD hostlen
,
1318 char *serv
, DWORD servlen
, int flags
);
1320 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1321 * don't need to try to load that one dynamically.
1324 static void socket_cleanup(void)
1328 FreeLibrary(ipv6_dll
);
1330 ipv6_freeaddrinfo
= freeaddrinfo_stub
;
1331 ipv6_getaddrinfo
= getaddrinfo_stub
;
1332 ipv6_getnameinfo
= getnameinfo_stub
;
1335 static void ensure_socket_initialization(void)
1338 static int initialized
= 0;
1339 const char *libraries
[] = { "ws2_32.dll", "wship6.dll", NULL
};
1345 if (WSAStartup(MAKEWORD(2,2), &wsa
))
1346 die("unable to initialize winsock subsystem, error %d",
1349 for (name
= libraries
; *name
; name
++) {
1350 ipv6_dll
= LoadLibrary(*name
);
1354 ipv6_freeaddrinfo
= (void (WSAAPI
*)(struct addrinfo
*))
1355 GetProcAddress(ipv6_dll
, "freeaddrinfo");
1356 ipv6_getaddrinfo
= (int (WSAAPI
*)(const char *, const char *,
1357 const struct addrinfo
*,
1358 struct addrinfo
**))
1359 GetProcAddress(ipv6_dll
, "getaddrinfo");
1360 ipv6_getnameinfo
= (int (WSAAPI
*)(const struct sockaddr
*,
1361 socklen_t
, char *, DWORD
,
1362 char *, DWORD
, int))
1363 GetProcAddress(ipv6_dll
, "getnameinfo");
1364 if (!ipv6_freeaddrinfo
|| !ipv6_getaddrinfo
|| !ipv6_getnameinfo
) {
1365 FreeLibrary(ipv6_dll
);
1370 if (!ipv6_freeaddrinfo
|| !ipv6_getaddrinfo
|| !ipv6_getnameinfo
) {
1371 ipv6_freeaddrinfo
= freeaddrinfo_stub
;
1372 ipv6_getaddrinfo
= getaddrinfo_stub
;
1373 ipv6_getnameinfo
= getnameinfo_stub
;
1376 atexit(socket_cleanup
);
1381 int mingw_gethostname(char *name
, int namelen
)
1383 ensure_socket_initialization();
1384 return gethostname(name
, namelen
);
1387 #undef gethostbyname
1388 struct hostent
*mingw_gethostbyname(const char *host
)
1390 ensure_socket_initialization();
1391 return gethostbyname(host
);
1394 void mingw_freeaddrinfo(struct addrinfo
*res
)
1396 ipv6_freeaddrinfo(res
);
1399 int mingw_getaddrinfo(const char *node
, const char *service
,
1400 const struct addrinfo
*hints
, struct addrinfo
**res
)
1402 ensure_socket_initialization();
1403 return ipv6_getaddrinfo(node
, service
, hints
, res
);
1406 int mingw_getnameinfo(const struct sockaddr
*sa
, socklen_t salen
,
1407 char *host
, DWORD hostlen
, char *serv
, DWORD servlen
,
1410 ensure_socket_initialization();
1411 return ipv6_getnameinfo(sa
, salen
, host
, hostlen
, serv
, servlen
, flags
);
1414 int mingw_socket(int domain
, int type
, int protocol
)
1419 ensure_socket_initialization();
1420 s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
1421 if (s
== INVALID_SOCKET
) {
1423 * WSAGetLastError() values are regular BSD error codes
1424 * biased by WSABASEERR.
1425 * However, strerror() does not know about networking
1426 * specific errors, which are values beginning at 38 or so.
1427 * Therefore, we choose to leave the biased error code
1428 * in errno so that _if_ someone looks up the code somewhere,
1429 * then it is at least the number that are usually listed.
1431 errno
= WSAGetLastError();
1434 /* convert into a file descriptor */
1435 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
1437 return error("unable to make a socket file descriptor: %s",
1444 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
1446 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1447 return connect(s
, sa
, sz
);
1451 int mingw_bind(int sockfd
, struct sockaddr
*sa
, size_t sz
)
1453 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1454 return bind(s
, sa
, sz
);
1458 int mingw_setsockopt(int sockfd
, int lvl
, int optname
, void *optval
, int optlen
)
1460 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1461 return setsockopt(s
, lvl
, optname
, (const char*)optval
, optlen
);
1465 int mingw_shutdown(int sockfd
, int how
)
1467 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1468 return shutdown(s
, how
);
1472 int mingw_listen(int sockfd
, int backlog
)
1474 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
1475 return listen(s
, backlog
);
1479 int mingw_accept(int sockfd1
, struct sockaddr
*sa
, socklen_t
*sz
)
1483 SOCKET s1
= (SOCKET
)_get_osfhandle(sockfd1
);
1484 SOCKET s2
= accept(s1
, sa
, sz
);
1486 /* convert into a file descriptor */
1487 if ((sockfd2
= _open_osfhandle(s2
, O_RDWR
|O_BINARY
)) < 0) {
1490 return error("unable to make a socket file descriptor: %s",
1497 int mingw_rename(const char *pold
, const char *pnew
)
1503 * Try native rename() first to get errno right.
1504 * It is based on MoveFile(), which cannot overwrite existing files.
1506 if (!rename(pold
, pnew
))
1508 if (errno
!= EEXIST
)
1511 if (MoveFileEx(pold
, pnew
, MOVEFILE_REPLACE_EXISTING
))
1513 /* TODO: translate more errors */
1514 gle
= GetLastError();
1515 if (gle
== ERROR_ACCESS_DENIED
&&
1516 (attrs
= GetFileAttributes(pnew
)) != INVALID_FILE_ATTRIBUTES
) {
1517 if (attrs
& FILE_ATTRIBUTE_DIRECTORY
) {
1521 if ((attrs
& FILE_ATTRIBUTE_READONLY
) &&
1522 SetFileAttributes(pnew
, attrs
& ~FILE_ATTRIBUTE_READONLY
)) {
1523 if (MoveFileEx(pold
, pnew
, MOVEFILE_REPLACE_EXISTING
))
1525 gle
= GetLastError();
1526 /* revert file attributes on failure */
1527 SetFileAttributes(pnew
, attrs
);
1530 if (tries
< ARRAY_SIZE(delay
) && gle
== ERROR_ACCESS_DENIED
) {
1532 * We assume that some other process had the source or
1533 * destination file open at the wrong moment and retry.
1534 * In order to give the other process a higher chance to
1535 * complete its operation, we give up our time slice now.
1536 * If we have to retry again, we do sleep a bit.
1538 Sleep(delay
[tries
]);
1542 if (gle
== ERROR_ACCESS_DENIED
&&
1543 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1544 "Should I try again?", pold
, pnew
))
1552 * Note that this doesn't return the actual pagesize, but
1553 * the allocation granularity. If future Windows specific git code
1554 * needs the real getpagesize function, we need to find another solution.
1556 int mingw_getpagesize(void)
1560 return si
.dwAllocationGranularity
;
1563 struct passwd
*getpwuid(int uid
)
1565 static char user_name
[100];
1566 static struct passwd p
;
1568 DWORD len
= sizeof(user_name
);
1569 if (!GetUserName(user_name
, &len
))
1571 p
.pw_name
= user_name
;
1572 p
.pw_gecos
= "unknown";
1577 static HANDLE timer_event
;
1578 static HANDLE timer_thread
;
1579 static int timer_interval
;
1580 static int one_shot
;
1581 static sig_handler_t timer_fn
= SIG_DFL
, sigint_fn
= SIG_DFL
;
1583 /* The timer works like this:
1584 * The thread, ticktack(), is a trivial routine that most of the time
1585 * only waits to receive the signal to terminate. The main thread tells
1586 * the thread to terminate by setting the timer_event to the signalled
1588 * But ticktack() interrupts the wait state after the timer's interval
1589 * length to call the signal handler.
1592 static unsigned __stdcall
ticktack(void *dummy
)
1594 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
1595 mingw_raise(SIGALRM
);
1602 static int start_timer_thread(void)
1604 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1606 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
1608 return errno
= ENOMEM
,
1609 error("cannot start timer thread");
1611 return errno
= ENOMEM
,
1612 error("cannot allocate resources for timer");
1616 static void stop_timer_thread(void)
1619 SetEvent(timer_event
); /* tell thread to terminate */
1621 int rc
= WaitForSingleObject(timer_thread
, 1000);
1622 if (rc
== WAIT_TIMEOUT
)
1623 error("timer thread did not terminate timely");
1624 else if (rc
!= WAIT_OBJECT_0
)
1625 error("waiting for timer thread failed: %lu",
1627 CloseHandle(timer_thread
);
1630 CloseHandle(timer_event
);
1632 timer_thread
= NULL
;
1635 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
1637 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
1640 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
1642 static const struct timeval zero
;
1643 static int atexit_done
;
1646 return errno
= EINVAL
,
1647 error("setitimer param 3 != NULL not implemented");
1648 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
1649 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
1650 return errno
= EINVAL
,
1651 error("setitimer: it_interval must be zero or eq it_value");
1654 stop_timer_thread();
1656 if (is_timeval_eq(&in
->it_value
, &zero
) &&
1657 is_timeval_eq(&in
->it_interval
, &zero
))
1660 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
1661 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
1663 atexit(stop_timer_thread
);
1666 return start_timer_thread();
1669 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
1672 return errno
= EINVAL
,
1673 error("sigaction only implemented for SIGALRM");
1675 return errno
= EINVAL
,
1676 error("sigaction: param 3 != NULL not implemented");
1678 timer_fn
= in
->sa_handler
;
1683 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
1695 sigint_fn
= handler
;
1699 return signal(sig
, handler
);
1706 int mingw_raise(int sig
)
1710 if (timer_fn
== SIG_DFL
) {
1711 if (isatty(STDERR_FILENO
))
1712 fputs("Alarm clock\n", stderr
);
1713 exit(128 + SIGALRM
);
1714 } else if (timer_fn
!= SIG_IGN
)
1719 if (sigint_fn
== SIG_DFL
)
1721 else if (sigint_fn
!= SIG_IGN
)
1731 static const char *make_backslash_path(const char *path
)
1733 static char buf
[PATH_MAX
+ 1];
1736 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
1737 die("Too long path: %.*s", 60, path
);
1739 for (c
= buf
; *c
; c
++) {
1746 void mingw_open_html(const char *unixpath
)
1748 const char *htmlpath
= make_backslash_path(unixpath
);
1749 typedef HINSTANCE (WINAPI
*T
)(HWND
, const char *,
1750 const char *, const char *, const char *, INT
);
1755 shell32
= LoadLibrary("shell32.dll");
1757 die("cannot load shell32.dll");
1758 ShellExecute
= (T
)GetProcAddress(shell32
, "ShellExecuteA");
1760 die("cannot run browser");
1762 printf("Launching default browser to display HTML ...\n");
1763 r
= (int)ShellExecute(NULL
, "open", htmlpath
, NULL
, "\\", SW_SHOWNORMAL
);
1764 FreeLibrary(shell32
);
1765 /* see the MSDN documentation referring to the result codes here */
1767 die("failed to launch browser for %.*s", MAX_PATH
, unixpath
);
1771 int link(const char *oldpath
, const char *newpath
)
1773 typedef BOOL (WINAPI
*T
)(const char*, const char*, LPSECURITY_ATTRIBUTES
);
1774 static T create_hard_link
= NULL
;
1775 if (!create_hard_link
) {
1776 create_hard_link
= (T
) GetProcAddress(
1777 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1778 if (!create_hard_link
)
1779 create_hard_link
= (T
)-1;
1781 if (create_hard_link
== (T
)-1) {
1785 if (!create_hard_link(newpath
, oldpath
, NULL
)) {
1786 errno
= err_win_to_posix(GetLastError());
1792 pid_t
waitpid(pid_t pid
, int *status
, int options
)
1794 HANDLE h
= OpenProcess(SYNCHRONIZE
| PROCESS_QUERY_INFORMATION
,
1801 if (pid
> 0 && options
& WNOHANG
) {
1802 if (WAIT_OBJECT_0
!= WaitForSingleObject(h
, 0)) {
1806 options
&= ~WNOHANG
;
1810 struct pinfo_t
**ppinfo
;
1811 if (WaitForSingleObject(h
, INFINITE
) != WAIT_OBJECT_0
) {
1817 GetExitCodeProcess(h
, (LPDWORD
)status
);
1819 EnterCriticalSection(&pinfo_cs
);
1823 struct pinfo_t
*info
= *ppinfo
;
1824 if (info
->pid
== pid
) {
1825 CloseHandle(info
->proc
);
1826 *ppinfo
= info
->next
;
1830 ppinfo
= &info
->next
;
1833 LeaveCriticalSection(&pinfo_cs
);