Fix style of multi-line comments
[git/mingw/4msysgit.git] / compat / mingw.c
blob4e8402a9417cf2ec79a947b94a6897141de8d2cf
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include <winioctl.h>
5 #include "../strbuf.h"
7 #include <shellapi.h>
9 static int err_win_to_posix(DWORD winerr)
11 int error = ENOSYS;
12 switch(winerr) {
13 case ERROR_ACCESS_DENIED: error = EACCES; break;
14 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
15 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
16 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
17 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
18 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
19 case ERROR_BAD_COMMAND: error = EIO; break;
20 case ERROR_BAD_DEVICE: error = ENODEV; break;
21 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
22 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
23 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
24 case ERROR_BAD_LENGTH: error = EINVAL; break;
25 case ERROR_BAD_PATHNAME: error = ENOENT; break;
26 case ERROR_BAD_PIPE: error = EPIPE; break;
27 case ERROR_BAD_UNIT: error = ENODEV; break;
28 case ERROR_BAD_USERNAME: error = EINVAL; break;
29 case ERROR_BROKEN_PIPE: error = EPIPE; break;
30 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
31 case ERROR_BUSY: error = EBUSY; break;
32 case ERROR_BUSY_DRIVE: error = EBUSY; break;
33 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
34 case ERROR_CANNOT_MAKE: error = EACCES; break;
35 case ERROR_CANTOPEN: error = EIO; break;
36 case ERROR_CANTREAD: error = EIO; break;
37 case ERROR_CANTWRITE: error = EIO; break;
38 case ERROR_CRC: error = EIO; break;
39 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
40 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
41 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
42 case ERROR_DIRECTORY: error = EINVAL; break;
43 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
44 case ERROR_DISK_CHANGE: error = EIO; break;
45 case ERROR_DISK_FULL: error = ENOSPC; break;
46 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
47 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
48 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
49 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
50 case ERROR_FILE_EXISTS: error = EEXIST; break;
51 case ERROR_FILE_INVALID: error = ENODEV; break;
52 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
53 case ERROR_GEN_FAILURE: error = EIO; break;
54 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
55 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
56 case ERROR_INVALID_ACCESS: error = EACCES; break;
57 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
58 case ERROR_INVALID_BLOCK: error = EFAULT; break;
59 case ERROR_INVALID_DATA: error = EINVAL; break;
60 case ERROR_INVALID_DRIVE: error = ENODEV; break;
61 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
62 case ERROR_INVALID_FLAGS: error = EINVAL; break;
63 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
64 case ERROR_INVALID_HANDLE: error = EBADF; break;
65 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
66 case ERROR_INVALID_NAME: error = EINVAL; break;
67 case ERROR_INVALID_OWNER: error = EINVAL; break;
68 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
69 case ERROR_INVALID_PASSWORD: error = EPERM; break;
70 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
71 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
72 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
73 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
74 case ERROR_IO_DEVICE: error = EIO; break;
75 case ERROR_IO_INCOMPLETE: error = EINTR; break;
76 case ERROR_LOCKED: error = EBUSY; break;
77 case ERROR_LOCK_VIOLATION: error = EACCES; break;
78 case ERROR_LOGON_FAILURE: error = EACCES; break;
79 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
80 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
81 case ERROR_MORE_DATA: error = EPIPE; break;
82 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
83 case ERROR_NOACCESS: error = EFAULT; break;
84 case ERROR_NONE_MAPPED: error = EINVAL; break;
85 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
86 case ERROR_NOT_READY: error = EAGAIN; break;
87 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
88 case ERROR_NO_DATA: error = EPIPE; break;
89 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
90 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
91 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
92 case ERROR_OPEN_FAILED: error = EIO; break;
93 case ERROR_OPEN_FILES: error = EBUSY; break;
94 case ERROR_OPERATION_ABORTED: error = EINTR; break;
95 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
96 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
97 case ERROR_PATH_BUSY: error = EBUSY; break;
98 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
99 case ERROR_PIPE_BUSY: error = EBUSY; break;
100 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
101 case ERROR_PIPE_LISTENING: error = EPIPE; break;
102 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
103 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
104 case ERROR_READ_FAULT: error = EIO; break;
105 case ERROR_SEEK: error = EIO; break;
106 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
107 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
108 case ERROR_SHARING_VIOLATION: error = EACCES; break;
109 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
110 case ERROR_SWAPERROR: error = ENOENT; break;
111 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
112 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
113 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
114 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
115 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
116 case ERROR_WRITE_FAULT: error = EIO; break;
117 case ERROR_WRITE_PROTECT: error = EROFS; break;
119 return error;
122 #undef open
123 int mingw_open (const char *filename, int oflags, ...)
125 va_list args;
126 unsigned mode;
127 int fd;
129 va_start(args, oflags);
130 mode = va_arg(args, int);
131 va_end(args);
133 if (!strcmp(filename, "/dev/null"))
134 filename = "nul";
136 fd = open(filename, oflags, mode);
138 if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
139 DWORD attrs = GetFileAttributes(filename);
140 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
141 errno = EISDIR;
143 return fd;
146 static inline time_t filetime_to_time_t(const FILETIME *ft)
148 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
149 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
150 winTime /= 10000000; /* Nano to seconds resolution */
151 return (time_t)winTime;
155 * We keep the do_lstat code in a separate function to avoid recursion.
156 * When a path ends with a slash, the stat will fail with ENOENT. In
157 * this case, we strip the trailing slashes and stat again.
159 static int do_lstat(const char *file_name, struct stat *buf)
161 WIN32_FILE_ATTRIBUTE_DATA fdata;
163 if (!(errno = get_file_attr(file_name, &fdata))) {
164 buf->st_ino = 0;
165 buf->st_gid = 0;
166 buf->st_uid = 0;
167 buf->st_nlink = 1;
168 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
169 buf->st_size = fdata.nFileSizeLow |
170 (((off_t)fdata.nFileSizeHigh)<<32);
171 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
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 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
176 WIN32_FIND_DATAA findbuf;
177 HANDLE handle = FindFirstFileA(file_name, &findbuf);
178 if (handle != INVALID_HANDLE_VALUE) {
179 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
180 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
181 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
182 buf->st_mode = S_IREAD | S_IFLNK;
183 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
184 buf->st_mode |= S_IWRITE;
185 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
187 FindClose(handle);
190 return 0;
192 return -1;
196 * We provide our own lstat/fstat functions, since the provided
197 * lstat/fstat functions are so slow. These stat functions are
198 * tailored for Git's usage (read: fast), and are not meant to be
199 * complete. Note that Git stat()s are redirected to mingw_lstat()
200 * too, since Windows doesn't really handle symlinks that well.
202 int mingw_lstat(const char *file_name, struct stat *buf)
204 int namelen;
205 static char alt_name[PATH_MAX];
207 if (!do_lstat(file_name, buf))
208 return 0;
211 * if file_name ended in a '/', Windows returned ENOENT;
212 * try again without trailing slashes
214 if (errno != ENOENT)
215 return -1;
217 namelen = strlen(file_name);
218 if (namelen && file_name[namelen-1] != '/')
219 return -1;
220 while (namelen && file_name[namelen-1] == '/')
221 --namelen;
222 if (!namelen || namelen >= PATH_MAX)
223 return -1;
225 memcpy(alt_name, file_name, namelen);
226 alt_name[namelen] = 0;
227 return do_lstat(alt_name, buf);
230 #undef fstat
231 int mingw_fstat(int fd, struct stat *buf)
233 HANDLE fh = (HANDLE)_get_osfhandle(fd);
234 BY_HANDLE_FILE_INFORMATION fdata;
236 if (fh == INVALID_HANDLE_VALUE) {
237 errno = EBADF;
238 return -1;
240 /* direct non-file handles to MS's fstat() */
241 if (GetFileType(fh) != FILE_TYPE_DISK)
242 return _fstati64(fd, buf);
244 if (GetFileInformationByHandle(fh, &fdata)) {
245 buf->st_ino = 0;
246 buf->st_gid = 0;
247 buf->st_uid = 0;
248 buf->st_nlink = 1;
249 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
250 buf->st_size = fdata.nFileSizeLow |
251 (((off_t)fdata.nFileSizeHigh)<<32);
252 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
253 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
254 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
255 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
256 return 0;
258 errno = EBADF;
259 return -1;
262 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
264 long long winTime = t * 10000000LL + 116444736000000000LL;
265 ft->dwLowDateTime = winTime;
266 ft->dwHighDateTime = winTime >> 32;
269 int mingw_utime (const char *file_name, const struct utimbuf *times)
271 FILETIME mft, aft;
272 int fh, rc;
274 /* must have write permission */
275 if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
276 return -1;
278 time_t_to_filetime(times->modtime, &mft);
279 time_t_to_filetime(times->actime, &aft);
280 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
281 errno = EINVAL;
282 rc = -1;
283 } else
284 rc = 0;
285 close(fh);
286 return rc;
289 unsigned int sleep (unsigned int seconds)
291 Sleep(seconds*1000);
292 return 0;
295 int mkstemp(char *template)
297 char *filename = mktemp(template);
298 if (filename == NULL)
299 return -1;
300 return open(filename, O_RDWR | O_CREAT, 0600);
303 int gettimeofday(struct timeval *tv, void *tz)
305 SYSTEMTIME st;
306 struct tm tm;
307 GetSystemTime(&st);
308 tm.tm_year = st.wYear-1900;
309 tm.tm_mon = st.wMonth-1;
310 tm.tm_mday = st.wDay;
311 tm.tm_hour = st.wHour;
312 tm.tm_min = st.wMinute;
313 tm.tm_sec = st.wSecond;
314 tv->tv_sec = tm_to_time_t(&tm);
315 if (tv->tv_sec < 0)
316 return -1;
317 tv->tv_usec = st.wMilliseconds*1000;
318 return 0;
321 int pipe(int filedes[2])
323 int fd;
324 HANDLE h[2], parent;
326 if (_pipe(filedes, 8192, 0) < 0)
327 return -1;
329 parent = GetCurrentProcess();
331 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
332 parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
333 close(filedes[0]);
334 close(filedes[1]);
335 return -1;
337 if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
338 parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
339 close(filedes[0]);
340 close(filedes[1]);
341 CloseHandle(h[0]);
342 return -1;
344 fd = _open_osfhandle((int)h[0], O_NOINHERIT);
345 if (fd < 0) {
346 close(filedes[0]);
347 close(filedes[1]);
348 CloseHandle(h[0]);
349 CloseHandle(h[1]);
350 return -1;
352 close(filedes[0]);
353 filedes[0] = fd;
354 fd = _open_osfhandle((int)h[1], O_NOINHERIT);
355 if (fd < 0) {
356 close(filedes[0]);
357 close(filedes[1]);
358 CloseHandle(h[1]);
359 return -1;
361 close(filedes[1]);
362 filedes[1] = fd;
363 return 0;
366 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
368 int i, pending;
370 if (timeout >= 0) {
371 if (nfds == 0) {
372 Sleep(timeout);
373 return 0;
375 return errno = EINVAL, error("poll timeout not supported");
379 * When there is only one fd to wait for, then we pretend that
380 * input is available and let the actual wait happen when the
381 * caller invokes read().
383 if (nfds == 1) {
384 if (!(ufds[0].events & POLLIN))
385 return errno = EINVAL, error("POLLIN not set");
386 ufds[0].revents = POLLIN;
387 return 0;
390 repeat:
391 pending = 0;
392 for (i = 0; i < nfds; i++) {
393 DWORD avail = 0;
394 HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
395 if (h == INVALID_HANDLE_VALUE)
396 return -1; /* errno was set */
398 if (!(ufds[i].events & POLLIN))
399 return errno = EINVAL, error("POLLIN not set");
401 /* this emulation works only for pipes */
402 if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
403 int err = GetLastError();
404 if (err == ERROR_BROKEN_PIPE) {
405 ufds[i].revents = POLLHUP;
406 pending++;
407 } else {
408 errno = EINVAL;
409 return error("PeekNamedPipe failed,"
410 " GetLastError: %u", err);
412 } else if (avail) {
413 ufds[i].revents = POLLIN;
414 pending++;
415 } else
416 ufds[i].revents = 0;
418 if (!pending) {
420 * The only times that we spin here is when the process
421 * that is connected through the pipes is waiting for
422 * its own input data to become available. But since
423 * the process (pack-objects) is itself CPU intensive,
424 * it will happily pick up the time slice that we are
425 * relinquishing here.
427 Sleep(0);
428 goto repeat;
430 return 0;
433 struct tm *gmtime_r(const time_t *timep, struct tm *result)
435 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
436 memcpy(result, gmtime(timep), sizeof(struct tm));
437 return result;
440 struct tm *localtime_r(const time_t *timep, struct tm *result)
442 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
443 memcpy(result, localtime(timep), sizeof(struct tm));
444 return result;
447 #undef getcwd
448 char *mingw_getcwd(char *pointer, int len)
450 int i;
451 char *ret = getcwd(pointer, len);
452 if (!ret)
453 return ret;
454 for (i = 0; pointer[i]; i++)
455 if (pointer[i] == '\\')
456 pointer[i] = '/';
457 return ret;
460 #undef getenv
461 char *mingw_getenv(const char *name)
463 char *result = getenv(name);
464 if (!result && !strcmp(name, "TMPDIR")) {
465 /* on Windows it is TMP and TEMP */
466 result = getenv("TMP");
467 if (!result)
468 result = getenv("TEMP");
470 return result;
474 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
475 * (Parsing C++ Command-Line Arguments)
477 static const char *quote_arg(const char *arg)
479 /* count chars to quote */
480 int len = 0, n = 0;
481 int force_quotes = 0;
482 char *q, *d;
483 const char *p = arg;
484 if (!*p) force_quotes = 1;
485 while (*p) {
486 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
487 force_quotes = 1;
488 else if (*p == '"')
489 n++;
490 else if (*p == '\\') {
491 int count = 0;
492 while (*p == '\\') {
493 count++;
494 p++;
495 len++;
497 if (*p == '"')
498 n += count*2 + 1;
499 continue;
501 len++;
502 p++;
504 if (!force_quotes && n == 0)
505 return arg;
507 /* insert \ where necessary */
508 d = q = xmalloc(len+n+3);
509 *d++ = '"';
510 while (*arg) {
511 if (*arg == '"')
512 *d++ = '\\';
513 else if (*arg == '\\') {
514 int count = 0;
515 while (*arg == '\\') {
516 count++;
517 *d++ = *arg++;
519 if (*arg == '"') {
520 while (count-- > 0)
521 *d++ = '\\';
522 *d++ = '\\';
525 *d++ = *arg++;
527 *d++ = '"';
528 *d++ = 0;
529 return q;
532 static const char *parse_interpreter(const char *cmd)
534 static char buf[100];
535 char *p, *opt;
536 int n, fd;
538 /* don't even try a .exe */
539 n = strlen(cmd);
540 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
541 return NULL;
543 fd = open(cmd, O_RDONLY);
544 if (fd < 0)
545 return NULL;
546 n = read(fd, buf, sizeof(buf)-1);
547 close(fd);
548 if (n < 4) /* at least '#!/x' and not error */
549 return NULL;
551 if (buf[0] != '#' || buf[1] != '!')
552 return NULL;
553 buf[n] = '\0';
554 p = buf + strcspn(buf, "\r\n");
555 if (!*p)
556 return NULL;
558 *p = '\0';
559 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
560 return NULL;
561 /* strip options */
562 if ((opt = strchr(p+1, ' ')))
563 *opt = '\0';
564 return p+1;
568 * Splits the PATH into parts.
570 static char **get_path_split(void)
572 char *p, **path, *envpath = getenv("PATH");
573 int i, n = 0;
575 if (!envpath || !*envpath)
576 return NULL;
578 envpath = xstrdup(envpath);
579 p = envpath;
580 while (p) {
581 char *dir = p;
582 p = strchr(p, ';');
583 if (p) *p++ = '\0';
584 if (*dir) { /* not earlier, catches series of ; */
585 ++n;
588 if (!n)
589 return NULL;
591 path = xmalloc((n+1)*sizeof(char *));
592 p = envpath;
593 i = 0;
594 do {
595 if (*p)
596 path[i++] = xstrdup(p);
597 p = p+strlen(p)+1;
598 } while (i < n);
599 path[i] = NULL;
601 free(envpath);
603 return path;
606 static void free_path_split(char **path)
608 char **p = path;
610 if (!path)
611 return;
613 while (*p)
614 free(*p++);
615 free(path);
619 * exe_only means that we only want to detect .exe files, but not scripts
620 * (which do not have an extension)
622 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
624 char path[MAX_PATH];
625 snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
627 if (!isexe && access(path, F_OK) == 0)
628 return xstrdup(path);
629 path[strlen(path)-4] = '\0';
630 if ((!exe_only || isexe) && access(path, F_OK) == 0)
631 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
632 return xstrdup(path);
633 return NULL;
637 * Determines the absolute path of cmd using the the split path in path.
638 * If cmd contains a slash or backslash, no lookup is performed.
640 static char *path_lookup(const char *cmd, char **path, int exe_only)
642 char *prog = NULL;
643 int len = strlen(cmd);
644 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
646 if (strchr(cmd, '/') || strchr(cmd, '\\'))
647 prog = xstrdup(cmd);
649 while (!prog && *path)
650 prog = lookup_prog(*path++, cmd, isexe, exe_only);
652 return prog;
655 static int env_compare(const void *a, const void *b)
657 char *const *ea = a;
658 char *const *eb = b;
659 return strcasecmp(*ea, *eb);
662 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
663 int prepend_cmd)
665 STARTUPINFO si;
666 PROCESS_INFORMATION pi;
667 struct strbuf envblk, args;
668 unsigned flags;
669 BOOL ret;
671 /* Determine whether or not we are associated to a console */
672 HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
673 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
674 FILE_ATTRIBUTE_NORMAL, NULL);
675 if (cons == INVALID_HANDLE_VALUE) {
677 * There is no console associated with this process.
678 * Since the child is a console process, Windows
679 * would normally create a console window. But
680 * since we'll be redirecting std streams, we do
681 * not need the console.
682 * It is necessary to use DETACHED_PROCESS
683 * instead of CREATE_NO_WINDOW to make ssh
684 * recognize that it has no console.
686 flags = DETACHED_PROCESS;
687 } else {
689 * There is already a console. If we specified
690 * DETACHED_PROCESS here, too, Windows would
691 * disassociate the child from the console.
692 * The same is true for CREATE_NO_WINDOW.
693 * Go figure!
695 flags = 0;
696 CloseHandle(cons);
698 memset(&si, 0, sizeof(si));
699 si.cb = sizeof(si);
700 si.dwFlags = STARTF_USESTDHANDLES;
701 si.hStdInput = (HANDLE) _get_osfhandle(0);
702 si.hStdOutput = (HANDLE) _get_osfhandle(1);
703 si.hStdError = (HANDLE) _get_osfhandle(2);
705 /* concatenate argv, quoting args as we go */
706 strbuf_init(&args, 0);
707 if (prepend_cmd) {
708 char *quoted = (char *)quote_arg(cmd);
709 strbuf_addstr(&args, quoted);
710 if (quoted != cmd)
711 free(quoted);
713 for (; *argv; argv++) {
714 char *quoted = (char *)quote_arg(*argv);
715 if (*args.buf)
716 strbuf_addch(&args, ' ');
717 strbuf_addstr(&args, quoted);
718 if (quoted != *argv)
719 free(quoted);
722 if (env) {
723 int count = 0;
724 char **e, **sorted_env;
726 for (e = env; *e; e++)
727 count++;
729 /* environment must be sorted */
730 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
731 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
732 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
734 strbuf_init(&envblk, 0);
735 for (e = sorted_env; *e; e++) {
736 strbuf_addstr(&envblk, *e);
737 strbuf_addch(&envblk, '\0');
739 free(sorted_env);
742 memset(&pi, 0, sizeof(pi));
743 ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
744 env ? envblk.buf : NULL, NULL, &si, &pi);
746 if (env)
747 strbuf_release(&envblk);
748 strbuf_release(&args);
750 if (!ret) {
751 errno = ENOENT;
752 return -1;
754 CloseHandle(pi.hThread);
755 return (pid_t)pi.hProcess;
758 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
760 pid_t pid;
761 char **path = get_path_split();
762 char *prog = path_lookup(cmd, path, 0);
764 if (!prog) {
765 errno = ENOENT;
766 pid = -1;
768 else {
769 const char *interpr = parse_interpreter(prog);
771 if (interpr) {
772 const char *argv0 = argv[0];
773 char *iprog = path_lookup(interpr, path, 1);
774 argv[0] = prog;
775 if (!iprog) {
776 errno = ENOENT;
777 pid = -1;
779 else {
780 pid = mingw_spawnve(iprog, argv, env, 1);
781 free(iprog);
783 argv[0] = argv0;
785 else
786 pid = mingw_spawnve(prog, argv, env, 0);
787 free(prog);
789 free_path_split(path);
790 return pid;
793 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
795 const char *interpr = parse_interpreter(cmd);
796 char **path;
797 char *prog;
798 int pid = 0;
800 if (!interpr)
801 return 0;
802 path = get_path_split();
803 prog = path_lookup(interpr, path, 1);
804 if (prog) {
805 int argc = 0;
806 const char **argv2;
807 while (argv[argc]) argc++;
808 argv2 = xmalloc(sizeof(*argv) * (argc+1));
809 argv2[0] = (char *)cmd; /* full path to the script file */
810 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
811 pid = mingw_spawnve(prog, argv2, env, 1);
812 if (pid >= 0) {
813 int status;
814 if (waitpid(pid, &status, 0) < 0)
815 status = 255;
816 exit(status);
818 pid = 1; /* indicate that we tried but failed */
819 free(prog);
820 free(argv2);
822 free_path_split(path);
823 return pid;
826 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
828 /* check if git_command is a shell script */
829 if (!try_shell_exec(cmd, argv, (char **)env)) {
830 int pid, status;
832 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
833 if (pid < 0)
834 return;
835 if (waitpid(pid, &status, 0) < 0)
836 status = 255;
837 exit(status);
841 void mingw_execvp(const char *cmd, char *const *argv)
843 char **path = get_path_split();
844 char *prog = path_lookup(cmd, path, 0);
846 if (prog) {
847 mingw_execve(prog, argv, environ);
848 free(prog);
849 } else
850 errno = ENOENT;
852 free_path_split(path);
855 static char **copy_environ(void)
857 char **env;
858 int i = 0;
859 while (environ[i])
860 i++;
861 env = xmalloc((i+1)*sizeof(*env));
862 for (i = 0; environ[i]; i++)
863 env[i] = xstrdup(environ[i]);
864 env[i] = NULL;
865 return env;
868 void free_environ(char **env)
870 int i;
871 for (i = 0; env[i]; i++)
872 free(env[i]);
873 free(env);
876 static int lookup_env(char **env, const char *name, size_t nmln)
878 int i;
880 for (i = 0; env[i]; i++) {
881 if (0 == strncmp(env[i], name, nmln)
882 && '=' == env[i][nmln])
883 /* matches */
884 return i;
886 return -1;
890 * If name contains '=', then sets the variable, otherwise it unsets it
892 static char **env_setenv(char **env, const char *name)
894 char *eq = strchrnul(name, '=');
895 int i = lookup_env(env, name, eq-name);
897 if (i < 0) {
898 if (*eq) {
899 for (i = 0; env[i]; i++)
901 env = xrealloc(env, (i+2)*sizeof(*env));
902 env[i] = xstrdup(name);
903 env[i+1] = NULL;
906 else {
907 free(env[i]);
908 if (*eq)
909 env[i] = xstrdup(name);
910 else
911 for (; env[i]; i++)
912 env[i] = env[i+1];
914 return env;
918 * Copies global environ and adjusts variables as specified by vars.
920 char **make_augmented_environ(const char *const *vars)
922 char **env = copy_environ();
924 while (*vars)
925 env = env_setenv(env, *vars++);
926 return env;
929 /* this is the first function to call into WS_32; initialize it */
930 #undef gethostbyname
931 struct hostent *mingw_gethostbyname(const char *host)
933 WSADATA wsa;
935 if (WSAStartup(MAKEWORD(2,2), &wsa))
936 die("unable to initialize winsock subsystem, error %d",
937 WSAGetLastError());
938 atexit((void(*)(void)) WSACleanup);
939 return gethostbyname(host);
942 int mingw_socket(int domain, int type, int protocol)
944 int sockfd;
945 SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
946 if (s == INVALID_SOCKET) {
948 * WSAGetLastError() values are regular BSD error codes
949 * biased by WSABASEERR.
950 * However, strerror() does not know about networking
951 * specific errors, which are values beginning at 38 or so.
952 * Therefore, we choose to leave the biased error code
953 * in errno so that _if_ someone looks up the code somewhere,
954 * then it is at least the number that are usually listed.
956 errno = WSAGetLastError();
957 return -1;
959 /* convert into a file descriptor */
960 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
961 closesocket(s);
962 return error("unable to make a socket file descriptor: %s",
963 strerror(errno));
965 return sockfd;
968 #undef connect
969 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
971 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
972 return connect(s, sa, sz);
975 #undef rename
976 int mingw_rename(const char *pold, const char *pnew)
978 DWORD attrs, gle;
979 int tries = 0;
980 static const int delay[] = { 0, 1, 10, 20, 40 };
983 * Try native rename() first to get errno right.
984 * It is based on MoveFile(), which cannot overwrite existing files.
986 if (!rename(pold, pnew))
987 return 0;
988 if (errno != EEXIST)
989 return -1;
990 repeat:
991 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
992 return 0;
993 /* TODO: translate more errors */
994 gle = GetLastError();
995 if (gle == ERROR_ACCESS_DENIED &&
996 (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
997 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
998 errno = EISDIR;
999 return -1;
1001 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1002 SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1003 if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1004 return 0;
1005 gle = GetLastError();
1006 /* revert file attributes on failure */
1007 SetFileAttributes(pnew, attrs);
1010 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1012 * We assume that some other process had the source or
1013 * destination file open at the wrong moment and retry.
1014 * In order to give the other process a higher chance to
1015 * complete its operation, we give up our time slice now.
1016 * If we have to retry again, we do sleep a bit.
1018 Sleep(delay[tries]);
1019 tries++;
1020 goto repeat;
1022 errno = EACCES;
1023 return -1;
1026 struct passwd *getpwuid(int uid)
1028 static char user_name[100];
1029 static struct passwd p;
1031 DWORD len = sizeof(user_name);
1032 if (!GetUserName(user_name, &len))
1033 return NULL;
1034 p.pw_name = user_name;
1035 p.pw_gecos = "unknown";
1036 p.pw_dir = NULL;
1037 return &p;
1040 static HANDLE timer_event;
1041 static HANDLE timer_thread;
1042 static int timer_interval;
1043 static int one_shot;
1044 static sig_handler_t timer_fn = SIG_DFL;
1047 * The timer works like this:
1048 * The thread, ticktack(), is a trivial routine that most of the time
1049 * only waits to receive the signal to terminate. The main thread tells
1050 * the thread to terminate by setting the timer_event to the signalled
1051 * state.
1052 * But ticktack() interrupts the wait state after the timer's interval
1053 * length to call the signal handler.
1056 static unsigned __stdcall ticktack(void *dummy)
1058 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1059 if (timer_fn == SIG_DFL)
1060 die("Alarm");
1061 if (timer_fn != SIG_IGN)
1062 timer_fn(SIGALRM);
1063 if (one_shot)
1064 break;
1066 return 0;
1069 static int start_timer_thread(void)
1071 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1072 if (timer_event) {
1073 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1074 if (!timer_thread )
1075 return errno = ENOMEM,
1076 error("cannot start timer thread");
1077 } else
1078 return errno = ENOMEM,
1079 error("cannot allocate resources for timer");
1080 return 0;
1083 static void stop_timer_thread(void)
1085 if (timer_event)
1086 SetEvent(timer_event); /* tell thread to terminate */
1087 if (timer_thread) {
1088 int rc = WaitForSingleObject(timer_thread, 1000);
1089 if (rc == WAIT_TIMEOUT)
1090 error("timer thread did not terminate timely");
1091 else if (rc != WAIT_OBJECT_0)
1092 error("waiting for timer thread failed: %lu",
1093 GetLastError());
1094 CloseHandle(timer_thread);
1096 if (timer_event)
1097 CloseHandle(timer_event);
1098 timer_event = NULL;
1099 timer_thread = NULL;
1102 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1104 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1107 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1109 static const struct timeval zero;
1110 static int atexit_done;
1112 if (out != NULL)
1113 return errno = EINVAL,
1114 error("setitimer param 3 != NULL not implemented");
1115 if (!is_timeval_eq(&in->it_interval, &zero) &&
1116 !is_timeval_eq(&in->it_interval, &in->it_value))
1117 return errno = EINVAL,
1118 error("setitimer: it_interval must be zero or eq it_value");
1120 if (timer_thread)
1121 stop_timer_thread();
1123 if (is_timeval_eq(&in->it_value, &zero) &&
1124 is_timeval_eq(&in->it_interval, &zero))
1125 return 0;
1127 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1128 one_shot = is_timeval_eq(&in->it_interval, &zero);
1129 if (!atexit_done) {
1130 atexit(stop_timer_thread);
1131 atexit_done = 1;
1133 return start_timer_thread();
1136 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1138 if (sig != SIGALRM)
1139 return errno = EINVAL,
1140 error("sigaction only implemented for SIGALRM");
1141 if (out != NULL)
1142 return errno = EINVAL,
1143 error("sigaction: param 3 != NULL not implemented");
1145 timer_fn = in->sa_handler;
1146 return 0;
1149 #undef signal
1150 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1152 sig_handler_t old = timer_fn;
1153 if (sig != SIGALRM)
1154 return signal(sig, handler);
1155 timer_fn = handler;
1156 return old;
1159 static const char *make_backslash_path(const char *path)
1161 static char buf[PATH_MAX + 1];
1162 char *c;
1164 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1165 die("Too long path: %.*s", 60, path);
1167 for (c = buf; *c; c++) {
1168 if (*c == '/')
1169 *c = '\\';
1171 return buf;
1174 void mingw_open_html(const char *unixpath)
1176 const char *htmlpath = make_backslash_path(unixpath);
1177 printf("Launching default browser to display HTML ...\n");
1178 ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);
1181 int link(const char *oldpath, const char *newpath)
1183 typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1184 static T create_hard_link = NULL;
1185 if (!create_hard_link) {
1186 create_hard_link = (T) GetProcAddress(
1187 GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1188 if (!create_hard_link)
1189 create_hard_link = (T)-1;
1191 if (create_hard_link == (T)-1) {
1192 errno = ENOSYS;
1193 return -1;
1195 if (!create_hard_link(newpath, oldpath, NULL)) {
1196 errno = err_win_to_posix(GetLastError());
1197 return -1;
1199 return 0;
1202 int symlink(const char *oldpath, const char *newpath)
1204 typedef BOOL WINAPI (*symlink_fn)(const char*, const char*, DWORD);
1205 static symlink_fn create_symbolic_link = NULL;
1206 if (!create_symbolic_link) {
1207 create_symbolic_link = (symlink_fn) GetProcAddress(
1208 GetModuleHandle("kernel32.dll"), "CreateSymbolicLinkA");
1209 if (!create_symbolic_link)
1210 create_symbolic_link = (symlink_fn)-1;
1212 if (create_symbolic_link == (symlink_fn)-1) {
1213 errno = ENOSYS;
1214 return -1;
1217 if (!create_symbolic_link(newpath, oldpath, 0)) {
1218 errno = err_win_to_posix(GetLastError());
1219 return -1;
1221 return 0;
1224 int readlink(const char *path, char *buf, size_t bufsiz)
1226 HANDLE handle = CreateFile(path, GENERIC_READ,
1227 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1228 NULL, OPEN_EXISTING,
1229 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1230 NULL);
1232 if (handle != INVALID_HANDLE_VALUE) {
1233 unsigned char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1234 DWORD dummy = 0;
1235 if (DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buffer,
1236 MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dummy, NULL)) {
1237 REPARSE_DATA_BUFFER *b = (REPARSE_DATA_BUFFER *) buffer;
1238 if (b->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
1239 int len = b->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
1240 int offset = b->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(wchar_t);
1241 snprintf(buf, bufsiz, "%*ls", len, & b->SymbolicLinkReparseBuffer.PathBuffer[offset]);
1242 CloseHandle(handle);
1243 return len;
1247 CloseHandle(handle);
1250 errno = EINVAL;
1251 return -1;
1254 char *getpass(const char *prompt)
1256 struct strbuf buf = STRBUF_INIT;
1258 fputs(prompt, stderr);
1259 for (;;) {
1260 char c = _getch();
1261 if (c == '\r' || c == '\n')
1262 break;
1263 strbuf_addch(&buf, c);
1265 fputs("\n", stderr);
1266 return strbuf_detach(&buf, NULL);
1269 #ifndef NO_MINGW_REPLACE_READDIR
1270 /* MinGW readdir implementation to avoid extra lstats for Git */
1271 struct mingw_DIR
1273 struct _finddata_t dd_dta; /* disk transfer area for this dir */
1274 struct mingw_dirent dd_dir; /* Our own implementation, including d_type */
1275 long dd_handle; /* _findnext handle */
1276 int dd_stat; /* 0 = next entry to read is first entry, -1 = off the end, positive = 0 based index of next entry */
1277 char dd_name[1]; /* given path for dir with search pattern (struct is extended) */
1280 struct dirent *mingw_readdir(DIR *dir)
1282 WIN32_FIND_DATAA buf;
1283 HANDLE handle;
1284 struct mingw_DIR *mdir = (struct mingw_DIR*)dir;
1286 if (!dir->dd_handle) {
1287 errno = EBADF; /* No set_errno for mingw */
1288 return NULL;
1291 if (dir->dd_handle == (long)INVALID_HANDLE_VALUE && dir->dd_stat == 0)
1293 DWORD lasterr;
1294 handle = FindFirstFileA(dir->dd_name, &buf);
1295 lasterr = GetLastError();
1296 dir->dd_handle = (long)handle;
1297 if (handle == INVALID_HANDLE_VALUE && (lasterr != ERROR_NO_MORE_FILES)) {
1298 errno = err_win_to_posix(lasterr);
1299 return NULL;
1301 } else if (dir->dd_handle == (long)INVALID_HANDLE_VALUE) {
1302 return NULL;
1303 } else if (!FindNextFileA((HANDLE)dir->dd_handle, &buf)) {
1304 DWORD lasterr = GetLastError();
1305 FindClose((HANDLE)dir->dd_handle);
1306 dir->dd_handle = (long)INVALID_HANDLE_VALUE;
1308 * POSIX says you shouldn't set errno when readdir can't
1309 * find any more files; so, if another error we leave it set.
1311 if (lasterr != ERROR_NO_MORE_FILES)
1312 errno = err_win_to_posix(lasterr);
1313 return NULL;
1316 /* We get here if `buf' contains valid data. */
1317 strcpy(dir->dd_dir.d_name, buf.cFileName);
1318 ++dir->dd_stat;
1320 /* Set file type, based on WIN32_FIND_DATA */
1321 mdir->dd_dir.d_type = 0;
1322 if ((buf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1323 (buf.dwReserved0 == IO_REPARSE_TAG_SYMLINK))
1324 mdir->dd_dir.d_type |= DT_LNK;
1325 else if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1326 mdir->dd_dir.d_type |= DT_DIR;
1327 else
1328 mdir->dd_dir.d_type |= DT_REG;
1330 return (struct dirent*)&dir->dd_dir;
1332 #endif // !NO_MINGW_REPLACE_READDIR