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