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