363f047df0a3291e0d3d311f53066d6dabf673dd
   1#ifdef __MINGW64_VERSION_MAJOR
   2#include <stdint.h>
   3#include <wchar.h>
   4typedef _sigset_t sigset_t;
   5#endif
   6#include <winsock2.h>
   7#include <ws2tcpip.h>
   8
   9#ifdef __MINGW64_VERSION_MAJOR
  10/*
  11 * In Git for Windows, we cannot rely on `uname -m` to report the correct
  12 * architecture: /usr/bin/uname.exe will report the architecture with which the
  13 * current MSYS2 runtime was built, not the architecture for which we are
  14 * currently compiling (both 32-bit and 64-bit `git.exe` is built in the 64-bit
  15 * Git for Windows SDK).
  16 */
  17#undef GIT_HOST_CPU
  18/* This was figured out by looking at `cpp -dM </dev/null`'s output */
  19#if defined(__x86_64__)
  20#define GIT_HOST_CPU "x86_64"
  21#elif defined(__i686__)
  22#define GIT_HOST_CPU "i686"
  23#else
  24#error "Unknown architecture"
  25#endif
  26#endif
  27
  28/* MinGW-w64 reports to have flockfile, but it does not actually have it. */
  29#ifdef __MINGW64_VERSION_MAJOR
  30#undef _POSIX_THREAD_SAFE_FUNCTIONS
  31#endif
  32
  33extern int mingw_core_config(const char *var, const char *value, void *cb);
  34#define platform_core_config mingw_core_config
  35
  36/*
  37 * things that are not available in header files
  38 */
  39
  40typedef int uid_t;
  41typedef int socklen_t;
  42#ifndef __MINGW64_VERSION_MAJOR
  43typedef int pid_t;
  44#define hstrerror strerror
  45#endif
  46
  47#define S_IFLNK    0120000 /* Symbolic link */
  48#define S_ISLNK(x) (((x) & S_IFMT) == S_IFLNK)
  49#define S_ISSOCK(x) 0
  50
  51#ifndef S_IRWXG
  52#define S_IRGRP 0
  53#define S_IWGRP 0
  54#define S_IXGRP 0
  55#define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP)
  56#endif
  57#ifndef S_IRWXO
  58#define S_IROTH 0
  59#define S_IWOTH 0
  60#define S_IXOTH 0
  61#define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH)
  62#endif
  63
  64#define S_ISUID 0004000
  65#define S_ISGID 0002000
  66#define S_ISVTX 0001000
  67
  68#define WIFEXITED(x) 1
  69#define WIFSIGNALED(x) 0
  70#define WEXITSTATUS(x) ((x) & 0xff)
  71#define WTERMSIG(x) SIGTERM
  72
  73#ifndef EWOULDBLOCK
  74#define EWOULDBLOCK EAGAIN
  75#endif
  76#ifndef ELOOP
  77#define ELOOP EMLINK
  78#endif
  79#define SHUT_WR SD_SEND
  80
  81#define SIGHUP 1
  82#define SIGQUIT 3
  83#define SIGKILL 9
  84#define SIGPIPE 13
  85#define SIGALRM 14
  86#define SIGCHLD 17
  87
  88#define F_GETFD 1
  89#define F_SETFD 2
  90#define FD_CLOEXEC 0x1
  91
  92#if !defined O_CLOEXEC && defined O_NOINHERIT
  93#define O_CLOEXEC       O_NOINHERIT
  94#endif
  95
  96#ifndef EAFNOSUPPORT
  97#define EAFNOSUPPORT WSAEAFNOSUPPORT
  98#endif
  99#ifndef ECONNABORTED
 100#define ECONNABORTED WSAECONNABORTED
 101#endif
 102#ifndef ENOTSOCK
 103#define ENOTSOCK WSAENOTSOCK
 104#endif
 105
 106struct passwd {
 107        char *pw_name;
 108        char *pw_gecos;
 109        char *pw_dir;
 110};
 111
 112typedef void (__cdecl *sig_handler_t)(int);
 113struct sigaction {
 114        sig_handler_t sa_handler;
 115        unsigned sa_flags;
 116};
 117#define SA_RESTART 0
 118
 119struct itimerval {
 120        struct timeval it_value, it_interval;
 121};
 122#define ITIMER_REAL 0
 123
 124struct utsname {
 125        char sysname[16];
 126        char nodename[1];
 127        char release[16];
 128        char version[16];
 129        char machine[1];
 130};
 131
 132/*
 133 * sanitize preprocessor namespace polluted by Windows headers defining
 134 * macros which collide with git local versions
 135 */
 136#undef HELP_COMMAND /* from winuser.h */
 137
 138/*
 139 * trivial stubs
 140 */
 141
 142static inline int readlink(const char *path, char *buf, size_t bufsiz)
 143{ errno = ENOSYS; return -1; }
 144static inline int symlink(const char *oldpath, const char *newpath)
 145{ errno = ENOSYS; return -1; }
 146static inline int fchmod(int fildes, mode_t mode)
 147{ errno = ENOSYS; return -1; }
 148#ifndef __MINGW64_VERSION_MAJOR
 149static inline pid_t fork(void)
 150{ errno = ENOSYS; return -1; }
 151#endif
 152static inline unsigned int alarm(unsigned int seconds)
 153{ return 0; }
 154static inline int fsync(int fd)
 155{ return _commit(fd); }
 156static inline void sync(void)
 157{}
 158static inline uid_t getuid(void)
 159{ return 1; }
 160static inline struct passwd *getpwnam(const char *name)
 161{ return NULL; }
 162static inline int fcntl(int fd, int cmd, ...)
 163{
 164        if (cmd == F_GETFD || cmd == F_SETFD)
 165                return 0;
 166        errno = EINVAL;
 167        return -1;
 168}
 169/* bash cannot reliably detect negative return codes as failure */
 170#define exit(code) exit((code) & 0xff)
 171#define sigemptyset(x) (void)0
 172static inline int sigaddset(sigset_t *set, int signum)
 173{ return 0; }
 174#define SIG_BLOCK 0
 175#define SIG_UNBLOCK 0
 176static inline int sigprocmask(int how, const sigset_t *set, sigset_t *oldset)
 177{ return 0; }
 178static inline pid_t getppid(void)
 179{ return 1; }
 180static inline pid_t getpgid(pid_t pid)
 181{ return pid == 0 ? getpid() : pid; }
 182static inline pid_t tcgetpgrp(int fd)
 183{ return getpid(); }
 184
 185/*
 186 * simple adaptors
 187 */
 188
 189int mingw_mkdir(const char *path, int mode);
 190#define mkdir mingw_mkdir
 191
 192#define WNOHANG 1
 193pid_t waitpid(pid_t pid, int *status, int options);
 194
 195#define kill mingw_kill
 196int mingw_kill(pid_t pid, int sig);
 197
 198#ifndef NO_OPENSSL
 199#include <openssl/ssl.h>
 200static inline int mingw_SSL_set_fd(SSL *ssl, int fd)
 201{
 202        return SSL_set_fd(ssl, _get_osfhandle(fd));
 203}
 204#define SSL_set_fd mingw_SSL_set_fd
 205
 206static inline int mingw_SSL_set_rfd(SSL *ssl, int fd)
 207{
 208        return SSL_set_rfd(ssl, _get_osfhandle(fd));
 209}
 210#define SSL_set_rfd mingw_SSL_set_rfd
 211
 212static inline int mingw_SSL_set_wfd(SSL *ssl, int fd)
 213{
 214        return SSL_set_wfd(ssl, _get_osfhandle(fd));
 215}
 216#define SSL_set_wfd mingw_SSL_set_wfd
 217#endif
 218
 219/*
 220 * implementations of missing functions
 221 */
 222
 223int pipe(int filedes[2]);
 224unsigned int sleep (unsigned int seconds);
 225int mkstemp(char *template);
 226int gettimeofday(struct timeval *tv, void *tz);
 227#ifndef __MINGW64_VERSION_MAJOR
 228struct tm *gmtime_r(const time_t *timep, struct tm *result);
 229struct tm *localtime_r(const time_t *timep, struct tm *result);
 230#endif
 231int getpagesize(void);  /* defined in MinGW's libgcc.a */
 232struct passwd *getpwuid(uid_t uid);
 233int setitimer(int type, struct itimerval *in, struct itimerval *out);
 234int sigaction(int sig, struct sigaction *in, struct sigaction *out);
 235int link(const char *oldpath, const char *newpath);
 236int uname(struct utsname *buf);
 237
 238/*
 239 * replacements of existing functions
 240 */
 241
 242int mingw_unlink(const char *pathname);
 243#define unlink mingw_unlink
 244
 245int mingw_rmdir(const char *path);
 246#define rmdir mingw_rmdir
 247
 248int mingw_open (const char *filename, int oflags, ...);
 249#define open mingw_open
 250
 251int mingw_fgetc(FILE *stream);
 252#define fgetc mingw_fgetc
 253
 254FILE *mingw_fopen (const char *filename, const char *otype);
 255#define fopen mingw_fopen
 256
 257FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream);
 258#define freopen mingw_freopen
 259
 260int mingw_fflush(FILE *stream);
 261#define fflush mingw_fflush
 262
 263ssize_t mingw_write(int fd, const void *buf, size_t len);
 264#define write mingw_write
 265
 266int mingw_access(const char *filename, int mode);
 267#undef access
 268#define access mingw_access
 269
 270int mingw_chdir(const char *dirname);
 271#define chdir mingw_chdir
 272
 273int mingw_chmod(const char *filename, int mode);
 274#define chmod mingw_chmod
 275
 276char *mingw_mktemp(char *template);
 277#define mktemp mingw_mktemp
 278
 279char *mingw_getcwd(char *pointer, int len);
 280#define getcwd mingw_getcwd
 281
 282#ifdef NO_UNSETENV
 283#error "NO_UNSETENV is incompatible with the Windows-specific startup code!"
 284#endif
 285
 286/*
 287 * We bind *env() routines (even the mingw_ ones) to private mingw_ versions.
 288 * These talk to the CRT using UNICODE/wchar_t, but maintain the original
 289 * narrow-char API.
 290 *
 291 * Note that the MSCRT maintains both ANSI (getenv()) and UNICODE (_wgetenv())
 292 * routines and stores both versions of each environment variable in parallel
 293 * (and secretly updates both when you set one or the other), but it uses CP_ACP
 294 * to do the conversion rather than CP_UTF8.
 295 *
 296 * Since everything in the git code base is UTF8, we define the mingw_ routines
 297 * to access the CRT using the UNICODE routines and manually convert them to
 298 * UTF8.  This also avoids round-trip problems.
 299 *
 300 * This also helps with our linkage, since "_wenviron" is publicly exported
 301 * from the CRT.  But to access "_environ" we would have to statically link
 302 * to the CRT (/MT).
 303 *
 304 * We require NO_SETENV (and let gitsetenv() call our mingw_putenv).
 305 */
 306#define getenv       mingw_getenv
 307#define putenv       mingw_putenv
 308#define unsetenv     mingw_putenv
 309char *mingw_getenv(const char *name);
 310int   mingw_putenv(const char *name);
 311
 312int mingw_gethostname(char *host, int namelen);
 313#define gethostname mingw_gethostname
 314
 315struct hostent *mingw_gethostbyname(const char *host);
 316#define gethostbyname mingw_gethostbyname
 317
 318void mingw_freeaddrinfo(struct addrinfo *res);
 319#define freeaddrinfo mingw_freeaddrinfo
 320
 321int mingw_getaddrinfo(const char *node, const char *service,
 322                      const struct addrinfo *hints, struct addrinfo **res);
 323#define getaddrinfo mingw_getaddrinfo
 324
 325int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
 326                      char *host, DWORD hostlen, char *serv, DWORD servlen,
 327                      int flags);
 328#define getnameinfo mingw_getnameinfo
 329
 330int mingw_socket(int domain, int type, int protocol);
 331#define socket mingw_socket
 332
 333int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz);
 334#define connect mingw_connect
 335
 336int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz);
 337#define bind mingw_bind
 338
 339int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen);
 340#define setsockopt mingw_setsockopt
 341
 342int mingw_shutdown(int sockfd, int how);
 343#define shutdown mingw_shutdown
 344
 345int mingw_listen(int sockfd, int backlog);
 346#define listen mingw_listen
 347
 348int mingw_accept(int sockfd, struct sockaddr *sa, socklen_t *sz);
 349#define accept mingw_accept
 350
 351int mingw_rename(const char*, const char*);
 352#define rename mingw_rename
 353
 354#if defined(USE_WIN32_MMAP) || defined(_MSC_VER)
 355int mingw_getpagesize(void);
 356#define getpagesize mingw_getpagesize
 357#endif
 358
 359struct rlimit {
 360        unsigned int rlim_cur;
 361};
 362#define RLIMIT_NOFILE 0
 363
 364static inline int getrlimit(int resource, struct rlimit *rlp)
 365{
 366        if (resource != RLIMIT_NOFILE) {
 367                errno = EINVAL;
 368                return -1;
 369        }
 370
 371        rlp->rlim_cur = 2048;
 372        return 0;
 373}
 374
 375/*
 376 * Use mingw specific stat()/lstat()/fstat() implementations on Windows,
 377 * including our own struct stat with 64 bit st_size and nanosecond-precision
 378 * file times.
 379 */
 380#ifndef __MINGW64_VERSION_MAJOR
 381#define off_t off64_t
 382#define lseek _lseeki64
 383struct timespec {
 384        time_t tv_sec;
 385        long tv_nsec;
 386};
 387#endif
 388
 389struct mingw_stat {
 390    _dev_t st_dev;
 391    _ino_t st_ino;
 392    _mode_t st_mode;
 393    short st_nlink;
 394    short st_uid;
 395    short st_gid;
 396    _dev_t st_rdev;
 397    off64_t st_size;
 398    struct timespec st_atim;
 399    struct timespec st_mtim;
 400    struct timespec st_ctim;
 401};
 402
 403#define st_atime st_atim.tv_sec
 404#define st_mtime st_mtim.tv_sec
 405#define st_ctime st_ctim.tv_sec
 406
 407#ifdef stat
 408#undef stat
 409#endif
 410#define stat mingw_stat
 411int mingw_lstat(const char *file_name, struct stat *buf);
 412int mingw_stat(const char *file_name, struct stat *buf);
 413int mingw_fstat(int fd, struct stat *buf);
 414#ifdef fstat
 415#undef fstat
 416#endif
 417#define fstat mingw_fstat
 418#ifdef lstat
 419#undef lstat
 420#endif
 421#define lstat mingw_lstat
 422
 423
 424int mingw_utime(const char *file_name, const struct utimbuf *times);
 425#define utime mingw_utime
 426size_t mingw_strftime(char *s, size_t max,
 427                   const char *format, const struct tm *tm);
 428#define strftime mingw_strftime
 429
 430pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
 431                     const char *dir,
 432                     int fhin, int fhout, int fherr);
 433int mingw_execvp(const char *cmd, char *const *argv);
 434#define execvp mingw_execvp
 435int mingw_execv(const char *cmd, char *const *argv);
 436#define execv mingw_execv
 437
 438static inline unsigned int git_ntohl(unsigned int x)
 439{ return (unsigned int)ntohl(x); }
 440#define ntohl git_ntohl
 441
 442sig_handler_t mingw_signal(int sig, sig_handler_t handler);
 443#define signal mingw_signal
 444
 445int mingw_raise(int sig);
 446#define raise mingw_raise
 447
 448/*
 449 * ANSI emulation wrappers
 450 */
 451
 452int winansi_isatty(int fd);
 453#define isatty winansi_isatty
 454
 455int winansi_dup2(int oldfd, int newfd);
 456#define dup2 winansi_dup2
 457
 458void winansi_init(void);
 459HANDLE winansi_get_osfhandle(int fd);
 460
 461/*
 462 * git specific compatibility
 463 */
 464
 465#define has_dos_drive_prefix(path) \
 466        (isalpha(*(path)) && (path)[1] == ':' ? 2 : 0)
 467int mingw_skip_dos_drive_prefix(char **path);
 468#define skip_dos_drive_prefix mingw_skip_dos_drive_prefix
 469static inline int mingw_is_dir_sep(int c)
 470{
 471        return c == '/' || c == '\\';
 472}
 473#define is_dir_sep mingw_is_dir_sep
 474static inline char *mingw_find_last_dir_sep(const char *path)
 475{
 476        char *ret = NULL;
 477        for (; *path; ++path)
 478                if (is_dir_sep(*path))
 479                        ret = (char *)path;
 480        return ret;
 481}
 482static inline void convert_slashes(char *path)
 483{
 484        for (; *path; path++)
 485                if (*path == '\\')
 486                        *path = '/';
 487}
 488#define find_last_dir_sep mingw_find_last_dir_sep
 489int mingw_offset_1st_component(const char *path);
 490#define offset_1st_component mingw_offset_1st_component
 491#define PATH_SEP ';'
 492extern char *mingw_query_user_email(void);
 493#define query_user_email mingw_query_user_email
 494#if !defined(__MINGW64_VERSION_MAJOR) && (!defined(_MSC_VER) || _MSC_VER < 1800)
 495#define PRIuMAX "I64u"
 496#define PRId64 "I64d"
 497#else
 498#include <inttypes.h>
 499#endif
 500
 501/**
 502 * Converts UTF-8 encoded string to UTF-16LE.
 503 *
 504 * To support repositories with legacy-encoded file names, invalid UTF-8 bytes
 505 * 0xa0 - 0xff are converted to corresponding printable Unicode chars \u00a0 -
 506 * \u00ff, and invalid UTF-8 bytes 0x80 - 0x9f (which would make non-printable
 507 * Unicode) are converted to hex-code.
 508 *
 509 * Lead-bytes not followed by an appropriate number of trail-bytes, over-long
 510 * encodings and 4-byte encodings > \u10ffff are detected as invalid UTF-8.
 511 *
 512 * Maximum space requirement for the target buffer is two wide chars per UTF-8
 513 * char (((strlen(utf) * 2) + 1) [* sizeof(wchar_t)]).
 514 *
 515 * The maximum space is needed only if the entire input string consists of
 516 * invalid UTF-8 bytes in range 0x80-0x9f, as per the following table:
 517 *
 518 *               |                   | UTF-8 | UTF-16 |
 519 *   Code point  |  UTF-8 sequence   | bytes | words  | ratio
 520 * --------------+-------------------+-------+--------+-------
 521 * 000000-00007f | 0-7f              |   1   |   1    |  1
 522 * 000080-0007ff | c2-df + 80-bf     |   2   |   1    |  0.5
 523 * 000800-00ffff | e0-ef + 2 * 80-bf |   3   |   1    |  0.33
 524 * 010000-10ffff | f0-f4 + 3 * 80-bf |   4   |  2 (a) |  0.5
 525 * invalid       | 80-9f             |   1   |  2 (b) |  2
 526 * invalid       | a0-ff             |   1   |   1    |  1
 527 *
 528 * (a) encoded as UTF-16 surrogate pair
 529 * (b) encoded as two hex digits
 530 *
 531 * Note that, while the UTF-8 encoding scheme can be extended to 5-byte, 6-byte
 532 * or even indefinite-byte sequences, the largest valid code point \u10ffff
 533 * encodes as only 4 UTF-8 bytes.
 534 *
 535 * Parameters:
 536 * wcs: wide char target buffer
 537 * utf: string to convert
 538 * wcslen: size of target buffer (in wchar_t's)
 539 * utflen: size of string to convert, or -1 if 0-terminated
 540 *
 541 * Returns:
 542 * length of converted string (_wcslen(wcs)), or -1 on failure
 543 *
 544 * Errors:
 545 * EINVAL: one of the input parameters is invalid (e.g. NULL)
 546 * ERANGE: the output buffer is too small
 547 */
 548int xutftowcsn(wchar_t *wcs, const char *utf, size_t wcslen, int utflen);
 549
 550/**
 551 * Simplified variant of xutftowcsn, assumes input string is \0-terminated.
 552 */
 553static inline int xutftowcs(wchar_t *wcs, const char *utf, size_t wcslen)
 554{
 555        return xutftowcsn(wcs, utf, wcslen, -1);
 556}
 557
 558/**
 559 * Simplified file system specific variant of xutftowcsn, assumes output
 560 * buffer size is MAX_PATH wide chars and input string is \0-terminated,
 561 * fails with ENAMETOOLONG if input string is too long.
 562 */
 563static inline int xutftowcs_path(wchar_t *wcs, const char *utf)
 564{
 565        int result = xutftowcsn(wcs, utf, MAX_PATH, -1);
 566        if (result < 0 && errno == ERANGE)
 567                errno = ENAMETOOLONG;
 568        return result;
 569}
 570
 571/**
 572 * Converts UTF-16LE encoded string to UTF-8.
 573 *
 574 * Maximum space requirement for the target buffer is three UTF-8 chars per
 575 * wide char ((_wcslen(wcs) * 3) + 1).
 576 *
 577 * The maximum space is needed only if the entire input string consists of
 578 * UTF-16 words in range 0x0800-0xd7ff or 0xe000-0xffff (i.e. \u0800-\uffff
 579 * modulo surrogate pairs), as per the following table:
 580 *
 581 *               |                       | UTF-16 | UTF-8 |
 582 *   Code point  |  UTF-16 sequence      | words  | bytes | ratio
 583 * --------------+-----------------------+--------+-------+-------
 584 * 000000-00007f | 0000-007f             |   1    |   1   |  1
 585 * 000080-0007ff | 0080-07ff             |   1    |   2   |  2
 586 * 000800-00ffff | 0800-d7ff / e000-ffff |   1    |   3   |  3
 587 * 010000-10ffff | d800-dbff + dc00-dfff |   2    |   4   |  2
 588 *
 589 * Note that invalid code points > 10ffff cannot be represented in UTF-16.
 590 *
 591 * Parameters:
 592 * utf: target buffer
 593 * wcs: wide string to convert
 594 * utflen: size of target buffer
 595 *
 596 * Returns:
 597 * length of converted string, or -1 on failure
 598 *
 599 * Errors:
 600 * EINVAL: one of the input parameters is invalid (e.g. NULL)
 601 * ERANGE: the output buffer is too small
 602 */
 603int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen);
 604
 605/*
 606 * A critical section used in the implementation of the spawn
 607 * functions (mingw_spawnv[p]e()) and waitpid(). Intialised in
 608 * the replacement main() macro below.
 609 */
 610extern CRITICAL_SECTION pinfo_cs;
 611
 612/*
 613 * A replacement of main() that adds win32 specific initialization.
 614 */
 615
 616void mingw_startup(void);
 617#define main(c,v) dummy_decl_mingw_main(void); \
 618static int mingw_main(c,v); \
 619int main(int argc, const char **argv) \
 620{ \
 621        mingw_startup(); \
 622        return mingw_main(__argc, (void *)__argv); \
 623} \
 624static int mingw_main(c,v)
 625
 626/*
 627 * Used by Pthread API implementation for Windows
 628 */
 629extern int err_win_to_posix(DWORD winerr);