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