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