Better support for NetBSD/current
[sbcl.git] / src / runtime / wrap.c
1 /*
2  * wrappers around low-level operations to provide a simpler interface
3  * to the operations that Lisp (and some contributed modules) needs.
4  *
5  * The functions in this file are typically called directly from Lisp.
6  * Thus, when their signature changes, they don't need updates in a .h
7  * file somewhere, but they do need updates in the Lisp code. FIXME:
8  * It would be nice to enforce this at compile time. It mighn't even
9  * be all that hard: make the cross-compiler versions of DEFINE-ALIEN-FOO
10  * macros accumulate strings in a list which then gets written out at
11  * the end of sbcl2.h at the end of cross-compilation, then rerun
12  * 'make' in src/runtime/ using the new sbcl2.h as sbcl.h (and make
13  * sure that all the files in src/runtime/ include sbcl.h). */
14
15 /*
16  * This software is part of the SBCL system. See the README file for
17  * more information.
18  *
19  * This software is derived from the CMU CL system, which was
20  * written at Carnegie Mellon University and released into the
21  * public domain. The software is in the public domain and is
22  * provided with absolutely no warranty. See the COPYING and CREDITS
23  * files for more information.
24  */
25
26 #include "sbcl.h"
27
28 #include <sys/types.h>
29 #include <dirent.h>
30 #include <sys/stat.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <limits.h>
37 #include <fcntl.h>
38
39 #ifndef LISP_FEATURE_WIN32
40 #include <pwd.h>
41 #include <time.h>
42 #include <sys/wait.h>
43 #include <sys/resource.h>
44 #include <netdb.h>
45 #endif
46 #include <stdio.h>
47
48 #if defined(LISP_FEATURE_WIN32)
49 #define WIN32_LEAN_AND_MEAN
50 #include <errno.h>
51 #endif
52
53 #include "runtime.h"
54 #include "util.h"
55 #include "wrap.h"
56
57 /* Although it might seem as though this should be in some standard
58    Unix header, according to Perry E. Metzger, in a message on
59    sbcl-devel dated 2004-03-29, this is the POSIXly-correct way of
60    using environ: by an explicit declaration.  -- CSR, 2004-03-30 */
61 extern char **environ;
62 \f
63 /*
64  * stuff needed by CL:DIRECTORY and other Lisp directory operations
65  */
66
67 \f
68 /*
69  * readlink(2) stuff
70  */
71
72 #ifndef LISP_FEATURE_WIN32
73 /* a wrapped version of readlink(2):
74  *   -- If path isn't a symlink, or is a broken symlink, return 0.
75  *   -- If path is a symlink, return a newly allocated string holding
76  *      the thing it's linked to. */
77 char *
78 wrapped_readlink(char *path)
79 {
80     int bufsiz = strlen(path) + 16;
81     while (1) {
82         char *result = malloc(bufsiz);
83         int n_read = readlink(path, result, bufsiz);
84         if (n_read < 0) {
85             free(result);
86             return 0;
87         } else if (n_read < bufsiz) {
88             result[n_read] = 0;
89             return result;
90         } else {
91             free(result);
92             bufsiz *= 2;
93         }
94     }
95 }
96 #endif
97 \f
98 /*
99  * realpath(3), including a wrapper for Windows.
100  */
101 char * sb_realpath (char *path)
102 {
103 #ifndef LISP_FEATURE_WIN32
104     char *ret;
105     int errnum;
106
107     if ((ret = calloc(PATH_MAX, sizeof(char))) == NULL)
108         return NULL;
109     if (realpath(path, ret) == NULL) {
110         errnum = errno;
111         free(ret);
112         errno = errnum;
113         return NULL;
114     }
115     return(ret);
116 #else
117     char *ret;
118     char *cp;
119     int errnum;
120
121     if ((ret = calloc(MAX_PATH, sizeof(char))) == NULL)
122         return NULL;
123     if (GetFullPathName(path, MAX_PATH, ret, &cp) == 0) {
124         errnum = errno;
125         free(ret);
126         errno = errnum;
127         return NULL;
128     }
129     return(ret);
130 #endif
131 }
132 \f
133 /* readdir, closedir, and dirent name accessor. The first three are not strictly
134  * necessary, but should save us some #!+netbsd in the build, and this also allows
135  * building Windows versions using the non-ANSI variants of FindFirstFile &co
136  * under the same API. (Use a structure that appends the handle to the WIN32_FIND_DATA
137  * as the return value from sb_opendir, on sb_readdir grab the name from the previous
138  * call and save the new one.) Nikodemus thought he would have to do that to support
139  * DIRECTORY on UNC paths, but turns out opendir &co do TRT on Windows already -- so
140  * leaving that bit of tedium for a later date, once we figure out the whole *A vs. *W
141  * issue out properly. ...FIXME, obviously, as per above.
142  *
143  * Once that is done, the lisp side functions are best named OS-OPENDIR, etc.
144  */
145 extern DIR *
146 sb_opendir(char * name)
147 {
148     return opendir(name);
149 }
150
151 extern struct dirent *
152 sb_readdir(DIR * dirp)
153 {
154     return readdir(dirp);
155 }
156
157 extern int
158 sb_closedir(DIR * dirp)
159 {
160     return closedir(dirp);
161 }
162
163 extern char *
164 sb_dirent_name(struct dirent * ent)
165 {
166     return ent->d_name;
167 }
168 \f
169 /*
170  * stat(2) stuff
171  */
172
173 static void
174 copy_to_stat_wrapper(struct stat_wrapper *to, struct stat *from)
175 {
176 #define FROB(stem) to->wrapped_st_##stem = from->st_##stem
177 #ifndef LISP_FEATURE_WIN32
178 #define FROB2(stem) to->wrapped_st_##stem = from->st_##stem
179 #else
180 #define FROB2(stem) to->wrapped_st_##stem = 0;
181 #endif
182     FROB(dev);
183     FROB2(ino);
184     FROB(mode);
185     FROB(nlink);
186     FROB2(uid);
187     FROB2(gid);
188     FROB(rdev);
189     FROB(size);
190     FROB2(blksize);
191     FROB2(blocks);
192     FROB(atime);
193     FROB(mtime);
194     FROB(ctime);
195 #undef FROB
196 }
197
198 int
199 stat_wrapper(const char *file_name, struct stat_wrapper *buf)
200 {
201     struct stat real_buf;
202     int ret;
203
204 #ifdef LISP_FEATURE_WIN32
205     /*
206      * Windows won't match the last component of a pathname if there
207      * is a trailing #\/ or #\\, except if it's <drive>:\ or <drive>:/
208      * in which case it behaves the other way around. So we remove the
209      * trailing directory separator unless we are being passed just a
210      * drive name (e.g. "c:\\").  Some, but not all, of this
211      * strangeness is documented at Microsoft's support site (as of
212      * 2006-01-08, at
213      * <http://support.microsoft.com/default.aspx?scid=kb;en-us;168439>)
214      */
215     char file_buf[MAX_PATH];
216     strcpy(file_buf, file_name);
217     int len = strlen(file_name);
218     if (len != 0 && (file_name[len-1] == '/' || file_name[len-1] == '\\') &&
219         !(len == 3 && file_name[1] == ':' && isalpha(file_name[0])))
220         file_buf[len-1] = '\0';
221     file_name = file_buf;
222 #endif
223
224     if ((ret = stat(file_name,&real_buf)) >= 0)
225         copy_to_stat_wrapper(buf, &real_buf);
226     return ret;
227 }
228
229 #ifndef LISP_FEATURE_WIN32
230 int
231 lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
232 {
233     struct stat real_buf;
234     int ret;
235     if ((ret = lstat(file_name,&real_buf)) >= 0)
236         copy_to_stat_wrapper(buf, &real_buf);
237     return ret;
238 }
239 #else
240 /* cleaner to do it here than in Lisp */
241 int lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
242 {
243     return stat_wrapper(file_name, buf);
244 }
245 #endif
246
247 int
248 fstat_wrapper(int filedes, struct stat_wrapper *buf)
249 {
250     struct stat real_buf;
251     int ret;
252     if ((ret = fstat(filedes,&real_buf)) >= 0)
253         copy_to_stat_wrapper(buf, &real_buf);
254     return ret;
255 }
256 \f
257 /* A wrapper for mkstemp(3), for two reasons: (1) mkstemp does not
258    exist on Windows; (2) by passing down a mode_t, we don't need a
259    binding to chmod in SB-UNIX, and need not concern ourselves with
260    umask issues if we want to use mkstemp to make new files in
261    OPEN. */
262 int sb_mkstemp (char *template, mode_t mode) {
263 #ifdef LISP_FEATURE_WIN32
264 #define PATHNAME_BUFFER_SIZE MAX_PATH
265 #define MKTEMP _mktemp
266 #else
267 #define PATHNAME_BUFFER_SIZE PATH_MAX
268 #define MKTEMP mktemp
269 #endif
270   int fd;
271   char buf[PATHNAME_BUFFER_SIZE];
272
273   while (1) {
274     /* Fruit fallen from the tree: for people who like
275        microoptimizations, we might not need to copy the whole
276        template on every loop, but only the last several characters.
277        But I didn't feel like testing the boundary cases in Windows's
278        _mktemp. */
279     strncpy(buf, template, PATHNAME_BUFFER_SIZE);
280     buf[PATHNAME_BUFFER_SIZE-1]=0; /* force NULL-termination */
281     if (MKTEMP(buf)) {
282       if ((fd=open(buf, O_CREAT|O_EXCL|O_RDWR, mode))!=-1) {
283         strcpy(template, buf);
284         return (fd);
285       } else
286         if (errno != EEXIST)
287           return (-1);
288     } else
289       return (-1);
290   }
291 #undef MKTEMP
292 #undef PATHNAME_BUFFER_SIZE
293 }
294
295 \f
296 /*
297  * getpwuid() stuff
298  */
299
300 #ifndef LISP_FEATURE_WIN32
301 /* Return a newly-allocated string holding the username for "uid", or
302  * NULL if there's no such user.
303  *
304  * KLUDGE: We also return NULL if malloc() runs out of memory
305  * (returning strdup() result) since it's not clear how to handle that
306  * error better. -- WHN 2001-12-28 */
307 char *
308 uid_username(int uid)
309 {
310     struct passwd *p = getpwuid(uid);
311     if (p) {
312         /* The object *p is a static struct which'll be overwritten by
313          * the next call to getpwuid(), so it'd be unsafe to return
314          * p->pw_name without copying. */
315         return strdup(p->pw_name);
316     } else {
317         return 0;
318     }
319 }
320
321 char *
322 passwd_homedir(struct passwd *p)
323 {
324     if (p) {
325         /* Let's be careful about this, shall we? */
326         size_t len = strlen(p->pw_dir);
327         if (p->pw_dir[len-1] == '/') {
328             return strdup(p->pw_dir);
329         } else {
330             char *result = malloc(len + 2);
331             if (result) {
332                 unsigned int nchars = sprintf(result,"%s/",p->pw_dir);
333                 if (nchars == len + 1) {
334                     return result;
335                 } else {
336                     return 0;
337                 }
338             } else {
339                 return 0;
340             }
341         }
342     } else {
343         return 0;
344     }
345 }
346
347 char *
348 user_homedir(char *name)
349 {
350     return passwd_homedir(getpwnam(name));
351 }
352
353 char *
354 uid_homedir(uid_t uid)
355 {
356     return passwd_homedir(getpwuid(uid));
357 }
358 #endif /* !LISP_FEATURE_WIN32 */
359 \f
360 /*
361  * functions to get miscellaneous C-level variables
362  *
363  * (Doing this by calling functions lets us borrow the smarts of the C
364  * linker, so that things don't blow up when libc versions and thus
365  * variable locations change between compile time and run time.)
366  */
367
368 char **
369 wrapped_environ()
370 {
371     return environ;
372 }
373
374 #ifdef LISP_FEATURE_WIN32
375 #include <windows.h>
376 #include <time.h>
377 /*
378  * faked-up implementation of select(). Right now just enough to get through
379  * second genesis.
380  */
381 int sb_select(int top_fd, DWORD *read_set, DWORD *write_set, DWORD *except_set, time_t *timeout)
382 {
383     /*
384      * FIXME: Going forward, we may want to use MsgWaitForMultipleObjects
385      * in order to support a windows message loop inside serve-event.
386      */
387     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
388     int fds[MAXIMUM_WAIT_OBJECTS];
389     int num_handles;
390     int i;
391     DWORD retval;
392     int polling_write;
393     DWORD win_timeout;
394
395     num_handles = 0;
396     polling_write = 0;
397     for (i = 0; i < top_fd; i++) {
398         if (except_set) except_set[i >> 5] = 0;
399         if (write_set && (write_set[i >> 5] & (1 << (i & 31)))) polling_write = 1;
400         if (read_set[i >> 5] & (1 << (i & 31))) {
401             read_set[i >> 5] &= ~(1 << (i & 31));
402             fds[num_handles] = i;
403             handles[num_handles++] = (HANDLE) _get_osfhandle(i);
404         }
405     }
406
407     win_timeout = INFINITE;
408     if (timeout) win_timeout = (timeout[0] * 1000) + timeout[1];
409
410     /* Last parameter here is timeout in milliseconds. */
411     /* retval = WaitForMultipleObjects(num_handles, handles, 0, INFINITE); */
412     retval = WaitForMultipleObjects(num_handles, handles, 0, win_timeout);
413
414     if (retval < WAIT_ABANDONED) {
415         /* retval, at this point, is the index of the single live HANDLE/fd. */
416         read_set[fds[retval] >> 5] |= (1 << (fds[retval] & 31));
417         return 1;
418     }
419     return polling_write;
420 }
421
422 /*
423  * Windows doesn't have gettimeofday(), and we need it for the compiler,
424  * for serve-event, and for a couple other things. We don't need a timezone
425  * yet, however, and the closest we can easily get to a timeval is the
426  * seconds part. So that's what we do.
427  */
428 #define UNIX_EPOCH_FILETIME 116444736000000000ULL
429
430 int sb_gettimeofday(long *timeval, long *timezone)
431 {
432     FILETIME ft;
433     ULARGE_INTEGER uft;
434     GetSystemTimeAsFileTime(&ft);
435     uft.LowPart = ft.dwLowDateTime;
436     uft.HighPart = ft.dwHighDateTime;
437     uft.QuadPart -= UNIX_EPOCH_FILETIME;
438     timeval[0] = uft.QuadPart / 10000000;
439     timeval[1] = (uft.QuadPart % 10000000)/10;
440
441     return 0;
442 }
443 #endif
444
445
446 /* We will need to define these things or their equivalents for Win32
447    eventually, but for now let's get it working for everyone else. */
448 #ifndef LISP_FEATURE_WIN32
449 /* From SB-BSD-SOCKETS, to get h_errno */
450 int get_h_errno()
451 {
452     return h_errno;
453 }
454
455 /* From SB-POSIX, wait-macros */
456 int wifexited(int status) {
457     return WIFEXITED(status);
458 }
459 int wexitstatus(int status) {
460     return WEXITSTATUS(status);
461 }
462 int wifsignaled(int status) {
463     return WIFSIGNALED(status);
464 }
465 int wtermsig(int status) {
466     return WTERMSIG(status);
467 }
468 int wifstopped(int status) {
469     return WIFSTOPPED(status);
470 }
471 int wstopsig(int status) {
472     return WSTOPSIG(status);
473 }
474 /* FIXME: POSIX also defines WIFCONTINUED, but that appears not to
475    exist on at least Linux... */
476 #endif  /* !LISP_FEATURE_WIN32 */
477
478 /* From SB-POSIX, stat-macros */
479 int s_isreg(mode_t mode)
480 {
481     return S_ISREG(mode);
482 }
483 int s_isdir(mode_t mode)
484 {
485     return S_ISDIR(mode);
486 }
487 int s_ischr(mode_t mode)
488 {
489     return S_ISCHR(mode);
490 }
491 int s_isblk(mode_t mode)
492 {
493     return S_ISBLK(mode);
494 }
495 int s_isfifo(mode_t mode)
496 {
497     return S_ISFIFO(mode);
498 }
499 #ifndef LISP_FEATURE_WIN32
500 int s_islnk(mode_t mode)
501 {
502 #ifdef S_ISLNK
503     return S_ISLNK(mode);
504 #else
505     return ((mode & S_IFMT) == S_IFLNK);
506 #endif
507 }
508 int s_issock(mode_t mode)
509 {
510 #ifdef S_ISSOCK
511     return S_ISSOCK(mode);
512 #else
513     return ((mode & S_IFMT) == S_IFSOCK);
514 #endif
515 }
516 #endif /* !LISP_FEATURE_WIN32 */
517
518 #ifndef LISP_FEATURE_WIN32
519 int sb_getrusage(int who, struct rusage *rusage)
520 {
521         return getrusage(who, rusage);
522 }
523
524 int sb_gettimeofday(struct timeval *tp, void *tzp)
525 {
526         return gettimeofday(tp, tzp);
527 }
528
529 int sb_nanosleep(struct timespec *rqtp, struct timespec *rmtp)
530 {
531         return nanosleep(rqtp, rmtp);
532 }
533
534 int sb_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
535     struct timeval *timeout)
536 {
537         return select(nfds, readfds, writefds, exceptfds, timeout);
538 }
539
540 int sb_getitimer(int which, struct itimerval *value)
541 {
542         return getitimer(which, value);
543 }
544
545 int sb_setitimer(int which, struct itimerval *value, struct itimerval *ovalue)
546 {
547         return setitimer(which, value, ovalue);
548 }
549 #endif /* !LISP_FEATURE_WIN32 */
550