compat / mingw.con commit mingw: unset PERL5LIB by default (0e218f9)
   1#include "../git-compat-util.h"
   2#include "win32.h"
   3#include <conio.h>
   4#include <wchar.h>
   5#include "../strbuf.h"
   6#include "../run-command.h"
   7#include "../cache.h"
   8#include "win32/lazyload.h"
   9#include "../config.h"
  10
  11#define HCAST(type, handle) ((type)(intptr_t)handle)
  12
  13static const int delay[] = { 0, 1, 10, 20, 40 };
  14
  15int err_win_to_posix(DWORD winerr)
  16{
  17        int error = ENOSYS;
  18        switch(winerr) {
  19        case ERROR_ACCESS_DENIED: error = EACCES; break;
  20        case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
  21        case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
  22        case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
  23        case ERROR_ALREADY_EXISTS: error = EEXIST; break;
  24        case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
  25        case ERROR_BAD_COMMAND: error = EIO; break;
  26        case ERROR_BAD_DEVICE: error = ENODEV; break;
  27        case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
  28        case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
  29        case ERROR_BAD_FORMAT: error = ENOEXEC; break;
  30        case ERROR_BAD_LENGTH: error = EINVAL; break;
  31        case ERROR_BAD_PATHNAME: error = ENOENT; break;
  32        case ERROR_BAD_PIPE: error = EPIPE; break;
  33        case ERROR_BAD_UNIT: error = ENODEV; break;
  34        case ERROR_BAD_USERNAME: error = EINVAL; break;
  35        case ERROR_BROKEN_PIPE: error = EPIPE; break;
  36        case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
  37        case ERROR_BUSY: error = EBUSY; break;
  38        case ERROR_BUSY_DRIVE: error = EBUSY; break;
  39        case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
  40        case ERROR_CANNOT_MAKE: error = EACCES; break;
  41        case ERROR_CANTOPEN: error = EIO; break;
  42        case ERROR_CANTREAD: error = EIO; break;
  43        case ERROR_CANTWRITE: error = EIO; break;
  44        case ERROR_CRC: error = EIO; break;
  45        case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
  46        case ERROR_DEVICE_IN_USE: error = EBUSY; break;
  47        case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
  48        case ERROR_DIRECTORY: error = EINVAL; break;
  49        case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
  50        case ERROR_DISK_CHANGE: error = EIO; break;
  51        case ERROR_DISK_FULL: error = ENOSPC; break;
  52        case ERROR_DRIVE_LOCKED: error = EBUSY; break;
  53        case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
  54        case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
  55        case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
  56        case ERROR_FILE_EXISTS: error = EEXIST; break;
  57        case ERROR_FILE_INVALID: error = ENODEV; break;
  58        case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
  59        case ERROR_GEN_FAILURE: error = EIO; break;
  60        case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
  61        case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
  62        case ERROR_INVALID_ACCESS: error = EACCES; break;
  63        case ERROR_INVALID_ADDRESS: error = EFAULT; break;
  64        case ERROR_INVALID_BLOCK: error = EFAULT; break;
  65        case ERROR_INVALID_DATA: error = EINVAL; break;
  66        case ERROR_INVALID_DRIVE: error = ENODEV; break;
  67        case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
  68        case ERROR_INVALID_FLAGS: error = EINVAL; break;
  69        case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
  70        case ERROR_INVALID_HANDLE: error = EBADF; break;
  71        case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
  72        case ERROR_INVALID_NAME: error = EINVAL; break;
  73        case ERROR_INVALID_OWNER: error = EINVAL; break;
  74        case ERROR_INVALID_PARAMETER: error = EINVAL; break;
  75        case ERROR_INVALID_PASSWORD: error = EPERM; break;
  76        case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
  77        case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
  78        case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
  79        case ERROR_INVALID_WORKSTATION: error = EACCES; break;
  80        case ERROR_IO_DEVICE: error = EIO; break;
  81        case ERROR_IO_INCOMPLETE: error = EINTR; break;
  82        case ERROR_LOCKED: error = EBUSY; break;
  83        case ERROR_LOCK_VIOLATION: error = EACCES; break;
  84        case ERROR_LOGON_FAILURE: error = EACCES; break;
  85        case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
  86        case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
  87        case ERROR_MORE_DATA: error = EPIPE; break;
  88        case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
  89        case ERROR_NOACCESS: error = EFAULT; break;
  90        case ERROR_NONE_MAPPED: error = EINVAL; break;
  91        case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
  92        case ERROR_NOT_READY: error = EAGAIN; break;
  93        case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
  94        case ERROR_NO_DATA: error = EPIPE; break;
  95        case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
  96        case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
  97        case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
  98        case ERROR_OPEN_FAILED: error = EIO; break;
  99        case ERROR_OPEN_FILES: error = EBUSY; break;
 100        case ERROR_OPERATION_ABORTED: error = EINTR; break;
 101        case ERROR_OUTOFMEMORY: error = ENOMEM; break;
 102        case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
 103        case ERROR_PATH_BUSY: error = EBUSY; break;
 104        case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
 105        case ERROR_PIPE_BUSY: error = EBUSY; break;
 106        case ERROR_PIPE_CONNECTED: error = EPIPE; break;
 107        case ERROR_PIPE_LISTENING: error = EPIPE; break;
 108        case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
 109        case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
 110        case ERROR_READ_FAULT: error = EIO; break;
 111        case ERROR_SEEK: error = EIO; break;
 112        case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
 113        case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
 114        case ERROR_SHARING_VIOLATION: error = EACCES; break;
 115        case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
 116        case ERROR_SWAPERROR: error = ENOENT; break;
 117        case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
 118        case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
 119        case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
 120        case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
 121        case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
 122        case ERROR_WRITE_FAULT: error = EIO; break;
 123        case ERROR_WRITE_PROTECT: error = EROFS; break;
 124        }
 125        return error;
 126}
 127
 128static inline int is_file_in_use_error(DWORD errcode)
 129{
 130        switch (errcode) {
 131        case ERROR_SHARING_VIOLATION:
 132        case ERROR_ACCESS_DENIED:
 133                return 1;
 134        }
 135
 136        return 0;
 137}
 138
 139static int read_yes_no_answer(void)
 140{
 141        char answer[1024];
 142
 143        if (fgets(answer, sizeof(answer), stdin)) {
 144                size_t answer_len = strlen(answer);
 145                int got_full_line = 0, c;
 146
 147                /* remove the newline */
 148                if (answer_len >= 2 && answer[answer_len-2] == '\r') {
 149                        answer[answer_len-2] = '\0';
 150                        got_full_line = 1;
 151                } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
 152                        answer[answer_len-1] = '\0';
 153                        got_full_line = 1;
 154                }
 155                /* flush the buffer in case we did not get the full line */
 156                if (!got_full_line)
 157                        while ((c = getchar()) != EOF && c != '\n')
 158                                ;
 159        } else
 160                /* we could not read, return the
 161                 * default answer which is no */
 162                return 0;
 163
 164        if (tolower(answer[0]) == 'y' && !answer[1])
 165                return 1;
 166        if (!strncasecmp(answer, "yes", sizeof(answer)))
 167                return 1;
 168        if (tolower(answer[0]) == 'n' && !answer[1])
 169                return 0;
 170        if (!strncasecmp(answer, "no", sizeof(answer)))
 171                return 0;
 172
 173        /* did not find an answer we understand */
 174        return -1;
 175}
 176
 177static int ask_yes_no_if_possible(const char *format, ...)
 178{
 179        char question[4096];
 180        const char *retry_hook[] = { NULL, NULL, NULL };
 181        va_list args;
 182
 183        va_start(args, format);
 184        vsnprintf(question, sizeof(question), format, args);
 185        va_end(args);
 186
 187        if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
 188                retry_hook[1] = question;
 189                return !run_command_v_opt(retry_hook, 0);
 190        }
 191
 192        if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
 193                return 0;
 194
 195        while (1) {
 196                int answer;
 197                fprintf(stderr, "%s (y/n) ", question);
 198
 199                if ((answer = read_yes_no_answer()) >= 0)
 200                        return answer;
 201
 202                fprintf(stderr, "Sorry, I did not understand your answer. "
 203                                "Please type 'y' or 'n'\n");
 204        }
 205}
 206
 207/* Windows only */
 208enum hide_dotfiles_type {
 209        HIDE_DOTFILES_FALSE = 0,
 210        HIDE_DOTFILES_TRUE,
 211        HIDE_DOTFILES_DOTGITONLY
 212};
 213
 214static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
 215static char *unset_environment_variables;
 216
 217int mingw_core_config(const char *var, const char *value, void *cb)
 218{
 219        if (!strcmp(var, "core.hidedotfiles")) {
 220                if (value && !strcasecmp(value, "dotgitonly"))
 221                        hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
 222                else
 223                        hide_dotfiles = git_config_bool(var, value);
 224                return 0;
 225        }
 226
 227        if (!strcmp(var, "core.unsetenvvars")) {
 228                free(unset_environment_variables);
 229                unset_environment_variables = xstrdup(value);
 230                return 0;
 231        }
 232
 233        return 0;
 234}
 235
 236/* Normalizes NT paths as returned by some low-level APIs. */
 237static wchar_t *normalize_ntpath(wchar_t *wbuf)
 238{
 239        int i;
 240        /* fix absolute path prefixes */
 241        if (wbuf[0] == '\\') {
 242                /* strip NT namespace prefixes */
 243                if (!wcsncmp(wbuf, L"\\??\\", 4) ||
 244                    !wcsncmp(wbuf, L"\\\\?\\", 4))
 245                        wbuf += 4;
 246                else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
 247                        wbuf += 12;
 248                /* replace remaining '...UNC\' with '\\' */
 249                if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
 250                        wbuf += 2;
 251                        *wbuf = '\\';
 252                }
 253        }
 254        /* convert backslashes to slashes */
 255        for (i = 0; wbuf[i]; i++)
 256                if (wbuf[i] == '\\')
 257                        wbuf[i] = '/';
 258        return wbuf;
 259}
 260
 261int mingw_unlink(const char *pathname)
 262{
 263        int ret, tries = 0;
 264        wchar_t wpathname[MAX_PATH];
 265        if (xutftowcs_path(wpathname, pathname) < 0)
 266                return -1;
 267
 268        /* read-only files cannot be removed */
 269        _wchmod(wpathname, 0666);
 270        while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
 271                if (!is_file_in_use_error(GetLastError()))
 272                        break;
 273                /*
 274                 * We assume that some other process had the source or
 275                 * destination file open at the wrong moment and retry.
 276                 * In order to give the other process a higher chance to
 277                 * complete its operation, we give up our time slice now.
 278                 * If we have to retry again, we do sleep a bit.
 279                 */
 280                Sleep(delay[tries]);
 281                tries++;
 282        }
 283        while (ret == -1 && is_file_in_use_error(GetLastError()) &&
 284               ask_yes_no_if_possible("Unlink of file '%s' failed. "
 285                        "Should I try again?", pathname))
 286               ret = _wunlink(wpathname);
 287        return ret;
 288}
 289
 290static int is_dir_empty(const wchar_t *wpath)
 291{
 292        WIN32_FIND_DATAW findbuf;
 293        HANDLE handle;
 294        wchar_t wbuf[MAX_PATH + 2];
 295        wcscpy(wbuf, wpath);
 296        wcscat(wbuf, L"\\*");
 297        handle = FindFirstFileW(wbuf, &findbuf);
 298        if (handle == INVALID_HANDLE_VALUE)
 299                return GetLastError() == ERROR_NO_MORE_FILES;
 300
 301        while (!wcscmp(findbuf.cFileName, L".") ||
 302                        !wcscmp(findbuf.cFileName, L".."))
 303                if (!FindNextFileW(handle, &findbuf)) {
 304                        DWORD err = GetLastError();
 305                        FindClose(handle);
 306                        return err == ERROR_NO_MORE_FILES;
 307                }
 308        FindClose(handle);
 309        return 0;
 310}
 311
 312int mingw_rmdir(const char *pathname)
 313{
 314        int ret, tries = 0;
 315        wchar_t wpathname[MAX_PATH];
 316        if (xutftowcs_path(wpathname, pathname) < 0)
 317                return -1;
 318
 319        while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
 320                if (!is_file_in_use_error(GetLastError()))
 321                        errno = err_win_to_posix(GetLastError());
 322                if (errno != EACCES)
 323                        break;
 324                if (!is_dir_empty(wpathname)) {
 325                        errno = ENOTEMPTY;
 326                        break;
 327                }
 328                /*
 329                 * We assume that some other process had the source or
 330                 * destination file open at the wrong moment and retry.
 331                 * In order to give the other process a higher chance to
 332                 * complete its operation, we give up our time slice now.
 333                 * If we have to retry again, we do sleep a bit.
 334                 */
 335                Sleep(delay[tries]);
 336                tries++;
 337        }
 338        while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
 339               ask_yes_no_if_possible("Deletion of directory '%s' failed. "
 340                        "Should I try again?", pathname))
 341               ret = _wrmdir(wpathname);
 342        return ret;
 343}
 344
 345static inline int needs_hiding(const char *path)
 346{
 347        const char *basename;
 348
 349        if (hide_dotfiles == HIDE_DOTFILES_FALSE)
 350                return 0;
 351
 352        /* We cannot use basename(), as it would remove trailing slashes */
 353        mingw_skip_dos_drive_prefix((char **)&path);
 354        if (!*path)
 355                return 0;
 356
 357        for (basename = path; *path; path++)
 358                if (is_dir_sep(*path)) {
 359                        do {
 360                                path++;
 361                        } while (is_dir_sep(*path));
 362                        /* ignore trailing slashes */
 363                        if (*path)
 364                                basename = path;
 365                }
 366
 367        if (hide_dotfiles == HIDE_DOTFILES_TRUE)
 368                return *basename == '.';
 369
 370        assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
 371        return !strncasecmp(".git", basename, 4) &&
 372                (!basename[4] || is_dir_sep(basename[4]));
 373}
 374
 375static int set_hidden_flag(const wchar_t *path, int set)
 376{
 377        DWORD original = GetFileAttributesW(path), modified;
 378        if (set)
 379                modified = original | FILE_ATTRIBUTE_HIDDEN;
 380        else
 381                modified = original & ~FILE_ATTRIBUTE_HIDDEN;
 382        if (original == modified || SetFileAttributesW(path, modified))
 383                return 0;
 384        errno = err_win_to_posix(GetLastError());
 385        return -1;
 386}
 387
 388int mingw_mkdir(const char *path, int mode)
 389{
 390        int ret;
 391        wchar_t wpath[MAX_PATH];
 392        if (xutftowcs_path(wpath, path) < 0)
 393                return -1;
 394        ret = _wmkdir(wpath);
 395        if (!ret && needs_hiding(path))
 396                return set_hidden_flag(wpath, 1);
 397        return ret;
 398}
 399
 400/*
 401 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
 402 * is documented in [1] as opening a writable file handle in append mode.
 403 * (It is believed that) this is atomic since it is maintained by the
 404 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
 405 *
 406 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
 407 *
 408 * This trick does not appear to work for named pipes.  Instead it creates
 409 * a named pipe client handle that cannot be written to.  Callers should
 410 * just use the regular _wopen() for them.  (And since client handle gets
 411 * bound to a unique server handle, it isn't really an issue.)
 412 */
 413static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
 414{
 415        HANDLE handle;
 416        int fd;
 417        DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
 418
 419        /* only these flags are supported */
 420        if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
 421                return errno = ENOSYS, -1;
 422
 423        /*
 424         * FILE_SHARE_WRITE is required to permit child processes
 425         * to append to the file.
 426         */
 427        handle = CreateFileW(wfilename, FILE_APPEND_DATA,
 428                        FILE_SHARE_WRITE | FILE_SHARE_READ,
 429                        NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
 430        if (handle == INVALID_HANDLE_VALUE)
 431                return errno = err_win_to_posix(GetLastError()), -1;
 432
 433        /*
 434         * No O_APPEND here, because the CRT uses it only to reset the
 435         * file pointer to EOF before each write(); but that is not
 436         * necessary (and may lead to races) for a file created with
 437         * FILE_APPEND_DATA.
 438         */
 439        fd = _open_osfhandle((intptr_t)handle, O_BINARY);
 440        if (fd < 0)
 441                CloseHandle(handle);
 442        return fd;
 443}
 444
 445/*
 446 * Does the pathname map to the local named pipe filesystem?
 447 * That is, does it have a "//./pipe/" prefix?
 448 */
 449static int is_local_named_pipe_path(const char *filename)
 450{
 451        return (is_dir_sep(filename[0]) &&
 452                is_dir_sep(filename[1]) &&
 453                filename[2] == '.'  &&
 454                is_dir_sep(filename[3]) &&
 455                !strncasecmp(filename+4, "pipe", 4) &&
 456                is_dir_sep(filename[8]) &&
 457                filename[9]);
 458}
 459
 460int mingw_open (const char *filename, int oflags, ...)
 461{
 462        typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
 463        va_list args;
 464        unsigned mode;
 465        int fd;
 466        wchar_t wfilename[MAX_PATH];
 467        open_fn_t open_fn;
 468
 469        va_start(args, oflags);
 470        mode = va_arg(args, int);
 471        va_end(args);
 472
 473        if (filename && !strcmp(filename, "/dev/null"))
 474                filename = "nul";
 475
 476        if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
 477                open_fn = mingw_open_append;
 478        else
 479                open_fn = _wopen;
 480
 481        if (xutftowcs_path(wfilename, filename) < 0)
 482                return -1;
 483        fd = open_fn(wfilename, oflags, mode);
 484
 485        if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
 486                DWORD attrs = GetFileAttributesW(wfilename);
 487                if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
 488                        errno = EISDIR;
 489        }
 490        if ((oflags & O_CREAT) && needs_hiding(filename)) {
 491                /*
 492                 * Internally, _wopen() uses the CreateFile() API which errors
 493                 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
 494                 * specified and an already existing file's attributes do not
 495                 * match *exactly*. As there is no mode or flag we can set that
 496                 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
 497                 * again *without* the O_CREAT flag (that corresponds to the
 498                 * CREATE_ALWAYS flag of CreateFile()).
 499                 */
 500                if (fd < 0 && errno == EACCES)
 501                        fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
 502                if (fd >= 0 && set_hidden_flag(wfilename, 1))
 503                        warning("could not mark '%s' as hidden.", filename);
 504        }
 505        return fd;
 506}
 507
 508static BOOL WINAPI ctrl_ignore(DWORD type)
 509{
 510        return TRUE;
 511}
 512
 513#undef fgetc
 514int mingw_fgetc(FILE *stream)
 515{
 516        int ch;
 517        if (!isatty(_fileno(stream)))
 518                return fgetc(stream);
 519
 520        SetConsoleCtrlHandler(ctrl_ignore, TRUE);
 521        while (1) {
 522                ch = fgetc(stream);
 523                if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
 524                        break;
 525
 526                /* Ctrl+C was pressed, simulate SIGINT and retry */
 527                mingw_raise(SIGINT);
 528        }
 529        SetConsoleCtrlHandler(ctrl_ignore, FALSE);
 530        return ch;
 531}
 532
 533#undef fopen
 534FILE *mingw_fopen (const char *filename, const char *otype)
 535{
 536        int hide = needs_hiding(filename);
 537        FILE *file;
 538        wchar_t wfilename[MAX_PATH], wotype[4];
 539        if (filename && !strcmp(filename, "/dev/null"))
 540                filename = "nul";
 541        if (xutftowcs_path(wfilename, filename) < 0 ||
 542                xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
 543                return NULL;
 544        if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
 545                error("could not unhide %s", filename);
 546                return NULL;
 547        }
 548        file = _wfopen(wfilename, wotype);
 549        if (!file && GetLastError() == ERROR_INVALID_NAME)
 550                errno = ENOENT;
 551        if (file && hide && set_hidden_flag(wfilename, 1))
 552                warning("could not mark '%s' as hidden.", filename);
 553        return file;
 554}
 555
 556FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
 557{
 558        int hide = needs_hiding(filename);
 559        FILE *file;
 560        wchar_t wfilename[MAX_PATH], wotype[4];
 561        if (filename && !strcmp(filename, "/dev/null"))
 562                filename = "nul";
 563        if (xutftowcs_path(wfilename, filename) < 0 ||
 564                xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
 565                return NULL;
 566        if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
 567                error("could not unhide %s", filename);
 568                return NULL;
 569        }
 570        file = _wfreopen(wfilename, wotype, stream);
 571        if (file && hide && set_hidden_flag(wfilename, 1))
 572                warning("could not mark '%s' as hidden.", filename);
 573        return file;
 574}
 575
 576#undef fflush
 577int mingw_fflush(FILE *stream)
 578{
 579        int ret = fflush(stream);
 580
 581        /*
 582         * write() is used behind the scenes of stdio output functions.
 583         * Since git code does not check for errors after each stdio write
 584         * operation, it can happen that write() is called by a later
 585         * stdio function even if an earlier write() call failed. In the
 586         * case of a pipe whose readable end was closed, only the first
 587         * call to write() reports EPIPE on Windows. Subsequent write()
 588         * calls report EINVAL. It is impossible to notice whether this
 589         * fflush invocation triggered such a case, therefore, we have to
 590         * catch all EINVAL errors whole-sale.
 591         */
 592        if (ret && errno == EINVAL)
 593                errno = EPIPE;
 594
 595        return ret;
 596}
 597
 598#undef write
 599ssize_t mingw_write(int fd, const void *buf, size_t len)
 600{
 601        ssize_t result = write(fd, buf, len);
 602
 603        if (result < 0 && errno == EINVAL && buf) {
 604                /* check if fd is a pipe */
 605                HANDLE h = (HANDLE) _get_osfhandle(fd);
 606                if (GetFileType(h) == FILE_TYPE_PIPE)
 607                        errno = EPIPE;
 608                else
 609                        errno = EINVAL;
 610        }
 611
 612        return result;
 613}
 614
 615int mingw_access(const char *filename, int mode)
 616{
 617        wchar_t wfilename[MAX_PATH];
 618        if (xutftowcs_path(wfilename, filename) < 0)
 619                return -1;
 620        /* X_OK is not supported by the MSVCRT version */
 621        return _waccess(wfilename, mode & ~X_OK);
 622}
 623
 624int mingw_chdir(const char *dirname)
 625{
 626        wchar_t wdirname[MAX_PATH];
 627        if (xutftowcs_path(wdirname, dirname) < 0)
 628                return -1;
 629        return _wchdir(wdirname);
 630}
 631
 632int mingw_chmod(const char *filename, int mode)
 633{
 634        wchar_t wfilename[MAX_PATH];
 635        if (xutftowcs_path(wfilename, filename) < 0)
 636                return -1;
 637        return _wchmod(wfilename, mode);
 638}
 639
 640/*
 641 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
 642 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
 643 */
 644static inline long long filetime_to_hnsec(const FILETIME *ft)
 645{
 646        long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
 647        /* Windows to Unix Epoch conversion */
 648        return winTime - 116444736000000000LL;
 649}
 650
 651static inline time_t filetime_to_time_t(const FILETIME *ft)
 652{
 653        return (time_t)(filetime_to_hnsec(ft) / 10000000);
 654}
 655
 656/**
 657 * Verifies that safe_create_leading_directories() would succeed.
 658 */
 659static int has_valid_directory_prefix(wchar_t *wfilename)
 660{
 661        int n = wcslen(wfilename);
 662
 663        while (n > 0) {
 664                wchar_t c = wfilename[--n];
 665                DWORD attributes;
 666
 667                if (!is_dir_sep(c))
 668                        continue;
 669
 670                wfilename[n] = L'\0';
 671                attributes = GetFileAttributesW(wfilename);
 672                wfilename[n] = c;
 673                if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
 674                                attributes == FILE_ATTRIBUTE_DEVICE)
 675                        return 1;
 676                if (attributes == INVALID_FILE_ATTRIBUTES)
 677                        switch (GetLastError()) {
 678                        case ERROR_PATH_NOT_FOUND:
 679                                continue;
 680                        case ERROR_FILE_NOT_FOUND:
 681                                /* This implies parent directory exists. */
 682                                return 1;
 683                        }
 684                return 0;
 685        }
 686        return 1;
 687}
 688
 689/* We keep the do_lstat code in a separate function to avoid recursion.
 690 * When a path ends with a slash, the stat will fail with ENOENT. In
 691 * this case, we strip the trailing slashes and stat again.
 692 *
 693 * If follow is true then act like stat() and report on the link
 694 * target. Otherwise report on the link itself.
 695 */
 696static int do_lstat(int follow, const char *file_name, struct stat *buf)
 697{
 698        WIN32_FILE_ATTRIBUTE_DATA fdata;
 699        wchar_t wfilename[MAX_PATH];
 700        if (xutftowcs_path(wfilename, file_name) < 0)
 701                return -1;
 702
 703        if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
 704                buf->st_ino = 0;
 705                buf->st_gid = 0;
 706                buf->st_uid = 0;
 707                buf->st_nlink = 1;
 708                buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
 709                buf->st_size = fdata.nFileSizeLow |
 710                        (((off_t)fdata.nFileSizeHigh)<<32);
 711                buf->st_dev = buf->st_rdev = 0; /* not used by Git */
 712                buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
 713                buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
 714                buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
 715                if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
 716                        WIN32_FIND_DATAW findbuf;
 717                        HANDLE handle = FindFirstFileW(wfilename, &findbuf);
 718                        if (handle != INVALID_HANDLE_VALUE) {
 719                                if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
 720                                                (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
 721                                        if (follow) {
 722                                                char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
 723                                                buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
 724                                        } else {
 725                                                buf->st_mode = S_IFLNK;
 726                                        }
 727                                        buf->st_mode |= S_IREAD;
 728                                        if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
 729                                                buf->st_mode |= S_IWRITE;
 730                                }
 731                                FindClose(handle);
 732                        }
 733                }
 734                return 0;
 735        }
 736        switch (GetLastError()) {
 737        case ERROR_ACCESS_DENIED:
 738        case ERROR_SHARING_VIOLATION:
 739        case ERROR_LOCK_VIOLATION:
 740        case ERROR_SHARING_BUFFER_EXCEEDED:
 741                errno = EACCES;
 742                break;
 743        case ERROR_BUFFER_OVERFLOW:
 744                errno = ENAMETOOLONG;
 745                break;
 746        case ERROR_NOT_ENOUGH_MEMORY:
 747                errno = ENOMEM;
 748                break;
 749        case ERROR_PATH_NOT_FOUND:
 750                if (!has_valid_directory_prefix(wfilename)) {
 751                        errno = ENOTDIR;
 752                        break;
 753                }
 754                /* fallthru */
 755        default:
 756                errno = ENOENT;
 757                break;
 758        }
 759        return -1;
 760}
 761
 762/* We provide our own lstat/fstat functions, since the provided
 763 * lstat/fstat functions are so slow. These stat functions are
 764 * tailored for Git's usage (read: fast), and are not meant to be
 765 * complete. Note that Git stat()s are redirected to mingw_lstat()
 766 * too, since Windows doesn't really handle symlinks that well.
 767 */
 768static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
 769{
 770        int namelen;
 771        char alt_name[PATH_MAX];
 772
 773        if (!do_lstat(follow, file_name, buf))
 774                return 0;
 775
 776        /* if file_name ended in a '/', Windows returned ENOENT;
 777         * try again without trailing slashes
 778         */
 779        if (errno != ENOENT)
 780                return -1;
 781
 782        namelen = strlen(file_name);
 783        if (namelen && file_name[namelen-1] != '/')
 784                return -1;
 785        while (namelen && file_name[namelen-1] == '/')
 786                --namelen;
 787        if (!namelen || namelen >= PATH_MAX)
 788                return -1;
 789
 790        memcpy(alt_name, file_name, namelen);
 791        alt_name[namelen] = 0;
 792        return do_lstat(follow, alt_name, buf);
 793}
 794
 795int mingw_lstat(const char *file_name, struct stat *buf)
 796{
 797        return do_stat_internal(0, file_name, buf);
 798}
 799int mingw_stat(const char *file_name, struct stat *buf)
 800{
 801        return do_stat_internal(1, file_name, buf);
 802}
 803
 804int mingw_fstat(int fd, struct stat *buf)
 805{
 806        HANDLE fh = (HANDLE)_get_osfhandle(fd);
 807        BY_HANDLE_FILE_INFORMATION fdata;
 808
 809        if (fh == INVALID_HANDLE_VALUE) {
 810                errno = EBADF;
 811                return -1;
 812        }
 813        /* direct non-file handles to MS's fstat() */
 814        if (GetFileType(fh) != FILE_TYPE_DISK)
 815                return _fstati64(fd, buf);
 816
 817        if (GetFileInformationByHandle(fh, &fdata)) {
 818                buf->st_ino = 0;
 819                buf->st_gid = 0;
 820                buf->st_uid = 0;
 821                buf->st_nlink = 1;
 822                buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
 823                buf->st_size = fdata.nFileSizeLow |
 824                        (((off_t)fdata.nFileSizeHigh)<<32);
 825                buf->st_dev = buf->st_rdev = 0; /* not used by Git */
 826                buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
 827                buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
 828                buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
 829                return 0;
 830        }
 831        errno = EBADF;
 832        return -1;
 833}
 834
 835static inline void time_t_to_filetime(time_t t, FILETIME *ft)
 836{
 837        long long winTime = t * 10000000LL + 116444736000000000LL;
 838        ft->dwLowDateTime = winTime;
 839        ft->dwHighDateTime = winTime >> 32;
 840}
 841
 842int mingw_utime (const char *file_name, const struct utimbuf *times)
 843{
 844        FILETIME mft, aft;
 845        int fh, rc;
 846        DWORD attrs;
 847        wchar_t wfilename[MAX_PATH];
 848        if (xutftowcs_path(wfilename, file_name) < 0)
 849                return -1;
 850
 851        /* must have write permission */
 852        attrs = GetFileAttributesW(wfilename);
 853        if (attrs != INVALID_FILE_ATTRIBUTES &&
 854            (attrs & FILE_ATTRIBUTE_READONLY)) {
 855                /* ignore errors here; open() will report them */
 856                SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
 857        }
 858
 859        if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
 860                rc = -1;
 861                goto revert_attrs;
 862        }
 863
 864        if (times) {
 865                time_t_to_filetime(times->modtime, &mft);
 866                time_t_to_filetime(times->actime, &aft);
 867        } else {
 868                GetSystemTimeAsFileTime(&mft);
 869                aft = mft;
 870        }
 871        if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
 872                errno = EINVAL;
 873                rc = -1;
 874        } else
 875                rc = 0;
 876        close(fh);
 877
 878revert_attrs:
 879        if (attrs != INVALID_FILE_ATTRIBUTES &&
 880            (attrs & FILE_ATTRIBUTE_READONLY)) {
 881                /* ignore errors again */
 882                SetFileAttributesW(wfilename, attrs);
 883        }
 884        return rc;
 885}
 886
 887#undef strftime
 888size_t mingw_strftime(char *s, size_t max,
 889                      const char *format, const struct tm *tm)
 890{
 891        size_t ret = strftime(s, max, format, tm);
 892
 893        if (!ret && errno == EINVAL)
 894                die("invalid strftime format: '%s'", format);
 895        return ret;
 896}
 897
 898unsigned int sleep (unsigned int seconds)
 899{
 900        Sleep(seconds*1000);
 901        return 0;
 902}
 903
 904char *mingw_mktemp(char *template)
 905{
 906        wchar_t wtemplate[MAX_PATH];
 907        if (xutftowcs_path(wtemplate, template) < 0)
 908                return NULL;
 909        if (!_wmktemp(wtemplate))
 910                return NULL;
 911        if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
 912                return NULL;
 913        return template;
 914}
 915
 916int mkstemp(char *template)
 917{
 918        char *filename = mktemp(template);
 919        if (filename == NULL)
 920                return -1;
 921        return open(filename, O_RDWR | O_CREAT, 0600);
 922}
 923
 924int gettimeofday(struct timeval *tv, void *tz)
 925{
 926        FILETIME ft;
 927        long long hnsec;
 928
 929        GetSystemTimeAsFileTime(&ft);
 930        hnsec = filetime_to_hnsec(&ft);
 931        tv->tv_sec = hnsec / 10000000;
 932        tv->tv_usec = (hnsec % 10000000) / 10;
 933        return 0;
 934}
 935
 936int pipe(int filedes[2])
 937{
 938        HANDLE h[2];
 939
 940        /* this creates non-inheritable handles */
 941        if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
 942                errno = err_win_to_posix(GetLastError());
 943                return -1;
 944        }
 945        filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
 946        if (filedes[0] < 0) {
 947                CloseHandle(h[0]);
 948                CloseHandle(h[1]);
 949                return -1;
 950        }
 951        filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
 952        if (filedes[1] < 0) {
 953                close(filedes[0]);
 954                CloseHandle(h[1]);
 955                return -1;
 956        }
 957        return 0;
 958}
 959
 960struct tm *gmtime_r(const time_t *timep, struct tm *result)
 961{
 962        /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 963        memcpy(result, gmtime(timep), sizeof(struct tm));
 964        return result;
 965}
 966
 967struct tm *localtime_r(const time_t *timep, struct tm *result)
 968{
 969        /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 970        memcpy(result, localtime(timep), sizeof(struct tm));
 971        return result;
 972}
 973
 974char *mingw_getcwd(char *pointer, int len)
 975{
 976        wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
 977        DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
 978
 979        if (!ret || ret >= ARRAY_SIZE(cwd)) {
 980                errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
 981                return NULL;
 982        }
 983        ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
 984        if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
 985                HANDLE hnd = CreateFileW(cwd, 0,
 986                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
 987                        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
 988                if (hnd == INVALID_HANDLE_VALUE)
 989                        return NULL;
 990                ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
 991                CloseHandle(hnd);
 992                if (!ret || ret >= ARRAY_SIZE(wpointer))
 993                        return NULL;
 994                if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
 995                        return NULL;
 996                return pointer;
 997        }
 998        if (!ret || ret >= ARRAY_SIZE(wpointer))
 999                return NULL;
1000        if (xwcstoutf(pointer, wpointer, len) < 0)
1001                return NULL;
1002        convert_slashes(pointer);
1003        return pointer;
1004}
1005
1006/*
1007 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
1008 * (Parsing C++ Command-Line Arguments)
1009 */
1010static const char *quote_arg(const char *arg)
1011{
1012        /* count chars to quote */
1013        int len = 0, n = 0;
1014        int force_quotes = 0;
1015        char *q, *d;
1016        const char *p = arg;
1017        if (!*p) force_quotes = 1;
1018        while (*p) {
1019                if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1020                        force_quotes = 1;
1021                else if (*p == '"')
1022                        n++;
1023                else if (*p == '\\') {
1024                        int count = 0;
1025                        while (*p == '\\') {
1026                                count++;
1027                                p++;
1028                                len++;
1029                        }
1030                        if (*p == '"')
1031                                n += count*2 + 1;
1032                        continue;
1033                }
1034                len++;
1035                p++;
1036        }
1037        if (!force_quotes && n == 0)
1038                return arg;
1039
1040        /* insert \ where necessary */
1041        d = q = xmalloc(st_add3(len, n, 3));
1042        *d++ = '"';
1043        while (*arg) {
1044                if (*arg == '"')
1045                        *d++ = '\\';
1046                else if (*arg == '\\') {
1047                        int count = 0;
1048                        while (*arg == '\\') {
1049                                count++;
1050                                *d++ = *arg++;
1051                        }
1052                        if (*arg == '"') {
1053                                while (count-- > 0)
1054                                        *d++ = '\\';
1055                                *d++ = '\\';
1056                        }
1057                }
1058                *d++ = *arg++;
1059        }
1060        *d++ = '"';
1061        *d++ = 0;
1062        return q;
1063}
1064
1065static const char *parse_interpreter(const char *cmd)
1066{
1067        static char buf[100];
1068        char *p, *opt;
1069        int n, fd;
1070
1071        /* don't even try a .exe */
1072        n = strlen(cmd);
1073        if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1074                return NULL;
1075
1076        fd = open(cmd, O_RDONLY);
1077        if (fd < 0)
1078                return NULL;
1079        n = read(fd, buf, sizeof(buf)-1);
1080        close(fd);
1081        if (n < 4)      /* at least '#!/x' and not error */
1082                return NULL;
1083
1084        if (buf[0] != '#' || buf[1] != '!')
1085                return NULL;
1086        buf[n] = '\0';
1087        p = buf + strcspn(buf, "\r\n");
1088        if (!*p)
1089                return NULL;
1090
1091        *p = '\0';
1092        if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1093                return NULL;
1094        /* strip options */
1095        if ((opt = strchr(p+1, ' ')))
1096                *opt = '\0';
1097        return p+1;
1098}
1099
1100/*
1101 * exe_only means that we only want to detect .exe files, but not scripts
1102 * (which do not have an extension)
1103 */
1104static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1105                         int isexe, int exe_only)
1106{
1107        char path[MAX_PATH];
1108        snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1109
1110        if (!isexe && access(path, F_OK) == 0)
1111                return xstrdup(path);
1112        path[strlen(path)-4] = '\0';
1113        if ((!exe_only || isexe) && access(path, F_OK) == 0)
1114                if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
1115                        return xstrdup(path);
1116        return NULL;
1117}
1118
1119/*
1120 * Determines the absolute path of cmd using the split path in path.
1121 * If cmd contains a slash or backslash, no lookup is performed.
1122 */
1123static char *path_lookup(const char *cmd, int exe_only)
1124{
1125        const char *path;
1126        char *prog = NULL;
1127        int len = strlen(cmd);
1128        int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1129
1130        if (strchr(cmd, '/') || strchr(cmd, '\\'))
1131                return xstrdup(cmd);
1132
1133        path = mingw_getenv("PATH");
1134        if (!path)
1135                return NULL;
1136
1137        while (!prog) {
1138                const char *sep = strchrnul(path, ';');
1139                int dirlen = sep - path;
1140                if (dirlen)
1141                        prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1142                if (!*sep)
1143                        break;
1144                path = sep + 1;
1145        }
1146
1147        return prog;
1148}
1149
1150static int do_putenv(char **env, const char *name, int size, int free_old);
1151
1152/* used number of elements of environ array, including terminating NULL */
1153static int environ_size = 0;
1154/* allocated size of environ array, in bytes */
1155static int environ_alloc = 0;
1156
1157/*
1158 * Create environment block suitable for CreateProcess. Merges current
1159 * process environment and the supplied environment changes.
1160 */
1161static wchar_t *make_environment_block(char **deltaenv)
1162{
1163        wchar_t *wenvblk = NULL;
1164        char **tmpenv;
1165        int i = 0, size = environ_size, wenvsz = 0, wenvpos = 0;
1166
1167        while (deltaenv && deltaenv[i])
1168                i++;
1169
1170        /* copy the environment, leaving space for changes */
1171        ALLOC_ARRAY(tmpenv, size + i);
1172        memcpy(tmpenv, environ, size * sizeof(char*));
1173
1174        /* merge supplied environment changes into the temporary environment */
1175        for (i = 0; deltaenv && deltaenv[i]; i++)
1176                size = do_putenv(tmpenv, deltaenv[i], size, 0);
1177
1178        /* create environment block from temporary environment */
1179        for (i = 0; tmpenv[i]; i++) {
1180                size = 2 * strlen(tmpenv[i]) + 2; /* +2 for final \0 */
1181                ALLOC_GROW(wenvblk, (wenvpos + size) * sizeof(wchar_t), wenvsz);
1182                wenvpos += xutftowcs(&wenvblk[wenvpos], tmpenv[i], size) + 1;
1183        }
1184        /* add final \0 terminator */
1185        wenvblk[wenvpos] = 0;
1186        free(tmpenv);
1187        return wenvblk;
1188}
1189
1190static void do_unset_environment_variables(void)
1191{
1192        static int done;
1193        char *p = unset_environment_variables;
1194
1195        if (done || !p)
1196                return;
1197        done = 1;
1198
1199        for (;;) {
1200                char *comma = strchr(p, ',');
1201
1202                if (comma)
1203                        *comma = '\0';
1204                unsetenv(p);
1205                if (!comma)
1206                        break;
1207                p = comma + 1;
1208        }
1209}
1210
1211struct pinfo_t {
1212        struct pinfo_t *next;
1213        pid_t pid;
1214        HANDLE proc;
1215};
1216static struct pinfo_t *pinfo = NULL;
1217CRITICAL_SECTION pinfo_cs;
1218
1219static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1220                              const char *dir,
1221                              int prepend_cmd, int fhin, int fhout, int fherr)
1222{
1223        STARTUPINFOW si;
1224        PROCESS_INFORMATION pi;
1225        struct strbuf args;
1226        wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1227        unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1228        BOOL ret;
1229        HANDLE cons;
1230
1231        do_unset_environment_variables();
1232
1233        /* Determine whether or not we are associated to a console */
1234        cons = CreateFile("CONOUT$", GENERIC_WRITE,
1235                        FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1236                        FILE_ATTRIBUTE_NORMAL, NULL);
1237        if (cons == INVALID_HANDLE_VALUE) {
1238                /* There is no console associated with this process.
1239                 * Since the child is a console process, Windows
1240                 * would normally create a console window. But
1241                 * since we'll be redirecting std streams, we do
1242                 * not need the console.
1243                 * It is necessary to use DETACHED_PROCESS
1244                 * instead of CREATE_NO_WINDOW to make ssh
1245                 * recognize that it has no console.
1246                 */
1247                flags |= DETACHED_PROCESS;
1248        } else {
1249                /* There is already a console. If we specified
1250                 * DETACHED_PROCESS here, too, Windows would
1251                 * disassociate the child from the console.
1252                 * The same is true for CREATE_NO_WINDOW.
1253                 * Go figure!
1254                 */
1255                CloseHandle(cons);
1256        }
1257        memset(&si, 0, sizeof(si));
1258        si.cb = sizeof(si);
1259        si.dwFlags = STARTF_USESTDHANDLES;
1260        si.hStdInput = winansi_get_osfhandle(fhin);
1261        si.hStdOutput = winansi_get_osfhandle(fhout);
1262        si.hStdError = winansi_get_osfhandle(fherr);
1263
1264        if (xutftowcs_path(wcmd, cmd) < 0)
1265                return -1;
1266        if (dir && xutftowcs_path(wdir, dir) < 0)
1267                return -1;
1268
1269        /* concatenate argv, quoting args as we go */
1270        strbuf_init(&args, 0);
1271        if (prepend_cmd) {
1272                char *quoted = (char *)quote_arg(cmd);
1273                strbuf_addstr(&args, quoted);
1274                if (quoted != cmd)
1275                        free(quoted);
1276        }
1277        for (; *argv; argv++) {
1278                char *quoted = (char *)quote_arg(*argv);
1279                if (*args.buf)
1280                        strbuf_addch(&args, ' ');
1281                strbuf_addstr(&args, quoted);
1282                if (quoted != *argv)
1283                        free(quoted);
1284        }
1285
1286        ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1287        xutftowcs(wargs, args.buf, 2 * args.len + 1);
1288        strbuf_release(&args);
1289
1290        wenvblk = make_environment_block(deltaenv);
1291
1292        memset(&pi, 0, sizeof(pi));
1293        ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,
1294                wenvblk, dir ? wdir : NULL, &si, &pi);
1295
1296        free(wenvblk);
1297        free(wargs);
1298
1299        if (!ret) {
1300                errno = ENOENT;
1301                return -1;
1302        }
1303        CloseHandle(pi.hThread);
1304
1305        /*
1306         * The process ID is the human-readable identifier of the process
1307         * that we want to present in log and error messages. The handle
1308         * is not useful for this purpose. But we cannot close it, either,
1309         * because it is not possible to turn a process ID into a process
1310         * handle after the process terminated.
1311         * Keep the handle in a list for waitpid.
1312         */
1313        EnterCriticalSection(&pinfo_cs);
1314        {
1315                struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1316                info->pid = pi.dwProcessId;
1317                info->proc = pi.hProcess;
1318                info->next = pinfo;
1319                pinfo = info;
1320        }
1321        LeaveCriticalSection(&pinfo_cs);
1322
1323        return (pid_t)pi.dwProcessId;
1324}
1325
1326static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1327{
1328        return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1329}
1330
1331pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1332                     const char *dir,
1333                     int fhin, int fhout, int fherr)
1334{
1335        pid_t pid;
1336        char *prog = path_lookup(cmd, 0);
1337
1338        if (!prog) {
1339                errno = ENOENT;
1340                pid = -1;
1341        }
1342        else {
1343                const char *interpr = parse_interpreter(prog);
1344
1345                if (interpr) {
1346                        const char *argv0 = argv[0];
1347                        char *iprog = path_lookup(interpr, 1);
1348                        argv[0] = prog;
1349                        if (!iprog) {
1350                                errno = ENOENT;
1351                                pid = -1;
1352                        }
1353                        else {
1354                                pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1355                                                       fhin, fhout, fherr);
1356                                free(iprog);
1357                        }
1358                        argv[0] = argv0;
1359                }
1360                else
1361                        pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1362                                               fhin, fhout, fherr);
1363                free(prog);
1364        }
1365        return pid;
1366}
1367
1368static int try_shell_exec(const char *cmd, char *const *argv)
1369{
1370        const char *interpr = parse_interpreter(cmd);
1371        char *prog;
1372        int pid = 0;
1373
1374        if (!interpr)
1375                return 0;
1376        prog = path_lookup(interpr, 1);
1377        if (prog) {
1378                int argc = 0;
1379                const char **argv2;
1380                while (argv[argc]) argc++;
1381                ALLOC_ARRAY(argv2, argc + 1);
1382                argv2[0] = (char *)cmd; /* full path to the script file */
1383                memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1384                pid = mingw_spawnv(prog, argv2, 1);
1385                if (pid >= 0) {
1386                        int status;
1387                        if (waitpid(pid, &status, 0) < 0)
1388                                status = 255;
1389                        exit(status);
1390                }
1391                pid = 1;        /* indicate that we tried but failed */
1392                free(prog);
1393                free(argv2);
1394        }
1395        return pid;
1396}
1397
1398int mingw_execv(const char *cmd, char *const *argv)
1399{
1400        /* check if git_command is a shell script */
1401        if (!try_shell_exec(cmd, argv)) {
1402                int pid, status;
1403
1404                pid = mingw_spawnv(cmd, (const char **)argv, 0);
1405                if (pid < 0)
1406                        return -1;
1407                if (waitpid(pid, &status, 0) < 0)
1408                        status = 255;
1409                exit(status);
1410        }
1411        return -1;
1412}
1413
1414int mingw_execvp(const char *cmd, char *const *argv)
1415{
1416        char *prog = path_lookup(cmd, 0);
1417
1418        if (prog) {
1419                mingw_execv(prog, argv);
1420                free(prog);
1421        } else
1422                errno = ENOENT;
1423
1424        return -1;
1425}
1426
1427int mingw_kill(pid_t pid, int sig)
1428{
1429        if (pid > 0 && sig == SIGTERM) {
1430                HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1431
1432                if (TerminateProcess(h, -1)) {
1433                        CloseHandle(h);
1434                        return 0;
1435                }
1436
1437                errno = err_win_to_posix(GetLastError());
1438                CloseHandle(h);
1439                return -1;
1440        } else if (pid > 0 && sig == 0) {
1441                HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1442                if (h) {
1443                        CloseHandle(h);
1444                        return 0;
1445                }
1446        }
1447
1448        errno = EINVAL;
1449        return -1;
1450}
1451
1452/*
1453 * Compare environment entries by key (i.e. stopping at '=' or '\0').
1454 */
1455static int compareenv(const void *v1, const void *v2)
1456{
1457        const char *e1 = *(const char**)v1;
1458        const char *e2 = *(const char**)v2;
1459
1460        for (;;) {
1461                int c1 = *e1++;
1462                int c2 = *e2++;
1463                c1 = (c1 == '=') ? 0 : tolower(c1);
1464                c2 = (c2 == '=') ? 0 : tolower(c2);
1465                if (c1 > c2)
1466                        return 1;
1467                if (c1 < c2)
1468                        return -1;
1469                if (c1 == 0)
1470                        return 0;
1471        }
1472}
1473
1474static int bsearchenv(char **env, const char *name, size_t size)
1475{
1476        unsigned low = 0, high = size;
1477        while (low < high) {
1478                unsigned mid = low + ((high - low) >> 1);
1479                int cmp = compareenv(&env[mid], &name);
1480                if (cmp < 0)
1481                        low = mid + 1;
1482                else if (cmp > 0)
1483                        high = mid;
1484                else
1485                        return mid;
1486        }
1487        return ~low; /* not found, return 1's complement of insert position */
1488}
1489
1490/*
1491 * If name contains '=', then sets the variable, otherwise it unsets it
1492 * Size includes the terminating NULL. Env must have room for size + 1 entries
1493 * (in case of insert). Returns the new size. Optionally frees removed entries.
1494 */
1495static int do_putenv(char **env, const char *name, int size, int free_old)
1496{
1497        int i = bsearchenv(env, name, size - 1);
1498
1499        /* optionally free removed / replaced entry */
1500        if (i >= 0 && free_old)
1501                free(env[i]);
1502
1503        if (strchr(name, '=')) {
1504                /* if new value ('key=value') is specified, insert or replace entry */
1505                if (i < 0) {
1506                        i = ~i;
1507                        memmove(&env[i + 1], &env[i], (size - i) * sizeof(char*));
1508                        size++;
1509                }
1510                env[i] = (char*) name;
1511        } else if (i >= 0) {
1512                /* otherwise ('key') remove existing entry */
1513                size--;
1514                memmove(&env[i], &env[i + 1], (size - i) * sizeof(char*));
1515        }
1516        return size;
1517}
1518
1519char *mingw_getenv(const char *name)
1520{
1521        char *value;
1522        int pos = bsearchenv(environ, name, environ_size - 1);
1523        if (pos < 0)
1524                return NULL;
1525        value = strchr(environ[pos], '=');
1526        return value ? &value[1] : NULL;
1527}
1528
1529int mingw_putenv(const char *namevalue)
1530{
1531        ALLOC_GROW(environ, (environ_size + 1) * sizeof(char*), environ_alloc);
1532        environ_size = do_putenv(environ, namevalue, environ_size, 1);
1533        return 0;
1534}
1535
1536/*
1537 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1538 * that service contains a numerical port, or that it is null. It
1539 * does a simple search using gethostbyname, and returns one IPv4 host
1540 * if one was found.
1541 */
1542static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1543                                   const struct addrinfo *hints,
1544                                   struct addrinfo **res)
1545{
1546        struct hostent *h = NULL;
1547        struct addrinfo *ai;
1548        struct sockaddr_in *sin;
1549
1550        if (node) {
1551                h = gethostbyname(node);
1552                if (!h)
1553                        return WSAGetLastError();
1554        }
1555
1556        ai = xmalloc(sizeof(struct addrinfo));
1557        *res = ai;
1558        ai->ai_flags = 0;
1559        ai->ai_family = AF_INET;
1560        ai->ai_socktype = hints ? hints->ai_socktype : 0;
1561        switch (ai->ai_socktype) {
1562        case SOCK_STREAM:
1563                ai->ai_protocol = IPPROTO_TCP;
1564                break;
1565        case SOCK_DGRAM:
1566                ai->ai_protocol = IPPROTO_UDP;
1567                break;
1568        default:
1569                ai->ai_protocol = 0;
1570                break;
1571        }
1572        ai->ai_addrlen = sizeof(struct sockaddr_in);
1573        if (hints && (hints->ai_flags & AI_CANONNAME))
1574                ai->ai_canonname = h ? xstrdup(h->h_name) : NULL;
1575        else
1576                ai->ai_canonname = NULL;
1577
1578        sin = xcalloc(1, ai->ai_addrlen);
1579        sin->sin_family = AF_INET;
1580        /* Note: getaddrinfo is supposed to allow service to be a string,
1581         * which should be looked up using getservbyname. This is
1582         * currently not implemented */
1583        if (service)
1584                sin->sin_port = htons(atoi(service));
1585        if (h)
1586                sin->sin_addr = *(struct in_addr *)h->h_addr;
1587        else if (hints && (hints->ai_flags & AI_PASSIVE))
1588                sin->sin_addr.s_addr = INADDR_ANY;
1589        else
1590                sin->sin_addr.s_addr = INADDR_LOOPBACK;
1591        ai->ai_addr = (struct sockaddr *)sin;
1592        ai->ai_next = NULL;
1593        return 0;
1594}
1595
1596static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1597{
1598        free(res->ai_canonname);
1599        free(res->ai_addr);
1600        free(res);
1601}
1602
1603static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1604                                   char *host, DWORD hostlen,
1605                                   char *serv, DWORD servlen, int flags)
1606{
1607        const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1608        if (sa->sa_family != AF_INET)
1609                return EAI_FAMILY;
1610        if (!host && !serv)
1611                return EAI_NONAME;
1612
1613        if (host && hostlen > 0) {
1614                struct hostent *ent = NULL;
1615                if (!(flags & NI_NUMERICHOST))
1616                        ent = gethostbyaddr((const char *)&sin->sin_addr,
1617                                            sizeof(sin->sin_addr), AF_INET);
1618
1619                if (ent)
1620                        snprintf(host, hostlen, "%s", ent->h_name);
1621                else if (flags & NI_NAMEREQD)
1622                        return EAI_NONAME;
1623                else
1624                        snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1625        }
1626
1627        if (serv && servlen > 0) {
1628                struct servent *ent = NULL;
1629                if (!(flags & NI_NUMERICSERV))
1630                        ent = getservbyport(sin->sin_port,
1631                                            flags & NI_DGRAM ? "udp" : "tcp");
1632
1633                if (ent)
1634                        snprintf(serv, servlen, "%s", ent->s_name);
1635                else
1636                        snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1637        }
1638
1639        return 0;
1640}
1641
1642static HMODULE ipv6_dll = NULL;
1643static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1644static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1645                                      const struct addrinfo *hints,
1646                                      struct addrinfo **res);
1647static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1648                                      char *host, DWORD hostlen,
1649                                      char *serv, DWORD servlen, int flags);
1650/*
1651 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1652 * don't need to try to load that one dynamically.
1653 */
1654
1655static void socket_cleanup(void)
1656{
1657        WSACleanup();
1658        if (ipv6_dll)
1659                FreeLibrary(ipv6_dll);
1660        ipv6_dll = NULL;
1661        ipv6_freeaddrinfo = freeaddrinfo_stub;
1662        ipv6_getaddrinfo = getaddrinfo_stub;
1663        ipv6_getnameinfo = getnameinfo_stub;
1664}
1665
1666static void ensure_socket_initialization(void)
1667{
1668        WSADATA wsa;
1669        static int initialized = 0;
1670        const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1671        const char **name;
1672
1673        if (initialized)
1674                return;
1675
1676        if (WSAStartup(MAKEWORD(2,2), &wsa))
1677                die("unable to initialize winsock subsystem, error %d",
1678                        WSAGetLastError());
1679
1680        for (name = libraries; *name; name++) {
1681                ipv6_dll = LoadLibraryExA(*name, NULL,
1682                                          LOAD_LIBRARY_SEARCH_SYSTEM32);
1683                if (!ipv6_dll)
1684                        continue;
1685
1686                ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1687                        GetProcAddress(ipv6_dll, "freeaddrinfo");
1688                ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1689                                                   const struct addrinfo *,
1690                                                   struct addrinfo **))
1691                        GetProcAddress(ipv6_dll, "getaddrinfo");
1692                ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1693                                                   socklen_t, char *, DWORD,
1694                                                   char *, DWORD, int))
1695                        GetProcAddress(ipv6_dll, "getnameinfo");
1696                if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1697                        FreeLibrary(ipv6_dll);
1698                        ipv6_dll = NULL;
1699                } else
1700                        break;
1701        }
1702        if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1703                ipv6_freeaddrinfo = freeaddrinfo_stub;
1704                ipv6_getaddrinfo = getaddrinfo_stub;
1705                ipv6_getnameinfo = getnameinfo_stub;
1706        }
1707
1708        atexit(socket_cleanup);
1709        initialized = 1;
1710}
1711
1712#undef gethostname
1713int mingw_gethostname(char *name, int namelen)
1714{
1715    ensure_socket_initialization();
1716    return gethostname(name, namelen);
1717}
1718
1719#undef gethostbyname
1720struct hostent *mingw_gethostbyname(const char *host)
1721{
1722        ensure_socket_initialization();
1723        return gethostbyname(host);
1724}
1725
1726void mingw_freeaddrinfo(struct addrinfo *res)
1727{
1728        ipv6_freeaddrinfo(res);
1729}
1730
1731int mingw_getaddrinfo(const char *node, const char *service,
1732                      const struct addrinfo *hints, struct addrinfo **res)
1733{
1734        ensure_socket_initialization();
1735        return ipv6_getaddrinfo(node, service, hints, res);
1736}
1737
1738int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1739                      char *host, DWORD hostlen, char *serv, DWORD servlen,
1740                      int flags)
1741{
1742        ensure_socket_initialization();
1743        return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1744}
1745
1746int mingw_socket(int domain, int type, int protocol)
1747{
1748        int sockfd;
1749        SOCKET s;
1750
1751        ensure_socket_initialization();
1752        s = WSASocket(domain, type, protocol, NULL, 0, 0);
1753        if (s == INVALID_SOCKET) {
1754                /*
1755                 * WSAGetLastError() values are regular BSD error codes
1756                 * biased by WSABASEERR.
1757                 * However, strerror() does not know about networking
1758                 * specific errors, which are values beginning at 38 or so.
1759                 * Therefore, we choose to leave the biased error code
1760                 * in errno so that _if_ someone looks up the code somewhere,
1761                 * then it is at least the number that are usually listed.
1762                 */
1763                errno = WSAGetLastError();
1764                return -1;
1765        }
1766        /* convert into a file descriptor */
1767        if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1768                closesocket(s);
1769                return error("unable to make a socket file descriptor: %s",
1770                        strerror(errno));
1771        }
1772        return sockfd;
1773}
1774
1775#undef connect
1776int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1777{
1778        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1779        return connect(s, sa, sz);
1780}
1781
1782#undef bind
1783int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1784{
1785        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1786        return bind(s, sa, sz);
1787}
1788
1789#undef setsockopt
1790int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1791{
1792        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1793        return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1794}
1795
1796#undef shutdown
1797int mingw_shutdown(int sockfd, int how)
1798{
1799        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1800        return shutdown(s, how);
1801}
1802
1803#undef listen
1804int mingw_listen(int sockfd, int backlog)
1805{
1806        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1807        return listen(s, backlog);
1808}
1809
1810#undef accept
1811int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1812{
1813        int sockfd2;
1814
1815        SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1816        SOCKET s2 = accept(s1, sa, sz);
1817
1818        /* convert into a file descriptor */
1819        if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1820                int err = errno;
1821                closesocket(s2);
1822                return error("unable to make a socket file descriptor: %s",
1823                        strerror(err));
1824        }
1825        return sockfd2;
1826}
1827
1828#undef rename
1829int mingw_rename(const char *pold, const char *pnew)
1830{
1831        DWORD attrs, gle;
1832        int tries = 0;
1833        wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1834        if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1835                return -1;
1836
1837        /*
1838         * Try native rename() first to get errno right.
1839         * It is based on MoveFile(), which cannot overwrite existing files.
1840         */
1841        if (!_wrename(wpold, wpnew))
1842                return 0;
1843        if (errno != EEXIST)
1844                return -1;
1845repeat:
1846        if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1847                return 0;
1848        /* TODO: translate more errors */
1849        gle = GetLastError();
1850        if (gle == ERROR_ACCESS_DENIED &&
1851            (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
1852                if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1853                        DWORD attrsold = GetFileAttributesW(wpold);
1854                        if (attrsold == INVALID_FILE_ATTRIBUTES ||
1855                            !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
1856                                errno = EISDIR;
1857                        else if (!_wrmdir(wpnew))
1858                                goto repeat;
1859                        return -1;
1860                }
1861                if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1862                    SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1863                        if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1864                                return 0;
1865                        gle = GetLastError();
1866                        /* revert file attributes on failure */
1867                        SetFileAttributesW(wpnew, attrs);
1868                }
1869        }
1870        if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1871                /*
1872                 * We assume that some other process had the source or
1873                 * destination file open at the wrong moment and retry.
1874                 * In order to give the other process a higher chance to
1875                 * complete its operation, we give up our time slice now.
1876                 * If we have to retry again, we do sleep a bit.
1877                 */
1878                Sleep(delay[tries]);
1879                tries++;
1880                goto repeat;
1881        }
1882        if (gle == ERROR_ACCESS_DENIED &&
1883               ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1884                       "Should I try again?", pold, pnew))
1885                goto repeat;
1886
1887        errno = EACCES;
1888        return -1;
1889}
1890
1891/*
1892 * Note that this doesn't return the actual pagesize, but
1893 * the allocation granularity. If future Windows specific git code
1894 * needs the real getpagesize function, we need to find another solution.
1895 */
1896int mingw_getpagesize(void)
1897{
1898        SYSTEM_INFO si;
1899        GetSystemInfo(&si);
1900        return si.dwAllocationGranularity;
1901}
1902
1903/* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1904enum EXTENDED_NAME_FORMAT {
1905        NameDisplay = 3,
1906        NameUserPrincipal = 8
1907};
1908
1909static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
1910{
1911        DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
1912                enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
1913        static wchar_t wbuffer[1024];
1914        DWORD len;
1915
1916        if (!INIT_PROC_ADDR(GetUserNameExW))
1917                return NULL;
1918
1919        len = ARRAY_SIZE(wbuffer);
1920        if (GetUserNameExW(type, wbuffer, &len)) {
1921                char *converted = xmalloc((len *= 3));
1922                if (xwcstoutf(converted, wbuffer, len) >= 0)
1923                        return converted;
1924                free(converted);
1925        }
1926
1927        return NULL;
1928}
1929
1930char *mingw_query_user_email(void)
1931{
1932        return get_extended_user_info(NameUserPrincipal);
1933}
1934
1935struct passwd *getpwuid(int uid)
1936{
1937        static unsigned initialized;
1938        static char user_name[100];
1939        static struct passwd *p;
1940        DWORD len;
1941
1942        if (initialized)
1943                return p;
1944
1945        len = sizeof(user_name);
1946        if (!GetUserName(user_name, &len)) {
1947                initialized = 1;
1948                return NULL;
1949        }
1950
1951        p = xmalloc(sizeof(*p));
1952        p->pw_name = user_name;
1953        p->pw_gecos = get_extended_user_info(NameDisplay);
1954        if (!p->pw_gecos)
1955                p->pw_gecos = "unknown";
1956        p->pw_dir = NULL;
1957
1958        initialized = 1;
1959        return p;
1960}
1961
1962static HANDLE timer_event;
1963static HANDLE timer_thread;
1964static int timer_interval;
1965static int one_shot;
1966static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
1967
1968/* The timer works like this:
1969 * The thread, ticktack(), is a trivial routine that most of the time
1970 * only waits to receive the signal to terminate. The main thread tells
1971 * the thread to terminate by setting the timer_event to the signalled
1972 * state.
1973 * But ticktack() interrupts the wait state after the timer's interval
1974 * length to call the signal handler.
1975 */
1976
1977static unsigned __stdcall ticktack(void *dummy)
1978{
1979        while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1980                mingw_raise(SIGALRM);
1981                if (one_shot)
1982                        break;
1983        }
1984        return 0;
1985}
1986
1987static int start_timer_thread(void)
1988{
1989        timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1990        if (timer_event) {
1991                timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1992                if (!timer_thread )
1993                        return errno = ENOMEM,
1994                                error("cannot start timer thread");
1995        } else
1996                return errno = ENOMEM,
1997                        error("cannot allocate resources for timer");
1998        return 0;
1999}
2000
2001static void stop_timer_thread(void)
2002{
2003        if (timer_event)
2004                SetEvent(timer_event);  /* tell thread to terminate */
2005        if (timer_thread) {
2006                int rc = WaitForSingleObject(timer_thread, 1000);
2007                if (rc == WAIT_TIMEOUT)
2008                        error("timer thread did not terminate timely");
2009                else if (rc != WAIT_OBJECT_0)
2010                        error("waiting for timer thread failed: %lu",
2011                              GetLastError());
2012                CloseHandle(timer_thread);
2013        }
2014        if (timer_event)
2015                CloseHandle(timer_event);
2016        timer_event = NULL;
2017        timer_thread = NULL;
2018}
2019
2020static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2021{
2022        return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2023}
2024
2025int setitimer(int type, struct itimerval *in, struct itimerval *out)
2026{
2027        static const struct timeval zero;
2028        static int atexit_done;
2029
2030        if (out != NULL)
2031                return errno = EINVAL,
2032                        error("setitimer param 3 != NULL not implemented");
2033        if (!is_timeval_eq(&in->it_interval, &zero) &&
2034            !is_timeval_eq(&in->it_interval, &in->it_value))
2035                return errno = EINVAL,
2036                        error("setitimer: it_interval must be zero or eq it_value");
2037
2038        if (timer_thread)
2039                stop_timer_thread();
2040
2041        if (is_timeval_eq(&in->it_value, &zero) &&
2042            is_timeval_eq(&in->it_interval, &zero))
2043                return 0;
2044
2045        timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2046        one_shot = is_timeval_eq(&in->it_interval, &zero);
2047        if (!atexit_done) {
2048                atexit(stop_timer_thread);
2049                atexit_done = 1;
2050        }
2051        return start_timer_thread();
2052}
2053
2054int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2055{
2056        if (sig != SIGALRM)
2057                return errno = EINVAL,
2058                        error("sigaction only implemented for SIGALRM");
2059        if (out != NULL)
2060                return errno = EINVAL,
2061                        error("sigaction: param 3 != NULL not implemented");
2062
2063        timer_fn = in->sa_handler;
2064        return 0;
2065}
2066
2067#undef signal
2068sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2069{
2070        sig_handler_t old;
2071
2072        switch (sig) {
2073        case SIGALRM:
2074                old = timer_fn;
2075                timer_fn = handler;
2076                break;
2077
2078        case SIGINT:
2079                old = sigint_fn;
2080                sigint_fn = handler;
2081                break;
2082
2083        default:
2084                return signal(sig, handler);
2085        }
2086
2087        return old;
2088}
2089
2090#undef raise
2091int mingw_raise(int sig)
2092{
2093        switch (sig) {
2094        case SIGALRM:
2095                if (timer_fn == SIG_DFL) {
2096                        if (isatty(STDERR_FILENO))
2097                                fputs("Alarm clock\n", stderr);
2098                        exit(128 + SIGALRM);
2099                } else if (timer_fn != SIG_IGN)
2100                        timer_fn(SIGALRM);
2101                return 0;
2102
2103        case SIGINT:
2104                if (sigint_fn == SIG_DFL)
2105                        exit(128 + SIGINT);
2106                else if (sigint_fn != SIG_IGN)
2107                        sigint_fn(SIGINT);
2108                return 0;
2109
2110        default:
2111                return raise(sig);
2112        }
2113}
2114
2115int link(const char *oldpath, const char *newpath)
2116{
2117        typedef BOOL (WINAPI *T)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES);
2118        static T create_hard_link = NULL;
2119        wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2120        if (xutftowcs_path(woldpath, oldpath) < 0 ||
2121                xutftowcs_path(wnewpath, newpath) < 0)
2122                return -1;
2123
2124        if (!create_hard_link) {
2125                create_hard_link = (T) GetProcAddress(
2126                        GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
2127                if (!create_hard_link)
2128                        create_hard_link = (T)-1;
2129        }
2130        if (create_hard_link == (T)-1) {
2131                errno = ENOSYS;
2132                return -1;
2133        }
2134        if (!create_hard_link(wnewpath, woldpath, NULL)) {
2135                errno = err_win_to_posix(GetLastError());
2136                return -1;
2137        }
2138        return 0;
2139}
2140
2141pid_t waitpid(pid_t pid, int *status, int options)
2142{
2143        HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2144            FALSE, pid);
2145        if (!h) {
2146                errno = ECHILD;
2147                return -1;
2148        }
2149
2150        if (pid > 0 && options & WNOHANG) {
2151                if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2152                        CloseHandle(h);
2153                        return 0;
2154                }
2155                options &= ~WNOHANG;
2156        }
2157
2158        if (options == 0) {
2159                struct pinfo_t **ppinfo;
2160                if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2161                        CloseHandle(h);
2162                        return 0;
2163                }
2164
2165                if (status)
2166                        GetExitCodeProcess(h, (LPDWORD)status);
2167
2168                EnterCriticalSection(&pinfo_cs);
2169
2170                ppinfo = &pinfo;
2171                while (*ppinfo) {
2172                        struct pinfo_t *info = *ppinfo;
2173                        if (info->pid == pid) {
2174                                CloseHandle(info->proc);
2175                                *ppinfo = info->next;
2176                                free(info);
2177                                break;
2178                        }
2179                        ppinfo = &info->next;
2180                }
2181
2182                LeaveCriticalSection(&pinfo_cs);
2183
2184                CloseHandle(h);
2185                return pid;
2186        }
2187        CloseHandle(h);
2188
2189        errno = EINVAL;
2190        return -1;
2191}
2192
2193int mingw_skip_dos_drive_prefix(char **path)
2194{
2195        int ret = has_dos_drive_prefix(*path);
2196        *path += ret;
2197        return ret;
2198}
2199
2200int mingw_offset_1st_component(const char *path)
2201{
2202        char *pos = (char *)path;
2203
2204        /* unc paths */
2205        if (!skip_dos_drive_prefix(&pos) &&
2206                        is_dir_sep(pos[0]) && is_dir_sep(pos[1])) {
2207                /* skip server name */
2208                pos = strpbrk(pos + 2, "\\/");
2209                if (!pos)
2210                        return 0; /* Error: malformed unc path */
2211
2212                do {
2213                        pos++;
2214                } while (*pos && !is_dir_sep(*pos));
2215        }
2216
2217        return pos + is_dir_sep(*pos) - path;
2218}
2219
2220int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2221{
2222        int upos = 0, wpos = 0;
2223        const unsigned char *utf = (const unsigned char*) utfs;
2224        if (!utf || !wcs || wcslen < 1) {
2225                errno = EINVAL;
2226                return -1;
2227        }
2228        /* reserve space for \0 */
2229        wcslen--;
2230        if (utflen < 0)
2231                utflen = INT_MAX;
2232
2233        while (upos < utflen) {
2234                int c = utf[upos++] & 0xff;
2235                if (utflen == INT_MAX && c == 0)
2236                        break;
2237
2238                if (wpos >= wcslen) {
2239                        wcs[wpos] = 0;
2240                        errno = ERANGE;
2241                        return -1;
2242                }
2243
2244                if (c < 0x80) {
2245                        /* ASCII */
2246                        wcs[wpos++] = c;
2247                } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2248                                (utf[upos] & 0xc0) == 0x80) {
2249                        /* 2-byte utf-8 */
2250                        c = ((c & 0x1f) << 6);
2251                        c |= (utf[upos++] & 0x3f);
2252                        wcs[wpos++] = c;
2253                } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2254                                !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2255                                (utf[upos] & 0xc0) == 0x80 &&
2256                                (utf[upos + 1] & 0xc0) == 0x80) {
2257                        /* 3-byte utf-8 */
2258                        c = ((c & 0x0f) << 12);
2259                        c |= ((utf[upos++] & 0x3f) << 6);
2260                        c |= (utf[upos++] & 0x3f);
2261                        wcs[wpos++] = c;
2262                } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2263                                wpos + 1 < wcslen &&
2264                                !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2265                                !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2266                                (utf[upos] & 0xc0) == 0x80 &&
2267                                (utf[upos + 1] & 0xc0) == 0x80 &&
2268                                (utf[upos + 2] & 0xc0) == 0x80) {
2269                        /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2270                        c = ((c & 0x07) << 18);
2271                        c |= ((utf[upos++] & 0x3f) << 12);
2272                        c |= ((utf[upos++] & 0x3f) << 6);
2273                        c |= (utf[upos++] & 0x3f);
2274                        c -= 0x10000;
2275                        wcs[wpos++] = 0xd800 | (c >> 10);
2276                        wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2277                } else if (c >= 0xa0) {
2278                        /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2279                        wcs[wpos++] = c;
2280                } else {
2281                        /* invalid utf-8 byte, non-printable unicode: convert to hex */
2282                        static const char *hex = "0123456789abcdef";
2283                        wcs[wpos++] = hex[c >> 4];
2284                        if (wpos < wcslen)
2285                                wcs[wpos++] = hex[c & 0x0f];
2286                }
2287        }
2288        wcs[wpos] = 0;
2289        return wpos;
2290}
2291
2292int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2293{
2294        if (!wcs || !utf || utflen < 1) {
2295                errno = EINVAL;
2296                return -1;
2297        }
2298        utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2299        if (utflen)
2300                return utflen - 1;
2301        errno = ERANGE;
2302        return -1;
2303}
2304
2305static void setup_windows_environment(void)
2306{
2307        char *tmp = getenv("TMPDIR");
2308
2309        /* on Windows it is TMP and TEMP */
2310        if (!tmp) {
2311                if (!(tmp = getenv("TMP")))
2312                        tmp = getenv("TEMP");
2313                if (tmp) {
2314                        setenv("TMPDIR", tmp, 1);
2315                        tmp = getenv("TMPDIR");
2316                }
2317        }
2318
2319        if (tmp) {
2320                /*
2321                 * Convert all dir separators to forward slashes,
2322                 * to help shell commands called from the Git
2323                 * executable (by not mistaking the dir separators
2324                 * for escape characters).
2325                 */
2326                convert_slashes(tmp);
2327        }
2328
2329        /* simulate TERM to enable auto-color (see color.c) */
2330        if (!getenv("TERM"))
2331                setenv("TERM", "cygwin", 1);
2332}
2333
2334/*
2335 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2336 * mingw startup code, see init.c in mingw runtime).
2337 */
2338int _CRT_glob = 0;
2339
2340typedef struct {
2341        int newmode;
2342} _startupinfo;
2343
2344extern int __wgetmainargs(int *argc, wchar_t ***argv, wchar_t ***env, int glob,
2345                _startupinfo *si);
2346
2347static NORETURN void die_startup(void)
2348{
2349        fputs("fatal: not enough memory for initialization", stderr);
2350        exit(128);
2351}
2352
2353static void *malloc_startup(size_t size)
2354{
2355        void *result = malloc(size);
2356        if (!result)
2357                die_startup();
2358        return result;
2359}
2360
2361static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2362{
2363        len = xwcstoutf(buffer, wcs, len) + 1;
2364        return memcpy(malloc_startup(len), buffer, len);
2365}
2366
2367static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2368                                      DWORD desired_access, DWORD flags)
2369{
2370        DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2371        wchar_t buf[MAX_PATH];
2372        DWORD max = ARRAY_SIZE(buf);
2373        HANDLE handle;
2374        DWORD ret = GetEnvironmentVariableW(key, buf, max);
2375
2376        if (!ret || ret >= max)
2377                return;
2378
2379        /* make sure this does not leak into child processes */
2380        SetEnvironmentVariableW(key, NULL);
2381        if (!wcscmp(buf, L"off")) {
2382                close(fd);
2383                handle = GetStdHandle(std_id);
2384                if (handle != INVALID_HANDLE_VALUE)
2385                        CloseHandle(handle);
2386                return;
2387        }
2388        if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2389                handle = GetStdHandle(STD_OUTPUT_HANDLE);
2390                if (handle == INVALID_HANDLE_VALUE) {
2391                        close(fd);
2392                        handle = GetStdHandle(std_id);
2393                        if (handle != INVALID_HANDLE_VALUE)
2394                                CloseHandle(handle);
2395                } else {
2396                        int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2397                        SetStdHandle(std_id, handle);
2398                        dup2(new_fd, fd);
2399                        /* do *not* close the new_fd: that would close stdout */
2400                }
2401                return;
2402        }
2403        handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2404                             flags, NULL);
2405        if (handle != INVALID_HANDLE_VALUE) {
2406                int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2407                SetStdHandle(std_id, handle);
2408                dup2(new_fd, fd);
2409                close(new_fd);
2410        }
2411}
2412
2413static void maybe_redirect_std_handles(void)
2414{
2415        maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2416                                  GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2417        maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2418                                  GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2419        maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2420                                  GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2421}
2422
2423void mingw_startup(void)
2424{
2425        int i, maxlen, argc;
2426        char *buffer;
2427        wchar_t **wenv, **wargv;
2428        _startupinfo si;
2429
2430        maybe_redirect_std_handles();
2431
2432        /* get wide char arguments and environment */
2433        si.newmode = 0;
2434        if (__wgetmainargs(&argc, &wargv, &wenv, _CRT_glob, &si) < 0)
2435                die_startup();
2436
2437        /* determine size of argv and environ conversion buffer */
2438        maxlen = wcslen(wargv[0]);
2439        for (i = 1; i < argc; i++)
2440                maxlen = max(maxlen, wcslen(wargv[i]));
2441        for (i = 0; wenv[i]; i++)
2442                maxlen = max(maxlen, wcslen(wenv[i]));
2443
2444        /*
2445         * nedmalloc can't free CRT memory, allocate resizable environment
2446         * list. Note that xmalloc / xmemdupz etc. call getenv, so we cannot
2447         * use it while initializing the environment itself.
2448         */
2449        environ_size = i + 1;
2450        environ_alloc = alloc_nr(environ_size * sizeof(char*));
2451        environ = malloc_startup(environ_alloc);
2452
2453        /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2454        maxlen = 3 * maxlen + 1;
2455        buffer = malloc_startup(maxlen);
2456
2457        /* convert command line arguments and environment to UTF-8 */
2458        for (i = 0; i < argc; i++)
2459                __argv[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2460        for (i = 0; wenv[i]; i++)
2461                environ[i] = wcstoutfdup_startup(buffer, wenv[i], maxlen);
2462        environ[i] = NULL;
2463        free(buffer);
2464
2465        /* sort environment for O(log n) getenv / putenv */
2466        qsort(environ, i, sizeof(char*), compareenv);
2467
2468        /* fix Windows specific environment settings */
2469        setup_windows_environment();
2470
2471        unset_environment_variables = xstrdup("PERL5LIB");
2472
2473        /* initialize critical section for waitpid pinfo_t list */
2474        InitializeCriticalSection(&pinfo_cs);
2475
2476        /* set up default file mode and file modes for stdin/out/err */
2477        _fmode = _O_BINARY;
2478        _setmode(_fileno(stdin), _O_BINARY);
2479        _setmode(_fileno(stdout), _O_BINARY);
2480        _setmode(_fileno(stderr), _O_BINARY);
2481
2482        /* initialize Unicode console */
2483        winansi_init();
2484}
2485
2486int uname(struct utsname *buf)
2487{
2488        unsigned v = (unsigned)GetVersion();
2489        memset(buf, 0, sizeof(*buf));
2490        xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2491        xsnprintf(buf->release, sizeof(buf->release),
2492                 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2493        /* assuming NT variants only.. */
2494        xsnprintf(buf->version, sizeof(buf->version),
2495                  "%u", (v >> 16) & 0x7fff);
2496        return 0;
2497}