core.hidedotfiles: hide '.git' dir by default
[git/mingw/4msysgit.git] / compat / mingw.c
blobd2c17c70248ab8ebf6617f7574152d2c94aaf8b7
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"
9 static const int delay[] = { 0, 1, 10, 20, 40 };
10 unsigned int _CRT_fmode = _O_BINARY;
12 int err_win_to_posix(DWORD winerr)
14 int error = ENOSYS;
15 switch(winerr) {
16 case ERROR_ACCESS_DENIED: error = EACCES; break;
17 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
18 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
19 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
20 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
21 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
22 case ERROR_BAD_COMMAND: error = EIO; break;
23 case ERROR_BAD_DEVICE: error = ENODEV; break;
24 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
25 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
26 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
27 case ERROR_BAD_LENGTH: error = EINVAL; break;
28 case ERROR_BAD_PATHNAME: error = ENOENT; break;
29 case ERROR_BAD_PIPE: error = EPIPE; break;
30 case ERROR_BAD_UNIT: error = ENODEV; break;
31 case ERROR_BAD_USERNAME: error = EINVAL; break;
32 case ERROR_BROKEN_PIPE: error = EPIPE; break;
33 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
34 case ERROR_BUSY: error = EBUSY; break;
35 case ERROR_BUSY_DRIVE: error = EBUSY; break;
36 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
37 case ERROR_CANNOT_MAKE: error = EACCES; break;
38 case ERROR_CANTOPEN: error = EIO; break;
39 case ERROR_CANTREAD: error = EIO; break;
40 case ERROR_CANTWRITE: error = EIO; break;
41 case ERROR_CRC: error = EIO; break;
42 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
43 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
44 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
45 case ERROR_DIRECTORY: error = EINVAL; break;
46 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
47 case ERROR_DISK_CHANGE: error = EIO; break;
48 case ERROR_DISK_FULL: error = ENOSPC; break;
49 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
50 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
51 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
52 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
53 case ERROR_FILE_EXISTS: error = EEXIST; break;
54 case ERROR_FILE_INVALID: error = ENODEV; break;
55 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
56 case ERROR_GEN_FAILURE: error = EIO; break;
57 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
58 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
59 case ERROR_INVALID_ACCESS: error = EACCES; break;
60 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
61 case ERROR_INVALID_BLOCK: error = EFAULT; break;
62 case ERROR_INVALID_DATA: error = EINVAL; break;
63 case ERROR_INVALID_DRIVE: error = ENODEV; break;
64 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
65 case ERROR_INVALID_FLAGS: error = EINVAL; break;
66 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
67 case ERROR_INVALID_HANDLE: error = EBADF; break;
68 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
69 case ERROR_INVALID_NAME: error = EINVAL; break;
70 case ERROR_INVALID_OWNER: error = EINVAL; break;
71 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
72 case ERROR_INVALID_PASSWORD: error = EPERM; break;
73 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
74 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
75 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
76 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
77 case ERROR_IO_DEVICE: error = EIO; break;
78 case ERROR_IO_INCOMPLETE: error = EINTR; break;
79 case ERROR_LOCKED: error = EBUSY; break;
80 case ERROR_LOCK_VIOLATION: error = EACCES; break;
81 case ERROR_LOGON_FAILURE: error = EACCES; break;
82 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
83 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
84 case ERROR_MORE_DATA: error = EPIPE; break;
85 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
86 case ERROR_NOACCESS: error = EFAULT; break;
87 case ERROR_NONE_MAPPED: error = EINVAL; break;
88 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
89 case ERROR_NOT_READY: error = EAGAIN; break;
90 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
91 case ERROR_NO_DATA: error = EPIPE; break;
92 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
93 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
94 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
95 case ERROR_OPEN_FAILED: error = EIO; break;
96 case ERROR_OPEN_FILES: error = EBUSY; break;
97 case ERROR_OPERATION_ABORTED: error = EINTR; break;
98 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
99 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
100 case ERROR_PATH_BUSY: error = EBUSY; break;
101 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
102 case ERROR_PIPE_BUSY: error = EBUSY; break;
103 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
104 case ERROR_PIPE_LISTENING: error = EPIPE; break;
105 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
106 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
107 case ERROR_READ_FAULT: error = EIO; break;
108 case ERROR_SEEK: error = EIO; break;
109 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
110 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
111 case ERROR_SHARING_VIOLATION: error = EACCES; break;
112 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
113 case ERROR_SWAPERROR: error = ENOENT; break;
114 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
115 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
116 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
117 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
118 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
119 case ERROR_WRITE_FAULT: error = EIO; break;
120 case ERROR_WRITE_PROTECT: error = EROFS; break;
122 return error;
125 static inline int is_file_in_use_error(DWORD errcode)
127 switch (errcode) {
128 case ERROR_SHARING_VIOLATION:
129 case ERROR_ACCESS_DENIED:
130 return 1;
133 return 0;
136 static int read_yes_no_answer(void)
138 char answer[1024];
140 if (fgets(answer, sizeof(answer), stdin)) {
141 size_t answer_len = strlen(answer);
142 int got_full_line = 0, c;
144 /* remove the newline */
145 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
146 answer[answer_len-2] = '\0';
147 got_full_line = 1;
148 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
149 answer[answer_len-1] = '\0';
150 got_full_line = 1;
152 /* flush the buffer in case we did not get the full line */
153 if (!got_full_line)
154 while ((c = getchar()) != EOF && c != '\n')
156 } else
157 /* we could not read, return the
158 * default answer which is no */
159 return 0;
161 if (tolower(answer[0]) == 'y' && !answer[1])
162 return 1;
163 if (!strncasecmp(answer, "yes", sizeof(answer)))
164 return 1;
165 if (tolower(answer[0]) == 'n' && !answer[1])
166 return 0;
167 if (!strncasecmp(answer, "no", sizeof(answer)))
168 return 0;
170 /* did not find an answer we understand */
171 return -1;
174 static int ask_yes_no_if_possible(const char *format, ...)
176 char question[4096];
177 const char *retry_hook[] = { NULL, NULL, NULL };
178 va_list args;
180 va_start(args, format);
181 vsnprintf(question, sizeof(question), format, args);
182 va_end(args);
184 if ((retry_hook[0] = getenv("GIT_ASK_YESNO"))) {
185 retry_hook[1] = question;
186 return !run_command_v_opt(retry_hook, 0);
189 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
190 return 0;
192 while (1) {
193 int answer;
194 fprintf(stderr, "%s (y/n) ", question);
196 if ((answer = read_yes_no_answer()) >= 0)
197 return answer;
199 fprintf(stderr, "Sorry, I did not understand your answer. "
200 "Please type 'y' or 'n'\n");
204 int mingw_unlink(const char *pathname)
206 int ret, tries = 0;
207 wchar_t wpathname[MAX_PATH];
208 if (xutftowcs_path(wpathname, pathname) < 0)
209 return -1;
211 /* read-only files cannot be removed */
212 _wchmod(wpathname, 0666);
213 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
214 if (!is_file_in_use_error(GetLastError()))
215 break;
217 * We assume that some other process had the source or
218 * destination file open at the wrong moment and retry.
219 * In order to give the other process a higher chance to
220 * complete its operation, we give up our time slice now.
221 * If we have to retry again, we do sleep a bit.
223 Sleep(delay[tries]);
224 tries++;
226 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
227 ask_yes_no_if_possible("Unlink of file '%s' failed. "
228 "Should I try again?", pathname))
229 ret = _wunlink(wpathname);
230 return ret;
233 static int is_dir_empty(const wchar_t *wpath)
235 WIN32_FIND_DATAW findbuf;
236 HANDLE handle;
237 wchar_t wbuf[MAX_PATH + 2];
238 wcscpy(wbuf, wpath);
239 wcscat(wbuf, L"\\*");
240 handle = FindFirstFileW(wbuf, &findbuf);
241 if (handle == INVALID_HANDLE_VALUE)
242 return GetLastError() == ERROR_NO_MORE_FILES;
244 while (!wcscmp(findbuf.cFileName, L".") ||
245 !wcscmp(findbuf.cFileName, L".."))
246 if (!FindNextFileW(handle, &findbuf)) {
247 DWORD err = GetLastError();
248 FindClose(handle);
249 return err == ERROR_NO_MORE_FILES;
251 FindClose(handle);
252 return 0;
255 int mingw_rmdir(const char *pathname)
257 int ret, tries = 0;
258 wchar_t wpathname[MAX_PATH];
259 if (xutftowcs_path(wpathname, pathname) < 0)
260 return -1;
262 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
263 if (!is_file_in_use_error(GetLastError()))
264 errno = err_win_to_posix(GetLastError());
265 if (errno != EACCES)
266 break;
267 if (!is_dir_empty(wpathname)) {
268 errno = ENOTEMPTY;
269 break;
272 * We assume that some other process had the source or
273 * destination file open at the wrong moment and retry.
274 * In order to give the other process a higher chance to
275 * complete its operation, we give up our time slice now.
276 * If we have to retry again, we do sleep a bit.
278 Sleep(delay[tries]);
279 tries++;
281 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
282 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
283 "Should I try again?", pathname))
284 ret = _wrmdir(wpathname);
285 return ret;
288 static int make_hidden(const wchar_t *path)
290 DWORD attribs = GetFileAttributesW(path);
291 if (SetFileAttributesW(path, FILE_ATTRIBUTE_HIDDEN | attribs))
292 return 0;
293 errno = err_win_to_posix(GetLastError());
294 return -1;
297 void mingw_mark_as_git_dir(const char *dir)
299 wchar_t wdir[MAX_PATH];
300 if (hide_dotfiles != HIDE_DOTFILES_FALSE && !is_bare_repository())
301 if (xutftowcs_path(wdir, dir) < 0 || make_hidden(wdir))
302 warning("Failed to make '%s' hidden", dir);
305 int mingw_mkdir(const char *path, int mode)
307 int ret;
308 wchar_t wpath[MAX_PATH];
309 if (xutftowcs_path(wpath, path) < 0)
310 return -1;
311 ret = _wmkdir(wpath);
312 if (!ret && hide_dotfiles == HIDE_DOTFILES_TRUE) {
314 * In Windows a file or dir starting with a dot is not
315 * automatically hidden. So lets mark it as hidden when
316 * such a directory is created.
318 const char *start = basename((char*)path);
319 if (*start == '.')
320 return make_hidden(wpath);
322 return ret;
325 int mingw_open (const char *filename, int oflags, ...)
327 va_list args;
328 unsigned mode;
329 int fd;
330 wchar_t wfilename[MAX_PATH];
332 va_start(args, oflags);
333 mode = va_arg(args, int);
334 va_end(args);
336 if (filename && !strcmp(filename, "/dev/null"))
337 filename = "nul";
339 if (xutftowcs_path(wfilename, filename) < 0)
340 return -1;
341 fd = _wopen(wfilename, oflags, mode);
343 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
344 DWORD attrs = GetFileAttributesW(wfilename);
345 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
346 errno = EISDIR;
348 if ((oflags & O_CREAT) && fd >= 0 &&
349 hide_dotfiles == HIDE_DOTFILES_TRUE) {
351 * In Windows a file or dir starting with a dot is not
352 * automatically hidden. So lets mark it as hidden when
353 * such a file is created.
355 const char *start = basename((char*)filename);
356 if (*start == '.' && make_hidden(wfilename))
357 warning("Could not mark '%s' as hidden.", filename);
359 return fd;
362 static BOOL WINAPI ctrl_ignore(DWORD type)
364 return TRUE;
367 #undef fgetc
368 int mingw_fgetc(FILE *stream)
370 int ch;
371 if (!isatty(_fileno(stream)))
372 return fgetc(stream);
374 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
375 while (1) {
376 ch = fgetc(stream);
377 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
378 break;
380 /* Ctrl+C was pressed, simulate SIGINT and retry */
381 mingw_raise(SIGINT);
383 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
384 return ch;
387 #undef fopen
388 FILE *mingw_fopen (const char *filename, const char *otype)
390 int hide = 0;
391 FILE *file;
392 wchar_t wfilename[MAX_PATH], wotype[4];
393 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
394 basename((char*)filename)[0] == '.')
395 hide = access(filename, F_OK);
396 if (filename && !strcmp(filename, "/dev/null"))
397 filename = "nul";
398 if (xutftowcs_path(wfilename, filename) < 0 ||
399 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
400 return NULL;
401 file = _wfopen(wfilename, wotype);
402 if (file && hide && make_hidden(wfilename))
403 warning("Could not mark '%s' as hidden.", filename);
404 return file;
407 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
409 int hide = 0;
410 FILE *file;
411 wchar_t wfilename[MAX_PATH], wotype[4];
412 if (hide_dotfiles == HIDE_DOTFILES_TRUE &&
413 basename((char*)filename)[0] == '.')
414 hide = access(filename, F_OK);
415 if (filename && !strcmp(filename, "/dev/null"))
416 filename = "nul";
417 if (xutftowcs_path(wfilename, filename) < 0 ||
418 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
419 return NULL;
420 file = _wfreopen(wfilename, wotype, stream);
421 if (file && hide && make_hidden(wfilename))
422 warning("Could not mark '%s' as hidden.", filename);
423 return file;
426 #undef fflush
427 int mingw_fflush(FILE *stream)
429 int ret = fflush(stream);
432 * write() is used behind the scenes of stdio output functions.
433 * Since git code does not check for errors after each stdio write
434 * operation, it can happen that write() is called by a later
435 * stdio function even if an earlier write() call failed. In the
436 * case of a pipe whose readable end was closed, only the first
437 * call to write() reports EPIPE on Windows. Subsequent write()
438 * calls report EINVAL. It is impossible to notice whether this
439 * fflush invocation triggered such a case, therefore, we have to
440 * catch all EINVAL errors whole-sale.
442 if (ret && errno == EINVAL)
443 errno = EPIPE;
445 return ret;
448 int mingw_access(const char *filename, int mode)
450 wchar_t wfilename[MAX_PATH];
451 if (xutftowcs_path(wfilename, filename) < 0)
452 return -1;
453 /* X_OK is not supported by the MSVCRT version */
454 return _waccess(wfilename, mode & ~X_OK);
457 int mingw_chdir(const char *dirname)
459 wchar_t wdirname[MAX_PATH];
460 if (xutftowcs_path(wdirname, dirname) < 0)
461 return -1;
462 return _wchdir(wdirname);
465 int mingw_chmod(const char *filename, int mode)
467 wchar_t wfilename[MAX_PATH];
468 if (xutftowcs_path(wfilename, filename) < 0)
469 return -1;
470 return _wchmod(wfilename, mode);
474 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
475 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
477 static inline long long filetime_to_hnsec(const FILETIME *ft)
479 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
480 /* Windows to Unix Epoch conversion */
481 return winTime - 116444736000000000LL;
484 static inline time_t filetime_to_time_t(const FILETIME *ft)
486 return (time_t)(filetime_to_hnsec(ft) / 10000000);
489 /* We keep the do_lstat code in a separate function to avoid recursion.
490 * When a path ends with a slash, the stat will fail with ENOENT. In
491 * this case, we strip the trailing slashes and stat again.
493 * If follow is true then act like stat() and report on the link
494 * target. Otherwise report on the link itself.
496 static int do_lstat(int follow, const char *file_name, struct stat *buf)
498 WIN32_FILE_ATTRIBUTE_DATA fdata;
499 wchar_t wfilename[MAX_PATH];
500 if (xutftowcs_path(wfilename, file_name) < 0)
501 return -1;
503 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
504 buf->st_ino = 0;
505 buf->st_gid = 0;
506 buf->st_uid = 0;
507 buf->st_nlink = 1;
508 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
509 buf->st_size = fdata.nFileSizeLow |
510 (((off_t)fdata.nFileSizeHigh)<<32);
511 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
512 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
513 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
514 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
515 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
516 WIN32_FIND_DATAW findbuf;
517 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
518 if (handle != INVALID_HANDLE_VALUE) {
519 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
520 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
521 if (follow) {
522 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
523 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
524 } else {
525 buf->st_mode = S_IFLNK;
527 buf->st_mode |= S_IREAD;
528 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
529 buf->st_mode |= S_IWRITE;
531 FindClose(handle);
534 return 0;
536 switch (GetLastError()) {
537 case ERROR_ACCESS_DENIED:
538 case ERROR_SHARING_VIOLATION:
539 case ERROR_LOCK_VIOLATION:
540 case ERROR_SHARING_BUFFER_EXCEEDED:
541 errno = EACCES;
542 break;
543 case ERROR_BUFFER_OVERFLOW:
544 errno = ENAMETOOLONG;
545 break;
546 case ERROR_NOT_ENOUGH_MEMORY:
547 errno = ENOMEM;
548 break;
549 default:
550 errno = ENOENT;
551 break;
553 return -1;
556 /* We provide our own lstat/fstat functions, since the provided
557 * lstat/fstat functions are so slow. These stat functions are
558 * tailored for Git's usage (read: fast), and are not meant to be
559 * complete. Note that Git stat()s are redirected to mingw_lstat()
560 * too, since Windows doesn't really handle symlinks that well.
562 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
564 int namelen;
565 char alt_name[PATH_MAX];
567 if (!do_lstat(follow, file_name, buf))
568 return 0;
570 /* if file_name ended in a '/', Windows returned ENOENT;
571 * try again without trailing slashes
573 if (errno != ENOENT)
574 return -1;
576 namelen = strlen(file_name);
577 if (namelen && file_name[namelen-1] != '/')
578 return -1;
579 while (namelen && file_name[namelen-1] == '/')
580 --namelen;
581 if (!namelen || namelen >= PATH_MAX)
582 return -1;
584 memcpy(alt_name, file_name, namelen);
585 alt_name[namelen] = 0;
586 return do_lstat(follow, alt_name, buf);
589 int mingw_lstat(const char *file_name, struct stat *buf)
591 return do_stat_internal(0, file_name, buf);
593 int mingw_stat(const char *file_name, struct stat *buf)
595 return do_stat_internal(1, file_name, buf);
598 int mingw_fstat(int fd, struct stat *buf)
600 HANDLE fh = (HANDLE)_get_osfhandle(fd);
601 BY_HANDLE_FILE_INFORMATION fdata;
603 if (fh == INVALID_HANDLE_VALUE) {
604 errno = EBADF;
605 return -1;
607 /* direct non-file handles to MS's fstat() */
608 if (GetFileType(fh) != FILE_TYPE_DISK)
609 return _fstati64(fd, buf);
611 if (GetFileInformationByHandle(fh, &fdata)) {
612 buf->st_ino = 0;
613 buf->st_gid = 0;
614 buf->st_uid = 0;
615 buf->st_nlink = 1;
616 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
617 buf->st_size = fdata.nFileSizeLow |
618 (((off_t)fdata.nFileSizeHigh)<<32);
619 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
620 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
621 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
622 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
623 return 0;
625 errno = EBADF;
626 return -1;
629 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
631 long long winTime = t * 10000000LL + 116444736000000000LL;
632 ft->dwLowDateTime = winTime;
633 ft->dwHighDateTime = winTime >> 32;
636 int mingw_utime (const char *file_name, const struct utimbuf *times)
638 FILETIME mft, aft;
639 int fh, rc;
640 DWORD attrs;
641 wchar_t wfilename[MAX_PATH];
642 if (xutftowcs_path(wfilename, file_name) < 0)
643 return -1;
645 /* must have write permission */
646 attrs = GetFileAttributesW(wfilename);
647 if (attrs != INVALID_FILE_ATTRIBUTES &&
648 (attrs & FILE_ATTRIBUTE_READONLY)) {
649 /* ignore errors here; open() will report them */
650 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
653 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
654 rc = -1;
655 goto revert_attrs;
658 if (times) {
659 time_t_to_filetime(times->modtime, &mft);
660 time_t_to_filetime(times->actime, &aft);
661 } else {
662 GetSystemTimeAsFileTime(&mft);
663 aft = mft;
665 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
666 errno = EINVAL;
667 rc = -1;
668 } else
669 rc = 0;
670 close(fh);
672 revert_attrs:
673 if (attrs != INVALID_FILE_ATTRIBUTES &&
674 (attrs & FILE_ATTRIBUTE_READONLY)) {
675 /* ignore errors again */
676 SetFileAttributesW(wfilename, attrs);
678 return rc;
681 unsigned int sleep (unsigned int seconds)
683 Sleep(seconds*1000);
684 return 0;
687 char *mingw_mktemp(char *template)
689 wchar_t wtemplate[MAX_PATH];
690 if (xutftowcs_path(wtemplate, template) < 0)
691 return NULL;
692 if (!_wmktemp(wtemplate))
693 return NULL;
694 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
695 return NULL;
696 return template;
699 int mkstemp(char *template)
701 char *filename = mktemp(template);
702 if (filename == NULL)
703 return -1;
704 return open(filename, O_RDWR | O_CREAT, 0600);
707 int gettimeofday(struct timeval *tv, void *tz)
709 FILETIME ft;
710 long long hnsec;
712 GetSystemTimeAsFileTime(&ft);
713 hnsec = filetime_to_hnsec(&ft);
714 tv->tv_sec = hnsec / 10000000;
715 tv->tv_usec = (hnsec % 10000000) / 10;
716 return 0;
719 int pipe(int filedes[2])
721 HANDLE h[2];
723 /* this creates non-inheritable handles */
724 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
725 errno = err_win_to_posix(GetLastError());
726 return -1;
728 filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
729 if (filedes[0] < 0) {
730 CloseHandle(h[0]);
731 CloseHandle(h[1]);
732 return -1;
734 filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
735 if (filedes[0] < 0) {
736 close(filedes[0]);
737 CloseHandle(h[1]);
738 return -1;
740 return 0;
743 struct tm *gmtime_r(const time_t *timep, struct tm *result)
745 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
746 memcpy(result, gmtime(timep), sizeof(struct tm));
747 return result;
750 struct tm *localtime_r(const time_t *timep, struct tm *result)
752 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
753 memcpy(result, localtime(timep), sizeof(struct tm));
754 return result;
757 char *mingw_getcwd(char *pointer, int len)
759 int i;
760 wchar_t wpointer[MAX_PATH];
761 if (!_wgetcwd(wpointer, ARRAY_SIZE(wpointer)))
762 return NULL;
763 if (xwcstoutf(pointer, wpointer, len) < 0)
764 return NULL;
765 for (i = 0; pointer[i]; i++)
766 if (pointer[i] == '\\')
767 pointer[i] = '/';
768 return pointer;
772 * Compare environment entries by key (i.e. stopping at '=' or '\0').
774 static int compareenv(const void *v1, const void *v2)
776 const char *e1 = *(const char**)v1;
777 const char *e2 = *(const char**)v2;
779 for (;;) {
780 int c1 = *e1++;
781 int c2 = *e2++;
782 c1 = (c1 == '=') ? 0 : tolower(c1);
783 c2 = (c2 == '=') ? 0 : tolower(c2);
784 if (c1 > c2)
785 return 1;
786 if (c1 < c2)
787 return -1;
788 if (c1 == 0)
789 return 0;
793 static int bsearchenv(char **env, const char *name, size_t size)
795 unsigned low = 0, high = size;
796 while (low < high) {
797 unsigned mid = low + ((high - low) >> 1);
798 int cmp = compareenv(&env[mid], &name);
799 if (cmp < 0)
800 low = mid + 1;
801 else if (cmp > 0)
802 high = mid;
803 else
804 return mid;
806 return ~low; /* not found, return 1's complement of insert position */
810 * If name contains '=', then sets the variable, otherwise it unsets it
811 * Size includes the terminating NULL. Env must have room for size + 1 entries
812 * (in case of insert). Returns the new size. Optionally frees removed entries.
814 static int do_putenv(char **env, const char *name, int size, int free_old)
816 int i = bsearchenv(env, name, size - 1);
818 /* optionally free removed / replaced entry */
819 if (i >= 0 && free_old)
820 free(env[i]);
822 if (strchr(name, '=')) {
823 /* if new value ('key=value') is specified, insert or replace entry */
824 if (i < 0) {
825 i = ~i;
826 memmove(&env[i + 1], &env[i], (size - i) * sizeof(char*));
827 size++;
829 env[i] = (char*) name;
830 } else if (i >= 0) {
831 /* otherwise ('key') remove existing entry */
832 size--;
833 memmove(&env[i], &env[i + 1], (size - i) * sizeof(char*));
835 return size;
838 /* used number of elements of environ array, including terminating NULL */
839 static int environ_size = 0;
840 /* allocated size of environ array, in bytes */
841 static int environ_alloc = 0;
843 char *mingw_getenv(const char *name)
845 char *value;
846 int pos = bsearchenv(environ, name, environ_size - 1);
847 if (pos < 0)
848 return NULL;
849 value = strchr(environ[pos], '=');
850 return value ? &value[1] : NULL;
853 int mingw_putenv(const char *namevalue)
855 ALLOC_GROW(environ, (environ_size + 1) * sizeof(char*), environ_alloc);
856 environ_size = do_putenv(environ, namevalue, environ_size, 1);
857 return 0;
861 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
862 * (Parsing C++ Command-Line Arguments)
864 static const char *quote_arg(const char *arg)
866 /* count chars to quote */
867 int len = 0, n = 0;
868 int force_quotes = 0;
869 char *q, *d;
870 const char *p = arg;
871 if (!*p) force_quotes = 1;
872 while (*p) {
873 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
874 force_quotes = 1;
875 else if (*p == '"')
876 n++;
877 else if (*p == '\\') {
878 int count = 0;
879 while (*p == '\\') {
880 count++;
881 p++;
882 len++;
884 if (*p == '"')
885 n += count*2 + 1;
886 continue;
888 len++;
889 p++;
891 if (!force_quotes && n == 0)
892 return arg;
894 /* insert \ where necessary */
895 d = q = xmalloc(len+n+3);
896 *d++ = '"';
897 while (*arg) {
898 if (*arg == '"')
899 *d++ = '\\';
900 else if (*arg == '\\') {
901 int count = 0;
902 while (*arg == '\\') {
903 count++;
904 *d++ = *arg++;
906 if (*arg == '"') {
907 while (count-- > 0)
908 *d++ = '\\';
909 *d++ = '\\';
912 *d++ = *arg++;
914 *d++ = '"';
915 *d++ = 0;
916 return q;
919 static const char *parse_interpreter(const char *cmd)
921 static char buf[100];
922 char *p, *opt;
923 int n, fd;
925 /* don't even try a .exe */
926 n = strlen(cmd);
927 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
928 return NULL;
930 fd = open(cmd, O_RDONLY);
931 if (fd < 0)
932 return NULL;
933 n = read(fd, buf, sizeof(buf)-1);
934 close(fd);
935 if (n < 4) /* at least '#!/x' and not error */
936 return NULL;
938 if (buf[0] != '#' || buf[1] != '!')
939 return NULL;
940 buf[n] = '\0';
941 p = buf + strcspn(buf, "\r\n");
942 if (!*p)
943 return NULL;
945 *p = '\0';
946 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
947 return NULL;
948 /* strip options */
949 if ((opt = strchr(p+1, ' ')))
950 *opt = '\0';
951 return p+1;
955 * Splits the PATH into parts.
957 static char **get_path_split(void)
959 char *p, **path, *envpath = getenv("PATH");
960 int i, n = 0;
962 if (!envpath || !*envpath)
963 return NULL;
965 envpath = xstrdup(envpath);
966 p = envpath;
967 while (p) {
968 char *dir = p;
969 p = strchr(p, ';');
970 if (p) *p++ = '\0';
971 if (*dir) { /* not earlier, catches series of ; */
972 ++n;
975 if (!n)
976 return NULL;
978 path = xmalloc((n+1)*sizeof(char *));
979 p = envpath;
980 i = 0;
981 do {
982 if (*p)
983 path[i++] = xstrdup(p);
984 p = p+strlen(p)+1;
985 } while (i < n);
986 path[i] = NULL;
988 free(envpath);
990 return path;
993 static void free_path_split(char **path)
995 char **p = path;
997 if (!path)
998 return;
1000 while (*p)
1001 free(*p++);
1002 free(path);
1006 * exe_only means that we only want to detect .exe files, but not scripts
1007 * (which do not have an extension)
1009 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
1011 char path[MAX_PATH];
1012 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
1014 if (!isexe && access(path, F_OK) == 0)
1015 return xstrdup(path);
1016 path[strlen(path)-4] = '\0';
1017 if ((!exe_only || isexe) && access(path, F_OK) == 0)
1018 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
1019 return xstrdup(path);
1020 return NULL;
1024 * Determines the absolute path of cmd using the split path in path.
1025 * If cmd contains a slash or backslash, no lookup is performed.
1027 static char *path_lookup(const char *cmd, char **path, int exe_only)
1029 char *prog = NULL;
1030 int len = strlen(cmd);
1031 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1033 if (strchr(cmd, '/') || strchr(cmd, '\\'))
1034 prog = xstrdup(cmd);
1036 while (!prog && *path)
1037 prog = lookup_prog(*path++, cmd, isexe, exe_only);
1039 return prog;
1043 * Create environment block suitable for CreateProcess. Merges current
1044 * process environment and the supplied environment changes.
1046 static wchar_t *make_environment_block(char **deltaenv)
1048 wchar_t *wenvblk = NULL;
1049 char **tmpenv;
1050 int i = 0, size = environ_size, wenvsz = 0, wenvpos = 0;
1052 while (deltaenv && deltaenv[i])
1053 i++;
1055 /* copy the environment, leaving space for changes */
1056 tmpenv = xmalloc((size + i) * sizeof(char*));
1057 memcpy(tmpenv, environ, size * sizeof(char*));
1059 /* merge supplied environment changes into the temporary environment */
1060 for (i = 0; deltaenv && deltaenv[i]; i++)
1061 size = do_putenv(tmpenv, deltaenv[i], size, 0);
1063 /* create environment block from temporary environment */
1064 for (i = 0; tmpenv[i]; i++) {
1065 size = 2 * strlen(tmpenv[i]) + 2; /* +2 for final \0 */
1066 ALLOC_GROW(wenvblk, (wenvpos + size) * sizeof(wchar_t), wenvsz);
1067 wenvpos += xutftowcs(&wenvblk[wenvpos], tmpenv[i], size) + 1;
1069 /* add final \0 terminator */
1070 wenvblk[wenvpos] = 0;
1071 free(tmpenv);
1072 return wenvblk;
1075 struct pinfo_t {
1076 struct pinfo_t *next;
1077 pid_t pid;
1078 HANDLE proc;
1080 static struct pinfo_t *pinfo = NULL;
1081 CRITICAL_SECTION pinfo_cs;
1083 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1084 const char *dir,
1085 int prepend_cmd, int fhin, int fhout, int fherr)
1087 STARTUPINFOW si;
1088 PROCESS_INFORMATION pi;
1089 struct strbuf args;
1090 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1091 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1092 BOOL ret;
1094 /* Determine whether or not we are associated to a console */
1095 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
1096 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1097 FILE_ATTRIBUTE_NORMAL, NULL);
1098 if (cons == INVALID_HANDLE_VALUE) {
1099 /* There is no console associated with this process.
1100 * Since the child is a console process, Windows
1101 * would normally create a console window. But
1102 * since we'll be redirecting std streams, we do
1103 * not need the console.
1104 * It is necessary to use DETACHED_PROCESS
1105 * instead of CREATE_NO_WINDOW to make ssh
1106 * recognize that it has no console.
1108 flags |= DETACHED_PROCESS;
1109 } else {
1110 /* There is already a console. If we specified
1111 * DETACHED_PROCESS here, too, Windows would
1112 * disassociate the child from the console.
1113 * The same is true for CREATE_NO_WINDOW.
1114 * Go figure!
1116 CloseHandle(cons);
1118 memset(&si, 0, sizeof(si));
1119 si.cb = sizeof(si);
1120 si.dwFlags = STARTF_USESTDHANDLES;
1121 si.hStdInput = winansi_get_osfhandle(fhin);
1122 si.hStdOutput = winansi_get_osfhandle(fhout);
1123 si.hStdError = winansi_get_osfhandle(fherr);
1125 if (xutftowcs_path(wcmd, cmd) < 0)
1126 return -1;
1127 if (dir && xutftowcs_path(wdir, dir) < 0)
1128 return -1;
1130 /* concatenate argv, quoting args as we go */
1131 strbuf_init(&args, 0);
1132 if (prepend_cmd) {
1133 char *quoted = (char *)quote_arg(cmd);
1134 strbuf_addstr(&args, quoted);
1135 if (quoted != cmd)
1136 free(quoted);
1138 for (; *argv; argv++) {
1139 char *quoted = (char *)quote_arg(*argv);
1140 if (*args.buf)
1141 strbuf_addch(&args, ' ');
1142 strbuf_addstr(&args, quoted);
1143 if (quoted != *argv)
1144 free(quoted);
1147 wargs = xmalloc((2 * args.len + 1) * sizeof(wchar_t));
1148 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1149 strbuf_release(&args);
1151 wenvblk = make_environment_block(deltaenv);
1153 memset(&pi, 0, sizeof(pi));
1154 ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,
1155 wenvblk, dir ? wdir : NULL, &si, &pi);
1157 free(wenvblk);
1158 free(wargs);
1160 if (!ret) {
1161 errno = ENOENT;
1162 return -1;
1164 CloseHandle(pi.hThread);
1167 * The process ID is the human-readable identifier of the process
1168 * that we want to present in log and error messages. The handle
1169 * is not useful for this purpose. But we cannot close it, either,
1170 * because it is not possible to turn a process ID into a process
1171 * handle after the process terminated.
1172 * Keep the handle in a list for waitpid.
1174 EnterCriticalSection(&pinfo_cs);
1176 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1177 info->pid = pi.dwProcessId;
1178 info->proc = pi.hProcess;
1179 info->next = pinfo;
1180 pinfo = info;
1182 LeaveCriticalSection(&pinfo_cs);
1184 return (pid_t)pi.dwProcessId;
1187 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1189 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1192 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1193 const char *dir,
1194 int fhin, int fhout, int fherr)
1196 pid_t pid;
1197 char **path = get_path_split();
1198 char *prog = path_lookup(cmd, path, 0);
1200 if (!prog) {
1201 errno = ENOENT;
1202 pid = -1;
1204 else {
1205 const char *interpr = parse_interpreter(prog);
1207 if (interpr) {
1208 const char *argv0 = argv[0];
1209 char *iprog = path_lookup(interpr, path, 1);
1210 argv[0] = prog;
1211 if (!iprog) {
1212 errno = ENOENT;
1213 pid = -1;
1215 else {
1216 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1217 fhin, fhout, fherr);
1218 free(iprog);
1220 argv[0] = argv0;
1222 else
1223 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1224 fhin, fhout, fherr);
1225 free(prog);
1227 free_path_split(path);
1228 return pid;
1231 static int try_shell_exec(const char *cmd, char *const *argv)
1233 const char *interpr = parse_interpreter(cmd);
1234 char **path;
1235 char *prog;
1236 int pid = 0;
1238 if (!interpr)
1239 return 0;
1240 path = get_path_split();
1241 prog = path_lookup(interpr, path, 1);
1242 if (prog) {
1243 int argc = 0;
1244 const char **argv2;
1245 while (argv[argc]) argc++;
1246 argv2 = xmalloc(sizeof(*argv) * (argc+1));
1247 argv2[0] = (char *)cmd; /* full path to the script file */
1248 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1249 pid = mingw_spawnv(prog, argv2, 1);
1250 if (pid >= 0) {
1251 int status;
1252 if (waitpid(pid, &status, 0) < 0)
1253 status = 255;
1254 exit(status);
1256 pid = 1; /* indicate that we tried but failed */
1257 free(prog);
1258 free(argv2);
1260 free_path_split(path);
1261 return pid;
1264 int mingw_execv(const char *cmd, char *const *argv)
1266 /* check if git_command is a shell script */
1267 if (!try_shell_exec(cmd, argv)) {
1268 int pid, status;
1270 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1271 if (pid < 0)
1272 return -1;
1273 if (waitpid(pid, &status, 0) < 0)
1274 status = 255;
1275 exit(status);
1277 return -1;
1280 int mingw_execvp(const char *cmd, char *const *argv)
1282 char **path = get_path_split();
1283 char *prog = path_lookup(cmd, path, 0);
1285 if (prog) {
1286 mingw_execv(prog, argv);
1287 free(prog);
1288 } else
1289 errno = ENOENT;
1291 free_path_split(path);
1292 return -1;
1295 int mingw_kill(pid_t pid, int sig)
1297 if (pid > 0 && sig == SIGTERM) {
1298 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1300 if (TerminateProcess(h, -1)) {
1301 CloseHandle(h);
1302 return 0;
1305 errno = err_win_to_posix(GetLastError());
1306 CloseHandle(h);
1307 return -1;
1308 } else if (pid > 0 && sig == 0) {
1309 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1310 if (h) {
1311 CloseHandle(h);
1312 return 0;
1316 errno = EINVAL;
1317 return -1;
1321 * Note, this isn't a complete replacement for getaddrinfo. It assumes
1322 * that service contains a numerical port, or that it is null. It
1323 * does a simple search using gethostbyname, and returns one IPv4 host
1324 * if one was found.
1326 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1327 const struct addrinfo *hints,
1328 struct addrinfo **res)
1330 struct hostent *h = NULL;
1331 struct addrinfo *ai;
1332 struct sockaddr_in *sin;
1334 if (node) {
1335 h = gethostbyname(node);
1336 if (!h)
1337 return WSAGetLastError();
1340 ai = xmalloc(sizeof(struct addrinfo));
1341 *res = ai;
1342 ai->ai_flags = 0;
1343 ai->ai_family = AF_INET;
1344 ai->ai_socktype = hints ? hints->ai_socktype : 0;
1345 switch (ai->ai_socktype) {
1346 case SOCK_STREAM:
1347 ai->ai_protocol = IPPROTO_TCP;
1348 break;
1349 case SOCK_DGRAM:
1350 ai->ai_protocol = IPPROTO_UDP;
1351 break;
1352 default:
1353 ai->ai_protocol = 0;
1354 break;
1356 ai->ai_addrlen = sizeof(struct sockaddr_in);
1357 if (hints && (hints->ai_flags & AI_CANONNAME))
1358 ai->ai_canonname = h ? xstrdup(h->h_name) : NULL;
1359 else
1360 ai->ai_canonname = NULL;
1362 sin = xmalloc(ai->ai_addrlen);
1363 memset(sin, 0, ai->ai_addrlen);
1364 sin->sin_family = AF_INET;
1365 /* Note: getaddrinfo is supposed to allow service to be a string,
1366 * which should be looked up using getservbyname. This is
1367 * currently not implemented */
1368 if (service)
1369 sin->sin_port = htons(atoi(service));
1370 if (h)
1371 sin->sin_addr = *(struct in_addr *)h->h_addr;
1372 else if (hints && (hints->ai_flags & AI_PASSIVE))
1373 sin->sin_addr.s_addr = INADDR_ANY;
1374 else
1375 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1376 ai->ai_addr = (struct sockaddr *)sin;
1377 ai->ai_next = NULL;
1378 return 0;
1381 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1383 free(res->ai_canonname);
1384 free(res->ai_addr);
1385 free(res);
1388 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1389 char *host, DWORD hostlen,
1390 char *serv, DWORD servlen, int flags)
1392 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1393 if (sa->sa_family != AF_INET)
1394 return EAI_FAMILY;
1395 if (!host && !serv)
1396 return EAI_NONAME;
1398 if (host && hostlen > 0) {
1399 struct hostent *ent = NULL;
1400 if (!(flags & NI_NUMERICHOST))
1401 ent = gethostbyaddr((const char *)&sin->sin_addr,
1402 sizeof(sin->sin_addr), AF_INET);
1404 if (ent)
1405 snprintf(host, hostlen, "%s", ent->h_name);
1406 else if (flags & NI_NAMEREQD)
1407 return EAI_NONAME;
1408 else
1409 snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1412 if (serv && servlen > 0) {
1413 struct servent *ent = NULL;
1414 if (!(flags & NI_NUMERICSERV))
1415 ent = getservbyport(sin->sin_port,
1416 flags & NI_DGRAM ? "udp" : "tcp");
1418 if (ent)
1419 snprintf(serv, servlen, "%s", ent->s_name);
1420 else
1421 snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1424 return 0;
1427 static HMODULE ipv6_dll = NULL;
1428 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1429 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1430 const struct addrinfo *hints,
1431 struct addrinfo **res);
1432 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1433 char *host, DWORD hostlen,
1434 char *serv, DWORD servlen, int flags);
1436 * gai_strerror is an inline function in the ws2tcpip.h header, so we
1437 * don't need to try to load that one dynamically.
1440 static void socket_cleanup(void)
1442 WSACleanup();
1443 if (ipv6_dll)
1444 FreeLibrary(ipv6_dll);
1445 ipv6_dll = NULL;
1446 ipv6_freeaddrinfo = freeaddrinfo_stub;
1447 ipv6_getaddrinfo = getaddrinfo_stub;
1448 ipv6_getnameinfo = getnameinfo_stub;
1451 static void ensure_socket_initialization(void)
1453 WSADATA wsa;
1454 static int initialized = 0;
1455 const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1456 const char **name;
1458 if (initialized)
1459 return;
1461 if (WSAStartup(MAKEWORD(2,2), &wsa))
1462 die("unable to initialize winsock subsystem, error %d",
1463 WSAGetLastError());
1465 for (name = libraries; *name; name++) {
1466 ipv6_dll = LoadLibrary(*name);
1467 if (!ipv6_dll)
1468 continue;
1470 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1471 GetProcAddress(ipv6_dll, "freeaddrinfo");
1472 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1473 const struct addrinfo *,
1474 struct addrinfo **))
1475 GetProcAddress(ipv6_dll, "getaddrinfo");
1476 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1477 socklen_t, char *, DWORD,
1478 char *, DWORD, int))
1479 GetProcAddress(ipv6_dll, "getnameinfo");
1480 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1481 FreeLibrary(ipv6_dll);
1482 ipv6_dll = NULL;
1483 } else
1484 break;
1486 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1487 ipv6_freeaddrinfo = freeaddrinfo_stub;
1488 ipv6_getaddrinfo = getaddrinfo_stub;
1489 ipv6_getnameinfo = getnameinfo_stub;
1492 atexit(socket_cleanup);
1493 initialized = 1;
1496 #undef gethostname
1497 int mingw_gethostname(char *name, int namelen)
1499 ensure_socket_initialization();
1500 return gethostname(name, namelen);
1503 #undef gethostbyname
1504 struct hostent *mingw_gethostbyname(const char *host)
1506 ensure_socket_initialization();
1507 return gethostbyname(host);
1510 void mingw_freeaddrinfo(struct addrinfo *res)
1512 ipv6_freeaddrinfo(res);
1515 int mingw_getaddrinfo(const char *node, const char *service,
1516 const struct addrinfo *hints, struct addrinfo **res)
1518 ensure_socket_initialization();
1519 return ipv6_getaddrinfo(node, service, hints, res);
1522 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1523 char *host, DWORD hostlen, char *serv, DWORD servlen,
1524 int flags)
1526 ensure_socket_initialization();
1527 return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1530 int mingw_socket(int domain, int type, int protocol)
1532 int sockfd;
1533 SOCKET s;
1535 ensure_socket_initialization();
1536 s = WSASocket(domain, type, protocol, NULL, 0, 0);
1537 if (s == INVALID_SOCKET) {
1539 * WSAGetLastError() values are regular BSD error codes
1540 * biased by WSABASEERR.
1541 * However, strerror() does not know about networking
1542 * specific errors, which are values beginning at 38 or so.
1543 * Therefore, we choose to leave the biased error code
1544 * in errno so that _if_ someone looks up the code somewhere,
1545 * then it is at least the number that are usually listed.
1547 errno = WSAGetLastError();
1548 return -1;
1550 /* convert into a file descriptor */
1551 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1552 closesocket(s);
1553 return error("unable to make a socket file descriptor: %s",
1554 strerror(errno));
1556 return sockfd;
1559 #undef connect
1560 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1562 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1563 return connect(s, sa, sz);
1566 #undef bind
1567 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1569 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1570 return bind(s, sa, sz);
1573 #undef setsockopt
1574 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1576 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1577 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1580 #undef shutdown
1581 int mingw_shutdown(int sockfd, int how)
1583 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1584 return shutdown(s, how);
1587 #undef listen
1588 int mingw_listen(int sockfd, int backlog)
1590 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1591 return listen(s, backlog);
1594 #undef accept
1595 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1597 int sockfd2;
1599 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1600 SOCKET s2 = accept(s1, sa, sz);
1602 /* convert into a file descriptor */
1603 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1604 int err = errno;
1605 closesocket(s2);
1606 return error("unable to make a socket file descriptor: %s",
1607 strerror(err));
1609 return sockfd2;
1612 #undef rename
1613 int mingw_rename(const char *pold, const char *pnew)
1615 DWORD attrs, gle;
1616 int tries = 0;
1617 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1618 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1619 return -1;
1622 * Try native rename() first to get errno right.
1623 * It is based on MoveFile(), which cannot overwrite existing files.
1625 if (!_wrename(wpold, wpnew))
1626 return 0;
1627 if (errno != EEXIST)
1628 return -1;
1629 repeat:
1630 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1631 return 0;
1632 /* TODO: translate more errors */
1633 gle = GetLastError();
1634 if (gle == ERROR_ACCESS_DENIED &&
1635 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
1636 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1637 errno = EISDIR;
1638 return -1;
1640 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1641 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1642 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
1643 return 0;
1644 gle = GetLastError();
1645 /* revert file attributes on failure */
1646 SetFileAttributesW(wpnew, attrs);
1649 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1651 * We assume that some other process had the source or
1652 * destination file open at the wrong moment and retry.
1653 * In order to give the other process a higher chance to
1654 * complete its operation, we give up our time slice now.
1655 * If we have to retry again, we do sleep a bit.
1657 Sleep(delay[tries]);
1658 tries++;
1659 goto repeat;
1661 if (gle == ERROR_ACCESS_DENIED &&
1662 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1663 "Should I try again?", pold, pnew))
1664 goto repeat;
1666 errno = EACCES;
1667 return -1;
1671 * Note that this doesn't return the actual pagesize, but
1672 * the allocation granularity. If future Windows specific git code
1673 * needs the real getpagesize function, we need to find another solution.
1675 int mingw_getpagesize(void)
1677 SYSTEM_INFO si;
1678 GetSystemInfo(&si);
1679 return si.dwAllocationGranularity;
1682 struct passwd *getpwuid(int uid)
1684 static char user_name[100];
1685 static struct passwd p;
1687 DWORD len = sizeof(user_name);
1688 if (!GetUserName(user_name, &len))
1689 return NULL;
1690 p.pw_name = user_name;
1691 p.pw_gecos = "unknown";
1692 p.pw_dir = NULL;
1693 return &p;
1696 static HANDLE timer_event;
1697 static HANDLE timer_thread;
1698 static int timer_interval;
1699 static int one_shot;
1700 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
1702 /* The timer works like this:
1703 * The thread, ticktack(), is a trivial routine that most of the time
1704 * only waits to receive the signal to terminate. The main thread tells
1705 * the thread to terminate by setting the timer_event to the signalled
1706 * state.
1707 * But ticktack() interrupts the wait state after the timer's interval
1708 * length to call the signal handler.
1711 static unsigned __stdcall ticktack(void *dummy)
1713 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1714 mingw_raise(SIGALRM);
1715 if (one_shot)
1716 break;
1718 return 0;
1721 static int start_timer_thread(void)
1723 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1724 if (timer_event) {
1725 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1726 if (!timer_thread )
1727 return errno = ENOMEM,
1728 error("cannot start timer thread");
1729 } else
1730 return errno = ENOMEM,
1731 error("cannot allocate resources for timer");
1732 return 0;
1735 static void stop_timer_thread(void)
1737 if (timer_event)
1738 SetEvent(timer_event); /* tell thread to terminate */
1739 if (timer_thread) {
1740 int rc = WaitForSingleObject(timer_thread, 1000);
1741 if (rc == WAIT_TIMEOUT)
1742 error("timer thread did not terminate timely");
1743 else if (rc != WAIT_OBJECT_0)
1744 error("waiting for timer thread failed: %lu",
1745 GetLastError());
1746 CloseHandle(timer_thread);
1748 if (timer_event)
1749 CloseHandle(timer_event);
1750 timer_event = NULL;
1751 timer_thread = NULL;
1754 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1756 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1759 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1761 static const struct timeval zero;
1762 static int atexit_done;
1764 if (out != NULL)
1765 return errno = EINVAL,
1766 error("setitimer param 3 != NULL not implemented");
1767 if (!is_timeval_eq(&in->it_interval, &zero) &&
1768 !is_timeval_eq(&in->it_interval, &in->it_value))
1769 return errno = EINVAL,
1770 error("setitimer: it_interval must be zero or eq it_value");
1772 if (timer_thread)
1773 stop_timer_thread();
1775 if (is_timeval_eq(&in->it_value, &zero) &&
1776 is_timeval_eq(&in->it_interval, &zero))
1777 return 0;
1779 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1780 one_shot = is_timeval_eq(&in->it_interval, &zero);
1781 if (!atexit_done) {
1782 atexit(stop_timer_thread);
1783 atexit_done = 1;
1785 return start_timer_thread();
1788 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1790 if (sig != SIGALRM)
1791 return errno = EINVAL,
1792 error("sigaction only implemented for SIGALRM");
1793 if (out != NULL)
1794 return errno = EINVAL,
1795 error("sigaction: param 3 != NULL not implemented");
1797 timer_fn = in->sa_handler;
1798 return 0;
1801 #undef signal
1802 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1804 sig_handler_t old;
1806 switch (sig) {
1807 case SIGALRM:
1808 old = timer_fn;
1809 timer_fn = handler;
1810 break;
1812 case SIGINT:
1813 old = sigint_fn;
1814 sigint_fn = handler;
1815 break;
1817 default:
1818 return signal(sig, handler);
1821 return old;
1824 #undef raise
1825 int mingw_raise(int sig)
1827 switch (sig) {
1828 case SIGALRM:
1829 if (timer_fn == SIG_DFL) {
1830 if (isatty(STDERR_FILENO))
1831 fputs("Alarm clock\n", stderr);
1832 exit(128 + SIGALRM);
1833 } else if (timer_fn != SIG_IGN)
1834 timer_fn(SIGALRM);
1835 return 0;
1837 case SIGINT:
1838 if (sigint_fn == SIG_DFL)
1839 exit(128 + SIGINT);
1840 else if (sigint_fn != SIG_IGN)
1841 sigint_fn(SIGINT);
1842 return 0;
1844 default:
1845 return raise(sig);
1850 static const char *make_backslash_path(const char *path)
1852 static char buf[PATH_MAX + 1];
1853 char *c;
1855 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1856 die("Too long path: %.*s", 60, path);
1858 for (c = buf; *c; c++) {
1859 if (*c == '/')
1860 *c = '\\';
1862 return buf;
1865 void mingw_open_html(const char *unixpath)
1867 const char *htmlpath = make_backslash_path(unixpath);
1868 typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1869 const char *, const char *, const char *, INT);
1870 T ShellExecute;
1871 HMODULE shell32;
1872 int r;
1874 shell32 = LoadLibrary("shell32.dll");
1875 if (!shell32)
1876 die("cannot load shell32.dll");
1877 ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1878 if (!ShellExecute)
1879 die("cannot run browser");
1881 printf("Launching default browser to display HTML ...\n");
1882 r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1883 FreeLibrary(shell32);
1884 /* see the MSDN documentation referring to the result codes here */
1885 if (r <= 32) {
1886 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1890 int link(const char *oldpath, const char *newpath)
1892 typedef BOOL (WINAPI *T)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES);
1893 static T create_hard_link = NULL;
1894 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
1895 if (xutftowcs_path(woldpath, oldpath) < 0 ||
1896 xutftowcs_path(wnewpath, newpath) < 0)
1897 return -1;
1899 if (!create_hard_link) {
1900 create_hard_link = (T) GetProcAddress(
1901 GetModuleHandle("kernel32.dll"), "CreateHardLinkW");
1902 if (!create_hard_link)
1903 create_hard_link = (T)-1;
1905 if (create_hard_link == (T)-1) {
1906 errno = ENOSYS;
1907 return -1;
1909 if (!create_hard_link(wnewpath, woldpath, NULL)) {
1910 errno = err_win_to_posix(GetLastError());
1911 return -1;
1913 return 0;
1916 pid_t waitpid(pid_t pid, int *status, int options)
1918 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
1919 FALSE, pid);
1920 if (!h) {
1921 errno = ECHILD;
1922 return -1;
1925 if (pid > 0 && options & WNOHANG) {
1926 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
1927 CloseHandle(h);
1928 return 0;
1930 options &= ~WNOHANG;
1933 if (options == 0) {
1934 struct pinfo_t **ppinfo;
1935 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
1936 CloseHandle(h);
1937 return 0;
1940 if (status)
1941 GetExitCodeProcess(h, (LPDWORD)status);
1943 EnterCriticalSection(&pinfo_cs);
1945 ppinfo = &pinfo;
1946 while (*ppinfo) {
1947 struct pinfo_t *info = *ppinfo;
1948 if (info->pid == pid) {
1949 CloseHandle(info->proc);
1950 *ppinfo = info->next;
1951 free(info);
1952 break;
1954 ppinfo = &info->next;
1957 LeaveCriticalSection(&pinfo_cs);
1959 CloseHandle(h);
1960 return pid;
1962 CloseHandle(h);
1964 errno = EINVAL;
1965 return -1;
1968 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
1970 int upos = 0, wpos = 0;
1971 const unsigned char *utf = (const unsigned char*) utfs;
1972 if (!utf || !wcs || wcslen < 1) {
1973 errno = EINVAL;
1974 return -1;
1976 /* reserve space for \0 */
1977 wcslen--;
1978 if (utflen < 0)
1979 utflen = INT_MAX;
1981 while (upos < utflen) {
1982 int c = utf[upos++] & 0xff;
1983 if (utflen == INT_MAX && c == 0)
1984 break;
1986 if (wpos >= wcslen) {
1987 wcs[wpos] = 0;
1988 errno = ERANGE;
1989 return -1;
1992 if (c < 0x80) {
1993 /* ASCII */
1994 wcs[wpos++] = c;
1995 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
1996 (utf[upos] & 0xc0) == 0x80) {
1997 /* 2-byte utf-8 */
1998 c = ((c & 0x1f) << 6);
1999 c |= (utf[upos++] & 0x3f);
2000 wcs[wpos++] = c;
2001 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2002 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2003 (utf[upos] & 0xc0) == 0x80 &&
2004 (utf[upos + 1] & 0xc0) == 0x80) {
2005 /* 3-byte utf-8 */
2006 c = ((c & 0x0f) << 12);
2007 c |= ((utf[upos++] & 0x3f) << 6);
2008 c |= (utf[upos++] & 0x3f);
2009 wcs[wpos++] = c;
2010 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2011 wpos + 1 < wcslen &&
2012 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2013 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2014 (utf[upos] & 0xc0) == 0x80 &&
2015 (utf[upos + 1] & 0xc0) == 0x80 &&
2016 (utf[upos + 2] & 0xc0) == 0x80) {
2017 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2018 c = ((c & 0x07) << 18);
2019 c |= ((utf[upos++] & 0x3f) << 12);
2020 c |= ((utf[upos++] & 0x3f) << 6);
2021 c |= (utf[upos++] & 0x3f);
2022 c -= 0x10000;
2023 wcs[wpos++] = 0xd800 | (c >> 10);
2024 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2025 } else if (c >= 0xa0) {
2026 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2027 wcs[wpos++] = c;
2028 } else {
2029 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2030 static const char *hex = "0123456789abcdef";
2031 wcs[wpos++] = hex[c >> 4];
2032 if (wpos < wcslen)
2033 wcs[wpos++] = hex[c & 0x0f];
2036 wcs[wpos] = 0;
2037 return wpos;
2040 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2042 if (!wcs || !utf || utflen < 1) {
2043 errno = EINVAL;
2044 return -1;
2046 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2047 if (utflen)
2048 return utflen - 1;
2049 errno = ERANGE;
2050 return -1;
2054 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2055 * mingw startup code, see init.c in mingw runtime).
2057 int _CRT_glob = 0;
2059 typedef struct {
2060 int newmode;
2061 } _startupinfo;
2063 extern int __wgetmainargs(int *argc, wchar_t ***argv, wchar_t ***env, int glob,
2064 _startupinfo *si);
2066 static NORETURN void die_startup()
2068 fputs("fatal: not enough memory for initialization", stderr);
2069 exit(128);
2072 static void *malloc_startup(size_t size)
2074 void *result = malloc(size);
2075 if (!result)
2076 die_startup();
2077 return result;
2080 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2082 len = xwcstoutf(buffer, wcs, len) + 1;
2083 return memcpy(malloc_startup(len), buffer, len);
2086 void mingw_startup()
2088 int i, maxlen, argc;
2089 char *buffer;
2090 wchar_t **wenv, **wargv;
2091 _startupinfo si;
2093 /* get wide char arguments and environment */
2094 si.newmode = 0;
2095 if (__wgetmainargs(&argc, &wargv, &wenv, _CRT_glob, &si) < 0)
2096 die_startup();
2098 /* determine size of argv and environ conversion buffer */
2099 maxlen = wcslen(_wpgmptr);
2100 for (i = 1; i < argc; i++)
2101 maxlen = max(maxlen, wcslen(wargv[i]));
2102 for (i = 0; wenv[i]; i++)
2103 maxlen = max(maxlen, wcslen(wenv[i]));
2106 * nedmalloc can't free CRT memory, allocate resizable environment
2107 * list. Note that xmalloc / xmemdupz etc. call getenv, so we cannot
2108 * use it while initializing the environment itself.
2110 environ_size = i + 1;
2111 environ_alloc = alloc_nr(environ_size * sizeof(char*));
2112 environ = malloc_startup(environ_alloc);
2114 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2115 maxlen = 3 * maxlen + 1;
2116 buffer = malloc_startup(maxlen);
2118 /* convert command line arguments and environment to UTF-8 */
2119 __argv[0] = wcstoutfdup_startup(buffer, _wpgmptr, maxlen);
2120 for (i = 1; i < argc; i++)
2121 __argv[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2122 for (i = 0; wenv[i]; i++)
2123 environ[i] = wcstoutfdup_startup(buffer, wenv[i], maxlen);
2124 environ[i] = NULL;
2125 free(buffer);
2127 /* sort environment for O(log n) getenv / putenv */
2128 qsort(environ, i, sizeof(char*), compareenv);
2130 /* fix Windows specific environment settings */
2132 /* on Windows it is TMP and TEMP */
2133 if (!getenv("TMPDIR")) {
2134 const char *tmp = getenv("TMP");
2135 if (!tmp)
2136 tmp = getenv("TEMP");
2137 if (tmp)
2138 setenv("TMPDIR", tmp, 1);
2141 /* simulate TERM to enable auto-color (see color.c) */
2142 if (!getenv("TERM"))
2143 setenv("TERM", "winansi", 1);
2145 /* initialize critical section for waitpid pinfo_t list */
2146 InitializeCriticalSection(&pinfo_cs);
2148 /* set up default file mode and file modes for stdin/out/err */
2149 _fmode = _O_BINARY;
2150 _setmode(_fileno(stdin), _O_BINARY);
2151 _setmode(_fileno(stdout), _O_BINARY);
2152 _setmode(_fileno(stderr), _O_BINARY);
2154 /* initialize Unicode console */
2155 winansi_init();