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