f0e5746363a14dd17d473b393acea2fd1280477f
[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 #if defined (LISP_FEATURE_LARGEFILE)
171 typedef dev_t ffi_dev_t;
172 typedef off_t ffi_off_t;
173 #elif defined(LISP_FEATURE_MIPS)
174 typedef unsigned long ffi_dev_t; /* Linux/MIPS struct stat doesn't use dev_t */
175 typedef off_t ffi_off_t;
176 #else
177 typedef u32 ffi_dev_t; /* since Linux dev_t can be 64 bits */
178 typedef u32 ffi_off_t; /* since OpenBSD 2.8 st_size is 64 bits */
179 #endif
180
181 /* a representation of stat(2) results which doesn't depend on CPU or OS */
182 struct stat_wrapper {
183     /* KLUDGE: The verbose wrapped_st_ prefixes are to protect us from
184      * the C preprocessor as wielded by the fiends of OpenBSD, who do
185      * things like
186      *    #define st_atime        st_atimespec.tv_sec
187      * I remember when I was young and innocent, I read about how the
188      * C preprocessor isn't to be used to globally munge random
189      * lowercase symbols like this, because things like this could
190      * happen, and I nodded sagely. But now I know better.:-| This is
191      * another entry for Dan Barlow's ongoing episodic rant about C
192      * header files, I guess.. -- WHN 2001-05-10 */
193     ffi_dev_t     wrapped_st_dev;         /* device */
194     ino_t         wrapped_st_ino;         /* inode */
195     mode_t        wrapped_st_mode;        /* protection */
196 #ifndef LISP_FEATURE_WIN32
197     nlink_t       wrapped_st_nlink;       /* number of hard links */
198     uid_t         wrapped_st_uid;         /* user ID of owner */
199     gid_t         wrapped_st_gid;         /* group ID of owner */
200 #else
201     short         wrapped_st_nlink;       /* Win32 doesn't have nlink_t */
202     short         wrapped_st_uid;         /* Win32 doesn't have st_uid */
203     short         wrapped_st_gid;         /* Win32 doesn't have st_gid */
204 #endif
205     ffi_dev_t     wrapped_st_rdev;        /* device type (if inode device) */
206     ffi_off_t     wrapped_st_size;        /* total size, in bytes */
207     unsigned long wrapped_st_blksize;     /* blocksize for filesystem I/O */
208     unsigned long wrapped_st_blocks;      /* number of blocks allocated */
209     time_t        wrapped_st_atime;       /* time_t of last access */
210     time_t        wrapped_st_mtime;       /* time_t of last modification */
211     time_t        wrapped_st_ctime;       /* time_t of last change */
212 };
213
214 static void
215 copy_to_stat_wrapper(struct stat_wrapper *to, struct stat *from)
216 {
217 #define FROB(stem) to->wrapped_st_##stem = from->st_##stem
218 #ifndef LISP_FEATURE_WIN32
219 #define FROB2(stem) to->wrapped_st_##stem = from->st_##stem
220 #else
221 #define FROB2(stem) to->wrapped_st_##stem = 0;
222 #endif
223     FROB(dev);
224     FROB2(ino);
225     FROB(mode);
226     FROB(nlink);
227     FROB2(uid);
228     FROB2(gid);
229     FROB(rdev);
230     FROB(size);
231     FROB2(blksize);
232     FROB2(blocks);
233     FROB(atime);
234     FROB(mtime);
235     FROB(ctime);
236 #undef FROB
237 }
238
239 int
240 stat_wrapper(const char *file_name, struct stat_wrapper *buf)
241 {
242     struct stat real_buf;
243     int ret;
244
245 #ifdef LISP_FEATURE_WIN32
246     /*
247      * Windows won't match the last component of a pathname if there
248      * is a trailing #\/ or #\\, except if it's <drive>:\ or <drive>:/
249      * in which case it behaves the other way around. So we remove the
250      * trailing directory separator unless we are being passed just a
251      * drive name (e.g. "c:\\").  Some, but not all, of this
252      * strangeness is documented at Microsoft's support site (as of
253      * 2006-01-08, at
254      * <http://support.microsoft.com/default.aspx?scid=kb;en-us;168439>)
255      */
256     char file_buf[MAX_PATH];
257     strcpy(file_buf, file_name);
258     int len = strlen(file_name);
259     if (len != 0 && (file_name[len-1] == '/' || file_name[len-1] == '\\') &&
260         !(len == 3 && file_name[1] == ':' && isalpha(file_name[0])))
261         file_buf[len-1] = '\0';
262     file_name = file_buf;
263 #endif
264
265     if ((ret = stat(file_name,&real_buf)) >= 0)
266         copy_to_stat_wrapper(buf, &real_buf);
267     return ret;
268 }
269
270 #ifndef LISP_FEATURE_WIN32
271 int
272 lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
273 {
274     struct stat real_buf;
275     int ret;
276     if ((ret = lstat(file_name,&real_buf)) >= 0)
277         copy_to_stat_wrapper(buf, &real_buf);
278     return ret;
279 }
280 #else
281 /* cleaner to do it here than in Lisp */
282 int lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
283 {
284     return stat_wrapper(file_name, buf);
285 }
286 #endif
287
288 int
289 fstat_wrapper(int filedes, struct stat_wrapper *buf)
290 {
291     struct stat real_buf;
292     int ret;
293     if ((ret = fstat(filedes,&real_buf)) >= 0)
294         copy_to_stat_wrapper(buf, &real_buf);
295     return ret;
296 }
297 \f
298 /*
299  * getpwuid() stuff
300  */
301
302 #ifndef LISP_FEATURE_WIN32
303 /* Return a newly-allocated string holding the username for "uid", or
304  * NULL if there's no such user.
305  *
306  * KLUDGE: We also return NULL if malloc() runs out of memory
307  * (returning strdup() result) since it's not clear how to handle that
308  * error better. -- WHN 2001-12-28 */
309 char *
310 uid_username(int uid)
311 {
312     struct passwd *p = getpwuid(uid);
313     if (p) {
314         /* The object *p is a static struct which'll be overwritten by
315          * the next call to getpwuid(), so it'd be unsafe to return
316          * p->pw_name without copying. */
317         return strdup(p->pw_name);
318     } else {
319         return 0;
320     }
321 }
322
323 char *
324 uid_homedir(uid_t uid)
325 {
326     struct passwd *p = getpwuid(uid);
327     if(p) {
328         /* Let's be careful about this, shall we? */
329         size_t len = strlen(p->pw_dir);
330         if (p->pw_dir[len-1] == '/') {
331             return strdup(p->pw_dir);
332         } else {
333             char *result = malloc(len + 2);
334             if (result) {
335                 int nchars = sprintf(result,"%s/",p->pw_dir);
336                 if (nchars == len + 1) {
337                     return result;
338                 } else {
339                     return 0;
340                 }
341             } else {
342                 return 0;
343             }
344         }
345     } else {
346         return 0;
347     }
348 }
349 #endif /* !LISP_FEATURE_WIN32 */
350 \f
351 /*
352  * functions to get miscellaneous C-level variables
353  *
354  * (Doing this by calling functions lets us borrow the smarts of the C
355  * linker, so that things don't blow up when libc versions and thus
356  * variable locations change between compile time and run time.)
357  */
358
359 char **
360 wrapped_environ()
361 {
362     return environ;
363 }
364
365 #ifdef LISP_FEATURE_WIN32
366 #define WIN32_LEAN_AND_MEAN
367 #include <windows.h>
368 #include <time.h>
369 /*
370  * faked-up implementation of select(). Right now just enough to get through
371  * second genesis.
372  */
373 int select(int top_fd, DWORD *read_set, DWORD *write_set, DWORD *except_set, time_t *timeout)
374 {
375     /*
376      * FIXME: Going forward, we may want to use MsgWaitForMultipleObjects
377      * in order to support a windows message loop inside serve-event.
378      */
379     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
380     int fds[MAXIMUM_WAIT_OBJECTS];
381     int num_handles;
382     int i;
383     DWORD retval;
384     int polling_write;
385     DWORD win_timeout;
386
387     num_handles = 0;
388     polling_write = 0;
389     for (i = 0; i < top_fd; i++) {
390         if (except_set) except_set[i >> 5] = 0;
391         if (write_set && (write_set[i >> 5] & (1 << (i & 31)))) polling_write = 1;
392         if (read_set[i >> 5] & (1 << (i & 31))) {
393             read_set[i >> 5] &= ~(1 << (i & 31));
394             fds[num_handles] = i;
395             handles[num_handles++] = (HANDLE) _get_osfhandle(i);
396         }
397     }
398
399     win_timeout = INFINITE;
400     if (timeout) win_timeout = (timeout[0] * 1000) + timeout[1];
401
402     /* Last parameter here is timeout in milliseconds. */
403     /* retval = WaitForMultipleObjects(num_handles, handles, 0, INFINITE); */
404     retval = WaitForMultipleObjects(num_handles, handles, 0, win_timeout);
405
406     if (retval < WAIT_ABANDONED) {
407         /* retval, at this point, is the index of the single live HANDLE/fd. */
408         read_set[fds[retval] >> 5] |= (1 << (fds[retval] & 31));
409         return 1;
410     }
411     return polling_write;
412 }
413
414 /*
415  * Windows doesn't have gettimeofday(), and we need it for the compiler,
416  * for serve-event, and for a couple other things. We don't need a timezone
417  * yet, however, and the closest we can easily get to a timeval is the
418  * seconds part. So that's what we do.
419  */
420 int gettimeofday(long *timeval, long *timezone)
421 {
422     timeval[0] = time(NULL);
423     timeval[1] = 0;
424
425     return 0;
426 }
427 #endif
428
429
430 /* We will need to define these things or their equivalents for Win32
431    eventually, but for now let's get it working for everyone else. */
432 #ifndef LISP_FEATURE_WIN32
433 /* From SB-BSD-SOCKETS, to get h_errno */
434 int get_h_errno()
435 {
436     return h_errno;
437 }
438
439 /* From SB-POSIX, wait-macros */
440 int wifexited(int status) {
441     return WIFEXITED(status);
442 }
443 int wexitstatus(int status) {
444     return WEXITSTATUS(status);
445 }
446 int wifsignaled(int status) {
447     return WIFSIGNALED(status);
448 }
449 int wtermsig(int status) {
450     return WTERMSIG(status);
451 }
452 int wifstopped(int status) {
453     return WIFSTOPPED(status);
454 }
455 int wstopsig(int status) {
456     return WSTOPSIG(status);
457 }
458 /* FIXME: POSIX also defines WIFCONTINUED, but that appears not to
459    exist on at least Linux... */
460 #endif  /* !LISP_FEATURE_WIN32 */
461
462 /* From SB-POSIX, stat-macros */
463 int s_isreg(mode_t mode)
464 {
465     return S_ISREG(mode);
466 }
467 int s_isdir(mode_t mode)
468 {
469     return S_ISDIR(mode);
470 }
471 int s_ischr(mode_t mode)
472 {
473     return S_ISCHR(mode);
474 }
475 int s_isblk(mode_t mode)
476 {
477     return S_ISBLK(mode);
478 }
479 int s_isfifo(mode_t mode)
480 {
481     return S_ISFIFO(mode);
482 }
483 #ifndef LISP_FEATURE_WIN32
484 int s_islnk(mode_t mode)
485 {
486 #ifdef S_ISLNK
487     return S_ISLNK(mode);
488 #else
489     return ((mode & S_IFMT) == S_IFLNK);
490 #endif
491 }
492 int s_issock(mode_t mode)
493 {
494 #ifdef S_ISSOCK
495     return S_ISSOCK(mode);
496 #else
497     return ((mode & S_IFMT) == S_IFSOCK);
498 #endif
499 }
500 #endif /* !LISP_FEATURE_WIN32 */