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