0.9.2.45:
[sbcl/lichteblau.git] / src / code / unix.lisp
blob95f8fb12916e74fcf6ef7f1da71f6a34c640ee76
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-base-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 (eql ,errno sb!unix:eintr)
105 (return (values ,value ,errno))))
106 ,@body))
108 ;;;; hacking the Unix environment
110 (define-alien-routine ("getenv" posix-getenv) c-string
111 "Return the \"value\" part of the environment string \"name=value\" which
112 corresponds to NAME, or NIL if there is none."
113 (name c-string))
115 ;;; from stdio.h
117 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
118 ;;; error code is returned if an error occurs.
119 (defun unix-rename (name1 name2)
120 (declare (type unix-pathname name1 name2))
121 (void-syscall ("rename" c-string c-string) name1 name2))
123 ;;; from sys/types.h and gnu/types.h
125 (/show0 "unix.lisp 220")
127 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
128 ;;; like this unless we have extreme provocation. Reading directories
129 ;;; is not extreme enough, since it doesn't need to be blindingly
130 ;;; fast: we can just implement those functions in C as a wrapper
131 ;;; layer.
132 (define-alien-type fd-mask unsigned-long)
134 (eval-when (:compile-toplevel :load-toplevel :execute)
135 (defconstant fd-setsize 1024))
137 (define-alien-type nil
138 (struct fd-set
139 (fds-bits (array fd-mask #.(/ fd-setsize
140 sb!vm:n-machine-word-bits)))))
142 (/show0 "unix.lisp 304")
145 ;;;; fcntl.h
146 ;;;;
147 ;;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
149 ;;; Open the file whose pathname is specified by PATH for reading
150 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
151 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
153 ;;; If the O_CREAT flag is specified, then the file is created with a
154 ;;; permission of argument MODE if the file doesn't exist. An integer
155 ;;; file descriptor is returned by UNIX-OPEN.
156 (defun unix-open (path flags mode)
157 (declare (type unix-pathname path)
158 (type fixnum flags)
159 (type unix-file-mode mode))
160 (int-syscall ("open" c-string int int) path flags mode))
162 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
163 ;;; associated with it.
164 (/show0 "unix.lisp 391")
165 (defun unix-close (fd)
166 (declare (type unix-fd fd))
167 (void-syscall ("close" int) fd))
169 ;;;; timebits.h
171 ;; A time value that is accurate to the nearest
172 ;; microsecond but also has a range of years.
173 (define-alien-type nil
174 (struct timeval
175 (tv-sec time-t) ; seconds
176 (tv-usec time-t))) ; and microseconds
178 ;;;; resourcebits.h
180 (defconstant rusage_self 0) ; the calling process
181 (defconstant rusage_children -1) ; terminated child processes
182 (defconstant rusage_both -2)
184 (define-alien-type nil
185 (struct rusage
186 (ru-utime (struct timeval)) ; user time used
187 (ru-stime (struct timeval)) ; system time used.
188 (ru-maxrss long) ; maximum resident set size (in kilobytes)
189 (ru-ixrss long) ; integral shared memory size
190 (ru-idrss long) ; integral unshared data size
191 (ru-isrss long) ; integral unshared stack size
192 (ru-minflt long) ; page reclaims
193 (ru-majflt long) ; page faults
194 (ru-nswap long) ; swaps
195 (ru-inblock long) ; block input operations
196 (ru-oublock long) ; block output operations
197 (ru-msgsnd long) ; messages sent
198 (ru-msgrcv long) ; messages received
199 (ru-nsignals long) ; signals received
200 (ru-nvcsw long) ; voluntary context switches
201 (ru-nivcsw long))) ; involuntary context switches
203 ;;;; unistd.h
205 ;;; Given a file path (a string) and one of four constant modes,
206 ;;; return T if the file is accessible with that mode and NIL if not.
207 ;;; When NIL, also return an errno value with NIL which tells why the
208 ;;; file was not accessible.
210 ;;; The access modes are:
211 ;;; r_ok Read permission.
212 ;;; w_ok Write permission.
213 ;;; x_ok Execute permission.
214 ;;; f_ok Presence of file.
215 (defun unix-access (path mode)
216 (declare (type unix-pathname path)
217 (type (mod 8) mode))
218 (void-syscall ("access" c-string int) path mode))
220 ;;; values for the second argument to UNIX-LSEEK
221 (defconstant l_set 0) ; to set the file pointer
222 (defconstant l_incr 1) ; to increment the file pointer
223 (defconstant l_xtnd 2) ; to extend the file size
225 ;;; Is a stream interactive?
226 (defun unix-isatty (fd)
227 (declare (type unix-fd fd))
228 (int-syscall ("isatty" int) fd))
230 (defun unix-lseek (fd offset whence)
231 "Unix-lseek accepts a file descriptor and moves the file pointer by
232 OFFSET octets. Whence can be any of the following:
234 L_SET Set the file pointer.
235 L_INCR Increment the file pointer.
236 L_XTND Extend the file size.
238 (declare (type unix-fd fd)
239 (type (integer 0 2) whence))
240 (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
241 fd offset whence)))
242 (if (minusp result )
243 (values nil (get-errno))
244 (values result 0))))
246 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
247 ;;; It attempts to read len bytes from the device associated with fd
248 ;;; and store them into the buffer. It returns the actual number of
249 ;;; bytes read.
250 (defun unix-read (fd buf len)
251 (declare (type unix-fd fd)
252 (type (unsigned-byte 32) len))
254 (int-syscall ("read" int (* char) int) fd buf len))
256 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
257 ;;; length to write. It attempts to write len bytes to the device
258 ;;; associated with fd from the buffer starting at offset. It returns
259 ;;; the actual number of bytes written.
260 (defun unix-write (fd buf offset len)
261 (declare (type unix-fd fd)
262 (type (unsigned-byte 32) offset len))
263 (int-syscall ("write" int (* char) int)
265 (with-alien ((ptr (* char) (etypecase buf
266 ((simple-array * (*))
267 (vector-sap buf))
268 (system-area-pointer
269 buf))))
270 (addr (deref ptr offset)))
271 len))
273 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
274 ;;; output pipe. Return two values: if no error occurred the first
275 ;;; value is the pipe to be read from and the second is can be written
276 ;;; to. If an error occurred the first value is NIL and the second the
277 ;;; unix error code.
278 (defun unix-pipe ()
279 (with-alien ((fds (array int 2)))
280 (syscall ("pipe" (* int))
281 (values (deref fds 0) (deref fds 1))
282 (cast fds (* int)))))
284 (defun unix-mkdir (name mode)
285 (declare (type unix-pathname name)
286 (type unix-file-mode mode))
287 (void-syscall ("mkdir" c-string int) name mode))
289 ;;; Given a C char* pointer allocated by malloc(), free it and return a
290 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
291 (defun newcharstar-string (newcharstar)
292 (declare (type (alien (* char)) newcharstar))
293 (if (null-alien newcharstar)
295 (prog1
296 (cast newcharstar c-string)
297 (free-alien newcharstar))))
299 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
300 ;;; style returned by getcwd() (no trailing slash character).
301 (defun posix-getcwd ()
302 ;; This implementation relies on a BSD/Linux extension to getcwd()
303 ;; behavior, automatically allocating memory when a null buffer
304 ;; pointer is used. On a system which doesn't support that
305 ;; extension, it'll have to be rewritten somehow.
307 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
308 ;; buffer pointer, it will automatically allocate size space. The
309 ;; KLUDGE in this solution arises because we have just read off
310 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
311 ;; a constant. Going the grovel_headers route doesn't seem to be
312 ;; helpful, either, as Solaris doesn't export PATH_MAX from
313 ;; unistd.h.
314 #!-(or linux openbsd freebsd netbsd sunos osf1 darwin) (,stub,)
315 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin)
316 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
317 (function (* char)
318 (* char)
319 size-t))
321 #!+(or linux openbsd freebsd netbsd darwin) 0
322 #!+(or sunos osf1) 1025))
323 (simple-perror "getcwd")))
325 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
326 ;;; by a slash character.
327 (defun posix-getcwd/ ()
328 (concatenate 'string (posix-getcwd) "/"))
330 ;;; Convert at the UNIX level from a possibly relative filename to
331 ;;; an absolute filename.
333 ;;; FIXME: Do we still need this even as we switch to
334 ;;; *DEFAULT-PATHNAME-DEFAULTS*? I think maybe we do, since it seems
335 ;;; to be valid for the user to set *DEFAULT-PATHNAME-DEFAULTS* to
336 ;;; have a NIL directory component, and then this'd be the only way to
337 ;;; interpret a relative directory specification. But I don't find the
338 ;;; ANSI pathname documentation to be a model of clarity. Maybe
339 ;;; someone who understands it better can take a look at this.. -- WHN
340 (defun unix-maybe-prepend-current-directory (name)
341 (declare (simple-string name))
342 (if (and (> (length name) 0) (char= (schar name 0) #\/))
343 name
344 (concatenate 'simple-string (posix-getcwd/) name)))
346 ;;; Duplicate an existing file descriptor (given as the argument) and
347 ;;; return it. If FD is not a valid file descriptor, NIL and an error
348 ;;; number are returned.
349 (defun unix-dup (fd)
350 (declare (type unix-fd fd))
351 (int-syscall ("dup" int) fd))
353 ;;; Terminate the current process with an optional error code. If
354 ;;; successful, the call doesn't return. If unsuccessful, the call
355 ;;; returns NIL and an error number.
356 (defun unix-exit (&optional (code 0))
357 (declare (type (signed-byte 32) code))
358 (void-syscall ("exit" int) code))
360 ;;; Return the process id of the current process.
361 (define-alien-routine ("getpid" unix-getpid) int)
363 ;;; Return the real user id associated with the current process.
364 (define-alien-routine ("getuid" unix-getuid) int)
366 ;;; Translate a user id into a login name.
367 (defun uid-username (uid)
368 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
369 (function (* char) int))
370 uid))
371 (error "found no match for Unix uid=~S" uid)))
373 ;;; Return the namestring of the home directory, being careful to
374 ;;; include a trailing #\/
375 (defun uid-homedir (uid)
376 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
377 (function (* char) int))
378 uid))
379 (error "failed to resolve home directory for Unix uid=~S" uid)))
381 ;;; Invoke readlink(2) on the file name specified by PATH. Return
382 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
383 ;;; failure.
384 (defun unix-readlink (path)
385 (declare (type unix-pathname path))
386 (with-alien ((ptr (* char)
387 (alien-funcall (extern-alien
388 "wrapped_readlink"
389 (function (* char) c-string))
390 path)))
391 (if (null-alien ptr)
392 (values nil (get-errno))
393 (multiple-value-prog1
394 (values (with-alien ((c-string c-string ptr)) c-string)
395 nil)
396 (free-alien ptr)))))
398 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
399 ;;; name and the file if this is the last link.
400 (defun unix-unlink (name)
401 (declare (type unix-pathname name))
402 (void-syscall ("unlink" c-string) name))
404 ;;; Return the name of the host machine as a string.
405 (defun unix-gethostname ()
406 (with-alien ((buf (array char 256)))
407 (syscall ("gethostname" (* char) int)
408 (cast buf c-string)
409 (cast buf (* char)) 256)))
411 (defun unix-setsid ()
412 (int-syscall ("setsid")))
414 ;;;; sys/ioctl.h
416 ;;; UNIX-IOCTL performs a variety of operations on open i/o
417 ;;; descriptors. See the UNIX Programmer's Manual for more
418 ;;; information.
419 (defun unix-ioctl (fd cmd arg)
420 (declare (type unix-fd fd)
421 (type (signed-byte 32) cmd))
422 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
424 ;;;; sys/resource.h
426 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
428 ;;; This is like getrusage(2), except it returns only the system and
429 ;;; user time, and returns the seconds and microseconds as separate
430 ;;; values.
431 #!-sb-fluid (declaim (inline unix-fast-getrusage))
432 (defun unix-fast-getrusage (who)
433 (declare (values (member t)
434 (unsigned-byte 31) (integer 0 1000000)
435 (unsigned-byte 31) (integer 0 1000000)))
436 (with-alien ((usage (struct rusage)))
437 (syscall* ("getrusage" int (* (struct rusage)))
438 (values t
439 (slot (slot usage 'ru-utime) 'tv-sec)
440 (slot (slot usage 'ru-utime) 'tv-usec)
441 (slot (slot usage 'ru-stime) 'tv-sec)
442 (slot (slot usage 'ru-stime) 'tv-usec))
443 who (addr usage))))
445 ;;; Return information about the resource usage of the process
446 ;;; specified by WHO. WHO can be either the current process
447 ;;; (rusage_self) or all of the terminated child processes
448 ;;; (rusage_children). NIL and an error number is returned if the call
449 ;;; fails.
450 (defun unix-getrusage (who)
451 (with-alien ((usage (struct rusage)))
452 (syscall ("getrusage" int (* (struct rusage)))
453 (values t
454 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
455 (slot (slot usage 'ru-utime) 'tv-usec))
456 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
457 (slot (slot usage 'ru-stime) 'tv-usec))
458 (slot usage 'ru-maxrss)
459 (slot usage 'ru-ixrss)
460 (slot usage 'ru-idrss)
461 (slot usage 'ru-isrss)
462 (slot usage 'ru-minflt)
463 (slot usage 'ru-majflt)
464 (slot usage 'ru-nswap)
465 (slot usage 'ru-inblock)
466 (slot usage 'ru-oublock)
467 (slot usage 'ru-msgsnd)
468 (slot usage 'ru-msgrcv)
469 (slot usage 'ru-nsignals)
470 (slot usage 'ru-nvcsw)
471 (slot usage 'ru-nivcsw))
472 who (addr usage))))
474 ;;;; sys/select.h
476 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
478 ;;; Perform the UNIX select(2) system call.
479 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
480 (defun unix-fast-select (num-descriptors
481 read-fds write-fds exception-fds
482 timeout-secs &optional (timeout-usecs 0))
483 (declare (type (integer 0 #.fd-setsize) num-descriptors)
484 (type (or (alien (* (struct fd-set))) null)
485 read-fds write-fds exception-fds)
486 (type (or null (unsigned-byte 31)) timeout-secs)
487 (type (unsigned-byte 31) timeout-usecs))
488 ;; FIXME: CMU CL had
489 ;; (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
490 ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
491 (with-alien ((tv (struct timeval)))
492 (when timeout-secs
493 (setf (slot tv 'tv-sec) timeout-secs)
494 (setf (slot tv 'tv-usec) timeout-usecs))
495 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
496 (* (struct fd-set)) (* (struct timeval)))
497 num-descriptors read-fds write-fds exception-fds
498 (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
500 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
501 ;;; to happen on one of them or to time out.
502 (defmacro num-to-fd-set (fdset num)
503 `(if (fixnump ,num)
504 (progn
505 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
506 ,@(loop for index upfrom 1 below (/ fd-setsize
507 sb!vm:n-machine-word-bits)
508 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
509 (progn
510 ,@(loop for index upfrom 0 below (/ fd-setsize
511 sb!vm:n-machine-word-bits)
512 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
513 (ldb (byte sb!vm:n-machine-word-bits
514 ,(* index sb!vm:n-machine-word-bits))
515 ,num))))))
517 (defmacro fd-set-to-num (nfds fdset)
518 `(if (<= ,nfds sb!vm:n-machine-word-bits)
519 (deref (slot ,fdset 'fds-bits) 0)
520 (+ ,@(loop for index upfrom 0 below (/ fd-setsize
521 sb!vm:n-machine-word-bits)
522 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
523 ,(* index sb!vm:n-machine-word-bits))))))
525 ;;; Examine the sets of descriptors passed as arguments to see whether
526 ;;; they are ready for reading and writing. See the UNIX Programmer's
527 ;;; Manual for more information.
528 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
529 (declare (type (integer 0 #.fd-setsize) nfds)
530 (type unsigned-byte rdfds wrfds xpfds)
531 (type (or (unsigned-byte 31) null) to-secs)
532 (type (unsigned-byte 31) to-usecs)
533 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
534 (with-alien ((tv (struct timeval))
535 (rdf (struct fd-set))
536 (wrf (struct fd-set))
537 (xpf (struct fd-set)))
538 (when to-secs
539 (setf (slot tv 'tv-sec) to-secs)
540 (setf (slot tv 'tv-usec) to-usecs))
541 (num-to-fd-set rdf rdfds)
542 (num-to-fd-set wrf wrfds)
543 (num-to-fd-set xpf xpfds)
544 (macrolet ((frob (lispvar alienvar)
545 `(if (zerop ,lispvar)
546 (int-sap 0)
547 (alien-sap (addr ,alienvar)))))
548 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
549 (* (struct fd-set)) (* (struct timeval)))
550 (values result
551 (fd-set-to-num nfds rdf)
552 (fd-set-to-num nfds wrf)
553 (fd-set-to-num nfds xpf))
554 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
555 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
557 ;;;; sys/stat.h
559 ;;; This is a structure defined in src/runtime/wrap.c, to look
560 ;;; basically like "struct stat" according to stat(2). It may not
561 ;;; actually correspond to the real in-memory stat structure that the
562 ;;; syscall uses, and that's OK. Linux in particular is packed full of
563 ;;; stat macros, and trying to keep Lisp code in correspondence with
564 ;;; it is more pain than it's worth, so we just let our C runtime
565 ;;; synthesize a nice consistent structure for us.
567 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
568 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
569 ;;; those. We don't actually access that field anywhere, though, so
570 ;;; until we can get 64 bit alien support it'll do. Also note that
571 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
572 ;;; quantity on Alpha. And FIXME: "No one would want a file length
573 ;;; longer than 32 bits anyway, right?":-|
574 (define-alien-type nil
575 (struct wrapped_stat
576 (st-dev unsigned-int) ; would be dev-t in a real stat
577 (st-ino ino-t)
578 (st-mode mode-t)
579 (st-nlink nlink-t)
580 (st-uid uid-t)
581 (st-gid gid-t)
582 (st-rdev unsigned-int) ; would be dev-t in a real stat
583 (st-size unsigned-int) ; would be off-t in a real stat
584 (st-blksize unsigned-long)
585 (st-blocks unsigned-long)
586 (st-atime time-t)
587 (st-mtime time-t)
588 (st-ctime time-t)))
590 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
591 ;;; family of Unix system calls
593 ;;; FIXME: I think this should probably not be INLINE. However, when
594 ;;; this was not inline, it seemed to cause memory corruption
595 ;;; problems. My first guess is that it's a bug in the FFI code, where
596 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
597 ;;; around a call to a function returning >10 values. But I didn't try
598 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
599 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
600 ;;; output in the not-inlined case and see whether there's a problem,
601 ;;; and maybe even find a fix..
602 (declaim (inline %extract-stat-results))
603 (defun %extract-stat-results (wrapped-stat)
604 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
605 (values t
606 (slot wrapped-stat 'st-dev)
607 (slot wrapped-stat 'st-ino)
608 (slot wrapped-stat 'st-mode)
609 (slot wrapped-stat 'st-nlink)
610 (slot wrapped-stat 'st-uid)
611 (slot wrapped-stat 'st-gid)
612 (slot wrapped-stat 'st-rdev)
613 (slot wrapped-stat 'st-size)
614 (slot wrapped-stat 'st-atime)
615 (slot wrapped-stat 'st-mtime)
616 (slot wrapped-stat 'st-ctime)
617 (slot wrapped-stat 'st-blksize)
618 (slot wrapped-stat 'st-blocks)))
620 ;;; Unix system calls in the stat(2) family are handled by calls to
621 ;;; C-level wrapper functions which copy all the raw "struct stat"
622 ;;; slots into the system-independent wrapped_stat format.
623 ;;; stat(2) <-> stat_wrapper()
624 ;;; fstat(2) <-> fstat_wrapper()
625 ;;; lstat(2) <-> lstat_wrapper()
626 (defun unix-stat (name)
627 (declare (type unix-pathname name))
628 (with-alien ((buf (struct wrapped_stat)))
629 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
630 (%extract-stat-results (addr buf))
631 name (addr buf))))
632 (defun unix-lstat (name)
633 (declare (type unix-pathname name))
634 (with-alien ((buf (struct wrapped_stat)))
635 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
636 (%extract-stat-results (addr buf))
637 name (addr buf))))
638 (defun unix-fstat (fd)
639 (declare (type unix-fd fd))
640 (with-alien ((buf (struct wrapped_stat)))
641 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
642 (%extract-stat-results (addr buf))
643 fd (addr buf))))
645 ;;;; time.h
647 ;; the POSIX.4 structure for a time value. This is like a "struct
648 ;; timeval" but has nanoseconds instead of microseconds.
649 (define-alien-type nil
650 (struct timespec
651 (tv-sec long) ; seconds
652 (tv-nsec long))) ; nanoseconds
654 ;; used by other time functions
655 (define-alien-type nil
656 (struct tm
657 (tm-sec int) ; Seconds. [0-60] (1 leap second)
658 (tm-min int) ; Minutes. [0-59]
659 (tm-hour int) ; Hours. [0-23]
660 (tm-mday int) ; Day. [1-31]
661 (tm-mon int) ; Month. [0-11]
662 (tm-year int) ; Year - 1900.
663 (tm-wday int) ; Day of week. [0-6]
664 (tm-yday int) ; Days in year. [0-365]
665 (tm-isdst int) ; DST. [-1/0/1]
666 (tm-gmtoff long) ; Seconds east of UTC.
667 (tm-zone c-string))) ; Timezone abbreviation.
669 (define-alien-routine get-timezone sb!alien:void
670 (when sb!alien:long :in)
671 (seconds-west sb!alien:int :out)
672 (daylight-savings-p sb!alien:boolean :out))
674 (defun nanosleep (secs nsecs)
675 (with-alien ((req (struct timespec))
676 (rem (struct timespec)))
677 (setf (slot req 'tv-sec) secs)
678 (setf (slot req 'tv-nsec) nsecs)
679 (loop while (eql sb!unix:eintr
680 (nth-value 1
681 (int-syscall ("nanosleep" (* (struct timespec))
682 (* (struct timespec)))
683 (addr req) (addr rem))))
684 do (rotatef req rem))))
686 (defun unix-get-seconds-west (secs)
687 (multiple-value-bind (ignore seconds dst) (get-timezone secs)
688 (declare (ignore ignore) (ignore dst))
689 (values seconds)))
691 ;;;; sys/time.h
693 ;;; Structure crudely representing a timezone. KLUDGE: This is
694 ;;; obsolete and should never be used.
695 (define-alien-type nil
696 (struct timezone
697 (tz-minuteswest int) ; minutes west of Greenwich
698 (tz-dsttime int))) ; type of dst correction
700 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
701 ;;; and microseconds of the current time of day, the timezone (in
702 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
703 ;;; doesn't work, it returns NIL and the errno.
704 #!-sb-fluid (declaim (inline unix-gettimeofday))
705 (defun unix-gettimeofday ()
706 (with-alien ((tv (struct timeval))
707 (tz (struct timezone)))
708 (syscall* ("gettimeofday" (* (struct timeval))
709 (* (struct timezone)))
710 (values t
711 (slot tv 'tv-sec)
712 (slot tv 'tv-usec)
713 (slot tz 'tz-minuteswest)
714 (slot tz 'tz-dsttime))
715 (addr tv)
716 (addr tz))))
719 ;; Type of the second argument to `getitimer' and
720 ;; the second and third arguments `setitimer'.
721 (define-alien-type nil
722 (struct itimerval
723 (it-interval (struct timeval)) ; timer interval
724 (it-value (struct timeval)))) ; current value
726 (defconstant itimer-real 0)
727 (defconstant itimer-virtual 1)
728 (defconstant itimer-prof 2)
730 (defun unix-getitimer (which)
731 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
732 three system timers (:real :virtual or :profile). On success,
733 unix-getitimer returns 5 values,
734 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
735 (declare (type (member :real :virtual :profile) which)
736 (values t
737 (unsigned-byte 29) (mod 1000000)
738 (unsigned-byte 29) (mod 1000000)))
739 (let ((which (ecase which
740 (:real itimer-real)
741 (:virtual itimer-virtual)
742 (:profile itimer-prof))))
743 (with-alien ((itv (struct itimerval)))
744 (syscall* ("getitimer" int (* (struct itimerval)))
745 (values t
746 (slot (slot itv 'it-interval) 'tv-sec)
747 (slot (slot itv 'it-interval) 'tv-usec)
748 (slot (slot itv 'it-value) 'tv-sec)
749 (slot (slot itv 'it-value) 'tv-usec))
750 which (alien-sap (addr itv))))))
752 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
753 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
754 three system timers (:real :virtual or :profile). A SIGALRM signal
755 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
756 when non-zero, is <seconds+microseconds> to be loaded each time
757 the timer expires. Setting INTERVAL and VALUE to zero disables
758 the timer. See the Unix man page for more details. On success,
759 unix-setitimer returns the old contents of the INTERVAL and VALUE
760 slots as in unix-getitimer."
761 (declare (type (member :real :virtual :profile) which)
762 (type (unsigned-byte 29) int-secs val-secs)
763 (type (integer 0 (1000000)) int-usec val-usec)
764 (values t
765 (unsigned-byte 29) (mod 1000000)
766 (unsigned-byte 29) (mod 1000000)))
767 (let ((which (ecase which
768 (:real itimer-real)
769 (:virtual itimer-virtual)
770 (:profile itimer-prof))))
771 (with-alien ((itvn (struct itimerval))
772 (itvo (struct itimerval)))
773 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
774 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
775 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
776 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
777 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
778 (values t
779 (slot (slot itvo 'it-interval) 'tv-sec)
780 (slot (slot itvo 'it-interval) 'tv-usec)
781 (slot (slot itvo 'it-value) 'tv-sec)
782 (slot (slot itvo 'it-value) 'tv-usec))
783 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
785 (defmacro sb!ext:with-timeout (expires &body body)
786 "Execute the body, interrupting it with a SIGALRM after at least
787 EXPIRES seconds have passed. Uses Unix setitimer(), restoring any
788 previous timer after the body has finished executing"
789 (with-unique-names (saved-seconds saved-useconds s u)
790 `(let (- ,saved-seconds ,saved-useconds)
791 (multiple-value-setq (- - - ,saved-seconds ,saved-useconds)
792 (unix-getitimer :real))
793 (multiple-value-bind (,s ,u) (floor ,expires)
794 (setf ,u (floor (* ,u 1000000)))
795 (if (and (> ,expires 0)
796 (or (and (zerop ,saved-seconds) (zerop ,saved-useconds))
797 (> ,saved-seconds ,s)
798 (and (= ,saved-seconds ,s)
799 (> ,saved-useconds ,u))))
800 (unwind-protect
801 (progn
802 (unix-setitimer :real 0 0 ,s ,u)
803 ,@body)
804 (unix-setitimer :real 0 0 ,saved-seconds ,saved-useconds))
805 (progn
806 ,@body))))))
808 ;;; FIXME: Many Unix error code definitions were deleted from the old
809 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
810 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
811 ;;; unused symbols in package exports, but if I don't, there are
812 ;;; enough of them all in one place here that they should probably be
813 ;;; removed by hand.
815 ;;;; support routines for dealing with Unix pathnames
817 (defun unix-file-kind (name &optional check-for-links)
818 #!+sb-doc
819 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
820 (declare (simple-base-string name))
821 (multiple-value-bind (res dev ino mode)
822 (if check-for-links (unix-lstat name) (unix-stat name))
823 (declare (type (or fixnum null) mode)
824 (ignore dev ino))
825 (when res
826 (let ((kind (logand mode s-ifmt)))
827 (cond ((eql kind s-ifdir) :directory)
828 ((eql kind s-ifreg) :file)
829 ((eql kind s-iflnk) :link)
830 (t :special))))))
832 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
833 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
834 (defun relative-unix-pathname? (pathname)
835 (declare (type simple-string pathname))
836 (or (zerop (length pathname))
837 (char/= (schar pathname 0) #\/)))
839 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
840 ;;; already be a complete absolute Unix pathname, since at least in
841 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
842 ;;; paths have been converted to absolute paths, so we don't need to
843 ;;; try to handle any more generality than that.
844 (defun unix-resolve-links (pathname)
845 (declare (type simple-base-string pathname))
846 (aver (not (relative-unix-pathname? pathname)))
847 ;; KLUDGE: readlink and lstat are unreliable if given symlinks
848 ;; ending in slashes -- fix the issue here instead of waiting for
849 ;; libc to change...
850 (let ((len (length pathname)))
851 (when (and (plusp len) (eql #\/ (schar pathname (1- len))))
852 (setf pathname (subseq pathname 0 (1- len)))))
853 (/noshow "entering UNIX-RESOLVE-LINKS")
854 (loop with previous-pathnames = nil do
855 (/noshow pathname previous-pathnames)
856 (let ((link (unix-readlink pathname)))
857 (/noshow link)
858 ;; Unlike the old CMU CL code, we handle a broken symlink by
859 ;; returning the link itself. That way, CL:TRUENAME on a
860 ;; broken link returns the link itself, so that CL:DIRECTORY
861 ;; can return broken links, so that even without
862 ;; Unix-specific extensions to do interesting things with
863 ;; them, at least Lisp programs can see them and, if
864 ;; necessary, delete them. (This is handy e.g. when your
865 ;; managed-by-Lisp directories are visited by Emacs, which
866 ;; creates broken links as notes to itself.)
867 (if (null link)
868 (return pathname)
869 (let ((new-pathname
870 (unix-simplify-pathname
871 (if (relative-unix-pathname? link)
872 (let* ((dir-len (1+ (position #\/
873 pathname
874 :from-end t)))
875 (dir (subseq pathname 0 dir-len)))
876 (/noshow dir)
877 (concatenate 'base-string dir link))
878 link))))
879 (if (unix-file-kind new-pathname)
880 (setf pathname new-pathname)
881 (return pathname)))))
882 ;; To generalize the principle that even if portable Lisp code
883 ;; can't do anything interesting with a broken symlink, at
884 ;; least it should be able to see and delete it, when we
885 ;; detect a cyclic link, we return the link itself. (So even
886 ;; though portable Lisp code can't do anything interesting
887 ;; with a cyclic link, at least it can see it and delete it.)
888 (if (member pathname previous-pathnames :test #'string=)
889 (return pathname)
890 (push pathname previous-pathnames))))
892 (defun unix-simplify-pathname (src)
893 (declare (type simple-base-string src))
894 (let* ((src-len (length src))
895 (dst (make-string src-len :element-type 'base-char))
896 (dst-len 0)
897 (dots 0)
898 (last-slash nil))
899 (macrolet ((deposit (char)
900 `(progn
901 (setf (schar dst dst-len) ,char)
902 (incf dst-len))))
903 (dotimes (src-index src-len)
904 (let ((char (schar src src-index)))
905 (cond ((char= char #\.)
906 (when dots
907 (incf dots))
908 (deposit char))
909 ((char= char #\/)
910 (case dots
912 ;; either ``/...' or ``...//...'
913 (unless last-slash
914 (setf last-slash dst-len)
915 (deposit char)))
917 ;; either ``./...'' or ``..././...''
918 (decf dst-len))
920 ;; We've found ..
921 (cond
922 ((and last-slash (not (zerop last-slash)))
923 ;; There is something before this ..
924 (let ((prev-prev-slash
925 (position #\/ dst :end last-slash :from-end t)))
926 (cond ((and (= (+ (or prev-prev-slash 0) 2)
927 last-slash)
928 (char= (schar dst (- last-slash 2)) #\.)
929 (char= (schar dst (1- last-slash)) #\.))
930 ;; The something before this .. is another ..
931 (deposit char)
932 (setf last-slash dst-len))
934 ;; The something is some directory or other.
935 (setf dst-len
936 (if prev-prev-slash
937 (1+ prev-prev-slash)
939 (setf last-slash prev-prev-slash)))))
941 ;; There is nothing before this .., so we need to keep it
942 (setf last-slash dst-len)
943 (deposit char))))
945 ;; something other than a dot between slashes
946 (setf last-slash dst-len)
947 (deposit char)))
948 (setf dots 0))
950 (setf dots nil)
951 (setf (schar dst dst-len) char)
952 (incf dst-len))))))
953 (when (and last-slash (not (zerop last-slash)))
954 (case dots
956 ;; We've got ``foobar/.''
957 (decf dst-len))
959 ;; We've got ``foobar/..''
960 (unless (and (>= last-slash 2)
961 (char= (schar dst (1- last-slash)) #\.)
962 (char= (schar dst (- last-slash 2)) #\.)
963 (or (= last-slash 2)
964 (char= (schar dst (- last-slash 3)) #\/)))
965 (let ((prev-prev-slash
966 (position #\/ dst :end last-slash :from-end t)))
967 (if prev-prev-slash
968 (setf dst-len (1+ prev-prev-slash))
969 (return-from unix-simplify-pathname
970 (coerce "./" 'simple-base-string))))))))
971 (cond ((zerop dst-len)
972 "./")
973 ((= dst-len src-len)
974 dst)
976 (subseq dst 0 dst-len)))))
978 ;;;; A magic constant for wait3().
979 ;;;;
980 ;;;; FIXME: This used to be defined in run-program.lisp as
981 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
982 ;;;; According to some of the man pages, the #o177 is part of the API
983 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
984 ;;;; the headers that may or may not be the same thing. To be
985 ;;;; investigated. -- CSR, 2002-03-25
986 (defconstant wstopped #o177)
989 ;;;; stuff not yet found in the header files
990 ;;;;
991 ;;;; Abandon all hope who enters here...
993 ;;; not checked for linux...
994 (defmacro fd-set (offset fd-set)
995 (let ((word (gensym))
996 (bit (gensym)))
997 `(multiple-value-bind (,word ,bit) (floor ,offset
998 sb!vm:n-machine-word-bits)
999 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1000 (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1001 (ash 1 ,bit))
1002 (deref (slot ,fd-set 'fds-bits) ,word))))))
1004 ;;; not checked for linux...
1005 (defmacro fd-clr (offset fd-set)
1006 (let ((word (gensym))
1007 (bit (gensym)))
1008 `(multiple-value-bind (,word ,bit) (floor ,offset
1009 sb!vm:n-machine-word-bits)
1010 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1011 (logand (deref (slot ,fd-set 'fds-bits) ,word)
1012 (sb!kernel:word-logical-not
1013 (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1014 (ash 1 ,bit))))))))
1016 ;;; not checked for linux...
1017 (defmacro fd-isset (offset fd-set)
1018 (let ((word (gensym))
1019 (bit (gensym)))
1020 `(multiple-value-bind (,word ,bit) (floor ,offset
1021 sb!vm:n-machine-word-bits)
1022 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1024 ;;; not checked for linux...
1025 (defmacro fd-zero (fd-set)
1026 `(progn
1027 ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
1028 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))