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