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