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