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