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