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