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