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