28d32969b949a987e88007a5b7fe472ab3f93ac4
   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
  26static inline time_t filetime_to_time_t(const FILETIME *ft)
  27{
  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;
  32}
  33
  34static inline size_t size_to_blocks(size_t s)
  35{
  36        return (s+511)/512;
  37}
  38
  39extern 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.
  43 */
  44static int do_lstat(const char *file_name, struct stat *buf)
  45{
  46        WIN32_FILE_ATTRIBUTE_DATA fdata;
  47
  48        if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
  49                int fMode = S_IREAD;
  50                if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  51                        fMode |= S_IFDIR;
  52                else
  53                        fMode |= S_IFREG;
  54                if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
  55                        fMode |= S_IWRITE;
  56
  57                buf->st_ino = 0;
  58                buf->st_gid = 0;
  59                buf->st_uid = 0;
  60                buf->st_mode = fMode;
  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));
  67                errno = 0;
  68                return 0;
  69        }
  70
  71        switch (GetLastError()) {
  72        case ERROR_ACCESS_DENIED:
  73        case ERROR_SHARING_VIOLATION:
  74        case ERROR_LOCK_VIOLATION:
  75        case ERROR_SHARING_BUFFER_EXCEEDED:
  76                errno = EACCES;
  77                break;
  78        case ERROR_BUFFER_OVERFLOW:
  79                errno = ENAMETOOLONG;
  80                break;
  81        case ERROR_NOT_ENOUGH_MEMORY:
  82                errno = ENOMEM;
  83                break;
  84        default:
  85                errno = ENOENT;
  86                break;
  87        }
  88        return -1;
  89}
  90
  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.
  96 */
  97int mingw_lstat(const char *file_name, struct mingw_stat *buf)
  98{
  99        int namelen;
 100        static char alt_name[PATH_MAX];
 101
 102        if (!do_lstat(file_name, buf))
 103                return 0;
 104
 105        /* if file_name ended in a '/', Windows returned ENOENT;
 106         * try again without trailing slashes
 107         */
 108        if (errno != ENOENT)
 109                return -1;
 110
 111        namelen = strlen(file_name);
 112        if (namelen && file_name[namelen-1] != '/')
 113                return -1;
 114        while (namelen && file_name[namelen-1] == '/')
 115                --namelen;
 116        if (!namelen || namelen >= PATH_MAX)
 117                return -1;
 118
 119        memcpy(alt_name, file_name, namelen);
 120        alt_name[namelen] = 0;
 121        return do_lstat(alt_name, buf);
 122}
 123
 124#undef fstat
 125#undef stat
 126int mingw_fstat(int fd, struct mingw_stat *buf)
 127{
 128        HANDLE fh = (HANDLE)_get_osfhandle(fd);
 129        BY_HANDLE_FILE_INFORMATION fdata;
 130
 131        if (fh == INVALID_HANDLE_VALUE) {
 132                errno = EBADF;
 133                return -1;
 134        }
 135        /* direct non-file handles to MS's fstat() */
 136        if (GetFileType(fh) != FILE_TYPE_DISK) {
 137                struct stat st;
 138                if (fstat(fd, &st))
 139                        return -1;
 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;
 150                return 0;
 151        }
 152
 153        if (GetFileInformationByHandle(fh, &fdata)) {
 154                int fMode = S_IREAD;
 155                if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
 156                        fMode |= S_IFDIR;
 157                else
 158                        fMode |= S_IFREG;
 159                if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
 160                        fMode |= S_IWRITE;
 161
 162                buf->st_ino = 0;
 163                buf->st_gid = 0;
 164                buf->st_uid = 0;
 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));
 172                return 0;
 173        }
 174        errno = EBADF;
 175        return -1;
 176}
 177
 178static inline void time_t_to_filetime(time_t t, FILETIME *ft)
 179{
 180        long long winTime = t * 10000000LL + 116444736000000000LL;
 181        ft->dwLowDateTime = winTime;
 182        ft->dwHighDateTime = winTime >> 32;
 183}
 184
 185int mingw_utime (const char *file_name, const struct utimbuf *times)
 186{
 187        FILETIME mft, aft;
 188        int fh, rc;
 189
 190        /* must have write permission */
 191        if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
 192                return -1;
 193
 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)) {
 197                errno = EINVAL;
 198                rc = -1;
 199        } else
 200                rc = 0;
 201        close(fh);
 202        return rc;
 203}
 204
 205unsigned int sleep (unsigned int seconds)
 206{
 207        Sleep(seconds*1000);
 208        return 0;
 209}
 210
 211int mkstemp(char *template)
 212{
 213        char *filename = mktemp(template);
 214        if (filename == NULL)
 215                return -1;
 216        return open(filename, O_RDWR | O_CREAT, 0600);
 217}
 218
 219int gettimeofday(struct timeval *tv, void *tz)
 220{
 221        SYSTEMTIME st;
 222        struct tm tm;
 223        GetSystemTime(&st);
 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);
 231        if (tv->tv_sec < 0)
 232                return -1;
 233        tv->tv_usec = st.wMilliseconds*1000;
 234        return 0;
 235}
 236
 237int pipe(int filedes[2])
 238{
 239        int fd;
 240        HANDLE h[2], parent;
 241
 242        if (_pipe(filedes, 8192, 0) < 0)
 243                return -1;
 244
 245        parent = GetCurrentProcess();
 246
 247        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
 248                        parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
 249                close(filedes[0]);
 250                close(filedes[1]);
 251                return -1;
 252        }
 253        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
 254                        parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
 255                close(filedes[0]);
 256                close(filedes[1]);
 257                CloseHandle(h[0]);
 258                return -1;
 259        }
 260        fd = _open_osfhandle((int)h[0], O_NOINHERIT);
 261        if (fd < 0) {
 262                close(filedes[0]);
 263                close(filedes[1]);
 264                CloseHandle(h[0]);
 265                CloseHandle(h[1]);
 266                return -1;
 267        }
 268        close(filedes[0]);
 269        filedes[0] = fd;
 270        fd = _open_osfhandle((int)h[1], O_NOINHERIT);
 271        if (fd < 0) {
 272                close(filedes[0]);
 273                close(filedes[1]);
 274                CloseHandle(h[1]);
 275                return -1;
 276        }
 277        close(filedes[1]);
 278        filedes[1] = fd;
 279        return 0;
 280}
 281
 282int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
 283{
 284        int i, pending;
 285
 286        if (timeout != -1)
 287                return errno = EINVAL, error("poll timeout not supported");
 288
 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().
 292         */
 293        if (nfds == 1) {
 294                if (!(ufds[0].events & POLLIN))
 295                        return errno = EINVAL, error("POLLIN not set");
 296                ufds[0].revents = POLLIN;
 297                return 0;
 298        }
 299
 300repeat:
 301        pending = 0;
 302        for (i = 0; i < nfds; i++) {
 303                DWORD avail = 0;
 304                HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
 305                if (h == INVALID_HANDLE_VALUE)
 306                        return -1;      /* errno was set */
 307
 308                if (!(ufds[i].events & POLLIN))
 309                        return errno = EINVAL, error("POLLIN not set");
 310
 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;
 316                                pending++;
 317                        } else {
 318                                errno = EINVAL;
 319                                return error("PeekNamedPipe failed,"
 320                                        " GetLastError: %u", err);
 321                        }
 322                } else if (avail) {
 323                        ufds[i].revents = POLLIN;
 324                        pending++;
 325                } else
 326                        ufds[i].revents = 0;
 327        }
 328        if (!pending) {
 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.
 335                 */
 336                Sleep(0);
 337                goto repeat;
 338        }
 339        return 0;
 340}
 341
 342struct tm *gmtime_r(const time_t *timep, struct tm *result)
 343{
 344        /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 345        memcpy(result, gmtime(timep), sizeof(struct tm));
 346        return result;
 347}
 348
 349struct tm *localtime_r(const time_t *timep, struct tm *result)
 350{
 351        /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 352        memcpy(result, localtime(timep), sizeof(struct tm));
 353        return result;
 354}
 355
 356#undef getcwd
 357char *mingw_getcwd(char *pointer, int len)
 358{
 359        int i;
 360        char *ret = getcwd(pointer, len);
 361        if (!ret)
 362                return ret;
 363        for (i = 0; pointer[i]; i++)
 364                if (pointer[i] == '\\')
 365                        pointer[i] = '/';
 366        return ret;
 367}
 368
 369/*
 370 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
 371 * (Parsing C++ Command-Line Arguments)
 372 */
 373static const char *quote_arg(const char *arg)
 374{
 375        /* count chars to quote */
 376        int len = 0, n = 0;
 377        int force_quotes = 0;
 378        char *q, *d;
 379        const char *p = arg;
 380        if (!*p) force_quotes = 1;
 381        while (*p) {
 382                if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
 383                        force_quotes = 1;
 384                else if (*p == '"')
 385                        n++;
 386                else if (*p == '\\') {
 387                        int count = 0;
 388                        while (*p == '\\') {
 389                                count++;
 390                                p++;
 391                                len++;
 392                        }
 393                        if (*p == '"')
 394                                n += count*2 + 1;
 395                        continue;
 396                }
 397                len++;
 398                p++;
 399        }
 400        if (!force_quotes && n == 0)
 401                return arg;
 402
 403        /* insert \ where necessary */
 404        d = q = xmalloc(len+n+3);
 405        *d++ = '"';
 406        while (*arg) {
 407                if (*arg == '"')
 408                        *d++ = '\\';
 409                else if (*arg == '\\') {
 410                        int count = 0;
 411                        while (*arg == '\\') {
 412                                count++;
 413                                *d++ = *arg++;
 414                        }
 415                        if (*arg == '"') {
 416                                while (count-- > 0)
 417                                        *d++ = '\\';
 418                                *d++ = '\\';
 419                        }
 420                }
 421                *d++ = *arg++;
 422        }
 423        *d++ = '"';
 424        *d++ = 0;
 425        return q;
 426}
 427
 428static const char *parse_interpreter(const char *cmd)
 429{
 430        static char buf[100];
 431        char *p, *opt;
 432        int n, fd;
 433
 434        /* don't even try a .exe */
 435        n = strlen(cmd);
 436        if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
 437                return NULL;
 438
 439        fd = open(cmd, O_RDONLY);
 440        if (fd < 0)
 441                return NULL;
 442        n = read(fd, buf, sizeof(buf)-1);
 443        close(fd);
 444        if (n < 4)      /* at least '#!/x' and not error */
 445                return NULL;
 446
 447        if (buf[0] != '#' || buf[1] != '!')
 448                return NULL;
 449        buf[n] = '\0';
 450        p = strchr(buf, '\n');
 451        if (!p)
 452                return NULL;
 453
 454        *p = '\0';
 455        if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
 456                return NULL;
 457        /* strip options */
 458        if ((opt = strchr(p+1, ' ')))
 459                *opt = '\0';
 460        return p+1;
 461}
 462
 463/*
 464 * Splits the PATH into parts.
 465 */
 466static char **get_path_split(void)
 467{
 468        char *p, **path, *envpath = getenv("PATH");
 469        int i, n = 0;
 470
 471        if (!envpath || !*envpath)
 472                return NULL;
 473
 474        envpath = xstrdup(envpath);
 475        p = envpath;
 476        while (p) {
 477                char *dir = p;
 478                p = strchr(p, ';');
 479                if (p) *p++ = '\0';
 480                if (*dir) {     /* not earlier, catches series of ; */
 481                        ++n;
 482                }
 483        }
 484        if (!n)
 485                return NULL;
 486
 487        path = xmalloc((n+1)*sizeof(char*));
 488        p = envpath;
 489        i = 0;
 490        do {
 491                if (*p)
 492                        path[i++] = xstrdup(p);
 493                p = p+strlen(p)+1;
 494        } while (i < n);
 495        path[i] = NULL;
 496
 497        free(envpath);
 498
 499        return path;
 500}
 501
 502static void free_path_split(char **path)
 503{
 504        if (!path)
 505                return;
 506
 507        char **p = path;
 508        while (*p)
 509                free(*p++);
 510        free(path);
 511}
 512
 513/*
 514 * exe_only means that we only want to detect .exe files, but not scripts
 515 * (which do not have an extension)
 516 */
 517static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
 518{
 519        char path[MAX_PATH];
 520        snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
 521
 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);
 527        return NULL;
 528}
 529
 530/*
 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.
 533 */
 534static char *path_lookup(const char *cmd, char **path, int exe_only)
 535{
 536        char *prog = NULL;
 537        int len = strlen(cmd);
 538        int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
 539
 540        if (strchr(cmd, '/') || strchr(cmd, '\\'))
 541                prog = xstrdup(cmd);
 542
 543        while (!prog && *path)
 544                prog = lookup_prog(*path++, cmd, isexe, exe_only);
 545
 546        return prog;
 547}
 548
 549static int env_compare(const void *a, const void *b)
 550{
 551        char *const *ea = a;
 552        char *const *eb = b;
 553        return strcasecmp(*ea, *eb);
 554}
 555
 556static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
 557                           int prepend_cmd)
 558{
 559        STARTUPINFO si;
 560        PROCESS_INFORMATION pi;
 561        struct strbuf envblk, args;
 562        unsigned flags;
 563        BOOL ret;
 564
 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.
 575                 */
 576                flags = CREATE_NO_WINDOW;
 577        } else {
 578                /* There is already a console. If we specified
 579                 * CREATE_NO_WINDOW here, too, Windows would
 580                 * disassociate the child from the console.
 581                 * Go figure!
 582                 */
 583                flags = 0;
 584                CloseHandle(cons);
 585        }
 586        memset(&si, 0, sizeof(si));
 587        si.cb = 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);
 592
 593        /* concatenate argv, quoting args as we go */
 594        strbuf_init(&args, 0);
 595        if (prepend_cmd) {
 596                char *quoted = (char *)quote_arg(cmd);
 597                strbuf_addstr(&args, quoted);
 598                if (quoted != cmd)
 599                        free(quoted);
 600        }
 601        for (; *argv; argv++) {
 602                char *quoted = (char *)quote_arg(*argv);
 603                if (*args.buf)
 604                        strbuf_addch(&args, ' ');
 605                strbuf_addstr(&args, quoted);
 606                if (quoted != *argv)
 607                        free(quoted);
 608        }
 609
 610        if (env) {
 611                int count = 0;
 612                char **e, **sorted_env;
 613
 614                for (e = env; *e; e++)
 615                        count++;
 616
 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);
 621
 622                strbuf_init(&envblk, 0);
 623                for (e = sorted_env; *e; e++) {
 624                        strbuf_addstr(&envblk, *e);
 625                        strbuf_addch(&envblk, '\0');
 626                }
 627                free(sorted_env);
 628        }
 629
 630        memset(&pi, 0, sizeof(pi));
 631        ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
 632                env ? envblk.buf : NULL, NULL, &si, &pi);
 633
 634        if (env)
 635                strbuf_release(&envblk);
 636        strbuf_release(&args);
 637
 638        if (!ret) {
 639                errno = ENOENT;
 640                return -1;
 641        }
 642        CloseHandle(pi.hThread);
 643        return (pid_t)pi.hProcess;
 644}
 645
 646pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
 647{
 648        pid_t pid;
 649        char **path = get_path_split();
 650        char *prog = path_lookup(cmd, path, 0);
 651
 652        if (!prog) {
 653                errno = ENOENT;
 654                pid = -1;
 655        }
 656        else {
 657                const char *interpr = parse_interpreter(prog);
 658
 659                if (interpr) {
 660                        const char *argv0 = argv[0];
 661                        char *iprog = path_lookup(interpr, path, 1);
 662                        argv[0] = prog;
 663                        if (!iprog) {
 664                                errno = ENOENT;
 665                                pid = -1;
 666                        }
 667                        else {
 668                                pid = mingw_spawnve(iprog, argv, env, 1);
 669                                free(iprog);
 670                        }
 671                        argv[0] = argv0;
 672                }
 673                else
 674                        pid = mingw_spawnve(prog, argv, env, 0);
 675                free(prog);
 676        }
 677        free_path_split(path);
 678        return pid;
 679}
 680
 681static int try_shell_exec(const char *cmd, char *const *argv, char **env)
 682{
 683        const char *interpr = parse_interpreter(cmd);
 684        char **path;
 685        char *prog;
 686        int pid = 0;
 687
 688        if (!interpr)
 689                return 0;
 690        path = get_path_split();
 691        prog = path_lookup(interpr, path, 1);
 692        if (prog) {
 693                int argc = 0;
 694                const char **argv2;
 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);
 700                if (pid >= 0) {
 701                        int status;
 702                        if (waitpid(pid, &status, 0) < 0)
 703                                status = 255;
 704                        exit(status);
 705                }
 706                pid = 1;        /* indicate that we tried but failed */
 707                free(prog);
 708                free(argv2);
 709        }
 710        free_path_split(path);
 711        return pid;
 712}
 713
 714static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
 715{
 716        /* check if git_command is a shell script */
 717        if (!try_shell_exec(cmd, argv, (char **)env)) {
 718                int pid, status;
 719
 720                pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
 721                if (pid < 0)
 722                        return;
 723                if (waitpid(pid, &status, 0) < 0)
 724                        status = 255;
 725                exit(status);
 726        }
 727}
 728
 729void mingw_execvp(const char *cmd, char *const *argv)
 730{
 731        char **path = get_path_split();
 732        char *prog = path_lookup(cmd, path, 0);
 733
 734        if (prog) {
 735                mingw_execve(prog, argv, environ);
 736                free(prog);
 737        } else
 738                errno = ENOENT;
 739
 740        free_path_split(path);
 741}
 742
 743char **copy_environ()
 744{
 745        char **env;
 746        int i = 0;
 747        while (environ[i])
 748                i++;
 749        env = xmalloc((i+1)*sizeof(*env));
 750        for (i = 0; environ[i]; i++)
 751                env[i] = xstrdup(environ[i]);
 752        env[i] = NULL;
 753        return env;
 754}
 755
 756void free_environ(char **env)
 757{
 758        int i;
 759        for (i = 0; env[i]; i++)
 760                free(env[i]);
 761        free(env);
 762}
 763
 764static int lookup_env(char **env, const char *name, size_t nmln)
 765{
 766        int i;
 767
 768        for (i = 0; env[i]; i++) {
 769                if (0 == strncmp(env[i], name, nmln)
 770                    && '=' == env[i][nmln])
 771                        /* matches */
 772                        return i;
 773        }
 774        return -1;
 775}
 776
 777/*
 778 * If name contains '=', then sets the variable, otherwise it unsets it
 779 */
 780char **env_setenv(char **env, const char *name)
 781{
 782        char *eq = strchrnul(name, '=');
 783        int i = lookup_env(env, name, eq-name);
 784
 785        if (i < 0) {
 786                if (*eq) {
 787                        for (i = 0; env[i]; i++)
 788                                ;
 789                        env = xrealloc(env, (i+2)*sizeof(*env));
 790                        env[i] = xstrdup(name);
 791                        env[i+1] = NULL;
 792                }
 793        }
 794        else {
 795                free(env[i]);
 796                if (*eq)
 797                        env[i] = xstrdup(name);
 798                else
 799                        for (; env[i]; i++)
 800                                env[i] = env[i+1];
 801        }
 802        return env;
 803}
 804
 805/* this is the first function to call into WS_32; initialize it */
 806#undef gethostbyname
 807struct hostent *mingw_gethostbyname(const char *host)
 808{
 809        WSADATA wsa;
 810
 811        if (WSAStartup(MAKEWORD(2,2), &wsa))
 812                die("unable to initialize winsock subsystem, error %d",
 813                        WSAGetLastError());
 814        atexit((void(*)(void)) WSACleanup);
 815        return gethostbyname(host);
 816}
 817
 818int mingw_socket(int domain, int type, int protocol)
 819{
 820        int sockfd;
 821        SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
 822        if (s == INVALID_SOCKET) {
 823                /*
 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.
 831                 */
 832                errno = WSAGetLastError();
 833                return -1;
 834        }
 835        /* convert into a file descriptor */
 836        if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
 837                closesocket(s);
 838                return error("unable to make a socket file descriptor: %s",
 839                        strerror(errno));
 840        }
 841        return sockfd;
 842}
 843
 844#undef connect
 845int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
 846{
 847        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
 848        return connect(s, sa, sz);
 849}
 850
 851#undef rename
 852int mingw_rename(const char *pold, const char *pnew)
 853{
 854        /*
 855         * Try native rename() first to get errno right.
 856         * It is based on MoveFile(), which cannot overwrite existing files.
 857         */
 858        if (!rename(pold, pnew))
 859                return 0;
 860        if (errno != EEXIST)
 861                return -1;
 862        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
 863                return 0;
 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)) {
 868                        errno = EISDIR;
 869                        return -1;
 870                }
 871        }
 872        errno = EACCES;
 873        return -1;
 874}
 875
 876struct passwd *getpwuid(int uid)
 877{
 878        static char user_name[100];
 879        static struct passwd p;
 880
 881        DWORD len = sizeof(user_name);
 882        if (!GetUserName(user_name, &len))
 883                return NULL;
 884        p.pw_name = user_name;
 885        p.pw_gecos = "unknown";
 886        p.pw_dir = NULL;
 887        return &p;
 888}
 889
 890static HANDLE timer_event;
 891static HANDLE timer_thread;
 892static int timer_interval;
 893static int one_shot;
 894static sig_handler_t timer_fn = SIG_DFL;
 895
 896/* The timer works like this:
 897 * The thread, ticktack(), is a trivial routine that most of the time
 898 * only waits to receive the signal to terminate. The main thread tells
 899 * the thread to terminate by setting the timer_event to the signalled
 900 * state.
 901 * But ticktack() interrupts the wait state after the timer's interval
 902 * length to call the signal handler.
 903 */
 904
 905static __stdcall unsigned ticktack(void *dummy)
 906{
 907        while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
 908                if (timer_fn == SIG_DFL)
 909                        die("Alarm");
 910                if (timer_fn != SIG_IGN)
 911                        timer_fn(SIGALRM);
 912                if (one_shot)
 913                        break;
 914        }
 915        return 0;
 916}
 917
 918static int start_timer_thread(void)
 919{
 920        timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
 921        if (timer_event) {
 922                timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
 923                if (!timer_thread )
 924                        return errno = ENOMEM,
 925                                error("cannot start timer thread");
 926        } else
 927                return errno = ENOMEM,
 928                        error("cannot allocate resources for timer");
 929        return 0;
 930}
 931
 932static void stop_timer_thread(void)
 933{
 934        if (timer_event)
 935                SetEvent(timer_event);  /* tell thread to terminate */
 936        if (timer_thread) {
 937                int rc = WaitForSingleObject(timer_thread, 1000);
 938                if (rc == WAIT_TIMEOUT)
 939                        error("timer thread did not terminate timely");
 940                else if (rc != WAIT_OBJECT_0)
 941                        error("waiting for timer thread failed: %lu",
 942                              GetLastError());
 943                CloseHandle(timer_thread);
 944        }
 945        if (timer_event)
 946                CloseHandle(timer_event);
 947        timer_event = NULL;
 948        timer_thread = NULL;
 949}
 950
 951static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
 952{
 953        return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
 954}
 955
 956int setitimer(int type, struct itimerval *in, struct itimerval *out)
 957{
 958        static const struct timeval zero;
 959        static int atexit_done;
 960
 961        if (out != NULL)
 962                return errno = EINVAL,
 963                        error("setitimer param 3 != NULL not implemented");
 964        if (!is_timeval_eq(&in->it_interval, &zero) &&
 965            !is_timeval_eq(&in->it_interval, &in->it_value))
 966                return errno = EINVAL,
 967                        error("setitimer: it_interval must be zero or eq it_value");
 968
 969        if (timer_thread)
 970                stop_timer_thread();
 971
 972        if (is_timeval_eq(&in->it_value, &zero) &&
 973            is_timeval_eq(&in->it_interval, &zero))
 974                return 0;
 975
 976        timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
 977        one_shot = is_timeval_eq(&in->it_interval, &zero);
 978        if (!atexit_done) {
 979                atexit(stop_timer_thread);
 980                atexit_done = 1;
 981        }
 982        return start_timer_thread();
 983}
 984
 985int sigaction(int sig, struct sigaction *in, struct sigaction *out)
 986{
 987        if (sig != SIGALRM)
 988                return errno = EINVAL,
 989                        error("sigaction only implemented for SIGALRM");
 990        if (out != NULL)
 991                return errno = EINVAL,
 992                        error("sigaction: param 3 != NULL not implemented");
 993
 994        timer_fn = in->sa_handler;
 995        return 0;
 996}
 997
 998#undef signal
 999sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1000{
1001        if (sig != SIGALRM)
1002                return signal(sig, handler);
1003        sig_handler_t old = timer_fn;
1004        timer_fn = handler;
1005        return old;
1006}