0.9.6.7:
[sbcl.git] / src / code / fd-stream.lisp
1 ;;;; streams for UNIX file descriptors
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 ;;;; buffer manipulation routines
15
16 ;;; FIXME: Is it really good to maintain this pool separate from the
17 ;;; GC and the C malloc logic?
18 (defvar *available-buffers* ()
19   #!+sb-doc
20   "List of available buffers. Each buffer is an sap pointing to
21   bytes-per-buffer of memory.")
22
23 #!+sb-thread
24 (defvar *available-buffers-mutex* (sb!thread:make-mutex
25                                    :name "lock for *AVAILABLE-BUFFERS*")
26   #!+sb-doc
27   "Mutex for access to *AVAILABLE-BUFFERS*.")
28
29 (defmacro with-available-buffers-lock ((&optional) &body body)
30   ;; WITHOUT-INTERRUPTS because streams are low-level enough to be
31   ;; async signal safe, and in particular a C-c that brings up the
32   ;; debugger while holding the mutex would lose badly
33   `(without-interrupts
34     (sb!thread:with-mutex (*available-buffers-mutex*)
35       ,@body)))
36
37 (defconstant bytes-per-buffer (* 4 1024)
38   #!+sb-doc
39   "Number of bytes per buffer.")
40
41 ;;; Return the next available buffer, creating one if necessary.
42 #!-sb-fluid (declaim (inline next-available-buffer))
43 (defun next-available-buffer ()
44   (with-available-buffers-lock ()
45     (if *available-buffers*
46         (pop *available-buffers*)
47         (allocate-system-memory bytes-per-buffer))))
48 \f
49 ;;;; the FD-STREAM structure
50
51 (defstruct (fd-stream
52             (:constructor %make-fd-stream)
53             (:conc-name fd-stream-)
54             (:predicate fd-stream-p)
55             (:include ansi-stream
56                       (misc #'fd-stream-misc-routine))
57             (:copier nil))
58
59   ;; the name of this stream
60   (name nil)
61   ;; the file this stream is for
62   (file nil)
63   ;; the backup file namestring for the old file, for :IF-EXISTS
64   ;; :RENAME or :RENAME-AND-DELETE.
65   (original nil :type (or simple-string null))
66   (delete-original nil)       ; for :if-exists :rename-and-delete
67   ;;; the number of bytes per element
68   (element-size 1 :type index)
69   ;; the type of element being transfered
70   (element-type 'base-char)
71   ;; the Unix file descriptor
72   (fd -1 :type fixnum)
73   ;; controls when the output buffer is flushed
74   (buffering :full :type (member :full :line :none))
75   ;; controls whether the input buffer must be cleared before output
76   ;; (must be done for files, not for sockets, pipes and other data
77   ;; sources where input and output aren't related).  non-NIL means
78   ;; don't clear input buffer.
79   (dual-channel-p nil)
80   ;; character position (if known)
81   (char-pos nil :type (or index null))
82   ;; T if input is waiting on FD. :EOF if we hit EOF.
83   (listen nil :type (member nil t :eof))
84
85   ;; the input buffer
86   (unread nil)
87   (ibuf-sap nil :type (or system-area-pointer null))
88   (ibuf-length nil :type (or index null))
89   (ibuf-head 0 :type index)
90   (ibuf-tail 0 :type index)
91
92   ;; the output buffer
93   (obuf-sap nil :type (or system-area-pointer null))
94   (obuf-length nil :type (or index null))
95   (obuf-tail 0 :type index)
96
97   ;; output flushed, but not written due to non-blocking io?
98   (output-later nil)
99   (handler nil)
100   ;; timeout specified for this stream, or NIL if none
101   (timeout nil :type (or index null))
102   ;; pathname of the file this stream is opened to (returned by PATHNAME)
103   (pathname nil :type (or pathname null))
104   (external-format :default)
105   (output-bytes #'ill-out :type function))
106 (def!method print-object ((fd-stream fd-stream) stream)
107   (declare (type stream stream))
108   (print-unreadable-object (fd-stream stream :type t :identity t)
109     (format stream "for ~S" (fd-stream-name fd-stream))))
110 \f
111 ;;;; output routines and related noise
112
113 (defvar *output-routines* ()
114   #!+sb-doc
115   "List of all available output routines. Each element is a list of the
116   element-type output, the kind of buffering, the function name, and the number
117   of bytes per element.")
118
119 ;;; common idioms for reporting low-level stream and file problems
120 (defun simple-stream-perror (note-format stream errno)
121   (error 'simple-stream-error
122          :stream stream
123          :format-control "~@<~?: ~2I~_~A~:>"
124          :format-arguments (list note-format (list stream) (strerror errno))))
125 (defun simple-file-perror (note-format pathname errno)
126   (error 'simple-file-error
127          :pathname pathname
128          :format-control "~@<~?: ~2I~_~A~:>"
129          :format-arguments
130          (list note-format (list pathname) (strerror errno))))
131
132 (defun stream-decoding-error (stream octets)
133   (error 'stream-decoding-error
134          :stream stream
135          ;; FIXME: dunno how to get at OCTETS currently, or even if
136          ;; that's the right thing to report.
137          :octets octets))
138 (defun stream-encoding-error (stream code)
139   (error 'stream-encoding-error
140          :stream stream
141          :code code))
142
143 ;;; Returning true goes into end of file handling, false will enter another
144 ;;; round of input buffer filling followed by re-entering character decode.
145 (defun stream-decoding-error-and-handle (stream octet-count)
146   (restart-case
147       (stream-decoding-error stream
148                              (let ((sap (fd-stream-ibuf-sap stream))
149                                    (head (fd-stream-ibuf-head stream)))
150                                (loop for i from 0 below octet-count
151                                      collect (sap-ref-8 sap (+ head i)))))
152     (attempt-resync ()
153       :report (lambda (stream)
154                 (format stream
155                         "~@<Attempt to resync the stream at a character ~
156                         character boundary and continue.~@:>"))
157       (fd-stream-resync stream)
158       nil)
159     (force-end-of-file ()
160       :report (lambda (stream)
161                 (format stream "~@<Force an end of file.~@:>"))
162       t)))
163
164 (defun stream-encoding-error-and-handle (stream code)
165   (restart-case
166       (stream-encoding-error stream code)
167     (output-nothing ()
168       :report (lambda (stream)
169                 (format stream "~@<Skip output of this character.~@:>"))
170       (throw 'output-nothing nil))))
171
172 ;;; This is called by the server when we can write to the given file
173 ;;; descriptor. Attempt to write the data again. If it worked, remove
174 ;;; the data from the OUTPUT-LATER list. If it didn't work, something
175 ;;; is wrong.
176 (defun frob-output-later (stream)
177   (let* ((stuff (pop (fd-stream-output-later stream)))
178          (base (car stuff))
179          (start (cadr stuff))
180          (end (caddr stuff))
181          (reuse-sap (cadddr stuff))
182          (length (- end start)))
183     (declare (type index start end length))
184     (multiple-value-bind (count errno)
185         (sb!unix:unix-write (fd-stream-fd stream)
186                             base
187                             start
188                             length)
189       (cond ((not count)
190              (if (= errno sb!unix:ewouldblock)
191                  (error "Write would have blocked, but SERVER told us to go.")
192                  (simple-stream-perror "couldn't write to ~S" stream errno)))
193             ((eql count length) ; Hot damn, it worked.
194              (when reuse-sap
195                (with-available-buffers-lock ()
196                  (push base *available-buffers*))))
197             ((not (null count)) ; sorta worked..
198              (push (list base
199                          (the index (+ start count))
200                          end)
201                    (fd-stream-output-later stream))))))
202   (unless (fd-stream-output-later stream)
203     (sb!sys:remove-fd-handler (fd-stream-handler stream))
204     (setf (fd-stream-handler stream) nil)))
205
206 ;;; Arange to output the string when we can write on the file descriptor.
207 (defun output-later (stream base start end reuse-sap)
208   (cond ((null (fd-stream-output-later stream))
209          (setf (fd-stream-output-later stream)
210                (list (list base start end reuse-sap)))
211          (setf (fd-stream-handler stream)
212                (sb!sys:add-fd-handler (fd-stream-fd stream)
213                                       :output
214                                       (lambda (fd)
215                                         (declare (ignore fd))
216                                         (frob-output-later stream)))))
217         (t
218          (nconc (fd-stream-output-later stream)
219                 (list (list base start end reuse-sap)))))
220   (when reuse-sap
221     (let ((new-buffer (next-available-buffer)))
222       (setf (fd-stream-obuf-sap stream) new-buffer)
223       (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
224
225 ;;; Output the given noise. Check to see whether there are any pending
226 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
227 ;;; this would block, queue it.
228 (defun frob-output (stream base start end reuse-sap)
229   (declare (type fd-stream stream)
230            (type (or system-area-pointer (simple-array * (*))) base)
231            (type index start end))
232   (if (not (null (fd-stream-output-later stream))) ; something buffered.
233       (progn
234         (output-later stream base start end reuse-sap)
235         ;; ### check to see whether any of this noise can be output
236         )
237       (let ((length (- end start)))
238         (multiple-value-bind (count errno)
239             (sb!unix:unix-write (fd-stream-fd stream) base start length)
240           (cond ((not count)
241                  (if (= errno sb!unix:ewouldblock)
242                      (output-later stream base start end reuse-sap)
243                      (simple-stream-perror "couldn't write to ~S"
244                                            stream
245                                            errno)))
246                 ((not (eql count length))
247                  (output-later stream base (the index (+ start count))
248                                end reuse-sap)))))))
249
250 ;;; Flush any data in the output buffer.
251 (defun flush-output-buffer (stream)
252   (let ((length (fd-stream-obuf-tail stream)))
253     (unless (= length 0)
254       (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
255       (setf (fd-stream-obuf-tail stream) 0))))
256
257 (defmacro output-wrapper/variable-width ((stream size buffering restart)
258                                          &body body)
259   (let ((stream-var (gensym)))
260     `(let ((,stream-var ,stream)
261            (size ,size))
262       ,(unless (eq (car buffering) :none)
263          `(when (< (fd-stream-obuf-length ,stream-var)
264                    (+ (fd-stream-obuf-tail ,stream-var)
265                        size))
266             (flush-output-buffer ,stream-var)))
267       ,(unless (eq (car buffering) :none)
268          `(when (and (not (fd-stream-dual-channel-p ,stream-var))
269                      (> (fd-stream-ibuf-tail ,stream-var)
270                         (fd-stream-ibuf-head ,stream-var)))
271             (file-position ,stream-var (file-position ,stream-var))))
272       ,(if restart
273            `(catch 'output-nothing
274               ,@body
275               (incf (fd-stream-obuf-tail ,stream-var) size))
276            `(progn
277              ,@body
278              (incf (fd-stream-obuf-tail ,stream-var) size)))
279       ,(ecase (car buffering)
280          (:none
281           `(flush-output-buffer ,stream-var))
282          (:line
283           `(when (eq (char-code byte) (char-code #\Newline))
284              (flush-output-buffer ,stream-var)))
285          (:full))
286     (values))))
287
288 (defmacro output-wrapper ((stream size buffering restart) &body body)
289   (let ((stream-var (gensym)))
290     `(let ((,stream-var ,stream))
291       ,(unless (eq (car buffering) :none)
292          `(when (< (fd-stream-obuf-length ,stream-var)
293                    (+ (fd-stream-obuf-tail ,stream-var)
294                        ,size))
295             (flush-output-buffer ,stream-var)))
296       ,(unless (eq (car buffering) :none)
297          `(when (and (not (fd-stream-dual-channel-p ,stream-var))
298                      (> (fd-stream-ibuf-tail ,stream-var)
299                         (fd-stream-ibuf-head ,stream-var)))
300             (file-position ,stream-var (file-position ,stream-var))))
301       ,(if restart
302            `(catch 'output-nothing
303               ,@body
304               (incf (fd-stream-obuf-tail ,stream-var) ,size))
305            `(progn
306              ,@body
307              (incf (fd-stream-obuf-tail ,stream-var) ,size)))
308       ,(ecase (car buffering)
309          (:none
310           `(flush-output-buffer ,stream-var))
311          (:line
312           `(when (eq (char-code byte) (char-code #\Newline))
313              (flush-output-buffer ,stream-var)))
314          (:full))
315     (values))))
316
317 (defmacro def-output-routines/variable-width
318     ((name-fmt size restart external-format &rest bufferings)
319      &body body)
320   (declare (optimize (speed 1)))
321   (cons 'progn
322         (mapcar
323             (lambda (buffering)
324               (let ((function
325                      (intern (format nil name-fmt (string (car buffering))))))
326                 `(progn
327                    (defun ,function (stream byte)
328                      (output-wrapper/variable-width (stream ,size ,buffering ,restart)
329                        ,@body))
330                    (setf *output-routines*
331                          (nconc *output-routines*
332                                 ',(mapcar
333                                    (lambda (type)
334                                      (list type
335                                            (car buffering)
336                                            function
337                                            1
338                                            external-format))
339                                    (cdr buffering)))))))
340             bufferings)))
341
342 ;;; Define output routines that output numbers SIZE bytes long for the
343 ;;; given bufferings. Use BODY to do the actual output.
344 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
345                                &body body)
346   (declare (optimize (speed 1)))
347   (cons 'progn
348         (mapcar
349             (lambda (buffering)
350               (let ((function
351                      (intern (format nil name-fmt (string (car buffering))))))
352                 `(progn
353                    (defun ,function (stream byte)
354                      (output-wrapper (stream ,size ,buffering ,restart)
355                        ,@body))
356                    (setf *output-routines*
357                          (nconc *output-routines*
358                                 ',(mapcar
359                                    (lambda (type)
360                                      (list type
361                                            (car buffering)
362                                            function
363                                            size
364                                            nil))
365                                    (cdr buffering)))))))
366             bufferings)))
367
368 ;;; FIXME: is this used anywhere any more?
369 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
370                       1
371                       t
372                       (:none character)
373                       (:line character)
374                       (:full character))
375   (if (char= byte #\Newline)
376       (setf (fd-stream-char-pos stream) 0)
377       (incf (fd-stream-char-pos stream)))
378   (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
379         (char-code byte)))
380
381 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
382                       1
383                       nil
384                       (:none (unsigned-byte 8))
385                       (:full (unsigned-byte 8)))
386   (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
387         byte))
388
389 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
390                       1
391                       nil
392                       (:none (signed-byte 8))
393                       (:full (signed-byte 8)))
394   (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
395                           (fd-stream-obuf-tail stream))
396         byte))
397
398 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
399                       2
400                       nil
401                       (:none (unsigned-byte 16))
402                       (:full (unsigned-byte 16)))
403   (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
404         byte))
405
406 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
407                       2
408                       nil
409                       (:none (signed-byte 16))
410                       (:full (signed-byte 16)))
411   (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
412                            (fd-stream-obuf-tail stream))
413         byte))
414
415 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
416                       4
417                       nil
418                       (:none (unsigned-byte 32))
419                       (:full (unsigned-byte 32)))
420   (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
421         byte))
422
423 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
424                       4
425                       nil
426                       (:none (signed-byte 32))
427                       (:full (signed-byte 32)))
428   (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
429                            (fd-stream-obuf-tail stream))
430         byte))
431
432 ;;; Do the actual output. If there is space to buffer the string,
433 ;;; buffer it. If the string would normally fit in the buffer, but
434 ;;; doesn't because of other stuff in the buffer, flush the old noise
435 ;;; out of the buffer and put the string in it. Otherwise we have a
436 ;;; very long string, so just send it directly (after flushing the
437 ;;; buffer, of course).
438 (defun output-raw-bytes (fd-stream thing &optional start end)
439   #!+sb-doc
440   "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
441   THING is a SAP, END must be supplied (as length won't work)."
442   (let ((start (or start 0))
443         (end (or end (length (the (simple-array * (*)) thing)))))
444     (declare (type index start end))
445     (when (and (not (fd-stream-dual-channel-p fd-stream))
446                (> (fd-stream-ibuf-tail fd-stream)
447                   (fd-stream-ibuf-head fd-stream)))
448       (file-position fd-stream (file-position fd-stream)))
449     (let* ((len (fd-stream-obuf-length fd-stream))
450            (tail (fd-stream-obuf-tail fd-stream))
451            (space (- len tail))
452            (bytes (- end start))
453            (newtail (+ tail bytes)))
454       (cond ((minusp bytes) ; error case
455              (error ":END before :START!"))
456             ((zerop bytes)) ; easy case
457             ((<= bytes space)
458              (if (system-area-pointer-p thing)
459                  (system-area-ub8-copy thing start
460                                        (fd-stream-obuf-sap fd-stream)
461                                        tail
462                                        bytes)
463                  ;; FIXME: There should be some type checking somewhere to
464                  ;; verify that THING here is a vector, not just <not a SAP>.
465                  (copy-ub8-to-system-area thing start
466                                           (fd-stream-obuf-sap fd-stream)
467                                           tail
468                                           bytes))
469              (setf (fd-stream-obuf-tail fd-stream) newtail))
470             ((<= bytes len)
471              (flush-output-buffer fd-stream)
472              (if (system-area-pointer-p thing)
473                  (system-area-ub8-copy thing
474                                        start
475                                        (fd-stream-obuf-sap fd-stream)
476                                        0
477                                        bytes)
478                  ;; FIXME: There should be some type checking somewhere to
479                  ;; verify that THING here is a vector, not just <not a SAP>.
480                  (copy-ub8-to-system-area thing
481                                           start
482                                           (fd-stream-obuf-sap fd-stream)
483                                           0
484                                           bytes))
485              (setf (fd-stream-obuf-tail fd-stream) bytes))
486             (t
487              (flush-output-buffer fd-stream)
488              (frob-output fd-stream thing start end nil))))))
489
490 ;;; the routine to use to output a string. If the stream is
491 ;;; unbuffered, slam the string down the file descriptor, otherwise
492 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
493 ;;; checking to see where the last newline was.
494 ;;;
495 ;;; Note: some bozos (the FASL dumper) call write-string with things
496 ;;; other than strings. Therefore, we must make sure we have a string
497 ;;; before calling POSITION on it.
498 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
499 ;;; cover for them here. -- WHN 20000203
500 (defun fd-sout (stream thing start end)
501   (let ((start (or start 0))
502         (end (or end (length (the vector thing)))))
503     (declare (fixnum start end))
504     (if (stringp thing)
505         (let ((last-newline
506                (flet ((do-it (string)
507                         (and (find #\newline string :start start :end end)
508                              ;; FIXME why do we need both calls?
509                              ;; Is find faster forwards than
510                              ;; position is backwards?
511                              (position #\newline string
512                                        :from-end t
513                                        :start start
514                                        :end end))))
515                  (declare (inline do-it))
516                  ;; Specialize the common cases
517                  (etypecase thing
518                    (simple-base-string
519                     (do-it (the simple-base-string thing)))
520                    #!+sb-unicode
521                    ((simple-array character)
522                     (do-it (the (simple-array character) thing)))
523                    (string
524                     (do-it thing))))))
525           (if (and (typep thing 'base-string)
526                    (eq (fd-stream-external-format stream) :latin-1))
527               (ecase (fd-stream-buffering stream)
528                 (:full
529                  (output-raw-bytes stream thing start end))
530                 (:line
531                  (output-raw-bytes stream thing start end)
532                  (when last-newline
533                    (flush-output-buffer stream)))
534                 (:none
535                  (frob-output stream thing start end nil)))
536               (ecase (fd-stream-buffering stream)
537                 (:full (funcall (fd-stream-output-bytes stream)
538                                 stream thing nil start end))
539                 (:line (funcall (fd-stream-output-bytes stream)
540                                 stream thing last-newline start end))
541                 (:none (funcall (fd-stream-output-bytes stream)
542                                 stream thing t start end))))
543           (if last-newline
544               (setf (fd-stream-char-pos stream)
545                     (- end last-newline 1))
546               (incf (fd-stream-char-pos stream)
547                     (- end start))))
548         (ecase (fd-stream-buffering stream)
549           ((:line :full)
550            (output-raw-bytes stream thing start end))
551           (:none
552            (frob-output stream thing start end nil))))))
553
554 (defvar *external-formats* ()
555   #!+sb-doc
556   "List of all available external formats. Each element is a list of the
557   element-type, string input function name, character input function name,
558   and string output function name.")
559
560 ;;; Find an output routine to use given the type and buffering. Return
561 ;;; as multiple values the routine, the real type transfered, and the
562 ;;; number of bytes per element.
563 (defun pick-output-routine (type buffering &optional external-format)
564   (when (subtypep type 'character)
565     (dolist (entry *external-formats*)
566       (when (member external-format (first entry))
567         (return-from pick-output-routine
568           (values (symbol-function (nth (ecase buffering
569                                           (:none 4)
570                                           (:line 5)
571                                           (:full 6))
572                                         entry))
573                   'character
574                   1
575                   (symbol-function (fourth entry))
576                   (first (first entry)))))))
577   (dolist (entry *output-routines*)
578     (when (and (subtypep type (first entry))
579                (eq buffering (second entry))
580                (or (not (fifth entry))
581                    (eq external-format (fifth entry))))
582       (return-from pick-output-routine
583         (values (symbol-function (third entry))
584                 (first entry)
585                 (fourth entry)))))
586   ;; KLUDGE: dealing with the buffering here leads to excessive code
587   ;; explosion.
588   ;;
589   ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
590   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
591         if (subtypep type `(unsigned-byte ,i))
592         do (return-from pick-output-routine
593              (values
594               (ecase buffering
595                 (:none
596                  (lambda (stream byte)
597                    (output-wrapper (stream (/ i 8) (:none) nil)
598                      (loop for j from 0 below (/ i 8)
599                            do (setf (sap-ref-8
600                                      (fd-stream-obuf-sap stream)
601                                      (+ j (fd-stream-obuf-tail stream)))
602                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
603                 (:full
604                  (lambda (stream byte)
605                    (output-wrapper (stream (/ i 8) (:full) nil)
606                      (loop for j from 0 below (/ i 8)
607                            do (setf (sap-ref-8
608                                      (fd-stream-obuf-sap stream)
609                                      (+ j (fd-stream-obuf-tail stream)))
610                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
611               `(unsigned-byte ,i)
612               (/ i 8))))
613   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
614         if (subtypep type `(signed-byte ,i))
615         do (return-from pick-output-routine
616              (values
617               (ecase buffering
618                 (:none
619                  (lambda (stream byte)
620                    (output-wrapper (stream (/ i 8) (:none) nil)
621                      (loop for j from 0 below (/ i 8)
622                            do (setf (sap-ref-8
623                                      (fd-stream-obuf-sap stream)
624                                      (+ j (fd-stream-obuf-tail stream)))
625                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
626                 (:full
627                  (lambda (stream byte)
628                    (output-wrapper (stream (/ i 8) (:full) nil)
629                      (loop for j from 0 below (/ i 8)
630                            do (setf (sap-ref-8
631                                      (fd-stream-obuf-sap stream)
632                                      (+ j (fd-stream-obuf-tail stream)))
633                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
634               `(signed-byte ,i)
635               (/ i 8)))))
636 \f
637 ;;;; input routines and related noise
638
639 ;;; a list of all available input routines. Each element is a list of
640 ;;; the element-type input, the function name, and the number of bytes
641 ;;; per element.
642 (defvar *input-routines* ())
643
644 ;;; Fill the input buffer, and return the number of bytes read. Throw
645 ;;; to EOF-INPUT-CATCHER if the eof was reached. Drop into
646 ;;; SYSTEM:SERVER if necessary.
647 (defun refill-buffer/fd (stream)
648   (let ((fd (fd-stream-fd stream))
649         (ibuf-sap (fd-stream-ibuf-sap stream))
650         (buflen (fd-stream-ibuf-length stream))
651         (head (fd-stream-ibuf-head stream))
652         (tail (fd-stream-ibuf-tail stream)))
653     (declare (type index head tail))
654     (unless (zerop head)
655       (cond ((eql head tail)
656              (setf head 0)
657              (setf tail 0)
658              (setf (fd-stream-ibuf-head stream) 0)
659              (setf (fd-stream-ibuf-tail stream) 0))
660             (t
661              (decf tail head)
662              (system-area-ub8-copy ibuf-sap head
663                                    ibuf-sap 0 tail)
664              (setf head 0)
665              (setf (fd-stream-ibuf-head stream) 0)
666              (setf (fd-stream-ibuf-tail stream) tail))))
667     (setf (fd-stream-listen stream) nil)
668     (sb!unix:with-restarted-syscall (count errno)
669       ;; FIXME: Judging from compiler warnings, this WITH-ALIEN form expands
670       ;; into something which uses the not-yet-defined type
671       ;;   (SB!ALIEN-INTERNALS:ALIEN (* (SB!ALIEN:STRUCT SB!UNIX:FD-SET))).
672       ;; This is probably inefficient and unsafe and generally bad, so
673       ;; try to find some way to make that type known before
674       ;; this is compiled.
675       (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
676         (sb!unix:fd-zero read-fds)
677         (sb!unix:fd-set fd read-fds)
678         (sb!unix:unix-fast-select (1+ fd)
679                                   (sb!alien:addr read-fds)
680                                   nil nil 0 0))
681       (case count
682         (1)
683         (0
684          (unless (sb!sys:wait-until-fd-usable
685                   fd :input (fd-stream-timeout stream))
686            (error 'io-timeout :stream stream :direction :read)))
687         (t
688          (simple-stream-perror "couldn't check whether ~S is readable"
689                                stream
690                                errno))))
691     (multiple-value-bind (count errno)
692         (sb!unix:unix-read fd
693                            (sb!sys:int-sap (+ (sb!sys:sap-int ibuf-sap) tail))
694                            (- buflen tail))
695       (cond ((null count)
696              (if (eql errno sb!unix:ewouldblock)
697                  (progn
698                    (unless (sb!sys:wait-until-fd-usable
699                             fd :input (fd-stream-timeout stream))
700                      (error 'io-timeout :stream stream :direction :read))
701                    (refill-buffer/fd stream))
702                  (simple-stream-perror "couldn't read from ~S" stream errno)))
703             ((zerop count)
704              (setf (fd-stream-listen stream) :eof)
705              (/show0 "THROWing EOF-INPUT-CATCHER")
706              (throw 'eof-input-catcher nil))
707             (t
708              (incf (fd-stream-ibuf-tail stream) count)
709              count)))))
710
711 ;;; Make sure there are at least BYTES number of bytes in the input
712 ;;; buffer. Keep calling REFILL-BUFFER/FD until that condition is met.
713 (defmacro input-at-least (stream bytes)
714   (let ((stream-var (gensym))
715         (bytes-var (gensym)))
716     `(let ((,stream-var ,stream)
717            (,bytes-var ,bytes))
718        (loop
719          (when (>= (- (fd-stream-ibuf-tail ,stream-var)
720                       (fd-stream-ibuf-head ,stream-var))
721                    ,bytes-var)
722            (return))
723          (refill-buffer/fd ,stream-var)))))
724
725 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
726                                         &body read-forms)
727   (let ((stream-var (gensym))
728         (retry-var (gensym))
729         (element-var (gensym)))
730     `(let ((,stream-var ,stream)
731            (size nil))
732        (if (fd-stream-unread ,stream-var)
733            (prog1
734                (fd-stream-unread ,stream-var)
735              (setf (fd-stream-unread ,stream-var) nil)
736              (setf (fd-stream-listen ,stream-var) nil))
737            (let ((,element-var nil)
738                  (decode-break-reason nil))
739              (do ((,retry-var t))
740                  ((not ,retry-var))
741                (unless
742                    (catch 'eof-input-catcher
743                      (setf decode-break-reason
744                            (block decode-break-reason
745                              (input-at-least ,stream-var 1)
746                              (let* ((byte (sap-ref-8 (fd-stream-ibuf-sap
747                                                       ,stream-var)
748                                                      (fd-stream-ibuf-head
749                                                       ,stream-var))))
750                                (setq size ,bytes)
751                                (input-at-least ,stream-var size)
752                                (setq ,element-var (locally ,@read-forms))
753                                (setq ,retry-var nil))
754                              nil))
755                      (when decode-break-reason
756                        (stream-decoding-error-and-handle stream
757                                                          decode-break-reason))
758                      t)
759                  (let ((octet-count (- (fd-stream-ibuf-tail ,stream-var)
760                                       (fd-stream-ibuf-head ,stream-var))))
761                    (when (or (zerop octet-count)
762                              (and (not ,element-var)
763                                   (not decode-break-reason)
764                                   (stream-decoding-error-and-handle
765                                    stream octet-count)))
766                      (setq ,retry-var nil)))))
767              (cond (,element-var
768                     (incf (fd-stream-ibuf-head ,stream-var) size)
769                     ,element-var)
770                    (t
771                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
772
773 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
774 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
775   (let ((stream-var (gensym))
776         (element-var (gensym)))
777     `(let ((,stream-var ,stream))
778        (if (fd-stream-unread ,stream-var)
779            (prog1
780                (fd-stream-unread ,stream-var)
781              (setf (fd-stream-unread ,stream-var) nil)
782              (setf (fd-stream-listen ,stream-var) nil))
783            (let ((,element-var
784                   (catch 'eof-input-catcher
785                     (input-at-least ,stream-var ,bytes)
786                     (locally ,@read-forms))))
787              (cond (,element-var
788                     (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
789                     ,element-var)
790                    (t
791                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
792
793 (defmacro def-input-routine/variable-width (name
794                                             (type external-format size sap head)
795                                             &rest body)
796   `(progn
797      (defun ,name (stream eof-error eof-value)
798        (input-wrapper/variable-width (stream ,size eof-error eof-value)
799          (let ((,sap (fd-stream-ibuf-sap stream))
800                (,head (fd-stream-ibuf-head stream)))
801            ,@body)))
802      (setf *input-routines*
803            (nconc *input-routines*
804                   (list (list ',type ',name 1 ',external-format))))))
805
806 (defmacro def-input-routine (name
807                              (type size sap head)
808                              &rest body)
809   `(progn
810      (defun ,name (stream eof-error eof-value)
811        (input-wrapper (stream ,size eof-error eof-value)
812          (let ((,sap (fd-stream-ibuf-sap stream))
813                (,head (fd-stream-ibuf-head stream)))
814            ,@body)))
815      (setf *input-routines*
816            (nconc *input-routines*
817                   (list (list ',type ',name ',size nil))))))
818
819 ;;; STREAM-IN routine for reading a string char
820 (def-input-routine input-character
821                    (character 1 sap head)
822   (code-char (sap-ref-8 sap head)))
823
824 ;;; STREAM-IN routine for reading an unsigned 8 bit number
825 (def-input-routine input-unsigned-8bit-byte
826                    ((unsigned-byte 8) 1 sap head)
827   (sap-ref-8 sap head))
828
829 ;;; STREAM-IN routine for reading a signed 8 bit number
830 (def-input-routine input-signed-8bit-number
831                    ((signed-byte 8) 1 sap head)
832   (signed-sap-ref-8 sap head))
833
834 ;;; STREAM-IN routine for reading an unsigned 16 bit number
835 (def-input-routine input-unsigned-16bit-byte
836                    ((unsigned-byte 16) 2 sap head)
837   (sap-ref-16 sap head))
838
839 ;;; STREAM-IN routine for reading a signed 16 bit number
840 (def-input-routine input-signed-16bit-byte
841                    ((signed-byte 16) 2 sap head)
842   (signed-sap-ref-16 sap head))
843
844 ;;; STREAM-IN routine for reading a unsigned 32 bit number
845 (def-input-routine input-unsigned-32bit-byte
846                    ((unsigned-byte 32) 4 sap head)
847   (sap-ref-32 sap head))
848
849 ;;; STREAM-IN routine for reading a signed 32 bit number
850 (def-input-routine input-signed-32bit-byte
851                    ((signed-byte 32) 4 sap head)
852   (signed-sap-ref-32 sap head))
853
854
855
856 ;;; Find an input routine to use given the type. Return as multiple
857 ;;; values the routine, the real type transfered, and the number of
858 ;;; bytes per element (and for character types string input routine).
859 (defun pick-input-routine (type &optional external-format)
860   (when (subtypep type 'character)
861     (dolist (entry *external-formats*)
862       (when (member external-format (first entry))
863         (return-from pick-input-routine
864           (values (symbol-function (third entry))
865                   'character
866                   1
867                   (symbol-function (second entry))
868                   (first (first entry)))))))
869   (dolist (entry *input-routines*)
870     (when (and (subtypep type (first entry))
871                (or (not (fourth entry))
872                    (eq external-format (fourth entry))))
873       (return-from pick-input-routine
874         (values (symbol-function (second entry))
875                 (first entry)
876                 (third entry)))))
877   ;; FIXME: let's do it the hard way, then (but ignore things like
878   ;; endianness, efficiency, and the necessary coupling between these
879   ;; and the output routines).  -- CSR, 2004-02-09
880   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
881         if (subtypep type `(unsigned-byte ,i))
882         do (return-from pick-input-routine
883              (values
884               (lambda (stream eof-error eof-value)
885                 (input-wrapper (stream (/ i 8) eof-error eof-value)
886                   (let ((sap (fd-stream-ibuf-sap stream))
887                         (head (fd-stream-ibuf-head stream)))
888                     (loop for j from 0 below (/ i 8)
889                           with result = 0
890                           do (setf result
891                                    (+ (* 256 result)
892                                       (sap-ref-8 sap (+ head j))))
893                           finally (return result)))))
894               `(unsigned-byte ,i)
895               (/ i 8))))
896   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
897         if (subtypep type `(signed-byte ,i))
898         do (return-from pick-input-routine
899              (values
900               (lambda (stream eof-error eof-value)
901                 (input-wrapper (stream (/ i 8) eof-error eof-value)
902                   (let ((sap (fd-stream-ibuf-sap stream))
903                         (head (fd-stream-ibuf-head stream)))
904                     (loop for j from 0 below (/ i 8)
905                           with result = 0
906                           do (setf result
907                                    (+ (* 256 result)
908                                       (sap-ref-8 sap (+ head j))))
909                           finally (return (if (logbitp (1- i) result)
910                                               (dpb result (byte i 0) -1)
911                                               result))))))
912               `(signed-byte ,i)
913               (/ i 8)))))
914
915 ;;; Return a string constructed from SAP, START, and END.
916 (defun string-from-sap (sap start end)
917   (declare (type index start end))
918   (let* ((length (- end start))
919          (string (make-string length)))
920     (copy-ub8-from-system-area sap start
921                                string 0
922                                length)
923     string))
924
925 ;;; the N-BIN method for FD-STREAMs
926 ;;;
927 ;;; Note that this blocks in UNIX-READ. It is generally used where
928 ;;; there is a definite amount of reading to be done, so blocking
929 ;;; isn't too problematical.
930 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
931                                &aux (total-copied 0))
932   (declare (type fd-stream stream))
933   (declare (type index start requested total-copied))
934   (let ((unread (fd-stream-unread stream)))
935     (when unread
936       ;; AVERs designed to fail when we have more complicated
937       ;; character representations.
938       (aver (typep unread 'base-char))
939       (aver (= (fd-stream-element-size stream) 1))
940       ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
941       ;; %BYTE-BLT
942       (etypecase buffer
943         (system-area-pointer
944          (setf (sap-ref-8 buffer start) (char-code unread)))
945         ((simple-unboxed-array (*))
946          (setf (aref buffer start) unread)))
947       (setf (fd-stream-unread stream) nil)
948       (setf (fd-stream-listen stream) nil)
949       (incf total-copied)))
950   (do ()
951       (nil)
952     (let* ((remaining-request (- requested total-copied))
953            (head (fd-stream-ibuf-head stream))
954            (tail (fd-stream-ibuf-tail stream))
955            (available (- tail head))
956            (n-this-copy (min remaining-request available))
957            (this-start (+ start total-copied))
958            (this-end (+ this-start n-this-copy))
959            (sap (fd-stream-ibuf-sap stream)))
960       (declare (type index remaining-request head tail available))
961       (declare (type index n-this-copy))
962       ;; Copy data from stream buffer into user's buffer.
963       (%byte-blt sap head buffer this-start this-end)
964       (incf (fd-stream-ibuf-head stream) n-this-copy)
965       (incf total-copied n-this-copy)
966       ;; Maybe we need to refill the stream buffer.
967       (cond (;; If there were enough data in the stream buffer, we're done.
968              (= total-copied requested)
969              (return total-copied))
970             (;; If EOF, we're done in another way.
971              (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
972              (if eof-error-p
973                  (error 'end-of-file :stream stream)
974                  (return total-copied)))
975             ;; Otherwise we refilled the stream buffer, so fall
976             ;; through into another pass of the loop.
977             ))))
978
979 (defun fd-stream-resync (stream)
980   (dolist (entry *external-formats*)
981     (when (member (fd-stream-external-format stream) (first entry))
982       (return-from fd-stream-resync
983         (funcall (symbol-function (eighth entry)) stream)))))
984
985 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
986 (defmacro define-external-format (external-format size output-restart
987                                   out-expr in-expr)
988   (let* ((name (first external-format))
989          (out-function (symbolicate "OUTPUT-BYTES/" name))
990          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
991          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
992          (in-char-function (symbolicate "INPUT-CHAR/" name)))
993     `(progn
994       (defun ,out-function (stream string flush-p start end)
995         (let ((start (or start 0))
996               (end (or end (length string))))
997           (declare (type index start end))
998           (when (and (not (fd-stream-dual-channel-p stream))
999                      (> (fd-stream-ibuf-tail stream)
1000                         (fd-stream-ibuf-head stream)))
1001             (file-position stream (file-position stream)))
1002           (when (< end start)
1003             (error ":END before :START!"))
1004           (do ()
1005               ((= end start))
1006             (setf (fd-stream-obuf-tail stream)
1007                   (flet ((do-it (string)
1008                            (do* ((len (fd-stream-obuf-length stream))
1009                                  (sap (fd-stream-obuf-sap stream))
1010                                  (tail (fd-stream-obuf-tail stream)))
1011                                 ((or (= start end) (< (- len tail) 4)) tail)
1012                              ,(if output-restart
1013                                   `(catch 'output-nothing
1014                                      (let* ((byte (aref string start))
1015                                             (bits (char-code byte)))
1016                                        ,out-expr
1017                                        (incf tail ,size)))
1018                                   `(let* ((byte (aref string start))
1019                                           (bits (char-code byte)))
1020                                      ,out-expr
1021                                      (incf tail ,size)))
1022                              (incf start))))
1023                     (declare (inline do-it))
1024                     ;; Specialized versions for the common cases of
1025                     ;; SIMPLE-BASE-STRING and (SIMPLE-ARRAY CHARACTER)
1026                     ;; to avoid doing a generic AREF.
1027                     (etypecase string
1028                       (simple-base-string
1029                        (do-it (the simple-base-string string)))
1030                       #!+sb-unicode
1031                       ((simple-array character)
1032                        ;; For some reason the type information from the
1033                        ;; etypecase doesn't propagate through here without
1034                        ;; an explicit THE.
1035                        (do-it (the (simple-array character) string)))
1036                       (string
1037                        (do-it string)))))
1038             (when (< start end)
1039               (flush-output-buffer stream)))
1040           (when flush-p
1041             (flush-output-buffer stream))))
1042       (def-output-routines (,format
1043                             ,size
1044                             ,output-restart
1045                             (:none character)
1046                             (:line character)
1047                             (:full character))
1048           (if (char= byte #\Newline)
1049               (setf (fd-stream-char-pos stream) 0)
1050               (incf (fd-stream-char-pos stream)))
1051         (let ((bits (char-code byte))
1052               (sap (fd-stream-obuf-sap stream))
1053               (tail (fd-stream-obuf-tail stream)))
1054           ,out-expr))
1055       (defun ,in-function (stream buffer start requested eof-error-p
1056                            &aux (index start) (end (+ start requested)))
1057         (declare (type fd-stream stream))
1058         (declare (type index start requested index end))
1059         (declare (type (simple-array character (#.+ansi-stream-in-buffer-length+)) buffer))
1060         (let ((unread (fd-stream-unread stream)))
1061           (when unread
1062             (setf (aref buffer index) unread)
1063             (setf (fd-stream-unread stream) nil)
1064             (setf (fd-stream-listen stream) nil)
1065             (incf index)))
1066         (do ()
1067             (nil)
1068           (let* ((head (fd-stream-ibuf-head stream))
1069                  (tail (fd-stream-ibuf-tail stream))
1070                  (sap (fd-stream-ibuf-sap stream)))
1071             (declare (type index head tail)
1072                      (type system-area-pointer sap))
1073             ;; Copy data from stream buffer into user's buffer.
1074             (dotimes (i (min (truncate (- tail head) ,size)
1075                              (- end index)))
1076               (declare (optimize speed))
1077               (let* ((byte (sap-ref-8 sap head)))
1078                 (setf (aref buffer index) ,in-expr)
1079                 (incf index)
1080                 (incf head ,size)))
1081             (setf (fd-stream-ibuf-head stream) head)
1082             ;; Maybe we need to refill the stream buffer.
1083             (cond ( ;; If there was enough data in the stream buffer, we're done.
1084                    (= index end)
1085                    (return (- index start)))
1086                   ( ;; If EOF, we're done in another way.
1087                    (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1088                    (if eof-error-p
1089                        (error 'end-of-file :stream stream)
1090                        (return (- index start))))
1091                   ;; Otherwise we refilled the stream buffer, so fall
1092                   ;; through into another pass of the loop.
1093                   ))))
1094       (def-input-routine ,in-char-function (character ,size sap head)
1095         (let ((byte (sap-ref-8 sap head)))
1096           ,in-expr))
1097       (setf *external-formats*
1098        (cons '(,external-format ,in-function ,in-char-function ,out-function
1099                ,@(mapcar #'(lambda (buffering)
1100                              (intern (format nil format (string buffering))))
1101                          '(:none :line :full)))
1102         *external-formats*)))))
1103
1104 (defmacro define-external-format/variable-width
1105     (external-format output-restart out-size-expr
1106      out-expr in-size-expr in-expr)
1107   (let* ((name (first external-format))
1108          (out-function (symbolicate "OUTPUT-BYTES/" name))
1109          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1110          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1111          (in-char-function (symbolicate "INPUT-CHAR/" name))
1112          (resync-function (symbolicate "RESYNC/" name)))
1113     `(progn
1114       (defun ,out-function (stream string flush-p start end)
1115         (let ((start (or start 0))
1116               (end (or end (length string))))
1117           (declare (type index start end))
1118           (when (and (not (fd-stream-dual-channel-p stream))
1119                      (> (fd-stream-ibuf-tail stream)
1120                         (fd-stream-ibuf-head stream)))
1121             (file-position stream (file-position stream)))
1122           (when (< end start)
1123             (error ":END before :START!"))
1124           (do ()
1125               ((= end start))
1126             (setf (fd-stream-obuf-tail stream)
1127                   (flet ((do-it (string)
1128                            (do* ((len (fd-stream-obuf-length stream))
1129                                  (sap (fd-stream-obuf-sap stream))
1130                                  (tail (fd-stream-obuf-tail stream)))
1131                                 ((or (= start end) (< (- len tail) 4)) tail)
1132                              ,(if output-restart
1133                                   `(catch 'output-nothing
1134                                      (let* ((byte (aref string start))
1135                                             (bits (char-code byte))
1136                                             (size ,out-size-expr))
1137                                        ,out-expr
1138                                        (incf tail size)))
1139                                   `(let* ((byte (aref string start))
1140                                           (bits (char-code byte))
1141                                           (size ,out-size-expr))
1142                                      ,out-expr
1143                                      (incf tail size)))
1144                              (incf start))))
1145                     (declare (inline do-it))
1146                     ;; Specialized versions for the common cases of
1147                     ;; SIMPLE-BASE-STRING and (SIMPLE-ARRAY CHARACTER)
1148                     ;; to avoid doing a generic AREF.
1149                     (etypecase string
1150                       (simple-base-string
1151                        (do-it (the simple-base-string string)))
1152                       #!+sb-unicode
1153                       ((simple-array character)
1154                        ;; For some reason the type information from the
1155                        ;; etypecase doesn't propagate through here without
1156                        ;; an explicit THE.
1157                        (do-it (the (simple-array character) string)))
1158                       (string
1159                        (do-it string)))))
1160             (when (< start end)
1161               (flush-output-buffer stream)))
1162           (when flush-p
1163             (flush-output-buffer stream))))
1164       (def-output-routines/variable-width (,format
1165                                            ,out-size-expr
1166                                            ,output-restart
1167                                            ,external-format
1168                                            (:none character)
1169                                            (:line character)
1170                                            (:full character))
1171           (if (char= byte #\Newline)
1172               (setf (fd-stream-char-pos stream) 0)
1173               (incf (fd-stream-char-pos stream)))
1174         (let ((bits (char-code byte))
1175               (sap (fd-stream-obuf-sap stream))
1176               (tail (fd-stream-obuf-tail stream)))
1177           ,out-expr))
1178       (defun ,in-function (stream buffer start requested eof-error-p
1179                            &aux (total-copied 0))
1180         (declare (type fd-stream stream))
1181         (declare (type index start requested total-copied))
1182         (declare (type (simple-array character (#.+ansi-stream-in-buffer-length+)) buffer))
1183         (let ((unread (fd-stream-unread stream)))
1184           (when unread
1185             (setf (aref buffer start) unread)
1186             (setf (fd-stream-unread stream) nil)
1187             (setf (fd-stream-listen stream) nil)
1188             (incf total-copied)))
1189         (do ()
1190             (nil)
1191           (let* ((head (fd-stream-ibuf-head stream))
1192                  (tail (fd-stream-ibuf-tail stream))
1193                  (sap (fd-stream-ibuf-sap stream))
1194                  (head-start head)
1195                  (decode-break-reason nil))
1196             (declare (type index head tail))
1197             ;; Copy data from stream buffer into user's buffer.
1198             (do ((size nil nil))
1199                 ((or (= tail head) (= requested total-copied)))
1200               (setf decode-break-reason
1201                     (block decode-break-reason
1202                       (let ((byte (sap-ref-8 sap head)))
1203                         (setq size ,in-size-expr)
1204                         (when (> size (- tail head))
1205                           (return))
1206                         (setf (aref buffer (+ start total-copied)) ,in-expr)
1207                         (incf total-copied)
1208                         (incf head size))
1209                       nil))
1210               (setf (fd-stream-ibuf-head stream) head)
1211               (when (and decode-break-reason
1212                          (= head head-start))
1213                 (when (stream-decoding-error-and-handle
1214                        stream decode-break-reason)
1215                   (if eof-error-p
1216                       (error 'end-of-file :stream stream)
1217                       (return-from ,in-function total-copied)))
1218                 (setf head (fd-stream-ibuf-head stream))
1219                 (setf tail (fd-stream-ibuf-tail stream))))
1220             (setf (fd-stream-ibuf-head stream) head)
1221             ;; Maybe we need to refill the stream buffer.
1222             (cond ( ;; If there were enough data in the stream buffer, we're done.
1223                    (= total-copied requested)
1224                    (return total-copied))
1225                   ( ;; If EOF, we're done in another way.
1226                    (or (eq decode-break-reason 'eof)
1227                        (null (catch 'eof-input-catcher
1228                                (refill-buffer/fd stream))))
1229                    (if eof-error-p
1230                        (error 'end-of-file :stream stream)
1231                        (return total-copied)))
1232                   ;; Otherwise we refilled the stream buffer, so fall
1233                   ;; through into another pass of the loop.
1234                   ))))
1235       (def-input-routine/variable-width ,in-char-function (character
1236                                                            ,external-format
1237                                                            ,in-size-expr
1238                                                            sap head)
1239         (let ((byte (sap-ref-8 sap head)))
1240           ,in-expr))
1241       (defun ,resync-function (stream)
1242         (loop (input-at-least stream 1)
1243               (incf (fd-stream-ibuf-head stream))
1244               (unless (block decode-break-reason
1245                         (let* ((sap (fd-stream-ibuf-sap stream))
1246                                (head (fd-stream-ibuf-head stream))
1247                                (byte (sap-ref-8 sap head))
1248                                (size ,in-size-expr))
1249                           ,in-expr)
1250                         nil)
1251                 (return))))
1252       (setf *external-formats*
1253        (cons '(,external-format ,in-function ,in-char-function ,out-function
1254                ,@(mapcar #'(lambda (buffering)
1255                              (intern (format nil format (string buffering))))
1256                          '(:none :line :full))
1257                ,resync-function)
1258         *external-formats*)))))
1259
1260 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1261 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1262 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1263 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1264     1 t
1265   (if (>= bits 256)
1266       (stream-encoding-error-and-handle stream bits)
1267       (setf (sap-ref-8 sap tail) bits))
1268   (code-char byte))
1269
1270 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1271                          :iso-646 :iso-646-us :|646|)
1272     1 t
1273   (if (>= bits 128)
1274       (stream-encoding-error-and-handle stream bits)
1275       (setf (sap-ref-8 sap tail) bits))
1276   (code-char byte))
1277
1278 (let* ((table (let ((s (make-string 256)))
1279                 (map-into s #'code-char
1280                           '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1281                             #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1282                             #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1283                             #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1284                             #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1285                             #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1286                             #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1287                             #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1288                             #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1289                             #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1290                             #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1291                             #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1292                             #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1293                             #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1294                             #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1295                             #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1296                 s))
1297        (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1298                           (loop for char across table for i from 0
1299                                do (aver (= 0 (aref rt (char-code char))))
1300                                do (setf (aref rt (char-code char)) i))
1301                           rt)))
1302   (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1303       1 t
1304     (if (>= bits 256)
1305         (stream-encoding-error-and-handle stream bits)
1306         (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1307     (aref table byte)))
1308
1309
1310 #!+sb-unicode
1311 (let ((latin-9-table (let ((table (make-string 256)))
1312                        (do ((i 0 (1+ i)))
1313                            ((= i 256))
1314                          (setf (aref table i) (code-char i)))
1315                        (setf (aref table #xa4) (code-char #x20ac))
1316                        (setf (aref table #xa6) (code-char #x0160))
1317                        (setf (aref table #xa8) (code-char #x0161))
1318                        (setf (aref table #xb4) (code-char #x017d))
1319                        (setf (aref table #xb8) (code-char #x017e))
1320                        (setf (aref table #xbc) (code-char #x0152))
1321                        (setf (aref table #xbd) (code-char #x0153))
1322                        (setf (aref table #xbe) (code-char #x0178))
1323                        table))
1324       (latin-9-reverse-1 (make-array 16
1325                                      :element-type '(unsigned-byte 21)
1326                                      :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1327       (latin-9-reverse-2 (make-array 16
1328                                      :element-type '(unsigned-byte 8)
1329                                      :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1330   (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1331       1 t
1332     (setf (sap-ref-8 sap tail)
1333           (if (< bits 256)
1334               (if (= bits (char-code (aref latin-9-table bits)))
1335                   bits
1336                   (stream-encoding-error-and-handle stream byte))
1337               (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1338                   (aref latin-9-reverse-2 (logand bits 15))
1339                   (stream-encoding-error-and-handle stream byte))))
1340     (aref latin-9-table byte)))
1341
1342 (define-external-format/variable-width (:utf-8 :utf8) nil
1343   (let ((bits (char-code byte)))
1344     (cond ((< bits #x80) 1)
1345           ((< bits #x800) 2)
1346           ((< bits #x10000) 3)
1347           (t 4)))
1348   (ecase size
1349     (1 (setf (sap-ref-8 sap tail) bits))
1350     (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1351              (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 0) bits))))
1352     (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1353              (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 6) bits))
1354              (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1355     (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1356              (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 12) bits))
1357              (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1358              (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1359   (cond ((< byte #x80) 1)
1360         ((< byte #xc2) (return-from decode-break-reason 1))
1361         ((< byte #xe0) 2)
1362         ((< byte #xf0) 3)
1363         (t 4))
1364   (code-char (ecase size
1365                (1 byte)
1366                (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1367                     (unless (<= #x80 byte2 #xbf)
1368                       (return-from decode-break-reason 2))
1369                     (dpb byte (byte 5 6) byte2)))
1370                (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1371                         (byte3 (sap-ref-8 sap (+ 2 head))))
1372                     (unless (and (<= #x80 byte2 #xbf)
1373                                  (<= #x80 byte3 #xbf))
1374                       (return-from decode-break-reason 3))
1375                     (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1376                (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1377                         (byte3 (sap-ref-8 sap (+ 2 head)))
1378                         (byte4 (sap-ref-8 sap (+ 3 head))))
1379                     (unless (and (<= #x80 byte2 #xbf)
1380                                  (<= #x80 byte3 #xbf)
1381                                  (<= #x80 byte4 #xbf))
1382                       (return-from decode-break-reason 4))
1383                     (dpb byte (byte 3 18)
1384                          (dpb byte2 (byte 6 12)
1385                               (dpb byte3 (byte 6 6) byte4))))))))
1386 \f
1387 ;;;; utility functions (misc routines, etc)
1388
1389 ;;; Fill in the various routine slots for the given type. INPUT-P and
1390 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1391 ;;; set prior to calling this routine.
1392 (defun set-fd-stream-routines (fd-stream element-type external-format
1393                                input-p output-p buffer-p)
1394   (let* ((target-type (case element-type
1395                         (unsigned-byte '(unsigned-byte 8))
1396                         (signed-byte '(signed-byte 8))
1397                         (:default 'character)
1398                         (t element-type)))
1399          (character-stream-p (subtypep target-type 'character))
1400          (bivalent-stream-p (eq element-type :default))
1401          normalized-external-format
1402          (bin-routine #'ill-bin)
1403          (bin-type nil)
1404          (bin-size nil)
1405          (cin-routine #'ill-in)
1406          (cin-type nil)
1407          (cin-size nil)
1408          (input-type nil)           ;calculated from bin-type/cin-type
1409          (input-size nil)           ;calculated from bin-size/cin-size
1410          (read-n-characters #'ill-in)
1411          (bout-routine #'ill-bout)
1412          (bout-type nil)
1413          (bout-size nil)
1414          (cout-routine #'ill-out)
1415          (cout-type nil)
1416          (cout-size nil)
1417          (output-type nil)
1418          (output-size nil)
1419          (output-bytes #'ill-bout))
1420
1421     ;; drop buffers when direction changes
1422     (when (and (fd-stream-obuf-sap fd-stream) (not output-p))
1423       (with-available-buffers-lock ()
1424         (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1425         (setf (fd-stream-obuf-sap fd-stream) nil)))
1426     (when (and (fd-stream-ibuf-sap fd-stream) (not input-p))
1427       (with-available-buffers-lock ()
1428         (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1429         (setf (fd-stream-ibuf-sap fd-stream) nil)))
1430     (when input-p
1431       (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
1432       (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
1433       (setf (fd-stream-ibuf-tail fd-stream) 0))
1434     (when output-p
1435       (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
1436       (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
1437       (setf (fd-stream-obuf-tail fd-stream) 0)
1438       (setf (fd-stream-char-pos fd-stream) 0))
1439
1440     (when (and character-stream-p
1441                (eq external-format :default))
1442       (/show0 "/getting default external format")
1443       (setf external-format (default-external-format)))
1444
1445     (when input-p
1446       (when (or (not character-stream-p) bivalent-stream-p)
1447         (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1448                                           normalized-external-format)
1449           (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1450                                   target-type)
1451                               external-format))
1452         (unless bin-routine
1453           (error "could not find any input routine for ~S" target-type)))
1454       (when character-stream-p
1455         (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1456                                           normalized-external-format)
1457           (pick-input-routine target-type external-format))
1458         (unless cin-routine
1459           (error "could not find any input routine for ~S" target-type)))
1460       (setf (fd-stream-in fd-stream) cin-routine
1461             (fd-stream-bin fd-stream) bin-routine)
1462       ;; character type gets preferential treatment
1463       (setf input-size (or cin-size bin-size))
1464       (setf input-type (or cin-type bin-type))
1465       (when normalized-external-format
1466         (setf (fd-stream-external-format fd-stream)
1467               normalized-external-format))
1468       (when (= (or cin-size 1) (or bin-size 1) 1)
1469         (setf (fd-stream-n-bin fd-stream) ;XXX
1470               (if (and character-stream-p (not bivalent-stream-p))
1471                   read-n-characters
1472                   #'fd-stream-read-n-bytes))
1473         ;; Sometimes turn on fast-read-char/fast-read-byte.  Switch on
1474         ;; for character and (unsigned-byte 8) streams.  In these
1475         ;; cases, fast-read-* will read from the
1476         ;; ansi-stream-(c)in-buffer, saving function calls.
1477         ;; Otherwise, the various data-reading functions in the stream
1478         ;; structure will be called.
1479         (when (and buffer-p
1480                    (not bivalent-stream-p)
1481                    ;; temporary disable on :io streams
1482                    (not output-p))
1483           (cond (character-stream-p
1484                  (setf (ansi-stream-cin-buffer fd-stream)
1485                        (make-array +ansi-stream-in-buffer-length+
1486                                    :element-type 'character)))
1487                 ((equal target-type '(unsigned-byte 8))
1488                  (setf (ansi-stream-in-buffer fd-stream)
1489                        (make-array +ansi-stream-in-buffer-length+
1490                                    :element-type '(unsigned-byte 8))))))))
1491
1492     (when output-p
1493       (when (or (not character-stream-p) bivalent-stream-p)
1494         (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1495                                            normalized-external-format)
1496           (pick-output-routine (if bivalent-stream-p
1497                                    '(unsigned-byte 8)
1498                                    target-type)
1499                                (fd-stream-buffering fd-stream)
1500                                external-format))
1501         (unless bout-routine
1502           (error "could not find any output routine for ~S buffered ~S"
1503                  (fd-stream-buffering fd-stream)
1504                  target-type)))
1505       (when character-stream-p
1506         (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1507                                            normalized-external-format)
1508           (pick-output-routine target-type
1509                                (fd-stream-buffering fd-stream)
1510                                external-format))
1511         (unless cout-routine
1512           (error "could not find any output routine for ~S buffered ~S"
1513                  (fd-stream-buffering fd-stream)
1514                  target-type)))
1515       (when normalized-external-format
1516         (setf (fd-stream-external-format fd-stream)
1517               normalized-external-format))
1518       (when character-stream-p
1519         (setf (fd-stream-output-bytes fd-stream) output-bytes))
1520       (setf (fd-stream-out fd-stream) cout-routine
1521             (fd-stream-bout fd-stream) bout-routine
1522             (fd-stream-sout fd-stream) (if (eql cout-size 1)
1523                                            #'fd-sout #'ill-out))
1524       (setf output-size (or cout-size bout-size))
1525       (setf output-type (or cout-type bout-type)))
1526
1527     (when (and input-size output-size
1528                (not (eq input-size output-size)))
1529       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1530              input-type input-size
1531              output-type output-size))
1532     (setf (fd-stream-element-size fd-stream)
1533           (or input-size output-size))
1534
1535     (setf (fd-stream-element-type fd-stream)
1536           (cond ((equal input-type output-type)
1537                  input-type)
1538                 ((null output-type)
1539                  input-type)
1540                 ((null input-type)
1541                  output-type)
1542                 ((subtypep input-type output-type)
1543                  input-type)
1544                 ((subtypep output-type input-type)
1545                  output-type)
1546                 (t
1547                  (error "Input type (~S) and output type (~S) are unrelated?"
1548                         input-type
1549                         output-type))))))
1550
1551 ;;; Handle miscellaneous operations on FD-STREAM.
1552 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1553   (declare (ignore arg2))
1554   (case operation
1555     (:listen
1556      (or (not (eql (fd-stream-ibuf-head fd-stream)
1557                    (fd-stream-ibuf-tail fd-stream)))
1558          (fd-stream-listen fd-stream)
1559          (setf (fd-stream-listen fd-stream)
1560                (eql (sb!unix:with-restarted-syscall ()
1561                       (sb!alien:with-alien ((read-fds (sb!alien:struct
1562                                                        sb!unix:fd-set)))
1563                         (sb!unix:fd-zero read-fds)
1564                         (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
1565                         (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
1566                                                   (sb!alien:addr read-fds)
1567                                                   nil nil 0 0)))
1568                     1))))
1569     (:unread
1570      (setf (fd-stream-unread fd-stream) arg1)
1571      (setf (fd-stream-listen fd-stream) t))
1572     (:close
1573      (cond (arg1 ; We got us an abort on our hands.
1574             (when (fd-stream-handler fd-stream)
1575               (sb!sys:remove-fd-handler (fd-stream-handler fd-stream))
1576               (setf (fd-stream-handler fd-stream) nil))
1577             ;; We can't do anything unless we know what file were
1578             ;; dealing with, and we don't want to do anything
1579             ;; strange unless we were writing to the file.
1580             (when (and (fd-stream-file fd-stream)
1581                        (fd-stream-obuf-sap fd-stream))
1582               (if (fd-stream-original fd-stream)
1583                   ;; If the original is EQ to file we are appending
1584                   ;; and can just close the file without renaming.
1585                   (unless (eq (fd-stream-original fd-stream)
1586                               (fd-stream-file fd-stream))
1587                     ;; We have a handle on the original, just revert.
1588                     (multiple-value-bind (okay err)
1589                         (sb!unix:unix-rename (fd-stream-original fd-stream)
1590                                              (fd-stream-file fd-stream))
1591                       (unless okay
1592                         (simple-stream-perror
1593                          "couldn't restore ~S to its original contents"
1594                          fd-stream
1595                          err))))
1596                   ;; We can't restore the original, and aren't
1597                   ;; appending, so nuke that puppy.
1598                   ;;
1599                   ;; FIXME: This is currently the fate of superseded
1600                   ;; files, and according to the CLOSE spec this is
1601                   ;; wrong. However, there seems to be no clean way to
1602                   ;; do that that doesn't involve either copying the
1603                   ;; data (bad if the :abort resulted from a full
1604                   ;; disk), or renaming the old file temporarily
1605                   ;; (probably bad because stream opening becomes more
1606                   ;; racy).
1607                   (multiple-value-bind (okay err)
1608                       (sb!unix:unix-unlink (fd-stream-file fd-stream))
1609                     (unless okay
1610                       (error 'simple-file-error
1611                              :pathname (fd-stream-file fd-stream)
1612                              :format-control
1613                              "~@<couldn't remove ~S: ~2I~_~A~:>"
1614                              :format-arguments (list (fd-stream-file fd-stream)
1615                                                      (strerror err))))))))
1616            (t
1617             (fd-stream-misc-routine fd-stream :finish-output)
1618             (when (and (fd-stream-original fd-stream)
1619                        (fd-stream-delete-original fd-stream))
1620               (multiple-value-bind (okay err)
1621                   (sb!unix:unix-unlink (fd-stream-original fd-stream))
1622                 (unless okay
1623                   (error 'simple-file-error
1624                          :pathname (fd-stream-original fd-stream)
1625                          :format-control
1626                          "~@<couldn't delete ~S during close of ~S: ~
1627                           ~2I~_~A~:>"
1628                          :format-arguments
1629                          (list (fd-stream-original fd-stream)
1630                                fd-stream
1631                                (strerror err))))))))
1632      (when (fboundp 'cancel-finalization)
1633        (cancel-finalization fd-stream))
1634      (sb!unix:unix-close (fd-stream-fd fd-stream))
1635      (when (fd-stream-obuf-sap fd-stream)
1636        (with-available-buffers-lock ()
1637          (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1638          (setf (fd-stream-obuf-sap fd-stream) nil)))
1639      (when (fd-stream-ibuf-sap fd-stream)
1640        (with-available-buffers-lock ()
1641          (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1642          (setf (fd-stream-ibuf-sap fd-stream) nil)))
1643      (sb!impl::set-closed-flame fd-stream))
1644     (:clear-input
1645      (setf (fd-stream-unread fd-stream) nil)
1646      (setf (fd-stream-ibuf-head fd-stream) 0)
1647      (setf (fd-stream-ibuf-tail fd-stream) 0)
1648      (catch 'eof-input-catcher
1649        (loop
1650         (let ((count (sb!unix:with-restarted-syscall ()
1651                        (sb!alien:with-alien ((read-fds (sb!alien:struct
1652                                                         sb!unix:fd-set)))
1653                          (sb!unix:fd-zero read-fds)
1654                          (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
1655                          (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
1656                                                    (sb!alien:addr read-fds)
1657                                                    nil nil 0 0)))))
1658           (cond ((eql count 1)
1659                  (refill-buffer/fd fd-stream)
1660                  (setf (fd-stream-ibuf-head fd-stream) 0)
1661                  (setf (fd-stream-ibuf-tail fd-stream) 0))
1662                 (t
1663                  (return t)))))))
1664     (:force-output
1665      (flush-output-buffer fd-stream))
1666     (:finish-output
1667      (flush-output-buffer fd-stream)
1668      (do ()
1669          ((null (fd-stream-output-later fd-stream)))
1670        (sb!sys:serve-all-events)))
1671     (:element-type
1672      (fd-stream-element-type fd-stream))
1673     (:external-format
1674      (fd-stream-external-format fd-stream))
1675     (:interactive-p
1676      (= 1 (the (member 0 1)
1677             (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
1678     (:line-length
1679      80)
1680     (:charpos
1681      (fd-stream-char-pos fd-stream))
1682     (:file-length
1683      (unless (fd-stream-file fd-stream)
1684        ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
1685        ;; "should signal an error of type TYPE-ERROR if stream is not
1686        ;; a stream associated with a file". Too bad there's no very
1687        ;; appropriate value for the EXPECTED-TYPE slot..
1688        (error 'simple-type-error
1689               :datum fd-stream
1690               :expected-type 'fd-stream
1691               :format-control "~S is not a stream associated with a file."
1692               :format-arguments (list fd-stream)))
1693      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
1694                            atime mtime ctime blksize blocks)
1695          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
1696        (declare (ignore ino nlink uid gid rdev
1697                         atime mtime ctime blksize blocks))
1698        (unless okay
1699          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
1700        (if (zerop mode)
1701            nil
1702            (truncate size (fd-stream-element-size fd-stream)))))
1703     ;; FIXME: I doubt this is correct in the presence of Unicode,
1704     ;; since fd-stream FILE-POSITION is measured in bytes.
1705     (:file-string-length
1706      (etypecase arg1
1707        (character 1)
1708        (string (length arg1))))
1709     (:file-position
1710      (fd-stream-file-position fd-stream arg1))))
1711
1712 (defun fd-stream-file-position (stream &optional newpos)
1713   (declare (type fd-stream stream)
1714            (type (or (alien sb!unix:off-t) (member nil :start :end)) newpos))
1715   (if (null newpos)
1716       (sb!sys:without-interrupts
1717         ;; First, find the position of the UNIX file descriptor in the file.
1718         (multiple-value-bind (posn errno)
1719             (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)
1720           (declare (type (or (alien sb!unix:off-t) null) posn))
1721           (cond ((integerp posn)
1722                  ;; Adjust for buffered output: If there is any output
1723                  ;; buffered, the *real* file position will be larger
1724                  ;; than reported by lseek() because lseek() obviously
1725                  ;; cannot take into account output we have not sent
1726                  ;; yet.
1727                  (dolist (later (fd-stream-output-later stream))
1728                    (incf posn (- (caddr later)
1729                                  (cadr later))))
1730                  (incf posn (fd-stream-obuf-tail stream))
1731                  ;; Adjust for unread input: If there is any input
1732                  ;; read from UNIX but not supplied to the user of the
1733                  ;; stream, the *real* file position will smaller than
1734                  ;; reported, because we want to look like the unread
1735                  ;; stuff is still available.
1736                  (decf posn (- (fd-stream-ibuf-tail stream)
1737                                (fd-stream-ibuf-head stream)))
1738                  (when (fd-stream-unread stream)
1739                    (decf posn))
1740                  ;; Divide bytes by element size.
1741                  (truncate posn (fd-stream-element-size stream)))
1742                 ((eq errno sb!unix:espipe)
1743                  nil)
1744                 (t
1745                  (sb!sys:with-interrupts
1746                    (simple-stream-perror "failure in Unix lseek() on ~S"
1747                                          stream
1748                                          errno))))))
1749       (let ((offset 0) origin)
1750         (declare (type (alien sb!unix:off-t) offset))
1751         ;; Make sure we don't have any output pending, because if we
1752         ;; move the file pointer before writing this stuff, it will be
1753         ;; written in the wrong location.
1754         (flush-output-buffer stream)
1755         (do ()
1756             ((null (fd-stream-output-later stream)))
1757           (sb!sys:serve-all-events))
1758         ;; Clear out any pending input to force the next read to go to
1759         ;; the disk.
1760         (setf (fd-stream-unread stream) nil)
1761         (setf (fd-stream-ibuf-head stream) 0)
1762         (setf (fd-stream-ibuf-tail stream) 0)
1763         ;; Trash cached value for listen, so that we check next time.
1764         (setf (fd-stream-listen stream) nil)
1765         ;; Now move it.
1766         (cond ((eq newpos :start)
1767                (setf offset 0 origin sb!unix:l_set))
1768               ((eq newpos :end)
1769                (setf offset 0 origin sb!unix:l_xtnd))
1770               ((typep newpos '(alien sb!unix:off-t))
1771                (setf offset (* newpos (fd-stream-element-size stream))
1772                      origin sb!unix:l_set))
1773               (t
1774                (error "invalid position given to FILE-POSITION: ~S" newpos)))
1775         (multiple-value-bind (posn errno)
1776             (sb!unix:unix-lseek (fd-stream-fd stream) offset origin)
1777           (cond ((typep posn '(alien sb!unix:off-t))
1778                  t)
1779                 ((eq errno sb!unix:espipe)
1780                  nil)
1781                 (t
1782                  (simple-stream-perror "error in Unix lseek() on ~S"
1783                                        stream
1784                                        errno)))))))
1785 \f
1786 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
1787
1788 ;;; Create a stream for the given Unix file descriptor.
1789 ;;;
1790 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
1791 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
1792 ;;; default to allowing input.
1793 ;;;
1794 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
1795 ;;;
1796 ;;; BUFFERING indicates the kind of buffering to use.
1797 ;;;
1798 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
1799 ;;; NIL (the default), then wait forever. When we time out, we signal
1800 ;;; IO-TIMEOUT.
1801 ;;;
1802 ;;; FILE is the name of the file (will be returned by PATHNAME).
1803 ;;;
1804 ;;; NAME is used to identify the stream when printed.
1805 (defun make-fd-stream (fd
1806                        &key
1807                        (input nil input-p)
1808                        (output nil output-p)
1809                        (element-type 'base-char)
1810                        (buffering :full)
1811                        (external-format :default)
1812                        timeout
1813                        file
1814                        original
1815                        delete-original
1816                        pathname
1817                        input-buffer-p
1818                        dual-channel-p
1819                        (name (if file
1820                                  (format nil "file ~A" file)
1821                                  (format nil "descriptor ~W" fd)))
1822                        auto-close)
1823   (declare (type index fd) (type (or index null) timeout)
1824            (type (member :none :line :full) buffering))
1825   (cond ((not (or input-p output-p))
1826          (setf input t))
1827         ((not (or input output))
1828          (error "File descriptor must be opened either for input or output.")))
1829   (let ((stream (%make-fd-stream :fd fd
1830                                  :name name
1831                                  :file file
1832                                  :original original
1833                                  :delete-original delete-original
1834                                  :pathname pathname
1835                                  :buffering buffering
1836                                  :dual-channel-p dual-channel-p
1837                                  :external-format external-format
1838                                  :timeout timeout)))
1839     (set-fd-stream-routines stream element-type external-format
1840                             input output input-buffer-p)
1841     (when (and auto-close (fboundp 'finalize))
1842       (finalize stream
1843                 (lambda ()
1844                   (sb!unix:unix-close fd)
1845                   #!+sb-show
1846                   (format *terminal-io* "** closed file descriptor ~W **~%"
1847                           fd))))
1848     stream))
1849
1850 ;;; Pick a name to use for the backup file for the :IF-EXISTS
1851 ;;; :RENAME-AND-DELETE and :RENAME options.
1852 (defun pick-backup-name (name)
1853   (declare (type simple-base-string name))
1854   (concatenate 'simple-base-string name ".bak"))
1855
1856 ;;; Ensure that the given arg is one of the given list of valid
1857 ;;; things. Allow the user to fix any problems.
1858 (defun ensure-one-of (item list what)
1859   (unless (member item list)
1860     (error 'simple-type-error
1861            :datum item
1862            :expected-type `(member ,@list)
1863            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
1864            :format-arguments (list item what list))))
1865
1866 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
1867 ;;; access, since we don't want to trash unwritable files even if we
1868 ;;; technically can. We return true if we succeed in renaming.
1869 (defun rename-the-old-one (namestring original)
1870   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
1871     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
1872   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
1873     (if okay
1874         t
1875         (error 'simple-file-error
1876                :pathname namestring
1877                :format-control
1878                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
1879                :format-arguments (list namestring original (strerror err))))))
1880
1881 (defun open (filename
1882              &key
1883              (direction :input)
1884              (element-type 'base-char)
1885              (if-exists nil if-exists-given)
1886              (if-does-not-exist nil if-does-not-exist-given)
1887              (external-format :default)
1888              &aux ; Squelch assignment warning.
1889              (direction direction)
1890              (if-does-not-exist if-does-not-exist)
1891              (if-exists if-exists))
1892   #!+sb-doc
1893   "Return a stream which reads from or writes to FILENAME.
1894   Defined keywords:
1895    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
1896    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
1897    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
1898                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
1899    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
1900   See the manual for details."
1901
1902   ;; Calculate useful stuff.
1903   (multiple-value-bind (input output mask)
1904       (case direction
1905         (:input  (values   t nil sb!unix:o_rdonly))
1906         (:output (values nil   t sb!unix:o_wronly))
1907         (:io     (values   t   t sb!unix:o_rdwr))
1908         (:probe  (values   t nil sb!unix:o_rdonly)))
1909     (declare (type index mask))
1910     (let* ((pathname (merge-pathnames filename))
1911            (namestring
1912             (cond ((unix-namestring pathname input))
1913                   ((and input (eq if-does-not-exist :create))
1914                    (unix-namestring pathname nil))
1915                   ((and (eq direction :io) (not if-does-not-exist-given))
1916                    (unix-namestring pathname nil)))))
1917       ;; Process if-exists argument if we are doing any output.
1918       (cond (output
1919              (unless if-exists-given
1920                (setf if-exists
1921                      (if (eq (pathname-version pathname) :newest)
1922                          :new-version
1923                          :error)))
1924              (ensure-one-of if-exists
1925                             '(:error :new-version :rename
1926                                      :rename-and-delete :overwrite
1927                                      :append :supersede nil)
1928                             :if-exists)
1929              (case if-exists
1930                ((:new-version :error nil)
1931                 (setf mask (logior mask sb!unix:o_excl)))
1932                ((:rename :rename-and-delete)
1933                 (setf mask (logior mask sb!unix:o_creat)))
1934                ((:supersede)
1935                 (setf mask (logior mask sb!unix:o_trunc)))
1936                (:append
1937                 (setf mask (logior mask sb!unix:o_append)))))
1938             (t
1939              (setf if-exists :ignore-this-arg)))
1940
1941       (unless if-does-not-exist-given
1942         (setf if-does-not-exist
1943               (cond ((eq direction :input) :error)
1944                     ((and output
1945                           (member if-exists '(:overwrite :append)))
1946                      :error)
1947                     ((eq direction :probe)
1948                      nil)
1949                     (t
1950                      :create))))
1951       (ensure-one-of if-does-not-exist
1952                      '(:error :create nil)
1953                      :if-does-not-exist)
1954       (if (eq if-does-not-exist :create)
1955         (setf mask (logior mask sb!unix:o_creat)))
1956
1957       (let ((original (case if-exists
1958                         ((:rename :rename-and-delete)
1959                          (pick-backup-name namestring))
1960                         ((:append :overwrite)
1961                          ;; KLUDGE: Provent CLOSE from deleting
1962                          ;; appending streams when called with :ABORT T
1963                          namestring)))
1964             (delete-original (eq if-exists :rename-and-delete))
1965             (mode #o666))
1966         (when (and original (not (eq original namestring)))
1967           ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
1968           ;; whether the file already exists, make sure the original
1969           ;; file is not a directory, and keep the mode.
1970           (let ((exists
1971                  (and namestring
1972                       (multiple-value-bind (okay err/dev inode orig-mode)
1973                           (sb!unix:unix-stat namestring)
1974                         (declare (ignore inode)
1975                                  (type (or index null) orig-mode))
1976                         (cond
1977                          (okay
1978                           (when (and output (= (logand orig-mode #o170000)
1979                                                #o40000))
1980                             (error 'simple-file-error
1981                                    :pathname namestring
1982                                    :format-control
1983                                    "can't open ~S for output: is a directory"
1984                                    :format-arguments (list namestring)))
1985                           (setf mode (logand orig-mode #o777))
1986                           t)
1987                          ((eql err/dev sb!unix:enoent)
1988                           nil)
1989                          (t
1990                           (simple-file-perror "can't find ~S"
1991                                               namestring
1992                                               err/dev)))))))
1993             (unless (and exists
1994                          (rename-the-old-one namestring original))
1995               (setf original nil)
1996               (setf delete-original nil)
1997               ;; In order to use :SUPERSEDE instead, we have to make
1998               ;; sure SB!UNIX:O_CREAT corresponds to
1999               ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2000               ;; because of IF-EXISTS being :RENAME.
2001               (unless (eq if-does-not-exist :create)
2002                 (setf mask
2003                       (logior (logandc2 mask sb!unix:o_creat)
2004                               sb!unix:o_trunc)))
2005               (setf if-exists :supersede))))
2006
2007         ;; Now we can try the actual Unix open(2).
2008         (multiple-value-bind (fd errno)
2009             (if namestring
2010                 (sb!unix:unix-open namestring mask mode)
2011                 (values nil sb!unix:enoent))
2012           (labels ((open-error (format-control &rest format-arguments)
2013                      (error 'simple-file-error
2014                             :pathname pathname
2015                             :format-control format-control
2016                             :format-arguments format-arguments))
2017                    (vanilla-open-error ()
2018                      (simple-file-perror "error opening ~S" pathname errno)))
2019             (cond ((numberp fd)
2020                    (case direction
2021                      ((:input :output :io)
2022                       (make-fd-stream fd
2023                                       :input input
2024                                       :output output
2025                                       :element-type element-type
2026                                       :external-format external-format
2027                                       :file namestring
2028                                       :original original
2029                                       :delete-original delete-original
2030                                       :pathname pathname
2031                                       :dual-channel-p nil
2032                                       :input-buffer-p t
2033                                       :auto-close t))
2034                      (:probe
2035                       (let ((stream
2036                              (%make-fd-stream :name namestring
2037                                               :fd fd
2038                                               :pathname pathname
2039                                               :element-type element-type)))
2040                         (close stream)
2041                         stream))))
2042                   ((eql errno sb!unix:enoent)
2043                    (case if-does-not-exist
2044                      (:error (vanilla-open-error))
2045                      (:create
2046                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2047                                   pathname))
2048                      (t nil)))
2049                   ((and (eql errno sb!unix:eexist) (null if-exists))
2050                    nil)
2051                   (t
2052                    (vanilla-open-error)))))))))
2053 \f
2054 ;;;; initialization
2055
2056 ;;; the stream connected to the controlling terminal, or NIL if there is none
2057 (defvar *tty*)
2058
2059 ;;; the stream connected to the standard input (file descriptor 0)
2060 (defvar *stdin*)
2061
2062 ;;; the stream connected to the standard output (file descriptor 1)
2063 (defvar *stdout*)
2064
2065 ;;; the stream connected to the standard error output (file descriptor 2)
2066 (defvar *stderr*)
2067
2068 ;;; This is called when the cold load is first started up, and may also
2069 ;;; be called in an attempt to recover from nested errors.
2070 (defun stream-cold-init-or-reset ()
2071   (stream-reinit)
2072   (setf *terminal-io* (make-synonym-stream '*tty*))
2073   (setf *standard-output* (make-synonym-stream '*stdout*))
2074   (setf *standard-input* (make-synonym-stream '*stdin*))
2075   (setf *error-output* (make-synonym-stream '*stderr*))
2076   (setf *query-io* (make-synonym-stream '*terminal-io*))
2077   (setf *debug-io* *query-io*)
2078   (setf *trace-output* *standard-output*)
2079   (values))
2080
2081 ;;; This is called whenever a saved core is restarted.
2082 (defun stream-reinit ()
2083   (setf *available-buffers* nil)
2084   (with-output-to-string (*error-output*)
2085     (setf *stdin*
2086           (make-fd-stream 0 :name "standard input" :input t :buffering :line))
2087     (setf *stdout*
2088           (make-fd-stream 1 :name "standard output" :output t :buffering :line))
2089     (setf *stderr*
2090           (make-fd-stream 2 :name "standard error" :output t :buffering :line))
2091     (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2092            (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2093       (if tty
2094           (setf *tty*
2095                 (make-fd-stream tty
2096                                 :name "the terminal"
2097                                 :input t
2098                                 :output t
2099                                 :buffering :line
2100                                 :auto-close t))
2101           (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2102     (princ (get-output-stream-string *error-output*) *stderr*))
2103   (values))
2104 \f
2105 ;;;; miscellany
2106
2107 ;;; the Unix way to beep
2108 (defun beep (stream)
2109   (write-char (code-char bell-char-code) stream)
2110   (finish-output stream))
2111
2112 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2113 ;;; by the filesys stuff to get and set the file name.
2114 ;;;
2115 ;;; FIXME: misleading name, screwy interface
2116 (defun file-name (stream &optional new-name)
2117   (when (typep stream 'fd-stream)
2118       (cond (new-name
2119              (setf (fd-stream-pathname stream) new-name)
2120              (setf (fd-stream-file stream)
2121                    (unix-namestring new-name nil))
2122              t)
2123             (t
2124              (fd-stream-pathname stream)))))