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