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