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.
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.
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
)))
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))
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.
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
))
67 (concatenate 'string
#!+win32
"_" (subseq name
3))))
69 (declare (optimize (sb!c
::float-accuracy
0)))
70 (let ((result (alien-funcall (extern-alien ,name
(function int
,@arg-types
))
73 (values nil
(get-errno))
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
)
81 (declare (optimize (sb!c
::float-accuracy
0)))
82 (let ((result (alien-funcall (extern-alien ,name
(function int
,@arg-types
))
85 (error "Syscall ~A failed: ~A" ,name
(strerror))
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))
93 syscall-form
&rest body
)
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."
98 (loop (multiple-value-setq (,value
,errno
)
100 (unless #!-win32
(eql ,errno eintr
) #!+win32 nil
101 (return (values ,value
,errno
))))
104 (defmacro void-syscall
((name &rest arg-types
) &rest args
)
105 `(syscall (,name
,@arg-types
) (values t
0) ,@args
))
109 (defconstant espipe
29))
111 ;;;; hacking the Unix environment
114 (define-alien-routine ("getenv" posix-getenv
) c-string
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
)))
122 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
123 ;;; error code is returned if an error occurs.
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
))
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
140 (define-alien-type fd-mask unsigned
)
142 (define-alien-type nil
144 (fds-bits (array fd-mask
#.
(/ fd-setsize
145 sb
!vm
:n-machine-word-bits
)))))
147 (/show0
"unix.lisp 304")
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
&key
#!+win32 overlapped
)
162 (declare (type unix-pathname path
)
164 (type unix-file-mode mode
)
167 #!+win32
(sb!win32
:unixlike-open path flags
:overlapped overlapped
)
169 (with-restarted-syscall (value errno
)
170 (int-syscall ("open" c-string int int
)
172 (logior #!+largefile o_largefile
176 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
177 ;;; associated with it.
178 (/show0
"unix.lisp 391")
179 (defun unix-close (fd)
180 #!+win32
(sb!win32
:unixlike-close fd
)
181 #!-win32
(declare (type unix-fd fd
))
182 #!-win32
(void-syscall ("close" int
) fd
))
186 ;;; There are good reasons to implement some OPEN options with an
187 ;;; mkstemp(3)-like routine, but we don't do that yet. Instead, this
188 ;;; function is used only to make a temporary file for RUN-PROGRAM.
189 ;;; sb_mkstemp() is a wrapper that lives in src/runtime/wrap.c. Since
190 ;;; SUSv3 mkstemp() doesn't specify the mode of the created file and
191 ;;; since we have to implement most of this ourselves for Windows
192 ;;; anyway, it seems worthwhile to depart from the mkstemp()
193 ;;; specification by taking a mode to use when creating the new file.
194 (defun sb-mkstemp (template-string mode
)
195 (declare (type string template-string
)
196 (type unix-file-mode mode
))
197 (let ((template-buffer (string-to-octets template-string
:null-terminate t
)))
198 (with-pinned-objects (template-buffer)
199 (let ((fd (alien-funcall (extern-alien "sb_mkstemp"
200 (function int
(* char
) int
))
201 (vector-sap template-buffer
)
204 (values nil
(get-errno))
205 (values #!-win32 fd
#!+win32
(sb!win32
::duplicate-and-unwrap-fd fd
)
206 (octets-to-string template-buffer
)))))))
210 (defconstant rusage_self
0) ; the calling process
211 (defconstant rusage_children -
1) ; terminated child processes
212 (defconstant rusage_both -
2)
214 (define-alien-type nil
216 (ru-utime (struct timeval
)) ; user time used
217 (ru-stime (struct timeval
)) ; system time used.
218 (ru-maxrss long
) ; maximum resident set size (in kilobytes)
219 (ru-ixrss long
) ; integral shared memory size
220 (ru-idrss long
) ; integral unshared data size
221 (ru-isrss long
) ; integral unshared stack size
222 (ru-minflt long
) ; page reclaims
223 (ru-majflt long
) ; page faults
224 (ru-nswap long
) ; swaps
225 (ru-inblock long
) ; block input operations
226 (ru-oublock long
) ; block output operations
227 (ru-msgsnd long
) ; messages sent
228 (ru-msgrcv long
) ; messages received
229 (ru-nsignals long
) ; signals received
230 (ru-nvcsw long
) ; voluntary context switches
231 (ru-nivcsw long
))) ; involuntary context switches
235 ;;; Given a file path (a string) and one of four constant modes,
236 ;;; return T if the file is accessible with that mode and NIL if not.
237 ;;; When NIL, also return an errno value with NIL which tells why the
238 ;;; file was not accessible.
240 ;;; The access modes are:
241 ;;; r_ok Read permission.
242 ;;; w_ok Write permission.
243 ;;; x_ok Execute permission.
244 ;;; f_ok Presence of file.
246 ;;; In Windows, the MODE argument to access is defined in terms of
247 ;;; literal magic numbers---there are no constants to grovel. X_OK
253 (defconstant r_ok
4))
255 (defun unix-access (path mode
)
256 (declare (type unix-pathname path
)
258 (void-syscall ("[_]access" c-string int
) path mode
))
260 ;;; values for the second argument to UNIX-LSEEK
261 ;;; Note that nowadays these are called SEEK_SET, SEEK_CUR, and SEEK_END
262 (defconstant l_set
0) ; to set the file pointer
263 (defconstant l_incr
1) ; to increment the file pointer
264 (defconstant l_xtnd
2) ; to extend the file size
266 ;; off_t is 32 bit on Windows, yet our functions support 64 bit seeks.
267 (define-alien-type unix-offset
269 #!+win32
(signed 64))
271 ;;; Is a stream interactive?
272 (defun unix-isatty (fd)
273 (declare (type unix-fd fd
))
274 #!-win32
(int-syscall ("isatty" int
) fd
)
275 #!+win32
(sb!win32
::windows-isatty fd
))
277 (defun unix-lseek (fd offset whence
)
279 "Unix-lseek accepts a file descriptor and moves the file pointer by
280 OFFSET octets. Whence can be any of the following:
282 L_SET Set the file pointer.
283 L_INCR Increment the file pointer.
284 L_XTND Extend the file size.
286 (declare (type unix-fd fd
)
287 (type (integer 0 2) whence
))
290 (alien-funcall (extern-alien #!-largefile
"lseek"
291 #!+largefile
"lseek_largefile"
292 (function off-t int off-t int
))
294 #!+win32
(sb!win32
:lseeki64 fd offset whence
)))
296 (values nil
(get-errno))
299 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
300 ;;; It attempts to read len bytes from the device associated with fd
301 ;;; and store them into the buffer. It returns the actual number of
305 (declaim (maybe-inline unix-read
))
307 (defun unix-read (fd buf len
)
308 (declare (type unix-fd fd
)
309 (type (unsigned-byte 32) len
))
310 (int-syscall (#!-win32
"read" #!+win32
"win32_unix_read"
311 int
(* char
) int
) fd buf len
))
313 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
314 ;;; length to write. It attempts to write len bytes to the device
315 ;;; associated with fd from the buffer starting at offset. It returns
316 ;;; the actual number of bytes written.
317 (defun unix-write (fd buf offset len
)
318 (declare (type unix-fd fd
)
319 (type (unsigned-byte 32) offset len
))
321 (declare (system-area-pointer sap
))
322 (int-syscall (#!-win32
"write" #!+win32
"win32_unix_write"
325 (with-alien ((ptr (* char
) sap
))
326 (addr (deref ptr offset
)))
329 ((simple-array * (*))
330 (with-pinned-objects (buf)
331 (%write
(vector-sap buf
))))
335 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
336 ;;; output pipe. Return two values: if no error occurred the first
337 ;;; value is the pipe to be read from and the second is can be written
338 ;;; to. If an error occurred the first value is NIL and the second the
342 (with-alien ((fds (array int
2)))
343 (syscall ("pipe" (* int
))
344 (values (deref fds
0) (deref fds
1))
345 (cast fds
(* int
)))))
349 (sb!win32
::windows-pipe
))
351 ;; Windows mkdir() doesn't take the mode argument. It's cdecl, so we could
352 ;; actually call it passing the mode argument, but some sharp-eyed reader
353 ;; would put five and twenty-seven together and ask us about it, so...
356 (defun unix-mkdir (name mode
)
357 (declare (type unix-pathname name
)
358 (type unix-file-mode mode
)
359 #!+win32
(ignore mode
))
360 (void-syscall ("mkdir" c-string
#!-win32 int
) name
#!-win32 mode
))
362 ;;; Given a C char* pointer allocated by malloc(), free it and return a
363 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
364 (defun newcharstar-string (newcharstar)
365 (declare (type (alien (* char
)) newcharstar
))
366 (if (null-alien newcharstar
)
369 (cast newcharstar c-string
)
370 (free-alien newcharstar
))))
372 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
373 ;;; style returned by getcwd() (no trailing slash character).
375 (defun posix-getcwd ()
376 ;; This implementation relies on a BSD/Linux extension to getcwd()
377 ;; behavior, automatically allocating memory when a null buffer
378 ;; pointer is used. On a system which doesn't support that
379 ;; extension, it'll have to be rewritten somehow.
381 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
382 ;; buffer pointer, it will automatically allocate size space. The
383 ;; KLUDGE in this solution arises because we have just read off
384 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
385 ;; a constant. Going the grovel_headers route doesn't seem to be
386 ;; helpful, either, as Solaris doesn't export PATH_MAX from
389 ;; Signal an error at compile-time, since it's needed for the
390 ;; runtime to start up
391 #!-
(or android linux openbsd freebsd netbsd sunos osf1 darwin hpux win32 dragonfly
)
392 #.
(error "POSIX-GETCWD is not implemented.")
394 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin hpux win32 dragonfly
)
395 (newcharstar-string (alien-funcall (extern-alien "getcwd"
400 #!+(or linux openbsd freebsd netbsd darwin win32 dragonfly
) 0
401 #!+(or sunos osf1 hpux
) 1025))
403 (with-alien ((ptr (array char
#.path-max
)))
404 ;; Older bionic versions do not have the above feature.
406 (extern-alien "getcwd"
407 (function c-string
(array char
#.path-max
) int
))
409 (simple-perror "getcwd")))
411 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
412 ;;; by a slash character.
413 (defun posix-getcwd/ ()
414 (concatenate 'string
(posix-getcwd) "/"))
416 ;;; Duplicate an existing file descriptor (given as the argument) and
417 ;;; return it. If FD is not a valid file descriptor, NIL and an error
418 ;;; number are returned.
421 (declare (type unix-fd fd
))
422 (int-syscall ("dup" int
) fd
))
424 ;;; Terminate the current process with an optional error code. If
425 ;;; successful, the call doesn't return. If unsuccessful, the call
426 ;;; returns NIL and an error number.
427 (deftype exit-code
()
429 (defun os-exit (code &key abort
)
431 "Exit the process with CODE. If ABORT is true, exit is performed using _exit(2),
432 avoiding atexit(3) hooks, etc. Otherwise exit(2) is called."
433 (unless (typep code
'exit-code
)
434 (setf code
(if abort
1 0)))
436 (void-syscall ("_exit" int
) code
)
437 (void-syscall ("exit" int
) code
)))
439 (define-deprecated-function :early
"1.0.56.55" unix-exit os-exit
(code)
442 ;;; Return the process id of the current process.
443 (define-alien-routine (#!+win32
"_getpid" #!-win32
"getpid" unix-getpid
) int
)
445 ;;; Return the real user id associated with the current process.
447 (define-alien-routine ("getuid" unix-getuid
) int
)
449 ;;; Translate a user id into a login name.
451 (defun uid-username (uid)
452 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
453 (function (* char
) int
))
455 (error "found no match for Unix uid=~S" uid
)))
457 ;;; Return the namestring of the home directory, being careful to
458 ;;; include a trailing #\/
461 (defun uid-homedir (uid)
462 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
463 (function (* char
) int
))
465 (error "failed to resolve home directory for Unix uid=~S" uid
)))
467 (defun user-homedir (uid)
468 (or (newcharstar-string (alien-funcall (extern-alien "user_homedir"
469 (function (* char
) c-string
))
471 (error "failed to resolve home directory for Unix uid=~S" uid
))))
473 ;;; Invoke readlink(2) on the file name specified by PATH. Return
474 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
477 (defun unix-readlink (path)
478 (declare (type unix-pathname path
))
479 (with-alien ((ptr (* char
)
480 (alien-funcall (extern-alien
482 (function (* char
) c-string
))
485 (values nil
(get-errno))
486 (multiple-value-prog1
487 (values (with-alien ((c-string c-string ptr
)) c-string
)
491 ;; Win32 doesn't do links, but something likes to call this anyway.
492 ;; Something in this file, no less. But it only takes one result, so...
493 (defun unix-readlink (path)
494 (declare (ignore path
))
497 (defun unix-realpath (path)
498 (declare (type unix-pathname path
))
499 (with-alien ((ptr (* char
)
500 (alien-funcall (extern-alien
502 (function (* char
) c-string
))
505 (values nil
(get-errno))
506 (multiple-value-prog1
507 (values (with-alien ((c-string c-string ptr
)) c-string
)
511 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
512 ;;; name and the file if this is the last link.
513 (defun unix-unlink (name)
514 (declare (type unix-pathname name
))
515 (void-syscall ("[_]unlink" c-string
) name
))
517 ;;; Return the name of the host machine as a string.
519 (defun unix-gethostname ()
520 (with-alien ((buf (array char
256)))
521 (syscall ("gethostname" (* char
) int
)
523 (cast buf
(* char
)) 256)))
526 (defun unix-setsid ()
527 (int-syscall ("setsid")))
531 ;;; UNIX-IOCTL performs a variety of operations on open i/o
532 ;;; descriptors. See the UNIX Programmer's Manual for more
535 (defun unix-ioctl (fd cmd arg
)
536 (declare (type unix-fd fd
)
537 (type (signed-byte 32) cmd
))
538 (void-syscall ("ioctl" int int
(* char
)) fd cmd arg
))
542 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
544 ;;; This is like getrusage(2), except it returns only the system and
545 ;;; user time, and returns the seconds and microseconds as separate
547 #!-sb-fluid
(declaim (inline unix-fast-getrusage
))
549 (defun unix-fast-getrusage (who)
550 (declare (values (member t
)
552 unsigned-byte fixnum
))
553 (with-alien ((usage (struct rusage
)))
554 (syscall* ("sb_getrusage" int
(* (struct rusage
)))
556 (slot (slot usage
'ru-utime
) 'tv-sec
)
557 (slot (slot usage
'ru-utime
) 'tv-usec
)
558 (slot (slot usage
'ru-stime
) 'tv-sec
)
559 (slot (slot usage
'ru-stime
) 'tv-usec
))
562 ;;; Return information about the resource usage of the process
563 ;;; specified by WHO. WHO can be either the current process
564 ;;; (rusage_self) or all of the terminated child processes
565 ;;; (rusage_children). NIL and an error number is returned if the call
568 (defun unix-getrusage (who)
569 (with-alien ((usage (struct rusage
)))
570 (syscall ("sb_getrusage" int
(* (struct rusage
)))
572 (+ (* (slot (slot usage
'ru-utime
) 'tv-sec
) 1000000)
573 (slot (slot usage
'ru-utime
) 'tv-usec
))
574 (+ (* (slot (slot usage
'ru-stime
) 'tv-sec
) 1000000)
575 (slot (slot usage
'ru-stime
) 'tv-usec
))
576 (slot usage
'ru-maxrss
)
577 (slot usage
'ru-ixrss
)
578 (slot usage
'ru-idrss
)
579 (slot usage
'ru-isrss
)
580 (slot usage
'ru-minflt
)
581 (slot usage
'ru-majflt
)
582 (slot usage
'ru-nswap
)
583 (slot usage
'ru-inblock
)
584 (slot usage
'ru-oublock
)
585 (slot usage
'ru-msgsnd
)
586 (slot usage
'ru-msgrcv
)
587 (slot usage
'ru-nsignals
)
588 (slot usage
'ru-nvcsw
)
589 (slot usage
'ru-nivcsw
))
592 (defvar *on-dangerous-wait
* :warn
)
594 ;;; Calling select in a bad place can hang in a nasty manner, so it's better
595 ;;; to have some way to detect these.
596 (defun note-dangerous-wait (type)
597 (let ((action *on-dangerous-wait
*)
598 (*on-dangerous-wait
* nil
))
601 (warn "Starting a ~A without a timeout while interrupts are ~
605 (error "Starting a ~A without a timeout while interrupts are ~
610 "~&=== Starting a ~A without a timeout while interrupts are disabled. ===~%"
612 (sb!debug
:print-backtrace
)))
618 (define-alien-type nil
621 (events short
) ; requested events
622 (revents short
))) ; returned events
624 (defun unix-poll (pollfds nfds to-msec
)
625 (declare (fixnum nfds to-msec
))
626 (when (and (minusp to-msec
) (not *interrupts-enabled
*))
627 (note-dangerous-wait "poll(2)"))
628 ;; FAST-SELECT doesn't use WITH-RESTARTED-SYSCALL so this doesn't either
629 (int-syscall ("poll" (* (struct pollfd
)) int int
)
630 (alien-sap pollfds
) nfds to-msec
))
632 ;; "simple" poll operates on a single descriptor only
633 (defun unix-simple-poll (fd direction to-msec
)
634 (declare (fixnum fd to-msec
))
635 (when (and (minusp to-msec
) (not *interrupts-enabled
*))
636 (note-dangerous-wait "poll(2)"))
637 (let ((events (ecase direction
638 (:input
(logior pollin pollpri
))
640 (with-alien ((fds (struct pollfd
)))
641 (with-restarted-syscall (count errno
)
643 (setf (slot fds
'fd
) fd
644 (slot fds
'events
) events
645 (slot fds
'revents
) 0)
646 (int-syscall ("poll" (* (struct pollfd
)) int int
)
647 (addr fds
) 1 to-msec
))
649 (let ((revents (slot fds
'revents
)))
650 (or (and (eql 1 count
) (logtest events revents
))
651 (logtest pollhup revents
)))
652 (error "Syscall poll(2) failed: ~A" (strerror))))))))
656 (defmacro with-fd-setsize
((n) &body body
)
657 `(let ((,n
(if (< 0 ,n fd-setsize
)
659 (error "Cannot select(2) on ~D: above FD_SETSIZE limit."
661 (declare (type (integer 0 #.fd-setsize
) ,n
))
664 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
666 ;;; Perform the UNIX select(2) system call.
667 (declaim (inline unix-fast-select
))
668 (defun unix-fast-select (num-descriptors
669 read-fds write-fds exception-fds
670 timeout-secs timeout-usecs
)
671 (declare (type integer num-descriptors
)
672 (type (or (alien (* (struct fd-set
))) null
)
673 read-fds write-fds exception-fds
)
674 (type (or null
(unsigned-byte 31)) timeout-secs timeout-usecs
))
675 (with-fd-setsize (num-descriptors)
676 (flet ((select (tv-sap)
677 (int-syscall ("sb_select" int
(* (struct fd-set
)) (* (struct fd-set
))
678 (* (struct fd-set
)) (* (struct timeval
)))
679 num-descriptors read-fds write-fds exception-fds
681 (cond ((or timeout-secs timeout-usecs
)
682 (with-alien ((tv (struct timeval
)))
683 (setf (slot tv
'tv-sec
) (or timeout-secs
0))
684 (setf (slot tv
'tv-usec
) (or timeout-usecs
0))
685 (select (alien-sap (addr tv
)))))
687 (unless *interrupts-enabled
*
688 (note-dangerous-wait "select(2)"))
689 (select (int-sap 0)))))))
691 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
692 ;;; to happen on one of them or to time out.
693 (declaim (inline num-to-fd-set fd-set-to-num
))
694 (defun num-to-fd-set (fdset num
)
697 (setf (deref (slot fdset
'fds-bits
) 0) num
)
698 (loop for index from
1 below
(/ fd-setsize
699 sb
!vm
:n-machine-word-bits
)
700 do
(setf (deref (slot fdset
'fds-bits
) index
) 0)))
702 (loop for index from
0 below
(/ fd-setsize
703 sb
!vm
:n-machine-word-bits
)
704 do
(setf (deref (slot fdset
'fds-bits
) index
)
705 (ldb (byte sb
!vm
:n-machine-word-bits
706 (* index sb
!vm
:n-machine-word-bits
))
709 (defun fd-set-to-num (nfds fdset
)
710 (if (<= nfds sb
!vm
:n-machine-word-bits
)
711 (deref (slot fdset
'fds-bits
) 0)
712 (loop for index below
(/ fd-setsize
713 sb
!vm
:n-machine-word-bits
)
714 sum
(ash (deref (slot fdset
'fds-bits
) index
)
715 (* index sb
!vm
:n-machine-word-bits
)))))
717 ;;; Examine the sets of descriptors passed as arguments to see whether
718 ;;; they are ready for reading and writing. See the UNIX Programmer's
719 ;;; Manual for more information.
720 (defun unix-select (nfds rdfds wrfds xpfds to-secs
&optional
(to-usecs 0))
721 (declare (muffle-conditions t
))
722 (declare (type integer nfds
)
723 (type unsigned-byte rdfds wrfds xpfds
)
724 (type (or (unsigned-byte 31) null
) to-secs
)
725 (type (unsigned-byte 31) to-usecs
)
726 (optimize (speed 3) (safety 0)))
727 (with-fd-setsize (nfds)
728 (with-alien ((tv (struct timeval
))
729 (rdf (struct fd-set
))
730 (wrf (struct fd-set
))
731 (xpf (struct fd-set
)))
733 (setf (slot tv
'tv-sec
) to-secs
734 (slot tv
'tv-usec
) to-usecs
))
735 ((not *interrupts-enabled
*)
736 (note-dangerous-wait "select(2)")))
737 (num-to-fd-set rdf rdfds
)
738 (num-to-fd-set wrf wrfds
)
739 (num-to-fd-set xpf xpfds
)
740 (macrolet ((frob (lispvar alienvar
)
741 `(if (zerop ,lispvar
)
743 (alien-sap (addr ,alienvar
)))))
744 (syscall ("sb_select" int
(* (struct fd-set
)) (* (struct fd-set
))
745 (* (struct fd-set
)) (* (struct timeval
)))
747 (fd-set-to-num nfds rdf
)
748 (fd-set-to-num nfds wrf
)
749 (fd-set-to-num nfds xpf
))
750 nfds
(frob rdfds rdf
) (frob wrfds wrf
) (frob xpfds xpf
)
751 (if to-secs
(alien-sap (addr tv
)) (int-sap 0)))))))
753 ;;; Lisp-side implmentations of FD_FOO macros.
754 (declaim (inline fd-set fd-clr fd-isset fd-zero
))
755 (defun fd-set (offset fd-set
)
756 (multiple-value-bind (word bit
) (floor offset
757 sb
!vm
:n-machine-word-bits
)
758 (setf (deref (slot fd-set
'fds-bits
) word
)
759 (logior (truly-the (unsigned-byte #.sb
!vm
:n-machine-word-bits
)
761 (deref (slot fd-set
'fds-bits
) word
)))))
763 (defun fd-clr (offset fd-set
)
764 (multiple-value-bind (word bit
) (floor offset
765 sb
!vm
:n-machine-word-bits
)
766 (setf (deref (slot fd-set
'fds-bits
) word
)
767 (logand (deref (slot fd-set
'fds-bits
) word
)
768 (sb!kernel
:word-logical-not
769 (truly-the (unsigned-byte #.sb
!vm
:n-machine-word-bits
)
772 (defun fd-isset (offset fd-set
)
773 (multiple-value-bind (word bit
) (floor offset
774 sb
!vm
:n-machine-word-bits
)
775 (logbitp bit
(deref (slot fd-set
'fds-bits
) word
))))
777 (defun fd-zero (fd-set)
778 (loop for index below
(/ fd-setsize sb
!vm
:n-machine-word-bits
)
779 do
(setf (deref (slot fd-set
'fds-bits
) index
) 0)))
782 (defun unix-simple-poll (fd direction to-msec
)
783 (multiple-value-bind (to-sec to-usec
)
786 (multiple-value-bind (to-sec to-msec2
) (truncate to-msec
1000)
787 (values to-sec
(* to-msec2
1000))))
788 (with-restarted-syscall (count errno
)
789 (with-alien ((fds (struct fd-set
)))
792 (multiple-value-bind (read-fds write-fds
)
795 (values (addr fds
) nil
))
797 (values nil
(addr fds
))))
798 (unix-fast-select (1+ fd
)
799 read-fds write-fds nil
805 (error "Syscall select(2) failed on fd ~D: ~A" fd
(strerror)))))))
809 ;;; This is a structure defined in src/runtime/wrap.c, to look
810 ;;; basically like "struct stat" according to stat(2). It may not
811 ;;; actually correspond to the real in-memory stat structure that the
812 ;;; syscall uses, and that's OK. Linux in particular is packed full of
813 ;;; stat macros, and trying to keep Lisp code in correspondence with
814 ;;; it is more pain than it's worth, so we just let our C runtime
815 ;;; synthesize a nice consistent structure for us.
817 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
818 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
819 ;;; those. We don't actually access that field anywhere, though, so
820 ;;; until we can get 64 bit alien support it'll do. Also note that
821 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
822 ;;; quantity on Alpha. And FIXME: "No one would want a file length
823 ;;; longer than 32 bits anyway, right?":-|
825 ;;; The comment about alien and 64-bit quantities has not been kept in
826 ;;; sync with the comment now in wrap.h (formerly wrap.c), but it's
827 ;;; not clear whether either comment is correct. -- RMK 2007-11-14.
828 (define-alien-type nil
833 (st-nlink wst-nlink-t
)
838 (st-blksize wst-blksize-t
)
839 (st-blocks wst-blkcnt-t
)
844 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
845 ;;; family of Unix system calls
847 ;;; FIXME: I think this should probably not be INLINE. However, when
848 ;;; this was not inline, it seemed to cause memory corruption
849 ;;; problems. My first guess is that it's a bug in the FFI code, where
850 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
851 ;;; around a call to a function returning >10 values. But I didn't try
852 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
853 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
854 ;;; output in the not-inlined case and see whether there's a problem,
855 ;;; and maybe even find a fix..
856 (declaim (inline %extract-stat-results
))
857 (defun %extract-stat-results
(wrapped-stat)
858 (declare (type (alien (* (struct wrapped_stat
))) wrapped-stat
))
860 (slot wrapped-stat
'st-dev
)
861 (slot wrapped-stat
'st-ino
)
862 (slot wrapped-stat
'st-mode
)
863 (slot wrapped-stat
'st-nlink
)
864 (slot wrapped-stat
'st-uid
)
865 (slot wrapped-stat
'st-gid
)
866 (slot wrapped-stat
'st-rdev
)
867 (slot wrapped-stat
'st-size
)
868 (slot wrapped-stat
'st-atime
)
869 (slot wrapped-stat
'st-mtime
)
870 (slot wrapped-stat
'st-ctime
)
871 (slot wrapped-stat
'st-blksize
)
872 (slot wrapped-stat
'st-blocks
)))
874 ;;; Unix system calls in the stat(2) family are handled by calls to
875 ;;; C-level wrapper functions which copy all the raw "struct stat"
876 ;;; slots into the system-independent wrapped_stat format.
877 ;;; stat(2) <-> stat_wrapper()
878 ;;; fstat(2) <-> fstat_wrapper()
879 ;;; lstat(2) <-> lstat_wrapper()
880 (defun unix-stat (name)
881 (declare (type unix-pathname name
))
882 (with-alien ((buf (struct wrapped_stat
)))
883 (syscall ("stat_wrapper" c-string
(* (struct wrapped_stat
)))
884 (%extract-stat-results
(addr buf
))
886 (defun unix-lstat (name)
887 (declare (type unix-pathname name
))
888 (with-alien ((buf (struct wrapped_stat
)))
889 (syscall ("lstat_wrapper" c-string
(* (struct wrapped_stat
)))
890 (%extract-stat-results
(addr buf
))
892 (defun unix-fstat (fd)
894 (declare (type unix-fd fd
))
895 (#!-win32 funcall
#!+win32 sb
!win32
::call-with-crt-fd
897 (with-alien ((buf (struct wrapped_stat
)))
898 (syscall ("fstat_wrapper" int
(* (struct wrapped_stat
)))
899 (%extract-stat-results
(addr buf
))
905 (declare (type unix-fd fd
))
908 (or (with-alien ((buf (struct wrapped_stat
)))
909 (syscall ("fstat_wrapper" int
(* (struct wrapped_stat
)))
913 (cond ((logtest s-ififo fmt
)
915 ((logtest s-ifchr fmt
)
917 ((logtest s-ifdir fmt
)
919 ((logtest s-ifblk fmt
)
921 ((logtest s-ifreg fmt
)
923 ((logtest s-ifsock fmt
)
930 ;; used by other time functions
931 (define-alien-type nil
933 (tm-sec int
) ; Seconds. [0-60] (1 leap second)
934 (tm-min int
) ; Minutes. [0-59]
935 (tm-hour int
) ; Hours. [0-23]
936 (tm-mday int
) ; Day. [1-31]
937 (tm-mon int
) ; Month. [0-11]
938 (tm-year int
) ; Year - 1900.
939 (tm-wday int
) ; Day of week. [0-6]
940 (tm-yday int
) ; Days in year. [0-365]
941 (tm-isdst int
) ; DST. [-1/0/1]
942 (tm-gmtoff long
) ; Seconds east of UTC.
943 (tm-zone c-string
))) ; Timezone abbreviation.
945 (define-alien-routine get-timezone int
947 (daylight-savings-p boolean
:out
))
950 (defun nanosleep (secs nsecs
)
951 (declare (optimize (sb!c
:alien-funcall-saves-fp-and-pc
0)))
952 (with-alien ((req (struct timespec
))
953 (rem (struct timespec
)))
954 (setf (slot req
'tv-sec
) secs
955 (slot req
'tv-nsec
) nsecs
)
956 (loop while
(and (eql eintr
958 (int-syscall ("sb_nanosleep" (* (struct timespec
))
959 (* (struct timespec
)))
960 (addr req
) (addr rem
))))
961 ;; KLUDGE: On Darwin, if an interrupt cases nanosleep to
962 ;; take longer than the requested time, the call will
963 ;; return with EINT and (unsigned)-1 seconds in the
964 ;; remainder timespec, which would cause us to enter
965 ;; nanosleep again for ~136 years. So, we check that the
966 ;; remainder time is actually decreasing.
968 ;; It would be neat to do this bit of defensive
969 ;; programming on all platforms, but unfortunately on
970 ;; Linux, REM can be a little higher than REQ if the
971 ;; nanosleep() call is interrupted quickly enough,
972 ;; probably due to the request being rounded up to the
973 ;; nearest HZ. This would cause the sleep to return way
976 (let ((rem-sec (slot rem
'tv-sec
))
977 (rem-nsec (slot rem
'tv-nsec
)))
978 (when (or (> secs rem-sec
)
979 (and (= secs rem-sec
) (>= nsecs rem-nsec
)))
980 ;; Update for next round.
984 do
(setf (slot req
'tv-sec
) (slot rem
'tv-sec
)
985 (slot req
'tv-nsec
) (slot rem
'tv-nsec
)))))
989 ;;; Structure crudely representing a timezone. KLUDGE: This is
990 ;;; obsolete and should never be used.
991 (define-alien-type nil
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
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)
1009 (defun unix-getitimer (which)
1011 "UNIX-GETITIMER returns the INTERVAL and VALUE slots of one of
1012 three system timers (:real :virtual or :profile). On success,
1013 unix-getitimer returns 5 values,
1014 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
1015 (declare (type (member :real
:virtual
:profile
) which
)
1017 unsigned-byte
(mod 1000000)
1018 unsigned-byte
(mod 1000000)))
1019 (let ((which (ecase which
1021 (:virtual itimer-virtual
)
1022 (:profile itimer-prof
))))
1023 (with-alien ((itv (struct itimerval
)))
1024 (syscall* ("sb_getitimer" int
(* (struct itimerval
)))
1026 (slot (slot itv
'it-interval
) 'tv-sec
)
1027 (slot (slot itv
'it-interval
) 'tv-usec
)
1028 (slot (slot itv
'it-value
) 'tv-sec
)
1029 (slot (slot itv
'it-value
) 'tv-usec
))
1030 which
(alien-sap (addr itv
))))))
1033 (defun unix-setitimer (which int-secs int-usec val-secs val-usec
)
1035 "UNIX-SETITIMER sets the INTERVAL and VALUE slots of one of
1036 three system timers (:real :virtual or :profile). A SIGALRM signal
1037 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
1038 when non-zero, is <seconds+microseconds> to be loaded each time
1039 the timer expires. Setting INTERVAL and VALUE to zero disables
1040 the timer. See the Unix man page for more details. On success,
1041 unix-setitimer returns the old contents of the INTERVAL and VALUE
1042 slots as in unix-getitimer."
1043 (declare (type (member :real
:virtual
:profile
) which
)
1044 (type unsigned-byte int-secs val-secs
)
1045 (type (integer 0 (1000000)) int-usec val-usec
)
1047 unsigned-byte
(mod 1000000)
1048 unsigned-byte
(mod 1000000)))
1049 (let ((which (ecase which
1051 (:virtual itimer-virtual
)
1052 (:profile itimer-prof
))))
1053 (with-alien ((itvn (struct itimerval
))
1054 (itvo (struct itimerval
)))
1055 (setf (slot (slot itvn
'it-interval
) 'tv-sec
) int-secs
1056 (slot (slot itvn
'it-interval
) 'tv-usec
) int-usec
1057 (slot (slot itvn
'it-value
) 'tv-sec
) val-secs
1058 (slot (slot itvn
'it-value
) 'tv-usec
) val-usec
)
1059 (syscall* ("sb_setitimer" int
(* (struct timeval
))(* (struct timeval
)))
1061 (slot (slot itvo
'it-interval
) 'tv-sec
)
1062 (slot (slot itvo
'it-interval
) 'tv-usec
)
1063 (slot (slot itvo
'it-value
) 'tv-sec
)
1064 (slot (slot itvo
'it-value
) 'tv-usec
))
1065 which
(alien-sap (addr itvn
))(alien-sap (addr itvo
))))))
1068 ;;; FIXME: Many Unix error code definitions were deleted from the old
1069 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
1070 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
1071 ;;; unused symbols in package exports, but if I don't, there are
1072 ;;; enough of them all in one place here that they should probably be
1073 ;;; removed by hand.
1075 (defconstant micro-seconds-per-internal-time-unit
1076 (/ 1000000 sb
!xc
:internal-time-units-per-second
))
1078 ;;; UNIX specific code, that has been cleanly separated from the
1083 #!-sb-fluid
(declaim (inline get-time-of-day
))
1084 (defun get-time-of-day ()
1086 "Return the number of seconds and microseconds since the beginning of
1087 the UNIX epoch (January 1st 1970.)"
1088 #!+(or darwin netbsd
)
1089 (with-alien ((tv (struct timeval
)))
1090 ;; CLH: FIXME! This seems to be a MacOS bug, but on x86-64/darwin,
1091 ;; gettimeofday occasionally fails. passing in a null pointer for the
1092 ;; timezone struct seems to work around the problem. NS notes: Darwin
1093 ;; manpage says the timezone is not used anymore in their implementation
1095 (syscall* ("sb_gettimeofday" (* (struct timeval
))
1096 (* (struct timezone
)))
1097 (values (slot tv
'tv-sec
)
1101 #!-
(or darwin netbsd
)
1102 (with-alien ((tv (struct timeval
))
1103 (tz (struct timezone
)))
1104 (syscall* ("sb_gettimeofday" (* (struct timeval
))
1105 (* (struct timezone
)))
1106 (values (slot tv
'tv-sec
)
1111 (declaim (inline system-internal-run-time
1112 system-real-time-values
))
1114 (defun system-real-time-values ()
1115 (multiple-value-bind (sec usec
) (get-time-of-day)
1116 (declare (type unsigned-byte sec
) (type (unsigned-byte 31) usec
))
1117 (values sec
(truncate usec micro-seconds-per-internal-time-unit
))))
1119 ;; There are two optimizations here that actually matter (on 32-bit
1120 ;; systems): substract the epoch from seconds and milliseconds
1121 ;; separately, as those should remain fixnums for the first 17 years
1122 ;; or so of runtime. Also, avoid doing consing a new bignum if the
1123 ;; result would be = to the last result given.
1125 ;; Note: the next trick would be to spin a separate thread to update
1126 ;; a global value once per internal tick, so each individual call to
1127 ;; get-internal-real-time would be just a memory read... but that is
1128 ;; probably best left for user-level code. ;)
1130 ;; Thanks to James Anderson for the optimization hint.
1132 ;; Yes, it is possible to a computation to be GET-INTERNAL-REAL-TIME
1141 (declare (type sb
!kernel
:internal-seconds e-sec c-sec
)
1142 (type sb
!kernel
:internal-seconds e-msec c-msec
)
1143 (type sb
!kernel
:internal-time now
))
1144 (defun reinit-internal-real-time ()
1145 (setf (values e-sec e-msec
) (system-real-time-values)
1148 ;; If two threads call this at the same time, we're still safe, I
1149 ;; believe, as long as NOW is updated before either of C-MSEC or
1150 ;; C-SEC. Same applies to interrupts. --NS
1152 ;; I believe this is almost correct with x86/x86-64 cache
1153 ;; coherency, but if the new value of C-SEC, C-MSEC can become
1154 ;; visible to another CPU without NOW doing the same then it's
1155 ;; unsafe. It's `almost' correct on x86 because writes by other
1156 ;; processors may become visible in any order provided transitity
1157 ;; holds. With at least three cpus, C-MSEC and C-SEC may be from
1158 ;; different threads and an incorrect value may be returned.
1159 ;; Considering that this failure is not detectable by the caller -
1160 ;; it looks like time passes a bit slowly - and that it should be
1161 ;; an extremely rare occurance I'm inclinded to leave it as it is.
1163 (defun get-internal-real-time ()
1164 (multiple-value-bind (sec msec
) (system-real-time-values)
1165 (unless (and (= msec c-msec
) (= sec c-sec
))
1166 (setf now
(+ (* (- sec e-sec
)
1167 sb
!xc
:internal-time-units-per-second
)
1173 (defun system-internal-run-time ()
1174 (multiple-value-bind (ignore utime-sec utime-usec stime-sec stime-usec
)
1175 (unix-fast-getrusage rusage_self
)
1176 (declare (ignore ignore
)
1177 (type unsigned-byte utime-sec stime-sec
)
1178 ;; (Classic CMU CL had these (MOD 1000000) instead, but
1179 ;; at least in Linux 2.2.12, the type doesn't seem to
1180 ;; be documented anywhere and the observed behavior is
1181 ;; to sometimes return 1000000 exactly.)
1182 (type fixnum utime-usec stime-usec
))
1183 (let ((result (+ (* (+ utime-sec stime-sec
)
1184 sb
!xc
:internal-time-units-per-second
)
1185 (floor (+ utime-usec
1187 (floor micro-seconds-per-internal-time-unit
2))
1188 micro-seconds-per-internal-time-unit
))))
1191 ;;; FIXME, KLUDGE: GET-TIME-OF-DAY used to be UNIX-GETTIMEOFDAY, and had a
1192 ;;; primary return value indicating sucess, and also returned timezone
1193 ;;; information -- though the timezone data was not there on Darwin.
1194 ;;; Now we have GET-TIME-OF-DAY, but it turns out that despite SB-UNIX being
1195 ;;; an implementation package UNIX-GETTIMEOFDAY has users in the wild.
1196 ;;; So we're stuck with it for a while -- maybe delete it towards the end
1198 (defun unix-gettimeofday ()
1199 (multiple-value-bind (sec usec
) (get-time-of-day)
1200 (values t sec usec nil nil
)))
1202 ;;;; opendir, readdir, closedir, and dirent-name
1204 (declaim (inline unix-opendir
))
1205 (defun unix-opendir (namestring &optional
(errorp t
))
1206 (let ((dir (alien-funcall
1207 (extern-alien "sb_opendir"
1208 (function system-area-pointer c-string
))
1210 (if (zerop (sap-int dir
))
1211 (when errorp
(simple-perror
1212 (format nil
"Error opening directory ~S"
1216 (declaim (inline unix-readdir
))
1217 (defun unix-readdir (dir &optional
(errorp t
) namestring
)
1218 (let ((ent (alien-funcall
1219 (extern-alien "sb_readdir"
1220 (function system-area-pointer system-area-pointer
))
1223 (if (zerop (sap-int ent
))
1225 (not (zerop (setf errno
(get-errno)))))
1227 (format nil
"Error reading directory entry~@[ from ~S~]"
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
))
1238 (when errorp
(simple-perror
1239 (format nil
"Error closing directory~@[ ~S~]"
1243 (declaim (inline unix-dirent-name
))
1244 (defun unix-dirent-name (ent)
1246 (extern-alien "sb_dirent_name" (function c-string system-area-pointer
))
1249 ;;;; A magic constant for wait3().
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
)