Win32: unify environment case-sensitivity
[git/mingw/4msysgit.git] / compat / mingw.c
blob8618239a08314a4fa5c9ccdfd47c2cea89e381f2
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"
8 static const int delay[] = { 0, 1, 10, 20, 40 };
10 int err_win_to_posix(DWORD winerr)
12 int error = ENOSYS;
13 switch(winerr) {
14 case ERROR_ACCESS_DENIED: error = EACCES; break;
15 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
16 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
17 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
18 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
19 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
20 case ERROR_BAD_COMMAND: error = EIO; break;
21 case ERROR_BAD_DEVICE: error = ENODEV; break;
22 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
23 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
24 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
25 case ERROR_BAD_LENGTH: error = EINVAL; break;
26 case ERROR_BAD_PATHNAME: error = ENOENT; break;
27 case ERROR_BAD_PIPE: error = EPIPE; break;
28 case ERROR_BAD_UNIT: error = ENODEV; break;
29 case ERROR_BAD_USERNAME: error = EINVAL; break;
30 case ERROR_BROKEN_PIPE: error = EPIPE; break;
31 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
32 case ERROR_BUSY: error = EBUSY; break;
33 case ERROR_BUSY_DRIVE: error = EBUSY; break;
34 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
35 case ERROR_CANNOT_MAKE: error = EACCES; break;
36 case ERROR_CANTOPEN: error = EIO; break;
37 case ERROR_CANTREAD: error = EIO; break;
38 case ERROR_CANTWRITE: error = EIO; break;
39 case ERROR_CRC: error = EIO; break;
40 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
41 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
42 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
43 case ERROR_DIRECTORY: error = EINVAL; break;
44 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
45 case ERROR_DISK_CHANGE: error = EIO; break;
46 case ERROR_DISK_FULL: error = ENOSPC; break;
47 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
48 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
49 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
50 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
51 case ERROR_FILE_EXISTS: error = EEXIST; break;
52 case ERROR_FILE_INVALID: error = ENODEV; break;
53 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
54 case ERROR_GEN_FAILURE: error = EIO; break;
55 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
56 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
57 case ERROR_INVALID_ACCESS: error = EACCES; break;
58 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
59 case ERROR_INVALID_BLOCK: error = EFAULT; break;
60 case ERROR_INVALID_DATA: error = EINVAL; break;
61 case ERROR_INVALID_DRIVE: error = ENODEV; break;
62 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
63 case ERROR_INVALID_FLAGS: error = EINVAL; break;
64 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
65 case ERROR_INVALID_HANDLE: error = EBADF; break;
66 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
67 case ERROR_INVALID_NAME: error = EINVAL; break;
68 case ERROR_INVALID_OWNER: error = EINVAL; break;
69 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
70 case ERROR_INVALID_PASSWORD: error = EPERM; break;
71 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
72 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
73 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
74 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
75 case ERROR_IO_DEVICE: error = EIO; break;
76 case ERROR_IO_INCOMPLETE: error = EINTR; break;
77 case ERROR_LOCKED: error = EBUSY; break;
78 case ERROR_LOCK_VIOLATION: error = EACCES; break;
79 case ERROR_LOGON_FAILURE: error = EACCES; break;
80 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
81 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
82 case ERROR_MORE_DATA: error = EPIPE; break;
83 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
84 case ERROR_NOACCESS: error = EFAULT; break;
85 case ERROR_NONE_MAPPED: error = EINVAL; break;
86 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
87 case ERROR_NOT_READY: error = EAGAIN; break;
88 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
89 case ERROR_NO_DATA: error = EPIPE; break;
90 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
91 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
92 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
93 case ERROR_OPEN_FAILED: error = EIO; break;
94 case ERROR_OPEN_FILES: error = EBUSY; break;
95 case ERROR_OPERATION_ABORTED: error = EINTR; break;
96 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
97 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
98 case ERROR_PATH_BUSY: error = EBUSY; break;
99 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
100 case ERROR_PIPE_BUSY: error = EBUSY; break;
101 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
102 case ERROR_PIPE_LISTENING: error = EPIPE; break;
103 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
104 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
105 case ERROR_READ_FAULT: error = EIO; break;
106 case ERROR_SEEK: error = EIO; break;
107 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
108 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
109 case ERROR_SHARING_VIOLATION: error = EACCES; break;
110 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
111 case ERROR_SWAPERROR: error = ENOENT; break;
112 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
113 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
114 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
115 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
116 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
117 case ERROR_WRITE_FAULT: error = EIO; break;
118 case ERROR_WRITE_PROTECT: error = EROFS; break;
120 return error;
123 static inline int is_file_in_use_error(DWORD errcode)
125 switch (errcode) {
126 case ERROR_SHARING_VIOLATION:
127 case ERROR_ACCESS_DENIED:
128 return 1;
131 return 0;
134 static int read_yes_no_answer(void)
136 char answer[1024];
138 if (fgets(answer, sizeof(answer), stdin)) {
139 size_t answer_len = strlen(answer);
140 int got_full_line = 0, c;
142 /* remove the newline */
143 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
144 answer[answer_len-2] = '\0';
145 got_full_line = 1;
146 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
147 answer[answer_len-1] = '\0';
148 got_full_line = 1;
150 /* flush the buffer in case we did not get the full line */
151 if (!got_full_line)
152 while ((c = getchar()) != EOF && c != '\n')
154 } else
155 /* we could not read, return the
156 * default answer which is no */
157 return 0;
159 if (tolower(answer[0]) == 'y' && !answer[1])
160 return 1;
161 if (!strncasecmp(answer, "yes", sizeof(answer)))
162 return 1;
163 if (tolower(answer[0]) == 'n' && !answer[1])
164 return 0;
165 if (!strncasecmp(answer, "no", sizeof(answer)))
166 return 0;
168 /* did not find an answer we understand */
169 return -1;
172 static int ask_yes_no_if_possible(const char *format, ...)
174 char question[4096];
175 const char *retry_hook[] = { NULL, NULL, NULL };
176 va_list args;
178 va_start(args, format);
179 vsnprintf(question, sizeof(question), format, args);
180 va_end(args);
182 if ((retry_hook[0] = getenv("GIT_ASK_YESNO"))) {
183 retry_hook[1] = question;
184 return !run_command_v_opt(retry_hook, 0);
187 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
188 return 0;
190 while (1) {
191 int answer;
192 fprintf(stderr, "%s (y/n) ", question);
194 if ((answer = read_yes_no_answer()) >= 0)
195 return answer;
197 fprintf(stderr, "Sorry, I did not understand your answer. "
198 "Please type 'y' or 'n'\n");
202 int mingw_unlink(const char *pathname)
204 int ret, tries = 0;
205 wchar_t wpathname[MAX_PATH];
206 if (xutftowcs_path(wpathname, pathname) < 0)
207 return -1;
209 /* read-only files cannot be removed */
210 _wchmod(wpathname, 0666);
211 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
212 if (!is_file_in_use_error(GetLastError()))
213 break;
215 * We assume that some other process had the source or
216 * destination file open at the wrong moment and retry.
217 * In order to give the other process a higher chance to
218 * complete its operation, we give up our time slice now.
219 * If we have to retry again, we do sleep a bit.
221 Sleep(delay[tries]);
222 tries++;
224 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
225 ask_yes_no_if_possible("Unlink of file '%s' failed. "
226 "Should I try again?", pathname))
227 ret = _wunlink(wpathname);
228 return ret;
231 static int is_dir_empty(const wchar_t *wpath)
233 WIN32_FIND_DATAW findbuf;
234 HANDLE handle;
235 wchar_t wbuf[MAX_PATH + 2];
236 wcscpy(wbuf, wpath);
237 wcscat(wbuf, L"\\*");
238 handle = FindFirstFileW(wbuf, &findbuf);
239 if (handle == INVALID_HANDLE_VALUE)
240 return GetLastError() == ERROR_NO_MORE_FILES;
242 while (!wcscmp(findbuf.cFileName, L".") ||
243 !wcscmp(findbuf.cFileName, L".."))
244 if (!FindNextFileW(handle, &findbuf))
245 return GetLastError() == ERROR_NO_MORE_FILES;
246 FindClose(handle);
247 return 0;
250 int mingw_rmdir(const char *pathname)
252 int ret, tries = 0;
253 wchar_t wpathname[MAX_PATH];
254 if (xutftowcs_path(wpathname, pathname) < 0)
255 return -1;
257 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
258 if (!is_file_in_use_error(GetLastError()))
259 errno = err_win_to_posix(GetLastError());
260 if (errno != EACCES)
261 break;
262 if (!is_dir_empty(wpathname)) {
263 errno = ENOTEMPTY;
264 break;
267 * We assume that some other process had the source or
268 * destination file open at the wrong moment and retry.
269 * In order to give the other process a higher chance to
270 * complete its operation, we give up our time slice now.
271 * If we have to retry again, we do sleep a bit.
273 Sleep(delay[tries]);
274 tries++;
276 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
277 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
278 "Should I try again?", pathname))
279 ret = _wrmdir(wpathname);
280 return ret;
283 int mingw_mkdir(const char *path, int mode)
285 int ret;
286 wchar_t wpath[MAX_PATH];
287 if (xutftowcs_path(wpath, path) < 0)
288 return -1;
289 ret = _wmkdir(wpath);
290 return ret;
293 int mingw_open (const char *filename, int oflags, ...)
295 va_list args;
296 unsigned mode;
297 int fd;
298 wchar_t wfilename[MAX_PATH];
300 va_start(args, oflags);
301 mode = va_arg(args, int);
302 va_end(args);
304 if (filename && !strcmp(filename, "/dev/null"))
305 filename = "nul";
307 if (xutftowcs_path(wfilename, filename) < 0)
308 return -1;
309 fd = _wopen(wfilename, oflags, mode);
311 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
312 DWORD attrs = GetFileAttributesW(wfilename);
313 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
314 errno = EISDIR;
316 return fd;
319 #undef write
320 ssize_t mingw_write(int fd, const void *buf, size_t count)
323 * While write() calls to a file on a local disk are translated
324 * into WriteFile() calls with a maximum size of 64KB on Windows
325 * XP and 256KB on Vista, no such cap is placed on writes to
326 * files over the network on Windows XP. Unfortunately, there
327 * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
328 * bigger writes fail on Windows XP.
329 * So we cap to a nice 31MB here to avoid write failures over
330 * the net without changing the number of WriteFile() calls in
331 * the local case.
333 return write(fd, buf, min(count, 31 * 1024 * 1024));
336 static BOOL WINAPI ctrl_ignore(DWORD type)
338 return TRUE;
341 #undef fgetc
342 int mingw_fgetc(FILE *stream)
344 int ch;
345 if (!isatty(_fileno(stream)))
346 return fgetc(stream);
348 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
349 while (1) {
350 ch = fgetc(stream);
351 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
352 break;
354 /* Ctrl+C was pressed, simulate SIGINT and retry */
355 mingw_raise(SIGINT);
357 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
358 return ch;
361 #undef fopen
362 FILE *mingw_fopen (const char *filename, const char *otype)
364 FILE *file;
365 wchar_t wfilename[MAX_PATH], wotype[4];
366 if (filename && !strcmp(filename, "/dev/null"))
367 filename = "nul";
368 if (xutftowcs_path(wfilename, filename) < 0 ||
369 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
370 return NULL;
371 file = _wfopen(wfilename, wotype);
372 return file;
375 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
377 FILE *file;
378 wchar_t wfilename[MAX_PATH], wotype[4];
379 if (filename && !strcmp(filename, "/dev/null"))
380 filename = "nul";
381 if (xutftowcs_path(wfilename, filename) < 0 ||
382 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
383 return NULL;
384 file = _wfreopen(wfilename, wotype, stream);
385 return file;
388 #undef fflush
389 int mingw_fflush(FILE *stream)
391 int ret = fflush(stream);
394 * write() is used behind the scenes of stdio output functions.
395 * Since git code does not check for errors after each stdio write
396 * operation, it can happen that write() is called by a later
397 * stdio function even if an earlier write() call failed. In the
398 * case of a pipe whose readable end was closed, only the first
399 * call to write() reports EPIPE on Windows. Subsequent write()
400 * calls report EINVAL. It is impossible to notice whether this
401 * fflush invocation triggered such a case, therefore, we have to
402 * catch all EINVAL errors whole-sale.
404 if (ret && errno == EINVAL)
405 errno = EPIPE;
407 return ret;
410 int mingw_access(const char *filename, int mode)
412 wchar_t wfilename[MAX_PATH];
413 if (xutftowcs_path(wfilename, filename) < 0)
414 return -1;
415 /* X_OK is not supported by the MSVCRT version */
416 return _waccess(wfilename, mode & ~X_OK);
419 int mingw_chdir(const char *dirname)
421 wchar_t wdirname[MAX_PATH];
422 if (xutftowcs_path(wdirname, dirname) < 0)
423 return -1;
424 return _wchdir(wdirname);
427 int mingw_chmod(const char *filename, int mode)
429 wchar_t wfilename[MAX_PATH];
430 if (xutftowcs_path(wfilename, filename) < 0)
431 return -1;
432 return _wchmod(wfilename, mode);
436 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
437 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
439 static inline long long filetime_to_hnsec(const FILETIME *ft)
441 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
442 /* Windows to Unix Epoch conversion */
443 return winTime - 116444736000000000LL;
446 static inline time_t filetime_to_time_t(const FILETIME *ft)
448 return (time_t)(filetime_to_hnsec(ft) / 10000000);
451 /* We keep the do_lstat code in a separate function to avoid recursion.
452 * When a path ends with a slash, the stat will fail with ENOENT. In
453 * this case, we strip the trailing slashes and stat again.
455 * If follow is true then act like stat() and report on the link
456 * target. Otherwise report on the link itself.
458 static int do_lstat(int follow, const char *file_name, struct stat *buf)
460 WIN32_FILE_ATTRIBUTE_DATA fdata;
461 wchar_t wfilename[MAX_PATH];
462 if (xutftowcs_path(wfilename, file_name) < 0)
463 return -1;
465 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
466 buf->st_ino = 0;
467 buf->st_gid = 0;
468 buf->st_uid = 0;
469 buf->st_nlink = 1;
470 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
471 buf->st_size = fdata.nFileSizeLow |
472 (((off_t)fdata.nFileSizeHigh)<<32);
473 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
474 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
475 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
476 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
477 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
478 WIN32_FIND_DATAW findbuf;
479 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
480 if (handle != INVALID_HANDLE_VALUE) {
481 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
482 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
483 if (follow) {
484 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
485 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
486 } else {
487 buf->st_mode = S_IFLNK;
489 buf->st_mode |= S_IREAD;
490 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
491 buf->st_mode |= S_IWRITE;
493 FindClose(handle);
496 return 0;
498 switch (GetLastError()) {
499 case ERROR_ACCESS_DENIED:
500 case ERROR_SHARING_VIOLATION:
501 case ERROR_LOCK_VIOLATION:
502 case ERROR_SHARING_BUFFER_EXCEEDED:
503 errno = EACCES;
504 break;
505 case ERROR_BUFFER_OVERFLOW:
506 errno = ENAMETOOLONG;
507 break;
508 case ERROR_NOT_ENOUGH_MEMORY:
509 errno = ENOMEM;
510 break;
511 default:
512 errno = ENOENT;
513 break;
515 return -1;
518 /* We provide our own lstat/fstat functions, since the provided
519 * lstat/fstat functions are so slow. These stat functions are
520 * tailored for Git's usage (read: fast), and are not meant to be
521 * complete. Note that Git stat()s are redirected to mingw_lstat()
522 * too, since Windows doesn't really handle symlinks that well.
524 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
526 int namelen;
527 char alt_name[PATH_MAX];
529 if (!do_lstat(follow, file_name, buf))
530 return 0;
532 /* if file_name ended in a '/', Windows returned ENOENT;
533 * try again without trailing slashes
535 if (errno != ENOENT)
536 return -1;
538 namelen = strlen(file_name);
539 if (namelen && file_name[namelen-1] != '/')
540 return -1;
541 while (namelen && file_name[namelen-1] == '/')
542 --namelen;
543 if (!namelen || namelen >= PATH_MAX)
544 return -1;
546 memcpy(alt_name, file_name, namelen);
547 alt_name[namelen] = 0;
548 return do_lstat(follow, alt_name, buf);
551 int mingw_lstat(const char *file_name, struct stat *buf)
553 return do_stat_internal(0, file_name, buf);
555 int mingw_stat(const char *file_name, struct stat *buf)
557 return do_stat_internal(1, file_name, buf);
560 int mingw_fstat(int fd, struct stat *buf)
562 HANDLE fh = (HANDLE)_get_osfhandle(fd);
563 BY_HANDLE_FILE_INFORMATION fdata;
565 if (fh == INVALID_HANDLE_VALUE) {
566 errno = EBADF;
567 return -1;
569 /* direct non-file handles to MS's fstat() */
570 if (GetFileType(fh) != FILE_TYPE_DISK)
571 return _fstati64(fd, buf);
573 if (GetFileInformationByHandle(fh, &fdata)) {
574 buf->st_ino = 0;
575 buf->st_gid = 0;
576 buf->st_uid = 0;
577 buf->st_nlink = 1;
578 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
579 buf->st_size = fdata.nFileSizeLow |
580 (((off_t)fdata.nFileSizeHigh)<<32);
581 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
582 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
583 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
584 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
585 return 0;
587 errno = EBADF;
588 return -1;
591 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
593 long long winTime = t * 10000000LL + 116444736000000000LL;
594 ft->dwLowDateTime = winTime;
595 ft->dwHighDateTime = winTime >> 32;
598 int mingw_utime (const char *file_name, const struct utimbuf *times)
600 FILETIME mft, aft;
601 int fh, rc;
602 DWORD attrs;
603 wchar_t wfilename[MAX_PATH];
604 if (xutftowcs_path(wfilename, file_name) < 0)
605 return -1;
607 /* must have write permission */
608 attrs = GetFileAttributesW(wfilename);
609 if (attrs != INVALID_FILE_ATTRIBUTES &&
610 (attrs & FILE_ATTRIBUTE_READONLY)) {
611 /* ignore errors here; open() will report them */
612 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
615 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
616 rc = -1;
617 goto revert_attrs;
620 if (times) {
621 time_t_to_filetime(times->modtime, &mft);
622 time_t_to_filetime(times->actime, &aft);
623 } else {
624 GetSystemTimeAsFileTime(&mft);
625 aft = mft;
627 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
628 errno = EINVAL;
629 rc = -1;
630 } else
631 rc = 0;
632 close(fh);
634 revert_attrs:
635 if (attrs != INVALID_FILE_ATTRIBUTES &&
636 (attrs & FILE_ATTRIBUTE_READONLY)) {
637 /* ignore errors again */
638 SetFileAttributesW(wfilename, attrs);
640 return rc;
643 unsigned int sleep (unsigned int seconds)
645 Sleep(seconds*1000);
646 return 0;
649 char *mingw_mktemp(char *template)
651 wchar_t wtemplate[MAX_PATH];
652 if (xutftowcs_path(wtemplate, template) < 0)
653 return NULL;
654 if (!_wmktemp(wtemplate))
655 return NULL;
656 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
657 return NULL;
658 return template;
661 int mkstemp(char *template)
663 char *filename = mktemp(template);
664 if (filename == NULL)
665 return -1;
666 return open(filename, O_RDWR | O_CREAT, 0600);
669 int gettimeofday(struct timeval *tv, void *tz)
671 FILETIME ft;
672 long long hnsec;
674 GetSystemTimeAsFileTime(&ft);
675 hnsec = filetime_to_hnsec(&ft);
676 tv->tv_sec = hnsec / 10000000;
677 tv->tv_usec = (hnsec % 10000000) / 10;
678 return 0;
681 int pipe(int filedes[2])
683 HANDLE h[2];
685 /* this creates non-inheritable handles */
686 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
687 errno = err_win_to_posix(GetLastError());
688 return -1;
690 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
691 if (filedes[0] < 0) {
692 CloseHandle(h[0]);
693 CloseHandle(h[1]);
694 return -1;
696 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
697 if (filedes[0] < 0) {
698 close(filedes[0]);
699 CloseHandle(h[1]);
700 return -1;
702 return 0;
705 struct tm *gmtime_r(const time_t *timep, struct tm *result)
707 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
708 memcpy(result, gmtime(timep), sizeof(struct tm));
709 return result;
712 struct tm *localtime_r(const time_t *timep, struct tm *result)
714 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
715 memcpy(result, localtime(timep), sizeof(struct tm));
716 return result;
719 char *mingw_getcwd(char *pointer, int len)
721 int i;
722 wchar_t wpointer[MAX_PATH];
723 if (!_wgetcwd(wpointer, ARRAY_SIZE(wpointer)))
724 return NULL;
725 if (xwcstoutf(pointer, wpointer, len) < 0)
726 return NULL;
727 for (i = 0; pointer[i]; i++)
728 if (pointer[i] == '\\')
729 pointer[i] = '/';
730 return pointer;
733 #undef getenv
734 char *mingw_getenv(const char *name)
736 char *result = getenv(name);
737 if (!result && !strcmp(name, "TMPDIR")) {
738 /* on Windows it is TMP and TEMP */
739 result = getenv("TMP");
740 if (!result)
741 result = getenv("TEMP");
743 else if (!result && !strcmp(name, "TERM")) {
744 /* simulate TERM to enable auto-color (see color.c) */
745 result = "winansi";
747 return result;
751 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
752 * (Parsing C++ Command-Line Arguments)
754 static const char *quote_arg(const char *arg)
756 /* count chars to quote */
757 int len = 0, n = 0;
758 int force_quotes = 0;
759 char *q, *d;
760 const char *p = arg;
761 if (!*p) force_quotes = 1;
762 while (*p) {
763 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
764 force_quotes = 1;
765 else if (*p == '"')
766 n++;
767 else if (*p == '\\') {
768 int count = 0;
769 while (*p == '\\') {
770 count++;
771 p++;
772 len++;
774 if (*p == '"')
775 n += count*2 + 1;
776 continue;
778 len++;
779 p++;
781 if (!force_quotes && n == 0)
782 return arg;
784 /* insert \ where necessary */
785 d = q = xmalloc(len+n+3);
786 *d++ = '"';
787 while (*arg) {
788 if (*arg == '"')
789 *d++ = '\\';
790 else if (*arg == '\\') {
791 int count = 0;
792 while (*arg == '\\') {
793 count++;
794 *d++ = *arg++;
796 if (*arg == '"') {
797 while (count-- > 0)
798 *d++ = '\\';
799 *d++ = '\\';
802 *d++ = *arg++;
804 *d++ = '"';
805 *d++ = 0;
806 return q;
809 static const char *parse_interpreter(const char *cmd)
811 static char buf[100];
812 char *p, *opt;
813 int n, fd;
815 /* don't even try a .exe */
816 n = strlen(cmd);
817 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
818 return NULL;
820 fd = open(cmd, O_RDONLY);
821 if (fd < 0)
822 return NULL;
823 n = read(fd, buf, sizeof(buf)-1);
824 close(fd);
825 if (n < 4) /* at least '#!/x' and not error */
826 return NULL;
828 if (buf[0] != '#' || buf[1] != '!')
829 return NULL;
830 buf[n] = '\0';
831 p = buf + strcspn(buf, "\r\n");
832 if (!*p)
833 return NULL;
835 *p = '\0';
836 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
837 return NULL;
838 /* strip options */
839 if ((opt = strchr(p+1, ' ')))
840 *opt = '\0';
841 return p+1;
845 * Splits the PATH into parts.
847 static char **get_path_split(void)
849 char *p, **path, *envpath = getenv("PATH");
850 int i, n = 0;
852 if (!envpath || !*envpath)
853 return NULL;
855 envpath = xstrdup(envpath);
856 p = envpath;
857 while (p) {
858 char *dir = p;
859 p = strchr(p, ';');
860 if (p) *p++ = '\0';
861 if (*dir) { /* not earlier, catches series of ; */
862 ++n;
865 if (!n)
866 return NULL;
868 path = xmalloc((n+1)*sizeof(char *));
869 p = envpath;
870 i = 0;
871 do {
872 if (*p)
873 path[i++] = xstrdup(p);
874 p = p+strlen(p)+1;
875 } while (i < n);
876 path[i] = NULL;
878 free(envpath);
880 return path;
883 static void free_path_split(char **path)
885 char **p = path;
887 if (!path)
888 return;
890 while (*p)
891 free(*p++);
892 free(path);
896 * exe_only means that we only want to detect .exe files, but not scripts
897 * (which do not have an extension)
899 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
901 char path[MAX_PATH];
902 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
904 if (!isexe && access(path, F_OK) == 0)
905 return xstrdup(path);
906 path[strlen(path)-4] = '\0';
907 if ((!exe_only || isexe) && access(path, F_OK) == 0)
908 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
909 return xstrdup(path);
910 return NULL;
914 * Determines the absolute path of cmd using the split path in path.
915 * If cmd contains a slash or backslash, no lookup is performed.
917 static char *path_lookup(const char *cmd, char **path, int exe_only)
919 char *prog = NULL;
920 int len = strlen(cmd);
921 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
923 if (strchr(cmd, '/') || strchr(cmd, '\\'))
924 prog = xstrdup(cmd);
926 while (!prog && *path)
927 prog = lookup_prog(*path++, cmd, isexe, exe_only);
929 return prog;
932 static int env_compare(const void *a, const void *b)
934 char *const *ea = a;
935 char *const *eb = b;
936 return strcasecmp(*ea, *eb);
939 struct pinfo_t {
940 struct pinfo_t *next;
941 pid_t pid;
942 HANDLE proc;
944 static struct pinfo_t *pinfo = NULL;
945 CRITICAL_SECTION pinfo_cs;
947 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
948 const char *dir,
949 int prepend_cmd, int fhin, int fhout, int fherr)
951 STARTUPINFOW si;
952 PROCESS_INFORMATION pi;
953 struct strbuf args;
954 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
955 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
956 BOOL ret;
958 /* Determine whether or not we are associated to a console */
959 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
960 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
961 FILE_ATTRIBUTE_NORMAL, NULL);
962 if (cons == INVALID_HANDLE_VALUE) {
963 /* There is no console associated with this process.
964 * Since the child is a console process, Windows
965 * would normally create a console window. But
966 * since we'll be redirecting std streams, we do
967 * not need the console.
968 * It is necessary to use DETACHED_PROCESS
969 * instead of CREATE_NO_WINDOW to make ssh
970 * recognize that it has no console.
972 flags |= DETACHED_PROCESS;
973 } else {
974 /* There is already a console. If we specified
975 * DETACHED_PROCESS here, too, Windows would
976 * disassociate the child from the console.
977 * The same is true for CREATE_NO_WINDOW.
978 * Go figure!
980 CloseHandle(cons);
982 memset(&si, 0, sizeof(si));
983 si.cb = sizeof(si);
984 si.dwFlags = STARTF_USESTDHANDLES;
985 si.hStdInput = winansi_get_osfhandle(fhin);
986 si.hStdOutput = winansi_get_osfhandle(fhout);
987 si.hStdError = winansi_get_osfhandle(fherr);
989 if (xutftowcs_path(wcmd, cmd) < 0)
990 return -1;
991 if (dir && xutftowcs_path(wdir, dir) < 0)
992 return -1;
994 /* concatenate argv, quoting args as we go */
995 strbuf_init(&args, 0);
996 if (prepend_cmd) {
997 char *quoted = (char *)quote_arg(cmd);
998 strbuf_addstr(&args, quoted);
999 if (quoted != cmd)
1000 free(quoted);
1002 for (; *argv; argv++) {
1003 char *quoted = (char *)quote_arg(*argv);
1004 if (*args.buf)
1005 strbuf_addch(&args, ' ');
1006 strbuf_addstr(&args, quoted);
1007 if (quoted != *argv)
1008 free(quoted);
1011 wargs = xmalloc((2 * args.len + 1) * sizeof(wchar_t));
1012 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1013 strbuf_release(&args);
1015 if (env) {
1016 int count = 0;
1017 char **e, **sorted_env;
1018 int size = 0, wenvsz = 0, wenvpos = 0;
1020 for (e = env; *e; e++)
1021 count++;
1023 /* environment must be sorted */
1024 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
1025 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
1026 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
1028 /* create environment block from temporary environment */
1029 for (e = sorted_env; *e; e++) {
1030 size = 2 * strlen(*e) + 2; /* +2 for final \0 */
1031 ALLOC_GROW(wenvblk, (wenvpos + size) * sizeof(wchar_t), wenvsz);
1032 wenvpos += xutftowcs(&wenvblk[wenvpos], *e, size) + 1;
1034 /* add final \0 terminator */
1035 wenvblk[wenvpos] = 0;
1036 free(sorted_env);
1039 memset(&pi, 0, sizeof(pi));
1040 ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,
1041 wenvblk, dir ? wdir : NULL, &si, &pi);
1043 free(wenvblk);
1044 free(wargs);
1046 if (!ret) {
1047 errno = ENOENT;
1048 return -1;
1050 CloseHandle(pi.hThread);
1053 * The process ID is the human-readable identifier of the process
1054 * that we want to present in log and error messages. The handle
1055 * is not useful for this purpose. But we cannot close it, either,
1056 * because it is not possible to turn a process ID into a process
1057 * handle after the process terminated.
1058 * Keep the handle in a list for waitpid.
1060 EnterCriticalSection(&pinfo_cs);
1062 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1063 info->pid = pi.dwProcessId;
1064 info->proc = pi.hProcess;
1065 info->next = pinfo;
1066 pinfo = info;
1068 LeaveCriticalSection(&pinfo_cs);
1070 return (pid_t)pi.dwProcessId;
1073 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
1074 int prepend_cmd)
1076 return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
1079 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
1080 const char *dir,
1081 int fhin, int fhout, int fherr)
1083 pid_t pid;
1084 char **path = get_path_split();
1085 char *prog = path_lookup(cmd, path, 0);
1087 if (!prog) {
1088 errno = ENOENT;
1089 pid = -1;
1091 else {
1092 const char *interpr = parse_interpreter(prog);
1094 if (interpr) {
1095 const char *argv0 = argv[0];
1096 char *iprog = path_lookup(interpr, path, 1);
1097 argv[0] = prog;
1098 if (!iprog) {
1099 errno = ENOENT;
1100 pid = -1;
1102 else {
1103 pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
1104 fhin, fhout, fherr);
1105 free(iprog);
1107 argv[0] = argv0;
1109 else
1110 pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
1111 fhin, fhout, fherr);
1112 free(prog);
1114 free_path_split(path);
1115 return pid;
1118 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
1120 const char *interpr = parse_interpreter(cmd);
1121 char **path;
1122 char *prog;
1123 int pid = 0;
1125 if (!interpr)
1126 return 0;
1127 path = get_path_split();
1128 prog = path_lookup(interpr, path, 1);
1129 if (prog) {
1130 int argc = 0;
1131 const char **argv2;
1132 while (argv[argc]) argc++;
1133 argv2 = xmalloc(sizeof(*argv) * (argc+1));
1134 argv2[0] = (char *)cmd; /* full path to the script file */
1135 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1136 pid = mingw_spawnve(prog, argv2, env, 1);
1137 if (pid >= 0) {
1138 int status;
1139 if (waitpid(pid, &status, 0) < 0)
1140 status = 255;
1141 exit(status);
1143 pid = 1; /* indicate that we tried but failed */
1144 free(prog);
1145 free(argv2);
1147 free_path_split(path);
1148 return pid;
1151 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
1153 /* check if git_command is a shell script */
1154 if (!try_shell_exec(cmd, argv, (char **)env)) {
1155 int pid, status;
1157 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
1158 if (pid < 0)
1159 return;
1160 if (waitpid(pid, &status, 0) < 0)
1161 status = 255;
1162 exit(status);
1166 int mingw_execvp(const char *cmd, char *const *argv)
1168 char **path = get_path_split();
1169 char *prog = path_lookup(cmd, path, 0);
1171 if (prog) {
1172 mingw_execve(prog, argv, environ);
1173 free(prog);
1174 } else
1175 errno = ENOENT;
1177 free_path_split(path);
1178 return -1;
1181 int mingw_execv(const char *cmd, char *const *argv)
1183 mingw_execve(cmd, argv, environ);
1184 return -1;
1187 int mingw_kill(pid_t pid, int sig)
1189 if (pid > 0 && sig == SIGTERM) {
1190 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1192 if (TerminateProcess(h, -1)) {
1193 CloseHandle(h);
1194 return 0;
1197 errno = err_win_to_posix(GetLastError());
1198 CloseHandle(h);
1199 return -1;
1200 } else if (pid > 0 && sig == 0) {
1201 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1202 if (h) {
1203 CloseHandle(h);
1204 return 0;
1208 errno = EINVAL;
1209 return -1;
1212 static char **copy_environ(void)
1214 char **env;
1215 int i = 0;
1216 while (environ[i])
1217 i++;
1218 env = xmalloc((i+1)*sizeof(*env));
1219 for (i = 0; environ[i]; i++)
1220 env[i] = xstrdup(environ[i]);
1221 env[i] = NULL;
1222 return env;
1225 void free_environ(char **env)
1227 int i;
1228 for (i = 0; env[i]; i++)
1229 free(env[i]);
1230 free(env);
1233 static int lookup_env(char **env, const char *name, size_t nmln)
1235 int i;
1237 for (i = 0; env[i]; i++) {
1238 if (!strncasecmp(env[i], name, nmln) && '=' == env[i][nmln])
1239 /* matches */
1240 return i;
1242 return -1;
1246 * If name contains '=', then sets the variable, otherwise it unsets it
1248 static char **env_setenv(char **env, const char *name)
1250 char *eq = strchrnul(name, '=');
1251 int i = lookup_env(env, name, eq-name);
1253 if (i < 0) {
1254 if (*eq) {
1255 for (i = 0; env[i]; i++)
1257 env = xrealloc(env, (i+2)*sizeof(*env));
1258 env[i] = (char*) name;
1259 env[i+1] = NULL;
1262 else {
1263 free(env[i]);
1264 if (*eq)
1265 env[i] = (char*) name;
1266 else
1267 for (; env[i]; i++)
1268 env[i] = env[i+1];
1270 return env;
1274 * Copies global environ and adjusts variables as specified by vars.
1276 char **make_augmented_environ(const char *const *vars)
1278 char **env = copy_environ();
1280 while (*vars) {
1281 const char *v = *vars++;
1282 env = env_setenv(env, strchr(v, '=') ? xstrdup(v) : v);
1284 return env;
1287 int mingw_putenv(const char *namevalue)
1289 environ = env_setenv(environ, namevalue);
1290 return 0;
1294 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1295 * that service contains a numerical port, or that it is null. It
1296 * does a simple search using gethostbyname, and returns one IPv4 host
1297 * if one was found.
1299 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1300 const struct addrinfo *hints,
1301 struct addrinfo **res)
1303 struct hostent *h = NULL;
1304 struct addrinfo *ai;
1305 struct sockaddr_in *sin;
1307 if (node) {
1308 h = gethostbyname(node);
1309 if (!h)
1310 return WSAGetLastError();
1313 ai = xmalloc(sizeof(struct addrinfo));
1314 *res = ai;
1315 ai->ai_flags = 0;
1316 ai->ai_family = AF_INET;
1317 ai->ai_socktype = hints ? hints->ai_socktype : 0;
1318 switch (ai->ai_socktype) {
1319 case SOCK_STREAM:
1320 ai->ai_protocol = IPPROTO_TCP;
1321 break;
1322 case SOCK_DGRAM:
1323 ai->ai_protocol = IPPROTO_UDP;
1324 break;
1325 default:
1326 ai->ai_protocol = 0;
1327 break;
1329 ai->ai_addrlen = sizeof(struct sockaddr_in);
1330 if (hints && (hints->ai_flags & AI_CANONNAME))
1331 ai->ai_canonname = h ? xstrdup(h->h_name) : NULL;
1332 else
1333 ai->ai_canonname = NULL;
1335 sin = xmalloc(ai->ai_addrlen);
1336 memset(sin, 0, ai->ai_addrlen);
1337 sin->sin_family = AF_INET;
1338 /* Note: getaddrinfo is supposed to allow service to be a string,
1339 * which should be looked up using getservbyname. This is
1340 * currently not implemented */
1341 if (service)
1342 sin->sin_port = htons(atoi(service));
1343 if (h)
1344 sin->sin_addr = *(struct in_addr *)h->h_addr;
1345 else if (hints && (hints->ai_flags & AI_PASSIVE))
1346 sin->sin_addr.s_addr = INADDR_ANY;
1347 else
1348 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1349 ai->ai_addr = (struct sockaddr *)sin;
1350 ai->ai_next = NULL;
1351 return 0;
1354 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1356 free(res->ai_canonname);
1357 free(res->ai_addr);
1358 free(res);
1361 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1362 char *host, DWORD hostlen,
1363 char *serv, DWORD servlen, int flags)
1365 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1366 if (sa->sa_family != AF_INET)
1367 return EAI_FAMILY;
1368 if (!host && !serv)
1369 return EAI_NONAME;
1371 if (host && hostlen > 0) {
1372 struct hostent *ent = NULL;
1373 if (!(flags & NI_NUMERICHOST))
1374 ent = gethostbyaddr((const char *)&sin->sin_addr,
1375 sizeof(sin->sin_addr), AF_INET);
1377 if (ent)
1378 snprintf(host, hostlen, "%s", ent->h_name);
1379 else if (flags & NI_NAMEREQD)
1380 return EAI_NONAME;
1381 else
1382 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1385 if (serv && servlen > 0) {
1386 struct servent *ent = NULL;
1387 if (!(flags & NI_NUMERICSERV))
1388 ent = getservbyport(sin->sin_port,
1389 flags & NI_DGRAM ? "udp" : "tcp");
1391 if (ent)
1392 snprintf(serv, servlen, "%s", ent->s_name);
1393 else
1394 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1397 return 0;
1400 static HMODULE ipv6_dll = NULL;
1401 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1402 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1403 const struct addrinfo *hints,
1404 struct addrinfo **res);
1405 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1406 char *host, DWORD hostlen,
1407 char *serv, DWORD servlen, int flags);
1409 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1410 * don't need to try to load that one dynamically.
1413 static void socket_cleanup(void)
1415 WSACleanup();
1416 if (ipv6_dll)
1417 FreeLibrary(ipv6_dll);
1418 ipv6_dll = NULL;
1419 ipv6_freeaddrinfo = freeaddrinfo_stub;
1420 ipv6_getaddrinfo = getaddrinfo_stub;
1421 ipv6_getnameinfo = getnameinfo_stub;
1424 static void ensure_socket_initialization(void)
1426 WSADATA wsa;
1427 static int initialized = 0;
1428 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1429 const char **name;
1431 if (initialized)
1432 return;
1434 if (WSAStartup(MAKEWORD(2,2), &wsa))
1435 die("unable to initialize winsock subsystem, error %d",
1436 WSAGetLastError());
1438 for (name = libraries; *name; name++) {
1439 ipv6_dll = LoadLibrary(*name);
1440 if (!ipv6_dll)
1441 continue;
1443 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1444 GetProcAddress(ipv6_dll, "freeaddrinfo");
1445 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1446 const struct addrinfo *,
1447 struct addrinfo **))
1448 GetProcAddress(ipv6_dll, "getaddrinfo");
1449 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1450 socklen_t, char *, DWORD,
1451 char *, DWORD, int))
1452 GetProcAddress(ipv6_dll, "getnameinfo");
1453 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1454 FreeLibrary(ipv6_dll);
1455 ipv6_dll = NULL;
1456 } else
1457 break;
1459 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1460 ipv6_freeaddrinfo = freeaddrinfo_stub;
1461 ipv6_getaddrinfo = getaddrinfo_stub;
1462 ipv6_getnameinfo = getnameinfo_stub;
1465 atexit(socket_cleanup);
1466 initialized = 1;
1469 #undef gethostname
1470 int mingw_gethostname(char *name, int namelen)
1472 ensure_socket_initialization();
1473 return gethostname(name, namelen);
1476 #undef gethostbyname
1477 struct hostent *mingw_gethostbyname(const char *host)
1479 ensure_socket_initialization();
1480 return gethostbyname(host);
1483 void mingw_freeaddrinfo(struct addrinfo *res)
1485 ipv6_freeaddrinfo(res);
1488 int mingw_getaddrinfo(const char *node, const char *service,
1489 const struct addrinfo *hints, struct addrinfo **res)
1491 ensure_socket_initialization();
1492 return ipv6_getaddrinfo(node, service, hints, res);
1495 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1496 char *host, DWORD hostlen, char *serv, DWORD servlen,
1497 int flags)
1499 ensure_socket_initialization();
1500 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1503 int mingw_socket(int domain, int type, int protocol)
1505 int sockfd;
1506 SOCKET s;
1508 ensure_socket_initialization();
1509 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1510 if (s == INVALID_SOCKET) {
1512 * WSAGetLastError() values are regular BSD error codes
1513 * biased by WSABASEERR.
1514 * However, strerror() does not know about networking
1515 * specific errors, which are values beginning at 38 or so.
1516 * Therefore, we choose to leave the biased error code
1517 * in errno so that _if_ someone looks up the code somewhere,
1518 * then it is at least the number that are usually listed.
1520 errno = WSAGetLastError();
1521 return -1;
1523 /* convert into a file descriptor */
1524 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1525 closesocket(s);
1526 return error("unable to make a socket file descriptor: %s",
1527 strerror(errno));
1529 return sockfd;
1532 #undef connect
1533 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1535 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1536 return connect(s, sa, sz);
1539 #undef bind
1540 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1542 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1543 return bind(s, sa, sz);
1546 #undef setsockopt
1547 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1549 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1550 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1553 #undef shutdown
1554 int mingw_shutdown(int sockfd, int how)
1556 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1557 return shutdown(s, how);
1560 #undef listen
1561 int mingw_listen(int sockfd, int backlog)
1563 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1564 return listen(s, backlog);
1567 #undef accept
1568 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1570 int sockfd2;
1572 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1573 SOCKET s2 = accept(s1, sa, sz);
1575 /* convert into a file descriptor */
1576 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1577 int err = errno;
1578 closesocket(s2);
1579 return error("unable to make a socket file descriptor: %s",
1580 strerror(err));
1582 return sockfd2;
1585 #undef rename
1586 int mingw_rename(const char *pold, const char *pnew)
1588 DWORD attrs, gle;
1589 int tries = 0;
1590 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1591 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1592 return -1;
1595 * Try native rename() first to get errno right.
1596 * It is based on MoveFile(), which cannot overwrite existing files.
1598 if (!_wrename(wpold, wpnew))
1599 return 0;
1600 if (errno != EEXIST)
1601 return -1;
1602 repeat:
1603 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1604 return 0;
1605 /* TODO: translate more errors */
1606 gle = GetLastError();
1607 if (gle == ERROR_ACCESS_DENIED &&
1608 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
1609 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1610 errno = EISDIR;
1611 return -1;
1613 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1614 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1615 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1616 return 0;
1617 gle = GetLastError();
1618 /* revert file attributes on failure */
1619 SetFileAttributesW(wpnew, attrs);
1622 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1624 * We assume that some other process had the source or
1625 * destination file open at the wrong moment and retry.
1626 * In order to give the other process a higher chance to
1627 * complete its operation, we give up our time slice now.
1628 * If we have to retry again, we do sleep a bit.
1630 Sleep(delay[tries]);
1631 tries++;
1632 goto repeat;
1634 if (gle == ERROR_ACCESS_DENIED &&
1635 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1636 "Should I try again?", pold, pnew))
1637 goto repeat;
1639 errno = EACCES;
1640 return -1;
1644 * Note that this doesn't return the actual pagesize, but
1645 * the allocation granularity. If future Windows specific git code
1646 * needs the real getpagesize function, we need to find another solution.
1648 int mingw_getpagesize(void)
1650 SYSTEM_INFO si;
1651 GetSystemInfo(&si);
1652 return si.dwAllocationGranularity;
1655 struct passwd *getpwuid(int uid)
1657 static char user_name[100];
1658 static struct passwd p;
1660 DWORD len = sizeof(user_name);
1661 if (!GetUserName(user_name, &len))
1662 return NULL;
1663 p.pw_name = user_name;
1664 p.pw_gecos = "unknown";
1665 p.pw_dir = NULL;
1666 return &p;
1669 static HANDLE timer_event;
1670 static HANDLE timer_thread;
1671 static int timer_interval;
1672 static int one_shot;
1673 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
1675 /* The timer works like this:
1676 * The thread, ticktack(), is a trivial routine that most of the time
1677 * only waits to receive the signal to terminate. The main thread tells
1678 * the thread to terminate by setting the timer_event to the signalled
1679 * state.
1680 * But ticktack() interrupts the wait state after the timer's interval
1681 * length to call the signal handler.
1684 static unsigned __stdcall ticktack(void *dummy)
1686 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1687 mingw_raise(SIGALRM);
1688 if (one_shot)
1689 break;
1691 return 0;
1694 static int start_timer_thread(void)
1696 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1697 if (timer_event) {
1698 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1699 if (!timer_thread )
1700 return errno = ENOMEM,
1701 error("cannot start timer thread");
1702 } else
1703 return errno = ENOMEM,
1704 error("cannot allocate resources for timer");
1705 return 0;
1708 static void stop_timer_thread(void)
1710 if (timer_event)
1711 SetEvent(timer_event); /* tell thread to terminate */
1712 if (timer_thread) {
1713 int rc = WaitForSingleObject(timer_thread, 1000);
1714 if (rc == WAIT_TIMEOUT)
1715 error("timer thread did not terminate timely");
1716 else if (rc != WAIT_OBJECT_0)
1717 error("waiting for timer thread failed: %lu",
1718 GetLastError());
1719 CloseHandle(timer_thread);
1721 if (timer_event)
1722 CloseHandle(timer_event);
1723 timer_event = NULL;
1724 timer_thread = NULL;
1727 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1729 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1732 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1734 static const struct timeval zero;
1735 static int atexit_done;
1737 if (out != NULL)
1738 return errno = EINVAL,
1739 error("setitimer param 3 != NULL not implemented");
1740 if (!is_timeval_eq(&in->it_interval, &zero) &&
1741 !is_timeval_eq(&in->it_interval, &in->it_value))
1742 return errno = EINVAL,
1743 error("setitimer: it_interval must be zero or eq it_value");
1745 if (timer_thread)
1746 stop_timer_thread();
1748 if (is_timeval_eq(&in->it_value, &zero) &&
1749 is_timeval_eq(&in->it_interval, &zero))
1750 return 0;
1752 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1753 one_shot = is_timeval_eq(&in->it_interval, &zero);
1754 if (!atexit_done) {
1755 atexit(stop_timer_thread);
1756 atexit_done = 1;
1758 return start_timer_thread();
1761 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1763 if (sig != SIGALRM)
1764 return errno = EINVAL,
1765 error("sigaction only implemented for SIGALRM");
1766 if (out != NULL)
1767 return errno = EINVAL,
1768 error("sigaction: param 3 != NULL not implemented");
1770 timer_fn = in->sa_handler;
1771 return 0;
1774 #undef signal
1775 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1777 sig_handler_t old;
1779 switch (sig) {
1780 case SIGALRM:
1781 old = timer_fn;
1782 timer_fn = handler;
1783 break;
1785 case SIGINT:
1786 old = sigint_fn;
1787 sigint_fn = handler;
1788 break;
1790 default:
1791 return signal(sig, handler);
1794 return old;
1797 #undef raise
1798 int mingw_raise(int sig)
1800 switch (sig) {
1801 case SIGALRM:
1802 if (timer_fn == SIG_DFL) {
1803 if (isatty(STDERR_FILENO))
1804 fputs("Alarm clock\n", stderr);
1805 exit(128 + SIGALRM);
1806 } else if (timer_fn != SIG_IGN)
1807 timer_fn(SIGALRM);
1808 return 0;
1810 case SIGINT:
1811 if (sigint_fn == SIG_DFL)
1812 exit(128 + SIGINT);
1813 else if (sigint_fn != SIG_IGN)
1814 sigint_fn(SIGINT);
1815 return 0;
1817 default:
1818 return raise(sig);
1823 static const char *make_backslash_path(const char *path)
1825 static char buf[PATH_MAX + 1];
1826 char *c;
1828 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1829 die("Too long path: %.*s", 60, path);
1831 for (c = buf; *c; c++) {
1832 if (*c == '/')
1833 *c = '\\';
1835 return buf;
1838 void mingw_open_html(const char *unixpath)
1840 const char *htmlpath = make_backslash_path(unixpath);
1841 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1842 const char *, const char *, const char *, INT);
1843 T ShellExecute;
1844 HMODULE shell32;
1845 int r;
1847 shell32 = LoadLibrary("shell32.dll");
1848 if (!shell32)
1849 die("cannot load shell32.dll");
1850 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1851 if (!ShellExecute)
1852 die("cannot run browser");
1854 printf("Launching default browser to display HTML ...\n");
1855 r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1856 FreeLibrary(shell32);
1857 /* see the MSDN documentation referring to the result codes here */
1858 if (r <= 32) {
1859 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1863 int link(const char *oldpath, const char *newpath)
1865 typedef BOOL (WINAPI *T)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES);
1866 static T create_hard_link = NULL;
1867 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
1868 if (xutftowcs_path(woldpath, oldpath) < 0 ||
1869 xutftowcs_path(wnewpath, newpath) < 0)
1870 return -1;
1872 if (!create_hard_link) {
1873 create_hard_link = (T) GetProcAddress(
1874 GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
1875 if (!create_hard_link)
1876 create_hard_link = (T)-1;
1878 if (create_hard_link == (T)-1) {
1879 errno = ENOSYS;
1880 return -1;
1882 if (!create_hard_link(wnewpath, woldpath, NULL)) {
1883 errno = err_win_to_posix(GetLastError());
1884 return -1;
1886 return 0;
1889 pid_t waitpid(pid_t pid, int *status, int options)
1891 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
1892 FALSE, pid);
1893 if (!h) {
1894 errno = ECHILD;
1895 return -1;
1898 if (pid > 0 && options & WNOHANG) {
1899 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
1900 CloseHandle(h);
1901 return 0;
1903 options &= ~WNOHANG;
1906 if (options == 0) {
1907 struct pinfo_t **ppinfo;
1908 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
1909 CloseHandle(h);
1910 return 0;
1913 if (status)
1914 GetExitCodeProcess(h, (LPDWORD)status);
1916 EnterCriticalSection(&pinfo_cs);
1918 ppinfo = &pinfo;
1919 while (*ppinfo) {
1920 struct pinfo_t *info = *ppinfo;
1921 if (info->pid == pid) {
1922 CloseHandle(info->proc);
1923 *ppinfo = info->next;
1924 free(info);
1925 break;
1927 ppinfo = &info->next;
1930 LeaveCriticalSection(&pinfo_cs);
1932 CloseHandle(h);
1933 return pid;
1935 CloseHandle(h);
1937 errno = EINVAL;
1938 return -1;
1941 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
1943 int upos = 0, wpos = 0;
1944 const unsigned char *utf = (const unsigned char*) utfs;
1945 if (!utf || !wcs || wcslen < 1) {
1946 errno = EINVAL;
1947 return -1;
1949 /* reserve space for \0 */
1950 wcslen--;
1951 if (utflen < 0)
1952 utflen = INT_MAX;
1954 while (upos < utflen) {
1955 int c = utf[upos++] & 0xff;
1956 if (utflen == INT_MAX && c == 0)
1957 break;
1959 if (wpos >= wcslen) {
1960 wcs[wpos] = 0;
1961 errno = ERANGE;
1962 return -1;
1965 if (c < 0x80) {
1966 /* ASCII */
1967 wcs[wpos++] = c;
1968 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
1969 (utf[upos] & 0xc0) == 0x80) {
1970 /* 2-byte utf-8 */
1971 c = ((c & 0x1f) << 6);
1972 c |= (utf[upos++] & 0x3f);
1973 wcs[wpos++] = c;
1974 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
1975 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
1976 (utf[upos] & 0xc0) == 0x80 &&
1977 (utf[upos + 1] & 0xc0) == 0x80) {
1978 /* 3-byte utf-8 */
1979 c = ((c & 0x0f) << 12);
1980 c |= ((utf[upos++] & 0x3f) << 6);
1981 c |= (utf[upos++] & 0x3f);
1982 wcs[wpos++] = c;
1983 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
1984 wpos + 1 < wcslen &&
1985 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
1986 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
1987 (utf[upos] & 0xc0) == 0x80 &&
1988 (utf[upos + 1] & 0xc0) == 0x80 &&
1989 (utf[upos + 2] & 0xc0) == 0x80) {
1990 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
1991 c = ((c & 0x07) << 18);
1992 c |= ((utf[upos++] & 0x3f) << 12);
1993 c |= ((utf[upos++] & 0x3f) << 6);
1994 c |= (utf[upos++] & 0x3f);
1995 c -= 0x10000;
1996 wcs[wpos++] = 0xd800 | (c >> 10);
1997 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
1998 } else if (c >= 0xa0) {
1999 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2000 wcs[wpos++] = c;
2001 } else {
2002 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2003 static const char *hex = "0123456789abcdef";
2004 wcs[wpos++] = hex[c >> 4];
2005 if (wpos < wcslen)
2006 wcs[wpos++] = hex[c & 0x0f];
2009 wcs[wpos] = 0;
2010 return wpos;
2013 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2015 if (!wcs || !utf || utflen < 1) {
2016 errno = EINVAL;
2017 return -1;
2019 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2020 if (utflen)
2021 return utflen - 1;
2022 errno = ERANGE;
2023 return -1;
2027 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2028 * mingw startup code, see init.c in mingw runtime).
2030 int _CRT_glob = 0;
2032 typedef struct {
2033 int newmode;
2034 } _startupinfo;
2036 extern int __wgetmainargs(int *argc, wchar_t ***argv, wchar_t ***env, int glob,
2037 _startupinfo *si);
2039 void mingw_startup()
2041 int i, len, maxlen, argc;
2042 char *buffer;
2043 wchar_t **wenv, **wargv;
2044 _startupinfo si;
2046 /* get wide char arguments and environment */
2047 si.newmode = 0;
2048 __wgetmainargs(&argc, &wargv, &wenv, _CRT_glob, &si);
2050 /* determine size of argv and environ conversion buffer */
2051 maxlen = wcslen(_wpgmptr);
2052 for (i = 1; i < argc; i++)
2053 maxlen = max(maxlen, wcslen(wargv[i]));
2054 for (i = 0; wenv[i]; i++)
2055 maxlen = max(maxlen, wcslen(wenv[i]));
2057 /* nedmalloc can't free CRT memory, allocate resizable environment list */
2058 environ = xcalloc(i + 1, sizeof(char*));
2060 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2061 maxlen = 3 * maxlen + 1;
2062 buffer = xmalloc(maxlen);
2064 /* convert command line arguments and environment to UTF-8 */
2065 len = xwcstoutf(buffer, _wpgmptr, maxlen);
2066 __argv[0] = xmemdupz(buffer, len);
2067 for (i = 1; i < argc; i++) {
2068 len = xwcstoutf(buffer, wargv[i], maxlen);
2069 __argv[i] = xmemdupz(buffer, len);
2071 for (i = 0; wenv[i]; i++) {
2072 len = xwcstoutf(buffer, wenv[i], maxlen);
2073 environ[i] = xmemdupz(buffer, len);
2075 free(buffer);
2077 /* initialize critical section for waitpid pinfo_t list */
2078 InitializeCriticalSection(&pinfo_cs);
2080 /* set up default file mode and file modes for stdin/out/err */
2081 _fmode = _O_BINARY;
2082 _setmode(_fileno(stdin), _O_BINARY);
2083 _setmode(_fileno(stdout), _O_BINARY);
2084 _setmode(_fileno(stderr), _O_BINARY);
2086 /* initialize Unicode console */
2087 winansi_init();