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