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