1 ;;;; This file contains Unix support that SBCL needs to implement itself. It's
2 ;;;; derived from Peter Van Eynde's unix-glibc2.lisp for CMU CL, which was
3 ;;;; derived from CMU CL unix.lisp 1.56. But those files aspired to be complete
4 ;;;; Unix interfaces exported to the end user, while this file aims to be as
5 ;;;; simple as possible and is not intended for the end user.
7 ;;;; FIXME: The old CMU CL unix.lisp code was implemented as hand
8 ;;;; transcriptions from Unix headers into Lisp. It appears that this was as
9 ;;;; unmaintainable in practice as you'd expect in theory, so I really really
10 ;;;; don't want to do that. It'd be good to implement the various system calls
11 ;;;; as C code implemented using the Unix header files, and have their
12 ;;;; interface back to SBCL code be characterized by things like "32-bit-wide
13 ;;;; int" which are already in the interface between the runtime
14 ;;;; executable and the SBCL lisp code.
16 ;;;; This software is part of the SBCL system. See the README file for
17 ;;;; more information.
19 ;;;; This software is derived from the CMU CL system, which was
20 ;;;; written at Carnegie Mellon University and released into the
21 ;;;; public domain. The software is in the public domain and is
22 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
23 ;;;; files for more information.
25 (in-package "SB!UNIX")
30 (/show0 "unix.lisp 21")
32 ;;;; common machine-independent structures
34 (eval-when (:compile-toplevel :execute)
36 (defparameter *compiler-unix-errors* nil)
38 (/show0 "unix.lisp 29")
40 (sb!xc:defmacro def-unix-error (name number description)
42 (eval-when (:compile-toplevel :execute)
43 (push (cons ,number ,description) *compiler-unix-errors*))
44 (eval-when (:compile-toplevel :load-toplevel :execute)
45 (defconstant ,name ,number ,description))))
47 (sb!xc:defmacro emit-unix-errors ()
48 (let* ((max (apply #'max (mapcar #'car *compiler-unix-errors*)))
49 (array (make-array (1+ max) :initial-element nil)))
50 (dolist (error *compiler-unix-errors*)
51 (setf (svref array (car error)) (cdr error)))
53 (defvar *unix-errors* ',array)
54 (proclaim '(simple-vector *unix-errors*)))))
58 (defvar *unix-errors*)
60 (/show0 "unix.lisp 52")
62 (defmacro def-enum (inc cur &rest names)
63 (flet ((defform (name)
64 (prog1 (when name `(defconstant ,name ,cur))
65 (setf cur (funcall inc cur 1)))))
66 `(progn ,@(mapcar #'defform names))))
68 ;;;; Lisp types used by syscalls
70 (deftype unix-pathname () 'simple-string)
71 (deftype unix-fd () `(integer 0 ,most-positive-fixnum))
73 (deftype unix-file-mode () '(unsigned-byte 32))
74 (deftype unix-pid () '(unsigned-byte 32))
75 (deftype unix-uid () '(unsigned-byte 32))
76 (deftype unix-gid () '(unsigned-byte 32))
80 (def-alien-routine ("os_get_errno" get-errno) integer
81 "Return the value of the C library pseudo-variable named \"errno\".")
83 (/show0 "unix.lisp 74")
85 (defun get-unix-error-msg (&optional (error-number (get-errno)))
87 "Returns a string describing the error number which was returned by a
89 (declare (type integer error-number))
90 (if (array-in-bounds-p *unix-errors* error-number)
91 (svref *unix-errors* error-number)
92 (format nil "unknown error [~D]" error-number)))
94 ;;; FIXME: The various FOO-SYSCALL-BAR macros, and perhaps some other
95 ;;; macros in this file, are only used in this file, and could be
96 ;;; implemented using SB!XC:DEFMACRO wrapped in EVAL-WHEN.
98 (defmacro syscall ((name &rest arg-types) success-form &rest args)
99 `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
102 (values nil (get-errno))
105 ;;; Like SYSCALL, but if it fails, signal an error instead of returning error
106 ;;; codes. Should only be used for syscalls that will never really get an
108 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
109 `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
112 (error "Syscall ~A failed: ~A" ,name (get-unix-error-msg))
115 (/show0 "unix.lisp 109")
117 (defmacro void-syscall ((name &rest arg-types) &rest args)
118 `(syscall (,name ,@arg-types) (values t 0) ,@args))
120 (defmacro int-syscall ((name &rest arg-types) &rest args)
121 `(syscall (,name ,@arg-types) (values result 0) ,@args))
125 (/show0 "unix.lisp 124")
127 (defun unix-rename (name1 name2)
129 "Unix-rename renames the file with string name1 to the string
130 name2. NIL and an error code is returned if an error occurs."
131 (declare (type unix-pathname name1 name2))
132 (void-syscall ("rename" c-string c-string) name1 name2))
136 (def-alien-routine ("getenv" posix-getenv) c-string
137 "Return the environment string \"name=value\" which corresponds to NAME, or
138 NIL if there is none."
141 ;;; from sys/types.h and gnu/types.h
143 (/show0 "unix.lisp 144")
145 (defconstant +max-s-long+ 2147483647)
146 (defconstant +max-u-long+ 4294967295)
148 ;;; FIXME: Isn't there some way to use a C wrapper to avoid this hand-copying?
149 (def-alien-type quad-t #+nil long-long #-nil (array long 2))
150 (def-alien-type uquad-t #+nil unsigned-long-long
151 #-nil (array unsigned-long 2))
152 (def-alien-type qaddr-t (* quad-t))
153 (def-alien-type daddr-t int)
154 (def-alien-type caddr-t (* char))
155 (def-alien-type swblk-t long)
156 (def-alien-type size-t unsigned-int)
157 (def-alien-type time-t long)
158 (def-alien-type clock-t
160 #!+bsd unsigned-long)
161 (def-alien-type uid-t unsigned-int)
162 (def-alien-type ssize-t int)
164 (/show0 "unix.lisp 163")
166 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp like this
167 ;;; unless we have extreme provocation. Reading directories is not extreme
168 ;;; enough, since it doesn't need to be blindingly fast: we can just implement
169 ;;; those functions in C as a wrapper layer.
170 (def-alien-type fd-mask unsigned-long)
171 (/show0 "unix.lisp 171")
173 ;;; FIXME: Isn't there some way to use a C wrapper to avoid this hand-copying?
174 (def-alien-type dev-t
177 (def-alien-type uid-t unsigned-int)
178 (def-alien-type gid-t unsigned-int)
179 (def-alien-type ino-t
180 #!+linux unsigned-long
182 (def-alien-type mode-t
183 #!+linux unsigned-int
184 #!+bsd unsigned-short)
185 (def-alien-type nlink-t
186 #!+linux unsigned-int
187 #!+bsd unsigned-short)
188 (/show0 "unix.lisp 190")
190 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp like this
191 ;;; unless we have extreme provocation. Reading directories is not extreme
192 ;;; enough, since it doesn't need to be blindingly fast: we can just implement
193 ;;; those functions in C as a wrapper layer.
195 (def-alien-type off-t
199 (eval-when (:compile-toplevel :load-toplevel :execute)
200 (/show0 "unix.lisp 215")
201 (defconstant fd-setsize 1024))
202 (/show0 "unix.lisp 217")
206 (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
208 (/show0 "unix.lisp 223")
214 (d-ino long); inode number of entry
215 (d-off off-t) ; offset of next disk directory entry
216 (d-reclen unsigned-short) ; length of this record
217 (d_type unsigned-char)
218 (d-name (array char 256)))) ; name must be no longer than this
219 (/show0 "unix.lisp 241")
223 ;;; operations on Unix directories
225 ;;;; FIXME: It might be really nice to implement these in C, so that
226 ;;;; we don't need to do horrible things like hand-copying the
227 ;;;; direntry struct slot types into an alien struct.
229 ;;; FIXME: DIRECTORY is an external symbol of package CL, so we should use some
230 ;;; other name for this low-level implementation type.
233 (dir-struct (required-argument) :type system-area-pointer))
234 (/show0 "unix.lisp 258")
236 (def!method print-object ((dir directory) stream)
237 (print-unreadable-object (dir stream :type t)
238 (prin1 (directory-name dir) stream)))
240 (/show0 "unix.lisp 264")
241 (defun open-dir (pathname)
242 (declare (type unix-pathname pathname))
243 (when (string= pathname "")
245 (let ((kind (unix-file-kind pathname)))
249 (alien-funcall (extern-alien "opendir"
250 (function system-area-pointer
253 (if (zerop (sap-int dir-struct))
254 (values nil (get-errno))
255 (make-directory :name pathname :dir-struct dir-struct))))
259 (values nil enotdir)))))
260 (/show0 "unix.lisp 286")
262 (defun read-dir (dir)
263 (declare (type directory dir))
264 (let ((daddr (alien-funcall (extern-alien "readdir"
265 (function system-area-pointer
266 system-area-pointer))
267 (directory-dir-struct dir))))
268 (declare (type system-area-pointer daddr))
269 (if (zerop (sap-int daddr))
271 (with-alien ((direct (* (struct direct)) daddr))
272 (values (cast (slot direct 'd-name) c-string)
273 (slot direct 'd-ino))))))
275 (/show0 "unix.lisp 301")
276 (defun close-dir (dir)
277 (declare (type directory dir))
278 (alien-funcall (extern-alien "closedir"
279 (function void system-area-pointer))
280 (directory-dir-struct dir))
283 ;;; dlfcn.h -> in foreign.lisp
287 ;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
289 (/show0 "unix.lisp 318")
290 (defconstant r_ok 4 #!+sb-doc "Test for read permission")
291 (defconstant w_ok 2 #!+sb-doc "Test for write permission")
292 (defconstant x_ok 1 #!+sb-doc "Test for execute permission")
293 (defconstant f_ok 0 #!+sb-doc "Test for presence of file")
295 (/show0 "unix.lisp 352")
296 (defun unix-open (path flags mode)
298 "Unix-open opens the file whose pathname is specified by path
299 for reading and/or writing as specified by the flags argument.
300 The flags argument can be:
302 o_rdonly Read-only flag.
303 o_wronly Write-only flag.
304 o_rdwr Read-and-write flag.
305 o_append Append flag.
306 o_creat Create-if-nonexistent flag.
307 o_trunc Truncate-to-size-0 flag.
308 o_excl Error if the file allready exists
309 o_noctty Don't assign controlling tty
310 o_ndelay Non-blocking I/O
311 o_sync Synchronous I/O
312 o_async Asynchronous I/O
314 If the o_creat flag is specified, then the file is created with
315 a permission of argument mode if the file doesn't exist. An
316 integer file descriptor is returned by unix-open."
317 (declare (type unix-pathname path)
319 (type unix-file-mode mode))
320 (int-syscall ("open" c-string int int) path flags mode))
322 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
323 ;;; associated with it.
324 (/show0 "unix.lisp 391")
325 (defun unix-close (fd)
327 "Unix-close takes an integer file descriptor as an argument and
328 closes the file associated with it. T is returned upon successful
329 completion, otherwise NIL and an error number."
330 (declare (type unix-fd fd))
331 (void-syscall ("close" int) fd))
334 (eval-when (:compile-toplevel :load-toplevel :execute)
336 (/show0 "unix.lisp 337")
337 (defconstant o_rdonly 0) ; read-only flag
338 (defconstant o_wronly 1) ; write-only flag
339 (defconstant o_rdwr 2) ; read/write flag
340 (defconstant o_accmode 3) ; access mode mask
341 (defconstant o_creat ; create-if-nonexistent flag (not fcntl)
344 (/show0 "unix.lisp 345")
345 (defconstant o_excl ; error if already exists (not fcntl)
348 (defconstant o_noctty ; Don't assign controlling tty. (not fcntl)
351 (defconstant o_trunc ; truncation flag (not fcntl)
354 (defconstant o_append ; append flag
357 (/show0 "unix.lisp 361")
362 ;; A time value that is accurate to the nearest
363 ;; microsecond but also has a range of years.
366 (tv-sec time-t) ; seconds
367 (tv-usec time-t))) ; and microseconds
371 (defconstant rusage_self 0 #!+sb-doc "The calling process.")
372 (defconstant rusage_children -1 #!+sb-doc "Terminated child processes.")
373 (defconstant rusage_both -2)
377 (ru-utime (struct timeval)) ; user time used
378 (ru-stime (struct timeval)) ; system time used.
379 (ru-maxrss long) ; Maximum resident set size (in kilobytes)
380 (ru-ixrss long) ; integral shared memory size
381 (ru-idrss long) ; integral unshared data size
382 (ru-isrss long) ; integral unshared stack size
383 (ru-minflt long) ; page reclaims
384 (ru-majflt long) ; page faults
385 (ru-nswap long) ; swaps
386 (ru-inblock long) ; block input operations
387 (ru-oublock long) ; block output operations
388 (ru-msgsnd long) ; messages sent
389 (ru-msgrcv long) ; messages received
390 (ru-nsignals long) ; signals received
391 (ru-nvcsw long) ; voluntary context switches
392 (ru-nivcsw long))) ; involuntary context switches
396 ;;; FIXME: This should go into C code so that we don't need to hand-copy
397 ;;; it from header files.
402 (st-pad1 unsigned-short)
409 (st-pad2 unsigned-short)
411 (st-blksize unsigned-long)
412 (st-blocks unsigned-long)
414 (unused-1 unsigned-long)
416 (unused-2 unsigned-long)
418 (unused-3 unsigned-long)
419 (unused-4 unsigned-long)
420 (unused-5 unsigned-long)))
438 (st-atime (struct timespec-t))
439 (st-mtime (struct timespec-t))
440 (st-ctime (struct timespec-t))
441 (st-size unsigned-long) ; really quad
442 (st-sizeh unsigned-long) ;
443 (st-blocks unsigned-long) ; really quad
444 (st-blocksh unsigned-long)
445 (st-blksize unsigned-long)
446 (st-flags unsigned-long)
447 (st-gen unsigned-long)
449 (st-qspare (array long 4))
452 ;; encoding of the file mode
454 (defconstant s-ifmt #o0170000 #!+sb-doc "These bits determine file type.")
457 (defconstant s-ififo #o0010000 #!+sb-doc "FIFO")
458 (defconstant s-ifchr #o0020000 #!+sb-doc "Character device")
459 (defconstant s-ifdir #o0040000 #!+sb-doc "Directory")
460 (defconstant s-ifblk #o0060000 #!+sb-doc "Block device")
461 (defconstant s-ifreg #o0100000 #!+sb-doc "Regular file")
463 ;; These don't actually exist on System V, but having them doesn't hurt.
464 (defconstant s-iflnk #o0120000 #!+sb-doc "Symbolic link.")
465 (defconstant s-ifsock #o0140000 #!+sb-doc "Socket.")
469 ;;; values for the second argument to access
470 (defun unix-access (path mode)
472 "Given a file path (a string) and one of four constant modes,
473 UNIX-ACCESS returns T if the file is accessible with that
474 mode and NIL if not. It also returns an errno value with
475 NIL which determines why the file was not accessible.
477 The access modes are:
478 r_ok Read permission.
479 w_ok Write permission.
480 x_ok Execute permission.
481 f_ok Presence of file."
482 (declare (type unix-pathname path)
484 (void-syscall ("access" c-string int) path mode))
486 (defconstant l_set 0 #!+sb-doc "set the file pointer")
487 (defconstant l_incr 1 #!+sb-doc "increment the file pointer")
488 (defconstant l_xtnd 2 #!+sb-doc "extend the file size")
490 (defun unix-lseek (fd offset whence)
492 "Unix-lseek accepts a file descriptor and moves the file pointer ahead
493 a certain offset for that file. Whence can be any of the following:
495 l_set Set the file pointer.
496 l_incr Increment the file pointer.
497 l_xtnd Extend the file size.
499 (declare (type unix-fd fd)
500 (type (unsigned-byte 32) offset)
501 (type (integer 0 2) whence))
503 (int-syscall ("lseek" int off-t int) fd offset whence)
504 ;; Need a 64-bit return value type for this. TBD. For now,
505 ;; don't use this with any 2G+ partitions.
507 (int-syscall ("lseek" int unsigned-long unsigned-long int)
510 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
511 ;;; It attempts to read len bytes from the device associated with fd
512 ;;; and store them into the buffer. It returns the actual number of
514 (defun unix-read (fd buf len)
516 "Unix-read attempts to read from the file described by fd into
517 the buffer buf until it is full. Len is the length of the buffer.
518 The number of bytes actually read is returned or NIL and an error
519 number if an error occurred."
520 (declare (type unix-fd fd)
521 (type (unsigned-byte 32) len))
523 (int-syscall ("read" int (* char) int) fd buf len))
525 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
526 ;;; length to write. It attempts to write len bytes to the device
527 ;;; associated with fd from the the buffer starting at offset. It returns
528 ;;; the actual number of bytes written.
529 (defun unix-write (fd buf offset len)
531 "Unix-write attempts to write a character buffer (buf) of length
532 len to the file described by the file descriptor fd. NIL and an
533 error is returned if the call is unsuccessful."
534 (declare (type unix-fd fd)
535 (type (unsigned-byte 32) offset len))
536 (int-syscall ("write" int (* char) int)
538 (with-alien ((ptr (* char) (etypecase buf
539 ((simple-array * (*))
543 (addr (deref ptr offset)))
546 ;;; UNIX-CHDIR accepts a directory name and makes that the
547 ;;; current working directory.
548 (defun unix-chdir (path)
550 "Given a file path string, unix-chdir changes the current working
551 directory to the one specified."
552 (declare (type unix-pathname path))
553 (void-syscall ("chdir" c-string) path))
555 (defun unix-current-directory ()
557 "Return the current directory as a SIMPLE-STRING."
558 ;; FIXME: Gcc justifiably complains that getwd is dangerous and should
559 ;; not be used; especially with a hardwired 1024 buffer size, yecch.
560 ;; This should be rewritten to use getcwd(3), perhaps by writing
561 ;; a C service routine to do the actual call to getcwd(3) and check
563 (with-alien ((buf (array char 1024)))
564 (values (not (zerop (alien-funcall (extern-alien "getwd"
565 (function int (* char)))
566 (cast buf (* char)))))
567 (cast buf c-string))))
569 ;;; UNIX-EXIT terminates a program.
570 (defun unix-exit (&optional (code 0))
572 "Unix-exit terminates the current process with an optional
573 error code. If successful, the call doesn't return. If
574 unsuccessful, the call returns NIL and an error number."
575 (declare (type (signed-byte 32) code))
576 (void-syscall ("exit" int) code))
578 (def-alien-routine ("getpid" unix-getpid) int
580 "Unix-getpid returns the process-id of the current process.")
582 (def-alien-routine ("getuid" unix-getuid) int
584 "Unix-getuid returns the real user-id associated with the
587 (defun unix-readlink (path)
589 "Unix-readlink invokes the readlink system call on the file name
590 specified by the simple string path. It returns up to two values:
591 the contents of the symbolic link if the call is successful, or
592 NIL and the Unix error number."
593 (declare (type unix-pathname path))
594 (with-alien ((buf (array char 1024)))
595 (syscall ("readlink" c-string (* char) int)
596 (let ((string (make-string result)))
597 (sb!kernel:copy-from-system-area
599 string (* sb!vm:vector-data-offset sb!vm:word-bits)
600 (* result sb!vm:byte-bits))
602 path (cast buf (* char)) 1024)))
604 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
605 ;;; name and the file if this is the last link.
606 (defun unix-unlink (name)
608 "Unix-unlink removes the directory entry for the named file.
609 NIL and an error code is returned if the call fails."
610 (declare (type unix-pathname name))
611 (void-syscall ("unlink" c-string) name))
613 (defun %set-tty-process-group (pgrp &optional fd)
615 "Set the tty-process-group for the unix file-descriptor FD to PGRP. If not
616 supplied, FD defaults to /dev/tty."
617 (let ((old-sigs (unix-sigblock (sigmask :sigttou
621 (declare (type (unsigned-byte 32) old-sigs))
625 (multiple-value-bind (tty-fd errno) (unix-open "/dev/tty" o_rdwr 0)
627 (multiple-value-prog1
628 (tcsetpgrp tty-fd pgrp)
629 (unix-close tty-fd)))
631 (values nil errno)))))
632 (unix-sigsetmask old-sigs))))
634 (defun unix-gethostname ()
636 "Unix-gethostname returns the name of the host machine as a string."
637 (with-alien ((buf (array char 256)))
638 (syscall ("gethostname" (* char) int)
640 (cast buf (* char)) 256)))
642 ;;; Unix-fsync writes the core-image of the file described by "fd" to
643 ;;; permanent storage (i.e. disk).
645 (defun unix-fsync (fd)
647 "Unix-fsync writes the core image of the file described by
649 (declare (type unix-fd fd))
650 (void-syscall ("fsync" int) fd))
654 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
655 #!-sb-fluid (declaim (inline unix-fast-getrusage))
656 (defun unix-fast-getrusage (who)
658 "Like call getrusage, but return only the system and user time, and returns
659 the seconds and microseconds as separate values."
660 (declare (values (member t)
661 (unsigned-byte 31) (mod 1000000)
662 (unsigned-byte 31) (mod 1000000)))
663 (with-alien ((usage (struct rusage)))
664 (syscall* ("getrusage" int (* (struct rusage)))
666 (slot (slot usage 'ru-utime) 'tv-sec)
667 (slot (slot usage 'ru-utime) 'tv-usec)
668 (slot (slot usage 'ru-stime) 'tv-sec)
669 (slot (slot usage 'ru-stime) 'tv-usec))
672 (defun unix-getrusage (who)
674 "Unix-getrusage returns information about the resource usage
675 of the process specified by who. Who can be either the
676 current process (rusage_self) or all of the terminated
677 child processes (rusage_children). NIL and an error number
678 is returned if the call fails."
679 (with-alien ((usage (struct rusage)))
680 (syscall ("getrusage" int (* (struct rusage)))
682 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
683 (slot (slot usage 'ru-utime) 'tv-usec))
684 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
685 (slot (slot usage 'ru-stime) 'tv-usec))
686 (slot usage 'ru-maxrss)
687 (slot usage 'ru-ixrss)
688 (slot usage 'ru-idrss)
689 (slot usage 'ru-isrss)
690 (slot usage 'ru-minflt)
691 (slot usage 'ru-majflt)
692 (slot usage 'ru-nswap)
693 (slot usage 'ru-inblock)
694 (slot usage 'ru-oublock)
695 (slot usage 'ru-msgsnd)
696 (slot usage 'ru-msgrcv)
697 (slot usage 'ru-nsignals)
698 (slot usage 'ru-nvcsw)
699 (slot usage 'ru-nivcsw))
705 (defmacro unix-fast-select (num-descriptors
706 read-fds write-fds exception-fds
707 timeout-secs &optional (timeout-usecs 0))
709 "Perform the UNIX select(2) system call."
710 (declare (type (integer 0 #.FD-SETSIZE) num-descriptors)
711 (type (or (alien (* (struct fd-set))) null)
712 read-fds write-fds exception-fds)
713 (type (or null (unsigned-byte 31)) timeout-secs)
714 (type (unsigned-byte 31) timeout-usecs) )
716 ;; (optimize (speed 3) (safety 0) (inhibit-warnings 3))
717 ;; in the declarations above. If they're important, they should
718 ;; be in a declaration inside the LET expansion, not in the
719 ;; macro compile-time code.
720 `(let ((timeout-secs ,timeout-secs))
721 (with-alien ((tv (struct timeval)))
723 (setf (slot tv 'tv-sec) timeout-secs)
724 (setf (slot tv 'tv-usec) ,timeout-usecs))
725 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
726 (* (struct fd-set)) (* (struct timeval)))
727 ,num-descriptors ,read-fds ,write-fds ,exception-fds
728 (if timeout-secs (alien-sap (addr tv)) (int-sap 0))))))
730 ;;; Unix-select accepts sets of file descriptors and waits for an event
731 ;;; to happen on one of them or to time out.
733 (defmacro num-to-fd-set (fdset num)
736 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
737 ,@(loop for index upfrom 1 below (/ fd-setsize 32)
738 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
740 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
741 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
742 (ldb (byte 32 ,(* index 32)) ,num))))))
744 (defmacro fd-set-to-num (nfds fdset)
746 (deref (slot ,fdset 'fds-bits) 0)
747 (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
748 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
751 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
753 "Unix-select examines the sets of descriptors passed as arguments
754 to see whether they are ready for reading and writing. See the UNIX
755 Programmers Manual for more information."
756 (declare (type (integer 0 #.FD-SETSIZE) nfds)
757 (type unsigned-byte rdfds wrfds xpfds)
758 (type (or (unsigned-byte 31) null) to-secs)
759 (type (unsigned-byte 31) to-usecs)
760 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
761 (with-alien ((tv (struct timeval))
762 (rdf (struct fd-set))
763 (wrf (struct fd-set))
764 (xpf (struct fd-set)))
766 (setf (slot tv 'tv-sec) to-secs)
767 (setf (slot tv 'tv-usec) to-usecs))
768 (num-to-fd-set rdf rdfds)
769 (num-to-fd-set wrf wrfds)
770 (num-to-fd-set xpf xpfds)
771 (macrolet ((frob (lispvar alienvar)
772 `(if (zerop ,lispvar)
774 (alien-sap (addr ,alienvar)))))
775 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
776 (* (struct fd-set)) (* (struct timeval)))
778 (fd-set-to-num nfds rdf)
779 (fd-set-to-num nfds wrf)
780 (fd-set-to-num nfds xpf))
781 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
782 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
786 ;;; FIXME: This is only used in this file, and needn't be in target Lisp
787 ;;; runtime. It's also unclear why it needs to be a macro instead of a
788 ;;; function. Perhaps it should become a FLET.
789 (defmacro extract-stat-results (buf)
794 (+ (deref (slot ,buf 'st-dev) 0)
795 (* (+ +max-u-long+ 1)
796 (deref (slot ,buf 'st-dev) 1))) ;;; let's hope this works..
799 (slot ,buf 'st-nlink)
805 (+ (deref (slot ,buf 'st-rdev) 0)
806 (* (+ +max-u-long+ 1)
807 (deref (slot ,buf 'st-rdev) 1))) ;;; let's hope this works..
808 #!+linux (slot ,buf 'st-size)
810 (+ (slot ,buf 'st-size)
811 (* (+ +max-u-long+ 1)
812 (slot ,buf 'st-sizeh)))
813 #!+linux (slot ,buf 'st-atime)
814 #!+bsd (slot (slot ,buf 'st-atime) 'tv-sec)
815 #!+linux (slot ,buf 'st-mtime)
816 #!+bsd (slot (slot ,buf 'st-mtime) 'tv-sec)
817 #!+linux (slot ,buf 'st-ctime)
818 #!+bsd (slot (slot ,buf 'st-ctime) 'tv-sec)
819 (slot ,buf 'st-blksize)
820 #!+linux (slot ,buf 'st-blocks)
822 (+ (slot ,buf 'st-blocks)
823 (* (+ +max-u-long+ 1)
824 (slot ,buf 'st-blocksh)))
827 (defun unix-stat (name)
829 "Unix-stat retrieves information about the specified
830 file returning them in the form of multiple values.
831 See the UNIX Programmer's Manual for a description
832 of the values returned. If the call fails, then NIL
833 and an error number is returned instead."
834 (declare (type unix-pathname name))
835 (when (string= name "")
837 (with-alien ((buf (struct stat)))
838 (syscall ("stat" c-string (* (struct stat)))
839 (extract-stat-results buf)
842 (defun unix-fstat (fd)
844 "Unix-fstat is similar to unix-stat except the file is specified
845 by the file descriptor fd."
846 (declare (type unix-fd fd))
847 (with-alien ((buf (struct stat)))
848 (syscall ("fstat" int (* (struct stat)))
849 (extract-stat-results buf)
852 (defun unix-lstat (name)
854 "Unix-lstat is similar to unix-stat except the specified
855 file must be a symbolic link."
856 (declare (type unix-pathname name))
857 (with-alien ((buf (struct stat)))
858 (syscall ("lstat" c-string (* (struct stat)))
859 (extract-stat-results buf)
862 ;;; UNIX-MKDIR accepts a name and a mode and attempts to create the
863 ;;; corresponding directory with mode mode.
864 (defun unix-mkdir (name mode)
866 "Unix-mkdir creates a new directory with the specified name and mode.
867 (Same as those for unix-fchmod.) It returns T upon success, otherwise
868 NIL and an error number."
869 (declare (type unix-pathname name)
870 (type unix-file-mode mode))
871 (void-syscall ("mkdir" c-string int) name mode))
875 ;; POSIX.4 structure for a time value. This is like a `struct timeval' but
876 ;; has nanoseconds instead of microseconds.
880 (tv-sec long) ;Seconds
881 (tv-nsec long))) ;Nanoseconds
883 ;; Used by other time functions.
886 (tm-sec int) ; Seconds. [0-60] (1 leap second)
887 (tm-min int) ; Minutes. [0-59]
888 (tm-hour int) ; Hours. [0-23]
889 (tm-mday int) ; Day. [1-31]
890 (tm-mon int) ; Month. [0-11]
891 (tm-year int) ; Year - 1900.
892 (tm-wday int) ; Day of week. [0-6]
893 (tm-yday int) ; Days in year.[0-365]
894 (tm-isdst int) ; DST. [-1/0/1]
895 (tm-gmtoff long) ; Seconds east of UTC.
896 (tm-zone c-string))) ; Timezone abbreviation.
898 (def-alien-variable ("tzname" unix-tzname) (array c-string 2))
900 (def-alien-routine get-timezone sb!c-call:void
901 (when sb!c-call:long :in)
902 (minutes-west sb!c-call:int :out)
903 (daylight-savings-p sb!alien:boolean :out))
905 (defun unix-get-minutes-west (secs)
906 (multiple-value-bind (ignore minutes dst) (get-timezone secs)
907 (declare (ignore ignore) (ignore dst))
910 (defun unix-get-timezone (secs)
911 (multiple-value-bind (ignore minutes dst) (get-timezone secs)
912 (declare (ignore ignore) (ignore minutes))
913 (values (deref unix-tzname (if dst 1 0)))))
917 ;;; Structure crudely representing a timezone. KLUDGE: This is
918 ;;; obsolete and should never be used.
921 (tz-minuteswest int) ; minutes west of Greenwich
922 (tz-dsttime int))) ; type of dst correction
924 #!-sb-fluid (declaim (inline unix-gettimeofday))
925 (defun unix-gettimeofday ()
927 "If it works, unix-gettimeofday returns 5 values: T, the seconds and
928 microseconds of the current time of day, the timezone (in minutes west
929 of Greenwich), and a daylight-savings flag. If it doesn't work, it
930 returns NIL and the errno."
931 (with-alien ((tv (struct timeval))
932 (tz (struct timezone)))
933 (syscall* ("gettimeofday" (* (struct timeval))
934 (* (struct timezone)))
938 (slot tz 'tz-minuteswest)
939 (slot tz 'tz-dsttime))
946 (def-unix-error ESUCCESS 0 "Successful")
947 (def-unix-error EPERM 1 "Operation not permitted")
949 (def-unix-error ENOENT 2 "No such file or directory")
951 (def-unix-error ESRCH 3 "No such process")
952 (def-unix-error EINTR 4 "Interrupted system call")
953 (def-unix-error EIO 5 "I/O error")
954 (def-unix-error ENXIO 6 "No such device or address")
955 (def-unix-error E2BIG 7 "Arg list too long")
956 (def-unix-error ENOEXEC 8 "Exec format error")
957 (def-unix-error EBADF 9 "Bad file number")
958 (def-unix-error ECHILD 10 "No children")
959 (def-unix-error EAGAIN 11 "Try again")
960 (def-unix-error ENOMEM 12 "Out of memory")
962 (def-unix-error EACCES 13 "Permission denied")
964 (def-unix-error EFAULT 14 "Bad address")
965 (def-unix-error ENOTBLK 15 "Block device required")
966 (def-unix-error EBUSY 16 "Device or resource busy")
968 (def-unix-error EEXIST 17 "File exists")
970 (def-unix-error EXDEV 18 "Cross-device link")
971 (def-unix-error ENODEV 19 "No such device")
973 (def-unix-error ENOTDIR 20 "Not a directory")
975 (def-unix-error EISDIR 21 "Is a directory")
976 (def-unix-error EINVAL 22 "Invalid argument")
977 (def-unix-error ENFILE 23 "File table overflow")
978 (def-unix-error EMFILE 24 "Too many open files")
979 (def-unix-error ENOTTY 25 "Not a typewriter")
980 (def-unix-error ETXTBSY 26 "Text file busy")
981 (def-unix-error EFBIG 27 "File too large")
982 (def-unix-error ENOSPC 28 "No space left on device")
984 (def-unix-error ESPIPE 29 "Illegal seek")
986 (def-unix-error EROFS 30 "Read-only file system")
987 (def-unix-error EMLINK 31 "Too many links")
988 (def-unix-error EPIPE 32 "Broken pipe")
993 (def-unix-error EDOM 33 "Math argument out of domain")
994 (def-unix-error ERANGE 34 "Math result not representable")
995 (def-unix-error EDEADLK 35 "Resource deadlock would occur")
996 (def-unix-error ENAMETOOLONG 36 "File name too long")
997 (def-unix-error ENOLCK 37 "No record locks available")
998 (def-unix-error ENOSYS 38 "Function not implemented")
999 (def-unix-error ENOTEMPTY 39 "Directory not empty")
1000 (def-unix-error ELOOP 40 "Too many symbolic links encountered")
1002 (def-unix-error EWOULDBLOCK 11 "Operation would block")
1003 (/show0 "unix.lisp 3192")
1005 (def-unix-error ENOMSG 42 "No message of desired type")
1006 (def-unix-error EIDRM 43 "Identifier removed")
1007 (def-unix-error ECHRNG 44 "Channel number out of range")
1008 (def-unix-error EL2NSYNC 45 "Level 2 not synchronized")
1009 (def-unix-error EL3HLT 46 "Level 3 halted")
1010 (def-unix-error EL3RST 47 "Level 3 reset")
1011 (def-unix-error ELNRNG 48 "Link number out of range")
1012 (def-unix-error EUNATCH 49 "Protocol driver not attached")
1013 (def-unix-error ENOCSI 50 "No CSI structure available")
1014 (def-unix-error EL2HLT 51 "Level 2 halted")
1015 (def-unix-error EBADE 52 "Invalid exchange")
1016 (def-unix-error EBADR 53 "Invalid request descriptor")
1017 (def-unix-error EXFULL 54 "Exchange full")
1018 (def-unix-error ENOANO 55 "No anode")
1019 (def-unix-error EBADRQC 56 "Invalid request code")
1020 (def-unix-error EBADSLT 57 "Invalid slot")
1021 (def-unix-error EDEADLOCK EDEADLK "File locking deadlock error")
1022 (def-unix-error EBFONT 59 "Bad font file format")
1023 (def-unix-error ENOSTR 60 "Device not a stream")
1024 (def-unix-error ENODATA 61 "No data available")
1025 (def-unix-error ETIME 62 "Timer expired")
1026 (def-unix-error ENOSR 63 "Out of streams resources")
1027 (def-unix-error ENONET 64 "Machine is not on the network")
1028 (def-unix-error ENOPKG 65 "Package not installed")
1029 (def-unix-error EREMOTE 66 "Object is remote")
1030 (def-unix-error ENOLINK 67 "Link has been severed")
1031 (def-unix-error EADV 68 "Advertise error")
1032 (def-unix-error ESRMNT 69 "Srmount error")
1033 (def-unix-error ECOMM 70 "Communication error on send")
1034 (def-unix-error EPROTO 71 "Protocol error")
1035 (def-unix-error EMULTIHOP 72 "Multihop attempted")
1036 (def-unix-error EDOTDOT 73 "RFS specific error")
1037 (def-unix-error EBADMSG 74 "Not a data message")
1038 (def-unix-error EOVERFLOW 75 "Value too large for defined data type")
1039 (def-unix-error ENOTUNIQ 76 "Name not unique on network")
1040 (def-unix-error EBADFD 77 "File descriptor in bad state")
1041 (def-unix-error EREMCHG 78 "Remote address changed")
1042 (def-unix-error ELIBACC 79 "Can not access a needed shared library")
1043 (def-unix-error ELIBBAD 80 "Accessing a corrupted shared library")
1044 (def-unix-error ELIBSCN 81 ".lib section in a.out corrupted")
1045 (def-unix-error ELIBMAX 82 "Attempting to link in too many shared libraries")
1046 (def-unix-error ELIBEXEC 83 "Cannot exec a shared library directly")
1047 (def-unix-error EILSEQ 84 "Illegal byte sequence")
1048 (def-unix-error ERESTART 85 "Interrupted system call should be restarted ")
1049 (def-unix-error ESTRPIPE 86 "Streams pipe error")
1050 (def-unix-error EUSERS 87 "Too many users")
1051 (def-unix-error ENOTSOCK 88 "Socket operation on non-socket")
1052 (def-unix-error EDESTADDRREQ 89 "Destination address required")
1053 (def-unix-error EMSGSIZE 90 "Message too long")
1054 (def-unix-error EPROTOTYPE 91 "Protocol wrong type for socket")
1055 (def-unix-error ENOPROTOOPT 92 "Protocol not available")
1056 (def-unix-error EPROTONOSUPPORT 93 "Protocol not supported")
1057 (def-unix-error ESOCKTNOSUPPORT 94 "Socket type not supported")
1058 (def-unix-error EOPNOTSUPP 95 "Operation not supported on transport endpoint")
1059 (def-unix-error EPFNOSUPPORT 96 "Protocol family not supported")
1060 (def-unix-error EAFNOSUPPORT 97 "Address family not supported by protocol")
1061 (def-unix-error EADDRINUSE 98 "Address already in use")
1062 (def-unix-error EADDRNOTAVAIL 99 "Cannot assign requested address")
1063 (def-unix-error ENETDOWN 100 "Network is down")
1064 (def-unix-error ENETUNREACH 101 "Network is unreachable")
1065 (def-unix-error ENETRESET 102 "Network dropped connection because of reset")
1066 (def-unix-error ECONNABORTED 103 "Software caused connection abort")
1067 (def-unix-error ECONNRESET 104 "Connection reset by peer")
1068 (def-unix-error ENOBUFS 105 "No buffer space available")
1069 (def-unix-error EISCONN 106 "Transport endpoint is already connected")
1070 (def-unix-error ENOTCONN 107 "Transport endpoint is not connected")
1071 (def-unix-error ESHUTDOWN 108 "Cannot send after transport endpoint shutdown")
1072 (def-unix-error ETOOMANYREFS 109 "Too many references: cannot splice")
1073 (def-unix-error ETIMEDOUT 110 "Connection timed out")
1074 (def-unix-error ECONNREFUSED 111 "Connection refused")
1075 (def-unix-error EHOSTDOWN 112 "Host is down")
1076 (def-unix-error EHOSTUNREACH 113 "No route to host")
1077 (def-unix-error EALREADY 114 "Operation already in progress")
1078 (def-unix-error EINPROGRESS 115 "Operation now in progress")
1079 (def-unix-error ESTALE 116 "Stale NFS file handle")
1080 (def-unix-error EUCLEAN 117 "Structure needs cleaning")
1081 (def-unix-error ENOTNAM 118 "Not a XENIX named type file")
1082 (def-unix-error ENAVAIL 119 "No XENIX semaphores available")
1083 (def-unix-error EISNAM 120 "Is a named type file")
1084 (def-unix-error EREMOTEIO 121 "Remote I/O error")
1085 (def-unix-error EDQUOT 122 "Quota exceeded")
1088 ;;; And now for something completely different ...
1091 ;;;; support routines for dealing with unix pathnames
1093 (defun unix-file-kind (name &optional check-for-links)
1095 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
1096 (declare (simple-string name))
1097 (multiple-value-bind (res dev ino mode)
1098 (if check-for-links (unix-lstat name) (unix-stat name))
1099 (declare (type (or fixnum null) mode)
1102 (let ((kind (logand mode s-ifmt)))
1103 (cond ((eql kind s-ifdir) :directory)
1104 ((eql kind s-ifreg) :file)
1105 ((eql kind s-iflnk) :link)
1108 (defun unix-maybe-prepend-current-directory (name)
1109 (declare (simple-string name))
1110 (if (and (> (length name) 0) (char= (schar name 0) #\/))
1112 (multiple-value-bind (win dir) (unix-current-directory)
1114 (concatenate 'simple-string dir "/" name)
1117 (defun unix-resolve-links (pathname)
1119 "Returns the pathname with all symbolic links resolved."
1120 (declare (simple-string pathname))
1121 (let ((len (length pathname))
1123 (declare (fixnum len) (simple-string pending))
1126 (let ((result (make-string 1024 :initial-element (code-char 0)))
1130 (let* ((name-end (or (position #\/ pending :start name-start) len))
1131 (new-fill-ptr (+ fill-ptr (- name-end name-start))))
1132 (replace result pending
1137 (let ((kind (unix-file-kind (if (zerop name-end) "/" result) t)))
1138 (unless kind (return nil))
1139 (cond ((eq kind :link)
1140 (multiple-value-bind (link err) (unix-readlink result)
1142 (error "error reading link ~S: ~S"
1143 (subseq result 0 fill-ptr)
1144 (get-unix-error-msg err)))
1145 (cond ((or (zerop (length link))
1146 (char/= (schar link 0) #\/))
1147 ;; It's a relative link.
1148 (fill result (code-char 0)
1151 ((string= result "/../" :end1 4)
1152 ;; It's across the super-root.
1153 (let ((slash (or (position #\/ result :start 4)
1155 (fill result (code-char 0)
1158 (setf fill-ptr slash)))
1161 (and (> (length link) 0)
1162 (char= (schar link 0) #\/))
1163 (fill result (code-char 0) :end new-fill-ptr)
1166 (if (= name-end len)
1168 (concatenate 'simple-string
1170 (subseq pending name-end))))
1171 (setf len (length pending))
1172 (setf name-start 0)))
1174 (return (subseq result 0 new-fill-ptr)))
1175 ((eq kind :directory)
1176 (setf (schar result new-fill-ptr) #\/)
1177 (setf fill-ptr (1+ new-fill-ptr))
1178 (setf name-start (1+ name-end)))
1180 (return nil))))))))))
1182 (defun unix-simplify-pathname (src)
1183 (declare (simple-string src))
1184 (let* ((src-len (length src))
1185 (dst (make-string src-len))
1189 (macrolet ((deposit (char)
1191 (setf (schar dst dst-len) ,char)
1193 (dotimes (src-index src-len)
1194 (let ((char (schar src src-index)))
1195 (cond ((char= char #\.)
1202 ;; Either ``/...' or ``...//...'
1204 (setf last-slash dst-len)
1207 ;; Either ``./...'' or ``..././...''
1212 ((and last-slash (not (zerop last-slash)))
1213 ;; There is something before this ..
1214 (let ((prev-prev-slash
1215 (position #\/ dst :end last-slash :from-end t)))
1216 (cond ((and (= (+ (or prev-prev-slash 0) 2)
1218 (char= (schar dst (- last-slash 2)) #\.)
1219 (char= (schar dst (1- last-slash)) #\.))
1220 ;; The something before this .. is another ..
1222 (setf last-slash dst-len))
1224 ;; The something is some directory or other.
1227 (1+ prev-prev-slash)
1229 (setf last-slash prev-prev-slash)))))
1231 ;; There is nothing before this .., so we need to keep it
1232 (setf last-slash dst-len)
1235 ;; Something other than a dot between slashes.
1236 (setf last-slash dst-len)
1241 (setf (schar dst dst-len) char)
1243 (when (and last-slash (not (zerop last-slash)))
1246 ;; We've got ``foobar/.''
1249 ;; We've got ``foobar/..''
1250 (unless (and (>= last-slash 2)
1251 (char= (schar dst (1- last-slash)) #\.)
1252 (char= (schar dst (- last-slash 2)) #\.)
1253 (or (= last-slash 2)
1254 (char= (schar dst (- last-slash 3)) #\/)))
1255 (let ((prev-prev-slash
1256 (position #\/ dst :end last-slash :from-end t)))
1258 (setf dst-len (1+ prev-prev-slash))
1259 (return-from unix-simplify-pathname "./")))))))
1260 (cond ((zerop dst-len)
1262 ((= dst-len src-len)
1265 (subseq dst 0 dst-len)))))
1267 ;;;; stuff not yet found in the header files
1269 ;;;; Abandon all hope who enters here...
1271 ;;; not checked for linux...
1272 (defmacro fd-set (offset fd-set)
1273 (let ((word (gensym))
1275 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
1276 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1277 (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
1278 (deref (slot ,fd-set 'fds-bits) ,word))))))
1280 ;;; not checked for linux...
1281 (defmacro fd-clr (offset fd-set)
1282 (let ((word (gensym))
1284 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
1285 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1286 (logand (deref (slot ,fd-set 'fds-bits) ,word)
1287 (sb!kernel:32bit-logical-not
1288 (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
1290 ;;; not checked for linux...
1291 (defmacro fd-isset (offset fd-set)
1292 (let ((word (gensym))
1294 `(multiple-value-bind (,word ,bit) (floor ,offset 32)
1295 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1297 ;;; not checked for linux...
1298 (defmacro fd-zero (fd-set)
1300 ,@(loop for index upfrom 0 below (/ fd-setsize 32)
1301 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))
1303 (/show0 "unix.lisp 3555")