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