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