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