1.0.10.44: BUFFER-P, not BUFFERP
[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     (tagbody
849        ;; Check for blocking input before touching the stream, as if
850        ;; we happen to wait we are liable to be interrupted, and the
851        ;; interrupt handler may use the same stream.
852        (if (sysread-may-block-p stream)
853            (go :wait-for-input)
854            (go :main))
855        ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
856        ;; we can signal errors outside the WITHOUT-INTERRUPTS.
857      :closed-flame
858        (closed-flame stream)
859      :read-error
860        (simple-stream-perror "couldn't read from ~S" stream errno)
861      :wait-for-input
862        ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
863        ;; to wait for input if read tells us EWOULDBLOCK.
864        (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
865          (signal-timeout 'io-timeout :stream stream :direction :read
866                          :seconds (fd-stream-timeout stream)))
867      :main
868        ;; Since the read should not block, we'll disable the
869        ;; interrupts here, so that we don't accidentally unwind and
870        ;; leave the stream in an inconsistent state.
871        (without-interrupts
872          ;; Check the buffer: if it is null, then someone has closed
873          ;; the stream from underneath us. This is not ment to fix
874          ;; multithreaded races, but to deal with interrupt handlers
875          ;; closing the stream.
876          (let* ((ibuf (or (fd-stream-ibuf stream) (go :closed-flame)))
877                 (sap (buffer-sap ibuf))
878                 (length (buffer-length ibuf))
879                 (head (buffer-head ibuf))
880                 (tail (buffer-tail ibuf)))
881            (declare (index length head tail))
882            (unless (zerop head)
883              (cond ((eql head tail)
884                     ;; Buffer is empty, but not at yet reset -- make it so.
885                     (setf head 0
886                           tail 0)
887                     (reset-buffer ibuf))
888                    (t
889                     ;; Buffer has things in it, but they are not at the head
890                     ;; -- move them there.
891                     (let ((n (- tail head)))
892                       (system-area-ub8-copy sap head sap 0 n)
893                       (setf head 0
894                             (buffer-head ibuf) head
895                             tail n
896                             (buffer-tail ibuf) tail)))))
897            (setf (fd-stream-listen stream) nil)
898            (setf (values count errno)
899                  (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
900            (cond ((null count)
901                   #!+win32
902                   (go :read-error)
903                   #!-win32
904                   (if (eql errno sb!unix:ewouldblock)
905                       (go :wait-for-input)
906                       (go :read-error)))
907                  ((zerop count)
908                   (setf (fd-stream-listen stream) :eof)
909                   (/show0 "THROWing EOF-INPUT-CATCHER")
910                   (throw 'eof-input-catcher nil))
911                  (t
912                   ;; Success! (Do not use INCF, for sake of other threads.)
913                   (setf (buffer-tail ibuf) (+ count tail)))))))
914     count))
915
916 ;;; Make sure there are at least BYTES number of bytes in the input
917 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
918 (defmacro input-at-least (stream bytes)
919   (let ((stream-var (gensym "STREAM"))
920         (bytes-var (gensym "BYTES"))
921         (buffer-var (gensym "IBUF")))
922     `(let* ((,stream-var ,stream)
923             (,bytes-var ,bytes)
924             (,buffer-var (fd-stream-ibuf ,stream-var)))
925        (loop
926          (when (>= (- (buffer-tail ,buffer-var)
927                       (buffer-head ,buffer-var))
928                    ,bytes-var)
929            (return))
930          (refill-input-buffer ,stream-var)))))
931
932 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
933                                         &body read-forms)
934   (let ((stream-var (gensym "STREAM"))
935         (retry-var (gensym "RETRY"))
936         (element-var (gensym "ELT")))
937     `(let* ((,stream-var ,stream)
938             (ibuf (fd-stream-ibuf ,stream-var))
939             (size nil))
940        (if (fd-stream-unread ,stream-var)
941            (prog1
942                (fd-stream-unread ,stream-var)
943              (setf (fd-stream-unread ,stream-var) nil)
944              (setf (fd-stream-listen ,stream-var) nil))
945            (let ((,element-var nil)
946                  (decode-break-reason nil))
947              (do ((,retry-var t))
948                  ((not ,retry-var))
949                (unless
950                    (catch 'eof-input-catcher
951                      (setf decode-break-reason
952                            (block decode-break-reason
953                              (input-at-least ,stream-var 1)
954                              (let* ((byte (sap-ref-8 (buffer-sap ibuf)
955                                                      (buffer-head ibuf))))
956                                (declare (ignorable byte))
957                                (setq size ,bytes)
958                                (input-at-least ,stream-var size)
959                                (setq ,element-var (locally ,@read-forms))
960                                (setq ,retry-var nil))
961                              nil))
962                      (when decode-break-reason
963                        (stream-decoding-error-and-handle stream
964                                                          decode-break-reason))
965                      t)
966                  (let ((octet-count (- (buffer-tail ibuf)
967                                        (buffer-head ibuf))))
968                    (when (or (zerop octet-count)
969                              (and (not ,element-var)
970                                   (not decode-break-reason)
971                                   (stream-decoding-error-and-handle
972                                    stream octet-count)))
973                      (setq ,retry-var nil)))))
974              (cond (,element-var
975                     (incf (buffer-head ibuf) size)
976                     ,element-var)
977                    (t
978                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
979
980 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
981 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
982   (let ((stream-var (gensym "STREAM"))
983         (element-var (gensym "ELT")))
984     `(let* ((,stream-var ,stream)
985             (ibuf (fd-stream-ibuf ,stream-var)))
986        (if (fd-stream-unread ,stream-var)
987            (prog1
988                (fd-stream-unread ,stream-var)
989              (setf (fd-stream-unread ,stream-var) nil)
990              (setf (fd-stream-listen ,stream-var) nil))
991            (let ((,element-var
992                   (catch 'eof-input-catcher
993                     (input-at-least ,stream-var ,bytes)
994                     (locally ,@read-forms))))
995              (cond (,element-var
996                     (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
997                     ,element-var)
998                    (t
999                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1000
1001 (defmacro def-input-routine/variable-width (name
1002                                             (type external-format size sap head)
1003                                             &rest body)
1004   `(progn
1005      (defun ,name (stream eof-error eof-value)
1006        (input-wrapper/variable-width (stream ,size eof-error eof-value)
1007          (let ((,sap (buffer-sap ibuf))
1008                (,head (buffer-head ibuf)))
1009            ,@body)))
1010      (setf *input-routines*
1011            (nconc *input-routines*
1012                   (list (list ',type ',name 1 ',external-format))))))
1013
1014 (defmacro def-input-routine (name
1015                              (type size sap head)
1016                              &rest body)
1017   `(progn
1018      (defun ,name (stream eof-error eof-value)
1019        (input-wrapper (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 ',size nil))))))
1026
1027 ;;; STREAM-IN routine for reading a string char
1028 (def-input-routine input-character
1029                    (character 1 sap head)
1030   (code-char (sap-ref-8 sap head)))
1031
1032 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1033 (def-input-routine input-unsigned-8bit-byte
1034                    ((unsigned-byte 8) 1 sap head)
1035   (sap-ref-8 sap head))
1036
1037 ;;; STREAM-IN routine for reading a signed 8 bit number
1038 (def-input-routine input-signed-8bit-number
1039                    ((signed-byte 8) 1 sap head)
1040   (signed-sap-ref-8 sap head))
1041
1042 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1043 (def-input-routine input-unsigned-16bit-byte
1044                    ((unsigned-byte 16) 2 sap head)
1045   (sap-ref-16 sap head))
1046
1047 ;;; STREAM-IN routine for reading a signed 16 bit number
1048 (def-input-routine input-signed-16bit-byte
1049                    ((signed-byte 16) 2 sap head)
1050   (signed-sap-ref-16 sap head))
1051
1052 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1053 (def-input-routine input-unsigned-32bit-byte
1054                    ((unsigned-byte 32) 4 sap head)
1055   (sap-ref-32 sap head))
1056
1057 ;;; STREAM-IN routine for reading a signed 32 bit number
1058 (def-input-routine input-signed-32bit-byte
1059                    ((signed-byte 32) 4 sap head)
1060   (signed-sap-ref-32 sap head))
1061
1062 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1063 (progn
1064   (def-input-routine input-unsigned-64bit-byte
1065       ((unsigned-byte 64) 8 sap head)
1066     (sap-ref-64 sap head))
1067   (def-input-routine input-signed-64bit-byte
1068       ((signed-byte 64) 8 sap head)
1069     (signed-sap-ref-64 sap head)))
1070
1071 ;;; Find an input routine to use given the type. Return as multiple
1072 ;;; values the routine, the real type transfered, and the number of
1073 ;;; bytes per element (and for character types string input routine).
1074 (defun pick-input-routine (type &optional external-format)
1075   (when (subtypep type 'character)
1076     (dolist (entry *external-formats*)
1077       (when (member external-format (first entry))
1078         (return-from pick-input-routine
1079           (values (symbol-function (third entry))
1080                   'character
1081                   1
1082                   (symbol-function (second entry))
1083                   (first (first entry)))))))
1084   (dolist (entry *input-routines*)
1085     (when (and (subtypep type (first entry))
1086                (or (not (fourth entry))
1087                    (eq external-format (fourth entry))))
1088       (return-from pick-input-routine
1089         (values (symbol-function (second entry))
1090                 (first entry)
1091                 (third entry)))))
1092   ;; FIXME: let's do it the hard way, then (but ignore things like
1093   ;; endianness, efficiency, and the necessary coupling between these
1094   ;; and the output routines).  -- CSR, 2004-02-09
1095   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1096         if (subtypep type `(unsigned-byte ,i))
1097         do (return-from pick-input-routine
1098              (values
1099               (lambda (stream eof-error eof-value)
1100                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1101                   (let ((sap (buffer-sap ibuf))
1102                         (head (buffer-head ibuf)))
1103                     (loop for j from 0 below (/ i 8)
1104                           with result = 0
1105                           do (setf result
1106                                    (+ (* 256 result)
1107                                       (sap-ref-8 sap (+ head j))))
1108                           finally (return result)))))
1109               `(unsigned-byte ,i)
1110               (/ i 8))))
1111   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1112         if (subtypep type `(signed-byte ,i))
1113         do (return-from pick-input-routine
1114              (values
1115               (lambda (stream eof-error eof-value)
1116                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1117                   (let ((sap (buffer-sap ibuf))
1118                         (head (buffer-head ibuf)))
1119                     (loop for j from 0 below (/ i 8)
1120                           with result = 0
1121                           do (setf result
1122                                    (+ (* 256 result)
1123                                       (sap-ref-8 sap (+ head j))))
1124                           finally (return (if (logbitp (1- i) result)
1125                                               (dpb result (byte i 0) -1)
1126                                               result))))))
1127               `(signed-byte ,i)
1128               (/ i 8)))))
1129
1130 ;;; the N-BIN method for FD-STREAMs
1131 ;;;
1132 ;;; Note that this blocks in UNIX-READ. It is generally used where
1133 ;;; there is a definite amount of reading to be done, so blocking
1134 ;;; isn't too problematical.
1135 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1136                                &aux (total-copied 0))
1137   (declare (type fd-stream stream))
1138   (declare (type index start requested total-copied))
1139   (let ((unread (fd-stream-unread stream)))
1140     (when unread
1141       ;; AVERs designed to fail when we have more complicated
1142       ;; character representations.
1143       (aver (typep unread 'base-char))
1144       (aver (= (fd-stream-element-size stream) 1))
1145       ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1146       ;; %BYTE-BLT
1147       (etypecase buffer
1148         (system-area-pointer
1149          (setf (sap-ref-8 buffer start) (char-code unread)))
1150         ((simple-unboxed-array (*))
1151          (setf (aref buffer start) unread)))
1152       (setf (fd-stream-unread stream) nil)
1153       (setf (fd-stream-listen stream) nil)
1154       (incf total-copied)))
1155   (do ()
1156       (nil)
1157     (let* ((remaining-request (- requested total-copied))
1158            (ibuf (fd-stream-ibuf stream))
1159            (head (buffer-head ibuf))
1160            (tail (buffer-tail ibuf))
1161            (available (- tail head))
1162            (n-this-copy (min remaining-request available))
1163            (this-start (+ start total-copied))
1164            (this-end (+ this-start n-this-copy))
1165            (sap (buffer-sap ibuf)))
1166       (declare (type index remaining-request head tail available))
1167       (declare (type index n-this-copy))
1168       ;; Copy data from stream buffer into user's buffer.
1169       (%byte-blt sap head buffer this-start this-end)
1170       (incf (buffer-head ibuf) n-this-copy)
1171       (incf total-copied n-this-copy)
1172       ;; Maybe we need to refill the stream buffer.
1173       (cond (;; If there were enough data in the stream buffer, we're done.
1174              (eql total-copied requested)
1175              (return total-copied))
1176             (;; If EOF, we're done in another way.
1177              (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1178              (if eof-error-p
1179                  (error 'end-of-file :stream stream)
1180                  (return total-copied)))
1181             ;; Otherwise we refilled the stream buffer, so fall
1182             ;; through into another pass of the loop.
1183             ))))
1184
1185 (defun fd-stream-resync (stream)
1186   (dolist (entry *external-formats*)
1187     (when (member (fd-stream-external-format stream) (first entry))
1188       (return-from fd-stream-resync
1189         (funcall (symbol-function (eighth entry)) stream)))))
1190
1191 (defun get-fd-stream-character-sizer (stream)
1192   (dolist (entry *external-formats*)
1193     (when (member (fd-stream-external-format stream) (first entry))
1194       (return-from get-fd-stream-character-sizer (ninth entry)))))
1195
1196 (defun fd-stream-character-size (stream char)
1197   (let ((sizer (get-fd-stream-character-sizer stream)))
1198     (when sizer (funcall sizer char))))
1199
1200 (defun fd-stream-string-size (stream string)
1201   (let ((sizer (get-fd-stream-character-sizer stream)))
1202     (when sizer
1203       (loop for char across string summing (funcall sizer char)))))
1204
1205 (defun find-external-format (external-format)
1206   (when external-format
1207     (find external-format *external-formats* :test #'member :key #'car)))
1208
1209 (defun variable-width-external-format-p (ef-entry)
1210   (when (eighth ef-entry) t))
1211
1212 (defun bytes-for-char-fun (ef-entry)
1213   (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1214
1215 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1216 (defmacro define-external-format (external-format size output-restart
1217                                   out-expr in-expr)
1218   (let* ((name (first external-format))
1219          (out-function (symbolicate "OUTPUT-BYTES/" name))
1220          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1221          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1222          (in-char-function (symbolicate "INPUT-CHAR/" name))
1223          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1224          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1225          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1226          (n-buffer (gensym "BUFFER")))
1227     `(progn
1228       (defun ,size-function (byte)
1229         (declare (ignore byte))
1230         ,size)
1231       (defun ,out-function (stream string flush-p start end)
1232         (let ((start (or start 0))
1233               (end (or end (length string))))
1234           (declare (type index start end))
1235           (synchronize-stream-output stream)
1236           (unless (<= 0 start end (length string))
1237             (signal-bounding-indices-bad-error string start end))
1238           (do ()
1239               ((= end start))
1240             (let ((obuf (fd-stream-obuf stream)))
1241               (setf (buffer-tail obuf)
1242                     (string-dispatch (simple-base-string
1243                                       #!+sb-unicode
1244                                       (simple-array character (*))
1245                                       string)
1246                         string
1247                       (let ((sap (buffer-sap obuf))
1248                             (len (buffer-length obuf))
1249                             ;; FIXME: rename
1250                             (tail (buffer-tail obuf)))
1251                        (declare (type index tail)
1252                                 ;; STRING bounds have already been checked.
1253                                 (optimize (safety 0)))
1254                        (loop
1255                          (,@(if output-restart
1256                                 `(catch 'output-nothing)
1257                                 `(progn))
1258                             (do* ()
1259                                  ((or (= start end) (< (- len tail) 4)))
1260                               (let* ((byte (aref string start))
1261                                      (bits (char-code byte)))
1262                                 ,out-expr
1263                                 (incf tail ,size)
1264                                 (incf start)))
1265                             ;; Exited from the loop normally
1266                             (return tail))
1267                          ;; Exited via CATCH. Skip the current character
1268                          ;; and try the inner loop again.
1269                          (incf start))))))
1270             (when (< start end)
1271               (flush-output-buffer stream)))
1272           (when flush-p
1273             (flush-output-buffer stream))))
1274       (def-output-routines (,format
1275                             ,size
1276                             ,output-restart
1277                             (:none character)
1278                             (:line character)
1279                             (:full character))
1280           (if (eql byte #\Newline)
1281               (setf (fd-stream-char-pos stream) 0)
1282               (incf (fd-stream-char-pos stream)))
1283           (let* ((obuf (fd-stream-obuf stream))
1284                  (bits (char-code byte))
1285                  (sap (buffer-sap obuf))
1286                  (tail (buffer-tail obuf)))
1287             ,out-expr))
1288       (defun ,in-function (stream buffer start requested eof-error-p
1289                            &aux (index start) (end (+ start requested)))
1290         (declare (type fd-stream stream)
1291                  (type index start requested index end)
1292                  (type
1293                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1294                   buffer))
1295         (let ((unread (fd-stream-unread stream)))
1296           (when unread
1297             (setf (aref buffer index) unread)
1298             (setf (fd-stream-unread stream) nil)
1299             (setf (fd-stream-listen stream) nil)
1300             (incf index)))
1301         (do ()
1302             (nil)
1303           (let* ((ibuf (fd-stream-ibuf stream))
1304                  (head (buffer-head ibuf))
1305                  (tail (buffer-tail ibuf))
1306                  (sap (buffer-sap ibuf)))
1307             (declare (type index head tail)
1308                      (type system-area-pointer sap))
1309             ;; Copy data from stream buffer into user's buffer.
1310             (dotimes (i (min (truncate (- tail head) ,size)
1311                              (- end index)))
1312               (declare (optimize speed))
1313               (let* ((byte (sap-ref-8 sap head)))
1314                 (setf (aref buffer index) ,in-expr)
1315                 (incf index)
1316                 (incf head ,size)))
1317             (setf (buffer-head ibuf) head)
1318             ;; Maybe we need to refill the stream buffer.
1319             (cond ( ;; If there was enough data in the stream buffer, we're done.
1320                    (= index end)
1321                    (return (- index start)))
1322                   ( ;; If EOF, we're done in another way.
1323                    (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1324                    (if eof-error-p
1325                        (error 'end-of-file :stream stream)
1326                        (return (- index start))))
1327                   ;; Otherwise we refilled the stream buffer, so fall
1328                   ;; through into another pass of the loop.
1329                   ))))
1330       (def-input-routine ,in-char-function (character ,size sap head)
1331         (let ((byte (sap-ref-8 sap head)))
1332           ,in-expr))
1333       (defun ,read-c-string-function (sap element-type)
1334         (declare (type system-area-pointer sap)
1335                  (type (member character base-char) element-type))
1336         (locally
1337             (declare (optimize (speed 3) (safety 0)))
1338           (let* ((stream ,name)
1339                  (length
1340                   (loop for head of-type index upfrom 0 by ,size
1341                         for count of-type index upto (1- array-dimension-limit)
1342                         for byte = (sap-ref-8 sap head)
1343                         for char of-type character = ,in-expr
1344                         until (zerop (char-code char))
1345                         finally (return count)))
1346                  ;; Inline the common cases
1347                  (string (make-string length :element-type element-type)))
1348             (declare (ignorable stream)
1349                      (type index length)
1350                      (type simple-string string))
1351             (/show0 before-copy-loop)
1352             (loop for head of-type index upfrom 0 by ,size
1353                for index of-type index below length
1354                for byte = (sap-ref-8 sap head)
1355                for char of-type character = ,in-expr
1356                do (setf (aref string index) char))
1357             string))) ;; last loop rewrite to dotimes?
1358         (defun ,output-c-string-function (string)
1359           (declare (type simple-string string))
1360           (locally
1361               (declare (optimize (speed 3) (safety 0)))
1362             (let* ((length (length string))
1363                    (,n-buffer (make-array (* (1+ length) ,size)
1364                                           :element-type '(unsigned-byte 8)))
1365                    (tail 0)
1366                    (stream ,name))
1367               (declare (type index length tail))
1368               (with-pinned-objects (,n-buffer)
1369                 (let ((sap (vector-sap ,n-buffer)))
1370                   (declare (system-area-pointer sap))
1371                   (dotimes (i length)
1372                     (let* ((byte (aref string i))
1373                            (bits (char-code byte)))
1374                       (declare (ignorable byte bits))
1375                       ,out-expr)
1376                     (incf tail ,size))
1377                   (let* ((bits 0)
1378                          (byte (code-char bits)))
1379                     (declare (ignorable bits byte))
1380                     ,out-expr)))
1381               ,n-buffer)))
1382       (setf *external-formats*
1383        (cons '(,external-format ,in-function ,in-char-function ,out-function
1384                ,@(mapcar #'(lambda (buffering)
1385                              (intern (format nil format (string buffering))))
1386                          '(:none :line :full))
1387                nil ; no resync-function
1388                ,size-function ,read-c-string-function ,output-c-string-function)
1389         *external-formats*)))))
1390
1391 (defmacro define-external-format/variable-width
1392     (external-format output-restart out-size-expr
1393      out-expr in-size-expr in-expr)
1394   (let* ((name (first external-format))
1395          (out-function (symbolicate "OUTPUT-BYTES/" name))
1396          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1397          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1398          (in-char-function (symbolicate "INPUT-CHAR/" name))
1399          (resync-function (symbolicate "RESYNC/" name))
1400          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1401          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1402          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1403          (n-buffer (gensym "BUFFER")))
1404     `(progn
1405       (defun ,size-function (byte)
1406         (declare (ignorable byte))
1407         ,out-size-expr)
1408       (defun ,out-function (stream string flush-p start end)
1409         (let ((start (or start 0))
1410               (end (or end (length string))))
1411           (declare (type index start end))
1412           (synchronize-stream-output stream)
1413           (unless (<= 0 start end (length string))
1414             (signal-bounding-indices-bad-error string start end))
1415           (do ()
1416               ((= end start))
1417             (let ((obuf (fd-stream-obuf stream)))
1418               (setf (buffer-tail obuf)
1419                     (string-dispatch (simple-base-string
1420                                       #!+sb-unicode
1421                                       (simple-array character (*))
1422                                       string)
1423                         string
1424                       (let ((len (buffer-length obuf))
1425                             (sap (buffer-sap obuf))
1426                             ;; FIXME: Rename
1427                             (tail (buffer-tail obuf)))
1428                         (declare (type index tail)
1429                                  ;; STRING bounds have already been checked.
1430                                  (optimize (safety 0)))
1431                         (loop
1432                           (,@(if output-restart
1433                                  `(catch 'output-nothing)
1434                                  `(progn))
1435                              (do* ()
1436                                   ((or (= start end) (< (- len tail) 4)))
1437                                (let* ((byte (aref string start))
1438                                       (bits (char-code byte))
1439                                       (size ,out-size-expr))
1440                                  ,out-expr
1441                                  (incf tail size)
1442                                  (incf start)))
1443                              ;; Exited from the loop normally
1444                              (return tail))
1445                           ;; Exited via CATCH. Skip the current character
1446                           ;; and try the inner loop again.
1447                           (incf start))))))
1448             (when (< start end)
1449               (flush-output-buffer stream)))
1450           (when flush-p
1451             (flush-output-buffer stream))))
1452       (def-output-routines/variable-width (,format
1453                                            ,out-size-expr
1454                                            ,output-restart
1455                                            ,external-format
1456                                            (:none character)
1457                                            (:line character)
1458                                            (:full character))
1459           (if (eql byte #\Newline)
1460               (setf (fd-stream-char-pos stream) 0)
1461               (incf (fd-stream-char-pos stream)))
1462         (let ((bits (char-code byte))
1463               (sap (buffer-sap obuf))
1464               (tail (buffer-tail obuf)))
1465           ,out-expr))
1466       (defun ,in-function (stream buffer start requested eof-error-p
1467                            &aux (total-copied 0))
1468         (declare (type fd-stream stream)
1469                  (type index start requested total-copied)
1470                  (type
1471                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1472                   buffer))
1473         (let ((unread (fd-stream-unread stream)))
1474           (when unread
1475             (setf (aref buffer start) unread)
1476             (setf (fd-stream-unread stream) nil)
1477             (setf (fd-stream-listen stream) nil)
1478             (incf total-copied)))
1479         (do ()
1480             (nil)
1481           (let* ((ibuf (fd-stream-ibuf stream))
1482                  (head (buffer-head ibuf))
1483                  (tail (buffer-tail ibuf))
1484                  (sap (buffer-sap ibuf))
1485                  (decode-break-reason nil))
1486             (declare (type index head tail))
1487             ;; Copy data from stream buffer into user's buffer.
1488             (do ((size nil nil))
1489                 ((or (= tail head) (= requested total-copied)))
1490               (setf decode-break-reason
1491                     (block decode-break-reason
1492                       (let ((byte (sap-ref-8 sap head)))
1493                         (declare (ignorable byte))
1494                         (setq size ,in-size-expr)
1495                         (when (> size (- tail head))
1496                           (return))
1497                         (setf (aref buffer (+ start total-copied)) ,in-expr)
1498                         (incf total-copied)
1499                         (incf head size))
1500                       nil))
1501               (setf (buffer-head ibuf) head)
1502               (when decode-break-reason
1503                 ;; If we've already read some characters on when the invalid
1504                 ;; code sequence is detected, we return immediately. The
1505                 ;; handling of the error is deferred until the next call
1506                 ;; (where this check will be false). This allows establishing
1507                 ;; high-level handlers for decode errors (for example
1508                 ;; automatically resyncing in Lisp comments).
1509                 (when (plusp total-copied)
1510                   (return-from ,in-function total-copied))
1511                 (when (stream-decoding-error-and-handle
1512                        stream decode-break-reason)
1513                   (if eof-error-p
1514                       (error 'end-of-file :stream stream)
1515                       (return-from ,in-function total-copied)))
1516                 (setf head (buffer-head ibuf))
1517                 (setf tail (buffer-tail ibuf))))
1518             (setf (buffer-head ibuf) head)
1519             ;; Maybe we need to refill the stream buffer.
1520             (cond ( ;; If there were enough data in the stream buffer, we're done.
1521                    (= total-copied requested)
1522                    (return total-copied))
1523                   ( ;; If EOF, we're done in another way.
1524                    (or (eq decode-break-reason 'eof)
1525                        (null (catch 'eof-input-catcher
1526                                (refill-input-buffer stream))))
1527                    (if eof-error-p
1528                        (error 'end-of-file :stream stream)
1529                        (return total-copied)))
1530                   ;; Otherwise we refilled the stream buffer, so fall
1531                   ;; through into another pass of the loop.
1532                   ))))
1533       (def-input-routine/variable-width ,in-char-function (character
1534                                                            ,external-format
1535                                                            ,in-size-expr
1536                                                            sap head)
1537         (let ((byte (sap-ref-8 sap head)))
1538           (declare (ignorable byte))
1539           ,in-expr))
1540       (defun ,resync-function (stream)
1541         (let ((ibuf (fd-stream-ibuf stream)))
1542           (loop
1543             (input-at-least stream 2)
1544             (incf (buffer-head ibuf))
1545             (unless (block decode-break-reason
1546                       (let* ((sap (buffer-sap ibuf))
1547                              (head (buffer-head ibuf))
1548                              (byte (sap-ref-8 sap head))
1549                              (size ,in-size-expr))
1550                         (declare (ignorable byte))
1551                         (input-at-least stream size)
1552                         (setf head (buffer-head ibuf))
1553                         ,in-expr)
1554                      nil)
1555              (return)))))
1556       (defun ,read-c-string-function (sap element-type)
1557         (declare (type system-area-pointer sap))
1558         (locally
1559             (declare (optimize (speed 3) (safety 0)))
1560           (let* ((stream ,name)
1561                  (size 0) (head 0) (byte 0) (char nil)
1562                  (decode-break-reason nil)
1563                  (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1564                            (setf decode-break-reason
1565                                  (block decode-break-reason
1566                                    (setf byte (sap-ref-8 sap head)
1567                                          size ,in-size-expr
1568                                          char ,in-expr)
1569                                    (incf head size)
1570                                    nil))
1571                            (when decode-break-reason
1572                              (c-string-decoding-error ,name decode-break-reason))
1573                            (when (zerop (char-code char))
1574                              (return count))))
1575                  (string (make-string length :element-type element-type)))
1576             (declare (ignorable stream)
1577                      (type index head length) ;; size
1578                      (type (unsigned-byte 8) byte)
1579                      (type (or null character) char)
1580                      (type string string))
1581             (setf head 0)
1582             (dotimes (index length string)
1583               (setf decode-break-reason
1584                     (block decode-break-reason
1585                       (setf byte (sap-ref-8 sap head)
1586                             size ,in-size-expr
1587                             char ,in-expr)
1588                       (incf head size)
1589                       nil))
1590               (when decode-break-reason
1591                 (c-string-decoding-error ,name decode-break-reason))
1592               (setf (aref string index) char)))))
1593
1594       (defun ,output-c-string-function (string)
1595         (declare (type simple-string string))
1596         (locally
1597             (declare (optimize (speed 3) (safety 0)))
1598           (let* ((length (length string))
1599                  (char-length (make-array (1+ length) :element-type 'index))
1600                  (buffer-length
1601                   (+ (loop for i of-type index below length
1602                         for byte of-type character = (aref string i)
1603                         for bits = (char-code byte)
1604                         sum (setf (aref char-length i)
1605                                   (the index ,out-size-expr)))
1606                      (let* ((byte (code-char 0))
1607                             (bits (char-code byte)))
1608                        (declare (ignorable byte bits))
1609                        (setf (aref char-length length)
1610                              (the index ,out-size-expr)))))
1611                  (tail 0)
1612                  (,n-buffer (make-array buffer-length
1613                                         :element-type '(unsigned-byte 8)))
1614                  stream)
1615             (declare (type index length buffer-length tail)
1616                      (type null stream)
1617                      (ignorable stream))
1618             (with-pinned-objects (,n-buffer)
1619               (let ((sap (vector-sap ,n-buffer)))
1620                 (declare (system-area-pointer sap))
1621                 (loop for i of-type index below length
1622                       for byte of-type character = (aref string i)
1623                       for bits = (char-code byte)
1624                       for size of-type index = (aref char-length i)
1625                       do (prog1
1626                              ,out-expr
1627                            (incf tail size)))
1628                 (let* ((bits 0)
1629                        (byte (code-char bits))
1630                        (size (aref char-length length)))
1631                   (declare (ignorable bits byte size))
1632                   ,out-expr)))
1633             ,n-buffer)))
1634
1635       (setf *external-formats*
1636        (cons '(,external-format ,in-function ,in-char-function ,out-function
1637                ,@(mapcar #'(lambda (buffering)
1638                              (intern (format nil format (string buffering))))
1639                          '(:none :line :full))
1640                ,resync-function
1641                ,size-function ,read-c-string-function ,output-c-string-function)
1642         *external-formats*)))))
1643
1644 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1645 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1646 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1647 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1648     1 t
1649   (if (>= bits 256)
1650       (external-format-encoding-error stream bits)
1651       (setf (sap-ref-8 sap tail) bits))
1652   (code-char byte))
1653
1654 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1655                          :iso-646 :iso-646-us :|646|)
1656     1 t
1657   (if (>= bits 128)
1658       (external-format-encoding-error stream bits)
1659       (setf (sap-ref-8 sap tail) bits))
1660   (code-char byte))
1661
1662 (let* ((table (let ((s (make-string 256)))
1663                 (map-into s #'code-char
1664                           '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1665                             #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1666                             #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1667                             #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1668                             #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1669                             #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1670                             #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1671                             #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1672                             #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1673                             #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1674                             #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1675                             #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1676                             #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1677                             #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1678                             #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1679                             #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1680                 s))
1681        (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1682                           (loop for char across table for i from 0
1683                                do (aver (= 0 (aref rt (char-code char))))
1684                                do (setf (aref rt (char-code char)) i))
1685                           rt)))
1686   (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1687       1 t
1688     (if (>= bits 256)
1689         (external-format-encoding-error stream bits)
1690         (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1691     (aref table byte)))
1692
1693
1694 #!+sb-unicode
1695 (let ((latin-9-table (let ((table (make-string 256)))
1696                        (do ((i 0 (1+ i)))
1697                            ((= i 256))
1698                          (setf (aref table i) (code-char i)))
1699                        (setf (aref table #xa4) (code-char #x20ac))
1700                        (setf (aref table #xa6) (code-char #x0160))
1701                        (setf (aref table #xa8) (code-char #x0161))
1702                        (setf (aref table #xb4) (code-char #x017d))
1703                        (setf (aref table #xb8) (code-char #x017e))
1704                        (setf (aref table #xbc) (code-char #x0152))
1705                        (setf (aref table #xbd) (code-char #x0153))
1706                        (setf (aref table #xbe) (code-char #x0178))
1707                        table))
1708       (latin-9-reverse-1 (make-array 16
1709                                      :element-type '(unsigned-byte 21)
1710                                      :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1711       (latin-9-reverse-2 (make-array 16
1712                                      :element-type '(unsigned-byte 8)
1713                                      :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1714   (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1715       1 t
1716     (setf (sap-ref-8 sap tail)
1717           (if (< bits 256)
1718               (if (= bits (char-code (aref latin-9-table bits)))
1719                   bits
1720                   (external-format-encoding-error stream byte))
1721               (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1722                   (aref latin-9-reverse-2 (logand bits 15))
1723                   (external-format-encoding-error stream byte))))
1724     (aref latin-9-table byte)))
1725
1726 (define-external-format/variable-width (:utf-8 :utf8) nil
1727   (let ((bits (char-code byte)))
1728     (cond ((< bits #x80) 1)
1729           ((< bits #x800) 2)
1730           ((< bits #x10000) 3)
1731           (t 4)))
1732   (ecase size
1733     (1 (setf (sap-ref-8 sap tail) bits))
1734     (2 (setf (sap-ref-8 sap tail)       (logior #xc0 (ldb (byte 5 6) bits))
1735              (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1736     (3 (setf (sap-ref-8 sap tail)       (logior #xe0 (ldb (byte 4 12) bits))
1737              (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 6) bits))
1738              (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1739     (4 (setf (sap-ref-8 sap tail)       (logior #xf0 (ldb (byte 3 18) bits))
1740              (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 12) bits))
1741              (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1742              (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1743   (cond ((< byte #x80) 1)
1744         ((< byte #xc2) (return-from decode-break-reason 1))
1745         ((< byte #xe0) 2)
1746         ((< byte #xf0) 3)
1747         (t 4))
1748   (code-char (ecase size
1749                (1 byte)
1750                (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1751                     (unless (<= #x80 byte2 #xbf)
1752                       (return-from decode-break-reason 2))
1753                     (dpb byte (byte 5 6) byte2)))
1754                (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1755                         (byte3 (sap-ref-8 sap (+ 2 head))))
1756                     (unless (and (<= #x80 byte2 #xbf)
1757                                  (<= #x80 byte3 #xbf))
1758                       (return-from decode-break-reason 3))
1759                     (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1760                (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1761                         (byte3 (sap-ref-8 sap (+ 2 head)))
1762                         (byte4 (sap-ref-8 sap (+ 3 head))))
1763                     (unless (and (<= #x80 byte2 #xbf)
1764                                  (<= #x80 byte3 #xbf)
1765                                  (<= #x80 byte4 #xbf))
1766                       (return-from decode-break-reason 4))
1767                     (dpb byte (byte 3 18)
1768                          (dpb byte2 (byte 6 12)
1769                               (dpb byte3 (byte 6 6) byte4))))))))
1770 \f
1771 ;;;; utility functions (misc routines, etc)
1772
1773 ;;; Fill in the various routine slots for the given type. INPUT-P and
1774 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1775 ;;; set prior to calling this routine.
1776 (defun set-fd-stream-routines (fd-stream element-type external-format
1777                                input-p output-p buffer-p)
1778   (let* ((target-type (case element-type
1779                         (unsigned-byte '(unsigned-byte 8))
1780                         (signed-byte '(signed-byte 8))
1781                         (:default 'character)
1782                         (t element-type)))
1783          (character-stream-p (subtypep target-type 'character))
1784          (bivalent-stream-p (eq element-type :default))
1785          normalized-external-format
1786          (bin-routine #'ill-bin)
1787          (bin-type nil)
1788          (bin-size nil)
1789          (cin-routine #'ill-in)
1790          (cin-type nil)
1791          (cin-size nil)
1792          (input-type nil)           ;calculated from bin-type/cin-type
1793          (input-size nil)           ;calculated from bin-size/cin-size
1794          (read-n-characters #'ill-in)
1795          (bout-routine #'ill-bout)
1796          (bout-type nil)
1797          (bout-size nil)
1798          (cout-routine #'ill-out)
1799          (cout-type nil)
1800          (cout-size nil)
1801          (output-type nil)
1802          (output-size nil)
1803          (output-bytes #'ill-bout))
1804
1805     ;; Ensure that we have buffers in the desired direction(s) only,
1806     ;; getting new ones and dropping/resetting old ones as necessary.
1807     (let ((obuf (fd-stream-obuf fd-stream)))
1808       (if output-p
1809           (if obuf
1810               (reset-buffer obuf)
1811               (setf (fd-stream-obuf fd-stream) (get-buffer)))
1812           (when obuf
1813             (setf (fd-stream-obuf fd-stream) nil)
1814             (release-buffer obuf))))
1815
1816     (let ((ibuf (fd-stream-ibuf fd-stream)))
1817       (if input-p
1818           (if ibuf
1819               (reset-buffer ibuf)
1820               (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1821           (when ibuf
1822             (setf (fd-stream-ibuf fd-stream) nil)
1823             (release-buffer ibuf))))
1824
1825     ;; FIXME: Why only for output? Why unconditionally?
1826     (when output-p
1827       (setf (fd-stream-char-pos fd-stream) 0))
1828
1829     (when (and character-stream-p
1830                (eq external-format :default))
1831       (/show0 "/getting default external format")
1832       (setf external-format (default-external-format)))
1833
1834     (when input-p
1835       (when (or (not character-stream-p) bivalent-stream-p)
1836         (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1837                                           normalized-external-format)
1838           (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1839                                   target-type)
1840                               external-format))
1841         (unless bin-routine
1842           (error "could not find any input routine for ~S" target-type)))
1843       (when character-stream-p
1844         (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1845                                           normalized-external-format)
1846           (pick-input-routine target-type external-format))
1847         (unless cin-routine
1848           (error "could not find any input routine for ~S" target-type)))
1849       (setf (fd-stream-in fd-stream) cin-routine
1850             (fd-stream-bin fd-stream) bin-routine)
1851       ;; character type gets preferential treatment
1852       (setf input-size (or cin-size bin-size))
1853       (setf input-type (or cin-type bin-type))
1854       (when normalized-external-format
1855         (setf (fd-stream-external-format fd-stream)
1856               normalized-external-format))
1857       (when (= (or cin-size 1) (or bin-size 1) 1)
1858         (setf (fd-stream-n-bin fd-stream) ;XXX
1859               (if (and character-stream-p (not bivalent-stream-p))
1860                   read-n-characters
1861                   #'fd-stream-read-n-bytes))
1862         ;; Sometimes turn on fast-read-char/fast-read-byte.  Switch on
1863         ;; for character and (unsigned-byte 8) streams.  In these
1864         ;; cases, fast-read-* will read from the
1865         ;; ansi-stream-(c)in-buffer, saving function calls.
1866         ;; Otherwise, the various data-reading functions in the stream
1867         ;; structure will be called.
1868         (when (and buffer-p
1869                    (not bivalent-stream-p)
1870                    ;; temporary disable on :io streams
1871                    (not output-p))
1872           (cond (character-stream-p
1873                  (setf (ansi-stream-cin-buffer fd-stream)
1874                        (make-array +ansi-stream-in-buffer-length+
1875                                    :element-type 'character)))
1876                 ((equal target-type '(unsigned-byte 8))
1877                  (setf (ansi-stream-in-buffer fd-stream)
1878                        (make-array +ansi-stream-in-buffer-length+
1879                                    :element-type '(unsigned-byte 8))))))))
1880
1881     (when output-p
1882       (when (or (not character-stream-p) bivalent-stream-p)
1883         (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1884                                            normalized-external-format)
1885           (pick-output-routine (if bivalent-stream-p
1886                                    '(unsigned-byte 8)
1887                                    target-type)
1888                                (fd-stream-buffering fd-stream)
1889                                external-format))
1890         (unless bout-routine
1891           (error "could not find any output routine for ~S buffered ~S"
1892                  (fd-stream-buffering fd-stream)
1893                  target-type)))
1894       (when character-stream-p
1895         (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1896                                            normalized-external-format)
1897           (pick-output-routine target-type
1898                                (fd-stream-buffering fd-stream)
1899                                external-format))
1900         (unless cout-routine
1901           (error "could not find any output routine for ~S buffered ~S"
1902                  (fd-stream-buffering fd-stream)
1903                  target-type)))
1904       (when normalized-external-format
1905         (setf (fd-stream-external-format fd-stream)
1906               normalized-external-format))
1907       (when character-stream-p
1908         (setf (fd-stream-output-bytes fd-stream) output-bytes))
1909       (setf (fd-stream-out fd-stream) cout-routine
1910             (fd-stream-bout fd-stream) bout-routine
1911             (fd-stream-sout fd-stream) (if (eql cout-size 1)
1912                                            #'fd-sout #'ill-out))
1913       (setf output-size (or cout-size bout-size))
1914       (setf output-type (or cout-type bout-type)))
1915
1916     (when (and input-size output-size
1917                (not (eq input-size output-size)))
1918       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1919              input-type input-size
1920              output-type output-size))
1921     (setf (fd-stream-element-size fd-stream)
1922           (or input-size output-size))
1923
1924     (setf (fd-stream-element-type fd-stream)
1925           (cond ((equal input-type output-type)
1926                  input-type)
1927                 ((null output-type)
1928                  input-type)
1929                 ((null input-type)
1930                  output-type)
1931                 ((subtypep input-type output-type)
1932                  input-type)
1933                 ((subtypep output-type input-type)
1934                  output-type)
1935                 (t
1936                  (error "Input type (~S) and output type (~S) are unrelated?"
1937                         input-type
1938                         output-type))))))
1939
1940 ;;; Handles the resource-release aspects of stream closing.
1941 (defun release-fd-stream-resources (fd-stream)
1942   (handler-case
1943       (without-interrupts
1944         ;; Disable interrupts so that a asynch unwind will not leave
1945         ;; us with a dangling finalizer (that would close the same
1946         ;; --possibly reassigned-- FD again).
1947         (sb!unix:unix-close (fd-stream-fd fd-stream))
1948         (when (fboundp 'cancel-finalization)
1949           (cancel-finalization fd-stream)))
1950     ;; On error unwind from WITHOUT-INTERRUPTS.
1951     (serious-condition (e)
1952       (error e)))
1953
1954   ;; Release all buffers. If this is undone, or interrupted,
1955   ;; we're still safe: buffers have finalizers of their own.
1956   (release-fd-stream-buffers fd-stream))
1957
1958 ;;; Flushes the current input buffer and unread chatacter, and returns
1959 ;;; the input buffer, and the amount of of flushed input in bytes.
1960 (defun flush-input-buffer (stream)
1961   (let ((unread (if (fd-stream-unread stream)
1962                     1
1963                     0)))
1964     (setf (fd-stream-unread stream) nil)
1965     (let ((ibuf (fd-stream-ibuf stream)))
1966       (if ibuf
1967           (let ((head (buffer-head ibuf))
1968                 (tail (buffer-tail ibuf)))
1969             (values (reset-buffer ibuf) (- (+ unread tail) head)))
1970           (values nil unread)))))
1971
1972 (defun fd-stream-clear-input (stream)
1973   (flush-input-buffer stream)
1974   #!+win32
1975   (progn
1976     (sb!win32:fd-clear-input (fd-stream-fd stream))
1977     (setf (fd-stream-listen stream) nil))
1978   #!-win32
1979   (catch 'eof-input-catcher
1980     (loop until (sysread-may-block-p stream)
1981           do
1982           (refill-input-buffer stream)
1983           (reset-buffer (fd-stream-ibuf stream)))
1984     t))
1985
1986 ;;; Handle miscellaneous operations on FD-STREAM.
1987 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1988   (declare (ignore arg2))
1989   (case operation
1990     (:listen
1991      (labels ((do-listen ()
1992                 (let ((ibuf (fd-stream-ibuf fd-stream)))
1993                   (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1994                       (fd-stream-listen fd-stream)
1995                       #!+win32
1996                       (sb!win32:fd-listen (fd-stream-fd fd-stream))
1997                       #!-win32
1998                       ;; If the read can block, LISTEN will certainly return NIL.
1999                       (if (sysread-may-block-p fd-stream)
2000                           nil
2001                           ;; Otherwise select(2) and CL:LISTEN have slightly
2002                           ;; different semantics.  The former returns that an FD
2003                           ;; is readable when a read operation wouldn't block.
2004                           ;; That includes EOF.  However, LISTEN must return NIL
2005                           ;; at EOF.
2006                           (progn (catch 'eof-input-catcher
2007                                    ;; r-b/f too calls select, but it shouldn't
2008                                    ;; block as long as read can return once w/o
2009                                    ;; blocking
2010                                    (refill-input-buffer fd-stream))
2011                                  ;; At this point either IBUF-HEAD != IBUF-TAIL
2012                                  ;; and FD-STREAM-LISTEN is NIL, in which case
2013                                  ;; we should return T, or IBUF-HEAD ==
2014                                  ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2015                                  ;; which case we should return :EOF for this
2016                                  ;; call and all future LISTEN call on this stream.
2017                                  ;; Call ourselves again to determine which case
2018                                  ;; applies.
2019                                  (do-listen)))))))
2020        (do-listen)))
2021     (:unread
2022      (setf (fd-stream-unread fd-stream) arg1)
2023      (setf (fd-stream-listen fd-stream) t))
2024     (:close
2025      (cond (arg1                    ; We got us an abort on our hands.
2026             (when (fd-stream-handler fd-stream)
2027               (remove-fd-handler (fd-stream-handler fd-stream))
2028               (setf (fd-stream-handler fd-stream) nil))
2029             ;; We can't do anything unless we know what file were
2030             ;; dealing with, and we don't want to do anything
2031             ;; strange unless we were writing to the file.
2032             (when (and (fd-stream-file fd-stream) (fd-stream-obuf fd-stream))
2033               (if (fd-stream-original fd-stream)
2034                   ;; If the original is EQ to file we are appending
2035                   ;; and can just close the file without renaming.
2036                   (unless (eq (fd-stream-original fd-stream)
2037                               (fd-stream-file fd-stream))
2038                     ;; We have a handle on the original, just revert.
2039                     (multiple-value-bind (okay err)
2040                         (sb!unix:unix-rename (fd-stream-original fd-stream)
2041                                              (fd-stream-file fd-stream))
2042                       (unless okay
2043                         (simple-stream-perror
2044                          "couldn't restore ~S to its original contents"
2045                          fd-stream
2046                          err))))
2047                   ;; We can't restore the original, and aren't
2048                   ;; appending, so nuke that puppy.
2049                   ;;
2050                   ;; FIXME: This is currently the fate of superseded
2051                   ;; files, and according to the CLOSE spec this is
2052                   ;; wrong. However, there seems to be no clean way to
2053                   ;; do that that doesn't involve either copying the
2054                   ;; data (bad if the :abort resulted from a full
2055                   ;; disk), or renaming the old file temporarily
2056                   ;; (probably bad because stream opening becomes more
2057                   ;; racy).
2058                   (multiple-value-bind (okay err)
2059                       (sb!unix:unix-unlink (fd-stream-file fd-stream))
2060                     (unless okay
2061                       (error 'simple-file-error
2062                              :pathname (fd-stream-file fd-stream)
2063                              :format-control
2064                              "~@<couldn't remove ~S: ~2I~_~A~:>"
2065                              :format-arguments (list (fd-stream-file fd-stream)
2066                                                      (strerror err))))))))
2067            (t
2068             (finish-fd-stream-output fd-stream)
2069             (when (and (fd-stream-original fd-stream)
2070                        (fd-stream-delete-original fd-stream))
2071               (multiple-value-bind (okay err)
2072                   (sb!unix:unix-unlink (fd-stream-original fd-stream))
2073                 (unless okay
2074                   (error 'simple-file-error
2075                          :pathname (fd-stream-original fd-stream)
2076                          :format-control
2077                          "~@<couldn't delete ~S during close of ~S: ~
2078                           ~2I~_~A~:>"
2079                          :format-arguments
2080                          (list (fd-stream-original fd-stream)
2081                                fd-stream
2082                                (strerror err))))))))
2083      (release-fd-stream-resources fd-stream)
2084      ;; Mark as closed. FIXME: Maybe this should be the first thing done?
2085      (sb!impl::set-closed-flame fd-stream))
2086     (:clear-input
2087      (fd-stream-clear-input fd-stream))
2088     (:force-output
2089      (flush-output-buffer fd-stream))
2090     (:finish-output
2091      (finish-fd-stream-output fd-stream))
2092     (:element-type
2093      (fd-stream-element-type fd-stream))
2094     (:external-format
2095      (fd-stream-external-format fd-stream))
2096     (:interactive-p
2097      (= 1 (the (member 0 1)
2098             (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2099     (:line-length
2100      80)
2101     (:charpos
2102      (fd-stream-char-pos fd-stream))
2103     (:file-length
2104      (unless (fd-stream-file fd-stream)
2105        ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2106        ;; "should signal an error of type TYPE-ERROR if stream is not
2107        ;; a stream associated with a file". Too bad there's no very
2108        ;; appropriate value for the EXPECTED-TYPE slot..
2109        (error 'simple-type-error
2110               :datum fd-stream
2111               :expected-type 'fd-stream
2112               :format-control "~S is not a stream associated with a file."
2113               :format-arguments (list fd-stream)))
2114      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2115                                 atime mtime ctime blksize blocks)
2116          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2117        (declare (ignore ino nlink uid gid rdev
2118                         atime mtime ctime blksize blocks))
2119        (unless okay
2120          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2121        (if (zerop mode)
2122            nil
2123            (truncate size (fd-stream-element-size fd-stream)))))
2124     (:file-string-length
2125      (etypecase arg1
2126        (character (fd-stream-character-size fd-stream arg1))
2127        (string (fd-stream-string-size fd-stream arg1))))
2128     (:file-position
2129      (if arg1
2130          (fd-stream-set-file-position fd-stream arg1)
2131          (fd-stream-get-file-position fd-stream)))))
2132
2133 ;; FIXME: Think about this.
2134 ;;
2135 ;; (defun finish-fd-stream-output (fd-stream)
2136 ;;   (let ((timeout (fd-stream-timeout fd-stream)))
2137 ;;     (loop while (fd-stream-output-queue fd-stream)
2138 ;;        ;; FIXME: SIGINT while waiting for a timeout will
2139 ;;        ;; cause a timeout here.
2140 ;;        do (when (and (not (serve-event timeout)) timeout)
2141 ;;             (signal-timeout 'io-timeout
2142 ;;                             :stream fd-stream
2143 ;;                             :direction :write
2144 ;;                             :seconds timeout)))))
2145
2146 (defun finish-fd-stream-output (stream)
2147   (flush-output-buffer stream)
2148   (do ()
2149       ((null (fd-stream-output-queue stream)))
2150     (serve-all-events)))
2151
2152 (defun fd-stream-get-file-position (stream)
2153   (declare (fd-stream stream))
2154   (without-interrupts
2155     (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2156       (declare (type (or (alien sb!unix:off-t) null) posn))
2157       ;; We used to return NIL for errno==ESPIPE, and signal an error
2158       ;; in other failure cases. However, CLHS says to return NIL if
2159       ;; the position cannot be determined -- so that's what we do.
2160       (when (integerp posn)
2161         ;; Adjust for buffered output: If there is any output
2162         ;; buffered, the *real* file position will be larger
2163         ;; than reported by lseek() because lseek() obviously
2164         ;; cannot take into account output we have not sent
2165         ;; yet.
2166         (dolist (buffer (fd-stream-output-queue stream))
2167           (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2168         (let ((obuf (fd-stream-obuf stream)))
2169           (when obuf
2170             (incf posn (buffer-tail obuf))))
2171         ;; Adjust for unread input: If there is any input
2172         ;; read from UNIX but not supplied to the user of the
2173         ;; stream, the *real* file position will smaller than
2174         ;; reported, because we want to look like the unread
2175         ;; stuff is still available.
2176         (let ((ibuf (fd-stream-ibuf stream)))
2177           (when ibuf
2178             (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2179         (when (fd-stream-unread stream)
2180           (decf posn))
2181         ;; Divide bytes by element size.
2182         (truncate posn (fd-stream-element-size stream))))))
2183
2184 (defun fd-stream-set-file-position (stream position-spec)
2185   (declare (fd-stream stream))
2186   (check-type position-spec
2187               (or (alien sb!unix:off-t) (member nil :start :end))
2188               "valid file position designator")
2189   (tagbody
2190    :again
2191      ;; Make sure we don't have any output pending, because if we
2192      ;; move the file pointer before writing this stuff, it will be
2193      ;; written in the wrong location.
2194      (finish-fd-stream-output stream)
2195      ;; Disable interrupts so that interrupt handlers doing output
2196      ;; won't screw us.
2197      (without-interrupts
2198        (unless (fd-stream-output-finished-p stream)
2199          ;; We got interrupted and more output came our way during
2200          ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2201          ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2202          ;; so we prefer to do things like this...
2203          (go :again))
2204        ;; Clear out any pending input to force the next read to go to
2205        ;; the disk.
2206        (flush-input-buffer stream)
2207        ;; Trash cached value for listen, so that we check next time.
2208        (setf (fd-stream-listen stream) nil)
2209          ;; Now move it.
2210          (multiple-value-bind (offset origin)
2211              (case position-spec
2212                (:start
2213                 (values 0 sb!unix:l_set))
2214                (:end
2215                 (values 0 sb!unix:l_xtnd))
2216                (t
2217                 (values (* position-spec (fd-stream-element-size stream))
2218                         sb!unix:l_set)))
2219            (declare (type (alien sb!unix:off-t) offset))
2220            (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2221                                            offset origin)))
2222              ;; CLHS says to return true if the file-position was set
2223              ;; succesfully, and NIL otherwise. We are to signal an error
2224              ;; only if the given position was out of bounds, and that is
2225              ;; dealt with above. In times past we used to return NIL for
2226              ;; errno==ESPIPE, and signal an error in other cases.
2227              ;;
2228              ;; FIXME: We are still liable to signal an error if flushing
2229              ;; output fails.
2230              (return-from fd-stream-set-file-position
2231                (typep posn '(alien sb!unix:off-t))))))))
2232
2233 \f
2234 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2235
2236 ;;; Create a stream for the given Unix file descriptor.
2237 ;;;
2238 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2239 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2240 ;;; default to allowing input.
2241 ;;;
2242 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2243 ;;;
2244 ;;; BUFFERING indicates the kind of buffering to use.
2245 ;;;
2246 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2247 ;;; NIL (the default), then wait forever. When we time out, we signal
2248 ;;; IO-TIMEOUT.
2249 ;;;
2250 ;;; FILE is the name of the file (will be returned by PATHNAME).
2251 ;;;
2252 ;;; NAME is used to identify the stream when printed.
2253 (defun make-fd-stream (fd
2254                        &key
2255                        (input nil input-p)
2256                        (output nil output-p)
2257                        (element-type 'base-char)
2258                        (buffering :full)
2259                        (external-format :default)
2260                        timeout
2261                        file
2262                        original
2263                        delete-original
2264                        pathname
2265                        input-buffer-p
2266                        dual-channel-p
2267                        (name (if file
2268                                  (format nil "file ~A" file)
2269                                  (format nil "descriptor ~W" fd)))
2270                        auto-close)
2271   (declare (type index fd) (type (or real null) timeout)
2272            (type (member :none :line :full) buffering))
2273   (cond ((not (or input-p output-p))
2274          (setf input t))
2275         ((not (or input output))
2276          (error "File descriptor must be opened either for input or output.")))
2277   (let ((stream (%make-fd-stream :fd fd
2278                                  :name name
2279                                  :file file
2280                                  :original original
2281                                  :delete-original delete-original
2282                                  :pathname pathname
2283                                  :buffering buffering
2284                                  :dual-channel-p dual-channel-p
2285                                  :external-format external-format
2286                                  :timeout
2287                                  (if timeout
2288                                      (coerce timeout 'single-float)
2289                                      nil))))
2290     (set-fd-stream-routines stream element-type external-format
2291                             input output input-buffer-p)
2292     (when (and auto-close (fboundp 'finalize))
2293       (finalize stream
2294                 (lambda ()
2295                   (sb!unix:unix-close fd)
2296                   #!+sb-show
2297                   (format *terminal-io* "** closed file descriptor ~W **~%"
2298                           fd))
2299                 :dont-save t))
2300     stream))
2301
2302 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2303 ;;; :RENAME-AND-DELETE and :RENAME options.
2304 (defun pick-backup-name (name)
2305   (declare (type simple-string name))
2306   (concatenate 'simple-string name ".bak"))
2307
2308 ;;; Ensure that the given arg is one of the given list of valid
2309 ;;; things. Allow the user to fix any problems.
2310 (defun ensure-one-of (item list what)
2311   (unless (member item list)
2312     (error 'simple-type-error
2313            :datum item
2314            :expected-type `(member ,@list)
2315            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2316            :format-arguments (list item what list))))
2317
2318 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2319 ;;; access, since we don't want to trash unwritable files even if we
2320 ;;; technically can. We return true if we succeed in renaming.
2321 (defun rename-the-old-one (namestring original)
2322   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2323     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2324   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2325     (if okay
2326         t
2327         (error 'simple-file-error
2328                :pathname namestring
2329                :format-control
2330                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2331                :format-arguments (list namestring original (strerror err))))))
2332
2333 (defun open (filename
2334              &key
2335              (direction :input)
2336              (element-type 'base-char)
2337              (if-exists nil if-exists-given)
2338              (if-does-not-exist nil if-does-not-exist-given)
2339              (external-format :default)
2340              &aux ; Squelch assignment warning.
2341              (direction direction)
2342              (if-does-not-exist if-does-not-exist)
2343              (if-exists if-exists))
2344   #!+sb-doc
2345   "Return a stream which reads from or writes to FILENAME.
2346   Defined keywords:
2347    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2348    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2349    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2350                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2351    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2352   See the manual for details."
2353
2354   ;; Calculate useful stuff.
2355   (multiple-value-bind (input output mask)
2356       (case direction
2357         (:input  (values   t nil sb!unix:o_rdonly))
2358         (:output (values nil   t sb!unix:o_wronly))
2359         (:io     (values   t   t sb!unix:o_rdwr))
2360         (:probe  (values   t nil sb!unix:o_rdonly)))
2361     (declare (type index mask))
2362     (let* ((pathname (merge-pathnames filename))
2363            (namestring
2364             (cond ((unix-namestring pathname input))
2365                   ((and input (eq if-does-not-exist :create))
2366                    (unix-namestring pathname nil))
2367                   ((and (eq direction :io) (not if-does-not-exist-given))
2368                    (unix-namestring pathname nil)))))
2369       ;; Process if-exists argument if we are doing any output.
2370       (cond (output
2371              (unless if-exists-given
2372                (setf if-exists
2373                      (if (eq (pathname-version pathname) :newest)
2374                          :new-version
2375                          :error)))
2376              (ensure-one-of if-exists
2377                             '(:error :new-version :rename
2378                                      :rename-and-delete :overwrite
2379                                      :append :supersede nil)
2380                             :if-exists)
2381              (case if-exists
2382                ((:new-version :error nil)
2383                 (setf mask (logior mask sb!unix:o_excl)))
2384                ((:rename :rename-and-delete)
2385                 (setf mask (logior mask sb!unix:o_creat)))
2386                ((:supersede)
2387                 (setf mask (logior mask sb!unix:o_trunc)))
2388                (:append
2389                 (setf mask (logior mask sb!unix:o_append)))))
2390             (t
2391              (setf if-exists :ignore-this-arg)))
2392
2393       (unless if-does-not-exist-given
2394         (setf if-does-not-exist
2395               (cond ((eq direction :input) :error)
2396                     ((and output
2397                           (member if-exists '(:overwrite :append)))
2398                      :error)
2399                     ((eq direction :probe)
2400                      nil)
2401                     (t
2402                      :create))))
2403       (ensure-one-of if-does-not-exist
2404                      '(:error :create nil)
2405                      :if-does-not-exist)
2406       (if (eq if-does-not-exist :create)
2407         (setf mask (logior mask sb!unix:o_creat)))
2408
2409       (let ((original (case if-exists
2410                         ((:rename :rename-and-delete)
2411                          (pick-backup-name namestring))
2412                         ((:append :overwrite)
2413                          ;; KLUDGE: Provent CLOSE from deleting
2414                          ;; appending streams when called with :ABORT T
2415                          namestring)))
2416             (delete-original (eq if-exists :rename-and-delete))
2417             (mode #o666))
2418         (when (and original (not (eq original namestring)))
2419           ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2420           ;; whether the file already exists, make sure the original
2421           ;; file is not a directory, and keep the mode.
2422           (let ((exists
2423                  (and namestring
2424                       (multiple-value-bind (okay err/dev inode orig-mode)
2425                           (sb!unix:unix-stat namestring)
2426                         (declare (ignore inode)
2427                                  (type (or index null) orig-mode))
2428                         (cond
2429                          (okay
2430                           (when (and output (= (logand orig-mode #o170000)
2431                                                #o40000))
2432                             (error 'simple-file-error
2433                                    :pathname namestring
2434                                    :format-control
2435                                    "can't open ~S for output: is a directory"
2436                                    :format-arguments (list namestring)))
2437                           (setf mode (logand orig-mode #o777))
2438                           t)
2439                          ((eql err/dev sb!unix:enoent)
2440                           nil)
2441                          (t
2442                           (simple-file-perror "can't find ~S"
2443                                               namestring
2444                                               err/dev)))))))
2445             (unless (and exists
2446                          (rename-the-old-one namestring original))
2447               (setf original nil)
2448               (setf delete-original nil)
2449               ;; In order to use :SUPERSEDE instead, we have to make
2450               ;; sure SB!UNIX:O_CREAT corresponds to
2451               ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2452               ;; because of IF-EXISTS being :RENAME.
2453               (unless (eq if-does-not-exist :create)
2454                 (setf mask
2455                       (logior (logandc2 mask sb!unix:o_creat)
2456                               sb!unix:o_trunc)))
2457               (setf if-exists :supersede))))
2458
2459         ;; Now we can try the actual Unix open(2).
2460         (multiple-value-bind (fd errno)
2461             (if namestring
2462                 (sb!unix:unix-open namestring mask mode)
2463                 (values nil sb!unix:enoent))
2464           (labels ((open-error (format-control &rest format-arguments)
2465                      (error 'simple-file-error
2466                             :pathname pathname
2467                             :format-control format-control
2468                             :format-arguments format-arguments))
2469                    (vanilla-open-error ()
2470                      (simple-file-perror "error opening ~S" pathname errno)))
2471             (cond ((numberp fd)
2472                    (case direction
2473                      ((:input :output :io)
2474                       (make-fd-stream fd
2475                                       :input input
2476                                       :output output
2477                                       :element-type element-type
2478                                       :external-format external-format
2479                                       :file namestring
2480                                       :original original
2481                                       :delete-original delete-original
2482                                       :pathname pathname
2483                                       :dual-channel-p nil
2484                                       :input-buffer-p t
2485                                       :auto-close t))
2486                      (:probe
2487                       (let ((stream
2488                              (%make-fd-stream :name namestring
2489                                               :fd fd
2490                                               :pathname pathname
2491                                               :element-type element-type)))
2492                         (close stream)
2493                         stream))))
2494                   ((eql errno sb!unix:enoent)
2495                    (case if-does-not-exist
2496                      (:error (vanilla-open-error))
2497                      (:create
2498                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2499                                   pathname))
2500                      (t nil)))
2501                   ((and (eql errno sb!unix:eexist) (null if-exists))
2502                    nil)
2503                   (t
2504                    (vanilla-open-error)))))))))
2505 \f
2506 ;;;; initialization
2507
2508 ;;; the stream connected to the controlling terminal, or NIL if there is none
2509 (defvar *tty*)
2510
2511 ;;; the stream connected to the standard input (file descriptor 0)
2512 (defvar *stdin*)
2513
2514 ;;; the stream connected to the standard output (file descriptor 1)
2515 (defvar *stdout*)
2516
2517 ;;; the stream connected to the standard error output (file descriptor 2)
2518 (defvar *stderr*)
2519
2520 ;;; This is called when the cold load is first started up, and may also
2521 ;;; be called in an attempt to recover from nested errors.
2522 (defun stream-cold-init-or-reset ()
2523   (stream-reinit)
2524   (setf *terminal-io* (make-synonym-stream '*tty*))
2525   (setf *standard-output* (make-synonym-stream '*stdout*))
2526   (setf *standard-input* (make-synonym-stream '*stdin*))
2527   (setf *error-output* (make-synonym-stream '*stderr*))
2528   (setf *query-io* (make-synonym-stream '*terminal-io*))
2529   (setf *debug-io* *query-io*)
2530   (setf *trace-output* *standard-output*)
2531   (values))
2532
2533 (defun stream-deinit ()
2534   ;; Unbind to make sure we're not accidently dealing with it
2535   ;; before we're ready (or after we think it's been deinitialized).
2536   (with-available-buffers-lock ()
2537     (without-package-locks
2538         (makunbound '*available-buffers*))))
2539
2540 ;;; This is called whenever a saved core is restarted.
2541 (defun stream-reinit (&optional init-buffers-p)
2542   (when init-buffers-p
2543     (with-available-buffers-lock ()
2544       (aver (not (boundp '*available-buffers*)))
2545       (setf *available-buffers* nil)))
2546   (with-output-to-string (*error-output*)
2547     (setf *stdin*
2548           (make-fd-stream 0 :name "standard input" :input t :buffering :line
2549                             #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2550     (setf *stdout*
2551           (make-fd-stream 1 :name "standard output" :output t :buffering :line
2552                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2553     (setf *stderr*
2554           (make-fd-stream 2 :name "standard error" :output t :buffering :line
2555                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2556     (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2557            (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2558       (if tty
2559           (setf *tty*
2560                 (make-fd-stream tty
2561                                 :name "the terminal"
2562                                 :input t
2563                                 :output t
2564                                 :buffering :line
2565                                 :auto-close t))
2566           (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2567     (princ (get-output-stream-string *error-output*) *stderr*))
2568   (values))
2569 \f
2570 ;;;; miscellany
2571
2572 ;;; the Unix way to beep
2573 (defun beep (stream)
2574   (write-char (code-char bell-char-code) stream)
2575   (finish-output stream))
2576
2577 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2578 ;;; by the filesys stuff to get and set the file name.
2579 ;;;
2580 ;;; FIXME: misleading name, screwy interface
2581 (defun file-name (stream &optional new-name)
2582   (when (typep stream 'fd-stream)
2583       (cond (new-name
2584              (setf (fd-stream-pathname stream) new-name)
2585              (setf (fd-stream-file stream)
2586                    (unix-namestring new-name nil))
2587              t)
2588             (t
2589              (fd-stream-pathname stream)))))