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 (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
225 (values nil (get-errno))
228 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
229 ;;; It attempts to read len bytes from the device associated with fd
230 ;;; and store them into the buffer. It returns the actual number of
232 (defun unix-read (fd buf len)
233 (declare (type unix-fd fd)
234 (type (unsigned-byte 32) len))
236 (int-syscall ("read" int (* char) int) fd buf len))
238 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
239 ;;; length to write. It attempts to write len bytes to the device
240 ;;; associated with fd from the the buffer starting at offset. It returns
241 ;;; the actual number of bytes written.
242 (defun unix-write (fd buf offset len)
243 (declare (type unix-fd fd)
244 (type (unsigned-byte 32) offset len))
245 (int-syscall ("write" int (* char) int)
247 (with-alien ((ptr (* char) (etypecase buf
248 ((simple-array * (*))
252 (addr (deref ptr offset)))
255 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
256 ;;; output pipe. Return two values: if no error occurred the first
257 ;;; value is the pipe to be read from and the second is can be written
258 ;;; to. If an error occurred the first value is NIL and the second the
261 (with-alien ((fds (array int 2)))
262 (syscall ("pipe" (* int))
263 (values (deref fds 0) (deref fds 1))
264 (cast fds (* int)))))
266 (defun unix-mkdir (name mode)
267 (declare (type unix-pathname name)
268 (type unix-file-mode mode))
269 (void-syscall ("mkdir" c-string int) name mode))
271 ;;; Given a C char* pointer allocated by malloc(), free it and return a
272 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
273 (defun newcharstar-string (newcharstar)
274 (declare (type (alien (* char)) newcharstar))
275 (if (null-alien newcharstar)
278 (cast newcharstar c-string)
279 (free-alien newcharstar))))
281 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
282 ;;; style returned by getcwd() (no trailing slash character).
283 (defun posix-getcwd ()
284 ;; This implementation relies on a BSD/Linux extension to getcwd()
285 ;; behavior, automatically allocating memory when a null buffer
286 ;; pointer is used. On a system which doesn't support that
287 ;; extension, it'll have to be rewritten somehow.
289 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
290 ;; buffer pointer, it will automatically allocate size space. The
291 ;; KLUDGE in this solution arises because we have just read off
292 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
293 ;; a constant. Going the grovel_headers route doesn't seem to be
294 ;; helpful, either, as Solaris doesn't export PATH_MAX from
296 #!-(or linux openbsd freebsd sunos osf1 darwin) (,stub,)
297 #!+(or linux openbsd freebsd sunos osf1 darwin)
298 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
303 #!+(or linux openbsd freebsd darwin) 0
304 #!+(or sunos osf1) 1025))
305 (simple-perror "getcwd")))
307 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
308 ;;; by a slash character.
309 (defun posix-getcwd/ ()
310 (concatenate 'string (posix-getcwd) "/"))
312 ;;; Convert at the UNIX level from a possibly relative filename to
313 ;;; an absolute filename.
315 ;;; FIXME: Do we still need this even as we switch to
316 ;;; *DEFAULT-PATHNAME-DEFAULTS*? I think maybe we do, since it seems
317 ;;; to be valid for the user to set *DEFAULT-PATHNAME-DEFAULTS* to
318 ;;; have a NIL directory component, and then this'd be the only way to
319 ;;; interpret a relative directory specification. But I don't find the
320 ;;; ANSI pathname documentation to be a model of clarity. Maybe
321 ;;; someone who understands it better can take a look at this.. -- WHN
322 (defun unix-maybe-prepend-current-directory (name)
323 (declare (simple-string name))
324 (if (and (> (length name) 0) (char= (schar name 0) #\/))
326 (concatenate 'simple-string (posix-getcwd/) name)))
328 ;;; Duplicate an existing file descriptor (given as the argument) and
329 ;;; return it. If FD is not a valid file descriptor, NIL and an error
330 ;;; number are returned.
332 (declare (type unix-fd fd))
333 (int-syscall ("dup" int) fd))
335 ;;; Terminate the current process with an optional error code. If
336 ;;; successful, the call doesn't return. If unsuccessful, the call
337 ;;; returns NIL and an error number.
338 (defun unix-exit (&optional (code 0))
339 (declare (type (signed-byte 32) code))
340 (void-syscall ("exit" int) code))
342 ;;; Return the process id of the current process.
343 (define-alien-routine ("getpid" unix-getpid) int)
345 ;;; Return the real user id associated with the current process.
346 (define-alien-routine ("getuid" unix-getuid) int)
348 ;;; Translate a user id into a login name.
349 (defun uid-username (uid)
350 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
351 (function (* char) int))
353 (error "found no match for Unix uid=~S" uid)))
355 ;;; Return the namestring of the home directory, being careful to
356 ;;; include a trailing #\/
357 (defun uid-homedir (uid)
358 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
359 (function (* char) int))
361 (error "failed to resolve home directory for Unix uid=~S" uid)))
363 ;;; Invoke readlink(2) on the file name specified by PATH. Return
364 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
366 (defun unix-readlink (path)
367 (declare (type unix-pathname path))
368 (with-alien ((ptr (* char)
369 (alien-funcall (extern-alien
371 (function (* char) c-string))
374 (values nil (get-errno))
375 (multiple-value-prog1
376 (values (with-alien ((c-string c-string ptr)) c-string)
380 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
381 ;;; name and the file if this is the last link.
382 (defun unix-unlink (name)
383 (declare (type unix-pathname name))
384 (void-syscall ("unlink" c-string) name))
386 ;;; Return the name of the host machine as a string.
387 (defun unix-gethostname ()
388 (with-alien ((buf (array char 256)))
389 (syscall ("gethostname" (* char) int)
391 (cast buf (* char)) 256)))
393 ;;; Write the core image of the file described by FD to disk.
394 (defun unix-fsync (fd)
395 (declare (type unix-fd fd))
396 (void-syscall ("fsync" int) fd))
399 (defun unix-setsid ()
400 (int-syscall ("setsid")))
404 ;;; UNIX-IOCTL performs a variety of operations on open i/o
405 ;;; descriptors. See the UNIX Programmer's Manual for more
407 (defun unix-ioctl (fd cmd arg)
408 (declare (type unix-fd fd)
409 (type (signed-byte 32) cmd))
410 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
414 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
416 ;;; This is like getrusage(2), except it returns only the system and
417 ;;; user time, and returns the seconds and microseconds as separate
419 #!-sb-fluid (declaim (inline unix-fast-getrusage))
420 (defun unix-fast-getrusage (who)
421 (declare (values (member t)
422 (unsigned-byte 31) (integer 0 1000000)
423 (unsigned-byte 31) (integer 0 1000000)))
424 (with-alien ((usage (struct rusage)))
425 (syscall* ("getrusage" int (* (struct rusage)))
427 (slot (slot usage 'ru-utime) 'tv-sec)
428 (slot (slot usage 'ru-utime) 'tv-usec)
429 (slot (slot usage 'ru-stime) 'tv-sec)
430 (slot (slot usage 'ru-stime) 'tv-usec))
433 ;;; Return information about the resource usage of the process
434 ;;; specified by WHO. WHO can be either the current process
435 ;;; (rusage_self) or all of the terminated child processes
436 ;;; (rusage_children). NIL and an error number is returned if the call
438 (defun unix-getrusage (who)
439 (with-alien ((usage (struct rusage)))
440 (syscall ("getrusage" int (* (struct rusage)))
442 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
443 (slot (slot usage 'ru-utime) 'tv-usec))
444 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
445 (slot (slot usage 'ru-stime) 'tv-usec))
446 (slot usage 'ru-maxrss)
447 (slot usage 'ru-ixrss)
448 (slot usage 'ru-idrss)
449 (slot usage 'ru-isrss)
450 (slot usage 'ru-minflt)
451 (slot usage 'ru-majflt)
452 (slot usage 'ru-nswap)
453 (slot usage 'ru-inblock)
454 (slot usage 'ru-oublock)
455 (slot usage 'ru-msgsnd)
456 (slot usage 'ru-msgrcv)
457 (slot usage 'ru-nsignals)
458 (slot usage 'ru-nvcsw)
459 (slot usage 'ru-nivcsw))
464 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
466 ;;; Perform the UNIX select(2) system call.
467 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
468 (defun unix-fast-select (num-descriptors
469 read-fds write-fds exception-fds
470 timeout-secs &optional (timeout-usecs 0))
471 (declare (type (integer 0 #.fd-setsize) num-descriptors)
472 (type (or (alien (* (struct fd-set))) null)
473 read-fds write-fds exception-fds)
474 (type (or null (unsigned-byte 31)) timeout-secs)
475 (type (unsigned-byte 31) timeout-usecs))
477 ;; (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
478 ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
479 (with-alien ((tv (struct timeval)))
481 (setf (slot tv 'tv-sec) timeout-secs)
482 (setf (slot tv 'tv-usec) timeout-usecs))
483 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
484 (* (struct fd-set)) (* (struct timeval)))
485 num-descriptors read-fds write-fds exception-fds
486 (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
488 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
489 ;;; to happen on one of them or to time out.
490 (defmacro num-to-fd-set (fdset num)
493 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
494 ,@(loop for index upfrom 1 below (/ fd-setsize 32)
495 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
497 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
498 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
499 (ldb (byte 32 ,(* index 32)) ,num))))))
501 (defmacro fd-set-to-num (nfds fdset)
503 (deref (slot ,fdset 'fds-bits) 0)
504 (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
505 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
508 ;;; Examine the sets of descriptors passed as arguments to see whether
509 ;;; they are ready for reading and writing. See the UNIX Programmer's
510 ;;; Manual for more information.
511 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
512 (declare (type (integer 0 #.FD-SETSIZE) nfds)
513 (type unsigned-byte rdfds wrfds xpfds)
514 (type (or (unsigned-byte 31) null) to-secs)
515 (type (unsigned-byte 31) to-usecs)
516 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
517 (with-alien ((tv (struct timeval))
518 (rdf (struct fd-set))
519 (wrf (struct fd-set))
520 (xpf (struct fd-set)))
522 (setf (slot tv 'tv-sec) to-secs)
523 (setf (slot tv 'tv-usec) to-usecs))
524 (num-to-fd-set rdf rdfds)
525 (num-to-fd-set wrf wrfds)
526 (num-to-fd-set xpf xpfds)
527 (macrolet ((frob (lispvar alienvar)
528 `(if (zerop ,lispvar)
530 (alien-sap (addr ,alienvar)))))
531 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
532 (* (struct fd-set)) (* (struct timeval)))
534 (fd-set-to-num nfds rdf)
535 (fd-set-to-num nfds wrf)
536 (fd-set-to-num nfds xpf))
537 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
538 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
542 ;;; This is a structure defined in src/runtime/wrap.c, to look
543 ;;; basically like "struct stat" according to stat(2). It may not
544 ;;; actually correspond to the real in-memory stat structure that the
545 ;;; syscall uses, and that's OK. Linux in particular is packed full of
546 ;;; stat macros, and trying to keep Lisp code in correspondence with
547 ;;; it is more pain than it's worth, so we just let our C runtime
548 ;;; synthesize a nice consistent structure for us.
550 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
551 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
552 ;;; those. We don't actually access that field anywhere, though, so
553 ;;; until we can get 64 bit alien support it'll do. Also note that
554 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
555 ;;; quantity on Alpha. And FIXME: "No one would want a file length
556 ;;; longer than 32 bits anyway, right?":-|
557 (define-alien-type nil
559 (st-dev unsigned-long) ; would be dev-t in a real stat
565 (st-rdev unsigned-long) ; would be dev-t in a real stat
566 (st-size unsigned-long) ; would be off-t in a real stat
567 (st-blksize unsigned-long)
568 (st-blocks unsigned-long)
573 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
574 ;;; family of Unix system calls
576 ;;; FIXME: I think this should probably not be INLINE. However, when
577 ;;; this was not inline, it seemed to cause memory corruption
578 ;;; problems. My first guess is that it's a bug in the FFI code, where
579 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
580 ;;; around a call to a function returning >10 values. But I didn't try
581 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
582 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
583 ;;; output in the not-inlined case and see whether there's a problem,
584 ;;; and maybe even find a fix..
585 (declaim (inline %extract-stat-results))
586 (defun %extract-stat-results (wrapped-stat)
587 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
589 (slot wrapped-stat 'st-dev)
590 (slot wrapped-stat 'st-ino)
591 (slot wrapped-stat 'st-mode)
592 (slot wrapped-stat 'st-nlink)
593 (slot wrapped-stat 'st-uid)
594 (slot wrapped-stat 'st-gid)
595 (slot wrapped-stat 'st-rdev)
596 (slot wrapped-stat 'st-size)
597 (slot wrapped-stat 'st-atime)
598 (slot wrapped-stat 'st-mtime)
599 (slot wrapped-stat 'st-ctime)
600 (slot wrapped-stat 'st-blksize)
601 (slot wrapped-stat 'st-blocks)))
603 ;;; Unix system calls in the stat(2) family are handled by calls to
604 ;;; C-level wrapper functions which copy all the raw "struct stat"
605 ;;; slots into the system-independent wrapped_stat format.
606 ;;; stat(2) <-> stat_wrapper()
607 ;;; fstat(2) <-> fstat_wrapper()
608 ;;; lstat(2) <-> lstat_wrapper()
609 (defun unix-stat (name)
610 (declare (type unix-pathname name))
611 (with-alien ((buf (struct wrapped_stat)))
612 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
613 (%extract-stat-results (addr buf))
615 (defun unix-lstat (name)
616 (declare (type unix-pathname name))
617 (with-alien ((buf (struct wrapped_stat)))
618 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
619 (%extract-stat-results (addr buf))
621 (defun unix-fstat (fd)
622 (declare (type unix-fd fd))
623 (with-alien ((buf (struct wrapped_stat)))
624 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
625 (%extract-stat-results (addr buf))
630 ;; the POSIX.4 structure for a time value. This is like a "struct
631 ;; timeval" but has nanoseconds instead of microseconds.
632 (define-alien-type nil
634 (tv-sec long) ; seconds
635 (tv-nsec long))) ; nanoseconds
637 ;; used by other time functions
638 (define-alien-type nil
640 (tm-sec int) ; Seconds. [0-60] (1 leap second)
641 (tm-min int) ; Minutes. [0-59]
642 (tm-hour int) ; Hours. [0-23]
643 (tm-mday int) ; Day. [1-31]
644 (tm-mon int) ; Month. [0-11]
645 (tm-year int) ; Year - 1900.
646 (tm-wday int) ; Day of week. [0-6]
647 (tm-yday int) ; Days in year. [0-365]
648 (tm-isdst int) ; DST. [-1/0/1]
649 (tm-gmtoff long) ; Seconds east of UTC.
650 (tm-zone c-string))) ; Timezone abbreviation.
652 (define-alien-routine get-timezone sb!alien:void
653 (when sb!alien:long :in)
654 (minutes-west sb!alien:int :out)
655 (daylight-savings-p sb!alien:boolean :out))
657 (defun unix-get-minutes-west (secs)
658 (multiple-value-bind (ignore minutes dst) (get-timezone secs)
659 (declare (ignore ignore) (ignore dst))
662 (defun unix-get-timezone (secs)
663 (multiple-value-bind (ignore minutes dst) (get-timezone secs)
664 (declare (ignore ignore) (ignore minutes))
665 (values (deref unix-tzname (if dst 1 0)))))
670 ;;; Structure crudely representing a timezone. KLUDGE: This is
671 ;;; obsolete and should never be used.
672 (define-alien-type nil
674 (tz-minuteswest int) ; minutes west of Greenwich
675 (tz-dsttime int))) ; type of dst correction
677 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
678 ;;; and microseconds of the current time of day, the timezone (in
679 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
680 ;;; doesn't work, it returns NIL and the errno.
681 #!-sb-fluid (declaim (inline unix-gettimeofday))
682 (defun unix-gettimeofday ()
683 (with-alien ((tv (struct timeval))
684 (tz (struct timezone)))
685 (syscall* ("gettimeofday" (* (struct timeval))
686 (* (struct timezone)))
690 (slot tz 'tz-minuteswest)
691 (slot tz 'tz-dsttime))
696 ;; Type of the second argument to `getitimer' and
697 ;; the second and third arguments `setitimer'.
698 (define-alien-type nil
700 (it-interval (struct timeval)) ; timer interval
701 (it-value (struct timeval)))) ; current value
703 (defconstant ITIMER-REAL 0)
704 (defconstant ITIMER-VIRTUAL 1)
705 (defconstant ITIMER-PROF 2)
707 (defun unix-getitimer(which)
708 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
709 three system timers (:real :virtual or :profile). On success,
710 unix-getitimer returns 5 values,
711 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
712 (declare (type (member :real :virtual :profile) which)
714 (unsigned-byte 29) (mod 1000000)
715 (unsigned-byte 29) (mod 1000000)))
716 (let ((which (ecase which
718 (:virtual ITIMER-VIRTUAL)
719 (:profile ITIMER-PROF))))
720 (with-alien ((itv (struct itimerval)))
721 (syscall* ("getitimer" int (* (struct itimerval)))
723 (slot (slot itv 'it-interval) 'tv-sec)
724 (slot (slot itv 'it-interval) 'tv-usec)
725 (slot (slot itv 'it-value) 'tv-sec)
726 (slot (slot itv 'it-value) 'tv-usec))
727 which (alien-sap (addr itv))))))
729 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
730 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
731 three system timers (:real :virtual or :profile). A SIGALRM signal
732 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
733 when non-zero, is <seconds+microseconds> to be loaded each time
734 the timer expires. Setting INTERVAL and VALUE to zero disables
735 the timer. See the Unix man page for more details. On success,
736 unix-setitimer returns the old contents of the INTERVAL and VALUE
737 slots as in unix-getitimer."
738 (declare (type (member :real :virtual :profile) which)
739 (type (unsigned-byte 29) int-secs val-secs)
740 (type (integer 0 (1000000)) int-usec val-usec)
742 (unsigned-byte 29) (mod 1000000)
743 (unsigned-byte 29) (mod 1000000)))
744 (let ((which (ecase which
746 (:virtual ITIMER-VIRTUAL)
747 (:profile ITIMER-PROF))))
748 (with-alien ((itvn (struct itimerval))
749 (itvo (struct itimerval)))
750 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
751 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
752 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
753 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
754 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
756 (slot (slot itvo 'it-interval) 'tv-sec)
757 (slot (slot itvo 'it-interval) 'tv-usec)
758 (slot (slot itvo 'it-value) 'tv-sec)
759 (slot (slot itvo 'it-value) 'tv-usec))
760 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
762 (defmacro sb!ext:with-timeout (expires &body body)
763 "Execute the body, interrupting it with a SIGALRM after at least
764 EXPIRES seconds have passed. Uses Unix setitimer(), restoring any
765 previous timer after the body has finished executing"
766 (with-unique-names (saved-seconds saved-useconds s u)
767 `(let (- ,saved-seconds ,saved-useconds)
768 (multiple-value-setq (- - - ,saved-seconds ,saved-useconds)
769 (unix-getitimer :real))
770 (multiple-value-bind (,s ,u) (floor ,expires)
771 (setf ,u (floor (* ,u 1000000)))
772 (if (and (> ,expires 0)
773 (or (and (zerop ,saved-seconds) (zerop ,saved-useconds))
774 (> ,saved-seconds ,s)
775 (and (= ,saved-seconds ,s)
776 (> ,saved-useconds ,u))))
779 (unix-setitimer :real 0 0 ,s ,u)
781 (unix-setitimer :real 0 0 ,saved-seconds ,saved-useconds))
786 (defconstant ENOENT 2) ; Unix error code, "No such file or directory"
787 (defconstant EINTR 4) ; Unix error code, "Interrupted system call"
788 (defconstant EIO 5) ; Unix error code, "I/O error"
789 (defconstant EEXIST 17) ; Unix error code, "File exists"
790 (defconstant ESPIPE 29) ; Unix error code, "Illegal seek"
791 (defconstant EWOULDBLOCK 11) ; Unix error code, "Operation would block"
792 ;;; FIXME: Many Unix error code definitions were deleted from the old
793 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
794 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
795 ;;; unused symbols in package exports, but if I don't, there are
796 ;;; enough of them all in one place here that they should probably be
800 ;;;; support routines for dealing with Unix pathnames
802 (defun unix-file-kind (name &optional check-for-links)
804 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
805 (declare (simple-base-string name))
806 (multiple-value-bind (res dev ino mode)
807 (if check-for-links (unix-lstat name) (unix-stat name))
808 (declare (type (or fixnum null) mode)
811 (let ((kind (logand mode s-ifmt)))
812 (cond ((eql kind s-ifdir) :directory)
813 ((eql kind s-ifreg) :file)
814 ((eql kind s-iflnk) :link)
817 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
818 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
819 (defun relative-unix-pathname? (pathname)
820 (declare (type simple-string pathname))
821 (or (zerop (length pathname))
822 (char/= (schar pathname 0) #\/)))
824 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
825 ;;; already be a complete absolute Unix pathname, since at least in
826 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
827 ;;; paths have been converted to absolute paths, so we don't need to
828 ;;; try to handle any more generality than that.
829 (defun unix-resolve-links (pathname)
830 (declare (type simple-string pathname))
831 (aver (not (relative-unix-pathname? pathname)))
832 (/noshow "entering UNIX-RESOLVE-LINKS")
833 (loop with previous-pathnames = nil do
834 (/noshow pathname previous-pathnames)
835 (let ((link (unix-readlink pathname)))
837 ;; Unlike the old CMU CL code, we handle a broken symlink by
838 ;; returning the link itself. That way, CL:TRUENAME on a
839 ;; broken link returns the link itself, so that CL:DIRECTORY
840 ;; can return broken links, so that even without
841 ;; Unix-specific extensions to do interesting things with
842 ;; them, at least Lisp programs can see them and, if
843 ;; necessary, delete them. (This is handy e.g. when your
844 ;; managed-by-Lisp directories are visited by Emacs, which
845 ;; creates broken links as notes to itself.)
849 (unix-simplify-pathname
850 (if (relative-unix-pathname? link)
851 (let* ((dir-len (1+ (position #\/
854 (dir (subseq pathname 0 dir-len)))
856 (concatenate 'string dir link))
858 (if (unix-file-kind new-pathname)
859 (setf pathname new-pathname)
860 (return pathname)))))
861 ;; To generalize the principle that even if portable Lisp code
862 ;; can't do anything interesting with a broken symlink, at
863 ;; least it should be able to see and delete it, when we
864 ;; detect a cyclic link, we return the link itself. (So even
865 ;; though portable Lisp code can't do anything interesting
866 ;; with a cyclic link, at least it can see it and delete it.)
867 (if (member pathname previous-pathnames :test #'string=)
869 (push pathname previous-pathnames))))
871 (defun unix-simplify-pathname (src)
872 (declare (type simple-string src))
873 (let* ((src-len (length src))
874 (dst (make-string src-len))
878 (macrolet ((deposit (char)
880 (setf (schar dst dst-len) ,char)
882 (dotimes (src-index src-len)
883 (let ((char (schar src src-index)))
884 (cond ((char= char #\.)
891 ;; either ``/...' or ``...//...'
893 (setf last-slash dst-len)
896 ;; either ``./...'' or ``..././...''
901 ((and last-slash (not (zerop last-slash)))
902 ;; There is something before this ..
903 (let ((prev-prev-slash
904 (position #\/ dst :end last-slash :from-end t)))
905 (cond ((and (= (+ (or prev-prev-slash 0) 2)
907 (char= (schar dst (- last-slash 2)) #\.)
908 (char= (schar dst (1- last-slash)) #\.))
909 ;; The something before this .. is another ..
911 (setf last-slash dst-len))
913 ;; The something is some directory or other.
918 (setf last-slash prev-prev-slash)))))
920 ;; There is nothing before this .., so we need to keep it
921 (setf last-slash dst-len)
924 ;; something other than a dot between slashes
925 (setf last-slash dst-len)
930 (setf (schar dst dst-len) char)
932 (when (and last-slash (not (zerop last-slash)))
935 ;; We've got ``foobar/.''
938 ;; We've got ``foobar/..''
939 (unless (and (>= last-slash 2)
940 (char= (schar dst (1- last-slash)) #\.)
941 (char= (schar dst (- last-slash 2)) #\.)
943 (char= (schar dst (- last-slash 3)) #\/)))
944 (let ((prev-prev-slash
945 (position #\/ dst :end last-slash :from-end t)))
947 (setf dst-len (1+ prev-prev-slash))
948 (return-from unix-simplify-pathname "./")))))))
949 (cond ((zerop dst-len)
954 (subseq dst 0 dst-len)))))
956 ;;;; A magic constant for wait3().
958 ;;;; FIXME: This used to be defined in run-program.lisp as
959 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
960 ;;;; According to some of the man pages, the #o177 is part of the API
961 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
962 ;;;; the headers that may or may not be the same thing. To be
963 ;;;; investigated. -- CSR, 2002-03-25
964 (defconstant wstopped #o177)
967 ;;;; stuff not yet found in the header files
969 ;;;; Abandon all hope who enters here...
971 ;;; not checked for linux...
972 (defmacro fd-set (offset fd-set)
973 (let ((word (gensym))
975 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
976 (setf (deref (slot ,fd-set 'fds-bits) ,word)
977 (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
978 (deref (slot ,fd-set 'fds-bits) ,word))))))
980 ;;; not checked for linux...
981 (defmacro fd-clr (offset fd-set)
982 (let ((word (gensym))
984 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
985 (setf (deref (slot ,fd-set 'fds-bits) ,word)
986 (logand (deref (slot ,fd-set 'fds-bits) ,word)
987 (sb!kernel:32bit-logical-not
988 (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
990 ;;; not checked for linux...
991 (defmacro fd-isset (offset fd-set)
992 (let ((word (gensym))
994 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
995 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
997 ;;; not checked for linux...
998 (defmacro fd-zero (fd-set)
1000 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
1001 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))