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