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