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