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)
67 `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
70 (values nil (get-errno))
73 ;;; This is like SYSCALL, but if it fails, signal an error instead of
74 ;;; returning error codes. Should only be used for syscalls that will
75 ;;; never really get an error.
76 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
77 `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
80 (error "Syscall ~A failed: ~A" ,name (strerror))
83 (/show0 "unix.lisp 109")
85 (defmacro void-syscall ((name &rest arg-types) &rest args)
86 `(syscall (,name ,@arg-types) (values t 0) ,@args))
88 (defmacro int-syscall ((name &rest arg-types) &rest args)
89 `(syscall (,name ,@arg-types) (values result 0) ,@args))
91 ;;;; hacking the Unix environment
93 (define-alien-routine ("getenv" posix-getenv) c-string
94 "Return the \"value\" part of the environment string \"name=value\" which
95 corresponds to NAME, or NIL if there is none."
100 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
101 ;;; error code is returned if an error occurs.
102 (defun unix-rename (name1 name2)
103 (declare (type unix-pathname name1 name2))
104 (void-syscall ("rename" c-string c-string) name1 name2))
106 ;;; from sys/types.h and gnu/types.h
108 (/show0 "unix.lisp 220")
110 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
111 ;;; like this unless we have extreme provocation. Reading directories
112 ;;; is not extreme enough, since it doesn't need to be blindingly
113 ;;; fast: we can just implement those functions in C as a wrapper
115 (define-alien-type fd-mask unsigned-long)
117 (eval-when (:compile-toplevel :load-toplevel :execute)
118 (defconstant fd-setsize 1024))
120 (define-alien-type nil
122 (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
124 (/show0 "unix.lisp 304")
129 ;;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
131 ;;; Open the file whose pathname is specified by PATH for reading
132 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
133 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
135 ;;; If the O_CREAT flag is specified, then the file is created with a
136 ;;; permission of argument MODE if the file doesn't exist. An integer
137 ;;; file descriptor is returned by UNIX-OPEN.
138 (defun unix-open (path flags mode)
139 (declare (type unix-pathname path)
141 (type unix-file-mode mode))
142 (int-syscall ("open" c-string int int) path flags mode))
144 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
145 ;;; associated with it.
146 (/show0 "unix.lisp 391")
147 (defun unix-close (fd)
148 (declare (type unix-fd fd))
149 (void-syscall ("close" int) fd))
153 ;; A time value that is accurate to the nearest
154 ;; microsecond but also has a range of years.
155 (define-alien-type nil
157 (tv-sec time-t) ; seconds
158 (tv-usec time-t))) ; and microseconds
162 (defconstant rusage_self 0) ; the calling process
163 (defconstant rusage_children -1) ; terminated child processes
164 (defconstant rusage_both -2)
166 (define-alien-type nil
168 (ru-utime (struct timeval)) ; user time used
169 (ru-stime (struct timeval)) ; system time used.
170 (ru-maxrss long) ; maximum resident set size (in kilobytes)
171 (ru-ixrss long) ; integral shared memory size
172 (ru-idrss long) ; integral unshared data size
173 (ru-isrss long) ; integral unshared stack size
174 (ru-minflt long) ; page reclaims
175 (ru-majflt long) ; page faults
176 (ru-nswap long) ; swaps
177 (ru-inblock long) ; block input operations
178 (ru-oublock long) ; block output operations
179 (ru-msgsnd long) ; messages sent
180 (ru-msgrcv long) ; messages received
181 (ru-nsignals long) ; signals received
182 (ru-nvcsw long) ; voluntary context switches
183 (ru-nivcsw long))) ; involuntary context switches
187 ;;; Given a file path (a string) and one of four constant modes,
188 ;;; return T if the file is accessible with that mode and NIL if not.
189 ;;; When NIL, also return an errno value with NIL which tells why the
190 ;;; file was not accessible.
192 ;;; The access modes are:
193 ;;; r_ok Read permission.
194 ;;; w_ok Write permission.
195 ;;; x_ok Execute permission.
196 ;;; f_ok Presence of file.
197 (defun unix-access (path mode)
198 (declare (type unix-pathname path)
200 (void-syscall ("access" c-string int) path mode))
202 ;;; values for the second argument to UNIX-LSEEK
203 (defconstant l_set 0) ; to set the file pointer
204 (defconstant l_incr 1) ; to increment the file pointer
205 (defconstant l_xtnd 2) ; to extend the file size
207 ;;; Is a stream interactive?
208 (defun unix-isatty (fd)
209 (declare (type unix-fd fd))
210 (int-syscall ("isatty" int) fd))
212 (defun unix-lseek (fd offset whence)
213 "Unix-lseek accepts a file descriptor and moves the file pointer by
214 OFFSET octets. Whence can be any of the following:
216 L_SET Set the file pointer.
217 L_INCR Increment the file pointer.
218 L_XTND Extend the file size.
220 (declare (type unix-fd fd)
221 (type (integer 0 2) whence))
222 (int-syscall ("lseek" int off-t int) fd offset whence))
224 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
225 ;;; It attempts to read len bytes from the device associated with fd
226 ;;; and store them into the buffer. It returns the actual number of
228 (defun unix-read (fd buf len)
229 (declare (type unix-fd fd)
230 (type (unsigned-byte 32) len))
232 (int-syscall ("read" int (* char) int) fd buf len))
234 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
235 ;;; length to write. It attempts to write len bytes to the device
236 ;;; associated with fd from the the buffer starting at offset. It returns
237 ;;; the actual number of bytes written.
238 (defun unix-write (fd buf offset len)
239 (declare (type unix-fd fd)
240 (type (unsigned-byte 32) offset len))
241 (int-syscall ("write" int (* char) int)
243 (with-alien ((ptr (* char) (etypecase buf
244 ((simple-array * (*))
248 (addr (deref ptr offset)))
251 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
252 ;;; output pipe. Return two values: if no error occurred the first
253 ;;; value is the pipe to be read from and the second is can be written
254 ;;; to. If an error occurred the first value is NIL and the second the
257 (with-alien ((fds (array int 2)))
258 (syscall ("pipe" (* int))
259 (values (deref fds 0) (deref fds 1))
260 (cast fds (* int)))))
262 (defun unix-mkdir (name mode)
263 (declare (type unix-pathname name)
264 (type unix-file-mode mode))
265 (void-syscall ("mkdir" c-string int) name mode))
267 ;;; Given a C char* pointer allocated by malloc(), free it and return a
268 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
269 (defun newcharstar-string (newcharstar)
270 (declare (type (alien (* char)) newcharstar))
271 (if (null-alien newcharstar)
274 (cast newcharstar c-string)
275 (free-alien newcharstar))))
277 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
278 ;;; style returned by getcwd() (no trailing slash character).
279 (defun posix-getcwd ()
280 ;; This implementation relies on a BSD/Linux extension to getcwd()
281 ;; behavior, automatically allocating memory when a null buffer
282 ;; pointer is used. On a system which doesn't support that
283 ;; extension, it'll have to be rewritten somehow.
285 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
286 ;; buffer pointer, it will automatically allocate size space. The
287 ;; KLUDGE in this solution arises because we have just read off
288 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
289 ;; a constant. Going the grovel_headers route doesn't seem to be
290 ;; helpful, either, as Solaris doesn't export PATH_MAX from
292 #!-(or linux openbsd freebsd sunos osf1) (,stub,)
293 #!+(or linux openbsd freebsd sunos osf1)
294 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
299 #!+(or linux openbsd freebsd) 0
300 #!+(or sunos osf1) 1025))
301 (simple-perror "getcwd")))
303 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
304 ;;; by a slash character.
305 (defun posix-getcwd/ ()
306 (concatenate 'string (posix-getcwd) "/"))
308 ;;; Convert at the UNIX level from a possibly relative filename to
309 ;;; an absolute filename.
311 ;;; FIXME: Do we still need this even as we switch to
312 ;;; *DEFAULT-PATHNAME-DEFAULTS*? I think maybe we do, since it seems
313 ;;; to be valid for the user to set *DEFAULT-PATHNAME-DEFAULTS* to
314 ;;; have a NIL directory component, and then this'd be the only way to
315 ;;; interpret a relative directory specification. But I don't find the
316 ;;; ANSI pathname documentation to be a model of clarity. Maybe
317 ;;; someone who understands it better can take a look at this.. -- WHN
318 (defun unix-maybe-prepend-current-directory (name)
319 (declare (simple-string name))
320 (if (and (> (length name) 0) (char= (schar name 0) #\/))
322 (concatenate 'simple-string (posix-getcwd/) name)))
324 ;;; Duplicate an existing file descriptor (given as the argument) and
325 ;;; return it. If FD is not a valid file descriptor, NIL and an error
326 ;;; number are returned.
328 (declare (type unix-fd fd))
329 (int-syscall ("dup" int) fd))
331 ;;; Terminate the current process with an optional error code. If
332 ;;; successful, the call doesn't return. If unsuccessful, the call
333 ;;; returns NIL and an error number.
334 (defun unix-exit (&optional (code 0))
335 (declare (type (signed-byte 32) code))
336 (void-syscall ("exit" int) code))
338 ;;; Return the process id of the current process.
339 (define-alien-routine ("getpid" unix-getpid) int)
341 ;;; Return the real user id associated with the current process.
342 (define-alien-routine ("getuid" unix-getuid) int)
344 ;;; Translate a user id into a login name.
345 (defun uid-username (uid)
346 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
347 (function (* char) int))
349 (error "found no match for Unix uid=~S" uid)))
351 ;;; Return the namestring of the home directory, being careful to
352 ;;; include a trailing #\/
353 (defun uid-homedir (uid)
354 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
355 (function (* char) int))
357 (error "failed to resolve home directory for Unix uid=~S" uid)))
359 ;;; Invoke readlink(2) on the file name specified by PATH. Return
360 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
362 (defun unix-readlink (path)
363 (declare (type unix-pathname path))
364 (with-alien ((ptr (* char)
365 (alien-funcall (extern-alien
367 (function (* char) c-string))
370 (values nil (get-errno))
371 (multiple-value-prog1
372 (values (with-alien ((c-string c-string ptr)) c-string)
376 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
377 ;;; name and the file if this is the last link.
378 (defun unix-unlink (name)
379 (declare (type unix-pathname name))
380 (void-syscall ("unlink" c-string) name))
382 ;;; Return the name of the host machine as a string.
383 (defun unix-gethostname ()
384 (with-alien ((buf (array char 256)))
385 (syscall ("gethostname" (* char) int)
387 (cast buf (* char)) 256)))
389 ;;; Write the core image of the file described by FD to disk.
390 (defun unix-fsync (fd)
391 (declare (type unix-fd fd))
392 (void-syscall ("fsync" int) fd))
395 (defun unix-setsid ()
396 (int-syscall ("setsid")))
400 ;;; UNIX-IOCTL performs a variety of operations on open i/o
401 ;;; descriptors. See the UNIX Programmer's Manual for more
403 (defun unix-ioctl (fd cmd arg)
404 (declare (type unix-fd fd)
405 (type (signed-byte 32) cmd))
406 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
410 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
412 ;;; This is like getrusage(2), except it returns only the system and
413 ;;; user time, and returns the seconds and microseconds as separate
415 #!-sb-fluid (declaim (inline unix-fast-getrusage))
416 (defun unix-fast-getrusage (who)
417 (declare (values (member t)
418 (unsigned-byte 31) (integer 0 1000000)
419 (unsigned-byte 31) (integer 0 1000000)))
420 (with-alien ((usage (struct rusage)))
421 (syscall* ("getrusage" int (* (struct rusage)))
423 (slot (slot usage 'ru-utime) 'tv-sec)
424 (slot (slot usage 'ru-utime) 'tv-usec)
425 (slot (slot usage 'ru-stime) 'tv-sec)
426 (slot (slot usage 'ru-stime) 'tv-usec))
429 ;;; Return information about the resource usage of the process
430 ;;; specified by WHO. WHO can be either the current process
431 ;;; (rusage_self) or all of the terminated child processes
432 ;;; (rusage_children). NIL and an error number is returned if the call
434 (defun unix-getrusage (who)
435 (with-alien ((usage (struct rusage)))
436 (syscall ("getrusage" int (* (struct rusage)))
438 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
439 (slot (slot usage 'ru-utime) 'tv-usec))
440 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
441 (slot (slot usage 'ru-stime) 'tv-usec))
442 (slot usage 'ru-maxrss)
443 (slot usage 'ru-ixrss)
444 (slot usage 'ru-idrss)
445 (slot usage 'ru-isrss)
446 (slot usage 'ru-minflt)
447 (slot usage 'ru-majflt)
448 (slot usage 'ru-nswap)
449 (slot usage 'ru-inblock)
450 (slot usage 'ru-oublock)
451 (slot usage 'ru-msgsnd)
452 (slot usage 'ru-msgrcv)
453 (slot usage 'ru-nsignals)
454 (slot usage 'ru-nvcsw)
455 (slot usage 'ru-nivcsw))
460 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
462 ;;; Perform the UNIX select(2) system call.
463 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
464 (defun unix-fast-select (num-descriptors
465 read-fds write-fds exception-fds
466 timeout-secs &optional (timeout-usecs 0))
467 (declare (type (integer 0 #.fd-setsize) num-descriptors)
468 (type (or (alien (* (struct fd-set))) null)
469 read-fds write-fds exception-fds)
470 (type (or null (unsigned-byte 31)) timeout-secs)
471 (type (unsigned-byte 31) timeout-usecs))
473 ;; (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
474 ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
475 (with-alien ((tv (struct timeval)))
477 (setf (slot tv 'tv-sec) timeout-secs)
478 (setf (slot tv 'tv-usec) timeout-usecs))
479 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
480 (* (struct fd-set)) (* (struct timeval)))
481 num-descriptors read-fds write-fds exception-fds
482 (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
484 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
485 ;;; to happen on one of them or to time out.
486 (defmacro num-to-fd-set (fdset num)
489 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
490 ,@(loop for index upfrom 1 below (/ fd-setsize 32)
491 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
493 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
494 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
495 (ldb (byte 32 ,(* index 32)) ,num))))))
497 (defmacro fd-set-to-num (nfds fdset)
499 (deref (slot ,fdset 'fds-bits) 0)
500 (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
501 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
504 ;;; Examine the sets of descriptors passed as arguments to see whether
505 ;;; they are ready for reading and writing. See the UNIX Programmer's
506 ;;; Manual for more information.
507 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
508 (declare (type (integer 0 #.FD-SETSIZE) nfds)
509 (type unsigned-byte rdfds wrfds xpfds)
510 (type (or (unsigned-byte 31) null) to-secs)
511 (type (unsigned-byte 31) to-usecs)
512 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
513 (with-alien ((tv (struct timeval))
514 (rdf (struct fd-set))
515 (wrf (struct fd-set))
516 (xpf (struct fd-set)))
518 (setf (slot tv 'tv-sec) to-secs)
519 (setf (slot tv 'tv-usec) to-usecs))
520 (num-to-fd-set rdf rdfds)
521 (num-to-fd-set wrf wrfds)
522 (num-to-fd-set xpf xpfds)
523 (macrolet ((frob (lispvar alienvar)
524 `(if (zerop ,lispvar)
526 (alien-sap (addr ,alienvar)))))
527 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
528 (* (struct fd-set)) (* (struct timeval)))
530 (fd-set-to-num nfds rdf)
531 (fd-set-to-num nfds wrf)
532 (fd-set-to-num nfds xpf))
533 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
534 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
538 ;;; This is a structure defined in src/runtime/wrap.c, to look
539 ;;; basically like "struct stat" according to stat(2). It may not
540 ;;; actually correspond to the real in-memory stat structure that the
541 ;;; syscall uses, and that's OK. Linux in particular is packed full of
542 ;;; stat macros, and trying to keep Lisp code in correspondence with
543 ;;; it is more pain than it's worth, so we just let our C runtime
544 ;;; synthesize a nice consistent structure for us.
546 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
547 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
548 ;;; those. We don't actually access that field anywhere, though, so
549 ;;; until we can get 64 bit alien support it'll do. Also note that
550 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
551 ;;; quantity on Alpha. And FIXME: "No one would want a file length
552 ;;; longer than 32 bits anyway, right?":-|
553 (define-alien-type nil
555 (st-dev unsigned-long) ; would be dev-t in a real stat
561 (st-rdev unsigned-long) ; would be dev-t in a real stat
562 (st-size unsigned-long) ; would be off-t in a real stat
563 (st-blksize unsigned-long)
564 (st-blocks unsigned-long)
569 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
570 ;;; family of Unix system calls
572 ;;; FIXME: I think this should probably not be INLINE. However, when
573 ;;; this was not inline, it seemed to cause memory corruption
574 ;;; problems. My first guess is that it's a bug in the FFI code, where
575 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
576 ;;; around a call to a function returning >10 values. But I didn't try
577 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
578 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
579 ;;; output in the not-inlined case and see whether there's a problem,
580 ;;; and maybe even find a fix..
581 (declaim (inline %extract-stat-results))
582 (defun %extract-stat-results (wrapped-stat)
583 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
585 (slot wrapped-stat 'st-dev)
586 (slot wrapped-stat 'st-ino)
587 (slot wrapped-stat 'st-mode)
588 (slot wrapped-stat 'st-nlink)
589 (slot wrapped-stat 'st-uid)
590 (slot wrapped-stat 'st-gid)
591 (slot wrapped-stat 'st-rdev)
592 (slot wrapped-stat 'st-size)
593 (slot wrapped-stat 'st-atime)
594 (slot wrapped-stat 'st-mtime)
595 (slot wrapped-stat 'st-ctime)
596 (slot wrapped-stat 'st-blksize)
597 (slot wrapped-stat 'st-blocks)))
599 ;;; Unix system calls in the stat(2) family are handled by calls to
600 ;;; C-level wrapper functions which copy all the raw "struct stat"
601 ;;; slots into the system-independent wrapped_stat format.
602 ;;; stat(2) <-> stat_wrapper()
603 ;;; fstat(2) <-> fstat_wrapper()
604 ;;; lstat(2) <-> lstat_wrapper()
605 (defun unix-stat (name)
606 (declare (type unix-pathname name))
607 (with-alien ((buf (struct wrapped_stat)))
608 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
609 (%extract-stat-results (addr buf))
611 (defun unix-lstat (name)
612 (declare (type unix-pathname name))
613 (with-alien ((buf (struct wrapped_stat)))
614 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
615 (%extract-stat-results (addr buf))
617 (defun unix-fstat (fd)
618 (declare (type unix-fd fd))
619 (with-alien ((buf (struct wrapped_stat)))
620 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
621 (%extract-stat-results (addr buf))
626 ;; the POSIX.4 structure for a time value. This is like a "struct
627 ;; timeval" but has nanoseconds instead of microseconds.
628 (define-alien-type nil
630 (tv-sec long) ; seconds
631 (tv-nsec long))) ; nanoseconds
633 ;; used by other time functions
634 (define-alien-type nil
636 (tm-sec int) ; Seconds. [0-60] (1 leap second)
637 (tm-min int) ; Minutes. [0-59]
638 (tm-hour int) ; Hours. [0-23]
639 (tm-mday int) ; Day. [1-31]
640 (tm-mon int) ; Month. [0-11]
641 (tm-year int) ; Year - 1900.
642 (tm-wday int) ; Day of week. [0-6]
643 (tm-yday int) ; Days in year. [0-365]
644 (tm-isdst int) ; DST. [-1/0/1]
645 (tm-gmtoff long) ; Seconds east of UTC.
646 (tm-zone c-string))) ; Timezone abbreviation.
648 (define-alien-routine get-timezone sb!alien:void
649 (when sb!alien:long :in)
650 (minutes-west sb!alien:int :out)
651 (daylight-savings-p sb!alien:boolean :out))
653 (defun unix-get-minutes-west (secs)
654 (multiple-value-bind (ignore minutes dst) (get-timezone secs)
655 (declare (ignore ignore) (ignore dst))
658 (defun unix-get-timezone (secs)
659 (multiple-value-bind (ignore minutes dst) (get-timezone secs)
660 (declare (ignore ignore) (ignore minutes))
661 (values (deref unix-tzname (if dst 1 0)))))
666 ;;; Structure crudely representing a timezone. KLUDGE: This is
667 ;;; obsolete and should never be used.
668 (define-alien-type nil
670 (tz-minuteswest int) ; minutes west of Greenwich
671 (tz-dsttime int))) ; type of dst correction
673 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
674 ;;; and microseconds of the current time of day, the timezone (in
675 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
676 ;;; doesn't work, it returns NIL and the errno.
677 #!-sb-fluid (declaim (inline unix-gettimeofday))
678 (defun unix-gettimeofday ()
679 (with-alien ((tv (struct timeval))
680 (tz (struct timezone)))
681 (syscall* ("gettimeofday" (* (struct timeval))
682 (* (struct timezone)))
686 (slot tz 'tz-minuteswest)
687 (slot tz 'tz-dsttime))
692 ;; Type of the second argument to `getitimer' and
693 ;; the second and third arguments `setitimer'.
694 (define-alien-type nil
696 (it-interval (struct timeval)) ; timer interval
697 (it-value (struct timeval)))) ; current value
699 (defconstant ITIMER-REAL 0)
700 (defconstant ITIMER-VIRTUAL 1)
701 (defconstant ITIMER-PROF 2)
703 (defun unix-getitimer(which)
704 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
705 three system timers (:real :virtual or :profile). On success,
706 unix-getitimer returns 5 values,
707 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
708 (declare (type (member :real :virtual :profile) which)
710 (unsigned-byte 29) (mod 1000000)
711 (unsigned-byte 29) (mod 1000000)))
712 (let ((which (ecase which
714 (:virtual ITIMER-VIRTUAL)
715 (:profile ITIMER-PROF))))
716 (with-alien ((itv (struct itimerval)))
717 (syscall* ("getitimer" int (* (struct itimerval)))
719 (slot (slot itv 'it-interval) 'tv-sec)
720 (slot (slot itv 'it-interval) 'tv-usec)
721 (slot (slot itv 'it-value) 'tv-sec)
722 (slot (slot itv 'it-value) 'tv-usec))
723 which (alien-sap (addr itv))))))
725 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
726 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
727 three system timers (:real :virtual or :profile). A SIGALRM signal
728 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
729 when non-zero, is <seconds+microseconds> to be loaded each time
730 the timer expires. Setting INTERVAL and VALUE to zero disables
731 the timer. See the Unix man page for more details. On success,
732 unix-setitimer returns the old contents of the INTERVAL and VALUE
733 slots as in unix-getitimer."
734 (declare (type (member :real :virtual :profile) which)
735 (type (unsigned-byte 29) int-secs val-secs)
736 (type (integer 0 (1000000)) int-usec val-usec)
738 (unsigned-byte 29) (mod 1000000)
739 (unsigned-byte 29) (mod 1000000)))
740 (let ((which (ecase which
742 (:virtual ITIMER-VIRTUAL)
743 (:profile ITIMER-PROF))))
744 (with-alien ((itvn (struct itimerval))
745 (itvo (struct itimerval)))
746 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
747 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
748 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
749 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
750 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
752 (slot (slot itvo 'it-interval) 'tv-sec)
753 (slot (slot itvo 'it-interval) 'tv-usec)
754 (slot (slot itvo 'it-value) 'tv-sec)
755 (slot (slot itvo 'it-value) 'tv-usec))
756 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
758 (defmacro sb!ext::with-timeout (expires &body body)
759 "Execute the body, interrupting it with a SIGALRM after at least
760 EXPIRES seconds have passed. Uses Unix setitimer(), restoring any
761 previous timer after the body has finished executing"
762 (with-unique-names (saved-seconds saved-useconds s u)
763 `(let (- ,saved-seconds ,saved-useconds)
764 (multiple-value-setq (- - - ,saved-seconds ,saved-useconds)
765 (unix-getitimer :real))
766 (multiple-value-bind (,s ,u) (floor ,expires)
767 (setf ,u (floor (* ,u 1000000)))
768 (if (and (> ,expires 0)
769 (or (and (zerop ,saved-seconds) (zerop ,saved-useconds))
770 (> ,saved-seconds ,s)
771 (and (= ,saved-seconds ,s)
772 (> ,saved-useconds ,u))))
775 (unix-setitimer :real 0 0 ,s ,u)
777 (unix-setitimer :real 0 0 ,saved-seconds ,saved-useconds))
782 (defconstant ENOENT 2) ; Unix error code, "No such file or directory"
783 (defconstant EINTR 4) ; Unix error code, "Interrupted system call"
784 (defconstant EIO 5) ; Unix error code, "I/O error"
785 (defconstant EEXIST 17) ; Unix error code, "File exists"
786 (defconstant ESPIPE 29) ; Unix error code, "Illegal seek"
787 (defconstant EWOULDBLOCK 11) ; Unix error code, "Operation would block"
788 ;;; FIXME: Many Unix error code definitions were deleted from the old
789 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
790 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
791 ;;; unused symbols in package exports, but if I don't, there are
792 ;;; enough of them all in one place here that they should probably be
796 ;;;; support routines for dealing with Unix pathnames
798 (defun unix-file-kind (name &optional check-for-links)
800 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
801 (declare (simple-base-string name))
802 (multiple-value-bind (res dev ino mode)
803 (if check-for-links (unix-lstat name) (unix-stat name))
804 (declare (type (or fixnum null) mode)
807 (let ((kind (logand mode s-ifmt)))
808 (cond ((eql kind s-ifdir) :directory)
809 ((eql kind s-ifreg) :file)
810 ((eql kind s-iflnk) :link)
813 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
814 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
815 (defun relative-unix-pathname? (pathname)
816 (declare (type simple-string pathname))
817 (or (zerop (length pathname))
818 (char/= (schar pathname 0) #\/)))
820 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
821 ;;; already be a complete absolute Unix pathname, since at least in
822 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
823 ;;; paths have been converted to absolute paths, so we don't need to
824 ;;; try to handle any more generality than that.
825 (defun unix-resolve-links (pathname)
826 (declare (type simple-string pathname))
827 (aver (not (relative-unix-pathname? pathname)))
828 (/noshow "entering UNIX-RESOLVE-LINKS")
829 (loop with previous-pathnames = nil do
830 (/noshow pathname previous-pathnames)
831 (let ((link (unix-readlink pathname)))
833 ;; Unlike the old CMU CL code, we handle a broken symlink by
834 ;; returning the link itself. That way, CL:TRUENAME on a
835 ;; broken link returns the link itself, so that CL:DIRECTORY
836 ;; can return broken links, so that even without
837 ;; Unix-specific extensions to do interesting things with
838 ;; them, at least Lisp programs can see them and, if
839 ;; necessary, delete them. (This is handy e.g. when your
840 ;; managed-by-Lisp directories are visited by Emacs, which
841 ;; creates broken links as notes to itself.)
845 (unix-simplify-pathname
846 (if (relative-unix-pathname? link)
847 (let* ((dir-len (1+ (position #\/
850 (dir (subseq pathname 0 dir-len)))
852 (concatenate 'string dir link))
854 (if (unix-file-kind new-pathname)
855 (setf pathname new-pathname)
856 (return pathname)))))
857 ;; To generalize the principle that even if portable Lisp code
858 ;; can't do anything interesting with a broken symlink, at
859 ;; least it should be able to see and delete it, when we
860 ;; detect a cyclic link, we return the link itself. (So even
861 ;; though portable Lisp code can't do anything interesting
862 ;; with a cyclic link, at least it can see it and delete it.)
863 (if (member pathname previous-pathnames :test #'string=)
865 (push pathname previous-pathnames))))
867 (defun unix-simplify-pathname (src)
868 (declare (type simple-string src))
869 (let* ((src-len (length src))
870 (dst (make-string src-len))
874 (macrolet ((deposit (char)
876 (setf (schar dst dst-len) ,char)
878 (dotimes (src-index src-len)
879 (let ((char (schar src src-index)))
880 (cond ((char= char #\.)
887 ;; either ``/...' or ``...//...'
889 (setf last-slash dst-len)
892 ;; either ``./...'' or ``..././...''
897 ((and last-slash (not (zerop last-slash)))
898 ;; There is something before this ..
899 (let ((prev-prev-slash
900 (position #\/ dst :end last-slash :from-end t)))
901 (cond ((and (= (+ (or prev-prev-slash 0) 2)
903 (char= (schar dst (- last-slash 2)) #\.)
904 (char= (schar dst (1- last-slash)) #\.))
905 ;; The something before this .. is another ..
907 (setf last-slash dst-len))
909 ;; The something is some directory or other.
914 (setf last-slash prev-prev-slash)))))
916 ;; There is nothing before this .., so we need to keep it
917 (setf last-slash dst-len)
920 ;; something other than a dot between slashes
921 (setf last-slash dst-len)
926 (setf (schar dst dst-len) char)
928 (when (and last-slash (not (zerop last-slash)))
931 ;; We've got ``foobar/.''
934 ;; We've got ``foobar/..''
935 (unless (and (>= last-slash 2)
936 (char= (schar dst (1- last-slash)) #\.)
937 (char= (schar dst (- last-slash 2)) #\.)
939 (char= (schar dst (- last-slash 3)) #\/)))
940 (let ((prev-prev-slash
941 (position #\/ dst :end last-slash :from-end t)))
943 (setf dst-len (1+ prev-prev-slash))
944 (return-from unix-simplify-pathname "./")))))))
945 (cond ((zerop dst-len)
950 (subseq dst 0 dst-len)))))
952 ;;;; A magic constant for wait3().
954 ;;;; FIXME: This used to be defined in run-program.lisp as
955 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
956 ;;;; According to some of the man pages, the #o177 is part of the API
957 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
958 ;;;; the headers that may or may not be the same thing. To be
959 ;;;; investigated. -- CSR, 2002-03-25
960 (defconstant wstopped #o177)
963 ;;;; stuff not yet found in the header files
965 ;;;; Abandon all hope who enters here...
967 ;;; not checked for linux...
968 (defmacro fd-set (offset fd-set)
969 (let ((word (gensym))
971 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
972 (setf (deref (slot ,fd-set 'fds-bits) ,word)
973 (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
974 (deref (slot ,fd-set 'fds-bits) ,word))))))
976 ;;; not checked for linux...
977 (defmacro fd-clr (offset fd-set)
978 (let ((word (gensym))
980 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
981 (setf (deref (slot ,fd-set 'fds-bits) ,word)
982 (logand (deref (slot ,fd-set 'fds-bits) ,word)
983 (sb!kernel:32bit-logical-not
984 (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
986 ;;; not checked for linux...
987 (defmacro fd-isset (offset fd-set)
988 (let ((word (gensym))
990 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
991 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
993 ;;; not checked for linux...
994 (defmacro fd-zero (fd-set)
996 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
997 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))