365d89569707a5150c4c71951630ed736dd495f2
[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 <sys/types.h>
27 #include <dirent.h>
28 #include <sys/stat.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <pwd.h>
33 #include <stdio.h>
34
35 #include "sbcl.h"
36 #include "runtime.h"
37 #include "util.h"
38
39 /* Although it might seem as though this should be in some standard
40    Unix header, according to Perry E. Metzger, in a message on
41    sbcl-devel dated 2004-03-29, this is the POSIXly-correct way of
42    using environ: by an explicit declaration.  -- CSR, 2004-03-30 */
43 extern char **environ;
44 \f
45 /*
46  * stuff needed by CL:DIRECTORY and other Lisp directory operations
47  */
48
49 /* Unix directory operations think of "." and ".." as filenames, but
50  * Lisp directory operations do not. */
51 int
52 is_lispy_filename(const char *filename)
53 {
54     return strcmp(filename, ".") && strcmp(filename, "..");
55 }
56
57 /* Return a zero-terminated array of strings holding the Lispy filenames
58  * (i.e. excluding the Unix magic "." and "..") in the named directory. */
59 char**
60 alloc_directory_lispy_filenames(const char *directory_name)
61 {
62     DIR *dir_ptr = opendir(directory_name);
63     char **result = 0;
64
65     if (dir_ptr) { /* if opendir success */
66
67         struct voidacc va;
68
69         if (0 == voidacc_ctor(&va)) { /* if voidacc_ctor success */
70             struct dirent *dirent_ptr;
71
72             while ( (dirent_ptr = readdir(dir_ptr)) ) { /* until end of data */
73                 char* original_name = dirent_ptr->d_name;
74                 if (is_lispy_filename(original_name)) {
75                     /* strdup(3) is in Linux and *BSD. If you port
76                      * somewhere else that doesn't have it, it's easy
77                      * to reimplement. */
78                     char* dup_name = strdup(original_name);
79                     if (!dup_name) { /* if strdup failure */
80                         goto dtors;
81                     }
82                     if (voidacc_acc(&va, dup_name)) { /* if acc failure */
83                         goto dtors;
84                     }
85                 }
86             }
87             result = (char**)voidacc_give_away_result(&va);
88         }
89
90     dtors:
91         voidacc_dtor(&va);
92         /* ignoring closedir(3) return code, since what could we do?
93          *
94          * "Never ask questions you don't want to know the answer to."
95          * -- William Irving Zumwalt (Rich Cook, _The Wizardry Quested_) */
96         closedir(dir_ptr);
97     }
98
99     return result;
100 }
101
102 /* Free a result returned by alloc_directory_lispy_filenames(). */
103 void
104 free_directory_lispy_filenames(char** directory_lispy_filenames)
105 {
106     char** p;
107
108     /* Free the strings. */
109     for (p = directory_lispy_filenames; *p; ++p) {
110         free(*p);
111     }
112
113     /* Free the table of strings. */
114     free(directory_lispy_filenames);
115 }
116 \f
117 /*
118  * readlink(2) stuff
119  */
120
121 /* a wrapped version of readlink(2):
122  *   -- If path isn't a symlink, or is a broken symlink, return 0.
123  *   -- If path is a symlink, return a newly allocated string holding
124  *      the thing it's linked to. */
125 char *
126 wrapped_readlink(char *path)
127 {
128     int bufsiz = strlen(path) + 16;
129     while (1) {
130         char *result = malloc(bufsiz);
131         int n_read = readlink(path, result, bufsiz);
132         if (n_read < 0) {
133             free(result);
134             return 0;
135         } else if (n_read < bufsiz) {
136             result[n_read] = 0;
137             return result;
138         } else {
139             free(result);
140             bufsiz *= 2;
141         }
142     }
143 }
144 \f
145 /*
146  * stat(2) stuff
147  */
148
149 /* As of 0.6.12, the FFI can't handle 64-bit values. For now, we use
150  * these munged-to-32-bits values for might-be-64-bit slots of
151  * stat_wrapper as a workaround, so that at least we can still work
152  * when values are small.
153  *
154  * FIXME: But of course we should fix the FFI so that we can use the
155  * actual 64-bit values instead.  In fact, we probably have by now
156  * (2003-10-03) on all working platforms except MIPS and HPPA; if some
157  * motivated spark would simply fix those, this hack could go away.
158  * -- CSR, 2003-10-03
159  *
160  * Some motivated spark fixed MIPS. -- ths, 2005-10-06 */
161
162 #ifdef LISP_FEATURE_MIPS
163 typedef unsigned long ffi_dev_t; /* Linux/MIPS struct stat doesn't use dev_t */
164 typedef off_t ffi_off_t;
165 #else
166 typedef u32 ffi_dev_t; /* since Linux dev_t can be 64 bits */
167 typedef u32 ffi_off_t; /* since OpenBSD 2.8 st_size is 64 bits */
168 #endif
169
170 /* a representation of stat(2) results which doesn't depend on CPU or OS */
171 struct stat_wrapper {
172     /* KLUDGE: The verbose wrapped_st_ prefixes are to protect us from
173      * the C preprocessor as wielded by the fiends of OpenBSD, who do
174      * things like
175      *    #define st_atime        st_atimespec.tv_sec
176      * I remember when I was young and innocent, I read about how the
177      * C preprocessor isn't to be used to globally munge random
178      * lowercase symbols like this, because things like this could
179      * happen, and I nodded sagely. But now I know better.:-| This is
180      * another entry for Dan Barlow's ongoing episodic rant about C
181      * header files, I guess.. -- WHN 2001-05-10 */
182     ffi_dev_t     wrapped_st_dev;         /* device */
183     ino_t         wrapped_st_ino;         /* inode */
184     mode_t        wrapped_st_mode;        /* protection */
185     nlink_t       wrapped_st_nlink;       /* number of hard links */
186     uid_t         wrapped_st_uid;         /* user ID of owner */
187     gid_t         wrapped_st_gid;         /* group ID of owner */
188     ffi_dev_t     wrapped_st_rdev;        /* device type (if inode device) */
189     ffi_off_t     wrapped_st_size;        /* total size, in bytes */
190     unsigned long wrapped_st_blksize;     /* blocksize for filesystem I/O */
191     unsigned long wrapped_st_blocks;      /* number of blocks allocated */
192     time_t        wrapped_st_atime;       /* time_t of last access */
193     time_t        wrapped_st_mtime;       /* time_t of last modification */
194     time_t        wrapped_st_ctime;       /* time_t of last change */
195 };
196
197 static void
198 copy_to_stat_wrapper(struct stat_wrapper *to, struct stat *from)
199 {
200 #define FROB(stem) to->wrapped_st_##stem = from->st_##stem
201     FROB(dev);
202     FROB(ino);
203     FROB(mode);
204     FROB(nlink);
205     FROB(uid);
206     FROB(gid);
207     FROB(rdev);
208     FROB(size);
209     FROB(blksize);
210     FROB(blocks);
211     FROB(atime);
212     FROB(mtime);
213     FROB(ctime);
214 #undef FROB
215 }
216
217 int
218 stat_wrapper(const char *file_name, struct stat_wrapper *buf)
219 {
220     struct stat real_buf;
221     int ret;
222     if ((ret = stat(file_name,&real_buf)) >= 0)
223         copy_to_stat_wrapper(buf, &real_buf);
224     return ret;
225 }
226
227 int
228 lstat_wrapper(const char *file_name, struct stat_wrapper *buf)
229 {
230     struct stat real_buf;
231     int ret;
232     if ((ret = lstat(file_name,&real_buf)) >= 0)
233         copy_to_stat_wrapper(buf, &real_buf);
234     return ret;
235 }
236
237 int
238 fstat_wrapper(int filedes, struct stat_wrapper *buf)
239 {
240     struct stat real_buf;
241     int ret;
242     if ((ret = fstat(filedes,&real_buf)) >= 0)
243         copy_to_stat_wrapper(buf, &real_buf);
244     return ret;
245 }
246 \f
247 /*
248  * getpwuid() stuff
249  */
250
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 \f
298 /*
299  * functions to get miscellaneous C-level variables
300  *
301  * (Doing this by calling functions lets us borrow the smarts of the C
302  * linker, so that things don't blow up when libc versions and thus
303  * variable locations change between compile time and run time.)
304  */
305
306 char **
307 wrapped_environ()
308 {
309     return environ;
310 }