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