Code

Windows: Implement start_command().
[git.git] / compat / mingw.c
1 #include "../git-compat-util.h"
3 unsigned int _CRT_fmode = _O_BINARY;
5 #undef open
6 int mingw_open (const char *filename, int oflags, ...)
7 {
8         va_list args;
9         unsigned mode;
10         va_start(args, oflags);
11         mode = va_arg(args, int);
12         va_end(args);
14         if (!strcmp(filename, "/dev/null"))
15                 filename = "nul";
16         int fd = open(filename, oflags, mode);
17         if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
18                 DWORD attrs = GetFileAttributes(filename);
19                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
20                         errno = EISDIR;
21         }
22         return fd;
23 }
25 unsigned int sleep (unsigned int seconds)
26 {
27         Sleep(seconds*1000);
28         return 0;
29 }
31 int mkstemp(char *template)
32 {
33         char *filename = mktemp(template);
34         if (filename == NULL)
35                 return -1;
36         return open(filename, O_RDWR | O_CREAT, 0600);
37 }
39 int gettimeofday(struct timeval *tv, void *tz)
40 {
41         SYSTEMTIME st;
42         struct tm tm;
43         GetSystemTime(&st);
44         tm.tm_year = st.wYear-1900;
45         tm.tm_mon = st.wMonth-1;
46         tm.tm_mday = st.wDay;
47         tm.tm_hour = st.wHour;
48         tm.tm_min = st.wMinute;
49         tm.tm_sec = st.wSecond;
50         tv->tv_sec = tm_to_time_t(&tm);
51         if (tv->tv_sec < 0)
52                 return -1;
53         tv->tv_usec = st.wMilliseconds*1000;
54         return 0;
55 }
57 int pipe(int filedes[2])
58 {
59         int fd;
60         HANDLE h[2], parent;
62         if (_pipe(filedes, 8192, 0) < 0)
63                 return -1;
65         parent = GetCurrentProcess();
67         if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
68                         parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
69                 close(filedes[0]);
70                 close(filedes[1]);
71                 return -1;
72         }
73         if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
74                         parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
75                 close(filedes[0]);
76                 close(filedes[1]);
77                 CloseHandle(h[0]);
78                 return -1;
79         }
80         fd = _open_osfhandle((int)h[0], O_NOINHERIT);
81         if (fd < 0) {
82                 close(filedes[0]);
83                 close(filedes[1]);
84                 CloseHandle(h[0]);
85                 CloseHandle(h[1]);
86                 return -1;
87         }
88         close(filedes[0]);
89         filedes[0] = fd;
90         fd = _open_osfhandle((int)h[1], O_NOINHERIT);
91         if (fd < 0) {
92                 close(filedes[0]);
93                 close(filedes[1]);
94                 CloseHandle(h[1]);
95                 return -1;
96         }
97         close(filedes[1]);
98         filedes[1] = fd;
99         return 0;
102 int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
104         return -1;
107 struct tm *gmtime_r(const time_t *timep, struct tm *result)
109         /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
110         memcpy(result, gmtime(timep), sizeof(struct tm));
111         return result;
114 struct tm *localtime_r(const time_t *timep, struct tm *result)
116         /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
117         memcpy(result, localtime(timep), sizeof(struct tm));
118         return result;
121 #undef getcwd
122 char *mingw_getcwd(char *pointer, int len)
124         int i;
125         char *ret = getcwd(pointer, len);
126         if (!ret)
127                 return ret;
128         for (i = 0; pointer[i]; i++)
129                 if (pointer[i] == '\\')
130                         pointer[i] = '/';
131         return ret;
134 static const char *parse_interpreter(const char *cmd)
136         static char buf[100];
137         char *p, *opt;
138         int n, fd;
140         /* don't even try a .exe */
141         n = strlen(cmd);
142         if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
143                 return NULL;
145         fd = open(cmd, O_RDONLY);
146         if (fd < 0)
147                 return NULL;
148         n = read(fd, buf, sizeof(buf)-1);
149         close(fd);
150         if (n < 4)      /* at least '#!/x' and not error */
151                 return NULL;
153         if (buf[0] != '#' || buf[1] != '!')
154                 return NULL;
155         buf[n] = '\0';
156         p = strchr(buf, '\n');
157         if (!p)
158                 return NULL;
160         *p = '\0';
161         if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
162                 return NULL;
163         /* strip options */
164         if ((opt = strchr(p+1, ' ')))
165                 *opt = '\0';
166         return p+1;
169 /*
170  * Splits the PATH into parts.
171  */
172 static char **get_path_split(void)
174         char *p, **path, *envpath = getenv("PATH");
175         int i, n = 0;
177         if (!envpath || !*envpath)
178                 return NULL;
180         envpath = xstrdup(envpath);
181         p = envpath;
182         while (p) {
183                 char *dir = p;
184                 p = strchr(p, ';');
185                 if (p) *p++ = '\0';
186                 if (*dir) {     /* not earlier, catches series of ; */
187                         ++n;
188                 }
189         }
190         if (!n)
191                 return NULL;
193         path = xmalloc((n+1)*sizeof(char*));
194         p = envpath;
195         i = 0;
196         do {
197                 if (*p)
198                         path[i++] = xstrdup(p);
199                 p = p+strlen(p)+1;
200         } while (i < n);
201         path[i] = NULL;
203         free(envpath);
205         return path;
208 static void free_path_split(char **path)
210         if (!path)
211                 return;
213         char **p = path;
214         while (*p)
215                 free(*p++);
216         free(path);
219 /*
220  * exe_only means that we only want to detect .exe files, but not scripts
221  * (which do not have an extension)
222  */
223 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
225         char path[MAX_PATH];
226         snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
228         if (!isexe && access(path, F_OK) == 0)
229                 return xstrdup(path);
230         path[strlen(path)-4] = '\0';
231         if ((!exe_only || isexe) && access(path, F_OK) == 0)
232                 return xstrdup(path);
233         return NULL;
236 /*
237  * Determines the absolute path of cmd using the the split path in path.
238  * If cmd contains a slash or backslash, no lookup is performed.
239  */
240 static char *path_lookup(const char *cmd, char **path, int exe_only)
242         char *prog = NULL;
243         int len = strlen(cmd);
244         int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
246         if (strchr(cmd, '/') || strchr(cmd, '\\'))
247                 prog = xstrdup(cmd);
249         while (!prog && *path)
250                 prog = lookup_prog(*path++, cmd, isexe, exe_only);
252         return prog;
255 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
257         const char *interpr = parse_interpreter(cmd);
258         char **path;
259         char *prog;
260         int pid = 0;
262         if (!interpr)
263                 return 0;
264         path = get_path_split();
265         prog = path_lookup(interpr, path, 1);
266         if (prog) {
267                 int argc = 0;
268                 const char **argv2;
269                 while (argv[argc]) argc++;
270                 argv2 = xmalloc(sizeof(*argv) * (argc+2));
271                 argv2[0] = (char *)interpr;
272                 argv2[1] = (char *)cmd; /* full path to the script file */
273                 memcpy(&argv2[2], &argv[1], sizeof(*argv) * argc);
274                 pid = spawnve(_P_NOWAIT, prog, argv2, (const char **)env);
275                 if (pid >= 0) {
276                         int status;
277                         if (waitpid(pid, &status, 0) < 0)
278                                 status = 255;
279                         exit(status);
280                 }
281                 pid = 1;        /* indicate that we tried but failed */
282                 free(prog);
283                 free(argv2);
284         }
285         free_path_split(path);
286         return pid;
289 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
291         /* check if git_command is a shell script */
292         if (!try_shell_exec(cmd, argv, (char **)env)) {
293                 int pid, status;
295                 pid = spawnve(_P_NOWAIT, cmd, (const char **)argv, (const char **)env);
296                 if (pid < 0)
297                         return;
298                 if (waitpid(pid, &status, 0) < 0)
299                         status = 255;
300                 exit(status);
301         }
304 void mingw_execvp(const char *cmd, char *const *argv)
306         char **path = get_path_split();
307         char *prog = path_lookup(cmd, path, 0);
309         if (prog) {
310                 mingw_execve(prog, argv, environ);
311                 free(prog);
312         } else
313                 errno = ENOENT;
315         free_path_split(path);
318 char **copy_environ()
320         char **env;
321         int i = 0;
322         while (environ[i])
323                 i++;
324         env = xmalloc((i+1)*sizeof(*env));
325         for (i = 0; environ[i]; i++)
326                 env[i] = xstrdup(environ[i]);
327         env[i] = NULL;
328         return env;
331 void free_environ(char **env)
333         int i;
334         for (i = 0; env[i]; i++)
335                 free(env[i]);
336         free(env);
339 static int lookup_env(char **env, const char *name, size_t nmln)
341         int i;
343         for (i = 0; env[i]; i++) {
344                 if (0 == strncmp(env[i], name, nmln)
345                     && '=' == env[i][nmln])
346                         /* matches */
347                         return i;
348         }
349         return -1;
352 /*
353  * If name contains '=', then sets the variable, otherwise it unsets it
354  */
355 char **env_setenv(char **env, const char *name)
357         char *eq = strchrnul(name, '=');
358         int i = lookup_env(env, name, eq-name);
360         if (i < 0) {
361                 if (*eq) {
362                         for (i = 0; env[i]; i++)
363                                 ;
364                         env = xrealloc(env, (i+2)*sizeof(*env));
365                         env[i] = xstrdup(name);
366                         env[i+1] = NULL;
367                 }
368         }
369         else {
370                 free(env[i]);
371                 if (*eq)
372                         env[i] = xstrdup(name);
373                 else
374                         for (; env[i]; i++)
375                                 env[i] = env[i+1];
376         }
377         return env;
380 #undef rename
381 int mingw_rename(const char *pold, const char *pnew)
383         /*
384          * Try native rename() first to get errno right.
385          * It is based on MoveFile(), which cannot overwrite existing files.
386          */
387         if (!rename(pold, pnew))
388                 return 0;
389         if (errno != EEXIST)
390                 return -1;
391         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
392                 return 0;
393         /* TODO: translate more errors */
394         if (GetLastError() == ERROR_ACCESS_DENIED) {
395                 DWORD attrs = GetFileAttributes(pnew);
396                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
397                         errno = EISDIR;
398                         return -1;
399                 }
400         }
401         errno = EACCES;
402         return -1;
405 struct passwd *getpwuid(int uid)
407         static char user_name[100];
408         static struct passwd p;
410         DWORD len = sizeof(user_name);
411         if (!GetUserName(user_name, &len))
412                 return NULL;
413         p.pw_name = user_name;
414         p.pw_gecos = "unknown";
415         p.pw_dir = NULL;
416         return &p;
419 static HANDLE timer_event;
420 static HANDLE timer_thread;
421 static int timer_interval;
422 static int one_shot;
423 static sig_handler_t timer_fn = SIG_DFL;
425 /* The timer works like this:
426  * The thread, ticktack(), is a trivial routine that most of the time
427  * only waits to receive the signal to terminate. The main thread tells
428  * the thread to terminate by setting the timer_event to the signalled
429  * state.
430  * But ticktack() interrupts the wait state after the timer's interval
431  * length to call the signal handler.
432  */
434 static __stdcall unsigned ticktack(void *dummy)
436         while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
437                 if (timer_fn == SIG_DFL)
438                         die("Alarm");
439                 if (timer_fn != SIG_IGN)
440                         timer_fn(SIGALRM);
441                 if (one_shot)
442                         break;
443         }
444         return 0;
447 static int start_timer_thread(void)
449         timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
450         if (timer_event) {
451                 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
452                 if (!timer_thread )
453                         return errno = ENOMEM,
454                                 error("cannot start timer thread");
455         } else
456                 return errno = ENOMEM,
457                         error("cannot allocate resources for timer");
458         return 0;
461 static void stop_timer_thread(void)
463         if (timer_event)
464                 SetEvent(timer_event);  /* tell thread to terminate */
465         if (timer_thread) {
466                 int rc = WaitForSingleObject(timer_thread, 1000);
467                 if (rc == WAIT_TIMEOUT)
468                         error("timer thread did not terminate timely");
469                 else if (rc != WAIT_OBJECT_0)
470                         error("waiting for timer thread failed: %lu",
471                               GetLastError());
472                 CloseHandle(timer_thread);
473         }
474         if (timer_event)
475                 CloseHandle(timer_event);
476         timer_event = NULL;
477         timer_thread = NULL;
480 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
482         return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
485 int setitimer(int type, struct itimerval *in, struct itimerval *out)
487         static const struct timeval zero;
488         static int atexit_done;
490         if (out != NULL)
491                 return errno = EINVAL,
492                         error("setitimer param 3 != NULL not implemented");
493         if (!is_timeval_eq(&in->it_interval, &zero) &&
494             !is_timeval_eq(&in->it_interval, &in->it_value))
495                 return errno = EINVAL,
496                         error("setitimer: it_interval must be zero or eq it_value");
498         if (timer_thread)
499                 stop_timer_thread();
501         if (is_timeval_eq(&in->it_value, &zero) &&
502             is_timeval_eq(&in->it_interval, &zero))
503                 return 0;
505         timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
506         one_shot = is_timeval_eq(&in->it_interval, &zero);
507         if (!atexit_done) {
508                 atexit(stop_timer_thread);
509                 atexit_done = 1;
510         }
511         return start_timer_thread();
514 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
516         if (sig != SIGALRM)
517                 return errno = EINVAL,
518                         error("sigaction only implemented for SIGALRM");
519         if (out != NULL)
520                 return errno = EINVAL,
521                         error("sigaction: param 3 != NULL not implemented");
523         timer_fn = in->sa_handler;
524         return 0;
527 #undef signal
528 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
530         if (sig != SIGALRM)
531                 return signal(sig, handler);
532         sig_handler_t old = timer_fn;
533         timer_fn = handler;
534         return old;