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