Code

772cad510d5d260fdf33b4f7d6ff79f9f3367b05
[git.git] / compat / mingw.c
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, ...)
8 {
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;
22         }
23         return fd;
24 }
26 static inline time_t filetime_to_time_t(const FILETIME *ft)
27 {
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;
32 }
34 static inline size_t size_to_blocks(size_t s)
35 {
36         return (s+511)/512;
37 }
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.
43  */
44 static int do_lstat(const char *file_name, struct stat *buf)
45 {
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;
69         }
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;
87         }
88         return -1;
89 }
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.
96  */
97 int mingw_lstat(const char *file_name, struct mingw_stat *buf)
98 {
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
107          */
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;
134         }
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;
151         }
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;
173         }
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         SYSTEMTIME st;
222         struct tm tm;
223         GetSystemTime(&st);
224         tm.tm_year = st.wYear-1900;
225         tm.tm_mon = st.wMonth-1;
226         tm.tm_mday = st.wDay;
227         tm.tm_hour = st.wHour;
228         tm.tm_min = st.wMinute;
229         tm.tm_sec = st.wSecond;
230         tv->tv_sec = tm_to_time_t(&tm);
231         if (tv->tv_sec < 0)
232                 return -1;
233         tv->tv_usec = st.wMilliseconds*1000;
234         return 0;
237 int pipe(int filedes[2])
239         int fd;
240         HANDLE h[2], parent;
242         if (_pipe(filedes, 8192, 0) < 0)
243                 return -1;
245         parent = GetCurrentProcess();
247         if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
248                         parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
249                 close(filedes[0]);
250                 close(filedes[1]);
251                 return -1;
252         }
253         if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
254                         parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
255                 close(filedes[0]);
256                 close(filedes[1]);
257                 CloseHandle(h[0]);
258                 return -1;
259         }
260         fd = _open_osfhandle((int)h[0], O_NOINHERIT);
261         if (fd < 0) {
262                 close(filedes[0]);
263                 close(filedes[1]);
264                 CloseHandle(h[0]);
265                 CloseHandle(h[1]);
266                 return -1;
267         }
268         close(filedes[0]);
269         filedes[0] = fd;
270         fd = _open_osfhandle((int)h[1], O_NOINHERIT);
271         if (fd < 0) {
272                 close(filedes[0]);
273                 close(filedes[1]);
274                 CloseHandle(h[1]);
275                 return -1;
276         }
277         close(filedes[1]);
278         filedes[1] = fd;
279         return 0;
282 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
284         int i, pending;
286         if (timeout != -1)
287                 return errno = EINVAL, error("poll timeout not supported");
289         /* When there is only one fd to wait for, then we pretend that
290          * input is available and let the actual wait happen when the
291          * caller invokes read().
292          */
293         if (nfds == 1) {
294                 if (!(ufds[0].events & POLLIN))
295                         return errno = EINVAL, error("POLLIN not set");
296                 ufds[0].revents = POLLIN;
297                 return 0;
298         }
300 repeat:
301         pending = 0;
302         for (i = 0; i < nfds; i++) {
303                 DWORD avail = 0;
304                 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
305                 if (h == INVALID_HANDLE_VALUE)
306                         return -1;      /* errno was set */
308                 if (!(ufds[i].events & POLLIN))
309                         return errno = EINVAL, error("POLLIN not set");
311                 /* this emulation works only for pipes */
312                 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
313                         int err = GetLastError();
314                         if (err == ERROR_BROKEN_PIPE) {
315                                 ufds[i].revents = POLLHUP;
316                                 pending++;
317                         } else {
318                                 errno = EINVAL;
319                                 return error("PeekNamedPipe failed,"
320                                         " GetLastError: %u", err);
321                         }
322                 } else if (avail) {
323                         ufds[i].revents = POLLIN;
324                         pending++;
325                 } else
326                         ufds[i].revents = 0;
327         }
328         if (!pending) {
329                 /* The only times that we spin here is when the process
330                  * that is connected through the pipes is waiting for
331                  * its own input data to become available. But since
332                  * the process (pack-objects) is itself CPU intensive,
333                  * it will happily pick up the time slice that we are
334                  * relinguishing here.
335                  */
336                 Sleep(0);
337                 goto repeat;
338         }
339         return 0;
342 struct tm *gmtime_r(const time_t *timep, struct tm *result)
344         /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
345         memcpy(result, gmtime(timep), sizeof(struct tm));
346         return result;
349 struct tm *localtime_r(const time_t *timep, struct tm *result)
351         /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
352         memcpy(result, localtime(timep), sizeof(struct tm));
353         return result;
356 #undef getcwd
357 char *mingw_getcwd(char *pointer, int len)
359         int i;
360         char *ret = getcwd(pointer, len);
361         if (!ret)
362                 return ret;
363         for (i = 0; pointer[i]; i++)
364                 if (pointer[i] == '\\')
365                         pointer[i] = '/';
366         return ret;
369 #undef getenv
370 char *mingw_getenv(const char *name)
372         char *result = getenv(name);
373         if (!result && !strcmp(name, "TMPDIR")) {
374                 /* on Windows it is TMP and TEMP */
375                 result = getenv("TMP");
376                 if (!result)
377                         result = getenv("TEMP");
378         }
379         return result;
382 /*
383  * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
384  * (Parsing C++ Command-Line Arguments)
385  */
386 static const char *quote_arg(const char *arg)
388         /* count chars to quote */
389         int len = 0, n = 0;
390         int force_quotes = 0;
391         char *q, *d;
392         const char *p = arg;
393         if (!*p) force_quotes = 1;
394         while (*p) {
395                 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
396                         force_quotes = 1;
397                 else if (*p == '"')
398                         n++;
399                 else if (*p == '\\') {
400                         int count = 0;
401                         while (*p == '\\') {
402                                 count++;
403                                 p++;
404                                 len++;
405                         }
406                         if (*p == '"')
407                                 n += count*2 + 1;
408                         continue;
409                 }
410                 len++;
411                 p++;
412         }
413         if (!force_quotes && n == 0)
414                 return arg;
416         /* insert \ where necessary */
417         d = q = xmalloc(len+n+3);
418         *d++ = '"';
419         while (*arg) {
420                 if (*arg == '"')
421                         *d++ = '\\';
422                 else if (*arg == '\\') {
423                         int count = 0;
424                         while (*arg == '\\') {
425                                 count++;
426                                 *d++ = *arg++;
427                         }
428                         if (*arg == '"') {
429                                 while (count-- > 0)
430                                         *d++ = '\\';
431                                 *d++ = '\\';
432                         }
433                 }
434                 *d++ = *arg++;
435         }
436         *d++ = '"';
437         *d++ = 0;
438         return q;
441 static const char *parse_interpreter(const char *cmd)
443         static char buf[100];
444         char *p, *opt;
445         int n, fd;
447         /* don't even try a .exe */
448         n = strlen(cmd);
449         if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
450                 return NULL;
452         fd = open(cmd, O_RDONLY);
453         if (fd < 0)
454                 return NULL;
455         n = read(fd, buf, sizeof(buf)-1);
456         close(fd);
457         if (n < 4)      /* at least '#!/x' and not error */
458                 return NULL;
460         if (buf[0] != '#' || buf[1] != '!')
461                 return NULL;
462         buf[n] = '\0';
463         p = strchr(buf, '\n');
464         if (!p)
465                 return NULL;
467         *p = '\0';
468         if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
469                 return NULL;
470         /* strip options */
471         if ((opt = strchr(p+1, ' ')))
472                 *opt = '\0';
473         return p+1;
476 /*
477  * Splits the PATH into parts.
478  */
479 static char **get_path_split(void)
481         char *p, **path, *envpath = getenv("PATH");
482         int i, n = 0;
484         if (!envpath || !*envpath)
485                 return NULL;
487         envpath = xstrdup(envpath);
488         p = envpath;
489         while (p) {
490                 char *dir = p;
491                 p = strchr(p, ';');
492                 if (p) *p++ = '\0';
493                 if (*dir) {     /* not earlier, catches series of ; */
494                         ++n;
495                 }
496         }
497         if (!n)
498                 return NULL;
500         path = xmalloc((n+1)*sizeof(char*));
501         p = envpath;
502         i = 0;
503         do {
504                 if (*p)
505                         path[i++] = xstrdup(p);
506                 p = p+strlen(p)+1;
507         } while (i < n);
508         path[i] = NULL;
510         free(envpath);
512         return path;
515 static void free_path_split(char **path)
517         if (!path)
518                 return;
520         char **p = path;
521         while (*p)
522                 free(*p++);
523         free(path);
526 /*
527  * exe_only means that we only want to detect .exe files, but not scripts
528  * (which do not have an extension)
529  */
530 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
532         char path[MAX_PATH];
533         snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
535         if (!isexe && access(path, F_OK) == 0)
536                 return xstrdup(path);
537         path[strlen(path)-4] = '\0';
538         if ((!exe_only || isexe) && access(path, F_OK) == 0)
539                 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
540                         return xstrdup(path);
541         return NULL;
544 /*
545  * Determines the absolute path of cmd using the the split path in path.
546  * If cmd contains a slash or backslash, no lookup is performed.
547  */
548 static char *path_lookup(const char *cmd, char **path, int exe_only)
550         char *prog = NULL;
551         int len = strlen(cmd);
552         int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
554         if (strchr(cmd, '/') || strchr(cmd, '\\'))
555                 prog = xstrdup(cmd);
557         while (!prog && *path)
558                 prog = lookup_prog(*path++, cmd, isexe, exe_only);
560         return prog;
563 static int env_compare(const void *a, const void *b)
565         char *const *ea = a;
566         char *const *eb = b;
567         return strcasecmp(*ea, *eb);
570 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
571                            int prepend_cmd)
573         STARTUPINFO si;
574         PROCESS_INFORMATION pi;
575         struct strbuf envblk, args;
576         unsigned flags;
577         BOOL ret;
579         /* Determine whether or not we are associated to a console */
580         HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
581                         FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
582                         FILE_ATTRIBUTE_NORMAL, NULL);
583         if (cons == INVALID_HANDLE_VALUE) {
584                 /* There is no console associated with this process.
585                  * Since the child is a console process, Windows
586                  * would normally create a console window. But
587                  * since we'll be redirecting std streams, we do
588                  * not need the console.
589                  */
590                 flags = CREATE_NO_WINDOW;
591         } else {
592                 /* There is already a console. If we specified
593                  * CREATE_NO_WINDOW here, too, Windows would
594                  * disassociate the child from the console.
595                  * Go figure!
596                  */
597                 flags = 0;
598                 CloseHandle(cons);
599         }
600         memset(&si, 0, sizeof(si));
601         si.cb = sizeof(si);
602         si.dwFlags = STARTF_USESTDHANDLES;
603         si.hStdInput = (HANDLE) _get_osfhandle(0);
604         si.hStdOutput = (HANDLE) _get_osfhandle(1);
605         si.hStdError = (HANDLE) _get_osfhandle(2);
607         /* concatenate argv, quoting args as we go */
608         strbuf_init(&args, 0);
609         if (prepend_cmd) {
610                 char *quoted = (char *)quote_arg(cmd);
611                 strbuf_addstr(&args, quoted);
612                 if (quoted != cmd)
613                         free(quoted);
614         }
615         for (; *argv; argv++) {
616                 char *quoted = (char *)quote_arg(*argv);
617                 if (*args.buf)
618                         strbuf_addch(&args, ' ');
619                 strbuf_addstr(&args, quoted);
620                 if (quoted != *argv)
621                         free(quoted);
622         }
624         if (env) {
625                 int count = 0;
626                 char **e, **sorted_env;
628                 for (e = env; *e; e++)
629                         count++;
631                 /* environment must be sorted */
632                 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
633                 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
634                 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
636                 strbuf_init(&envblk, 0);
637                 for (e = sorted_env; *e; e++) {
638                         strbuf_addstr(&envblk, *e);
639                         strbuf_addch(&envblk, '\0');
640                 }
641                 free(sorted_env);
642         }
644         memset(&pi, 0, sizeof(pi));
645         ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
646                 env ? envblk.buf : NULL, NULL, &si, &pi);
648         if (env)
649                 strbuf_release(&envblk);
650         strbuf_release(&args);
652         if (!ret) {
653                 errno = ENOENT;
654                 return -1;
655         }
656         CloseHandle(pi.hThread);
657         return (pid_t)pi.hProcess;
660 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
662         pid_t pid;
663         char **path = get_path_split();
664         char *prog = path_lookup(cmd, path, 0);
666         if (!prog) {
667                 errno = ENOENT;
668                 pid = -1;
669         }
670         else {
671                 const char *interpr = parse_interpreter(prog);
673                 if (interpr) {
674                         const char *argv0 = argv[0];
675                         char *iprog = path_lookup(interpr, path, 1);
676                         argv[0] = prog;
677                         if (!iprog) {
678                                 errno = ENOENT;
679                                 pid = -1;
680                         }
681                         else {
682                                 pid = mingw_spawnve(iprog, argv, env, 1);
683                                 free(iprog);
684                         }
685                         argv[0] = argv0;
686                 }
687                 else
688                         pid = mingw_spawnve(prog, argv, env, 0);
689                 free(prog);
690         }
691         free_path_split(path);
692         return pid;
695 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
697         const char *interpr = parse_interpreter(cmd);
698         char **path;
699         char *prog;
700         int pid = 0;
702         if (!interpr)
703                 return 0;
704         path = get_path_split();
705         prog = path_lookup(interpr, path, 1);
706         if (prog) {
707                 int argc = 0;
708                 const char **argv2;
709                 while (argv[argc]) argc++;
710                 argv2 = xmalloc(sizeof(*argv) * (argc+1));
711                 argv2[0] = (char *)cmd; /* full path to the script file */
712                 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
713                 pid = mingw_spawnve(prog, argv2, env, 1);
714                 if (pid >= 0) {
715                         int status;
716                         if (waitpid(pid, &status, 0) < 0)
717                                 status = 255;
718                         exit(status);
719                 }
720                 pid = 1;        /* indicate that we tried but failed */
721                 free(prog);
722                 free(argv2);
723         }
724         free_path_split(path);
725         return pid;
728 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
730         /* check if git_command is a shell script */
731         if (!try_shell_exec(cmd, argv, (char **)env)) {
732                 int pid, status;
734                 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
735                 if (pid < 0)
736                         return;
737                 if (waitpid(pid, &status, 0) < 0)
738                         status = 255;
739                 exit(status);
740         }
743 void mingw_execvp(const char *cmd, char *const *argv)
745         char **path = get_path_split();
746         char *prog = path_lookup(cmd, path, 0);
748         if (prog) {
749                 mingw_execve(prog, argv, environ);
750                 free(prog);
751         } else
752                 errno = ENOENT;
754         free_path_split(path);
757 char **copy_environ()
759         char **env;
760         int i = 0;
761         while (environ[i])
762                 i++;
763         env = xmalloc((i+1)*sizeof(*env));
764         for (i = 0; environ[i]; i++)
765                 env[i] = xstrdup(environ[i]);
766         env[i] = NULL;
767         return env;
770 void free_environ(char **env)
772         int i;
773         for (i = 0; env[i]; i++)
774                 free(env[i]);
775         free(env);
778 static int lookup_env(char **env, const char *name, size_t nmln)
780         int i;
782         for (i = 0; env[i]; i++) {
783                 if (0 == strncmp(env[i], name, nmln)
784                     && '=' == env[i][nmln])
785                         /* matches */
786                         return i;
787         }
788         return -1;
791 /*
792  * If name contains '=', then sets the variable, otherwise it unsets it
793  */
794 char **env_setenv(char **env, const char *name)
796         char *eq = strchrnul(name, '=');
797         int i = lookup_env(env, name, eq-name);
799         if (i < 0) {
800                 if (*eq) {
801                         for (i = 0; env[i]; i++)
802                                 ;
803                         env = xrealloc(env, (i+2)*sizeof(*env));
804                         env[i] = xstrdup(name);
805                         env[i+1] = NULL;
806                 }
807         }
808         else {
809                 free(env[i]);
810                 if (*eq)
811                         env[i] = xstrdup(name);
812                 else
813                         for (; env[i]; i++)
814                                 env[i] = env[i+1];
815         }
816         return env;
819 /* this is the first function to call into WS_32; initialize it */
820 #undef gethostbyname
821 struct hostent *mingw_gethostbyname(const char *host)
823         WSADATA wsa;
825         if (WSAStartup(MAKEWORD(2,2), &wsa))
826                 die("unable to initialize winsock subsystem, error %d",
827                         WSAGetLastError());
828         atexit((void(*)(void)) WSACleanup);
829         return gethostbyname(host);
832 int mingw_socket(int domain, int type, int protocol)
834         int sockfd;
835         SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
836         if (s == INVALID_SOCKET) {
837                 /*
838                  * WSAGetLastError() values are regular BSD error codes
839                  * biased by WSABASEERR.
840                  * However, strerror() does not know about networking
841                  * specific errors, which are values beginning at 38 or so.
842                  * Therefore, we choose to leave the biased error code
843                  * in errno so that _if_ someone looks up the code somewhere,
844                  * then it is at least the number that are usually listed.
845                  */
846                 errno = WSAGetLastError();
847                 return -1;
848         }
849         /* convert into a file descriptor */
850         if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
851                 closesocket(s);
852                 return error("unable to make a socket file descriptor: %s",
853                         strerror(errno));
854         }
855         return sockfd;
858 #undef connect
859 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
861         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
862         return connect(s, sa, sz);
865 #undef rename
866 int mingw_rename(const char *pold, const char *pnew)
868         /*
869          * Try native rename() first to get errno right.
870          * It is based on MoveFile(), which cannot overwrite existing files.
871          */
872         if (!rename(pold, pnew))
873                 return 0;
874         if (errno != EEXIST)
875                 return -1;
876         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
877                 return 0;
878         /* TODO: translate more errors */
879         if (GetLastError() == ERROR_ACCESS_DENIED) {
880                 DWORD attrs = GetFileAttributes(pnew);
881                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
882                         errno = EISDIR;
883                         return -1;
884                 }
885         }
886         errno = EACCES;
887         return -1;
890 struct passwd *getpwuid(int uid)
892         static char user_name[100];
893         static struct passwd p;
895         DWORD len = sizeof(user_name);
896         if (!GetUserName(user_name, &len))
897                 return NULL;
898         p.pw_name = user_name;
899         p.pw_gecos = "unknown";
900         p.pw_dir = NULL;
901         return &p;
904 static HANDLE timer_event;
905 static HANDLE timer_thread;
906 static int timer_interval;
907 static int one_shot;
908 static sig_handler_t timer_fn = SIG_DFL;
910 /* The timer works like this:
911  * The thread, ticktack(), is a trivial routine that most of the time
912  * only waits to receive the signal to terminate. The main thread tells
913  * the thread to terminate by setting the timer_event to the signalled
914  * state.
915  * But ticktack() interrupts the wait state after the timer's interval
916  * length to call the signal handler.
917  */
919 static __stdcall unsigned ticktack(void *dummy)
921         while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
922                 if (timer_fn == SIG_DFL)
923                         die("Alarm");
924                 if (timer_fn != SIG_IGN)
925                         timer_fn(SIGALRM);
926                 if (one_shot)
927                         break;
928         }
929         return 0;
932 static int start_timer_thread(void)
934         timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
935         if (timer_event) {
936                 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
937                 if (!timer_thread )
938                         return errno = ENOMEM,
939                                 error("cannot start timer thread");
940         } else
941                 return errno = ENOMEM,
942                         error("cannot allocate resources for timer");
943         return 0;
946 static void stop_timer_thread(void)
948         if (timer_event)
949                 SetEvent(timer_event);  /* tell thread to terminate */
950         if (timer_thread) {
951                 int rc = WaitForSingleObject(timer_thread, 1000);
952                 if (rc == WAIT_TIMEOUT)
953                         error("timer thread did not terminate timely");
954                 else if (rc != WAIT_OBJECT_0)
955                         error("waiting for timer thread failed: %lu",
956                               GetLastError());
957                 CloseHandle(timer_thread);
958         }
959         if (timer_event)
960                 CloseHandle(timer_event);
961         timer_event = NULL;
962         timer_thread = NULL;
965 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
967         return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
970 int setitimer(int type, struct itimerval *in, struct itimerval *out)
972         static const struct timeval zero;
973         static int atexit_done;
975         if (out != NULL)
976                 return errno = EINVAL,
977                         error("setitimer param 3 != NULL not implemented");
978         if (!is_timeval_eq(&in->it_interval, &zero) &&
979             !is_timeval_eq(&in->it_interval, &in->it_value))
980                 return errno = EINVAL,
981                         error("setitimer: it_interval must be zero or eq it_value");
983         if (timer_thread)
984                 stop_timer_thread();
986         if (is_timeval_eq(&in->it_value, &zero) &&
987             is_timeval_eq(&in->it_interval, &zero))
988                 return 0;
990         timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
991         one_shot = is_timeval_eq(&in->it_interval, &zero);
992         if (!atexit_done) {
993                 atexit(stop_timer_thread);
994                 atexit_done = 1;
995         }
996         return start_timer_thread();
999 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1001         if (sig != SIGALRM)
1002                 return errno = EINVAL,
1003                         error("sigaction only implemented for SIGALRM");
1004         if (out != NULL)
1005                 return errno = EINVAL,
1006                         error("sigaction: param 3 != NULL not implemented");
1008         timer_fn = in->sa_handler;
1009         return 0;
1012 #undef signal
1013 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1015         if (sig != SIGALRM)
1016                 return signal(sig, handler);
1017         sig_handler_t old = timer_fn;
1018         timer_fn = handler;
1019         return old;
1022 static const char *make_backslash_path(const char *path)
1024         static char buf[PATH_MAX + 1];
1025         char *c;
1027         if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1028                 die("Too long path: %.*s", 60, path);
1030         for (c = buf; *c; c++) {
1031                 if (*c == '/')
1032                         *c = '\\';
1033         }
1034         return buf;
1037 void mingw_open_html(const char *unixpath)
1039         const char *htmlpath = make_backslash_path(unixpath);
1040         printf("Launching default browser to display HTML ...\n");
1041         ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);