1ef2a4caf2be92acebd847a9707c78e41d26eb50
   1#include "../git-compat-util.h"
   2#include "../strbuf.h"
   3
   4unsigned int _CRT_fmode = _O_BINARY;
   5
   6#undef open
   7int mingw_open (const char *filename, int oflags, ...)
   8{
   9        va_list args;
  10        unsigned mode;
  11        va_start(args, oflags);
  12        mode = va_arg(args, int);
  13        va_end(args);
  14
  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;
  22        }
  23        return fd;
  24}
  25
  26unsigned int sleep (unsigned int seconds)
  27{
  28        Sleep(seconds*1000);
  29        return 0;
  30}
  31
  32int mkstemp(char *template)
  33{
  34        char *filename = mktemp(template);
  35        if (filename == NULL)
  36                return -1;
  37        return open(filename, O_RDWR | O_CREAT, 0600);
  38}
  39
  40int gettimeofday(struct timeval *tv, void *tz)
  41{
  42        SYSTEMTIME st;
  43        struct tm tm;
  44        GetSystemTime(&st);
  45        tm.tm_year = st.wYear-1900;
  46        tm.tm_mon = st.wMonth-1;
  47        tm.tm_mday = st.wDay;
  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);
  52        if (tv->tv_sec < 0)
  53                return -1;
  54        tv->tv_usec = st.wMilliseconds*1000;
  55        return 0;
  56}
  57
  58int pipe(int filedes[2])
  59{
  60        int fd;
  61        HANDLE h[2], parent;
  62
  63        if (_pipe(filedes, 8192, 0) < 0)
  64                return -1;
  65
  66        parent = GetCurrentProcess();
  67
  68        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
  69                        parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
  70                close(filedes[0]);
  71                close(filedes[1]);
  72                return -1;
  73        }
  74        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
  75                        parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
  76                close(filedes[0]);
  77                close(filedes[1]);
  78                CloseHandle(h[0]);
  79                return -1;
  80        }
  81        fd = _open_osfhandle((int)h[0], O_NOINHERIT);
  82        if (fd < 0) {
  83                close(filedes[0]);
  84                close(filedes[1]);
  85                CloseHandle(h[0]);
  86                CloseHandle(h[1]);
  87                return -1;
  88        }
  89        close(filedes[0]);
  90        filedes[0] = fd;
  91        fd = _open_osfhandle((int)h[1], O_NOINHERIT);
  92        if (fd < 0) {
  93                close(filedes[0]);
  94                close(filedes[1]);
  95                CloseHandle(h[1]);
  96                return -1;
  97        }
  98        close(filedes[1]);
  99        filedes[1] = fd;
 100        return 0;
 101}
 102
 103int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
 104{
 105        int i, pending;
 106
 107        if (timeout != -1)
 108                return errno = EINVAL, error("poll timeout not supported");
 109
 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().
 113         */
 114        if (nfds == 1) {
 115                if (!(ufds[0].events & POLLIN))
 116                        return errno = EINVAL, error("POLLIN not set");
 117                ufds[0].revents = POLLIN;
 118                return 0;
 119        }
 120
 121repeat:
 122        pending = 0;
 123        for (i = 0; i < nfds; i++) {
 124                DWORD avail = 0;
 125                HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
 126                if (h == INVALID_HANDLE_VALUE)
 127                        return -1;      /* errno was set */
 128
 129                if (!(ufds[i].events & POLLIN))
 130                        return errno = EINVAL, error("POLLIN not set");
 131
 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;
 137                                pending++;
 138                        } else {
 139                                errno = EINVAL;
 140                                return error("PeekNamedPipe failed,"
 141                                        " GetLastError: %u", err);
 142                        }
 143                } else if (avail) {
 144                        ufds[i].revents = POLLIN;
 145                        pending++;
 146                } else
 147                        ufds[i].revents = 0;
 148        }
 149        if (!pending) {
 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.
 156                 */
 157                Sleep(0);
 158                goto repeat;
 159        }
 160        return 0;
 161}
 162
 163struct tm *gmtime_r(const time_t *timep, struct tm *result)
 164{
 165        /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 166        memcpy(result, gmtime(timep), sizeof(struct tm));
 167        return result;
 168}
 169
 170struct tm *localtime_r(const time_t *timep, struct tm *result)
 171{
 172        /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 173        memcpy(result, localtime(timep), sizeof(struct tm));
 174        return result;
 175}
 176
 177#undef getcwd
 178char *mingw_getcwd(char *pointer, int len)
 179{
 180        int i;
 181        char *ret = getcwd(pointer, len);
 182        if (!ret)
 183                return ret;
 184        for (i = 0; pointer[i]; i++)
 185                if (pointer[i] == '\\')
 186                        pointer[i] = '/';
 187        return ret;
 188}
 189
 190/*
 191 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
 192 * (Parsing C++ Command-Line Arguments)
 193 */
 194static const char *quote_arg(const char *arg)
 195{
 196        /* count chars to quote */
 197        int len = 0, n = 0;
 198        int force_quotes = 0;
 199        char *q, *d;
 200        const char *p = arg;
 201        if (!*p) force_quotes = 1;
 202        while (*p) {
 203                if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
 204                        force_quotes = 1;
 205                else if (*p == '"')
 206                        n++;
 207                else if (*p == '\\') {
 208                        int count = 0;
 209                        while (*p == '\\') {
 210                                count++;
 211                                p++;
 212                                len++;
 213                        }
 214                        if (*p == '"')
 215                                n += count*2 + 1;
 216                        continue;
 217                }
 218                len++;
 219                p++;
 220        }
 221        if (!force_quotes && n == 0)
 222                return arg;
 223
 224        /* insert \ where necessary */
 225        d = q = xmalloc(len+n+3);
 226        *d++ = '"';
 227        while (*arg) {
 228                if (*arg == '"')
 229                        *d++ = '\\';
 230                else if (*arg == '\\') {
 231                        int count = 0;
 232                        while (*arg == '\\') {
 233                                count++;
 234                                *d++ = *arg++;
 235                        }
 236                        if (*arg == '"') {
 237                                while (count-- > 0)
 238                                        *d++ = '\\';
 239                                *d++ = '\\';
 240                        }
 241                }
 242                *d++ = *arg++;
 243        }
 244        *d++ = '"';
 245        *d++ = 0;
 246        return q;
 247}
 248
 249static const char *parse_interpreter(const char *cmd)
 250{
 251        static char buf[100];
 252        char *p, *opt;
 253        int n, fd;
 254
 255        /* don't even try a .exe */
 256        n = strlen(cmd);
 257        if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
 258                return NULL;
 259
 260        fd = open(cmd, O_RDONLY);
 261        if (fd < 0)
 262                return NULL;
 263        n = read(fd, buf, sizeof(buf)-1);
 264        close(fd);
 265        if (n < 4)      /* at least '#!/x' and not error */
 266                return NULL;
 267
 268        if (buf[0] != '#' || buf[1] != '!')
 269                return NULL;
 270        buf[n] = '\0';
 271        p = strchr(buf, '\n');
 272        if (!p)
 273                return NULL;
 274
 275        *p = '\0';
 276        if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
 277                return NULL;
 278        /* strip options */
 279        if ((opt = strchr(p+1, ' ')))
 280                *opt = '\0';
 281        return p+1;
 282}
 283
 284/*
 285 * Splits the PATH into parts.
 286 */
 287static char **get_path_split(void)
 288{
 289        char *p, **path, *envpath = getenv("PATH");
 290        int i, n = 0;
 291
 292        if (!envpath || !*envpath)
 293                return NULL;
 294
 295        envpath = xstrdup(envpath);
 296        p = envpath;
 297        while (p) {
 298                char *dir = p;
 299                p = strchr(p, ';');
 300                if (p) *p++ = '\0';
 301                if (*dir) {     /* not earlier, catches series of ; */
 302                        ++n;
 303                }
 304        }
 305        if (!n)
 306                return NULL;
 307
 308        path = xmalloc((n+1)*sizeof(char*));
 309        p = envpath;
 310        i = 0;
 311        do {
 312                if (*p)
 313                        path[i++] = xstrdup(p);
 314                p = p+strlen(p)+1;
 315        } while (i < n);
 316        path[i] = NULL;
 317
 318        free(envpath);
 319
 320        return path;
 321}
 322
 323static void free_path_split(char **path)
 324{
 325        if (!path)
 326                return;
 327
 328        char **p = path;
 329        while (*p)
 330                free(*p++);
 331        free(path);
 332}
 333
 334/*
 335 * exe_only means that we only want to detect .exe files, but not scripts
 336 * (which do not have an extension)
 337 */
 338static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
 339{
 340        char path[MAX_PATH];
 341        snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
 342
 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);
 348        return NULL;
 349}
 350
 351/*
 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.
 354 */
 355static char *path_lookup(const char *cmd, char **path, int exe_only)
 356{
 357        char *prog = NULL;
 358        int len = strlen(cmd);
 359        int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
 360
 361        if (strchr(cmd, '/') || strchr(cmd, '\\'))
 362                prog = xstrdup(cmd);
 363
 364        while (!prog && *path)
 365                prog = lookup_prog(*path++, cmd, isexe, exe_only);
 366
 367        return prog;
 368}
 369
 370static int env_compare(const void *a, const void *b)
 371{
 372        char *const *ea = a;
 373        char *const *eb = b;
 374        return strcasecmp(*ea, *eb);
 375}
 376
 377static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
 378                           int prepend_cmd)
 379{
 380        STARTUPINFO si;
 381        PROCESS_INFORMATION pi;
 382        struct strbuf envblk, args;
 383        unsigned flags;
 384        BOOL ret;
 385
 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.
 396                 */
 397                flags = CREATE_NO_WINDOW;
 398        } else {
 399                /* There is already a console. If we specified
 400                 * CREATE_NO_WINDOW here, too, Windows would
 401                 * disassociate the child from the console.
 402                 * Go figure!
 403                 */
 404                flags = 0;
 405                CloseHandle(cons);
 406        }
 407        memset(&si, 0, sizeof(si));
 408        si.cb = 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);
 413
 414        /* concatenate argv, quoting args as we go */
 415        strbuf_init(&args, 0);
 416        if (prepend_cmd) {
 417                char *quoted = (char *)quote_arg(cmd);
 418                strbuf_addstr(&args, quoted);
 419                if (quoted != cmd)
 420                        free(quoted);
 421        }
 422        for (; *argv; argv++) {
 423                char *quoted = (char *)quote_arg(*argv);
 424                if (*args.buf)
 425                        strbuf_addch(&args, ' ');
 426                strbuf_addstr(&args, quoted);
 427                if (quoted != *argv)
 428                        free(quoted);
 429        }
 430
 431        if (env) {
 432                int count = 0;
 433                char **e, **sorted_env;
 434
 435                for (e = env; *e; e++)
 436                        count++;
 437
 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);
 442
 443                strbuf_init(&envblk, 0);
 444                for (e = sorted_env; *e; e++) {
 445                        strbuf_addstr(&envblk, *e);
 446                        strbuf_addch(&envblk, '\0');
 447                }
 448                free(sorted_env);
 449        }
 450
 451        memset(&pi, 0, sizeof(pi));
 452        ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
 453                env ? envblk.buf : NULL, NULL, &si, &pi);
 454
 455        if (env)
 456                strbuf_release(&envblk);
 457        strbuf_release(&args);
 458
 459        if (!ret) {
 460                errno = ENOENT;
 461                return -1;
 462        }
 463        CloseHandle(pi.hThread);
 464        return (pid_t)pi.hProcess;
 465}
 466
 467pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
 468{
 469        pid_t pid;
 470        char **path = get_path_split();
 471        char *prog = path_lookup(cmd, path, 0);
 472
 473        if (!prog) {
 474                errno = ENOENT;
 475                pid = -1;
 476        }
 477        else {
 478                const char *interpr = parse_interpreter(prog);
 479
 480                if (interpr) {
 481                        const char *argv0 = argv[0];
 482                        char *iprog = path_lookup(interpr, path, 1);
 483                        argv[0] = prog;
 484                        if (!iprog) {
 485                                errno = ENOENT;
 486                                pid = -1;
 487                        }
 488                        else {
 489                                pid = mingw_spawnve(iprog, argv, env, 1);
 490                                free(iprog);
 491                        }
 492                        argv[0] = argv0;
 493                }
 494                else
 495                        pid = mingw_spawnve(prog, argv, env, 0);
 496                free(prog);
 497        }
 498        free_path_split(path);
 499        return pid;
 500}
 501
 502static int try_shell_exec(const char *cmd, char *const *argv, char **env)
 503{
 504        const char *interpr = parse_interpreter(cmd);
 505        char **path;
 506        char *prog;
 507        int pid = 0;
 508
 509        if (!interpr)
 510                return 0;
 511        path = get_path_split();
 512        prog = path_lookup(interpr, path, 1);
 513        if (prog) {
 514                int argc = 0;
 515                const char **argv2;
 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);
 521                if (pid >= 0) {
 522                        int status;
 523                        if (waitpid(pid, &status, 0) < 0)
 524                                status = 255;
 525                        exit(status);
 526                }
 527                pid = 1;        /* indicate that we tried but failed */
 528                free(prog);
 529                free(argv2);
 530        }
 531        free_path_split(path);
 532        return pid;
 533}
 534
 535static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
 536{
 537        /* check if git_command is a shell script */
 538        if (!try_shell_exec(cmd, argv, (char **)env)) {
 539                int pid, status;
 540
 541                pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
 542                if (pid < 0)
 543                        return;
 544                if (waitpid(pid, &status, 0) < 0)
 545                        status = 255;
 546                exit(status);
 547        }
 548}
 549
 550void mingw_execvp(const char *cmd, char *const *argv)
 551{
 552        char **path = get_path_split();
 553        char *prog = path_lookup(cmd, path, 0);
 554
 555        if (prog) {
 556                mingw_execve(prog, argv, environ);
 557                free(prog);
 558        } else
 559                errno = ENOENT;
 560
 561        free_path_split(path);
 562}
 563
 564char **copy_environ()
 565{
 566        char **env;
 567        int i = 0;
 568        while (environ[i])
 569                i++;
 570        env = xmalloc((i+1)*sizeof(*env));
 571        for (i = 0; environ[i]; i++)
 572                env[i] = xstrdup(environ[i]);
 573        env[i] = NULL;
 574        return env;
 575}
 576
 577void free_environ(char **env)
 578{
 579        int i;
 580        for (i = 0; env[i]; i++)
 581                free(env[i]);
 582        free(env);
 583}
 584
 585static int lookup_env(char **env, const char *name, size_t nmln)
 586{
 587        int i;
 588
 589        for (i = 0; env[i]; i++) {
 590                if (0 == strncmp(env[i], name, nmln)
 591                    && '=' == env[i][nmln])
 592                        /* matches */
 593                        return i;
 594        }
 595        return -1;
 596}
 597
 598/*
 599 * If name contains '=', then sets the variable, otherwise it unsets it
 600 */
 601char **env_setenv(char **env, const char *name)
 602{
 603        char *eq = strchrnul(name, '=');
 604        int i = lookup_env(env, name, eq-name);
 605
 606        if (i < 0) {
 607                if (*eq) {
 608                        for (i = 0; env[i]; i++)
 609                                ;
 610                        env = xrealloc(env, (i+2)*sizeof(*env));
 611                        env[i] = xstrdup(name);
 612                        env[i+1] = NULL;
 613                }
 614        }
 615        else {
 616                free(env[i]);
 617                if (*eq)
 618                        env[i] = xstrdup(name);
 619                else
 620                        for (; env[i]; i++)
 621                                env[i] = env[i+1];
 622        }
 623        return env;
 624}
 625
 626/* this is the first function to call into WS_32; initialize it */
 627#undef gethostbyname
 628struct hostent *mingw_gethostbyname(const char *host)
 629{
 630        WSADATA wsa;
 631
 632        if (WSAStartup(MAKEWORD(2,2), &wsa))
 633                die("unable to initialize winsock subsystem, error %d",
 634                        WSAGetLastError());
 635        atexit((void(*)(void)) WSACleanup);
 636        return gethostbyname(host);
 637}
 638
 639int mingw_socket(int domain, int type, int protocol)
 640{
 641        int sockfd;
 642        SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
 643        if (s == INVALID_SOCKET) {
 644                /*
 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.
 652                 */
 653                errno = WSAGetLastError();
 654                return -1;
 655        }
 656        /* convert into a file descriptor */
 657        if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
 658                closesocket(s);
 659                return error("unable to make a socket file descriptor: %s",
 660                        strerror(errno));
 661        }
 662        return sockfd;
 663}
 664
 665#undef connect
 666int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
 667{
 668        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
 669        return connect(s, sa, sz);
 670}
 671
 672#undef rename
 673int mingw_rename(const char *pold, const char *pnew)
 674{
 675        /*
 676         * Try native rename() first to get errno right.
 677         * It is based on MoveFile(), which cannot overwrite existing files.
 678         */
 679        if (!rename(pold, pnew))
 680                return 0;
 681        if (errno != EEXIST)
 682                return -1;
 683        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
 684                return 0;
 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)) {
 689                        errno = EISDIR;
 690                        return -1;
 691                }
 692        }
 693        errno = EACCES;
 694        return -1;
 695}
 696
 697struct passwd *getpwuid(int uid)
 698{
 699        static char user_name[100];
 700        static struct passwd p;
 701
 702        DWORD len = sizeof(user_name);
 703        if (!GetUserName(user_name, &len))
 704                return NULL;
 705        p.pw_name = user_name;
 706        p.pw_gecos = "unknown";
 707        p.pw_dir = NULL;
 708        return &p;
 709}
 710
 711static HANDLE timer_event;
 712static HANDLE timer_thread;
 713static int timer_interval;
 714static int one_shot;
 715static sig_handler_t timer_fn = SIG_DFL;
 716
 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
 721 * state.
 722 * But ticktack() interrupts the wait state after the timer's interval
 723 * length to call the signal handler.
 724 */
 725
 726static __stdcall unsigned ticktack(void *dummy)
 727{
 728        while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
 729                if (timer_fn == SIG_DFL)
 730                        die("Alarm");
 731                if (timer_fn != SIG_IGN)
 732                        timer_fn(SIGALRM);
 733                if (one_shot)
 734                        break;
 735        }
 736        return 0;
 737}
 738
 739static int start_timer_thread(void)
 740{
 741        timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
 742        if (timer_event) {
 743                timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
 744                if (!timer_thread )
 745                        return errno = ENOMEM,
 746                                error("cannot start timer thread");
 747        } else
 748                return errno = ENOMEM,
 749                        error("cannot allocate resources for timer");
 750        return 0;
 751}
 752
 753static void stop_timer_thread(void)
 754{
 755        if (timer_event)
 756                SetEvent(timer_event);  /* tell thread to terminate */
 757        if (timer_thread) {
 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",
 763                              GetLastError());
 764                CloseHandle(timer_thread);
 765        }
 766        if (timer_event)
 767                CloseHandle(timer_event);
 768        timer_event = NULL;
 769        timer_thread = NULL;
 770}
 771
 772static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
 773{
 774        return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
 775}
 776
 777int setitimer(int type, struct itimerval *in, struct itimerval *out)
 778{
 779        static const struct timeval zero;
 780        static int atexit_done;
 781
 782        if (out != NULL)
 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");
 789
 790        if (timer_thread)
 791                stop_timer_thread();
 792
 793        if (is_timeval_eq(&in->it_value, &zero) &&
 794            is_timeval_eq(&in->it_interval, &zero))
 795                return 0;
 796
 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);
 799        if (!atexit_done) {
 800                atexit(stop_timer_thread);
 801                atexit_done = 1;
 802        }
 803        return start_timer_thread();
 804}
 805
 806int sigaction(int sig, struct sigaction *in, struct sigaction *out)
 807{
 808        if (sig != SIGALRM)
 809                return errno = EINVAL,
 810                        error("sigaction only implemented for SIGALRM");
 811        if (out != NULL)
 812                return errno = EINVAL,
 813                        error("sigaction: param 3 != NULL not implemented");
 814
 815        timer_fn = in->sa_handler;
 816        return 0;
 817}
 818
 819#undef signal
 820sig_handler_t mingw_signal(int sig, sig_handler_t handler)
 821{
 822        if (sig != SIGALRM)
 823                return signal(sig, handler);
 824        sig_handler_t old = timer_fn;
 825        timer_fn = handler;
 826        return old;
 827}