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