Merge commit 'junio/next' into next
[git/platforms/storm.git] / compat / mingw.c
bloba5b43bcf6fd68421ef97f8f6ca794aa2389e7e65
1 #include "../git-compat-util.h"
2 #include "../strbuf.h"
4 unsigned int _CRT_fmode = _O_BINARY;
6 #undef open
7 int mingw_open (const char *filename, int oflags, ...)
9 va_list args;
10 unsigned mode;
11 va_start(args, oflags);
12 mode = va_arg(args, int);
13 va_end(args);
15 if (!strcmp(filename, "/dev/null"))
16 filename = "nul";
17 int fd = open(filename, oflags, mode);
18 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
19 DWORD attrs = GetFileAttributes(filename);
20 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
21 errno = EISDIR;
23 return fd;
26 static inline time_t filetime_to_time_t(const FILETIME *ft)
28 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
29 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
30 winTime /= 10000000; /* Nano to seconds resolution */
31 return (time_t)winTime;
34 static inline size_t size_to_blocks(size_t s)
36 return (s+511)/512;
39 extern int _getdrive( void );
40 /* We keep the do_lstat code in a separate function to avoid recursion.
41 * When a path ends with a slash, the stat will fail with ENOENT. In
42 * this case, we strip the trailing slashes and stat again.
44 static int do_lstat(const char *file_name, struct stat *buf)
46 WIN32_FILE_ATTRIBUTE_DATA fdata;
48 if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
49 int fMode = S_IREAD;
50 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
51 fMode |= S_IFDIR;
52 else
53 fMode |= S_IFREG;
54 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
55 fMode |= S_IWRITE;
57 buf->st_ino = 0;
58 buf->st_gid = 0;
59 buf->st_uid = 0;
60 buf->st_mode = fMode;
61 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
62 buf->st_blocks = size_to_blocks(buf->st_size);
63 buf->st_dev = _getdrive() - 1;
64 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
65 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
66 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
67 errno = 0;
68 return 0;
71 switch (GetLastError()) {
72 case ERROR_ACCESS_DENIED:
73 case ERROR_SHARING_VIOLATION:
74 case ERROR_LOCK_VIOLATION:
75 case ERROR_SHARING_BUFFER_EXCEEDED:
76 errno = EACCES;
77 break;
78 case ERROR_BUFFER_OVERFLOW:
79 errno = ENAMETOOLONG;
80 break;
81 case ERROR_NOT_ENOUGH_MEMORY:
82 errno = ENOMEM;
83 break;
84 default:
85 errno = ENOENT;
86 break;
88 return -1;
91 /* We provide our own lstat/fstat functions, since the provided
92 * lstat/fstat functions are so slow. These stat functions are
93 * tailored for Git's usage (read: fast), and are not meant to be
94 * complete. Note that Git stat()s are redirected to mingw_lstat()
95 * too, since Windows doesn't really handle symlinks that well.
97 int mingw_lstat(const char *file_name, struct mingw_stat *buf)
99 int namelen;
100 static char alt_name[PATH_MAX];
102 if (!do_lstat(file_name, buf))
103 return 0;
105 /* if file_name ended in a '/', Windows returned ENOENT;
106 * try again without trailing slashes
108 if (errno != ENOENT)
109 return -1;
111 namelen = strlen(file_name);
112 if (namelen && file_name[namelen-1] != '/')
113 return -1;
114 while (namelen && file_name[namelen-1] == '/')
115 --namelen;
116 if (!namelen || namelen >= PATH_MAX)
117 return -1;
119 memcpy(alt_name, file_name, namelen);
120 alt_name[namelen] = 0;
121 return do_lstat(alt_name, buf);
124 #undef fstat
125 #undef stat
126 int mingw_fstat(int fd, struct mingw_stat *buf)
128 HANDLE fh = (HANDLE)_get_osfhandle(fd);
129 BY_HANDLE_FILE_INFORMATION fdata;
131 if (fh == INVALID_HANDLE_VALUE) {
132 errno = EBADF;
133 return -1;
135 /* direct non-file handles to MS's fstat() */
136 if (GetFileType(fh) != FILE_TYPE_DISK) {
137 struct stat st;
138 if (fstat(fd, &st))
139 return -1;
140 buf->st_ino = st.st_ino;
141 buf->st_gid = st.st_gid;
142 buf->st_uid = st.st_uid;
143 buf->st_mode = st.st_mode;
144 buf->st_size = st.st_size;
145 buf->st_blocks = size_to_blocks(buf->st_size);
146 buf->st_dev = st.st_dev;
147 buf->st_atime = st.st_atime;
148 buf->st_mtime = st.st_mtime;
149 buf->st_ctime = st.st_ctime;
150 return 0;
153 if (GetFileInformationByHandle(fh, &fdata)) {
154 int fMode = S_IREAD;
155 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
156 fMode |= S_IFDIR;
157 else
158 fMode |= S_IFREG;
159 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
160 fMode |= S_IWRITE;
162 buf->st_ino = 0;
163 buf->st_gid = 0;
164 buf->st_uid = 0;
165 buf->st_mode = fMode;
166 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
167 buf->st_blocks = size_to_blocks(buf->st_size);
168 buf->st_dev = _getdrive() - 1;
169 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
170 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
171 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
172 return 0;
174 errno = EBADF;
175 return -1;
178 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
180 long long winTime = t * 10000000LL + 116444736000000000LL;
181 ft->dwLowDateTime = winTime;
182 ft->dwHighDateTime = winTime >> 32;
185 int mingw_utime (const char *file_name, const struct utimbuf *times)
187 FILETIME mft, aft;
188 int fh, rc;
190 /* must have write permission */
191 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
192 return -1;
194 time_t_to_filetime(times->modtime, &mft);
195 time_t_to_filetime(times->actime, &aft);
196 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
197 errno = EINVAL;
198 rc = -1;
199 } else
200 rc = 0;
201 close(fh);
202 return rc;
205 unsigned int sleep (unsigned int seconds)
207 Sleep(seconds*1000);
208 return 0;
211 int mkstemp(char *template)
213 char *filename = mktemp(template);
214 if (filename == NULL)
215 return -1;
216 return open(filename, O_RDWR | O_CREAT, 0600);
219 int gettimeofday(struct timeval *tv, void *tz)
221 extern time_t my_mktime(struct tm *tm);
222 SYSTEMTIME st;
223 struct tm tm;
224 GetSystemTime(&st);
225 tm.tm_year = st.wYear-1900;
226 tm.tm_mon = st.wMonth-1;
227 tm.tm_mday = st.wDay;
228 tm.tm_hour = st.wHour;
229 tm.tm_min = st.wMinute;
230 tm.tm_sec = st.wSecond;
231 tv->tv_sec = my_mktime(&tm);
232 if (tv->tv_sec < 0)
233 return -1;
234 tv->tv_usec = st.wMilliseconds*1000;
235 return 0;
238 int pipe(int filedes[2])
240 int fd;
241 HANDLE h[2], parent;
243 if (_pipe(filedes, 8192, 0) < 0)
244 return -1;
246 parent = GetCurrentProcess();
248 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
249 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
250 close(filedes[0]);
251 close(filedes[1]);
252 return -1;
254 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
255 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
256 close(filedes[0]);
257 close(filedes[1]);
258 CloseHandle(h[0]);
259 return -1;
261 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
262 if (fd < 0) {
263 close(filedes[0]);
264 close(filedes[1]);
265 CloseHandle(h[0]);
266 CloseHandle(h[1]);
267 return -1;
269 close(filedes[0]);
270 filedes[0] = fd;
271 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
272 if (fd < 0) {
273 close(filedes[0]);
274 close(filedes[1]);
275 CloseHandle(h[1]);
276 return -1;
278 close(filedes[1]);
279 filedes[1] = fd;
280 return 0;
283 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
285 int i, pending;
287 if (timeout != -1)
288 return errno = EINVAL, error("poll timeout not supported");
290 /* When there is only one fd to wait for, then we pretend that
291 * input is available and let the actual wait happen when the
292 * caller invokes read().
294 if (nfds == 1) {
295 if (!(ufds[0].events & POLLIN))
296 return errno = EINVAL, error("POLLIN not set");
297 ufds[0].revents = POLLIN;
298 return 0;
301 repeat:
302 pending = 0;
303 for (i = 0; i < nfds; i++) {
304 DWORD avail = 0;
305 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
306 if (h == INVALID_HANDLE_VALUE)
307 return -1; /* errno was set */
309 if (!(ufds[i].events & POLLIN))
310 return errno = EINVAL, error("POLLIN not set");
312 /* this emulation works only for pipes */
313 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
314 int err = GetLastError();
315 if (err == ERROR_BROKEN_PIPE) {
316 ufds[i].revents = POLLHUP;
317 pending++;
318 } else {
319 errno = EINVAL;
320 return error("PeekNamedPipe failed,"
321 " GetLastError: %u", err);
323 } else if (avail) {
324 ufds[i].revents = POLLIN;
325 pending++;
326 } else
327 ufds[i].revents = 0;
329 if (!pending) {
330 /* The only times that we spin here is when the process
331 * that is connected through the pipes is waiting for
332 * its own input data to become available. But since
333 * the process (pack-objects) is itself CPU intensive,
334 * it will happily pick up the time slice that we are
335 * relinguishing here.
337 Sleep(0);
338 goto repeat;
340 return 0;
343 struct tm *gmtime_r(const time_t *timep, struct tm *result)
345 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
346 memcpy(result, gmtime(timep), sizeof(struct tm));
347 return result;
350 struct tm *localtime_r(const time_t *timep, struct tm *result)
352 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
353 memcpy(result, localtime(timep), sizeof(struct tm));
354 return result;
357 #undef getcwd
358 char *mingw_getcwd(char *pointer, int len)
360 int i;
361 char *ret = getcwd(pointer, len);
362 if (!ret)
363 return ret;
364 for (i = 0; pointer[i]; i++)
365 if (pointer[i] == '\\')
366 pointer[i] = '/';
367 return ret;
371 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
372 * (Parsing C++ Command-Line Arguments)
374 static const char *quote_arg(const char *arg)
376 /* count chars to quote */
377 int len = 0, n = 0;
378 int force_quotes = 0;
379 char *q, *d;
380 const char *p = arg;
381 if (!*p) force_quotes = 1;
382 while (*p) {
383 if (isspace(*p) || *p == '*' || *p == '?')
384 force_quotes = 1;
385 else if (*p == '"')
386 n++;
387 else if (*p == '\\') {
388 int count = 0;
389 while (*p == '\\') {
390 count++;
391 p++;
392 len++;
394 if (*p == '"')
395 n += count*2 + 1;
396 continue;
398 len++;
399 p++;
401 if (!force_quotes && n == 0)
402 return arg;
404 /* insert \ where necessary */
405 d = q = xmalloc(len+n+3);
406 *d++ = '"';
407 while (*arg) {
408 if (*arg == '"')
409 *d++ = '\\';
410 else if (*arg == '\\') {
411 int count = 0;
412 while (*arg == '\\') {
413 count++;
414 *d++ = *arg++;
416 if (*arg == '"') {
417 while (count-- > 0)
418 *d++ = '\\';
419 *d++ = '\\';
422 *d++ = *arg++;
424 *d++ = '"';
425 *d++ = 0;
426 return q;
429 static const char *parse_interpreter(const char *cmd)
431 static char buf[100];
432 char *p, *opt;
433 int n, fd;
435 /* don't even try a .exe */
436 n = strlen(cmd);
437 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
438 return NULL;
440 fd = open(cmd, O_RDONLY);
441 if (fd < 0)
442 return NULL;
443 n = read(fd, buf, sizeof(buf)-1);
444 close(fd);
445 if (n < 4) /* at least '#!/x' and not error */
446 return NULL;
448 if (buf[0] != '#' || buf[1] != '!')
449 return NULL;
450 buf[n] = '\0';
451 p = strchr(buf, '\n');
452 if (!p)
453 return NULL;
455 *p = '\0';
456 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
457 return NULL;
458 /* strip options */
459 if ((opt = strchr(p+1, ' ')))
460 *opt = '\0';
461 return p+1;
465 * Splits the PATH into parts.
467 static char **get_path_split(void)
469 char *p, **path, *envpath = getenv("PATH");
470 int i, n = 0;
472 if (!envpath || !*envpath)
473 return NULL;
475 envpath = xstrdup(envpath);
476 p = envpath;
477 while (p) {
478 char *dir = p;
479 p = strchr(p, ';');
480 if (p) *p++ = '\0';
481 if (*dir) { /* not earlier, catches series of ; */
482 ++n;
485 if (!n)
486 return NULL;
488 path = xmalloc((n+1)*sizeof(char*));
489 p = envpath;
490 i = 0;
491 do {
492 if (*p)
493 path[i++] = xstrdup(p);
494 p = p+strlen(p)+1;
495 } while (i < n);
496 path[i] = NULL;
498 free(envpath);
500 return path;
503 static void free_path_split(char **path)
505 if (!path)
506 return;
508 char **p = path;
509 while (*p)
510 free(*p++);
511 free(path);
515 * exe_only means that we only want to detect .exe files, but not scripts
516 * (which do not have an extension)
518 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
520 char path[MAX_PATH];
521 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
523 if (!isexe && access(path, F_OK) == 0)
524 return xstrdup(path);
525 path[strlen(path)-4] = '\0';
526 if ((!exe_only || isexe) && access(path, F_OK) == 0)
527 return xstrdup(path);
528 return NULL;
532 * Determines the absolute path of cmd using the the split path in path.
533 * If cmd contains a slash or backslash, no lookup is performed.
535 static char *path_lookup(const char *cmd, char **path, int exe_only)
537 char *prog = NULL;
538 int len = strlen(cmd);
539 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
541 if (strchr(cmd, '/') || strchr(cmd, '\\'))
542 prog = xstrdup(cmd);
544 while (!prog && *path)
545 prog = lookup_prog(*path++, cmd, isexe, exe_only);
547 return prog;
550 static int env_compare(const void *a, const void *b)
552 char *const *ea = a;
553 char *const *eb = b;
554 return strcasecmp(*ea, *eb);
557 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
558 int prepend_cmd)
560 STARTUPINFO si;
561 PROCESS_INFORMATION pi;
562 struct strbuf envblk, args;
563 unsigned flags;
564 BOOL ret;
566 /* Determine whether or not we are associated to a console */
567 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
568 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
569 FILE_ATTRIBUTE_NORMAL, NULL);
570 if (cons == INVALID_HANDLE_VALUE) {
571 /* There is no console associated with this process.
572 * Since the child is a console process, Windows
573 * would normally create a console window. But
574 * since we'll be redirecting std streams, we do
575 * not need the console.
577 flags = CREATE_NO_WINDOW;
578 } else {
579 /* There is already a console. If we specified
580 * CREATE_NO_WINDOW here, too, Windows would
581 * disassociate the child from the console.
582 * Go figure!
584 flags = 0;
585 CloseHandle(cons);
587 memset(&si, 0, sizeof(si));
588 si.cb = sizeof(si);
589 si.dwFlags = STARTF_USESTDHANDLES;
590 si.hStdInput = (HANDLE) _get_osfhandle(0);
591 si.hStdOutput = (HANDLE) _get_osfhandle(1);
592 si.hStdError = (HANDLE) _get_osfhandle(2);
594 /* concatenate argv, quoting args as we go */
595 strbuf_init(&args, 0);
596 if (prepend_cmd) {
597 char *quoted = (char *)quote_arg(cmd);
598 strbuf_addstr(&args, quoted);
599 if (quoted != cmd)
600 free(quoted);
602 for (; *argv; argv++) {
603 char *quoted = (char *)quote_arg(*argv);
604 if (*args.buf)
605 strbuf_addch(&args, ' ');
606 strbuf_addstr(&args, quoted);
607 if (quoted != *argv)
608 free(quoted);
611 if (env) {
612 int count = 0;
613 char **e, **sorted_env;
615 for (e = env; *e; e++)
616 count++;
618 /* environment must be sorted */
619 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
620 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
621 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
623 strbuf_init(&envblk, 0);
624 for (e = sorted_env; *e; e++) {
625 strbuf_addstr(&envblk, *e);
626 strbuf_addch(&envblk, '\0');
628 free(sorted_env);
631 memset(&pi, 0, sizeof(pi));
632 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
633 env ? envblk.buf : NULL, NULL, &si, &pi);
635 if (env)
636 strbuf_release(&envblk);
637 strbuf_release(&args);
639 if (!ret) {
640 errno = ENOENT;
641 return -1;
643 CloseHandle(pi.hThread);
644 return (pid_t)pi.hProcess;
647 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
649 pid_t pid;
650 char **path = get_path_split();
651 char *prog = path_lookup(cmd, path, 0);
653 if (!prog) {
654 errno = ENOENT;
655 pid = -1;
657 else {
658 const char *interpr = parse_interpreter(prog);
660 if (interpr) {
661 const char *argv0 = argv[0];
662 char *iprog = path_lookup(interpr, path, 1);
663 argv[0] = prog;
664 if (!iprog) {
665 errno = ENOENT;
666 pid = -1;
668 else {
669 pid = mingw_spawnve(iprog, argv, env, 1);
670 free(iprog);
672 argv[0] = argv0;
674 else
675 pid = mingw_spawnve(prog, argv, env, 0);
676 free(prog);
678 free_path_split(path);
679 return pid;
682 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
684 const char *interpr = parse_interpreter(cmd);
685 char **path;
686 char *prog;
687 int pid = 0;
689 if (!interpr)
690 return 0;
691 path = get_path_split();
692 prog = path_lookup(interpr, path, 1);
693 if (prog) {
694 int argc = 0;
695 const char **argv2;
696 while (argv[argc]) argc++;
697 argv2 = xmalloc(sizeof(*argv) * (argc+1));
698 argv2[0] = (char *)cmd; /* full path to the script file */
699 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
700 pid = mingw_spawnve(prog, argv2, env, 1);
701 if (pid >= 0) {
702 int status;
703 if (waitpid(pid, &status, 0) < 0)
704 status = 255;
705 exit(status);
707 pid = 1; /* indicate that we tried but failed */
708 free(prog);
709 free(argv2);
711 free_path_split(path);
712 return pid;
715 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
717 /* check if git_command is a shell script */
718 if (!try_shell_exec(cmd, argv, (char **)env)) {
719 int pid, status;
721 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
722 if (pid < 0)
723 return;
724 if (waitpid(pid, &status, 0) < 0)
725 status = 255;
726 exit(status);
730 void mingw_execvp(const char *cmd, char *const *argv)
732 char **path = get_path_split();
733 char *prog = path_lookup(cmd, path, 0);
735 if (prog) {
736 mingw_execve(prog, argv, environ);
737 free(prog);
738 } else
739 errno = ENOENT;
741 free_path_split(path);
744 char **copy_environ()
746 char **env;
747 int i = 0;
748 while (environ[i])
749 i++;
750 env = xmalloc((i+1)*sizeof(*env));
751 for (i = 0; environ[i]; i++)
752 env[i] = xstrdup(environ[i]);
753 env[i] = NULL;
754 return env;
757 void free_environ(char **env)
759 int i;
760 for (i = 0; env[i]; i++)
761 free(env[i]);
762 free(env);
765 static int lookup_env(char **env, const char *name, size_t nmln)
767 int i;
769 for (i = 0; env[i]; i++) {
770 if (0 == strncmp(env[i], name, nmln)
771 && '=' == env[i][nmln])
772 /* matches */
773 return i;
775 return -1;
779 * If name contains '=', then sets the variable, otherwise it unsets it
781 char **env_setenv(char **env, const char *name)
783 char *eq = strchrnul(name, '=');
784 int i = lookup_env(env, name, eq-name);
786 if (i < 0) {
787 if (*eq) {
788 for (i = 0; env[i]; i++)
790 env = xrealloc(env, (i+2)*sizeof(*env));
791 env[i] = xstrdup(name);
792 env[i+1] = NULL;
795 else {
796 free(env[i]);
797 if (*eq)
798 env[i] = xstrdup(name);
799 else
800 for (; env[i]; i++)
801 env[i] = env[i+1];
803 return env;
806 /* this is the first function to call into WS_32; initialize it */
807 #undef gethostbyname
808 struct hostent *mingw_gethostbyname(const char *host)
810 WSADATA wsa;
812 if (WSAStartup(MAKEWORD(2,2), &wsa))
813 die("unable to initialize winsock subsystem, error %d",
814 WSAGetLastError());
815 atexit((void(*)(void)) WSACleanup);
816 return gethostbyname(host);
819 int mingw_socket(int domain, int type, int protocol)
821 int sockfd;
822 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
823 if (s == INVALID_SOCKET) {
825 * WSAGetLastError() values are regular BSD error codes
826 * biased by WSABASEERR.
827 * However, strerror() does not know about networking
828 * specific errors, which are values beginning at 38 or so.
829 * Therefore, we choose to leave the biased error code
830 * in errno so that _if_ someone looks up the code somewhere,
831 * then it is at least the number that are usually listed.
833 errno = WSAGetLastError();
834 return -1;
836 /* convert into a file descriptor */
837 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
838 closesocket(s);
839 return error("unable to make a socket file descriptor: %s",
840 strerror(errno));
842 return sockfd;
845 #undef connect
846 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
848 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
849 return connect(s, sa, sz);
852 #undef rename
853 int mingw_rename(const char *pold, const char *pnew)
856 * Try native rename() first to get errno right.
857 * It is based on MoveFile(), which cannot overwrite existing files.
859 if (!rename(pold, pnew))
860 return 0;
861 if (errno != EEXIST)
862 return -1;
863 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
864 return 0;
865 /* TODO: translate more errors */
866 if (GetLastError() == ERROR_ACCESS_DENIED) {
867 DWORD attrs = GetFileAttributes(pnew);
868 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
869 errno = EISDIR;
870 return -1;
873 errno = EACCES;
874 return -1;
877 struct passwd *getpwuid(int uid)
879 static char user_name[100];
880 static struct passwd p;
882 DWORD len = sizeof(user_name);
883 if (!GetUserName(user_name, &len))
884 return NULL;
885 p.pw_name = user_name;
886 p.pw_gecos = "unknown";
887 p.pw_dir = NULL;
888 return &p;
891 static HANDLE timer_event;
892 static HANDLE timer_thread;
893 static int timer_interval;
894 static int one_shot;
895 static sig_handler_t timer_fn = SIG_DFL;
897 /* The timer works like this:
898 * The thread, ticktack(), is basically a trivial routine that most of the
899 * time only waits to receive the signal to terminate. The main thread
900 * tells the thread to terminate by setting the timer_event to the signalled
901 * state.
902 * But ticktack() does not wait indefinitely; instead, it interrupts the
903 * wait state every now and then, namely exactly after timer's interval
904 * length. At these opportunities it calls the signal handler.
907 static __stdcall unsigned ticktack(void *dummy)
909 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
910 if (timer_fn == SIG_DFL)
911 die("Alarm");
912 if (timer_fn != SIG_IGN)
913 timer_fn(SIGALRM);
914 if (one_shot)
915 break;
917 return 0;
920 static int start_timer_thread(void)
922 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
923 if (timer_event) {
924 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
925 if (!timer_thread )
926 return errno = ENOMEM,
927 error("cannot start timer thread");
928 } else
929 return errno = ENOMEM,
930 error("cannot allocate resources timer");
931 return 0;
934 static void stop_timer_thread(void)
936 if (timer_event)
937 SetEvent(timer_event); /* tell thread to terminate */
938 if (timer_thread) {
939 int rc = WaitForSingleObject(timer_thread, 1000);
940 if (rc == WAIT_TIMEOUT)
941 error("timer thread did not terminate timely");
942 else if (rc != WAIT_OBJECT_0)
943 error("waiting for timer thread failed: %lu",
944 GetLastError());
945 CloseHandle(timer_thread);
947 if (timer_event)
948 CloseHandle(timer_event);
949 timer_event = NULL;
950 timer_thread = NULL;
953 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
955 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
958 int setitimer(int type, struct itimerval *in, struct itimerval *out)
960 static const struct timeval zero;
961 static int atexit_done;
963 if (out != NULL)
964 return errno = EINVAL,
965 error("setitmer param 3 != NULL not implemented");
966 if (!is_timeval_eq(&in->it_interval, &zero) &&
967 !is_timeval_eq(&in->it_interval, &in->it_value))
968 return errno = EINVAL,
969 error("setitmer: it_interval must be zero or eq it_value");
971 if (timer_thread)
972 stop_timer_thread();
974 if (is_timeval_eq(&in->it_value, &zero) &&
975 is_timeval_eq(&in->it_interval, &zero))
976 return 0;
978 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
979 one_shot = is_timeval_eq(&in->it_interval, &zero);
980 if (!atexit_done) {
981 atexit(stop_timer_thread);
982 atexit_done = 1;
984 return start_timer_thread();
987 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
989 if (sig != SIGALRM)
990 return errno = EINVAL,
991 error("sigaction only implemented for SIGALRM");
992 if (out != NULL)
993 return errno = EINVAL,
994 error("sigaction: param 3 != NULL not implemented");
996 timer_fn = in->sa_handler;
997 return 0;
1000 #undef signal
1001 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1003 if (sig != SIGALRM)
1004 return signal(sig, handler);
1005 sig_handler_t old = timer_fn;
1006 timer_fn = handler;
1007 return old;