0.6.12.3:
[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: Isn't there some way to use a C wrapper to avoid this hand-copying?
111 (defconstant +max-s-long+ 2147483647)
112 (defconstant +max-u-long+ 4294967295)
113 (def-alien-type quad-t #+nil long-long #-nil (array long 2))
114 (def-alien-type uquad-t #+nil unsigned-long-long
115                 #-nil (array unsigned-long 2))
116 (def-alien-type qaddr-t (* quad-t))
117 (def-alien-type daddr-t int)
118 (def-alien-type caddr-t (* char))
119 (def-alien-type swblk-t long)
120 (def-alien-type size-t unsigned-int)
121 (def-alien-type ssize-t int)
122
123 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp like this
124 ;;; unless we have extreme provocation. Reading directories is not extreme
125 ;;; enough, since it doesn't need to be blindingly fast: we can just implement
126 ;;; those functions in C as a wrapper layer.
127 (def-alien-type fd-mask unsigned-long)
128
129 (eval-when (:compile-toplevel :load-toplevel :execute)
130   (defconstant fd-setsize 1024))
131
132 (def-alien-type nil
133   (struct fd-set
134           (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
135
136 (/show0 "unix.lisp 304")
137 \f
138 \f
139 ;;;; fcntl.h
140 ;;;;
141 ;;;; POSIX Standard: 6.5 File Control Operations        <fcntl.h>
142
143 ;;; Open the file whose pathname is specified by PATH for reading
144 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
145 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
146 ;;;
147 ;;; If the O_CREAT flag is specified, then the file is created with a
148 ;;; permission of argument MODE if the file doesn't exist. An integer
149 ;;; file descriptor is returned by UNIX-OPEN.
150 (defun unix-open (path flags mode)
151   (declare (type unix-pathname path)
152            (type fixnum flags)
153            (type unix-file-mode mode))
154   (int-syscall ("open" c-string int int) path flags mode))
155
156 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
157 ;;; associated with it.
158 (/show0 "unix.lisp 391")
159 (defun unix-close (fd)
160   (declare (type unix-fd fd))
161   (void-syscall ("close" int) fd))
162 \f
163 ;;;; timebits.h
164
165 ;; A time value that is accurate to the nearest
166 ;; microsecond but also has a range of years.
167 (def-alien-type nil
168   (struct timeval
169           (tv-sec time-t)               ; seconds
170           (tv-usec time-t)))            ; and microseconds
171 \f
172 ;;;; resourcebits.h
173
174 (defconstant rusage_self 0) ; the calling process
175 (defconstant rusage_children -1) ; terminated child processes
176 (defconstant rusage_both -2)
177
178 (def-alien-type nil
179   (struct rusage
180     (ru-utime (struct timeval))     ; user time used
181     (ru-stime (struct timeval))     ; system time used.
182     (ru-maxrss long)                ; maximum resident set size (in kilobytes)
183     (ru-ixrss long)                 ; integral shared memory size
184     (ru-idrss long)                 ; integral unshared data size
185     (ru-isrss long)                 ; integral unshared stack size
186     (ru-minflt long)                ; page reclaims
187     (ru-majflt long)                ; page faults
188     (ru-nswap long)                 ; swaps
189     (ru-inblock long)               ; block input operations
190     (ru-oublock long)               ; block output operations
191     (ru-msgsnd long)                ; messages sent
192     (ru-msgrcv long)                ; messages received
193     (ru-nsignals long)              ; signals received
194     (ru-nvcsw long)                 ; voluntary context switches
195     (ru-nivcsw long)))              ; involuntary context switches
196 \f
197
198 ;;;; runtime/stat-wrapper.h
199 \f
200 ;;; this looks like "struct stat" according to stat(2).  It may not
201 ;;; correspond to the real in-memory stat structure that the syscall
202 ;;; uses, and if it doesn't, shouldn't.  Linux in particular is packed
203 ;;; full of stat macros, so we do this stuff in runtime/stat-wrapper.c
204
205 ;;; Note that st-dev is a long, not a dev-t.  This is because dev-t on
206 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
207 ;;; those.  We don't actually access that field anywhere, though, so until
208 ;;; we can get 64 bit alien support it'll do
209
210 (def-alien-type nil
211   (struct stat
212     (st-dev unsigned-long)              ;would be dev-t in a real stat
213     (st-ino ino-t)
214     (st-mode mode-t)
215     (st-nlink  nlink-t)
216     (st-uid  uid-t)
217     (st-gid  gid-t)
218     (st-rdev unsigned-long)             ;ditto
219     (st-size off-t)
220     (st-blksize unsigned-long)
221     (st-blocks unsigned-long)
222     (st-atime time-t)
223     (st-mtime time-t)
224     (st-ctime time-t)))
225
226 ;;;; unistd.h
227
228 ;;; Given a file path (a string) and one of four constant modes,
229 ;;; return T if the file is accessible with that mode and NIL if not.
230 ;;; When NIL, also return an errno value with NIL which tells why the
231 ;;; file was not accessible.
232 ;;; 
233 ;;; The access modes are:
234 ;;;   r_ok     Read permission.
235 ;;;   w_ok     Write permission.
236 ;;;   x_ok     Execute permission.
237 ;;;   f_ok     Presence of file.
238 (defun unix-access (path mode)
239   (declare (type unix-pathname path)
240            (type (mod 8) mode))
241   (void-syscall ("access" c-string int) path mode))
242
243 ;;; values for the second argument to UNIX-LSEEK
244 (defconstant l_set 0) ; to set the file pointer
245 (defconstant l_incr 1) ; to increment the file pointer
246 (defconstant l_xtnd 2) ; to extend the file size
247
248 ;;; Accept a file descriptor and move the file pointer ahead
249 ;;; a certain offset for that file. WHENCE can be any of the following:
250 ;;;  L_SET     Set the file pointer.
251 ;;;  L_INCR    Increment the file pointer.
252 ;;;  L_XTND    Extend the file size.
253 (defun unix-lseek (fd offset whence)
254   (declare (type unix-fd fd)
255            (type (unsigned-byte 32) offset)
256            (type (integer 0 2) whence))
257   #!-(and x86 bsd)
258   (int-syscall ("lseek" int off-t int) fd offset whence)
259   ;; Need a 64-bit return value type for this. TBD. For now,
260   ;; don't use this with any 2G+ partitions.
261   #!+(and x86 bsd)
262   (int-syscall ("lseek" int unsigned-long unsigned-long int)
263                fd offset 0 whence))
264
265 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
266 ;;; It attempts to read len bytes from the device associated with fd
267 ;;; and store them into the buffer. It returns the actual number of
268 ;;; bytes read.
269 (defun unix-read (fd buf len)
270   (declare (type unix-fd fd)
271            (type (unsigned-byte 32) len))
272
273   (int-syscall ("read" int (* char) int) fd buf len))
274
275 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
276 ;;; length to write. It attempts to write len bytes to the device
277 ;;; associated with fd from the the buffer starting at offset. It returns
278 ;;; the actual number of bytes written.
279 (defun unix-write (fd buf offset len)
280   (declare (type unix-fd fd)
281            (type (unsigned-byte 32) offset len))
282   (int-syscall ("write" int (* char) int)
283                fd
284                (with-alien ((ptr (* char) (etypecase buf
285                                             ((simple-array * (*))
286                                              (vector-sap buf))
287                                             (system-area-pointer
288                                              buf))))
289                  (addr (deref ptr offset)))
290                len))
291
292 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
293 ;;; output pipe. Return two values: if no error occurred the first
294 ;;; value is the pipe to be read from and the second is can be written
295 ;;; to. If an error occurred the first value is NIL and the second the
296 ;;; unix error code.
297 (defun unix-pipe ()
298   (with-alien ((fds (array int 2)))
299     (syscall ("pipe" (* int))
300              (values (deref fds 0) (deref fds 1))
301              (cast fds (* int)))))
302
303 ;;; UNIX-CHDIR accepts a directory name and makes that the
304 ;;; current working directory.
305 (defun unix-chdir (path)
306   (declare (type unix-pathname path))
307   (void-syscall ("chdir" c-string) path))
308
309 ;;; Return the current directory as a SIMPLE-STRING.
310 (defun unix-current-directory ()
311   ;; FIXME: Gcc justifiably complains that getwd is dangerous and should
312   ;; not be used; especially with a hardwired 1024 buffer size, yecch.
313   ;; This should be rewritten to use getcwd(3), perhaps by writing
314   ;; a C service routine to do the actual call to getcwd(3) and check
315   ;; of return values.
316   (with-alien ((buf (array char 1024)))
317     (values (not (zerop (alien-funcall (extern-alien "getwd"
318                                                      (function int (* char)))
319                                        (cast buf (* char)))))
320             (cast buf c-string))))
321
322 ;;; Duplicate an existing file descriptor (given as the argument) and
323 ;;; return it. If FD is not a valid file descriptor, NIL and an error
324 ;;; number are returned.
325 (defun unix-dup (fd)
326   (declare (type unix-fd fd))
327   (int-syscall ("dup" int) fd))
328
329 ;;; Terminate the current process with an optional error code. If
330 ;;; successful, the call doesn't return. If unsuccessful, the call
331 ;;; returns NIL and an error number.
332 (defun unix-exit (&optional (code 0))
333   (declare (type (signed-byte 32) code))
334   (void-syscall ("exit" int) code))
335
336 ;;; Return the process id of the current process.
337 (def-alien-routine ("getpid" unix-getpid) int)
338
339 ;;; Return the real user-id associated with the current process.
340 (def-alien-routine ("getuid" unix-getuid) int)
341
342 ;;; Invoke readlink(2) on the file name specified by the simple string
343 ;;; PATH. Return up to two values: the contents of the symbolic link
344 ;;; if the call is successful, or NIL and the Unix error number.
345 (defun unix-readlink (path)
346   (declare (type unix-pathname path))
347   (with-alien ((buf (array char 1024)))
348     (syscall ("readlink" c-string (* char) int)
349              (let ((string (make-string result)))
350                (sb!kernel:copy-from-system-area
351                 (alien-sap buf) 0
352                 string (* sb!vm:vector-data-offset sb!vm:word-bits)
353                 (* result sb!vm:byte-bits))
354                string)
355              path (cast buf (* char)) 1024)))
356
357 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
358 ;;; name and the file if this is the last link. 
359 (defun unix-unlink (name)
360   (declare (type unix-pathname name))
361   (void-syscall ("unlink" c-string) name))
362
363 ;;; Set the tty-process-group for the unix file-descriptor FD to PGRP.
364 ;;; If not supplied, FD defaults to "/dev/tty".
365 (defun %set-tty-process-group (pgrp &optional fd)
366   (let ((old-sigs (unix-sigblock (sigmask :sigttou
367                                           :sigttin
368                                           :sigtstp
369                                           :sigchld))))
370     (declare (type (unsigned-byte 32) old-sigs))
371     (unwind-protect
372         (if fd
373             (tcsetpgrp fd pgrp)
374             (multiple-value-bind (tty-fd errno) (unix-open "/dev/tty" o_rdwr 0)
375               (cond (tty-fd
376                      (multiple-value-prog1
377                          (tcsetpgrp tty-fd pgrp)
378                        (unix-close tty-fd)))
379                     (t
380                      (values nil errno)))))
381       (unix-sigsetmask old-sigs))))
382
383 ;;; Return the name of the host machine as a string.
384 (defun unix-gethostname ()
385   (with-alien ((buf (array char 256)))
386     (syscall ("gethostname" (* char) int)
387              (cast buf c-string)
388              (cast buf (* char)) 256)))
389
390 ;;; Write the core image of the file described by FD to disk.
391 (defun unix-fsync (fd)
392   (declare (type unix-fd fd))
393   (void-syscall ("fsync" int) fd))
394 \f
395 ;;;; sys/ioctl.h
396
397 ;;; UNIX-IOCTL performs a variety of operations on open i/o
398 ;;; descriptors. See the UNIX Programmer's Manual for more
399 ;;; information.
400 (defun unix-ioctl (fd cmd arg)
401   (declare (type unix-fd fd)
402            (type (unsigned-byte 32) cmd))
403   (void-syscall ("ioctl" int unsigned-int (* char)) fd cmd arg))
404 \f
405 ;;;; sys/resource.h
406
407 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
408 ;;;
409 ;;; Like getrusage(2), but return only the system and user time,
410 ;;; and return the seconds and microseconds as separate values.
411 #!-sb-fluid (declaim (inline unix-fast-getrusage))
412 (defun unix-fast-getrusage (who)
413   (declare (values (member t)
414                    (unsigned-byte 31) (mod 1000000)
415                    (unsigned-byte 31) (mod 1000000)))
416   (with-alien ((usage (struct rusage)))
417     (syscall* ("getrusage" int (* (struct rusage)))
418               (values t
419                       (slot (slot usage 'ru-utime) 'tv-sec)
420                       (slot (slot usage 'ru-utime) 'tv-usec)
421                       (slot (slot usage 'ru-stime) 'tv-sec)
422                       (slot (slot usage 'ru-stime) 'tv-usec))
423               who (addr usage))))
424
425 ;;; Return information about the resource usage of the process
426 ;;; specified by WHO. WHO can be either the current process
427 ;;; (rusage_self) or all of the terminated child processes
428 ;;; (rusage_children). NIL and an error number is returned if the call
429 ;;; fails.
430 (defun unix-getrusage (who)
431   (with-alien ((usage (struct rusage)))
432     (syscall ("getrusage" int (* (struct rusage)))
433               (values t
434                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
435                          (slot (slot usage 'ru-utime) 'tv-usec))
436                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
437                          (slot (slot usage 'ru-stime) 'tv-usec))
438                       (slot usage 'ru-maxrss)
439                       (slot usage 'ru-ixrss)
440                       (slot usage 'ru-idrss)
441                       (slot usage 'ru-isrss)
442                       (slot usage 'ru-minflt)
443                       (slot usage 'ru-majflt)
444                       (slot usage 'ru-nswap)
445                       (slot usage 'ru-inblock)
446                       (slot usage 'ru-oublock)
447                       (slot usage 'ru-msgsnd)
448                       (slot usage 'ru-msgrcv)
449                       (slot usage 'ru-nsignals)
450                       (slot usage 'ru-nvcsw)
451                       (slot usage 'ru-nivcsw))
452               who (addr usage))))
453 \f
454 ;;;; sys/select.h
455
456 (defmacro unix-fast-select (num-descriptors
457                             read-fds write-fds exception-fds
458                             timeout-secs &optional (timeout-usecs 0))
459   #!+sb-doc
460   "Perform the UNIX select(2) system call."
461   (declare (type (integer 0 #.FD-SETSIZE) num-descriptors)
462            (type (or (alien (* (struct fd-set))) null)
463                  read-fds write-fds exception-fds)
464            (type (or null (unsigned-byte 31)) timeout-secs)
465            (type (unsigned-byte 31) timeout-usecs) )
466   ;; FIXME: CMU CL had
467   ;;   (optimize (speed 3) (safety 0) (inhibit-warnings 3))
468   ;; in the declarations above. If they're important, they should
469   ;; be in a declaration inside the LET expansion, not in the
470   ;; macro compile-time code.
471   `(let ((timeout-secs ,timeout-secs))
472      (with-alien ((tv (struct timeval)))
473        (when timeout-secs
474          (setf (slot tv 'tv-sec) timeout-secs)
475          (setf (slot tv 'tv-usec) ,timeout-usecs))
476        (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
477                      (* (struct fd-set)) (* (struct timeval)))
478                     ,num-descriptors ,read-fds ,write-fds ,exception-fds
479                     (if timeout-secs (alien-sap (addr tv)) (int-sap 0))))))
480
481 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
482 ;;; to happen on one of them or to time out.
483 (defmacro num-to-fd-set (fdset num)
484   `(if (fixnump ,num)
485        (progn
486          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
487          ,@(loop for index upfrom 1 below (/ fd-setsize 32)
488              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
489        (progn
490          ,@(loop for index upfrom 0 below (/ fd-setsize 32)
491              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
492                             (ldb (byte 32 ,(* index 32)) ,num))))))
493
494 (defmacro fd-set-to-num (nfds fdset)
495   `(if (<= ,nfds 32)
496        (deref (slot ,fdset 'fds-bits) 0)
497        (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
498               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
499                             ,(* index 32))))))
500
501 ;;; Examine the sets of descriptors passed as arguments to see whether
502 ;;; they are ready for reading and writing. See the UNIX Programmer's
503 ;;; Manual for more information.
504 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
505   (declare (type (integer 0 #.FD-SETSIZE) nfds)
506            (type unsigned-byte rdfds wrfds xpfds)
507            (type (or (unsigned-byte 31) null) to-secs)
508            (type (unsigned-byte 31) to-usecs)
509            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
510   (with-alien ((tv (struct timeval))
511                (rdf (struct fd-set))
512                (wrf (struct fd-set))
513                (xpf (struct fd-set)))
514     (when to-secs
515       (setf (slot tv 'tv-sec) to-secs)
516      (setf (slot tv 'tv-usec) to-usecs))
517     (num-to-fd-set rdf rdfds)
518     (num-to-fd-set wrf wrfds)
519     (num-to-fd-set xpf xpfds)
520     (macrolet ((frob (lispvar alienvar)
521                  `(if (zerop ,lispvar)
522                       (int-sap 0)
523                       (alien-sap (addr ,alienvar)))))
524       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
525                 (* (struct fd-set)) (* (struct timeval)))
526                (values result
527                        (fd-set-to-num nfds rdf)
528                        (fd-set-to-num nfds wrf)
529                        (fd-set-to-num nfds xpf))
530                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
531                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
532 \f
533 ;;;; sys/stat.h
534
535 ;;; FIXME: This is only used in this file, and needn't be in target Lisp
536 ;;; runtime. It's also unclear why it needs to be a macro instead of a
537 ;;; function. Perhaps it should become a FLET.
538 (defmacro extract-stat-results (buf)
539   `(values T                            ; result
540            (slot ,buf 'st-dev)
541            (slot ,buf 'st-ino)
542            (slot ,buf 'st-mode)
543            (slot ,buf 'st-nlink)
544            (slot ,buf 'st-uid)
545            (slot ,buf 'st-gid)
546            (slot ,buf 'st-rdev)
547            (slot ,buf 'st-size)
548            (slot ,buf 'st-atime)
549            (slot ,buf 'st-mtime)
550            (slot ,buf 'st-ctime)
551            (slot ,buf 'st-blksize)
552            (slot ,buf 'st-blocks)))
553
554 ;;; Retrieve information about the specified file returning them in
555 ;;; the form of multiple values. See the UNIX Programmer's Manual for
556 ;;; a description of the values returned. If the call fails, then NIL
557 ;;; and an error number is returned instead.
558
559 (defun unix-stat (name)
560   (declare (type unix-pathname name))
561   (when (string= name "")
562     (setf name "."))
563   (with-alien ((buf (struct stat)))
564     (syscall ("stat_wrapper" c-string (* (struct stat)))
565              (extract-stat-results buf)
566              name (addr buf))))
567
568 (defun unix-lstat (name)
569   #!+sb-doc
570   "Unix-lstat is identical to unix-stat, except if NAME is 
571    a symlink, in which case it returns information about the
572    link itself rather than dereferencing it."
573   (declare (type unix-pathname name))
574   (with-alien ((buf (struct stat)))
575     (syscall ("lstat_wrapper" c-string (* (struct stat)))
576              (extract-stat-results buf)
577              name (addr buf))))
578
579 ;;; like UNIX-STAT except the file is specified by the file descriptor FD
580 (defun unix-fstat (fd)
581   (declare (type unix-fd fd))
582   (with-alien ((buf (struct stat)))
583     (syscall ("fstat_wrapper" int (* (struct stat)))
584              (extract-stat-results buf)
585              fd (addr buf))))
586
587
588 ;;; UNIX-MKDIR accepts a name and a mode and attempts to create the
589 ;;; corresponding directory with mode mode.
590 (defun unix-mkdir (name mode)
591   (declare (type unix-pathname name)
592            (type unix-file-mode mode))
593   (void-syscall ("mkdir" c-string int) name mode))
594 \f
595 ;;;; time.h
596
597 ;; the POSIX.4 structure for a time value. This is like a `struct
598 ;; timeval' but has nanoseconds instead of microseconds.
599 (def-alien-type nil
600     (struct timespec
601             (tv-sec long)   ;Seconds
602             (tv-nsec long))) ;Nanoseconds
603
604 ;; used by other time functions
605 (def-alien-type nil
606     (struct tm
607             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
608             (tm-min int)   ; Minutes.   [0-59]
609             (tm-hour int)  ; Hours.     [0-23]
610             (tm-mday int)  ; Day.               [1-31]
611             (tm-mon int)   ;  Month.    [0-11]
612             (tm-year int)  ; Year       - 1900.
613             (tm-wday int)  ; Day of week.       [0-6]
614             (tm-yday int)  ; Days in year.[0-365]
615             (tm-isdst int) ;  DST.              [-1/0/1]
616             (tm-gmtoff long)    ;  Seconds east of UTC.
617             (tm-zone c-string)))        ; Timezone abbreviation.
618
619 (def-alien-routine get-timezone sb!c-call:void
620   (when sb!c-call:long :in)
621   (minutes-west sb!c-call:int :out)
622   (daylight-savings-p sb!alien:boolean :out))
623
624 (defun unix-get-minutes-west (secs)
625   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
626     (declare (ignore ignore) (ignore dst))
627     (values minutes)))
628
629 (defun unix-get-timezone (secs)
630   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
631     (declare (ignore ignore) (ignore minutes))
632     (values (deref unix-tzname (if dst 1 0)))))
633
634 \f
635 ;;;; sys/time.h
636
637 ;;; Structure crudely representing a timezone. KLUDGE: This is
638 ;;; obsolete and should never be used.
639 (def-alien-type nil
640   (struct timezone
641     (tz-minuteswest int)                ; minutes west of Greenwich
642     (tz-dsttime int)))                  ; type of dst correction
643
644 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
645 ;;; and microseconds of the current time of day, the timezone (in
646 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
647 ;;; doesn't work, it returns NIL and the errno.
648 #!-sb-fluid (declaim (inline unix-gettimeofday))
649 (defun unix-gettimeofday ()
650   (with-alien ((tv (struct timeval))
651                (tz (struct timezone)))
652     (syscall* ("gettimeofday" (* (struct timeval))
653                               (* (struct timezone)))
654               (values T
655                       (slot tv 'tv-sec)
656                       (slot tv 'tv-usec)
657                       (slot tz 'tz-minuteswest)
658                       (slot tz 'tz-dsttime))
659               (addr tv)
660               (addr tz))))
661 \f
662
663 (defconstant ENOENT 2) ; Unix error code, "No such file or directory"
664 (defconstant EINTR 4) ; Unix error code, "Interrupted system call"
665 (defconstant EIO 5) ; Unix error code, "I/O error"
666 (defconstant EEXIST 17) ; Unix error code, "File exists"
667 (defconstant ESPIPE 29) ; Unix error code, "Illegal seek"
668 (defconstant EWOULDBLOCK 11) ; Unix error code, "Operation would block"
669 ;;; FIXME: Many Unix error code definitions were deleted from the old
670 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
671 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
672 ;;; unused symbols in package exports, but if I don't, there are
673 ;;; enough of them all in one place here that they should probably be
674 ;;; removed by hand.
675 \f
676 \f
677 ;;;; support routines for dealing with Unix pathnames
678
679 (defun unix-file-kind (name &optional check-for-links)
680   #!+sb-doc
681   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
682   (declare (simple-string name))
683   (multiple-value-bind (res dev ino mode)
684       (if check-for-links (unix-lstat name) (unix-stat name))
685     (declare (type (or fixnum null) mode)
686              (ignore dev ino))
687     (when res
688       (let ((kind (logand mode s-ifmt)))
689         (cond ((eql kind s-ifdir) :directory)
690               ((eql kind s-ifreg) :file)
691               ((eql kind s-iflnk) :link)
692               (t :special))))))
693
694 (defun unix-maybe-prepend-current-directory (name)
695   (declare (simple-string name))
696   (if (and (> (length name) 0) (char= (schar name 0) #\/))
697       name
698       (multiple-value-bind (win dir) (unix-current-directory)
699         (if win
700             (concatenate 'simple-string dir "/" name)
701             name))))
702
703 ;;; Return the pathname with all symbolic links resolved.
704 ;;;
705 ;;; FIXME: Could we just use Unix readlink(2) instead?
706 (defun unix-resolve-links (pathname)
707   (declare (simple-string pathname))
708   (let ((len (length pathname))
709         (pending pathname))
710     (declare (fixnum len) (simple-string pending))
711     (if (zerop len)
712         pathname
713         (let ((result (make-string 1024 :initial-element (code-char 0)))
714               (fill-ptr 0)
715               (name-start 0))
716           (loop
717             (let* ((name-end (or (position #\/ pending :start name-start) len))
718                    (new-fill-ptr (+ fill-ptr (- name-end name-start))))
719               (replace result pending
720                        :start1 fill-ptr
721                        :end1 new-fill-ptr
722                        :start2 name-start
723                        :end2 name-end)
724               (let ((kind (unix-file-kind (if (zerop name-end) "/" result) t)))
725                 (unless kind (return nil))
726                 (cond ((eq kind :link)
727                        (multiple-value-bind (link err) (unix-readlink result)
728                          (unless link
729                            (error 'simple-file-error
730                                   :pathname pathname
731                                   :format-control
732                                   "~@<error reading link ~S: ~2I~_~A~:>"
733                                   :format-arguments (list (subseq
734                                                            result 0 fill-ptr)
735                                                           (strerror err))))
736                          (cond ((or (zerop (length link))
737                                     (char/= (schar link 0) #\/))
738                                 ;; It's a relative link.
739                                 (fill result (code-char 0)
740                                       :start fill-ptr
741                                       :end new-fill-ptr))
742                                ((string= result "/../" :end1 4)
743                                 ;; It's across the super-root.
744                                 (let ((slash (or (position #\/ result :start 4)
745                                                  0)))
746                                   (fill result (code-char 0)
747                                         :start slash
748                                         :end new-fill-ptr)
749                                   (setf fill-ptr slash)))
750                                (t
751                                 ;; It's absolute.
752                                 (and (> (length link) 0)
753                                      (char= (schar link 0) #\/))
754                                 (fill result (code-char 0) :end new-fill-ptr)
755                                 (setf fill-ptr 0)))
756                          (setf pending
757                                (if (= name-end len)
758                                    link
759                                    (concatenate 'simple-string
760                                                 link
761                                                 (subseq pending name-end))))
762                          (setf len (length pending))
763                          (setf name-start 0)))
764                       ((= name-end len)
765                        (return (subseq result 0 new-fill-ptr)))
766                       ((eq kind :directory)
767                        (setf (schar result new-fill-ptr) #\/)
768                        (setf fill-ptr (1+ new-fill-ptr))
769                        (setf name-start (1+ name-end)))
770                       (t
771                        (return nil))))))))))
772
773 (defun unix-simplify-pathname (src)
774   (declare (simple-string src))
775   (let* ((src-len (length src))
776          (dst (make-string src-len))
777          (dst-len 0)
778          (dots 0)
779          (last-slash nil))
780     (macrolet ((deposit (char)
781                         `(progn
782                            (setf (schar dst dst-len) ,char)
783                            (incf dst-len))))
784       (dotimes (src-index src-len)
785         (let ((char (schar src src-index)))
786           (cond ((char= char #\.)
787                  (when dots
788                    (incf dots))
789                  (deposit char))
790                 ((char= char #\/)
791                  (case dots
792                    (0
793                     ;; Either ``/...' or ``...//...'
794                     (unless last-slash
795                       (setf last-slash dst-len)
796                       (deposit char)))
797                    (1
798                     ;; Either ``./...'' or ``..././...''
799                     (decf dst-len))
800                    (2
801                     ;; We've found ..
802                     (cond
803                      ((and last-slash (not (zerop last-slash)))
804                       ;; There is something before this ..
805                       (let ((prev-prev-slash
806                              (position #\/ dst :end last-slash :from-end t)))
807                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
808                                        last-slash)
809                                     (char= (schar dst (- last-slash 2)) #\.)
810                                     (char= (schar dst (1- last-slash)) #\.))
811                                ;; The something before this .. is another ..
812                                (deposit char)
813                                (setf last-slash dst-len))
814                               (t
815                                ;; The something is some directory or other.
816                                (setf dst-len
817                                      (if prev-prev-slash
818                                          (1+ prev-prev-slash)
819                                          0))
820                                (setf last-slash prev-prev-slash)))))
821                      (t
822                       ;; There is nothing before this .., so we need to keep it
823                       (setf last-slash dst-len)
824                       (deposit char))))
825                    (t
826                     ;; Something other than a dot between slashes.
827                     (setf last-slash dst-len)
828                     (deposit char)))
829                  (setf dots 0))
830                 (t
831                  (setf dots nil)
832                  (setf (schar dst dst-len) char)
833                  (incf dst-len))))))
834     (when (and last-slash (not (zerop last-slash)))
835       (case dots
836         (1
837          ;; We've got  ``foobar/.''
838          (decf dst-len))
839         (2
840          ;; We've got ``foobar/..''
841          (unless (and (>= last-slash 2)
842                       (char= (schar dst (1- last-slash)) #\.)
843                       (char= (schar dst (- last-slash 2)) #\.)
844                       (or (= last-slash 2)
845                           (char= (schar dst (- last-slash 3)) #\/)))
846            (let ((prev-prev-slash
847                   (position #\/ dst :end last-slash :from-end t)))
848              (if prev-prev-slash
849                  (setf dst-len (1+ prev-prev-slash))
850                  (return-from unix-simplify-pathname "./")))))))
851     (cond ((zerop dst-len)
852            "./")
853           ((= dst-len src-len)
854            dst)
855           (t
856            (subseq dst 0 dst-len)))))
857 \f
858 ;;;; stuff not yet found in the header files
859 ;;;;
860 ;;;; Abandon all hope who enters here...
861
862 ;;; not checked for linux...
863 (defmacro fd-set (offset fd-set)
864   (let ((word (gensym))
865         (bit (gensym)))
866     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
867        (setf (deref (slot ,fd-set 'fds-bits) ,word)
868              (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
869                      (deref (slot ,fd-set 'fds-bits) ,word))))))
870
871 ;;; not checked for linux...
872 (defmacro fd-clr (offset fd-set)
873   (let ((word (gensym))
874         (bit (gensym)))
875     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
876        (setf (deref (slot ,fd-set 'fds-bits) ,word)
877              (logand (deref (slot ,fd-set 'fds-bits) ,word)
878                      (sb!kernel:32bit-logical-not
879                       (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
880
881 ;;; not checked for linux...
882 (defmacro fd-isset (offset fd-set)
883   (let ((word (gensym))
884         (bit (gensym)))
885     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
886        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
887
888 ;;; not checked for linux...
889 (defmacro fd-zero (fd-set)
890   `(progn
891      ,@(loop for index upfrom 0 below (/ fd-setsize 32)
892          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))
893
894