0.6.8.9:
[sbcl.git] / src / code / unix.lisp
1 ;;;; This file contains Unix support that SBCL needs to implement itself. It's
2 ;;;; derived from Peter Van Eynde's unix-glibc2.lisp for CMU CL, which was
3 ;;;; derived from CMU CL unix.lisp 1.56. But those files aspired to be complete
4 ;;;; Unix interfaces exported to the end user, while this file aims to be as
5 ;;;; simple as possible and is not intended for the end user.
6 ;;;;
7 ;;;; FIXME: The old CMU CL unix.lisp code was implemented as hand
8 ;;;; transcriptions from Unix headers into Lisp. It appears that this was as
9 ;;;; unmaintainable in practice as you'd expect in theory, so I really really
10 ;;;; don't want to do that. It'd be good to implement the various system calls
11 ;;;; as C code implemented using the Unix header files, and have their
12 ;;;; interface back to SBCL code be characterized by things like "32-bit-wide
13 ;;;; int" which are already in the interface between the runtime
14 ;;;; executable and the SBCL lisp code.
15
16 ;;;; This software is part of the SBCL system. See the README file for
17 ;;;; more information.
18 ;;;;
19 ;;;; This software is derived from the CMU CL system, which was
20 ;;;; written at Carnegie Mellon University and released into the
21 ;;;; public domain. The software is in the public domain and is
22 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
23 ;;;; files for more information.
24
25 (in-package "SB!UNIX")
26
27 (/show0 "unix.lisp 21")
28
29 ;;;; common machine-independent structures
30
31 (eval-when (:compile-toplevel :execute)
32
33 (defparameter *compiler-unix-errors* nil)
34
35 (/show0 "unix.lisp 29")
36
37 (sb!xc:defmacro def-unix-error (name number description)
38   `(progn
39      (defconstant ,name ,number ,description)
40      (eval-when (:compile-toplevel :execute)
41        (push (cons ,number ,description) *compiler-unix-errors*))))
42
43 (sb!xc:defmacro emit-unix-errors ()
44   (let* ((max (apply #'max (mapcar #'car *compiler-unix-errors*)))
45          (array (make-array (1+ max) :initial-element nil)))
46     (dolist (error *compiler-unix-errors*)
47       (setf (svref array (car error)) (cdr error)))
48     `(progn
49        (defvar *unix-errors* ',array)
50        (proclaim '(simple-vector *unix-errors*)))))
51
52 ) ; EVAL-WHEN
53
54 (defvar *unix-errors*)
55
56 (/show0 "unix.lisp 52")
57
58 (defmacro def-enum (inc cur &rest names)
59   (flet ((defform (name)
60            (prog1 (when name `(defconstant ,name ,cur))
61              (setf cur (funcall inc cur 1)))))
62     `(progn ,@(mapcar #'defform names))))
63 \f
64 ;;;; Lisp types used by syscalls
65
66 (deftype unix-pathname () 'simple-string)
67 (deftype unix-fd () `(integer 0 ,most-positive-fixnum))
68
69 (deftype unix-file-mode () '(unsigned-byte 32))
70 (deftype unix-pid () '(unsigned-byte 32))
71 (deftype unix-uid () '(unsigned-byte 32))
72 (deftype unix-gid () '(unsigned-byte 32))
73 \f
74 ;;;; system calls
75
76 (def-alien-routine ("os_get_errno" get-errno) integer
77   "Return the value of the C library pseudo-variable named \"errno\".")
78
79 (/show0 "unix.lisp 74")
80
81 (defun get-unix-error-msg (&optional (error-number (get-errno)))
82   #!+sb-doc
83   "Returns a string describing the error number which was returned by a
84   UNIX system call."
85   (declare (type integer error-number))
86   (if (array-in-bounds-p *unix-errors* error-number)
87       (svref *unix-errors* error-number)
88       (format nil "unknown error [~D]" error-number)))
89
90 ;;; FIXME: The various FOO-SYSCALL-BAR macros, and perhaps some other
91 ;;; macros in this file, are only used in this file, and could be
92 ;;; implemented using SB!XC:DEFMACRO wrapped in EVAL-WHEN.
93
94 (defmacro syscall ((name &rest arg-types) success-form &rest args)
95   `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
96                                 ,@args)))
97      (if (minusp result)
98          (values nil (get-errno))
99          ,success-form)))
100
101 ;;; Like SYSCALL, but if it fails, signal an error instead of returning error
102 ;;; codes. Should only be used for syscalls that will never really get an
103 ;;; error.
104 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
105   `(let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
106                                 ,@args)))
107      (if (minusp result)
108          (error "Syscall ~A failed: ~A" ,name (get-unix-error-msg))
109          ,success-form)))
110
111 (/show0 "unix.lisp 109")
112
113 (defmacro void-syscall ((name &rest arg-types) &rest args)
114   `(syscall (,name ,@arg-types) (values t 0) ,@args))
115
116 (defmacro int-syscall ((name &rest arg-types) &rest args)
117   `(syscall (,name ,@arg-types) (values result 0) ,@args))
118 \f
119 ;;; from stdio.h
120
121 (/show0 "unix.lisp 124")
122
123 (defun unix-rename (name1 name2)
124   #!+sb-doc
125   "Unix-rename renames the file with string name1 to the string
126    name2. NIL and an error code is returned if an error occurs."
127   (declare (type unix-pathname name1 name2))
128   (void-syscall ("rename" c-string c-string) name1 name2))
129 \f
130 ;;; from stdlib.h
131
132 (def-alien-routine ("getenv" posix-getenv) c-string
133   "Return the environment string \"name=value\" which corresponds to NAME, or
134    NIL if there is none."
135   (name c-string))
136 \f
137 ;;; from sys/types.h and gnu/types.h
138
139 (/show0 "unix.lisp 144")
140
141 (defconstant +max-s-long+ 2147483647)
142 (defconstant +max-u-long+ 4294967295)
143
144 ;;; FIXME: Isn't there some way to use a C wrapper to avoid this hand-copying?
145 (def-alien-type quad-t #+nil long-long #-nil (array long 2))
146 (def-alien-type uquad-t #+nil unsigned-long-long
147                 #-nil (array unsigned-long 2))
148 (def-alien-type qaddr-t (* quad-t))
149 (def-alien-type daddr-t int)
150 (def-alien-type caddr-t (* char))
151 (def-alien-type swblk-t long)
152 (def-alien-type size-t unsigned-int)
153 (def-alien-type time-t long)
154 (def-alien-type clock-t
155   #!+linux long
156   #!+bsd   unsigned-long)
157 (def-alien-type uid-t unsigned-int)
158 (def-alien-type ssize-t int)
159
160 (/show0 "unix.lisp 163")
161
162 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp like this
163 ;;; unless we have extreme provocation. Reading directories is not extreme
164 ;;; enough, since it doesn't need to be blindingly fast: we can just implement
165 ;;; those functions in C as a wrapper layer.
166 (def-alien-type fd-mask unsigned-long)
167 (/show0 "unix.lisp 171")
168
169 ;;; FIXME: Isn't there some way to use a C wrapper to avoid this hand-copying?
170 (def-alien-type dev-t
171   #!+linux uquad-t
172   #!+bsd   unsigned-int)
173 (def-alien-type uid-t unsigned-int)
174 (def-alien-type gid-t unsigned-int)
175 (def-alien-type ino-t
176   #!+linux unsigned-long
177   #!+bsd   unsigned-int)
178 (def-alien-type mode-t
179   #!+linux unsigned-int
180   #!+bsd   unsigned-short)
181 (def-alien-type nlink-t
182   #!+linux unsigned-int
183   #!+bsd   unsigned-short)
184 (/show0 "unix.lisp 190")
185
186 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp like this
187 ;;; unless we have extreme provocation. Reading directories is not extreme
188 ;;; enough, since it doesn't need to be blindingly fast: we can just implement
189 ;;; those functions in C as a wrapper layer.
190
191 (def-alien-type off-t
192   #!+linux long
193   #!+bsd   quad-t)
194
195 (/show0 "unix.lisp 195")
196 (defconstant fd-setsize 1024)
197 (/show0 "unix.lisp 217")
198
199 (def-alien-type nil
200   (struct fd-set
201           (fds-bits (array fd-mask #.(/ fd-setsize 32)))))
202
203 (/show0 "unix.lisp 223")
204 \f
205 ;;;; direntry.h
206
207 (def-alien-type nil
208   (struct direct
209     (d-ino long); inode number of entry
210     (d-off off-t)                       ; offset of next disk directory entry
211     (d-reclen unsigned-short)           ; length of this record
212     (d_type unsigned-char)
213     (d-name (array char 256))))         ; name must be no longer than this
214 (/show0 "unix.lisp 241")
215 \f
216 ;;;; dirent.h
217
218 ;;; operations on Unix directories
219
220 ;;;; FIXME: It might be really nice to implement these in C, so that
221 ;;;; we don't need to do horrible things like hand-copying the
222 ;;;; direntry struct slot types into an alien struct.
223
224 ;;; FIXME: DIRECTORY is an external symbol of package CL, so we should use some
225 ;;; other name for this low-level implementation type.
226 (defstruct directory
227   name
228   (dir-struct (required-argument) :type system-area-pointer))
229 (/show0 "unix.lisp 258")
230
231 (def!method print-object ((dir directory) stream)
232   (print-unreadable-object (dir stream :type t)
233     (prin1 (directory-name dir) stream)))
234
235 (/show0 "unix.lisp 264")
236 (defun open-dir (pathname)
237   (declare (type unix-pathname pathname))
238   (when (string= pathname "")
239     (setf pathname "."))
240   (let ((kind (unix-file-kind pathname)))
241     (case kind
242       (:directory
243        (let ((dir-struct
244               (alien-funcall (extern-alien "opendir"
245                                            (function system-area-pointer
246                                                      c-string))
247                              pathname)))
248          (if (zerop (sap-int dir-struct))
249              (values nil (get-errno))
250              (make-directory :name pathname :dir-struct dir-struct))))
251       ((nil)
252        (values nil enoent))
253       (t
254        (values nil enotdir)))))
255 (/show0 "unix.lisp 286")
256
257 (defun read-dir (dir)
258   (declare (type directory dir))
259   (let ((daddr (alien-funcall (extern-alien "readdir"
260                                             (function system-area-pointer
261                                                       system-area-pointer))
262                               (directory-dir-struct dir))))
263     (declare (type system-area-pointer daddr))
264     (if (zerop (sap-int daddr))
265         nil
266         (with-alien ((direct (* (struct direct)) daddr))
267           (values (cast (slot direct 'd-name) c-string)
268                   (slot direct 'd-ino))))))
269
270 (/show0 "unix.lisp 301")
271 (defun close-dir (dir)
272   (declare (type directory dir))
273   (alien-funcall (extern-alien "closedir"
274                                (function void system-area-pointer))
275                  (directory-dir-struct dir))
276   nil)
277
278 ;;; dlfcn.h -> in foreign.lisp
279
280 ;;; fcntl.h
281 ;;;
282 ;;; POSIX Standard: 6.5 File Control Operations <fcntl.h>
283
284 (/show0 "unix.lisp 318")
285 (defconstant r_ok 4 #!+sb-doc "Test for read permission")
286 (defconstant w_ok 2 #!+sb-doc "Test for write permission")
287 (defconstant x_ok 1 #!+sb-doc "Test for execute permission")
288 (defconstant f_ok 0 #!+sb-doc "Test for presence of file")
289
290 (/show0 "unix.lisp 352")
291 (defun unix-open (path flags mode)
292   #!+sb-doc
293   "Unix-open opens the file whose pathname is specified by path
294    for reading and/or writing as specified by the flags argument.
295    The flags argument can be:
296
297      o_rdonly   Read-only flag.
298      o_wronly   Write-only flag.
299      o_rdwr       Read-and-write flag.
300      o_append   Append flag.
301      o_creat     Create-if-nonexistent flag.
302      o_trunc     Truncate-to-size-0 flag.
303      o_excl       Error if the file allready exists
304      o_noctty   Don't assign controlling tty
305      o_ndelay   Non-blocking I/O
306      o_sync       Synchronous I/O
307      o_async     Asynchronous I/O
308
309    If the o_creat flag is specified, then the file is created with
310    a permission of argument mode if the file doesn't exist. An
311    integer file descriptor is returned by unix-open."
312   (declare (type unix-pathname path)
313            (type fixnum flags)
314            (type unix-file-mode mode))
315   (int-syscall ("open" c-string int int) path flags mode))
316
317 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
318 ;;; associated with it.
319 (/show0 "unix.lisp 391")
320 (defun unix-close (fd)
321   #!+sb-doc
322   "Unix-close takes an integer file descriptor as an argument and
323    closes the file associated with it. T is returned upon successful
324    completion, otherwise NIL and an error number."
325   (declare (type unix-fd fd))
326   (void-syscall ("close" int) fd))
327 \f
328 ;;; fcntlbits.h
329
330 (/show0 "unix.lisp 337")
331 (defconstant o_rdonly  0) ; read-only flag
332 (defconstant o_wronly  1) ; write-only flag
333 (defconstant o_rdwr    2) ; read/write flag
334 (defconstant o_accmode 3) ; access mode mask
335 (defconstant o_creat ; create-if-nonexistent flag (not fcntl)
336   #!+linux #o100
337   #!+bsd   #x0200)
338 (/show0 "unix.lisp 345")
339 (defconstant o_excl ; error if already exists (not fcntl)
340   #!+linux #o200
341   #!+bsd   #x0800)
342 (defconstant o_noctty ; Don't assign controlling tty. (not fcntl)
343   #!+linux #o400
344   #!+bsd   #x8000)
345 (defconstant o_trunc ; truncation flag (not fcntl)
346   #!+linux #o1000
347   #!+bsd   #x0400)
348 (defconstant o_append ; append flag
349   #!+linux #o2000
350   #!+bsd   #x0008)
351 (/show0 "unix.lisp 361")
352 \f
353 ;;;; timebits.h
354
355 ;; A time value that is accurate to the nearest
356 ;; microsecond but also has a range of years.
357 (def-alien-type nil
358   (struct timeval
359           (tv-sec time-t)               ; seconds
360           (tv-usec time-t)))            ; and microseconds
361 \f
362 ;;;; resourcebits.h
363
364 (defconstant rusage_self 0 #!+sb-doc "The calling process.")
365 (defconstant rusage_children -1 #!+sb-doc "Terminated child processes.")
366 (defconstant rusage_both -2)
367
368 (def-alien-type nil
369   (struct rusage
370     (ru-utime (struct timeval))         ; user time used
371     (ru-stime (struct timeval))         ; system time used.
372     (ru-maxrss long)                ; Maximum resident set size (in kilobytes)
373     (ru-ixrss long)                     ; integral shared memory size
374     (ru-idrss long)                     ; integral unshared data size
375     (ru-isrss long)                     ; integral unshared stack size
376     (ru-minflt long)                    ; page reclaims
377     (ru-majflt long)                    ; page faults
378     (ru-nswap long)                     ; swaps
379     (ru-inblock long)                   ; block input operations
380     (ru-oublock long)                   ; block output operations
381     (ru-msgsnd long)                    ; messages sent
382     (ru-msgrcv long)                    ; messages received
383     (ru-nsignals long)                  ; signals received
384     (ru-nvcsw long)                     ; voluntary context switches
385     (ru-nivcsw long)))                  ; involuntary context switches
386 \f
387 ;;;; statbuf.h
388
389 ;;; FIXME: This should go into C code so that we don't need to hand-copy
390 ;;; it from header files.
391 #!+Linux
392 (def-alien-type nil
393   (struct stat
394     (st-dev dev-t)
395     (st-pad1 unsigned-short)
396     (st-ino ino-t)
397     (st-mode mode-t)
398     (st-nlink  nlink-t)
399     (st-uid  uid-t)
400     (st-gid  gid-t)
401     (st-rdev dev-t)
402     (st-pad2  unsigned-short)
403     (st-size off-t)
404     (st-blksize unsigned-long)
405     (st-blocks unsigned-long)
406     (st-atime time-t)
407     (unused-1 unsigned-long)
408     (st-mtime time-t)
409     (unused-2 unsigned-long)
410     (st-ctime time-t)
411     (unused-3 unsigned-long)
412     (unused-4 unsigned-long)
413     (unused-5 unsigned-long)))
414
415 #!+bsd
416 (def-alien-type nil
417   (struct timespec-t
418     (tv-sec long)
419     (tv-nsec long)))
420
421 #!+bsd
422 (def-alien-type nil
423   (struct stat
424     (st-dev dev-t)
425     (st-ino ino-t)
426     (st-mode mode-t)
427     (st-nlink nlink-t)
428     (st-uid uid-t)
429     (st-gid gid-t)
430     (st-rdev dev-t)
431     (st-atime (struct timespec-t))
432     (st-mtime (struct timespec-t))
433     (st-ctime (struct timespec-t))
434     (st-size    unsigned-long)          ; really quad
435     (st-sizeh   unsigned-long)          ;
436     (st-blocks  unsigned-long)          ; really quad
437     (st-blocksh unsigned-long)
438     (st-blksize unsigned-long)
439     (st-flags   unsigned-long)
440     (st-gen     unsigned-long)
441     (st-lspare  long)
442     (st-qspare (array long 4))
443     ))
444
445 ;; encoding of the file mode
446
447 (defconstant s-ifmt   #o0170000 #!+sb-doc "These bits determine file type.")
448
449 ;; file types
450 (defconstant s-ififo  #o0010000 #!+sb-doc "FIFO")
451 (defconstant s-ifchr  #o0020000 #!+sb-doc "Character device")
452 (defconstant s-ifdir  #o0040000 #!+sb-doc "Directory")
453 (defconstant s-ifblk  #o0060000 #!+sb-doc "Block device")
454 (defconstant s-ifreg  #o0100000 #!+sb-doc "Regular file")
455
456 ;; These don't actually exist on System V, but having them doesn't hurt.
457 (defconstant s-iflnk  #o0120000 #!+sb-doc "Symbolic link.")
458 (defconstant s-ifsock #o0140000 #!+sb-doc "Socket.")
459 \f
460 ;;;; unistd.h
461
462 ;;; values for the second argument to access
463 (defun unix-access (path mode)
464   #!+sb-doc
465   "Given a file path (a string) and one of four constant modes,
466    UNIX-ACCESS returns T if the file is accessible with that
467    mode and NIL if not. It also returns an errno value with
468    NIL which determines why the file was not accessible.
469
470    The access modes are:
471         r_ok     Read permission.
472         w_ok     Write permission.
473         x_ok     Execute permission.
474         f_ok     Presence of file."
475   (declare (type unix-pathname path)
476            (type (mod 8) mode))
477   (void-syscall ("access" c-string int) path mode))
478
479 (defconstant l_set 0 #!+sb-doc "set the file pointer")
480 (defconstant l_incr 1 #!+sb-doc "increment the file pointer")
481 (defconstant l_xtnd 2 #!+sb-doc "extend the file size")
482
483 (defun unix-lseek (fd offset whence)
484   #!+sb-doc
485   "Unix-lseek accepts a file descriptor and moves the file pointer ahead
486    a certain offset for that file. Whence can be any of the following:
487
488    l_set        Set the file pointer.
489    l_incr       Increment the file pointer.
490    l_xtnd       Extend the file size.
491   "
492   (declare (type unix-fd fd)
493            (type (unsigned-byte 32) offset)
494            (type (integer 0 2) whence))
495   #!-(and x86 bsd)
496   (int-syscall ("lseek" int off-t int) fd offset whence)
497   ;; Need a 64-bit return value type for this. TBD. For now,
498   ;; don't use this with any 2G+ partitions.
499   #!+(and x86 bsd)
500   (int-syscall ("lseek" int unsigned-long unsigned-long int)
501                fd offset 0 whence))
502
503 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
504 ;;; It attempts to read len bytes from the device associated with fd
505 ;;; and store them into the buffer. It returns the actual number of
506 ;;; bytes read.
507 (defun unix-read (fd buf len)
508   #!+sb-doc
509   "Unix-read attempts to read from the file described by fd into
510    the buffer buf until it is full. Len is the length of the buffer.
511    The number of bytes actually read is returned or NIL and an error
512    number if an error occurred."
513   (declare (type unix-fd fd)
514            (type (unsigned-byte 32) len))
515
516   (int-syscall ("read" int (* char) int) fd buf len))
517
518 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
519 ;;; length to write. It attempts to write len bytes to the device
520 ;;; associated with fd from the the buffer starting at offset. It returns
521 ;;; the actual number of bytes written.
522 (defun unix-write (fd buf offset len)
523   #!+sb-doc
524   "Unix-write attempts to write a character buffer (buf) of length
525    len to the file described by the file descriptor fd. NIL and an
526    error is returned if the call is unsuccessful."
527   (declare (type unix-fd fd)
528            (type (unsigned-byte 32) offset len))
529   (int-syscall ("write" int (* char) int)
530                fd
531                (with-alien ((ptr (* char) (etypecase buf
532                                             ((simple-array * (*))
533                                              (vector-sap buf))
534                                             (system-area-pointer
535                                              buf))))
536                  (addr (deref ptr offset)))
537                len))
538
539 (defun unix-pipe ()
540   #!+sb-doc
541   "Unix-pipe sets up a unix-piping mechanism consisting of
542   an input pipe and an output pipe.  Unix-Pipe returns two
543   values: if no error occurred the first value is the pipe
544   to be read from and the second is can be written to.  If
545   an error occurred the first value is NIL and the second
546   the unix error code."
547   (with-alien ((fds (array int 2)))
548     (syscall ("pipe" (* int))
549              (values (deref fds 0) (deref fds 1))
550              (cast fds (* int)))))
551
552 ;;; UNIX-CHDIR accepts a directory name and makes that the
553 ;;; current working directory.
554 (defun unix-chdir (path)
555   #!+sb-doc
556   "Given a file path string, unix-chdir changes the current working
557    directory to the one specified."
558   (declare (type unix-pathname path))
559   (void-syscall ("chdir" c-string) path))
560
561 (defun unix-current-directory ()
562   #!+sb-doc
563   "Return the current directory as a SIMPLE-STRING."
564   ;; FIXME: Gcc justifiably complains that getwd is dangerous and should
565   ;; not be used; especially with a hardwired 1024 buffer size, yecch.
566   ;; This should be rewritten to use getcwd(3), perhaps by writing
567   ;; a C service routine to do the actual call to getcwd(3) and check
568   ;; of return values.
569   (with-alien ((buf (array char 1024)))
570     (values (not (zerop (alien-funcall (extern-alien "getwd"
571                                                      (function int (* char)))
572                                        (cast buf (* char)))))
573             (cast buf c-string))))
574
575 (defun unix-dup (fd)
576   #!+sb-doc
577   "Unix-dup duplicates an existing file descriptor (given as the
578    argument) and returns it.  If FD is not a valid file descriptor, NIL
579    and an error number are returned."
580   (declare (type unix-fd fd))
581   (int-syscall ("dup" int) fd))
582
583 ;;; UNIX-EXIT terminates a program.
584 (defun unix-exit (&optional (code 0))
585   #!+sb-doc
586   "Unix-exit terminates the current process with an optional
587    error code. If successful, the call doesn't return. If
588    unsuccessful, the call returns NIL and an error number."
589   (declare (type (signed-byte 32) code))
590   (void-syscall ("exit" int) code))
591
592 (def-alien-routine ("getpid" unix-getpid) int
593   #!+sb-doc
594   "Unix-getpid returns the process-id of the current process.")
595
596 (def-alien-routine ("getuid" unix-getuid) int
597   #!+sb-doc
598   "Unix-getuid returns the real user-id associated with the
599    current process.")
600
601 (defun unix-readlink (path)
602   #!+sb-doc
603   "Unix-readlink invokes the readlink system call on the file name
604   specified by the simple string path. It returns up to two values:
605   the contents of the symbolic link if the call is successful, or
606   NIL and the Unix error number."
607   (declare (type unix-pathname path))
608   (with-alien ((buf (array char 1024)))
609     (syscall ("readlink" c-string (* char) int)
610              (let ((string (make-string result)))
611                (sb!kernel:copy-from-system-area
612                 (alien-sap buf) 0
613                 string (* sb!vm:vector-data-offset sb!vm:word-bits)
614                 (* result sb!vm:byte-bits))
615                string)
616              path (cast buf (* char)) 1024)))
617
618 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
619 ;;; name and the file if this is the last link.
620 (defun unix-unlink (name)
621   #!+sb-doc
622   "Unix-unlink removes the directory entry for the named file.
623    NIL and an error code is returned if the call fails."
624   (declare (type unix-pathname name))
625   (void-syscall ("unlink" c-string) name))
626
627 (defun %set-tty-process-group (pgrp &optional fd)
628   #!+sb-doc
629   "Set the tty-process-group for the unix file-descriptor FD to PGRP. If not
630   supplied, FD defaults to /dev/tty."
631   (let ((old-sigs (unix-sigblock (sigmask :sigttou
632                                           :sigttin
633                                           :sigtstp
634                                           :sigchld))))
635     (declare (type (unsigned-byte 32) old-sigs))
636     (unwind-protect
637         (if fd
638             (tcsetpgrp fd pgrp)
639             (multiple-value-bind (tty-fd errno) (unix-open "/dev/tty" o_rdwr 0)
640               (cond (tty-fd
641                      (multiple-value-prog1
642                          (tcsetpgrp tty-fd pgrp)
643                        (unix-close tty-fd)))
644                     (t
645                      (values nil errno)))))
646       (unix-sigsetmask old-sigs))))
647
648 (defun unix-gethostname ()
649   #!+sb-doc
650   "Unix-gethostname returns the name of the host machine as a string."
651   (with-alien ((buf (array char 256)))
652     (syscall ("gethostname" (* char) int)
653              (cast buf c-string)
654              (cast buf (* char)) 256)))
655
656 (defun unix-fsync (fd)
657   #!+sb-doc
658   "Unix-fsync writes the core image of the file described by
659    fd to disk."
660   (declare (type unix-fd fd))
661   (void-syscall ("fsync" int) fd))
662 \f
663 ;;;; sys/ioctl.h
664
665 (defun unix-ioctl (fd cmd arg)
666   #!+sb-doc
667   "Unix-ioctl performs a variety of operations on open i/o
668    descriptors.  See the UNIX Programmer's Manual for more
669    information."
670   (declare (type unix-fd fd)
671            (type (unsigned-byte 32) cmd))
672   (void-syscall ("ioctl" int unsigned-int (* char)) fd cmd arg))
673 \f
674 ;;;; sys/resource.h
675
676 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
677 #!-sb-fluid (declaim (inline unix-fast-getrusage))
678 (defun unix-fast-getrusage (who)
679   #!+sb-doc
680   "Like call getrusage, but return only the system and user time, and returns
681    the seconds and microseconds as separate values."
682   (declare (values (member t)
683                    (unsigned-byte 31) (mod 1000000)
684                    (unsigned-byte 31) (mod 1000000)))
685   (with-alien ((usage (struct rusage)))
686     (syscall* ("getrusage" int (* (struct rusage)))
687               (values t
688                       (slot (slot usage 'ru-utime) 'tv-sec)
689                       (slot (slot usage 'ru-utime) 'tv-usec)
690                       (slot (slot usage 'ru-stime) 'tv-sec)
691                       (slot (slot usage 'ru-stime) 'tv-usec))
692               who (addr usage))))
693
694 (defun unix-getrusage (who)
695   #!+sb-doc
696   "Unix-getrusage returns information about the resource usage
697    of the process specified by who. Who can be either the
698    current process (rusage_self) or all of the terminated
699    child processes (rusage_children). NIL and an error number
700    is returned if the call fails."
701   (with-alien ((usage (struct rusage)))
702     (syscall ("getrusage" int (* (struct rusage)))
703               (values t
704                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
705                          (slot (slot usage 'ru-utime) 'tv-usec))
706                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
707                          (slot (slot usage 'ru-stime) 'tv-usec))
708                       (slot usage 'ru-maxrss)
709                       (slot usage 'ru-ixrss)
710                       (slot usage 'ru-idrss)
711                       (slot usage 'ru-isrss)
712                       (slot usage 'ru-minflt)
713                       (slot usage 'ru-majflt)
714                       (slot usage 'ru-nswap)
715                       (slot usage 'ru-inblock)
716                       (slot usage 'ru-oublock)
717                       (slot usage 'ru-msgsnd)
718                       (slot usage 'ru-msgrcv)
719                       (slot usage 'ru-nsignals)
720                       (slot usage 'ru-nvcsw)
721                       (slot usage 'ru-nivcsw))
722               who (addr usage))))
723
724 \f
725 ;;;; sys/select.h
726
727 (defmacro unix-fast-select (num-descriptors
728                             read-fds write-fds exception-fds
729                             timeout-secs &optional (timeout-usecs 0))
730   #!+sb-doc
731   "Perform the UNIX select(2) system call."
732   (declare (type (integer 0 #.FD-SETSIZE) num-descriptors)
733            (type (or (alien (* (struct fd-set))) null)
734                  read-fds write-fds exception-fds)
735            (type (or null (unsigned-byte 31)) timeout-secs)
736            (type (unsigned-byte 31) timeout-usecs) )
737   ;; FIXME: CMU CL had
738   ;;   (optimize (speed 3) (safety 0) (inhibit-warnings 3))
739   ;; in the declarations above. If they're important, they should
740   ;; be in a declaration inside the LET expansion, not in the
741   ;; macro compile-time code.
742   `(let ((timeout-secs ,timeout-secs))
743      (with-alien ((tv (struct timeval)))
744        (when timeout-secs
745          (setf (slot tv 'tv-sec) timeout-secs)
746          (setf (slot tv 'tv-usec) ,timeout-usecs))
747        (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
748                      (* (struct fd-set)) (* (struct timeval)))
749                     ,num-descriptors ,read-fds ,write-fds ,exception-fds
750                     (if timeout-secs (alien-sap (addr tv)) (int-sap 0))))))
751
752 ;;; Unix-select accepts sets of file descriptors and waits for an event
753 ;;; to happen on one of them or to time out.
754
755 (defmacro num-to-fd-set (fdset num)
756   `(if (fixnump ,num)
757        (progn
758          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
759          ,@(loop for index upfrom 1 below (/ fd-setsize 32)
760              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
761        (progn
762          ,@(loop for index upfrom 0 below (/ fd-setsize 32)
763              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
764                             (ldb (byte 32 ,(* index 32)) ,num))))))
765
766 (defmacro fd-set-to-num (nfds fdset)
767   `(if (<= ,nfds 32)
768        (deref (slot ,fdset 'fds-bits) 0)
769        (+ ,@(loop for index upfrom 0 below (/ fd-setsize 32)
770               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
771                             ,(* index 32))))))
772
773 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
774   #!+sb-doc
775   "Unix-select examines the sets of descriptors passed as arguments
776    to see whether they are ready for reading and writing. See the UNIX
777    Programmers Manual for more information."
778   (declare (type (integer 0 #.FD-SETSIZE) nfds)
779            (type unsigned-byte rdfds wrfds xpfds)
780            (type (or (unsigned-byte 31) null) to-secs)
781            (type (unsigned-byte 31) to-usecs)
782            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
783   (with-alien ((tv (struct timeval))
784                (rdf (struct fd-set))
785                (wrf (struct fd-set))
786                (xpf (struct fd-set)))
787     (when to-secs
788       (setf (slot tv 'tv-sec) to-secs)
789       (setf (slot tv 'tv-usec) to-usecs))
790     (num-to-fd-set rdf rdfds)
791     (num-to-fd-set wrf wrfds)
792     (num-to-fd-set xpf xpfds)
793     (macrolet ((frob (lispvar alienvar)
794                  `(if (zerop ,lispvar)
795                       (int-sap 0)
796                       (alien-sap (addr ,alienvar)))))
797       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
798                 (* (struct fd-set)) (* (struct timeval)))
799                (values result
800                        (fd-set-to-num nfds rdf)
801                        (fd-set-to-num nfds wrf)
802                        (fd-set-to-num nfds xpf))
803                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
804                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
805 \f
806 ;;;; sys/stat.h
807
808 ;;; FIXME: This is only used in this file, and needn't be in target Lisp
809 ;;; runtime. It's also unclear why it needs to be a macro instead of a
810 ;;; function. Perhaps it should become a FLET.
811 (defmacro extract-stat-results (buf)
812   `(values T
813            #!+bsd
814            (slot ,buf 'st-dev)
815            #!+linux
816            (+ (deref (slot ,buf 'st-dev) 0)
817               (* (+ +max-u-long+  1)
818                  (deref (slot ,buf 'st-dev) 1)))   ;;; let's hope this works..
819            (slot ,buf 'st-ino)
820            (slot ,buf 'st-mode)
821            (slot ,buf 'st-nlink)
822            (slot ,buf 'st-uid)
823            (slot ,buf 'st-gid)
824            #!+bsd
825            (slot ,buf 'st-rdev)
826            #!+linux
827            (+ (deref (slot ,buf 'st-rdev) 0)
828               (* (+ +max-u-long+  1)
829                  (deref (slot ,buf 'st-rdev) 1)))   ;;; let's hope this works..
830            #!+linux (slot ,buf 'st-size)
831            #!+bsd
832            (+ (slot ,buf 'st-size)
833               (* (+ +max-u-long+ 1)
834                  (slot ,buf 'st-sizeh)))
835            #!+linux (slot ,buf 'st-atime)
836            #!+bsd   (slot (slot ,buf 'st-atime) 'tv-sec)
837            #!+linux (slot ,buf 'st-mtime)
838            #!+bsd   (slot (slot ,buf 'st-mtime) 'tv-sec)
839            #!+linux (slot ,buf 'st-ctime)
840            #!+bsd   (slot (slot ,buf 'st-ctime) 'tv-sec)
841            (slot ,buf 'st-blksize)
842            #!+linux (slot ,buf 'st-blocks)
843            #!+bsd
844            (+ (slot ,buf 'st-blocks)
845               (* (+ +max-u-long+ 1)
846                  (slot ,buf 'st-blocksh)))
847            ))
848
849 (defun unix-stat (name)
850   #!+sb-doc
851   "Unix-stat retrieves information about the specified
852    file returning them in the form of multiple values.
853    See the UNIX Programmer's Manual for a description
854    of the values returned. If the call fails, then NIL
855    and an error number is returned instead."
856   (declare (type unix-pathname name))
857   (when (string= name "")
858     (setf name "."))
859   (with-alien ((buf (struct stat)))
860     (syscall ("stat" c-string (* (struct stat)))
861              (extract-stat-results buf)
862              name (addr buf))))
863
864 (defun unix-fstat (fd)
865   #!+sb-doc
866   "Unix-fstat is similar to unix-stat except the file is specified
867    by the file descriptor fd."
868   (declare (type unix-fd fd))
869   (with-alien ((buf (struct stat)))
870     (syscall ("fstat" int (* (struct stat)))
871              (extract-stat-results buf)
872              fd (addr buf))))
873
874 (defun unix-lstat (name)
875   #!+sb-doc
876   "Unix-lstat is similar to unix-stat except the specified
877    file must be a symbolic link."
878   (declare (type unix-pathname name))
879   (with-alien ((buf (struct stat)))
880     (syscall ("lstat" c-string (* (struct stat)))
881              (extract-stat-results buf)
882              name (addr buf))))
883
884 ;;; UNIX-MKDIR accepts a name and a mode and attempts to create the
885 ;;; corresponding directory with mode mode.
886 (defun unix-mkdir (name mode)
887   #!+sb-doc
888   "Unix-mkdir creates a new directory with the specified name and mode.
889    (Same as those for unix-fchmod.)  It returns T upon success, otherwise
890    NIL and an error number."
891   (declare (type unix-pathname name)
892            (type unix-file-mode mode))
893   (void-syscall ("mkdir" c-string int) name mode))
894 \f
895 ;;;; time.h
896
897 ;; POSIX.4 structure for a time value. This is like a `struct timeval' but
898 ;; has nanoseconds instead of microseconds.
899
900 (def-alien-type nil
901     (struct timespec
902             (tv-sec long)   ;Seconds
903             (tv-nsec long))) ;Nanoseconds
904
905 ;; Used by other time functions.
906 (def-alien-type nil
907     (struct tm
908             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
909             (tm-min int)   ; Minutes.   [0-59]
910             (tm-hour int)  ; Hours.     [0-23]
911             (tm-mday int)  ; Day.               [1-31]
912             (tm-mon int)   ;  Month.    [0-11]
913             (tm-year int)  ; Year       - 1900.
914             (tm-wday int)  ; Day of week.       [0-6]
915             (tm-yday int)  ; Days in year.[0-365]
916             (tm-isdst int) ;  DST.              [-1/0/1]
917             (tm-gmtoff long)    ;  Seconds east of UTC.
918             (tm-zone c-string)))        ; Timezone abbreviation.
919
920 (def-alien-routine get-timezone sb!c-call:void
921   (when sb!c-call:long :in)
922   (minutes-west sb!c-call:int :out)
923   (daylight-savings-p sb!alien:boolean :out))
924
925 (defun unix-get-minutes-west (secs)
926   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
927     (declare (ignore ignore) (ignore dst))
928     (values minutes)))
929
930 (defun unix-get-timezone (secs)
931   (multiple-value-bind (ignore minutes dst) (get-timezone secs)
932     (declare (ignore ignore) (ignore minutes))
933     (values (deref unix-tzname (if dst 1 0)))))
934
935 \f
936 ;;;; sys/time.h
937
938 ;;; Structure crudely representing a timezone. KLUDGE: This is
939 ;;; obsolete and should never be used.
940 (def-alien-type nil
941   (struct timezone
942     (tz-minuteswest int)                ; minutes west of Greenwich
943     (tz-dsttime int)))                  ; type of dst correction
944
945 #!-sb-fluid (declaim (inline unix-gettimeofday))
946 (defun unix-gettimeofday ()
947   #!+sb-doc
948   "If it works, unix-gettimeofday returns 5 values: T, the seconds and
949    microseconds of the current time of day, the timezone (in minutes west
950    of Greenwich), and a daylight-savings flag. If it doesn't work, it
951    returns NIL and the errno."
952   (with-alien ((tv (struct timeval))
953                (tz (struct timezone)))
954     (syscall* ("gettimeofday" (* (struct timeval))
955                               (* (struct timezone)))
956               (values T
957                       (slot tv 'tv-sec)
958                       (slot tv 'tv-usec)
959                       (slot tz 'tz-minuteswest)
960                       (slot tz 'tz-dsttime))
961               (addr tv)
962               (addr tz))))
963 \f
964 ;;;; asm/errno.h
965
966 #|
967 (def-unix-error ESUCCESS 0 "Successful")
968 (def-unix-error EPERM 1 "Operation not permitted")
969 |#
970 (def-unix-error ENOENT 2 "No such file or directory")
971 #|
972 (def-unix-error ESRCH 3 "No such process")
973 |#
974 (def-unix-error EINTR 4 "Interrupted system call")
975 (def-unix-error EIO 5 "I/O error")
976 #|
977 (def-unix-error ENXIO 6 "No such device or address")
978 (def-unix-error E2BIG 7 "Arg list too long")
979 (def-unix-error ENOEXEC 8 "Exec format error")
980 (def-unix-error EBADF 9 "Bad file number")
981 (def-unix-error ECHILD 10 "No children")
982 (def-unix-error EAGAIN 11 "Try again")
983 (def-unix-error ENOMEM 12 "Out of memory")
984 |#
985 (def-unix-error EACCES 13 "Permission denied")
986 #|
987 (def-unix-error EFAULT 14 "Bad address")
988 (def-unix-error ENOTBLK 15 "Block device required")
989 (def-unix-error EBUSY 16 "Device or resource busy")
990 |#
991 (def-unix-error EEXIST 17 "File exists")
992 #|
993 (def-unix-error EXDEV 18 "Cross-device link")
994 (def-unix-error ENODEV 19 "No such device")
995 |#
996 (def-unix-error ENOTDIR 20 "Not a directory")
997 #|
998 (def-unix-error EISDIR 21 "Is a directory")
999 (def-unix-error EINVAL 22 "Invalid argument")
1000 (def-unix-error ENFILE 23 "File table overflow")
1001 (def-unix-error EMFILE 24 "Too many open files")
1002 (def-unix-error ENOTTY 25 "Not a typewriter")
1003 (def-unix-error ETXTBSY 26 "Text file busy")
1004 (def-unix-error EFBIG 27 "File too large")
1005 (def-unix-error ENOSPC 28 "No space left on device")
1006 |#
1007 (def-unix-error ESPIPE 29 "Illegal seek")
1008 #|
1009 (def-unix-error EROFS 30 "Read-only file system")
1010 (def-unix-error EMLINK 31 "Too many links")
1011 (def-unix-error EPIPE 32 "Broken pipe")
1012 |#
1013
1014 #|
1015 ;;; Math
1016 (def-unix-error EDOM 33 "Math argument out of domain")
1017 (def-unix-error ERANGE 34 "Math result not representable")
1018 (def-unix-error  EDEADLK         35     "Resource deadlock would occur")
1019 (def-unix-error  ENAMETOOLONG    36     "File name too long")
1020 (def-unix-error  ENOLCK   37     "No record locks available")
1021 (def-unix-error  ENOSYS   38     "Function not implemented")
1022 (def-unix-error  ENOTEMPTY       39     "Directory not empty")
1023 (def-unix-error  ELOOP     40     "Too many symbolic links encountered")
1024 |#
1025 (def-unix-error  EWOULDBLOCK     11     "Operation would block")
1026 (/show0 "unix.lisp 3192")
1027 #|
1028 (def-unix-error  ENOMSG   42     "No message of desired type")
1029 (def-unix-error  EIDRM     43     "Identifier removed")
1030 (def-unix-error  ECHRNG   44     "Channel number out of range")
1031 (def-unix-error  EL2NSYNC       45     "Level 2 not synchronized")
1032 (def-unix-error  EL3HLT   46     "Level 3 halted")
1033 (def-unix-error  EL3RST   47     "Level 3 reset")
1034 (def-unix-error  ELNRNG   48     "Link number out of range")
1035 (def-unix-error  EUNATCH         49     "Protocol driver not attached")
1036 (def-unix-error  ENOCSI   50     "No CSI structure available")
1037 (def-unix-error  EL2HLT   51     "Level 2 halted")
1038 (def-unix-error  EBADE     52     "Invalid exchange")
1039 (def-unix-error  EBADR     53     "Invalid request descriptor")
1040 (def-unix-error  EXFULL   54     "Exchange full")
1041 (def-unix-error  ENOANO   55     "No anode")
1042 (def-unix-error  EBADRQC         56     "Invalid request code")
1043 (def-unix-error  EBADSLT         57     "Invalid slot")
1044 (def-unix-error  EDEADLOCK       EDEADLK     "File locking deadlock error")
1045 (def-unix-error  EBFONT   59     "Bad font file format")
1046 (def-unix-error  ENOSTR   60     "Device not a stream")
1047 (def-unix-error  ENODATA         61     "No data available")
1048 (def-unix-error  ETIME     62     "Timer expired")
1049 (def-unix-error  ENOSR     63     "Out of streams resources")
1050 (def-unix-error  ENONET   64     "Machine is not on the network")
1051 (def-unix-error  ENOPKG   65     "Package not installed")
1052 (def-unix-error  EREMOTE         66     "Object is remote")
1053 (def-unix-error  ENOLINK         67     "Link has been severed")
1054 (def-unix-error  EADV       68     "Advertise error")
1055 (def-unix-error  ESRMNT   69     "Srmount error")
1056 (def-unix-error  ECOMM     70     "Communication error on send")
1057 (def-unix-error  EPROTO   71     "Protocol error")
1058 (def-unix-error  EMULTIHOP       72     "Multihop attempted")
1059 (def-unix-error  EDOTDOT         73     "RFS specific error")
1060 (def-unix-error  EBADMSG         74     "Not a data message")
1061 (def-unix-error  EOVERFLOW       75     "Value too large for defined data type")
1062 (def-unix-error  ENOTUNIQ       76     "Name not unique on network")
1063 (def-unix-error  EBADFD   77     "File descriptor in bad state")
1064 (def-unix-error  EREMCHG         78     "Remote address changed")
1065 (def-unix-error  ELIBACC         79     "Can not access a needed shared library")
1066 (def-unix-error  ELIBBAD         80     "Accessing a corrupted shared library")
1067 (def-unix-error  ELIBSCN         81     ".lib section in a.out corrupted")
1068 (def-unix-error  ELIBMAX         82     "Attempting to link in too many shared libraries")
1069 (def-unix-error  ELIBEXEC       83     "Cannot exec a shared library directly")
1070 (def-unix-error  EILSEQ   84     "Illegal byte sequence")
1071 (def-unix-error  ERESTART       85     "Interrupted system call should be restarted ")
1072 (def-unix-error  ESTRPIPE       86     "Streams pipe error")
1073 (def-unix-error  EUSERS   87     "Too many users")
1074 (def-unix-error  ENOTSOCK       88     "Socket operation on non-socket")
1075 (def-unix-error  EDESTADDRREQ    89     "Destination address required")
1076 (def-unix-error  EMSGSIZE       90     "Message too long")
1077 (def-unix-error  EPROTOTYPE      91     "Protocol wrong type for socket")
1078 (def-unix-error  ENOPROTOOPT     92     "Protocol not available")
1079 (def-unix-error  EPROTONOSUPPORT 93     "Protocol not supported")
1080 (def-unix-error  ESOCKTNOSUPPORT 94     "Socket type not supported")
1081 (def-unix-error  EOPNOTSUPP      95     "Operation not supported on transport endpoint")
1082 (def-unix-error  EPFNOSUPPORT    96     "Protocol family not supported")
1083 (def-unix-error  EAFNOSUPPORT    97     "Address family not supported by protocol")
1084 (def-unix-error  EADDRINUSE      98     "Address already in use")
1085 (def-unix-error  EADDRNOTAVAIL   99     "Cannot assign requested address")
1086 (def-unix-error  ENETDOWN       100    "Network is down")
1087 (def-unix-error  ENETUNREACH     101    "Network is unreachable")
1088 (def-unix-error  ENETRESET       102    "Network dropped connection because of reset")
1089 (def-unix-error  ECONNABORTED    103    "Software caused connection abort")
1090 (def-unix-error  ECONNRESET      104    "Connection reset by peer")
1091 (def-unix-error  ENOBUFS         105    "No buffer space available")
1092 (def-unix-error  EISCONN         106    "Transport endpoint is already connected")
1093 (def-unix-error  ENOTCONN       107    "Transport endpoint is not connected")
1094 (def-unix-error  ESHUTDOWN       108    "Cannot send after transport endpoint shutdown")
1095 (def-unix-error  ETOOMANYREFS    109    "Too many references: cannot splice")
1096 (def-unix-error  ETIMEDOUT       110    "Connection timed out")
1097 (def-unix-error  ECONNREFUSED    111    "Connection refused")
1098 (def-unix-error  EHOSTDOWN       112    "Host is down")
1099 (def-unix-error  EHOSTUNREACH    113    "No route to host")
1100 (def-unix-error  EALREADY       114    "Operation already in progress")
1101 (def-unix-error  EINPROGRESS     115    "Operation now in progress")
1102 (def-unix-error  ESTALE   116    "Stale NFS file handle")
1103 (def-unix-error  EUCLEAN         117    "Structure needs cleaning")
1104 (def-unix-error  ENOTNAM         118    "Not a XENIX named type file")
1105 (def-unix-error  ENAVAIL         119    "No XENIX semaphores available")
1106 (def-unix-error  EISNAM   120    "Is a named type file")
1107 (def-unix-error  EREMOTEIO       121    "Remote I/O error")
1108 (def-unix-error  EDQUOT   122    "Quota exceeded")
1109 |#
1110
1111 ;;; And now for something completely different ...
1112 (emit-unix-errors)
1113 \f
1114 ;;;; support routines for dealing with unix pathnames
1115
1116 (defun unix-file-kind (name &optional check-for-links)
1117   #!+sb-doc
1118   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
1119   (declare (simple-string name))
1120   (multiple-value-bind (res dev ino mode)
1121       (if check-for-links (unix-lstat name) (unix-stat name))
1122     (declare (type (or fixnum null) mode)
1123              (ignore dev ino))
1124     (when res
1125       (let ((kind (logand mode s-ifmt)))
1126         (cond ((eql kind s-ifdir) :directory)
1127               ((eql kind s-ifreg) :file)
1128               ((eql kind s-iflnk) :link)
1129               (t :special))))))
1130
1131 (defun unix-maybe-prepend-current-directory (name)
1132   (declare (simple-string name))
1133   (if (and (> (length name) 0) (char= (schar name 0) #\/))
1134       name
1135       (multiple-value-bind (win dir) (unix-current-directory)
1136         (if win
1137             (concatenate 'simple-string dir "/" name)
1138             name))))
1139
1140 (defun unix-resolve-links (pathname)
1141   #!+sb-doc
1142   "Returns the pathname with all symbolic links resolved."
1143   (declare (simple-string pathname))
1144   (let ((len (length pathname))
1145         (pending pathname))
1146     (declare (fixnum len) (simple-string pending))
1147     (if (zerop len)
1148         pathname
1149         (let ((result (make-string 1024 :initial-element (code-char 0)))
1150               (fill-ptr 0)
1151               (name-start 0))
1152           (loop
1153             (let* ((name-end (or (position #\/ pending :start name-start) len))
1154                    (new-fill-ptr (+ fill-ptr (- name-end name-start))))
1155               (replace result pending
1156                        :start1 fill-ptr
1157                        :end1 new-fill-ptr
1158                        :start2 name-start
1159                        :end2 name-end)
1160               (let ((kind (unix-file-kind (if (zerop name-end) "/" result) t)))
1161                 (unless kind (return nil))
1162                 (cond ((eq kind :link)
1163                        (multiple-value-bind (link err) (unix-readlink result)
1164                          (unless link
1165                            (error "error reading link ~S: ~S"
1166                                   (subseq result 0 fill-ptr)
1167                                   (get-unix-error-msg err)))
1168                          (cond ((or (zerop (length link))
1169                                     (char/= (schar link 0) #\/))
1170                                 ;; It's a relative link.
1171                                 (fill result (code-char 0)
1172                                       :start fill-ptr
1173                                       :end new-fill-ptr))
1174                                ((string= result "/../" :end1 4)
1175                                 ;; It's across the super-root.
1176                                 (let ((slash (or (position #\/ result :start 4)
1177                                                  0)))
1178                                   (fill result (code-char 0)
1179                                         :start slash
1180                                         :end new-fill-ptr)
1181                                   (setf fill-ptr slash)))
1182                                (t
1183                                 ;; It's absolute.
1184                                 (and (> (length link) 0)
1185                                      (char= (schar link 0) #\/))
1186                                 (fill result (code-char 0) :end new-fill-ptr)
1187                                 (setf fill-ptr 0)))
1188                          (setf pending
1189                                (if (= name-end len)
1190                                    link
1191                                    (concatenate 'simple-string
1192                                                 link
1193                                                 (subseq pending name-end))))
1194                          (setf len (length pending))
1195                          (setf name-start 0)))
1196                       ((= name-end len)
1197                        (return (subseq result 0 new-fill-ptr)))
1198                       ((eq kind :directory)
1199                        (setf (schar result new-fill-ptr) #\/)
1200                        (setf fill-ptr (1+ new-fill-ptr))
1201                        (setf name-start (1+ name-end)))
1202                       (t
1203                        (return nil))))))))))
1204
1205 (defun unix-simplify-pathname (src)
1206   (declare (simple-string src))
1207   (let* ((src-len (length src))
1208          (dst (make-string src-len))
1209          (dst-len 0)
1210          (dots 0)
1211          (last-slash nil))
1212     (macrolet ((deposit (char)
1213                         `(progn
1214                            (setf (schar dst dst-len) ,char)
1215                            (incf dst-len))))
1216       (dotimes (src-index src-len)
1217         (let ((char (schar src src-index)))
1218           (cond ((char= char #\.)
1219                  (when dots
1220                    (incf dots))
1221                  (deposit char))
1222                 ((char= char #\/)
1223                  (case dots
1224                    (0
1225                     ;; Either ``/...' or ``...//...'
1226                     (unless last-slash
1227                       (setf last-slash dst-len)
1228                       (deposit char)))
1229                    (1
1230                     ;; Either ``./...'' or ``..././...''
1231                     (decf dst-len))
1232                    (2
1233                     ;; We've found ..
1234                     (cond
1235                      ((and last-slash (not (zerop last-slash)))
1236                       ;; There is something before this ..
1237                       (let ((prev-prev-slash
1238                              (position #\/ dst :end last-slash :from-end t)))
1239                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
1240                                        last-slash)
1241                                     (char= (schar dst (- last-slash 2)) #\.)
1242                                     (char= (schar dst (1- last-slash)) #\.))
1243                                ;; The something before this .. is another ..
1244                                (deposit char)
1245                                (setf last-slash dst-len))
1246                               (t
1247                                ;; The something is some directory or other.
1248                                (setf dst-len
1249                                      (if prev-prev-slash
1250                                          (1+ prev-prev-slash)
1251                                          0))
1252                                (setf last-slash prev-prev-slash)))))
1253                      (t
1254                       ;; There is nothing before this .., so we need to keep it
1255                       (setf last-slash dst-len)
1256                       (deposit char))))
1257                    (t
1258                     ;; Something other than a dot between slashes.
1259                     (setf last-slash dst-len)
1260                     (deposit char)))
1261                  (setf dots 0))
1262                 (t
1263                  (setf dots nil)
1264                  (setf (schar dst dst-len) char)
1265                  (incf dst-len))))))
1266     (when (and last-slash (not (zerop last-slash)))
1267       (case dots
1268         (1
1269          ;; We've got  ``foobar/.''
1270          (decf dst-len))
1271         (2
1272          ;; We've got ``foobar/..''
1273          (unless (and (>= last-slash 2)
1274                       (char= (schar dst (1- last-slash)) #\.)
1275                       (char= (schar dst (- last-slash 2)) #\.)
1276                       (or (= last-slash 2)
1277                           (char= (schar dst (- last-slash 3)) #\/)))
1278            (let ((prev-prev-slash
1279                   (position #\/ dst :end last-slash :from-end t)))
1280              (if prev-prev-slash
1281                  (setf dst-len (1+ prev-prev-slash))
1282                  (return-from unix-simplify-pathname "./")))))))
1283     (cond ((zerop dst-len)
1284            "./")
1285           ((= dst-len src-len)
1286            dst)
1287           (t
1288            (subseq dst 0 dst-len)))))
1289 \f
1290 ;;;; stuff not yet found in the header files
1291 ;;;;
1292 ;;;; Abandon all hope who enters here...
1293
1294 ;;; not checked for linux...
1295 (defmacro fd-set (offset fd-set)
1296   (let ((word (gensym))
1297         (bit (gensym)))
1298     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
1299        (setf (deref (slot ,fd-set 'fds-bits) ,word)
1300              (logior (truly-the (unsigned-byte 32) (ash 1 ,bit))
1301                      (deref (slot ,fd-set 'fds-bits) ,word))))))
1302
1303 ;;; not checked for linux...
1304 (defmacro fd-clr (offset fd-set)
1305   (let ((word (gensym))
1306         (bit (gensym)))
1307     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
1308        (setf (deref (slot ,fd-set 'fds-bits) ,word)
1309              (logand (deref (slot ,fd-set 'fds-bits) ,word)
1310                      (sb!kernel:32bit-logical-not
1311                       (truly-the (unsigned-byte 32) (ash 1 ,bit))))))))
1312
1313 ;;; not checked for linux...
1314 (defmacro fd-isset (offset fd-set)
1315   (let ((word (gensym))
1316         (bit (gensym)))
1317     `(multiple-value-bind (,word ,bit) (floor ,offset 32)
1318        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1319
1320 ;;; not checked for linux...
1321 (defmacro fd-zero (fd-set)
1322   `(progn
1323      ,@(loop for index upfrom 0 below (/ fd-setsize 32)
1324          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))
1325
1326 (/show0 "unix.lisp 3555")