A bit of comment and whitespace cleanup in compat/mingw.c.
[git/mingw.git] / compat / mingw.c
blob0888288b5cb2e83b18c3c3fbbb099b68bda06579
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, ...)
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;
23 return fd;
26 static inline time_t filetime_to_time_t(const FILETIME *ft)
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;
34 static inline size_t size_to_blocks(size_t s)
36 return (s+511)/512;
39 extern int _getdrive( void );
40 /* We keep the do_lstat code in a separate function to avoid recursion.
41 * When a path ends with a slash, the stat will fail with ENOENT. In
42 * this case, we strip the trailing slashes and stat again.
44 static int do_lstat(const char *file_name, struct stat *buf)
46 WIN32_FILE_ATTRIBUTE_DATA fdata;
48 if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) {
49 int fMode = S_IREAD;
50 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
51 fMode |= S_IFDIR;
52 else
53 fMode |= S_IFREG;
54 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
55 fMode |= S_IWRITE;
57 buf->st_ino = 0;
58 buf->st_gid = 0;
59 buf->st_uid = 0;
60 buf->st_mode = fMode;
61 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
62 buf->st_blocks = size_to_blocks(buf->st_size);
63 buf->st_dev = _getdrive() - 1;
64 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
65 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
66 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
67 errno = 0;
68 return 0;
71 switch (GetLastError()) {
72 case ERROR_ACCESS_DENIED:
73 case ERROR_SHARING_VIOLATION:
74 case ERROR_LOCK_VIOLATION:
75 case ERROR_SHARING_BUFFER_EXCEEDED:
76 errno = EACCES;
77 break;
78 case ERROR_BUFFER_OVERFLOW:
79 errno = ENAMETOOLONG;
80 break;
81 case ERROR_NOT_ENOUGH_MEMORY:
82 errno = ENOMEM;
83 break;
84 default:
85 errno = ENOENT;
86 break;
88 return -1;
91 /* We provide our own lstat/fstat functions, since the provided
92 * lstat/fstat functions are so slow. These stat functions are
93 * tailored for Git's usage (read: fast), and are not meant to be
94 * complete. Note that Git stat()s are redirected to mingw_lstat()
95 * too, since Windows doesn't really handle symlinks that well.
97 int mingw_lstat(const char *file_name, struct mingw_stat *buf)
99 int namelen;
100 static char alt_name[PATH_MAX];
102 if (!do_lstat(file_name, buf))
103 return 0;
105 /* if file_name ended in a '/', Windows returned ENOENT;
106 * try again without trailing slashes
108 if (errno != ENOENT)
109 return -1;
111 namelen = strlen(file_name);
112 if (namelen && file_name[namelen-1] != '/')
113 return -1;
114 while (namelen && file_name[namelen-1] == '/')
115 --namelen;
116 if (!namelen || namelen >= PATH_MAX)
117 return -1;
119 memcpy(alt_name, file_name, namelen);
120 alt_name[namelen] = 0;
121 return do_lstat(alt_name, buf);
124 #undef fstat
125 #undef stat
126 int mingw_fstat(int fd, struct mingw_stat *buf)
128 HANDLE fh = (HANDLE)_get_osfhandle(fd);
129 BY_HANDLE_FILE_INFORMATION fdata;
131 if (fh == INVALID_HANDLE_VALUE) {
132 errno = EBADF;
133 return -1;
135 /* direct non-file handles to MS's fstat() */
136 if (GetFileType(fh) != FILE_TYPE_DISK) {
137 struct stat st;
138 if (fstat(fd, &st))
139 return -1;
140 buf->st_ino = st.st_ino;
141 buf->st_gid = st.st_gid;
142 buf->st_uid = st.st_uid;
143 buf->st_mode = st.st_mode;
144 buf->st_size = st.st_size;
145 buf->st_blocks = size_to_blocks(buf->st_size);
146 buf->st_dev = st.st_dev;
147 buf->st_atime = st.st_atime;
148 buf->st_mtime = st.st_mtime;
149 buf->st_ctime = st.st_ctime;
150 return 0;
153 if (GetFileInformationByHandle(fh, &fdata)) {
154 int fMode = S_IREAD;
155 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
156 fMode |= S_IFDIR;
157 else
158 fMode |= S_IFREG;
159 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
160 fMode |= S_IWRITE;
162 buf->st_ino = 0;
163 buf->st_gid = 0;
164 buf->st_uid = 0;
165 buf->st_mode = fMode;
166 buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */
167 buf->st_blocks = size_to_blocks(buf->st_size);
168 buf->st_dev = _getdrive() - 1;
169 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
170 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
171 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
172 return 0;
174 errno = EBADF;
175 return -1;
178 unsigned int sleep (unsigned int seconds)
180 Sleep(seconds*1000);
181 return 0;
184 int mkstemp(char *template)
186 char *filename = mktemp(template);
187 if (filename == NULL)
188 return -1;
189 return open(filename, O_RDWR | O_CREAT, 0600);
192 int gettimeofday(struct timeval *tv, void *tz)
194 extern time_t my_mktime(struct tm *tm);
195 SYSTEMTIME st;
196 struct tm tm;
197 GetSystemTime(&st);
198 tm.tm_year = st.wYear-1900;
199 tm.tm_mon = st.wMonth-1;
200 tm.tm_mday = st.wDay;
201 tm.tm_hour = st.wHour;
202 tm.tm_min = st.wMinute;
203 tm.tm_sec = st.wSecond;
204 tv->tv_sec = my_mktime(&tm);
205 if (tv->tv_sec < 0)
206 return -1;
207 tv->tv_usec = st.wMilliseconds*1000;
208 return 0;
211 int pipe(int filedes[2])
213 int fd;
214 HANDLE h[2], parent;
216 if (_pipe(filedes, 8192, 0) < 0)
217 return -1;
219 parent = GetCurrentProcess();
221 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
222 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
223 close(filedes[0]);
224 close(filedes[1]);
225 return -1;
227 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
228 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
229 close(filedes[0]);
230 close(filedes[1]);
231 CloseHandle(h[0]);
232 return -1;
234 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
235 if (fd < 0) {
236 close(filedes[0]);
237 close(filedes[1]);
238 CloseHandle(h[0]);
239 CloseHandle(h[1]);
240 return -1;
242 close(filedes[0]);
243 filedes[0] = fd;
244 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
245 if (fd < 0) {
246 close(filedes[0]);
247 close(filedes[1]);
248 CloseHandle(h[1]);
249 return -1;
251 close(filedes[1]);
252 filedes[1] = fd;
253 return 0;
256 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
258 int i, pending;
260 if (timeout != -1)
261 return errno = EINVAL, error("poll timeout not supported");
263 /* When there is only one fd to wait for, then we pretend that
264 * input is available and let the actual wait happen when the
265 * caller invokes read().
267 if (nfds == 1) {
268 if (!(ufds[0].events & POLLIN))
269 return errno = EINVAL, error("POLLIN not set");
270 ufds[0].revents = POLLIN;
271 return 0;
274 repeat:
275 pending = 0;
276 for (i = 0; i < nfds; i++) {
277 DWORD avail = 0;
278 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
279 if (h == INVALID_HANDLE_VALUE)
280 return -1; /* errno was set */
282 if (!(ufds[i].events & POLLIN))
283 return errno = EINVAL, error("POLLIN not set");
285 /* this emulation works only for pipes */
286 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
287 int err = GetLastError();
288 if (err == ERROR_BROKEN_PIPE) {
289 ufds[i].revents = POLLHUP;
290 pending++;
291 } else {
292 errno = EINVAL;
293 return error("PeekNamedPipe failed,"
294 " GetLastError: %u", err);
296 } else if (avail) {
297 ufds[i].revents = POLLIN;
298 pending++;
299 } else
300 ufds[i].revents = 0;
302 if (!pending) {
303 /* The only times that we spin here is when the process
304 * that is connected through the pipes is waiting for
305 * its own input data to become available. But since
306 * the process (pack-objects) is itself CPU intensive,
307 * it will happily pick up the time slice that we are
308 * relinguishing here.
310 Sleep(0);
311 goto repeat;
313 return 0;
316 struct tm *gmtime_r(const time_t *timep, struct tm *result)
318 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
319 memcpy(result, gmtime(timep), sizeof(struct tm));
320 return result;
323 struct tm *localtime_r(const time_t *timep, struct tm *result)
325 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
326 memcpy(result, localtime(timep), sizeof(struct tm));
327 return result;
330 #undef getcwd
331 char *mingw_getcwd(char *pointer, int len)
333 char *ret = getcwd(pointer, len);
334 if (!ret)
335 return ret;
336 if (pointer[0] != 0 && pointer[1] == ':') {
337 int i;
338 for (i = 2; pointer[i]; i++)
339 /* Thanks, Bill. You'll burn in hell for that. */
340 if (pointer[i] == '\\')
341 pointer[i] = '/';
343 return ret;
347 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
348 * (Parsing C++ Command-Line Arguments)
350 static const char *quote_arg(const char *arg)
352 /* count chars to quote */
353 int len = 0, n = 0;
354 int force_quotes = 0;
355 char *q, *d;
356 const char *p = arg;
357 if (!*p) force_quotes = 1;
358 while (*p) {
359 if (isspace(*p) || *p == '*' || *p == '?')
360 force_quotes = 1;
361 else if (*p == '"')
362 n++;
363 else if (*p == '\\') {
364 int count = 0;
365 while (*p == '\\') {
366 count++;
367 p++;
368 len++;
370 if (*p == '"')
371 n += count*2 + 1;
372 continue;
374 len++;
375 p++;
377 if (!force_quotes && n == 0)
378 return arg;
380 /* insert \ where necessary */
381 d = q = xmalloc(len+n+3);
382 *d++ = '"';
383 while (*arg) {
384 if (*arg == '"')
385 *d++ = '\\';
386 else if (*arg == '\\') {
387 int count = 0;
388 while (*arg == '\\') {
389 count++;
390 *d++ = *arg++;
392 if (*arg == '"') {
393 while (count-- > 0)
394 *d++ = '\\';
395 *d++ = '\\';
398 *d++ = *arg++;
400 *d++ = '"';
401 *d++ = 0;
402 return q;
405 static const char *parse_interpreter(const char *cmd)
407 static char buf[100];
408 char *p, *opt;
409 int n, fd;
411 /* don't even try a .exe */
412 n = strlen(cmd);
413 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
414 return NULL;
416 fd = open(cmd, O_RDONLY);
417 if (fd < 0)
418 return NULL;
419 n = read(fd, buf, sizeof(buf)-1);
420 close(fd);
421 if (n < 4) /* at least '#!/x' and not error */
422 return NULL;
424 if (buf[0] != '#' || buf[1] != '!')
425 return NULL;
426 buf[n] = '\0';
427 p = strchr(buf, '\n');
428 if (!p)
429 return NULL;
431 *p = '\0';
432 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
433 return NULL;
434 /* strip options */
435 if ((opt = strchr(p+1, ' ')))
436 *opt = '\0';
437 return p+1;
441 * Splits the PATH into parts.
443 static char **get_path_split(void)
445 char *p, **path, *envpath = getenv("PATH");
446 int i, n = 0;
448 if (!envpath || !*envpath)
449 return NULL;
451 envpath = xstrdup(envpath);
452 p = envpath;
453 while (p) {
454 char *dir = p;
455 p = strchr(p, ';');
456 if (p) *p++ = '\0';
457 if (*dir) { /* not earlier, catches series of ; */
458 ++n;
461 if (!n)
462 return NULL;
464 path = xmalloc((n+1)*sizeof(char*));
465 p = envpath;
466 i = 0;
467 do {
468 if (*p)
469 path[i++] = xstrdup(p);
470 p = p+strlen(p)+1;
471 } while (i < n);
472 path[i] = NULL;
474 free(envpath);
476 return path;
479 static void free_path_split(char **path)
481 if (!path)
482 return;
484 char **p = path;
485 while (*p)
486 free(*p++);
487 free(path);
491 * exe_only means that we only want to detect .exe files, but not scripts
492 * (which do not have an extension)
494 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
496 char path[MAX_PATH];
497 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
499 if (!isexe && access(path, F_OK) == 0)
500 return xstrdup(path);
501 path[strlen(path)-4] = '\0';
502 if ((!exe_only || isexe) && access(path, F_OK) == 0)
503 return xstrdup(path);
504 return NULL;
508 * Determines the absolute path of cmd using the the split path in path.
509 * If cmd contains a slash or backslash, no lookup is performed.
511 static char *path_lookup(const char *cmd, char **path, int exe_only)
513 char *prog = NULL;
514 int len = strlen(cmd);
515 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
517 if (strchr(cmd, '/') || strchr(cmd, '\\'))
518 prog = xstrdup(cmd);
520 while (!prog && *path)
521 prog = lookup_prog(*path++, cmd, isexe, exe_only);
523 return prog;
526 static int env_compare(const void *a, const void *b)
528 char *const *ea = a;
529 char *const *eb = b;
530 return strcasecmp(*ea, *eb);
533 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
534 int prepend_cmd)
536 STARTUPINFO si;
537 PROCESS_INFORMATION pi;
538 struct strbuf envblk, args;
539 unsigned flags;
540 BOOL ret;
542 /* Determine whether or not we are associated to a console */
543 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
544 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
545 FILE_ATTRIBUTE_NORMAL, NULL);
546 if (cons == INVALID_HANDLE_VALUE) {
547 /* There is no console associated with this process.
548 * Since the child is a console process, Windows
549 * would normally create a console window. But
550 * since we'll be redirecting std streams, we do
551 * not need the console.
553 flags = CREATE_NO_WINDOW;
554 } else {
555 /* There is already a console. If we specified
556 * CREATE_NO_WINDOW here, too, Windows would
557 * disassociate the child from the console.
558 * Go figure!
560 flags = 0;
561 CloseHandle(cons);
563 memset(&si, 0, sizeof(si));
564 si.cb = sizeof(si);
565 si.dwFlags = STARTF_USESTDHANDLES;
566 si.hStdInput = (HANDLE) _get_osfhandle(0);
567 si.hStdOutput = (HANDLE) _get_osfhandle(1);
568 si.hStdError = (HANDLE) _get_osfhandle(2);
570 /* concatenate argv, quoting args as we go */
571 strbuf_init(&args, 0);
572 if (prepend_cmd) {
573 char *quoted = (char *)quote_arg(cmd);
574 strbuf_addstr(&args, quoted);
575 if (quoted != cmd)
576 free(quoted);
578 for (; *argv; argv++) {
579 char *quoted = (char *)quote_arg(*argv);
580 if (*args.buf)
581 strbuf_addch(&args, ' ');
582 strbuf_addstr(&args, quoted);
583 if (quoted != *argv)
584 free(quoted);
587 if (env) {
588 int count = 0;
589 char **e, **sorted_env;
591 for (e = env; *e; e++)
592 count++;
594 /* environment must be sorted */
595 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
596 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
597 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
599 strbuf_init(&envblk, 0);
600 for (e = sorted_env; *e; e++) {
601 strbuf_addstr(&envblk, *e);
602 strbuf_addch(&envblk, '\0');
604 free(sorted_env);
607 memset(&pi, 0, sizeof(pi));
608 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
609 env ? envblk.buf : NULL, NULL, &si, &pi);
611 if (env)
612 strbuf_release(&envblk);
613 strbuf_release(&args);
615 if (!ret) {
616 errno = ENOENT;
617 return -1;
619 CloseHandle(pi.hThread);
620 return (pid_t)pi.hProcess;
623 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
625 pid_t pid;
626 char **path = get_path_split();
627 char *prog = path_lookup(cmd, path, 0);
629 if (!prog) {
630 errno = ENOENT;
631 pid = -1;
633 else {
634 const char *interpr = parse_interpreter(prog);
636 if (interpr) {
637 const char *argv0 = argv[0];
638 char *iprog = path_lookup(interpr, path, 1);
639 argv[0] = prog;
640 if (!iprog) {
641 errno = ENOENT;
642 pid = -1;
644 else {
645 pid = mingw_spawnve(iprog, argv, env, 1);
646 free(iprog);
648 argv[0] = argv0;
650 else
651 pid = mingw_spawnve(prog, argv, env, 0);
652 free(prog);
654 free_path_split(path);
655 return pid;
658 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
660 const char *interpr = parse_interpreter(cmd);
661 char **path;
662 char *prog;
663 int pid = 0;
665 if (!interpr)
666 return 0;
667 path = get_path_split();
668 prog = path_lookup(interpr, path, 1);
669 if (prog) {
670 int argc = 0;
671 const char **argv2;
672 while (argv[argc]) argc++;
673 argv2 = xmalloc(sizeof(*argv) * (argc+1));
674 argv2[0] = (char *)cmd; /* full path to the script file */
675 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
676 pid = mingw_spawnve(prog, argv2, env, 1);
677 if (pid >= 0) {
678 int status;
679 if (waitpid(pid, &status, 0) < 0)
680 status = 255;
681 exit(status);
683 pid = 1; /* indicate that we tried but failed */
684 free(prog);
685 free(argv2);
687 free_path_split(path);
688 return pid;
691 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
693 /* check if git_command is a shell script */
694 if (!try_shell_exec(cmd, argv, (char **)env)) {
695 int pid, status;
697 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
698 if (pid < 0)
699 return;
700 if (waitpid(pid, &status, 0) < 0)
701 status = 255;
702 exit(status);
706 void mingw_execvp(const char *cmd, char *const *argv)
708 char **path = get_path_split();
709 char *prog = path_lookup(cmd, path, 0);
711 if (prog) {
712 mingw_execve(prog, argv, environ);
713 free(prog);
714 } else
715 errno = ENOENT;
717 free_path_split(path);
720 char **copy_environ()
722 char **env;
723 int i = 0;
724 while (environ[i])
725 i++;
726 env = xmalloc((i+1)*sizeof(*env));
727 for (i = 0; environ[i]; i++)
728 env[i] = xstrdup(environ[i]);
729 env[i] = NULL;
730 return env;
733 void free_environ(char **env)
735 int i;
736 for (i = 0; env[i]; i++)
737 free(env[i]);
738 free(env);
741 static int lookup_env(char **env, const char *name, size_t nmln)
743 int i;
745 for (i = 0; env[i]; i++) {
746 if (0 == strncmp(env[i], name, nmln)
747 && '=' == env[i][nmln])
748 /* matches */
749 return i;
751 return -1;
755 * If name contains '=', then sets the variable, otherwise it unsets it
757 char **env_setenv(char **env, const char *name)
759 char *eq = strchrnul(name, '=');
760 int i = lookup_env(env, name, eq-name);
762 if (i < 0) {
763 if (*eq) {
764 for (i = 0; env[i]; i++)
766 env = xrealloc(env, (i+2)*sizeof(*env));
767 env[i] = xstrdup(name);
768 env[i+1] = NULL;
771 else {
772 free(env[i]);
773 if (*eq)
774 env[i] = xstrdup(name);
775 else
776 for (; env[i]; i++)
777 env[i] = env[i+1];
779 return env;
782 /* this is the first function to call into WS_32; initialize it */
783 #undef gethostbyname
784 struct hostent *mingw_gethostbyname(const char *host)
786 WSADATA wsa;
788 if (WSAStartup(MAKEWORD(2,2), &wsa))
789 die("unable to initialize winsock subsystem, error %d",
790 WSAGetLastError());
791 atexit((void(*)(void)) WSACleanup);
792 return gethostbyname(host);
795 int mingw_socket(int domain, int type, int protocol)
797 int sockfd;
798 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
799 if (s == INVALID_SOCKET) {
801 * WSAGetLastError() values are regular BSD error codes
802 * biased by WSABASEERR.
803 * However, strerror() does not know about networking
804 * specific errors, which are values beginning at 38 or so.
805 * Therefore, we choose to leave the biased error code
806 * in errno so that _if_ someone looks up the code somewhere,
807 * then it is at least the number that are usually listed.
809 errno = WSAGetLastError();
810 return -1;
812 /* convert into a file descriptor */
813 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
814 closesocket(s);
815 return error("unable to make a socket file descriptor: %s",
816 strerror(errno));
818 return sockfd;
821 #undef connect
822 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
824 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
825 return connect(s, sa, sz);
828 #undef rename
829 int mingw_rename(const char *pold, const char *pnew)
832 * Try native rename() first to get errno right.
833 * It is based on MoveFile(), which cannot overwrite existing files.
835 if (!rename(pold, pnew))
836 return 0;
837 if (errno != EEXIST)
838 return -1;
839 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
840 return 0;
841 /* TODO: translate more errors */
842 if (GetLastError() == ERROR_ACCESS_DENIED) {
843 DWORD attrs = GetFileAttributes(pnew);
844 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
845 errno = EISDIR;
846 return -1;
849 errno = EACCES;
850 return -1;
853 #undef vsnprintf
854 /* Note that the size parameter specifies the available space, i.e.
855 * includes the trailing NUL byte; but Windows's vsnprintf expects the
856 * number of characters to write without the trailing NUL.
859 /* This is out of line because it uses alloca() behind the scenes,
860 * which must not be called in a loop (alloca() reclaims the allocations
861 * only at function exit).
863 static int try_vsnprintf(size_t size, const char *fmt, va_list args)
865 char buf[size]; /* gcc-ism */
866 return vsnprintf(buf, size-1, fmt, args);
869 int mingw_vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
871 int len;
872 if (size > 0) {
873 len = vsnprintf(buf, size-1, fmt, args);
874 if (len >= 0)
875 return len;
877 /* ouch, buffer too small; need to compute the size */
878 if (size < 250)
879 size = 250;
880 do {
881 size *= 4;
882 len = try_vsnprintf(size, fmt, args);
883 } while (len < 0);
884 return len;
887 struct passwd *getpwuid(int uid)
889 static char user_name[100];
890 static struct passwd p;
892 DWORD len = sizeof(user_name);
893 if (!GetUserName(user_name, &len))
894 return NULL;
895 p.pw_name = user_name;
896 p.pw_gecos = "unknown";
897 p.pw_dir = NULL;
898 return &p;
901 static HANDLE timer_event;
902 static HANDLE timer_thread;
903 static int timer_interval;
904 static int one_shot;
905 static sig_handler_t timer_fn = SIG_DFL;
907 /* The timer works like this:
908 * The thread, ticktack(), is basically a trivial routine that most of the
909 * time only waits to receive the signal to terminate. The main thread
910 * tells the thread to terminate by setting the timer_event to the signalled
911 * state.
912 * But ticktack() does not wait indefinitely; instead, it interrupts the
913 * wait state every now and then, namely exactly after timer's interval
914 * length. At these opportunities it calls the signal handler.
917 static __stdcall unsigned ticktack(void *dummy)
919 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
920 if (timer_fn == SIG_DFL)
921 die("Alarm");
922 if (timer_fn != SIG_IGN)
923 timer_fn(SIGALRM);
924 if (one_shot)
925 break;
927 return 0;
930 static int start_timer_thread(void)
932 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
933 if (timer_event) {
934 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
935 if (!timer_thread )
936 return errno = ENOMEM,
937 error("cannot start timer thread");
938 } else
939 return errno = ENOMEM,
940 error("cannot allocate resources timer");
941 return 0;
944 static void stop_timer_thread(void)
946 if (timer_event)
947 SetEvent(timer_event); /* tell thread to terminate */
948 if (timer_thread) {
949 int rc = WaitForSingleObject(timer_thread, 1000);
950 if (rc == WAIT_TIMEOUT)
951 error("timer thread did not terminate timely");
952 else if (rc != WAIT_OBJECT_0)
953 error("waiting for timer thread failed: %lu",
954 GetLastError());
955 CloseHandle(timer_thread);
957 if (timer_event)
958 CloseHandle(timer_event);
959 timer_event = NULL;
960 timer_thread = NULL;
963 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
965 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
968 int setitimer(int type, struct itimerval *in, struct itimerval *out)
970 static const struct timeval zero;
971 static int atexit_done;
973 if (out != NULL)
974 return errno = EINVAL,
975 error("setitmer param 3 != NULL not implemented");
976 if (!is_timeval_eq(&in->it_interval, &zero) &&
977 !is_timeval_eq(&in->it_interval, &in->it_value))
978 return errno = EINVAL,
979 error("setitmer: it_interval must be zero or eq it_value");
981 if (timer_thread)
982 stop_timer_thread();
984 if (is_timeval_eq(&in->it_value, &zero) &&
985 is_timeval_eq(&in->it_interval, &zero))
986 return 0;
988 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
989 one_shot = is_timeval_eq(&in->it_interval, &zero);
990 if (!atexit_done) {
991 atexit(stop_timer_thread);
992 atexit_done = 1;
994 return start_timer_thread();
997 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
999 if (sig != SIGALRM)
1000 return errno = EINVAL,
1001 error("sigaction only implemented for SIGALRM");
1002 if (out != NULL)
1003 return errno = EINVAL,
1004 error("sigaction: param 3 != NULL not implemented");
1006 timer_fn = in->sa_handler;
1007 return 0;
1010 #undef signal
1011 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1013 if (sig != SIGALRM)
1014 return signal(sig, handler);
1015 sig_handler_t old = timer_fn;
1016 timer_fn = handler;
1017 return old;