1d17e9ac1837725dc57ea31580e8241e11170441
[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 #include "wrap.h"
45
46 /* Although it might seem as though this should be in some standard
47    Unix header, according to Perry E. Metzger, in a message on
48    sbcl-devel dated 2004-03-29, this is the POSIXly-correct way of
49    using environ: by an explicit declaration.  -- CSR, 2004-03-30 */
50 extern char **environ;
51 \f
52 /*
53  * stuff needed by CL:DIRECTORY and other Lisp directory operations
54  */
55
56 /* Unix directory operations think of "." and ".." as filenames, but
57  * Lisp directory operations do not. */
58 int
59 is_lispy_filename(const char *filename)
60 {
61     return strcmp(filename, ".") && strcmp(filename, "..");
62 }
63
64 /* Return a zero-terminated array of strings holding the Lispy filenames
65  * (i.e. excluding the Unix magic "." and "..") in the named directory. */
66 char**
67 alloc_directory_lispy_filenames(const char *directory_name)
68 {
69     DIR *dir_ptr = opendir(directory_name);
70     char **result = 0;
71
72     if (dir_ptr) { /* if opendir success */
73
74         struct voidacc va;
75
76         if (0 == voidacc_ctor(&va)) { /* if voidacc_ctor success */
77             struct dirent *dirent_ptr;
78
79             while ( (dirent_ptr = readdir(dir_ptr)) ) { /* until end of data */
80                 char* original_name = dirent_ptr->d_name;
81                 if (is_lispy_filename(original_name)) {
82                     /* strdup(3) is in Linux and *BSD. If you port
83                      * somewhere else that doesn't have it, it's easy
84                      * to reimplement. */
85                     char* dup_name = strdup(original_name);
86                     if (!dup_name) { /* if strdup failure */
87                         goto dtors;
88                     }
89                     if (voidacc_acc(&va, dup_name)) { /* if acc failure */
90                         goto dtors;
91                     }
92                 }
93             }
94             result = (char**)voidacc_give_away_result(&va);
95         }
96
97     dtors:
98         voidacc_dtor(&va);
99         /* ignoring closedir(3) return code, since what could we do?
100          *
101          * "Never ask questions you don't want to know the answer to."
102          * -- William Irving Zumwalt (Rich Cook, _The Wizardry Quested_) */
103         closedir(dir_ptr);
104     }
105
106     return result;
107 }
108
109 /* Free a result returned by alloc_directory_lispy_filenames(). */
110 void
111 free_directory_lispy_filenames(char** directory_lispy_filenames)
112 {
113     char** p;
114
115     /* Free the strings. */
116     for (p = directory_lispy_filenames; *p; ++p) {
117         free(*p);
118     }
119
120     /* Free the table of strings. */
121     free(directory_lispy_filenames);
122 }
123 \f
124 /*
125  * readlink(2) stuff
126  */
127
128 #ifndef LISP_FEATURE_WIN32
129 /* a wrapped version of readlink(2):
130  *   -- If path isn't a symlink, or is a broken symlink, return 0.
131  *   -- If path is a symlink, return a newly allocated string holding
132  *      the thing it's linked to. */
133 char *
134 wrapped_readlink(char *path)
135 {
136     int bufsiz = strlen(path) + 16;
137     while (1) {
138         char *result = malloc(bufsiz);
139         int n_read = readlink(path, result, bufsiz);
140         if (n_read < 0) {
141             free(result);
142             return 0;
143         } else if (n_read < bufsiz) {
144             result[n_read] = 0;
145             return result;
146         } else {
147             free(result);
148             bufsiz *= 2;
149         }
150     }
151 }
152 #endif
153 \f
154 /*
155  * stat(2) stuff
156  */
157
158 static void
159 copy_to_stat_wrapper(struct stat_wrapper *to, struct stat *from)
160 {
161 #define FROB(stem) to->wrapped_st_##stem = from->st_##stem
162 #ifndef LISP_FEATURE_WIN32
163 #define FROB2(stem) to->wrapped_st_##stem = from->st_##stem
164 #else
165 #define FROB2(stem) to->wrapped_st_##stem = 0;
166 #endif
167     FROB(dev);
168     FROB2(ino);
169     FROB(mode);
170     FROB(nlink);
171     FROB2(uid);
172     FROB2(gid);
173     FROB(rdev);
174     FROB(size);
175     FROB2(blksize);
176     FROB2(blocks);
177     FROB(atime);
178     FROB(mtime);
179     FROB(ctime);
180 #undef FROB
181 }
182
183 int
184 stat_wrapper(const char *file_name, struct stat_wrapper *buf)
185 {
186     struct stat real_buf;
187     int ret;
188
189 #ifdef LISP_FEATURE_WIN32
190     /*
191      * Windows won't match the last component of a pathname if there
192      * is a trailing #\/ or #\\, except if it's <drive>:\ or <drive>:/
193      * in which case it behaves the other way around. So we remove the
194      * trailing directory separator unless we are being passed just a
195      * drive name (e.g. "c:\\").  Some, but not all, of this
196      * strangeness is documented at Microsoft's support site (as of
197      * 2006-01-08, at
198      * <http://support.microsoft.com/default.aspx?scid=kb;en-us;168439>)
199      */
200     char file_buf[MAX_PATH];
201     strcpy(file_buf, file_name);
202     int len = strlen(file_name);
203     if (len != 0 && (file_name[len-1] == '/' || file_name[len-1] == '\\') &&
204         !(len == 3 && file_name[1] == ':' && isalpha(file_name[0])))
205         file_buf[len-1] = '\0';
206     file_name = file_buf;
207 #endif
208
209     if ((ret = stat(file_name,&real_buf)) >= 0)
210         copy_to_stat_wrapper(buf, &real_buf);
211     return ret;
212 }
213
214 #ifndef LISP_FEATURE_WIN32
215 int
216 lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
217 {
218     struct stat real_buf;
219     int ret;
220     if ((ret = lstat(file_name,&real_buf)) >= 0)
221         copy_to_stat_wrapper(buf, &real_buf);
222     return ret;
223 }
224 #else
225 /* cleaner to do it here than in Lisp */
226 int lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
227 {
228     return stat_wrapper(file_name, buf);
229 }
230 #endif
231
232 int
233 fstat_wrapper(int filedes, struct stat_wrapper *buf)
234 {
235     struct stat real_buf;
236     int ret;
237     if ((ret = fstat(filedes,&real_buf)) >= 0)
238         copy_to_stat_wrapper(buf, &real_buf);
239     return ret;
240 }
241 \f
242 /*
243  * getpwuid() stuff
244  */
245
246 #ifndef LISP_FEATURE_WIN32
247 /* Return a newly-allocated string holding the username for "uid", or
248  * NULL if there's no such user.
249  *
250  * KLUDGE: We also return NULL if malloc() runs out of memory
251  * (returning strdup() result) since it's not clear how to handle that
252  * error better. -- WHN 2001-12-28 */
253 char *
254 uid_username(int uid)
255 {
256     struct passwd *p = getpwuid(uid);
257     if (p) {
258         /* The object *p is a static struct which'll be overwritten by
259          * the next call to getpwuid(), so it'd be unsafe to return
260          * p->pw_name without copying. */
261         return strdup(p->pw_name);
262     } else {
263         return 0;
264     }
265 }
266
267 char *
268 uid_homedir(uid_t uid)
269 {
270     struct passwd *p = getpwuid(uid);
271     if(p) {
272         /* Let's be careful about this, shall we? */
273         size_t len = strlen(p->pw_dir);
274         if (p->pw_dir[len-1] == '/') {
275             return strdup(p->pw_dir);
276         } else {
277             char *result = malloc(len + 2);
278             if (result) {
279                 int nchars = sprintf(result,"%s/",p->pw_dir);
280                 if (nchars == len + 1) {
281                     return result;
282                 } else {
283                     return 0;
284                 }
285             } else {
286                 return 0;
287             }
288         }
289     } else {
290         return 0;
291     }
292 }
293 #endif /* !LISP_FEATURE_WIN32 */
294 \f
295 /*
296  * functions to get miscellaneous C-level variables
297  *
298  * (Doing this by calling functions lets us borrow the smarts of the C
299  * linker, so that things don't blow up when libc versions and thus
300  * variable locations change between compile time and run time.)
301  */
302
303 char **
304 wrapped_environ()
305 {
306     return environ;
307 }
308
309 #ifdef LISP_FEATURE_WIN32
310 #define WIN32_LEAN_AND_MEAN
311 #include <windows.h>
312 #include <time.h>
313 /*
314  * faked-up implementation of select(). Right now just enough to get through
315  * second genesis.
316  */
317 int select(int top_fd, DWORD *read_set, DWORD *write_set, DWORD *except_set, time_t *timeout)
318 {
319     /*
320      * FIXME: Going forward, we may want to use MsgWaitForMultipleObjects
321      * in order to support a windows message loop inside serve-event.
322      */
323     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
324     int fds[MAXIMUM_WAIT_OBJECTS];
325     int num_handles;
326     int i;
327     DWORD retval;
328     int polling_write;
329     DWORD win_timeout;
330
331     num_handles = 0;
332     polling_write = 0;
333     for (i = 0; i < top_fd; i++) {
334         if (except_set) except_set[i >> 5] = 0;
335         if (write_set && (write_set[i >> 5] & (1 << (i & 31)))) polling_write = 1;
336         if (read_set[i >> 5] & (1 << (i & 31))) {
337             read_set[i >> 5] &= ~(1 << (i & 31));
338             fds[num_handles] = i;
339             handles[num_handles++] = (HANDLE) _get_osfhandle(i);
340         }
341     }
342
343     win_timeout = INFINITE;
344     if (timeout) win_timeout = (timeout[0] * 1000) + timeout[1];
345
346     /* Last parameter here is timeout in milliseconds. */
347     /* retval = WaitForMultipleObjects(num_handles, handles, 0, INFINITE); */
348     retval = WaitForMultipleObjects(num_handles, handles, 0, win_timeout);
349
350     if (retval < WAIT_ABANDONED) {
351         /* retval, at this point, is the index of the single live HANDLE/fd. */
352         read_set[fds[retval] >> 5] |= (1 << (fds[retval] & 31));
353         return 1;
354     }
355     return polling_write;
356 }
357
358 /*
359  * Windows doesn't have gettimeofday(), and we need it for the compiler,
360  * for serve-event, and for a couple other things. We don't need a timezone
361  * yet, however, and the closest we can easily get to a timeval is the
362  * seconds part. So that's what we do.
363  */
364 int gettimeofday(long *timeval, long *timezone)
365 {
366     timeval[0] = time(NULL);
367     timeval[1] = 0;
368
369     return 0;
370 }
371 #endif
372
373
374 /* We will need to define these things or their equivalents for Win32
375    eventually, but for now let's get it working for everyone else. */
376 #ifndef LISP_FEATURE_WIN32
377 /* From SB-BSD-SOCKETS, to get h_errno */
378 int get_h_errno()
379 {
380     return h_errno;
381 }
382
383 /* From SB-POSIX, wait-macros */
384 int wifexited(int status) {
385     return WIFEXITED(status);
386 }
387 int wexitstatus(int status) {
388     return WEXITSTATUS(status);
389 }
390 int wifsignaled(int status) {
391     return WIFSIGNALED(status);
392 }
393 int wtermsig(int status) {
394     return WTERMSIG(status);
395 }
396 int wifstopped(int status) {
397     return WIFSTOPPED(status);
398 }
399 int wstopsig(int status) {
400     return WSTOPSIG(status);
401 }
402 /* FIXME: POSIX also defines WIFCONTINUED, but that appears not to
403    exist on at least Linux... */
404 #endif  /* !LISP_FEATURE_WIN32 */
405
406 /* From SB-POSIX, stat-macros */
407 int s_isreg(mode_t mode)
408 {
409     return S_ISREG(mode);
410 }
411 int s_isdir(mode_t mode)
412 {
413     return S_ISDIR(mode);
414 }
415 int s_ischr(mode_t mode)
416 {
417     return S_ISCHR(mode);
418 }
419 int s_isblk(mode_t mode)
420 {
421     return S_ISBLK(mode);
422 }
423 int s_isfifo(mode_t mode)
424 {
425     return S_ISFIFO(mode);
426 }
427 #ifndef LISP_FEATURE_WIN32
428 int s_islnk(mode_t mode)
429 {
430 #ifdef S_ISLNK
431     return S_ISLNK(mode);
432 #else
433     return ((mode & S_IFMT) == S_IFLNK);
434 #endif
435 }
436 int s_issock(mode_t mode)
437 {
438 #ifdef S_ISSOCK
439     return S_ISSOCK(mode);
440 #else
441     return ((mode & S_IFMT) == S_IFSOCK);
442 #endif
443 }
444 #endif /* !LISP_FEATURE_WIN32 */