e6dfddf5912df2a1891bedee2712b3f1a10a3138
[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-base-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   `(locally
68     (declare (optimize (sb!c::float-accuracy 0)))
69     (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
70                                 ,@args)))
71       (if (minusp result)
72           (values nil (get-errno))
73           ,success-form))))
74
75 ;;; This is like SYSCALL, but if it fails, signal an error instead of
76 ;;; returning error codes. Should only be used for syscalls that will
77 ;;; never really get an error.
78 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
79   `(locally
80     (declare (optimize (sb!c::float-accuracy 0)))
81     (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
82                                  ,@args)))
83       (if (minusp result)
84           (error "Syscall ~A failed: ~A" ,name (strerror))
85           ,success-form))))
86
87 (/show0 "unix.lisp 109")
88
89 (defmacro void-syscall ((name &rest arg-types) &rest args)
90   `(syscall (,name ,@arg-types) (values t 0) ,@args))
91
92 (defmacro int-syscall ((name &rest arg-types) &rest args)
93   `(syscall (,name ,@arg-types) (values result 0) ,@args))
94
95 (defmacro with-restarted-syscall ((&optional (value (gensym))
96                                              (errno (gensym)))
97                                   syscall-form &rest body)
98   #!+sb-doc
99   "Evaluate BODY with VALUE and ERRNO bound to the return values of
100 SYSCALL-FORM. Repeat evaluation of SYSCALL-FORM if it is interrupted."
101   `(let (,value ,errno)
102      (loop (multiple-value-setq (,value ,errno)
103              ,syscall-form)
104         (unless (eql ,errno sb!unix:eintr)
105           (return (values ,value ,errno))))
106      ,@body))
107 \f
108 ;;;; hacking the Unix environment
109
110 (define-alien-routine ("getenv" posix-getenv) c-string
111   "Return the \"value\" part of the environment string \"name=value\" which
112    corresponds to NAME, or NIL if there is none."
113   (name c-string))
114 \f
115 ;;; from stdio.h
116
117 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
118 ;;; error code is returned if an error occurs.
119 (defun unix-rename (name1 name2)
120   (declare (type unix-pathname name1 name2))
121   (void-syscall ("rename" c-string c-string) name1 name2))
122 \f
123 ;;; from sys/types.h and gnu/types.h
124
125 (/show0 "unix.lisp 220")
126
127 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
128 ;;; like this unless we have extreme provocation. Reading directories
129 ;;; is not extreme enough, since it doesn't need to be blindingly
130 ;;; fast: we can just implement those functions in C as a wrapper
131 ;;; layer.
132 (define-alien-type fd-mask unsigned-long)
133
134 (eval-when (:compile-toplevel :load-toplevel :execute)
135   (defconstant fd-setsize 1024))
136
137 (define-alien-type nil
138   (struct fd-set
139           (fds-bits (array fd-mask #.(/ fd-setsize
140                                         sb!vm:n-machine-word-bits)))))
141
142 (/show0 "unix.lisp 304")
143 \f
144 \f
145 ;;;; fcntl.h
146 ;;;;
147 ;;;; POSIX Standard: 6.5 File Control Operations        <fcntl.h>
148
149 ;;; Open the file whose pathname is specified by PATH for reading
150 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
151 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
152 ;;;
153 ;;; If the O_CREAT flag is specified, then the file is created with a
154 ;;; permission of argument MODE if the file doesn't exist. An integer
155 ;;; file descriptor is returned by UNIX-OPEN.
156 (defun unix-open (path flags mode)
157   (declare (type unix-pathname path)
158            (type fixnum flags)
159            (type unix-file-mode mode))
160   (int-syscall ("open" c-string int int) path flags mode))
161
162 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
163 ;;; associated with it.
164 (/show0 "unix.lisp 391")
165 (defun unix-close (fd)
166   (declare (type unix-fd fd))
167   (void-syscall ("close" int) fd))
168 \f
169 ;;;; timebits.h
170
171 ;; A time value that is accurate to the nearest
172 ;; microsecond but also has a range of years.
173 (define-alien-type nil
174   (struct timeval
175           (tv-sec time-t)               ; seconds
176           (tv-usec time-t)))            ; and microseconds
177 \f
178 ;;;; resourcebits.h
179
180 (defconstant rusage_self 0) ; the calling process
181 (defconstant rusage_children -1) ; terminated child processes
182 (defconstant rusage_both -2)
183
184 (define-alien-type nil
185   (struct rusage
186     (ru-utime (struct timeval))     ; user time used
187     (ru-stime (struct timeval))     ; system time used.
188     (ru-maxrss long)                ; maximum resident set size (in kilobytes)
189     (ru-ixrss long)                 ; integral shared memory size
190     (ru-idrss long)                 ; integral unshared data size
191     (ru-isrss long)                 ; integral unshared stack size
192     (ru-minflt long)                ; page reclaims
193     (ru-majflt long)                ; page faults
194     (ru-nswap long)                 ; swaps
195     (ru-inblock long)               ; block input operations
196     (ru-oublock long)               ; block output operations
197     (ru-msgsnd long)                ; messages sent
198     (ru-msgrcv long)                ; messages received
199     (ru-nsignals long)              ; signals received
200     (ru-nvcsw long)                 ; voluntary context switches
201     (ru-nivcsw long)))              ; involuntary context switches
202 \f
203 ;;;; unistd.h
204
205 ;;; Given a file path (a string) and one of four constant modes,
206 ;;; return T if the file is accessible with that mode and NIL if not.
207 ;;; When NIL, also return an errno value with NIL which tells why the
208 ;;; file was not accessible.
209 ;;;
210 ;;; The access modes are:
211 ;;;   r_ok     Read permission.
212 ;;;   w_ok     Write permission.
213 ;;;   x_ok     Execute permission.
214 ;;;   f_ok     Presence of file.
215 (defun unix-access (path mode)
216   (declare (type unix-pathname path)
217            (type (mod 8) mode))
218   (void-syscall ("access" c-string int) path mode))
219
220 ;;; values for the second argument to UNIX-LSEEK
221 (defconstant l_set 0) ; to set the file pointer
222 (defconstant l_incr 1) ; to increment the file pointer
223 (defconstant l_xtnd 2) ; to extend the file size
224
225 ;;; Is a stream interactive?
226 (defun unix-isatty (fd)
227   (declare (type unix-fd fd))
228   (int-syscall ("isatty" int) fd))
229
230 (defun unix-lseek (fd offset whence)
231   "Unix-lseek accepts a file descriptor and moves the file pointer by
232    OFFSET octets.  Whence can be any of the following:
233
234    L_SET        Set the file pointer.
235    L_INCR       Increment the file pointer.
236    L_XTND       Extend the file size.
237   "
238   (declare (type unix-fd fd)
239            (type (integer 0 2) whence))
240   (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
241                  fd offset whence)))
242     (if (minusp result )
243         (values nil (get-errno))
244       (values result 0))))
245
246 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
247 ;;; It attempts to read len bytes from the device associated with fd
248 ;;; and store them into the buffer. It returns the actual number of
249 ;;; bytes read.
250 (defun unix-read (fd buf len)
251   (declare (type unix-fd fd)
252            (type (unsigned-byte 32) len))
253
254   (int-syscall ("read" int (* char) int) fd buf len))
255
256 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
257 ;;; length to write. It attempts to write len bytes to the device
258 ;;; associated with fd from the buffer starting at offset. It returns
259 ;;; the actual number of bytes written.
260 (defun unix-write (fd buf offset len)
261   (declare (type unix-fd fd)
262            (type (unsigned-byte 32) offset len))
263   (int-syscall ("write" int (* char) int)
264                fd
265                (with-alien ((ptr (* char) (etypecase buf
266                                             ((simple-array * (*))
267                                              (vector-sap buf))
268                                             (system-area-pointer
269                                              buf))))
270                  (addr (deref ptr offset)))
271                len))
272
273 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
274 ;;; output pipe. Return two values: if no error occurred the first
275 ;;; value is the pipe to be read from and the second is can be written
276 ;;; to. If an error occurred the first value is NIL and the second the
277 ;;; unix error code.
278 (defun unix-pipe ()
279   (with-alien ((fds (array int 2)))
280     (syscall ("pipe" (* int))
281              (values (deref fds 0) (deref fds 1))
282              (cast fds (* int)))))
283
284 (defun unix-mkdir (name mode)
285   (declare (type unix-pathname name)
286            (type unix-file-mode mode))
287   (void-syscall ("mkdir" c-string int) name mode))
288
289 ;;; Given a C char* pointer allocated by malloc(), free it and return a
290 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
291 (defun newcharstar-string (newcharstar)
292   (declare (type (alien (* char)) newcharstar))
293   (if (null-alien newcharstar)
294       nil
295       (prog1
296           (cast newcharstar c-string)
297         (free-alien newcharstar))))
298
299 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
300 ;;; style returned by getcwd() (no trailing slash character).
301 (defun posix-getcwd ()
302   ;; This implementation relies on a BSD/Linux extension to getcwd()
303   ;; behavior, automatically allocating memory when a null buffer
304   ;; pointer is used. On a system which doesn't support that
305   ;; extension, it'll have to be rewritten somehow.
306   ;;
307   ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
308   ;; buffer pointer, it will automatically allocate size space. The
309   ;; KLUDGE in this solution arises because we have just read off
310   ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
311   ;; a constant. Going the grovel_headers route doesn't seem to be
312   ;; helpful, either, as Solaris doesn't export PATH_MAX from
313   ;; unistd.h.
314   #!-(or linux openbsd freebsd netbsd sunos osf1 darwin) (,stub,)
315   #!+(or linux openbsd freebsd netbsd sunos osf1 darwin)
316   (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
317                                                        (function (* char)
318                                                                  (* char)
319                                                                  size-t))
320                                          nil
321                                          #!+(or linux openbsd freebsd netbsd darwin) 0
322                                          #!+(or sunos osf1) 1025))
323       (simple-perror "getcwd")))
324
325 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
326 ;;; by a slash character.
327 (defun posix-getcwd/ ()
328   (concatenate 'string (posix-getcwd) "/"))
329
330 ;;; Convert at the UNIX level from a possibly relative filename to
331 ;;; an absolute filename.
332 ;;;
333 ;;; FIXME: Do we still need this even as we switch to
334 ;;; *DEFAULT-PATHNAME-DEFAULTS*? I think maybe we do, since it seems
335 ;;; to be valid for the user to set *DEFAULT-PATHNAME-DEFAULTS* to
336 ;;; have a NIL directory component, and then this'd be the only way to
337 ;;; interpret a relative directory specification. But I don't find the
338 ;;; ANSI pathname documentation to be a model of clarity. Maybe
339 ;;; someone who understands it better can take a look at this.. -- WHN
340 (defun unix-maybe-prepend-current-directory (name)
341   (declare (simple-string name))
342   (if (and (> (length name) 0) (char= (schar name 0) #\/))
343       name
344       (concatenate 'simple-string (posix-getcwd/) name)))
345
346 ;;; Duplicate an existing file descriptor (given as the argument) and
347 ;;; return it. If FD is not a valid file descriptor, NIL and an error
348 ;;; number are returned.
349 (defun unix-dup (fd)
350   (declare (type unix-fd fd))
351   (int-syscall ("dup" int) fd))
352
353 ;;; Terminate the current process with an optional error code. If
354 ;;; successful, the call doesn't return. If unsuccessful, the call
355 ;;; returns NIL and an error number.
356 (defun unix-exit (&optional (code 0))
357   (declare (type (signed-byte 32) code))
358   (void-syscall ("exit" int) code))
359
360 ;;; Return the process id of the current process.
361 (define-alien-routine ("getpid" unix-getpid) int)
362
363 ;;; Return the real user id associated with the current process.
364 (define-alien-routine ("getuid" unix-getuid) int)
365
366 ;;; Translate a user id into a login name.
367 (defun uid-username (uid)
368   (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
369                                                        (function (* char) int))
370                                          uid))
371       (error "found no match for Unix uid=~S" uid)))
372
373 ;;; Return the namestring of the home directory, being careful to
374 ;;; include a trailing #\/
375 (defun uid-homedir (uid)
376   (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
377                                                        (function (* char) int))
378                                          uid))
379       (error "failed to resolve home directory for Unix uid=~S" uid)))
380
381 ;;; Invoke readlink(2) on the file name specified by PATH. Return
382 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
383 ;;; failure.
384 (defun unix-readlink (path)
385   (declare (type unix-pathname path))
386   (with-alien ((ptr (* char)
387                     (alien-funcall (extern-alien
388                                     "wrapped_readlink"
389                                     (function (* char) c-string))
390                                    path)))
391     (if (null-alien ptr)
392         (values nil (get-errno))
393         (multiple-value-prog1
394             (values (with-alien ((c-string c-string ptr)) c-string)
395                     nil)
396           (free-alien ptr)))))
397
398 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
399 ;;; name and the file if this is the last link.
400 (defun unix-unlink (name)
401   (declare (type unix-pathname name))
402   (void-syscall ("unlink" c-string) name))
403
404 ;;; Return the name of the host machine as a string.
405 (defun unix-gethostname ()
406   (with-alien ((buf (array char 256)))
407     (syscall ("gethostname" (* char) int)
408              (cast buf c-string)
409              (cast buf (* char)) 256)))
410
411 (defun unix-setsid ()
412   (int-syscall ("setsid")))
413
414 ;;;; sys/ioctl.h
415
416 ;;; UNIX-IOCTL performs a variety of operations on open i/o
417 ;;; descriptors. See the UNIX Programmer's Manual for more
418 ;;; information.
419 (defun unix-ioctl (fd cmd arg)
420   (declare (type unix-fd fd)
421            (type (signed-byte 32) cmd))
422   (void-syscall ("ioctl" int int (* char)) fd cmd arg))
423 \f
424 ;;;; sys/resource.h
425
426 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
427 ;;;
428 ;;; This is like getrusage(2), except it returns only the system and
429 ;;; user time, and returns the seconds and microseconds as separate
430 ;;; values.
431 #!-sb-fluid (declaim (inline unix-fast-getrusage))
432 (defun unix-fast-getrusage (who)
433   (declare (values (member t)
434                    (unsigned-byte 31) (integer 0 1000000)
435                    (unsigned-byte 31) (integer 0 1000000)))
436   (with-alien ((usage (struct rusage)))
437     (syscall* ("getrusage" int (* (struct rusage)))
438               (values t
439                       (slot (slot usage 'ru-utime) 'tv-sec)
440                       (slot (slot usage 'ru-utime) 'tv-usec)
441                       (slot (slot usage 'ru-stime) 'tv-sec)
442                       (slot (slot usage 'ru-stime) 'tv-usec))
443               who (addr usage))))
444
445 ;;; Return information about the resource usage of the process
446 ;;; specified by WHO. WHO can be either the current process
447 ;;; (rusage_self) or all of the terminated child processes
448 ;;; (rusage_children). NIL and an error number is returned if the call
449 ;;; fails.
450 (defun unix-getrusage (who)
451   (with-alien ((usage (struct rusage)))
452     (syscall ("getrusage" int (* (struct rusage)))
453               (values t
454                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
455                          (slot (slot usage 'ru-utime) 'tv-usec))
456                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
457                          (slot (slot usage 'ru-stime) 'tv-usec))
458                       (slot usage 'ru-maxrss)
459                       (slot usage 'ru-ixrss)
460                       (slot usage 'ru-idrss)
461                       (slot usage 'ru-isrss)
462                       (slot usage 'ru-minflt)
463                       (slot usage 'ru-majflt)
464                       (slot usage 'ru-nswap)
465                       (slot usage 'ru-inblock)
466                       (slot usage 'ru-oublock)
467                       (slot usage 'ru-msgsnd)
468                       (slot usage 'ru-msgrcv)
469                       (slot usage 'ru-nsignals)
470                       (slot usage 'ru-nvcsw)
471                       (slot usage 'ru-nivcsw))
472               who (addr usage))))
473 \f
474 ;;;; sys/select.h
475
476 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
477
478 ;;; Perform the UNIX select(2) system call.
479 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
480 (defun unix-fast-select (num-descriptors
481                          read-fds write-fds exception-fds
482                          timeout-secs &optional (timeout-usecs 0))
483   (declare (type (integer 0 #.fd-setsize) num-descriptors)
484            (type (or (alien (* (struct fd-set))) null)
485                  read-fds write-fds exception-fds)
486            (type (or null (unsigned-byte 31)) timeout-secs)
487            (type (unsigned-byte 31) timeout-usecs))
488   ;; FIXME: CMU CL had
489   ;;   (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
490   ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
491   (with-alien ((tv (struct timeval)))
492     (when timeout-secs
493       (setf (slot tv 'tv-sec) timeout-secs)
494       (setf (slot tv 'tv-usec) timeout-usecs))
495     (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
496                   (* (struct fd-set)) (* (struct timeval)))
497                  num-descriptors read-fds write-fds exception-fds
498                  (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
499
500 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
501 ;;; to happen on one of them or to time out.
502 (defmacro num-to-fd-set (fdset num)
503   `(if (fixnump ,num)
504        (progn
505          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
506          ,@(loop for index upfrom 1 below (/ fd-setsize
507                                              sb!vm:n-machine-word-bits)
508              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
509        (progn
510          ,@(loop for index upfrom 0 below (/ fd-setsize
511                                              sb!vm:n-machine-word-bits)
512              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
513                             (ldb (byte sb!vm:n-machine-word-bits
514                                        ,(* index sb!vm:n-machine-word-bits))
515                                  ,num))))))
516
517 (defmacro fd-set-to-num (nfds fdset)
518   `(if (<= ,nfds sb!vm:n-machine-word-bits)
519        (deref (slot ,fdset 'fds-bits) 0)
520        (+ ,@(loop for index upfrom 0 below (/ fd-setsize
521                                               sb!vm:n-machine-word-bits)
522               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
523                             ,(* index sb!vm:n-machine-word-bits))))))
524
525 ;;; Examine the sets of descriptors passed as arguments to see whether
526 ;;; they are ready for reading and writing. See the UNIX Programmer's
527 ;;; Manual for more information.
528 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
529   (declare (type (integer 0 #.fd-setsize) nfds)
530            (type unsigned-byte rdfds wrfds xpfds)
531            (type (or (unsigned-byte 31) null) to-secs)
532            (type (unsigned-byte 31) to-usecs)
533            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
534   (with-alien ((tv (struct timeval))
535                (rdf (struct fd-set))
536                (wrf (struct fd-set))
537                (xpf (struct fd-set)))
538     (when to-secs
539       (setf (slot tv 'tv-sec) to-secs)
540      (setf (slot tv 'tv-usec) to-usecs))
541     (num-to-fd-set rdf rdfds)
542     (num-to-fd-set wrf wrfds)
543     (num-to-fd-set xpf xpfds)
544     (macrolet ((frob (lispvar alienvar)
545                  `(if (zerop ,lispvar)
546                       (int-sap 0)
547                       (alien-sap (addr ,alienvar)))))
548       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
549                 (* (struct fd-set)) (* (struct timeval)))
550                (values result
551                        (fd-set-to-num nfds rdf)
552                        (fd-set-to-num nfds wrf)
553                        (fd-set-to-num nfds xpf))
554                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
555                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
556 \f
557 ;;;; sys/stat.h
558
559 ;;; This is a structure defined in src/runtime/wrap.c, to look
560 ;;; basically like "struct stat" according to stat(2). It may not
561 ;;; actually correspond to the real in-memory stat structure that the
562 ;;; syscall uses, and that's OK. Linux in particular is packed full of
563 ;;; stat macros, and trying to keep Lisp code in correspondence with
564 ;;; it is more pain than it's worth, so we just let our C runtime
565 ;;; synthesize a nice consistent structure for us.
566 ;;;
567 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
568 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
569 ;;; those. We don't actually access that field anywhere, though, so
570 ;;; until we can get 64 bit alien support it'll do. Also note that
571 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
572 ;;; quantity on Alpha. And FIXME: "No one would want a file length
573 ;;; longer than 32 bits anyway, right?":-|
574 (define-alien-type nil
575   (struct wrapped_stat
576     #!-mips
577     (st-dev unsigned-int)              ; would be dev-t in a real stat
578     #!+mips
579     (st-dev unsigned-long)             ; this is _not_ a dev-t on mips
580     (st-ino ino-t)
581     (st-mode mode-t)
582     (st-nlink nlink-t)
583     (st-uid uid-t)
584     (st-gid gid-t)
585     #!-mips
586     (st-rdev unsigned-int)             ; would be dev-t in a real stat
587     #!+mips
588     (st-rdev unsigned-long)             ; this is _not_ a dev-t on mips
589     #!-mips
590     (st-size unsigned-int)              ; would be off-t in a real stat
591     #!+mips
592     (st-size off-t)
593     (st-blksize unsigned-long)
594     (st-blocks unsigned-long)
595     (st-atime time-t)
596     (st-mtime time-t)
597     (st-ctime time-t)))
598
599 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
600 ;;; family of Unix system calls
601 ;;;
602 ;;; FIXME: I think this should probably not be INLINE. However, when
603 ;;; this was not inline, it seemed to cause memory corruption
604 ;;; problems. My first guess is that it's a bug in the FFI code, where
605 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
606 ;;; around a call to a function returning >10 values. But I didn't try
607 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
608 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
609 ;;; output in the not-inlined case and see whether there's a problem,
610 ;;; and maybe even find a fix..
611 (declaim (inline %extract-stat-results))
612 (defun %extract-stat-results (wrapped-stat)
613   (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
614   (values t
615           (slot wrapped-stat 'st-dev)
616           (slot wrapped-stat 'st-ino)
617           (slot wrapped-stat 'st-mode)
618           (slot wrapped-stat 'st-nlink)
619           (slot wrapped-stat 'st-uid)
620           (slot wrapped-stat 'st-gid)
621           (slot wrapped-stat 'st-rdev)
622           (slot wrapped-stat 'st-size)
623           (slot wrapped-stat 'st-atime)
624           (slot wrapped-stat 'st-mtime)
625           (slot wrapped-stat 'st-ctime)
626           (slot wrapped-stat 'st-blksize)
627           (slot wrapped-stat 'st-blocks)))
628
629 ;;; Unix system calls in the stat(2) family are handled by calls to
630 ;;; C-level wrapper functions which copy all the raw "struct stat"
631 ;;; slots into the system-independent wrapped_stat format.
632 ;;;    stat(2) <->  stat_wrapper()
633 ;;;   fstat(2) <-> fstat_wrapper()
634 ;;;   lstat(2) <-> lstat_wrapper()
635 (defun unix-stat (name)
636   (declare (type unix-pathname name))
637   (with-alien ((buf (struct wrapped_stat)))
638     (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
639              (%extract-stat-results (addr buf))
640              name (addr buf))))
641 (defun unix-lstat (name)
642   (declare (type unix-pathname name))
643   (with-alien ((buf (struct wrapped_stat)))
644     (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
645              (%extract-stat-results (addr buf))
646              name (addr buf))))
647 (defun unix-fstat (fd)
648   (declare (type unix-fd fd))
649   (with-alien ((buf (struct wrapped_stat)))
650     (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
651              (%extract-stat-results (addr buf))
652              fd (addr buf))))
653 \f
654 ;;;; time.h
655
656 ;; the POSIX.4 structure for a time value. This is like a "struct
657 ;; timeval" but has nanoseconds instead of microseconds.
658 (define-alien-type nil
659     (struct timespec
660             (tv-sec long)   ; seconds
661             (tv-nsec long))) ; nanoseconds
662
663 ;; used by other time functions
664 (define-alien-type nil
665     (struct tm
666             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
667             (tm-min int)   ; Minutes.   [0-59]
668             (tm-hour int)  ; Hours.     [0-23]
669             (tm-mday int)  ; Day.       [1-31]
670             (tm-mon int)   ; Month.     [0-11]
671             (tm-year int)  ; Year - 1900.
672             (tm-wday int)  ; Day of week. [0-6]
673             (tm-yday int)  ; Days in year. [0-365]
674             (tm-isdst int) ; DST.       [-1/0/1]
675             (tm-gmtoff long) ;  Seconds east of UTC.
676             (tm-zone c-string))) ; Timezone abbreviation.
677
678 (define-alien-routine get-timezone sb!alien:void
679   (when sb!alien:long :in)
680   (seconds-west sb!alien:int :out)
681   (daylight-savings-p sb!alien:boolean :out))
682
683 (defun nanosleep (secs nsecs)
684   (with-alien ((req (struct timespec))
685                (rem (struct timespec)))
686     (setf (slot req 'tv-sec) secs)
687     (setf (slot req 'tv-nsec) nsecs)
688     (loop while (eql sb!unix:eintr
689                      (nth-value 1
690                                 (int-syscall ("nanosleep" (* (struct timespec))
691                                                           (* (struct timespec)))
692                                              (addr req) (addr rem))))
693        do (rotatef req rem))))
694
695 (defun unix-get-seconds-west (secs)
696   (multiple-value-bind (ignore seconds dst) (get-timezone secs)
697     (declare (ignore ignore) (ignore dst))
698     (values seconds)))
699 \f
700 ;;;; sys/time.h
701
702 ;;; Structure crudely representing a timezone. KLUDGE: This is
703 ;;; obsolete and should never be used.
704 (define-alien-type nil
705   (struct timezone
706     (tz-minuteswest int)                ; minutes west of Greenwich
707     (tz-dsttime int)))                  ; type of dst correction
708
709 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
710 ;;; and microseconds of the current time of day, the timezone (in
711 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
712 ;;; doesn't work, it returns NIL and the errno.
713 #!-sb-fluid (declaim (inline unix-gettimeofday))
714 (defun unix-gettimeofday ()
715   (with-alien ((tv (struct timeval))
716                (tz (struct timezone)))
717     (syscall* ("gettimeofday" (* (struct timeval))
718                               (* (struct timezone)))
719               (values t
720                       (slot tv 'tv-sec)
721                       (slot tv 'tv-usec)
722                       (slot tz 'tz-minuteswest)
723                       (slot tz 'tz-dsttime))
724               (addr tv)
725               (addr tz))))
726 \f
727
728 ;; Type of the second argument to `getitimer' and
729 ;; the second and third arguments `setitimer'.
730 (define-alien-type nil
731   (struct itimerval
732     (it-interval (struct timeval))      ; timer interval
733     (it-value (struct timeval))))       ; current value
734
735 (defconstant itimer-real 0)
736 (defconstant itimer-virtual 1)
737 (defconstant itimer-prof 2)
738
739 (defun unix-getitimer (which)
740   "Unix-getitimer returns the INTERVAL and VALUE slots of one of
741    three system timers (:real :virtual or :profile). On success,
742    unix-getitimer returns 5 values,
743    T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
744   (declare (type (member :real :virtual :profile) which)
745            (values t
746                    (unsigned-byte 29) (mod 1000000)
747                    (unsigned-byte 29) (mod 1000000)))
748   (let ((which (ecase which
749                  (:real itimer-real)
750                  (:virtual itimer-virtual)
751                  (:profile itimer-prof))))
752     (with-alien ((itv (struct itimerval)))
753       (syscall* ("getitimer" int (* (struct itimerval)))
754                 (values t
755                         (slot (slot itv 'it-interval) 'tv-sec)
756                         (slot (slot itv 'it-interval) 'tv-usec)
757                         (slot (slot itv 'it-value) 'tv-sec)
758                         (slot (slot itv 'it-value) 'tv-usec))
759                 which (alien-sap (addr itv))))))
760
761 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
762   " Unix-setitimer sets the INTERVAL and VALUE slots of one of
763    three system timers (:real :virtual or :profile). A SIGALRM signal
764    will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
765    when non-zero, is <seconds+microseconds> to be loaded each time
766    the timer expires. Setting INTERVAL and VALUE to zero disables
767    the timer. See the Unix man page for more details. On success,
768    unix-setitimer returns the old contents of the INTERVAL and VALUE
769    slots as in unix-getitimer."
770   (declare (type (member :real :virtual :profile) which)
771            (type (unsigned-byte 29) int-secs val-secs)
772            (type (integer 0 (1000000)) int-usec val-usec)
773            (values t
774                    (unsigned-byte 29) (mod 1000000)
775                    (unsigned-byte 29) (mod 1000000)))
776   (let ((which (ecase which
777                  (:real itimer-real)
778                  (:virtual itimer-virtual)
779                  (:profile itimer-prof))))
780     (with-alien ((itvn (struct itimerval))
781                  (itvo (struct itimerval)))
782       (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
783             (slot (slot itvn 'it-interval) 'tv-usec) int-usec
784             (slot (slot itvn 'it-value   ) 'tv-sec ) val-secs
785             (slot (slot itvn 'it-value   ) 'tv-usec) val-usec)
786       (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
787                 (values t
788                         (slot (slot itvo 'it-interval) 'tv-sec)
789                         (slot (slot itvo 'it-interval) 'tv-usec)
790                         (slot (slot itvo 'it-value) 'tv-sec)
791                         (slot (slot itvo 'it-value) 'tv-usec))
792                 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
793
794 \f
795 ;;; FIXME: Many Unix error code definitions were deleted from the old
796 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
797 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
798 ;;; unused symbols in package exports, but if I don't, there are
799 ;;; enough of them all in one place here that they should probably be
800 ;;; removed by hand.
801 \f
802 ;;;; support routines for dealing with Unix pathnames
803
804 (defun unix-file-kind (name &optional check-for-links)
805   #!+sb-doc
806   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
807   (declare (simple-base-string name))
808   (multiple-value-bind (res dev ino mode)
809       (if check-for-links (unix-lstat name) (unix-stat name))
810     (declare (type (or fixnum null) mode)
811              (ignore dev ino))
812     (when res
813       (let ((kind (logand mode s-ifmt)))
814         (cond ((eql kind s-ifdir) :directory)
815               ((eql kind s-ifreg) :file)
816               ((eql kind s-iflnk) :link)
817               (t :special))))))
818
819 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
820 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
821 (defun relative-unix-pathname? (pathname)
822   (declare (type simple-string pathname))
823   (or (zerop (length pathname))
824       (char/= (schar pathname 0) #\/)))
825
826 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
827 ;;; already be a complete absolute Unix pathname, since at least in
828 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
829 ;;; paths have been converted to absolute paths, so we don't need to
830 ;;; try to handle any more generality than that.
831 (defun unix-resolve-links (pathname)
832   (declare (type simple-base-string pathname))
833   (aver (not (relative-unix-pathname? pathname)))
834   ;; KLUDGE: readlink and lstat are unreliable if given symlinks
835   ;; ending in slashes -- fix the issue here instead of waiting for
836   ;; libc to change...
837   (let ((len (length pathname)))
838     (when (and (plusp len) (eql #\/ (schar pathname (1- len))))
839       (setf pathname (subseq pathname 0 (1- len)))))
840   (/noshow "entering UNIX-RESOLVE-LINKS")
841   (loop with previous-pathnames = nil do
842        (/noshow pathname previous-pathnames)
843        (let ((link (unix-readlink pathname)))
844           (/noshow link)
845           ;; Unlike the old CMU CL code, we handle a broken symlink by
846           ;; returning the link itself. That way, CL:TRUENAME on a
847           ;; broken link returns the link itself, so that CL:DIRECTORY
848           ;; can return broken links, so that even without
849           ;; Unix-specific extensions to do interesting things with
850           ;; them, at least Lisp programs can see them and, if
851           ;; necessary, delete them. (This is handy e.g. when your
852           ;; managed-by-Lisp directories are visited by Emacs, which
853           ;; creates broken links as notes to itself.)
854           (if (null link)
855               (return pathname)
856               (let ((new-pathname
857                      (unix-simplify-pathname
858                       (if (relative-unix-pathname? link)
859                           (let* ((dir-len (1+ (position #\/
860                                                         pathname
861                                                         :from-end t)))
862                                  (dir (subseq pathname 0 dir-len)))
863                             (/noshow dir)
864                             (concatenate 'base-string dir link))
865                           link))))
866                 (if (unix-file-kind new-pathname)
867                     (setf pathname new-pathname)
868                     (return pathname)))))
869         ;; To generalize the principle that even if portable Lisp code
870         ;; can't do anything interesting with a broken symlink, at
871         ;; least it should be able to see and delete it, when we
872         ;; detect a cyclic link, we return the link itself. (So even
873         ;; though portable Lisp code can't do anything interesting
874         ;; with a cyclic link, at least it can see it and delete it.)
875         (if (member pathname previous-pathnames :test #'string=)
876             (return pathname)
877             (push pathname previous-pathnames))))
878
879 (defun unix-simplify-pathname (src)
880   (declare (type simple-base-string src))
881   (let* ((src-len (length src))
882          (dst (make-string src-len :element-type 'base-char))
883          (dst-len 0)
884          (dots 0)
885          (last-slash nil))
886     (macrolet ((deposit (char)
887                  `(progn
888                     (setf (schar dst dst-len) ,char)
889                     (incf dst-len))))
890       (dotimes (src-index src-len)
891         (let ((char (schar src src-index)))
892           (cond ((char= char #\.)
893                  (when dots
894                    (incf dots))
895                  (deposit char))
896                 ((char= char #\/)
897                  (case dots
898                    (0
899                     ;; either ``/...' or ``...//...'
900                     (unless last-slash
901                       (setf last-slash dst-len)
902                       (deposit char)))
903                    (1
904                     ;; either ``./...'' or ``..././...''
905                     (decf dst-len))
906                    (2
907                     ;; We've found ..
908                     (cond
909                      ((and last-slash (not (zerop last-slash)))
910                       ;; There is something before this ..
911                       (let ((prev-prev-slash
912                              (position #\/ dst :end last-slash :from-end t)))
913                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
914                                        last-slash)
915                                     (char= (schar dst (- last-slash 2)) #\.)
916                                     (char= (schar dst (1- last-slash)) #\.))
917                                ;; The something before this .. is another ..
918                                (deposit char)
919                                (setf last-slash dst-len))
920                               (t
921                                ;; The something is some directory or other.
922                                (setf dst-len
923                                      (if prev-prev-slash
924                                          (1+ prev-prev-slash)
925                                          0))
926                                (setf last-slash prev-prev-slash)))))
927                      (t
928                       ;; There is nothing before this .., so we need to keep it
929                       (setf last-slash dst-len)
930                       (deposit char))))
931                    (t
932                     ;; something other than a dot between slashes
933                     (setf last-slash dst-len)
934                     (deposit char)))
935                  (setf dots 0))
936                 (t
937                  (setf dots nil)
938                  (setf (schar dst dst-len) char)
939                  (incf dst-len))))))
940     (when (and last-slash (not (zerop last-slash)))
941       (case dots
942         (1
943          ;; We've got  ``foobar/.''
944          (decf dst-len))
945         (2
946          ;; We've got ``foobar/..''
947          (unless (and (>= last-slash 2)
948                       (char= (schar dst (1- last-slash)) #\.)
949                       (char= (schar dst (- last-slash 2)) #\.)
950                       (or (= last-slash 2)
951                           (char= (schar dst (- last-slash 3)) #\/)))
952            (let ((prev-prev-slash
953                   (position #\/ dst :end last-slash :from-end t)))
954              (if prev-prev-slash
955                  (setf dst-len (1+ prev-prev-slash))
956                  (return-from unix-simplify-pathname
957                    (coerce "./" 'simple-base-string))))))))
958     (cond ((zerop dst-len)
959            "./")
960           ((= dst-len src-len)
961            dst)
962           (t
963            (subseq dst 0 dst-len)))))
964 \f
965 ;;;; A magic constant for wait3().
966 ;;;;
967 ;;;; FIXME: This used to be defined in run-program.lisp as
968 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
969 ;;;; According to some of the man pages, the #o177 is part of the API
970 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
971 ;;;; the headers that may or may not be the same thing. To be
972 ;;;; investigated. -- CSR, 2002-03-25
973 (defconstant wstopped #o177)
974
975 \f
976 ;;;; stuff not yet found in the header files
977 ;;;;
978 ;;;; Abandon all hope who enters here...
979
980 ;;; not checked for linux...
981 (defmacro fd-set (offset fd-set)
982   (let ((word (gensym))
983         (bit (gensym)))
984     `(multiple-value-bind (,word ,bit) (floor ,offset
985                                               sb!vm:n-machine-word-bits)
986        (setf (deref (slot ,fd-set 'fds-bits) ,word)
987              (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
988                                 (ash 1 ,bit))
989                      (deref (slot ,fd-set 'fds-bits) ,word))))))
990
991 ;;; not checked for linux...
992 (defmacro fd-clr (offset fd-set)
993   (let ((word (gensym))
994         (bit (gensym)))
995     `(multiple-value-bind (,word ,bit) (floor ,offset
996                                               sb!vm:n-machine-word-bits)
997        (setf (deref (slot ,fd-set 'fds-bits) ,word)
998              (logand (deref (slot ,fd-set 'fds-bits) ,word)
999                      (sb!kernel:word-logical-not
1000                       (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1001                                  (ash 1 ,bit))))))))
1002
1003 ;;; not checked for linux...
1004 (defmacro fd-isset (offset fd-set)
1005   (let ((word (gensym))
1006         (bit (gensym)))
1007     `(multiple-value-bind (,word ,bit) (floor ,offset
1008                                               sb!vm:n-machine-word-bits)
1009        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1010
1011 ;;; not checked for linux...
1012 (defmacro fd-zero (fd-set)
1013   `(progn
1014      ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
1015          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))