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