1.0.22.22: (SETF FIND-CLASSOID) to drop DEFTYPE lambda-lists and source-locations
[sbcl/tcr.git] / src / code / unix.lisp
blob0a25f7b6240ac08200ae3ebe4498119ec5823a60
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 (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)))
44 (if c-string
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))
58 ;;;; system calls
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)
67 `(locally
68 (declare (optimize (sb!c::float-accuracy 0)))
69 (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
70 ,@args)))
71 (if (minusp result)
72 (values nil (get-errno))
73 ,success-form))))
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)
79 `(locally
80 (declare (optimize (sb!c::float-accuracy 0)))
81 (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
82 ,@args)))
83 (if (minusp result)
84 (error "Syscall ~A failed: ~A" ,name (strerror))
85 ,success-form))))
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))
96 (errno (gensym)))
97 syscall-form &rest body)
98 #!+sb-doc
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)
103 ,syscall-form)
104 (unless #!-win32 (eql ,errno sb!unix:eintr) #!+win32 nil
105 (return (values ,value ,errno))))
106 ,@body))
108 #!+win32
109 (progn
110 (defconstant espipe 29))
112 ;;;; hacking the Unix environment
114 #!-win32
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."
118 (name c-string))
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 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
137 ;;; layer.
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
144 (struct fd-set
145 (fds-bits (array fd-mask #.(/ fd-setsize
146 sb!vm:n-machine-word-bits)))))
148 (/show0 "unix.lisp 304")
151 ;;;; fcntl.h
152 ;;;;
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)
164 (type fixnum flags)
165 (type unix-file-mode mode))
166 (int-syscall ("open" c-string int int)
167 path
168 (logior #!+win32 o_binary
169 #!+largefile o_largefile
170 flags)
171 mode))
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))
180 ;;;; stdlib.h
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)
198 mode)))
199 (if (minusp fd)
200 (values nil (get-errno))
201 (values fd (octets-to-string template-buffer)))))))
203 ;;;; timebits.h
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 #!-win32
210 (define-alien-type nil
211 (struct timeval
212 (tv-sec time-t) ; seconds
213 (tv-usec suseconds-t))) ; and microseconds
215 #!+win32
216 (define-alien-type nil
217 (struct timeval
218 (tv-sec time-t) ; seconds
219 (tv-usec long))) ; and microseconds
221 ;;;; resourcebits.h
223 (defconstant rusage_self 0) ; the calling process
224 (defconstant rusage_children -1) ; terminated child processes
225 (defconstant rusage_both -2)
227 (define-alien-type nil
228 (struct rusage
229 (ru-utime (struct timeval)) ; user time used
230 (ru-stime (struct timeval)) ; system time used.
231 (ru-maxrss long) ; maximum resident set size (in kilobytes)
232 (ru-ixrss long) ; integral shared memory size
233 (ru-idrss long) ; integral unshared data size
234 (ru-isrss long) ; integral unshared stack size
235 (ru-minflt long) ; page reclaims
236 (ru-majflt long) ; page faults
237 (ru-nswap long) ; swaps
238 (ru-inblock long) ; block input operations
239 (ru-oublock long) ; block output operations
240 (ru-msgsnd long) ; messages sent
241 (ru-msgrcv long) ; messages received
242 (ru-nsignals long) ; signals received
243 (ru-nvcsw long) ; voluntary context switches
244 (ru-nivcsw long))) ; involuntary context switches
246 ;;;; unistd.h
248 ;;; Given a file path (a string) and one of four constant modes,
249 ;;; return T if the file is accessible with that mode and NIL if not.
250 ;;; When NIL, also return an errno value with NIL which tells why the
251 ;;; file was not accessible.
253 ;;; The access modes are:
254 ;;; r_ok Read permission.
255 ;;; w_ok Write permission.
256 ;;; x_ok Execute permission.
257 ;;; f_ok Presence of file.
259 ;;; In Windows, the MODE argument to access is defined in terms of
260 ;;; literal magic numbers---there are no constants to grovel. X_OK
261 ;;; is not defined.
262 #!+win32
263 (progn
264 (defconstant f_ok 0)
265 (defconstant w_ok 2)
266 (defconstant r_ok 4))
268 (defun unix-access (path mode)
269 (declare (type unix-pathname path)
270 (type (mod 8) mode))
271 (void-syscall ("access" c-string int) path mode))
273 ;;; values for the second argument to UNIX-LSEEK
274 (defconstant l_set 0) ; to set the file pointer
275 (defconstant l_incr 1) ; to increment the file pointer
276 (defconstant l_xtnd 2) ; to extend the file size
278 ;;; Is a stream interactive?
279 (defun unix-isatty (fd)
280 (declare (type unix-fd fd))
281 (int-syscall ("isatty" int) fd))
283 (defun unix-lseek (fd offset whence)
284 "Unix-lseek accepts a file descriptor and moves the file pointer by
285 OFFSET octets. Whence can be any of the following:
287 L_SET Set the file pointer.
288 L_INCR Increment the file pointer.
289 L_XTND Extend the file size.
291 (declare (type unix-fd fd)
292 (type (integer 0 2) whence))
293 (let ((result (alien-funcall (extern-alien #!-largefile "lseek"
294 #!+largefile "lseek_largefile"
295 (function off-t int off-t int))
296 fd offset whence)))
297 (if (minusp result)
298 (values nil (get-errno))
299 (values result 0))))
301 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
302 ;;; It attempts to read len bytes from the device associated with fd
303 ;;; and store them into the buffer. It returns the actual number of
304 ;;; bytes read.
306 #!-sb!fluid
307 (declaim (maybe-inline unix-read))
309 (defun unix-read (fd buf len)
310 (declare (type unix-fd fd)
311 (type (unsigned-byte 32) len))
312 (int-syscall ("read" int (* char) int) fd buf len))
314 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
315 ;;; length to write. It attempts to write len bytes to the device
316 ;;; associated with fd from the buffer starting at offset. It returns
317 ;;; the actual number of bytes written.
318 (defun unix-write (fd buf offset len)
319 (declare (type unix-fd fd)
320 (type (unsigned-byte 32) offset len))
321 (flet ((%write (sap)
322 (declare (system-area-pointer sap))
323 (int-syscall ("write" int (* char) int)
325 (with-alien ((ptr (* char) sap))
326 (addr (deref ptr offset)))
327 len)))
328 (etypecase buf
329 ((simple-array * (*))
330 (with-pinned-objects (buf)
331 (%write (vector-sap buf))))
332 (system-area-pointer
333 (%write 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
339 ;;; unix error code.
340 #!-win32
341 (defun unix-pipe ()
342 (with-alien ((fds (array int 2)))
343 (syscall ("pipe" (* int))
344 (values (deref fds 0) (deref fds 1))
345 (cast fds (* int)))))
346 #!+win32
347 (defun msvcrt-raw-pipe (fds size mode)
348 (syscall ("_pipe" (* int) int int)
349 (values (deref fds 0) (deref fds 1))
350 (cast fds (* int)) size mode))
351 #!+win32
352 (defun unix-pipe ()
353 (with-alien ((fds (array int 2)))
354 (msvcrt-raw-pipe fds 256 o_binary)))
356 ;; Windows mkdir() doesn't take the mode argument. It's cdecl, so we could
357 ;; actually call it passing the mode argument, but some sharp-eyed reader
358 ;; would put five and twenty-seven together and ask us about it, so...
359 ;; -- AB, 2005-12-27
360 #!-win32
361 (defun unix-mkdir (name mode)
362 (declare (type unix-pathname name)
363 (type unix-file-mode mode)
364 #!+win32 (ignore mode))
365 (void-syscall ("mkdir" c-string #!-win32 int) name #!-win32 mode))
367 ;;; Given a C char* pointer allocated by malloc(), free it and return a
368 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
369 (defun newcharstar-string (newcharstar)
370 (declare (type (alien (* char)) newcharstar))
371 (if (null-alien newcharstar)
373 (prog1
374 (cast newcharstar c-string)
375 (free-alien newcharstar))))
377 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
378 ;;; style returned by getcwd() (no trailing slash character).
379 #!-win32
380 (defun posix-getcwd ()
381 ;; This implementation relies on a BSD/Linux extension to getcwd()
382 ;; behavior, automatically allocating memory when a null buffer
383 ;; pointer is used. On a system which doesn't support that
384 ;; extension, it'll have to be rewritten somehow.
386 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
387 ;; buffer pointer, it will automatically allocate size space. The
388 ;; KLUDGE in this solution arises because we have just read off
389 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
390 ;; a constant. Going the grovel_headers route doesn't seem to be
391 ;; helpful, either, as Solaris doesn't export PATH_MAX from
392 ;; unistd.h.
394 ;; FIXME: The (,stub,) nastiness produces an error message about a
395 ;; comma not inside a backquote. This error has absolutely nothing
396 ;; to do with the actual meaning of the error (and little to do with
397 ;; its location, either).
398 #!-(or linux openbsd freebsd netbsd sunos osf1 darwin win32) (,stub,)
399 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin win32)
400 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
401 (function (* char)
402 (* char)
403 size-t))
405 #!+(or linux openbsd freebsd netbsd darwin win32) 0
406 #!+(or sunos osf1) 1025))
407 (simple-perror "getcwd")))
409 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
410 ;;; by a slash character.
411 (defun posix-getcwd/ ()
412 (concatenate 'string (posix-getcwd) "/"))
414 ;;; Duplicate an existing file descriptor (given as the argument) and
415 ;;; return it. If FD is not a valid file descriptor, NIL and an error
416 ;;; number are returned.
417 (defun unix-dup (fd)
418 (declare (type unix-fd fd))
419 (int-syscall ("dup" int) fd))
421 ;;; Terminate the current process with an optional error code. If
422 ;;; successful, the call doesn't return. If unsuccessful, the call
423 ;;; returns NIL and an error number.
424 (defun unix-exit (&optional (code 0))
425 (declare (type (signed-byte 32) code))
426 (void-syscall ("exit" int) code))
428 ;;; Return the process id of the current process.
429 (define-alien-routine ("getpid" unix-getpid) int)
431 ;;; Return the real user id associated with the current process.
432 #!-win32
433 (define-alien-routine ("getuid" unix-getuid) int)
435 ;;; Translate a user id into a login name.
436 #!-win32
437 (defun uid-username (uid)
438 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
439 (function (* char) int))
440 uid))
441 (error "found no match for Unix uid=~S" uid)))
443 ;;; Return the namestring of the home directory, being careful to
444 ;;; include a trailing #\/
445 #!-win32
446 (defun uid-homedir (uid)
447 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
448 (function (* char) int))
449 uid))
450 (error "failed to resolve home directory for Unix uid=~S" uid)))
452 ;;; Invoke readlink(2) on the file name specified by PATH. Return
453 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
454 ;;; failure.
455 #!-win32
456 (defun unix-readlink (path)
457 (declare (type unix-pathname path))
458 (with-alien ((ptr (* char)
459 (alien-funcall (extern-alien
460 "wrapped_readlink"
461 (function (* char) c-string))
462 path)))
463 (if (null-alien ptr)
464 (values nil (get-errno))
465 (multiple-value-prog1
466 (values (with-alien ((c-string c-string ptr)) c-string)
467 nil)
468 (free-alien ptr)))))
469 #!+win32
470 ;; Win32 doesn't do links, but something likes to call this anyway.
471 ;; Something in this file, no less. But it only takes one result, so...
472 (defun unix-readlink (path)
473 (declare (ignore path))
474 nil)
476 (defun unix-realpath (path)
477 (declare (type unix-pathname path))
478 (with-alien ((ptr (* char)
479 (alien-funcall (extern-alien
480 "sb_realpath"
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)))))
490 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
491 ;;; name and the file if this is the last link.
492 (defun unix-unlink (name)
493 (declare (type unix-pathname name))
494 (void-syscall ("unlink" c-string) name))
496 ;;; Return the name of the host machine as a string.
497 #!-win32
498 (defun unix-gethostname ()
499 (with-alien ((buf (array char 256)))
500 (syscall ("gethostname" (* char) int)
501 (cast buf c-string)
502 (cast buf (* char)) 256)))
504 #!-win32
505 (defun unix-setsid ()
506 (int-syscall ("setsid")))
508 ;;;; sys/ioctl.h
510 ;;; UNIX-IOCTL performs a variety of operations on open i/o
511 ;;; descriptors. See the UNIX Programmer's Manual for more
512 ;;; information.
513 #!-win32
514 (defun unix-ioctl (fd cmd arg)
515 (declare (type unix-fd fd)
516 (type (signed-byte 32) cmd))
517 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
519 ;;;; sys/resource.h
521 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
523 ;;; This is like getrusage(2), except it returns only the system and
524 ;;; user time, and returns the seconds and microseconds as separate
525 ;;; values.
526 #!-sb-fluid (declaim (inline unix-fast-getrusage))
527 #!-win32
528 (defun unix-fast-getrusage (who)
529 (declare (values (member t)
530 (unsigned-byte 31) (integer 0 1000000)
531 (unsigned-byte 31) (integer 0 1000000)))
532 (with-alien ((usage (struct rusage)))
533 (syscall* ("getrusage" int (* (struct rusage)))
534 (values t
535 (slot (slot usage 'ru-utime) 'tv-sec)
536 (slot (slot usage 'ru-utime) 'tv-usec)
537 (slot (slot usage 'ru-stime) 'tv-sec)
538 (slot (slot usage 'ru-stime) 'tv-usec))
539 who (addr usage))))
541 ;;; Return information about the resource usage of the process
542 ;;; specified by WHO. WHO can be either the current process
543 ;;; (rusage_self) or all of the terminated child processes
544 ;;; (rusage_children). NIL and an error number is returned if the call
545 ;;; fails.
546 #!-win32
547 (defun unix-getrusage (who)
548 (with-alien ((usage (struct rusage)))
549 (syscall ("getrusage" int (* (struct rusage)))
550 (values t
551 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
552 (slot (slot usage 'ru-utime) 'tv-usec))
553 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
554 (slot (slot usage 'ru-stime) 'tv-usec))
555 (slot usage 'ru-maxrss)
556 (slot usage 'ru-ixrss)
557 (slot usage 'ru-idrss)
558 (slot usage 'ru-isrss)
559 (slot usage 'ru-minflt)
560 (slot usage 'ru-majflt)
561 (slot usage 'ru-nswap)
562 (slot usage 'ru-inblock)
563 (slot usage 'ru-oublock)
564 (slot usage 'ru-msgsnd)
565 (slot usage 'ru-msgrcv)
566 (slot usage 'ru-nsignals)
567 (slot usage 'ru-nvcsw)
568 (slot usage 'ru-nivcsw))
569 who (addr usage))))
571 ;;;; sys/select.h
573 (defvar *on-dangerous-select* :warn)
575 ;;; Calling select in a bad place can hang in a nasty manner, so it's better
576 ;;; to have some way to detect these.
577 (defun note-dangerous-select ()
578 (let ((action *on-dangerous-select*)
579 (*on-dangerous-select* nil))
580 (case action
581 (:warn
582 (warn "Starting a select without a timeout while interrupts are ~
583 disabled."))
584 (:error
585 (error "Starting a select without a timeout while interrupts are ~
586 disabled."))
587 (:backtrace
588 (write-line
589 "=== Starting a select without a timeout while interrupts are disabled. ==="
590 *debug-io*)
591 (sb!debug:backtrace)))
592 nil))
594 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
596 ;;; Perform the UNIX select(2) system call.
597 (declaim (inline unix-fast-select))
598 (defun unix-fast-select (num-descriptors
599 read-fds write-fds exception-fds
600 timeout-secs timeout-usecs)
601 (declare (type (integer 0 #.fd-setsize) num-descriptors)
602 (type (or (alien (* (struct fd-set))) null)
603 read-fds write-fds exception-fds)
604 (type (or null (unsigned-byte 31)) timeout-secs timeout-usecs))
605 (flet ((select (tv-sap)
606 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
607 (* (struct fd-set)) (* (struct timeval)))
608 num-descriptors read-fds write-fds exception-fds
609 tv-sap)))
610 (cond ((or timeout-secs timeout-usecs)
611 (with-alien ((tv (struct timeval)))
612 (setf (slot tv 'tv-sec) (or timeout-secs 0))
613 (setf (slot tv 'tv-usec) (or timeout-usecs 0))
614 (select (alien-sap (addr tv)))))
616 (unless *interrupts-enabled*
617 (note-dangerous-select))
618 (select (int-sap 0))))))
620 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
621 ;;; to happen on one of them or to time out.
622 (defmacro num-to-fd-set (fdset num)
623 `(if (fixnump ,num)
624 (progn
625 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
626 ,@(loop for index upfrom 1 below (/ fd-setsize
627 sb!vm:n-machine-word-bits)
628 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
629 (progn
630 ,@(loop for index upfrom 0 below (/ fd-setsize
631 sb!vm:n-machine-word-bits)
632 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
633 (ldb (byte sb!vm:n-machine-word-bits
634 ,(* index sb!vm:n-machine-word-bits))
635 ,num))))))
637 (defmacro fd-set-to-num (nfds fdset)
638 `(if (<= ,nfds sb!vm:n-machine-word-bits)
639 (deref (slot ,fdset 'fds-bits) 0)
640 (+ ,@(loop for index upfrom 0 below (/ fd-setsize
641 sb!vm:n-machine-word-bits)
642 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
643 ,(* index sb!vm:n-machine-word-bits))))))
645 ;;; Examine the sets of descriptors passed as arguments to see whether
646 ;;; they are ready for reading and writing. See the UNIX Programmer's
647 ;;; Manual for more information.
648 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
649 (declare (type (integer 0 #.fd-setsize) nfds)
650 (type unsigned-byte rdfds wrfds xpfds)
651 (type (or (unsigned-byte 31) null) to-secs)
652 (type (unsigned-byte 31) to-usecs)
653 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
654 (with-alien ((tv (struct timeval))
655 (rdf (struct fd-set))
656 (wrf (struct fd-set))
657 (xpf (struct fd-set)))
658 (cond (to-secs
659 (setf (slot tv 'tv-sec) to-secs
660 (slot tv 'tv-usec) to-usecs))
661 ((not *interrupts-enabled*)
662 (note-dangerous-select)))
663 (num-to-fd-set rdf rdfds)
664 (num-to-fd-set wrf wrfds)
665 (num-to-fd-set xpf xpfds)
666 (macrolet ((frob (lispvar alienvar)
667 `(if (zerop ,lispvar)
668 (int-sap 0)
669 (alien-sap (addr ,alienvar)))))
670 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
671 (* (struct fd-set)) (* (struct timeval)))
672 (values result
673 (fd-set-to-num nfds rdf)
674 (fd-set-to-num nfds wrf)
675 (fd-set-to-num nfds xpf))
676 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
677 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
679 ;;;; sys/stat.h
681 ;;; This is a structure defined in src/runtime/wrap.c, to look
682 ;;; basically like "struct stat" according to stat(2). It may not
683 ;;; actually correspond to the real in-memory stat structure that the
684 ;;; syscall uses, and that's OK. Linux in particular is packed full of
685 ;;; stat macros, and trying to keep Lisp code in correspondence with
686 ;;; it is more pain than it's worth, so we just let our C runtime
687 ;;; synthesize a nice consistent structure for us.
689 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
690 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
691 ;;; those. We don't actually access that field anywhere, though, so
692 ;;; until we can get 64 bit alien support it'll do. Also note that
693 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
694 ;;; quantity on Alpha. And FIXME: "No one would want a file length
695 ;;; longer than 32 bits anyway, right?":-|
697 ;;; The comment about alien and 64-bit quantities has not been kept in
698 ;;; sync with the comment now in wrap.h (formerly wrap.c), but it's
699 ;;; not clear whether either comment is correct. -- RMK 2007-11-14.
700 (define-alien-type nil
701 (struct wrapped_stat
702 (st-dev wst-dev-t)
703 (st-ino ino-t)
704 (st-mode mode-t)
705 (st-nlink wst-nlink-t)
706 (st-uid wst-uid-t)
707 (st-gid wst-gid-t)
708 (st-rdev wst-dev-t)
709 (st-size wst-off-t)
710 (st-blksize wst-blksize-t)
711 (st-blocks wst-blkcnt-t)
712 (st-atime time-t)
713 (st-mtime time-t)
714 (st-ctime time-t)))
716 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
717 ;;; family of Unix system calls
719 ;;; FIXME: I think this should probably not be INLINE. However, when
720 ;;; this was not inline, it seemed to cause memory corruption
721 ;;; problems. My first guess is that it's a bug in the FFI code, where
722 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
723 ;;; around a call to a function returning >10 values. But I didn't try
724 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
725 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
726 ;;; output in the not-inlined case and see whether there's a problem,
727 ;;; and maybe even find a fix..
728 (declaim (inline %extract-stat-results))
729 (defun %extract-stat-results (wrapped-stat)
730 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
731 (values t
732 (slot wrapped-stat 'st-dev)
733 (slot wrapped-stat 'st-ino)
734 (slot wrapped-stat 'st-mode)
735 (slot wrapped-stat 'st-nlink)
736 (slot wrapped-stat 'st-uid)
737 (slot wrapped-stat 'st-gid)
738 (slot wrapped-stat 'st-rdev)
739 (slot wrapped-stat 'st-size)
740 (slot wrapped-stat 'st-atime)
741 (slot wrapped-stat 'st-mtime)
742 (slot wrapped-stat 'st-ctime)
743 (slot wrapped-stat 'st-blksize)
744 (slot wrapped-stat 'st-blocks)))
746 ;;; Unix system calls in the stat(2) family are handled by calls to
747 ;;; C-level wrapper functions which copy all the raw "struct stat"
748 ;;; slots into the system-independent wrapped_stat format.
749 ;;; stat(2) <-> stat_wrapper()
750 ;;; fstat(2) <-> fstat_wrapper()
751 ;;; lstat(2) <-> lstat_wrapper()
752 (defun unix-stat (name)
753 (declare (type unix-pathname name))
754 (with-alien ((buf (struct wrapped_stat)))
755 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
756 (%extract-stat-results (addr buf))
757 name (addr buf))))
758 (defun unix-lstat (name)
759 (declare (type unix-pathname name))
760 (with-alien ((buf (struct wrapped_stat)))
761 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
762 (%extract-stat-results (addr buf))
763 name (addr buf))))
764 (defun unix-fstat (fd)
765 (declare (type unix-fd fd))
766 (with-alien ((buf (struct wrapped_stat)))
767 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
768 (%extract-stat-results (addr buf))
769 fd (addr buf))))
771 ;;;; time.h
773 ;; the POSIX.4 structure for a time value. This is like a "struct
774 ;; timeval" but has nanoseconds instead of microseconds.
775 (define-alien-type nil
776 (struct timespec
777 (tv-sec long) ; seconds
778 (tv-nsec long))) ; nanoseconds
780 ;; used by other time functions
781 (define-alien-type nil
782 (struct tm
783 (tm-sec int) ; Seconds. [0-60] (1 leap second)
784 (tm-min int) ; Minutes. [0-59]
785 (tm-hour int) ; Hours. [0-23]
786 (tm-mday int) ; Day. [1-31]
787 (tm-mon int) ; Month. [0-11]
788 (tm-year int) ; Year - 1900.
789 (tm-wday int) ; Day of week. [0-6]
790 (tm-yday int) ; Days in year. [0-365]
791 (tm-isdst int) ; DST. [-1/0/1]
792 (tm-gmtoff long) ; Seconds east of UTC.
793 (tm-zone c-string))) ; Timezone abbreviation.
795 (define-alien-routine get-timezone sb!alien:void
796 (when sb!alien:long :in)
797 (seconds-west sb!alien:int :out)
798 (daylight-savings-p sb!alien:boolean :out))
800 #!-win32
801 (defun nanosleep (secs nsecs)
802 (with-alien ((req (struct timespec))
803 (rem (struct timespec)))
804 (setf (slot req 'tv-sec) secs)
805 (setf (slot req 'tv-nsec) nsecs)
806 (loop while (eql sb!unix:eintr
807 (nth-value 1
808 (int-syscall ("nanosleep" (* (struct timespec))
809 (* (struct timespec)))
810 (addr req) (addr rem))))
811 do (rotatef req rem))))
813 (defun unix-get-seconds-west (secs)
814 (multiple-value-bind (ignore seconds dst) (get-timezone secs)
815 (declare (ignore ignore) (ignore dst))
816 (values seconds)))
818 ;;;; sys/time.h
820 ;;; Structure crudely representing a timezone. KLUDGE: This is
821 ;;; obsolete and should never be used.
822 (define-alien-type nil
823 (struct timezone
824 (tz-minuteswest int) ; minutes west of Greenwich
825 (tz-dsttime int))) ; type of dst correction
827 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
828 ;;; and microseconds of the current time of day, the timezone (in
829 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
830 ;;; doesn't work, it returns NIL and the errno.
831 #!-sb-fluid (declaim (inline unix-gettimeofday))
832 (defun unix-gettimeofday ()
833 #!+(and x86-64 darwin)
834 (with-alien ((tv (struct timeval)))
835 ;; CLH: FIXME! This seems to be a MacOS bug, but on x86-64/darwin,
836 ;; gettimeofday occasionally fails. passing in a null pointer for
837 ;; the timezone struct seems to work around the problem. I can't
838 ;; find any instances in the SBCL where we actually ues the
839 ;; timezone values, so we just punt for the moment.
840 (syscall* ("gettimeofday" (* (struct timeval))
841 (* (struct timezone)))
842 (values t
843 (slot tv 'tv-sec)
844 (slot tv 'tv-usec))
845 (addr tv)
846 nil))
847 #!-(and x86-64 darwin)
848 (with-alien ((tv (struct timeval))
849 (tz (struct timezone)))
850 (syscall* ("gettimeofday" (* (struct timeval))
851 (* (struct timezone)))
852 (values t
853 (slot tv 'tv-sec)
854 (slot tv 'tv-usec)
855 (slot tz 'tz-minuteswest)
856 (slot tz 'tz-dsttime))
857 (addr tv)
858 (addr tz))))
861 ;; Type of the second argument to `getitimer' and
862 ;; the second and third arguments `setitimer'.
863 (define-alien-type nil
864 (struct itimerval
865 (it-interval (struct timeval)) ; timer interval
866 (it-value (struct timeval)))) ; current value
868 (defconstant itimer-real 0)
869 (defconstant itimer-virtual 1)
870 (defconstant itimer-prof 2)
872 #!-win32
873 (defun unix-getitimer (which)
874 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
875 three system timers (:real :virtual or :profile). On success,
876 unix-getitimer returns 5 values,
877 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
878 (declare (type (member :real :virtual :profile) which)
879 (values t
880 (unsigned-byte 29) (mod 1000000)
881 (unsigned-byte 29) (mod 1000000)))
882 (let ((which (ecase which
883 (:real itimer-real)
884 (:virtual itimer-virtual)
885 (:profile itimer-prof))))
886 (with-alien ((itv (struct itimerval)))
887 (syscall* ("getitimer" int (* (struct itimerval)))
888 (values t
889 (slot (slot itv 'it-interval) 'tv-sec)
890 (slot (slot itv 'it-interval) 'tv-usec)
891 (slot (slot itv 'it-value) 'tv-sec)
892 (slot (slot itv 'it-value) 'tv-usec))
893 which (alien-sap (addr itv))))))
895 #!-win32
896 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
897 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
898 three system timers (:real :virtual or :profile). A SIGALRM signal
899 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
900 when non-zero, is <seconds+microseconds> to be loaded each time
901 the timer expires. Setting INTERVAL and VALUE to zero disables
902 the timer. See the Unix man page for more details. On success,
903 unix-setitimer returns the old contents of the INTERVAL and VALUE
904 slots as in unix-getitimer."
905 (declare (type (member :real :virtual :profile) which)
906 (type (unsigned-byte 29) int-secs val-secs)
907 (type (integer 0 (1000000)) int-usec val-usec)
908 (values t
909 (unsigned-byte 29) (mod 1000000)
910 (unsigned-byte 29) (mod 1000000)))
911 (let ((which (ecase which
912 (:real itimer-real)
913 (:virtual itimer-virtual)
914 (:profile itimer-prof))))
915 (with-alien ((itvn (struct itimerval))
916 (itvo (struct itimerval)))
917 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
918 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
919 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
920 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
921 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
922 (values t
923 (slot (slot itvo 'it-interval) 'tv-sec)
924 (slot (slot itvo 'it-interval) 'tv-usec)
925 (slot (slot itvo 'it-value) 'tv-sec)
926 (slot (slot itvo 'it-value) 'tv-usec))
927 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
930 ;;; FIXME: Many Unix error code definitions were deleted from the old
931 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
932 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
933 ;;; unused symbols in package exports, but if I don't, there are
934 ;;; enough of them all in one place here that they should probably be
935 ;;; removed by hand.
937 ;;;; support routines for dealing with Unix pathnames
939 (defun unix-file-kind (name &optional check-for-links)
940 #!+sb-doc
941 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
942 (declare (simple-string name))
943 (multiple-value-bind (res dev ino mode)
944 (if check-for-links (unix-lstat name) (unix-stat name))
945 (declare (type (or fixnum null) mode)
946 (ignore dev ino))
947 (when res
948 (let ((kind (logand mode s-ifmt)))
949 (cond ((eql kind s-ifdir) :directory)
950 ((eql kind s-ifreg) :file)
951 #!-win32
952 ((eql kind s-iflnk) :link)
953 (t :special))))))
955 (defconstant micro-seconds-per-internal-time-unit
956 (/ 1000000 sb!xc:internal-time-units-per-second))
958 ;;; UNIX specific code, that has been cleanly separated from the
959 ;;; Windows build.
960 #!-win32
961 (progn
962 (declaim (inline system-internal-run-time
963 system-real-time-values))
965 (defun system-real-time-values ()
966 (multiple-value-bind (_ sec usec) (unix-gettimeofday)
967 (declare (ignore _) (type (unsigned-byte 32) sec usec))
968 (values sec (truncate usec micro-seconds-per-internal-time-unit))))
970 ;; There are two optimizations here that actually matter (on 32-bit
971 ;; systems): substract the epoch from seconds and milliseconds
972 ;; separately, as those should remain fixnums for the first 17 years
973 ;; or so of runtime. Also, avoid doing consing a new bignum if the
974 ;; result would be = to the last result given.
976 ;; Note: the next trick would be to spin a separate thread to update
977 ;; a global value once per internal tick, so each individual call to
978 ;; get-internal-real-time would be just a memory read... but that is
979 ;; probably best left for user-level code. ;)
981 ;; Thanks to James Anderson for the optimization hint.
983 ;; Yes, it is possible to a computation to be GET-INTERNAL-REAL-TIME
984 ;; bound.
986 ;; --NS 2007-04-05
987 (let ((e-sec 0)
988 (e-msec 0)
989 (c-sec 0)
990 (c-msec 0)
991 (now 0))
992 (declare (type (unsigned-byte 32) e-sec c-sec)
993 (type fixnum e-msec c-msec)
994 (type unsigned-byte now))
995 (defun reinit-internal-real-time ()
996 (setf (values e-sec e-msec) (system-real-time-values)
997 c-sec 0
998 c-msec 0))
999 ;; If two threads call this at the same time, we're still safe, I believe,
1000 ;; as long as NOW is updated before either of C-MSEC or C-SEC. Same applies
1001 ;; to interrupts. --NS
1002 (defun get-internal-real-time ()
1003 (multiple-value-bind (sec msec) (system-real-time-values)
1004 (unless (and (= msec c-msec) (= sec c-sec))
1005 (setf now (+ (* (- sec e-sec)
1006 sb!xc:internal-time-units-per-second)
1007 (- msec e-msec))
1008 c-msec msec
1009 c-sec sec))
1010 now)))
1012 (defun system-internal-run-time ()
1013 (multiple-value-bind (ignore utime-sec utime-usec stime-sec stime-usec)
1014 (unix-fast-getrusage rusage_self)
1015 (declare (ignore ignore)
1016 (type (unsigned-byte 31) utime-sec stime-sec)
1017 ;; (Classic CMU CL had these (MOD 1000000) instead, but
1018 ;; at least in Linux 2.2.12, the type doesn't seem to
1019 ;; be documented anywhere and the observed behavior is
1020 ;; to sometimes return 1000000 exactly.)
1021 (type (integer 0 1000000) utime-usec stime-usec))
1022 (let ((result (+ (* (+ utime-sec stime-sec)
1023 sb!xc:internal-time-units-per-second)
1024 (floor (+ utime-usec
1025 stime-usec
1026 (floor micro-seconds-per-internal-time-unit 2))
1027 micro-seconds-per-internal-time-unit))))
1028 result))))
1030 ;;;; A magic constant for wait3().
1031 ;;;;
1032 ;;;; FIXME: This used to be defined in run-program.lisp as
1033 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
1034 ;;;; According to some of the man pages, the #o177 is part of the API
1035 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
1036 ;;;; the headers that may or may not be the same thing. To be
1037 ;;;; investigated. -- CSR, 2002-03-25
1038 (defconstant wstopped #o177)
1041 ;;;; stuff not yet found in the header files
1042 ;;;;
1043 ;;;; Abandon all hope who enters here...
1045 ;;; not checked for linux...
1046 (defmacro fd-set (offset fd-set)
1047 (let ((word (gensym))
1048 (bit (gensym)))
1049 `(multiple-value-bind (,word ,bit) (floor ,offset
1050 sb!vm:n-machine-word-bits)
1051 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1052 (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1053 (ash 1 ,bit))
1054 (deref (slot ,fd-set 'fds-bits) ,word))))))
1056 ;;; not checked for linux...
1057 (defmacro fd-clr (offset fd-set)
1058 (let ((word (gensym))
1059 (bit (gensym)))
1060 `(multiple-value-bind (,word ,bit) (floor ,offset
1061 sb!vm:n-machine-word-bits)
1062 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1063 (logand (deref (slot ,fd-set 'fds-bits) ,word)
1064 (sb!kernel:word-logical-not
1065 (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1066 (ash 1 ,bit))))))))
1068 ;;; not checked for linux...
1069 (defmacro fd-isset (offset fd-set)
1070 (let ((word (gensym))
1071 (bit (gensym)))
1072 `(multiple-value-bind (,word ,bit) (floor ,offset
1073 sb!vm:n-machine-word-bits)
1074 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1076 ;;; not checked for linux...
1077 (defmacro fd-zero (fd-set)
1078 `(progn
1079 ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
1080 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))