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