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