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 (defmacro def-enum
(inc cur
&rest names
)
31 (flet ((defform (name)
32 (prog1 (when name
`(defconstant ,name
,cur
))
33 (setf cur
(funcall inc cur
1)))))
34 `(progn ,@(mapcar #'defform names
))))
36 ;;; Given a C-level zero-terminated array of C strings, return a
37 ;;; corresponding Lisp-level list of SIMPLE-STRINGs.
38 (defun c-strings->string-list
(c-strings)
39 (declare (type (alien (* c-string
)) c-strings
))
40 (let ((reversed-result nil
))
41 (dotimes (i most-positive-fixnum
(error "argh! can't happen"))
42 (declare (type index i
))
43 (let ((c-string (deref c-strings i
)))
45 (push c-string reversed-result
)
46 (return (nreverse reversed-result
)))))))
48 ;;;; Lisp types used by syscalls
50 (deftype unix-pathname
() 'simple-string
)
51 (deftype unix-fd
() `(integer 0 ,most-positive-fixnum
))
53 (deftype unix-file-mode
() '(unsigned-byte 32))
54 (deftype unix-pid
() '(unsigned-byte 32))
55 (deftype unix-uid
() '(unsigned-byte 32))
56 (deftype unix-gid
() '(unsigned-byte 32))
60 (/show0
"unix.lisp 74")
62 ;;; FIXME: The various FOO-SYSCALL-BAR macros, and perhaps some other
63 ;;; macros in this file, are only used in this file, and could be
64 ;;; implemented using SB!XC:DEFMACRO wrapped in EVAL-WHEN.
66 (defmacro syscall
((name &rest arg-types
) success-form
&rest args
)
68 (declare (optimize (sb!c
::float-accuracy
0)))
69 (let ((result (alien-funcall (extern-alien ,name
(function int
,@arg-types
))
72 (values nil
(get-errno))
75 ;;; This is like SYSCALL, but if it fails, signal an error instead of
76 ;;; returning error codes. Should only be used for syscalls that will
77 ;;; never really get an error.
78 (defmacro syscall
* ((name &rest arg-types
) success-form
&rest args
)
80 (declare (optimize (sb!c
::float-accuracy
0)))
81 (let ((result (alien-funcall (extern-alien ,name
(function int
,@arg-types
))
84 (error "Syscall ~A failed: ~A" ,name
(strerror))
87 (/show0
"unix.lisp 109")
89 (defmacro void-syscall
((name &rest arg-types
) &rest args
)
90 `(syscall (,name
,@arg-types
) (values t
0) ,@args
))
92 (defmacro int-syscall
((name &rest arg-types
) &rest args
)
93 `(syscall (,name
,@arg-types
) (values result
0) ,@args
))
95 (defmacro with-restarted-syscall
((&optional
(value (gensym))
97 syscall-form
&rest body
)
99 "Evaluate BODY with VALUE and ERRNO bound to the return values of
100 SYSCALL-FORM. Repeat evaluation of SYSCALL-FORM if it is interrupted."
101 `(let (,value
,errno
)
102 (loop (multiple-value-setq (,value
,errno
)
104 (unless #!-win32
(eql ,errno sb
!unix
:eintr
) #!+win32 nil
105 (return (values ,value
,errno
))))
110 (defconstant espipe
29))
112 ;;;; hacking the Unix environment
115 (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."
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 c-string
) 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
138 (define-alien-type fd-mask unsigned-long
)
140 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
141 (defconstant fd-setsize
1024))
143 (define-alien-type nil
145 (fds-bits (array fd-mask
#.
(/ fd-setsize
146 sb
!vm
:n-machine-word-bits
)))))
148 (/show0
"unix.lisp 304")
153 ;;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
155 ;;; Open the file whose pathname is specified by PATH for reading
156 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
157 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
159 ;;; If the O_CREAT flag is specified, then the file is created with a
160 ;;; permission of argument MODE if the file doesn't exist. An integer
161 ;;; file descriptor is returned by UNIX-OPEN.
162 (defun unix-open (path flags mode
)
163 (declare (type unix-pathname path
)
165 (type unix-file-mode mode
))
166 (int-syscall ("open" c-string int int
)
168 (logior #!+win32 o_binary
169 #!+largefile o_largefile
173 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
174 ;;; associated with it.
175 (/show0
"unix.lisp 391")
176 (defun unix-close (fd)
177 (declare (type unix-fd fd
))
178 (void-syscall ("close" int
) fd
))
182 ;;; There are good reasons to implement some OPEN options with an
183 ;;; mkstemp(3)-like routine, but we don't do that yet. Instead, this
184 ;;; function is used only to make a temporary file for RUN-PROGRAM.
185 ;;; sb_mkstemp() is a wrapper that lives in src/runtime/wrap.c. Since
186 ;;; SUSv3 mkstemp() doesn't specify the mode of the created file and
187 ;;; since we have to implement most of this ourselves for Windows
188 ;;; anyway, it seems worthwhile to depart from the mkstemp()
189 ;;; specification by taking a mode to use when creating the new file.
190 (defun sb-mkstemp (template-string mode
)
191 (declare (type string template-string
)
192 (type unix-file-mode mode
))
193 (let ((template-buffer (string-to-octets template-string
:null-terminate t
)))
194 (with-pinned-objects (template-buffer)
195 (let ((fd (alien-funcall (extern-alien "sb_mkstemp"
196 (function int
(* char
) int
))
197 (vector-sap template-buffer
)
200 (values nil
(get-errno))
201 (values fd
(octets-to-string template-buffer
)))))))
205 ;; A time value that is accurate to the nearest
206 ;; microsecond but also has a range of years.
207 ;; CLH: Note that tv-usec used to be a time-t, but that this seems
208 ;; problematic on Darwin x86-64 (and wrong). Trying suseconds-t.
209 #!-
(or win32 openbsd
)
210 (define-alien-type nil
212 (tv-sec time-t
) ; seconds
213 (tv-usec suseconds-t
))) ; and microseconds
215 ;; The above definition doesn't work on 64-bit OpenBSD platforms.
216 ;; Both tv_sec and tv_usec are declared as long instead of time_t, and
217 ;; time_t is a typedef for int.
219 (define-alien-type nil
221 (tv-sec long
) ; seconds
222 (tv-usec long
))) ; and microseconds
225 (define-alien-type nil
227 (tv-sec time-t
) ; seconds
228 (tv-usec long
))) ; and microseconds
232 (defconstant rusage_self
0) ; the calling process
233 (defconstant rusage_children -
1) ; terminated child processes
234 (defconstant rusage_both -
2)
236 (define-alien-type nil
238 (ru-utime (struct timeval
)) ; user time used
239 (ru-stime (struct timeval
)) ; system time used.
240 (ru-maxrss long
) ; maximum resident set size (in kilobytes)
241 (ru-ixrss long
) ; integral shared memory size
242 (ru-idrss long
) ; integral unshared data size
243 (ru-isrss long
) ; integral unshared stack size
244 (ru-minflt long
) ; page reclaims
245 (ru-majflt long
) ; page faults
246 (ru-nswap long
) ; swaps
247 (ru-inblock long
) ; block input operations
248 (ru-oublock long
) ; block output operations
249 (ru-msgsnd long
) ; messages sent
250 (ru-msgrcv long
) ; messages received
251 (ru-nsignals long
) ; signals received
252 (ru-nvcsw long
) ; voluntary context switches
253 (ru-nivcsw long
))) ; involuntary context switches
257 ;;; Given a file path (a string) and one of four constant modes,
258 ;;; return T if the file is accessible with that mode and NIL if not.
259 ;;; When NIL, also return an errno value with NIL which tells why the
260 ;;; file was not accessible.
262 ;;; The access modes are:
263 ;;; r_ok Read permission.
264 ;;; w_ok Write permission.
265 ;;; x_ok Execute permission.
266 ;;; f_ok Presence of file.
268 ;;; In Windows, the MODE argument to access is defined in terms of
269 ;;; literal magic numbers---there are no constants to grovel. X_OK
275 (defconstant r_ok
4))
277 (defun unix-access (path mode
)
278 (declare (type unix-pathname path
)
280 (void-syscall ("access" c-string int
) path mode
))
282 ;;; values for the second argument to UNIX-LSEEK
283 (defconstant l_set
0) ; to set the file pointer
284 (defconstant l_incr
1) ; to increment the file pointer
285 (defconstant l_xtnd
2) ; to extend the file size
287 ;;; Is a stream interactive?
288 (defun unix-isatty (fd)
289 (declare (type unix-fd fd
))
290 (int-syscall ("isatty" int
) fd
))
292 (defun unix-lseek (fd offset whence
)
293 "Unix-lseek accepts a file descriptor and moves the file pointer by
294 OFFSET octets. Whence can be any of the following:
296 L_SET Set the file pointer.
297 L_INCR Increment the file pointer.
298 L_XTND Extend the file size.
300 (declare (type unix-fd fd
)
301 (type (integer 0 2) whence
))
302 (let ((result (alien-funcall (extern-alien #!-largefile
"lseek"
303 #!+largefile
"lseek_largefile"
304 (function off-t int off-t int
))
307 (values nil
(get-errno))
310 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
311 ;;; It attempts to read len bytes from the device associated with fd
312 ;;; and store them into the buffer. It returns the actual number of
316 (declaim (maybe-inline unix-read
))
318 (defun unix-read (fd buf len
)
319 (declare (type unix-fd fd
)
320 (type (unsigned-byte 32) len
))
321 (int-syscall ("read" int
(* char
) int
) fd buf len
))
323 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
324 ;;; length to write. It attempts to write len bytes to the device
325 ;;; associated with fd from the buffer starting at offset. It returns
326 ;;; the actual number of bytes written.
327 (defun unix-write (fd buf offset len
)
328 (declare (type unix-fd fd
)
329 (type (unsigned-byte 32) offset len
))
331 (declare (system-area-pointer sap
))
332 (int-syscall ("write" int
(* char
) int
)
334 (with-alien ((ptr (* char
) sap
))
335 (addr (deref ptr offset
)))
338 ((simple-array * (*))
339 (with-pinned-objects (buf)
340 (%write
(vector-sap buf
))))
344 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
345 ;;; output pipe. Return two values: if no error occurred the first
346 ;;; value is the pipe to be read from and the second is can be written
347 ;;; to. If an error occurred the first value is NIL and the second the
351 (with-alien ((fds (array int
2)))
352 (syscall ("pipe" (* int
))
353 (values (deref fds
0) (deref fds
1))
354 (cast fds
(* int
)))))
356 (defun msvcrt-raw-pipe (fds size mode
)
357 (syscall ("_pipe" (* int
) int int
)
358 (values (deref fds
0) (deref fds
1))
359 (cast fds
(* int
)) size mode
))
362 (with-alien ((fds (array int
2)))
363 (msvcrt-raw-pipe fds
256 o_binary
)))
365 ;; Windows mkdir() doesn't take the mode argument. It's cdecl, so we could
366 ;; actually call it passing the mode argument, but some sharp-eyed reader
367 ;; would put five and twenty-seven together and ask us about it, so...
370 (defun unix-mkdir (name mode
)
371 (declare (type unix-pathname name
)
372 (type unix-file-mode mode
)
373 #!+win32
(ignore mode
))
374 (void-syscall ("mkdir" c-string
#!-win32 int
) name
#!-win32 mode
))
376 ;;; Given a C char* pointer allocated by malloc(), free it and return a
377 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
378 (defun newcharstar-string (newcharstar)
379 (declare (type (alien (* char
)) newcharstar
))
380 (if (null-alien newcharstar
)
383 (cast newcharstar c-string
)
384 (free-alien newcharstar
))))
386 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
387 ;;; style returned by getcwd() (no trailing slash character).
389 (defun posix-getcwd ()
390 ;; This implementation relies on a BSD/Linux extension to getcwd()
391 ;; behavior, automatically allocating memory when a null buffer
392 ;; pointer is used. On a system which doesn't support that
393 ;; extension, it'll have to be rewritten somehow.
395 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
396 ;; buffer pointer, it will automatically allocate size space. The
397 ;; KLUDGE in this solution arises because we have just read off
398 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
399 ;; a constant. Going the grovel_headers route doesn't seem to be
400 ;; helpful, either, as Solaris doesn't export PATH_MAX from
403 ;; FIXME: The (,stub,) nastiness produces an error message about a
404 ;; comma not inside a backquote. This error has absolutely nothing
405 ;; to do with the actual meaning of the error (and little to do with
406 ;; its location, either).
407 #!-
(or linux openbsd freebsd netbsd sunos osf1 darwin hpux win32
) (,stub
,)
408 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin hpux win32
)
409 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
414 #!+(or linux openbsd freebsd netbsd darwin win32
) 0
415 #!+(or sunos osf1 hpux
) 1025))
416 (simple-perror "getcwd")))
418 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
419 ;;; by a slash character.
420 (defun posix-getcwd/ ()
421 (concatenate 'string
(posix-getcwd) "/"))
423 ;;; Duplicate an existing file descriptor (given as the argument) and
424 ;;; return it. If FD is not a valid file descriptor, NIL and an error
425 ;;; number are returned.
427 (declare (type unix-fd fd
))
428 (int-syscall ("dup" int
) fd
))
430 ;;; Terminate the current process with an optional error code. If
431 ;;; successful, the call doesn't return. If unsuccessful, the call
432 ;;; returns NIL and an error number.
433 (defun unix-exit (&optional
(code 0))
434 (declare (type (signed-byte 32) code
))
435 (void-syscall ("exit" int
) code
))
437 ;;; Return the process id of the current process.
438 (define-alien-routine ("getpid" unix-getpid
) int
)
440 ;;; Return the real user id associated with the current process.
442 (define-alien-routine ("getuid" unix-getuid
) int
)
444 ;;; Translate a user id into a login name.
446 (defun uid-username (uid)
447 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
448 (function (* char
) int
))
450 (error "found no match for Unix uid=~S" uid
)))
452 ;;; Return the namestring of the home directory, being careful to
453 ;;; include a trailing #\/
455 (defun uid-homedir (uid)
456 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
457 (function (* char
) int
))
459 (error "failed to resolve home directory for Unix uid=~S" uid
)))
461 ;;; Invoke readlink(2) on the file name specified by PATH. Return
462 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
465 (defun unix-readlink (path)
466 (declare (type unix-pathname path
))
467 (with-alien ((ptr (* char
)
468 (alien-funcall (extern-alien
470 (function (* char
) c-string
))
473 (values nil
(get-errno))
474 (multiple-value-prog1
475 (values (with-alien ((c-string c-string ptr
)) c-string
)
479 ;; Win32 doesn't do links, but something likes to call this anyway.
480 ;; Something in this file, no less. But it only takes one result, so...
481 (defun unix-readlink (path)
482 (declare (ignore path
))
485 (defun unix-realpath (path)
486 (declare (type unix-pathname path
))
487 (with-alien ((ptr (* char
)
488 (alien-funcall (extern-alien
490 (function (* char
) c-string
))
493 (values nil
(get-errno))
494 (multiple-value-prog1
495 (values (with-alien ((c-string c-string ptr
)) c-string
)
499 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
500 ;;; name and the file if this is the last link.
501 (defun unix-unlink (name)
502 (declare (type unix-pathname name
))
503 (void-syscall ("unlink" c-string
) name
))
505 ;;; Return the name of the host machine as a string.
507 (defun unix-gethostname ()
508 (with-alien ((buf (array char
256)))
509 (syscall ("gethostname" (* char
) int
)
511 (cast buf
(* char
)) 256)))
514 (defun unix-setsid ()
515 (int-syscall ("setsid")))
519 ;;; UNIX-IOCTL performs a variety of operations on open i/o
520 ;;; descriptors. See the UNIX Programmer's Manual for more
523 (defun unix-ioctl (fd cmd arg
)
524 (declare (type unix-fd fd
)
525 (type (signed-byte 32) cmd
))
526 (void-syscall ("ioctl" int int
(* char
)) fd cmd arg
))
530 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
532 ;;; This is like getrusage(2), except it returns only the system and
533 ;;; user time, and returns the seconds and microseconds as separate
535 #!-sb-fluid
(declaim (inline unix-fast-getrusage
))
537 (defun unix-fast-getrusage (who)
538 (declare (values (member t
)
539 (unsigned-byte 31) (integer 0 1000000)
540 (unsigned-byte 31) (integer 0 1000000)))
541 (with-alien ((usage (struct rusage
)))
542 (syscall* ("getrusage" int
(* (struct rusage
)))
544 (slot (slot usage
'ru-utime
) 'tv-sec
)
545 (slot (slot usage
'ru-utime
) 'tv-usec
)
546 (slot (slot usage
'ru-stime
) 'tv-sec
)
547 (slot (slot usage
'ru-stime
) 'tv-usec
))
550 ;;; Return information about the resource usage of the process
551 ;;; specified by WHO. WHO can be either the current process
552 ;;; (rusage_self) or all of the terminated child processes
553 ;;; (rusage_children). NIL and an error number is returned if the call
556 (defun unix-getrusage (who)
557 (with-alien ((usage (struct rusage
)))
558 (syscall ("getrusage" int
(* (struct rusage
)))
560 (+ (* (slot (slot usage
'ru-utime
) 'tv-sec
) 1000000)
561 (slot (slot usage
'ru-utime
) 'tv-usec
))
562 (+ (* (slot (slot usage
'ru-stime
) 'tv-sec
) 1000000)
563 (slot (slot usage
'ru-stime
) 'tv-usec
))
564 (slot usage
'ru-maxrss
)
565 (slot usage
'ru-ixrss
)
566 (slot usage
'ru-idrss
)
567 (slot usage
'ru-isrss
)
568 (slot usage
'ru-minflt
)
569 (slot usage
'ru-majflt
)
570 (slot usage
'ru-nswap
)
571 (slot usage
'ru-inblock
)
572 (slot usage
'ru-oublock
)
573 (slot usage
'ru-msgsnd
)
574 (slot usage
'ru-msgrcv
)
575 (slot usage
'ru-nsignals
)
576 (slot usage
'ru-nvcsw
)
577 (slot usage
'ru-nivcsw
))
582 (defvar *on-dangerous-select
* :warn
)
584 ;;; Calling select in a bad place can hang in a nasty manner, so it's better
585 ;;; to have some way to detect these.
586 (defun note-dangerous-select ()
587 (let ((action *on-dangerous-select
*)
588 (*on-dangerous-select
* nil
))
591 (warn "Starting a select without a timeout while interrupts are ~
594 (error "Starting a select without a timeout while interrupts are ~
598 "=== Starting a select without a timeout while interrupts are disabled. ==="
600 (sb!debug
:backtrace
)))
603 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
605 ;;; Perform the UNIX select(2) system call.
606 (declaim (inline unix-fast-select
))
607 (defun unix-fast-select (num-descriptors
608 read-fds write-fds exception-fds
609 timeout-secs timeout-usecs
)
610 (declare (type (integer 0 #.fd-setsize
) num-descriptors
)
611 (type (or (alien (* (struct fd-set
))) null
)
612 read-fds write-fds exception-fds
)
613 (type (or null
(unsigned-byte 31)) timeout-secs timeout-usecs
))
614 (flet ((select (tv-sap)
615 (int-syscall ("select" int
(* (struct fd-set
)) (* (struct fd-set
))
616 (* (struct fd-set
)) (* (struct timeval
)))
617 num-descriptors read-fds write-fds exception-fds
619 (cond ((or timeout-secs timeout-usecs
)
620 (with-alien ((tv (struct timeval
)))
621 (setf (slot tv
'tv-sec
) (or timeout-secs
0))
622 (setf (slot tv
'tv-usec
) (or timeout-usecs
0))
623 (select (alien-sap (addr tv
)))))
625 (unless *interrupts-enabled
*
626 (note-dangerous-select))
627 (select (int-sap 0))))))
629 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
630 ;;; to happen on one of them or to time out.
631 (defmacro num-to-fd-set
(fdset num
)
634 (setf (deref (slot ,fdset
'fds-bits
) 0) ,num
)
635 ,@(loop for index upfrom
1 below
(/ fd-setsize
636 sb
!vm
:n-machine-word-bits
)
637 collect
`(setf (deref (slot ,fdset
'fds-bits
) ,index
) 0)))
639 ,@(loop for index upfrom
0 below
(/ fd-setsize
640 sb
!vm
:n-machine-word-bits
)
641 collect
`(setf (deref (slot ,fdset
'fds-bits
) ,index
)
642 (ldb (byte sb
!vm
:n-machine-word-bits
643 ,(* index sb
!vm
:n-machine-word-bits
))
646 (defmacro fd-set-to-num
(nfds fdset
)
647 `(if (<= ,nfds sb
!vm
:n-machine-word-bits
)
648 (deref (slot ,fdset
'fds-bits
) 0)
649 (+ ,@(loop for index upfrom
0 below
(/ fd-setsize
650 sb
!vm
:n-machine-word-bits
)
651 collect
`(ash (deref (slot ,fdset
'fds-bits
) ,index
)
652 ,(* index sb
!vm
:n-machine-word-bits
))))))
654 ;;; Examine the sets of descriptors passed as arguments to see whether
655 ;;; they are ready for reading and writing. See the UNIX Programmer's
656 ;;; Manual for more information.
657 (defun unix-select (nfds rdfds wrfds xpfds to-secs
&optional
(to-usecs 0))
658 (declare (type (integer 0 #.fd-setsize
) nfds
)
659 (type unsigned-byte rdfds wrfds xpfds
)
660 (type (or (unsigned-byte 31) null
) to-secs
)
661 (type (unsigned-byte 31) to-usecs
)
662 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
663 (with-alien ((tv (struct timeval
))
664 (rdf (struct fd-set
))
665 (wrf (struct fd-set
))
666 (xpf (struct fd-set
)))
668 (setf (slot tv
'tv-sec
) to-secs
669 (slot tv
'tv-usec
) to-usecs
))
670 ((not *interrupts-enabled
*)
671 (note-dangerous-select)))
672 (num-to-fd-set rdf rdfds
)
673 (num-to-fd-set wrf wrfds
)
674 (num-to-fd-set xpf xpfds
)
675 (macrolet ((frob (lispvar alienvar
)
676 `(if (zerop ,lispvar
)
678 (alien-sap (addr ,alienvar
)))))
679 (syscall ("select" int
(* (struct fd-set
)) (* (struct fd-set
))
680 (* (struct fd-set
)) (* (struct timeval
)))
682 (fd-set-to-num nfds rdf
)
683 (fd-set-to-num nfds wrf
)
684 (fd-set-to-num nfds xpf
))
685 nfds
(frob rdfds rdf
) (frob wrfds wrf
) (frob xpfds xpf
)
686 (if to-secs
(alien-sap (addr tv
)) (int-sap 0))))))
690 ;;; This is a structure defined in src/runtime/wrap.c, to look
691 ;;; basically like "struct stat" according to stat(2). It may not
692 ;;; actually correspond to the real in-memory stat structure that the
693 ;;; syscall uses, and that's OK. Linux in particular is packed full of
694 ;;; stat macros, and trying to keep Lisp code in correspondence with
695 ;;; it is more pain than it's worth, so we just let our C runtime
696 ;;; synthesize a nice consistent structure for us.
698 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
699 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
700 ;;; those. We don't actually access that field anywhere, though, so
701 ;;; until we can get 64 bit alien support it'll do. Also note that
702 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
703 ;;; quantity on Alpha. And FIXME: "No one would want a file length
704 ;;; longer than 32 bits anyway, right?":-|
706 ;;; The comment about alien and 64-bit quantities has not been kept in
707 ;;; sync with the comment now in wrap.h (formerly wrap.c), but it's
708 ;;; not clear whether either comment is correct. -- RMK 2007-11-14.
709 (define-alien-type nil
714 (st-nlink wst-nlink-t
)
719 (st-blksize wst-blksize-t
)
720 (st-blocks wst-blkcnt-t
)
725 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
726 ;;; family of Unix system calls
728 ;;; FIXME: I think this should probably not be INLINE. However, when
729 ;;; this was not inline, it seemed to cause memory corruption
730 ;;; problems. My first guess is that it's a bug in the FFI code, where
731 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
732 ;;; around a call to a function returning >10 values. But I didn't try
733 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
734 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
735 ;;; output in the not-inlined case and see whether there's a problem,
736 ;;; and maybe even find a fix..
737 (declaim (inline %extract-stat-results
))
738 (defun %extract-stat-results
(wrapped-stat)
739 (declare (type (alien (* (struct wrapped_stat
))) wrapped-stat
))
741 (slot wrapped-stat
'st-dev
)
742 (slot wrapped-stat
'st-ino
)
743 (slot wrapped-stat
'st-mode
)
744 (slot wrapped-stat
'st-nlink
)
745 (slot wrapped-stat
'st-uid
)
746 (slot wrapped-stat
'st-gid
)
747 (slot wrapped-stat
'st-rdev
)
748 (slot wrapped-stat
'st-size
)
749 (slot wrapped-stat
'st-atime
)
750 (slot wrapped-stat
'st-mtime
)
751 (slot wrapped-stat
'st-ctime
)
752 (slot wrapped-stat
'st-blksize
)
753 (slot wrapped-stat
'st-blocks
)))
755 ;;; Unix system calls in the stat(2) family are handled by calls to
756 ;;; C-level wrapper functions which copy all the raw "struct stat"
757 ;;; slots into the system-independent wrapped_stat format.
758 ;;; stat(2) <-> stat_wrapper()
759 ;;; fstat(2) <-> fstat_wrapper()
760 ;;; lstat(2) <-> lstat_wrapper()
761 (defun unix-stat (name)
762 (declare (type unix-pathname name
))
763 (with-alien ((buf (struct wrapped_stat
)))
764 (syscall ("stat_wrapper" c-string
(* (struct wrapped_stat
)))
765 (%extract-stat-results
(addr buf
))
767 (defun unix-lstat (name)
768 (declare (type unix-pathname name
))
769 (with-alien ((buf (struct wrapped_stat
)))
770 (syscall ("lstat_wrapper" c-string
(* (struct wrapped_stat
)))
771 (%extract-stat-results
(addr buf
))
773 (defun unix-fstat (fd)
774 (declare (type unix-fd fd
))
775 (with-alien ((buf (struct wrapped_stat
)))
776 (syscall ("fstat_wrapper" int
(* (struct wrapped_stat
)))
777 (%extract-stat-results
(addr buf
))
782 ;; the POSIX.4 structure for a time value. This is like a "struct
783 ;; timeval" but has nanoseconds instead of microseconds.
785 (define-alien-type nil
787 (tv-sec long
) ; seconds
788 (tv-nsec long
))) ; nanoseconds
790 ;; Just as with struct timeval, 64-bit OpenBSD has problems with the
791 ;; above definition. tv_sec is declared as time_t instead of long,
792 ;; and time_t is a typedef for int.
794 (define-alien-type nil
796 (tv-sec time-t
) ; seconds
797 (tv-nsec long
))) ; nanoseconds
799 ;; used by other time functions
800 (define-alien-type nil
802 (tm-sec int
) ; Seconds. [0-60] (1 leap second)
803 (tm-min int
) ; Minutes. [0-59]
804 (tm-hour int
) ; Hours. [0-23]
805 (tm-mday int
) ; Day. [1-31]
806 (tm-mon int
) ; Month. [0-11]
807 (tm-year int
) ; Year - 1900.
808 (tm-wday int
) ; Day of week. [0-6]
809 (tm-yday int
) ; Days in year. [0-365]
810 (tm-isdst int
) ; DST. [-1/0/1]
811 (tm-gmtoff long
) ; Seconds east of UTC.
812 (tm-zone c-string
))) ; Timezone abbreviation.
814 (define-alien-routine get-timezone sb
!alien
:void
815 (when sb
!alien
:long
:in
)
816 (seconds-west sb
!alien
:int
:out
)
817 (daylight-savings-p sb
!alien
:boolean
:out
))
820 (defun nanosleep (secs nsecs
)
821 (with-alien ((req (struct timespec
))
822 (rem (struct timespec
)))
823 (setf (slot req
'tv-sec
) secs
)
824 (setf (slot req
'tv-nsec
) nsecs
)
825 (loop while
(eql sb
!unix
:eintr
827 (int-syscall ("nanosleep" (* (struct timespec
))
828 (* (struct timespec
)))
829 (addr req
) (addr rem
))))
830 do
(rotatef req rem
))))
832 (defun unix-get-seconds-west (secs)
833 (multiple-value-bind (ignore seconds dst
) (get-timezone secs
)
834 (declare (ignore ignore
) (ignore dst
))
839 ;;; Structure crudely representing a timezone. KLUDGE: This is
840 ;;; obsolete and should never be used.
841 (define-alien-type nil
843 (tz-minuteswest int
) ; minutes west of Greenwich
844 (tz-dsttime int
))) ; type of dst correction
846 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
847 ;;; and microseconds of the current time of day, the timezone (in
848 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
849 ;;; doesn't work, it returns NIL and the errno.
850 #!-sb-fluid
(declaim (inline unix-gettimeofday
))
851 (defun unix-gettimeofday ()
852 #!+(and x86-64 darwin
)
853 (with-alien ((tv (struct timeval
)))
854 ;; CLH: FIXME! This seems to be a MacOS bug, but on x86-64/darwin,
855 ;; gettimeofday occasionally fails. passing in a null pointer for
856 ;; the timezone struct seems to work around the problem. I can't
857 ;; find any instances in the SBCL where we actually ues the
858 ;; timezone values, so we just punt for the moment.
859 (syscall* ("gettimeofday" (* (struct timeval
))
860 (* (struct timezone
)))
866 #!-
(and x86-64 darwin
)
867 (with-alien ((tv (struct timeval
))
868 (tz (struct timezone
)))
869 (syscall* ("gettimeofday" (* (struct timeval
))
870 (* (struct timezone
)))
874 (slot tz
'tz-minuteswest
)
875 (slot tz
'tz-dsttime
))
880 ;; Type of the second argument to `getitimer' and
881 ;; the second and third arguments `setitimer'.
882 (define-alien-type nil
884 (it-interval (struct timeval
)) ; timer interval
885 (it-value (struct timeval
)))) ; current value
887 (defconstant itimer-real
0)
888 (defconstant itimer-virtual
1)
889 (defconstant itimer-prof
2)
892 (defun unix-getitimer (which)
893 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
894 three system timers (:real :virtual or :profile). On success,
895 unix-getitimer returns 5 values,
896 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
897 (declare (type (member :real
:virtual
:profile
) which
)
899 (unsigned-byte 29) (mod 1000000)
900 (unsigned-byte 29) (mod 1000000)))
901 (let ((which (ecase which
903 (:virtual itimer-virtual
)
904 (:profile itimer-prof
))))
905 (with-alien ((itv (struct itimerval
)))
906 (syscall* ("getitimer" int
(* (struct itimerval
)))
908 (slot (slot itv
'it-interval
) 'tv-sec
)
909 (slot (slot itv
'it-interval
) 'tv-usec
)
910 (slot (slot itv
'it-value
) 'tv-sec
)
911 (slot (slot itv
'it-value
) 'tv-usec
))
912 which
(alien-sap (addr itv
))))))
915 (defun unix-setitimer (which int-secs int-usec val-secs val-usec
)
916 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
917 three system timers (:real :virtual or :profile). A SIGALRM signal
918 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
919 when non-zero, is <seconds+microseconds> to be loaded each time
920 the timer expires. Setting INTERVAL and VALUE to zero disables
921 the timer. See the Unix man page for more details. On success,
922 unix-setitimer returns the old contents of the INTERVAL and VALUE
923 slots as in unix-getitimer."
924 (declare (type (member :real
:virtual
:profile
) which
)
925 (type (unsigned-byte 29) int-secs val-secs
)
926 (type (integer 0 (1000000)) int-usec val-usec
)
928 (unsigned-byte 29) (mod 1000000)
929 (unsigned-byte 29) (mod 1000000)))
930 (let ((which (ecase which
932 (:virtual itimer-virtual
)
933 (:profile itimer-prof
))))
934 (with-alien ((itvn (struct itimerval
))
935 (itvo (struct itimerval
)))
936 (setf (slot (slot itvn
'it-interval
) 'tv-sec
) int-secs
937 (slot (slot itvn
'it-interval
) 'tv-usec
) int-usec
938 (slot (slot itvn
'it-value
) 'tv-sec
) val-secs
939 (slot (slot itvn
'it-value
) 'tv-usec
) val-usec
)
940 (syscall* ("setitimer" int
(* (struct timeval
))(* (struct timeval
)))
942 (slot (slot itvo
'it-interval
) 'tv-sec
)
943 (slot (slot itvo
'it-interval
) 'tv-usec
)
944 (slot (slot itvo
'it-value
) 'tv-sec
)
945 (slot (slot itvo
'it-value
) 'tv-usec
))
946 which
(alien-sap (addr itvn
))(alien-sap (addr itvo
))))))
949 ;;; FIXME: Many Unix error code definitions were deleted from the old
950 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
951 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
952 ;;; unused symbols in package exports, but if I don't, there are
953 ;;; enough of them all in one place here that they should probably be
956 ;;;; support routines for dealing with Unix pathnames
958 (defun unix-file-kind (name &optional check-for-links
)
960 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
961 (declare (simple-string name
))
962 (multiple-value-bind (res dev ino mode
)
963 (if check-for-links
(unix-lstat name
) (unix-stat name
))
964 (declare (type (or fixnum null
) mode
)
967 (let ((kind (logand mode s-ifmt
)))
968 (cond ((eql kind s-ifdir
) :directory
)
969 ((eql kind s-ifreg
) :file
)
971 ((eql kind s-iflnk
) :link
)
974 (defconstant micro-seconds-per-internal-time-unit
975 (/ 1000000 sb
!xc
:internal-time-units-per-second
))
977 ;;; UNIX specific code, that has been cleanly separated from the
981 (declaim (inline system-internal-run-time
982 system-real-time-values
))
984 (defun system-real-time-values ()
985 (multiple-value-bind (_ sec usec
) (unix-gettimeofday)
986 (declare (ignore _
) (type (unsigned-byte 32) sec usec
))
987 (values sec
(truncate usec micro-seconds-per-internal-time-unit
))))
989 ;; There are two optimizations here that actually matter (on 32-bit
990 ;; systems): substract the epoch from seconds and milliseconds
991 ;; separately, as those should remain fixnums for the first 17 years
992 ;; or so of runtime. Also, avoid doing consing a new bignum if the
993 ;; result would be = to the last result given.
995 ;; Note: the next trick would be to spin a separate thread to update
996 ;; a global value once per internal tick, so each individual call to
997 ;; get-internal-real-time would be just a memory read... but that is
998 ;; probably best left for user-level code. ;)
1000 ;; Thanks to James Anderson for the optimization hint.
1002 ;; Yes, it is possible to a computation to be GET-INTERNAL-REAL-TIME
1011 (declare (type (unsigned-byte 32) e-sec c-sec
)
1012 (type fixnum e-msec c-msec
)
1013 (type unsigned-byte now
))
1014 (defun reinit-internal-real-time ()
1015 (setf (values e-sec e-msec
) (system-real-time-values)
1018 ;; If two threads call this at the same time, we're still safe, I
1019 ;; believe, as long as NOW is updated before either of C-MSEC or
1020 ;; C-SEC. Same applies to interrupts. --NS
1022 ;; I believe this is almost correct with x86/x86-64 cache
1023 ;; coherency, but if the new value of C-SEC, C-MSEC can become
1024 ;; visible to another CPU without NOW doing the same then it's
1025 ;; unsafe. It's `almost' correct on x86 because writes by other
1026 ;; processors may become visible in any order provided transitity
1027 ;; holds. With at least three cpus, C-MSEC and C-SEC may be from
1028 ;; different threads and an incorrect value may be returned.
1029 ;; Considering that this failure is not detectable by the caller -
1030 ;; it looks like time passes a bit slowly - and that it should be
1031 ;; an extremely rare occurance I'm inclinded to leave it as it is.
1033 (defun get-internal-real-time ()
1034 (multiple-value-bind (sec msec
) (system-real-time-values)
1035 (unless (and (= msec c-msec
) (= sec c-sec
))
1036 (setf now
(+ (* (- sec e-sec
)
1037 sb
!xc
:internal-time-units-per-second
)
1043 (defun system-internal-run-time ()
1044 (multiple-value-bind (ignore utime-sec utime-usec stime-sec stime-usec
)
1045 (unix-fast-getrusage rusage_self
)
1046 (declare (ignore ignore
)
1047 (type (unsigned-byte 31) utime-sec stime-sec
)
1048 ;; (Classic CMU CL had these (MOD 1000000) instead, but
1049 ;; at least in Linux 2.2.12, the type doesn't seem to
1050 ;; be documented anywhere and the observed behavior is
1051 ;; to sometimes return 1000000 exactly.)
1052 (type (integer 0 1000000) utime-usec stime-usec
))
1053 (let ((result (+ (* (+ utime-sec stime-sec
)
1054 sb
!xc
:internal-time-units-per-second
)
1055 (floor (+ utime-usec
1057 (floor micro-seconds-per-internal-time-unit
2))
1058 micro-seconds-per-internal-time-unit
))))
1061 ;;;; A magic constant for wait3().
1063 ;;;; FIXME: This used to be defined in run-program.lisp as
1064 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
1065 ;;;; According to some of the man pages, the #o177 is part of the API
1066 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
1067 ;;;; the headers that may or may not be the same thing. To be
1068 ;;;; investigated. -- CSR, 2002-03-25
1069 (defconstant wstopped
#o177
)
1072 ;;;; stuff not yet found in the header files
1074 ;;;; Abandon all hope who enters here...
1076 ;;; not checked for linux...
1077 (defmacro fd-set
(offset fd-set
)
1078 (let ((word (gensym))
1080 `(multiple-value-bind (,word
,bit
) (floor ,offset
1081 sb
!vm
:n-machine-word-bits
)
1082 (setf (deref (slot ,fd-set
'fds-bits
) ,word
)
1083 (logior (truly-the (unsigned-byte #.sb
!vm
:n-machine-word-bits
)
1085 (deref (slot ,fd-set
'fds-bits
) ,word
))))))
1087 ;;; not checked for linux...
1088 (defmacro fd-clr
(offset fd-set
)
1089 (let ((word (gensym))
1091 `(multiple-value-bind (,word
,bit
) (floor ,offset
1092 sb
!vm
:n-machine-word-bits
)
1093 (setf (deref (slot ,fd-set
'fds-bits
) ,word
)
1094 (logand (deref (slot ,fd-set
'fds-bits
) ,word
)
1095 (sb!kernel
:word-logical-not
1096 (truly-the (unsigned-byte #.sb
!vm
:n-machine-word-bits
)
1099 ;;; not checked for linux...
1100 (defmacro fd-isset
(offset fd-set
)
1101 (let ((word (gensym))
1103 `(multiple-value-bind (,word
,bit
) (floor ,offset
1104 sb
!vm
:n-machine-word-bits
)
1105 (logbitp ,bit
(deref (slot ,fd-set
'fds-bits
) ,word
)))))
1107 ;;; not checked for linux...
1108 (defmacro fd-zero
(fd-set)
1110 ,@(loop for index upfrom
0 below
(/ fd-setsize sb
!vm
:n-machine-word-bits
)
1111 collect
`(setf (deref (slot ,fd-set
'fds-bits
) ,index
) 0))))