1.0.32.9: fix thinko in DEFINE-EXTERNAL-FORMAT/VARIABLE-WIDTH
[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 (defstruct (external-format
727              (:constructor %make-external-format)
728              (:conc-name ef-)
729              (:predicate external-format-p)
730              (:copier nil))
731   ;; All the names that can refer to this external format.  The first
732   ;; one is the canonical name.
733   (names (missing-arg) :type list :read-only t)
734   (read-n-chars-fun (missing-arg) :type function :read-only t)
735   (read-char-fun (missing-arg) :type function :read-only t)
736   (write-n-bytes-fun (missing-arg) :type function :read-only t)
737   (write-char-none-buffered-fun (missing-arg) :type function :read-only t)
738   (write-char-line-buffered-fun (missing-arg) :type function :read-only t)
739   (write-char-full-buffered-fun (missing-arg) :type function :read-only t)
740   ;; Can be nil for fixed-width formats.
741   (resync-fun nil :type (or function null) :read-only t)
742   (bytes-for-char-fun (missing-arg) :type function :read-only t)
743   (read-c-string-fun (missing-arg) :type function :read-only t)
744   (write-c-string-fun (missing-arg) :type function :read-only t)
745   ;; We make these symbols so that a developer working on the octets
746   ;; code can easily redefine things and use the new function definition
747   ;; without redefining the external format as well.  The slots above
748   ;; are functions because a developer working with those slots would be
749   ;; redefining the external format anyway.
750   (octets-to-string-sym (missing-arg) :type symbol :read-only t)
751   (string-to-octets-sym (missing-arg) :type symbol :read-only t))
752
753 (defvar *external-formats* (make-hash-table)
754   #!+sb-doc
755   "Hashtable of all available external formats. The table maps from
756   external-format names to EXTERNAL-FORMAT structures.")
757
758 (defun get-external-format (external-format)
759   (gethash external-format *external-formats*))
760
761 (defun get-external-format-or-lose (external-format)
762   (or (get-external-format external-format)
763       (error "Undefined external-format ~A" external-format)))
764
765 ;;; Find an output routine to use given the type and buffering. Return
766 ;;; as multiple values the routine, the real type transfered, and the
767 ;;; number of bytes per element.
768 (defun pick-output-routine (type buffering &optional external-format)
769   (when (subtypep type 'character)
770     (let ((entry (get-external-format external-format)))
771       (when entry
772         (return-from pick-output-routine
773           (values (ecase buffering
774                     (:none (ef-write-char-none-buffered-fun entry))
775                     (:line (ef-write-char-line-buffered-fun entry))
776                     (:full (ef-write-char-full-buffered-fun entry)))
777                   'character
778                   1
779                   (ef-write-n-bytes-fun entry)
780                   (first (ef-names entry)))))))
781   (dolist (entry *output-routines*)
782     (when (and (subtypep type (first entry))
783                (eq buffering (second entry))
784                (or (not (fifth entry))
785                    (eq external-format (fifth entry))))
786       (return-from pick-output-routine
787         (values (symbol-function (third entry))
788                 (first entry)
789                 (fourth entry)))))
790   ;; KLUDGE: dealing with the buffering here leads to excessive code
791   ;; explosion.
792   ;;
793   ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
794   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
795         if (subtypep type `(unsigned-byte ,i))
796         do (return-from pick-output-routine
797              (values
798               (ecase buffering
799                 (:none
800                  (lambda (stream byte)
801                    (output-wrapper (stream (/ i 8) (:none) nil)
802                      (loop for j from 0 below (/ i 8)
803                            do (setf (sap-ref-8 (buffer-sap obuf)
804                                                (+ j tail))
805                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
806                 (:full
807                  (lambda (stream byte)
808                    (output-wrapper (stream (/ i 8) (:full) nil)
809                      (loop for j from 0 below (/ i 8)
810                            do (setf (sap-ref-8 (buffer-sap obuf)
811                                                (+ j tail))
812                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
813               `(unsigned-byte ,i)
814               (/ i 8))))
815   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
816         if (subtypep type `(signed-byte ,i))
817         do (return-from pick-output-routine
818              (values
819               (ecase buffering
820                 (:none
821                  (lambda (stream byte)
822                    (output-wrapper (stream (/ i 8) (:none) nil)
823                      (loop for j from 0 below (/ i 8)
824                            do (setf (sap-ref-8 (buffer-sap obuf)
825                                                (+ j tail))
826                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
827                 (:full
828                  (lambda (stream byte)
829                    (output-wrapper (stream (/ i 8) (:full) nil)
830                      (loop for j from 0 below (/ i 8)
831                            do (setf (sap-ref-8 (buffer-sap obuf)
832                                                (+ j tail))
833                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
834               `(signed-byte ,i)
835               (/ i 8)))))
836 \f
837 ;;;; input routines and related noise
838
839 ;;; a list of all available input routines. Each element is a list of
840 ;;; the element-type input, the function name, and the number of bytes
841 ;;; per element.
842 (defvar *input-routines* ())
843
844 ;;; Return whether a primitive partial read operation on STREAM's FD
845 ;;; would (probably) block.  Signal a `simple-stream-error' if the
846 ;;; system call implementing this operation fails.
847 ;;;
848 ;;; It is "may" instead of "would" because "would" is not quite
849 ;;; correct on win32.  However, none of the places that use it require
850 ;;; further assurance than "may" versus "will definitely not".
851 (defun sysread-may-block-p (stream)
852   #!+win32
853   ;; This answers T at EOF on win32, I think.
854   (not (sb!win32:fd-listen (fd-stream-fd stream)))
855   #!-win32
856   (sb!unix:with-restarted-syscall (count errno)
857     (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
858       (sb!unix:fd-zero read-fds)
859       (sb!unix:fd-set (fd-stream-fd stream) read-fds)
860       (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
861                                 (sb!alien:addr read-fds)
862                                 nil nil 0 0))
863     (case count
864       ((1) nil)
865       ((0) t)
866       (otherwise
867        (simple-stream-perror "couldn't check whether ~S is readable"
868                              stream
869                              errno)))))
870
871 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
872 ;;; then fill the input buffer, and return the number of bytes read. Throws
873 ;;; to EOF-INPUT-CATCHER if the eof was reached.
874 (defun refill-input-buffer (stream)
875   (dx-let ((fd (fd-stream-fd stream))
876            (errno 0)
877            (count 0))
878     (tagbody
879        ;; Check for blocking input before touching the stream, as if
880        ;; we happen to wait we are liable to be interrupted, and the
881        ;; interrupt handler may use the same stream.
882        (if (sysread-may-block-p stream)
883            (go :wait-for-input)
884            (go :main))
885        ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
886        ;; we can signal errors outside the WITHOUT-INTERRUPTS.
887      :closed-flame
888        (closed-flame stream)
889      :read-error
890        (simple-stream-perror "couldn't read from ~S" stream errno)
891      :wait-for-input
892        ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
893        ;; to wait for input if read tells us EWOULDBLOCK.
894        (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
895          (signal-timeout 'io-timeout :stream stream :direction :read
896                          :seconds (fd-stream-timeout stream)))
897      :main
898        ;; Since the read should not block, we'll disable the
899        ;; interrupts here, so that we don't accidentally unwind and
900        ;; leave the stream in an inconsistent state.
901
902        ;; Execute the nlx outside without-interrupts to ensure the
903        ;; resulting thunk is stack-allocatable.
904        ((lambda (return-reason)
905           (ecase return-reason
906             ((nil))             ; fast path normal cases
907             ((:wait-for-input) (go :wait-for-input))
908             ((:closed-flame)   (go :closed-flame))
909             ((:read-error)     (go :read-error))))
910         (without-interrupts
911           ;; Check the buffer: if it is null, then someone has closed
912           ;; the stream from underneath us. This is not ment to fix
913           ;; multithreaded races, but to deal with interrupt handlers
914           ;; closing the stream.
915           (block nil
916             (prog1 nil
917               (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
918                      (sap (buffer-sap ibuf))
919                      (length (buffer-length ibuf))
920                      (head (buffer-head ibuf))
921                      (tail (buffer-tail ibuf)))
922                 (declare (index length head tail)
923                          (inline sb!unix:unix-read))
924                 (unless (zerop head)
925                   (cond ((eql head tail)
926                          ;; Buffer is empty, but not at yet reset -- make it so.
927                          (setf head 0
928                                tail 0)
929                          (reset-buffer ibuf))
930                         (t
931                          ;; Buffer has things in it, but they are not at the
932                          ;; head -- move them there.
933                          (let ((n (- tail head)))
934                            (system-area-ub8-copy sap head sap 0 n)
935                            (setf head 0
936                                  (buffer-head ibuf) head
937                                  tail n
938                                  (buffer-tail ibuf) tail)))))
939                 (setf (fd-stream-listen stream) nil)
940                 (setf (values count errno)
941                       (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
942                 (cond ((null count)
943                        #!+win32
944                        (return :read-error)
945                        #!-win32
946                        (if (eql errno sb!unix:ewouldblock)
947                            (return :wait-for-input)
948                            (return :read-error)))
949                       ((zerop count)
950                        (setf (fd-stream-listen stream) :eof)
951                        (/show0 "THROWing EOF-INPUT-CATCHER")
952                        (throw 'eof-input-catcher nil))
953                       (t
954                        ;; Success! (Do not use INCF, for sake of other threads.)
955                        (setf (buffer-tail ibuf) (+ count tail))))))))))
956     count))
957
958 ;;; Make sure there are at least BYTES number of bytes in the input
959 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
960 (defmacro input-at-least (stream bytes)
961   (let ((stream-var (gensym "STREAM"))
962         (bytes-var (gensym "BYTES"))
963         (buffer-var (gensym "IBUF")))
964     `(let* ((,stream-var ,stream)
965             (,bytes-var ,bytes)
966             (,buffer-var (fd-stream-ibuf ,stream-var)))
967        (loop
968          (when (>= (- (buffer-tail ,buffer-var)
969                       (buffer-head ,buffer-var))
970                    ,bytes-var)
971            (return))
972          (refill-input-buffer ,stream-var)))))
973
974 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
975                                         &body read-forms)
976   (let ((stream-var (gensym "STREAM"))
977         (retry-var (gensym "RETRY"))
978         (element-var (gensym "ELT")))
979     `(let* ((,stream-var ,stream)
980             (ibuf (fd-stream-ibuf ,stream-var))
981             (size nil))
982        (if (fd-stream-unread ,stream-var)
983            (prog1
984                (fd-stream-unread ,stream-var)
985              (setf (fd-stream-unread ,stream-var) nil)
986              (setf (fd-stream-listen ,stream-var) nil))
987            (let ((,element-var nil)
988                  (decode-break-reason nil))
989              (do ((,retry-var t))
990                  ((not ,retry-var))
991                (unless
992                    (catch 'eof-input-catcher
993                      (setf decode-break-reason
994                            (block decode-break-reason
995                              (input-at-least ,stream-var 1)
996                              (let* ((byte (sap-ref-8 (buffer-sap ibuf)
997                                                      (buffer-head ibuf))))
998                                (declare (ignorable byte))
999                                (setq size ,bytes)
1000                                (input-at-least ,stream-var size)
1001                                (setq ,element-var (locally ,@read-forms))
1002                                (setq ,retry-var nil))
1003                              nil))
1004                      (when decode-break-reason
1005                        (stream-decoding-error-and-handle stream
1006                                                          decode-break-reason))
1007                      t)
1008                  (let ((octet-count (- (buffer-tail ibuf)
1009                                        (buffer-head ibuf))))
1010                    (when (or (zerop octet-count)
1011                              (and (not ,element-var)
1012                                   (not decode-break-reason)
1013                                   (stream-decoding-error-and-handle
1014                                    stream octet-count)))
1015                      (setq ,retry-var nil)))))
1016              (cond (,element-var
1017                     (incf (buffer-head ibuf) size)
1018                     ,element-var)
1019                    (t
1020                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1021
1022 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1023 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1024   (let ((stream-var (gensym "STREAM"))
1025         (element-var (gensym "ELT")))
1026     `(let* ((,stream-var ,stream)
1027             (ibuf (fd-stream-ibuf ,stream-var)))
1028        (if (fd-stream-unread ,stream-var)
1029            (prog1
1030                (fd-stream-unread ,stream-var)
1031              (setf (fd-stream-unread ,stream-var) nil)
1032              (setf (fd-stream-listen ,stream-var) nil))
1033            (let ((,element-var
1034                   (catch 'eof-input-catcher
1035                     (input-at-least ,stream-var ,bytes)
1036                     (locally ,@read-forms))))
1037              (cond (,element-var
1038                     (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1039                     ,element-var)
1040                    (t
1041                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1042
1043 (defmacro def-input-routine/variable-width (name
1044                                             (type external-format size sap head)
1045                                             &rest body)
1046   `(progn
1047      (defun ,name (stream eof-error eof-value)
1048        (input-wrapper/variable-width (stream ,size eof-error eof-value)
1049          (let ((,sap (buffer-sap ibuf))
1050                (,head (buffer-head ibuf)))
1051            ,@body)))
1052      (setf *input-routines*
1053            (nconc *input-routines*
1054                   (list (list ',type ',name 1 ',external-format))))))
1055
1056 (defmacro def-input-routine (name
1057                              (type size sap head)
1058                              &rest body)
1059   `(progn
1060      (defun ,name (stream eof-error eof-value)
1061        (input-wrapper (stream ,size eof-error eof-value)
1062          (let ((,sap (buffer-sap ibuf))
1063                (,head (buffer-head ibuf)))
1064            ,@body)))
1065      (setf *input-routines*
1066            (nconc *input-routines*
1067                   (list (list ',type ',name ',size nil))))))
1068
1069 ;;; STREAM-IN routine for reading a string char
1070 (def-input-routine input-character
1071                    (character 1 sap head)
1072   (code-char (sap-ref-8 sap head)))
1073
1074 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1075 (def-input-routine input-unsigned-8bit-byte
1076                    ((unsigned-byte 8) 1 sap head)
1077   (sap-ref-8 sap head))
1078
1079 ;;; STREAM-IN routine for reading a signed 8 bit number
1080 (def-input-routine input-signed-8bit-number
1081                    ((signed-byte 8) 1 sap head)
1082   (signed-sap-ref-8 sap head))
1083
1084 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1085 (def-input-routine input-unsigned-16bit-byte
1086                    ((unsigned-byte 16) 2 sap head)
1087   (sap-ref-16 sap head))
1088
1089 ;;; STREAM-IN routine for reading a signed 16 bit number
1090 (def-input-routine input-signed-16bit-byte
1091                    ((signed-byte 16) 2 sap head)
1092   (signed-sap-ref-16 sap head))
1093
1094 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1095 (def-input-routine input-unsigned-32bit-byte
1096                    ((unsigned-byte 32) 4 sap head)
1097   (sap-ref-32 sap head))
1098
1099 ;;; STREAM-IN routine for reading a signed 32 bit number
1100 (def-input-routine input-signed-32bit-byte
1101                    ((signed-byte 32) 4 sap head)
1102   (signed-sap-ref-32 sap head))
1103
1104 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1105 (progn
1106   (def-input-routine input-unsigned-64bit-byte
1107       ((unsigned-byte 64) 8 sap head)
1108     (sap-ref-64 sap head))
1109   (def-input-routine input-signed-64bit-byte
1110       ((signed-byte 64) 8 sap head)
1111     (signed-sap-ref-64 sap head)))
1112
1113 ;;; Find an input routine to use given the type. Return as multiple
1114 ;;; values the routine, the real type transfered, and the number of
1115 ;;; bytes per element (and for character types string input routine).
1116 (defun pick-input-routine (type &optional external-format)
1117   (when (subtypep type 'character)
1118     (let ((entry (get-external-format external-format)))
1119       (when entry
1120         (return-from pick-input-routine
1121           (values (ef-read-char-fun entry)
1122                   'character
1123                   1
1124                   (ef-read-n-chars-fun entry)
1125                   (first (ef-names entry)))))))
1126   (dolist (entry *input-routines*)
1127     (when (and (subtypep type (first entry))
1128                (or (not (fourth entry))
1129                    (eq external-format (fourth entry))))
1130       (return-from pick-input-routine
1131         (values (symbol-function (second entry))
1132                 (first entry)
1133                 (third entry)))))
1134   ;; FIXME: let's do it the hard way, then (but ignore things like
1135   ;; endianness, efficiency, and the necessary coupling between these
1136   ;; and the output routines).  -- CSR, 2004-02-09
1137   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1138         if (subtypep type `(unsigned-byte ,i))
1139         do (return-from pick-input-routine
1140              (values
1141               (lambda (stream eof-error eof-value)
1142                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1143                   (let ((sap (buffer-sap ibuf))
1144                         (head (buffer-head ibuf)))
1145                     (loop for j from 0 below (/ i 8)
1146                           with result = 0
1147                           do (setf result
1148                                    (+ (* 256 result)
1149                                       (sap-ref-8 sap (+ head j))))
1150                           finally (return result)))))
1151               `(unsigned-byte ,i)
1152               (/ i 8))))
1153   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1154         if (subtypep type `(signed-byte ,i))
1155         do (return-from pick-input-routine
1156              (values
1157               (lambda (stream eof-error eof-value)
1158                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1159                   (let ((sap (buffer-sap ibuf))
1160                         (head (buffer-head ibuf)))
1161                     (loop for j from 0 below (/ i 8)
1162                           with result = 0
1163                           do (setf result
1164                                    (+ (* 256 result)
1165                                       (sap-ref-8 sap (+ head j))))
1166                           finally (return (if (logbitp (1- i) result)
1167                                               (dpb result (byte i 0) -1)
1168                                               result))))))
1169               `(signed-byte ,i)
1170               (/ i 8)))))
1171
1172 ;;; the N-BIN method for FD-STREAMs
1173 ;;;
1174 ;;; Note that this blocks in UNIX-READ. It is generally used where
1175 ;;; there is a definite amount of reading to be done, so blocking
1176 ;;; isn't too problematical.
1177 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1178                                &aux (total-copied 0))
1179   (declare (type fd-stream stream))
1180   (declare (type index start requested total-copied))
1181   (let ((unread (fd-stream-unread stream)))
1182     (when unread
1183       ;; AVERs designed to fail when we have more complicated
1184       ;; character representations.
1185       (aver (typep unread 'base-char))
1186       (aver (= (fd-stream-element-size stream) 1))
1187       ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1188       ;; %BYTE-BLT
1189       (etypecase buffer
1190         (system-area-pointer
1191          (setf (sap-ref-8 buffer start) (char-code unread)))
1192         ((simple-unboxed-array (*))
1193          (setf (aref buffer start) unread)))
1194       (setf (fd-stream-unread stream) nil)
1195       (setf (fd-stream-listen stream) nil)
1196       (incf total-copied)))
1197   (do ()
1198       (nil)
1199     (let* ((remaining-request (- requested total-copied))
1200            (ibuf (fd-stream-ibuf stream))
1201            (head (buffer-head ibuf))
1202            (tail (buffer-tail ibuf))
1203            (available (- tail head))
1204            (n-this-copy (min remaining-request available))
1205            (this-start (+ start total-copied))
1206            (this-end (+ this-start n-this-copy))
1207            (sap (buffer-sap ibuf)))
1208       (declare (type index remaining-request head tail available))
1209       (declare (type index n-this-copy))
1210       ;; Copy data from stream buffer into user's buffer.
1211       (%byte-blt sap head buffer this-start this-end)
1212       (incf (buffer-head ibuf) n-this-copy)
1213       (incf total-copied n-this-copy)
1214       ;; Maybe we need to refill the stream buffer.
1215       (cond (;; If there were enough data in the stream buffer, we're done.
1216              (eql total-copied requested)
1217              (return total-copied))
1218             (;; If EOF, we're done in another way.
1219              (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1220              (if eof-error-p
1221                  (error 'end-of-file :stream stream)
1222                  (return total-copied)))
1223             ;; Otherwise we refilled the stream buffer, so fall
1224             ;; through into another pass of the loop.
1225             ))))
1226
1227 (defun fd-stream-resync (stream)
1228   (let ((entry (get-external-format (fd-stream-external-format stream))))
1229     (when entry
1230       (funcall (ef-resync-fun entry) stream))))
1231
1232 (defun get-fd-stream-character-sizer (stream)
1233   (let ((entry (get-external-format (fd-stream-external-format stream))))
1234     (when entry
1235       (ef-bytes-for-char-fun entry))))
1236
1237 (defun fd-stream-character-size (stream char)
1238   (let ((sizer (get-fd-stream-character-sizer stream)))
1239     (when sizer (funcall sizer char))))
1240
1241 (defun fd-stream-string-size (stream string)
1242   (let ((sizer (get-fd-stream-character-sizer stream)))
1243     (when sizer
1244       (loop for char across string summing (funcall sizer char)))))
1245
1246 (defun find-external-format (external-format)
1247   (when external-format
1248     (get-external-format external-format)))
1249
1250 (defun variable-width-external-format-p (ef-entry)
1251   (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1252
1253 (defun bytes-for-char-fun (ef-entry)
1254   (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1255
1256 (defmacro define-external-format (external-format size output-restart
1257                                   out-expr in-expr
1258                                   octets-to-string-sym
1259                                   string-to-octets-sym)
1260   (let* ((name (first external-format))
1261          (out-function (symbolicate "OUTPUT-BYTES/" name))
1262          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1263          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1264          (in-char-function (symbolicate "INPUT-CHAR/" name))
1265          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1266          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1267          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1268          (n-buffer (gensym "BUFFER")))
1269     `(progn
1270       (defun ,size-function (byte)
1271         (declare (ignore byte))
1272         ,size)
1273       (defun ,out-function (stream string flush-p start end)
1274         (let ((start (or start 0))
1275               (end (or end (length string))))
1276           (declare (type index start end))
1277           (synchronize-stream-output stream)
1278           (unless (<= 0 start end (length string))
1279             (sequence-bounding-indices-bad-error string start end))
1280           (do ()
1281               ((= end start))
1282             (let ((obuf (fd-stream-obuf stream)))
1283               (setf (buffer-tail obuf)
1284                     (string-dispatch (simple-base-string
1285                                       #!+sb-unicode
1286                                       (simple-array character (*))
1287                                       string)
1288                         string
1289                       (let ((sap (buffer-sap obuf))
1290                             (len (buffer-length obuf))
1291                             ;; FIXME: rename
1292                             (tail (buffer-tail obuf)))
1293                        (declare (type index tail)
1294                                 ;; STRING bounds have already been checked.
1295                                 (optimize (safety 0)))
1296                        (loop
1297                          (,@(if output-restart
1298                                 `(catch 'output-nothing)
1299                                 `(progn))
1300                             (do* ()
1301                                  ((or (= start end) (< (- len tail) 4)))
1302                               (let* ((byte (aref string start))
1303                                      (bits (char-code byte)))
1304                                 ,out-expr
1305                                 (incf tail ,size)
1306                                 (incf start)))
1307                             ;; Exited from the loop normally
1308                             (return tail))
1309                          ;; Exited via CATCH. Skip the current character
1310                          ;; and try the inner loop again.
1311                          (incf start))))))
1312             (when (< start end)
1313               (flush-output-buffer stream)))
1314           (when flush-p
1315             (flush-output-buffer stream))))
1316       (def-output-routines (,format
1317                             ,size
1318                             ,output-restart
1319                             (:none character)
1320                             (:line character)
1321                             (:full character))
1322           (if (eql byte #\Newline)
1323               (setf (fd-stream-char-pos stream) 0)
1324               (incf (fd-stream-char-pos stream)))
1325           (let* ((obuf (fd-stream-obuf stream))
1326                  (bits (char-code byte))
1327                  (sap (buffer-sap obuf))
1328                  (tail (buffer-tail obuf)))
1329             ,out-expr))
1330       (defun ,in-function (stream buffer start requested eof-error-p
1331                            &aux (index start) (end (+ start requested)))
1332         (declare (type fd-stream stream)
1333                  (type index start requested index end)
1334                  (type
1335                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1336                   buffer))
1337         (let ((unread (fd-stream-unread stream)))
1338           (when unread
1339             (setf (aref buffer index) unread)
1340             (setf (fd-stream-unread stream) nil)
1341             (setf (fd-stream-listen stream) nil)
1342             (incf index)))
1343         (do ()
1344             (nil)
1345           (let* ((ibuf (fd-stream-ibuf stream))
1346                  (head (buffer-head ibuf))
1347                  (tail (buffer-tail ibuf))
1348                  (sap (buffer-sap ibuf)))
1349             (declare (type index head tail)
1350                      (type system-area-pointer sap))
1351             ;; Copy data from stream buffer into user's buffer.
1352             (dotimes (i (min (truncate (- tail head) ,size)
1353                              (- end index)))
1354               (declare (optimize speed))
1355               (let* ((byte (sap-ref-8 sap head)))
1356                 (setf (aref buffer index) ,in-expr)
1357                 (incf index)
1358                 (incf head ,size)))
1359             (setf (buffer-head ibuf) head)
1360             ;; Maybe we need to refill the stream buffer.
1361             (cond ( ;; If there was enough data in the stream buffer, we're done.
1362                    (= index end)
1363                    (return (- index start)))
1364                   ( ;; If EOF, we're done in another way.
1365                    (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1366                    (if eof-error-p
1367                        (error 'end-of-file :stream stream)
1368                        (return (- index start))))
1369                   ;; Otherwise we refilled the stream buffer, so fall
1370                   ;; through into another pass of the loop.
1371                   ))))
1372       (def-input-routine ,in-char-function (character ,size sap head)
1373         (let ((byte (sap-ref-8 sap head)))
1374           ,in-expr))
1375       (defun ,read-c-string-function (sap element-type)
1376         (declare (type system-area-pointer sap)
1377                  (type (member character base-char) element-type))
1378         (locally
1379             (declare (optimize (speed 3) (safety 0)))
1380           (let* ((stream ,name)
1381                  (length
1382                   (loop for head of-type index upfrom 0 by ,size
1383                         for count of-type index upto (1- array-dimension-limit)
1384                         for byte = (sap-ref-8 sap head)
1385                         for char of-type character = ,in-expr
1386                         until (zerop (char-code char))
1387                         finally (return count)))
1388                  ;; Inline the common cases
1389                  (string (make-string length :element-type element-type)))
1390             (declare (ignorable stream)
1391                      (type index length)
1392                      (type simple-string string))
1393             (/show0 before-copy-loop)
1394             (loop for head of-type index upfrom 0 by ,size
1395                for index of-type index below length
1396                for byte = (sap-ref-8 sap head)
1397                for char of-type character = ,in-expr
1398                do (setf (aref string index) char))
1399             string))) ;; last loop rewrite to dotimes?
1400         (defun ,output-c-string-function (string)
1401           (declare (type simple-string string))
1402           (locally
1403               (declare (optimize (speed 3) (safety 0)))
1404             (let* ((length (length string))
1405                    (,n-buffer (make-array (* (1+ length) ,size)
1406                                           :element-type '(unsigned-byte 8)))
1407                    (tail 0)
1408                    (stream ,name))
1409               (declare (type index length tail))
1410               (with-pinned-objects (,n-buffer)
1411                 (let ((sap (vector-sap ,n-buffer)))
1412                   (declare (system-area-pointer sap))
1413                   (dotimes (i length)
1414                     (let* ((byte (aref string i))
1415                            (bits (char-code byte)))
1416                       (declare (ignorable byte bits))
1417                       ,out-expr)
1418                     (incf tail ,size))
1419                   (let* ((bits 0)
1420                          (byte (code-char bits)))
1421                     (declare (ignorable bits byte))
1422                     ,out-expr)))
1423               ,n-buffer)))
1424         (let ((entry (%make-external-format
1425                       :names ',external-format
1426                       :read-n-chars-fun #',in-function
1427                       :read-char-fun #',in-char-function
1428                       :write-n-bytes-fun #',out-function
1429                       ,@(mapcan #'(lambda (buffering)
1430                                     (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1431                                           `#',(intern (format nil format (string buffering)))))
1432                                 '(:none :line :full))
1433                       :resync-fun nil
1434                       :bytes-for-char-fun #',size-function
1435                       :read-c-string-fun #',read-c-string-function
1436                       :write-c-string-fun #',output-c-string-function
1437                       :octets-to-string-sym ',octets-to-string-sym
1438                       :string-to-octets-sym ',string-to-octets-sym)))
1439           (dolist (ef ',external-format)
1440             (setf (gethash ef *external-formats*) entry))))))
1441
1442 (defmacro define-external-format/variable-width
1443     (external-format output-restart out-size-expr
1444      out-expr in-size-expr in-expr
1445      octets-to-string-sym string-to-octets-sym)
1446   (let* ((name (first external-format))
1447          (out-function (symbolicate "OUTPUT-BYTES/" name))
1448          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1449          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1450          (in-char-function (symbolicate "INPUT-CHAR/" name))
1451          (resync-function (symbolicate "RESYNC/" name))
1452          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1453          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1454          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1455          (n-buffer (gensym "BUFFER")))
1456     `(progn
1457       (defun ,size-function (byte)
1458         (declare (ignorable byte))
1459         ,out-size-expr)
1460       (defun ,out-function (stream string flush-p start end)
1461         (let ((start (or start 0))
1462               (end (or end (length string))))
1463           (declare (type index start end))
1464           (synchronize-stream-output stream)
1465           (unless (<= 0 start end (length string))
1466             (sequence-bounding-indices-bad-error string start end))
1467           (do ()
1468               ((= end start))
1469             (let ((obuf (fd-stream-obuf stream)))
1470               (setf (buffer-tail obuf)
1471                     (string-dispatch (simple-base-string
1472                                       #!+sb-unicode
1473                                       (simple-array character (*))
1474                                       string)
1475                         string
1476                       (let ((len (buffer-length obuf))
1477                             (sap (buffer-sap obuf))
1478                             ;; FIXME: Rename
1479                             (tail (buffer-tail obuf)))
1480                         (declare (type index tail)
1481                                  ;; STRING bounds have already been checked.
1482                                  (optimize (safety 0)))
1483                         (loop
1484                           (,@(if output-restart
1485                                  `(catch 'output-nothing)
1486                                  `(progn))
1487                              (do* ()
1488                                   ((or (= start end) (< (- len tail) 4)))
1489                                (let* ((byte (aref string start))
1490                                       (bits (char-code byte))
1491                                       (size ,out-size-expr))
1492                                  ,out-expr
1493                                  (incf tail size)
1494                                  (incf start)))
1495                              ;; Exited from the loop normally
1496                              (return tail))
1497                           ;; Exited via CATCH. Skip the current character
1498                           ;; and try the inner loop again.
1499                           (incf start))))))
1500             (when (< start end)
1501               (flush-output-buffer stream)))
1502           (when flush-p
1503             (flush-output-buffer stream))))
1504       (def-output-routines/variable-width (,format
1505                                            ,out-size-expr
1506                                            ,output-restart
1507                                            ,external-format
1508                                            (:none character)
1509                                            (:line character)
1510                                            (:full character))
1511           (if (eql byte #\Newline)
1512               (setf (fd-stream-char-pos stream) 0)
1513               (incf (fd-stream-char-pos stream)))
1514         (let ((bits (char-code byte))
1515               (sap (buffer-sap obuf))
1516               (tail (buffer-tail obuf)))
1517           ,out-expr))
1518       (defun ,in-function (stream buffer start requested eof-error-p
1519                            &aux (total-copied 0))
1520         (declare (type fd-stream stream)
1521                  (type index start requested total-copied)
1522                  (type
1523                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1524                   buffer))
1525         (let ((unread (fd-stream-unread stream)))
1526           (when unread
1527             (setf (aref buffer start) unread)
1528             (setf (fd-stream-unread stream) nil)
1529             (setf (fd-stream-listen stream) nil)
1530             (incf total-copied)))
1531         (do ()
1532             (nil)
1533           (let* ((ibuf (fd-stream-ibuf stream))
1534                  (head (buffer-head ibuf))
1535                  (tail (buffer-tail ibuf))
1536                  (sap (buffer-sap ibuf))
1537                  (decode-break-reason nil))
1538             (declare (type index head tail))
1539             ;; Copy data from stream buffer into user's buffer.
1540             (do ((size nil nil))
1541                 ((or (= tail head) (= requested total-copied)))
1542               (setf decode-break-reason
1543                     (block decode-break-reason
1544                       (let ((byte (sap-ref-8 sap head)))
1545                         (declare (ignorable byte))
1546                         (setq size ,in-size-expr)
1547                         (when (> size (- tail head))
1548                           (return))
1549                         (setf (aref buffer (+ start total-copied)) ,in-expr)
1550                         (incf total-copied)
1551                         (incf head size))
1552                       nil))
1553               (setf (buffer-head ibuf) head)
1554               (when decode-break-reason
1555                 ;; If we've already read some characters on when the invalid
1556                 ;; code sequence is detected, we return immediately. The
1557                 ;; handling of the error is deferred until the next call
1558                 ;; (where this check will be false). This allows establishing
1559                 ;; high-level handlers for decode errors (for example
1560                 ;; automatically resyncing in Lisp comments).
1561                 (when (plusp total-copied)
1562                   (return-from ,in-function total-copied))
1563                 (when (stream-decoding-error-and-handle
1564                        stream decode-break-reason)
1565                   (if eof-error-p
1566                       (error 'end-of-file :stream stream)
1567                       (return-from ,in-function total-copied)))
1568                 (setf head (buffer-head ibuf))
1569                 (setf tail (buffer-tail ibuf))))
1570             (setf (buffer-head ibuf) head)
1571             ;; Maybe we need to refill the stream buffer.
1572             (cond ( ;; If there were enough data in the stream buffer, we're done.
1573                    (= total-copied requested)
1574                    (return total-copied))
1575                   ( ;; If EOF, we're done in another way.
1576                    (or (eq decode-break-reason 'eof)
1577                        (null (catch 'eof-input-catcher
1578                                (refill-input-buffer stream))))
1579                    (if eof-error-p
1580                        (error 'end-of-file :stream stream)
1581                        (return total-copied)))
1582                   ;; Otherwise we refilled the stream buffer, so fall
1583                   ;; through into another pass of the loop.
1584                   ))))
1585       (def-input-routine/variable-width ,in-char-function (character
1586                                                            ,external-format
1587                                                            ,in-size-expr
1588                                                            sap head)
1589         (let ((byte (sap-ref-8 sap head)))
1590           (declare (ignorable byte))
1591           ,in-expr))
1592       (defun ,resync-function (stream)
1593         (let ((ibuf (fd-stream-ibuf stream)))
1594           (loop
1595             (input-at-least stream 2)
1596             (incf (buffer-head ibuf))
1597             (unless (block decode-break-reason
1598                       (let* ((sap (buffer-sap ibuf))
1599                              (head (buffer-head ibuf))
1600                              (byte (sap-ref-8 sap head))
1601                              (size ,in-size-expr))
1602                         (declare (ignorable byte))
1603                         (input-at-least stream size)
1604                         (setf head (buffer-head ibuf))
1605                         ,in-expr)
1606                      nil)
1607              (return)))))
1608       (defun ,read-c-string-function (sap element-type)
1609         (declare (type system-area-pointer sap))
1610         (locally
1611             (declare (optimize (speed 3) (safety 0)))
1612           (let* ((stream ,name)
1613                  (size 0) (head 0) (byte 0) (char nil)
1614                  (decode-break-reason nil)
1615                  (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1616                            (setf decode-break-reason
1617                                  (block decode-break-reason
1618                                    (setf byte (sap-ref-8 sap head)
1619                                          size ,in-size-expr
1620                                          char ,in-expr)
1621                                    (incf head size)
1622                                    nil))
1623                            (when decode-break-reason
1624                              (c-string-decoding-error ,name decode-break-reason))
1625                            (when (zerop (char-code char))
1626                              (return count))))
1627                  (string (make-string length :element-type element-type)))
1628             (declare (ignorable stream)
1629                      (type index head length) ;; size
1630                      (type (unsigned-byte 8) byte)
1631                      (type (or null character) char)
1632                      (type string string))
1633             (setf head 0)
1634             (dotimes (index length string)
1635               (setf decode-break-reason
1636                     (block decode-break-reason
1637                       (setf byte (sap-ref-8 sap head)
1638                             size ,in-size-expr
1639                             char ,in-expr)
1640                       (incf head size)
1641                       nil))
1642               (when decode-break-reason
1643                 (c-string-decoding-error ,name decode-break-reason))
1644               (setf (aref string index) char)))))
1645
1646       (defun ,output-c-string-function (string)
1647         (declare (type simple-string string))
1648         (locally
1649             (declare (optimize (speed 3) (safety 0)))
1650           (let* ((length (length string))
1651                  (char-length (make-array (1+ length) :element-type 'index))
1652                  (buffer-length
1653                   (+ (loop for i of-type index below length
1654                         for byte of-type character = (aref string i)
1655                         for bits = (char-code byte)
1656                         sum (setf (aref char-length i)
1657                                   (the index ,out-size-expr)))
1658                      (let* ((byte (code-char 0))
1659                             (bits (char-code byte)))
1660                        (declare (ignorable byte bits))
1661                        (setf (aref char-length length)
1662                              (the index ,out-size-expr)))))
1663                  (tail 0)
1664                  (,n-buffer (make-array buffer-length
1665                                         :element-type '(unsigned-byte 8)))
1666                  stream)
1667             (declare (type index length buffer-length tail)
1668                      (type null stream)
1669                      (ignorable stream))
1670             (with-pinned-objects (,n-buffer)
1671               (let ((sap (vector-sap ,n-buffer)))
1672                 (declare (system-area-pointer sap))
1673                 (loop for i of-type index below length
1674                       for byte of-type character = (aref string i)
1675                       for bits = (char-code byte)
1676                       for size of-type index = (aref char-length i)
1677                       do (prog1
1678                              ,out-expr
1679                            (incf tail size)))
1680                 (let* ((bits 0)
1681                        (byte (code-char bits))
1682                        (size (aref char-length length)))
1683                   (declare (ignorable bits byte size))
1684                   ,out-expr)))
1685             ,n-buffer)))
1686
1687       (let ((entry (%make-external-format
1688                     :names ',external-format
1689                     :read-n-chars-fun #',in-function
1690                     :read-char-fun #',in-char-function
1691                     :write-n-bytes-fun #',out-function
1692                     ,@(mapcan #'(lambda (buffering)
1693                                   (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1694                                         `#',(intern (format nil format (string buffering)))))
1695                               '(:none :line :full))
1696                     :resync-fun #',resync-function
1697                     :bytes-for-char-fun #',size-function
1698                     :read-c-string-fun #',read-c-string-function
1699                     :write-c-string-fun #',output-c-string-function
1700                     :octets-to-string-sym ',octets-to-string-sym
1701                     :string-to-octets-sym ',string-to-octets-sym)))
1702         (dolist (ef ',external-format)
1703           (setf (gethash ef *external-formats*) entry))))))
1704 \f
1705 ;;;; utility functions (misc routines, etc)
1706
1707 ;;; Fill in the various routine slots for the given type. INPUT-P and
1708 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1709 ;;; set prior to calling this routine.
1710 (defun set-fd-stream-routines (fd-stream element-type external-format
1711                                input-p output-p buffer-p)
1712   (let* ((target-type (case element-type
1713                         (unsigned-byte '(unsigned-byte 8))
1714                         (signed-byte '(signed-byte 8))
1715                         (:default 'character)
1716                         (t element-type)))
1717          (character-stream-p (subtypep target-type 'character))
1718          (bivalent-stream-p (eq element-type :default))
1719          normalized-external-format
1720          (bin-routine #'ill-bin)
1721          (bin-type nil)
1722          (bin-size nil)
1723          (cin-routine #'ill-in)
1724          (cin-type nil)
1725          (cin-size nil)
1726          (input-type nil)           ;calculated from bin-type/cin-type
1727          (input-size nil)           ;calculated from bin-size/cin-size
1728          (read-n-characters #'ill-in)
1729          (bout-routine #'ill-bout)
1730          (bout-type nil)
1731          (bout-size nil)
1732          (cout-routine #'ill-out)
1733          (cout-type nil)
1734          (cout-size nil)
1735          (output-type nil)
1736          (output-size nil)
1737          (output-bytes #'ill-bout))
1738
1739     ;; Ensure that we have buffers in the desired direction(s) only,
1740     ;; getting new ones and dropping/resetting old ones as necessary.
1741     (let ((obuf (fd-stream-obuf fd-stream)))
1742       (if output-p
1743           (if obuf
1744               (reset-buffer obuf)
1745               (setf (fd-stream-obuf fd-stream) (get-buffer)))
1746           (when obuf
1747             (setf (fd-stream-obuf fd-stream) nil)
1748             (release-buffer obuf))))
1749
1750     (let ((ibuf (fd-stream-ibuf fd-stream)))
1751       (if input-p
1752           (if ibuf
1753               (reset-buffer ibuf)
1754               (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1755           (when ibuf
1756             (setf (fd-stream-ibuf fd-stream) nil)
1757             (release-buffer ibuf))))
1758
1759     ;; FIXME: Why only for output? Why unconditionally?
1760     (when output-p
1761       (setf (fd-stream-char-pos fd-stream) 0))
1762
1763     (when (and character-stream-p
1764                (eq external-format :default))
1765       (/show0 "/getting default external format")
1766       (setf external-format (default-external-format)))
1767
1768     (when input-p
1769       (when (or (not character-stream-p) bivalent-stream-p)
1770         (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1771                                           normalized-external-format)
1772           (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1773                                   target-type)
1774                               external-format))
1775         (unless bin-routine
1776           (error "could not find any input routine for ~S" target-type)))
1777       (when character-stream-p
1778         (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1779                                           normalized-external-format)
1780           (pick-input-routine target-type external-format))
1781         (unless cin-routine
1782           (error "could not find any input routine for ~S" target-type)))
1783       (setf (fd-stream-in fd-stream) cin-routine
1784             (fd-stream-bin fd-stream) bin-routine)
1785       ;; character type gets preferential treatment
1786       (setf input-size (or cin-size bin-size))
1787       (setf input-type (or cin-type bin-type))
1788       (when normalized-external-format
1789         (setf (fd-stream-external-format fd-stream)
1790               normalized-external-format))
1791       (when (= (or cin-size 1) (or bin-size 1) 1)
1792         (setf (fd-stream-n-bin fd-stream) ;XXX
1793               (if (and character-stream-p (not bivalent-stream-p))
1794                   read-n-characters
1795                   #'fd-stream-read-n-bytes))
1796         ;; Sometimes turn on fast-read-char/fast-read-byte.  Switch on
1797         ;; for character and (unsigned-byte 8) streams.  In these
1798         ;; cases, fast-read-* will read from the
1799         ;; ansi-stream-(c)in-buffer, saving function calls.
1800         ;; Otherwise, the various data-reading functions in the stream
1801         ;; structure will be called.
1802         (when (and buffer-p
1803                    (not bivalent-stream-p)
1804                    ;; temporary disable on :io streams
1805                    (not output-p))
1806           (cond (character-stream-p
1807                  (setf (ansi-stream-cin-buffer fd-stream)
1808                        (make-array +ansi-stream-in-buffer-length+
1809                                    :element-type 'character)))
1810                 ((equal target-type '(unsigned-byte 8))
1811                  (setf (ansi-stream-in-buffer fd-stream)
1812                        (make-array +ansi-stream-in-buffer-length+
1813                                    :element-type '(unsigned-byte 8))))))))
1814
1815     (when output-p
1816       (when (or (not character-stream-p) bivalent-stream-p)
1817         (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1818                                            normalized-external-format)
1819           (pick-output-routine (if bivalent-stream-p
1820                                    '(unsigned-byte 8)
1821                                    target-type)
1822                                (fd-stream-buffering fd-stream)
1823                                external-format))
1824         (unless bout-routine
1825           (error "could not find any output routine for ~S buffered ~S"
1826                  (fd-stream-buffering fd-stream)
1827                  target-type)))
1828       (when character-stream-p
1829         (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1830                                            normalized-external-format)
1831           (pick-output-routine target-type
1832                                (fd-stream-buffering fd-stream)
1833                                external-format))
1834         (unless cout-routine
1835           (error "could not find any output routine for ~S buffered ~S"
1836                  (fd-stream-buffering fd-stream)
1837                  target-type)))
1838       (when normalized-external-format
1839         (setf (fd-stream-external-format fd-stream)
1840               normalized-external-format))
1841       (when character-stream-p
1842         (setf (fd-stream-output-bytes fd-stream) output-bytes))
1843       (setf (fd-stream-out fd-stream) cout-routine
1844             (fd-stream-bout fd-stream) bout-routine
1845             (fd-stream-sout fd-stream) (if (eql cout-size 1)
1846                                            #'fd-sout #'ill-out))
1847       (setf output-size (or cout-size bout-size))
1848       (setf output-type (or cout-type bout-type)))
1849
1850     (when (and input-size output-size
1851                (not (eq input-size output-size)))
1852       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1853              input-type input-size
1854              output-type output-size))
1855     (setf (fd-stream-element-size fd-stream)
1856           (or input-size output-size))
1857
1858     (setf (fd-stream-element-type fd-stream)
1859           (cond ((equal input-type output-type)
1860                  input-type)
1861                 ((null output-type)
1862                  input-type)
1863                 ((null input-type)
1864                  output-type)
1865                 ((subtypep input-type output-type)
1866                  input-type)
1867                 ((subtypep output-type input-type)
1868                  output-type)
1869                 (t
1870                  (error "Input type (~S) and output type (~S) are unrelated?"
1871                         input-type
1872                         output-type))))))
1873
1874 ;;; Handles the resource-release aspects of stream closing, and marks
1875 ;;; it as closed.
1876 (defun release-fd-stream-resources (fd-stream)
1877   (handler-case
1878       (without-interrupts
1879         ;; Drop handlers first.
1880         (when (fd-stream-handler fd-stream)
1881           (remove-fd-handler (fd-stream-handler fd-stream))
1882           (setf (fd-stream-handler fd-stream) nil))
1883         ;; Disable interrupts so that a asynch unwind will not leave
1884         ;; us with a dangling finalizer (that would close the same
1885         ;; --possibly reassigned-- FD again), or a stream with a closed
1886         ;; FD that appears open.
1887         (sb!unix:unix-close (fd-stream-fd fd-stream))
1888         (set-closed-flame fd-stream)
1889         (when (fboundp 'cancel-finalization)
1890           (cancel-finalization fd-stream)))
1891     ;; On error unwind from WITHOUT-INTERRUPTS.
1892     (serious-condition (e)
1893       (error e)))
1894   ;; Release all buffers. If this is undone, or interrupted,
1895   ;; we're still safe: buffers have finalizers of their own.
1896   (release-fd-stream-buffers fd-stream))
1897
1898 ;;; Flushes the current input buffer and unread chatacter, and returns
1899 ;;; the input buffer, and the amount of of flushed input in bytes.
1900 (defun flush-input-buffer (stream)
1901   (let ((unread (if (fd-stream-unread stream)
1902                     1
1903                     0)))
1904     (setf (fd-stream-unread stream) nil)
1905     (let ((ibuf (fd-stream-ibuf stream)))
1906       (if ibuf
1907           (let ((head (buffer-head ibuf))
1908                 (tail (buffer-tail ibuf)))
1909             (values (reset-buffer ibuf) (- (+ unread tail) head)))
1910           (values nil unread)))))
1911
1912 (defun fd-stream-clear-input (stream)
1913   (flush-input-buffer stream)
1914   #!+win32
1915   (progn
1916     (sb!win32:fd-clear-input (fd-stream-fd stream))
1917     (setf (fd-stream-listen stream) nil))
1918   #!-win32
1919   (catch 'eof-input-catcher
1920     (loop until (sysread-may-block-p stream)
1921           do
1922           (refill-input-buffer stream)
1923           (reset-buffer (fd-stream-ibuf stream)))
1924     t))
1925
1926 ;;; Handle miscellaneous operations on FD-STREAM.
1927 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1928   (declare (ignore arg2))
1929   (case operation
1930     (:listen
1931      (labels ((do-listen ()
1932                 (let ((ibuf (fd-stream-ibuf fd-stream)))
1933                   (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1934                       (fd-stream-listen fd-stream)
1935                       #!+win32
1936                       (sb!win32:fd-listen (fd-stream-fd fd-stream))
1937                       #!-win32
1938                       ;; If the read can block, LISTEN will certainly return NIL.
1939                       (if (sysread-may-block-p fd-stream)
1940                           nil
1941                           ;; Otherwise select(2) and CL:LISTEN have slightly
1942                           ;; different semantics.  The former returns that an FD
1943                           ;; is readable when a read operation wouldn't block.
1944                           ;; That includes EOF.  However, LISTEN must return NIL
1945                           ;; at EOF.
1946                           (progn (catch 'eof-input-catcher
1947                                    ;; r-b/f too calls select, but it shouldn't
1948                                    ;; block as long as read can return once w/o
1949                                    ;; blocking
1950                                    (refill-input-buffer fd-stream))
1951                                  ;; At this point either IBUF-HEAD != IBUF-TAIL
1952                                  ;; and FD-STREAM-LISTEN is NIL, in which case
1953                                  ;; we should return T, or IBUF-HEAD ==
1954                                  ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1955                                  ;; which case we should return :EOF for this
1956                                  ;; call and all future LISTEN call on this stream.
1957                                  ;; Call ourselves again to determine which case
1958                                  ;; applies.
1959                                  (do-listen)))))))
1960        (do-listen)))
1961     (:unread
1962      ;; If the stream is bivalent, the user might follow an
1963      ;; unread-char with a read-byte.  In this case, the bookkeeping
1964      ;; is simpler if we adjust the buffer head by the number of code
1965      ;; units in the character.
1966      ;; FIXME: there has to be a proper way to check for bivalence,
1967      ;; right?
1968      (if (fd-stream-bivalent-p fd-stream)
1969          (decf (buffer-head (fd-stream-ibuf fd-stream))
1970                (fd-stream-character-size fd-stream arg1))
1971          (setf (fd-stream-unread fd-stream) arg1))
1972      (setf (fd-stream-listen fd-stream) t))
1973     (:close
1974      ;; Drop input buffers
1975      (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1976            (ansi-stream-cin-buffer fd-stream) nil
1977            (ansi-stream-in-buffer fd-stream) nil)
1978      (cond (arg1
1979             ;; We got us an abort on our hands.
1980             (let ((outputp (fd-stream-obuf fd-stream))
1981                   (file (fd-stream-file fd-stream))
1982                   (orig (fd-stream-original fd-stream)))
1983               ;; This takes care of the important stuff -- everything
1984               ;; rest is cleaning up the file-system, which we cannot
1985               ;; do on some platforms as long as the file is open.
1986               (release-fd-stream-resources fd-stream)
1987               ;; We can't do anything unless we know what file were
1988               ;; dealing with, and we don't want to do anything
1989               ;; strange unless we were writing to the file.
1990               (when (and outputp file)
1991                 (if orig
1992                     ;; If the original is EQ to file we are appending to
1993                     ;; and can just close the file without renaming.
1994                     (unless (eq orig file)
1995                       ;; We have a handle on the original, just revert.
1996                       (multiple-value-bind (okay err)
1997                           (sb!unix:unix-rename orig file)
1998                         ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1999                         ;; others are SIMPLE-FILE-ERRORS? Surely they should
2000                         ;; all be the same?
2001                         (unless okay
2002                           (error 'simple-stream-error
2003                                  :format-control
2004                                  "~@<Couldn't restore ~S to its original contents ~
2005                                   from ~S while closing ~S: ~2I~_~A~:>"
2006                                  :format-arguments
2007                                  (list file orig fd-stream (strerror err))
2008                                  :stream fd-stream))))
2009                     ;; We can't restore the original, and aren't
2010                     ;; appending, so nuke that puppy.
2011                     ;;
2012                     ;; FIXME: This is currently the fate of superseded
2013                     ;; files, and according to the CLOSE spec this is
2014                     ;; wrong. However, there seems to be no clean way to
2015                     ;; do that that doesn't involve either copying the
2016                     ;; data (bad if the :abort resulted from a full
2017                     ;; disk), or renaming the old file temporarily
2018                     ;; (probably bad because stream opening becomes more
2019                     ;; racy).
2020                     (multiple-value-bind (okay err)
2021                         (sb!unix:unix-unlink file)
2022                       (unless okay
2023                         (error 'simple-file-error
2024                                :pathname file
2025                                :format-control
2026                                "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2027                                :format-arguments
2028                                (list file fd-stream (strerror err)))))))))
2029            (t
2030             (finish-fd-stream-output fd-stream)
2031             (let ((orig (fd-stream-original fd-stream)))
2032               (when (and orig (fd-stream-delete-original fd-stream))
2033                 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2034                   (unless okay
2035                     (error 'simple-file-error
2036                            :pathname orig
2037                            :format-control
2038                            "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2039                            :format-arguments
2040                            (list orig fd-stream (strerror err)))))))
2041             ;; In case of no-abort close, don't *really* close the
2042             ;; stream until the last moment -- the cleaning up of the
2043             ;; original can be done first.
2044             (release-fd-stream-resources fd-stream))))
2045     (:clear-input
2046      (fd-stream-clear-input fd-stream))
2047     (:force-output
2048      (flush-output-buffer fd-stream))
2049     (:finish-output
2050      (finish-fd-stream-output fd-stream))
2051     (:element-type
2052      (fd-stream-element-type fd-stream))
2053     (:external-format
2054      (fd-stream-external-format fd-stream))
2055     (:interactive-p
2056      (= 1 (the (member 0 1)
2057             (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2058     (:line-length
2059      80)
2060     (:charpos
2061      (fd-stream-char-pos fd-stream))
2062     (:file-length
2063      (unless (fd-stream-file fd-stream)
2064        ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2065        ;; "should signal an error of type TYPE-ERROR if stream is not
2066        ;; a stream associated with a file". Too bad there's no very
2067        ;; appropriate value for the EXPECTED-TYPE slot..
2068        (error 'simple-type-error
2069               :datum fd-stream
2070               :expected-type 'fd-stream
2071               :format-control "~S is not a stream associated with a file."
2072               :format-arguments (list fd-stream)))
2073      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2074                                 atime mtime ctime blksize blocks)
2075          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2076        (declare (ignore ino nlink uid gid rdev
2077                         atime mtime ctime blksize blocks))
2078        (unless okay
2079          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2080        (if (zerop mode)
2081            nil
2082            (truncate size (fd-stream-element-size fd-stream)))))
2083     (:file-string-length
2084      (etypecase arg1
2085        (character (fd-stream-character-size fd-stream arg1))
2086        (string (fd-stream-string-size fd-stream arg1))))
2087     (:file-position
2088      (if arg1
2089          (fd-stream-set-file-position fd-stream arg1)
2090          (fd-stream-get-file-position fd-stream)))))
2091
2092 ;; FIXME: Think about this.
2093 ;;
2094 ;; (defun finish-fd-stream-output (fd-stream)
2095 ;;   (let ((timeout (fd-stream-timeout fd-stream)))
2096 ;;     (loop while (fd-stream-output-queue fd-stream)
2097 ;;        ;; FIXME: SIGINT while waiting for a timeout will
2098 ;;        ;; cause a timeout here.
2099 ;;        do (when (and (not (serve-event timeout)) timeout)
2100 ;;             (signal-timeout 'io-timeout
2101 ;;                             :stream fd-stream
2102 ;;                             :direction :write
2103 ;;                             :seconds timeout)))))
2104
2105 (defun finish-fd-stream-output (stream)
2106   (flush-output-buffer stream)
2107   (do ()
2108       ((null (fd-stream-output-queue stream)))
2109     (serve-all-events)))
2110
2111 (defun fd-stream-get-file-position (stream)
2112   (declare (fd-stream stream))
2113   (without-interrupts
2114     (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2115       (declare (type (or (alien sb!unix:off-t) null) posn))
2116       ;; We used to return NIL for errno==ESPIPE, and signal an error
2117       ;; in other failure cases. However, CLHS says to return NIL if
2118       ;; the position cannot be determined -- so that's what we do.
2119       (when (integerp posn)
2120         ;; Adjust for buffered output: If there is any output
2121         ;; buffered, the *real* file position will be larger
2122         ;; than reported by lseek() because lseek() obviously
2123         ;; cannot take into account output we have not sent
2124         ;; yet.
2125         (dolist (buffer (fd-stream-output-queue stream))
2126           (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2127         (let ((obuf (fd-stream-obuf stream)))
2128           (when obuf
2129             (incf posn (buffer-tail obuf))))
2130         ;; Adjust for unread input: If there is any input
2131         ;; read from UNIX but not supplied to the user of the
2132         ;; stream, the *real* file position will smaller than
2133         ;; reported, because we want to look like the unread
2134         ;; stuff is still available.
2135         (let ((ibuf (fd-stream-ibuf stream)))
2136           (when ibuf
2137             (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2138         (when (fd-stream-unread stream)
2139           (decf posn))
2140         ;; Divide bytes by element size.
2141         (truncate posn (fd-stream-element-size stream))))))
2142
2143 (defun fd-stream-set-file-position (stream position-spec)
2144   (declare (fd-stream stream))
2145   (check-type position-spec
2146               (or (alien sb!unix:off-t) (member nil :start :end))
2147               "valid file position designator")
2148   (tagbody
2149    :again
2150      ;; Make sure we don't have any output pending, because if we
2151      ;; move the file pointer before writing this stuff, it will be
2152      ;; written in the wrong location.
2153      (finish-fd-stream-output stream)
2154      ;; Disable interrupts so that interrupt handlers doing output
2155      ;; won't screw us.
2156      (without-interrupts
2157        (unless (fd-stream-output-finished-p stream)
2158          ;; We got interrupted and more output came our way during
2159          ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2160          ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2161          ;; so we prefer to do things like this...
2162          (go :again))
2163        ;; Clear out any pending input to force the next read to go to
2164        ;; the disk.
2165        (flush-input-buffer stream)
2166        ;; Trash cached value for listen, so that we check next time.
2167        (setf (fd-stream-listen stream) nil)
2168          ;; Now move it.
2169          (multiple-value-bind (offset origin)
2170              (case position-spec
2171                (:start
2172                 (values 0 sb!unix:l_set))
2173                (:end
2174                 (values 0 sb!unix:l_xtnd))
2175                (t
2176                 (values (* position-spec (fd-stream-element-size stream))
2177                         sb!unix:l_set)))
2178            (declare (type (alien sb!unix:off-t) offset))
2179            (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2180                                            offset origin)))
2181              ;; CLHS says to return true if the file-position was set
2182              ;; succesfully, and NIL otherwise. We are to signal an error
2183              ;; only if the given position was out of bounds, and that is
2184              ;; dealt with above. In times past we used to return NIL for
2185              ;; errno==ESPIPE, and signal an error in other cases.
2186              ;;
2187              ;; FIXME: We are still liable to signal an error if flushing
2188              ;; output fails.
2189              (return-from fd-stream-set-file-position
2190                (typep posn '(alien sb!unix:off-t))))))))
2191
2192 \f
2193 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2194
2195 ;;; Create a stream for the given Unix file descriptor.
2196 ;;;
2197 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2198 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2199 ;;; default to allowing input.
2200 ;;;
2201 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2202 ;;;
2203 ;;; BUFFERING indicates the kind of buffering to use.
2204 ;;;
2205 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2206 ;;; NIL (the default), then wait forever. When we time out, we signal
2207 ;;; IO-TIMEOUT.
2208 ;;;
2209 ;;; FILE is the name of the file (will be returned by PATHNAME).
2210 ;;;
2211 ;;; NAME is used to identify the stream when printed.
2212 (defun make-fd-stream (fd
2213                        &key
2214                        (input nil input-p)
2215                        (output nil output-p)
2216                        (element-type 'base-char)
2217                        (buffering :full)
2218                        (external-format :default)
2219                        timeout
2220                        file
2221                        original
2222                        delete-original
2223                        pathname
2224                        input-buffer-p
2225                        dual-channel-p
2226                        (name (if file
2227                                  (format nil "file ~A" file)
2228                                  (format nil "descriptor ~W" fd)))
2229                        auto-close)
2230   (declare (type index fd) (type (or real null) timeout)
2231            (type (member :none :line :full) buffering))
2232   (cond ((not (or input-p output-p))
2233          (setf input t))
2234         ((not (or input output))
2235          (error "File descriptor must be opened either for input or output.")))
2236   (let ((stream (%make-fd-stream :fd fd
2237                                  :name name
2238                                  :file file
2239                                  :original original
2240                                  :delete-original delete-original
2241                                  :pathname pathname
2242                                  :buffering buffering
2243                                  :dual-channel-p dual-channel-p
2244                                  :external-format external-format
2245                                  :bivalent-p (eq element-type :default)
2246                                  :char-size (external-format-char-size external-format)
2247                                  :timeout
2248                                  (if timeout
2249                                      (coerce timeout 'single-float)
2250                                      nil))))
2251     (set-fd-stream-routines stream element-type external-format
2252                             input output input-buffer-p)
2253     (when (and auto-close (fboundp 'finalize))
2254       (finalize stream
2255                 (lambda ()
2256                   (sb!unix:unix-close fd)
2257                   #!+sb-show
2258                   (format *terminal-io* "** closed file descriptor ~W **~%"
2259                           fd))
2260                 :dont-save t))
2261     stream))
2262
2263 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2264 ;;; :RENAME-AND-DELETE and :RENAME options.
2265 (defun pick-backup-name (name)
2266   (declare (type simple-string name))
2267   (concatenate 'simple-string name ".bak"))
2268
2269 ;;; Ensure that the given arg is one of the given list of valid
2270 ;;; things. Allow the user to fix any problems.
2271 (defun ensure-one-of (item list what)
2272   (unless (member item list)
2273     (error 'simple-type-error
2274            :datum item
2275            :expected-type `(member ,@list)
2276            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2277            :format-arguments (list item what list))))
2278
2279 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2280 ;;; access, since we don't want to trash unwritable files even if we
2281 ;;; technically can. We return true if we succeed in renaming.
2282 (defun rename-the-old-one (namestring original)
2283   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2284     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2285   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2286     (if okay
2287         t
2288         (error 'simple-file-error
2289                :pathname namestring
2290                :format-control
2291                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2292                :format-arguments (list namestring original (strerror err))))))
2293
2294 (defun open (filename
2295              &key
2296              (direction :input)
2297              (element-type 'base-char)
2298              (if-exists nil if-exists-given)
2299              (if-does-not-exist nil if-does-not-exist-given)
2300              (external-format :default)
2301              &aux ; Squelch assignment warning.
2302              (direction direction)
2303              (if-does-not-exist if-does-not-exist)
2304              (if-exists if-exists))
2305   #!+sb-doc
2306   "Return a stream which reads from or writes to FILENAME.
2307   Defined keywords:
2308    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2309    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2310    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2311                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2312    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2313   See the manual for details."
2314
2315   ;; Calculate useful stuff.
2316   (multiple-value-bind (input output mask)
2317       (ecase direction
2318         (:input  (values   t nil sb!unix:o_rdonly))
2319         (:output (values nil   t sb!unix:o_wronly))
2320         (:io     (values   t   t sb!unix:o_rdwr))
2321         (:probe  (values   t nil sb!unix:o_rdonly)))
2322     (declare (type index mask))
2323     (let* (;; PATHNAME is the pathname we associate with the stream.
2324            (pathname (merge-pathnames filename))
2325            (physical (physicalize-pathname pathname))
2326            (truename (probe-file physical))
2327            ;; NAMESTRING is the native namestring we open the file with.
2328            (namestring (cond (truename
2329                               (native-namestring truename :as-file t))
2330                              ((or (not input)
2331                                   (and input (eq if-does-not-exist :create))
2332                                   (and (eq direction :io) (not if-does-not-exist-given)))
2333                               (native-namestring physical :as-file t)))))
2334       ;; Process if-exists argument if we are doing any output.
2335       (cond (output
2336              (unless if-exists-given
2337                (setf if-exists
2338                      (if (eq (pathname-version pathname) :newest)
2339                          :new-version
2340                          :error)))
2341              (ensure-one-of if-exists
2342                             '(:error :new-version :rename
2343                                      :rename-and-delete :overwrite
2344                                      :append :supersede nil)
2345                             :if-exists)
2346              (case if-exists
2347                ((:new-version :error nil)
2348                 (setf mask (logior mask sb!unix:o_excl)))
2349                ((:rename :rename-and-delete)
2350                 (setf mask (logior mask sb!unix:o_creat)))
2351                ((:supersede)
2352                 (setf mask (logior mask sb!unix:o_trunc)))
2353                (:append
2354                 (setf mask (logior mask sb!unix:o_append)))))
2355             (t
2356              (setf if-exists :ignore-this-arg)))
2357
2358       (unless if-does-not-exist-given
2359         (setf if-does-not-exist
2360               (cond ((eq direction :input) :error)
2361                     ((and output
2362                           (member if-exists '(:overwrite :append)))
2363                      :error)
2364                     ((eq direction :probe)
2365                      nil)
2366                     (t
2367                      :create))))
2368       (ensure-one-of if-does-not-exist
2369                      '(:error :create nil)
2370                      :if-does-not-exist)
2371       (if (eq if-does-not-exist :create)
2372         (setf mask (logior mask sb!unix:o_creat)))
2373
2374       (let ((original (case if-exists
2375                         ((:rename :rename-and-delete)
2376                          (pick-backup-name namestring))
2377                         ((:append :overwrite)
2378                          ;; KLUDGE: Provent CLOSE from deleting
2379                          ;; appending streams when called with :ABORT T
2380                          namestring)))
2381             (delete-original (eq if-exists :rename-and-delete))
2382             (mode #o666))
2383         (when (and original (not (eq original namestring)))
2384           ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2385           ;; whether the file already exists, make sure the original
2386           ;; file is not a directory, and keep the mode.
2387           (let ((exists
2388                  (and namestring
2389                       (multiple-value-bind (okay err/dev inode orig-mode)
2390                           (sb!unix:unix-stat namestring)
2391                         (declare (ignore inode)
2392                                  (type (or index null) orig-mode))
2393                         (cond
2394                          (okay
2395                           (when (and output (= (logand orig-mode #o170000)
2396                                                #o40000))
2397                             (error 'simple-file-error
2398                                    :pathname pathname
2399                                    :format-control
2400                                    "can't open ~S for output: is a directory"
2401                                    :format-arguments (list namestring)))
2402                           (setf mode (logand orig-mode #o777))
2403                           t)
2404                          ((eql err/dev sb!unix:enoent)
2405                           nil)
2406                          (t
2407                           (simple-file-perror "can't find ~S"
2408                                               namestring
2409                                               err/dev)))))))
2410             (unless (and exists
2411                          (rename-the-old-one namestring original))
2412               (setf original nil)
2413               (setf delete-original nil)
2414               ;; In order to use :SUPERSEDE instead, we have to make
2415               ;; sure SB!UNIX:O_CREAT corresponds to
2416               ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2417               ;; because of IF-EXISTS being :RENAME.
2418               (unless (eq if-does-not-exist :create)
2419                 (setf mask
2420                       (logior (logandc2 mask sb!unix:o_creat)
2421                               sb!unix:o_trunc)))
2422               (setf if-exists :supersede))))
2423
2424         ;; Now we can try the actual Unix open(2).
2425         (multiple-value-bind (fd errno)
2426             (if namestring
2427                 (sb!unix:unix-open namestring mask mode)
2428                 (values nil sb!unix:enoent))
2429           (labels ((open-error (format-control &rest format-arguments)
2430                      (error 'simple-file-error
2431                             :pathname pathname
2432                             :format-control format-control
2433                             :format-arguments format-arguments))
2434                    (vanilla-open-error ()
2435                      (simple-file-perror "error opening ~S" pathname errno)))
2436             (cond ((numberp fd)
2437                    (case direction
2438                      ((:input :output :io)
2439                       (make-fd-stream fd
2440                                       :input input
2441                                       :output output
2442                                       :element-type element-type
2443                                       :external-format external-format
2444                                       :file namestring
2445                                       :original original
2446                                       :delete-original delete-original
2447                                       :pathname pathname
2448                                       :dual-channel-p nil
2449                                       :input-buffer-p t
2450                                       :auto-close t))
2451                      (:probe
2452                       (let ((stream
2453                              (%make-fd-stream :name namestring
2454                                               :fd fd
2455                                               :pathname pathname
2456                                               :element-type element-type)))
2457                         (close stream)
2458                         stream))))
2459                   ((eql errno sb!unix:enoent)
2460                    (case if-does-not-exist
2461                      (:error (vanilla-open-error))
2462                      (:create
2463                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2464                                   pathname))
2465                      (t nil)))
2466                   ((and (eql errno sb!unix:eexist) (null if-exists))
2467                    nil)
2468                   (t
2469                    (vanilla-open-error)))))))))
2470 \f
2471 ;;;; initialization
2472
2473 ;;; the stream connected to the controlling terminal, or NIL if there is none
2474 (defvar *tty*)
2475
2476 ;;; the stream connected to the standard input (file descriptor 0)
2477 (defvar *stdin*)
2478
2479 ;;; the stream connected to the standard output (file descriptor 1)
2480 (defvar *stdout*)
2481
2482 ;;; the stream connected to the standard error output (file descriptor 2)
2483 (defvar *stderr*)
2484
2485 ;;; This is called when the cold load is first started up, and may also
2486 ;;; be called in an attempt to recover from nested errors.
2487 (defun stream-cold-init-or-reset ()
2488   (stream-reinit)
2489   (setf *terminal-io* (make-synonym-stream '*tty*))
2490   (setf *standard-output* (make-synonym-stream '*stdout*))
2491   (setf *standard-input* (make-synonym-stream '*stdin*))
2492   (setf *error-output* (make-synonym-stream '*stderr*))
2493   (setf *query-io* (make-synonym-stream '*terminal-io*))
2494   (setf *debug-io* *query-io*)
2495   (setf *trace-output* *standard-output*)
2496   (values))
2497
2498 (defun stream-deinit ()
2499   ;; Unbind to make sure we're not accidently dealing with it
2500   ;; before we're ready (or after we think it's been deinitialized).
2501   (with-available-buffers-lock ()
2502     (without-package-locks
2503         (makunbound '*available-buffers*))))
2504
2505 ;;; This is called whenever a saved core is restarted.
2506 (defun stream-reinit (&optional init-buffers-p)
2507   (when init-buffers-p
2508     (with-available-buffers-lock ()
2509       (aver (not (boundp '*available-buffers*)))
2510       (setf *available-buffers* nil)))
2511   (with-output-to-string (*error-output*)
2512     (setf *stdin*
2513           (make-fd-stream 0 :name "standard input" :input t :buffering :line
2514                             #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2515     (setf *stdout*
2516           (make-fd-stream 1 :name "standard output" :output t :buffering :line
2517                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2518     (setf *stderr*
2519           (make-fd-stream 2 :name "standard error" :output t :buffering :line
2520                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2521     (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2522            (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2523       (if tty
2524           (setf *tty*
2525                 (make-fd-stream tty
2526                                 :name "the terminal"
2527                                 :input t
2528                                 :output t
2529                                 :buffering :line
2530                                 :auto-close t))
2531           (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2532     (princ (get-output-stream-string *error-output*) *stderr*))
2533   (values))
2534 \f
2535 ;;;; miscellany
2536
2537 ;;; the Unix way to beep
2538 (defun beep (stream)
2539   (write-char (code-char bell-char-code) stream)
2540   (finish-output stream))
2541
2542 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2543 ;;; by the filesys stuff to get and set the file name.
2544 ;;;
2545 ;;; FIXME: misleading name, screwy interface
2546 (defun file-name (stream &optional new-name)
2547   (when (typep stream 'fd-stream)
2548       (cond (new-name
2549              (setf (fd-stream-pathname stream) new-name)
2550              (setf (fd-stream-file stream)
2551                    (native-namestring (physicalize-pathname new-name)
2552                                       :as-file t))
2553              t)
2554             (t
2555              (fd-stream-pathname stream)))))