Revert "do not inherit handles into child processes"
[git-cheetah/kirill.git] / compat / mingw.c
blob288e1520d5156251e9315cc993b06ca7201c31a7
1 #include "../common/git-compat-util.h"
2 #include "../common/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 int fd;
13 va_start(args, oflags);
14 mode = va_arg(args, int);
15 va_end(args);
17 if (!strcmp(filename, "/dev/null"))
18 filename = "nul";
19 fd = open(filename, oflags, mode);
20 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
21 DWORD attrs = GetFileAttributes(filename);
22 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
23 errno = EISDIR;
25 return fd;
28 static inline time_t filetime_to_time_t(const FILETIME *ft)
30 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
31 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
32 winTime /= 10000000; /* Nano to seconds resolution */
33 return (time_t)winTime;
36 static inline size_t size_to_blocks(size_t s)
38 return (s+511)/512;
41 extern int _getdrive( void );
42 /* We keep the do_lstat code in a separate function to avoid recursion.
43 * When a path ends with a slash, the stat will fail with ENOENT. In
44 * this case, we strip the trailing slashes and stat again.
46 static int do_lstat(const char *file_name, struct stat *buf)
48 WIN32_FILE_ATTRIBUTE_DATA fdata;
50 if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
51 int fMode = S_IREAD;
52 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
53 fMode |= S_IFDIR;
54 else
55 fMode |= S_IFREG;
56 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
57 fMode |= S_IWRITE;
59 buf->st_ino = 0;
60 buf->st_gid = 0;
61 buf->st_uid = 0;
62 buf->st_mode = fMode;
63 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
64 buf->st_blocks = size_to_blocks(buf->st_size);
65 buf->st_dev = _getdrive() - 1;
66 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
67 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
68 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
69 errno = 0;
70 return 0;
73 switch (GetLastError()) {
74 case ERROR_ACCESS_DENIED:
75 case ERROR_SHARING_VIOLATION:
76 case ERROR_LOCK_VIOLATION:
77 case ERROR_SHARING_BUFFER_EXCEEDED:
78 errno = EACCES;
79 break;
80 case ERROR_BUFFER_OVERFLOW:
81 errno = ENAMETOOLONG;
82 break;
83 case ERROR_NOT_ENOUGH_MEMORY:
84 errno = ENOMEM;
85 break;
86 default:
87 errno = ENOENT;
88 break;
90 return -1;
93 /* We provide our own lstat/fstat functions, since the provided
94 * lstat/fstat functions are so slow. These stat functions are
95 * tailored for Git's usage (read: fast), and are not meant to be
96 * complete. Note that Git stat()s are redirected to mingw_lstat()
97 * too, since Windows doesn't really handle symlinks that well.
99 int mingw_lstat(const char *file_name, struct mingw_stat *buf)
101 int namelen;
102 static char alt_name[PATH_MAX];
104 if (!do_lstat(file_name, buf))
105 return 0;
107 /* if file_name ended in a '/', Windows returned ENOENT;
108 * try again without trailing slashes
110 if (errno != ENOENT)
111 return -1;
113 namelen = strlen(file_name);
114 if (namelen && file_name[namelen-1] != '/')
115 return -1;
116 while (namelen && file_name[namelen-1] == '/')
117 --namelen;
118 if (!namelen || namelen >= PATH_MAX)
119 return -1;
121 memcpy(alt_name, file_name, namelen);
122 alt_name[namelen] = 0;
123 return do_lstat(alt_name, buf);
126 #undef fstat
127 #undef stat
128 int mingw_fstat(int fd, struct mingw_stat *buf)
130 HANDLE fh = (HANDLE)_get_osfhandle(fd);
131 BY_HANDLE_FILE_INFORMATION fdata;
133 if (fh == INVALID_HANDLE_VALUE) {
134 errno = EBADF;
135 return -1;
137 /* direct non-file handles to MS's fstat() */
138 if (GetFileType(fh) != FILE_TYPE_DISK) {
139 struct stat st;
140 if (fstat(fd, &st))
141 return -1;
142 buf->st_ino = st.st_ino;
143 buf->st_gid = st.st_gid;
144 buf->st_uid = st.st_uid;
145 buf->st_mode = st.st_mode;
146 buf->st_size = st.st_size;
147 buf->st_blocks = size_to_blocks(buf->st_size);
148 buf->st_dev = st.st_dev;
149 buf->st_atime = st.st_atime;
150 buf->st_mtime = st.st_mtime;
151 buf->st_ctime = st.st_ctime;
152 return 0;
155 if (GetFileInformationByHandle(fh, &fdata)) {
156 int fMode = S_IREAD;
157 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
158 fMode |= S_IFDIR;
159 else
160 fMode |= S_IFREG;
161 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
162 fMode |= S_IWRITE;
164 buf->st_ino = 0;
165 buf->st_gid = 0;
166 buf->st_uid = 0;
167 buf->st_mode = fMode;
168 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
169 buf->st_blocks = size_to_blocks(buf->st_size);
170 buf->st_dev = _getdrive() - 1;
171 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
172 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
173 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
174 return 0;
176 errno = EBADF;
177 return -1;
180 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
182 long long winTime = t * 10000000LL + 116444736000000000LL;
183 ft->dwLowDateTime = (DWORD)winTime;
184 ft->dwHighDateTime = winTime >> 32;
187 int mingw_utime (const char *file_name, const struct utimbuf *times)
189 FILETIME mft, aft;
190 int fh, rc;
192 /* must have write permission */
193 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
194 return -1;
196 time_t_to_filetime(times->modtime, &mft);
197 time_t_to_filetime(times->actime, &aft);
198 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
199 errno = EINVAL;
200 rc = -1;
201 } else
202 rc = 0;
203 close(fh);
204 return rc;
207 unsigned int sleep (unsigned int seconds)
209 Sleep(seconds*1000);
210 return 0;
213 int mkstemp(char *template)
215 char *filename = mktemp(template);
216 if (filename == NULL)
217 return -1;
218 return open(filename, O_RDWR | O_CREAT, 0600);
221 int gettimeofday(struct timeval *tv, void *tz)
223 SYSTEMTIME st;
224 struct tm tm;
225 GetSystemTime(&st);
226 tm.tm_year = st.wYear-1900;
227 tm.tm_mon = st.wMonth-1;
228 tm.tm_mday = st.wDay;
229 tm.tm_hour = st.wHour;
230 tm.tm_min = st.wMinute;
231 tm.tm_sec = st.wSecond;
232 tv->tv_sec = tm_to_time_t(&tm);
233 if (tv->tv_sec < 0)
234 return -1;
235 tv->tv_usec = st.wMilliseconds*1000;
236 return 0;
239 int pipe(int filedes[2])
241 int fd;
242 HANDLE h[2], parent;
244 if (_pipe(filedes, 8192, 0) < 0)
245 return -1;
247 parent = GetCurrentProcess();
249 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
250 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
251 close(filedes[0]);
252 close(filedes[1]);
253 return -1;
255 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
256 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
257 close(filedes[0]);
258 close(filedes[1]);
259 CloseHandle(h[0]);
260 return -1;
262 fd = _open_osfhandle((intptr_t)h[0], O_NOINHERIT);
263 if (fd < 0) {
264 close(filedes[0]);
265 close(filedes[1]);
266 CloseHandle(h[0]);
267 CloseHandle(h[1]);
268 return -1;
270 close(filedes[0]);
271 filedes[0] = fd;
272 fd = _open_osfhandle((intptr_t)h[1], O_NOINHERIT);
273 if (fd < 0) {
274 close(filedes[0]);
275 close(filedes[1]);
276 CloseHandle(h[1]);
277 return -1;
279 close(filedes[1]);
280 filedes[1] = fd;
281 return 0;
284 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
286 unsigned int i;
287 int pending;
289 if (timeout != -1)
290 return errno = EINVAL, error("poll timeout not supported");
292 /* When there is only one fd to wait for, then we pretend that
293 * input is available and let the actual wait happen when the
294 * caller invokes read().
296 if (nfds == 1) {
297 if (!(ufds[0].events & POLLIN))
298 return errno = EINVAL, error("POLLIN not set");
299 ufds[0].revents = POLLIN;
300 return 0;
303 repeat:
304 pending = 0;
305 for (i = 0; i < nfds; i++) {
306 DWORD avail = 0;
307 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
308 if (h == INVALID_HANDLE_VALUE)
309 return -1; /* errno was set */
311 if (!(ufds[i].events & POLLIN))
312 return errno = EINVAL, error("POLLIN not set");
314 /* this emulation works only for pipes */
315 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
316 int err = GetLastError();
317 if (err == ERROR_BROKEN_PIPE) {
318 ufds[i].revents = POLLHUP;
319 pending++;
320 } else {
321 errno = EINVAL;
322 return error("PeekNamedPipe failed,"
323 " GetLastError: %u", err);
325 } else if (avail) {
326 ufds[i].revents = POLLIN;
327 pending++;
328 } else
329 ufds[i].revents = 0;
331 if (!pending) {
332 /* The only times that we spin here is when the process
333 * that is connected through the pipes is waiting for
334 * its own input data to become available. But since
335 * the process (pack-objects) is itself CPU intensive,
336 * it will happily pick up the time slice that we are
337 * relinguishing here.
339 Sleep(0);
340 goto repeat;
342 return 0;
345 struct tm *gmtime_r(const time_t *timep, struct tm *result)
347 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
348 memcpy(result, gmtime(timep), sizeof(struct tm));
349 return result;
352 struct tm *localtime_r(const time_t *timep, struct tm *result)
354 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
355 memcpy(result, localtime(timep), sizeof(struct tm));
356 return result;
359 #undef getcwd
360 char *mingw_getcwd(char *pointer, int len)
362 int i;
363 char *ret = getcwd(pointer, len);
364 if (!ret)
365 return ret;
366 for (i = 0; pointer[i]; i++)
367 if (pointer[i] == '\\')
368 pointer[i] = '/';
369 return ret;
372 #undef getenv
373 char *mingw_getenv(const char *name)
375 char *result = getenv(name);
376 if (!result && !strcmp(name, "TMPDIR")) {
377 /* on Windows it is TMP and TEMP */
378 result = getenv("TMP");
379 if (!result)
380 result = getenv("TEMP");
382 return result;
386 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
387 * (Parsing C++ Command-Line Arguments)
389 static const char *quote_arg(const char *arg)
391 /* count chars to quote */
392 int len = 0, n = 0;
393 int force_quotes = 0;
394 char *q, *d;
395 const char *p = arg;
396 if (!*p) force_quotes = 1;
397 while (*p) {
398 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
399 force_quotes = 1;
400 else if (*p == '"')
401 n++;
402 else if (*p == '\\') {
403 int count = 0;
404 while (*p == '\\') {
405 count++;
406 p++;
407 len++;
409 if (*p == '"')
410 n += count*2 + 1;
411 continue;
413 len++;
414 p++;
416 if (!force_quotes && n == 0)
417 return arg;
419 /* insert \ where necessary */
420 d = q = xmalloc(len+n+3);
421 *d++ = '"';
422 while (*arg) {
423 if (*arg == '"')
424 *d++ = '\\';
425 else if (*arg == '\\') {
426 int count = 0;
427 while (*arg == '\\') {
428 count++;
429 *d++ = *arg++;
431 if (*arg == '"') {
432 while (count-- > 0)
433 *d++ = '\\';
434 *d++ = '\\';
437 *d++ = *arg++;
439 *d++ = '"';
440 *d++ = 0;
441 return q;
444 static const char *parse_interpreter(const char *cmd)
446 static char buf[100];
447 char *p, *opt;
448 int n, fd;
450 /* don't even try a .exe */
451 n = strlen(cmd);
452 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
453 return NULL;
455 fd = open(cmd, O_RDONLY);
456 if (fd < 0)
457 return NULL;
458 n = read(fd, buf, sizeof(buf)-1);
459 close(fd);
460 if (n < 4) /* at least '#!/x' and not error */
461 return NULL;
463 if (buf[0] != '#' || buf[1] != '!')
464 return NULL;
465 buf[n] = '\0';
466 p = buf + strcspn(buf, "\r\n");
467 if (!*p)
468 return NULL;
470 *p = '\0';
471 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
472 return NULL;
473 /* strip options */
474 if ((opt = strchr(p+1, ' ')))
475 *opt = '\0';
476 return p+1;
480 * returns value of PATH environment variable in the given environment or
481 * in the system environment if NULL == env
483 static char *get_path(char **env)
485 char **e;
486 if (!env)
487 return getenv("PATH");
489 for (e = env; *e; e++) {
490 /* if it's PATH variable (could be Path= too!) */
491 if (!strnicmp(*e, "PATH=", 5)) {
492 return *e + 5;
496 return NULL;
500 * Splits the PATH into parts.
502 static char **get_path_split(char **env)
504 char *p, **path, *envpath = get_path(env);
505 int i, n = 0;
507 if (!envpath || !*envpath)
508 return NULL;
510 envpath = xstrdup(envpath);
511 p = envpath;
512 while (p) {
513 char *dir = p;
514 p = strchr(p, ';');
515 if (p) *p++ = '\0';
516 if (*dir) { /* not earlier, catches series of ; */
517 ++n;
520 if (!n)
521 return NULL;
523 path = xmalloc((n+1)*sizeof(char*));
524 p = envpath;
525 i = 0;
526 do {
527 if (*p)
528 path[i++] = xstrdup(p);
529 p = p+strlen(p)+1;
530 } while (i < n);
531 path[i] = NULL;
533 free(envpath);
535 return path;
538 static void free_path_split(char **path)
540 char **p;
541 if (!path)
542 return;
544 p = path;
545 while (*p)
546 free(*p++);
547 free(path);
551 * exe_only means that we only want to detect .exe files, but not scripts
552 * (which do not have an extension)
554 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
556 char path[MAX_PATH];
557 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
559 if (!isexe && access(path, F_OK) == 0)
560 return xstrdup(path);
561 path[strlen(path)-4] = '\0';
562 if ((!exe_only || isexe) && access(path, F_OK) == 0)
563 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
564 return xstrdup(path);
565 return NULL;
569 * Determines the absolute path of cmd using the the split path in path.
570 * If cmd contains a slash or backslash, no lookup is performed.
572 static char *path_lookup(const char *cmd, char **path, int exe_only)
574 char *prog = NULL;
575 int len = strlen(cmd);
576 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
578 if (strchr(cmd, '/') || strchr(cmd, '\\'))
579 prog = xstrdup(cmd);
581 while (!prog && *path)
582 prog = lookup_prog(*path++, cmd, isexe, exe_only);
584 return prog;
587 static int env_compare(const void *a, const void *b)
589 char *const *ea = a;
590 char *const *eb = b;
591 return strcasecmp(*ea, *eb);
594 static pid_t mingw_spawnve_cwd(const char *cmd, const char **argv, char **env,
595 int prepend_cmd, const char *working_directory)
597 STARTUPINFO si;
598 PROCESS_INFORMATION pi;
599 struct strbuf envblk, args;
600 unsigned flags;
601 BOOL ret;
603 /* Determine whether or not we are associated to a console */
604 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
605 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
606 FILE_ATTRIBUTE_NORMAL, NULL);
607 if (cons == INVALID_HANDLE_VALUE) {
608 /* There is no console associated with this process.
609 * Since the child is a console process, Windows
610 * would normally create a console window. But
611 * since we'll be redirecting std streams, we do
612 * not need the console.
614 flags = CREATE_NO_WINDOW;
615 } else {
616 /* There is already a console. If we specified
617 * CREATE_NO_WINDOW here, too, Windows would
618 * disassociate the child from the console.
619 * Go figure!
621 flags = 0;
622 CloseHandle(cons);
624 memset(&si, 0, sizeof(si));
625 si.cb = sizeof(si);
626 si.dwFlags = STARTF_USESTDHANDLES;
627 si.hStdInput = (HANDLE) _get_osfhandle(0);
628 si.hStdOutput = (HANDLE) _get_osfhandle(1);
629 si.hStdError = (HANDLE) _get_osfhandle(2);
631 /* concatenate argv, quoting args as we go */
632 strbuf_init(&args, 0);
633 if (prepend_cmd) {
634 char *quoted = (char *)quote_arg(cmd);
635 strbuf_addstr(&args, quoted);
636 if (quoted != cmd)
637 free(quoted);
639 for (; *argv; argv++) {
640 char *quoted = (char *)quote_arg(*argv);
641 if (*args.buf)
642 strbuf_addch(&args, ' ');
643 strbuf_addstr(&args, quoted);
644 if (quoted != *argv)
645 free(quoted);
648 if (env) {
649 int count = 0;
650 char **e, **sorted_env;
652 for (e = env; *e; e++)
653 count++;
655 /* environment must be sorted */
656 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
657 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
658 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
660 strbuf_init(&envblk, 0);
661 for (e = sorted_env; *e; e++) {
662 strbuf_addstr(&envblk, *e);
663 strbuf_addch(&envblk, '\0');
665 free(sorted_env);
668 memset(&pi, 0, sizeof(pi));
669 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
670 env ? envblk.buf : NULL, working_directory, &si, &pi);
672 if (env)
673 strbuf_release(&envblk);
674 strbuf_release(&args);
676 if (!ret) {
677 errno = ENOENT;
678 return -1;
680 CloseHandle(pi.hThread);
681 return (pid_t)pi.hProcess;
684 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
685 int prepend_cmd)
687 return mingw_spawnve_cwd(cmd, argv, env, prepend_cmd, NULL);
690 pid_t mingw_spawnvpe_cwd(const char *cmd, const char **argv, char **env,
691 const char *working_directory)
693 pid_t pid;
694 char **path = get_path_split(env);
695 char *prog = path_lookup(cmd, path, 0);
697 if (!prog) {
698 errno = ENOENT;
699 pid = -1;
701 else {
702 const char *interpr = parse_interpreter(prog);
704 if (interpr) {
705 const char *argv0 = argv[0];
706 char *iprog = path_lookup(interpr, path, 1);
707 argv[0] = prog;
708 if (!iprog) {
709 errno = ENOENT;
710 pid = -1;
712 else {
713 pid = mingw_spawnve_cwd(iprog, argv, env, 1,
714 working_directory);
715 free(iprog);
717 argv[0] = argv0;
719 else
720 pid = mingw_spawnve_cwd(prog, argv, env, 0,
721 working_directory);
722 free(prog);
724 free_path_split(path);
725 return pid;
728 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
730 return mingw_spawnvpe_cwd(cmd, argv, env, NULL);
733 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
735 const char *interpr = parse_interpreter(cmd);
736 char **path;
737 char *prog;
738 int pid = 0;
740 if (!interpr)
741 return 0;
742 path = get_path_split(env);
743 prog = path_lookup(interpr, path, 1);
744 if (prog) {
745 int argc = 0;
746 const char **argv2;
747 while (argv[argc]) argc++;
748 argv2 = xmalloc(sizeof(*argv) * (argc+1));
749 argv2[0] = (char *)cmd; /* full path to the script file */
750 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
751 pid = mingw_spawnve(prog, argv2, env, 1);
752 if (pid >= 0) {
753 int status;
754 if (waitpid(pid, &status, 0) < 0)
755 status = 255;
756 exit(status);
758 pid = 1; /* indicate that we tried but failed */
759 free(prog);
760 free(argv2);
762 free_path_split(path);
763 return pid;
766 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
768 /* check if git_command is a shell script */
769 if (!try_shell_exec(cmd, argv, (char **)env)) {
770 int pid, status;
772 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
773 if (pid < 0)
774 return;
775 if (waitpid(pid, &status, 0) < 0)
776 status = 255;
777 exit(status);
781 void mingw_execvp(const char *cmd, char *const *argv)
783 char **path = get_path_split(NULL);
784 char *prog = path_lookup(cmd, path, 0);
786 if (prog) {
787 mingw_execve(prog, argv, environ);
788 free(prog);
789 } else
790 errno = ENOENT;
792 free_path_split(path);
795 char **copy_environ()
797 char **env;
798 int i = 0;
799 while (environ[i])
800 i++;
801 env = xmalloc((i+1)*sizeof(*env));
802 for (i = 0; environ[i]; i++)
803 env[i] = xstrdup(environ[i]);
804 env[i] = NULL;
805 return env;
808 void free_environ(char **env)
810 int i;
811 for (i = 0; env[i]; i++)
812 free(env[i]);
813 free(env);
816 static int lookup_env(char **env, const char *name, size_t nmln)
818 int i;
820 for (i = 0; env[i]; i++) {
821 if (0 == strncmp(env[i], name, nmln)
822 && '=' == env[i][nmln])
823 /* matches */
824 return i;
826 return -1;
830 * If name contains '=', then sets the variable, otherwise it unsets it
832 char **env_setenv(char **env, const char *name)
834 char *eq = strchrnul(name, '=');
835 int i = lookup_env(env, name, eq-name);
837 if (i < 0) {
838 if (*eq) {
839 for (i = 0; env[i]; i++)
841 env = xrealloc(env, (i+2)*sizeof(*env));
842 env[i] = xstrdup(name);
843 env[i+1] = NULL;
846 else {
847 free(env[i]);
848 if (*eq)
849 env[i] = xstrdup(name);
850 else
851 for (; env[i]; i++)
852 env[i] = env[i+1];
854 return env;
857 /* this is the first function to call into WS_32; initialize it */
858 #undef gethostbyname
859 struct hostent *mingw_gethostbyname(const char *host)
861 WSADATA wsa;
863 if (WSAStartup(MAKEWORD(2,2), &wsa))
864 die("unable to initialize winsock subsystem, error %d",
865 WSAGetLastError());
866 atexit((void(*)(void)) WSACleanup);
867 return gethostbyname(host);
870 int mingw_socket(int domain, int type, int protocol)
872 int sockfd;
873 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
874 if (s == INVALID_SOCKET) {
876 * WSAGetLastError() values are regular BSD error codes
877 * biased by WSABASEERR.
878 * However, strerror() does not know about networking
879 * specific errors, which are values beginning at 38 or so.
880 * Therefore, we choose to leave the biased error code
881 * in errno so that _if_ someone looks up the code somewhere,
882 * then it is at least the number that are usually listed.
884 errno = WSAGetLastError();
885 return -1;
887 /* convert into a file descriptor */
888 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
889 closesocket(s);
890 return error("unable to make a socket file descriptor: %s",
891 strerror(errno));
893 return sockfd;
896 #undef connect
897 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
899 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
900 return connect(s, sa, sz);
903 #undef rename
904 int mingw_rename(const char *pold, const char *pnew)
907 * Try native rename() first to get errno right.
908 * It is based on MoveFile(), which cannot overwrite existing files.
910 if (!rename(pold, pnew))
911 return 0;
912 if (errno != EEXIST)
913 return -1;
914 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
915 return 0;
916 /* TODO: translate more errors */
917 if (GetLastError() == ERROR_ACCESS_DENIED) {
918 DWORD attrs = GetFileAttributes(pnew);
919 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
920 errno = EISDIR;
921 return -1;
924 errno = EACCES;
925 return -1;
928 struct passwd *getpwuid(int uid)
930 static char user_name[100];
931 static struct passwd p;
933 DWORD len = sizeof(user_name);
934 if (!GetUserName(user_name, &len))
935 return NULL;
936 p.pw_name = user_name;
937 p.pw_gecos = "unknown";
938 p.pw_dir = NULL;
939 return &p;
942 static HANDLE timer_event;
943 static HANDLE timer_thread;
944 static int timer_interval;
945 static int one_shot;
946 static sig_handler_t timer_fn = SIG_DFL;
948 /* The timer works like this:
949 * The thread, ticktack(), is a trivial routine that most of the time
950 * only waits to receive the signal to terminate. The main thread tells
951 * the thread to terminate by setting the timer_event to the signalled
952 * state.
953 * But ticktack() interrupts the wait state after the timer's interval
954 * length to call the signal handler.
957 static unsigned __stdcall ticktack(void *dummy)
959 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
960 if (timer_fn == SIG_DFL)
961 die("Alarm");
962 if (timer_fn != SIG_IGN)
963 timer_fn(SIGALRM);
964 if (one_shot)
965 break;
967 return 0;
970 static int start_timer_thread(void)
972 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
973 if (timer_event) {
974 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
975 if (!timer_thread )
976 return errno = ENOMEM,
977 error("cannot start timer thread");
978 } else
979 return errno = ENOMEM,
980 error("cannot allocate resources for timer");
981 return 0;
984 static void stop_timer_thread(void)
986 if (timer_event)
987 SetEvent(timer_event); /* tell thread to terminate */
988 if (timer_thread) {
989 int rc = WaitForSingleObject(timer_thread, 1000);
990 if (rc == WAIT_TIMEOUT)
991 error("timer thread did not terminate timely");
992 else if (rc != WAIT_OBJECT_0)
993 error("waiting for timer thread failed: %lu",
994 GetLastError());
995 CloseHandle(timer_thread);
997 if (timer_event)
998 CloseHandle(timer_event);
999 timer_event = NULL;
1000 timer_thread = NULL;
1003 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1005 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1008 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1010 static const struct timeval zero;
1011 static int atexit_done;
1013 if (out != NULL)
1014 return errno = EINVAL,
1015 error("setitimer param 3 != NULL not implemented");
1016 if (!is_timeval_eq(&in->it_interval, &zero) &&
1017 !is_timeval_eq(&in->it_interval, &in->it_value))
1018 return errno = EINVAL,
1019 error("setitimer: it_interval must be zero or eq it_value");
1021 if (timer_thread)
1022 stop_timer_thread();
1024 if (is_timeval_eq(&in->it_value, &zero) &&
1025 is_timeval_eq(&in->it_interval, &zero))
1026 return 0;
1028 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1029 one_shot = is_timeval_eq(&in->it_interval, &zero);
1030 if (!atexit_done) {
1031 atexit(stop_timer_thread);
1032 atexit_done = 1;
1034 return start_timer_thread();
1037 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1039 if (sig != SIGALRM)
1040 return errno = EINVAL,
1041 error("sigaction only implemented for SIGALRM");
1042 if (out != NULL)
1043 return errno = EINVAL,
1044 error("sigaction: param 3 != NULL not implemented");
1046 timer_fn = in->sa_handler;
1047 return 0;
1050 #undef signal
1051 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1053 sig_handler_t old;
1055 if (sig != SIGALRM)
1056 return signal(sig, handler);
1057 old = timer_fn;
1058 timer_fn = handler;
1059 return old;
1062 static const char *make_backslash_path(const char *path)
1064 static char buf[PATH_MAX + 1];
1065 char *c;
1067 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1068 die("Too long path: %.*s", 60, path);
1070 for (c = buf; *c; c++) {
1071 if (*c == '/')
1072 *c = '\\';
1074 return buf;
1077 void mingw_open_html(const char *unixpath)
1079 const char *htmlpath = make_backslash_path(unixpath);
1080 printf("Launching default browser to display HTML ...\n");
1081 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);