Code

Merge branch 'maint'
[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 /* We keep the do_lstat code in a separate function to avoid recursion.
35  * When a path ends with a slash, the stat will fail with ENOENT. In
36  * this case, we strip the trailing slashes and stat again.
37  */
38 static int do_lstat(const char *file_name, struct stat *buf)
39 {
40         WIN32_FILE_ATTRIBUTE_DATA fdata;
42         if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
43                 int fMode = S_IREAD;
44                 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
45                         fMode |= S_IFDIR;
46                 else
47                         fMode |= S_IFREG;
48                 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
49                         fMode |= S_IWRITE;
51                 buf->st_ino = 0;
52                 buf->st_gid = 0;
53                 buf->st_uid = 0;
54                 buf->st_nlink = 1;
55                 buf->st_mode = fMode;
56                 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
57                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
58                 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
59                 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
60                 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
61                 errno = 0;
62                 return 0;
63         }
65         switch (GetLastError()) {
66         case ERROR_ACCESS_DENIED:
67         case ERROR_SHARING_VIOLATION:
68         case ERROR_LOCK_VIOLATION:
69         case ERROR_SHARING_BUFFER_EXCEEDED:
70                 errno = EACCES;
71                 break;
72         case ERROR_BUFFER_OVERFLOW:
73                 errno = ENAMETOOLONG;
74                 break;
75         case ERROR_NOT_ENOUGH_MEMORY:
76                 errno = ENOMEM;
77                 break;
78         default:
79                 errno = ENOENT;
80                 break;
81         }
82         return -1;
83 }
85 /* We provide our own lstat/fstat functions, since the provided
86  * lstat/fstat functions are so slow. These stat functions are
87  * tailored for Git's usage (read: fast), and are not meant to be
88  * complete. Note that Git stat()s are redirected to mingw_lstat()
89  * too, since Windows doesn't really handle symlinks that well.
90  */
91 int mingw_lstat(const char *file_name, struct stat *buf)
92 {
93         int namelen;
94         static char alt_name[PATH_MAX];
96         if (!do_lstat(file_name, buf))
97                 return 0;
99         /* if file_name ended in a '/', Windows returned ENOENT;
100          * try again without trailing slashes
101          */
102         if (errno != ENOENT)
103                 return -1;
105         namelen = strlen(file_name);
106         if (namelen && file_name[namelen-1] != '/')
107                 return -1;
108         while (namelen && file_name[namelen-1] == '/')
109                 --namelen;
110         if (!namelen || namelen >= PATH_MAX)
111                 return -1;
113         memcpy(alt_name, file_name, namelen);
114         alt_name[namelen] = 0;
115         return do_lstat(alt_name, buf);
118 #undef fstat
119 int mingw_fstat(int fd, struct stat *buf)
121         HANDLE fh = (HANDLE)_get_osfhandle(fd);
122         BY_HANDLE_FILE_INFORMATION fdata;
124         if (fh == INVALID_HANDLE_VALUE) {
125                 errno = EBADF;
126                 return -1;
127         }
128         /* direct non-file handles to MS's fstat() */
129         if (GetFileType(fh) != FILE_TYPE_DISK)
130                 return fstat(fd, buf);
132         if (GetFileInformationByHandle(fh, &fdata)) {
133                 int fMode = S_IREAD;
134                 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
135                         fMode |= S_IFDIR;
136                 else
137                         fMode |= S_IFREG;
138                 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
139                         fMode |= S_IWRITE;
141                 buf->st_ino = 0;
142                 buf->st_gid = 0;
143                 buf->st_uid = 0;
144                 buf->st_nlink = 1;
145                 buf->st_mode = fMode;
146                 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
147                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
148                 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
149                 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
150                 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
151                 return 0;
152         }
153         errno = EBADF;
154         return -1;
157 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
159         long long winTime = t * 10000000LL + 116444736000000000LL;
160         ft->dwLowDateTime = winTime;
161         ft->dwHighDateTime = winTime >> 32;
164 int mingw_utime (const char *file_name, const struct utimbuf *times)
166         FILETIME mft, aft;
167         int fh, rc;
169         /* must have write permission */
170         if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
171                 return -1;
173         time_t_to_filetime(times->modtime, &mft);
174         time_t_to_filetime(times->actime, &aft);
175         if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
176                 errno = EINVAL;
177                 rc = -1;
178         } else
179                 rc = 0;
180         close(fh);
181         return rc;
184 unsigned int sleep (unsigned int seconds)
186         Sleep(seconds*1000);
187         return 0;
190 int mkstemp(char *template)
192         char *filename = mktemp(template);
193         if (filename == NULL)
194                 return -1;
195         return open(filename, O_RDWR | O_CREAT, 0600);
198 int gettimeofday(struct timeval *tv, void *tz)
200         SYSTEMTIME st;
201         struct tm tm;
202         GetSystemTime(&st);
203         tm.tm_year = st.wYear-1900;
204         tm.tm_mon = st.wMonth-1;
205         tm.tm_mday = st.wDay;
206         tm.tm_hour = st.wHour;
207         tm.tm_min = st.wMinute;
208         tm.tm_sec = st.wSecond;
209         tv->tv_sec = tm_to_time_t(&tm);
210         if (tv->tv_sec < 0)
211                 return -1;
212         tv->tv_usec = st.wMilliseconds*1000;
213         return 0;
216 int pipe(int filedes[2])
218         int fd;
219         HANDLE h[2], parent;
221         if (_pipe(filedes, 8192, 0) < 0)
222                 return -1;
224         parent = GetCurrentProcess();
226         if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
227                         parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
228                 close(filedes[0]);
229                 close(filedes[1]);
230                 return -1;
231         }
232         if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
233                         parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
234                 close(filedes[0]);
235                 close(filedes[1]);
236                 CloseHandle(h[0]);
237                 return -1;
238         }
239         fd = _open_osfhandle((int)h[0], O_NOINHERIT);
240         if (fd < 0) {
241                 close(filedes[0]);
242                 close(filedes[1]);
243                 CloseHandle(h[0]);
244                 CloseHandle(h[1]);
245                 return -1;
246         }
247         close(filedes[0]);
248         filedes[0] = fd;
249         fd = _open_osfhandle((int)h[1], O_NOINHERIT);
250         if (fd < 0) {
251                 close(filedes[0]);
252                 close(filedes[1]);
253                 CloseHandle(h[1]);
254                 return -1;
255         }
256         close(filedes[1]);
257         filedes[1] = fd;
258         return 0;
261 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
263         int i, pending;
265         if (timeout >= 0) {
266                 if (nfds == 0) {
267                         Sleep(timeout);
268                         return 0;
269                 }
270                 return errno = EINVAL, error("poll timeout not supported");
271         }
273         /* When there is only one fd to wait for, then we pretend that
274          * input is available and let the actual wait happen when the
275          * caller invokes read().
276          */
277         if (nfds == 1) {
278                 if (!(ufds[0].events & POLLIN))
279                         return errno = EINVAL, error("POLLIN not set");
280                 ufds[0].revents = POLLIN;
281                 return 0;
282         }
284 repeat:
285         pending = 0;
286         for (i = 0; i < nfds; i++) {
287                 DWORD avail = 0;
288                 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
289                 if (h == INVALID_HANDLE_VALUE)
290                         return -1;      /* errno was set */
292                 if (!(ufds[i].events & POLLIN))
293                         return errno = EINVAL, error("POLLIN not set");
295                 /* this emulation works only for pipes */
296                 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
297                         int err = GetLastError();
298                         if (err == ERROR_BROKEN_PIPE) {
299                                 ufds[i].revents = POLLHUP;
300                                 pending++;
301                         } else {
302                                 errno = EINVAL;
303                                 return error("PeekNamedPipe failed,"
304                                         " GetLastError: %u", err);
305                         }
306                 } else if (avail) {
307                         ufds[i].revents = POLLIN;
308                         pending++;
309                 } else
310                         ufds[i].revents = 0;
311         }
312         if (!pending) {
313                 /* The only times that we spin here is when the process
314                  * that is connected through the pipes is waiting for
315                  * its own input data to become available. But since
316                  * the process (pack-objects) is itself CPU intensive,
317                  * it will happily pick up the time slice that we are
318                  * relinguishing here.
319                  */
320                 Sleep(0);
321                 goto repeat;
322         }
323         return 0;
326 struct tm *gmtime_r(const time_t *timep, struct tm *result)
328         /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
329         memcpy(result, gmtime(timep), sizeof(struct tm));
330         return result;
333 struct tm *localtime_r(const time_t *timep, struct tm *result)
335         /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
336         memcpy(result, localtime(timep), sizeof(struct tm));
337         return result;
340 #undef getcwd
341 char *mingw_getcwd(char *pointer, int len)
343         int i;
344         char *ret = getcwd(pointer, len);
345         if (!ret)
346                 return ret;
347         for (i = 0; pointer[i]; i++)
348                 if (pointer[i] == '\\')
349                         pointer[i] = '/';
350         return ret;
353 #undef getenv
354 char *mingw_getenv(const char *name)
356         char *result = getenv(name);
357         if (!result && !strcmp(name, "TMPDIR")) {
358                 /* on Windows it is TMP and TEMP */
359                 result = getenv("TMP");
360                 if (!result)
361                         result = getenv("TEMP");
362         }
363         return result;
366 /*
367  * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
368  * (Parsing C++ Command-Line Arguments)
369  */
370 static const char *quote_arg(const char *arg)
372         /* count chars to quote */
373         int len = 0, n = 0;
374         int force_quotes = 0;
375         char *q, *d;
376         const char *p = arg;
377         if (!*p) force_quotes = 1;
378         while (*p) {
379                 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
380                         force_quotes = 1;
381                 else if (*p == '"')
382                         n++;
383                 else if (*p == '\\') {
384                         int count = 0;
385                         while (*p == '\\') {
386                                 count++;
387                                 p++;
388                                 len++;
389                         }
390                         if (*p == '"')
391                                 n += count*2 + 1;
392                         continue;
393                 }
394                 len++;
395                 p++;
396         }
397         if (!force_quotes && n == 0)
398                 return arg;
400         /* insert \ where necessary */
401         d = q = xmalloc(len+n+3);
402         *d++ = '"';
403         while (*arg) {
404                 if (*arg == '"')
405                         *d++ = '\\';
406                 else if (*arg == '\\') {
407                         int count = 0;
408                         while (*arg == '\\') {
409                                 count++;
410                                 *d++ = *arg++;
411                         }
412                         if (*arg == '"') {
413                                 while (count-- > 0)
414                                         *d++ = '\\';
415                                 *d++ = '\\';
416                         }
417                 }
418                 *d++ = *arg++;
419         }
420         *d++ = '"';
421         *d++ = 0;
422         return q;
425 static const char *parse_interpreter(const char *cmd)
427         static char buf[100];
428         char *p, *opt;
429         int n, fd;
431         /* don't even try a .exe */
432         n = strlen(cmd);
433         if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
434                 return NULL;
436         fd = open(cmd, O_RDONLY);
437         if (fd < 0)
438                 return NULL;
439         n = read(fd, buf, sizeof(buf)-1);
440         close(fd);
441         if (n < 4)      /* at least '#!/x' and not error */
442                 return NULL;
444         if (buf[0] != '#' || buf[1] != '!')
445                 return NULL;
446         buf[n] = '\0';
447         p = strchr(buf, '\n');
448         if (!p)
449                 return NULL;
451         *p = '\0';
452         if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
453                 return NULL;
454         /* strip options */
455         if ((opt = strchr(p+1, ' ')))
456                 *opt = '\0';
457         return p+1;
460 /*
461  * Splits the PATH into parts.
462  */
463 static char **get_path_split(void)
465         char *p, **path, *envpath = getenv("PATH");
466         int i, n = 0;
468         if (!envpath || !*envpath)
469                 return NULL;
471         envpath = xstrdup(envpath);
472         p = envpath;
473         while (p) {
474                 char *dir = p;
475                 p = strchr(p, ';');
476                 if (p) *p++ = '\0';
477                 if (*dir) {     /* not earlier, catches series of ; */
478                         ++n;
479                 }
480         }
481         if (!n)
482                 return NULL;
484         path = xmalloc((n+1)*sizeof(char*));
485         p = envpath;
486         i = 0;
487         do {
488                 if (*p)
489                         path[i++] = xstrdup(p);
490                 p = p+strlen(p)+1;
491         } while (i < n);
492         path[i] = NULL;
494         free(envpath);
496         return path;
499 static void free_path_split(char **path)
501         if (!path)
502                 return;
504         char **p = path;
505         while (*p)
506                 free(*p++);
507         free(path);
510 /*
511  * exe_only means that we only want to detect .exe files, but not scripts
512  * (which do not have an extension)
513  */
514 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
516         char path[MAX_PATH];
517         snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
519         if (!isexe && access(path, F_OK) == 0)
520                 return xstrdup(path);
521         path[strlen(path)-4] = '\0';
522         if ((!exe_only || isexe) && access(path, F_OK) == 0)
523                 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
524                         return xstrdup(path);
525         return NULL;
528 /*
529  * Determines the absolute path of cmd using the the split path in path.
530  * If cmd contains a slash or backslash, no lookup is performed.
531  */
532 static char *path_lookup(const char *cmd, char **path, int exe_only)
534         char *prog = NULL;
535         int len = strlen(cmd);
536         int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
538         if (strchr(cmd, '/') || strchr(cmd, '\\'))
539                 prog = xstrdup(cmd);
541         while (!prog && *path)
542                 prog = lookup_prog(*path++, cmd, isexe, exe_only);
544         return prog;
547 static int env_compare(const void *a, const void *b)
549         char *const *ea = a;
550         char *const *eb = b;
551         return strcasecmp(*ea, *eb);
554 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
555                            int prepend_cmd)
557         STARTUPINFO si;
558         PROCESS_INFORMATION pi;
559         struct strbuf envblk, args;
560         unsigned flags;
561         BOOL ret;
563         /* Determine whether or not we are associated to a console */
564         HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
565                         FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
566                         FILE_ATTRIBUTE_NORMAL, NULL);
567         if (cons == INVALID_HANDLE_VALUE) {
568                 /* There is no console associated with this process.
569                  * Since the child is a console process, Windows
570                  * would normally create a console window. But
571                  * since we'll be redirecting std streams, we do
572                  * not need the console.
573                  */
574                 flags = CREATE_NO_WINDOW;
575         } else {
576                 /* There is already a console. If we specified
577                  * CREATE_NO_WINDOW here, too, Windows would
578                  * disassociate the child from the console.
579                  * Go figure!
580                  */
581                 flags = 0;
582                 CloseHandle(cons);
583         }
584         memset(&si, 0, sizeof(si));
585         si.cb = sizeof(si);
586         si.dwFlags = STARTF_USESTDHANDLES;
587         si.hStdInput = (HANDLE) _get_osfhandle(0);
588         si.hStdOutput = (HANDLE) _get_osfhandle(1);
589         si.hStdError = (HANDLE) _get_osfhandle(2);
591         /* concatenate argv, quoting args as we go */
592         strbuf_init(&args, 0);
593         if (prepend_cmd) {
594                 char *quoted = (char *)quote_arg(cmd);
595                 strbuf_addstr(&args, quoted);
596                 if (quoted != cmd)
597                         free(quoted);
598         }
599         for (; *argv; argv++) {
600                 char *quoted = (char *)quote_arg(*argv);
601                 if (*args.buf)
602                         strbuf_addch(&args, ' ');
603                 strbuf_addstr(&args, quoted);
604                 if (quoted != *argv)
605                         free(quoted);
606         }
608         if (env) {
609                 int count = 0;
610                 char **e, **sorted_env;
612                 for (e = env; *e; e++)
613                         count++;
615                 /* environment must be sorted */
616                 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
617                 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
618                 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
620                 strbuf_init(&envblk, 0);
621                 for (e = sorted_env; *e; e++) {
622                         strbuf_addstr(&envblk, *e);
623                         strbuf_addch(&envblk, '\0');
624                 }
625                 free(sorted_env);
626         }
628         memset(&pi, 0, sizeof(pi));
629         ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
630                 env ? envblk.buf : NULL, NULL, &si, &pi);
632         if (env)
633                 strbuf_release(&envblk);
634         strbuf_release(&args);
636         if (!ret) {
637                 errno = ENOENT;
638                 return -1;
639         }
640         CloseHandle(pi.hThread);
641         return (pid_t)pi.hProcess;
644 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
646         pid_t pid;
647         char **path = get_path_split();
648         char *prog = path_lookup(cmd, path, 0);
650         if (!prog) {
651                 errno = ENOENT;
652                 pid = -1;
653         }
654         else {
655                 const char *interpr = parse_interpreter(prog);
657                 if (interpr) {
658                         const char *argv0 = argv[0];
659                         char *iprog = path_lookup(interpr, path, 1);
660                         argv[0] = prog;
661                         if (!iprog) {
662                                 errno = ENOENT;
663                                 pid = -1;
664                         }
665                         else {
666                                 pid = mingw_spawnve(iprog, argv, env, 1);
667                                 free(iprog);
668                         }
669                         argv[0] = argv0;
670                 }
671                 else
672                         pid = mingw_spawnve(prog, argv, env, 0);
673                 free(prog);
674         }
675         free_path_split(path);
676         return pid;
679 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
681         const char *interpr = parse_interpreter(cmd);
682         char **path;
683         char *prog;
684         int pid = 0;
686         if (!interpr)
687                 return 0;
688         path = get_path_split();
689         prog = path_lookup(interpr, path, 1);
690         if (prog) {
691                 int argc = 0;
692                 const char **argv2;
693                 while (argv[argc]) argc++;
694                 argv2 = xmalloc(sizeof(*argv) * (argc+1));
695                 argv2[0] = (char *)cmd; /* full path to the script file */
696                 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
697                 pid = mingw_spawnve(prog, argv2, env, 1);
698                 if (pid >= 0) {
699                         int status;
700                         if (waitpid(pid, &status, 0) < 0)
701                                 status = 255;
702                         exit(status);
703                 }
704                 pid = 1;        /* indicate that we tried but failed */
705                 free(prog);
706                 free(argv2);
707         }
708         free_path_split(path);
709         return pid;
712 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
714         /* check if git_command is a shell script */
715         if (!try_shell_exec(cmd, argv, (char **)env)) {
716                 int pid, status;
718                 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
719                 if (pid < 0)
720                         return;
721                 if (waitpid(pid, &status, 0) < 0)
722                         status = 255;
723                 exit(status);
724         }
727 void mingw_execvp(const char *cmd, char *const *argv)
729         char **path = get_path_split();
730         char *prog = path_lookup(cmd, path, 0);
732         if (prog) {
733                 mingw_execve(prog, argv, environ);
734                 free(prog);
735         } else
736                 errno = ENOENT;
738         free_path_split(path);
741 char **copy_environ()
743         char **env;
744         int i = 0;
745         while (environ[i])
746                 i++;
747         env = xmalloc((i+1)*sizeof(*env));
748         for (i = 0; environ[i]; i++)
749                 env[i] = xstrdup(environ[i]);
750         env[i] = NULL;
751         return env;
754 void free_environ(char **env)
756         int i;
757         for (i = 0; env[i]; i++)
758                 free(env[i]);
759         free(env);
762 static int lookup_env(char **env, const char *name, size_t nmln)
764         int i;
766         for (i = 0; env[i]; i++) {
767                 if (0 == strncmp(env[i], name, nmln)
768                     && '=' == env[i][nmln])
769                         /* matches */
770                         return i;
771         }
772         return -1;
775 /*
776  * If name contains '=', then sets the variable, otherwise it unsets it
777  */
778 char **env_setenv(char **env, const char *name)
780         char *eq = strchrnul(name, '=');
781         int i = lookup_env(env, name, eq-name);
783         if (i < 0) {
784                 if (*eq) {
785                         for (i = 0; env[i]; i++)
786                                 ;
787                         env = xrealloc(env, (i+2)*sizeof(*env));
788                         env[i] = xstrdup(name);
789                         env[i+1] = NULL;
790                 }
791         }
792         else {
793                 free(env[i]);
794                 if (*eq)
795                         env[i] = xstrdup(name);
796                 else
797                         for (; env[i]; i++)
798                                 env[i] = env[i+1];
799         }
800         return env;
803 /* this is the first function to call into WS_32; initialize it */
804 #undef gethostbyname
805 struct hostent *mingw_gethostbyname(const char *host)
807         WSADATA wsa;
809         if (WSAStartup(MAKEWORD(2,2), &wsa))
810                 die("unable to initialize winsock subsystem, error %d",
811                         WSAGetLastError());
812         atexit((void(*)(void)) WSACleanup);
813         return gethostbyname(host);
816 int mingw_socket(int domain, int type, int protocol)
818         int sockfd;
819         SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
820         if (s == INVALID_SOCKET) {
821                 /*
822                  * WSAGetLastError() values are regular BSD error codes
823                  * biased by WSABASEERR.
824                  * However, strerror() does not know about networking
825                  * specific errors, which are values beginning at 38 or so.
826                  * Therefore, we choose to leave the biased error code
827                  * in errno so that _if_ someone looks up the code somewhere,
828                  * then it is at least the number that are usually listed.
829                  */
830                 errno = WSAGetLastError();
831                 return -1;
832         }
833         /* convert into a file descriptor */
834         if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
835                 closesocket(s);
836                 return error("unable to make a socket file descriptor: %s",
837                         strerror(errno));
838         }
839         return sockfd;
842 #undef connect
843 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
845         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
846         return connect(s, sa, sz);
849 #undef rename
850 int mingw_rename(const char *pold, const char *pnew)
852         /*
853          * Try native rename() first to get errno right.
854          * It is based on MoveFile(), which cannot overwrite existing files.
855          */
856         if (!rename(pold, pnew))
857                 return 0;
858         if (errno != EEXIST)
859                 return -1;
860         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
861                 return 0;
862         /* TODO: translate more errors */
863         if (GetLastError() == ERROR_ACCESS_DENIED) {
864                 DWORD attrs = GetFileAttributes(pnew);
865                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
866                         errno = EISDIR;
867                         return -1;
868                 }
869         }
870         errno = EACCES;
871         return -1;
874 struct passwd *getpwuid(int uid)
876         static char user_name[100];
877         static struct passwd p;
879         DWORD len = sizeof(user_name);
880         if (!GetUserName(user_name, &len))
881                 return NULL;
882         p.pw_name = user_name;
883         p.pw_gecos = "unknown";
884         p.pw_dir = NULL;
885         return &p;
888 static HANDLE timer_event;
889 static HANDLE timer_thread;
890 static int timer_interval;
891 static int one_shot;
892 static sig_handler_t timer_fn = SIG_DFL;
894 /* The timer works like this:
895  * The thread, ticktack(), is a trivial routine that most of the time
896  * only waits to receive the signal to terminate. The main thread tells
897  * the thread to terminate by setting the timer_event to the signalled
898  * state.
899  * But ticktack() interrupts the wait state after the timer's interval
900  * length to call the signal handler.
901  */
903 static __stdcall unsigned ticktack(void *dummy)
905         while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
906                 if (timer_fn == SIG_DFL)
907                         die("Alarm");
908                 if (timer_fn != SIG_IGN)
909                         timer_fn(SIGALRM);
910                 if (one_shot)
911                         break;
912         }
913         return 0;
916 static int start_timer_thread(void)
918         timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
919         if (timer_event) {
920                 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
921                 if (!timer_thread )
922                         return errno = ENOMEM,
923                                 error("cannot start timer thread");
924         } else
925                 return errno = ENOMEM,
926                         error("cannot allocate resources for timer");
927         return 0;
930 static void stop_timer_thread(void)
932         if (timer_event)
933                 SetEvent(timer_event);  /* tell thread to terminate */
934         if (timer_thread) {
935                 int rc = WaitForSingleObject(timer_thread, 1000);
936                 if (rc == WAIT_TIMEOUT)
937                         error("timer thread did not terminate timely");
938                 else if (rc != WAIT_OBJECT_0)
939                         error("waiting for timer thread failed: %lu",
940                               GetLastError());
941                 CloseHandle(timer_thread);
942         }
943         if (timer_event)
944                 CloseHandle(timer_event);
945         timer_event = NULL;
946         timer_thread = NULL;
949 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
951         return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
954 int setitimer(int type, struct itimerval *in, struct itimerval *out)
956         static const struct timeval zero;
957         static int atexit_done;
959         if (out != NULL)
960                 return errno = EINVAL,
961                         error("setitimer param 3 != NULL not implemented");
962         if (!is_timeval_eq(&in->it_interval, &zero) &&
963             !is_timeval_eq(&in->it_interval, &in->it_value))
964                 return errno = EINVAL,
965                         error("setitimer: it_interval must be zero or eq it_value");
967         if (timer_thread)
968                 stop_timer_thread();
970         if (is_timeval_eq(&in->it_value, &zero) &&
971             is_timeval_eq(&in->it_interval, &zero))
972                 return 0;
974         timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
975         one_shot = is_timeval_eq(&in->it_interval, &zero);
976         if (!atexit_done) {
977                 atexit(stop_timer_thread);
978                 atexit_done = 1;
979         }
980         return start_timer_thread();
983 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
985         if (sig != SIGALRM)
986                 return errno = EINVAL,
987                         error("sigaction only implemented for SIGALRM");
988         if (out != NULL)
989                 return errno = EINVAL,
990                         error("sigaction: param 3 != NULL not implemented");
992         timer_fn = in->sa_handler;
993         return 0;
996 #undef signal
997 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
999         if (sig != SIGALRM)
1000                 return signal(sig, handler);
1001         sig_handler_t old = timer_fn;
1002         timer_fn = handler;
1003         return old;
1006 static const char *make_backslash_path(const char *path)
1008         static char buf[PATH_MAX + 1];
1009         char *c;
1011         if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1012                 die("Too long path: %.*s", 60, path);
1014         for (c = buf; *c; c++) {
1015                 if (*c == '/')
1016                         *c = '\\';
1017         }
1018         return buf;
1021 void mingw_open_html(const char *unixpath)
1023         const char *htmlpath = make_backslash_path(unixpath);
1024         printf("Launching default browser to display HTML ...\n");
1025         ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);