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