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