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