0.6.12.18:
[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 (def-alien-routine ("getenv" posix-getenv) c-string
94   "Return the environment string \"name=value\" which corresponds to NAME, or
95    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: Isn't there some way to use a C wrapper to avoid this hand-copying?
111 (defconstant +max-s-long+ 2147483647)
112 (defconstant +max-u-long+ 4294967295)
113 (def-alien-type quad-t #+nil long-long #-nil (array long 2))
114 (def-alien-type uquad-t #+nil unsigned-long-long
115                 #-nil (array unsigned-long 2))
116 (def-alien-type qaddr-t (* quad-t))
117 (def-alien-type daddr-t int)
118 (def-alien-type caddr-t (* char))
119 (def-alien-type swblk-t long)
120 (def-alien-type size-t unsigned-int)
121 (def-alien-type ssize-t int)
122
123 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp like this
124 ;;; unless we have extreme provocation. Reading directories is not extreme
125 ;;; enough, since it doesn't need to be blindingly fast: we can just implement
126 ;;; those functions in C as a wrapper layer.
127 (def-alien-type fd-mask unsigned-long)
128
129 (eval-when (:compile-toplevel :load-toplevel :execute)
130   (defconstant fd-setsize 1024))
131
132 (def-alien-type nil
133   (struct fd-set
134           (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
135
136 (/show0 "unix.lisp 304")
137 \f
138 \f
139 ;;;; fcntl.h
140 ;;;;
141 ;;;; POSIX Standard: 6.5 File Control Operations        <fcntl.h>
142
143 ;;; Open the file whose pathname is specified by PATH for reading
144 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
145 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
146 ;;;
147 ;;; If the O_CREAT flag is specified, then the file is created with a
148 ;;; permission of argument MODE if the file doesn't exist. An integer
149 ;;; file descriptor is returned by UNIX-OPEN.
150 (defun unix-open (path flags mode)
151   (declare (type unix-pathname path)
152            (type fixnum flags)
153            (type unix-file-mode mode))
154   (int-syscall ("open" c-string int int) path flags mode))
155
156 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
157 ;;; associated with it.
158 (/show0 "unix.lisp 391")
159 (defun unix-close (fd)
160   (declare (type unix-fd fd))
161   (void-syscall ("close" int) fd))
162 \f
163 ;;;; timebits.h
164
165 ;; A time value that is accurate to the nearest
166 ;; microsecond but also has a range of years.
167 (def-alien-type nil
168   (struct timeval
169           (tv-sec time-t)               ; seconds
170           (tv-usec time-t)))            ; and microseconds
171 \f
172 ;;;; resourcebits.h
173
174 (defconstant rusage_self 0) ; the calling process
175 (defconstant rusage_children -1) ; terminated child processes
176 (defconstant rusage_both -2)
177
178 (def-alien-type nil
179   (struct rusage
180     (ru-utime (struct timeval))     ; user time used
181     (ru-stime (struct timeval))     ; system time used.
182     (ru-maxrss long)                ; maximum resident set size (in kilobytes)
183     (ru-ixrss long)                 ; integral shared memory size
184     (ru-idrss long)                 ; integral unshared data size
185     (ru-isrss long)                 ; integral unshared stack size
186     (ru-minflt long)                ; page reclaims
187     (ru-majflt long)                ; page faults
188     (ru-nswap long)                 ; swaps
189     (ru-inblock long)               ; block input operations
190     (ru-oublock long)               ; block output operations
191     (ru-msgsnd long)                ; messages sent
192     (ru-msgrcv long)                ; messages received
193     (ru-nsignals long)              ; signals received
194     (ru-nvcsw long)                 ; voluntary context switches
195     (ru-nivcsw long)))              ; involuntary context switches
196 \f
197 ;;;; unistd.h
198
199 ;;; Given a file path (a string) and one of four constant modes,
200 ;;; return T if the file is accessible with that mode and NIL if not.
201 ;;; When NIL, also return an errno value with NIL which tells why the
202 ;;; file was not accessible.
203 ;;; 
204 ;;; The access modes are:
205 ;;;   r_ok     Read permission.
206 ;;;   w_ok     Write permission.
207 ;;;   x_ok     Execute permission.
208 ;;;   f_ok     Presence of file.
209 (defun unix-access (path mode)
210   (declare (type unix-pathname path)
211            (type (mod 8) mode))
212   (void-syscall ("access" c-string int) path mode))
213
214 ;;; values for the second argument to UNIX-LSEEK
215 (defconstant l_set 0) ; to set the file pointer
216 (defconstant l_incr 1) ; to increment the file pointer
217 (defconstant l_xtnd 2) ; to extend the file size
218
219 ;;; Accept a file descriptor and move the file pointer ahead
220 ;;; a certain offset for that file. WHENCE can be any of the following:
221 ;;;  L_SET     Set the file pointer.
222 ;;;  L_INCR    Increment the file pointer.
223 ;;;  L_XTND    Extend the file size.
224 (defun unix-lseek (fd offset whence)
225   (declare (type unix-fd fd)
226            (type (unsigned-byte 32) offset)
227            (type (integer 0 2) whence))
228   #!-(and x86 bsd)
229   (int-syscall ("lseek" int off-t int) fd offset whence)
230   ;; Need a 64-bit return value type for this. TBD. For now,
231   ;; don't use this with any 2G+ partitions.
232   #!+(and x86 bsd)
233   (int-syscall ("lseek" int unsigned-long unsigned-long int)
234                fd offset 0 whence))
235
236 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
237 ;;; It attempts to read len bytes from the device associated with fd
238 ;;; and store them into the buffer. It returns the actual number of
239 ;;; bytes read.
240 (defun unix-read (fd buf len)
241   (declare (type unix-fd fd)
242            (type (unsigned-byte 32) len))
243
244   (int-syscall ("read" int (* char) int) fd buf len))
245
246 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
247 ;;; length to write. It attempts to write len bytes to the device
248 ;;; associated with fd from the the buffer starting at offset. It returns
249 ;;; the actual number of bytes written.
250 (defun unix-write (fd buf offset len)
251   (declare (type unix-fd fd)
252            (type (unsigned-byte 32) offset len))
253   (int-syscall ("write" int (* char) int)
254                fd
255                (with-alien ((ptr (* char) (etypecase buf
256                                             ((simple-array * (*))
257                                              (vector-sap buf))
258                                             (system-area-pointer
259                                              buf))))
260                  (addr (deref ptr offset)))
261                len))
262
263 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
264 ;;; output pipe. Return two values: if no error occurred the first
265 ;;; value is the pipe to be read from and the second is can be written
266 ;;; to. If an error occurred the first value is NIL and the second the
267 ;;; unix error code.
268 (defun unix-pipe ()
269   (with-alien ((fds (array int 2)))
270     (syscall ("pipe" (* int))
271              (values (deref fds 0) (deref fds 1))
272              (cast fds (* int)))))
273
274 ;;; UNIX-CHDIR accepts a directory name and makes that the
275 ;;; current working directory.
276 (defun unix-chdir (path)
277   (declare (type unix-pathname path))
278   (void-syscall ("chdir" c-string) path))
279
280 (defun unix-mkdir (name mode)
281   (declare (type unix-pathname name)
282            (type unix-file-mode mode))
283   (void-syscall ("mkdir" c-string int) name mode))
284
285 ;;; Return the current directory as a SIMPLE-STRING.
286 (defun unix-current-directory ()
287   ;; FIXME: Gcc justifiably complains that getwd is dangerous and should
288   ;; not be used; especially with a hardwired 1024 buffer size, yecch.
289   ;; This should be rewritten to use getcwd(3), perhaps by writing
290   ;; a C service routine to do the actual call to getcwd(3) and check
291   ;; of return values.
292   (with-alien ((buf (array char 1024)))
293     (values (not (zerop (alien-funcall (extern-alien "getwd"
294                                                      (function int (* char)))
295                                        (cast buf (* char)))))
296             (cast buf c-string))))
297
298 ;;; Duplicate an existing file descriptor (given as the argument) and
299 ;;; return it. If FD is not a valid file descriptor, NIL and an error
300 ;;; number are returned.
301 (defun unix-dup (fd)
302   (declare (type unix-fd fd))
303   (int-syscall ("dup" int) fd))
304
305 ;;; Terminate the current process with an optional error code. If
306 ;;; successful, the call doesn't return. If unsuccessful, the call
307 ;;; returns NIL and an error number.
308 (defun unix-exit (&optional (code 0))
309   (declare (type (signed-byte 32) code))
310   (void-syscall ("exit" int) code))
311
312 ;;; Return the process id of the current process.
313 (def-alien-routine ("getpid" unix-getpid) int)
314
315 ;;; Return the real user-id associated with the current process.
316 (def-alien-routine ("getuid" unix-getuid) int)
317
318 ;;; Invoke readlink(2) on the file name specified by the simple string
319 ;;; PATH. Return up to two values: the contents of the symbolic link
320 ;;; if the call is successful, or NIL and the Unix error number.
321 (defun unix-readlink (path)
322   (declare (type unix-pathname path))
323   (with-alien ((buf (array char 1024)))
324     (syscall ("readlink" c-string (* char) int)
325              (let ((string (make-string result)))
326                (sb!kernel:copy-from-system-area
327                 (alien-sap buf) 0
328                 string (* sb!vm:vector-data-offset sb!vm:word-bits)
329                 (* result sb!vm:byte-bits))
330                string)
331              path (cast buf (* char)) 1024)))
332
333 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
334 ;;; name and the file if this is the last link. 
335 (defun unix-unlink (name)
336   (declare (type unix-pathname name))
337   (void-syscall ("unlink" c-string) name))
338
339 ;;; Set the tty-process-group for the unix file-descriptor FD to PGRP.
340 ;;; If not supplied, FD defaults to "/dev/tty".
341 (defun %set-tty-process-group (pgrp &optional fd)
342   (let ((old-sigs (unix-sigblock (sigmask :sigttou
343                                           :sigttin
344                                           :sigtstp
345                                           :sigchld))))
346     (declare (type (unsigned-byte 32) old-sigs))
347     (unwind-protect
348         (if fd
349             (tcsetpgrp fd pgrp)
350             (multiple-value-bind (tty-fd errno) (unix-open "/dev/tty" o_rdwr 0)
351               (cond (tty-fd
352                      (multiple-value-prog1
353                          (tcsetpgrp tty-fd pgrp)
354                        (unix-close tty-fd)))
355                     (t
356                      (values nil errno)))))
357       (unix-sigsetmask old-sigs))))
358
359 ;;; Return the name of the host machine as a string.
360 (defun unix-gethostname ()
361   (with-alien ((buf (array char 256)))
362     (syscall ("gethostname" (* char) int)
363              (cast buf c-string)
364              (cast buf (* char)) 256)))
365
366 ;;; Write the core image of the file described by FD to disk.
367 (defun unix-fsync (fd)
368   (declare (type unix-fd fd))
369   (void-syscall ("fsync" int) fd))
370 \f
371 ;;;; sys/ioctl.h
372
373 ;;; UNIX-IOCTL performs a variety of operations on open i/o
374 ;;; descriptors. See the UNIX Programmer's Manual for more
375 ;;; information.
376 (defun unix-ioctl (fd cmd arg)
377   (declare (type unix-fd fd)
378            (type (unsigned-byte 32) cmd))
379   (void-syscall ("ioctl" int unsigned-int (* char)) fd cmd arg))
380 \f
381 ;;;; sys/resource.h
382
383 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
384 ;;;
385 ;;; Like getrusage(2), but return only the system and user time,
386 ;;; and return the seconds and microseconds as separate values.
387 #!-sb-fluid (declaim (inline unix-fast-getrusage))
388 (defun unix-fast-getrusage (who)
389   (declare (values (member t)
390                    (unsigned-byte 31) (mod 1000000)
391                    (unsigned-byte 31) (mod 1000000)))
392   (with-alien ((usage (struct rusage)))
393     (syscall* ("getrusage" int (* (struct rusage)))
394               (values t
395                       (slot (slot usage 'ru-utime) 'tv-sec)
396                       (slot (slot usage 'ru-utime) 'tv-usec)
397                       (slot (slot usage 'ru-stime) 'tv-sec)
398                       (slot (slot usage 'ru-stime) 'tv-usec))
399               who (addr usage))))
400
401 ;;; Return information about the resource usage of the process
402 ;;; specified by WHO. WHO can be either the current process
403 ;;; (rusage_self) or all of the terminated child processes
404 ;;; (rusage_children). NIL and an error number is returned if the call
405 ;;; fails.
406 (defun unix-getrusage (who)
407   (with-alien ((usage (struct rusage)))
408     (syscall ("getrusage" int (* (struct rusage)))
409               (values t
410                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
411                          (slot (slot usage 'ru-utime) 'tv-usec))
412                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
413                          (slot (slot usage 'ru-stime) 'tv-usec))
414                       (slot usage 'ru-maxrss)
415                       (slot usage 'ru-ixrss)
416                       (slot usage 'ru-idrss)
417                       (slot usage 'ru-isrss)
418                       (slot usage 'ru-minflt)
419                       (slot usage 'ru-majflt)
420                       (slot usage 'ru-nswap)
421                       (slot usage 'ru-inblock)
422                       (slot usage 'ru-oublock)
423                       (slot usage 'ru-msgsnd)
424                       (slot usage 'ru-msgrcv)
425                       (slot usage 'ru-nsignals)
426                       (slot usage 'ru-nvcsw)
427                       (slot usage 'ru-nivcsw))
428               who (addr usage))))
429 \f
430 ;;;; sys/select.h
431
432 (defmacro unix-fast-select (num-descriptors
433                             read-fds write-fds exception-fds
434                             timeout-secs &optional (timeout-usecs 0))
435   #!+sb-doc
436   "Perform the UNIX select(2) system call."
437   (declare (type (integer 0 #.FD-SETSIZE) num-descriptors)
438            (type (or (alien (* (struct fd-set))) null)
439                  read-fds write-fds exception-fds)
440            (type (or null (unsigned-byte 31)) timeout-secs)
441            (type (unsigned-byte 31) timeout-usecs) )
442   ;; FIXME: CMU CL had
443   ;;   (optimize (speed 3) (safety 0) (inhibit-warnings 3))
444   ;; in the declarations above. If they're important, they should
445   ;; be in a declaration inside the LET expansion, not in the
446   ;; macro compile-time code.
447   `(let ((timeout-secs ,timeout-secs))
448      (with-alien ((tv (struct timeval)))
449        (when timeout-secs
450          (setf (slot tv 'tv-sec) timeout-secs)
451          (setf (slot tv 'tv-usec) ,timeout-usecs))
452        (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
453                      (* (struct fd-set)) (* (struct timeval)))
454                     ,num-descriptors ,read-fds ,write-fds ,exception-fds
455                     (if timeout-secs (alien-sap (addr tv)) (int-sap 0))))))
456
457 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
458 ;;; to happen on one of them or to time out.
459 (defmacro num-to-fd-set (fdset num)
460   `(if (fixnump ,num)
461        (progn
462          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
463          ,@(loop for index upfrom 1 below (/ fd-setsize 32)
464              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
465        (progn
466          ,@(loop for index upfrom 0 below (/ fd-setsize 32)
467              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
468                             (ldb (byte 32 ,(* index 32)) ,num))))))
469
470 (defmacro fd-set-to-num (nfds fdset)
471   `(if (<= ,nfds 32)
472        (deref (slot ,fdset 'fds-bits) 0)
473        (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
474               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
475                             ,(* index 32))))))
476
477 ;;; Examine the sets of descriptors passed as arguments to see whether
478 ;;; they are ready for reading and writing. See the UNIX Programmer's
479 ;;; Manual for more information.
480 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
481   (declare (type (integer 0 #.FD-SETSIZE) nfds)
482            (type unsigned-byte rdfds wrfds xpfds)
483            (type (or (unsigned-byte 31) null) to-secs)
484            (type (unsigned-byte 31) to-usecs)
485            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
486   (with-alien ((tv (struct timeval))
487                (rdf (struct fd-set))
488                (wrf (struct fd-set))
489                (xpf (struct fd-set)))
490     (when to-secs
491       (setf (slot tv 'tv-sec) to-secs)
492      (setf (slot tv 'tv-usec) to-usecs))
493     (num-to-fd-set rdf rdfds)
494     (num-to-fd-set wrf wrfds)
495     (num-to-fd-set xpf xpfds)
496     (macrolet ((frob (lispvar alienvar)
497                  `(if (zerop ,lispvar)
498                       (int-sap 0)
499                       (alien-sap (addr ,alienvar)))))
500       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
501                 (* (struct fd-set)) (* (struct timeval)))
502                (values result
503                        (fd-set-to-num nfds rdf)
504                        (fd-set-to-num nfds wrf)
505                        (fd-set-to-num nfds xpf))
506                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
507                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
508 \f
509 ;;;; sys/stat.h
510
511 ;;; This is a structure defined in src/runtime/wrap.c, to look
512 ;;; basically like "struct stat" according to stat(2). It may not
513 ;;; actually correspond to the real in-memory stat structure that the
514 ;;; syscall uses, and that's OK. Linux in particular is packed full of
515 ;;; stat macros, and trying to keep Lisp code in correspondence with
516 ;;; it is more pain than it's worth, so we just let our C runtime
517 ;;; synthesize a nice consistent structure for us.
518 ;;;
519 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
520 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn's support
521 ;;; those. We don't actually access that field anywhere, though, so
522 ;;; until we can get 64 bit alien support it'll do. Also note that
523 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
524 ;;; quantity on Alpha. And FIXME: "No one would want a file length
525 ;;; longer than 32 bits anyway, right?":-|
526 (def-alien-type nil
527   (struct wrapped_stat
528     (st-dev unsigned-long)              ; would be dev-t in a real stat
529     (st-ino ino-t)
530     (st-mode mode-t)
531     (st-nlink  nlink-t)
532     (st-uid  uid-t)
533     (st-gid  gid-t)
534     (st-rdev unsigned-long)             ; would be dev-t in a real stat
535     (st-size unsigned-long)             ; would be off-t in a real stat
536     (st-blksize unsigned-long)
537     (st-blocks unsigned-long)
538     (st-atime time-t)
539     (st-mtime time-t)
540     (st-ctime time-t)))
541
542 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
543 ;;; family of Unix system calls
544 ;;;
545 ;;; FIXME: I think this should probably not be INLINE. However, when
546 ;;; this was not inline, it seemed to cause memory corruption
547 ;;; problems. My first guess is that it's a bug in the FFI code, where
548 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
549 ;;; around a call to a function returning >10 values. But I didn't try
550 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
551 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
552 ;;; output in the not-inlined case and see whether there's a problem,
553 ;;; and maybe even find a fix..
554 (declaim (inline %extract-stat-results))
555 (defun %extract-stat-results (wrapped-stat)
556   (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
557   (values t
558           (slot wrapped-stat 'st-dev)
559           (slot wrapped-stat 'st-ino)
560           (slot wrapped-stat 'st-mode)
561           (slot wrapped-stat 'st-nlink)
562           (slot wrapped-stat 'st-uid)
563           (slot wrapped-stat 'st-gid)
564           (slot wrapped-stat 'st-rdev)
565           (slot wrapped-stat 'st-size)
566           (slot wrapped-stat 'st-atime)
567           (slot wrapped-stat 'st-mtime)
568           (slot wrapped-stat 'st-ctime)
569           (slot wrapped-stat 'st-blksize)
570           (slot wrapped-stat 'st-blocks)))
571
572 ;;; Unix system calls in the stat(2) family are handled by calls to
573 ;;; C-level wrapper functions which copy all the raw "struct stat"
574 ;;; slots into the system-independent wrapped_stat format.
575 ;;;    stat(2) <->  stat_wrapper()
576 ;;;   fstat(2) <-> fstat_wrapper()
577 ;;;   lstat(2) <-> lstat_wrapper()
578 (defun unix-stat (name)
579   (declare (type unix-pathname name))
580   (with-alien ((buf (struct wrapped_stat)))
581     (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
582              (%extract-stat-results (addr buf))
583              name (addr buf))))
584 (defun unix-lstat (name)
585   (declare (type unix-pathname name))
586   (with-alien ((buf (struct wrapped_stat)))
587     (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
588              (%extract-stat-results (addr buf))
589              name (addr buf))))
590 (defun unix-fstat (fd)
591   (declare (type unix-fd fd))
592   (with-alien ((buf (struct wrapped_stat)))
593     (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
594              (%extract-stat-results (addr buf))
595              fd (addr buf))))
596 \f
597 ;;;; time.h
598
599 ;; the POSIX.4 structure for a time value. This is like a "struct
600 ;; timeval" but has nanoseconds instead of microseconds.
601 (def-alien-type nil
602     (struct timespec
603             (tv-sec long)   ; seconds
604             (tv-nsec long))) ; nanoseconds
605
606 ;; used by other time functions
607 (def-alien-type nil
608     (struct tm
609             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
610             (tm-min int)   ; Minutes.   [0-59]
611             (tm-hour int)  ; Hours.     [0-23]
612             (tm-mday int)  ; Day.       [1-31]
613             (tm-mon int)   ; Month.     [0-11]
614             (tm-year int)  ; Year - 1900.
615             (tm-wday int)  ; Day of week. [0-6]
616             (tm-yday int)  ; Days in year. [0-365]
617             (tm-isdst int) ; DST.       [-1/0/1]
618             (tm-gmtoff long) ;  Seconds east of UTC.
619             (tm-zone c-string))) ; Timezone abbreviation.
620
621 (def-alien-routine get-timezone sb!c-call:void
622   (when sb!c-call:long :in)
623   (minutes-west sb!c-call:int :out)
624   (daylight-savings-p sb!alien:boolean :out))
625
626 (defun unix-get-minutes-west (secs)
627   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
628     (declare (ignore ignore) (ignore dst))
629     (values minutes)))
630
631 (defun unix-get-timezone (secs)
632   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
633     (declare (ignore ignore) (ignore minutes))
634     (values (deref unix-tzname (if dst 1 0)))))
635
636 \f
637 ;;;; sys/time.h
638
639 ;;; Structure crudely representing a timezone. KLUDGE: This is
640 ;;; obsolete and should never be used.
641 (def-alien-type nil
642   (struct timezone
643     (tz-minuteswest int)                ; minutes west of Greenwich
644     (tz-dsttime int)))                  ; type of dst correction
645
646 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
647 ;;; and microseconds of the current time of day, the timezone (in
648 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
649 ;;; doesn't work, it returns NIL and the errno.
650 #!-sb-fluid (declaim (inline unix-gettimeofday))
651 (defun unix-gettimeofday ()
652   (with-alien ((tv (struct timeval))
653                (tz (struct timezone)))
654     (syscall* ("gettimeofday" (* (struct timeval))
655                               (* (struct timezone)))
656               (values T
657                       (slot tv 'tv-sec)
658                       (slot tv 'tv-usec)
659                       (slot tz 'tz-minuteswest)
660                       (slot tz 'tz-dsttime))
661               (addr tv)
662               (addr tz))))
663 \f
664
665 (defconstant ENOENT 2) ; Unix error code, "No such file or directory"
666 (defconstant EINTR 4) ; Unix error code, "Interrupted system call"
667 (defconstant EIO 5) ; Unix error code, "I/O error"
668 (defconstant EEXIST 17) ; Unix error code, "File exists"
669 (defconstant ESPIPE 29) ; Unix error code, "Illegal seek"
670 (defconstant EWOULDBLOCK 11) ; Unix error code, "Operation would block"
671 ;;; FIXME: Many Unix error code definitions were deleted from the old
672 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
673 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
674 ;;; unused symbols in package exports, but if I don't, there are
675 ;;; enough of them all in one place here that they should probably be
676 ;;; removed by hand.
677 \f
678 \f
679 ;;;; support routines for dealing with Unix pathnames
680
681 (defun unix-file-kind (name &optional check-for-links)
682   #!+sb-doc
683   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
684   (declare (simple-string name))
685   (multiple-value-bind (res dev ino mode)
686       (if check-for-links (unix-lstat name) (unix-stat name))
687     (declare (type (or fixnum null) mode)
688              (ignore dev ino))
689     (when res
690       (let ((kind (logand mode s-ifmt)))
691         (cond ((eql kind s-ifdir) :directory)
692               ((eql kind s-ifreg) :file)
693               ((eql kind s-iflnk) :link)
694               (t :special))))))
695
696 (defun unix-maybe-prepend-current-directory (name)
697   (declare (simple-string name))
698   (if (and (> (length name) 0) (char= (schar name 0) #\/))
699       name
700       (multiple-value-bind (win dir) (unix-current-directory)
701         (if win
702             (concatenate 'simple-string dir "/" name)
703             name))))
704
705 ;;; Return the pathname with all symbolic links resolved.
706 ;;;
707 ;;; FIXME: Could we just use Unix readlink(2) instead?
708 (defun unix-resolve-links (pathname)
709   (declare (simple-string pathname))
710   (let ((len (length pathname))
711         (pending pathname))
712     (declare (fixnum len) (simple-string pending))
713     (if (zerop len)
714         pathname
715         (let ((result (make-string 1024 :initial-element (code-char 0)))
716               (fill-ptr 0)
717               (name-start 0))
718           (loop
719             (let* ((name-end (or (position #\/ pending :start name-start) len))
720                    (new-fill-ptr (+ fill-ptr (- name-end name-start))))
721               (replace result pending
722                        :start1 fill-ptr
723                        :end1 new-fill-ptr
724                        :start2 name-start
725                        :end2 name-end)
726               (let ((kind (unix-file-kind (if (zerop name-end) "/" result) t)))
727                 (unless kind (return nil))
728                 (cond ((eq kind :link)
729                        (multiple-value-bind (link err) (unix-readlink result)
730                          (unless link
731                            (error 'simple-file-error
732                                   :pathname pathname
733                                   :format-control
734                                   "~@<error reading link ~S: ~2I~_~A~:>"
735                                   :format-arguments (list (subseq
736                                                            result 0 fill-ptr)
737                                                           (strerror err))))
738                          (cond ((or (zerop (length link))
739                                     (char/= (schar link 0) #\/))
740                                 ;; It's a relative link.
741                                 (fill result (code-char 0)
742                                       :start fill-ptr
743                                       :end new-fill-ptr))
744                                ((string= result "/../" :end1 4)
745                                 ;; It's across the super-root.
746                                 (let ((slash (or (position #\/ result :start 4)
747                                                  0)))
748                                   (fill result (code-char 0)
749                                         :start slash
750                                         :end new-fill-ptr)
751                                   (setf fill-ptr slash)))
752                                (t
753                                 ;; It's absolute.
754                                 (and (> (length link) 0)
755                                      (char= (schar link 0) #\/))
756                                 (fill result (code-char 0) :end new-fill-ptr)
757                                 (setf fill-ptr 0)))
758                          (setf pending
759                                (if (= name-end len)
760                                    link
761                                    (concatenate 'simple-string
762                                                 link
763                                                 (subseq pending name-end))))
764                          (setf len (length pending))
765                          (setf name-start 0)))
766                       ((= name-end len)
767                        (return (subseq result 0 new-fill-ptr)))
768                       ((eq kind :directory)
769                        (setf (schar result new-fill-ptr) #\/)
770                        (setf fill-ptr (1+ new-fill-ptr))
771                        (setf name-start (1+ name-end)))
772                       (t
773                        (return nil))))))))))
774
775 (defun unix-simplify-pathname (src)
776   (declare (simple-string src))
777   (let* ((src-len (length src))
778          (dst (make-string src-len))
779          (dst-len 0)
780          (dots 0)
781          (last-slash nil))
782     (macrolet ((deposit (char)
783                         `(progn
784                            (setf (schar dst dst-len) ,char)
785                            (incf dst-len))))
786       (dotimes (src-index src-len)
787         (let ((char (schar src src-index)))
788           (cond ((char= char #\.)
789                  (when dots
790                    (incf dots))
791                  (deposit char))
792                 ((char= char #\/)
793                  (case dots
794                    (0
795                     ;; Either ``/...' or ``...//...'
796                     (unless last-slash
797                       (setf last-slash dst-len)
798                       (deposit char)))
799                    (1
800                     ;; Either ``./...'' or ``..././...''
801                     (decf dst-len))
802                    (2
803                     ;; We've found ..
804                     (cond
805                      ((and last-slash (not (zerop last-slash)))
806                       ;; There is something before this ..
807                       (let ((prev-prev-slash
808                              (position #\/ dst :end last-slash :from-end t)))
809                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
810                                        last-slash)
811                                     (char= (schar dst (- last-slash 2)) #\.)
812                                     (char= (schar dst (1- last-slash)) #\.))
813                                ;; The something before this .. is another ..
814                                (deposit char)
815                                (setf last-slash dst-len))
816                               (t
817                                ;; The something is some directory or other.
818                                (setf dst-len
819                                      (if prev-prev-slash
820                                          (1+ prev-prev-slash)
821                                          0))
822                                (setf last-slash prev-prev-slash)))))
823                      (t
824                       ;; There is nothing before this .., so we need to keep it
825                       (setf last-slash dst-len)
826                       (deposit char))))
827                    (t
828                     ;; Something other than a dot between slashes.
829                     (setf last-slash dst-len)
830                     (deposit char)))
831                  (setf dots 0))
832                 (t
833                  (setf dots nil)
834                  (setf (schar dst dst-len) char)
835                  (incf dst-len))))))
836     (when (and last-slash (not (zerop last-slash)))
837       (case dots
838         (1
839          ;; We've got  ``foobar/.''
840          (decf dst-len))
841         (2
842          ;; We've got ``foobar/..''
843          (unless (and (>= last-slash 2)
844                       (char= (schar dst (1- last-slash)) #\.)
845                       (char= (schar dst (- last-slash 2)) #\.)
846                       (or (= last-slash 2)
847                           (char= (schar dst (- last-slash 3)) #\/)))
848            (let ((prev-prev-slash
849                   (position #\/ dst :end last-slash :from-end t)))
850              (if prev-prev-slash
851                  (setf dst-len (1+ prev-prev-slash))
852                  (return-from unix-simplify-pathname "./")))))))
853     (cond ((zerop dst-len)
854            "./")
855           ((= dst-len src-len)
856            dst)
857           (t
858            (subseq dst 0 dst-len)))))
859 \f
860 ;;;; stuff not yet found in the header files
861 ;;;;
862 ;;;; Abandon all hope who enters here...
863
864 ;;; not checked for linux...
865 (defmacro fd-set (offset fd-set)
866   (let ((word (gensym))
867         (bit (gensym)))
868     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
869        (setf (deref (slot ,fd-set 'fds-bits) ,word)
870              (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
871                      (deref (slot ,fd-set 'fds-bits) ,word))))))
872
873 ;;; not checked for linux...
874 (defmacro fd-clr (offset fd-set)
875   (let ((word (gensym))
876         (bit (gensym)))
877     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
878        (setf (deref (slot ,fd-set 'fds-bits) ,word)
879              (logand (deref (slot ,fd-set 'fds-bits) ,word)
880                      (sb!kernel:32bit-logical-not
881                       (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
882
883 ;;; not checked for linux...
884 (defmacro fd-isset (offset fd-set)
885   (let ((word (gensym))
886         (bit (gensym)))
887     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
888        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
889
890 ;;; not checked for linux...
891 (defmacro fd-zero (fd-set)
892   `(progn
893      ,@(loop for index upfrom 0 below (/ fd-setsize 32)
894          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))
895
896