1 #include "../git-compat-util.h"
4 unsigned int _CRT_fmode
= _O_BINARY
;
7 int mingw_open (const char *filename
, int oflags
, ...)
11 va_start(args
, oflags
);
12 mode
= va_arg(args
, int);
15 if (!strcmp(filename
, "/dev/null"))
17 int fd
= open(filename
, oflags
, mode
);
18 if (fd
< 0 && (oflags
& O_CREAT
) && errno
== EACCES
) {
19 DWORD attrs
= GetFileAttributes(filename
);
20 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
))
26 static inline time_t filetime_to_time_t(const FILETIME
*ft
)
28 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
29 winTime
-= 116444736000000000LL; /* Windows to Unix Epoch conversion */
30 winTime
/= 10000000; /* Nano to seconds resolution */
31 return (time_t)winTime
;
34 static inline size_t size_to_blocks(size_t s
)
39 extern int _getdrive( void );
40 /* We keep the do_lstat code in a separate function to avoid recursion.
41 * When a path ends with a slash, the stat will fail with ENOENT. In
42 * this case, we strip the trailing slashes and stat again.
44 static int do_lstat(const char *file_name
, struct stat
*buf
)
46 WIN32_FILE_ATTRIBUTE_DATA fdata
;
48 if (GetFileAttributesExA(file_name
, GetFileExInfoStandard
, &fdata
)) {
50 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
54 if (!(fdata
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
61 buf
->st_size
= fdata
.nFileSizeLow
; /* Can't use nFileSizeHigh, since it's not a stat64 */
62 buf
->st_blocks
= size_to_blocks(buf
->st_size
);
63 buf
->st_dev
= _getdrive() - 1;
64 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
65 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
66 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
71 switch (GetLastError()) {
72 case ERROR_ACCESS_DENIED
:
73 case ERROR_SHARING_VIOLATION
:
74 case ERROR_LOCK_VIOLATION
:
75 case ERROR_SHARING_BUFFER_EXCEEDED
:
78 case ERROR_BUFFER_OVERFLOW
:
81 case ERROR_NOT_ENOUGH_MEMORY
:
91 /* We provide our own lstat/fstat functions, since the provided
92 * lstat/fstat functions are so slow. These stat functions are
93 * tailored for Git's usage (read: fast), and are not meant to be
94 * complete. Note that Git stat()s are redirected to mingw_lstat()
95 * too, since Windows doesn't really handle symlinks that well.
97 int mingw_lstat(const char *file_name
, struct mingw_stat
*buf
)
100 static char alt_name
[PATH_MAX
];
102 if (!do_lstat(file_name
, buf
))
105 /* if file_name ended in a '/', Windows returned ENOENT;
106 * try again without trailing slashes
111 namelen
= strlen(file_name
);
112 if (namelen
&& file_name
[namelen
-1] != '/')
114 while (namelen
&& file_name
[namelen
-1] == '/')
116 if (!namelen
|| namelen
>= PATH_MAX
)
119 memcpy(alt_name
, file_name
, namelen
);
120 alt_name
[namelen
] = 0;
121 return do_lstat(alt_name
, buf
);
126 int mingw_fstat(int fd
, struct mingw_stat
*buf
)
128 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
129 BY_HANDLE_FILE_INFORMATION fdata
;
131 if (fh
== INVALID_HANDLE_VALUE
) {
135 /* direct non-file handles to MS's fstat() */
136 if (GetFileType(fh
) != FILE_TYPE_DISK
) {
140 buf
->st_ino
= st
.st_ino
;
141 buf
->st_gid
= st
.st_gid
;
142 buf
->st_uid
= st
.st_uid
;
143 buf
->st_mode
= st
.st_mode
;
144 buf
->st_size
= st
.st_size
;
145 buf
->st_blocks
= size_to_blocks(buf
->st_size
);
146 buf
->st_dev
= st
.st_dev
;
147 buf
->st_atime
= st
.st_atime
;
148 buf
->st_mtime
= st
.st_mtime
;
149 buf
->st_ctime
= st
.st_ctime
;
153 if (GetFileInformationByHandle(fh
, &fdata
)) {
155 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
159 if (!(fdata
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
165 buf
->st_mode
= fMode
;
166 buf
->st_size
= fdata
.nFileSizeLow
; /* Can't use nFileSizeHigh, since it's not a stat64 */
167 buf
->st_blocks
= size_to_blocks(buf
->st_size
);
168 buf
->st_dev
= _getdrive() - 1;
169 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
170 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
171 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
178 static inline void time_t_to_filetime(time_t t
, FILETIME
*ft
)
180 long long winTime
= t
* 10000000LL + 116444736000000000LL;
181 ft
->dwLowDateTime
= winTime
;
182 ft
->dwHighDateTime
= winTime
>> 32;
185 int mingw_utime (const char *file_name
, const struct utimbuf
*times
)
190 /* must have write permission */
191 if ((fh
= open(file_name
, O_RDWR
| O_BINARY
)) < 0)
194 time_t_to_filetime(times
->modtime
, &mft
);
195 time_t_to_filetime(times
->actime
, &aft
);
196 if (!SetFileTime((HANDLE
)_get_osfhandle(fh
), NULL
, &aft
, &mft
)) {
205 unsigned int sleep (unsigned int seconds
)
211 int mkstemp(char *template)
213 char *filename
= mktemp(template);
214 if (filename
== NULL
)
216 return open(filename
, O_RDWR
| O_CREAT
, 0600);
219 int gettimeofday(struct timeval
*tv
, void *tz
)
224 tm
.tm_year
= st
.wYear
-1900;
225 tm
.tm_mon
= st
.wMonth
-1;
226 tm
.tm_mday
= st
.wDay
;
227 tm
.tm_hour
= st
.wHour
;
228 tm
.tm_min
= st
.wMinute
;
229 tm
.tm_sec
= st
.wSecond
;
230 tv
->tv_sec
= tm_to_time_t(&tm
);
233 tv
->tv_usec
= st
.wMilliseconds
*1000;
237 int pipe(int filedes
[2])
242 if (_pipe(filedes
, 8192, 0) < 0)
245 parent
= GetCurrentProcess();
247 if (!DuplicateHandle (parent
, (HANDLE
)_get_osfhandle(filedes
[0]),
248 parent
, &h
[0], 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
253 if (!DuplicateHandle (parent
, (HANDLE
)_get_osfhandle(filedes
[1]),
254 parent
, &h
[1], 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
260 fd
= _open_osfhandle((int)h
[0], O_NOINHERIT
);
270 fd
= _open_osfhandle((int)h
[1], O_NOINHERIT
);
282 int poll(struct pollfd
*ufds
, unsigned int nfds
, int timeout
)
287 return errno
= EINVAL
, error("poll timeout not supported");
289 /* When there is only one fd to wait for, then we pretend that
290 * input is available and let the actual wait happen when the
291 * caller invokes read().
294 if (!(ufds
[0].events
& POLLIN
))
295 return errno
= EINVAL
, error("POLLIN not set");
296 ufds
[0].revents
= POLLIN
;
302 for (i
= 0; i
< nfds
; i
++) {
304 HANDLE h
= (HANDLE
) _get_osfhandle(ufds
[i
].fd
);
305 if (h
== INVALID_HANDLE_VALUE
)
306 return -1; /* errno was set */
308 if (!(ufds
[i
].events
& POLLIN
))
309 return errno
= EINVAL
, error("POLLIN not set");
311 /* this emulation works only for pipes */
312 if (!PeekNamedPipe(h
, NULL
, 0, NULL
, &avail
, NULL
)) {
313 int err
= GetLastError();
314 if (err
== ERROR_BROKEN_PIPE
) {
315 ufds
[i
].revents
= POLLHUP
;
319 return error("PeekNamedPipe failed,"
320 " GetLastError: %u", err
);
323 ufds
[i
].revents
= POLLIN
;
329 /* The only times that we spin here is when the process
330 * that is connected through the pipes is waiting for
331 * its own input data to become available. But since
332 * the process (pack-objects) is itself CPU intensive,
333 * it will happily pick up the time slice that we are
334 * relinguishing here.
342 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
344 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
345 memcpy(result
, gmtime(timep
), sizeof(struct tm
));
349 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
351 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
352 memcpy(result
, localtime(timep
), sizeof(struct tm
));
357 char *mingw_getcwd(char *pointer
, int len
)
360 char *ret
= getcwd(pointer
, len
);
363 for (i
= 0; pointer
[i
]; i
++)
364 if (pointer
[i
] == '\\')
370 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
371 * (Parsing C++ Command-Line Arguments)
373 static const char *quote_arg(const char *arg
)
375 /* count chars to quote */
377 int force_quotes
= 0;
380 if (!*p
) force_quotes
= 1;
382 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{')
386 else if (*p
== '\\') {
400 if (!force_quotes
&& n
== 0)
403 /* insert \ where necessary */
404 d
= q
= xmalloc(len
+n
+3);
409 else if (*arg
== '\\') {
411 while (*arg
== '\\') {
428 static const char *parse_interpreter(const char *cmd
)
430 static char buf
[100];
434 /* don't even try a .exe */
436 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
439 fd
= open(cmd
, O_RDONLY
);
442 n
= read(fd
, buf
, sizeof(buf
)-1);
444 if (n
< 4) /* at least '#!/x' and not error */
447 if (buf
[0] != '#' || buf
[1] != '!')
450 p
= strchr(buf
, '\n');
455 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
458 if ((opt
= strchr(p
+1, ' ')))
464 * Splits the PATH into parts.
466 static char **get_path_split(void)
468 char *p
, **path
, *envpath
= getenv("PATH");
471 if (!envpath
|| !*envpath
)
474 envpath
= xstrdup(envpath
);
480 if (*dir
) { /* not earlier, catches series of ; */
487 path
= xmalloc((n
+1)*sizeof(char*));
492 path
[i
++] = xstrdup(p
);
502 static void free_path_split(char **path
)
514 * exe_only means that we only want to detect .exe files, but not scripts
515 * (which do not have an extension)
517 static char *lookup_prog(const char *dir
, const char *cmd
, int isexe
, int exe_only
)
520 snprintf(path
, sizeof(path
), "%s/%s.exe", dir
, cmd
);
522 if (!isexe
&& access(path
, F_OK
) == 0)
523 return xstrdup(path
);
524 path
[strlen(path
)-4] = '\0';
525 if ((!exe_only
|| isexe
) && access(path
, F_OK
) == 0)
526 return xstrdup(path
);
531 * Determines the absolute path of cmd using the the split path in path.
532 * If cmd contains a slash or backslash, no lookup is performed.
534 static char *path_lookup(const char *cmd
, char **path
, int exe_only
)
537 int len
= strlen(cmd
);
538 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
540 if (strchr(cmd
, '/') || strchr(cmd
, '\\'))
543 while (!prog
&& *path
)
544 prog
= lookup_prog(*path
++, cmd
, isexe
, exe_only
);
549 static int env_compare(const void *a
, const void *b
)
553 return strcasecmp(*ea
, *eb
);
556 static pid_t
mingw_spawnve(const char *cmd
, const char **argv
, char **env
,
560 PROCESS_INFORMATION pi
;
561 struct strbuf envblk
, args
;
565 /* Determine whether or not we are associated to a console */
566 HANDLE cons
= CreateFile("CONOUT$", GENERIC_WRITE
,
567 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
568 FILE_ATTRIBUTE_NORMAL
, NULL
);
569 if (cons
== INVALID_HANDLE_VALUE
) {
570 /* There is no console associated with this process.
571 * Since the child is a console process, Windows
572 * would normally create a console window. But
573 * since we'll be redirecting std streams, we do
574 * not need the console.
576 flags
= CREATE_NO_WINDOW
;
578 /* There is already a console. If we specified
579 * CREATE_NO_WINDOW here, too, Windows would
580 * disassociate the child from the console.
586 memset(&si
, 0, sizeof(si
));
588 si
.dwFlags
= STARTF_USESTDHANDLES
;
589 si
.hStdInput
= (HANDLE
) _get_osfhandle(0);
590 si
.hStdOutput
= (HANDLE
) _get_osfhandle(1);
591 si
.hStdError
= (HANDLE
) _get_osfhandle(2);
593 /* concatenate argv, quoting args as we go */
594 strbuf_init(&args
, 0);
596 char *quoted
= (char *)quote_arg(cmd
);
597 strbuf_addstr(&args
, quoted
);
601 for (; *argv
; argv
++) {
602 char *quoted
= (char *)quote_arg(*argv
);
604 strbuf_addch(&args
, ' ');
605 strbuf_addstr(&args
, quoted
);
612 char **e
, **sorted_env
;
614 for (e
= env
; *e
; e
++)
617 /* environment must be sorted */
618 sorted_env
= xmalloc(sizeof(*sorted_env
) * (count
+ 1));
619 memcpy(sorted_env
, env
, sizeof(*sorted_env
) * (count
+ 1));
620 qsort(sorted_env
, count
, sizeof(*sorted_env
), env_compare
);
622 strbuf_init(&envblk
, 0);
623 for (e
= sorted_env
; *e
; e
++) {
624 strbuf_addstr(&envblk
, *e
);
625 strbuf_addch(&envblk
, '\0');
630 memset(&pi
, 0, sizeof(pi
));
631 ret
= CreateProcess(cmd
, args
.buf
, NULL
, NULL
, TRUE
, flags
,
632 env
? envblk
.buf
: NULL
, NULL
, &si
, &pi
);
635 strbuf_release(&envblk
);
636 strbuf_release(&args
);
642 CloseHandle(pi
.hThread
);
643 return (pid_t
)pi
.hProcess
;
646 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **env
)
649 char **path
= get_path_split();
650 char *prog
= path_lookup(cmd
, path
, 0);
657 const char *interpr
= parse_interpreter(prog
);
660 const char *argv0
= argv
[0];
661 char *iprog
= path_lookup(interpr
, path
, 1);
668 pid
= mingw_spawnve(iprog
, argv
, env
, 1);
674 pid
= mingw_spawnve(prog
, argv
, env
, 0);
677 free_path_split(path
);
681 static int try_shell_exec(const char *cmd
, char *const *argv
, char **env
)
683 const char *interpr
= parse_interpreter(cmd
);
690 path
= get_path_split();
691 prog
= path_lookup(interpr
, path
, 1);
695 while (argv
[argc
]) argc
++;
696 argv2
= xmalloc(sizeof(*argv
) * (argc
+1));
697 argv2
[0] = (char *)cmd
; /* full path to the script file */
698 memcpy(&argv2
[1], &argv
[1], sizeof(*argv
) * argc
);
699 pid
= mingw_spawnve(prog
, argv2
, env
, 1);
702 if (waitpid(pid
, &status
, 0) < 0)
706 pid
= 1; /* indicate that we tried but failed */
710 free_path_split(path
);
714 static void mingw_execve(const char *cmd
, char *const *argv
, char *const *env
)
716 /* check if git_command is a shell script */
717 if (!try_shell_exec(cmd
, argv
, (char **)env
)) {
720 pid
= mingw_spawnve(cmd
, (const char **)argv
, (char **)env
, 0);
723 if (waitpid(pid
, &status
, 0) < 0)
729 void mingw_execvp(const char *cmd
, char *const *argv
)
731 char **path
= get_path_split();
732 char *prog
= path_lookup(cmd
, path
, 0);
735 mingw_execve(prog
, argv
, environ
);
740 free_path_split(path
);
743 char **copy_environ()
749 env
= xmalloc((i
+1)*sizeof(*env
));
750 for (i
= 0; environ
[i
]; i
++)
751 env
[i
] = xstrdup(environ
[i
]);
756 void free_environ(char **env
)
759 for (i
= 0; env
[i
]; i
++)
764 static int lookup_env(char **env
, const char *name
, size_t nmln
)
768 for (i
= 0; env
[i
]; i
++) {
769 if (0 == strncmp(env
[i
], name
, nmln
)
770 && '=' == env
[i
][nmln
])
778 * If name contains '=', then sets the variable, otherwise it unsets it
780 char **env_setenv(char **env
, const char *name
)
782 char *eq
= strchrnul(name
, '=');
783 int i
= lookup_env(env
, name
, eq
-name
);
787 for (i
= 0; env
[i
]; i
++)
789 env
= xrealloc(env
, (i
+2)*sizeof(*env
));
790 env
[i
] = xstrdup(name
);
797 env
[i
] = xstrdup(name
);
805 /* this is the first function to call into WS_32; initialize it */
807 struct hostent
*mingw_gethostbyname(const char *host
)
811 if (WSAStartup(MAKEWORD(2,2), &wsa
))
812 die("unable to initialize winsock subsystem, error %d",
814 atexit((void(*)(void)) WSACleanup
);
815 return gethostbyname(host
);
818 int mingw_socket(int domain
, int type
, int protocol
)
821 SOCKET s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
822 if (s
== INVALID_SOCKET
) {
824 * WSAGetLastError() values are regular BSD error codes
825 * biased by WSABASEERR.
826 * However, strerror() does not know about networking
827 * specific errors, which are values beginning at 38 or so.
828 * Therefore, we choose to leave the biased error code
829 * in errno so that _if_ someone looks up the code somewhere,
830 * then it is at least the number that are usually listed.
832 errno
= WSAGetLastError();
835 /* convert into a file descriptor */
836 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
838 return error("unable to make a socket file descriptor: %s",
845 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
847 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
848 return connect(s
, sa
, sz
);
852 int mingw_rename(const char *pold
, const char *pnew
)
855 * Try native rename() first to get errno right.
856 * It is based on MoveFile(), which cannot overwrite existing files.
858 if (!rename(pold
, pnew
))
862 if (MoveFileEx(pold
, pnew
, MOVEFILE_REPLACE_EXISTING
))
864 /* TODO: translate more errors */
865 if (GetLastError() == ERROR_ACCESS_DENIED
) {
866 DWORD attrs
= GetFileAttributes(pnew
);
867 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) {
876 struct passwd
*getpwuid(int uid
)
878 static char user_name
[100];
879 static struct passwd p
;
881 DWORD len
= sizeof(user_name
);
882 if (!GetUserName(user_name
, &len
))
884 p
.pw_name
= user_name
;
885 p
.pw_gecos
= "unknown";
890 static HANDLE timer_event
;
891 static HANDLE timer_thread
;
892 static int timer_interval
;
894 static sig_handler_t timer_fn
= SIG_DFL
;
896 /* The timer works like this:
897 * The thread, ticktack(), is basically a trivial routine that most of the
898 * time only waits to receive the signal to terminate. The main thread
899 * tells the thread to terminate by setting the timer_event to the signalled
901 * But ticktack() does not wait indefinitely; instead, it interrupts the
902 * wait state every now and then, namely exactly after timer's interval
903 * length. At these opportunities it calls the signal handler.
906 static __stdcall
unsigned ticktack(void *dummy
)
908 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
909 if (timer_fn
== SIG_DFL
)
911 if (timer_fn
!= SIG_IGN
)
919 static int start_timer_thread(void)
921 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
923 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
925 return errno
= ENOMEM
,
926 error("cannot start timer thread");
928 return errno
= ENOMEM
,
929 error("cannot allocate resources timer");
933 static void stop_timer_thread(void)
936 SetEvent(timer_event
); /* tell thread to terminate */
938 int rc
= WaitForSingleObject(timer_thread
, 1000);
939 if (rc
== WAIT_TIMEOUT
)
940 error("timer thread did not terminate timely");
941 else if (rc
!= WAIT_OBJECT_0
)
942 error("waiting for timer thread failed: %lu",
944 CloseHandle(timer_thread
);
947 CloseHandle(timer_event
);
952 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
954 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
957 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
959 static const struct timeval zero
;
960 static int atexit_done
;
963 return errno
= EINVAL
,
964 error("setitmer param 3 != NULL not implemented");
965 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
966 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
967 return errno
= EINVAL
,
968 error("setitmer: it_interval must be zero or eq it_value");
973 if (is_timeval_eq(&in
->it_value
, &zero
) &&
974 is_timeval_eq(&in
->it_interval
, &zero
))
977 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
978 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
980 atexit(stop_timer_thread
);
983 return start_timer_thread();
986 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
989 return errno
= EINVAL
,
990 error("sigaction only implemented for SIGALRM");
992 return errno
= EINVAL
,
993 error("sigaction: param 3 != NULL not implemented");
995 timer_fn
= in
->sa_handler
;
1000 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
1003 return signal(sig
, handler
);
1004 sig_handler_t old
= timer_fn
;