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