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