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