0.9.7.31:
[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 ;;; Duplicate an existing file descriptor (given as the argument) and
331 ;;; return it. If FD is not a valid file descriptor, NIL and an error
332 ;;; number are returned.
333 (defun unix-dup (fd)
334   (declare (type unix-fd fd))
335   (int-syscall ("dup" int) fd))
336
337 ;;; Terminate the current process with an optional error code. If
338 ;;; successful, the call doesn't return. If unsuccessful, the call
339 ;;; returns NIL and an error number.
340 (defun unix-exit (&optional (code 0))
341   (declare (type (signed-byte 32) code))
342   (void-syscall ("exit" int) code))
343
344 ;;; Return the process id of the current process.
345 (define-alien-routine ("getpid" unix-getpid) int)
346
347 ;;; Return the real user id associated with the current process.
348 (define-alien-routine ("getuid" unix-getuid) int)
349
350 ;;; Translate a user id into a login name.
351 (defun uid-username (uid)
352   (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
353                                                        (function (* char) int))
354                                          uid))
355       (error "found no match for Unix uid=~S" uid)))
356
357 ;;; Return the namestring of the home directory, being careful to
358 ;;; include a trailing #\/
359 (defun uid-homedir (uid)
360   (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
361                                                        (function (* char) int))
362                                          uid))
363       (error "failed to resolve home directory for Unix uid=~S" uid)))
364
365 ;;; Invoke readlink(2) on the file name specified by PATH. Return
366 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
367 ;;; failure.
368 (defun unix-readlink (path)
369   (declare (type unix-pathname path))
370   (with-alien ((ptr (* char)
371                     (alien-funcall (extern-alien
372                                     "wrapped_readlink"
373                                     (function (* char) c-string))
374                                    path)))
375     (if (null-alien ptr)
376         (values nil (get-errno))
377         (multiple-value-prog1
378             (values (with-alien ((c-string c-string ptr)) c-string)
379                     nil)
380           (free-alien ptr)))))
381
382 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
383 ;;; name and the file if this is the last link.
384 (defun unix-unlink (name)
385   (declare (type unix-pathname name))
386   (void-syscall ("unlink" c-string) name))
387
388 ;;; Return the name of the host machine as a string.
389 (defun unix-gethostname ()
390   (with-alien ((buf (array char 256)))
391     (syscall ("gethostname" (* char) int)
392              (cast buf c-string)
393              (cast buf (* char)) 256)))
394
395 (defun unix-setsid ()
396   (int-syscall ("setsid")))
397
398 ;;;; sys/ioctl.h
399
400 ;;; UNIX-IOCTL performs a variety of operations on open i/o
401 ;;; descriptors. See the UNIX Programmer's Manual for more
402 ;;; information.
403 (defun unix-ioctl (fd cmd arg)
404   (declare (type unix-fd fd)
405            (type (signed-byte 32) cmd))
406   (void-syscall ("ioctl" int int (* char)) fd cmd arg))
407 \f
408 ;;;; sys/resource.h
409
410 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
411 ;;;
412 ;;; This is like getrusage(2), except it returns only the system and
413 ;;; user time, and returns the seconds and microseconds as separate
414 ;;; values.
415 #!-sb-fluid (declaim (inline unix-fast-getrusage))
416 (defun unix-fast-getrusage (who)
417   (declare (values (member t)
418                    (unsigned-byte 31) (integer 0 1000000)
419                    (unsigned-byte 31) (integer 0 1000000)))
420   (with-alien ((usage (struct rusage)))
421     (syscall* ("getrusage" int (* (struct rusage)))
422               (values t
423                       (slot (slot usage 'ru-utime) 'tv-sec)
424                       (slot (slot usage 'ru-utime) 'tv-usec)
425                       (slot (slot usage 'ru-stime) 'tv-sec)
426                       (slot (slot usage 'ru-stime) 'tv-usec))
427               who (addr usage))))
428
429 ;;; Return information about the resource usage of the process
430 ;;; specified by WHO. WHO can be either the current process
431 ;;; (rusage_self) or all of the terminated child processes
432 ;;; (rusage_children). NIL and an error number is returned if the call
433 ;;; fails.
434 (defun unix-getrusage (who)
435   (with-alien ((usage (struct rusage)))
436     (syscall ("getrusage" int (* (struct rusage)))
437               (values t
438                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
439                          (slot (slot usage 'ru-utime) 'tv-usec))
440                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
441                          (slot (slot usage 'ru-stime) 'tv-usec))
442                       (slot usage 'ru-maxrss)
443                       (slot usage 'ru-ixrss)
444                       (slot usage 'ru-idrss)
445                       (slot usage 'ru-isrss)
446                       (slot usage 'ru-minflt)
447                       (slot usage 'ru-majflt)
448                       (slot usage 'ru-nswap)
449                       (slot usage 'ru-inblock)
450                       (slot usage 'ru-oublock)
451                       (slot usage 'ru-msgsnd)
452                       (slot usage 'ru-msgrcv)
453                       (slot usage 'ru-nsignals)
454                       (slot usage 'ru-nvcsw)
455                       (slot usage 'ru-nivcsw))
456               who (addr usage))))
457 \f
458 ;;;; sys/select.h
459
460 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
461
462 ;;; Perform the UNIX select(2) system call.
463 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
464 (defun unix-fast-select (num-descriptors
465                          read-fds write-fds exception-fds
466                          timeout-secs &optional (timeout-usecs 0))
467   (declare (type (integer 0 #.fd-setsize) num-descriptors)
468            (type (or (alien (* (struct fd-set))) null)
469                  read-fds write-fds exception-fds)
470            (type (or null (unsigned-byte 31)) timeout-secs)
471            (type (unsigned-byte 31) timeout-usecs))
472   ;; FIXME: CMU CL had
473   ;;   (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
474   ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
475   (with-alien ((tv (struct timeval)))
476     (when timeout-secs
477       (setf (slot tv 'tv-sec) timeout-secs)
478       (setf (slot tv 'tv-usec) timeout-usecs))
479     (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
480                   (* (struct fd-set)) (* (struct timeval)))
481                  num-descriptors read-fds write-fds exception-fds
482                  (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
483
484 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
485 ;;; to happen on one of them or to time out.
486 (defmacro num-to-fd-set (fdset num)
487   `(if (fixnump ,num)
488        (progn
489          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
490          ,@(loop for index upfrom 1 below (/ fd-setsize
491                                              sb!vm:n-machine-word-bits)
492              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
493        (progn
494          ,@(loop for index upfrom 0 below (/ fd-setsize
495                                              sb!vm:n-machine-word-bits)
496              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
497                             (ldb (byte sb!vm:n-machine-word-bits
498                                        ,(* index sb!vm:n-machine-word-bits))
499                                  ,num))))))
500
501 (defmacro fd-set-to-num (nfds fdset)
502   `(if (<= ,nfds sb!vm:n-machine-word-bits)
503        (deref (slot ,fdset 'fds-bits) 0)
504        (+ ,@(loop for index upfrom 0 below (/ fd-setsize
505                                               sb!vm:n-machine-word-bits)
506               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
507                             ,(* index sb!vm:n-machine-word-bits))))))
508
509 ;;; Examine the sets of descriptors passed as arguments to see whether
510 ;;; they are ready for reading and writing. See the UNIX Programmer's
511 ;;; Manual for more information.
512 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
513   (declare (type (integer 0 #.fd-setsize) nfds)
514            (type unsigned-byte rdfds wrfds xpfds)
515            (type (or (unsigned-byte 31) null) to-secs)
516            (type (unsigned-byte 31) to-usecs)
517            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
518   (with-alien ((tv (struct timeval))
519                (rdf (struct fd-set))
520                (wrf (struct fd-set))
521                (xpf (struct fd-set)))
522     (when to-secs
523       (setf (slot tv 'tv-sec) to-secs)
524      (setf (slot tv 'tv-usec) to-usecs))
525     (num-to-fd-set rdf rdfds)
526     (num-to-fd-set wrf wrfds)
527     (num-to-fd-set xpf xpfds)
528     (macrolet ((frob (lispvar alienvar)
529                  `(if (zerop ,lispvar)
530                       (int-sap 0)
531                       (alien-sap (addr ,alienvar)))))
532       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
533                 (* (struct fd-set)) (* (struct timeval)))
534                (values result
535                        (fd-set-to-num nfds rdf)
536                        (fd-set-to-num nfds wrf)
537                        (fd-set-to-num nfds xpf))
538                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
539                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
540 \f
541 ;;;; sys/stat.h
542
543 ;;; This is a structure defined in src/runtime/wrap.c, to look
544 ;;; basically like "struct stat" according to stat(2). It may not
545 ;;; actually correspond to the real in-memory stat structure that the
546 ;;; syscall uses, and that's OK. Linux in particular is packed full of
547 ;;; stat macros, and trying to keep Lisp code in correspondence with
548 ;;; it is more pain than it's worth, so we just let our C runtime
549 ;;; synthesize a nice consistent structure for us.
550 ;;;
551 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
552 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
553 ;;; those. We don't actually access that field anywhere, though, so
554 ;;; until we can get 64 bit alien support it'll do. Also note that
555 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
556 ;;; quantity on Alpha. And FIXME: "No one would want a file length
557 ;;; longer than 32 bits anyway, right?":-|
558 (define-alien-type nil
559   (struct wrapped_stat
560     #!-mips
561     (st-dev unsigned-int)              ; would be dev-t in a real stat
562     #!+mips
563     (st-dev unsigned-long)             ; this is _not_ a dev-t on mips
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     #!-mips
570     (st-rdev unsigned-int)             ; would be dev-t in a real stat
571     #!+mips
572     (st-rdev unsigned-long)             ; this is _not_ a dev-t on mips
573     #!-mips
574     (st-size unsigned-int)              ; would be off-t in a real stat
575     #!+mips
576     (st-size off-t)
577     (st-blksize unsigned-long)
578     (st-blocks unsigned-long)
579     (st-atime time-t)
580     (st-mtime time-t)
581     (st-ctime time-t)))
582
583 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
584 ;;; family of Unix system calls
585 ;;;
586 ;;; FIXME: I think this should probably not be INLINE. However, when
587 ;;; this was not inline, it seemed to cause memory corruption
588 ;;; problems. My first guess is that it's a bug in the FFI code, where
589 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
590 ;;; around a call to a function returning >10 values. But I didn't try
591 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
592 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
593 ;;; output in the not-inlined case and see whether there's a problem,
594 ;;; and maybe even find a fix..
595 (declaim (inline %extract-stat-results))
596 (defun %extract-stat-results (wrapped-stat)
597   (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
598   (values t
599           (slot wrapped-stat 'st-dev)
600           (slot wrapped-stat 'st-ino)
601           (slot wrapped-stat 'st-mode)
602           (slot wrapped-stat 'st-nlink)
603           (slot wrapped-stat 'st-uid)
604           (slot wrapped-stat 'st-gid)
605           (slot wrapped-stat 'st-rdev)
606           (slot wrapped-stat 'st-size)
607           (slot wrapped-stat 'st-atime)
608           (slot wrapped-stat 'st-mtime)
609           (slot wrapped-stat 'st-ctime)
610           (slot wrapped-stat 'st-blksize)
611           (slot wrapped-stat 'st-blocks)))
612
613 ;;; Unix system calls in the stat(2) family are handled by calls to
614 ;;; C-level wrapper functions which copy all the raw "struct stat"
615 ;;; slots into the system-independent wrapped_stat format.
616 ;;;    stat(2) <->  stat_wrapper()
617 ;;;   fstat(2) <-> fstat_wrapper()
618 ;;;   lstat(2) <-> lstat_wrapper()
619 (defun unix-stat (name)
620   (declare (type unix-pathname name))
621   (with-alien ((buf (struct wrapped_stat)))
622     (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
623              (%extract-stat-results (addr buf))
624              name (addr buf))))
625 (defun unix-lstat (name)
626   (declare (type unix-pathname name))
627   (with-alien ((buf (struct wrapped_stat)))
628     (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
629              (%extract-stat-results (addr buf))
630              name (addr buf))))
631 (defun unix-fstat (fd)
632   (declare (type unix-fd fd))
633   (with-alien ((buf (struct wrapped_stat)))
634     (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
635              (%extract-stat-results (addr buf))
636              fd (addr buf))))
637 \f
638 ;;;; time.h
639
640 ;; the POSIX.4 structure for a time value. This is like a "struct
641 ;; timeval" but has nanoseconds instead of microseconds.
642 (define-alien-type nil
643     (struct timespec
644             (tv-sec long)   ; seconds
645             (tv-nsec long))) ; nanoseconds
646
647 ;; used by other time functions
648 (define-alien-type nil
649     (struct tm
650             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
651             (tm-min int)   ; Minutes.   [0-59]
652             (tm-hour int)  ; Hours.     [0-23]
653             (tm-mday int)  ; Day.       [1-31]
654             (tm-mon int)   ; Month.     [0-11]
655             (tm-year int)  ; Year - 1900.
656             (tm-wday int)  ; Day of week. [0-6]
657             (tm-yday int)  ; Days in year. [0-365]
658             (tm-isdst int) ; DST.       [-1/0/1]
659             (tm-gmtoff long) ;  Seconds east of UTC.
660             (tm-zone c-string))) ; Timezone abbreviation.
661
662 (define-alien-routine get-timezone sb!alien:void
663   (when sb!alien:long :in)
664   (seconds-west sb!alien:int :out)
665   (daylight-savings-p sb!alien:boolean :out))
666
667 (defun nanosleep (secs nsecs)
668   (with-alien ((req (struct timespec))
669                (rem (struct timespec)))
670     (setf (slot req 'tv-sec) secs)
671     (setf (slot req 'tv-nsec) nsecs)
672     (loop while (eql sb!unix:eintr
673                      (nth-value 1
674                                 (int-syscall ("nanosleep" (* (struct timespec))
675                                                           (* (struct timespec)))
676                                              (addr req) (addr rem))))
677        do (rotatef req rem))))
678
679 (defun unix-get-seconds-west (secs)
680   (multiple-value-bind (ignore seconds dst) (get-timezone secs)
681     (declare (ignore ignore) (ignore dst))
682     (values seconds)))
683 \f
684 ;;;; sys/time.h
685
686 ;;; Structure crudely representing a timezone. KLUDGE: This is
687 ;;; obsolete and should never be used.
688 (define-alien-type nil
689   (struct timezone
690     (tz-minuteswest int)                ; minutes west of Greenwich
691     (tz-dsttime int)))                  ; type of dst correction
692
693 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
694 ;;; and microseconds of the current time of day, the timezone (in
695 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
696 ;;; doesn't work, it returns NIL and the errno.
697 #!-sb-fluid (declaim (inline unix-gettimeofday))
698 (defun unix-gettimeofday ()
699   (with-alien ((tv (struct timeval))
700                (tz (struct timezone)))
701     (syscall* ("gettimeofday" (* (struct timeval))
702                               (* (struct timezone)))
703               (values t
704                       (slot tv 'tv-sec)
705                       (slot tv 'tv-usec)
706                       (slot tz 'tz-minuteswest)
707                       (slot tz 'tz-dsttime))
708               (addr tv)
709               (addr tz))))
710 \f
711
712 ;; Type of the second argument to `getitimer' and
713 ;; the second and third arguments `setitimer'.
714 (define-alien-type nil
715   (struct itimerval
716     (it-interval (struct timeval))      ; timer interval
717     (it-value (struct timeval))))       ; current value
718
719 (defconstant itimer-real 0)
720 (defconstant itimer-virtual 1)
721 (defconstant itimer-prof 2)
722
723 (defun unix-getitimer (which)
724   "Unix-getitimer returns the INTERVAL and VALUE slots of one of
725    three system timers (:real :virtual or :profile). On success,
726    unix-getitimer returns 5 values,
727    T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
728   (declare (type (member :real :virtual :profile) which)
729            (values t
730                    (unsigned-byte 29) (mod 1000000)
731                    (unsigned-byte 29) (mod 1000000)))
732   (let ((which (ecase which
733                  (:real itimer-real)
734                  (:virtual itimer-virtual)
735                  (:profile itimer-prof))))
736     (with-alien ((itv (struct itimerval)))
737       (syscall* ("getitimer" int (* (struct itimerval)))
738                 (values t
739                         (slot (slot itv 'it-interval) 'tv-sec)
740                         (slot (slot itv 'it-interval) 'tv-usec)
741                         (slot (slot itv 'it-value) 'tv-sec)
742                         (slot (slot itv 'it-value) 'tv-usec))
743                 which (alien-sap (addr itv))))))
744
745 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
746   " Unix-setitimer sets the INTERVAL and VALUE slots of one of
747    three system timers (:real :virtual or :profile). A SIGALRM signal
748    will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
749    when non-zero, is <seconds+microseconds> to be loaded each time
750    the timer expires. Setting INTERVAL and VALUE to zero disables
751    the timer. See the Unix man page for more details. On success,
752    unix-setitimer returns the old contents of the INTERVAL and VALUE
753    slots as in unix-getitimer."
754   (declare (type (member :real :virtual :profile) which)
755            (type (unsigned-byte 29) int-secs val-secs)
756            (type (integer 0 (1000000)) int-usec val-usec)
757            (values t
758                    (unsigned-byte 29) (mod 1000000)
759                    (unsigned-byte 29) (mod 1000000)))
760   (let ((which (ecase which
761                  (:real itimer-real)
762                  (:virtual itimer-virtual)
763                  (:profile itimer-prof))))
764     (with-alien ((itvn (struct itimerval))
765                  (itvo (struct itimerval)))
766       (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
767             (slot (slot itvn 'it-interval) 'tv-usec) int-usec
768             (slot (slot itvn 'it-value   ) 'tv-sec ) val-secs
769             (slot (slot itvn 'it-value   ) 'tv-usec) val-usec)
770       (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
771                 (values t
772                         (slot (slot itvo 'it-interval) 'tv-sec)
773                         (slot (slot itvo 'it-interval) 'tv-usec)
774                         (slot (slot itvo 'it-value) 'tv-sec)
775                         (slot (slot itvo 'it-value) 'tv-usec))
776                 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
777
778 \f
779 ;;; FIXME: Many Unix error code definitions were deleted from the old
780 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
781 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
782 ;;; unused symbols in package exports, but if I don't, there are
783 ;;; enough of them all in one place here that they should probably be
784 ;;; removed by hand.
785 \f
786 ;;;; support routines for dealing with Unix pathnames
787
788 (defun unix-file-kind (name &optional check-for-links)
789   #!+sb-doc
790   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
791   (declare (simple-base-string name))
792   (multiple-value-bind (res dev ino mode)
793       (if check-for-links (unix-lstat name) (unix-stat name))
794     (declare (type (or fixnum null) mode)
795              (ignore dev ino))
796     (when res
797       (let ((kind (logand mode s-ifmt)))
798         (cond ((eql kind s-ifdir) :directory)
799               ((eql kind s-ifreg) :file)
800               ((eql kind s-iflnk) :link)
801               (t :special))))))
802
803 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
804 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
805 (defun relative-unix-pathname? (pathname)
806   (declare (type simple-string pathname))
807   (or (zerop (length pathname))
808       (char/= (schar pathname 0) #\/)))
809
810 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
811 ;;; already be a complete absolute Unix pathname, since at least in
812 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
813 ;;; paths have been converted to absolute paths, so we don't need to
814 ;;; try to handle any more generality than that.
815 (defun unix-resolve-links (pathname)
816   (declare (type simple-base-string pathname))
817   (aver (not (relative-unix-pathname? pathname)))
818   ;; KLUDGE: readlink and lstat are unreliable if given symlinks
819   ;; ending in slashes -- fix the issue here instead of waiting for
820   ;; libc to change...
821   (let ((len (length pathname)))
822     (when (and (plusp len) (eql #\/ (schar pathname (1- len))))
823       (setf pathname (subseq pathname 0 (1- len)))))
824   (/noshow "entering UNIX-RESOLVE-LINKS")
825   (loop with previous-pathnames = nil do
826        (/noshow pathname previous-pathnames)
827        (let ((link (unix-readlink pathname)))
828           (/noshow link)
829           ;; Unlike the old CMU CL code, we handle a broken symlink by
830           ;; returning the link itself. That way, CL:TRUENAME on a
831           ;; broken link returns the link itself, so that CL:DIRECTORY
832           ;; can return broken links, so that even without
833           ;; Unix-specific extensions to do interesting things with
834           ;; them, at least Lisp programs can see them and, if
835           ;; necessary, delete them. (This is handy e.g. when your
836           ;; managed-by-Lisp directories are visited by Emacs, which
837           ;; creates broken links as notes to itself.)
838           (if (null link)
839               (return pathname)
840               (let ((new-pathname
841                      (unix-simplify-pathname
842                       (if (relative-unix-pathname? link)
843                           (let* ((dir-len (1+ (position #\/
844                                                         pathname
845                                                         :from-end t)))
846                                  (dir (subseq pathname 0 dir-len)))
847                             (/noshow dir)
848                             (concatenate 'base-string dir link))
849                           link))))
850                 (if (unix-file-kind new-pathname)
851                     (setf pathname new-pathname)
852                     (return pathname)))))
853         ;; To generalize the principle that even if portable Lisp code
854         ;; can't do anything interesting with a broken symlink, at
855         ;; least it should be able to see and delete it, when we
856         ;; detect a cyclic link, we return the link itself. (So even
857         ;; though portable Lisp code can't do anything interesting
858         ;; with a cyclic link, at least it can see it and delete it.)
859         (if (member pathname previous-pathnames :test #'string=)
860             (return pathname)
861             (push pathname previous-pathnames))))
862
863 (defun unix-simplify-pathname (src)
864   (declare (type simple-base-string src))
865   (let* ((src-len (length src))
866          (dst (make-string src-len :element-type 'base-char))
867          (dst-len 0)
868          (dots 0)
869          (last-slash nil))
870     (macrolet ((deposit (char)
871                  `(progn
872                     (setf (schar dst dst-len) ,char)
873                     (incf dst-len))))
874       (dotimes (src-index src-len)
875         (let ((char (schar src src-index)))
876           (cond ((char= char #\.)
877                  (when dots
878                    (incf dots))
879                  (deposit char))
880                 ((char= char #\/)
881                  (case dots
882                    (0
883                     ;; either ``/...' or ``...//...'
884                     (unless last-slash
885                       (setf last-slash dst-len)
886                       (deposit char)))
887                    (1
888                     ;; either ``./...'' or ``..././...''
889                     (decf dst-len))
890                    (2
891                     ;; We've found ..
892                     (cond
893                      ((and last-slash (not (zerop last-slash)))
894                       ;; There is something before this ..
895                       (let ((prev-prev-slash
896                              (position #\/ dst :end last-slash :from-end t)))
897                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
898                                        last-slash)
899                                     (char= (schar dst (- last-slash 2)) #\.)
900                                     (char= (schar dst (1- last-slash)) #\.))
901                                ;; The something before this .. is another ..
902                                (deposit char)
903                                (setf last-slash dst-len))
904                               (t
905                                ;; The something is some directory or other.
906                                (setf dst-len
907                                      (if prev-prev-slash
908                                          (1+ prev-prev-slash)
909                                          0))
910                                (setf last-slash prev-prev-slash)))))
911                      (t
912                       ;; There is nothing before this .., so we need to keep it
913                       (setf last-slash dst-len)
914                       (deposit char))))
915                    (t
916                     ;; something other than a dot between slashes
917                     (setf last-slash dst-len)
918                     (deposit char)))
919                  (setf dots 0))
920                 (t
921                  (setf dots nil)
922                  (setf (schar dst dst-len) char)
923                  (incf dst-len))))))
924     (when (and last-slash (not (zerop last-slash)))
925       (case dots
926         (1
927          ;; We've got  ``foobar/.''
928          (decf dst-len))
929         (2
930          ;; We've got ``foobar/..''
931          (unless (and (>= last-slash 2)
932                       (char= (schar dst (1- last-slash)) #\.)
933                       (char= (schar dst (- last-slash 2)) #\.)
934                       (or (= last-slash 2)
935                           (char= (schar dst (- last-slash 3)) #\/)))
936            (let ((prev-prev-slash
937                   (position #\/ dst :end last-slash :from-end t)))
938              (if prev-prev-slash
939                  (setf dst-len (1+ prev-prev-slash))
940                  (return-from unix-simplify-pathname
941                    (coerce "./" 'simple-base-string))))))))
942     (cond ((zerop dst-len)
943            "./")
944           ((= dst-len src-len)
945            dst)
946           (t
947            (subseq dst 0 dst-len)))))
948 \f
949 ;;;; A magic constant for wait3().
950 ;;;;
951 ;;;; FIXME: This used to be defined in run-program.lisp as
952 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
953 ;;;; According to some of the man pages, the #o177 is part of the API
954 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
955 ;;;; the headers that may or may not be the same thing. To be
956 ;;;; investigated. -- CSR, 2002-03-25
957 (defconstant wstopped #o177)
958
959 \f
960 ;;;; stuff not yet found in the header files
961 ;;;;
962 ;;;; Abandon all hope who enters here...
963
964 ;;; not checked for linux...
965 (defmacro fd-set (offset fd-set)
966   (let ((word (gensym))
967         (bit (gensym)))
968     `(multiple-value-bind (,word ,bit) (floor ,offset
969                                               sb!vm:n-machine-word-bits)
970        (setf (deref (slot ,fd-set 'fds-bits) ,word)
971              (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
972                                 (ash 1 ,bit))
973                      (deref (slot ,fd-set 'fds-bits) ,word))))))
974
975 ;;; not checked for linux...
976 (defmacro fd-clr (offset fd-set)
977   (let ((word (gensym))
978         (bit (gensym)))
979     `(multiple-value-bind (,word ,bit) (floor ,offset
980                                               sb!vm:n-machine-word-bits)
981        (setf (deref (slot ,fd-set 'fds-bits) ,word)
982              (logand (deref (slot ,fd-set 'fds-bits) ,word)
983                      (sb!kernel:word-logical-not
984                       (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
985                                  (ash 1 ,bit))))))))
986
987 ;;; not checked for linux...
988 (defmacro fd-isset (offset fd-set)
989   (let ((word (gensym))
990         (bit (gensym)))
991     `(multiple-value-bind (,word ,bit) (floor ,offset
992                                               sb!vm:n-machine-word-bits)
993        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
994
995 ;;; not checked for linux...
996 (defmacro fd-zero (fd-set)
997   `(progn
998      ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
999          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))