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 () #!-win32 'simple-base-string #!+win32 'simple-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 espipe 29)
111 ;; For stat-wrapper hack (different-type or non-existing win32 fields).
112 (define-alien-type nlink-t short)
113 (define-alien-type uid-t short)
114 (define-alien-type gid-t short))
116 ;;;; hacking the Unix environment
119 (define-alien-routine ("getenv" posix-getenv) c-string
120 "Return the \"value\" part of the environment string \"name=value\" which
121 corresponds to NAME, or NIL if there is none."
126 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
127 ;;; error code is returned if an error occurs.
129 (defun unix-rename (name1 name2)
130 (declare (type unix-pathname name1 name2))
131 (void-syscall ("rename" c-string c-string) name1 name2))
133 ;;; from sys/types.h and gnu/types.h
135 (/show0 "unix.lisp 220")
137 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
138 ;;; like this unless we have extreme provocation. Reading directories
139 ;;; is not extreme enough, since it doesn't need to be blindingly
140 ;;; fast: we can just implement those functions in C as a wrapper
142 (define-alien-type fd-mask unsigned-long)
144 (eval-when (:compile-toplevel :load-toplevel :execute)
145 (defconstant fd-setsize 1024))
147 (define-alien-type nil
149 (fds-bits (array fd-mask #.(/ fd-setsize
150 sb!vm:n-machine-word-bits)))))
152 (/show0 "unix.lisp 304")
157 ;;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
159 ;;; Open the file whose pathname is specified by PATH for reading
160 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
161 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
163 ;;; If the O_CREAT flag is specified, then the file is created with a
164 ;;; permission of argument MODE if the file doesn't exist. An integer
165 ;;; file descriptor is returned by UNIX-OPEN.
166 (defun unix-open (path flags mode)
167 (declare (type unix-pathname path)
169 (type unix-file-mode mode))
170 (int-syscall ("open" c-string int int) path (logior #!+win32 o_binary flags) mode))
172 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
173 ;;; associated with it.
174 (/show0 "unix.lisp 391")
175 (defun unix-close (fd)
176 (declare (type unix-fd fd))
177 (void-syscall ("close" int) fd))
181 ;; A time value that is accurate to the nearest
182 ;; microsecond but also has a range of years.
183 (define-alien-type nil
185 (tv-sec time-t) ; seconds
186 (tv-usec time-t))) ; and microseconds
190 (defconstant rusage_self 0) ; the calling process
191 (defconstant rusage_children -1) ; terminated child processes
192 (defconstant rusage_both -2)
194 (define-alien-type nil
196 (ru-utime (struct timeval)) ; user time used
197 (ru-stime (struct timeval)) ; system time used.
198 (ru-maxrss long) ; maximum resident set size (in kilobytes)
199 (ru-ixrss long) ; integral shared memory size
200 (ru-idrss long) ; integral unshared data size
201 (ru-isrss long) ; integral unshared stack size
202 (ru-minflt long) ; page reclaims
203 (ru-majflt long) ; page faults
204 (ru-nswap long) ; swaps
205 (ru-inblock long) ; block input operations
206 (ru-oublock long) ; block output operations
207 (ru-msgsnd long) ; messages sent
208 (ru-msgrcv long) ; messages received
209 (ru-nsignals long) ; signals received
210 (ru-nvcsw long) ; voluntary context switches
211 (ru-nivcsw long))) ; involuntary context switches
215 ;;; Given a file path (a string) and one of four constant modes,
216 ;;; return T if the file is accessible with that mode and NIL if not.
217 ;;; When NIL, also return an errno value with NIL which tells why the
218 ;;; file was not accessible.
220 ;;; The access modes are:
221 ;;; r_ok Read permission.
222 ;;; w_ok Write permission.
223 ;;; x_ok Execute permission.
224 ;;; f_ok Presence of file.
226 ;;; In Windows, the MODE argument to access is defined in terms of
227 ;;; literal magic numbers---there are no constants to grovel. X_OK
233 (defconstant r_ok 4))
235 (defun unix-access (path mode)
236 (declare (type unix-pathname path)
238 (void-syscall ("access" c-string int) path mode))
240 ;;; values for the second argument to UNIX-LSEEK
241 (defconstant l_set 0) ; to set the file pointer
242 (defconstant l_incr 1) ; to increment the file pointer
243 (defconstant l_xtnd 2) ; to extend the file size
245 ;;; Is a stream interactive?
246 (defun unix-isatty (fd)
247 (declare (type unix-fd fd))
248 (int-syscall ("isatty" int) fd))
250 (defun unix-lseek (fd offset whence)
251 "Unix-lseek accepts a file descriptor and moves the file pointer by
252 OFFSET octets. Whence can be any of the following:
254 L_SET Set the file pointer.
255 L_INCR Increment the file pointer.
256 L_XTND Extend the file size.
258 (declare (type unix-fd fd)
259 (type (integer 0 2) whence))
260 (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
263 (values nil (get-errno))
266 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
267 ;;; It attempts to read len bytes from the device associated with fd
268 ;;; and store them into the buffer. It returns the actual number of
270 (defun unix-read (fd buf len)
271 (declare (type unix-fd fd)
272 (type (unsigned-byte 32) len))
274 (int-syscall ("read" int (* char) int) fd buf len))
276 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
277 ;;; length to write. It attempts to write len bytes to the device
278 ;;; associated with fd from the buffer starting at offset. It returns
279 ;;; the actual number of bytes written.
280 (defun unix-write (fd buf offset len)
281 (declare (type unix-fd fd)
282 (type (unsigned-byte 32) offset len))
283 (int-syscall ("write" int (* char) int)
285 (with-alien ((ptr (* char) (etypecase buf
286 ((simple-array * (*))
290 (addr (deref ptr offset)))
293 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
294 ;;; output pipe. Return two values: if no error occurred the first
295 ;;; value is the pipe to be read from and the second is can be written
296 ;;; to. If an error occurred the first value is NIL and the second the
300 (with-alien ((fds (array int 2)))
301 (syscall ("pipe" (* int))
302 (values (deref fds 0) (deref fds 1))
303 (cast fds (* int)))))
305 (defun msvcrt-raw-pipe (fds size mode)
306 (syscall ("_pipe" (* int) int int)
307 (values (deref fds 0) (deref fds 1))
308 (cast fds (* int)) size mode))
311 (with-alien ((fds (array int 2)))
312 (msvcrt-raw-pipe fds 256 o_binary)))
314 ;; Windows mkdir() doesn't take the mode argument. It's cdecl, so we could
315 ;; actually call it passing the mode argument, but some sharp-eyed reader
316 ;; would put five and twenty-seven together and ask us about it, so...
319 (defun unix-mkdir (name mode)
320 (declare (type unix-pathname name)
321 (type unix-file-mode mode)
322 #!+win32 (ignore mode))
323 (void-syscall ("mkdir" c-string #!-win32 int) name #!-win32 mode))
325 ;;; Given a C char* pointer allocated by malloc(), free it and return a
326 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
327 (defun newcharstar-string (newcharstar)
328 (declare (type (alien (* char)) newcharstar))
329 (if (null-alien newcharstar)
332 (cast newcharstar c-string)
333 (free-alien newcharstar))))
335 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
336 ;;; style returned by getcwd() (no trailing slash character).
338 (defun posix-getcwd ()
339 ;; This implementation relies on a BSD/Linux extension to getcwd()
340 ;; behavior, automatically allocating memory when a null buffer
341 ;; pointer is used. On a system which doesn't support that
342 ;; extension, it'll have to be rewritten somehow.
344 ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
345 ;; buffer pointer, it will automatically allocate size space. The
346 ;; KLUDGE in this solution arises because we have just read off
347 ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
348 ;; a constant. Going the grovel_headers route doesn't seem to be
349 ;; helpful, either, as Solaris doesn't export PATH_MAX from
352 ;; FIXME: The (,stub,) nastiness produces an error message about a
353 ;; comma not inside a backquote. This error has absolutely nothing
354 ;; to do with the actual meaning of the error (and little to do with
355 ;; its location, either).
356 #!-(or linux openbsd freebsd netbsd sunos osf1 darwin win32) (,stub,)
357 #!+(or linux openbsd freebsd netbsd sunos osf1 darwin win32)
358 (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
363 #!+(or linux openbsd freebsd netbsd darwin win32) 0
364 #!+(or sunos osf1) 1025))
365 (simple-perror "getcwd")))
367 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
368 ;;; by a slash character.
369 (defun posix-getcwd/ ()
370 (concatenate 'string (posix-getcwd) "/"))
372 ;;; Duplicate an existing file descriptor (given as the argument) and
373 ;;; return it. If FD is not a valid file descriptor, NIL and an error
374 ;;; number are returned.
376 (declare (type unix-fd fd))
377 (int-syscall ("dup" int) fd))
379 ;;; Terminate the current process with an optional error code. If
380 ;;; successful, the call doesn't return. If unsuccessful, the call
381 ;;; returns NIL and an error number.
382 (defun unix-exit (&optional (code 0))
383 (declare (type (signed-byte 32) code))
384 (void-syscall ("exit" int) code))
386 ;;; Return the process id of the current process.
387 (define-alien-routine ("getpid" unix-getpid) int)
389 ;;; Return the real user id associated with the current process.
391 (define-alien-routine ("getuid" unix-getuid) int)
393 ;;; Translate a user id into a login name.
395 (defun uid-username (uid)
396 (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
397 (function (* char) int))
399 (error "found no match for Unix uid=~S" uid)))
401 ;;; Return the namestring of the home directory, being careful to
402 ;;; include a trailing #\/
404 (defun uid-homedir (uid)
405 (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
406 (function (* char) int))
408 (error "failed to resolve home directory for Unix uid=~S" uid)))
410 ;;; Invoke readlink(2) on the file name specified by PATH. Return
411 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
414 (defun unix-readlink (path)
415 (declare (type unix-pathname path))
416 (with-alien ((ptr (* char)
417 (alien-funcall (extern-alien
419 (function (* char) c-string))
422 (values nil (get-errno))
423 (multiple-value-prog1
424 (values (with-alien ((c-string c-string ptr)) c-string)
428 ;; Win32 doesn't do links, but something likes to call this anyway.
429 ;; Something in this file, no less. But it only takes one result, so...
430 (defun unix-readlink (path)
431 (declare (ignore path))
434 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
435 ;;; name and the file if this is the last link.
436 (defun unix-unlink (name)
437 (declare (type unix-pathname name))
438 (void-syscall ("unlink" c-string) name))
440 ;;; Return the name of the host machine as a string.
442 (defun unix-gethostname ()
443 (with-alien ((buf (array char 256)))
444 (syscall ("gethostname" (* char) int)
446 (cast buf (* char)) 256)))
449 (defun unix-setsid ()
450 (int-syscall ("setsid")))
454 ;;; UNIX-IOCTL performs a variety of operations on open i/o
455 ;;; descriptors. See the UNIX Programmer's Manual for more
458 (defun unix-ioctl (fd cmd arg)
459 (declare (type unix-fd fd)
460 (type (signed-byte 32) cmd))
461 (void-syscall ("ioctl" int int (* char)) fd cmd arg))
465 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
467 ;;; This is like getrusage(2), except it returns only the system and
468 ;;; user time, and returns the seconds and microseconds as separate
470 #!-sb-fluid (declaim (inline unix-fast-getrusage))
472 (defun unix-fast-getrusage (who)
473 (declare (values (member t)
474 (unsigned-byte 31) (integer 0 1000000)
475 (unsigned-byte 31) (integer 0 1000000)))
476 (with-alien ((usage (struct rusage)))
477 (syscall* ("getrusage" int (* (struct rusage)))
479 (slot (slot usage 'ru-utime) 'tv-sec)
480 (slot (slot usage 'ru-utime) 'tv-usec)
481 (slot (slot usage 'ru-stime) 'tv-sec)
482 (slot (slot usage 'ru-stime) 'tv-usec))
485 ;;; Return information about the resource usage of the process
486 ;;; specified by WHO. WHO can be either the current process
487 ;;; (rusage_self) or all of the terminated child processes
488 ;;; (rusage_children). NIL and an error number is returned if the call
491 (defun unix-getrusage (who)
492 (with-alien ((usage (struct rusage)))
493 (syscall ("getrusage" int (* (struct rusage)))
495 (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
496 (slot (slot usage 'ru-utime) 'tv-usec))
497 (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
498 (slot (slot usage 'ru-stime) 'tv-usec))
499 (slot usage 'ru-maxrss)
500 (slot usage 'ru-ixrss)
501 (slot usage 'ru-idrss)
502 (slot usage 'ru-isrss)
503 (slot usage 'ru-minflt)
504 (slot usage 'ru-majflt)
505 (slot usage 'ru-nswap)
506 (slot usage 'ru-inblock)
507 (slot usage 'ru-oublock)
508 (slot usage 'ru-msgsnd)
509 (slot usage 'ru-msgrcv)
510 (slot usage 'ru-nsignals)
511 (slot usage 'ru-nvcsw)
512 (slot usage 'ru-nivcsw))
517 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
519 ;;; Perform the UNIX select(2) system call.
520 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
521 (defun unix-fast-select (num-descriptors
522 read-fds write-fds exception-fds
523 timeout-secs &optional (timeout-usecs 0))
524 (declare (type (integer 0 #.fd-setsize) num-descriptors)
525 (type (or (alien (* (struct fd-set))) null)
526 read-fds write-fds exception-fds)
527 (type (or null (unsigned-byte 31)) timeout-secs)
528 (type (unsigned-byte 31) timeout-usecs))
530 ;; (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
531 ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
532 (with-alien ((tv (struct timeval)))
534 (setf (slot tv 'tv-sec) timeout-secs)
535 (setf (slot tv 'tv-usec) timeout-usecs))
536 (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
537 (* (struct fd-set)) (* (struct timeval)))
538 num-descriptors read-fds write-fds exception-fds
539 (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
541 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
542 ;;; to happen on one of them or to time out.
543 (defmacro num-to-fd-set (fdset num)
546 (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
547 ,@(loop for index upfrom 1 below (/ fd-setsize
548 sb!vm:n-machine-word-bits)
549 collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
551 ,@(loop for index upfrom 0 below (/ fd-setsize
552 sb!vm:n-machine-word-bits)
553 collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
554 (ldb (byte sb!vm:n-machine-word-bits
555 ,(* index sb!vm:n-machine-word-bits))
558 (defmacro fd-set-to-num (nfds fdset)
559 `(if (<= ,nfds sb!vm:n-machine-word-bits)
560 (deref (slot ,fdset 'fds-bits) 0)
561 (+ ,@(loop for index upfrom 0 below (/ fd-setsize
562 sb!vm:n-machine-word-bits)
563 collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
564 ,(* index sb!vm:n-machine-word-bits))))))
566 ;;; Examine the sets of descriptors passed as arguments to see whether
567 ;;; they are ready for reading and writing. See the UNIX Programmer's
568 ;;; Manual for more information.
569 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
570 (declare (type (integer 0 #.fd-setsize) nfds)
571 (type unsigned-byte rdfds wrfds xpfds)
572 (type (or (unsigned-byte 31) null) to-secs)
573 (type (unsigned-byte 31) to-usecs)
574 (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
575 (with-alien ((tv (struct timeval))
576 (rdf (struct fd-set))
577 (wrf (struct fd-set))
578 (xpf (struct fd-set)))
580 (setf (slot tv 'tv-sec) to-secs)
581 (setf (slot tv 'tv-usec) to-usecs))
582 (num-to-fd-set rdf rdfds)
583 (num-to-fd-set wrf wrfds)
584 (num-to-fd-set xpf xpfds)
585 (macrolet ((frob (lispvar alienvar)
586 `(if (zerop ,lispvar)
588 (alien-sap (addr ,alienvar)))))
589 (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
590 (* (struct fd-set)) (* (struct timeval)))
592 (fd-set-to-num nfds rdf)
593 (fd-set-to-num nfds wrf)
594 (fd-set-to-num nfds xpf))
595 nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
596 (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
600 ;;; This is a structure defined in src/runtime/wrap.c, to look
601 ;;; basically like "struct stat" according to stat(2). It may not
602 ;;; actually correspond to the real in-memory stat structure that the
603 ;;; syscall uses, and that's OK. Linux in particular is packed full of
604 ;;; stat macros, and trying to keep Lisp code in correspondence with
605 ;;; it is more pain than it's worth, so we just let our C runtime
606 ;;; synthesize a nice consistent structure for us.
608 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
609 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
610 ;;; those. We don't actually access that field anywhere, though, so
611 ;;; until we can get 64 bit alien support it'll do. Also note that
612 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
613 ;;; quantity on Alpha. And FIXME: "No one would want a file length
614 ;;; longer than 32 bits anyway, right?":-|
615 (define-alien-type nil
618 (st-dev unsigned-int) ; would be dev-t in a real stat
620 (st-dev unsigned-long) ; this is _not_ a dev-t on mips
627 (st-rdev unsigned-int) ; would be dev-t in a real stat
629 (st-rdev unsigned-long) ; this is _not_ a dev-t on mips
631 (st-size unsigned-int) ; would be off-t in a real stat
634 (st-blksize unsigned-long)
635 (st-blocks unsigned-long)
640 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
641 ;;; family of Unix system calls
643 ;;; FIXME: I think this should probably not be INLINE. However, when
644 ;;; this was not inline, it seemed to cause memory corruption
645 ;;; problems. My first guess is that it's a bug in the FFI code, where
646 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
647 ;;; around a call to a function returning >10 values. But I didn't try
648 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
649 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
650 ;;; output in the not-inlined case and see whether there's a problem,
651 ;;; and maybe even find a fix..
652 (declaim (inline %extract-stat-results))
653 (defun %extract-stat-results (wrapped-stat)
654 (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
656 (slot wrapped-stat 'st-dev)
657 (slot wrapped-stat 'st-ino)
658 (slot wrapped-stat 'st-mode)
659 (slot wrapped-stat 'st-nlink)
660 (slot wrapped-stat 'st-uid)
661 (slot wrapped-stat 'st-gid)
662 (slot wrapped-stat 'st-rdev)
663 (slot wrapped-stat 'st-size)
664 (slot wrapped-stat 'st-atime)
665 (slot wrapped-stat 'st-mtime)
666 (slot wrapped-stat 'st-ctime)
667 (slot wrapped-stat 'st-blksize)
668 (slot wrapped-stat 'st-blocks)))
670 ;;; Unix system calls in the stat(2) family are handled by calls to
671 ;;; C-level wrapper functions which copy all the raw "struct stat"
672 ;;; slots into the system-independent wrapped_stat format.
673 ;;; stat(2) <-> stat_wrapper()
674 ;;; fstat(2) <-> fstat_wrapper()
675 ;;; lstat(2) <-> lstat_wrapper()
676 (defun unix-stat (name)
677 (declare (type unix-pathname name))
678 (with-alien ((buf (struct wrapped_stat)))
679 (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
680 (%extract-stat-results (addr buf))
682 (defun unix-lstat (name)
683 (declare (type unix-pathname name))
684 (with-alien ((buf (struct wrapped_stat)))
685 (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
686 (%extract-stat-results (addr buf))
688 (defun unix-fstat (fd)
689 (declare (type unix-fd fd))
690 (with-alien ((buf (struct wrapped_stat)))
691 (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
692 (%extract-stat-results (addr buf))
697 ;; the POSIX.4 structure for a time value. This is like a "struct
698 ;; timeval" but has nanoseconds instead of microseconds.
699 (define-alien-type nil
701 (tv-sec long) ; seconds
702 (tv-nsec long))) ; nanoseconds
704 ;; used by other time functions
705 (define-alien-type nil
707 (tm-sec int) ; Seconds. [0-60] (1 leap second)
708 (tm-min int) ; Minutes. [0-59]
709 (tm-hour int) ; Hours. [0-23]
710 (tm-mday int) ; Day. [1-31]
711 (tm-mon int) ; Month. [0-11]
712 (tm-year int) ; Year - 1900.
713 (tm-wday int) ; Day of week. [0-6]
714 (tm-yday int) ; Days in year. [0-365]
715 (tm-isdst int) ; DST. [-1/0/1]
716 (tm-gmtoff long) ; Seconds east of UTC.
717 (tm-zone c-string))) ; Timezone abbreviation.
719 (define-alien-routine get-timezone sb!alien:void
720 (when sb!alien:long :in)
721 (seconds-west sb!alien:int :out)
722 (daylight-savings-p sb!alien:boolean :out))
725 (defun nanosleep (secs nsecs)
726 (with-alien ((req (struct timespec))
727 (rem (struct timespec)))
728 (setf (slot req 'tv-sec) secs)
729 (setf (slot req 'tv-nsec) nsecs)
730 (loop while (eql sb!unix:eintr
732 (int-syscall ("nanosleep" (* (struct timespec))
733 (* (struct timespec)))
734 (addr req) (addr rem))))
735 do (rotatef req rem))))
737 (defun unix-get-seconds-west (secs)
738 (multiple-value-bind (ignore seconds dst) (get-timezone secs)
739 (declare (ignore ignore) (ignore dst))
744 ;;; Structure crudely representing a timezone. KLUDGE: This is
745 ;;; obsolete and should never be used.
746 (define-alien-type nil
748 (tz-minuteswest int) ; minutes west of Greenwich
749 (tz-dsttime int))) ; type of dst correction
751 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
752 ;;; and microseconds of the current time of day, the timezone (in
753 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
754 ;;; doesn't work, it returns NIL and the errno.
755 #!-sb-fluid (declaim (inline unix-gettimeofday))
756 (defun unix-gettimeofday ()
757 (with-alien ((tv (struct timeval))
758 (tz (struct timezone)))
759 (syscall* ("gettimeofday" (* (struct timeval))
760 (* (struct timezone)))
764 (slot tz 'tz-minuteswest)
765 (slot tz 'tz-dsttime))
770 ;; Type of the second argument to `getitimer' and
771 ;; the second and third arguments `setitimer'.
772 (define-alien-type nil
774 (it-interval (struct timeval)) ; timer interval
775 (it-value (struct timeval)))) ; current value
777 (defconstant itimer-real 0)
778 (defconstant itimer-virtual 1)
779 (defconstant itimer-prof 2)
782 (defun unix-getitimer (which)
783 "Unix-getitimer returns the INTERVAL and VALUE slots of one of
784 three system timers (:real :virtual or :profile). On success,
785 unix-getitimer returns 5 values,
786 T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
787 (declare (type (member :real :virtual :profile) which)
789 (unsigned-byte 29) (mod 1000000)
790 (unsigned-byte 29) (mod 1000000)))
791 (let ((which (ecase which
793 (:virtual itimer-virtual)
794 (:profile itimer-prof))))
795 (with-alien ((itv (struct itimerval)))
796 (syscall* ("getitimer" int (* (struct itimerval)))
798 (slot (slot itv 'it-interval) 'tv-sec)
799 (slot (slot itv 'it-interval) 'tv-usec)
800 (slot (slot itv 'it-value) 'tv-sec)
801 (slot (slot itv 'it-value) 'tv-usec))
802 which (alien-sap (addr itv))))))
805 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
806 " Unix-setitimer sets the INTERVAL and VALUE slots of one of
807 three system timers (:real :virtual or :profile). A SIGALRM signal
808 will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
809 when non-zero, is <seconds+microseconds> to be loaded each time
810 the timer expires. Setting INTERVAL and VALUE to zero disables
811 the timer. See the Unix man page for more details. On success,
812 unix-setitimer returns the old contents of the INTERVAL and VALUE
813 slots as in unix-getitimer."
814 (declare (type (member :real :virtual :profile) which)
815 (type (unsigned-byte 29) int-secs val-secs)
816 (type (integer 0 (1000000)) int-usec val-usec)
818 (unsigned-byte 29) (mod 1000000)
819 (unsigned-byte 29) (mod 1000000)))
820 (let ((which (ecase which
822 (:virtual itimer-virtual)
823 (:profile itimer-prof))))
824 (with-alien ((itvn (struct itimerval))
825 (itvo (struct itimerval)))
826 (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
827 (slot (slot itvn 'it-interval) 'tv-usec) int-usec
828 (slot (slot itvn 'it-value ) 'tv-sec ) val-secs
829 (slot (slot itvn 'it-value ) 'tv-usec) val-usec)
830 (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
832 (slot (slot itvo 'it-interval) 'tv-sec)
833 (slot (slot itvo 'it-interval) 'tv-usec)
834 (slot (slot itvo 'it-value) 'tv-sec)
835 (slot (slot itvo 'it-value) 'tv-usec))
836 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
839 ;;; FIXME: Many Unix error code definitions were deleted from the old
840 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
841 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
842 ;;; unused symbols in package exports, but if I don't, there are
843 ;;; enough of them all in one place here that they should probably be
846 ;;;; support routines for dealing with Unix pathnames
848 (defun unix-file-kind (name &optional check-for-links)
850 "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
851 (declare (simple-base-string name))
852 (multiple-value-bind (res dev ino mode)
853 (if check-for-links (unix-lstat name) (unix-stat name))
854 (declare (type (or fixnum null) mode)
857 (let ((kind (logand mode s-ifmt)))
858 (cond ((eql kind s-ifdir) :directory)
859 ((eql kind s-ifreg) :file)
861 ((eql kind s-iflnk) :link)
864 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
865 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
866 (defun relative-unix-pathname? (pathname)
867 (declare (type simple-string pathname))
868 (or (zerop (length pathname))
869 (char/= (schar pathname 0) #\/)))
871 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
872 ;;; already be a complete absolute Unix pathname, since at least in
873 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
874 ;;; paths have been converted to absolute paths, so we don't need to
875 ;;; try to handle any more generality than that.
876 (defun unix-resolve-links (pathname)
877 (declare (type simple-base-string pathname))
878 ;; KLUDGE: The Win32 platform doesn't have symbolic links, so
879 ;; short-cut this computation (and the check for being an absolute
881 #!+win32 (return-from unix-resolve-links pathname)
882 (aver (not (relative-unix-pathname? pathname)))
883 ;; KLUDGE: readlink and lstat are unreliable if given symlinks
884 ;; ending in slashes -- fix the issue here instead of waiting for
887 ;; but be careful! Must not strip the final slash from "/". (This
888 ;; adjustment might be a candidate for being transferred into the C
889 ;; code in a wrap_readlink() function, too.) CSR, 2006-01-18
890 (let ((len (length pathname)))
891 (when (and (> len 1) (eql #\/ (schar pathname (1- len))))
892 (setf pathname (subseq pathname 0 (1- len)))))
893 (/noshow "entering UNIX-RESOLVE-LINKS")
894 (loop with previous-pathnames = nil do
895 (/noshow pathname previous-pathnames)
896 (let ((link (unix-readlink pathname)))
898 ;; Unlike the old CMU CL code, we handle a broken symlink by
899 ;; returning the link itself. That way, CL:TRUENAME on a
900 ;; broken link returns the link itself, so that CL:DIRECTORY
901 ;; can return broken links, so that even without
902 ;; Unix-specific extensions to do interesting things with
903 ;; them, at least Lisp programs can see them and, if
904 ;; necessary, delete them. (This is handy e.g. when your
905 ;; managed-by-Lisp directories are visited by Emacs, which
906 ;; creates broken links as notes to itself.)
910 (unix-simplify-pathname
911 (if (relative-unix-pathname? link)
912 (let* ((dir-len (1+ (position #\/
915 (dir (subseq pathname 0 dir-len)))
917 (concatenate 'base-string dir link))
919 (if (unix-file-kind new-pathname)
920 (setf pathname new-pathname)
921 (return pathname)))))
922 ;; To generalize the principle that even if portable Lisp code
923 ;; can't do anything interesting with a broken symlink, at
924 ;; least it should be able to see and delete it, when we
925 ;; detect a cyclic link, we return the link itself. (So even
926 ;; though portable Lisp code can't do anything interesting
927 ;; with a cyclic link, at least it can see it and delete it.)
928 (if (member pathname previous-pathnames :test #'string=)
930 (push pathname previous-pathnames))))
932 (defun unix-simplify-pathname (src)
933 (declare (type simple-base-string src))
934 (let* ((src-len (length src))
935 (dst (make-string src-len :element-type 'base-char))
939 (macrolet ((deposit (char)
941 (setf (schar dst dst-len) ,char)
943 (dotimes (src-index src-len)
944 (let ((char (schar src src-index)))
945 (cond ((char= char #\.)
952 ;; either ``/...' or ``...//...'
954 (setf last-slash dst-len)
957 ;; either ``./...'' or ``..././...''
962 ((and last-slash (not (zerop last-slash)))
963 ;; There is something before this ..
964 (let ((prev-prev-slash
965 (position #\/ dst :end last-slash :from-end t)))
966 (cond ((and (= (+ (or prev-prev-slash 0) 2)
968 (char= (schar dst (- last-slash 2)) #\.)
969 (char= (schar dst (1- last-slash)) #\.))
970 ;; The something before this .. is another ..
972 (setf last-slash dst-len))
974 ;; The something is some directory or other.
979 (setf last-slash prev-prev-slash)))))
981 ;; There is nothing before this .., so we need to keep it
982 (setf last-slash dst-len)
985 ;; something other than a dot between slashes
986 (setf last-slash dst-len)
991 (setf (schar dst dst-len) char)
993 (when (and last-slash (not (zerop last-slash)))
996 ;; We've got ``foobar/.''
999 ;; We've got ``foobar/..''
1000 (unless (and (>= last-slash 2)
1001 (char= (schar dst (1- last-slash)) #\.)
1002 (char= (schar dst (- last-slash 2)) #\.)
1003 (or (= last-slash 2)
1004 (char= (schar dst (- last-slash 3)) #\/)))
1005 (let ((prev-prev-slash
1006 (position #\/ dst :end last-slash :from-end t)))
1008 (setf dst-len (1+ prev-prev-slash))
1009 (return-from unix-simplify-pathname
1010 (coerce "./" 'simple-base-string))))))))
1011 (cond ((zerop dst-len)
1013 ((= dst-len src-len)
1016 (subseq dst 0 dst-len)))))
1018 ;;;; A magic constant for wait3().
1020 ;;;; FIXME: This used to be defined in run-program.lisp as
1021 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
1022 ;;;; According to some of the man pages, the #o177 is part of the API
1023 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
1024 ;;;; the headers that may or may not be the same thing. To be
1025 ;;;; investigated. -- CSR, 2002-03-25
1026 (defconstant wstopped #o177)
1029 ;;;; stuff not yet found in the header files
1031 ;;;; Abandon all hope who enters here...
1033 ;;; not checked for linux...
1034 (defmacro fd-set (offset fd-set)
1035 (let ((word (gensym))
1037 `(multiple-value-bind (,word ,bit) (floor ,offset
1038 sb!vm:n-machine-word-bits)
1039 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1040 (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1042 (deref (slot ,fd-set 'fds-bits) ,word))))))
1044 ;;; not checked for linux...
1045 (defmacro fd-clr (offset fd-set)
1046 (let ((word (gensym))
1048 `(multiple-value-bind (,word ,bit) (floor ,offset
1049 sb!vm:n-machine-word-bits)
1050 (setf (deref (slot ,fd-set 'fds-bits) ,word)
1051 (logand (deref (slot ,fd-set 'fds-bits) ,word)
1052 (sb!kernel:word-logical-not
1053 (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1056 ;;; not checked for linux...
1057 (defmacro fd-isset (offset fd-set)
1058 (let ((word (gensym))
1060 `(multiple-value-bind (,word ,bit) (floor ,offset
1061 sb!vm:n-machine-word-bits)
1062 (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1064 ;;; not checked for linux...
1065 (defmacro fd-zero (fd-set)
1067 ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
1068 collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))