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