a7e1c6b47148c042dd1eda87a6aa2b58c38a34e2
   1#include "../git-compat-util.h"
   2#include "win32.h"
   3#include <conio.h>
   4#include "../strbuf.h"
   5
   6int err_win_to_posix(DWORD winerr)
   7{
   8        int error = ENOSYS;
   9        switch(winerr) {
  10        case ERROR_ACCESS_DENIED: error = EACCES; break;
  11        case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
  12        case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
  13        case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
  14        case ERROR_ALREADY_EXISTS: error = EEXIST; break;
  15        case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
  16        case ERROR_BAD_COMMAND: error = EIO; break;
  17        case ERROR_BAD_DEVICE: error = ENODEV; break;
  18        case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
  19        case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
  20        case ERROR_BAD_FORMAT: error = ENOEXEC; break;
  21        case ERROR_BAD_LENGTH: error = EINVAL; break;
  22        case ERROR_BAD_PATHNAME: error = ENOENT; break;
  23        case ERROR_BAD_PIPE: error = EPIPE; break;
  24        case ERROR_BAD_UNIT: error = ENODEV; break;
  25        case ERROR_BAD_USERNAME: error = EINVAL; break;
  26        case ERROR_BROKEN_PIPE: error = EPIPE; break;
  27        case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
  28        case ERROR_BUSY: error = EBUSY; break;
  29        case ERROR_BUSY_DRIVE: error = EBUSY; break;
  30        case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
  31        case ERROR_CANNOT_MAKE: error = EACCES; break;
  32        case ERROR_CANTOPEN: error = EIO; break;
  33        case ERROR_CANTREAD: error = EIO; break;
  34        case ERROR_CANTWRITE: error = EIO; break;
  35        case ERROR_CRC: error = EIO; break;
  36        case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
  37        case ERROR_DEVICE_IN_USE: error = EBUSY; break;
  38        case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
  39        case ERROR_DIRECTORY: error = EINVAL; break;
  40        case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
  41        case ERROR_DISK_CHANGE: error = EIO; break;
  42        case ERROR_DISK_FULL: error = ENOSPC; break;
  43        case ERROR_DRIVE_LOCKED: error = EBUSY; break;
  44        case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
  45        case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
  46        case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
  47        case ERROR_FILE_EXISTS: error = EEXIST; break;
  48        case ERROR_FILE_INVALID: error = ENODEV; break;
  49        case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
  50        case ERROR_GEN_FAILURE: error = EIO; break;
  51        case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
  52        case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
  53        case ERROR_INVALID_ACCESS: error = EACCES; break;
  54        case ERROR_INVALID_ADDRESS: error = EFAULT; break;
  55        case ERROR_INVALID_BLOCK: error = EFAULT; break;
  56        case ERROR_INVALID_DATA: error = EINVAL; break;
  57        case ERROR_INVALID_DRIVE: error = ENODEV; break;
  58        case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
  59        case ERROR_INVALID_FLAGS: error = EINVAL; break;
  60        case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
  61        case ERROR_INVALID_HANDLE: error = EBADF; break;
  62        case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
  63        case ERROR_INVALID_NAME: error = EINVAL; break;
  64        case ERROR_INVALID_OWNER: error = EINVAL; break;
  65        case ERROR_INVALID_PARAMETER: error = EINVAL; break;
  66        case ERROR_INVALID_PASSWORD: error = EPERM; break;
  67        case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
  68        case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
  69        case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
  70        case ERROR_INVALID_WORKSTATION: error = EACCES; break;
  71        case ERROR_IO_DEVICE: error = EIO; break;
  72        case ERROR_IO_INCOMPLETE: error = EINTR; break;
  73        case ERROR_LOCKED: error = EBUSY; break;
  74        case ERROR_LOCK_VIOLATION: error = EACCES; break;
  75        case ERROR_LOGON_FAILURE: error = EACCES; break;
  76        case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
  77        case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
  78        case ERROR_MORE_DATA: error = EPIPE; break;
  79        case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
  80        case ERROR_NOACCESS: error = EFAULT; break;
  81        case ERROR_NONE_MAPPED: error = EINVAL; break;
  82        case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
  83        case ERROR_NOT_READY: error = EAGAIN; break;
  84        case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
  85        case ERROR_NO_DATA: error = EPIPE; break;
  86        case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
  87        case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
  88        case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
  89        case ERROR_OPEN_FAILED: error = EIO; break;
  90        case ERROR_OPEN_FILES: error = EBUSY; break;
  91        case ERROR_OPERATION_ABORTED: error = EINTR; break;
  92        case ERROR_OUTOFMEMORY: error = ENOMEM; break;
  93        case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
  94        case ERROR_PATH_BUSY: error = EBUSY; break;
  95        case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
  96        case ERROR_PIPE_BUSY: error = EBUSY; break;
  97        case ERROR_PIPE_CONNECTED: error = EPIPE; break;
  98        case ERROR_PIPE_LISTENING: error = EPIPE; break;
  99        case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
 100        case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
 101        case ERROR_READ_FAULT: error = EIO; break;
 102        case ERROR_SEEK: error = EIO; break;
 103        case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
 104        case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
 105        case ERROR_SHARING_VIOLATION: error = EACCES; break;
 106        case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
 107        case ERROR_SWAPERROR: error = ENOENT; break;
 108        case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
 109        case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
 110        case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
 111        case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
 112        case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
 113        case ERROR_WRITE_FAULT: error = EIO; break;
 114        case ERROR_WRITE_PROTECT: error = EROFS; break;
 115        }
 116        return error;
 117}
 118
 119#undef unlink
 120int mingw_unlink(const char *pathname)
 121{
 122        /* read-only files cannot be removed */
 123        chmod(pathname, 0666);
 124        return unlink(pathname);
 125}
 126
 127#undef open
 128int mingw_open (const char *filename, int oflags, ...)
 129{
 130        va_list args;
 131        unsigned mode;
 132        int fd;
 133
 134        va_start(args, oflags);
 135        mode = va_arg(args, int);
 136        va_end(args);
 137
 138        if (filename && !strcmp(filename, "/dev/null"))
 139                filename = "nul";
 140
 141        fd = open(filename, oflags, mode);
 142
 143        if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
 144                DWORD attrs = GetFileAttributes(filename);
 145                if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
 146                        errno = EISDIR;
 147        }
 148        return fd;
 149}
 150
 151#undef write
 152ssize_t mingw_write(int fd, const void *buf, size_t count)
 153{
 154        /*
 155         * While write() calls to a file on a local disk are translated
 156         * into WriteFile() calls with a maximum size of 64KB on Windows
 157         * XP and 256KB on Vista, no such cap is placed on writes to
 158         * files over the network on Windows XP.  Unfortunately, there
 159         * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
 160         * bigger writes fail on Windows XP.
 161         * So we cap to a nice 31MB here to avoid write failures over
 162         * the net without changing the number of WriteFile() calls in
 163         * the local case.
 164         */
 165        return write(fd, buf, min(count, 31 * 1024 * 1024));
 166}
 167
 168#undef fopen
 169FILE *mingw_fopen (const char *filename, const char *otype)
 170{
 171        if (filename && !strcmp(filename, "/dev/null"))
 172                filename = "nul";
 173        return fopen(filename, otype);
 174}
 175
 176#undef freopen
 177FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
 178{
 179        if (filename && !strcmp(filename, "/dev/null"))
 180                filename = "nul";
 181        return freopen(filename, otype, stream);
 182}
 183
 184/*
 185 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
 186 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
 187 */
 188static inline long long filetime_to_hnsec(const FILETIME *ft)
 189{
 190        long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
 191        /* Windows to Unix Epoch conversion */
 192        return winTime - 116444736000000000LL;
 193}
 194
 195static inline time_t filetime_to_time_t(const FILETIME *ft)
 196{
 197        return (time_t)(filetime_to_hnsec(ft) / 10000000);
 198}
 199
 200/* We keep the do_lstat code in a separate function to avoid recursion.
 201 * When a path ends with a slash, the stat will fail with ENOENT. In
 202 * this case, we strip the trailing slashes and stat again.
 203 *
 204 * If follow is true then act like stat() and report on the link
 205 * target. Otherwise report on the link itself.
 206 */
 207static int do_lstat(int follow, const char *file_name, struct stat *buf)
 208{
 209        int err;
 210        WIN32_FILE_ATTRIBUTE_DATA fdata;
 211
 212        if (!(err = get_file_attr(file_name, &fdata))) {
 213                buf->st_ino = 0;
 214                buf->st_gid = 0;
 215                buf->st_uid = 0;
 216                buf->st_nlink = 1;
 217                buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
 218                buf->st_size = fdata.nFileSizeLow |
 219                        (((off_t)fdata.nFileSizeHigh)<<32);
 220                buf->st_dev = buf->st_rdev = 0; /* not used by Git */
 221                buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
 222                buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
 223                buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
 224                if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
 225                        WIN32_FIND_DATAA findbuf;
 226                        HANDLE handle = FindFirstFileA(file_name, &findbuf);
 227                        if (handle != INVALID_HANDLE_VALUE) {
 228                                if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
 229                                                (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
 230                                        if (follow) {
 231                                                char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
 232                                                buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
 233                                        } else {
 234                                                buf->st_mode = S_IFLNK;
 235                                        }
 236                                        buf->st_mode |= S_IREAD;
 237                                        if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
 238                                                buf->st_mode |= S_IWRITE;
 239                                }
 240                                FindClose(handle);
 241                        }
 242                }
 243                return 0;
 244        }
 245        errno = err;
 246        return -1;
 247}
 248
 249/* We provide our own lstat/fstat functions, since the provided
 250 * lstat/fstat functions are so slow. These stat functions are
 251 * tailored for Git's usage (read: fast), and are not meant to be
 252 * complete. Note that Git stat()s are redirected to mingw_lstat()
 253 * too, since Windows doesn't really handle symlinks that well.
 254 */
 255static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
 256{
 257        int namelen;
 258        static char alt_name[PATH_MAX];
 259
 260        if (!do_lstat(follow, file_name, buf))
 261                return 0;
 262
 263        /* if file_name ended in a '/', Windows returned ENOENT;
 264         * try again without trailing slashes
 265         */
 266        if (errno != ENOENT)
 267                return -1;
 268
 269        namelen = strlen(file_name);
 270        if (namelen && file_name[namelen-1] != '/')
 271                return -1;
 272        while (namelen && file_name[namelen-1] == '/')
 273                --namelen;
 274        if (!namelen || namelen >= PATH_MAX)
 275                return -1;
 276
 277        memcpy(alt_name, file_name, namelen);
 278        alt_name[namelen] = 0;
 279        return do_lstat(follow, alt_name, buf);
 280}
 281
 282int mingw_lstat(const char *file_name, struct stat *buf)
 283{
 284        return do_stat_internal(0, file_name, buf);
 285}
 286int mingw_stat(const char *file_name, struct stat *buf)
 287{
 288        return do_stat_internal(1, file_name, buf);
 289}
 290
 291#undef fstat
 292int mingw_fstat(int fd, struct stat *buf)
 293{
 294        HANDLE fh = (HANDLE)_get_osfhandle(fd);
 295        BY_HANDLE_FILE_INFORMATION fdata;
 296
 297        if (fh == INVALID_HANDLE_VALUE) {
 298                errno = EBADF;
 299                return -1;
 300        }
 301        /* direct non-file handles to MS's fstat() */
 302        if (GetFileType(fh) != FILE_TYPE_DISK)
 303                return _fstati64(fd, buf);
 304
 305        if (GetFileInformationByHandle(fh, &fdata)) {
 306                buf->st_ino = 0;
 307                buf->st_gid = 0;
 308                buf->st_uid = 0;
 309                buf->st_nlink = 1;
 310                buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
 311                buf->st_size = fdata.nFileSizeLow |
 312                        (((off_t)fdata.nFileSizeHigh)<<32);
 313                buf->st_dev = buf->st_rdev = 0; /* not used by Git */
 314                buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
 315                buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
 316                buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
 317                return 0;
 318        }
 319        errno = EBADF;
 320        return -1;
 321}
 322
 323static inline void time_t_to_filetime(time_t t, FILETIME *ft)
 324{
 325        long long winTime = t * 10000000LL + 116444736000000000LL;
 326        ft->dwLowDateTime = winTime;
 327        ft->dwHighDateTime = winTime >> 32;
 328}
 329
 330int mingw_utime (const char *file_name, const struct utimbuf *times)
 331{
 332        FILETIME mft, aft;
 333        int fh, rc;
 334
 335        /* must have write permission */
 336        DWORD attrs = GetFileAttributes(file_name);
 337        if (attrs != INVALID_FILE_ATTRIBUTES &&
 338            (attrs & FILE_ATTRIBUTE_READONLY)) {
 339                /* ignore errors here; open() will report them */
 340                SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
 341        }
 342
 343        if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
 344                rc = -1;
 345                goto revert_attrs;
 346        }
 347
 348        if (times) {
 349                time_t_to_filetime(times->modtime, &mft);
 350                time_t_to_filetime(times->actime, &aft);
 351        } else {
 352                GetSystemTimeAsFileTime(&mft);
 353                aft = mft;
 354        }
 355        if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
 356                errno = EINVAL;
 357                rc = -1;
 358        } else
 359                rc = 0;
 360        close(fh);
 361
 362revert_attrs:
 363        if (attrs != INVALID_FILE_ATTRIBUTES &&
 364            (attrs & FILE_ATTRIBUTE_READONLY)) {
 365                /* ignore errors again */
 366                SetFileAttributes(file_name, attrs);
 367        }
 368        return rc;
 369}
 370
 371unsigned int sleep (unsigned int seconds)
 372{
 373        Sleep(seconds*1000);
 374        return 0;
 375}
 376
 377int mkstemp(char *template)
 378{
 379        char *filename = mktemp(template);
 380        if (filename == NULL)
 381                return -1;
 382        return open(filename, O_RDWR | O_CREAT, 0600);
 383}
 384
 385int gettimeofday(struct timeval *tv, void *tz)
 386{
 387        FILETIME ft;
 388        long long hnsec;
 389
 390        GetSystemTimeAsFileTime(&ft);
 391        hnsec = filetime_to_hnsec(&ft);
 392        tv->tv_sec = hnsec / 10000000;
 393        tv->tv_usec = (hnsec % 10000000) / 10;
 394        return 0;
 395}
 396
 397int pipe(int filedes[2])
 398{
 399        HANDLE h[2];
 400
 401        /* this creates non-inheritable handles */
 402        if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
 403                errno = err_win_to_posix(GetLastError());
 404                return -1;
 405        }
 406        filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
 407        if (filedes[0] < 0) {
 408                CloseHandle(h[0]);
 409                CloseHandle(h[1]);
 410                return -1;
 411        }
 412        filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
 413        if (filedes[0] < 0) {
 414                close(filedes[0]);
 415                CloseHandle(h[1]);
 416                return -1;
 417        }
 418        return 0;
 419}
 420
 421struct tm *gmtime_r(const time_t *timep, struct tm *result)
 422{
 423        /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 424        memcpy(result, gmtime(timep), sizeof(struct tm));
 425        return result;
 426}
 427
 428struct tm *localtime_r(const time_t *timep, struct tm *result)
 429{
 430        /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 431        memcpy(result, localtime(timep), sizeof(struct tm));
 432        return result;
 433}
 434
 435#undef getcwd
 436char *mingw_getcwd(char *pointer, int len)
 437{
 438        int i;
 439        char *ret = getcwd(pointer, len);
 440        if (!ret)
 441                return ret;
 442        for (i = 0; pointer[i]; i++)
 443                if (pointer[i] == '\\')
 444                        pointer[i] = '/';
 445        return ret;
 446}
 447
 448#undef getenv
 449char *mingw_getenv(const char *name)
 450{
 451        char *result = getenv(name);
 452        if (!result && !strcmp(name, "TMPDIR")) {
 453                /* on Windows it is TMP and TEMP */
 454                result = getenv("TMP");
 455                if (!result)
 456                        result = getenv("TEMP");
 457        }
 458        return result;
 459}
 460
 461/*
 462 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
 463 * (Parsing C++ Command-Line Arguments)
 464 */
 465static const char *quote_arg(const char *arg)
 466{
 467        /* count chars to quote */
 468        int len = 0, n = 0;
 469        int force_quotes = 0;
 470        char *q, *d;
 471        const char *p = arg;
 472        if (!*p) force_quotes = 1;
 473        while (*p) {
 474                if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
 475                        force_quotes = 1;
 476                else if (*p == '"')
 477                        n++;
 478                else if (*p == '\\') {
 479                        int count = 0;
 480                        while (*p == '\\') {
 481                                count++;
 482                                p++;
 483                                len++;
 484                        }
 485                        if (*p == '"')
 486                                n += count*2 + 1;
 487                        continue;
 488                }
 489                len++;
 490                p++;
 491        }
 492        if (!force_quotes && n == 0)
 493                return arg;
 494
 495        /* insert \ where necessary */
 496        d = q = xmalloc(len+n+3);
 497        *d++ = '"';
 498        while (*arg) {
 499                if (*arg == '"')
 500                        *d++ = '\\';
 501                else if (*arg == '\\') {
 502                        int count = 0;
 503                        while (*arg == '\\') {
 504                                count++;
 505                                *d++ = *arg++;
 506                        }
 507                        if (*arg == '"') {
 508                                while (count-- > 0)
 509                                        *d++ = '\\';
 510                                *d++ = '\\';
 511                        }
 512                }
 513                *d++ = *arg++;
 514        }
 515        *d++ = '"';
 516        *d++ = 0;
 517        return q;
 518}
 519
 520static const char *parse_interpreter(const char *cmd)
 521{
 522        static char buf[100];
 523        char *p, *opt;
 524        int n, fd;
 525
 526        /* don't even try a .exe */
 527        n = strlen(cmd);
 528        if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
 529                return NULL;
 530
 531        fd = open(cmd, O_RDONLY);
 532        if (fd < 0)
 533                return NULL;
 534        n = read(fd, buf, sizeof(buf)-1);
 535        close(fd);
 536        if (n < 4)      /* at least '#!/x' and not error */
 537                return NULL;
 538
 539        if (buf[0] != '#' || buf[1] != '!')
 540                return NULL;
 541        buf[n] = '\0';
 542        p = buf + strcspn(buf, "\r\n");
 543        if (!*p)
 544                return NULL;
 545
 546        *p = '\0';
 547        if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
 548                return NULL;
 549        /* strip options */
 550        if ((opt = strchr(p+1, ' ')))
 551                *opt = '\0';
 552        return p+1;
 553}
 554
 555/*
 556 * Splits the PATH into parts.
 557 */
 558static char **get_path_split(void)
 559{
 560        char *p, **path, *envpath = getenv("PATH");
 561        int i, n = 0;
 562
 563        if (!envpath || !*envpath)
 564                return NULL;
 565
 566        envpath = xstrdup(envpath);
 567        p = envpath;
 568        while (p) {
 569                char *dir = p;
 570                p = strchr(p, ';');
 571                if (p) *p++ = '\0';
 572                if (*dir) {     /* not earlier, catches series of ; */
 573                        ++n;
 574                }
 575        }
 576        if (!n)
 577                return NULL;
 578
 579        path = xmalloc((n+1)*sizeof(char *));
 580        p = envpath;
 581        i = 0;
 582        do {
 583                if (*p)
 584                        path[i++] = xstrdup(p);
 585                p = p+strlen(p)+1;
 586        } while (i < n);
 587        path[i] = NULL;
 588
 589        free(envpath);
 590
 591        return path;
 592}
 593
 594static void free_path_split(char **path)
 595{
 596        char **p = path;
 597
 598        if (!path)
 599                return;
 600
 601        while (*p)
 602                free(*p++);
 603        free(path);
 604}
 605
 606/*
 607 * exe_only means that we only want to detect .exe files, but not scripts
 608 * (which do not have an extension)
 609 */
 610static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
 611{
 612        char path[MAX_PATH];
 613        snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
 614
 615        if (!isexe && access(path, F_OK) == 0)
 616                return xstrdup(path);
 617        path[strlen(path)-4] = '\0';
 618        if ((!exe_only || isexe) && access(path, F_OK) == 0)
 619                if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
 620                        return xstrdup(path);
 621        return NULL;
 622}
 623
 624/*
 625 * Determines the absolute path of cmd using the split path in path.
 626 * If cmd contains a slash or backslash, no lookup is performed.
 627 */
 628static char *path_lookup(const char *cmd, char **path, int exe_only)
 629{
 630        char *prog = NULL;
 631        int len = strlen(cmd);
 632        int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
 633
 634        if (strchr(cmd, '/') || strchr(cmd, '\\'))
 635                prog = xstrdup(cmd);
 636
 637        while (!prog && *path)
 638                prog = lookup_prog(*path++, cmd, isexe, exe_only);
 639
 640        return prog;
 641}
 642
 643static int env_compare(const void *a, const void *b)
 644{
 645        char *const *ea = a;
 646        char *const *eb = b;
 647        return strcasecmp(*ea, *eb);
 648}
 649
 650struct pinfo_t {
 651        struct pinfo_t *next;
 652        pid_t pid;
 653        HANDLE proc;
 654} pinfo_t;
 655struct pinfo_t *pinfo = NULL;
 656CRITICAL_SECTION pinfo_cs;
 657
 658static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
 659                              const char *dir,
 660                              int prepend_cmd, int fhin, int fhout, int fherr)
 661{
 662        STARTUPINFO si;
 663        PROCESS_INFORMATION pi;
 664        struct strbuf envblk, args;
 665        unsigned flags;
 666        BOOL ret;
 667
 668        /* Determine whether or not we are associated to a console */
 669        HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
 670                        FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
 671                        FILE_ATTRIBUTE_NORMAL, NULL);
 672        if (cons == INVALID_HANDLE_VALUE) {
 673                /* There is no console associated with this process.
 674                 * Since the child is a console process, Windows
 675                 * would normally create a console window. But
 676                 * since we'll be redirecting std streams, we do
 677                 * not need the console.
 678                 * It is necessary to use DETACHED_PROCESS
 679                 * instead of CREATE_NO_WINDOW to make ssh
 680                 * recognize that it has no console.
 681                 */
 682                flags = DETACHED_PROCESS;
 683        } else {
 684                /* There is already a console. If we specified
 685                 * DETACHED_PROCESS here, too, Windows would
 686                 * disassociate the child from the console.
 687                 * The same is true for CREATE_NO_WINDOW.
 688                 * Go figure!
 689                 */
 690                flags = 0;
 691                CloseHandle(cons);
 692        }
 693        memset(&si, 0, sizeof(si));
 694        si.cb = sizeof(si);
 695        si.dwFlags = STARTF_USESTDHANDLES;
 696        si.hStdInput = (HANDLE) _get_osfhandle(fhin);
 697        si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
 698        si.hStdError = (HANDLE) _get_osfhandle(fherr);
 699
 700        /* concatenate argv, quoting args as we go */
 701        strbuf_init(&args, 0);
 702        if (prepend_cmd) {
 703                char *quoted = (char *)quote_arg(cmd);
 704                strbuf_addstr(&args, quoted);
 705                if (quoted != cmd)
 706                        free(quoted);
 707        }
 708        for (; *argv; argv++) {
 709                char *quoted = (char *)quote_arg(*argv);
 710                if (*args.buf)
 711                        strbuf_addch(&args, ' ');
 712                strbuf_addstr(&args, quoted);
 713                if (quoted != *argv)
 714                        free(quoted);
 715        }
 716
 717        if (env) {
 718                int count = 0;
 719                char **e, **sorted_env;
 720
 721                for (e = env; *e; e++)
 722                        count++;
 723
 724                /* environment must be sorted */
 725                sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
 726                memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
 727                qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
 728
 729                strbuf_init(&envblk, 0);
 730                for (e = sorted_env; *e; e++) {
 731                        strbuf_addstr(&envblk, *e);
 732                        strbuf_addch(&envblk, '\0');
 733                }
 734                free(sorted_env);
 735        }
 736
 737        memset(&pi, 0, sizeof(pi));
 738        ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
 739                env ? envblk.buf : NULL, dir, &si, &pi);
 740
 741        if (env)
 742                strbuf_release(&envblk);
 743        strbuf_release(&args);
 744
 745        if (!ret) {
 746                errno = ENOENT;
 747                return -1;
 748        }
 749        CloseHandle(pi.hThread);
 750
 751        /*
 752         * The process ID is the human-readable identifier of the process
 753         * that we want to present in log and error messages. The handle
 754         * is not useful for this purpose. But we cannot close it, either,
 755         * because it is not possible to turn a process ID into a process
 756         * handle after the process terminated.
 757         * Keep the handle in a list for waitpid.
 758         */
 759        EnterCriticalSection(&pinfo_cs);
 760        {
 761                struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
 762                info->pid = pi.dwProcessId;
 763                info->proc = pi.hProcess;
 764                info->next = pinfo;
 765                pinfo = info;
 766        }
 767        LeaveCriticalSection(&pinfo_cs);
 768
 769        return (pid_t)pi.dwProcessId;
 770}
 771
 772static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
 773                           int prepend_cmd)
 774{
 775        return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
 776}
 777
 778pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
 779                     const char *dir,
 780                     int fhin, int fhout, int fherr)
 781{
 782        pid_t pid;
 783        char **path = get_path_split();
 784        char *prog = path_lookup(cmd, path, 0);
 785
 786        if (!prog) {
 787                errno = ENOENT;
 788                pid = -1;
 789        }
 790        else {
 791                const char *interpr = parse_interpreter(prog);
 792
 793                if (interpr) {
 794                        const char *argv0 = argv[0];
 795                        char *iprog = path_lookup(interpr, path, 1);
 796                        argv[0] = prog;
 797                        if (!iprog) {
 798                                errno = ENOENT;
 799                                pid = -1;
 800                        }
 801                        else {
 802                                pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
 803                                                       fhin, fhout, fherr);
 804                                free(iprog);
 805                        }
 806                        argv[0] = argv0;
 807                }
 808                else
 809                        pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
 810                                               fhin, fhout, fherr);
 811                free(prog);
 812        }
 813        free_path_split(path);
 814        return pid;
 815}
 816
 817static int try_shell_exec(const char *cmd, char *const *argv, char **env)
 818{
 819        const char *interpr = parse_interpreter(cmd);
 820        char **path;
 821        char *prog;
 822        int pid = 0;
 823
 824        if (!interpr)
 825                return 0;
 826        path = get_path_split();
 827        prog = path_lookup(interpr, path, 1);
 828        if (prog) {
 829                int argc = 0;
 830                const char **argv2;
 831                while (argv[argc]) argc++;
 832                argv2 = xmalloc(sizeof(*argv) * (argc+1));
 833                argv2[0] = (char *)cmd; /* full path to the script file */
 834                memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
 835                pid = mingw_spawnve(prog, argv2, env, 1);
 836                if (pid >= 0) {
 837                        int status;
 838                        if (waitpid(pid, &status, 0) < 0)
 839                                status = 255;
 840                        exit(status);
 841                }
 842                pid = 1;        /* indicate that we tried but failed */
 843                free(prog);
 844                free(argv2);
 845        }
 846        free_path_split(path);
 847        return pid;
 848}
 849
 850static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
 851{
 852        /* check if git_command is a shell script */
 853        if (!try_shell_exec(cmd, argv, (char **)env)) {
 854                int pid, status;
 855
 856                pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
 857                if (pid < 0)
 858                        return;
 859                if (waitpid(pid, &status, 0) < 0)
 860                        status = 255;
 861                exit(status);
 862        }
 863}
 864
 865void mingw_execvp(const char *cmd, char *const *argv)
 866{
 867        char **path = get_path_split();
 868        char *prog = path_lookup(cmd, path, 0);
 869
 870        if (prog) {
 871                mingw_execve(prog, argv, environ);
 872                free(prog);
 873        } else
 874                errno = ENOENT;
 875
 876        free_path_split(path);
 877}
 878
 879void mingw_execv(const char *cmd, char *const *argv)
 880{
 881        mingw_execve(cmd, argv, environ);
 882}
 883
 884int mingw_kill(pid_t pid, int sig)
 885{
 886        if (pid > 0 && sig == SIGTERM) {
 887                HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
 888
 889                if (TerminateProcess(h, -1)) {
 890                        CloseHandle(h);
 891                        return 0;
 892                }
 893
 894                errno = err_win_to_posix(GetLastError());
 895                CloseHandle(h);
 896                return -1;
 897        }
 898
 899        errno = EINVAL;
 900        return -1;
 901}
 902
 903static char **copy_environ(void)
 904{
 905        char **env;
 906        int i = 0;
 907        while (environ[i])
 908                i++;
 909        env = xmalloc((i+1)*sizeof(*env));
 910        for (i = 0; environ[i]; i++)
 911                env[i] = xstrdup(environ[i]);
 912        env[i] = NULL;
 913        return env;
 914}
 915
 916void free_environ(char **env)
 917{
 918        int i;
 919        for (i = 0; env[i]; i++)
 920                free(env[i]);
 921        free(env);
 922}
 923
 924static int lookup_env(char **env, const char *name, size_t nmln)
 925{
 926        int i;
 927
 928        for (i = 0; env[i]; i++) {
 929                if (0 == strncmp(env[i], name, nmln)
 930                    && '=' == env[i][nmln])
 931                        /* matches */
 932                        return i;
 933        }
 934        return -1;
 935}
 936
 937/*
 938 * If name contains '=', then sets the variable, otherwise it unsets it
 939 */
 940static char **env_setenv(char **env, const char *name)
 941{
 942        char *eq = strchrnul(name, '=');
 943        int i = lookup_env(env, name, eq-name);
 944
 945        if (i < 0) {
 946                if (*eq) {
 947                        for (i = 0; env[i]; i++)
 948                                ;
 949                        env = xrealloc(env, (i+2)*sizeof(*env));
 950                        env[i] = xstrdup(name);
 951                        env[i+1] = NULL;
 952                }
 953        }
 954        else {
 955                free(env[i]);
 956                if (*eq)
 957                        env[i] = xstrdup(name);
 958                else
 959                        for (; env[i]; i++)
 960                                env[i] = env[i+1];
 961        }
 962        return env;
 963}
 964
 965/*
 966 * Copies global environ and adjusts variables as specified by vars.
 967 */
 968char **make_augmented_environ(const char *const *vars)
 969{
 970        char **env = copy_environ();
 971
 972        while (*vars)
 973                env = env_setenv(env, *vars++);
 974        return env;
 975}
 976
 977/*
 978 * Note, this isn't a complete replacement for getaddrinfo. It assumes
 979 * that service contains a numerical port, or that it it is null. It
 980 * does a simple search using gethostbyname, and returns one IPv4 host
 981 * if one was found.
 982 */
 983static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
 984                                   const struct addrinfo *hints,
 985                                   struct addrinfo **res)
 986{
 987        struct hostent *h = NULL;
 988        struct addrinfo *ai;
 989        struct sockaddr_in *sin;
 990
 991        if (node) {
 992                h = gethostbyname(node);
 993                if (!h)
 994                        return WSAGetLastError();
 995        }
 996
 997        ai = xmalloc(sizeof(struct addrinfo));
 998        *res = ai;
 999        ai->ai_flags = 0;
1000        ai->ai_family = AF_INET;
1001        ai->ai_socktype = hints ? hints->ai_socktype : 0;
1002        switch (ai->ai_socktype) {
1003        case SOCK_STREAM:
1004                ai->ai_protocol = IPPROTO_TCP;
1005                break;
1006        case SOCK_DGRAM:
1007                ai->ai_protocol = IPPROTO_UDP;
1008                break;
1009        default:
1010                ai->ai_protocol = 0;
1011                break;
1012        }
1013        ai->ai_addrlen = sizeof(struct sockaddr_in);
1014        if (hints && (hints->ai_flags & AI_CANONNAME))
1015                ai->ai_canonname = h ? strdup(h->h_name) : NULL;
1016        else
1017                ai->ai_canonname = NULL;
1018
1019        sin = xmalloc(ai->ai_addrlen);
1020        memset(sin, 0, ai->ai_addrlen);
1021        sin->sin_family = AF_INET;
1022        /* Note: getaddrinfo is supposed to allow service to be a string,
1023         * which should be looked up using getservbyname. This is
1024         * currently not implemented */
1025        if (service)
1026                sin->sin_port = htons(atoi(service));
1027        if (h)
1028                sin->sin_addr = *(struct in_addr *)h->h_addr;
1029        else if (hints && (hints->ai_flags & AI_PASSIVE))
1030                sin->sin_addr.s_addr = INADDR_ANY;
1031        else
1032                sin->sin_addr.s_addr = INADDR_LOOPBACK;
1033        ai->ai_addr = (struct sockaddr *)sin;
1034        ai->ai_next = 0;
1035        return 0;
1036}
1037
1038static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1039{
1040        free(res->ai_canonname);
1041        free(res->ai_addr);
1042        free(res);
1043}
1044
1045static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1046                                   char *host, DWORD hostlen,
1047                                   char *serv, DWORD servlen, int flags)
1048{
1049        const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1050        if (sa->sa_family != AF_INET)
1051                return EAI_FAMILY;
1052        if (!host && !serv)
1053                return EAI_NONAME;
1054
1055        if (host && hostlen > 0) {
1056                struct hostent *ent = NULL;
1057                if (!(flags & NI_NUMERICHOST))
1058                        ent = gethostbyaddr((const char *)&sin->sin_addr,
1059                                            sizeof(sin->sin_addr), AF_INET);
1060
1061                if (ent)
1062                        snprintf(host, hostlen, "%s", ent->h_name);
1063                else if (flags & NI_NAMEREQD)
1064                        return EAI_NONAME;
1065                else
1066                        snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1067        }
1068
1069        if (serv && servlen > 0) {
1070                struct servent *ent = NULL;
1071                if (!(flags & NI_NUMERICSERV))
1072                        ent = getservbyport(sin->sin_port,
1073                                            flags & NI_DGRAM ? "udp" : "tcp");
1074
1075                if (ent)
1076                        snprintf(serv, servlen, "%s", ent->s_name);
1077                else
1078                        snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1079        }
1080
1081        return 0;
1082}
1083
1084static HMODULE ipv6_dll = NULL;
1085static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1086static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1087                                      const struct addrinfo *hints,
1088                                      struct addrinfo **res);
1089static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1090                                      char *host, DWORD hostlen,
1091                                      char *serv, DWORD servlen, int flags);
1092/*
1093 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1094 * don't need to try to load that one dynamically.
1095 */
1096
1097static void socket_cleanup(void)
1098{
1099        WSACleanup();
1100        if (ipv6_dll)
1101                FreeLibrary(ipv6_dll);
1102        ipv6_dll = NULL;
1103        ipv6_freeaddrinfo = freeaddrinfo_stub;
1104        ipv6_getaddrinfo = getaddrinfo_stub;
1105        ipv6_getnameinfo = getnameinfo_stub;
1106}
1107
1108static void ensure_socket_initialization(void)
1109{
1110        WSADATA wsa;
1111        static int initialized = 0;
1112        const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1113        const char **name;
1114
1115        if (initialized)
1116                return;
1117
1118        if (WSAStartup(MAKEWORD(2,2), &wsa))
1119                die("unable to initialize winsock subsystem, error %d",
1120                        WSAGetLastError());
1121
1122        for (name = libraries; *name; name++) {
1123                ipv6_dll = LoadLibrary(*name);
1124                if (!ipv6_dll)
1125                        continue;
1126
1127                ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1128                        GetProcAddress(ipv6_dll, "freeaddrinfo");
1129                ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1130                                                   const struct addrinfo *,
1131                                                   struct addrinfo **))
1132                        GetProcAddress(ipv6_dll, "getaddrinfo");
1133                ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1134                                                   socklen_t, char *, DWORD,
1135                                                   char *, DWORD, int))
1136                        GetProcAddress(ipv6_dll, "getnameinfo");
1137                if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1138                        FreeLibrary(ipv6_dll);
1139                        ipv6_dll = NULL;
1140                } else
1141                        break;
1142        }
1143        if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1144                ipv6_freeaddrinfo = freeaddrinfo_stub;
1145                ipv6_getaddrinfo = getaddrinfo_stub;
1146                ipv6_getnameinfo = getnameinfo_stub;
1147        }
1148
1149        atexit(socket_cleanup);
1150        initialized = 1;
1151}
1152
1153#undef gethostbyname
1154struct hostent *mingw_gethostbyname(const char *host)
1155{
1156        ensure_socket_initialization();
1157        return gethostbyname(host);
1158}
1159
1160void mingw_freeaddrinfo(struct addrinfo *res)
1161{
1162        ipv6_freeaddrinfo(res);
1163}
1164
1165int mingw_getaddrinfo(const char *node, const char *service,
1166                      const struct addrinfo *hints, struct addrinfo **res)
1167{
1168        ensure_socket_initialization();
1169        return ipv6_getaddrinfo(node, service, hints, res);
1170}
1171
1172int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1173                      char *host, DWORD hostlen, char *serv, DWORD servlen,
1174                      int flags)
1175{
1176        ensure_socket_initialization();
1177        return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1178}
1179
1180int mingw_socket(int domain, int type, int protocol)
1181{
1182        int sockfd;
1183        SOCKET s;
1184
1185        ensure_socket_initialization();
1186        s = WSASocket(domain, type, protocol, NULL, 0, 0);
1187        if (s == INVALID_SOCKET) {
1188                /*
1189                 * WSAGetLastError() values are regular BSD error codes
1190                 * biased by WSABASEERR.
1191                 * However, strerror() does not know about networking
1192                 * specific errors, which are values beginning at 38 or so.
1193                 * Therefore, we choose to leave the biased error code
1194                 * in errno so that _if_ someone looks up the code somewhere,
1195                 * then it is at least the number that are usually listed.
1196                 */
1197                errno = WSAGetLastError();
1198                return -1;
1199        }
1200        /* convert into a file descriptor */
1201        if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1202                closesocket(s);
1203                return error("unable to make a socket file descriptor: %s",
1204                        strerror(errno));
1205        }
1206        return sockfd;
1207}
1208
1209#undef connect
1210int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1211{
1212        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1213        return connect(s, sa, sz);
1214}
1215
1216#undef bind
1217int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1218{
1219        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1220        return bind(s, sa, sz);
1221}
1222
1223#undef setsockopt
1224int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1225{
1226        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1227        return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1228}
1229
1230#undef listen
1231int mingw_listen(int sockfd, int backlog)
1232{
1233        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1234        return listen(s, backlog);
1235}
1236
1237#undef accept
1238int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1239{
1240        int sockfd2;
1241
1242        SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1243        SOCKET s2 = accept(s1, sa, sz);
1244
1245        /* convert into a file descriptor */
1246        if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1247                int err = errno;
1248                closesocket(s2);
1249                return error("unable to make a socket file descriptor: %s",
1250                        strerror(err));
1251        }
1252        return sockfd2;
1253}
1254
1255#undef rename
1256int mingw_rename(const char *pold, const char *pnew)
1257{
1258        DWORD attrs, gle;
1259        int tries = 0;
1260        static const int delay[] = { 0, 1, 10, 20, 40 };
1261
1262        /*
1263         * Try native rename() first to get errno right.
1264         * It is based on MoveFile(), which cannot overwrite existing files.
1265         */
1266        if (!rename(pold, pnew))
1267                return 0;
1268        if (errno != EEXIST)
1269                return -1;
1270repeat:
1271        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1272                return 0;
1273        /* TODO: translate more errors */
1274        gle = GetLastError();
1275        if (gle == ERROR_ACCESS_DENIED &&
1276            (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1277                if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1278                        errno = EISDIR;
1279                        return -1;
1280                }
1281                if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1282                    SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1283                        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1284                                return 0;
1285                        gle = GetLastError();
1286                        /* revert file attributes on failure */
1287                        SetFileAttributes(pnew, attrs);
1288                }
1289        }
1290        if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1291                /*
1292                 * We assume that some other process had the source or
1293                 * destination file open at the wrong moment and retry.
1294                 * In order to give the other process a higher chance to
1295                 * complete its operation, we give up our time slice now.
1296                 * If we have to retry again, we do sleep a bit.
1297                 */
1298                Sleep(delay[tries]);
1299                tries++;
1300                goto repeat;
1301        }
1302        errno = EACCES;
1303        return -1;
1304}
1305
1306/*
1307 * Note that this doesn't return the actual pagesize, but
1308 * the allocation granularity. If future Windows specific git code
1309 * needs the real getpagesize function, we need to find another solution.
1310 */
1311int mingw_getpagesize(void)
1312{
1313        SYSTEM_INFO si;
1314        GetSystemInfo(&si);
1315        return si.dwAllocationGranularity;
1316}
1317
1318struct passwd *getpwuid(int uid)
1319{
1320        static char user_name[100];
1321        static struct passwd p;
1322
1323        DWORD len = sizeof(user_name);
1324        if (!GetUserName(user_name, &len))
1325                return NULL;
1326        p.pw_name = user_name;
1327        p.pw_gecos = "unknown";
1328        p.pw_dir = NULL;
1329        return &p;
1330}
1331
1332static HANDLE timer_event;
1333static HANDLE timer_thread;
1334static int timer_interval;
1335static int one_shot;
1336static sig_handler_t timer_fn = SIG_DFL;
1337
1338/* The timer works like this:
1339 * The thread, ticktack(), is a trivial routine that most of the time
1340 * only waits to receive the signal to terminate. The main thread tells
1341 * the thread to terminate by setting the timer_event to the signalled
1342 * state.
1343 * But ticktack() interrupts the wait state after the timer's interval
1344 * length to call the signal handler.
1345 */
1346
1347static unsigned __stdcall ticktack(void *dummy)
1348{
1349        while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1350                if (timer_fn == SIG_DFL)
1351                        die("Alarm");
1352                if (timer_fn != SIG_IGN)
1353                        timer_fn(SIGALRM);
1354                if (one_shot)
1355                        break;
1356        }
1357        return 0;
1358}
1359
1360static int start_timer_thread(void)
1361{
1362        timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1363        if (timer_event) {
1364                timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1365                if (!timer_thread )
1366                        return errno = ENOMEM,
1367                                error("cannot start timer thread");
1368        } else
1369                return errno = ENOMEM,
1370                        error("cannot allocate resources for timer");
1371        return 0;
1372}
1373
1374static void stop_timer_thread(void)
1375{
1376        if (timer_event)
1377                SetEvent(timer_event);  /* tell thread to terminate */
1378        if (timer_thread) {
1379                int rc = WaitForSingleObject(timer_thread, 1000);
1380                if (rc == WAIT_TIMEOUT)
1381                        error("timer thread did not terminate timely");
1382                else if (rc != WAIT_OBJECT_0)
1383                        error("waiting for timer thread failed: %lu",
1384                              GetLastError());
1385                CloseHandle(timer_thread);
1386        }
1387        if (timer_event)
1388                CloseHandle(timer_event);
1389        timer_event = NULL;
1390        timer_thread = NULL;
1391}
1392
1393static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1394{
1395        return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1396}
1397
1398int setitimer(int type, struct itimerval *in, struct itimerval *out)
1399{
1400        static const struct timeval zero;
1401        static int atexit_done;
1402
1403        if (out != NULL)
1404                return errno = EINVAL,
1405                        error("setitimer param 3 != NULL not implemented");
1406        if (!is_timeval_eq(&in->it_interval, &zero) &&
1407            !is_timeval_eq(&in->it_interval, &in->it_value))
1408                return errno = EINVAL,
1409                        error("setitimer: it_interval must be zero or eq it_value");
1410
1411        if (timer_thread)
1412                stop_timer_thread();
1413
1414        if (is_timeval_eq(&in->it_value, &zero) &&
1415            is_timeval_eq(&in->it_interval, &zero))
1416                return 0;
1417
1418        timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1419        one_shot = is_timeval_eq(&in->it_interval, &zero);
1420        if (!atexit_done) {
1421                atexit(stop_timer_thread);
1422                atexit_done = 1;
1423        }
1424        return start_timer_thread();
1425}
1426
1427int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1428{
1429        if (sig != SIGALRM)
1430                return errno = EINVAL,
1431                        error("sigaction only implemented for SIGALRM");
1432        if (out != NULL)
1433                return errno = EINVAL,
1434                        error("sigaction: param 3 != NULL not implemented");
1435
1436        timer_fn = in->sa_handler;
1437        return 0;
1438}
1439
1440#undef signal
1441sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1442{
1443        sig_handler_t old = timer_fn;
1444        if (sig != SIGALRM)
1445                return signal(sig, handler);
1446        timer_fn = handler;
1447        return old;
1448}
1449
1450static const char *make_backslash_path(const char *path)
1451{
1452        static char buf[PATH_MAX + 1];
1453        char *c;
1454
1455        if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1456                die("Too long path: %.*s", 60, path);
1457
1458        for (c = buf; *c; c++) {
1459                if (*c == '/')
1460                        *c = '\\';
1461        }
1462        return buf;
1463}
1464
1465void mingw_open_html(const char *unixpath)
1466{
1467        const char *htmlpath = make_backslash_path(unixpath);
1468        typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1469                        const char *, const char *, const char *, INT);
1470        T ShellExecute;
1471        HMODULE shell32;
1472        int r;
1473
1474        shell32 = LoadLibrary("shell32.dll");
1475        if (!shell32)
1476                die("cannot load shell32.dll");
1477        ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1478        if (!ShellExecute)
1479                die("cannot run browser");
1480
1481        printf("Launching default browser to display HTML ...\n");
1482        r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1483        FreeLibrary(shell32);
1484        /* see the MSDN documentation referring to the result codes here */
1485        if (r <= 32) {
1486                die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1487        }
1488}
1489
1490int link(const char *oldpath, const char *newpath)
1491{
1492        typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1493        static T create_hard_link = NULL;
1494        if (!create_hard_link) {
1495                create_hard_link = (T) GetProcAddress(
1496                        GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1497                if (!create_hard_link)
1498                        create_hard_link = (T)-1;
1499        }
1500        if (create_hard_link == (T)-1) {
1501                errno = ENOSYS;
1502                return -1;
1503        }
1504        if (!create_hard_link(newpath, oldpath, NULL)) {
1505                errno = err_win_to_posix(GetLastError());
1506                return -1;
1507        }
1508        return 0;
1509}
1510
1511char *getpass(const char *prompt)
1512{
1513        struct strbuf buf = STRBUF_INIT;
1514
1515        fputs(prompt, stderr);
1516        for (;;) {
1517                char c = _getch();
1518                if (c == '\r' || c == '\n')
1519                        break;
1520                strbuf_addch(&buf, c);
1521        }
1522        fputs("\n", stderr);
1523        return strbuf_detach(&buf, NULL);
1524}
1525
1526pid_t waitpid(pid_t pid, int *status, unsigned options)
1527{
1528        HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
1529            FALSE, pid);
1530        if (!h) {
1531                errno = ECHILD;
1532                return -1;
1533        }
1534
1535        if (pid > 0 && options & WNOHANG) {
1536                if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
1537                        CloseHandle(h);
1538                        return 0;
1539                }
1540                options &= ~WNOHANG;
1541        }
1542
1543        if (options == 0) {
1544                struct pinfo_t **ppinfo;
1545                if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
1546                        CloseHandle(h);
1547                        return 0;
1548                }
1549
1550                if (status)
1551                        GetExitCodeProcess(h, (LPDWORD)status);
1552
1553                EnterCriticalSection(&pinfo_cs);
1554
1555                ppinfo = &pinfo;
1556                while (*ppinfo) {
1557                        struct pinfo_t *info = *ppinfo;
1558                        if (info->pid == pid) {
1559                                CloseHandle(info->proc);
1560                                *ppinfo = info->next;
1561                                free(info);
1562                                break;
1563                        }
1564                        ppinfo = &info->next;
1565                }
1566
1567                LeaveCriticalSection(&pinfo_cs);
1568
1569                CloseHandle(h);
1570                return pid;
1571        }
1572        CloseHandle(h);
1573
1574        errno = EINVAL;
1575        return -1;
1576}