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