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