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