0.pre7.90:
[sbcl.git] / src / code / unix.lisp
1 ;;;; This file contains Unix support that SBCL needs to implement
2 ;;;; itself. It's derived from Peter Van Eynde's unix-glibc2.lisp for
3 ;;;; CMU CL, which was derived from CMU CL unix.lisp 1.56. But those
4 ;;;; files aspired to be complete Unix interfaces exported to the end
5 ;;;; user, while this file aims to be as simple as possible and is not
6 ;;;; intended for the end user.
7 ;;;;
8 ;;;; FIXME: The old CMU CL unix.lisp code was implemented as hand
9 ;;;; transcriptions from Unix headers into Lisp. It appears that this was as
10 ;;;; unmaintainable in practice as you'd expect in theory, so I really really
11 ;;;; don't want to do that. It'd be good to implement the various system calls
12 ;;;; as C code implemented using the Unix header files, and have their
13 ;;;; interface back to SBCL code be characterized by things like "32-bit-wide
14 ;;;; int" which are already in the interface between the runtime
15 ;;;; executable and the SBCL lisp code.
16
17 ;;;; This software is part of the SBCL system. See the README file for
18 ;;;; more information.
19 ;;;;
20 ;;;; This software is derived from the CMU CL system, which was
21 ;;;; written at Carnegie Mellon University and released into the
22 ;;;; public domain. The software is in the public domain and is
23 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
24 ;;;; files for more information.
25
26 (in-package "SB!UNIX")
27
28 (/show0 "unix.lisp 21")
29
30 (defmacro def-enum (inc cur &rest names)
31   (flet ((defform (name)
32            (prog1 (when name `(defconstant ,name ,cur))
33              (setf cur (funcall inc cur 1)))))
34     `(progn ,@(mapcar #'defform names))))
35
36 ;;; Given a C-level zero-terminated array of C strings, return a
37 ;;; corresponding Lisp-level list of SIMPLE-STRINGs.
38 (defun c-strings->string-list (c-strings)
39   (declare (type (alien (* c-string)) c-strings))
40   (let ((reversed-result nil))
41     (dotimes (i most-positive-fixnum (error "argh! can't happen"))
42       (declare (type index i))
43       (let ((c-string (deref c-strings i)))
44         (if c-string
45             (push c-string reversed-result)
46             (return (nreverse reversed-result)))))))
47 \f
48 ;;;; Lisp types used by syscalls
49
50 (deftype unix-pathname () 'simple-string)
51 (deftype unix-fd () `(integer 0 ,most-positive-fixnum))
52
53 (deftype unix-file-mode () '(unsigned-byte 32))
54 (deftype unix-pid () '(unsigned-byte 32))
55 (deftype unix-uid () '(unsigned-byte 32))
56 (deftype unix-gid () '(unsigned-byte 32))
57 \f
58 ;;;; system calls
59
60 (/show0 "unix.lisp 74")
61
62 ;;; FIXME: The various FOO-SYSCALL-BAR macros, and perhaps some other
63 ;;; macros in this file, are only used in this file, and could be
64 ;;; implemented using SB!XC:DEFMACRO wrapped in EVAL-WHEN.
65
66 (defmacro syscall ((name &rest arg-types) success-form &rest args)
67   `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
68                                 ,@args)))
69      (if (minusp result)
70          (values nil (get-errno))
71          ,success-form)))
72
73 ;;; This is like SYSCALL, but if it fails, signal an error instead of
74 ;;; returning error codes. Should only be used for syscalls that will
75 ;;; never really get an error.
76 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
77   `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
78                                 ,@args)))
79      (if (minusp result)
80          (error "Syscall ~A failed: ~A" ,name (strerror))
81          ,success-form)))
82
83 (/show0 "unix.lisp 109")
84
85 (defmacro void-syscall ((name &rest arg-types) &rest args)
86   `(syscall (,name ,@arg-types) (values t 0) ,@args))
87
88 (defmacro int-syscall ((name &rest arg-types) &rest args)
89   `(syscall (,name ,@arg-types) (values result 0) ,@args))
90 \f
91 ;;;; hacking the Unix environment
92
93 (define-alien-routine ("getenv" posix-getenv) c-string
94   "Return the \"value\" part of the environment string \"name=value\" which
95    corresponds to NAME, or NIL if there is none."
96   (name c-string))
97 \f
98 ;;; from stdio.h
99
100 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
101 ;;; error code is returned if an error occurs.
102 (defun unix-rename (name1 name2)
103   (declare (type unix-pathname name1 name2))
104   (void-syscall ("rename" c-string c-string) name1 name2))
105 \f
106 ;;; from sys/types.h and gnu/types.h
107
108 (/show0 "unix.lisp 220")
109
110 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
111 ;;; like this unless we have extreme provocation. Reading directories
112 ;;; is not extreme enough, since it doesn't need to be blindingly
113 ;;; fast: we can just implement those functions in C as a wrapper
114 ;;; layer.
115 (define-alien-type fd-mask unsigned-long)
116
117 (eval-when (:compile-toplevel :load-toplevel :execute)
118   (defconstant fd-setsize 1024))
119
120 (define-alien-type nil
121   (struct fd-set
122           (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
123
124 (/show0 "unix.lisp 304")
125 \f
126 \f
127 ;;;; fcntl.h
128 ;;;;
129 ;;;; POSIX Standard: 6.5 File Control Operations        <fcntl.h>
130
131 ;;; Open the file whose pathname is specified by PATH for reading
132 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
133 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
134 ;;;
135 ;;; If the O_CREAT flag is specified, then the file is created with a
136 ;;; permission of argument MODE if the file doesn't exist. An integer
137 ;;; file descriptor is returned by UNIX-OPEN.
138 (defun unix-open (path flags mode)
139   (declare (type unix-pathname path)
140            (type fixnum flags)
141            (type unix-file-mode mode))
142   (int-syscall ("open" c-string int int) path flags mode))
143
144 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
145 ;;; associated with it.
146 (/show0 "unix.lisp 391")
147 (defun unix-close (fd)
148   (declare (type unix-fd fd))
149   (void-syscall ("close" int) fd))
150 \f
151 ;;;; timebits.h
152
153 ;; A time value that is accurate to the nearest
154 ;; microsecond but also has a range of years.
155 (define-alien-type nil
156   (struct timeval
157           (tv-sec time-t)               ; seconds
158           (tv-usec time-t)))            ; and microseconds
159 \f
160 ;;;; resourcebits.h
161
162 (defconstant rusage_self 0) ; the calling process
163 (defconstant rusage_children -1) ; terminated child processes
164 (defconstant rusage_both -2)
165
166 (define-alien-type nil
167   (struct rusage
168     (ru-utime (struct timeval))     ; user time used
169     (ru-stime (struct timeval))     ; system time used.
170     (ru-maxrss long)                ; maximum resident set size (in kilobytes)
171     (ru-ixrss long)                 ; integral shared memory size
172     (ru-idrss long)                 ; integral unshared data size
173     (ru-isrss long)                 ; integral unshared stack size
174     (ru-minflt long)                ; page reclaims
175     (ru-majflt long)                ; page faults
176     (ru-nswap long)                 ; swaps
177     (ru-inblock long)               ; block input operations
178     (ru-oublock long)               ; block output operations
179     (ru-msgsnd long)                ; messages sent
180     (ru-msgrcv long)                ; messages received
181     (ru-nsignals long)              ; signals received
182     (ru-nvcsw long)                 ; voluntary context switches
183     (ru-nivcsw long)))              ; involuntary context switches
184 \f
185 ;;;; unistd.h
186
187 ;;; Given a file path (a string) and one of four constant modes,
188 ;;; return T if the file is accessible with that mode and NIL if not.
189 ;;; When NIL, also return an errno value with NIL which tells why the
190 ;;; file was not accessible.
191 ;;; 
192 ;;; The access modes are:
193 ;;;   r_ok     Read permission.
194 ;;;   w_ok     Write permission.
195 ;;;   x_ok     Execute permission.
196 ;;;   f_ok     Presence of file.
197 (defun unix-access (path mode)
198   (declare (type unix-pathname path)
199            (type (mod 8) mode))
200   (void-syscall ("access" c-string int) path mode))
201
202 ;;; values for the second argument to UNIX-LSEEK
203 (defconstant l_set 0) ; to set the file pointer
204 (defconstant l_incr 1) ; to increment the file pointer
205 (defconstant l_xtnd 2) ; to extend the file size
206
207 ;;; Accept a file descriptor and move the file pointer ahead
208 ;;; a certain offset for that file. WHENCE can be any of the following:
209 ;;;  L_SET     Set the file pointer.
210 ;;;  L_INCR    Increment the file pointer.
211 ;;;  L_XTND    Extend the file size.
212 (defun unix-lseek (fd offset whence)
213   (declare (type unix-fd fd)
214            (type (unsigned-byte 32) offset)
215            (type (integer 0 2) whence))
216   #!-(and x86 bsd)
217   (int-syscall ("lseek" int off-t int) fd offset whence)
218   ;; Need a 64-bit return value type for this. TBD. For now,
219   ;; don't use this with any 2G+ partitions.
220   #!+(and x86 bsd)
221   (int-syscall ("lseek" int unsigned-long unsigned-long int)
222                fd offset 0 whence))
223
224 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
225 ;;; It attempts to read len bytes from the device associated with fd
226 ;;; and store them into the buffer. It returns the actual number of
227 ;;; bytes read.
228 (defun unix-read (fd buf len)
229   (declare (type unix-fd fd)
230            (type (unsigned-byte 32) len))
231
232   (int-syscall ("read" int (* char) int) fd buf len))
233
234 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
235 ;;; length to write. It attempts to write len bytes to the device
236 ;;; associated with fd from the the buffer starting at offset. It returns
237 ;;; the actual number of bytes written.
238 (defun unix-write (fd buf offset len)
239   (declare (type unix-fd fd)
240            (type (unsigned-byte 32) offset len))
241   (int-syscall ("write" int (* char) int)
242                fd
243                (with-alien ((ptr (* char) (etypecase buf
244                                             ((simple-array * (*))
245                                              (vector-sap buf))
246                                             (system-area-pointer
247                                              buf))))
248                  (addr (deref ptr offset)))
249                len))
250
251 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
252 ;;; output pipe. Return two values: if no error occurred the first
253 ;;; value is the pipe to be read from and the second is can be written
254 ;;; to. If an error occurred the first value is NIL and the second the
255 ;;; unix error code.
256 (defun unix-pipe ()
257   (with-alien ((fds (array int 2)))
258     (syscall ("pipe" (* int))
259              (values (deref fds 0) (deref fds 1))
260              (cast fds (* int)))))
261
262 (defun unix-mkdir (name mode)
263   (declare (type unix-pathname name)
264            (type unix-file-mode mode))
265   (void-syscall ("mkdir" c-string int) name mode))
266
267 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
268 ;;; style returned by getcwd() (no trailing slash character). 
269 (defun posix-getcwd ()
270   ;; This implementation relies on a BSD/Linux extension to getcwd()
271   ;; behavior, automatically allocating memory when a null buffer
272   ;; pointer is used. On a system which doesn't support that
273   ;; extension, it'll have to be rewritten somehow.
274   #!-(or linux openbsd freebsd) (,stub,)
275   (let* ((raw-char-ptr (alien-funcall (extern-alien "getcwd"
276                                                     (function (* char)
277                                                               (* char) size-t))
278                                       nil 0)))
279     (if (null-alien raw-char-ptr)
280         (simple-perror "getcwd")
281         (prog1
282             (cast raw-char-ptr c-string)
283           (free-alien raw-char-ptr)))))
284
285 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
286 ;;; by a slash character.
287 (defun posix-getcwd/ ()
288   (concatenate 'string (posix-getcwd) "/"))
289
290 ;;; Convert at the UNIX level from a possibly relative filename to
291 ;;; an absolute filename.
292 ;;;
293 ;;; FIXME: Do we still need this even as we switch to
294 ;;; *DEFAULT-PATHNAME-DEFAULTS*? I think maybe we do, since it seems
295 ;;; to be valid for the user to set *DEFAULT-PATHNAME-DEFAULTS* to
296 ;;; have a NIL directory component, and then this'd be the only way to
297 ;;; interpret a relative directory specification. But I don't find the
298 ;;; ANSI pathname documentation to be a model of clarity. Maybe
299 ;;; someone who understands it better can take a look at this.. -- WHN
300 (defun unix-maybe-prepend-current-directory (name)
301   (declare (simple-string name))
302   (if (and (> (length name) 0) (char= (schar name 0) #\/))
303       name
304       (concatenate 'simple-string (posix-getcwd/) name)))
305
306 ;;; Duplicate an existing file descriptor (given as the argument) and
307 ;;; return it. If FD is not a valid file descriptor, NIL and an error
308 ;;; number are returned.
309 (defun unix-dup (fd)
310   (declare (type unix-fd fd))
311   (int-syscall ("dup" int) fd))
312
313 ;;; Terminate the current process with an optional error code. If
314 ;;; successful, the call doesn't return. If unsuccessful, the call
315 ;;; returns NIL and an error number.
316 (defun unix-exit (&optional (code 0))
317   (declare (type (signed-byte 32) code))
318   (void-syscall ("exit" int) code))
319
320 ;;; Return the process id of the current process.
321 (define-alien-routine ("getpid" unix-getpid) int)
322
323 ;;; Return the real user-id associated with the current process.
324 (define-alien-routine ("getuid" unix-getuid) int)
325
326 ;;; Invoke readlink(2) on the file name specified by PATH. Return
327 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
328 ;;; failure.
329 (defun unix-readlink (path)
330   (declare (type unix-pathname path))
331   (with-alien ((ptr (* char)
332                     (alien-funcall (extern-alien
333                                     "wrapped_readlink"
334                                     (function (* char) c-string))
335                                    path)))
336     (if (null-alien ptr)
337         (values nil (get-errno))
338         (multiple-value-prog1
339             (values (with-alien ((c-string c-string ptr)) c-string)
340                     nil)
341           (free-alien ptr)))))
342
343 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
344 ;;; name and the file if this is the last link. 
345 (defun unix-unlink (name)
346   (declare (type unix-pathname name))
347   (void-syscall ("unlink" c-string) name))
348
349 ;;; Return the name of the host machine as a string.
350 (defun unix-gethostname ()
351   (with-alien ((buf (array char 256)))
352     (syscall ("gethostname" (* char) int)
353              (cast buf c-string)
354              (cast buf (* char)) 256)))
355
356 ;;; Write the core image of the file described by FD to disk.
357 (defun unix-fsync (fd)
358   (declare (type unix-fd fd))
359   (void-syscall ("fsync" int) fd))
360 \f
361 ;;;; sys/ioctl.h
362
363 ;;; UNIX-IOCTL performs a variety of operations on open i/o
364 ;;; descriptors. See the UNIX Programmer's Manual for more
365 ;;; information.
366 (defun unix-ioctl (fd cmd arg)
367   (declare (type unix-fd fd)
368            (type (unsigned-byte 32) cmd))
369   (void-syscall ("ioctl" int unsigned-int (* char)) fd cmd arg))
370 \f
371 ;;;; sys/resource.h
372
373 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
374 ;;;
375 ;;; Like getrusage(2), but return only the system and user time,
376 ;;; and return the seconds and microseconds as separate values.
377 #!-sb-fluid (declaim (inline unix-fast-getrusage))
378 (defun unix-fast-getrusage (who)
379   (declare (values (member t)
380                    (unsigned-byte 31) (integer 0 1000000)
381                    (unsigned-byte 31) (integer 0 1000000)))
382   (with-alien ((usage (struct rusage)))
383     (syscall* ("getrusage" int (* (struct rusage)))
384               (values t
385                       (slot (slot usage 'ru-utime) 'tv-sec)
386                       (slot (slot usage 'ru-utime) 'tv-usec)
387                       (slot (slot usage 'ru-stime) 'tv-sec)
388                       (slot (slot usage 'ru-stime) 'tv-usec))
389               who (addr usage))))
390
391 ;;; Return information about the resource usage of the process
392 ;;; specified by WHO. WHO can be either the current process
393 ;;; (rusage_self) or all of the terminated child processes
394 ;;; (rusage_children). NIL and an error number is returned if the call
395 ;;; fails.
396 (defun unix-getrusage (who)
397   (with-alien ((usage (struct rusage)))
398     (syscall ("getrusage" int (* (struct rusage)))
399               (values t
400                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
401                          (slot (slot usage 'ru-utime) 'tv-usec))
402                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
403                          (slot (slot usage 'ru-stime) 'tv-usec))
404                       (slot usage 'ru-maxrss)
405                       (slot usage 'ru-ixrss)
406                       (slot usage 'ru-idrss)
407                       (slot usage 'ru-isrss)
408                       (slot usage 'ru-minflt)
409                       (slot usage 'ru-majflt)
410                       (slot usage 'ru-nswap)
411                       (slot usage 'ru-inblock)
412                       (slot usage 'ru-oublock)
413                       (slot usage 'ru-msgsnd)
414                       (slot usage 'ru-msgrcv)
415                       (slot usage 'ru-nsignals)
416                       (slot usage 'ru-nvcsw)
417                       (slot usage 'ru-nivcsw))
418               who (addr usage))))
419 \f
420 ;;;; sys/select.h
421
422 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
423
424 ;;; Perform the UNIX select(2) system call.
425 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
426 (defun unix-fast-select (num-descriptors
427                          read-fds write-fds exception-fds
428                          timeout-secs &optional (timeout-usecs 0))
429   (declare (type (integer 0 #.fd-setsize) num-descriptors)
430            (type (or (alien (* (struct fd-set))) null)
431                  read-fds write-fds exception-fds)
432            (type (or null (unsigned-byte 31)) timeout-secs)
433            (type (unsigned-byte 31) timeout-usecs))
434   ;; FIXME: CMU CL had
435   ;;   (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
436   ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
437   (with-alien ((tv (struct timeval)))
438     (when timeout-secs
439       (setf (slot tv 'tv-sec) timeout-secs)
440       (setf (slot tv 'tv-usec) timeout-usecs))
441     (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
442                   (* (struct fd-set)) (* (struct timeval)))
443                  num-descriptors read-fds write-fds exception-fds
444                  (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
445
446 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
447 ;;; to happen on one of them or to time out.
448 (defmacro num-to-fd-set (fdset num)
449   `(if (fixnump ,num)
450        (progn
451          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
452          ,@(loop for index upfrom 1 below (/ fd-setsize 32)
453              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
454        (progn
455          ,@(loop for index upfrom 0 below (/ fd-setsize 32)
456              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
457                             (ldb (byte 32 ,(* index 32)) ,num))))))
458
459 (defmacro fd-set-to-num (nfds fdset)
460   `(if (<= ,nfds 32)
461        (deref (slot ,fdset 'fds-bits) 0)
462        (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
463               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
464                             ,(* index 32))))))
465
466 ;;; Examine the sets of descriptors passed as arguments to see whether
467 ;;; they are ready for reading and writing. See the UNIX Programmer's
468 ;;; Manual for more information.
469 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
470   (declare (type (integer 0 #.FD-SETSIZE) nfds)
471            (type unsigned-byte rdfds wrfds xpfds)
472            (type (or (unsigned-byte 31) null) to-secs)
473            (type (unsigned-byte 31) to-usecs)
474            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
475   (with-alien ((tv (struct timeval))
476                (rdf (struct fd-set))
477                (wrf (struct fd-set))
478                (xpf (struct fd-set)))
479     (when to-secs
480       (setf (slot tv 'tv-sec) to-secs)
481      (setf (slot tv 'tv-usec) to-usecs))
482     (num-to-fd-set rdf rdfds)
483     (num-to-fd-set wrf wrfds)
484     (num-to-fd-set xpf xpfds)
485     (macrolet ((frob (lispvar alienvar)
486                  `(if (zerop ,lispvar)
487                       (int-sap 0)
488                       (alien-sap (addr ,alienvar)))))
489       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
490                 (* (struct fd-set)) (* (struct timeval)))
491                (values result
492                        (fd-set-to-num nfds rdf)
493                        (fd-set-to-num nfds wrf)
494                        (fd-set-to-num nfds xpf))
495                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
496                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
497 \f
498 ;;;; sys/stat.h
499
500 ;;; This is a structure defined in src/runtime/wrap.c, to look
501 ;;; basically like "struct stat" according to stat(2). It may not
502 ;;; actually correspond to the real in-memory stat structure that the
503 ;;; syscall uses, and that's OK. Linux in particular is packed full of
504 ;;; stat macros, and trying to keep Lisp code in correspondence with
505 ;;; it is more pain than it's worth, so we just let our C runtime
506 ;;; synthesize a nice consistent structure for us.
507 ;;;
508 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
509 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
510 ;;; those. We don't actually access that field anywhere, though, so
511 ;;; until we can get 64 bit alien support it'll do. Also note that
512 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
513 ;;; quantity on Alpha. And FIXME: "No one would want a file length
514 ;;; longer than 32 bits anyway, right?":-|
515 (define-alien-type nil
516   (struct wrapped_stat
517     (st-dev unsigned-long)              ; would be dev-t in a real stat
518     (st-ino ino-t)
519     (st-mode mode-t)
520     (st-nlink  nlink-t)
521     (st-uid  uid-t)
522     (st-gid  gid-t)
523     (st-rdev unsigned-long)             ; would be dev-t in a real stat
524     (st-size unsigned-long)             ; would be off-t in a real stat
525     (st-blksize unsigned-long)
526     (st-blocks unsigned-long)
527     (st-atime time-t)
528     (st-mtime time-t)
529     (st-ctime time-t)))
530
531 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
532 ;;; family of Unix system calls
533 ;;;
534 ;;; FIXME: I think this should probably not be INLINE. However, when
535 ;;; this was not inline, it seemed to cause memory corruption
536 ;;; problems. My first guess is that it's a bug in the FFI code, where
537 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
538 ;;; around a call to a function returning >10 values. But I didn't try
539 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
540 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
541 ;;; output in the not-inlined case and see whether there's a problem,
542 ;;; and maybe even find a fix..
543 (declaim (inline %extract-stat-results))
544 (defun %extract-stat-results (wrapped-stat)
545   (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
546   (values t
547           (slot wrapped-stat 'st-dev)
548           (slot wrapped-stat 'st-ino)
549           (slot wrapped-stat 'st-mode)
550           (slot wrapped-stat 'st-nlink)
551           (slot wrapped-stat 'st-uid)
552           (slot wrapped-stat 'st-gid)
553           (slot wrapped-stat 'st-rdev)
554           (slot wrapped-stat 'st-size)
555           (slot wrapped-stat 'st-atime)
556           (slot wrapped-stat 'st-mtime)
557           (slot wrapped-stat 'st-ctime)
558           (slot wrapped-stat 'st-blksize)
559           (slot wrapped-stat 'st-blocks)))
560
561 ;;; Unix system calls in the stat(2) family are handled by calls to
562 ;;; C-level wrapper functions which copy all the raw "struct stat"
563 ;;; slots into the system-independent wrapped_stat format.
564 ;;;    stat(2) <->  stat_wrapper()
565 ;;;   fstat(2) <-> fstat_wrapper()
566 ;;;   lstat(2) <-> lstat_wrapper()
567 (defun unix-stat (name)
568   (declare (type unix-pathname name))
569   (with-alien ((buf (struct wrapped_stat)))
570     (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
571              (%extract-stat-results (addr buf))
572              name (addr buf))))
573 (defun unix-lstat (name)
574   (declare (type unix-pathname name))
575   (with-alien ((buf (struct wrapped_stat)))
576     (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
577              (%extract-stat-results (addr buf))
578              name (addr buf))))
579 (defun unix-fstat (fd)
580   (declare (type unix-fd fd))
581   (with-alien ((buf (struct wrapped_stat)))
582     (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
583              (%extract-stat-results (addr buf))
584              fd (addr buf))))
585 \f
586 ;;;; time.h
587
588 ;; the POSIX.4 structure for a time value. This is like a "struct
589 ;; timeval" but has nanoseconds instead of microseconds.
590 (define-alien-type nil
591     (struct timespec
592             (tv-sec long)   ; seconds
593             (tv-nsec long))) ; nanoseconds
594
595 ;; used by other time functions
596 (define-alien-type nil
597     (struct tm
598             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
599             (tm-min int)   ; Minutes.   [0-59]
600             (tm-hour int)  ; Hours.     [0-23]
601             (tm-mday int)  ; Day.       [1-31]
602             (tm-mon int)   ; Month.     [0-11]
603             (tm-year int)  ; Year - 1900.
604             (tm-wday int)  ; Day of week. [0-6]
605             (tm-yday int)  ; Days in year. [0-365]
606             (tm-isdst int) ; DST.       [-1/0/1]
607             (tm-gmtoff long) ;  Seconds east of UTC.
608             (tm-zone c-string))) ; Timezone abbreviation.
609
610 (define-alien-routine get-timezone sb!c-call:void
611   (when sb!c-call:long :in)
612   (minutes-west sb!c-call:int :out)
613   (daylight-savings-p sb!alien:boolean :out))
614
615 (defun unix-get-minutes-west (secs)
616   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
617     (declare (ignore ignore) (ignore dst))
618     (values minutes)))
619
620 (defun unix-get-timezone (secs)
621   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
622     (declare (ignore ignore) (ignore minutes))
623     (values (deref unix-tzname (if dst 1 0)))))
624
625 \f
626 ;;;; sys/time.h
627
628 ;;; Structure crudely representing a timezone. KLUDGE: This is
629 ;;; obsolete and should never be used.
630 (define-alien-type nil
631   (struct timezone
632     (tz-minuteswest int)                ; minutes west of Greenwich
633     (tz-dsttime int)))                  ; type of dst correction
634
635 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
636 ;;; and microseconds of the current time of day, the timezone (in
637 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
638 ;;; doesn't work, it returns NIL and the errno.
639 #!-sb-fluid (declaim (inline unix-gettimeofday))
640 (defun unix-gettimeofday ()
641   (with-alien ((tv (struct timeval))
642                (tz (struct timezone)))
643     (syscall* ("gettimeofday" (* (struct timeval))
644                               (* (struct timezone)))
645               (values T
646                       (slot tv 'tv-sec)
647                       (slot tv 'tv-usec)
648                       (slot tz 'tz-minuteswest)
649                       (slot tz 'tz-dsttime))
650               (addr tv)
651               (addr tz))))
652 \f
653
654 (defconstant ENOENT 2) ; Unix error code, "No such file or directory"
655 (defconstant EINTR 4) ; Unix error code, "Interrupted system call"
656 (defconstant EIO 5) ; Unix error code, "I/O error"
657 (defconstant EEXIST 17) ; Unix error code, "File exists"
658 (defconstant ESPIPE 29) ; Unix error code, "Illegal seek"
659 (defconstant EWOULDBLOCK 11) ; Unix error code, "Operation would block"
660 ;;; FIXME: Many Unix error code definitions were deleted from the old
661 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
662 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
663 ;;; unused symbols in package exports, but if I don't, there are
664 ;;; enough of them all in one place here that they should probably be
665 ;;; removed by hand.
666 \f
667 \f
668 ;;;; support routines for dealing with Unix pathnames
669
670 (defun unix-file-kind (name &optional check-for-links)
671   #!+sb-doc
672   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
673   (declare (simple-string name))
674   (multiple-value-bind (res dev ino mode)
675       (if check-for-links (unix-lstat name) (unix-stat name))
676     (declare (type (or fixnum null) mode)
677              (ignore dev ino))
678     (when res
679       (let ((kind (logand mode s-ifmt)))
680         (cond ((eql kind s-ifdir) :directory)
681               ((eql kind s-ifreg) :file)
682               ((eql kind s-iflnk) :link)
683               (t :special))))))
684
685 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
686 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
687 (defun relative-unix-pathname? (pathname)
688   (declare (type simple-string pathname))
689   (or (zerop (length pathname))
690       (char/= (schar pathname 0) #\/)))
691
692 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
693 ;;; already be a complete absolute Unix pathname, since at least in
694 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
695 ;;; paths have been converted to absolute paths, so we don't need to
696 ;;; try to handle any more generality than that.
697 (defun unix-resolve-links (pathname)
698   (declare (type simple-string pathname))
699   (aver (not (relative-unix-pathname? pathname)))
700   (/noshow "entering UNIX-RESOLVE-LINKS")
701   (loop with previous-pathnames = nil do
702         (/noshow pathname previous-pathnames)
703         (let ((link (unix-readlink pathname)))
704           (/noshow link)
705           ;; Unlike the old CMU CL code, we handle a broken symlink by
706           ;; returning the link itself. That way, CL:TRUENAME on a
707           ;; broken link returns the link itself, so that CL:DIRECTORY
708           ;; can return broken links, so that even without
709           ;; Unix-specific extensions to do interesting things with
710           ;; them, at least Lisp programs can see them and, if
711           ;; necessary, delete them. (This is handy e.g. when your
712           ;; managed-by-Lisp directories are visited by Emacs, which
713           ;; creates broken links as notes to itself.)
714           (if (null link)
715               (return pathname)
716               (let ((new-pathname 
717                      (unix-simplify-pathname
718                       (if (relative-unix-pathname? link)
719                           (let* ((dir-len (1+ (position #\/
720                                                         pathname
721                                                         :from-end t)))
722                                  (dir (subseq pathname 0 dir-len)))
723                             (/noshow dir)
724                             (concatenate 'string dir link))
725                           link))))
726                 (if (unix-file-kind new-pathname)
727                     (setf pathname new-pathname)
728                     (return pathname)))))
729         ;; To generalize the principle that even if portable Lisp code
730         ;; can't do anything interesting with a broken symlink, at
731         ;; least it should be able to see and delete it, when we
732         ;; detect a cyclic link, we return the link itself. (So even
733         ;; though portable Lisp code can't do anything interesting
734         ;; with a cyclic link, at least it can see it and delete it.)
735         (if (member pathname previous-pathnames :test #'string=)
736             (return pathname)
737             (push pathname previous-pathnames))))
738
739 (defun unix-simplify-pathname (src)
740   (declare (type simple-string src))
741   (let* ((src-len (length src))
742          (dst (make-string src-len))
743          (dst-len 0)
744          (dots 0)
745          (last-slash nil))
746     (macrolet ((deposit (char)
747                  `(progn
748                     (setf (schar dst dst-len) ,char)
749                     (incf dst-len))))
750       (dotimes (src-index src-len)
751         (let ((char (schar src src-index)))
752           (cond ((char= char #\.)
753                  (when dots
754                    (incf dots))
755                  (deposit char))
756                 ((char= char #\/)
757                  (case dots
758                    (0
759                     ;; either ``/...' or ``...//...'
760                     (unless last-slash
761                       (setf last-slash dst-len)
762                       (deposit char)))
763                    (1
764                     ;; either ``./...'' or ``..././...''
765                     (decf dst-len))
766                    (2
767                     ;; We've found ..
768                     (cond
769                      ((and last-slash (not (zerop last-slash)))
770                       ;; There is something before this ..
771                       (let ((prev-prev-slash
772                              (position #\/ dst :end last-slash :from-end t)))
773                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
774                                        last-slash)
775                                     (char= (schar dst (- last-slash 2)) #\.)
776                                     (char= (schar dst (1- last-slash)) #\.))
777                                ;; The something before this .. is another ..
778                                (deposit char)
779                                (setf last-slash dst-len))
780                               (t
781                                ;; The something is some directory or other.
782                                (setf dst-len
783                                      (if prev-prev-slash
784                                          (1+ prev-prev-slash)
785                                          0))
786                                (setf last-slash prev-prev-slash)))))
787                      (t
788                       ;; There is nothing before this .., so we need to keep it
789                       (setf last-slash dst-len)
790                       (deposit char))))
791                    (t
792                     ;; something other than a dot between slashes
793                     (setf last-slash dst-len)
794                     (deposit char)))
795                  (setf dots 0))
796                 (t
797                  (setf dots nil)
798                  (setf (schar dst dst-len) char)
799                  (incf dst-len))))))
800     (when (and last-slash (not (zerop last-slash)))
801       (case dots
802         (1
803          ;; We've got  ``foobar/.''
804          (decf dst-len))
805         (2
806          ;; We've got ``foobar/..''
807          (unless (and (>= last-slash 2)
808                       (char= (schar dst (1- last-slash)) #\.)
809                       (char= (schar dst (- last-slash 2)) #\.)
810                       (or (= last-slash 2)
811                           (char= (schar dst (- last-slash 3)) #\/)))
812            (let ((prev-prev-slash
813                   (position #\/ dst :end last-slash :from-end t)))
814              (if prev-prev-slash
815                  (setf dst-len (1+ prev-prev-slash))
816                  (return-from unix-simplify-pathname "./")))))))
817     (cond ((zerop dst-len)
818            "./")
819           ((= dst-len src-len)
820            dst)
821           (t
822            (subseq dst 0 dst-len)))))
823 \f
824 ;;;; stuff not yet found in the header files
825 ;;;;
826 ;;;; Abandon all hope who enters here...
827
828 ;;; not checked for linux...
829 (defmacro fd-set (offset fd-set)
830   (let ((word (gensym))
831         (bit (gensym)))
832     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
833        (setf (deref (slot ,fd-set 'fds-bits) ,word)
834              (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
835                      (deref (slot ,fd-set 'fds-bits) ,word))))))
836
837 ;;; not checked for linux...
838 (defmacro fd-clr (offset fd-set)
839   (let ((word (gensym))
840         (bit (gensym)))
841     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
842        (setf (deref (slot ,fd-set 'fds-bits) ,word)
843              (logand (deref (slot ,fd-set 'fds-bits) ,word)
844                      (sb!kernel:32bit-logical-not
845                       (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
846
847 ;;; not checked for linux...
848 (defmacro fd-isset (offset fd-set)
849   (let ((word (gensym))
850         (bit (gensym)))
851     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
852        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
853
854 ;;; not checked for linux...
855 (defmacro fd-zero (fd-set)
856   `(progn
857      ,@(loop for index upfrom 0 below (/ fd-setsize 32)
858          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))
859
860