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