153ebd5f90f34516c645198ee4450126c8221025
[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 #ifndef LISP_FEATURE_WIN32
36 #include <pwd.h>
37 #include <sys/wait.h>
38 #include <netdb.h>
39 #endif
40 #include <stdio.h>
41
42 #include "runtime.h"
43 #include "util.h"
44
45 /* Although it might seem as though this should be in some standard
46    Unix header, according to Perry E. Metzger, in a message on
47    sbcl-devel dated 2004-03-29, this is the POSIXly-correct way of
48    using environ: by an explicit declaration.  -- CSR, 2004-03-30 */
49 extern char **environ;
50 \f
51 /*
52  * stuff needed by CL:DIRECTORY and other Lisp directory operations
53  */
54
55 /* Unix directory operations think of "." and ".." as filenames, but
56  * Lisp directory operations do not. */
57 int
58 is_lispy_filename(const char *filename)
59 {
60     return strcmp(filename, ".") && strcmp(filename, "..");
61 }
62
63 /* Return a zero-terminated array of strings holding the Lispy filenames
64  * (i.e. excluding the Unix magic "." and "..") in the named directory. */
65 char**
66 alloc_directory_lispy_filenames(const char *directory_name)
67 {
68     DIR *dir_ptr = opendir(directory_name);
69     char **result = 0;
70
71     if (dir_ptr) { /* if opendir success */
72
73         struct voidacc va;
74
75         if (0 == voidacc_ctor(&va)) { /* if voidacc_ctor success */
76             struct dirent *dirent_ptr;
77
78             while ( (dirent_ptr = readdir(dir_ptr)) ) { /* until end of data */
79                 char* original_name = dirent_ptr->d_name;
80                 if (is_lispy_filename(original_name)) {
81                     /* strdup(3) is in Linux and *BSD. If you port
82                      * somewhere else that doesn't have it, it's easy
83                      * to reimplement. */
84                     char* dup_name = strdup(original_name);
85                     if (!dup_name) { /* if strdup failure */
86                         goto dtors;
87                     }
88                     if (voidacc_acc(&va, dup_name)) { /* if acc failure */
89                         goto dtors;
90                     }
91                 }
92             }
93             result = (char**)voidacc_give_away_result(&va);
94         }
95
96     dtors:
97         voidacc_dtor(&va);
98         /* ignoring closedir(3) return code, since what could we do?
99          *
100          * "Never ask questions you don't want to know the answer to."
101          * -- William Irving Zumwalt (Rich Cook, _The Wizardry Quested_) */
102         closedir(dir_ptr);
103     }
104
105     return result;
106 }
107
108 /* Free a result returned by alloc_directory_lispy_filenames(). */
109 void
110 free_directory_lispy_filenames(char** directory_lispy_filenames)
111 {
112     char** p;
113
114     /* Free the strings. */
115     for (p = directory_lispy_filenames; *p; ++p) {
116         free(*p);
117     }
118
119     /* Free the table of strings. */
120     free(directory_lispy_filenames);
121 }
122 \f
123 /*
124  * readlink(2) stuff
125  */
126
127 #ifndef LISP_FEATURE_WIN32
128 /* a wrapped version of readlink(2):
129  *   -- If path isn't a symlink, or is a broken symlink, return 0.
130  *   -- If path is a symlink, return a newly allocated string holding
131  *      the thing it's linked to. */
132 char *
133 wrapped_readlink(char *path)
134 {
135     int bufsiz = strlen(path) + 16;
136     while (1) {
137         char *result = malloc(bufsiz);
138         int n_read = readlink(path, result, bufsiz);
139         if (n_read < 0) {
140             free(result);
141             return 0;
142         } else if (n_read < bufsiz) {
143             result[n_read] = 0;
144             return result;
145         } else {
146             free(result);
147             bufsiz *= 2;
148         }
149     }
150 }
151 #endif
152 \f
153 /*
154  * stat(2) stuff
155  */
156
157 /* As of 0.6.12, the FFI can't handle 64-bit values. For now, we use
158  * these munged-to-32-bits values for might-be-64-bit slots of
159  * stat_wrapper as a workaround, so that at least we can still work
160  * when values are small.
161  *
162  * FIXME: But of course we should fix the FFI so that we can use the
163  * actual 64-bit values instead.  In fact, we probably have by now
164  * (2003-10-03) on all working platforms except MIPS and HPPA; if some
165  * motivated spark would simply fix those, this hack could go away.
166  * -- CSR, 2003-10-03
167  *
168  * Some motivated spark fixed MIPS. -- ths, 2005-10-06 */
169
170 #ifdef LISP_FEATURE_MIPS
171 typedef unsigned long ffi_dev_t; /* Linux/MIPS struct stat doesn't use dev_t */
172 typedef off_t ffi_off_t;
173 #else
174 typedef u32 ffi_dev_t; /* since Linux dev_t can be 64 bits */
175 typedef u32 ffi_off_t; /* since OpenBSD 2.8 st_size is 64 bits */
176 #endif
177
178 /* a representation of stat(2) results which doesn't depend on CPU or OS */
179 struct stat_wrapper {
180     /* KLUDGE: The verbose wrapped_st_ prefixes are to protect us from
181      * the C preprocessor as wielded by the fiends of OpenBSD, who do
182      * things like
183      *    #define st_atime        st_atimespec.tv_sec
184      * I remember when I was young and innocent, I read about how the
185      * C preprocessor isn't to be used to globally munge random
186      * lowercase symbols like this, because things like this could
187      * happen, and I nodded sagely. But now I know better.:-| This is
188      * another entry for Dan Barlow's ongoing episodic rant about C
189      * header files, I guess.. -- WHN 2001-05-10 */
190     ffi_dev_t     wrapped_st_dev;         /* device */
191     ino_t         wrapped_st_ino;         /* inode */
192     mode_t        wrapped_st_mode;        /* protection */
193 #ifndef LISP_FEATURE_WIN32
194     nlink_t       wrapped_st_nlink;       /* number of hard links */
195     uid_t         wrapped_st_uid;         /* user ID of owner */
196     gid_t         wrapped_st_gid;         /* group ID of owner */
197 #else
198     short         wrapped_st_nlink;       /* Win32 doesn't have nlink_t */
199     short         wrapped_st_uid;         /* Win32 doesn't have st_uid */
200     short         wrapped_st_gid;         /* Win32 doesn't have st_gid */
201 #endif
202     ffi_dev_t     wrapped_st_rdev;        /* device type (if inode device) */
203     ffi_off_t     wrapped_st_size;        /* total size, in bytes */
204     unsigned long wrapped_st_blksize;     /* blocksize for filesystem I/O */
205     unsigned long wrapped_st_blocks;      /* number of blocks allocated */
206     time_t        wrapped_st_atime;       /* time_t of last access */
207     time_t        wrapped_st_mtime;       /* time_t of last modification */
208     time_t        wrapped_st_ctime;       /* time_t of last change */
209 };
210
211 static void
212 copy_to_stat_wrapper(struct stat_wrapper *to, struct stat *from)
213 {
214 #define FROB(stem) to->wrapped_st_##stem = from->st_##stem
215 #ifndef LISP_FEATURE_WIN32
216 #define FROB2(stem) to->wrapped_st_##stem = from->st_##stem
217 #else
218 #define FROB2(stem) to->wrapped_st_##stem = 0;
219 #endif
220     FROB(dev);
221     FROB2(ino);
222     FROB(mode);
223     FROB(nlink);
224     FROB2(uid);
225     FROB2(gid);
226     FROB(rdev);
227     FROB(size);
228     FROB2(blksize);
229     FROB2(blocks);
230     FROB(atime);
231     FROB(mtime);
232     FROB(ctime);
233 #undef FROB
234 }
235
236 int
237 stat_wrapper(const char *file_name, struct stat_wrapper *buf)
238 {
239     struct stat real_buf;
240     int ret;
241
242 #ifdef LISP_FEATURE_WIN32
243     /*
244      * Windows won't match the last component of a pathname if there
245      * is a trailing #\/ or #\\, except if it's <drive>:\ or <drive>:/
246      * in which case it behaves the other way around. So we remove the
247      * trailing directory separator unless we are being passed just a
248      * drive name (e.g. "c:\\").  Some, but not all, of this
249      * strangeness is documented at Microsoft's support site (as of
250      * 2006-01-08, at
251      * <http://support.microsoft.com/default.aspx?scid=kb;en-us;168439>)
252      */
253     char file_buf[MAX_PATH];
254     strcpy(file_buf, file_name);
255     int len = strlen(file_name);
256     if (len != 0 && (file_name[len-1] == '/' || file_name[len-1] == '\\') &&
257         !(len == 3 && file_name[1] == ':' && isalpha(file_name[0])))
258         file_buf[len-1] = '\0';
259     file_name = file_buf;
260 #endif
261
262     if ((ret = stat(file_name,&real_buf)) >= 0)
263         copy_to_stat_wrapper(buf, &real_buf);
264     return ret;
265 }
266
267 #ifndef LISP_FEATURE_WIN32
268 int
269 lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
270 {
271     struct stat real_buf;
272     int ret;
273     if ((ret = lstat(file_name,&real_buf)) >= 0)
274         copy_to_stat_wrapper(buf, &real_buf);
275     return ret;
276 }
277 #else
278 /* cleaner to do it here than in Lisp */
279 int lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
280 {
281     return stat_wrapper(file_name, buf);
282 }
283 #endif
284
285 int
286 fstat_wrapper(int filedes, struct stat_wrapper *buf)
287 {
288     struct stat real_buf;
289     int ret;
290     if ((ret = fstat(filedes,&real_buf)) >= 0)
291         copy_to_stat_wrapper(buf, &real_buf);
292     return ret;
293 }
294 \f
295 /*
296  * getpwuid() stuff
297  */
298
299 #ifndef LISP_FEATURE_WIN32
300 /* Return a newly-allocated string holding the username for "uid", or
301  * NULL if there's no such user.
302  *
303  * KLUDGE: We also return NULL if malloc() runs out of memory
304  * (returning strdup() result) since it's not clear how to handle that
305  * error better. -- WHN 2001-12-28 */
306 char *
307 uid_username(int uid)
308 {
309     struct passwd *p = getpwuid(uid);
310     if (p) {
311         /* The object *p is a static struct which'll be overwritten by
312          * the next call to getpwuid(), so it'd be unsafe to return
313          * p->pw_name without copying. */
314         return strdup(p->pw_name);
315     } else {
316         return 0;
317     }
318 }
319
320 char *
321 uid_homedir(uid_t uid)
322 {
323     struct passwd *p = getpwuid(uid);
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                 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 #endif /* !LISP_FEATURE_WIN32 */
347 \f
348 /*
349  * functions to get miscellaneous C-level variables
350  *
351  * (Doing this by calling functions lets us borrow the smarts of the C
352  * linker, so that things don't blow up when libc versions and thus
353  * variable locations change between compile time and run time.)
354  */
355
356 char **
357 wrapped_environ()
358 {
359     return environ;
360 }
361
362 #ifdef LISP_FEATURE_WIN32
363 #define WIN32_LEAN_AND_MEAN
364 #include <windows.h>
365 #include <time.h>
366 /*
367  * faked-up implementation of select(). Right now just enough to get through
368  * second genesis.
369  */
370 int select(int top_fd, DWORD *read_set, DWORD *write_set, DWORD *except_set, time_t *timeout)
371 {
372     /*
373      * FIXME: Going forward, we may want to use MsgWaitForMultipleObjects
374      * in order to support a windows message loop inside serve-event.
375      */
376     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
377     int fds[MAXIMUM_WAIT_OBJECTS];
378     int num_handles;
379     int i;
380     DWORD retval;
381     int polling_write;
382     DWORD win_timeout;
383
384     num_handles = 0;
385     polling_write = 0;
386     for (i = 0; i < top_fd; i++) {
387         if (except_set) except_set[i >> 5] = 0;
388         if (write_set && (write_set[i >> 5] & (1 << (i & 31)))) polling_write = 1;
389         if (read_set[i >> 5] & (1 << (i & 31))) {
390             read_set[i >> 5] &= ~(1 << (i & 31));
391             fds[num_handles] = i;
392             handles[num_handles++] = (HANDLE) _get_osfhandle(i);
393         }
394     }
395
396     win_timeout = INFINITE;
397     if (timeout) win_timeout = (timeout[0] * 1000) + timeout[1];
398
399     /* Last parameter here is timeout in milliseconds. */
400     /* retval = WaitForMultipleObjects(num_handles, handles, 0, INFINITE); */
401     retval = WaitForMultipleObjects(num_handles, handles, 0, win_timeout);
402
403     if (retval < WAIT_ABANDONED) {
404         /* retval, at this point, is the index of the single live HANDLE/fd. */
405         read_set[fds[retval] >> 5] |= (1 << (fds[retval] & 31));
406         return 1;
407     }
408     return polling_write;
409 }
410
411 /*
412  * Windows doesn't have gettimeofday(), and we need it for the compiler,
413  * for serve-event, and for a couple other things. We don't need a timezone
414  * yet, however, and the closest we can easily get to a timeval is the
415  * seconds part. So that's what we do.
416  */
417 int gettimeofday(long *timeval, long *timezone)
418 {
419     timeval[0] = time(NULL);
420     timeval[1] = 0;
421
422     return 0;
423 }
424 #endif
425
426
427 /* We will need to define these things or their equivalents for Win32
428    eventually, but for now let's get it working for everyone else. */
429 #ifndef LISP_FEATURE_WIN32
430 /* From SB-BSD-SOCKETS, to get h_errno */
431 int get_h_errno()
432 {
433     return h_errno;
434 }
435
436 /* From SB-POSIX, wait-macros */
437 int wifexited(int status) {
438     return WIFEXITED(status);
439 }
440 int wexitstatus(int status) {
441     return WEXITSTATUS(status);
442 }
443 int wifsignaled(int status) {
444     return WIFSIGNALED(status);
445 }
446 int wtermsig(int status) {
447     return WTERMSIG(status);
448 }
449 int wifstopped(int status) {
450     return WIFSTOPPED(status);
451 }
452 int wstopsig(int status) {
453     return WSTOPSIG(status);
454 }
455
456 /* FIXME: POSIX also defines WIFCONTINUED, but that appears not to
457    exist on at least Linux... */
458
459 /* From SB-POSIX, stat-macros */
460 int s_isreg(mode_t mode)
461 {
462     return S_ISREG(mode);
463 }
464 int s_isdir(mode_t mode)
465 {
466     return S_ISDIR(mode);
467 }
468 int s_ischr(mode_t mode)
469 {
470     return S_ISCHR(mode);
471 }
472 int s_isblk(mode_t mode)
473 {
474     return S_ISBLK(mode);
475 }
476 int s_isfifo(mode_t mode)
477 {
478     return S_ISFIFO(mode);
479 }
480 int s_islnk(mode_t mode)
481 {
482 #ifdef S_ISLNK
483     return S_ISLNK(mode);
484 #else
485     return ((mode & S_IFMT) == S_IFLNK);
486 #endif
487 }
488 int s_issock(mode_t mode)
489 {
490 #ifdef S_ISSOCK
491     return S_ISSOCK(mode);
492 #else
493     return ((mode & S_IFMT) == S_IFSOCK);
494 #endif
495 }
496 #endif /* !LISP_FEATURE_WIN32 */