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