Windows: A rudimentary poll() emulation.
[git/dscho.git] / compat / mingw.c
blob2677e78626f9a618d2b17b112c6b58ca1f5f0394
1 #include "../git-compat-util.h"
3 unsigned int _CRT_fmode = _O_BINARY;
5 #undef open
6 int mingw_open (const char *filename, int oflags, ...)
8 va_list args;
9 unsigned mode;
10 va_start(args, oflags);
11 mode = va_arg(args, int);
12 va_end(args);
14 if (!strcmp(filename, "/dev/null"))
15 filename = "nul";
16 int fd = open(filename, oflags, mode);
17 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
18 DWORD attrs = GetFileAttributes(filename);
19 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
20 errno = EISDIR;
22 return fd;
25 unsigned int sleep (unsigned int seconds)
27 Sleep(seconds*1000);
28 return 0;
31 int mkstemp(char *template)
33 char *filename = mktemp(template);
34 if (filename == NULL)
35 return -1;
36 return open(filename, O_RDWR | O_CREAT, 0600);
39 int gettimeofday(struct timeval *tv, void *tz)
41 SYSTEMTIME st;
42 struct tm tm;
43 GetSystemTime(&st);
44 tm.tm_year = st.wYear-1900;
45 tm.tm_mon = st.wMonth-1;
46 tm.tm_mday = st.wDay;
47 tm.tm_hour = st.wHour;
48 tm.tm_min = st.wMinute;
49 tm.tm_sec = st.wSecond;
50 tv->tv_sec = tm_to_time_t(&tm);
51 if (tv->tv_sec < 0)
52 return -1;
53 tv->tv_usec = st.wMilliseconds*1000;
54 return 0;
57 int pipe(int filedes[2])
59 int fd;
60 HANDLE h[2], parent;
62 if (_pipe(filedes, 8192, 0) < 0)
63 return -1;
65 parent = GetCurrentProcess();
67 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
68 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
69 close(filedes[0]);
70 close(filedes[1]);
71 return -1;
73 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
74 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
75 close(filedes[0]);
76 close(filedes[1]);
77 CloseHandle(h[0]);
78 return -1;
80 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
81 if (fd < 0) {
82 close(filedes[0]);
83 close(filedes[1]);
84 CloseHandle(h[0]);
85 CloseHandle(h[1]);
86 return -1;
88 close(filedes[0]);
89 filedes[0] = fd;
90 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
91 if (fd < 0) {
92 close(filedes[0]);
93 close(filedes[1]);
94 CloseHandle(h[1]);
95 return -1;
97 close(filedes[1]);
98 filedes[1] = fd;
99 return 0;
102 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
104 int i, pending;
106 if (timeout != -1)
107 return errno = EINVAL, error("poll timeout not supported");
109 /* When there is only one fd to wait for, then we pretend that
110 * input is available and let the actual wait happen when the
111 * caller invokes read().
113 if (nfds == 1) {
114 if (!(ufds[0].events & POLLIN))
115 return errno = EINVAL, error("POLLIN not set");
116 ufds[0].revents = POLLIN;
117 return 0;
120 repeat:
121 pending = 0;
122 for (i = 0; i < nfds; i++) {
123 DWORD avail = 0;
124 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
125 if (h == INVALID_HANDLE_VALUE)
126 return -1; /* errno was set */
128 if (!(ufds[i].events & POLLIN))
129 return errno = EINVAL, error("POLLIN not set");
131 /* this emulation works only for pipes */
132 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
133 int err = GetLastError();
134 if (err == ERROR_BROKEN_PIPE) {
135 ufds[i].revents = POLLHUP;
136 pending++;
137 } else {
138 errno = EINVAL;
139 return error("PeekNamedPipe failed,"
140 " GetLastError: %u", err);
142 } else if (avail) {
143 ufds[i].revents = POLLIN;
144 pending++;
145 } else
146 ufds[i].revents = 0;
148 if (!pending) {
149 /* The only times that we spin here is when the process
150 * that is connected through the pipes is waiting for
151 * its own input data to become available. But since
152 * the process (pack-objects) is itself CPU intensive,
153 * it will happily pick up the time slice that we are
154 * relinguishing here.
156 Sleep(0);
157 goto repeat;
159 return 0;
162 struct tm *gmtime_r(const time_t *timep, struct tm *result)
164 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
165 memcpy(result, gmtime(timep), sizeof(struct tm));
166 return result;
169 struct tm *localtime_r(const time_t *timep, struct tm *result)
171 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
172 memcpy(result, localtime(timep), sizeof(struct tm));
173 return result;
176 #undef getcwd
177 char *mingw_getcwd(char *pointer, int len)
179 int i;
180 char *ret = getcwd(pointer, len);
181 if (!ret)
182 return ret;
183 for (i = 0; pointer[i]; i++)
184 if (pointer[i] == '\\')
185 pointer[i] = '/';
186 return ret;
189 static const char *parse_interpreter(const char *cmd)
191 static char buf[100];
192 char *p, *opt;
193 int n, fd;
195 /* don't even try a .exe */
196 n = strlen(cmd);
197 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
198 return NULL;
200 fd = open(cmd, O_RDONLY);
201 if (fd < 0)
202 return NULL;
203 n = read(fd, buf, sizeof(buf)-1);
204 close(fd);
205 if (n < 4) /* at least '#!/x' and not error */
206 return NULL;
208 if (buf[0] != '#' || buf[1] != '!')
209 return NULL;
210 buf[n] = '\0';
211 p = strchr(buf, '\n');
212 if (!p)
213 return NULL;
215 *p = '\0';
216 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
217 return NULL;
218 /* strip options */
219 if ((opt = strchr(p+1, ' ')))
220 *opt = '\0';
221 return p+1;
225 * Splits the PATH into parts.
227 static char **get_path_split(void)
229 char *p, **path, *envpath = getenv("PATH");
230 int i, n = 0;
232 if (!envpath || !*envpath)
233 return NULL;
235 envpath = xstrdup(envpath);
236 p = envpath;
237 while (p) {
238 char *dir = p;
239 p = strchr(p, ';');
240 if (p) *p++ = '\0';
241 if (*dir) { /* not earlier, catches series of ; */
242 ++n;
245 if (!n)
246 return NULL;
248 path = xmalloc((n+1)*sizeof(char*));
249 p = envpath;
250 i = 0;
251 do {
252 if (*p)
253 path[i++] = xstrdup(p);
254 p = p+strlen(p)+1;
255 } while (i < n);
256 path[i] = NULL;
258 free(envpath);
260 return path;
263 static void free_path_split(char **path)
265 if (!path)
266 return;
268 char **p = path;
269 while (*p)
270 free(*p++);
271 free(path);
275 * exe_only means that we only want to detect .exe files, but not scripts
276 * (which do not have an extension)
278 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
280 char path[MAX_PATH];
281 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
283 if (!isexe && access(path, F_OK) == 0)
284 return xstrdup(path);
285 path[strlen(path)-4] = '\0';
286 if ((!exe_only || isexe) && access(path, F_OK) == 0)
287 return xstrdup(path);
288 return NULL;
292 * Determines the absolute path of cmd using the the split path in path.
293 * If cmd contains a slash or backslash, no lookup is performed.
295 static char *path_lookup(const char *cmd, char **path, int exe_only)
297 char *prog = NULL;
298 int len = strlen(cmd);
299 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
301 if (strchr(cmd, '/') || strchr(cmd, '\\'))
302 prog = xstrdup(cmd);
304 while (!prog && *path)
305 prog = lookup_prog(*path++, cmd, isexe, exe_only);
307 return prog;
310 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
312 const char *interpr = parse_interpreter(cmd);
313 char **path;
314 char *prog;
315 int pid = 0;
317 if (!interpr)
318 return 0;
319 path = get_path_split();
320 prog = path_lookup(interpr, path, 1);
321 if (prog) {
322 int argc = 0;
323 const char **argv2;
324 while (argv[argc]) argc++;
325 argv2 = xmalloc(sizeof(*argv) * (argc+2));
326 argv2[0] = (char *)interpr;
327 argv2[1] = (char *)cmd; /* full path to the script file */
328 memcpy(&argv2[2], &argv[1], sizeof(*argv) * argc);
329 pid = spawnve(_P_NOWAIT, prog, argv2, (const char **)env);
330 if (pid >= 0) {
331 int status;
332 if (waitpid(pid, &status, 0) < 0)
333 status = 255;
334 exit(status);
336 pid = 1; /* indicate that we tried but failed */
337 free(prog);
338 free(argv2);
340 free_path_split(path);
341 return pid;
344 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
346 /* check if git_command is a shell script */
347 if (!try_shell_exec(cmd, argv, (char **)env)) {
348 int pid, status;
350 pid = spawnve(_P_NOWAIT, cmd, (const char **)argv, (const char **)env);
351 if (pid < 0)
352 return;
353 if (waitpid(pid, &status, 0) < 0)
354 status = 255;
355 exit(status);
359 void mingw_execvp(const char *cmd, char *const *argv)
361 char **path = get_path_split();
362 char *prog = path_lookup(cmd, path, 0);
364 if (prog) {
365 mingw_execve(prog, argv, environ);
366 free(prog);
367 } else
368 errno = ENOENT;
370 free_path_split(path);
373 char **copy_environ()
375 char **env;
376 int i = 0;
377 while (environ[i])
378 i++;
379 env = xmalloc((i+1)*sizeof(*env));
380 for (i = 0; environ[i]; i++)
381 env[i] = xstrdup(environ[i]);
382 env[i] = NULL;
383 return env;
386 void free_environ(char **env)
388 int i;
389 for (i = 0; env[i]; i++)
390 free(env[i]);
391 free(env);
394 static int lookup_env(char **env, const char *name, size_t nmln)
396 int i;
398 for (i = 0; env[i]; i++) {
399 if (0 == strncmp(env[i], name, nmln)
400 && '=' == env[i][nmln])
401 /* matches */
402 return i;
404 return -1;
408 * If name contains '=', then sets the variable, otherwise it unsets it
410 char **env_setenv(char **env, const char *name)
412 char *eq = strchrnul(name, '=');
413 int i = lookup_env(env, name, eq-name);
415 if (i < 0) {
416 if (*eq) {
417 for (i = 0; env[i]; i++)
419 env = xrealloc(env, (i+2)*sizeof(*env));
420 env[i] = xstrdup(name);
421 env[i+1] = NULL;
424 else {
425 free(env[i]);
426 if (*eq)
427 env[i] = xstrdup(name);
428 else
429 for (; env[i]; i++)
430 env[i] = env[i+1];
432 return env;
435 #undef rename
436 int mingw_rename(const char *pold, const char *pnew)
439 * Try native rename() first to get errno right.
440 * It is based on MoveFile(), which cannot overwrite existing files.
442 if (!rename(pold, pnew))
443 return 0;
444 if (errno != EEXIST)
445 return -1;
446 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
447 return 0;
448 /* TODO: translate more errors */
449 if (GetLastError() == ERROR_ACCESS_DENIED) {
450 DWORD attrs = GetFileAttributes(pnew);
451 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
452 errno = EISDIR;
453 return -1;
456 errno = EACCES;
457 return -1;
460 struct passwd *getpwuid(int uid)
462 static char user_name[100];
463 static struct passwd p;
465 DWORD len = sizeof(user_name);
466 if (!GetUserName(user_name, &len))
467 return NULL;
468 p.pw_name = user_name;
469 p.pw_gecos = "unknown";
470 p.pw_dir = NULL;
471 return &p;
474 static HANDLE timer_event;
475 static HANDLE timer_thread;
476 static int timer_interval;
477 static int one_shot;
478 static sig_handler_t timer_fn = SIG_DFL;
480 /* The timer works like this:
481 * The thread, ticktack(), is a trivial routine that most of the time
482 * only waits to receive the signal to terminate. The main thread tells
483 * the thread to terminate by setting the timer_event to the signalled
484 * state.
485 * But ticktack() interrupts the wait state after the timer's interval
486 * length to call the signal handler.
489 static __stdcall unsigned ticktack(void *dummy)
491 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
492 if (timer_fn == SIG_DFL)
493 die("Alarm");
494 if (timer_fn != SIG_IGN)
495 timer_fn(SIGALRM);
496 if (one_shot)
497 break;
499 return 0;
502 static int start_timer_thread(void)
504 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
505 if (timer_event) {
506 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
507 if (!timer_thread )
508 return errno = ENOMEM,
509 error("cannot start timer thread");
510 } else
511 return errno = ENOMEM,
512 error("cannot allocate resources for timer");
513 return 0;
516 static void stop_timer_thread(void)
518 if (timer_event)
519 SetEvent(timer_event); /* tell thread to terminate */
520 if (timer_thread) {
521 int rc = WaitForSingleObject(timer_thread, 1000);
522 if (rc == WAIT_TIMEOUT)
523 error("timer thread did not terminate timely");
524 else if (rc != WAIT_OBJECT_0)
525 error("waiting for timer thread failed: %lu",
526 GetLastError());
527 CloseHandle(timer_thread);
529 if (timer_event)
530 CloseHandle(timer_event);
531 timer_event = NULL;
532 timer_thread = NULL;
535 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
537 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
540 int setitimer(int type, struct itimerval *in, struct itimerval *out)
542 static const struct timeval zero;
543 static int atexit_done;
545 if (out != NULL)
546 return errno = EINVAL,
547 error("setitimer param 3 != NULL not implemented");
548 if (!is_timeval_eq(&in->it_interval, &zero) &&
549 !is_timeval_eq(&in->it_interval, &in->it_value))
550 return errno = EINVAL,
551 error("setitimer: it_interval must be zero or eq it_value");
553 if (timer_thread)
554 stop_timer_thread();
556 if (is_timeval_eq(&in->it_value, &zero) &&
557 is_timeval_eq(&in->it_interval, &zero))
558 return 0;
560 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
561 one_shot = is_timeval_eq(&in->it_interval, &zero);
562 if (!atexit_done) {
563 atexit(stop_timer_thread);
564 atexit_done = 1;
566 return start_timer_thread();
569 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
571 if (sig != SIGALRM)
572 return errno = EINVAL,
573 error("sigaction only implemented for SIGALRM");
574 if (out != NULL)
575 return errno = EINVAL,
576 error("sigaction: param 3 != NULL not implemented");
578 timer_fn = in->sa_handler;
579 return 0;
582 #undef signal
583 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
585 if (sig != SIGALRM)
586 return signal(sig, handler);
587 sig_handler_t old = timer_fn;
588 timer_fn = handler;
589 return old;