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