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