1 ;;;; This file contains Unix support that SBCL needs to implement
2 ;;;; itself. It's derived from Peter Van Eynde's unix-glibc2.lisp for
3 ;;;; CMU CL, which was derived from CMU CL unix.lisp 1.56. But those
4 ;;;; files aspired to be complete Unix interfaces exported to the end
5 ;;;; user, while this file aims to be as simple as possible and is not
6 ;;;; intended for the end user.
8 ;;;; FIXME: The old CMU CL unix.lisp code was implemented as hand
9 ;;;; transcriptions from Unix headers into Lisp. It appears that this was as
10 ;;;; unmaintainable in practice as you'd expect in theory, so I really really
11 ;;;; don't want to do that. It'd be good to implement the various system calls
12 ;;;; as C code implemented using the Unix header files, and have their
13 ;;;; interface back to SBCL code be characterized by things like "32-bit-wide
14 ;;;; int" which are already in the interface between the runtime
15 ;;;; executable and the SBCL lisp code.
17 ;;;; This software is part of the SBCL system. See the README file for
18 ;;;; more information.
20 ;;;; This software is derived from the CMU CL system, which was
21 ;;;; written at Carnegie Mellon University and released into the
22 ;;;; public domain. The software is in the public domain and is
23 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
24 ;;;; files for more information.
26 (in-package "SB!UNIX")
28 (/show0 "unix.lisp 21")
30 (defmacro def-enum (inc cur &rest names)
31 (flet ((defform (name)
32 (prog1 (when name `(defconstant ,name ,cur))
33 (setf cur (funcall inc cur 1)))))
34 `(progn ,@(mapcar #'defform names))))
36 ;;; Given a C-level zero-terminated array of C strings, return a
37 ;;; corresponding Lisp-level list of SIMPLE-STRINGs.
38 (defun c-strings->string-list (c-strings)
39 (declare (type (alien (* c-string)) c-strings))
40 (let ((reversed-result nil))
41 (dotimes (i most-positive-fixnum (error "argh! can't happen"))
42 (declare (type index i))
43 (let ((c-string (deref c-strings i)))
45 (push c-string reversed-result)
46 (return (nreverse reversed-result)))))))
48 ;;;; Lisp types used by syscalls
50 (deftype unix-pathname () 'simple-base-string)
51 (deftype unix-fd () `(integer 0 ,most-positive-fixnum))
53 (deftype unix-file-mode () '(unsigned-byte 32))
54 (deftype unix-pid () '(unsigned-byte 32))
55 (deftype unix-uid () '(unsigned-byte 32))
56 (deftype unix-gid () '(unsigned-byte 32))
60 (/show0 "unix.lisp 74")
62 ;;; FIXME: The various FOO-SYSCALL-BAR macros, and perhaps some other
63 ;;; macros in this file, are only used in this file, and could be
64 ;;; implemented using SB!XC:DEFMACRO wrapped in EVAL-WHEN.
66 (defmacro syscall ((name &rest arg-types) success-form &rest args)
68 (declare (optimize (sb!c::float-accuracy 0)))
69 (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
72 (values nil (get-errno))
75 ;;; This is like SYSCALL, but if it fails, signal an error instead of
76 ;;; returning error codes. Should only be used for syscalls that will
77 ;;; never really get an error.
78 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
80 (declare (optimize (sb!c::float-accuracy 0)))
81 (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
84 (error "Syscall ~A failed: ~A" ,name (strerror))
87 (/show0 "unix.lisp 109")
89 (defmacro void-syscall ((name &rest arg-types) &rest args)
90 `(syscall (,name ,@arg-types) (values t 0) ,@args))
92 (defmacro int-syscall ((name &rest arg-types) &rest args)
93 `(syscall (,name ,@arg-types) (values result 0) ,@args))
95 (defmacro with-restarted-syscall ((&optional (value (gensym))
97 syscall-form &rest body)
99 "Evaluate BODY with VALUE and ERRNO bound to the return values of
100 SYSCALL-FORM. Repeat evaluation of SYSCALL-FORM if it is interrupted."
101 `(let (,value ,errno)
102 (loop (multiple-value-setq (,value ,errno)
104 (unless #!-win32 (eql ,errno sb!unix:eintr) #!+win32 nil
105 (return (values ,value ,errno))))
110 (defconstant o_rdonly 0)
111 (defconstant o_wronly 1)
112 (defconstant o_rdwr 2)
113 (defconstant o_creat #x100)
114 (defconstant o_trunc #x200)
115 (defconstant o_append #x008)
116 (defconstant o_excl #x400)
117 (defconstant enoent 2)
118 (defconstant eexist 17)
119 (defconstant espipe 29)
120 (defconstant o_binary #x8000)
121 (defconstant s-ifmt #xf000)
122 (defconstant s-ifdir #x4000)
123 (defconstant s-ifreg #x8000)
124 (define-alien-type ino-t short)
125 (define-alien-type time-t long)
126 (define-alien-type off-t long)
127 (define-alien-type size-t long)
128 (define-alien-type mode-t unsigned-short)
130 ;; For stat-wrapper hack (different-type or non-existing win32 fields).
131 (define-alien-type nlink-t short)
132 (define-alien-type uid-t short)
133 (define-alien-type gid-t short))
135 ;;;; hacking the Unix environment
137 (define-alien-routine ("getenv" posix-getenv) c-string
138 "Return the \"value\" part of the environment string \"name=value\" which
139 corresponds to NAME, or NIL if there is none."
144 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
145 ;;; error code is returned if an error occurs.
146 (defun unix-rename (name1 name2)
147 (declare (type unix-pathname name1 name2))
148 (void-syscall ("rename" c-string c-string) name1 name2))
150 ;;; from sys/types.h and gnu/types.h
152 (/show0 "unix.lisp 220")
154 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
155 ;;; like this unless we have extreme provocation. Reading directories
156 ;;; is not extreme enough, since it doesn't need to be blindingly
157 ;;; fast: we can just implement those functions in C as a wrapper
159 (define-alien-type fd-mask unsigned-long)
161 (eval-when (:compile-toplevel :load-toplevel :execute)
162 (defconstant fd-setsize 1024))
164 (define-alien-type nil
166 (fds-bits (array fd-mask #.(/ fd-setsize
167 sb!vm:n-machine-word-bits)))))
169 (/show0 "unix.lisp 304")
174 ;;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
176 ;;; Open the file whose pathname is specified by PATH for reading
177 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
178 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
180 ;;; If the O_CREAT flag is specified, then the file is created with a
181 ;;; permission of argument MODE if the file doesn't exist. An integer
182 ;;; file descriptor is returned by UNIX-OPEN.
183 (defun unix-open (path flags mode)
184 (declare (type unix-pathname path)
186 (type unix-file-mode mode))
187 (int-syscall ("open" c-string int int) path (logior #!+win32 o_binary flags) mode))
189 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
190 ;;; associated with it.
191 (/show0 "unix.lisp 391")
192 (defun unix-close (fd)
193 (declare (type unix-fd fd))
194 (void-syscall ("close" int) fd))
198 ;; A time value that is accurate to the nearest
199 ;; microsecond but also has a range of years.
200 (define-alien-type nil
202 (tv-sec time-t) ; seconds
203 (tv-usec time-t))) ; and microseconds
207 (defconstant rusage_self 0) ; the calling process
208 (defconstant rusage_children -1) ; terminated child processes
209 (defconstant rusage_both -2)
211 (define-alien-type nil
213 (ru-utime (struct timeval)) ; user time used
214 (ru-stime (struct timeval)) ; system time used.
215 (ru-maxrss long) ; maximum resident set size (in kilobytes)
216 (ru-ixrss long) ; integral shared memory size
217 (ru-idrss long) ; integral unshared data size
218 (ru-isrss long) ; integral unshared stack size
219 (ru-minflt long) ; page reclaims
220 (ru-majflt long) ; page faults
221 (ru-nswap long) ; swaps
222 (ru-inblock long) ; block input operations
223 (ru-oublock long) ; block output operations
224 (ru-msgsnd long) ; messages sent
225 (ru-msgrcv long) ; messages received
226 (ru-nsignals long) ; signals received
227 (ru-nvcsw long) ; voluntary context switches
228 (ru-nivcsw long))) ; involuntary context switches
232 ;;; Given a file path (a string) and one of four constant modes,
233 ;;; return T if the file is accessible with that mode and NIL if not.
234 ;;; When NIL, also return an errno value with NIL which tells why the
235 ;;; file was not accessible.
237 ;;; The access modes are:
238 ;;; r_ok Read permission.
239 ;;; w_ok Write permission.
240 ;;; x_ok Execute permission.
241 ;;; f_ok Presence of file.
243 ;;; In Windows, the MODE argument to access is defined in terms of
244 ;;; literal magic numbers---there are no constants to grovel. X_OK
250 (defconstant r_ok 4))
252 (defun unix-access (path mode)
253 (declare (type unix-pathname path)
255 (void-syscall ("access" c-string int) path mode))
257 ;;; values for the second argument to UNIX-LSEEK
258 (defconstant l_set 0) ; to set the file pointer
259 (defconstant l_incr 1) ; to increment the file pointer
260 (defconstant l_xtnd 2) ; to extend the file size
262 ;;; Is a stream interactive?
263 (defun unix-isatty (fd)
264 (declare (type unix-fd fd))
265 (int-syscall ("isatty" int) fd))
267 (defun unix-lseek (fd offset whence)
268 "Unix-lseek accepts a file descriptor and moves the file pointer by
269 OFFSET octets. Whence can be any of the following:
271 L_SET Set the file pointer.
272 L_INCR Increment the file pointer.
273 L_XTND Extend the file size.
275 (declare (type unix-fd fd)
276 (type (integer 0 2) whence))
277 (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
280 (values nil (get-errno))
283 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
284 ;;; It attempts to read len bytes from the device associated with fd
285 ;;; and store them into the buffer. It returns the actual number of
287 (defun unix-read (fd buf len)
288 (declare (type unix-fd fd)
289 (type (unsigned-byte 32) len))
291 (int-syscall ("read" int (* char) int) fd buf len))
293 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
294 ;;; length to write. It attempts to write len bytes to the device
295 ;;; associated with fd from the buffer starting at offset. It returns
296 ;;; the actual number of bytes written.
297 (defun unix-write (fd buf offset len)
298 (declare (type unix-fd fd)
299 (type (unsigned-byte 32) offset len))
300 (int-syscall ("write" int (* char) int)
302 (with-alien ((ptr (* char) (etypecase buf
303 ((simple-array * (*))
307 (addr (deref ptr offset)))
310 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
311 ;;; output pipe. Return two values: if no error occurred the first
312 ;;; value is the pipe to be read from and the second is can be written
313 ;;; to. If an error occurred the first value is NIL and the second the
317 (with-alien ((fds (array int 2)))
318 (syscall ("pipe" (* int))
319 (values (deref fds 0) (deref fds 1))
320 (cast fds (* int)))))
322 ;; Windows mkdir() doesn't take the mode argument. It's cdecl, so we could
323 ;; actually call it passing the mode argument, but some sharp-eyed reader
324 ;; would put five and twenty-seven together and ask us about it, so...
326 (defun unix-mkdir (name mode)
327 (declare (type unix-pathname name)
328 (type unix-file-mode mode)
329 #!+win32 (ignore mode))
330 (void-syscall ("mkdir" c-string #!-win32 int) name #!-win32 mode))
332 ;;; Given a C char* pointer allocated by malloc(), free it and return a
333 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
334 (defun newcharstar-string (newcharstar)
335 (declare (type (alien (* char)) newcharstar))
336 (if (null-alien newcharstar)
339 (cast newcharstar c-string)
340 (free-alien newcharstar))))
342 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
343 ;;; style returned by getcwd() (no trailing slash character).
344 (defun posix-getcwd ()
345 ;; This implementation relies on a BSD/Linux extension to getcwd()
346 ;; behavior, automatically allocating memory when a null buffer
347 ;; pointer is used. On a system which doesn't support that
348 ;; extension, it'll have to be rewritten somehow.
350 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
351 ;; buffer pointer, it will automatically allocate size space. The
352 ;; KLUDGE in this solution arises because we have just read off
353 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
354 ;; a constant. Going the grovel_headers route doesn't seem to be
355 ;; helpful, either, as Solaris doesn't export PATH_MAX from
358 ;; FIXME: The (,stub,) nastiness produces an error message about a
359 ;; comma not inside a backquote. This error has absolutely nothing
360 ;; to do with the actual meaning of the error (and little to do with
361 ;; its location, either).
362 #!-(or linux openbsd freebsd netbsd sunos osf1 darwin win32) (,stub,)
363 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin win32)
364 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
369 #!+(or linux openbsd freebsd netbsd darwin win32) 0
370 #!+(or sunos osf1) 1025))
371 (simple-perror "getcwd")))
373 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
374 ;;; by a slash character.
375 (defun posix-getcwd/ ()
376 (concatenate 'string (posix-getcwd) "/"))
378 ;;; Duplicate an existing file descriptor (given as the argument) and
379 ;;; return it. If FD is not a valid file descriptor, NIL and an error
380 ;;; number are returned.
382 (declare (type unix-fd fd))
383 (int-syscall ("dup" int) fd))
385 ;;; Terminate the current process with an optional error code. If
386 ;;; successful, the call doesn't return. If unsuccessful, the call
387 ;;; returns NIL and an error number.
388 (defun unix-exit (&optional (code 0))
389 (declare (type (signed-byte 32) code))
390 (void-syscall ("exit" int) code))
392 ;;; Return the process id of the current process.
393 (define-alien-routine ("getpid" unix-getpid) int)
395 ;;; Return the real user id associated with the current process.
397 (define-alien-routine ("getuid" unix-getuid) int)
399 ;;; Translate a user id into a login name.
401 (defun uid-username (uid)
402 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
403 (function (* char) int))
405 (error "found no match for Unix uid=~S" uid)))
407 ;;; Return the namestring of the home directory, being careful to
408 ;;; include a trailing #\/
410 (defun uid-homedir (uid)
411 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
412 (function (* char) int))
414 (error "failed to resolve home directory for Unix uid=~S" uid)))
416 ;;; Invoke readlink(2) on the file name specified by PATH. Return
417 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
420 (defun unix-readlink (path)
421 (declare (type unix-pathname path))
422 (with-alien ((ptr (* char)
423 (alien-funcall (extern-alien
425 (function (* char) c-string))
428 (values nil (get-errno))
429 (multiple-value-prog1
430 (values (with-alien ((c-string c-string ptr)) c-string)
434 ;; Win32 doesn't do links, but something likes to call this anyway.
435 ;; Something in this file, no less. But it only takes one result, so...
436 (defun unix-readlink (path)
437 (declare (ignore path))
440 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
441 ;;; name and the file if this is the last link.
442 (defun unix-unlink (name)
443 (declare (type unix-pathname name))
444 (void-syscall ("unlink" c-string) name))
446 ;;; Return the name of the host machine as a string.
448 (defun unix-gethostname ()
449 (with-alien ((buf (array char 256)))
450 (syscall ("gethostname" (* char) int)
452 (cast buf (* char)) 256)))
455 (defun unix-setsid ()
456 (int-syscall ("setsid")))
460 ;;; UNIX-IOCTL performs a variety of operations on open i/o
461 ;;; descriptors. See the UNIX Programmer's Manual for more
464 (defun unix-ioctl (fd cmd arg)
465 (declare (type unix-fd fd)
466 (type (signed-byte 32) cmd))
467 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
471 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
473 ;;; This is like getrusage(2), except it returns only the system and
474 ;;; user time, and returns the seconds and microseconds as separate
476 #!-sb-fluid (declaim (inline unix-fast-getrusage))
478 (defun unix-fast-getrusage (who)
479 (declare (values (member t)
480 (unsigned-byte 31) (integer 0 1000000)
481 (unsigned-byte 31) (integer 0 1000000)))
482 (with-alien ((usage (struct rusage)))
483 (syscall* ("getrusage" int (* (struct rusage)))
485 (slot (slot usage 'ru-utime) 'tv-sec)
486 (slot (slot usage 'ru-utime) 'tv-usec)
487 (slot (slot usage 'ru-stime) 'tv-sec)
488 (slot (slot usage 'ru-stime) 'tv-usec))
491 ;;; Return information about the resource usage of the process
492 ;;; specified by WHO. WHO can be either the current process
493 ;;; (rusage_self) or all of the terminated child processes
494 ;;; (rusage_children). NIL and an error number is returned if the call
497 (defun unix-getrusage (who)
498 (with-alien ((usage (struct rusage)))
499 (syscall ("getrusage" int (* (struct rusage)))
501 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
502 (slot (slot usage 'ru-utime) 'tv-usec))
503 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
504 (slot (slot usage 'ru-stime) 'tv-usec))
505 (slot usage 'ru-maxrss)
506 (slot usage 'ru-ixrss)
507 (slot usage 'ru-idrss)
508 (slot usage 'ru-isrss)
509 (slot usage 'ru-minflt)
510 (slot usage 'ru-majflt)
511 (slot usage 'ru-nswap)
512 (slot usage 'ru-inblock)
513 (slot usage 'ru-oublock)
514 (slot usage 'ru-msgsnd)
515 (slot usage 'ru-msgrcv)
516 (slot usage 'ru-nsignals)
517 (slot usage 'ru-nvcsw)
518 (slot usage 'ru-nivcsw))
523 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
525 ;;; Perform the UNIX select(2) system call.
526 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
527 (defun unix-fast-select (num-descriptors
528 read-fds write-fds exception-fds
529 timeout-secs &optional (timeout-usecs 0))
530 (declare (type (integer 0 #.fd-setsize) num-descriptors)
531 (type (or (alien (* (struct fd-set))) null)
532 read-fds write-fds exception-fds)
533 (type (or null (unsigned-byte 31)) timeout-secs)
534 (type (unsigned-byte 31) timeout-usecs))
536 ;; (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
537 ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
538 (with-alien ((tv (struct timeval)))
540 (setf (slot tv 'tv-sec) timeout-secs)
541 (setf (slot tv 'tv-usec) timeout-usecs))
542 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
543 (* (struct fd-set)) (* (struct timeval)))
544 num-descriptors read-fds write-fds exception-fds
545 (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
547 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
548 ;;; to happen on one of them or to time out.
549 (defmacro num-to-fd-set (fdset num)
552 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
553 ,@(loop for index upfrom 1 below (/ fd-setsize
554 sb!vm:n-machine-word-bits)
555 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
557 ,@(loop for index upfrom 0 below (/ fd-setsize
558 sb!vm:n-machine-word-bits)
559 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
560 (ldb (byte sb!vm:n-machine-word-bits
561 ,(* index sb!vm:n-machine-word-bits))
564 (defmacro fd-set-to-num (nfds fdset)
565 `(if (<= ,nfds sb!vm:n-machine-word-bits)
566 (deref (slot ,fdset 'fds-bits) 0)
567 (+ ,@(loop for index upfrom 0 below (/ fd-setsize
568 sb!vm:n-machine-word-bits)
569 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
570 ,(* index sb!vm:n-machine-word-bits))))))
572 ;;; Examine the sets of descriptors passed as arguments to see whether
573 ;;; they are ready for reading and writing. See the UNIX Programmer's
574 ;;; Manual for more information.
575 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
576 (declare (type (integer 0 #.fd-setsize) nfds)
577 (type unsigned-byte rdfds wrfds xpfds)
578 (type (or (unsigned-byte 31) null) to-secs)
579 (type (unsigned-byte 31) to-usecs)
580 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
581 (with-alien ((tv (struct timeval))
582 (rdf (struct fd-set))
583 (wrf (struct fd-set))
584 (xpf (struct fd-set)))
586 (setf (slot tv 'tv-sec) to-secs)
587 (setf (slot tv 'tv-usec) to-usecs))
588 (num-to-fd-set rdf rdfds)
589 (num-to-fd-set wrf wrfds)
590 (num-to-fd-set xpf xpfds)
591 (macrolet ((frob (lispvar alienvar)
592 `(if (zerop ,lispvar)
594 (alien-sap (addr ,alienvar)))))
595 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
596 (* (struct fd-set)) (* (struct timeval)))
598 (fd-set-to-num nfds rdf)
599 (fd-set-to-num nfds wrf)
600 (fd-set-to-num nfds xpf))
601 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
602 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
606 ;;; This is a structure defined in src/runtime/wrap.c, to look
607 ;;; basically like "struct stat" according to stat(2). It may not
608 ;;; actually correspond to the real in-memory stat structure that the
609 ;;; syscall uses, and that's OK. Linux in particular is packed full of
610 ;;; stat macros, and trying to keep Lisp code in correspondence with
611 ;;; it is more pain than it's worth, so we just let our C runtime
612 ;;; synthesize a nice consistent structure for us.
614 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
615 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
616 ;;; those. We don't actually access that field anywhere, though, so
617 ;;; until we can get 64 bit alien support it'll do. Also note that
618 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
619 ;;; quantity on Alpha. And FIXME: "No one would want a file length
620 ;;; longer than 32 bits anyway, right?":-|
621 (define-alien-type nil
624 (st-dev unsigned-int) ; would be dev-t in a real stat
626 (st-dev unsigned-long) ; this is _not_ a dev-t on mips
633 (st-rdev unsigned-int) ; would be dev-t in a real stat
635 (st-rdev unsigned-long) ; this is _not_ a dev-t on mips
637 (st-size unsigned-int) ; would be off-t in a real stat
640 (st-blksize unsigned-long)
641 (st-blocks unsigned-long)
646 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
647 ;;; family of Unix system calls
649 ;;; FIXME: I think this should probably not be INLINE. However, when
650 ;;; this was not inline, it seemed to cause memory corruption
651 ;;; problems. My first guess is that it's a bug in the FFI code, where
652 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
653 ;;; around a call to a function returning >10 values. But I didn't try
654 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
655 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
656 ;;; output in the not-inlined case and see whether there's a problem,
657 ;;; and maybe even find a fix..
658 (declaim (inline %extract-stat-results))
659 (defun %extract-stat-results (wrapped-stat)
660 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
662 (slot wrapped-stat 'st-dev)
663 (slot wrapped-stat 'st-ino)
664 (slot wrapped-stat 'st-mode)
665 (slot wrapped-stat 'st-nlink)
666 (slot wrapped-stat 'st-uid)
667 (slot wrapped-stat 'st-gid)
668 (slot wrapped-stat 'st-rdev)
669 (slot wrapped-stat 'st-size)
670 (slot wrapped-stat 'st-atime)
671 (slot wrapped-stat 'st-mtime)
672 (slot wrapped-stat 'st-ctime)
673 (slot wrapped-stat 'st-blksize)
674 (slot wrapped-stat 'st-blocks)))
676 ;;; Unix system calls in the stat(2) family are handled by calls to
677 ;;; C-level wrapper functions which copy all the raw "struct stat"
678 ;;; slots into the system-independent wrapped_stat format.
679 ;;; stat(2) <-> stat_wrapper()
680 ;;; fstat(2) <-> fstat_wrapper()
681 ;;; lstat(2) <-> lstat_wrapper()
682 (defun unix-stat (name)
683 (declare (type unix-pathname name))
684 (with-alien ((buf (struct wrapped_stat)))
685 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
686 (%extract-stat-results (addr buf))
688 (defun unix-lstat (name)
689 (declare (type unix-pathname name))
690 (with-alien ((buf (struct wrapped_stat)))
691 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
692 (%extract-stat-results (addr buf))
694 (defun unix-fstat (fd)
695 (declare (type unix-fd fd))
696 (with-alien ((buf (struct wrapped_stat)))
697 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
698 (%extract-stat-results (addr buf))
703 ;; the POSIX.4 structure for a time value. This is like a "struct
704 ;; timeval" but has nanoseconds instead of microseconds.
705 (define-alien-type nil
707 (tv-sec long) ; seconds
708 (tv-nsec long))) ; nanoseconds
710 ;; used by other time functions
711 (define-alien-type nil
713 (tm-sec int) ; Seconds. [0-60] (1 leap second)
714 (tm-min int) ; Minutes. [0-59]
715 (tm-hour int) ; Hours. [0-23]
716 (tm-mday int) ; Day. [1-31]
717 (tm-mon int) ; Month. [0-11]
718 (tm-year int) ; Year - 1900.
719 (tm-wday int) ; Day of week. [0-6]
720 (tm-yday int) ; Days in year. [0-365]
721 (tm-isdst int) ; DST. [-1/0/1]
722 (tm-gmtoff long) ; Seconds east of UTC.
723 (tm-zone c-string))) ; Timezone abbreviation.
725 (define-alien-routine get-timezone sb!alien:void
726 (when sb!alien:long :in)
727 (seconds-west sb!alien:int :out)
728 (daylight-savings-p sb!alien:boolean :out))
731 (defun nanosleep (secs nsecs)
732 (with-alien ((req (struct timespec))
733 (rem (struct timespec)))
734 (setf (slot req 'tv-sec) secs)
735 (setf (slot req 'tv-nsec) nsecs)
736 (loop while (eql sb!unix:eintr
738 (int-syscall ("nanosleep" (* (struct timespec))
739 (* (struct timespec)))
740 (addr req) (addr rem))))
741 do (rotatef req rem))))
743 (defun unix-get-seconds-west (secs)
744 (multiple-value-bind (ignore seconds dst) (get-timezone secs)
745 (declare (ignore ignore) (ignore dst))
750 ;;; Structure crudely representing a timezone. KLUDGE: This is
751 ;;; obsolete and should never be used.
752 (define-alien-type nil
754 (tz-minuteswest int) ; minutes west of Greenwich
755 (tz-dsttime int))) ; type of dst correction
757 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
758 ;;; and microseconds of the current time of day, the timezone (in
759 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
760 ;;; doesn't work, it returns NIL and the errno.
761 #!-sb-fluid (declaim (inline unix-gettimeofday))
762 (defun unix-gettimeofday ()
763 (with-alien ((tv (struct timeval))
764 (tz (struct timezone)))
765 (syscall* ("gettimeofday" (* (struct timeval))
766 (* (struct timezone)))
770 (slot tz 'tz-minuteswest)
771 (slot tz 'tz-dsttime))
776 ;; Type of the second argument to `getitimer' and
777 ;; the second and third arguments `setitimer'.
778 (define-alien-type nil
780 (it-interval (struct timeval)) ; timer interval
781 (it-value (struct timeval)))) ; current value
783 (defconstant itimer-real 0)
784 (defconstant itimer-virtual 1)
785 (defconstant itimer-prof 2)
788 (defun unix-getitimer (which)
789 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
790 three system timers (:real :virtual or :profile). On success,
791 unix-getitimer returns 5 values,
792 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
793 (declare (type (member :real :virtual :profile) which)
795 (unsigned-byte 29) (mod 1000000)
796 (unsigned-byte 29) (mod 1000000)))
797 (let ((which (ecase which
799 (:virtual itimer-virtual)
800 (:profile itimer-prof))))
801 (with-alien ((itv (struct itimerval)))
802 (syscall* ("getitimer" int (* (struct itimerval)))
804 (slot (slot itv 'it-interval) 'tv-sec)
805 (slot (slot itv 'it-interval) 'tv-usec)
806 (slot (slot itv 'it-value) 'tv-sec)
807 (slot (slot itv 'it-value) 'tv-usec))
808 which (alien-sap (addr itv))))))
811 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
812 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
813 three system timers (:real :virtual or :profile). A SIGALRM signal
814 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
815 when non-zero, is <seconds+microseconds> to be loaded each time
816 the timer expires. Setting INTERVAL and VALUE to zero disables
817 the timer. See the Unix man page for more details. On success,
818 unix-setitimer returns the old contents of the INTERVAL and VALUE
819 slots as in unix-getitimer."
820 (declare (type (member :real :virtual :profile) which)
821 (type (unsigned-byte 29) int-secs val-secs)
822 (type (integer 0 (1000000)) int-usec val-usec)
824 (unsigned-byte 29) (mod 1000000)
825 (unsigned-byte 29) (mod 1000000)))
826 (let ((which (ecase which
828 (:virtual itimer-virtual)
829 (:profile itimer-prof))))
830 (with-alien ((itvn (struct itimerval))
831 (itvo (struct itimerval)))
832 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
833 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
834 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
835 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
836 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
838 (slot (slot itvo 'it-interval) 'tv-sec)
839 (slot (slot itvo 'it-interval) 'tv-usec)
840 (slot (slot itvo 'it-value) 'tv-sec)
841 (slot (slot itvo 'it-value) 'tv-usec))
842 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
845 ;;; FIXME: Many Unix error code definitions were deleted from the old
846 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
847 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
848 ;;; unused symbols in package exports, but if I don't, there are
849 ;;; enough of them all in one place here that they should probably be
852 ;;;; support routines for dealing with Unix pathnames
854 (defun unix-file-kind (name &optional check-for-links)
856 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
857 (declare (simple-base-string name))
858 (multiple-value-bind (res dev ino mode)
859 (if check-for-links (unix-lstat name) (unix-stat name))
860 (declare (type (or fixnum null) mode)
863 (let ((kind (logand mode s-ifmt)))
864 (cond ((eql kind s-ifdir) :directory)
865 ((eql kind s-ifreg) :file)
867 ((eql kind s-iflnk) :link)
870 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
871 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
872 (defun relative-unix-pathname? (pathname)
873 (declare (type simple-string pathname))
874 (or (zerop (length pathname))
875 (char/= (schar pathname 0) #\/)))
877 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
878 ;;; already be a complete absolute Unix pathname, since at least in
879 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
880 ;;; paths have been converted to absolute paths, so we don't need to
881 ;;; try to handle any more generality than that.
882 (defun unix-resolve-links (pathname)
883 (declare (type simple-base-string pathname))
884 ;; KLUDGE: The Win32 platform doesn't have symbolic links, so
885 ;; short-cut this computation (and the check for being an absolute
887 #!+win32 (return-from unix-resolve-links pathname)
888 (aver (not (relative-unix-pathname? pathname)))
889 ;; KLUDGE: readlink and lstat are unreliable if given symlinks
890 ;; ending in slashes -- fix the issue here instead of waiting for
893 ;; but be careful! Must not strip the final slash from "/". (This
894 ;; adjustment might be a candidate for being transferred into the C
895 ;; code in a wrap_readlink() function, too.) CSR, 2006-01-18
896 (let ((len (length pathname)))
897 (when (and (> len 1) (eql #\/ (schar pathname (1- len))))
898 (setf pathname (subseq pathname 0 (1- len)))))
899 (/noshow "entering UNIX-RESOLVE-LINKS")
900 (loop with previous-pathnames = nil do
901 (/noshow pathname previous-pathnames)
902 (let ((link (unix-readlink pathname)))
904 ;; Unlike the old CMU CL code, we handle a broken symlink by
905 ;; returning the link itself. That way, CL:TRUENAME on a
906 ;; broken link returns the link itself, so that CL:DIRECTORY
907 ;; can return broken links, so that even without
908 ;; Unix-specific extensions to do interesting things with
909 ;; them, at least Lisp programs can see them and, if
910 ;; necessary, delete them. (This is handy e.g. when your
911 ;; managed-by-Lisp directories are visited by Emacs, which
912 ;; creates broken links as notes to itself.)
916 (unix-simplify-pathname
917 (if (relative-unix-pathname? link)
918 (let* ((dir-len (1+ (position #\/
921 (dir (subseq pathname 0 dir-len)))
923 (concatenate 'base-string dir link))
925 (if (unix-file-kind new-pathname)
926 (setf pathname new-pathname)
927 (return pathname)))))
928 ;; To generalize the principle that even if portable Lisp code
929 ;; can't do anything interesting with a broken symlink, at
930 ;; least it should be able to see and delete it, when we
931 ;; detect a cyclic link, we return the link itself. (So even
932 ;; though portable Lisp code can't do anything interesting
933 ;; with a cyclic link, at least it can see it and delete it.)
934 (if (member pathname previous-pathnames :test #'string=)
936 (push pathname previous-pathnames))))
938 (defun unix-simplify-pathname (src)
939 (declare (type simple-base-string src))
940 (let* ((src-len (length src))
941 (dst (make-string src-len :element-type 'base-char))
945 (macrolet ((deposit (char)
947 (setf (schar dst dst-len) ,char)
949 (dotimes (src-index src-len)
950 (let ((char (schar src src-index)))
951 (cond ((char= char #\.)
958 ;; either ``/...' or ``...//...'
960 (setf last-slash dst-len)
963 ;; either ``./...'' or ``..././...''
968 ((and last-slash (not (zerop last-slash)))
969 ;; There is something before this ..
970 (let ((prev-prev-slash
971 (position #\/ dst :end last-slash :from-end t)))
972 (cond ((and (= (+ (or prev-prev-slash 0) 2)
974 (char= (schar dst (- last-slash 2)) #\.)
975 (char= (schar dst (1- last-slash)) #\.))
976 ;; The something before this .. is another ..
978 (setf last-slash dst-len))
980 ;; The something is some directory or other.
985 (setf last-slash prev-prev-slash)))))
987 ;; There is nothing before this .., so we need to keep it
988 (setf last-slash dst-len)
991 ;; something other than a dot between slashes
992 (setf last-slash dst-len)
997 (setf (schar dst dst-len) char)
999 (when (and last-slash (not (zerop last-slash)))
1002 ;; We've got ``foobar/.''
1005 ;; We've got ``foobar/..''
1006 (unless (and (>= last-slash 2)
1007 (char= (schar dst (1- last-slash)) #\.)
1008 (char= (schar dst (- last-slash 2)) #\.)
1009 (or (= last-slash 2)
1010 (char= (schar dst (- last-slash 3)) #\/)))
1011 (let ((prev-prev-slash
1012 (position #\/ dst :end last-slash :from-end t)))
1014 (setf dst-len (1+ prev-prev-slash))
1015 (return-from unix-simplify-pathname
1016 (coerce "./" 'simple-base-string))))))))
1017 (cond ((zerop dst-len)
1019 ((= dst-len src-len)
1022 (subseq dst 0 dst-len)))))
1024 ;;;; A magic constant for wait3().
1026 ;;;; FIXME: This used to be defined in run-program.lisp as
1027 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
1028 ;;;; According to some of the man pages, the #o177 is part of the API
1029 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
1030 ;;;; the headers that may or may not be the same thing. To be
1031 ;;;; investigated. -- CSR, 2002-03-25
1032 (defconstant wstopped #o177)
1035 ;;;; stuff not yet found in the header files
1037 ;;;; Abandon all hope who enters here...
1039 ;;; not checked for linux...
1040 (defmacro fd-set (offset fd-set)
1041 (let ((word (gensym))
1043 `(multiple-value-bind (,word ,bit) (floor ,offset
1044 sb!vm:n-machine-word-bits)
1045 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1046 (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1048 (deref (slot ,fd-set 'fds-bits) ,word))))))
1050 ;;; not checked for linux...
1051 (defmacro fd-clr (offset fd-set)
1052 (let ((word (gensym))
1054 `(multiple-value-bind (,word ,bit) (floor ,offset
1055 sb!vm:n-machine-word-bits)
1056 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1057 (logand (deref (slot ,fd-set 'fds-bits) ,word)
1058 (sb!kernel:word-logical-not
1059 (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1062 ;;; not checked for linux...
1063 (defmacro fd-isset (offset fd-set)
1064 (let ((word (gensym))
1066 `(multiple-value-bind (,word ,bit) (floor ,offset
1067 sb!vm:n-machine-word-bits)
1068 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1070 ;;; not checked for linux...
1071 (defmacro fd-zero (fd-set)
1073 ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
1074 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))