Fix find_msysgit_in_path() when PATH is in cmd folder rather than bin
[git-cheetah.git] / compat / mingw.c
blob7b41e0aa83eb5ae4b191cdfb0366a4931c43c385
1 #include "../common/git-compat-util.h"
2 #include "../common/strbuf.h"
3 #include "../common/cache.h"
5 unsigned int _CRT_fmode = _O_BINARY;
7 #undef open
8 int mingw_open (const char *filename, int oflags, ...)
10 va_list args;
11 unsigned mode;
12 int fd;
14 va_start(args, oflags);
15 mode = va_arg(args, int);
16 va_end(args);
18 if (!strcmp(filename, "/dev/null"))
19 filename = "nul";
20 fd = open(filename, oflags, mode);
21 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
22 DWORD attrs = GetFileAttributes(filename);
23 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
24 errno = EISDIR;
26 return fd;
29 static inline time_t filetime_to_time_t(const FILETIME *ft)
31 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
32 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
33 winTime /= 10000000; /* Nano to seconds resolution */
34 return (time_t)winTime;
37 static inline size_t size_to_blocks(size_t s)
39 return (s+511)/512;
42 extern int _getdrive( void );
43 /* We keep the do_lstat code in a separate function to avoid recursion.
44 * When a path ends with a slash, the stat will fail with ENOENT. In
45 * this case, we strip the trailing slashes and stat again.
47 static int do_lstat(const char *file_name, struct stat *buf)
49 WIN32_FILE_ATTRIBUTE_DATA fdata;
51 if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
52 int fMode = S_IREAD;
53 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
54 fMode |= S_IFDIR;
55 else
56 fMode |= S_IFREG;
57 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
58 fMode |= S_IWRITE;
60 buf->st_ino = 0;
61 buf->st_gid = 0;
62 buf->st_uid = 0;
63 buf->st_mode = fMode;
64 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
65 buf->st_blocks = size_to_blocks(buf->st_size);
66 buf->st_dev = _getdrive() - 1;
67 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
68 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
69 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
70 errno = 0;
71 return 0;
74 switch (GetLastError()) {
75 case ERROR_ACCESS_DENIED:
76 case ERROR_SHARING_VIOLATION:
77 case ERROR_LOCK_VIOLATION:
78 case ERROR_SHARING_BUFFER_EXCEEDED:
79 errno = EACCES;
80 break;
81 case ERROR_BUFFER_OVERFLOW:
82 errno = ENAMETOOLONG;
83 break;
84 case ERROR_NOT_ENOUGH_MEMORY:
85 errno = ENOMEM;
86 break;
87 default:
88 errno = ENOENT;
89 break;
91 return -1;
94 /* We provide our own lstat/fstat functions, since the provided
95 * lstat/fstat functions are so slow. These stat functions are
96 * tailored for Git's usage (read: fast), and are not meant to be
97 * complete. Note that Git stat()s are redirected to mingw_lstat()
98 * too, since Windows doesn't really handle symlinks that well.
100 int mingw_lstat(const char *file_name, struct mingw_stat *buf)
102 int namelen;
103 static char alt_name[PATH_MAX];
105 if (!do_lstat(file_name, buf))
106 return 0;
108 /* if file_name ended in a '/', Windows returned ENOENT;
109 * try again without trailing slashes
111 if (errno != ENOENT)
112 return -1;
114 namelen = strlen(file_name);
115 if (namelen && file_name[namelen-1] != '/')
116 return -1;
117 while (namelen && file_name[namelen-1] == '/')
118 --namelen;
119 if (!namelen || namelen >= PATH_MAX)
120 return -1;
122 memcpy(alt_name, file_name, namelen);
123 alt_name[namelen] = 0;
124 return do_lstat(alt_name, buf);
127 #undef fstat
128 #undef stat
129 int mingw_fstat(int fd, struct mingw_stat *buf)
131 HANDLE fh = (HANDLE)_get_osfhandle(fd);
132 BY_HANDLE_FILE_INFORMATION fdata;
134 if (fh == INVALID_HANDLE_VALUE) {
135 errno = EBADF;
136 return -1;
138 /* direct non-file handles to MS's fstat() */
139 if (GetFileType(fh) != FILE_TYPE_DISK) {
140 struct stat st;
141 if (fstat(fd, &st))
142 return -1;
143 buf->st_ino = st.st_ino;
144 buf->st_gid = st.st_gid;
145 buf->st_uid = st.st_uid;
146 buf->st_mode = st.st_mode;
147 buf->st_size = st.st_size;
148 buf->st_blocks = size_to_blocks(buf->st_size);
149 buf->st_dev = st.st_dev;
150 buf->st_atime = st.st_atime;
151 buf->st_mtime = st.st_mtime;
152 buf->st_ctime = st.st_ctime;
153 return 0;
156 if (GetFileInformationByHandle(fh, &fdata)) {
157 int fMode = S_IREAD;
158 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
159 fMode |= S_IFDIR;
160 else
161 fMode |= S_IFREG;
162 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
163 fMode |= S_IWRITE;
165 buf->st_ino = 0;
166 buf->st_gid = 0;
167 buf->st_uid = 0;
168 buf->st_mode = fMode;
169 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
170 buf->st_blocks = size_to_blocks(buf->st_size);
171 buf->st_dev = _getdrive() - 1;
172 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
173 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
174 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
175 return 0;
177 errno = EBADF;
178 return -1;
181 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
183 long long winTime = t * 10000000LL + 116444736000000000LL;
184 ft->dwLowDateTime = (DWORD)winTime;
185 ft->dwHighDateTime = winTime >> 32;
188 int mingw_utime (const char *file_name, const struct utimbuf *times)
190 FILETIME mft, aft;
191 int fh, rc;
193 /* must have write permission */
194 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
195 return -1;
197 time_t_to_filetime(times->modtime, &mft);
198 time_t_to_filetime(times->actime, &aft);
199 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
200 errno = EINVAL;
201 rc = -1;
202 } else
203 rc = 0;
204 close(fh);
205 return rc;
208 unsigned int sleep (unsigned int seconds)
210 Sleep(seconds*1000);
211 return 0;
214 int mkstemp(char *template)
216 char *filename = mktemp(template);
217 if (filename == NULL)
218 return -1;
219 return open(filename, O_RDWR | O_CREAT, 0600);
222 int gettimeofday(struct timeval *tv, void *tz)
224 SYSTEMTIME st;
225 struct tm tm;
226 GetSystemTime(&st);
227 tm.tm_year = st.wYear-1900;
228 tm.tm_mon = st.wMonth-1;
229 tm.tm_mday = st.wDay;
230 tm.tm_hour = st.wHour;
231 tm.tm_min = st.wMinute;
232 tm.tm_sec = st.wSecond;
233 tv->tv_sec = tm_to_time_t(&tm);
234 if (tv->tv_sec < 0)
235 return -1;
236 tv->tv_usec = st.wMilliseconds*1000;
237 return 0;
240 int pipe(int filedes[2])
242 int fd;
243 HANDLE h[2], parent;
245 if (_pipe(filedes, 8192, 0) < 0)
246 return -1;
248 parent = GetCurrentProcess();
250 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
251 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
252 close(filedes[0]);
253 close(filedes[1]);
254 return -1;
256 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
257 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
258 close(filedes[0]);
259 close(filedes[1]);
260 CloseHandle(h[0]);
261 return -1;
263 fd = _open_osfhandle((intptr_t)h[0], O_NOINHERIT);
264 if (fd < 0) {
265 close(filedes[0]);
266 close(filedes[1]);
267 CloseHandle(h[0]);
268 CloseHandle(h[1]);
269 return -1;
271 close(filedes[0]);
272 filedes[0] = fd;
273 fd = _open_osfhandle((intptr_t)h[1], O_NOINHERIT);
274 if (fd < 0) {
275 close(filedes[0]);
276 close(filedes[1]);
277 CloseHandle(h[1]);
278 return -1;
280 close(filedes[1]);
281 filedes[1] = fd;
282 return 0;
285 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
287 unsigned int i;
288 int pending;
290 if (timeout != -1)
291 return errno = EINVAL, error("poll timeout not supported");
293 /* When there is only one fd to wait for, then we pretend that
294 * input is available and let the actual wait happen when the
295 * caller invokes read().
297 if (nfds == 1) {
298 if (!(ufds[0].events & POLLIN))
299 return errno = EINVAL, error("POLLIN not set");
300 ufds[0].revents = POLLIN;
301 return 0;
304 repeat:
305 pending = 0;
306 for (i = 0; i < nfds; i++) {
307 DWORD avail = 0;
308 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
309 if (h == INVALID_HANDLE_VALUE)
310 return -1; /* errno was set */
312 if (!(ufds[i].events & POLLIN))
313 return errno = EINVAL, error("POLLIN not set");
315 /* this emulation works only for pipes */
316 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
317 int err = GetLastError();
318 if (err == ERROR_BROKEN_PIPE) {
319 ufds[i].revents = POLLHUP;
320 pending++;
321 } else {
322 errno = EINVAL;
323 return error("PeekNamedPipe failed,"
324 " GetLastError: %u", err);
326 } else if (avail) {
327 ufds[i].revents = POLLIN;
328 pending++;
329 } else
330 ufds[i].revents = 0;
332 if (!pending) {
333 /* The only times that we spin here is when the process
334 * that is connected through the pipes is waiting for
335 * its own input data to become available. But since
336 * the process (pack-objects) is itself CPU intensive,
337 * it will happily pick up the time slice that we are
338 * relinguishing here.
340 Sleep(0);
341 goto repeat;
343 return 0;
346 struct tm *gmtime_r(const time_t *timep, struct tm *result)
348 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
349 memcpy(result, gmtime(timep), sizeof(struct tm));
350 return result;
353 struct tm *localtime_r(const time_t *timep, struct tm *result)
355 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
356 memcpy(result, localtime(timep), sizeof(struct tm));
357 return result;
360 #undef getcwd
361 char *mingw_getcwd(char *pointer, int len)
363 int i;
364 char *ret = getcwd(pointer, len);
365 if (!ret)
366 return ret;
367 for (i = 0; pointer[i]; i++)
368 if (pointer[i] == '\\')
369 pointer[i] = '/';
370 return ret;
374 * Use GetEnvironmentVariable() instead of getenv() to see updates to the
375 * hosting explorer process's environment (e.g. PATH). MSVCRT's getenv() is
376 * just a copy which may not be up to date.
378 * This implementation is *not* thread safe. This is not a problem as the
379 * git-cheetah DLL is appartment threaded, so all calls should be made from
380 * the same COM thread.
382 * Additionally, each call overwrites the previous return value (i.e. use
383 * strdup(getenv(...)) if necessary).
385 * Note: both of these limitations are POSIX compliant.
387 static char *do_getenv(const char *name)
389 static char *value;
390 static unsigned value_len;
391 unsigned len = GetEnvironmentVariableA(name, NULL, 0);
392 if (!len)
393 return NULL;
394 ALLOC_GROW(value, len, value_len);
395 if (!GetEnvironmentVariableA(name, value, value_len))
396 return NULL;
397 return value;
400 char *mingw_getenv(const char *name)
402 char *result = do_getenv(name);
403 if (!result && !strcmp(name, "TMPDIR")) {
404 /* on Windows it is TMP and TEMP */
405 result = do_getenv("TMP");
406 if (!result)
407 result = do_getenv("TEMP");
409 return result;
412 int mingw_setenv(const char *name, const char *value, int overwrite)
414 if (!overwrite && GetEnvironmentVariableA(name, NULL, 0))
415 return 0;
416 if (SetEnvironmentVariableA(name, value))
417 return 0;
418 errno = EINVAL;
419 return -1;
423 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
424 * (Parsing C++ Command-Line Arguments)
426 static const char *quote_arg(const char *arg)
428 /* count chars to quote */
429 int len = 0, n = 0;
430 int force_quotes = 0;
431 char *q, *d;
432 const char *p = arg;
433 if (!*p) force_quotes = 1;
434 while (*p) {
435 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
436 force_quotes = 1;
437 else if (*p == '"')
438 n++;
439 else if (*p == '\\') {
440 int count = 0;
441 while (*p == '\\') {
442 count++;
443 p++;
444 len++;
446 if (*p == '"')
447 n += count*2 + 1;
448 continue;
450 len++;
451 p++;
453 if (!force_quotes && n == 0)
454 return arg;
456 /* insert \ where necessary */
457 d = q = xmalloc(len+n+3);
458 *d++ = '"';
459 while (*arg) {
460 if (*arg == '"')
461 *d++ = '\\';
462 else if (*arg == '\\') {
463 int count = 0;
464 while (*arg == '\\') {
465 count++;
466 *d++ = *arg++;
468 if (*arg == '"') {
469 while (count-- > 0)
470 *d++ = '\\';
471 *d++ = '\\';
474 *d++ = *arg++;
476 *d++ = '"';
477 *d++ = 0;
478 return q;
481 static const char *parse_interpreter(const char *cmd)
483 static char buf[100];
484 char *p, *opt;
485 int n, fd;
487 /* don't even try a .exe */
488 n = strlen(cmd);
489 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
490 return NULL;
492 fd = open(cmd, O_RDONLY);
493 if (fd < 0)
494 return NULL;
495 n = read(fd, buf, sizeof(buf)-1);
496 close(fd);
497 if (n < 4) /* at least '#!/x' and not error */
498 return NULL;
500 if (buf[0] != '#' || buf[1] != '!')
501 return NULL;
502 buf[n] = '\0';
503 p = buf + strcspn(buf, "\r\n");
504 if (!*p)
505 return NULL;
507 *p = '\0';
508 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
509 return NULL;
510 /* strip options */
511 if ((opt = strchr(p+1, ' ')))
512 *opt = '\0';
513 return p+1;
517 * returns value of PATH environment variable in the given environment or
518 * in the system environment if NULL == env
520 static char *get_path(char **env)
522 char **e;
523 if (!env)
524 return getenv("PATH");
526 for (e = env; *e; e++) {
527 /* if it's PATH variable (could be Path= too!) */
528 if (!strnicmp(*e, "PATH=", 5)) {
529 return *e + 5;
533 return NULL;
537 * Splits the PATH into parts.
539 static char **get_path_split(char **env)
541 char *p, **path, *envpath = get_path(env);
542 int i, n = 0;
544 if (!envpath || !*envpath)
545 return NULL;
547 envpath = xstrdup(envpath);
548 p = envpath;
549 while (p) {
550 char *dir = p;
551 p = strchr(p, ';');
552 if (p) *p++ = '\0';
553 if (*dir) { /* not earlier, catches series of ; */
554 ++n;
557 if (!n)
558 return NULL;
560 path = xmalloc((n+1)*sizeof(char*));
561 p = envpath;
562 i = 0;
563 do {
564 if (*p)
565 path[i++] = xstrdup(p);
566 p = p+strlen(p)+1;
567 } while (i < n);
568 path[i] = NULL;
570 free(envpath);
572 return path;
575 static void free_path_split(char **path)
577 char **p;
578 if (!path)
579 return;
581 p = path;
582 while (*p)
583 free(*p++);
584 free(path);
588 * exe_only means that we only want to detect .exe files, but not scripts
589 * (which do not have an extension)
591 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
593 char path[MAX_PATH];
594 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
596 if (!isexe && access(path, F_OK) == 0)
597 return xstrdup(path);
598 path[strlen(path)-4] = '\0';
599 if ((!exe_only || isexe) && access(path, F_OK) == 0)
600 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
601 return xstrdup(path);
602 return NULL;
606 * Determines the absolute path of cmd using the the split path in path.
607 * If cmd contains a slash or backslash, no lookup is performed.
609 static char *path_lookup(const char *cmd, char **path, int exe_only)
611 char *prog = NULL;
612 int len = strlen(cmd);
613 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
615 if (strchr(cmd, '/') || strchr(cmd, '\\'))
616 prog = xstrdup(cmd);
618 while (!prog && *path)
619 prog = lookup_prog(*path++, cmd, isexe, exe_only);
621 return prog;
624 static int env_compare(const void *a, const void *b)
626 char *const *ea = a;
627 char *const *eb = b;
628 return strcasecmp(*ea, *eb);
631 static pid_t mingw_spawnve_cwd(const char *cmd, const char **argv, char **env,
632 int prepend_cmd, const char *working_directory)
634 STARTUPINFO si;
635 PROCESS_INFORMATION pi;
636 struct strbuf envblk, args;
637 unsigned flags;
638 BOOL ret;
640 /* Determine whether or not we are associated to a console */
641 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
642 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
643 FILE_ATTRIBUTE_NORMAL, NULL);
644 if (cons == INVALID_HANDLE_VALUE) {
645 /* There is no console associated with this process.
646 * Since the child is a console process, Windows
647 * would normally create a console window. But
648 * since we'll be redirecting std streams, we do
649 * not need the console.
651 flags = CREATE_NO_WINDOW;
652 } else {
653 /* There is already a console. If we specified
654 * CREATE_NO_WINDOW here, too, Windows would
655 * disassociate the child from the console.
656 * Go figure!
658 flags = 0;
659 CloseHandle(cons);
661 memset(&si, 0, sizeof(si));
662 si.cb = sizeof(si);
663 si.dwFlags = STARTF_USESTDHANDLES;
664 si.hStdInput = (HANDLE) _get_osfhandle(0);
665 si.hStdOutput = (HANDLE) _get_osfhandle(1);
666 si.hStdError = (HANDLE) _get_osfhandle(2);
668 /* concatenate argv, quoting args as we go */
669 strbuf_init(&args, 0);
670 if (prepend_cmd) {
671 char *quoted = (char *)quote_arg(cmd);
672 strbuf_addstr(&args, quoted);
673 if (quoted != cmd)
674 free(quoted);
676 for (; *argv; argv++) {
677 char *quoted = (char *)quote_arg(*argv);
678 if (*args.buf)
679 strbuf_addch(&args, ' ');
680 strbuf_addstr(&args, quoted);
681 if (quoted != *argv)
682 free(quoted);
685 if (env) {
686 int count = 0;
687 char **e, **sorted_env;
689 for (e = env; *e; e++)
690 count++;
692 /* environment must be sorted */
693 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
694 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
695 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
697 strbuf_init(&envblk, 0);
698 for (e = sorted_env; *e; e++) {
699 strbuf_addstr(&envblk, *e);
700 strbuf_addch(&envblk, '\0');
702 free(sorted_env);
705 memset(&pi, 0, sizeof(pi));
706 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
707 env ? envblk.buf : NULL, working_directory, &si, &pi);
709 if (env)
710 strbuf_release(&envblk);
711 strbuf_release(&args);
713 if (!ret) {
714 errno = ENOENT;
715 return -1;
717 CloseHandle(pi.hThread);
718 return (pid_t)pi.hProcess;
721 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
722 int prepend_cmd)
724 return mingw_spawnve_cwd(cmd, argv, env, prepend_cmd, NULL);
727 pid_t mingw_spawnvpe_cwd(const char *cmd, const char **argv, char **env,
728 const char *working_directory)
730 pid_t pid;
731 char **path = get_path_split(env);
732 char *prog = path_lookup(cmd, path, 0);
734 if (!prog) {
735 errno = ENOENT;
736 pid = -1;
738 else {
739 const char *interpr = parse_interpreter(prog);
741 if (interpr) {
742 const char *argv0 = argv[0];
743 char *iprog = path_lookup(interpr, path, 1);
744 argv[0] = prog;
745 if (!iprog) {
746 errno = ENOENT;
747 pid = -1;
749 else {
750 pid = mingw_spawnve_cwd(iprog, argv, env, 1,
751 working_directory);
752 free(iprog);
754 argv[0] = argv0;
756 else
757 pid = mingw_spawnve_cwd(prog, argv, env, 0,
758 working_directory);
759 free(prog);
761 free_path_split(path);
762 return pid;
765 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
767 return mingw_spawnvpe_cwd(cmd, argv, env, NULL);
770 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
772 const char *interpr = parse_interpreter(cmd);
773 char **path;
774 char *prog;
775 int pid = 0;
777 if (!interpr)
778 return 0;
779 path = get_path_split(env);
780 prog = path_lookup(interpr, path, 1);
781 if (prog) {
782 int argc = 0;
783 const char **argv2;
784 while (argv[argc]) argc++;
785 argv2 = xmalloc(sizeof(*argv) * (argc+1));
786 argv2[0] = (char *)cmd; /* full path to the script file */
787 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
788 pid = mingw_spawnve(prog, argv2, env, 1);
789 if (pid >= 0) {
790 int status;
791 if (waitpid(pid, &status, 0) < 0)
792 status = 255;
793 exit(status);
795 pid = 1; /* indicate that we tried but failed */
796 free(prog);
797 free(argv2);
799 free_path_split(path);
800 return pid;
803 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
805 /* check if git_command is a shell script */
806 if (!try_shell_exec(cmd, argv, (char **)env)) {
807 int pid, status;
809 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
810 if (pid < 0)
811 return;
812 if (waitpid(pid, &status, 0) < 0)
813 status = 255;
814 exit(status);
818 void mingw_execvp(const char *cmd, char *const *argv)
820 char **path = get_path_split(NULL);
821 char *prog = path_lookup(cmd, path, 0);
823 if (prog) {
824 mingw_execve(prog, argv, environ);
825 free(prog);
826 } else
827 errno = ENOENT;
829 free_path_split(path);
832 char **copy_environ()
834 char **env;
835 int i = 0;
836 while (environ[i])
837 i++;
838 env = xmalloc((i+1)*sizeof(*env));
839 for (i = 0; environ[i]; i++)
840 env[i] = xstrdup(environ[i]);
841 env[i] = NULL;
842 return env;
845 void free_environ(char **env)
847 int i;
848 for (i = 0; env[i]; i++)
849 free(env[i]);
850 free(env);
853 static int lookup_env(char **env, const char *name, size_t nmln)
855 int i;
857 for (i = 0; env[i]; i++) {
858 if (0 == strncmp(env[i], name, nmln)
859 && '=' == env[i][nmln])
860 /* matches */
861 return i;
863 return -1;
867 * If name contains '=', then sets the variable, otherwise it unsets it
869 char **env_setenv(char **env, const char *name)
871 char *eq = strchrnul(name, '=');
872 int i = lookup_env(env, name, eq-name);
874 if (i < 0) {
875 if (*eq) {
876 for (i = 0; env[i]; i++)
878 env = xrealloc(env, (i+2)*sizeof(*env));
879 env[i] = xstrdup(name);
880 env[i+1] = NULL;
883 else {
884 free(env[i]);
885 if (*eq)
886 env[i] = xstrdup(name);
887 else
888 for (; env[i]; i++)
889 env[i] = env[i+1];
891 return env;
894 /* this is the first function to call into WS_32; initialize it */
895 #undef gethostbyname
896 struct hostent *mingw_gethostbyname(const char *host)
898 WSADATA wsa;
900 if (WSAStartup(MAKEWORD(2,2), &wsa))
901 die("unable to initialize winsock subsystem, error %d",
902 WSAGetLastError());
903 atexit((void(*)(void)) WSACleanup);
904 return gethostbyname(host);
907 int mingw_socket(int domain, int type, int protocol)
909 int sockfd;
910 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
911 if (s == INVALID_SOCKET) {
913 * WSAGetLastError() values are regular BSD error codes
914 * biased by WSABASEERR.
915 * However, strerror() does not know about networking
916 * specific errors, which are values beginning at 38 or so.
917 * Therefore, we choose to leave the biased error code
918 * in errno so that _if_ someone looks up the code somewhere,
919 * then it is at least the number that are usually listed.
921 errno = WSAGetLastError();
922 return -1;
924 /* convert into a file descriptor */
925 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
926 closesocket(s);
927 return error("unable to make a socket file descriptor: %s",
928 strerror(errno));
930 return sockfd;
933 #undef connect
934 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
936 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
937 return connect(s, sa, sz);
940 #undef rename
941 int mingw_rename(const char *pold, const char *pnew)
944 * Try native rename() first to get errno right.
945 * It is based on MoveFile(), which cannot overwrite existing files.
947 if (!rename(pold, pnew))
948 return 0;
949 if (errno != EEXIST)
950 return -1;
951 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
952 return 0;
953 /* TODO: translate more errors */
954 if (GetLastError() == ERROR_ACCESS_DENIED) {
955 DWORD attrs = GetFileAttributes(pnew);
956 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
957 errno = EISDIR;
958 return -1;
961 errno = EACCES;
962 return -1;
965 struct passwd *getpwuid(int uid)
967 static char user_name[100];
968 static struct passwd p;
970 DWORD len = sizeof(user_name);
971 if (!GetUserName(user_name, &len))
972 return NULL;
973 p.pw_name = user_name;
974 p.pw_gecos = "unknown";
975 p.pw_dir = NULL;
976 return &p;
979 static HANDLE timer_event;
980 static HANDLE timer_thread;
981 static int timer_interval;
982 static int one_shot;
983 static sig_handler_t timer_fn = SIG_DFL;
985 /* The timer works like this:
986 * The thread, ticktack(), is a trivial routine that most of the time
987 * only waits to receive the signal to terminate. The main thread tells
988 * the thread to terminate by setting the timer_event to the signalled
989 * state.
990 * But ticktack() interrupts the wait state after the timer's interval
991 * length to call the signal handler.
994 static unsigned __stdcall ticktack(void *dummy)
996 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
997 if (timer_fn == SIG_DFL)
998 die("Alarm");
999 if (timer_fn != SIG_IGN)
1000 timer_fn(SIGALRM);
1001 if (one_shot)
1002 break;
1004 return 0;
1007 static int start_timer_thread(void)
1009 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1010 if (timer_event) {
1011 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1012 if (!timer_thread )
1013 return errno = ENOMEM,
1014 error("cannot start timer thread");
1015 } else
1016 return errno = ENOMEM,
1017 error("cannot allocate resources for timer");
1018 return 0;
1021 static void stop_timer_thread(void)
1023 if (timer_event)
1024 SetEvent(timer_event); /* tell thread to terminate */
1025 if (timer_thread) {
1026 int rc = WaitForSingleObject(timer_thread, 1000);
1027 if (rc == WAIT_TIMEOUT)
1028 error("timer thread did not terminate timely");
1029 else if (rc != WAIT_OBJECT_0)
1030 error("waiting for timer thread failed: %lu",
1031 GetLastError());
1032 CloseHandle(timer_thread);
1034 if (timer_event)
1035 CloseHandle(timer_event);
1036 timer_event = NULL;
1037 timer_thread = NULL;
1040 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1042 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1045 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1047 static const struct timeval zero;
1048 static int atexit_done;
1050 if (out != NULL)
1051 return errno = EINVAL,
1052 error("setitimer param 3 != NULL not implemented");
1053 if (!is_timeval_eq(&in->it_interval, &zero) &&
1054 !is_timeval_eq(&in->it_interval, &in->it_value))
1055 return errno = EINVAL,
1056 error("setitimer: it_interval must be zero or eq it_value");
1058 if (timer_thread)
1059 stop_timer_thread();
1061 if (is_timeval_eq(&in->it_value, &zero) &&
1062 is_timeval_eq(&in->it_interval, &zero))
1063 return 0;
1065 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1066 one_shot = is_timeval_eq(&in->it_interval, &zero);
1067 if (!atexit_done) {
1068 atexit(stop_timer_thread);
1069 atexit_done = 1;
1071 return start_timer_thread();
1074 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1076 if (sig != SIGALRM)
1077 return errno = EINVAL,
1078 error("sigaction only implemented for SIGALRM");
1079 if (out != NULL)
1080 return errno = EINVAL,
1081 error("sigaction: param 3 != NULL not implemented");
1083 timer_fn = in->sa_handler;
1084 return 0;
1087 #undef signal
1088 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1090 sig_handler_t old;
1092 if (sig != SIGALRM)
1093 return signal(sig, handler);
1094 old = timer_fn;
1095 timer_fn = handler;
1096 return old;
1099 static const char *make_backslash_path(const char *path)
1101 static char buf[PATH_MAX + 1];
1102 char *c;
1104 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1105 die("Too long path: %.*s", 60, path);
1107 for (c = buf; *c; c++) {
1108 if (*c == '/')
1109 *c = '\\';
1111 return buf;
1114 void mingw_open_html(const char *unixpath)
1116 const char *htmlpath = make_backslash_path(unixpath);
1117 printf("Launching default browser to display HTML ...\n");
1118 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);