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-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))
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 ;;;; hacking the Unix environment
97 (define-alien-routine ("getenv" posix-getenv) c-string
98 "Return the \"value\" part of the environment string \"name=value\" which
99 corresponds to NAME, or NIL if there is none."
104 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
105 ;;; error code is returned if an error occurs.
106 (defun unix-rename (name1 name2)
107 (declare (type unix-pathname name1 name2))
108 (void-syscall ("rename" c-string c-string) name1 name2))
110 ;;; from sys/types.h and gnu/types.h
112 (/show0 "unix.lisp 220")
114 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
115 ;;; like this unless we have extreme provocation. Reading directories
116 ;;; is not extreme enough, since it doesn't need to be blindingly
117 ;;; fast: we can just implement those functions in C as a wrapper
119 (define-alien-type fd-mask unsigned-long)
121 (eval-when (:compile-toplevel :load-toplevel :execute)
122 (defconstant fd-setsize 1024))
124 (define-alien-type nil
126 (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
128 (/show0 "unix.lisp 304")
133 ;;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
135 ;;; Open the file whose pathname is specified by PATH for reading
136 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
137 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
139 ;;; If the O_CREAT flag is specified, then the file is created with a
140 ;;; permission of argument MODE if the file doesn't exist. An integer
141 ;;; file descriptor is returned by UNIX-OPEN.
142 (defun unix-open (path flags mode)
143 (declare (type unix-pathname path)
145 (type unix-file-mode mode))
146 (int-syscall ("open" c-string int int) path flags mode))
148 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
149 ;;; associated with it.
150 (/show0 "unix.lisp 391")
151 (defun unix-close (fd)
152 (declare (type unix-fd fd))
153 (void-syscall ("close" int) fd))
157 ;; A time value that is accurate to the nearest
158 ;; microsecond but also has a range of years.
159 (define-alien-type nil
161 (tv-sec time-t) ; seconds
162 (tv-usec time-t))) ; and microseconds
166 (defconstant rusage_self 0) ; the calling process
167 (defconstant rusage_children -1) ; terminated child processes
168 (defconstant rusage_both -2)
170 (define-alien-type nil
172 (ru-utime (struct timeval)) ; user time used
173 (ru-stime (struct timeval)) ; system time used.
174 (ru-maxrss long) ; maximum resident set size (in kilobytes)
175 (ru-ixrss long) ; integral shared memory size
176 (ru-idrss long) ; integral unshared data size
177 (ru-isrss long) ; integral unshared stack size
178 (ru-minflt long) ; page reclaims
179 (ru-majflt long) ; page faults
180 (ru-nswap long) ; swaps
181 (ru-inblock long) ; block input operations
182 (ru-oublock long) ; block output operations
183 (ru-msgsnd long) ; messages sent
184 (ru-msgrcv long) ; messages received
185 (ru-nsignals long) ; signals received
186 (ru-nvcsw long) ; voluntary context switches
187 (ru-nivcsw long))) ; involuntary context switches
191 ;;; Given a file path (a string) and one of four constant modes,
192 ;;; return T if the file is accessible with that mode and NIL if not.
193 ;;; When NIL, also return an errno value with NIL which tells why the
194 ;;; file was not accessible.
196 ;;; The access modes are:
197 ;;; r_ok Read permission.
198 ;;; w_ok Write permission.
199 ;;; x_ok Execute permission.
200 ;;; f_ok Presence of file.
201 (defun unix-access (path mode)
202 (declare (type unix-pathname path)
204 (void-syscall ("access" c-string int) path mode))
206 ;;; values for the second argument to UNIX-LSEEK
207 (defconstant l_set 0) ; to set the file pointer
208 (defconstant l_incr 1) ; to increment the file pointer
209 (defconstant l_xtnd 2) ; to extend the file size
211 ;;; Is a stream interactive?
212 (defun unix-isatty (fd)
213 (declare (type unix-fd fd))
214 (int-syscall ("isatty" int) fd))
216 (defun unix-lseek (fd offset whence)
217 "Unix-lseek accepts a file descriptor and moves the file pointer by
218 OFFSET octets. Whence can be any of the following:
220 L_SET Set the file pointer.
221 L_INCR Increment the file pointer.
222 L_XTND Extend the file size.
224 (declare (type unix-fd fd)
225 (type (integer 0 2) whence))
226 (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
229 (values nil (get-errno))
232 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
233 ;;; It attempts to read len bytes from the device associated with fd
234 ;;; and store them into the buffer. It returns the actual number of
236 (defun unix-read (fd buf len)
237 (declare (type unix-fd fd)
238 (type (unsigned-byte 32) len))
240 (int-syscall ("read" int (* char) int) fd buf len))
242 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
243 ;;; length to write. It attempts to write len bytes to the device
244 ;;; associated with fd from the buffer starting at offset. It returns
245 ;;; the actual number of bytes written.
246 (defun unix-write (fd buf offset len)
247 (declare (type unix-fd fd)
248 (type (unsigned-byte 32) offset len))
249 (int-syscall ("write" int (* char) int)
251 (with-alien ((ptr (* char) (etypecase buf
252 ((simple-array * (*))
256 (addr (deref ptr offset)))
259 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
260 ;;; output pipe. Return two values: if no error occurred the first
261 ;;; value is the pipe to be read from and the second is can be written
262 ;;; to. If an error occurred the first value is NIL and the second the
265 (with-alien ((fds (array int 2)))
266 (syscall ("pipe" (* int))
267 (values (deref fds 0) (deref fds 1))
268 (cast fds (* int)))))
270 (defun unix-mkdir (name mode)
271 (declare (type unix-pathname name)
272 (type unix-file-mode mode))
273 (void-syscall ("mkdir" c-string int) name mode))
275 ;;; Given a C char* pointer allocated by malloc(), free it and return a
276 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
277 (defun newcharstar-string (newcharstar)
278 (declare (type (alien (* char)) newcharstar))
279 (if (null-alien newcharstar)
282 (cast newcharstar c-string)
283 (free-alien newcharstar))))
285 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
286 ;;; style returned by getcwd() (no trailing slash character).
287 (defun posix-getcwd ()
288 ;; This implementation relies on a BSD/Linux extension to getcwd()
289 ;; behavior, automatically allocating memory when a null buffer
290 ;; pointer is used. On a system which doesn't support that
291 ;; extension, it'll have to be rewritten somehow.
293 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
294 ;; buffer pointer, it will automatically allocate size space. The
295 ;; KLUDGE in this solution arises because we have just read off
296 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
297 ;; a constant. Going the grovel_headers route doesn't seem to be
298 ;; helpful, either, as Solaris doesn't export PATH_MAX from
300 #!-(or linux openbsd freebsd netbsd sunos osf1 darwin) (,stub,)
301 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin)
302 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
307 #!+(or linux openbsd freebsd netbsd darwin) 0
308 #!+(or sunos osf1) 1025))
309 (simple-perror "getcwd")))
311 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
312 ;;; by a slash character.
313 (defun posix-getcwd/ ()
314 (concatenate 'string (posix-getcwd) "/"))
316 ;;; Convert at the UNIX level from a possibly relative filename to
317 ;;; an absolute filename.
319 ;;; FIXME: Do we still need this even as we switch to
320 ;;; *DEFAULT-PATHNAME-DEFAULTS*? I think maybe we do, since it seems
321 ;;; to be valid for the user to set *DEFAULT-PATHNAME-DEFAULTS* to
322 ;;; have a NIL directory component, and then this'd be the only way to
323 ;;; interpret a relative directory specification. But I don't find the
324 ;;; ANSI pathname documentation to be a model of clarity. Maybe
325 ;;; someone who understands it better can take a look at this.. -- WHN
326 (defun unix-maybe-prepend-current-directory (name)
327 (declare (simple-string name))
328 (if (and (> (length name) 0) (char= (schar name 0) #\/))
330 (concatenate 'simple-string (posix-getcwd/) name)))
332 ;;; Duplicate an existing file descriptor (given as the argument) and
333 ;;; return it. If FD is not a valid file descriptor, NIL and an error
334 ;;; number are returned.
336 (declare (type unix-fd fd))
337 (int-syscall ("dup" int) fd))
339 ;;; Terminate the current process with an optional error code. If
340 ;;; successful, the call doesn't return. If unsuccessful, the call
341 ;;; returns NIL and an error number.
342 (defun unix-exit (&optional (code 0))
343 (declare (type (signed-byte 32) code))
344 (void-syscall ("exit" int) code))
346 ;;; Return the process id of the current process.
347 (define-alien-routine ("getpid" unix-getpid) int)
349 ;;; Return the real user id associated with the current process.
350 (define-alien-routine ("getuid" unix-getuid) int)
352 ;;; Translate a user id into a login name.
353 (defun uid-username (uid)
354 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
355 (function (* char) int))
357 (error "found no match for Unix uid=~S" uid)))
359 ;;; Return the namestring of the home directory, being careful to
360 ;;; include a trailing #\/
361 (defun uid-homedir (uid)
362 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
363 (function (* char) int))
365 (error "failed to resolve home directory for Unix uid=~S" uid)))
367 ;;; Invoke readlink(2) on the file name specified by PATH. Return
368 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
370 (defun unix-readlink (path)
371 (declare (type unix-pathname path))
372 (with-alien ((ptr (* char)
373 (alien-funcall (extern-alien
375 (function (* char) c-string))
378 (values nil (get-errno))
379 (multiple-value-prog1
380 (values (with-alien ((c-string c-string ptr)) c-string)
384 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
385 ;;; name and the file if this is the last link.
386 (defun unix-unlink (name)
387 (declare (type unix-pathname name))
388 (void-syscall ("unlink" c-string) name))
390 ;;; Return the name of the host machine as a string.
391 (defun unix-gethostname ()
392 (with-alien ((buf (array char 256)))
393 (syscall ("gethostname" (* char) int)
395 (cast buf (* char)) 256)))
397 (defun unix-setsid ()
398 (int-syscall ("setsid")))
402 ;;; UNIX-IOCTL performs a variety of operations on open i/o
403 ;;; descriptors. See the UNIX Programmer's Manual for more
405 (defun unix-ioctl (fd cmd arg)
406 (declare (type unix-fd fd)
407 (type (signed-byte 32) cmd))
408 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
412 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
414 ;;; This is like getrusage(2), except it returns only the system and
415 ;;; user time, and returns the seconds and microseconds as separate
417 #!-sb-fluid (declaim (inline unix-fast-getrusage))
418 (defun unix-fast-getrusage (who)
419 (declare (values (member t)
420 (unsigned-byte 31) (integer 0 1000000)
421 (unsigned-byte 31) (integer 0 1000000)))
422 (with-alien ((usage (struct rusage)))
423 (syscall* ("getrusage" int (* (struct rusage)))
425 (slot (slot usage 'ru-utime) 'tv-sec)
426 (slot (slot usage 'ru-utime) 'tv-usec)
427 (slot (slot usage 'ru-stime) 'tv-sec)
428 (slot (slot usage 'ru-stime) 'tv-usec))
431 ;;; Return information about the resource usage of the process
432 ;;; specified by WHO. WHO can be either the current process
433 ;;; (rusage_self) or all of the terminated child processes
434 ;;; (rusage_children). NIL and an error number is returned if the call
436 (defun unix-getrusage (who)
437 (with-alien ((usage (struct rusage)))
438 (syscall ("getrusage" int (* (struct rusage)))
440 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
441 (slot (slot usage 'ru-utime) 'tv-usec))
442 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
443 (slot (slot usage 'ru-stime) 'tv-usec))
444 (slot usage 'ru-maxrss)
445 (slot usage 'ru-ixrss)
446 (slot usage 'ru-idrss)
447 (slot usage 'ru-isrss)
448 (slot usage 'ru-minflt)
449 (slot usage 'ru-majflt)
450 (slot usage 'ru-nswap)
451 (slot usage 'ru-inblock)
452 (slot usage 'ru-oublock)
453 (slot usage 'ru-msgsnd)
454 (slot usage 'ru-msgrcv)
455 (slot usage 'ru-nsignals)
456 (slot usage 'ru-nvcsw)
457 (slot usage 'ru-nivcsw))
462 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
464 ;;; Perform the UNIX select(2) system call.
465 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
466 (defun unix-fast-select (num-descriptors
467 read-fds write-fds exception-fds
468 timeout-secs &optional (timeout-usecs 0))
469 (declare (type (integer 0 #.fd-setsize) num-descriptors)
470 (type (or (alien (* (struct fd-set))) null)
471 read-fds write-fds exception-fds)
472 (type (or null (unsigned-byte 31)) timeout-secs)
473 (type (unsigned-byte 31) timeout-usecs))
475 ;; (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
476 ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
477 (with-alien ((tv (struct timeval)))
479 (setf (slot tv 'tv-sec) timeout-secs)
480 (setf (slot tv 'tv-usec) timeout-usecs))
481 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
482 (* (struct fd-set)) (* (struct timeval)))
483 num-descriptors read-fds write-fds exception-fds
484 (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
486 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
487 ;;; to happen on one of them or to time out.
488 (defmacro num-to-fd-set (fdset num)
491 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
492 ,@(loop for index upfrom 1 below (/ fd-setsize 32)
493 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
495 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
496 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
497 (ldb (byte 32 ,(* index 32)) ,num))))))
499 (defmacro fd-set-to-num (nfds fdset)
501 (deref (slot ,fdset 'fds-bits) 0)
502 (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
503 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
506 ;;; Examine the sets of descriptors passed as arguments to see whether
507 ;;; they are ready for reading and writing. See the UNIX Programmer's
508 ;;; Manual for more information.
509 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
510 (declare (type (integer 0 #.FD-SETSIZE) nfds)
511 (type unsigned-byte rdfds wrfds xpfds)
512 (type (or (unsigned-byte 31) null) to-secs)
513 (type (unsigned-byte 31) to-usecs)
514 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
515 (with-alien ((tv (struct timeval))
516 (rdf (struct fd-set))
517 (wrf (struct fd-set))
518 (xpf (struct fd-set)))
520 (setf (slot tv 'tv-sec) to-secs)
521 (setf (slot tv 'tv-usec) to-usecs))
522 (num-to-fd-set rdf rdfds)
523 (num-to-fd-set wrf wrfds)
524 (num-to-fd-set xpf xpfds)
525 (macrolet ((frob (lispvar alienvar)
526 `(if (zerop ,lispvar)
528 (alien-sap (addr ,alienvar)))))
529 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
530 (* (struct fd-set)) (* (struct timeval)))
532 (fd-set-to-num nfds rdf)
533 (fd-set-to-num nfds wrf)
534 (fd-set-to-num nfds xpf))
535 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
536 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
540 ;;; This is a structure defined in src/runtime/wrap.c, to look
541 ;;; basically like "struct stat" according to stat(2). It may not
542 ;;; actually correspond to the real in-memory stat structure that the
543 ;;; syscall uses, and that's OK. Linux in particular is packed full of
544 ;;; stat macros, and trying to keep Lisp code in correspondence with
545 ;;; it is more pain than it's worth, so we just let our C runtime
546 ;;; synthesize a nice consistent structure for us.
548 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
549 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
550 ;;; those. We don't actually access that field anywhere, though, so
551 ;;; until we can get 64 bit alien support it'll do. Also note that
552 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
553 ;;; quantity on Alpha. And FIXME: "No one would want a file length
554 ;;; longer than 32 bits anyway, right?":-|
555 (define-alien-type nil
557 (st-dev unsigned-int) ; would be dev-t in a real stat
563 (st-rdev unsigned-int) ; would be dev-t in a real stat
564 (st-size unsigned-int) ; would be off-t in a real stat
565 (st-blksize unsigned-long)
566 (st-blocks unsigned-long)
571 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
572 ;;; family of Unix system calls
574 ;;; FIXME: I think this should probably not be INLINE. However, when
575 ;;; this was not inline, it seemed to cause memory corruption
576 ;;; problems. My first guess is that it's a bug in the FFI code, where
577 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
578 ;;; around a call to a function returning >10 values. But I didn't try
579 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
580 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
581 ;;; output in the not-inlined case and see whether there's a problem,
582 ;;; and maybe even find a fix..
583 (declaim (inline %extract-stat-results))
584 (defun %extract-stat-results (wrapped-stat)
585 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
587 (slot wrapped-stat 'st-dev)
588 (slot wrapped-stat 'st-ino)
589 (slot wrapped-stat 'st-mode)
590 (slot wrapped-stat 'st-nlink)
591 (slot wrapped-stat 'st-uid)
592 (slot wrapped-stat 'st-gid)
593 (slot wrapped-stat 'st-rdev)
594 (slot wrapped-stat 'st-size)
595 (slot wrapped-stat 'st-atime)
596 (slot wrapped-stat 'st-mtime)
597 (slot wrapped-stat 'st-ctime)
598 (slot wrapped-stat 'st-blksize)
599 (slot wrapped-stat 'st-blocks)))
601 ;;; Unix system calls in the stat(2) family are handled by calls to
602 ;;; C-level wrapper functions which copy all the raw "struct stat"
603 ;;; slots into the system-independent wrapped_stat format.
604 ;;; stat(2) <-> stat_wrapper()
605 ;;; fstat(2) <-> fstat_wrapper()
606 ;;; lstat(2) <-> lstat_wrapper()
607 (defun unix-stat (name)
608 (declare (type unix-pathname name))
609 (with-alien ((buf (struct wrapped_stat)))
610 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
611 (%extract-stat-results (addr buf))
613 (defun unix-lstat (name)
614 (declare (type unix-pathname name))
615 (with-alien ((buf (struct wrapped_stat)))
616 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
617 (%extract-stat-results (addr buf))
619 (defun unix-fstat (fd)
620 (declare (type unix-fd fd))
621 (with-alien ((buf (struct wrapped_stat)))
622 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
623 (%extract-stat-results (addr buf))
628 ;; the POSIX.4 structure for a time value. This is like a "struct
629 ;; timeval" but has nanoseconds instead of microseconds.
630 (define-alien-type nil
632 (tv-sec long) ; seconds
633 (tv-nsec long))) ; nanoseconds
635 ;; used by other time functions
636 (define-alien-type nil
638 (tm-sec int) ; Seconds. [0-60] (1 leap second)
639 (tm-min int) ; Minutes. [0-59]
640 (tm-hour int) ; Hours. [0-23]
641 (tm-mday int) ; Day. [1-31]
642 (tm-mon int) ; Month. [0-11]
643 (tm-year int) ; Year - 1900.
644 (tm-wday int) ; Day of week. [0-6]
645 (tm-yday int) ; Days in year. [0-365]
646 (tm-isdst int) ; DST. [-1/0/1]
647 (tm-gmtoff long) ; Seconds east of UTC.
648 (tm-zone c-string))) ; Timezone abbreviation.
650 (define-alien-routine get-timezone sb!alien:void
651 (when sb!alien:long :in)
652 (seconds-west sb!alien:int :out)
653 (daylight-savings-p sb!alien:boolean :out))
655 (defun unix-get-seconds-west (secs)
656 (multiple-value-bind (ignore seconds dst) (get-timezone secs)
657 (declare (ignore ignore) (ignore dst))
662 ;;; Structure crudely representing a timezone. KLUDGE: This is
663 ;;; obsolete and should never be used.
664 (define-alien-type nil
666 (tz-minuteswest int) ; minutes west of Greenwich
667 (tz-dsttime int))) ; type of dst correction
669 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
670 ;;; and microseconds of the current time of day, the timezone (in
671 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
672 ;;; doesn't work, it returns NIL and the errno.
673 #!-sb-fluid (declaim (inline unix-gettimeofday))
674 (defun unix-gettimeofday ()
675 (with-alien ((tv (struct timeval))
676 (tz (struct timezone)))
677 (syscall* ("gettimeofday" (* (struct timeval))
678 (* (struct timezone)))
682 (slot tz 'tz-minuteswest)
683 (slot tz 'tz-dsttime))
688 ;; Type of the second argument to `getitimer' and
689 ;; the second and third arguments `setitimer'.
690 (define-alien-type nil
692 (it-interval (struct timeval)) ; timer interval
693 (it-value (struct timeval)))) ; current value
695 (defconstant ITIMER-REAL 0)
696 (defconstant ITIMER-VIRTUAL 1)
697 (defconstant ITIMER-PROF 2)
699 (defun unix-getitimer(which)
700 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
701 three system timers (:real :virtual or :profile). On success,
702 unix-getitimer returns 5 values,
703 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
704 (declare (type (member :real :virtual :profile) which)
706 (unsigned-byte 29) (mod 1000000)
707 (unsigned-byte 29) (mod 1000000)))
708 (let ((which (ecase which
710 (:virtual ITIMER-VIRTUAL)
711 (:profile ITIMER-PROF))))
712 (with-alien ((itv (struct itimerval)))
713 (syscall* ("getitimer" int (* (struct itimerval)))
715 (slot (slot itv 'it-interval) 'tv-sec)
716 (slot (slot itv 'it-interval) 'tv-usec)
717 (slot (slot itv 'it-value) 'tv-sec)
718 (slot (slot itv 'it-value) 'tv-usec))
719 which (alien-sap (addr itv))))))
721 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
722 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
723 three system timers (:real :virtual or :profile). A SIGALRM signal
724 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
725 when non-zero, is <seconds+microseconds> to be loaded each time
726 the timer expires. Setting INTERVAL and VALUE to zero disables
727 the timer. See the Unix man page for more details. On success,
728 unix-setitimer returns the old contents of the INTERVAL and VALUE
729 slots as in unix-getitimer."
730 (declare (type (member :real :virtual :profile) which)
731 (type (unsigned-byte 29) int-secs val-secs)
732 (type (integer 0 (1000000)) int-usec val-usec)
734 (unsigned-byte 29) (mod 1000000)
735 (unsigned-byte 29) (mod 1000000)))
736 (let ((which (ecase which
738 (:virtual ITIMER-VIRTUAL)
739 (:profile ITIMER-PROF))))
740 (with-alien ((itvn (struct itimerval))
741 (itvo (struct itimerval)))
742 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
743 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
744 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
745 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
746 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
748 (slot (slot itvo 'it-interval) 'tv-sec)
749 (slot (slot itvo 'it-interval) 'tv-usec)
750 (slot (slot itvo 'it-value) 'tv-sec)
751 (slot (slot itvo 'it-value) 'tv-usec))
752 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
754 (defmacro sb!ext:with-timeout (expires &body body)
755 "Execute the body, interrupting it with a SIGALRM after at least
756 EXPIRES seconds have passed. Uses Unix setitimer(), restoring any
757 previous timer after the body has finished executing"
758 (with-unique-names (saved-seconds saved-useconds s u)
759 `(let (- ,saved-seconds ,saved-useconds)
760 (multiple-value-setq (- - - ,saved-seconds ,saved-useconds)
761 (unix-getitimer :real))
762 (multiple-value-bind (,s ,u) (floor ,expires)
763 (setf ,u (floor (* ,u 1000000)))
764 (if (and (> ,expires 0)
765 (or (and (zerop ,saved-seconds) (zerop ,saved-useconds))
766 (> ,saved-seconds ,s)
767 (and (= ,saved-seconds ,s)
768 (> ,saved-useconds ,u))))
771 (unix-setitimer :real 0 0 ,s ,u)
773 (unix-setitimer :real 0 0 ,saved-seconds ,saved-useconds))
777 ;;; FIXME: Many Unix error code definitions were deleted from the old
778 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
779 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
780 ;;; unused symbols in package exports, but if I don't, there are
781 ;;; enough of them all in one place here that they should probably be
784 ;;;; support routines for dealing with Unix pathnames
786 (defun unix-file-kind (name &optional check-for-links)
788 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
789 (declare (simple-base-string name))
790 (multiple-value-bind (res dev ino mode)
791 (if check-for-links (unix-lstat name) (unix-stat name))
792 (declare (type (or fixnum null) mode)
795 (let ((kind (logand mode s-ifmt)))
796 (cond ((eql kind s-ifdir) :directory)
797 ((eql kind s-ifreg) :file)
798 ((eql kind s-iflnk) :link)
801 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
802 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
803 (defun relative-unix-pathname? (pathname)
804 (declare (type simple-string pathname))
805 (or (zerop (length pathname))
806 (char/= (schar pathname 0) #\/)))
808 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
809 ;;; already be a complete absolute Unix pathname, since at least in
810 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
811 ;;; paths have been converted to absolute paths, so we don't need to
812 ;;; try to handle any more generality than that.
813 (defun unix-resolve-links (pathname)
814 (declare (type simple-string pathname))
815 (aver (not (relative-unix-pathname? pathname)))
816 (/noshow "entering UNIX-RESOLVE-LINKS")
817 (loop with previous-pathnames = nil do
818 (/noshow pathname previous-pathnames)
819 (let ((link (unix-readlink pathname)))
821 ;; Unlike the old CMU CL code, we handle a broken symlink by
822 ;; returning the link itself. That way, CL:TRUENAME on a
823 ;; broken link returns the link itself, so that CL:DIRECTORY
824 ;; can return broken links, so that even without
825 ;; Unix-specific extensions to do interesting things with
826 ;; them, at least Lisp programs can see them and, if
827 ;; necessary, delete them. (This is handy e.g. when your
828 ;; managed-by-Lisp directories are visited by Emacs, which
829 ;; creates broken links as notes to itself.)
833 (unix-simplify-pathname
834 (if (relative-unix-pathname? link)
835 (let* ((dir-len (1+ (position #\/
838 (dir (subseq pathname 0 dir-len)))
840 (concatenate 'string dir link))
842 (if (unix-file-kind new-pathname)
843 (setf pathname new-pathname)
844 (return pathname)))))
845 ;; To generalize the principle that even if portable Lisp code
846 ;; can't do anything interesting with a broken symlink, at
847 ;; least it should be able to see and delete it, when we
848 ;; detect a cyclic link, we return the link itself. (So even
849 ;; though portable Lisp code can't do anything interesting
850 ;; with a cyclic link, at least it can see it and delete it.)
851 (if (member pathname previous-pathnames :test #'string=)
853 (push pathname previous-pathnames))))
855 (defun unix-simplify-pathname (src)
856 (declare (type simple-string src))
857 (let* ((src-len (length src))
858 (dst (make-string src-len))
862 (macrolet ((deposit (char)
864 (setf (schar dst dst-len) ,char)
866 (dotimes (src-index src-len)
867 (let ((char (schar src src-index)))
868 (cond ((char= char #\.)
875 ;; either ``/...' or ``...//...'
877 (setf last-slash dst-len)
880 ;; either ``./...'' or ``..././...''
885 ((and last-slash (not (zerop last-slash)))
886 ;; There is something before this ..
887 (let ((prev-prev-slash
888 (position #\/ dst :end last-slash :from-end t)))
889 (cond ((and (= (+ (or prev-prev-slash 0) 2)
891 (char= (schar dst (- last-slash 2)) #\.)
892 (char= (schar dst (1- last-slash)) #\.))
893 ;; The something before this .. is another ..
895 (setf last-slash dst-len))
897 ;; The something is some directory or other.
902 (setf last-slash prev-prev-slash)))))
904 ;; There is nothing before this .., so we need to keep it
905 (setf last-slash dst-len)
908 ;; something other than a dot between slashes
909 (setf last-slash dst-len)
914 (setf (schar dst dst-len) char)
916 (when (and last-slash (not (zerop last-slash)))
919 ;; We've got ``foobar/.''
922 ;; We've got ``foobar/..''
923 (unless (and (>= last-slash 2)
924 (char= (schar dst (1- last-slash)) #\.)
925 (char= (schar dst (- last-slash 2)) #\.)
927 (char= (schar dst (- last-slash 3)) #\/)))
928 (let ((prev-prev-slash
929 (position #\/ dst :end last-slash :from-end t)))
931 (setf dst-len (1+ prev-prev-slash))
932 (return-from unix-simplify-pathname "./")))))))
933 (cond ((zerop dst-len)
938 (subseq dst 0 dst-len)))))
940 ;;;; A magic constant for wait3().
942 ;;;; FIXME: This used to be defined in run-program.lisp as
943 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
944 ;;;; According to some of the man pages, the #o177 is part of the API
945 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
946 ;;;; the headers that may or may not be the same thing. To be
947 ;;;; investigated. -- CSR, 2002-03-25
948 (defconstant wstopped #o177)
951 ;;;; stuff not yet found in the header files
953 ;;;; Abandon all hope who enters here...
955 ;;; not checked for linux...
956 (defmacro fd-set (offset fd-set)
957 (let ((word (gensym))
959 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
960 (setf (deref (slot ,fd-set 'fds-bits) ,word)
961 (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
962 (deref (slot ,fd-set 'fds-bits) ,word))))))
964 ;;; not checked for linux...
965 (defmacro fd-clr (offset fd-set)
966 (let ((word (gensym))
968 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
969 (setf (deref (slot ,fd-set 'fds-bits) ,word)
970 (logand (deref (slot ,fd-set 'fds-bits) ,word)
971 ;; FIXME: This may not be quite right for 64-bit
972 ;; ports of SBCL. --njf, 2004-08-04
973 (sb!kernel:word-logical-not
974 (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
976 ;;; not checked for linux...
977 (defmacro fd-isset (offset fd-set)
978 (let ((word (gensym))
980 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
981 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
983 ;;; not checked for linux...
984 (defmacro fd-zero (fd-set)
986 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
987 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))