0.6.12.19:
[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 (def-alien-routine ("getenv" posix-getenv) c-string
94   "Return the environment string \"name=value\" which corresponds to NAME, or
95    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 (def-alien-type fd-mask unsigned-long)
116
117 (eval-when (:compile-toplevel :load-toplevel :execute)
118   (defconstant fd-setsize 1024))
119
120 (def-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 (def-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 (def-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 ;;; UNIX-CHDIR accepts a directory name and makes that the
263 ;;; current working directory.
264 (defun unix-chdir (path)
265   (declare (type unix-pathname path))
266   (void-syscall ("chdir" c-string) path))
267
268 (defun unix-mkdir (name mode)
269   (declare (type unix-pathname name)
270            (type unix-file-mode mode))
271   (void-syscall ("mkdir" c-string int) name mode))
272
273 ;;; Return the current directory as a SIMPLE-STRING.
274 (defun unix-current-directory ()
275   ;; FIXME: Gcc justifiably complains that getwd is dangerous and should
276   ;; not be used; especially with a hardwired 1024 buffer size, yecch.
277   ;; This should be rewritten to use getcwd(3), perhaps by writing
278   ;; a C service routine to do the actual call to getcwd(3) and check
279   ;; of return values.
280   (with-alien ((buf (array char 1024)))
281     (values (not (zerop (alien-funcall (extern-alien "getwd"
282                                                      (function int (* char)))
283                                        (cast buf (* char)))))
284             (cast buf c-string))))
285
286 ;;; Duplicate an existing file descriptor (given as the argument) and
287 ;;; return it. If FD is not a valid file descriptor, NIL and an error
288 ;;; number are returned.
289 (defun unix-dup (fd)
290   (declare (type unix-fd fd))
291   (int-syscall ("dup" int) fd))
292
293 ;;; Terminate the current process with an optional error code. If
294 ;;; successful, the call doesn't return. If unsuccessful, the call
295 ;;; returns NIL and an error number.
296 (defun unix-exit (&optional (code 0))
297   (declare (type (signed-byte 32) code))
298   (void-syscall ("exit" int) code))
299
300 ;;; Return the process id of the current process.
301 (def-alien-routine ("getpid" unix-getpid) int)
302
303 ;;; Return the real user-id associated with the current process.
304 (def-alien-routine ("getuid" unix-getuid) int)
305
306 ;;; Invoke readlink(2) on the file name specified by the simple string
307 ;;; PATH. Return up to two values: the contents of the symbolic link
308 ;;; if the call is successful, or NIL and the Unix error number.
309 (defun unix-readlink (path)
310   (declare (type unix-pathname path))
311   (with-alien ((buf (array char 1024)))
312     (syscall ("readlink" c-string (* char) int)
313              (let ((string (make-string result)))
314                (sb!kernel:copy-from-system-area
315                 (alien-sap buf) 0
316                 string (* sb!vm:vector-data-offset sb!vm:word-bits)
317                 (* result sb!vm:byte-bits))
318                string)
319              path (cast buf (* char)) 1024)))
320
321 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
322 ;;; name and the file if this is the last link. 
323 (defun unix-unlink (name)
324   (declare (type unix-pathname name))
325   (void-syscall ("unlink" c-string) name))
326
327 ;;; Set the tty-process-group for the unix file-descriptor FD to PGRP.
328 ;;; If not supplied, FD defaults to "/dev/tty".
329 (defun %set-tty-process-group (pgrp &optional fd)
330   (let ((old-sigs (unix-sigblock (sigmask :sigttou
331                                           :sigttin
332                                           :sigtstp
333                                           :sigchld))))
334     (declare (type (unsigned-byte 32) old-sigs))
335     (unwind-protect
336         (if fd
337             (tcsetpgrp fd pgrp)
338             (multiple-value-bind (tty-fd errno) (unix-open "/dev/tty" o_rdwr 0)
339               (cond (tty-fd
340                      (multiple-value-prog1
341                          (tcsetpgrp tty-fd pgrp)
342                        (unix-close tty-fd)))
343                     (t
344                      (values nil errno)))))
345       (unix-sigsetmask old-sigs))))
346
347 ;;; Return the name of the host machine as a string.
348 (defun unix-gethostname ()
349   (with-alien ((buf (array char 256)))
350     (syscall ("gethostname" (* char) int)
351              (cast buf c-string)
352              (cast buf (* char)) 256)))
353
354 ;;; Write the core image of the file described by FD to disk.
355 (defun unix-fsync (fd)
356   (declare (type unix-fd fd))
357   (void-syscall ("fsync" int) fd))
358 \f
359 ;;;; sys/ioctl.h
360
361 ;;; UNIX-IOCTL performs a variety of operations on open i/o
362 ;;; descriptors. See the UNIX Programmer's Manual for more
363 ;;; information.
364 (defun unix-ioctl (fd cmd arg)
365   (declare (type unix-fd fd)
366            (type (unsigned-byte 32) cmd))
367   (void-syscall ("ioctl" int unsigned-int (* char)) fd cmd arg))
368 \f
369 ;;;; sys/resource.h
370
371 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
372 ;;;
373 ;;; Like getrusage(2), but return only the system and user time,
374 ;;; and return the seconds and microseconds as separate values.
375 #!-sb-fluid (declaim (inline unix-fast-getrusage))
376 (defun unix-fast-getrusage (who)
377   (declare (values (member t)
378                    (unsigned-byte 31) (mod 1000000)
379                    (unsigned-byte 31) (mod 1000000)))
380   (with-alien ((usage (struct rusage)))
381     (syscall* ("getrusage" int (* (struct rusage)))
382               (values t
383                       (slot (slot usage 'ru-utime) 'tv-sec)
384                       (slot (slot usage 'ru-utime) 'tv-usec)
385                       (slot (slot usage 'ru-stime) 'tv-sec)
386                       (slot (slot usage 'ru-stime) 'tv-usec))
387               who (addr usage))))
388
389 ;;; Return information about the resource usage of the process
390 ;;; specified by WHO. WHO can be either the current process
391 ;;; (rusage_self) or all of the terminated child processes
392 ;;; (rusage_children). NIL and an error number is returned if the call
393 ;;; fails.
394 (defun unix-getrusage (who)
395   (with-alien ((usage (struct rusage)))
396     (syscall ("getrusage" int (* (struct rusage)))
397               (values t
398                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
399                          (slot (slot usage 'ru-utime) 'tv-usec))
400                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
401                          (slot (slot usage 'ru-stime) 'tv-usec))
402                       (slot usage 'ru-maxrss)
403                       (slot usage 'ru-ixrss)
404                       (slot usage 'ru-idrss)
405                       (slot usage 'ru-isrss)
406                       (slot usage 'ru-minflt)
407                       (slot usage 'ru-majflt)
408                       (slot usage 'ru-nswap)
409                       (slot usage 'ru-inblock)
410                       (slot usage 'ru-oublock)
411                       (slot usage 'ru-msgsnd)
412                       (slot usage 'ru-msgrcv)
413                       (slot usage 'ru-nsignals)
414                       (slot usage 'ru-nvcsw)
415                       (slot usage 'ru-nivcsw))
416               who (addr usage))))
417 \f
418 ;;;; sys/select.h
419
420 (defmacro unix-fast-select (num-descriptors
421                             read-fds write-fds exception-fds
422                             timeout-secs &optional (timeout-usecs 0))
423   #!+sb-doc
424   "Perform the UNIX select(2) system call."
425   (declare (type (integer 0 #.FD-SETSIZE) num-descriptors)
426            (type (or (alien (* (struct fd-set))) null)
427                  read-fds write-fds exception-fds)
428            (type (or null (unsigned-byte 31)) timeout-secs)
429            (type (unsigned-byte 31) timeout-usecs) )
430   ;; FIXME: CMU CL had
431   ;;   (optimize (speed 3) (safety 0) (inhibit-warnings 3))
432   ;; in the declarations above. If they're important, they should
433   ;; be in a declaration inside the LET expansion, not in the
434   ;; macro compile-time code.
435   `(let ((timeout-secs ,timeout-secs))
436      (with-alien ((tv (struct timeval)))
437        (when timeout-secs
438          (setf (slot tv 'tv-sec) timeout-secs)
439          (setf (slot tv 'tv-usec) ,timeout-usecs))
440        (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
441                      (* (struct fd-set)) (* (struct timeval)))
442                     ,num-descriptors ,read-fds ,write-fds ,exception-fds
443                     (if timeout-secs (alien-sap (addr tv)) (int-sap 0))))))
444
445 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
446 ;;; to happen on one of them or to time out.
447 (defmacro num-to-fd-set (fdset num)
448   `(if (fixnump ,num)
449        (progn
450          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
451          ,@(loop for index upfrom 1 below (/ fd-setsize 32)
452              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
453        (progn
454          ,@(loop for index upfrom 0 below (/ fd-setsize 32)
455              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
456                             (ldb (byte 32 ,(* index 32)) ,num))))))
457
458 (defmacro fd-set-to-num (nfds fdset)
459   `(if (<= ,nfds 32)
460        (deref (slot ,fdset 'fds-bits) 0)
461        (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
462               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
463                             ,(* index 32))))))
464
465 ;;; Examine the sets of descriptors passed as arguments to see whether
466 ;;; they are ready for reading and writing. See the UNIX Programmer's
467 ;;; Manual for more information.
468 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
469   (declare (type (integer 0 #.FD-SETSIZE) nfds)
470            (type unsigned-byte rdfds wrfds xpfds)
471            (type (or (unsigned-byte 31) null) to-secs)
472            (type (unsigned-byte 31) to-usecs)
473            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
474   (with-alien ((tv (struct timeval))
475                (rdf (struct fd-set))
476                (wrf (struct fd-set))
477                (xpf (struct fd-set)))
478     (when to-secs
479       (setf (slot tv 'tv-sec) to-secs)
480      (setf (slot tv 'tv-usec) to-usecs))
481     (num-to-fd-set rdf rdfds)
482     (num-to-fd-set wrf wrfds)
483     (num-to-fd-set xpf xpfds)
484     (macrolet ((frob (lispvar alienvar)
485                  `(if (zerop ,lispvar)
486                       (int-sap 0)
487                       (alien-sap (addr ,alienvar)))))
488       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
489                 (* (struct fd-set)) (* (struct timeval)))
490                (values result
491                        (fd-set-to-num nfds rdf)
492                        (fd-set-to-num nfds wrf)
493                        (fd-set-to-num nfds xpf))
494                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
495                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
496 \f
497 ;;;; sys/stat.h
498
499 ;;; This is a structure defined in src/runtime/wrap.c, to look
500 ;;; basically like "struct stat" according to stat(2). It may not
501 ;;; actually correspond to the real in-memory stat structure that the
502 ;;; syscall uses, and that's OK. Linux in particular is packed full of
503 ;;; stat macros, and trying to keep Lisp code in correspondence with
504 ;;; it is more pain than it's worth, so we just let our C runtime
505 ;;; synthesize a nice consistent structure for us.
506 ;;;
507 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
508 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
509 ;;; those. We don't actually access that field anywhere, though, so
510 ;;; until we can get 64 bit alien support it'll do. Also note that
511 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
512 ;;; quantity on Alpha. And FIXME: "No one would want a file length
513 ;;; longer than 32 bits anyway, right?":-|
514 (def-alien-type nil
515   (struct wrapped_stat
516     (st-dev unsigned-long)              ; would be dev-t in a real stat
517     (st-ino ino-t)
518     (st-mode mode-t)
519     (st-nlink  nlink-t)
520     (st-uid  uid-t)
521     (st-gid  gid-t)
522     (st-rdev unsigned-long)             ; would be dev-t in a real stat
523     (st-size unsigned-long)             ; would be off-t in a real stat
524     (st-blksize unsigned-long)
525     (st-blocks unsigned-long)
526     (st-atime time-t)
527     (st-mtime time-t)
528     (st-ctime time-t)))
529
530 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
531 ;;; family of Unix system calls
532 ;;;
533 ;;; FIXME: I think this should probably not be INLINE. However, when
534 ;;; this was not inline, it seemed to cause memory corruption
535 ;;; problems. My first guess is that it's a bug in the FFI code, where
536 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
537 ;;; around a call to a function returning >10 values. But I didn't try
538 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
539 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
540 ;;; output in the not-inlined case and see whether there's a problem,
541 ;;; and maybe even find a fix..
542 (declaim (inline %extract-stat-results))
543 (defun %extract-stat-results (wrapped-stat)
544   (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
545   (values t
546           (slot wrapped-stat 'st-dev)
547           (slot wrapped-stat 'st-ino)
548           (slot wrapped-stat 'st-mode)
549           (slot wrapped-stat 'st-nlink)
550           (slot wrapped-stat 'st-uid)
551           (slot wrapped-stat 'st-gid)
552           (slot wrapped-stat 'st-rdev)
553           (slot wrapped-stat 'st-size)
554           (slot wrapped-stat 'st-atime)
555           (slot wrapped-stat 'st-mtime)
556           (slot wrapped-stat 'st-ctime)
557           (slot wrapped-stat 'st-blksize)
558           (slot wrapped-stat 'st-blocks)))
559
560 ;;; Unix system calls in the stat(2) family are handled by calls to
561 ;;; C-level wrapper functions which copy all the raw "struct stat"
562 ;;; slots into the system-independent wrapped_stat format.
563 ;;;    stat(2) <->  stat_wrapper()
564 ;;;   fstat(2) <-> fstat_wrapper()
565 ;;;   lstat(2) <-> lstat_wrapper()
566 (defun unix-stat (name)
567   (declare (type unix-pathname name))
568   (with-alien ((buf (struct wrapped_stat)))
569     (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
570              (%extract-stat-results (addr buf))
571              name (addr buf))))
572 (defun unix-lstat (name)
573   (declare (type unix-pathname name))
574   (with-alien ((buf (struct wrapped_stat)))
575     (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
576              (%extract-stat-results (addr buf))
577              name (addr buf))))
578 (defun unix-fstat (fd)
579   (declare (type unix-fd fd))
580   (with-alien ((buf (struct wrapped_stat)))
581     (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
582              (%extract-stat-results (addr buf))
583              fd (addr buf))))
584 \f
585 ;;;; time.h
586
587 ;; the POSIX.4 structure for a time value. This is like a "struct
588 ;; timeval" but has nanoseconds instead of microseconds.
589 (def-alien-type nil
590     (struct timespec
591             (tv-sec long)   ; seconds
592             (tv-nsec long))) ; nanoseconds
593
594 ;; used by other time functions
595 (def-alien-type nil
596     (struct tm
597             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
598             (tm-min int)   ; Minutes.   [0-59]
599             (tm-hour int)  ; Hours.     [0-23]
600             (tm-mday int)  ; Day.       [1-31]
601             (tm-mon int)   ; Month.     [0-11]
602             (tm-year int)  ; Year - 1900.
603             (tm-wday int)  ; Day of week. [0-6]
604             (tm-yday int)  ; Days in year. [0-365]
605             (tm-isdst int) ; DST.       [-1/0/1]
606             (tm-gmtoff long) ;  Seconds east of UTC.
607             (tm-zone c-string))) ; Timezone abbreviation.
608
609 (def-alien-routine get-timezone sb!c-call:void
610   (when sb!c-call:long :in)
611   (minutes-west sb!c-call:int :out)
612   (daylight-savings-p sb!alien:boolean :out))
613
614 (defun unix-get-minutes-west (secs)
615   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
616     (declare (ignore ignore) (ignore dst))
617     (values minutes)))
618
619 (defun unix-get-timezone (secs)
620   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
621     (declare (ignore ignore) (ignore minutes))
622     (values (deref unix-tzname (if dst 1 0)))))
623
624 \f
625 ;;;; sys/time.h
626
627 ;;; Structure crudely representing a timezone. KLUDGE: This is
628 ;;; obsolete and should never be used.
629 (def-alien-type nil
630   (struct timezone
631     (tz-minuteswest int)                ; minutes west of Greenwich
632     (tz-dsttime int)))                  ; type of dst correction
633
634 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
635 ;;; and microseconds of the current time of day, the timezone (in
636 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
637 ;;; doesn't work, it returns NIL and the errno.
638 #!-sb-fluid (declaim (inline unix-gettimeofday))
639 (defun unix-gettimeofday ()
640   (with-alien ((tv (struct timeval))
641                (tz (struct timezone)))
642     (syscall* ("gettimeofday" (* (struct timeval))
643                               (* (struct timezone)))
644               (values T
645                       (slot tv 'tv-sec)
646                       (slot tv 'tv-usec)
647                       (slot tz 'tz-minuteswest)
648                       (slot tz 'tz-dsttime))
649               (addr tv)
650               (addr tz))))
651 \f
652
653 (defconstant ENOENT 2) ; Unix error code, "No such file or directory"
654 (defconstant EINTR 4) ; Unix error code, "Interrupted system call"
655 (defconstant EIO 5) ; Unix error code, "I/O error"
656 (defconstant EEXIST 17) ; Unix error code, "File exists"
657 (defconstant ESPIPE 29) ; Unix error code, "Illegal seek"
658 (defconstant EWOULDBLOCK 11) ; Unix error code, "Operation would block"
659 ;;; FIXME: Many Unix error code definitions were deleted from the old
660 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
661 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
662 ;;; unused symbols in package exports, but if I don't, there are
663 ;;; enough of them all in one place here that they should probably be
664 ;;; removed by hand.
665 \f
666 \f
667 ;;;; support routines for dealing with Unix pathnames
668
669 (defun unix-file-kind (name &optional check-for-links)
670   #!+sb-doc
671   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
672   (declare (simple-string name))
673   (multiple-value-bind (res dev ino mode)
674       (if check-for-links (unix-lstat name) (unix-stat name))
675     (declare (type (or fixnum null) mode)
676              (ignore dev ino))
677     (when res
678       (let ((kind (logand mode s-ifmt)))
679         (cond ((eql kind s-ifdir) :directory)
680               ((eql kind s-ifreg) :file)
681               ((eql kind s-iflnk) :link)
682               (t :special))))))
683
684 (defun unix-maybe-prepend-current-directory (name)
685   (declare (simple-string name))
686   (if (and (> (length name) 0) (char= (schar name 0) #\/))
687       name
688       (multiple-value-bind (win dir) (unix-current-directory)
689         (if win
690             (concatenate 'simple-string dir "/" name)
691             name))))
692
693 ;;; Return the pathname with all symbolic links resolved.
694 ;;;
695 ;;; FIXME: Could we just use Unix readlink(2) instead?
696 (defun unix-resolve-links (pathname)
697   (declare (simple-string pathname))
698   (let ((len (length pathname))
699         (pending pathname))
700     (declare (fixnum len) (simple-string pending))
701     (if (zerop len)
702         pathname
703         (let ((result (make-string 1024 :initial-element (code-char 0)))
704               (fill-ptr 0)
705               (name-start 0))
706           (loop
707             (let* ((name-end (or (position #\/ pending :start name-start) len))
708                    (new-fill-ptr (+ fill-ptr (- name-end name-start))))
709               (replace result pending
710                        :start1 fill-ptr
711                        :end1 new-fill-ptr
712                        :start2 name-start
713                        :end2 name-end)
714               (let ((kind (unix-file-kind (if (zerop name-end) "/" result) t)))
715                 (unless kind (return nil))
716                 (cond ((eq kind :link)
717                        (multiple-value-bind (link err) (unix-readlink result)
718                          (unless link
719                            (error 'simple-file-error
720                                   :pathname pathname
721                                   :format-control
722                                   "~@<error reading link ~S: ~2I~_~A~:>"
723                                   :format-arguments (list (subseq
724                                                            result 0 fill-ptr)
725                                                           (strerror err))))
726                          (cond ((or (zerop (length link))
727                                     (char/= (schar link 0) #\/))
728                                 ;; It's a relative link.
729                                 (fill result (code-char 0)
730                                       :start fill-ptr
731                                       :end new-fill-ptr))
732                                ((string= result "/../" :end1 4)
733                                 ;; It's across the super-root.
734                                 (let ((slash (or (position #\/ result :start 4)
735                                                  0)))
736                                   (fill result (code-char 0)
737                                         :start slash
738                                         :end new-fill-ptr)
739                                   (setf fill-ptr slash)))
740                                (t
741                                 ;; It's absolute.
742                                 (and (> (length link) 0)
743                                      (char= (schar link 0) #\/))
744                                 (fill result (code-char 0) :end new-fill-ptr)
745                                 (setf fill-ptr 0)))
746                          (setf pending
747                                (if (= name-end len)
748                                    link
749                                    (concatenate 'simple-string
750                                                 link
751                                                 (subseq pending name-end))))
752                          (setf len (length pending))
753                          (setf name-start 0)))
754                       ((= name-end len)
755                        (return (subseq result 0 new-fill-ptr)))
756                       ((eq kind :directory)
757                        (setf (schar result new-fill-ptr) #\/)
758                        (setf fill-ptr (1+ new-fill-ptr))
759                        (setf name-start (1+ name-end)))
760                       (t
761                        (return nil))))))))))
762
763 (defun unix-simplify-pathname (src)
764   (declare (simple-string src))
765   (let* ((src-len (length src))
766          (dst (make-string src-len))
767          (dst-len 0)
768          (dots 0)
769          (last-slash nil))
770     (macrolet ((deposit (char)
771                         `(progn
772                            (setf (schar dst dst-len) ,char)
773                            (incf dst-len))))
774       (dotimes (src-index src-len)
775         (let ((char (schar src src-index)))
776           (cond ((char= char #\.)
777                  (when dots
778                    (incf dots))
779                  (deposit char))
780                 ((char= char #\/)
781                  (case dots
782                    (0
783                     ;; Either ``/...' or ``...//...'
784                     (unless last-slash
785                       (setf last-slash dst-len)
786                       (deposit char)))
787                    (1
788                     ;; Either ``./...'' or ``..././...''
789                     (decf dst-len))
790                    (2
791                     ;; We've found ..
792                     (cond
793                      ((and last-slash (not (zerop last-slash)))
794                       ;; There is something before this ..
795                       (let ((prev-prev-slash
796                              (position #\/ dst :end last-slash :from-end t)))
797                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
798                                        last-slash)
799                                     (char= (schar dst (- last-slash 2)) #\.)
800                                     (char= (schar dst (1- last-slash)) #\.))
801                                ;; The something before this .. is another ..
802                                (deposit char)
803                                (setf last-slash dst-len))
804                               (t
805                                ;; The something is some directory or other.
806                                (setf dst-len
807                                      (if prev-prev-slash
808                                          (1+ prev-prev-slash)
809                                          0))
810                                (setf last-slash prev-prev-slash)))))
811                      (t
812                       ;; There is nothing before this .., so we need to keep it
813                       (setf last-slash dst-len)
814                       (deposit char))))
815                    (t
816                     ;; Something other than a dot between slashes.
817                     (setf last-slash dst-len)
818                     (deposit char)))
819                  (setf dots 0))
820                 (t
821                  (setf dots nil)
822                  (setf (schar dst dst-len) char)
823                  (incf dst-len))))))
824     (when (and last-slash (not (zerop last-slash)))
825       (case dots
826         (1
827          ;; We've got  ``foobar/.''
828          (decf dst-len))
829         (2
830          ;; We've got ``foobar/..''
831          (unless (and (>= last-slash 2)
832                       (char= (schar dst (1- last-slash)) #\.)
833                       (char= (schar dst (- last-slash 2)) #\.)
834                       (or (= last-slash 2)
835                           (char= (schar dst (- last-slash 3)) #\/)))
836            (let ((prev-prev-slash
837                   (position #\/ dst :end last-slash :from-end t)))
838              (if prev-prev-slash
839                  (setf dst-len (1+ prev-prev-slash))
840                  (return-from unix-simplify-pathname "./")))))))
841     (cond ((zerop dst-len)
842            "./")
843           ((= dst-len src-len)
844            dst)
845           (t
846            (subseq dst 0 dst-len)))))
847 \f
848 ;;;; stuff not yet found in the header files
849 ;;;;
850 ;;;; Abandon all hope who enters here...
851
852 ;;; not checked for linux...
853 (defmacro fd-set (offset fd-set)
854   (let ((word (gensym))
855         (bit (gensym)))
856     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
857        (setf (deref (slot ,fd-set 'fds-bits) ,word)
858              (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
859                      (deref (slot ,fd-set 'fds-bits) ,word))))))
860
861 ;;; not checked for linux...
862 (defmacro fd-clr (offset fd-set)
863   (let ((word (gensym))
864         (bit (gensym)))
865     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
866        (setf (deref (slot ,fd-set 'fds-bits) ,word)
867              (logand (deref (slot ,fd-set 'fds-bits) ,word)
868                      (sb!kernel:32bit-logical-not
869                       (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
870
871 ;;; not checked for linux...
872 (defmacro fd-isset (offset fd-set)
873   (let ((word (gensym))
874         (bit (gensym)))
875     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
876        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
877
878 ;;; not checked for linux...
879 (defmacro fd-zero (fd-set)
880   `(progn
881      ,@(loop for index upfrom 0 below (/ fd-setsize 32)
882          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))
883
884