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 unsigned int sleep (unsigned int seconds
)
32 int mkstemp(char *template)
34 char *filename
= mktemp(template);
37 return open(filename
, O_RDWR
| O_CREAT
, 0600);
40 int gettimeofday(struct timeval
*tv
, void *tz
)
45 tm
.tm_year
= st
.wYear
-1900;
46 tm
.tm_mon
= st
.wMonth
-1;
48 tm
.tm_hour
= st
.wHour
;
49 tm
.tm_min
= st
.wMinute
;
50 tm
.tm_sec
= st
.wSecond
;
51 tv
->tv_sec
= tm_to_time_t(&tm
);
54 tv
->tv_usec
= st
.wMilliseconds
*1000;
58 int pipe(int filedes
[2])
63 if (_pipe(filedes
, 8192, 0) < 0)
66 parent
= GetCurrentProcess();
68 if (!DuplicateHandle (parent
, (HANDLE
)_get_osfhandle(filedes
[0]),
69 parent
, &h
[0], 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
74 if (!DuplicateHandle (parent
, (HANDLE
)_get_osfhandle(filedes
[1]),
75 parent
, &h
[1], 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
81 fd
= _open_osfhandle((int)h
[0], O_NOINHERIT
);
91 fd
= _open_osfhandle((int)h
[1], O_NOINHERIT
);
103 int poll(struct pollfd
*ufds
, unsigned int nfds
, int timeout
)
108 return errno
= EINVAL
, error("poll timeout not supported");
110 /* When there is only one fd to wait for, then we pretend that
111 * input is available and let the actual wait happen when the
112 * caller invokes read().
115 if (!(ufds
[0].events
& POLLIN
))
116 return errno
= EINVAL
, error("POLLIN not set");
117 ufds
[0].revents
= POLLIN
;
123 for (i
= 0; i
< nfds
; i
++) {
125 HANDLE h
= (HANDLE
) _get_osfhandle(ufds
[i
].fd
);
126 if (h
== INVALID_HANDLE_VALUE
)
127 return -1; /* errno was set */
129 if (!(ufds
[i
].events
& POLLIN
))
130 return errno
= EINVAL
, error("POLLIN not set");
132 /* this emulation works only for pipes */
133 if (!PeekNamedPipe(h
, NULL
, 0, NULL
, &avail
, NULL
)) {
134 int err
= GetLastError();
135 if (err
== ERROR_BROKEN_PIPE
) {
136 ufds
[i
].revents
= POLLHUP
;
140 return error("PeekNamedPipe failed,"
141 " GetLastError: %u", err
);
144 ufds
[i
].revents
= POLLIN
;
150 /* The only times that we spin here is when the process
151 * that is connected through the pipes is waiting for
152 * its own input data to become available. But since
153 * the process (pack-objects) is itself CPU intensive,
154 * it will happily pick up the time slice that we are
155 * relinguishing here.
163 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
165 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
166 memcpy(result
, gmtime(timep
), sizeof(struct tm
));
170 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
172 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
173 memcpy(result
, localtime(timep
), sizeof(struct tm
));
178 char *mingw_getcwd(char *pointer
, int len
)
181 char *ret
= getcwd(pointer
, len
);
184 for (i
= 0; pointer
[i
]; i
++)
185 if (pointer
[i
] == '\\')
191 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
192 * (Parsing C++ Command-Line Arguments)
194 static const char *quote_arg(const char *arg
)
196 /* count chars to quote */
198 int force_quotes
= 0;
201 if (!*p
) force_quotes
= 1;
203 if (isspace(*p
) || *p
== '*' || *p
== '?' || *p
== '{')
207 else if (*p
== '\\') {
221 if (!force_quotes
&& n
== 0)
224 /* insert \ where necessary */
225 d
= q
= xmalloc(len
+n
+3);
230 else if (*arg
== '\\') {
232 while (*arg
== '\\') {
249 static const char *parse_interpreter(const char *cmd
)
251 static char buf
[100];
255 /* don't even try a .exe */
257 if (n
>= 4 && !strcasecmp(cmd
+n
-4, ".exe"))
260 fd
= open(cmd
, O_RDONLY
);
263 n
= read(fd
, buf
, sizeof(buf
)-1);
265 if (n
< 4) /* at least '#!/x' and not error */
268 if (buf
[0] != '#' || buf
[1] != '!')
271 p
= strchr(buf
, '\n');
276 if (!(p
= strrchr(buf
+2, '/')) && !(p
= strrchr(buf
+2, '\\')))
279 if ((opt
= strchr(p
+1, ' ')))
285 * Splits the PATH into parts.
287 static char **get_path_split(void)
289 char *p
, **path
, *envpath
= getenv("PATH");
292 if (!envpath
|| !*envpath
)
295 envpath
= xstrdup(envpath
);
301 if (*dir
) { /* not earlier, catches series of ; */
308 path
= xmalloc((n
+1)*sizeof(char*));
313 path
[i
++] = xstrdup(p
);
323 static void free_path_split(char **path
)
335 * exe_only means that we only want to detect .exe files, but not scripts
336 * (which do not have an extension)
338 static char *lookup_prog(const char *dir
, const char *cmd
, int isexe
, int exe_only
)
341 snprintf(path
, sizeof(path
), "%s/%s.exe", dir
, cmd
);
343 if (!isexe
&& access(path
, F_OK
) == 0)
344 return xstrdup(path
);
345 path
[strlen(path
)-4] = '\0';
346 if ((!exe_only
|| isexe
) && access(path
, F_OK
) == 0)
347 return xstrdup(path
);
352 * Determines the absolute path of cmd using the the split path in path.
353 * If cmd contains a slash or backslash, no lookup is performed.
355 static char *path_lookup(const char *cmd
, char **path
, int exe_only
)
358 int len
= strlen(cmd
);
359 int isexe
= len
>= 4 && !strcasecmp(cmd
+len
-4, ".exe");
361 if (strchr(cmd
, '/') || strchr(cmd
, '\\'))
364 while (!prog
&& *path
)
365 prog
= lookup_prog(*path
++, cmd
, isexe
, exe_only
);
370 static int env_compare(const void *a
, const void *b
)
374 return strcasecmp(*ea
, *eb
);
377 static pid_t
mingw_spawnve(const char *cmd
, const char **argv
, char **env
,
381 PROCESS_INFORMATION pi
;
382 struct strbuf envblk
, args
;
386 /* Determine whether or not we are associated to a console */
387 HANDLE cons
= CreateFile("CONOUT$", GENERIC_WRITE
,
388 FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
389 FILE_ATTRIBUTE_NORMAL
, NULL
);
390 if (cons
== INVALID_HANDLE_VALUE
) {
391 /* There is no console associated with this process.
392 * Since the child is a console process, Windows
393 * would normally create a console window. But
394 * since we'll be redirecting std streams, we do
395 * not need the console.
397 flags
= CREATE_NO_WINDOW
;
399 /* There is already a console. If we specified
400 * CREATE_NO_WINDOW here, too, Windows would
401 * disassociate the child from the console.
407 memset(&si
, 0, sizeof(si
));
409 si
.dwFlags
= STARTF_USESTDHANDLES
;
410 si
.hStdInput
= (HANDLE
) _get_osfhandle(0);
411 si
.hStdOutput
= (HANDLE
) _get_osfhandle(1);
412 si
.hStdError
= (HANDLE
) _get_osfhandle(2);
414 /* concatenate argv, quoting args as we go */
415 strbuf_init(&args
, 0);
417 char *quoted
= (char *)quote_arg(cmd
);
418 strbuf_addstr(&args
, quoted
);
422 for (; *argv
; argv
++) {
423 char *quoted
= (char *)quote_arg(*argv
);
425 strbuf_addch(&args
, ' ');
426 strbuf_addstr(&args
, quoted
);
433 char **e
, **sorted_env
;
435 for (e
= env
; *e
; e
++)
438 /* environment must be sorted */
439 sorted_env
= xmalloc(sizeof(*sorted_env
) * (count
+ 1));
440 memcpy(sorted_env
, env
, sizeof(*sorted_env
) * (count
+ 1));
441 qsort(sorted_env
, count
, sizeof(*sorted_env
), env_compare
);
443 strbuf_init(&envblk
, 0);
444 for (e
= sorted_env
; *e
; e
++) {
445 strbuf_addstr(&envblk
, *e
);
446 strbuf_addch(&envblk
, '\0');
451 memset(&pi
, 0, sizeof(pi
));
452 ret
= CreateProcess(cmd
, args
.buf
, NULL
, NULL
, TRUE
, flags
,
453 env
? envblk
.buf
: NULL
, NULL
, &si
, &pi
);
456 strbuf_release(&envblk
);
457 strbuf_release(&args
);
463 CloseHandle(pi
.hThread
);
464 return (pid_t
)pi
.hProcess
;
467 pid_t
mingw_spawnvpe(const char *cmd
, const char **argv
, char **env
)
470 char **path
= get_path_split();
471 char *prog
= path_lookup(cmd
, path
, 0);
478 const char *interpr
= parse_interpreter(prog
);
481 const char *argv0
= argv
[0];
482 char *iprog
= path_lookup(interpr
, path
, 1);
489 pid
= mingw_spawnve(iprog
, argv
, env
, 1);
495 pid
= mingw_spawnve(prog
, argv
, env
, 0);
498 free_path_split(path
);
502 static int try_shell_exec(const char *cmd
, char *const *argv
, char **env
)
504 const char *interpr
= parse_interpreter(cmd
);
511 path
= get_path_split();
512 prog
= path_lookup(interpr
, path
, 1);
516 while (argv
[argc
]) argc
++;
517 argv2
= xmalloc(sizeof(*argv
) * (argc
+1));
518 argv2
[0] = (char *)cmd
; /* full path to the script file */
519 memcpy(&argv2
[1], &argv
[1], sizeof(*argv
) * argc
);
520 pid
= mingw_spawnve(prog
, argv2
, env
, 1);
523 if (waitpid(pid
, &status
, 0) < 0)
527 pid
= 1; /* indicate that we tried but failed */
531 free_path_split(path
);
535 static void mingw_execve(const char *cmd
, char *const *argv
, char *const *env
)
537 /* check if git_command is a shell script */
538 if (!try_shell_exec(cmd
, argv
, (char **)env
)) {
541 pid
= mingw_spawnve(cmd
, (const char **)argv
, (char **)env
, 0);
544 if (waitpid(pid
, &status
, 0) < 0)
550 void mingw_execvp(const char *cmd
, char *const *argv
)
552 char **path
= get_path_split();
553 char *prog
= path_lookup(cmd
, path
, 0);
556 mingw_execve(prog
, argv
, environ
);
561 free_path_split(path
);
564 char **copy_environ()
570 env
= xmalloc((i
+1)*sizeof(*env
));
571 for (i
= 0; environ
[i
]; i
++)
572 env
[i
] = xstrdup(environ
[i
]);
577 void free_environ(char **env
)
580 for (i
= 0; env
[i
]; i
++)
585 static int lookup_env(char **env
, const char *name
, size_t nmln
)
589 for (i
= 0; env
[i
]; i
++) {
590 if (0 == strncmp(env
[i
], name
, nmln
)
591 && '=' == env
[i
][nmln
])
599 * If name contains '=', then sets the variable, otherwise it unsets it
601 char **env_setenv(char **env
, const char *name
)
603 char *eq
= strchrnul(name
, '=');
604 int i
= lookup_env(env
, name
, eq
-name
);
608 for (i
= 0; env
[i
]; i
++)
610 env
= xrealloc(env
, (i
+2)*sizeof(*env
));
611 env
[i
] = xstrdup(name
);
618 env
[i
] = xstrdup(name
);
626 /* this is the first function to call into WS_32; initialize it */
628 struct hostent
*mingw_gethostbyname(const char *host
)
632 if (WSAStartup(MAKEWORD(2,2), &wsa
))
633 die("unable to initialize winsock subsystem, error %d",
635 atexit((void(*)(void)) WSACleanup
);
636 return gethostbyname(host
);
639 int mingw_socket(int domain
, int type
, int protocol
)
642 SOCKET s
= WSASocket(domain
, type
, protocol
, NULL
, 0, 0);
643 if (s
== INVALID_SOCKET
) {
645 * WSAGetLastError() values are regular BSD error codes
646 * biased by WSABASEERR.
647 * However, strerror() does not know about networking
648 * specific errors, which are values beginning at 38 or so.
649 * Therefore, we choose to leave the biased error code
650 * in errno so that _if_ someone looks up the code somewhere,
651 * then it is at least the number that are usually listed.
653 errno
= WSAGetLastError();
656 /* convert into a file descriptor */
657 if ((sockfd
= _open_osfhandle(s
, O_RDWR
|O_BINARY
)) < 0) {
659 return error("unable to make a socket file descriptor: %s",
666 int mingw_connect(int sockfd
, struct sockaddr
*sa
, size_t sz
)
668 SOCKET s
= (SOCKET
)_get_osfhandle(sockfd
);
669 return connect(s
, sa
, sz
);
673 int mingw_rename(const char *pold
, const char *pnew
)
676 * Try native rename() first to get errno right.
677 * It is based on MoveFile(), which cannot overwrite existing files.
679 if (!rename(pold
, pnew
))
683 if (MoveFileEx(pold
, pnew
, MOVEFILE_REPLACE_EXISTING
))
685 /* TODO: translate more errors */
686 if (GetLastError() == ERROR_ACCESS_DENIED
) {
687 DWORD attrs
= GetFileAttributes(pnew
);
688 if (attrs
!= INVALID_FILE_ATTRIBUTES
&& (attrs
& FILE_ATTRIBUTE_DIRECTORY
)) {
697 struct passwd
*getpwuid(int uid
)
699 static char user_name
[100];
700 static struct passwd p
;
702 DWORD len
= sizeof(user_name
);
703 if (!GetUserName(user_name
, &len
))
705 p
.pw_name
= user_name
;
706 p
.pw_gecos
= "unknown";
711 static HANDLE timer_event
;
712 static HANDLE timer_thread
;
713 static int timer_interval
;
715 static sig_handler_t timer_fn
= SIG_DFL
;
717 /* The timer works like this:
718 * The thread, ticktack(), is a trivial routine that most of the time
719 * only waits to receive the signal to terminate. The main thread tells
720 * the thread to terminate by setting the timer_event to the signalled
722 * But ticktack() interrupts the wait state after the timer's interval
723 * length to call the signal handler.
726 static __stdcall
unsigned ticktack(void *dummy
)
728 while (WaitForSingleObject(timer_event
, timer_interval
) == WAIT_TIMEOUT
) {
729 if (timer_fn
== SIG_DFL
)
731 if (timer_fn
!= SIG_IGN
)
739 static int start_timer_thread(void)
741 timer_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
743 timer_thread
= (HANDLE
) _beginthreadex(NULL
, 0, ticktack
, NULL
, 0, NULL
);
745 return errno
= ENOMEM
,
746 error("cannot start timer thread");
748 return errno
= ENOMEM
,
749 error("cannot allocate resources for timer");
753 static void stop_timer_thread(void)
756 SetEvent(timer_event
); /* tell thread to terminate */
758 int rc
= WaitForSingleObject(timer_thread
, 1000);
759 if (rc
== WAIT_TIMEOUT
)
760 error("timer thread did not terminate timely");
761 else if (rc
!= WAIT_OBJECT_0
)
762 error("waiting for timer thread failed: %lu",
764 CloseHandle(timer_thread
);
767 CloseHandle(timer_event
);
772 static inline int is_timeval_eq(const struct timeval
*i1
, const struct timeval
*i2
)
774 return i1
->tv_sec
== i2
->tv_sec
&& i1
->tv_usec
== i2
->tv_usec
;
777 int setitimer(int type
, struct itimerval
*in
, struct itimerval
*out
)
779 static const struct timeval zero
;
780 static int atexit_done
;
783 return errno
= EINVAL
,
784 error("setitimer param 3 != NULL not implemented");
785 if (!is_timeval_eq(&in
->it_interval
, &zero
) &&
786 !is_timeval_eq(&in
->it_interval
, &in
->it_value
))
787 return errno
= EINVAL
,
788 error("setitimer: it_interval must be zero or eq it_value");
793 if (is_timeval_eq(&in
->it_value
, &zero
) &&
794 is_timeval_eq(&in
->it_interval
, &zero
))
797 timer_interval
= in
->it_value
.tv_sec
* 1000 + in
->it_value
.tv_usec
/ 1000;
798 one_shot
= is_timeval_eq(&in
->it_interval
, &zero
);
800 atexit(stop_timer_thread
);
803 return start_timer_thread();
806 int sigaction(int sig
, struct sigaction
*in
, struct sigaction
*out
)
809 return errno
= EINVAL
,
810 error("sigaction only implemented for SIGALRM");
812 return errno
= EINVAL
,
813 error("sigaction: param 3 != NULL not implemented");
815 timer_fn
= in
->sa_handler
;
820 sig_handler_t
mingw_signal(int sig
, sig_handler_t handler
)
823 return signal(sig
, handler
);
824 sig_handler_t old
= timer_fn
;