Windows: Add a new lstat and fstat implementation based on Win32 API.
[git/vmiklos.git] / compat / mingw.c
blob6b742873da066b6e48e14519cb6f2ed42e5fc524
1 #include "../git-compat-util.h"
2 #include "../strbuf.h"
4 unsigned int _CRT_fmode = _O_BINARY;
6 #undef open
7 int mingw_open (const char *filename, int oflags, ...)
9 va_list args;
10 unsigned mode;
11 va_start(args, oflags);
12 mode = va_arg(args, int);
13 va_end(args);
15 if (!strcmp(filename, "/dev/null"))
16 filename = "nul";
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))
21 errno = EISDIR;
23 return fd;
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 extern int _getdrive( void );
35 /* We keep the do_lstat code in a separate function to avoid recursion.
36 * When a path ends with a slash, the stat will fail with ENOENT. In
37 * this case, we strip the trailing slashes and stat again.
39 static int do_lstat(const char *file_name, struct stat *buf)
41 WIN32_FILE_ATTRIBUTE_DATA fdata;
43 if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
44 int fMode = S_IREAD;
45 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
46 fMode |= S_IFDIR;
47 else
48 fMode |= S_IFREG;
49 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
50 fMode |= S_IWRITE;
52 buf->st_ino = 0;
53 buf->st_gid = 0;
54 buf->st_uid = 0;
55 buf->st_nlink = 1;
56 buf->st_mode = fMode;
57 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
58 buf->st_dev = buf->st_rdev = (_getdrive() - 1);
59 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
60 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
61 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
62 errno = 0;
63 return 0;
66 switch (GetLastError()) {
67 case ERROR_ACCESS_DENIED:
68 case ERROR_SHARING_VIOLATION:
69 case ERROR_LOCK_VIOLATION:
70 case ERROR_SHARING_BUFFER_EXCEEDED:
71 errno = EACCES;
72 break;
73 case ERROR_BUFFER_OVERFLOW:
74 errno = ENAMETOOLONG;
75 break;
76 case ERROR_NOT_ENOUGH_MEMORY:
77 errno = ENOMEM;
78 break;
79 default:
80 errno = ENOENT;
81 break;
83 return -1;
86 /* We provide our own lstat/fstat functions, since the provided
87 * lstat/fstat functions are so slow. These stat functions are
88 * tailored for Git's usage (read: fast), and are not meant to be
89 * complete. Note that Git stat()s are redirected to mingw_lstat()
90 * too, since Windows doesn't really handle symlinks that well.
92 int mingw_lstat(const char *file_name, struct stat *buf)
94 int namelen;
95 static char alt_name[PATH_MAX];
97 if (!do_lstat(file_name, buf))
98 return 0;
100 /* if file_name ended in a '/', Windows returned ENOENT;
101 * try again without trailing slashes
103 if (errno != ENOENT)
104 return -1;
106 namelen = strlen(file_name);
107 if (namelen && file_name[namelen-1] != '/')
108 return -1;
109 while (namelen && file_name[namelen-1] == '/')
110 --namelen;
111 if (!namelen || namelen >= PATH_MAX)
112 return -1;
114 memcpy(alt_name, file_name, namelen);
115 alt_name[namelen] = 0;
116 return do_lstat(alt_name, buf);
119 #undef fstat
120 int mingw_fstat(int fd, struct stat *buf)
122 HANDLE fh = (HANDLE)_get_osfhandle(fd);
123 BY_HANDLE_FILE_INFORMATION fdata;
125 if (fh == INVALID_HANDLE_VALUE) {
126 errno = EBADF;
127 return -1;
129 /* direct non-file handles to MS's fstat() */
130 if (GetFileType(fh) != FILE_TYPE_DISK)
131 return fstat(fd, buf);
133 if (GetFileInformationByHandle(fh, &fdata)) {
134 int fMode = S_IREAD;
135 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
136 fMode |= S_IFDIR;
137 else
138 fMode |= S_IFREG;
139 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
140 fMode |= S_IWRITE;
142 buf->st_ino = 0;
143 buf->st_gid = 0;
144 buf->st_uid = 0;
145 buf->st_nlink = 1;
146 buf->st_mode = fMode;
147 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
148 buf->st_dev = buf->st_rdev = (_getdrive() - 1);
149 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
150 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
151 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
152 return 0;
154 errno = EBADF;
155 return -1;
158 unsigned int sleep (unsigned int seconds)
160 Sleep(seconds*1000);
161 return 0;
164 int mkstemp(char *template)
166 char *filename = mktemp(template);
167 if (filename == NULL)
168 return -1;
169 return open(filename, O_RDWR | O_CREAT, 0600);
172 int gettimeofday(struct timeval *tv, void *tz)
174 SYSTEMTIME st;
175 struct tm tm;
176 GetSystemTime(&st);
177 tm.tm_year = st.wYear-1900;
178 tm.tm_mon = st.wMonth-1;
179 tm.tm_mday = st.wDay;
180 tm.tm_hour = st.wHour;
181 tm.tm_min = st.wMinute;
182 tm.tm_sec = st.wSecond;
183 tv->tv_sec = tm_to_time_t(&tm);
184 if (tv->tv_sec < 0)
185 return -1;
186 tv->tv_usec = st.wMilliseconds*1000;
187 return 0;
190 int pipe(int filedes[2])
192 int fd;
193 HANDLE h[2], parent;
195 if (_pipe(filedes, 8192, 0) < 0)
196 return -1;
198 parent = GetCurrentProcess();
200 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
201 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
202 close(filedes[0]);
203 close(filedes[1]);
204 return -1;
206 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
207 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
208 close(filedes[0]);
209 close(filedes[1]);
210 CloseHandle(h[0]);
211 return -1;
213 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
214 if (fd < 0) {
215 close(filedes[0]);
216 close(filedes[1]);
217 CloseHandle(h[0]);
218 CloseHandle(h[1]);
219 return -1;
221 close(filedes[0]);
222 filedes[0] = fd;
223 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
224 if (fd < 0) {
225 close(filedes[0]);
226 close(filedes[1]);
227 CloseHandle(h[1]);
228 return -1;
230 close(filedes[1]);
231 filedes[1] = fd;
232 return 0;
235 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
237 int i, pending;
239 if (timeout != -1)
240 return errno = EINVAL, error("poll timeout not supported");
242 /* When there is only one fd to wait for, then we pretend that
243 * input is available and let the actual wait happen when the
244 * caller invokes read().
246 if (nfds == 1) {
247 if (!(ufds[0].events & POLLIN))
248 return errno = EINVAL, error("POLLIN not set");
249 ufds[0].revents = POLLIN;
250 return 0;
253 repeat:
254 pending = 0;
255 for (i = 0; i < nfds; i++) {
256 DWORD avail = 0;
257 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
258 if (h == INVALID_HANDLE_VALUE)
259 return -1; /* errno was set */
261 if (!(ufds[i].events & POLLIN))
262 return errno = EINVAL, error("POLLIN not set");
264 /* this emulation works only for pipes */
265 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
266 int err = GetLastError();
267 if (err == ERROR_BROKEN_PIPE) {
268 ufds[i].revents = POLLHUP;
269 pending++;
270 } else {
271 errno = EINVAL;
272 return error("PeekNamedPipe failed,"
273 " GetLastError: %u", err);
275 } else if (avail) {
276 ufds[i].revents = POLLIN;
277 pending++;
278 } else
279 ufds[i].revents = 0;
281 if (!pending) {
282 /* The only times that we spin here is when the process
283 * that is connected through the pipes is waiting for
284 * its own input data to become available. But since
285 * the process (pack-objects) is itself CPU intensive,
286 * it will happily pick up the time slice that we are
287 * relinguishing here.
289 Sleep(0);
290 goto repeat;
292 return 0;
295 struct tm *gmtime_r(const time_t *timep, struct tm *result)
297 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
298 memcpy(result, gmtime(timep), sizeof(struct tm));
299 return result;
302 struct tm *localtime_r(const time_t *timep, struct tm *result)
304 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
305 memcpy(result, localtime(timep), sizeof(struct tm));
306 return result;
309 #undef getcwd
310 char *mingw_getcwd(char *pointer, int len)
312 int i;
313 char *ret = getcwd(pointer, len);
314 if (!ret)
315 return ret;
316 for (i = 0; pointer[i]; i++)
317 if (pointer[i] == '\\')
318 pointer[i] = '/';
319 return ret;
323 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
324 * (Parsing C++ Command-Line Arguments)
326 static const char *quote_arg(const char *arg)
328 /* count chars to quote */
329 int len = 0, n = 0;
330 int force_quotes = 0;
331 char *q, *d;
332 const char *p = arg;
333 if (!*p) force_quotes = 1;
334 while (*p) {
335 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
336 force_quotes = 1;
337 else if (*p == '"')
338 n++;
339 else if (*p == '\\') {
340 int count = 0;
341 while (*p == '\\') {
342 count++;
343 p++;
344 len++;
346 if (*p == '"')
347 n += count*2 + 1;
348 continue;
350 len++;
351 p++;
353 if (!force_quotes && n == 0)
354 return arg;
356 /* insert \ where necessary */
357 d = q = xmalloc(len+n+3);
358 *d++ = '"';
359 while (*arg) {
360 if (*arg == '"')
361 *d++ = '\\';
362 else if (*arg == '\\') {
363 int count = 0;
364 while (*arg == '\\') {
365 count++;
366 *d++ = *arg++;
368 if (*arg == '"') {
369 while (count-- > 0)
370 *d++ = '\\';
371 *d++ = '\\';
374 *d++ = *arg++;
376 *d++ = '"';
377 *d++ = 0;
378 return q;
381 static const char *parse_interpreter(const char *cmd)
383 static char buf[100];
384 char *p, *opt;
385 int n, fd;
387 /* don't even try a .exe */
388 n = strlen(cmd);
389 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
390 return NULL;
392 fd = open(cmd, O_RDONLY);
393 if (fd < 0)
394 return NULL;
395 n = read(fd, buf, sizeof(buf)-1);
396 close(fd);
397 if (n < 4) /* at least '#!/x' and not error */
398 return NULL;
400 if (buf[0] != '#' || buf[1] != '!')
401 return NULL;
402 buf[n] = '\0';
403 p = strchr(buf, '\n');
404 if (!p)
405 return NULL;
407 *p = '\0';
408 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
409 return NULL;
410 /* strip options */
411 if ((opt = strchr(p+1, ' ')))
412 *opt = '\0';
413 return p+1;
417 * Splits the PATH into parts.
419 static char **get_path_split(void)
421 char *p, **path, *envpath = getenv("PATH");
422 int i, n = 0;
424 if (!envpath || !*envpath)
425 return NULL;
427 envpath = xstrdup(envpath);
428 p = envpath;
429 while (p) {
430 char *dir = p;
431 p = strchr(p, ';');
432 if (p) *p++ = '\0';
433 if (*dir) { /* not earlier, catches series of ; */
434 ++n;
437 if (!n)
438 return NULL;
440 path = xmalloc((n+1)*sizeof(char*));
441 p = envpath;
442 i = 0;
443 do {
444 if (*p)
445 path[i++] = xstrdup(p);
446 p = p+strlen(p)+1;
447 } while (i < n);
448 path[i] = NULL;
450 free(envpath);
452 return path;
455 static void free_path_split(char **path)
457 if (!path)
458 return;
460 char **p = path;
461 while (*p)
462 free(*p++);
463 free(path);
467 * exe_only means that we only want to detect .exe files, but not scripts
468 * (which do not have an extension)
470 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
472 char path[MAX_PATH];
473 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
475 if (!isexe && access(path, F_OK) == 0)
476 return xstrdup(path);
477 path[strlen(path)-4] = '\0';
478 if ((!exe_only || isexe) && access(path, F_OK) == 0)
479 return xstrdup(path);
480 return NULL;
484 * Determines the absolute path of cmd using the the split path in path.
485 * If cmd contains a slash or backslash, no lookup is performed.
487 static char *path_lookup(const char *cmd, char **path, int exe_only)
489 char *prog = NULL;
490 int len = strlen(cmd);
491 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
493 if (strchr(cmd, '/') || strchr(cmd, '\\'))
494 prog = xstrdup(cmd);
496 while (!prog && *path)
497 prog = lookup_prog(*path++, cmd, isexe, exe_only);
499 return prog;
502 static int env_compare(const void *a, const void *b)
504 char *const *ea = a;
505 char *const *eb = b;
506 return strcasecmp(*ea, *eb);
509 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
510 int prepend_cmd)
512 STARTUPINFO si;
513 PROCESS_INFORMATION pi;
514 struct strbuf envblk, args;
515 unsigned flags;
516 BOOL ret;
518 /* Determine whether or not we are associated to a console */
519 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
520 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
521 FILE_ATTRIBUTE_NORMAL, NULL);
522 if (cons == INVALID_HANDLE_VALUE) {
523 /* There is no console associated with this process.
524 * Since the child is a console process, Windows
525 * would normally create a console window. But
526 * since we'll be redirecting std streams, we do
527 * not need the console.
529 flags = CREATE_NO_WINDOW;
530 } else {
531 /* There is already a console. If we specified
532 * CREATE_NO_WINDOW here, too, Windows would
533 * disassociate the child from the console.
534 * Go figure!
536 flags = 0;
537 CloseHandle(cons);
539 memset(&si, 0, sizeof(si));
540 si.cb = sizeof(si);
541 si.dwFlags = STARTF_USESTDHANDLES;
542 si.hStdInput = (HANDLE) _get_osfhandle(0);
543 si.hStdOutput = (HANDLE) _get_osfhandle(1);
544 si.hStdError = (HANDLE) _get_osfhandle(2);
546 /* concatenate argv, quoting args as we go */
547 strbuf_init(&args, 0);
548 if (prepend_cmd) {
549 char *quoted = (char *)quote_arg(cmd);
550 strbuf_addstr(&args, quoted);
551 if (quoted != cmd)
552 free(quoted);
554 for (; *argv; argv++) {
555 char *quoted = (char *)quote_arg(*argv);
556 if (*args.buf)
557 strbuf_addch(&args, ' ');
558 strbuf_addstr(&args, quoted);
559 if (quoted != *argv)
560 free(quoted);
563 if (env) {
564 int count = 0;
565 char **e, **sorted_env;
567 for (e = env; *e; e++)
568 count++;
570 /* environment must be sorted */
571 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
572 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
573 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
575 strbuf_init(&envblk, 0);
576 for (e = sorted_env; *e; e++) {
577 strbuf_addstr(&envblk, *e);
578 strbuf_addch(&envblk, '\0');
580 free(sorted_env);
583 memset(&pi, 0, sizeof(pi));
584 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
585 env ? envblk.buf : NULL, NULL, &si, &pi);
587 if (env)
588 strbuf_release(&envblk);
589 strbuf_release(&args);
591 if (!ret) {
592 errno = ENOENT;
593 return -1;
595 CloseHandle(pi.hThread);
596 return (pid_t)pi.hProcess;
599 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
601 pid_t pid;
602 char **path = get_path_split();
603 char *prog = path_lookup(cmd, path, 0);
605 if (!prog) {
606 errno = ENOENT;
607 pid = -1;
609 else {
610 const char *interpr = parse_interpreter(prog);
612 if (interpr) {
613 const char *argv0 = argv[0];
614 char *iprog = path_lookup(interpr, path, 1);
615 argv[0] = prog;
616 if (!iprog) {
617 errno = ENOENT;
618 pid = -1;
620 else {
621 pid = mingw_spawnve(iprog, argv, env, 1);
622 free(iprog);
624 argv[0] = argv0;
626 else
627 pid = mingw_spawnve(prog, argv, env, 0);
628 free(prog);
630 free_path_split(path);
631 return pid;
634 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
636 const char *interpr = parse_interpreter(cmd);
637 char **path;
638 char *prog;
639 int pid = 0;
641 if (!interpr)
642 return 0;
643 path = get_path_split();
644 prog = path_lookup(interpr, path, 1);
645 if (prog) {
646 int argc = 0;
647 const char **argv2;
648 while (argv[argc]) argc++;
649 argv2 = xmalloc(sizeof(*argv) * (argc+1));
650 argv2[0] = (char *)cmd; /* full path to the script file */
651 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
652 pid = mingw_spawnve(prog, argv2, env, 1);
653 if (pid >= 0) {
654 int status;
655 if (waitpid(pid, &status, 0) < 0)
656 status = 255;
657 exit(status);
659 pid = 1; /* indicate that we tried but failed */
660 free(prog);
661 free(argv2);
663 free_path_split(path);
664 return pid;
667 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
669 /* check if git_command is a shell script */
670 if (!try_shell_exec(cmd, argv, (char **)env)) {
671 int pid, status;
673 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
674 if (pid < 0)
675 return;
676 if (waitpid(pid, &status, 0) < 0)
677 status = 255;
678 exit(status);
682 void mingw_execvp(const char *cmd, char *const *argv)
684 char **path = get_path_split();
685 char *prog = path_lookup(cmd, path, 0);
687 if (prog) {
688 mingw_execve(prog, argv, environ);
689 free(prog);
690 } else
691 errno = ENOENT;
693 free_path_split(path);
696 char **copy_environ()
698 char **env;
699 int i = 0;
700 while (environ[i])
701 i++;
702 env = xmalloc((i+1)*sizeof(*env));
703 for (i = 0; environ[i]; i++)
704 env[i] = xstrdup(environ[i]);
705 env[i] = NULL;
706 return env;
709 void free_environ(char **env)
711 int i;
712 for (i = 0; env[i]; i++)
713 free(env[i]);
714 free(env);
717 static int lookup_env(char **env, const char *name, size_t nmln)
719 int i;
721 for (i = 0; env[i]; i++) {
722 if (0 == strncmp(env[i], name, nmln)
723 && '=' == env[i][nmln])
724 /* matches */
725 return i;
727 return -1;
731 * If name contains '=', then sets the variable, otherwise it unsets it
733 char **env_setenv(char **env, const char *name)
735 char *eq = strchrnul(name, '=');
736 int i = lookup_env(env, name, eq-name);
738 if (i < 0) {
739 if (*eq) {
740 for (i = 0; env[i]; i++)
742 env = xrealloc(env, (i+2)*sizeof(*env));
743 env[i] = xstrdup(name);
744 env[i+1] = NULL;
747 else {
748 free(env[i]);
749 if (*eq)
750 env[i] = xstrdup(name);
751 else
752 for (; env[i]; i++)
753 env[i] = env[i+1];
755 return env;
758 /* this is the first function to call into WS_32; initialize it */
759 #undef gethostbyname
760 struct hostent *mingw_gethostbyname(const char *host)
762 WSADATA wsa;
764 if (WSAStartup(MAKEWORD(2,2), &wsa))
765 die("unable to initialize winsock subsystem, error %d",
766 WSAGetLastError());
767 atexit((void(*)(void)) WSACleanup);
768 return gethostbyname(host);
771 int mingw_socket(int domain, int type, int protocol)
773 int sockfd;
774 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
775 if (s == INVALID_SOCKET) {
777 * WSAGetLastError() values are regular BSD error codes
778 * biased by WSABASEERR.
779 * However, strerror() does not know about networking
780 * specific errors, which are values beginning at 38 or so.
781 * Therefore, we choose to leave the biased error code
782 * in errno so that _if_ someone looks up the code somewhere,
783 * then it is at least the number that are usually listed.
785 errno = WSAGetLastError();
786 return -1;
788 /* convert into a file descriptor */
789 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
790 closesocket(s);
791 return error("unable to make a socket file descriptor: %s",
792 strerror(errno));
794 return sockfd;
797 #undef connect
798 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
800 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
801 return connect(s, sa, sz);
804 #undef rename
805 int mingw_rename(const char *pold, const char *pnew)
808 * Try native rename() first to get errno right.
809 * It is based on MoveFile(), which cannot overwrite existing files.
811 if (!rename(pold, pnew))
812 return 0;
813 if (errno != EEXIST)
814 return -1;
815 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
816 return 0;
817 /* TODO: translate more errors */
818 if (GetLastError() == ERROR_ACCESS_DENIED) {
819 DWORD attrs = GetFileAttributes(pnew);
820 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
821 errno = EISDIR;
822 return -1;
825 errno = EACCES;
826 return -1;
829 struct passwd *getpwuid(int uid)
831 static char user_name[100];
832 static struct passwd p;
834 DWORD len = sizeof(user_name);
835 if (!GetUserName(user_name, &len))
836 return NULL;
837 p.pw_name = user_name;
838 p.pw_gecos = "unknown";
839 p.pw_dir = NULL;
840 return &p;
843 static HANDLE timer_event;
844 static HANDLE timer_thread;
845 static int timer_interval;
846 static int one_shot;
847 static sig_handler_t timer_fn = SIG_DFL;
849 /* The timer works like this:
850 * The thread, ticktack(), is a trivial routine that most of the time
851 * only waits to receive the signal to terminate. The main thread tells
852 * the thread to terminate by setting the timer_event to the signalled
853 * state.
854 * But ticktack() interrupts the wait state after the timer's interval
855 * length to call the signal handler.
858 static __stdcall unsigned ticktack(void *dummy)
860 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
861 if (timer_fn == SIG_DFL)
862 die("Alarm");
863 if (timer_fn != SIG_IGN)
864 timer_fn(SIGALRM);
865 if (one_shot)
866 break;
868 return 0;
871 static int start_timer_thread(void)
873 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
874 if (timer_event) {
875 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
876 if (!timer_thread )
877 return errno = ENOMEM,
878 error("cannot start timer thread");
879 } else
880 return errno = ENOMEM,
881 error("cannot allocate resources for timer");
882 return 0;
885 static void stop_timer_thread(void)
887 if (timer_event)
888 SetEvent(timer_event); /* tell thread to terminate */
889 if (timer_thread) {
890 int rc = WaitForSingleObject(timer_thread, 1000);
891 if (rc == WAIT_TIMEOUT)
892 error("timer thread did not terminate timely");
893 else if (rc != WAIT_OBJECT_0)
894 error("waiting for timer thread failed: %lu",
895 GetLastError());
896 CloseHandle(timer_thread);
898 if (timer_event)
899 CloseHandle(timer_event);
900 timer_event = NULL;
901 timer_thread = NULL;
904 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
906 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
909 int setitimer(int type, struct itimerval *in, struct itimerval *out)
911 static const struct timeval zero;
912 static int atexit_done;
914 if (out != NULL)
915 return errno = EINVAL,
916 error("setitimer param 3 != NULL not implemented");
917 if (!is_timeval_eq(&in->it_interval, &zero) &&
918 !is_timeval_eq(&in->it_interval, &in->it_value))
919 return errno = EINVAL,
920 error("setitimer: it_interval must be zero or eq it_value");
922 if (timer_thread)
923 stop_timer_thread();
925 if (is_timeval_eq(&in->it_value, &zero) &&
926 is_timeval_eq(&in->it_interval, &zero))
927 return 0;
929 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
930 one_shot = is_timeval_eq(&in->it_interval, &zero);
931 if (!atexit_done) {
932 atexit(stop_timer_thread);
933 atexit_done = 1;
935 return start_timer_thread();
938 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
940 if (sig != SIGALRM)
941 return errno = EINVAL,
942 error("sigaction only implemented for SIGALRM");
943 if (out != NULL)
944 return errno = EINVAL,
945 error("sigaction: param 3 != NULL not implemented");
947 timer_fn = in->sa_handler;
948 return 0;
951 #undef signal
952 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
954 if (sig != SIGALRM)
955 return signal(sig, handler);
956 sig_handler_t old = timer_fn;
957 timer_fn = handler;
958 return old;