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