1.0.27.1: Fix binary input after UNREAD-CHAR on bivalent streams.
[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
15 ;;;;
16 ;;;; Streams hold BUFFER objects, which contain a SAP, size of the
17 ;;;; memory area the SAP stands for (LENGTH bytes), and HEAD and TAIL
18 ;;;; indexes which delimit the "valid", or "active" area of the
19 ;;;; memory. HEAD is inclusive, TAIL is exclusive.
20 ;;;;
21 ;;;; Buffers get allocated lazily, and are recycled by returning them
22 ;;;; to the *AVAILABLE-BUFFERS* list. Every buffer has it's own
23 ;;;; finalizer, to take care of releasing the SAP memory when a stream
24 ;;;; is not properly closed.
25 ;;;;
26 ;;;; The code aims to provide a limited form of thread and interrupt
27 ;;;; safety: parallel writes and reads may lose output or input, cause
28 ;;;; interleaved IO, etc -- but they should not corrupt memory. The
29 ;;;; key to doing this is to read buffer state once, and update the
30 ;;;; state based on the read state:
31 ;;;;
32 ;;;; (let ((tail (buffer-tail buffer)))
33 ;;;;   ...
34 ;;;;   (setf (buffer-tail buffer) (+ tail n)))
35 ;;;;
36 ;;;; NOT
37 ;;;;
38 ;;;; (let ((tail (buffer-tail buffer)))
39 ;;;;   ...
40 ;;;;  (incf (buffer-tail buffer) n))
41 ;;;;
42
43 (declaim (inline buffer-sap buffer-length buffer-head buffer-tail
44                  (setf buffer-head) (setf buffer-tail)))
45 (defstruct (buffer (:constructor %make-buffer (sap length)))
46   (sap (missing-arg) :type system-area-pointer :read-only t)
47   (length (missing-arg) :type index :read-only t)
48   (head 0 :type index)
49   (tail 0 :type index))
50
51 (defvar *available-buffers* ()
52   #!+sb-doc
53   "List of available buffers.")
54
55 (defvar *available-buffers-spinlock* (sb!thread::make-spinlock
56                                       :name "lock for *AVAILABLE-BUFFERS*")
57   #!+sb-doc
58   "Mutex for access to *AVAILABLE-BUFFERS*.")
59
60 (defmacro with-available-buffers-lock ((&optional) &body body)
61   ;; CALL-WITH-SYSTEM-SPINLOCK because
62   ;;
63   ;; 1. streams are low-level enough to be async signal safe, and in
64   ;;    particular a C-c that brings up the debugger while holding the
65   ;;    mutex would lose badly
66   ;;
67   ;; 2. this can potentially be a fairly busy (but also probably
68   ;;    uncontended) lock, so we don't want to pay the syscall per
69   ;;    release -- hence a spinlock.
70   ;;
71   ;; ...again, once we have smarted locks the spinlock here can become
72   ;; a mutex.
73   `(sb!thread::with-system-spinlock (*available-buffers-spinlock*)
74      ,@body))
75
76 (defconstant +bytes-per-buffer+ (* 4 1024)
77   #!+sb-doc
78   "Default number of bytes per buffer.")
79
80 (defun alloc-buffer (&optional (size +bytes-per-buffer+))
81   ;; Don't want to allocate & unwind before the finalizer is in place.
82   (without-interrupts
83     (let* ((sap (allocate-system-memory size))
84            (buffer (%make-buffer sap size)))
85       (when (zerop (sap-int sap))
86         (error "Could not allocate ~D bytes for buffer." size))
87       (finalize buffer (lambda ()
88                          (deallocate-system-memory sap size))
89                 :dont-save t)
90       buffer)))
91
92 (defun get-buffer ()
93   ;; Don't go for the lock if there is nothing to be had -- sure,
94   ;; another thread might just release one before we get it, but that
95   ;; is not worth the cost of locking. Also release the lock before
96   ;; allocation, since it's going to take a while.
97   (if *available-buffers*
98       (or (with-available-buffers-lock ()
99             (pop *available-buffers*))
100           (alloc-buffer))
101       (alloc-buffer)))
102
103 (declaim (inline reset-buffer))
104 (defun reset-buffer (buffer)
105   (setf (buffer-head buffer) 0
106         (buffer-tail buffer) 0)
107   buffer)
108
109 (defun release-buffer (buffer)
110   (reset-buffer buffer)
111   (with-available-buffers-lock ()
112     (push buffer *available-buffers*)))
113
114 ;;; This is a separate buffer management function, as it wants to be
115 ;;; clever about locking -- grabbing the lock just once.
116 (defun release-fd-stream-buffers (fd-stream)
117   (let ((ibuf (fd-stream-ibuf fd-stream))
118         (obuf (fd-stream-obuf fd-stream))
119         (queue (loop for item in (fd-stream-output-queue fd-stream)
120                        when (buffer-p item)
121                        collect (reset-buffer item))))
122     (when ibuf
123       (push (reset-buffer ibuf) queue))
124     (when obuf
125       (push (reset-buffer obuf) queue))
126     ;; ...so, anything found?
127     (when queue
128       ;; detach from stream
129       (setf (fd-stream-ibuf fd-stream) nil
130             (fd-stream-obuf fd-stream) nil
131             (fd-stream-output-queue fd-stream) nil)
132       ;; splice to *available-buffers*
133       (with-available-buffers-lock ()
134         (setf *available-buffers* (nconc queue *available-buffers*))))))
135 \f
136 ;;;; the FD-STREAM structure
137
138 (defstruct (fd-stream
139             (:constructor %make-fd-stream)
140             (:conc-name fd-stream-)
141             (:predicate fd-stream-p)
142             (:include ansi-stream
143                       (misc #'fd-stream-misc-routine))
144             (:copier nil))
145
146   ;; the name of this stream
147   (name nil)
148   ;; the file this stream is for
149   (file nil)
150   ;; the backup file namestring for the old file, for :IF-EXISTS
151   ;; :RENAME or :RENAME-AND-DELETE.
152   (original nil :type (or simple-string null))
153   (delete-original nil)       ; for :if-exists :rename-and-delete
154   ;;; the number of bytes per element
155   (element-size 1 :type index)
156   ;; the type of element being transfered
157   (element-type 'base-char)
158   ;; the Unix file descriptor
159   (fd -1 :type fixnum)
160   ;; controls when the output buffer is flushed
161   (buffering :full :type (member :full :line :none))
162   ;; controls whether the input buffer must be cleared before output
163   ;; (must be done for files, not for sockets, pipes and other data
164   ;; sources where input and output aren't related).  non-NIL means
165   ;; don't clear input buffer.
166   (dual-channel-p nil)
167   ;; character position if known -- this may run into bignums, but
168   ;; we probably should flip it into null then for efficiency's sake...
169   (char-pos nil :type (or unsigned-byte null))
170   ;; T if input is waiting on FD. :EOF if we hit EOF.
171   (listen nil :type (member nil t :eof))
172
173   ;; the input buffer
174   (unread nil)
175   (ibuf nil :type (or buffer null))
176
177   ;; the output buffer
178   (obuf nil :type (or buffer null))
179
180   ;; output flushed, but not written due to non-blocking io?
181   (output-queue nil)
182   (handler nil)
183   ;; timeout specified for this stream as seconds or NIL if none
184   (timeout nil :type (or single-float null))
185   ;; pathname of the file this stream is opened to (returned by PATHNAME)
186   (pathname nil :type (or pathname null))
187   (external-format :default)
188   ;; fixed width, or function to call with a character
189   (char-size 1 :type (or fixnum function))
190   (output-bytes #'ill-out :type function)
191   ;; a boolean indicating whether the stream is bivalent.  For
192   ;; internal use only.
193   (bivalent-p nil :type boolean))
194 (def!method print-object ((fd-stream fd-stream) stream)
195   (declare (type stream stream))
196   (print-unreadable-object (fd-stream stream :type t :identity t)
197     (format stream "for ~S" (fd-stream-name fd-stream))))
198 \f
199 ;;;; CORE OUTPUT FUNCTIONS
200
201 ;;; Buffer the section of THING delimited by START and END by copying
202 ;;; to output buffer(s) of stream.
203 (defun buffer-output (stream thing start end)
204   (declare (index start end))
205   (when (< end start)
206     (error ":END before :START!"))
207   (when (> end start)
208     ;; Copy bytes from THING to buffers.
209     (flet ((copy-to-buffer (buffer tail count)
210              (declare (buffer buffer) (index tail count))
211              (aver (plusp count))
212              (let ((sap (buffer-sap buffer)))
213                (etypecase thing
214                  (system-area-pointer
215                   (system-area-ub8-copy thing start sap tail count))
216                  ((simple-unboxed-array (*))
217                   (copy-ub8-to-system-area thing start sap tail count))))
218              ;; Not INCF! If another thread has moved tail from under
219              ;; us, we don't want to accidentally increment tail
220              ;; beyond buffer-length.
221              (setf (buffer-tail buffer) (+ count tail))
222              (incf start count)))
223       (tagbody
224          ;; First copy is special: the buffer may already contain
225          ;; something, or be even full.
226          (let* ((obuf (fd-stream-obuf stream))
227                 (tail (buffer-tail obuf))
228                 (space (- (buffer-length obuf) tail)))
229            (when (plusp space)
230              (copy-to-buffer obuf tail (min space (- end start)))
231              (go :more-output-p)))
232        :flush-and-fill
233          ;; Later copies should always have an empty buffer, since
234          ;; they are freshly flushed, but if another thread is
235          ;; stomping on the same buffer that might not be the case.
236          (let* ((obuf (flush-output-buffer stream))
237                 (tail (buffer-tail obuf))
238                 (space (- (buffer-length obuf) tail)))
239            (copy-to-buffer obuf tail (min space (- end start))))
240        :more-output-p
241          (when (> end start)
242            (go :flush-and-fill))))))
243
244 ;;; Flush the current output buffer of the stream, ensuring that the
245 ;;; new buffer is empty. Returns (for convenience) the new output
246 ;;; buffer -- which may or may not be EQ to the old one. If the is no
247 ;;; queued output we try to write the buffer immediately -- otherwise
248 ;;; we queue it for later.
249 (defun flush-output-buffer (stream)
250   (let ((obuf (fd-stream-obuf stream)))
251     (when obuf
252       (let ((head (buffer-head obuf))
253             (tail (buffer-tail obuf)))
254         (cond ((eql head tail)
255                ;; Buffer is already empty -- just ensure that is is
256                ;; set to zero as well.
257                (reset-buffer obuf))
258               ((fd-stream-output-queue stream)
259                ;; There is already stuff on the queue -- go directly
260                ;; there.
261                (aver (< head tail))
262                (%queue-and-replace-output-buffer stream))
263               (t
264                ;; Try a non-blocking write, queue whatever is left over.
265                (aver (< head tail))
266                (synchronize-stream-output stream)
267                (let ((length (- tail head)))
268                  (multiple-value-bind (count errno)
269                      (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
270                                          head length)
271                    (cond ((eql count length)
272                           ;; Complete write -- we can use the same buffer.
273                           (reset-buffer obuf))
274                          (count
275                           ;; Partial write -- update buffer status and queue.
276                           ;; Do not use INCF! Another thread might have moved
277                           ;; head...
278                           (setf (buffer-head obuf) (+ count head))
279                           (%queue-and-replace-output-buffer stream))
280                          #!-win32
281                          ((eql errno sb!unix:ewouldblock)
282                           ;; Blocking, queue.
283                           (%queue-and-replace-output-buffer stream))
284                          (t
285                           (simple-stream-perror "Couldn't write to ~s"
286                                                 stream errno)))))))))))
287
288 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
289 (defun %queue-and-replace-output-buffer (stream)
290   (let ((queue (fd-stream-output-queue stream))
291         (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
292         (new (get-buffer)))
293     ;; Important: before putting the buffer on queue, give the stream
294     ;; a new one. If we get an interrupt and unwind losing the buffer
295     ;; is relatively OK, but having the same buffer in two places
296     ;; would be bad.
297     (setf (fd-stream-obuf stream) new)
298     (cond (queue
299            (nconc queue later))
300           (t
301            (setf (fd-stream-output-queue stream) later)))
302     (unless (fd-stream-handler stream)
303       (setf (fd-stream-handler stream)
304             (add-fd-handler (fd-stream-fd stream)
305                             :output
306                             (lambda (fd)
307                               (declare (ignore fd))
308                               (write-output-from-queue stream)))))
309     new))
310
311 ;;; This is called by the FD-HANDLER for the stream when output is
312 ;;; possible.
313 (defun write-output-from-queue (stream)
314   (synchronize-stream-output stream)
315   (let (not-first-p)
316     (tagbody
317      :pop-buffer
318        (let* ((buffer (pop (fd-stream-output-queue stream)))
319               (head (buffer-head buffer))
320               (length (- (buffer-tail buffer) head)))
321          (declare (index head length))
322          (aver (>= length 0))
323          (multiple-value-bind (count errno)
324              (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
325                                  head length)
326            (cond ((eql count length)
327                   ;; Complete write, see if we can do another right
328                   ;; away, or remove the handler if we're done.
329                   (release-buffer buffer)
330                   (cond ((fd-stream-output-queue stream)
331                          (setf not-first-p t)
332                          (go :pop-buffer))
333                         (t
334                          (let ((handler (fd-stream-handler stream)))
335                            (aver handler)
336                            (setf (fd-stream-handler stream) nil)
337                            (remove-fd-handler handler)))))
338                  (count
339                   ;; Partial write. Update buffer status and requeue.
340                   (aver (< count length))
341                   ;; Do not use INCF! Another thread might have moved head.
342                   (setf (buffer-head buffer) (+ head count))
343                   (push buffer (fd-stream-output-queue stream)))
344                  (not-first-p
345                   ;; We tried to do multiple writes, and finally our
346                   ;; luck ran out. Requeue.
347                   (push buffer (fd-stream-output-queue stream)))
348                  (t
349                   ;; Could not write on the first try at all!
350                   #!+win32
351                   (simple-stream-perror "Couldn't write to ~S." stream errno)
352                   #!-win32
353                   (if (= errno sb!unix:ewouldblock)
354                       (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
355                       (simple-stream-perror "Couldn't write to ~S"
356                                             stream errno))))))))
357   nil)
358
359 ;;; Try to write THING directly to STREAM without buffering, if
360 ;;; possible. If direct write doesn't happen, buffer.
361 (defun write-or-buffer-output (stream thing start end)
362   (declare (index start end))
363   (cond ((fd-stream-output-queue stream)
364          (buffer-output stream thing start end))
365         ((< end start)
366          (error ":END before :START!"))
367         ((> end start)
368          (let ((length (- end start)))
369            (synchronize-stream-output stream)
370            (multiple-value-bind (count errno)
371                (sb!unix:unix-write (fd-stream-fd stream) thing start length)
372              (cond ((eql count length)
373                     ;; Complete write -- done!
374                     )
375                    (count
376                     (aver (< count length))
377                     ;; Partial write -- buffer the rest.
378                     (buffer-output stream thing (+ start count) end))
379                    (t
380                     ;; Could not write -- buffer or error.
381                     #!+win32
382                     (simple-stream-perror "couldn't write to ~s" stream errno)
383                     #!-win32
384                     (if (= errno sb!unix:ewouldblock)
385                         (buffer-output stream thing start end)
386                         (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
387
388 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
389 ;;; this is not something we want to export. Nikodemus thinks the
390 ;;; right thing is to support a low-level non-stream like IO layer,
391 ;;; akin to java.nio.
392 (defun output-raw-bytes (stream thing &optional start end)
393   (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
394
395 (define-compiler-macro output-raw-bytes (stream thing &optional start end)
396   (deprecation-warning 'output-raw-bytes)
397   (let ((x (gensym "THING")))
398     `(let ((,x ,thing))
399        (write-or-buffer-output ,stream ,x (or ,start 0) (or ,end (length ,x))))))
400 \f
401 ;;;; output routines and related noise
402
403 (defvar *output-routines* ()
404   #!+sb-doc
405   "List of all available output routines. Each element is a list of the
406   element-type output, the kind of buffering, the function name, and the number
407   of bytes per element.")
408
409 ;;; common idioms for reporting low-level stream and file problems
410 (defun simple-stream-perror (note-format stream errno)
411   (error 'simple-stream-error
412          :stream stream
413          :format-control "~@<~?: ~2I~_~A~:>"
414          :format-arguments (list note-format (list stream) (strerror errno))))
415 (defun simple-file-perror (note-format pathname errno)
416   (error 'simple-file-error
417          :pathname pathname
418          :format-control "~@<~?: ~2I~_~A~:>"
419          :format-arguments
420          (list note-format (list pathname) (strerror errno))))
421
422 (defun stream-decoding-error (stream octets)
423   (error 'stream-decoding-error
424          :external-format (stream-external-format stream)
425          :stream stream
426          ;; FIXME: dunno how to get at OCTETS currently, or even if
427          ;; that's the right thing to report.
428          :octets octets))
429 (defun stream-encoding-error (stream code)
430   (error 'stream-encoding-error
431          :external-format (stream-external-format stream)
432          :stream stream
433          :code code))
434
435 (defun c-string-encoding-error (external-format code)
436   (error 'c-string-encoding-error
437          :external-format external-format
438          :code code))
439
440 (defun c-string-decoding-error (external-format octets)
441   (error 'c-string-decoding-error
442          :external-format external-format
443          :octets octets))
444
445 ;;; Returning true goes into end of file handling, false will enter another
446 ;;; round of input buffer filling followed by re-entering character decode.
447 (defun stream-decoding-error-and-handle (stream octet-count)
448   (restart-case
449       (stream-decoding-error stream
450                              (let* ((buffer (fd-stream-ibuf stream))
451                                     (sap (buffer-sap buffer))
452                                     (head (buffer-head buffer)))
453                                (loop for i from 0 below octet-count
454                                      collect (sap-ref-8 sap (+ head i)))))
455     (attempt-resync ()
456       :report (lambda (stream)
457                 (format stream
458                         "~@<Attempt to resync the stream at a ~
459                         character boundary and continue.~@:>"))
460       (fd-stream-resync stream)
461       nil)
462     (force-end-of-file ()
463       :report (lambda (stream)
464                 (format stream "~@<Force an end of file.~@:>"))
465       t)))
466
467 (defun stream-encoding-error-and-handle (stream code)
468   (restart-case
469       (stream-encoding-error stream code)
470     (output-nothing ()
471       :report (lambda (stream)
472                 (format stream "~@<Skip output of this character.~@:>"))
473       (throw 'output-nothing nil))))
474
475 (defun external-format-encoding-error (stream code)
476   (if (streamp stream)
477       (stream-encoding-error-and-handle stream code)
478       (c-string-encoding-error stream code)))
479
480 (defun external-format-decoding-error (stream octet-count)
481   (if (streamp stream)
482       (stream-decoding-error stream octet-count)
483       (c-string-decoding-error stream octet-count)))
484
485 (defun synchronize-stream-output (stream)
486   ;; If we're reading and writing on the same file, flush buffered
487   ;; input and rewind file position accordingly.
488   (unless (fd-stream-dual-channel-p stream)
489     (let ((adjust (nth-value 1 (flush-input-buffer stream))))
490       (unless (eql 0 adjust)
491         (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
492
493 (defun fd-stream-output-finished-p (stream)
494   (let ((obuf (fd-stream-obuf stream)))
495     (or (not obuf)
496         (and (zerop (buffer-tail obuf))
497              (not (fd-stream-output-queue stream))))))
498
499 (defmacro output-wrapper/variable-width ((stream size buffering restart)
500                                          &body body)
501   (let ((stream-var (gensym "STREAM")))
502     `(let* ((,stream-var ,stream)
503             (obuf (fd-stream-obuf ,stream-var))
504             (tail (buffer-tail obuf))
505             (size ,size))
506       ,(unless (eq (car buffering) :none)
507          `(when (<= (buffer-length obuf) (+ tail size))
508             (setf obuf (flush-output-buffer ,stream-var)
509                   tail (buffer-tail obuf))))
510       ,(unless (eq (car buffering) :none)
511          ;; FIXME: Why this here? Doesn't seem necessary.
512          `(synchronize-stream-output ,stream-var))
513       ,(if restart
514            `(catch 'output-nothing
515               ,@body
516               (setf (buffer-tail obuf) (+ tail size)))
517            `(progn
518              ,@body
519              (setf (buffer-tail obuf) (+ tail size))))
520       ,(ecase (car buffering)
521          (:none
522           `(flush-output-buffer ,stream-var))
523          (:line
524           `(when (eql byte #\Newline)
525              (flush-output-buffer ,stream-var)))
526          (:full))
527     (values))))
528
529 (defmacro output-wrapper ((stream size buffering restart) &body body)
530   (let ((stream-var (gensym "STREAM")))
531     `(let* ((,stream-var ,stream)
532             (obuf (fd-stream-obuf ,stream-var))
533             (tail (buffer-tail obuf)))
534       ,(unless (eq (car buffering) :none)
535          `(when (<= (buffer-length obuf) (+ tail ,size))
536             (setf obuf (flush-output-buffer ,stream-var)
537                   tail (buffer-tail obuf))))
538       ;; FIXME: Why this here? Doesn't seem necessary.
539       ,(unless (eq (car buffering) :none)
540          `(synchronize-stream-output ,stream-var))
541       ,(if restart
542            `(catch 'output-nothing
543               ,@body
544               (setf (buffer-tail obuf) (+ tail ,size)))
545            `(progn
546              ,@body
547              (setf (buffer-tail obuf) (+ tail ,size))))
548       ,(ecase (car buffering)
549          (:none
550           `(flush-output-buffer ,stream-var))
551          (:line
552           `(when (eql byte #\Newline)
553              (flush-output-buffer ,stream-var)))
554          (:full))
555     (values))))
556
557 (defmacro def-output-routines/variable-width
558     ((name-fmt size restart external-format &rest bufferings)
559      &body body)
560   (declare (optimize (speed 1)))
561   (cons 'progn
562         (mapcar
563             (lambda (buffering)
564               (let ((function
565                      (intern (format nil name-fmt (string (car buffering))))))
566                 `(progn
567                    (defun ,function (stream byte)
568                      (declare (ignorable byte))
569                      (output-wrapper/variable-width (stream ,size ,buffering ,restart)
570                        ,@body))
571                    (setf *output-routines*
572                          (nconc *output-routines*
573                                 ',(mapcar
574                                    (lambda (type)
575                                      (list type
576                                            (car buffering)
577                                            function
578                                            1
579                                            external-format))
580                                    (cdr buffering)))))))
581             bufferings)))
582
583 ;;; Define output routines that output numbers SIZE bytes long for the
584 ;;; given bufferings. Use BODY to do the actual output.
585 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
586                                &body body)
587   (declare (optimize (speed 1)))
588   (cons 'progn
589         (mapcar
590             (lambda (buffering)
591               (let ((function
592                      (intern (format nil name-fmt (string (car buffering))))))
593                 `(progn
594                    (defun ,function (stream byte)
595                      (output-wrapper (stream ,size ,buffering ,restart)
596                        ,@body))
597                    (setf *output-routines*
598                          (nconc *output-routines*
599                                 ',(mapcar
600                                    (lambda (type)
601                                      (list type
602                                            (car buffering)
603                                            function
604                                            size
605                                            nil))
606                                    (cdr buffering)))))))
607             bufferings)))
608
609 ;;; FIXME: is this used anywhere any more?
610 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
611                       1
612                       t
613                       (:none character)
614                       (:line character)
615                       (:full character))
616   (if (eql byte #\Newline)
617       (setf (fd-stream-char-pos stream) 0)
618       (incf (fd-stream-char-pos stream)))
619   (setf (sap-ref-8 (buffer-sap obuf) tail)
620         (char-code byte)))
621
622 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
623                       1
624                       nil
625                       (:none (unsigned-byte 8))
626                       (:full (unsigned-byte 8)))
627   (setf (sap-ref-8 (buffer-sap obuf) tail)
628         byte))
629
630 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
631                       1
632                       nil
633                       (:none (signed-byte 8))
634                       (:full (signed-byte 8)))
635   (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
636         byte))
637
638 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
639                       2
640                       nil
641                       (:none (unsigned-byte 16))
642                       (:full (unsigned-byte 16)))
643   (setf (sap-ref-16 (buffer-sap obuf) tail)
644         byte))
645
646 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
647                       2
648                       nil
649                       (:none (signed-byte 16))
650                       (:full (signed-byte 16)))
651   (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
652         byte))
653
654 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
655                       4
656                       nil
657                       (:none (unsigned-byte 32))
658                       (:full (unsigned-byte 32)))
659   (setf (sap-ref-32 (buffer-sap obuf) tail)
660         byte))
661
662 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
663                       4
664                       nil
665                       (:none (signed-byte 32))
666                       (:full (signed-byte 32)))
667   (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
668         byte))
669
670 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
671 (progn
672   (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
673                         8
674                         nil
675                         (:none (unsigned-byte 64))
676                         (:full (unsigned-byte 64)))
677     (setf (sap-ref-64 (buffer-sap obuf) tail)
678           byte))
679   (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
680                         8
681                         nil
682                         (:none (signed-byte 64))
683                         (:full (signed-byte 64)))
684     (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
685           byte)))
686
687 ;;; the routine to use to output a string. If the stream is
688 ;;; unbuffered, slam the string down the file descriptor, otherwise
689 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
690 ;;; checking to see where the last newline was.
691 (defun fd-sout (stream thing start end)
692   (declare (type fd-stream stream) (type string thing))
693   (let ((start (or start 0))
694         (end (or end (length (the vector thing)))))
695     (declare (fixnum start end))
696     (let ((last-newline
697            (string-dispatch (simple-base-string
698                              #!+sb-unicode
699                              (simple-array character (*))
700                              string)
701                thing
702              (position #\newline thing :from-end t
703                        :start start :end end))))
704       (if (and (typep thing 'base-string)
705                (eq (fd-stream-external-format stream) :latin-1))
706           (ecase (fd-stream-buffering stream)
707             (:full
708              (buffer-output stream thing start end))
709             (:line
710              (buffer-output stream thing start end)
711              (when last-newline
712                (flush-output-buffer stream)))
713             (:none
714              (write-or-buffer-output stream thing start end)))
715           (ecase (fd-stream-buffering stream)
716             (:full (funcall (fd-stream-output-bytes stream)
717                             stream thing nil start end))
718             (:line (funcall (fd-stream-output-bytes stream)
719                             stream thing last-newline start end))
720             (:none (funcall (fd-stream-output-bytes stream)
721                             stream thing t start end))))
722       (if last-newline
723           (setf (fd-stream-char-pos stream) (- end last-newline 1))
724           (incf (fd-stream-char-pos stream) (- end start))))))
725
726 (defvar *external-formats* ()
727   #!+sb-doc
728   "List of all available external formats. Each element is a list of the
729   element-type, string input function name, character input function name,
730   and string output function name.")
731
732 (defun get-external-format (external-format)
733   (dolist (entry *external-formats*)
734     (when (member external-format (first entry))
735       (return entry))))
736
737 (defun get-external-format-function (external-format index)
738   (let ((entry (get-external-format external-format)))
739     (when entry (nth index entry))))
740
741 ;;; Find an output routine to use given the type and buffering. Return
742 ;;; as multiple values the routine, the real type transfered, and the
743 ;;; number of bytes per element.
744 (defun pick-output-routine (type buffering &optional external-format)
745   (when (subtypep type 'character)
746     (let ((entry (get-external-format external-format)))
747       (when entry
748         (return-from pick-output-routine
749           (values (symbol-function (nth (ecase buffering
750                                           (:none 4)
751                                           (:line 5)
752                                           (:full 6))
753                                         entry))
754                   'character
755                   1
756                   (symbol-function (fourth entry))
757                   (first (first entry)))))))
758   (dolist (entry *output-routines*)
759     (when (and (subtypep type (first entry))
760                (eq buffering (second entry))
761                (or (not (fifth entry))
762                    (eq external-format (fifth entry))))
763       (return-from pick-output-routine
764         (values (symbol-function (third entry))
765                 (first entry)
766                 (fourth entry)))))
767   ;; KLUDGE: dealing with the buffering here leads to excessive code
768   ;; explosion.
769   ;;
770   ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
771   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
772         if (subtypep type `(unsigned-byte ,i))
773         do (return-from pick-output-routine
774              (values
775               (ecase buffering
776                 (:none
777                  (lambda (stream byte)
778                    (output-wrapper (stream (/ i 8) (:none) nil)
779                      (loop for j from 0 below (/ i 8)
780                            do (setf (sap-ref-8 (buffer-sap obuf)
781                                                (+ j tail))
782                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
783                 (:full
784                  (lambda (stream byte)
785                    (output-wrapper (stream (/ i 8) (:full) nil)
786                      (loop for j from 0 below (/ i 8)
787                            do (setf (sap-ref-8 (buffer-sap obuf)
788                                                (+ j tail))
789                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
790               `(unsigned-byte ,i)
791               (/ i 8))))
792   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
793         if (subtypep type `(signed-byte ,i))
794         do (return-from pick-output-routine
795              (values
796               (ecase buffering
797                 (:none
798                  (lambda (stream byte)
799                    (output-wrapper (stream (/ i 8) (:none) nil)
800                      (loop for j from 0 below (/ i 8)
801                            do (setf (sap-ref-8 (buffer-sap obuf)
802                                                (+ j tail))
803                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
804                 (:full
805                  (lambda (stream byte)
806                    (output-wrapper (stream (/ i 8) (:full) nil)
807                      (loop for j from 0 below (/ i 8)
808                            do (setf (sap-ref-8 (buffer-sap obuf)
809                                                (+ j tail))
810                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
811               `(signed-byte ,i)
812               (/ i 8)))))
813 \f
814 ;;;; input routines and related noise
815
816 ;;; a list of all available input routines. Each element is a list of
817 ;;; the element-type input, the function name, and the number of bytes
818 ;;; per element.
819 (defvar *input-routines* ())
820
821 ;;; Return whether a primitive partial read operation on STREAM's FD
822 ;;; would (probably) block.  Signal a `simple-stream-error' if the
823 ;;; system call implementing this operation fails.
824 ;;;
825 ;;; It is "may" instead of "would" because "would" is not quite
826 ;;; correct on win32.  However, none of the places that use it require
827 ;;; further assurance than "may" versus "will definitely not".
828 (defun sysread-may-block-p (stream)
829   #!+win32
830   ;; This answers T at EOF on win32, I think.
831   (not (sb!win32:fd-listen (fd-stream-fd stream)))
832   #!-win32
833   (sb!unix:with-restarted-syscall (count errno)
834     (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
835       (sb!unix:fd-zero read-fds)
836       (sb!unix:fd-set (fd-stream-fd stream) read-fds)
837       (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
838                                 (sb!alien:addr read-fds)
839                                 nil nil 0 0))
840     (case count
841       ((1) nil)
842       ((0) t)
843       (otherwise
844        (simple-stream-perror "couldn't check whether ~S is readable"
845                              stream
846                              errno)))))
847
848 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
849 ;;; then fill the input buffer, and return the number of bytes read. Throws
850 ;;; to EOF-INPUT-CATCHER if the eof was reached.
851 (defun refill-input-buffer (stream)
852   (dx-let ((fd (fd-stream-fd stream))
853            (errno 0)
854            (count 0))
855     (tagbody
856        ;; Check for blocking input before touching the stream, as if
857        ;; we happen to wait we are liable to be interrupted, and the
858        ;; interrupt handler may use the same stream.
859        (if (sysread-may-block-p stream)
860            (go :wait-for-input)
861            (go :main))
862        ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
863        ;; we can signal errors outside the WITHOUT-INTERRUPTS.
864      :closed-flame
865        (closed-flame stream)
866      :read-error
867        (simple-stream-perror "couldn't read from ~S" stream errno)
868      :wait-for-input
869        ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
870        ;; to wait for input if read tells us EWOULDBLOCK.
871        (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
872          (signal-timeout 'io-timeout :stream stream :direction :read
873                          :seconds (fd-stream-timeout stream)))
874      :main
875        ;; Since the read should not block, we'll disable the
876        ;; interrupts here, so that we don't accidentally unwind and
877        ;; leave the stream in an inconsistent state.
878
879        ;; Execute the nlx outside without-interrupts to ensure the
880        ;; resulting thunk is stack-allocatable.
881        ((lambda (return-reason)
882           (ecase return-reason
883             ((nil))             ; fast path normal cases
884             ((:wait-for-input) (go :wait-for-input))
885             ((:closed-flame)   (go :closed-flame))
886             ((:read-error)     (go :read-error))))
887         (without-interrupts
888           ;; Check the buffer: if it is null, then someone has closed
889           ;; the stream from underneath us. This is not ment to fix
890           ;; multithreaded races, but to deal with interrupt handlers
891           ;; closing the stream.
892           (block nil
893             (prog1 nil
894               (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
895                      (sap (buffer-sap ibuf))
896                      (length (buffer-length ibuf))
897                      (head (buffer-head ibuf))
898                      (tail (buffer-tail ibuf)))
899                 (declare (index length head tail)
900                          (inline sb!unix:unix-read))
901                 (unless (zerop head)
902                   (cond ((eql head tail)
903                          ;; Buffer is empty, but not at yet reset -- make it so.
904                          (setf head 0
905                                tail 0)
906                          (reset-buffer ibuf))
907                         (t
908                          ;; Buffer has things in it, but they are not at the
909                          ;; head -- move them there.
910                          (let ((n (- tail head)))
911                            (system-area-ub8-copy sap head sap 0 n)
912                            (setf head 0
913                                  (buffer-head ibuf) head
914                                  tail n
915                                  (buffer-tail ibuf) tail)))))
916                 (setf (fd-stream-listen stream) nil)
917                 (setf (values count errno)
918                       (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
919                 (cond ((null count)
920                        #!+win32
921                        (return :read-error)
922                        #!-win32
923                        (if (eql errno sb!unix:ewouldblock)
924                            (return :wait-for-input)
925                            (return :read-error)))
926                       ((zerop count)
927                        (setf (fd-stream-listen stream) :eof)
928                        (/show0 "THROWing EOF-INPUT-CATCHER")
929                        (throw 'eof-input-catcher nil))
930                       (t
931                        ;; Success! (Do not use INCF, for sake of other threads.)
932                        (setf (buffer-tail ibuf) (+ count tail))))))))))
933     count))
934
935 ;;; Make sure there are at least BYTES number of bytes in the input
936 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
937 (defmacro input-at-least (stream bytes)
938   (let ((stream-var (gensym "STREAM"))
939         (bytes-var (gensym "BYTES"))
940         (buffer-var (gensym "IBUF")))
941     `(let* ((,stream-var ,stream)
942             (,bytes-var ,bytes)
943             (,buffer-var (fd-stream-ibuf ,stream-var)))
944        (loop
945          (when (>= (- (buffer-tail ,buffer-var)
946                       (buffer-head ,buffer-var))
947                    ,bytes-var)
948            (return))
949          (refill-input-buffer ,stream-var)))))
950
951 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
952                                         &body read-forms)
953   (let ((stream-var (gensym "STREAM"))
954         (retry-var (gensym "RETRY"))
955         (element-var (gensym "ELT")))
956     `(let* ((,stream-var ,stream)
957             (ibuf (fd-stream-ibuf ,stream-var))
958             (size nil))
959        (if (fd-stream-unread ,stream-var)
960            (prog1
961                (fd-stream-unread ,stream-var)
962              (setf (fd-stream-unread ,stream-var) nil)
963              (setf (fd-stream-listen ,stream-var) nil))
964            (let ((,element-var nil)
965                  (decode-break-reason nil))
966              (do ((,retry-var t))
967                  ((not ,retry-var))
968                (unless
969                    (catch 'eof-input-catcher
970                      (setf decode-break-reason
971                            (block decode-break-reason
972                              (input-at-least ,stream-var 1)
973                              (let* ((byte (sap-ref-8 (buffer-sap ibuf)
974                                                      (buffer-head ibuf))))
975                                (declare (ignorable byte))
976                                (setq size ,bytes)
977                                (input-at-least ,stream-var size)
978                                (setq ,element-var (locally ,@read-forms))
979                                (setq ,retry-var nil))
980                              nil))
981                      (when decode-break-reason
982                        (stream-decoding-error-and-handle stream
983                                                          decode-break-reason))
984                      t)
985                  (let ((octet-count (- (buffer-tail ibuf)
986                                        (buffer-head ibuf))))
987                    (when (or (zerop octet-count)
988                              (and (not ,element-var)
989                                   (not decode-break-reason)
990                                   (stream-decoding-error-and-handle
991                                    stream octet-count)))
992                      (setq ,retry-var nil)))))
993              (cond (,element-var
994                     (incf (buffer-head ibuf) size)
995                     ,element-var)
996                    (t
997                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
998
999 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1000 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1001   (let ((stream-var (gensym "STREAM"))
1002         (element-var (gensym "ELT")))
1003     `(let* ((,stream-var ,stream)
1004             (ibuf (fd-stream-ibuf ,stream-var)))
1005        (if (fd-stream-unread ,stream-var)
1006            (prog1
1007                (fd-stream-unread ,stream-var)
1008              (setf (fd-stream-unread ,stream-var) nil)
1009              (setf (fd-stream-listen ,stream-var) nil))
1010            (let ((,element-var
1011                   (catch 'eof-input-catcher
1012                     (input-at-least ,stream-var ,bytes)
1013                     (locally ,@read-forms))))
1014              (cond (,element-var
1015                     (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1016                     ,element-var)
1017                    (t
1018                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1019
1020 (defmacro def-input-routine/variable-width (name
1021                                             (type external-format size sap head)
1022                                             &rest body)
1023   `(progn
1024      (defun ,name (stream eof-error eof-value)
1025        (input-wrapper/variable-width (stream ,size eof-error eof-value)
1026          (let ((,sap (buffer-sap ibuf))
1027                (,head (buffer-head ibuf)))
1028            ,@body)))
1029      (setf *input-routines*
1030            (nconc *input-routines*
1031                   (list (list ',type ',name 1 ',external-format))))))
1032
1033 (defmacro def-input-routine (name
1034                              (type size sap head)
1035                              &rest body)
1036   `(progn
1037      (defun ,name (stream eof-error eof-value)
1038        (input-wrapper (stream ,size eof-error eof-value)
1039          (let ((,sap (buffer-sap ibuf))
1040                (,head (buffer-head ibuf)))
1041            ,@body)))
1042      (setf *input-routines*
1043            (nconc *input-routines*
1044                   (list (list ',type ',name ',size nil))))))
1045
1046 ;;; STREAM-IN routine for reading a string char
1047 (def-input-routine input-character
1048                    (character 1 sap head)
1049   (code-char (sap-ref-8 sap head)))
1050
1051 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1052 (def-input-routine input-unsigned-8bit-byte
1053                    ((unsigned-byte 8) 1 sap head)
1054   (sap-ref-8 sap head))
1055
1056 ;;; STREAM-IN routine for reading a signed 8 bit number
1057 (def-input-routine input-signed-8bit-number
1058                    ((signed-byte 8) 1 sap head)
1059   (signed-sap-ref-8 sap head))
1060
1061 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1062 (def-input-routine input-unsigned-16bit-byte
1063                    ((unsigned-byte 16) 2 sap head)
1064   (sap-ref-16 sap head))
1065
1066 ;;; STREAM-IN routine for reading a signed 16 bit number
1067 (def-input-routine input-signed-16bit-byte
1068                    ((signed-byte 16) 2 sap head)
1069   (signed-sap-ref-16 sap head))
1070
1071 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1072 (def-input-routine input-unsigned-32bit-byte
1073                    ((unsigned-byte 32) 4 sap head)
1074   (sap-ref-32 sap head))
1075
1076 ;;; STREAM-IN routine for reading a signed 32 bit number
1077 (def-input-routine input-signed-32bit-byte
1078                    ((signed-byte 32) 4 sap head)
1079   (signed-sap-ref-32 sap head))
1080
1081 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1082 (progn
1083   (def-input-routine input-unsigned-64bit-byte
1084       ((unsigned-byte 64) 8 sap head)
1085     (sap-ref-64 sap head))
1086   (def-input-routine input-signed-64bit-byte
1087       ((signed-byte 64) 8 sap head)
1088     (signed-sap-ref-64 sap head)))
1089
1090 ;;; Find an input routine to use given the type. Return as multiple
1091 ;;; values the routine, the real type transfered, and the number of
1092 ;;; bytes per element (and for character types string input routine).
1093 (defun pick-input-routine (type &optional external-format)
1094   (when (subtypep type 'character)
1095     (dolist (entry *external-formats*)
1096       (when (member external-format (first entry))
1097         (return-from pick-input-routine
1098           (values (symbol-function (third entry))
1099                   'character
1100                   1
1101                   (symbol-function (second entry))
1102                   (first (first entry)))))))
1103   (dolist (entry *input-routines*)
1104     (when (and (subtypep type (first entry))
1105                (or (not (fourth entry))
1106                    (eq external-format (fourth entry))))
1107       (return-from pick-input-routine
1108         (values (symbol-function (second entry))
1109                 (first entry)
1110                 (third entry)))))
1111   ;; FIXME: let's do it the hard way, then (but ignore things like
1112   ;; endianness, efficiency, and the necessary coupling between these
1113   ;; and the output routines).  -- CSR, 2004-02-09
1114   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1115         if (subtypep type `(unsigned-byte ,i))
1116         do (return-from pick-input-routine
1117              (values
1118               (lambda (stream eof-error eof-value)
1119                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1120                   (let ((sap (buffer-sap ibuf))
1121                         (head (buffer-head ibuf)))
1122                     (loop for j from 0 below (/ i 8)
1123                           with result = 0
1124                           do (setf result
1125                                    (+ (* 256 result)
1126                                       (sap-ref-8 sap (+ head j))))
1127                           finally (return result)))))
1128               `(unsigned-byte ,i)
1129               (/ i 8))))
1130   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1131         if (subtypep type `(signed-byte ,i))
1132         do (return-from pick-input-routine
1133              (values
1134               (lambda (stream eof-error eof-value)
1135                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1136                   (let ((sap (buffer-sap ibuf))
1137                         (head (buffer-head ibuf)))
1138                     (loop for j from 0 below (/ i 8)
1139                           with result = 0
1140                           do (setf result
1141                                    (+ (* 256 result)
1142                                       (sap-ref-8 sap (+ head j))))
1143                           finally (return (if (logbitp (1- i) result)
1144                                               (dpb result (byte i 0) -1)
1145                                               result))))))
1146               `(signed-byte ,i)
1147               (/ i 8)))))
1148
1149 ;;; the N-BIN method for FD-STREAMs
1150 ;;;
1151 ;;; Note that this blocks in UNIX-READ. It is generally used where
1152 ;;; there is a definite amount of reading to be done, so blocking
1153 ;;; isn't too problematical.
1154 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1155                                &aux (total-copied 0))
1156   (declare (type fd-stream stream))
1157   (declare (type index start requested total-copied))
1158   (let ((unread (fd-stream-unread stream)))
1159     (when unread
1160       ;; AVERs designed to fail when we have more complicated
1161       ;; character representations.
1162       (aver (typep unread 'base-char))
1163       (aver (= (fd-stream-element-size stream) 1))
1164       ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1165       ;; %BYTE-BLT
1166       (etypecase buffer
1167         (system-area-pointer
1168          (setf (sap-ref-8 buffer start) (char-code unread)))
1169         ((simple-unboxed-array (*))
1170          (setf (aref buffer start) unread)))
1171       (setf (fd-stream-unread stream) nil)
1172       (setf (fd-stream-listen stream) nil)
1173       (incf total-copied)))
1174   (do ()
1175       (nil)
1176     (let* ((remaining-request (- requested total-copied))
1177            (ibuf (fd-stream-ibuf stream))
1178            (head (buffer-head ibuf))
1179            (tail (buffer-tail ibuf))
1180            (available (- tail head))
1181            (n-this-copy (min remaining-request available))
1182            (this-start (+ start total-copied))
1183            (this-end (+ this-start n-this-copy))
1184            (sap (buffer-sap ibuf)))
1185       (declare (type index remaining-request head tail available))
1186       (declare (type index n-this-copy))
1187       ;; Copy data from stream buffer into user's buffer.
1188       (%byte-blt sap head buffer this-start this-end)
1189       (incf (buffer-head ibuf) n-this-copy)
1190       (incf total-copied n-this-copy)
1191       ;; Maybe we need to refill the stream buffer.
1192       (cond (;; If there were enough data in the stream buffer, we're done.
1193              (eql total-copied requested)
1194              (return total-copied))
1195             (;; If EOF, we're done in another way.
1196              (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1197              (if eof-error-p
1198                  (error 'end-of-file :stream stream)
1199                  (return total-copied)))
1200             ;; Otherwise we refilled the stream buffer, so fall
1201             ;; through into another pass of the loop.
1202             ))))
1203
1204 (defun fd-stream-resync (stream)
1205   (dolist (entry *external-formats*)
1206     (when (member (fd-stream-external-format stream) (first entry))
1207       (return-from fd-stream-resync
1208         (funcall (symbol-function (eighth entry)) stream)))))
1209
1210 (defun get-fd-stream-character-sizer (stream)
1211   (dolist (entry *external-formats*)
1212     (when (member (fd-stream-external-format stream) (first entry))
1213       (return-from get-fd-stream-character-sizer (ninth entry)))))
1214
1215 (defun fd-stream-character-size (stream char)
1216   (let ((sizer (get-fd-stream-character-sizer stream)))
1217     (when sizer (funcall sizer char))))
1218
1219 (defun fd-stream-string-size (stream string)
1220   (let ((sizer (get-fd-stream-character-sizer stream)))
1221     (when sizer
1222       (loop for char across string summing (funcall sizer char)))))
1223
1224 (defun find-external-format (external-format)
1225   (when external-format
1226     (find external-format *external-formats* :test #'member :key #'car)))
1227
1228 (defun variable-width-external-format-p (ef-entry)
1229   (when (eighth ef-entry) t))
1230
1231 (defun bytes-for-char-fun (ef-entry)
1232   (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1233
1234 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1235 (defmacro define-external-format (external-format size output-restart
1236                                   out-expr in-expr)
1237   (let* ((name (first external-format))
1238          (out-function (symbolicate "OUTPUT-BYTES/" name))
1239          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1240          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1241          (in-char-function (symbolicate "INPUT-CHAR/" name))
1242          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1243          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1244          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1245          (n-buffer (gensym "BUFFER")))
1246     `(progn
1247       (defun ,size-function (byte)
1248         (declare (ignore byte))
1249         ,size)
1250       (defun ,out-function (stream string flush-p start end)
1251         (let ((start (or start 0))
1252               (end (or end (length string))))
1253           (declare (type index start end))
1254           (synchronize-stream-output stream)
1255           (unless (<= 0 start end (length string))
1256             (sequence-bounding-indices-bad-error string start end))
1257           (do ()
1258               ((= end start))
1259             (let ((obuf (fd-stream-obuf stream)))
1260               (setf (buffer-tail obuf)
1261                     (string-dispatch (simple-base-string
1262                                       #!+sb-unicode
1263                                       (simple-array character (*))
1264                                       string)
1265                         string
1266                       (let ((sap (buffer-sap obuf))
1267                             (len (buffer-length obuf))
1268                             ;; FIXME: rename
1269                             (tail (buffer-tail obuf)))
1270                        (declare (type index tail)
1271                                 ;; STRING bounds have already been checked.
1272                                 (optimize (safety 0)))
1273                        (loop
1274                          (,@(if output-restart
1275                                 `(catch 'output-nothing)
1276                                 `(progn))
1277                             (do* ()
1278                                  ((or (= start end) (< (- len tail) 4)))
1279                               (let* ((byte (aref string start))
1280                                      (bits (char-code byte)))
1281                                 ,out-expr
1282                                 (incf tail ,size)
1283                                 (incf start)))
1284                             ;; Exited from the loop normally
1285                             (return tail))
1286                          ;; Exited via CATCH. Skip the current character
1287                          ;; and try the inner loop again.
1288                          (incf start))))))
1289             (when (< start end)
1290               (flush-output-buffer stream)))
1291           (when flush-p
1292             (flush-output-buffer stream))))
1293       (def-output-routines (,format
1294                             ,size
1295                             ,output-restart
1296                             (:none character)
1297                             (:line character)
1298                             (:full character))
1299           (if (eql byte #\Newline)
1300               (setf (fd-stream-char-pos stream) 0)
1301               (incf (fd-stream-char-pos stream)))
1302           (let* ((obuf (fd-stream-obuf stream))
1303                  (bits (char-code byte))
1304                  (sap (buffer-sap obuf))
1305                  (tail (buffer-tail obuf)))
1306             ,out-expr))
1307       (defun ,in-function (stream buffer start requested eof-error-p
1308                            &aux (index start) (end (+ start requested)))
1309         (declare (type fd-stream stream)
1310                  (type index start requested index end)
1311                  (type
1312                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1313                   buffer))
1314         (let ((unread (fd-stream-unread stream)))
1315           (when unread
1316             (setf (aref buffer index) unread)
1317             (setf (fd-stream-unread stream) nil)
1318             (setf (fd-stream-listen stream) nil)
1319             (incf index)))
1320         (do ()
1321             (nil)
1322           (let* ((ibuf (fd-stream-ibuf stream))
1323                  (head (buffer-head ibuf))
1324                  (tail (buffer-tail ibuf))
1325                  (sap (buffer-sap ibuf)))
1326             (declare (type index head tail)
1327                      (type system-area-pointer sap))
1328             ;; Copy data from stream buffer into user's buffer.
1329             (dotimes (i (min (truncate (- tail head) ,size)
1330                              (- end index)))
1331               (declare (optimize speed))
1332               (let* ((byte (sap-ref-8 sap head)))
1333                 (setf (aref buffer index) ,in-expr)
1334                 (incf index)
1335                 (incf head ,size)))
1336             (setf (buffer-head ibuf) head)
1337             ;; Maybe we need to refill the stream buffer.
1338             (cond ( ;; If there was enough data in the stream buffer, we're done.
1339                    (= index end)
1340                    (return (- index start)))
1341                   ( ;; If EOF, we're done in another way.
1342                    (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1343                    (if eof-error-p
1344                        (error 'end-of-file :stream stream)
1345                        (return (- index start))))
1346                   ;; Otherwise we refilled the stream buffer, so fall
1347                   ;; through into another pass of the loop.
1348                   ))))
1349       (def-input-routine ,in-char-function (character ,size sap head)
1350         (let ((byte (sap-ref-8 sap head)))
1351           ,in-expr))
1352       (defun ,read-c-string-function (sap element-type)
1353         (declare (type system-area-pointer sap)
1354                  (type (member character base-char) element-type))
1355         (locally
1356             (declare (optimize (speed 3) (safety 0)))
1357           (let* ((stream ,name)
1358                  (length
1359                   (loop for head of-type index upfrom 0 by ,size
1360                         for count of-type index upto (1- array-dimension-limit)
1361                         for byte = (sap-ref-8 sap head)
1362                         for char of-type character = ,in-expr
1363                         until (zerop (char-code char))
1364                         finally (return count)))
1365                  ;; Inline the common cases
1366                  (string (make-string length :element-type element-type)))
1367             (declare (ignorable stream)
1368                      (type index length)
1369                      (type simple-string string))
1370             (/show0 before-copy-loop)
1371             (loop for head of-type index upfrom 0 by ,size
1372                for index of-type index below length
1373                for byte = (sap-ref-8 sap head)
1374                for char of-type character = ,in-expr
1375                do (setf (aref string index) char))
1376             string))) ;; last loop rewrite to dotimes?
1377         (defun ,output-c-string-function (string)
1378           (declare (type simple-string string))
1379           (locally
1380               (declare (optimize (speed 3) (safety 0)))
1381             (let* ((length (length string))
1382                    (,n-buffer (make-array (* (1+ length) ,size)
1383                                           :element-type '(unsigned-byte 8)))
1384                    (tail 0)
1385                    (stream ,name))
1386               (declare (type index length tail))
1387               (with-pinned-objects (,n-buffer)
1388                 (let ((sap (vector-sap ,n-buffer)))
1389                   (declare (system-area-pointer sap))
1390                   (dotimes (i length)
1391                     (let* ((byte (aref string i))
1392                            (bits (char-code byte)))
1393                       (declare (ignorable byte bits))
1394                       ,out-expr)
1395                     (incf tail ,size))
1396                   (let* ((bits 0)
1397                          (byte (code-char bits)))
1398                     (declare (ignorable bits byte))
1399                     ,out-expr)))
1400               ,n-buffer)))
1401       (setf *external-formats*
1402        (cons '(,external-format ,in-function ,in-char-function ,out-function
1403                ,@(mapcar #'(lambda (buffering)
1404                              (intern (format nil format (string buffering))))
1405                          '(:none :line :full))
1406                nil ; no resync-function
1407                ,size-function ,read-c-string-function ,output-c-string-function)
1408         *external-formats*)))))
1409
1410 (defmacro define-external-format/variable-width
1411     (external-format output-restart out-size-expr
1412      out-expr in-size-expr in-expr)
1413   (let* ((name (first external-format))
1414          (out-function (symbolicate "OUTPUT-BYTES/" name))
1415          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1416          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1417          (in-char-function (symbolicate "INPUT-CHAR/" name))
1418          (resync-function (symbolicate "RESYNC/" name))
1419          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1420          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1421          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1422          (n-buffer (gensym "BUFFER")))
1423     `(progn
1424       (defun ,size-function (byte)
1425         (declare (ignorable byte))
1426         ,out-size-expr)
1427       (defun ,out-function (stream string flush-p start end)
1428         (let ((start (or start 0))
1429               (end (or end (length string))))
1430           (declare (type index start end))
1431           (synchronize-stream-output stream)
1432           (unless (<= 0 start end (length string))
1433             (sequence-bounding-indices-bad string start end))
1434           (do ()
1435               ((= end start))
1436             (let ((obuf (fd-stream-obuf stream)))
1437               (setf (buffer-tail obuf)
1438                     (string-dispatch (simple-base-string
1439                                       #!+sb-unicode
1440                                       (simple-array character (*))
1441                                       string)
1442                         string
1443                       (let ((len (buffer-length obuf))
1444                             (sap (buffer-sap obuf))
1445                             ;; FIXME: Rename
1446                             (tail (buffer-tail obuf)))
1447                         (declare (type index tail)
1448                                  ;; STRING bounds have already been checked.
1449                                  (optimize (safety 0)))
1450                         (loop
1451                           (,@(if output-restart
1452                                  `(catch 'output-nothing)
1453                                  `(progn))
1454                              (do* ()
1455                                   ((or (= start end) (< (- len tail) 4)))
1456                                (let* ((byte (aref string start))
1457                                       (bits (char-code byte))
1458                                       (size ,out-size-expr))
1459                                  ,out-expr
1460                                  (incf tail size)
1461                                  (incf start)))
1462                              ;; Exited from the loop normally
1463                              (return tail))
1464                           ;; Exited via CATCH. Skip the current character
1465                           ;; and try the inner loop again.
1466                           (incf start))))))
1467             (when (< start end)
1468               (flush-output-buffer stream)))
1469           (when flush-p
1470             (flush-output-buffer stream))))
1471       (def-output-routines/variable-width (,format
1472                                            ,out-size-expr
1473                                            ,output-restart
1474                                            ,external-format
1475                                            (:none character)
1476                                            (:line character)
1477                                            (:full character))
1478           (if (eql byte #\Newline)
1479               (setf (fd-stream-char-pos stream) 0)
1480               (incf (fd-stream-char-pos stream)))
1481         (let ((bits (char-code byte))
1482               (sap (buffer-sap obuf))
1483               (tail (buffer-tail obuf)))
1484           ,out-expr))
1485       (defun ,in-function (stream buffer start requested eof-error-p
1486                            &aux (total-copied 0))
1487         (declare (type fd-stream stream)
1488                  (type index start requested total-copied)
1489                  (type
1490                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1491                   buffer))
1492         (let ((unread (fd-stream-unread stream)))
1493           (when unread
1494             (setf (aref buffer start) unread)
1495             (setf (fd-stream-unread stream) nil)
1496             (setf (fd-stream-listen stream) nil)
1497             (incf total-copied)))
1498         (do ()
1499             (nil)
1500           (let* ((ibuf (fd-stream-ibuf stream))
1501                  (head (buffer-head ibuf))
1502                  (tail (buffer-tail ibuf))
1503                  (sap (buffer-sap ibuf))
1504                  (decode-break-reason nil))
1505             (declare (type index head tail))
1506             ;; Copy data from stream buffer into user's buffer.
1507             (do ((size nil nil))
1508                 ((or (= tail head) (= requested total-copied)))
1509               (setf decode-break-reason
1510                     (block decode-break-reason
1511                       (let ((byte (sap-ref-8 sap head)))
1512                         (declare (ignorable byte))
1513                         (setq size ,in-size-expr)
1514                         (when (> size (- tail head))
1515                           (return))
1516                         (setf (aref buffer (+ start total-copied)) ,in-expr)
1517                         (incf total-copied)
1518                         (incf head size))
1519                       nil))
1520               (setf (buffer-head ibuf) head)
1521               (when decode-break-reason
1522                 ;; If we've already read some characters on when the invalid
1523                 ;; code sequence is detected, we return immediately. The
1524                 ;; handling of the error is deferred until the next call
1525                 ;; (where this check will be false). This allows establishing
1526                 ;; high-level handlers for decode errors (for example
1527                 ;; automatically resyncing in Lisp comments).
1528                 (when (plusp total-copied)
1529                   (return-from ,in-function total-copied))
1530                 (when (stream-decoding-error-and-handle
1531                        stream decode-break-reason)
1532                   (if eof-error-p
1533                       (error 'end-of-file :stream stream)
1534                       (return-from ,in-function total-copied)))
1535                 (setf head (buffer-head ibuf))
1536                 (setf tail (buffer-tail ibuf))))
1537             (setf (buffer-head ibuf) head)
1538             ;; Maybe we need to refill the stream buffer.
1539             (cond ( ;; If there were enough data in the stream buffer, we're done.
1540                    (= total-copied requested)
1541                    (return total-copied))
1542                   ( ;; If EOF, we're done in another way.
1543                    (or (eq decode-break-reason 'eof)
1544                        (null (catch 'eof-input-catcher
1545                                (refill-input-buffer stream))))
1546                    (if eof-error-p
1547                        (error 'end-of-file :stream stream)
1548                        (return total-copied)))
1549                   ;; Otherwise we refilled the stream buffer, so fall
1550                   ;; through into another pass of the loop.
1551                   ))))
1552       (def-input-routine/variable-width ,in-char-function (character
1553                                                            ,external-format
1554                                                            ,in-size-expr
1555                                                            sap head)
1556         (let ((byte (sap-ref-8 sap head)))
1557           (declare (ignorable byte))
1558           ,in-expr))
1559       (defun ,resync-function (stream)
1560         (let ((ibuf (fd-stream-ibuf stream)))
1561           (loop
1562             (input-at-least stream 2)
1563             (incf (buffer-head ibuf))
1564             (unless (block decode-break-reason
1565                       (let* ((sap (buffer-sap ibuf))
1566                              (head (buffer-head ibuf))
1567                              (byte (sap-ref-8 sap head))
1568                              (size ,in-size-expr))
1569                         (declare (ignorable byte))
1570                         (input-at-least stream size)
1571                         (setf head (buffer-head ibuf))
1572                         ,in-expr)
1573                      nil)
1574              (return)))))
1575       (defun ,read-c-string-function (sap element-type)
1576         (declare (type system-area-pointer sap))
1577         (locally
1578             (declare (optimize (speed 3) (safety 0)))
1579           (let* ((stream ,name)
1580                  (size 0) (head 0) (byte 0) (char nil)
1581                  (decode-break-reason nil)
1582                  (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1583                            (setf decode-break-reason
1584                                  (block decode-break-reason
1585                                    (setf byte (sap-ref-8 sap head)
1586                                          size ,in-size-expr
1587                                          char ,in-expr)
1588                                    (incf head size)
1589                                    nil))
1590                            (when decode-break-reason
1591                              (c-string-decoding-error ,name decode-break-reason))
1592                            (when (zerop (char-code char))
1593                              (return count))))
1594                  (string (make-string length :element-type element-type)))
1595             (declare (ignorable stream)
1596                      (type index head length) ;; size
1597                      (type (unsigned-byte 8) byte)
1598                      (type (or null character) char)
1599                      (type string string))
1600             (setf head 0)
1601             (dotimes (index length string)
1602               (setf decode-break-reason
1603                     (block decode-break-reason
1604                       (setf byte (sap-ref-8 sap head)
1605                             size ,in-size-expr
1606                             char ,in-expr)
1607                       (incf head size)
1608                       nil))
1609               (when decode-break-reason
1610                 (c-string-decoding-error ,name decode-break-reason))
1611               (setf (aref string index) char)))))
1612
1613       (defun ,output-c-string-function (string)
1614         (declare (type simple-string string))
1615         (locally
1616             (declare (optimize (speed 3) (safety 0)))
1617           (let* ((length (length string))
1618                  (char-length (make-array (1+ length) :element-type 'index))
1619                  (buffer-length
1620                   (+ (loop for i of-type index below length
1621                         for byte of-type character = (aref string i)
1622                         for bits = (char-code byte)
1623                         sum (setf (aref char-length i)
1624                                   (the index ,out-size-expr)))
1625                      (let* ((byte (code-char 0))
1626                             (bits (char-code byte)))
1627                        (declare (ignorable byte bits))
1628                        (setf (aref char-length length)
1629                              (the index ,out-size-expr)))))
1630                  (tail 0)
1631                  (,n-buffer (make-array buffer-length
1632                                         :element-type '(unsigned-byte 8)))
1633                  stream)
1634             (declare (type index length buffer-length tail)
1635                      (type null stream)
1636                      (ignorable stream))
1637             (with-pinned-objects (,n-buffer)
1638               (let ((sap (vector-sap ,n-buffer)))
1639                 (declare (system-area-pointer sap))
1640                 (loop for i of-type index below length
1641                       for byte of-type character = (aref string i)
1642                       for bits = (char-code byte)
1643                       for size of-type index = (aref char-length i)
1644                       do (prog1
1645                              ,out-expr
1646                            (incf tail size)))
1647                 (let* ((bits 0)
1648                        (byte (code-char bits))
1649                        (size (aref char-length length)))
1650                   (declare (ignorable bits byte size))
1651                   ,out-expr)))
1652             ,n-buffer)))
1653
1654       (setf *external-formats*
1655        (cons '(,external-format ,in-function ,in-char-function ,out-function
1656                ,@(mapcar #'(lambda (buffering)
1657                              (intern (format nil format (string buffering))))
1658                          '(:none :line :full))
1659                ,resync-function
1660                ,size-function ,read-c-string-function ,output-c-string-function)
1661         *external-formats*)))))
1662
1663 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1664 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1665 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1666 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1667     1 t
1668   (if (>= bits 256)
1669       (external-format-encoding-error stream bits)
1670       (setf (sap-ref-8 sap tail) bits))
1671   (code-char byte))
1672
1673 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1674                          :iso-646 :iso-646-us :|646|)
1675     1 t
1676   (if (>= bits 128)
1677       (external-format-encoding-error stream bits)
1678       (setf (sap-ref-8 sap tail) bits))
1679   (code-char byte))
1680
1681 (let* ((table (let ((s (make-string 256)))
1682                 (map-into s #'code-char
1683                           '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1684                             #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1685                             #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1686                             #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1687                             #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1688                             #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1689                             #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1690                             #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1691                             #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1692                             #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1693                             #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1694                             #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1695                             #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1696                             #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1697                             #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1698                             #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1699                 s))
1700        (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1701                           (loop for char across table for i from 0
1702                                do (aver (= 0 (aref rt (char-code char))))
1703                                do (setf (aref rt (char-code char)) i))
1704                           rt)))
1705   (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1706       1 t
1707     (if (>= bits 256)
1708         (external-format-encoding-error stream bits)
1709         (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1710     (aref table byte)))
1711
1712
1713 #!+sb-unicode
1714 (let ((latin-9-table (let ((table (make-string 256)))
1715                        (do ((i 0 (1+ i)))
1716                            ((= i 256))
1717                          (setf (aref table i) (code-char i)))
1718                        (setf (aref table #xa4) (code-char #x20ac))
1719                        (setf (aref table #xa6) (code-char #x0160))
1720                        (setf (aref table #xa8) (code-char #x0161))
1721                        (setf (aref table #xb4) (code-char #x017d))
1722                        (setf (aref table #xb8) (code-char #x017e))
1723                        (setf (aref table #xbc) (code-char #x0152))
1724                        (setf (aref table #xbd) (code-char #x0153))
1725                        (setf (aref table #xbe) (code-char #x0178))
1726                        table))
1727       (latin-9-reverse-1 (make-array 16
1728                                      :element-type '(unsigned-byte 21)
1729                                      :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1730       (latin-9-reverse-2 (make-array 16
1731                                      :element-type '(unsigned-byte 8)
1732                                      :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1733   (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1734       1 t
1735     (setf (sap-ref-8 sap tail)
1736           (if (< bits 256)
1737               (if (= bits (char-code (aref latin-9-table bits)))
1738                   bits
1739                   (external-format-encoding-error stream byte))
1740               (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1741                   (aref latin-9-reverse-2 (logand bits 15))
1742                   (external-format-encoding-error stream byte))))
1743     (aref latin-9-table byte)))
1744
1745 (define-external-format/variable-width (:utf-8 :utf8) nil
1746   (let ((bits (char-code byte)))
1747     (cond ((< bits #x80) 1)
1748           ((< bits #x800) 2)
1749           ((< bits #x10000) 3)
1750           (t 4)))
1751   (ecase size
1752     (1 (setf (sap-ref-8 sap tail) bits))
1753     (2 (setf (sap-ref-8 sap tail)       (logior #xc0 (ldb (byte 5 6) bits))
1754              (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1755     (3 (setf (sap-ref-8 sap tail)       (logior #xe0 (ldb (byte 4 12) bits))
1756              (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 6) bits))
1757              (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1758     (4 (setf (sap-ref-8 sap tail)       (logior #xf0 (ldb (byte 3 18) bits))
1759              (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 12) bits))
1760              (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1761              (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1762   (cond ((< byte #x80) 1)
1763         ((< byte #xc2) (return-from decode-break-reason 1))
1764         ((< byte #xe0) 2)
1765         ((< byte #xf0) 3)
1766         (t 4))
1767   (code-char (ecase size
1768                (1 byte)
1769                (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1770                     (unless (<= #x80 byte2 #xbf)
1771                       (return-from decode-break-reason 2))
1772                     (dpb byte (byte 5 6) byte2)))
1773                (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1774                         (byte3 (sap-ref-8 sap (+ 2 head))))
1775                     (unless (and (<= #x80 byte2 #xbf)
1776                                  (<= #x80 byte3 #xbf))
1777                       (return-from decode-break-reason 3))
1778                     (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1779                (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1780                         (byte3 (sap-ref-8 sap (+ 2 head)))
1781                         (byte4 (sap-ref-8 sap (+ 3 head))))
1782                     (unless (and (<= #x80 byte2 #xbf)
1783                                  (<= #x80 byte3 #xbf)
1784                                  (<= #x80 byte4 #xbf))
1785                       (return-from decode-break-reason 4))
1786                     (dpb byte (byte 3 18)
1787                          (dpb byte2 (byte 6 12)
1788                               (dpb byte3 (byte 6 6) byte4))))))))
1789 \f
1790 ;;;; utility functions (misc routines, etc)
1791
1792 ;;; Fill in the various routine slots for the given type. INPUT-P and
1793 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1794 ;;; set prior to calling this routine.
1795 (defun set-fd-stream-routines (fd-stream element-type external-format
1796                                input-p output-p buffer-p)
1797   (let* ((target-type (case element-type
1798                         (unsigned-byte '(unsigned-byte 8))
1799                         (signed-byte '(signed-byte 8))
1800                         (:default 'character)
1801                         (t element-type)))
1802          (character-stream-p (subtypep target-type 'character))
1803          (bivalent-stream-p (eq element-type :default))
1804          normalized-external-format
1805          (bin-routine #'ill-bin)
1806          (bin-type nil)
1807          (bin-size nil)
1808          (cin-routine #'ill-in)
1809          (cin-type nil)
1810          (cin-size nil)
1811          (input-type nil)           ;calculated from bin-type/cin-type
1812          (input-size nil)           ;calculated from bin-size/cin-size
1813          (read-n-characters #'ill-in)
1814          (bout-routine #'ill-bout)
1815          (bout-type nil)
1816          (bout-size nil)
1817          (cout-routine #'ill-out)
1818          (cout-type nil)
1819          (cout-size nil)
1820          (output-type nil)
1821          (output-size nil)
1822          (output-bytes #'ill-bout))
1823
1824     ;; Ensure that we have buffers in the desired direction(s) only,
1825     ;; getting new ones and dropping/resetting old ones as necessary.
1826     (let ((obuf (fd-stream-obuf fd-stream)))
1827       (if output-p
1828           (if obuf
1829               (reset-buffer obuf)
1830               (setf (fd-stream-obuf fd-stream) (get-buffer)))
1831           (when obuf
1832             (setf (fd-stream-obuf fd-stream) nil)
1833             (release-buffer obuf))))
1834
1835     (let ((ibuf (fd-stream-ibuf fd-stream)))
1836       (if input-p
1837           (if ibuf
1838               (reset-buffer ibuf)
1839               (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1840           (when ibuf
1841             (setf (fd-stream-ibuf fd-stream) nil)
1842             (release-buffer ibuf))))
1843
1844     ;; FIXME: Why only for output? Why unconditionally?
1845     (when output-p
1846       (setf (fd-stream-char-pos fd-stream) 0))
1847
1848     (when (and character-stream-p
1849                (eq external-format :default))
1850       (/show0 "/getting default external format")
1851       (setf external-format (default-external-format)))
1852
1853     (when input-p
1854       (when (or (not character-stream-p) bivalent-stream-p)
1855         (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1856                                           normalized-external-format)
1857           (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1858                                   target-type)
1859                               external-format))
1860         (unless bin-routine
1861           (error "could not find any input routine for ~S" target-type)))
1862       (when character-stream-p
1863         (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1864                                           normalized-external-format)
1865           (pick-input-routine target-type external-format))
1866         (unless cin-routine
1867           (error "could not find any input routine for ~S" target-type)))
1868       (setf (fd-stream-in fd-stream) cin-routine
1869             (fd-stream-bin fd-stream) bin-routine)
1870       ;; character type gets preferential treatment
1871       (setf input-size (or cin-size bin-size))
1872       (setf input-type (or cin-type bin-type))
1873       (when normalized-external-format
1874         (setf (fd-stream-external-format fd-stream)
1875               normalized-external-format))
1876       (when (= (or cin-size 1) (or bin-size 1) 1)
1877         (setf (fd-stream-n-bin fd-stream) ;XXX
1878               (if (and character-stream-p (not bivalent-stream-p))
1879                   read-n-characters
1880                   #'fd-stream-read-n-bytes))
1881         ;; Sometimes turn on fast-read-char/fast-read-byte.  Switch on
1882         ;; for character and (unsigned-byte 8) streams.  In these
1883         ;; cases, fast-read-* will read from the
1884         ;; ansi-stream-(c)in-buffer, saving function calls.
1885         ;; Otherwise, the various data-reading functions in the stream
1886         ;; structure will be called.
1887         (when (and buffer-p
1888                    (not bivalent-stream-p)
1889                    ;; temporary disable on :io streams
1890                    (not output-p))
1891           (cond (character-stream-p
1892                  (setf (ansi-stream-cin-buffer fd-stream)
1893                        (make-array +ansi-stream-in-buffer-length+
1894                                    :element-type 'character)))
1895                 ((equal target-type '(unsigned-byte 8))
1896                  (setf (ansi-stream-in-buffer fd-stream)
1897                        (make-array +ansi-stream-in-buffer-length+
1898                                    :element-type '(unsigned-byte 8))))))))
1899
1900     (when output-p
1901       (when (or (not character-stream-p) bivalent-stream-p)
1902         (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1903                                            normalized-external-format)
1904           (pick-output-routine (if bivalent-stream-p
1905                                    '(unsigned-byte 8)
1906                                    target-type)
1907                                (fd-stream-buffering fd-stream)
1908                                external-format))
1909         (unless bout-routine
1910           (error "could not find any output routine for ~S buffered ~S"
1911                  (fd-stream-buffering fd-stream)
1912                  target-type)))
1913       (when character-stream-p
1914         (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1915                                            normalized-external-format)
1916           (pick-output-routine target-type
1917                                (fd-stream-buffering fd-stream)
1918                                external-format))
1919         (unless cout-routine
1920           (error "could not find any output routine for ~S buffered ~S"
1921                  (fd-stream-buffering fd-stream)
1922                  target-type)))
1923       (when normalized-external-format
1924         (setf (fd-stream-external-format fd-stream)
1925               normalized-external-format))
1926       (when character-stream-p
1927         (setf (fd-stream-output-bytes fd-stream) output-bytes))
1928       (setf (fd-stream-out fd-stream) cout-routine
1929             (fd-stream-bout fd-stream) bout-routine
1930             (fd-stream-sout fd-stream) (if (eql cout-size 1)
1931                                            #'fd-sout #'ill-out))
1932       (setf output-size (or cout-size bout-size))
1933       (setf output-type (or cout-type bout-type)))
1934
1935     (when (and input-size output-size
1936                (not (eq input-size output-size)))
1937       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1938              input-type input-size
1939              output-type output-size))
1940     (setf (fd-stream-element-size fd-stream)
1941           (or input-size output-size))
1942
1943     (setf (fd-stream-element-type fd-stream)
1944           (cond ((equal input-type output-type)
1945                  input-type)
1946                 ((null output-type)
1947                  input-type)
1948                 ((null input-type)
1949                  output-type)
1950                 ((subtypep input-type output-type)
1951                  input-type)
1952                 ((subtypep output-type input-type)
1953                  output-type)
1954                 (t
1955                  (error "Input type (~S) and output type (~S) are unrelated?"
1956                         input-type
1957                         output-type))))))
1958
1959 ;;; Handles the resource-release aspects of stream closing, and marks
1960 ;;; it as closed.
1961 (defun release-fd-stream-resources (fd-stream)
1962   (handler-case
1963       (without-interrupts
1964         ;; Drop handlers first.
1965         (when (fd-stream-handler fd-stream)
1966           (remove-fd-handler (fd-stream-handler fd-stream))
1967           (setf (fd-stream-handler fd-stream) nil))
1968         ;; Disable interrupts so that a asynch unwind will not leave
1969         ;; us with a dangling finalizer (that would close the same
1970         ;; --possibly reassigned-- FD again), or a stream with a closed
1971         ;; FD that appears open.
1972         (sb!unix:unix-close (fd-stream-fd fd-stream))
1973         (set-closed-flame fd-stream)
1974         (when (fboundp 'cancel-finalization)
1975           (cancel-finalization fd-stream)))
1976     ;; On error unwind from WITHOUT-INTERRUPTS.
1977     (serious-condition (e)
1978       (error e)))
1979   ;; Release all buffers. If this is undone, or interrupted,
1980   ;; we're still safe: buffers have finalizers of their own.
1981   (release-fd-stream-buffers fd-stream))
1982
1983 ;;; Flushes the current input buffer and unread chatacter, and returns
1984 ;;; the input buffer, and the amount of of flushed input in bytes.
1985 (defun flush-input-buffer (stream)
1986   (let ((unread (if (fd-stream-unread stream)
1987                     1
1988                     0)))
1989     (setf (fd-stream-unread stream) nil)
1990     (let ((ibuf (fd-stream-ibuf stream)))
1991       (if ibuf
1992           (let ((head (buffer-head ibuf))
1993                 (tail (buffer-tail ibuf)))
1994             (values (reset-buffer ibuf) (- (+ unread tail) head)))
1995           (values nil unread)))))
1996
1997 (defun fd-stream-clear-input (stream)
1998   (flush-input-buffer stream)
1999   #!+win32
2000   (progn
2001     (sb!win32:fd-clear-input (fd-stream-fd stream))
2002     (setf (fd-stream-listen stream) nil))
2003   #!-win32
2004   (catch 'eof-input-catcher
2005     (loop until (sysread-may-block-p stream)
2006           do
2007           (refill-input-buffer stream)
2008           (reset-buffer (fd-stream-ibuf stream)))
2009     t))
2010
2011 ;;; Handle miscellaneous operations on FD-STREAM.
2012 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
2013   (declare (ignore arg2))
2014   (case operation
2015     (:listen
2016      (labels ((do-listen ()
2017                 (let ((ibuf (fd-stream-ibuf fd-stream)))
2018                   (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
2019                       (fd-stream-listen fd-stream)
2020                       #!+win32
2021                       (sb!win32:fd-listen (fd-stream-fd fd-stream))
2022                       #!-win32
2023                       ;; If the read can block, LISTEN will certainly return NIL.
2024                       (if (sysread-may-block-p fd-stream)
2025                           nil
2026                           ;; Otherwise select(2) and CL:LISTEN have slightly
2027                           ;; different semantics.  The former returns that an FD
2028                           ;; is readable when a read operation wouldn't block.
2029                           ;; That includes EOF.  However, LISTEN must return NIL
2030                           ;; at EOF.
2031                           (progn (catch 'eof-input-catcher
2032                                    ;; r-b/f too calls select, but it shouldn't
2033                                    ;; block as long as read can return once w/o
2034                                    ;; blocking
2035                                    (refill-input-buffer fd-stream))
2036                                  ;; At this point either IBUF-HEAD != IBUF-TAIL
2037                                  ;; and FD-STREAM-LISTEN is NIL, in which case
2038                                  ;; we should return T, or IBUF-HEAD ==
2039                                  ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2040                                  ;; which case we should return :EOF for this
2041                                  ;; call and all future LISTEN call on this stream.
2042                                  ;; Call ourselves again to determine which case
2043                                  ;; applies.
2044                                  (do-listen)))))))
2045        (do-listen)))
2046     (:unread
2047      ;; If the stream is bivalent, the user might follow an
2048      ;; unread-char with a read-byte.  In this case, the bookkeeping
2049      ;; is simpler if we adjust the buffer head by the number of code
2050      ;; units in the character.
2051      ;; FIXME: there has to be a proper way to check for bivalence,
2052      ;; right?
2053      (if (fd-stream-bivalent-p fd-stream)
2054          (decf (buffer-head (fd-stream-ibuf fd-stream))
2055                (fd-stream-character-size fd-stream arg1))
2056          (setf (fd-stream-unread fd-stream) arg1))
2057      (setf (fd-stream-listen fd-stream) t))
2058     (:close
2059      ;; Drop input buffers
2060      (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
2061            (ansi-stream-cin-buffer fd-stream) nil
2062            (ansi-stream-in-buffer fd-stream) nil)
2063      (cond (arg1
2064             ;; We got us an abort on our hands.
2065             (let ((outputp (fd-stream-obuf fd-stream))
2066                   (file (fd-stream-file fd-stream))
2067                   (orig (fd-stream-original fd-stream)))
2068               ;; This takes care of the important stuff -- everything
2069               ;; rest is cleaning up the file-system, which we cannot
2070               ;; do on some platforms as long as the file is open.
2071               (release-fd-stream-resources fd-stream)
2072               ;; We can't do anything unless we know what file were
2073               ;; dealing with, and we don't want to do anything
2074               ;; strange unless we were writing to the file.
2075               (when (and outputp file)
2076                 (if orig
2077                     ;; If the original is EQ to file we are appending to
2078                     ;; and can just close the file without renaming.
2079                     (unless (eq orig file)
2080                       ;; We have a handle on the original, just revert.
2081                       (multiple-value-bind (okay err)
2082                           (sb!unix:unix-rename orig file)
2083                         ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2084                         ;; others are SIMPLE-FILE-ERRORS? Surely they should
2085                         ;; all be the same?
2086                         (unless okay
2087                           (error 'simple-stream-error
2088                                  :format-control
2089                                  "~@<Couldn't restore ~S to its original contents ~
2090                                   from ~S while closing ~S: ~2I~_~A~:>"
2091                                  :format-arguments
2092                                  (list file orig fd-stream (strerror err))
2093                                  :stream fd-stream))))
2094                     ;; We can't restore the original, and aren't
2095                     ;; appending, so nuke that puppy.
2096                     ;;
2097                     ;; FIXME: This is currently the fate of superseded
2098                     ;; files, and according to the CLOSE spec this is
2099                     ;; wrong. However, there seems to be no clean way to
2100                     ;; do that that doesn't involve either copying the
2101                     ;; data (bad if the :abort resulted from a full
2102                     ;; disk), or renaming the old file temporarily
2103                     ;; (probably bad because stream opening becomes more
2104                     ;; racy).
2105                     (multiple-value-bind (okay err)
2106                         (sb!unix:unix-unlink file)
2107                       (unless okay
2108                         (error 'simple-file-error
2109                                :pathname file
2110                                :format-control
2111                                "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2112                                :format-arguments
2113                                (list file fd-stream (strerror err)))))))))
2114            (t
2115             (finish-fd-stream-output fd-stream)
2116             (let ((orig (fd-stream-original fd-stream)))
2117               (when (and orig (fd-stream-delete-original fd-stream))
2118                 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2119                   (unless okay
2120                     (error 'simple-file-error
2121                            :pathname orig
2122                            :format-control
2123                            "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2124                            :format-arguments
2125                            (list orig fd-stream (strerror err)))))))
2126             ;; In case of no-abort close, don't *really* close the
2127             ;; stream until the last moment -- the cleaning up of the
2128             ;; original can be done first.
2129             (release-fd-stream-resources fd-stream))))
2130     (:clear-input
2131      (fd-stream-clear-input fd-stream))
2132     (:force-output
2133      (flush-output-buffer fd-stream))
2134     (:finish-output
2135      (finish-fd-stream-output fd-stream))
2136     (:element-type
2137      (fd-stream-element-type fd-stream))
2138     (:external-format
2139      (fd-stream-external-format fd-stream))
2140     (:interactive-p
2141      (= 1 (the (member 0 1)
2142             (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2143     (:line-length
2144      80)
2145     (:charpos
2146      (fd-stream-char-pos fd-stream))
2147     (:file-length
2148      (unless (fd-stream-file fd-stream)
2149        ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2150        ;; "should signal an error of type TYPE-ERROR if stream is not
2151        ;; a stream associated with a file". Too bad there's no very
2152        ;; appropriate value for the EXPECTED-TYPE slot..
2153        (error 'simple-type-error
2154               :datum fd-stream
2155               :expected-type 'fd-stream
2156               :format-control "~S is not a stream associated with a file."
2157               :format-arguments (list fd-stream)))
2158      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2159                                 atime mtime ctime blksize blocks)
2160          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2161        (declare (ignore ino nlink uid gid rdev
2162                         atime mtime ctime blksize blocks))
2163        (unless okay
2164          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2165        (if (zerop mode)
2166            nil
2167            (truncate size (fd-stream-element-size fd-stream)))))
2168     (:file-string-length
2169      (etypecase arg1
2170        (character (fd-stream-character-size fd-stream arg1))
2171        (string (fd-stream-string-size fd-stream arg1))))
2172     (:file-position
2173      (if arg1
2174          (fd-stream-set-file-position fd-stream arg1)
2175          (fd-stream-get-file-position fd-stream)))))
2176
2177 ;; FIXME: Think about this.
2178 ;;
2179 ;; (defun finish-fd-stream-output (fd-stream)
2180 ;;   (let ((timeout (fd-stream-timeout fd-stream)))
2181 ;;     (loop while (fd-stream-output-queue fd-stream)
2182 ;;        ;; FIXME: SIGINT while waiting for a timeout will
2183 ;;        ;; cause a timeout here.
2184 ;;        do (when (and (not (serve-event timeout)) timeout)
2185 ;;             (signal-timeout 'io-timeout
2186 ;;                             :stream fd-stream
2187 ;;                             :direction :write
2188 ;;                             :seconds timeout)))))
2189
2190 (defun finish-fd-stream-output (stream)
2191   (flush-output-buffer stream)
2192   (do ()
2193       ((null (fd-stream-output-queue stream)))
2194     (serve-all-events)))
2195
2196 (defun fd-stream-get-file-position (stream)
2197   (declare (fd-stream stream))
2198   (without-interrupts
2199     (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2200       (declare (type (or (alien sb!unix:off-t) null) posn))
2201       ;; We used to return NIL for errno==ESPIPE, and signal an error
2202       ;; in other failure cases. However, CLHS says to return NIL if
2203       ;; the position cannot be determined -- so that's what we do.
2204       (when (integerp posn)
2205         ;; Adjust for buffered output: If there is any output
2206         ;; buffered, the *real* file position will be larger
2207         ;; than reported by lseek() because lseek() obviously
2208         ;; cannot take into account output we have not sent
2209         ;; yet.
2210         (dolist (buffer (fd-stream-output-queue stream))
2211           (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2212         (let ((obuf (fd-stream-obuf stream)))
2213           (when obuf
2214             (incf posn (buffer-tail obuf))))
2215         ;; Adjust for unread input: If there is any input
2216         ;; read from UNIX but not supplied to the user of the
2217         ;; stream, the *real* file position will smaller than
2218         ;; reported, because we want to look like the unread
2219         ;; stuff is still available.
2220         (let ((ibuf (fd-stream-ibuf stream)))
2221           (when ibuf
2222             (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2223         (when (fd-stream-unread stream)
2224           (decf posn))
2225         ;; Divide bytes by element size.
2226         (truncate posn (fd-stream-element-size stream))))))
2227
2228 (defun fd-stream-set-file-position (stream position-spec)
2229   (declare (fd-stream stream))
2230   (check-type position-spec
2231               (or (alien sb!unix:off-t) (member nil :start :end))
2232               "valid file position designator")
2233   (tagbody
2234    :again
2235      ;; Make sure we don't have any output pending, because if we
2236      ;; move the file pointer before writing this stuff, it will be
2237      ;; written in the wrong location.
2238      (finish-fd-stream-output stream)
2239      ;; Disable interrupts so that interrupt handlers doing output
2240      ;; won't screw us.
2241      (without-interrupts
2242        (unless (fd-stream-output-finished-p stream)
2243          ;; We got interrupted and more output came our way during
2244          ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2245          ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2246          ;; so we prefer to do things like this...
2247          (go :again))
2248        ;; Clear out any pending input to force the next read to go to
2249        ;; the disk.
2250        (flush-input-buffer stream)
2251        ;; Trash cached value for listen, so that we check next time.
2252        (setf (fd-stream-listen stream) nil)
2253          ;; Now move it.
2254          (multiple-value-bind (offset origin)
2255              (case position-spec
2256                (:start
2257                 (values 0 sb!unix:l_set))
2258                (:end
2259                 (values 0 sb!unix:l_xtnd))
2260                (t
2261                 (values (* position-spec (fd-stream-element-size stream))
2262                         sb!unix:l_set)))
2263            (declare (type (alien sb!unix:off-t) offset))
2264            (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2265                                            offset origin)))
2266              ;; CLHS says to return true if the file-position was set
2267              ;; succesfully, and NIL otherwise. We are to signal an error
2268              ;; only if the given position was out of bounds, and that is
2269              ;; dealt with above. In times past we used to return NIL for
2270              ;; errno==ESPIPE, and signal an error in other cases.
2271              ;;
2272              ;; FIXME: We are still liable to signal an error if flushing
2273              ;; output fails.
2274              (return-from fd-stream-set-file-position
2275                (typep posn '(alien sb!unix:off-t))))))))
2276
2277 \f
2278 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2279
2280 ;;; Create a stream for the given Unix file descriptor.
2281 ;;;
2282 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2283 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2284 ;;; default to allowing input.
2285 ;;;
2286 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2287 ;;;
2288 ;;; BUFFERING indicates the kind of buffering to use.
2289 ;;;
2290 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2291 ;;; NIL (the default), then wait forever. When we time out, we signal
2292 ;;; IO-TIMEOUT.
2293 ;;;
2294 ;;; FILE is the name of the file (will be returned by PATHNAME).
2295 ;;;
2296 ;;; NAME is used to identify the stream when printed.
2297 (defun make-fd-stream (fd
2298                        &key
2299                        (input nil input-p)
2300                        (output nil output-p)
2301                        (element-type 'base-char)
2302                        (buffering :full)
2303                        (external-format :default)
2304                        timeout
2305                        file
2306                        original
2307                        delete-original
2308                        pathname
2309                        input-buffer-p
2310                        dual-channel-p
2311                        (name (if file
2312                                  (format nil "file ~A" file)
2313                                  (format nil "descriptor ~W" fd)))
2314                        auto-close)
2315   (declare (type index fd) (type (or real null) timeout)
2316            (type (member :none :line :full) buffering))
2317   (cond ((not (or input-p output-p))
2318          (setf input t))
2319         ((not (or input output))
2320          (error "File descriptor must be opened either for input or output.")))
2321   (let ((stream (%make-fd-stream :fd fd
2322                                  :name name
2323                                  :file file
2324                                  :original original
2325                                  :delete-original delete-original
2326                                  :pathname pathname
2327                                  :buffering buffering
2328                                  :dual-channel-p dual-channel-p
2329                                  :external-format external-format
2330                                  :bivalent-p (eq element-type :default)
2331                                  :char-size (external-format-char-size external-format)
2332                                  :timeout
2333                                  (if timeout
2334                                      (coerce timeout 'single-float)
2335                                      nil))))
2336     (set-fd-stream-routines stream element-type external-format
2337                             input output input-buffer-p)
2338     (when (and auto-close (fboundp 'finalize))
2339       (finalize stream
2340                 (lambda ()
2341                   (sb!unix:unix-close fd)
2342                   #!+sb-show
2343                   (format *terminal-io* "** closed file descriptor ~W **~%"
2344                           fd))
2345                 :dont-save t))
2346     stream))
2347
2348 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2349 ;;; :RENAME-AND-DELETE and :RENAME options.
2350 (defun pick-backup-name (name)
2351   (declare (type simple-string name))
2352   (concatenate 'simple-string name ".bak"))
2353
2354 ;;; Ensure that the given arg is one of the given list of valid
2355 ;;; things. Allow the user to fix any problems.
2356 (defun ensure-one-of (item list what)
2357   (unless (member item list)
2358     (error 'simple-type-error
2359            :datum item
2360            :expected-type `(member ,@list)
2361            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2362            :format-arguments (list item what list))))
2363
2364 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2365 ;;; access, since we don't want to trash unwritable files even if we
2366 ;;; technically can. We return true if we succeed in renaming.
2367 (defun rename-the-old-one (namestring original)
2368   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2369     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2370   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2371     (if okay
2372         t
2373         (error 'simple-file-error
2374                :pathname namestring
2375                :format-control
2376                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2377                :format-arguments (list namestring original (strerror err))))))
2378
2379 (defun open (filename
2380              &key
2381              (direction :input)
2382              (element-type 'base-char)
2383              (if-exists nil if-exists-given)
2384              (if-does-not-exist nil if-does-not-exist-given)
2385              (external-format :default)
2386              &aux ; Squelch assignment warning.
2387              (direction direction)
2388              (if-does-not-exist if-does-not-exist)
2389              (if-exists if-exists))
2390   #!+sb-doc
2391   "Return a stream which reads from or writes to FILENAME.
2392   Defined keywords:
2393    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2394    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2395    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2396                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2397    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2398   See the manual for details."
2399
2400   ;; Calculate useful stuff.
2401   (multiple-value-bind (input output mask)
2402       (ecase direction
2403         (:input  (values   t nil sb!unix:o_rdonly))
2404         (:output (values nil   t sb!unix:o_wronly))
2405         (:io     (values   t   t sb!unix:o_rdwr))
2406         (:probe  (values   t nil sb!unix:o_rdonly)))
2407     (declare (type index mask))
2408     (let* ((pathname (merge-pathnames filename))
2409            (namestring
2410             (cond ((unix-namestring pathname input))
2411                   ((and input (eq if-does-not-exist :create))
2412                    (unix-namestring pathname nil))
2413                   ((and (eq direction :io) (not if-does-not-exist-given))
2414                    (unix-namestring pathname nil)))))
2415       ;; Process if-exists argument if we are doing any output.
2416       (cond (output
2417              (unless if-exists-given
2418                (setf if-exists
2419                      (if (eq (pathname-version pathname) :newest)
2420                          :new-version
2421                          :error)))
2422              (ensure-one-of if-exists
2423                             '(:error :new-version :rename
2424                                      :rename-and-delete :overwrite
2425                                      :append :supersede nil)
2426                             :if-exists)
2427              (case if-exists
2428                ((:new-version :error nil)
2429                 (setf mask (logior mask sb!unix:o_excl)))
2430                ((:rename :rename-and-delete)
2431                 (setf mask (logior mask sb!unix:o_creat)))
2432                ((:supersede)
2433                 (setf mask (logior mask sb!unix:o_trunc)))
2434                (:append
2435                 (setf mask (logior mask sb!unix:o_append)))))
2436             (t
2437              (setf if-exists :ignore-this-arg)))
2438
2439       (unless if-does-not-exist-given
2440         (setf if-does-not-exist
2441               (cond ((eq direction :input) :error)
2442                     ((and output
2443                           (member if-exists '(:overwrite :append)))
2444                      :error)
2445                     ((eq direction :probe)
2446                      nil)
2447                     (t
2448                      :create))))
2449       (ensure-one-of if-does-not-exist
2450                      '(:error :create nil)
2451                      :if-does-not-exist)
2452       (if (eq if-does-not-exist :create)
2453         (setf mask (logior mask sb!unix:o_creat)))
2454
2455       (let ((original (case if-exists
2456                         ((:rename :rename-and-delete)
2457                          (pick-backup-name namestring))
2458                         ((:append :overwrite)
2459                          ;; KLUDGE: Provent CLOSE from deleting
2460                          ;; appending streams when called with :ABORT T
2461                          namestring)))
2462             (delete-original (eq if-exists :rename-and-delete))
2463             (mode #o666))
2464         (when (and original (not (eq original namestring)))
2465           ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2466           ;; whether the file already exists, make sure the original
2467           ;; file is not a directory, and keep the mode.
2468           (let ((exists
2469                  (and namestring
2470                       (multiple-value-bind (okay err/dev inode orig-mode)
2471                           (sb!unix:unix-stat namestring)
2472                         (declare (ignore inode)
2473                                  (type (or index null) orig-mode))
2474                         (cond
2475                          (okay
2476                           (when (and output (= (logand orig-mode #o170000)
2477                                                #o40000))
2478                             (error 'simple-file-error
2479                                    :pathname namestring
2480                                    :format-control
2481                                    "can't open ~S for output: is a directory"
2482                                    :format-arguments (list namestring)))
2483                           (setf mode (logand orig-mode #o777))
2484                           t)
2485                          ((eql err/dev sb!unix:enoent)
2486                           nil)
2487                          (t
2488                           (simple-file-perror "can't find ~S"
2489                                               namestring
2490                                               err/dev)))))))
2491             (unless (and exists
2492                          (rename-the-old-one namestring original))
2493               (setf original nil)
2494               (setf delete-original nil)
2495               ;; In order to use :SUPERSEDE instead, we have to make
2496               ;; sure SB!UNIX:O_CREAT corresponds to
2497               ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2498               ;; because of IF-EXISTS being :RENAME.
2499               (unless (eq if-does-not-exist :create)
2500                 (setf mask
2501                       (logior (logandc2 mask sb!unix:o_creat)
2502                               sb!unix:o_trunc)))
2503               (setf if-exists :supersede))))
2504
2505         ;; Now we can try the actual Unix open(2).
2506         (multiple-value-bind (fd errno)
2507             (if namestring
2508                 (sb!unix:unix-open namestring mask mode)
2509                 (values nil sb!unix:enoent))
2510           (labels ((open-error (format-control &rest format-arguments)
2511                      (error 'simple-file-error
2512                             :pathname pathname
2513                             :format-control format-control
2514                             :format-arguments format-arguments))
2515                    (vanilla-open-error ()
2516                      (simple-file-perror "error opening ~S" pathname errno)))
2517             (cond ((numberp fd)
2518                    (case direction
2519                      ((:input :output :io)
2520                       (make-fd-stream fd
2521                                       :input input
2522                                       :output output
2523                                       :element-type element-type
2524                                       :external-format external-format
2525                                       :file namestring
2526                                       :original original
2527                                       :delete-original delete-original
2528                                       :pathname pathname
2529                                       :dual-channel-p nil
2530                                       :input-buffer-p t
2531                                       :auto-close t))
2532                      (:probe
2533                       (let ((stream
2534                              (%make-fd-stream :name namestring
2535                                               :fd fd
2536                                               :pathname pathname
2537                                               :element-type element-type)))
2538                         (close stream)
2539                         stream))))
2540                   ((eql errno sb!unix:enoent)
2541                    (case if-does-not-exist
2542                      (:error (vanilla-open-error))
2543                      (:create
2544                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2545                                   pathname))
2546                      (t nil)))
2547                   ((and (eql errno sb!unix:eexist) (null if-exists))
2548                    nil)
2549                   (t
2550                    (vanilla-open-error)))))))))
2551 \f
2552 ;;;; initialization
2553
2554 ;;; the stream connected to the controlling terminal, or NIL if there is none
2555 (defvar *tty*)
2556
2557 ;;; the stream connected to the standard input (file descriptor 0)
2558 (defvar *stdin*)
2559
2560 ;;; the stream connected to the standard output (file descriptor 1)
2561 (defvar *stdout*)
2562
2563 ;;; the stream connected to the standard error output (file descriptor 2)
2564 (defvar *stderr*)
2565
2566 ;;; This is called when the cold load is first started up, and may also
2567 ;;; be called in an attempt to recover from nested errors.
2568 (defun stream-cold-init-or-reset ()
2569   (stream-reinit)
2570   (setf *terminal-io* (make-synonym-stream '*tty*))
2571   (setf *standard-output* (make-synonym-stream '*stdout*))
2572   (setf *standard-input* (make-synonym-stream '*stdin*))
2573   (setf *error-output* (make-synonym-stream '*stderr*))
2574   (setf *query-io* (make-synonym-stream '*terminal-io*))
2575   (setf *debug-io* *query-io*)
2576   (setf *trace-output* *standard-output*)
2577   (values))
2578
2579 (defun stream-deinit ()
2580   ;; Unbind to make sure we're not accidently dealing with it
2581   ;; before we're ready (or after we think it's been deinitialized).
2582   (with-available-buffers-lock ()
2583     (without-package-locks
2584         (makunbound '*available-buffers*))))
2585
2586 ;;; This is called whenever a saved core is restarted.
2587 (defun stream-reinit (&optional init-buffers-p)
2588   (when init-buffers-p
2589     (with-available-buffers-lock ()
2590       (aver (not (boundp '*available-buffers*)))
2591       (setf *available-buffers* nil)))
2592   (with-output-to-string (*error-output*)
2593     (setf *stdin*
2594           (make-fd-stream 0 :name "standard input" :input t :buffering :line
2595                             #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2596     (setf *stdout*
2597           (make-fd-stream 1 :name "standard output" :output t :buffering :line
2598                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2599     (setf *stderr*
2600           (make-fd-stream 2 :name "standard error" :output t :buffering :line
2601                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2602     (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2603            (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2604       (if tty
2605           (setf *tty*
2606                 (make-fd-stream tty
2607                                 :name "the terminal"
2608                                 :input t
2609                                 :output t
2610                                 :buffering :line
2611                                 :auto-close t))
2612           (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2613     (princ (get-output-stream-string *error-output*) *stderr*))
2614   (values))
2615 \f
2616 ;;;; miscellany
2617
2618 ;;; the Unix way to beep
2619 (defun beep (stream)
2620   (write-char (code-char bell-char-code) stream)
2621   (finish-output stream))
2622
2623 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2624 ;;; by the filesys stuff to get and set the file name.
2625 ;;;
2626 ;;; FIXME: misleading name, screwy interface
2627 (defun file-name (stream &optional new-name)
2628   (when (typep stream 'fd-stream)
2629       (cond (new-name
2630              (setf (fd-stream-pathname stream) new-name)
2631              (setf (fd-stream-file stream)
2632                    (unix-namestring new-name nil))
2633              t)
2634             (t
2635              (fd-stream-pathname stream)))))