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