1 ;;;; streams for UNIX file descriptors
3 ;;;; This software is part of the SBCL system. See the README file for
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.
12 (in-package "SB!IMPL")
14 ;;;; buffer manipulation routines
16 ;;; FIXME: Is it really good to maintain this pool separate from the
17 ;;; GC and the C malloc logic?
18 (defvar *available-buffers* ()
20 "List of available buffers. Each buffer is an sap pointing to
21 bytes-per-buffer of memory.")
24 (defvar *available-buffers-mutex* (sb!thread:make-mutex
25 :name "lock for *AVAILABLE-BUFFERS*")
27 "Mutex for access to *AVAILABLE-BUFFERS*.")
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
34 (sb!thread:with-mutex (*available-buffers-mutex*)
37 (defconstant bytes-per-buffer (* 4 1024)
39 "Number of bytes per buffer.")
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))))
49 ;;;; the FD-STREAM structure
52 (:constructor %make-fd-stream)
53 (:conc-name fd-stream-)
54 (:predicate fd-stream-p)
56 (misc #'fd-stream-misc-routine))
59 ;; the name of this stream
61 ;; the file this stream is for
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
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.
80 ;; character position if known -- this may run into bignums, but
81 ;; we probably should flip it into null then for efficiency's sake...
82 (char-pos nil :type (or unsigned-byte null))
83 ;; T if input is waiting on FD. :EOF if we hit EOF.
84 (listen nil :type (member nil t :eof))
88 (ibuf-sap nil :type (or system-area-pointer null))
89 (ibuf-length nil :type (or index null))
90 (ibuf-head 0 :type index)
91 (ibuf-tail 0 :type index)
94 (obuf-sap nil :type (or system-area-pointer null))
95 (obuf-length nil :type (or index null))
96 (obuf-tail 0 :type index)
98 ;; output flushed, but not written due to non-blocking io?
101 ;; timeout specified for this stream, or NIL if none
102 (timeout nil :type (or index null))
103 ;; pathname of the file this stream is opened to (returned by PATHNAME)
104 (pathname nil :type (or pathname null))
105 (external-format :default)
106 (output-bytes #'ill-out :type function))
107 (def!method print-object ((fd-stream fd-stream) stream)
108 (declare (type stream stream))
109 (print-unreadable-object (fd-stream stream :type t :identity t)
110 (format stream "for ~S" (fd-stream-name fd-stream))))
112 ;;;; output routines and related noise
114 (defvar *output-routines* ()
116 "List of all available output routines. Each element is a list of the
117 element-type output, the kind of buffering, the function name, and the number
118 of bytes per element.")
120 ;;; common idioms for reporting low-level stream and file problems
121 (defun simple-stream-perror (note-format stream errno)
122 (error 'simple-stream-error
124 :format-control "~@<~?: ~2I~_~A~:>"
125 :format-arguments (list note-format (list stream) (strerror errno))))
126 (defun simple-file-perror (note-format pathname errno)
127 (error 'simple-file-error
129 :format-control "~@<~?: ~2I~_~A~:>"
131 (list note-format (list pathname) (strerror errno))))
133 (defun stream-decoding-error (stream octets)
134 (error 'stream-decoding-error
136 ;; FIXME: dunno how to get at OCTETS currently, or even if
137 ;; that's the right thing to report.
139 (defun stream-encoding-error (stream code)
140 (error 'stream-encoding-error
144 (defun c-string-encoding-error (external-format code)
145 (error 'c-string-encoding-error
146 :external-format external-format
149 (defun c-string-decoding-error (external-format octets)
150 (error 'c-string-decoding-error
151 :external-format external-format
154 ;;; Returning true goes into end of file handling, false will enter another
155 ;;; round of input buffer filling followed by re-entering character decode.
156 (defun stream-decoding-error-and-handle (stream octet-count)
158 (stream-decoding-error stream
159 (let ((sap (fd-stream-ibuf-sap stream))
160 (head (fd-stream-ibuf-head stream)))
161 (loop for i from 0 below octet-count
162 collect (sap-ref-8 sap (+ head i)))))
164 :report (lambda (stream)
166 "~@<Attempt to resync the stream at a character ~
167 character boundary and continue.~@:>"))
168 (fd-stream-resync stream)
170 (force-end-of-file ()
171 :report (lambda (stream)
172 (format stream "~@<Force an end of file.~@:>"))
175 (defun stream-encoding-error-and-handle (stream code)
177 (stream-encoding-error stream code)
179 :report (lambda (stream)
180 (format stream "~@<Skip output of this character.~@:>"))
181 (throw 'output-nothing nil))))
183 (defun external-format-encoding-error (stream code)
185 (stream-encoding-error-and-handle stream code)
186 (c-string-encoding-error stream code)))
188 (defun external-format-decoding-error (stream octet-count)
190 (stream-decoding-error stream octet-count)
191 (c-string-decoding-error stream octet-count)))
193 ;;; This is called by the server when we can write to the given file
194 ;;; descriptor. Attempt to write the data again. If it worked, remove
195 ;;; the data from the OUTPUT-LATER list. If it didn't work, something
197 (defun frob-output-later (stream)
198 (let* ((stuff (pop (fd-stream-output-later stream)))
202 (reuse-sap (cadddr stuff))
203 (length (- end start)))
204 (declare (type index start end length))
205 (multiple-value-bind (count errno)
206 (sb!unix:unix-write (fd-stream-fd stream)
211 (if #!-win32 (= errno sb!unix:ewouldblock) #!+win32 t #!-win32
212 (error "Write would have blocked, but SERVER told us to go.")
213 (simple-stream-perror "couldn't write to ~S" stream errno)))
214 ((eql count length) ; Hot damn, it worked.
216 (with-available-buffers-lock ()
217 (push base *available-buffers*))))
218 ((not (null count)) ; sorta worked..
220 (the index (+ start count))
222 (fd-stream-output-later stream))))))
223 (unless (fd-stream-output-later stream)
224 (sb!sys:remove-fd-handler (fd-stream-handler stream))
225 (setf (fd-stream-handler stream) nil)))
227 ;;; Arange to output the string when we can write on the file descriptor.
228 (defun output-later (stream base start end reuse-sap)
229 (cond ((null (fd-stream-output-later stream))
230 (setf (fd-stream-output-later stream)
231 (list (list base start end reuse-sap)))
232 (setf (fd-stream-handler stream)
233 (sb!sys:add-fd-handler (fd-stream-fd stream)
236 (declare (ignore fd))
237 (frob-output-later stream)))))
239 (nconc (fd-stream-output-later stream)
240 (list (list base start end reuse-sap)))))
242 (let ((new-buffer (next-available-buffer)))
243 (setf (fd-stream-obuf-sap stream) new-buffer)
244 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
246 ;;; Output the given noise. Check to see whether there are any pending
247 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
248 ;;; this would block, queue it.
249 (defun frob-output (stream base start end reuse-sap)
250 (declare (type fd-stream stream)
251 (type (or system-area-pointer (simple-array * (*))) base)
252 (type index start end))
253 (if (not (null (fd-stream-output-later stream))) ; something buffered.
255 (output-later stream base start end reuse-sap)
256 ;; ### check to see whether any of this noise can be output
258 (let ((length (- end start)))
259 (multiple-value-bind (count errno)
260 (sb!unix:unix-write (fd-stream-fd stream) base start length)
262 (if #!-win32 (= errno sb!unix:ewouldblock) #!+win32 t #!-win32
263 (output-later stream base start end reuse-sap)
264 (simple-stream-perror "couldn't write to ~S"
267 ((not (eql count length))
268 (output-later stream base (the index (+ start count))
271 ;;; Flush any data in the output buffer.
272 (defun flush-output-buffer (stream)
273 (let ((length (fd-stream-obuf-tail stream)))
275 (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
276 (setf (fd-stream-obuf-tail stream) 0))))
278 (defmacro output-wrapper/variable-width ((stream size buffering restart)
280 (let ((stream-var (gensym)))
281 `(let ((,stream-var ,stream)
283 ,(unless (eq (car buffering) :none)
284 `(when (< (fd-stream-obuf-length ,stream-var)
285 (+ (fd-stream-obuf-tail ,stream-var)
287 (flush-output-buffer ,stream-var)))
288 ,(unless (eq (car buffering) :none)
289 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
290 (> (fd-stream-ibuf-tail ,stream-var)
291 (fd-stream-ibuf-head ,stream-var)))
292 (file-position ,stream-var (file-position ,stream-var))))
294 `(catch 'output-nothing
296 (incf (fd-stream-obuf-tail ,stream-var) size))
299 (incf (fd-stream-obuf-tail ,stream-var) size)))
300 ,(ecase (car buffering)
302 `(flush-output-buffer ,stream-var))
304 `(when (eq (char-code byte) (char-code #\Newline))
305 (flush-output-buffer ,stream-var)))
309 (defmacro output-wrapper ((stream size buffering restart) &body body)
310 (let ((stream-var (gensym)))
311 `(let ((,stream-var ,stream))
312 ,(unless (eq (car buffering) :none)
313 `(when (< (fd-stream-obuf-length ,stream-var)
314 (+ (fd-stream-obuf-tail ,stream-var)
316 (flush-output-buffer ,stream-var)))
317 ,(unless (eq (car buffering) :none)
318 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
319 (> (fd-stream-ibuf-tail ,stream-var)
320 (fd-stream-ibuf-head ,stream-var)))
321 (file-position ,stream-var (file-position ,stream-var))))
323 `(catch 'output-nothing
325 (incf (fd-stream-obuf-tail ,stream-var) ,size))
328 (incf (fd-stream-obuf-tail ,stream-var) ,size)))
329 ,(ecase (car buffering)
331 `(flush-output-buffer ,stream-var))
333 `(when (eq (char-code byte) (char-code #\Newline))
334 (flush-output-buffer ,stream-var)))
338 (defmacro def-output-routines/variable-width
339 ((name-fmt size restart external-format &rest bufferings)
341 (declare (optimize (speed 1)))
346 (intern (format nil name-fmt (string (car buffering))))))
348 (defun ,function (stream byte)
349 (declare (ignorable byte))
350 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
352 (setf *output-routines*
353 (nconc *output-routines*
361 (cdr buffering)))))))
364 ;;; Define output routines that output numbers SIZE bytes long for the
365 ;;; given bufferings. Use BODY to do the actual output.
366 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
368 (declare (optimize (speed 1)))
373 (intern (format nil name-fmt (string (car buffering))))))
375 (defun ,function (stream byte)
376 (output-wrapper (stream ,size ,buffering ,restart)
378 (setf *output-routines*
379 (nconc *output-routines*
387 (cdr buffering)))))))
390 ;;; FIXME: is this used anywhere any more?
391 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
397 (if (char= byte #\Newline)
398 (setf (fd-stream-char-pos stream) 0)
399 (incf (fd-stream-char-pos stream)))
400 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
403 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
406 (:none (unsigned-byte 8))
407 (:full (unsigned-byte 8)))
408 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
411 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
414 (:none (signed-byte 8))
415 (:full (signed-byte 8)))
416 (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
417 (fd-stream-obuf-tail stream))
420 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
423 (:none (unsigned-byte 16))
424 (:full (unsigned-byte 16)))
425 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
428 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
431 (:none (signed-byte 16))
432 (:full (signed-byte 16)))
433 (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
434 (fd-stream-obuf-tail stream))
437 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
440 (:none (unsigned-byte 32))
441 (:full (unsigned-byte 32)))
442 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
445 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
448 (:none (signed-byte 32))
449 (:full (signed-byte 32)))
450 (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
451 (fd-stream-obuf-tail stream))
454 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
456 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
459 (:none (unsigned-byte 64))
460 (:full (unsigned-byte 64)))
461 (setf (sap-ref-64 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
463 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
466 (:none (signed-byte 64))
467 (:full (signed-byte 64)))
468 (setf (signed-sap-ref-64 (fd-stream-obuf-sap stream)
469 (fd-stream-obuf-tail stream))
472 ;;; Do the actual output. If there is space to buffer the string,
473 ;;; buffer it. If the string would normally fit in the buffer, but
474 ;;; doesn't because of other stuff in the buffer, flush the old noise
475 ;;; out of the buffer and put the string in it. Otherwise we have a
476 ;;; very long string, so just send it directly (after flushing the
477 ;;; buffer, of course).
478 (defun output-raw-bytes (fd-stream thing &optional start end)
480 "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
481 THING is a SAP, END must be supplied (as length won't work)."
482 (let ((start (or start 0))
483 (end (or end (length (the (simple-array * (*)) thing)))))
484 (declare (type index start end))
485 (when (and (not (fd-stream-dual-channel-p fd-stream))
486 (> (fd-stream-ibuf-tail fd-stream)
487 (fd-stream-ibuf-head fd-stream)))
488 (file-position fd-stream (file-position fd-stream)))
489 (let* ((len (fd-stream-obuf-length fd-stream))
490 (tail (fd-stream-obuf-tail fd-stream))
492 (bytes (- end start))
493 (newtail (+ tail bytes)))
494 (cond ((minusp bytes) ; error case
495 (error ":END before :START!"))
496 ((zerop bytes)) ; easy case
498 (if (system-area-pointer-p thing)
499 (system-area-ub8-copy thing start
500 (fd-stream-obuf-sap fd-stream)
503 ;; FIXME: There should be some type checking somewhere to
504 ;; verify that THING here is a vector, not just <not a SAP>.
505 (copy-ub8-to-system-area thing start
506 (fd-stream-obuf-sap fd-stream)
509 (setf (fd-stream-obuf-tail fd-stream) newtail))
511 (flush-output-buffer fd-stream)
512 (if (system-area-pointer-p thing)
513 (system-area-ub8-copy thing
515 (fd-stream-obuf-sap fd-stream)
518 ;; FIXME: There should be some type checking somewhere to
519 ;; verify that THING here is a vector, not just <not a SAP>.
520 (copy-ub8-to-system-area thing
522 (fd-stream-obuf-sap fd-stream)
525 (setf (fd-stream-obuf-tail fd-stream) bytes))
527 (flush-output-buffer fd-stream)
528 (frob-output fd-stream thing start end nil))))))
530 ;;; the routine to use to output a string. If the stream is
531 ;;; unbuffered, slam the string down the file descriptor, otherwise
532 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
533 ;;; checking to see where the last newline was.
535 ;;; Note: some bozos (the FASL dumper) call write-string with things
536 ;;; other than strings. Therefore, we must make sure we have a string
537 ;;; before calling POSITION on it.
538 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
539 ;;; cover for them here. -- WHN 20000203
540 (defun fd-sout (stream thing start end)
541 (let ((start (or start 0))
542 (end (or end (length (the vector thing)))))
543 (declare (fixnum start end))
546 (string-dispatch (simple-base-string
548 (simple-array character)
551 (and (find #\newline thing :start start :end end)
552 ;; FIXME why do we need both calls?
553 ;; Is find faster forwards than
554 ;; position is backwards?
555 (position #\newline thing
559 (if (and (typep thing 'base-string)
560 (eq (fd-stream-external-format stream) :latin-1))
561 (ecase (fd-stream-buffering stream)
563 (output-raw-bytes stream thing start end))
565 (output-raw-bytes stream thing start end)
567 (flush-output-buffer stream)))
569 (frob-output stream thing start end nil)))
570 (ecase (fd-stream-buffering stream)
571 (:full (funcall (fd-stream-output-bytes stream)
572 stream thing nil start end))
573 (:line (funcall (fd-stream-output-bytes stream)
574 stream thing last-newline start end))
575 (:none (funcall (fd-stream-output-bytes stream)
576 stream thing t start end))))
578 (setf (fd-stream-char-pos stream)
579 (- end last-newline 1))
580 (incf (fd-stream-char-pos stream)
582 (ecase (fd-stream-buffering stream)
584 (output-raw-bytes stream thing start end))
586 (frob-output stream thing start end nil))))))
588 (defvar *external-formats* ()
590 "List of all available external formats. Each element is a list of the
591 element-type, string input function name, character input function name,
592 and string output function name.")
594 (defun get-external-format (external-format)
595 (dolist (entry *external-formats*)
596 (when (member external-format (first entry))
599 (defun get-external-format-function (external-format index)
600 (let ((entry (get-external-format external-format)))
601 (when entry (nth index entry))))
603 ;;; Find an output routine to use given the type and buffering. Return
604 ;;; as multiple values the routine, the real type transfered, and the
605 ;;; number of bytes per element.
606 (defun pick-output-routine (type buffering &optional external-format)
607 (when (subtypep type 'character)
608 (let ((entry (get-external-format external-format)))
610 (return-from pick-output-routine
611 (values (symbol-function (nth (ecase buffering
618 (symbol-function (fourth entry))
619 (first (first entry)))))))
620 (dolist (entry *output-routines*)
621 (when (and (subtypep type (first entry))
622 (eq buffering (second entry))
623 (or (not (fifth entry))
624 (eq external-format (fifth entry))))
625 (return-from pick-output-routine
626 (values (symbol-function (third entry))
629 ;; KLUDGE: dealing with the buffering here leads to excessive code
632 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
633 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
634 if (subtypep type `(unsigned-byte ,i))
635 do (return-from pick-output-routine
639 (lambda (stream byte)
640 (output-wrapper (stream (/ i 8) (:none) nil)
641 (loop for j from 0 below (/ i 8)
643 (fd-stream-obuf-sap stream)
644 (+ j (fd-stream-obuf-tail stream)))
645 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
647 (lambda (stream byte)
648 (output-wrapper (stream (/ i 8) (:full) nil)
649 (loop for j from 0 below (/ i 8)
651 (fd-stream-obuf-sap stream)
652 (+ j (fd-stream-obuf-tail stream)))
653 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
656 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
657 if (subtypep type `(signed-byte ,i))
658 do (return-from pick-output-routine
662 (lambda (stream byte)
663 (output-wrapper (stream (/ i 8) (:none) nil)
664 (loop for j from 0 below (/ i 8)
666 (fd-stream-obuf-sap stream)
667 (+ j (fd-stream-obuf-tail stream)))
668 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
670 (lambda (stream byte)
671 (output-wrapper (stream (/ i 8) (:full) nil)
672 (loop for j from 0 below (/ i 8)
674 (fd-stream-obuf-sap stream)
675 (+ j (fd-stream-obuf-tail stream)))
676 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
680 ;;;; input routines and related noise
682 ;;; a list of all available input routines. Each element is a list of
683 ;;; the element-type input, the function name, and the number of bytes
685 (defvar *input-routines* ())
687 ;;; Return whether a primitive partial read operation on STREAM's FD
688 ;;; would (probably) block. Signal a `simple-stream-error' if the
689 ;;; system call implementing this operation fails.
691 ;;; It is "may" instead of "would" because "would" is not quite
692 ;;; correct on win32. However, none of the places that use it require
693 ;;; further assurance than "may" versus "will definitely not".
694 (defun sysread-may-block-p (stream)
696 ;; This answers T at EOF on win32, I think.
697 (not (sb!win32:fd-listen (fd-stream-fd stream)))
699 (sb!unix:with-restarted-syscall (count errno)
700 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
701 (sb!unix:fd-zero read-fds)
702 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
703 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
704 (sb!alien:addr read-fds)
710 (simple-stream-perror "couldn't check whether ~S is readable"
714 ;;; Fill the input buffer, and return the number of bytes read. Throw
715 ;;; to EOF-INPUT-CATCHER if the eof was reached. Drop into
716 ;;; SYSTEM:SERVER if necessary.
717 (defun refill-buffer/fd (stream)
718 (let ((fd (fd-stream-fd stream))
719 (ibuf-sap (fd-stream-ibuf-sap stream))
720 (buflen (fd-stream-ibuf-length stream))
721 (head (fd-stream-ibuf-head stream))
722 (tail (fd-stream-ibuf-tail stream)))
723 (declare (type index head tail))
725 (cond ((eql head tail)
728 (setf (fd-stream-ibuf-head stream) 0)
729 (setf (fd-stream-ibuf-tail stream) 0))
732 (system-area-ub8-copy ibuf-sap head
735 (setf (fd-stream-ibuf-head stream) 0)
736 (setf (fd-stream-ibuf-tail stream) tail))))
737 (setf (fd-stream-listen stream) nil)
738 ;;This isn't quite the same on win32. Then again, neither was
739 ;;(not (sb!win32:fd-listen fd)), as was originally here. See
740 ;;comment in `sysread-may-block-p'.
741 (when (sysread-may-block-p stream)
742 (unless (sb!sys:wait-until-fd-usable
743 fd :input (fd-stream-timeout stream))
744 (error 'io-timeout :stream stream :direction :read)))
745 (multiple-value-bind (count errno)
746 (sb!unix:unix-read fd
747 (sb!sys:int-sap (+ (sb!sys:sap-int ibuf-sap) tail))
750 (if #!-win32 (eql errno sb!unix:ewouldblock) #!+win32 t #!-win32
752 (unless (sb!sys:wait-until-fd-usable
753 fd :input (fd-stream-timeout stream))
754 (error 'io-timeout :stream stream :direction :read))
755 (refill-buffer/fd stream))
756 (simple-stream-perror "couldn't read from ~S" stream errno)))
758 (setf (fd-stream-listen stream) :eof)
759 (/show0 "THROWing EOF-INPUT-CATCHER")
760 (throw 'eof-input-catcher nil))
762 (incf (fd-stream-ibuf-tail stream) count)
765 ;;; Make sure there are at least BYTES number of bytes in the input
766 ;;; buffer. Keep calling REFILL-BUFFER/FD until that condition is met.
767 (defmacro input-at-least (stream bytes)
768 (let ((stream-var (gensym))
769 (bytes-var (gensym)))
770 `(let ((,stream-var ,stream)
773 (when (>= (- (fd-stream-ibuf-tail ,stream-var)
774 (fd-stream-ibuf-head ,stream-var))
777 (refill-buffer/fd ,stream-var)))))
779 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
781 (let ((stream-var (gensym))
783 (element-var (gensym)))
784 `(let ((,stream-var ,stream)
786 (if (fd-stream-unread ,stream-var)
788 (fd-stream-unread ,stream-var)
789 (setf (fd-stream-unread ,stream-var) nil)
790 (setf (fd-stream-listen ,stream-var) nil))
791 (let ((,element-var nil)
792 (decode-break-reason nil))
796 (catch 'eof-input-catcher
797 (setf decode-break-reason
798 (block decode-break-reason
799 (input-at-least ,stream-var 1)
800 (let* ((byte (sap-ref-8 (fd-stream-ibuf-sap
804 (declare (ignorable byte))
806 (input-at-least ,stream-var size)
807 (setq ,element-var (locally ,@read-forms))
808 (setq ,retry-var nil))
810 (when decode-break-reason
811 (stream-decoding-error-and-handle stream
812 decode-break-reason))
814 (let ((octet-count (- (fd-stream-ibuf-tail ,stream-var)
815 (fd-stream-ibuf-head ,stream-var))))
816 (when (or (zerop octet-count)
817 (and (not ,element-var)
818 (not decode-break-reason)
819 (stream-decoding-error-and-handle
820 stream octet-count)))
821 (setq ,retry-var nil)))))
823 (incf (fd-stream-ibuf-head ,stream-var) size)
826 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
828 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
829 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
830 (let ((stream-var (gensym))
831 (element-var (gensym)))
832 `(let ((,stream-var ,stream))
833 (if (fd-stream-unread ,stream-var)
835 (fd-stream-unread ,stream-var)
836 (setf (fd-stream-unread ,stream-var) nil)
837 (setf (fd-stream-listen ,stream-var) nil))
839 (catch 'eof-input-catcher
840 (input-at-least ,stream-var ,bytes)
841 (locally ,@read-forms))))
843 (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
846 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
848 (defmacro def-input-routine/variable-width (name
849 (type external-format size sap head)
852 (defun ,name (stream eof-error eof-value)
853 (input-wrapper/variable-width (stream ,size eof-error eof-value)
854 (let ((,sap (fd-stream-ibuf-sap stream))
855 (,head (fd-stream-ibuf-head stream)))
857 (setf *input-routines*
858 (nconc *input-routines*
859 (list (list ',type ',name 1 ',external-format))))))
861 (defmacro def-input-routine (name
865 (defun ,name (stream eof-error eof-value)
866 (input-wrapper (stream ,size eof-error eof-value)
867 (let ((,sap (fd-stream-ibuf-sap stream))
868 (,head (fd-stream-ibuf-head stream)))
870 (setf *input-routines*
871 (nconc *input-routines*
872 (list (list ',type ',name ',size nil))))))
874 ;;; STREAM-IN routine for reading a string char
875 (def-input-routine input-character
876 (character 1 sap head)
877 (code-char (sap-ref-8 sap head)))
879 ;;; STREAM-IN routine for reading an unsigned 8 bit number
880 (def-input-routine input-unsigned-8bit-byte
881 ((unsigned-byte 8) 1 sap head)
882 (sap-ref-8 sap head))
884 ;;; STREAM-IN routine for reading a signed 8 bit number
885 (def-input-routine input-signed-8bit-number
886 ((signed-byte 8) 1 sap head)
887 (signed-sap-ref-8 sap head))
889 ;;; STREAM-IN routine for reading an unsigned 16 bit number
890 (def-input-routine input-unsigned-16bit-byte
891 ((unsigned-byte 16) 2 sap head)
892 (sap-ref-16 sap head))
894 ;;; STREAM-IN routine for reading a signed 16 bit number
895 (def-input-routine input-signed-16bit-byte
896 ((signed-byte 16) 2 sap head)
897 (signed-sap-ref-16 sap head))
899 ;;; STREAM-IN routine for reading a unsigned 32 bit number
900 (def-input-routine input-unsigned-32bit-byte
901 ((unsigned-byte 32) 4 sap head)
902 (sap-ref-32 sap head))
904 ;;; STREAM-IN routine for reading a signed 32 bit number
905 (def-input-routine input-signed-32bit-byte
906 ((signed-byte 32) 4 sap head)
907 (signed-sap-ref-32 sap head))
909 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
911 (def-input-routine input-unsigned-64bit-byte
912 ((unsigned-byte 64) 8 sap head)
913 (sap-ref-64 sap head))
914 (def-input-routine input-signed-64bit-byte
915 ((signed-byte 64) 8 sap head)
916 (signed-sap-ref-64 sap head)))
918 ;;; Find an input routine to use given the type. Return as multiple
919 ;;; values the routine, the real type transfered, and the number of
920 ;;; bytes per element (and for character types string input routine).
921 (defun pick-input-routine (type &optional external-format)
922 (when (subtypep type 'character)
923 (dolist (entry *external-formats*)
924 (when (member external-format (first entry))
925 (return-from pick-input-routine
926 (values (symbol-function (third entry))
929 (symbol-function (second entry))
930 (first (first entry)))))))
931 (dolist (entry *input-routines*)
932 (when (and (subtypep type (first entry))
933 (or (not (fourth entry))
934 (eq external-format (fourth entry))))
935 (return-from pick-input-routine
936 (values (symbol-function (second entry))
939 ;; FIXME: let's do it the hard way, then (but ignore things like
940 ;; endianness, efficiency, and the necessary coupling between these
941 ;; and the output routines). -- CSR, 2004-02-09
942 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
943 if (subtypep type `(unsigned-byte ,i))
944 do (return-from pick-input-routine
946 (lambda (stream eof-error eof-value)
947 (input-wrapper (stream (/ i 8) eof-error eof-value)
948 (let ((sap (fd-stream-ibuf-sap stream))
949 (head (fd-stream-ibuf-head stream)))
950 (loop for j from 0 below (/ i 8)
954 (sap-ref-8 sap (+ head j))))
955 finally (return result)))))
958 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
959 if (subtypep type `(signed-byte ,i))
960 do (return-from pick-input-routine
962 (lambda (stream eof-error eof-value)
963 (input-wrapper (stream (/ i 8) eof-error eof-value)
964 (let ((sap (fd-stream-ibuf-sap stream))
965 (head (fd-stream-ibuf-head stream)))
966 (loop for j from 0 below (/ i 8)
970 (sap-ref-8 sap (+ head j))))
971 finally (return (if (logbitp (1- i) result)
972 (dpb result (byte i 0) -1)
977 ;;; Return a string constructed from SAP, START, and END.
978 (defun string-from-sap (sap start end)
979 (declare (type index start end))
980 (let* ((length (- end start))
981 (string (make-string length)))
982 (copy-ub8-from-system-area sap start
987 ;;; the N-BIN method for FD-STREAMs
989 ;;; Note that this blocks in UNIX-READ. It is generally used where
990 ;;; there is a definite amount of reading to be done, so blocking
991 ;;; isn't too problematical.
992 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
993 &aux (total-copied 0))
994 (declare (type fd-stream stream))
995 (declare (type index start requested total-copied))
996 (let ((unread (fd-stream-unread stream)))
998 ;; AVERs designed to fail when we have more complicated
999 ;; character representations.
1000 (aver (typep unread 'base-char))
1001 (aver (= (fd-stream-element-size stream) 1))
1002 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1005 (system-area-pointer
1006 (setf (sap-ref-8 buffer start) (char-code unread)))
1007 ((simple-unboxed-array (*))
1008 (setf (aref buffer start) unread)))
1009 (setf (fd-stream-unread stream) nil)
1010 (setf (fd-stream-listen stream) nil)
1011 (incf total-copied)))
1014 (let* ((remaining-request (- requested total-copied))
1015 (head (fd-stream-ibuf-head stream))
1016 (tail (fd-stream-ibuf-tail stream))
1017 (available (- tail head))
1018 (n-this-copy (min remaining-request available))
1019 (this-start (+ start total-copied))
1020 (this-end (+ this-start n-this-copy))
1021 (sap (fd-stream-ibuf-sap stream)))
1022 (declare (type index remaining-request head tail available))
1023 (declare (type index n-this-copy))
1024 ;; Copy data from stream buffer into user's buffer.
1025 (%byte-blt sap head buffer this-start this-end)
1026 (incf (fd-stream-ibuf-head stream) n-this-copy)
1027 (incf total-copied n-this-copy)
1028 ;; Maybe we need to refill the stream buffer.
1029 (cond (;; If there were enough data in the stream buffer, we're done.
1030 (= total-copied requested)
1031 (return total-copied))
1032 (;; If EOF, we're done in another way.
1033 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1035 (error 'end-of-file :stream stream)
1036 (return total-copied)))
1037 ;; Otherwise we refilled the stream buffer, so fall
1038 ;; through into another pass of the loop.
1041 (defun fd-stream-resync (stream)
1042 (dolist (entry *external-formats*)
1043 (when (member (fd-stream-external-format stream) (first entry))
1044 (return-from fd-stream-resync
1045 (funcall (symbol-function (eighth entry)) stream)))))
1047 (defun get-fd-stream-character-sizer (stream)
1048 (dolist (entry *external-formats*)
1049 (when (member (fd-stream-external-format stream) (first entry))
1050 (return-from get-fd-stream-character-sizer (ninth entry)))))
1052 (defun fd-stream-character-size (stream char)
1053 (let ((sizer (get-fd-stream-character-sizer stream)))
1054 (when sizer (funcall sizer char))))
1056 (defun fd-stream-string-size (stream string)
1057 (let ((sizer (get-fd-stream-character-sizer stream)))
1059 (loop for char across string summing (funcall sizer char)))))
1061 (defun find-external-format (external-format)
1062 (when external-format
1063 (find external-format *external-formats* :test #'member :key #'car)))
1065 (defun variable-width-external-format-p (ef-entry)
1066 (when (eighth ef-entry) t))
1068 (defun bytes-for-char-fun (ef-entry)
1069 (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1071 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1072 (defmacro define-external-format (external-format size output-restart
1074 (let* ((name (first external-format))
1075 (out-function (symbolicate "OUTPUT-BYTES/" name))
1076 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1077 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1078 (in-char-function (symbolicate "INPUT-CHAR/" name))
1079 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1080 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1081 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name)))
1083 (defun ,size-function (byte)
1084 (declare (ignore byte))
1086 (defun ,out-function (stream string flush-p start end)
1087 (let ((start (or start 0))
1088 (end (or end (length string))))
1089 (declare (type index start end))
1090 (when (and (not (fd-stream-dual-channel-p stream))
1091 (> (fd-stream-ibuf-tail stream)
1092 (fd-stream-ibuf-head stream)))
1093 (file-position stream (file-position stream)))
1094 (unless (<= 0 start end (length string))
1095 (signal-bounding-indices-bad-error string start end))
1098 (setf (fd-stream-obuf-tail stream)
1099 (string-dispatch (simple-base-string
1101 (simple-array character)
1104 (let ((len (fd-stream-obuf-length stream))
1105 (sap (fd-stream-obuf-sap stream))
1106 (tail (fd-stream-obuf-tail stream)))
1107 (declare (type index tail)
1108 ;; STRING bounds have already been checked.
1109 (optimize (safety 0)))
1111 (,@(if output-restart
1112 `(catch 'output-nothing)
1115 ((or (= start end) (< (- len tail) 4)))
1116 (let* ((byte (aref string start))
1117 (bits (char-code byte)))
1121 ;; Exited from the loop normally
1123 ;; Exited via CATCH. Skip the current character
1124 ;; and try the inner loop again.
1127 (flush-output-buffer stream)))
1129 (flush-output-buffer stream))))
1130 (def-output-routines (,format
1136 (if (char= byte #\Newline)
1137 (setf (fd-stream-char-pos stream) 0)
1138 (incf (fd-stream-char-pos stream)))
1139 (let ((bits (char-code byte))
1140 (sap (fd-stream-obuf-sap stream))
1141 (tail (fd-stream-obuf-tail stream)))
1143 (defun ,in-function (stream buffer start requested eof-error-p
1144 &aux (index start) (end (+ start requested)))
1145 (declare (type fd-stream stream))
1146 (declare (type index start requested index end))
1147 (declare (type (simple-array character (#.+ansi-stream-in-buffer-length+)) buffer))
1148 (let ((unread (fd-stream-unread stream)))
1150 (setf (aref buffer index) unread)
1151 (setf (fd-stream-unread stream) nil)
1152 (setf (fd-stream-listen stream) nil)
1156 (let* ((head (fd-stream-ibuf-head stream))
1157 (tail (fd-stream-ibuf-tail stream))
1158 (sap (fd-stream-ibuf-sap stream)))
1159 (declare (type index head tail)
1160 (type system-area-pointer sap))
1161 ;; Copy data from stream buffer into user's buffer.
1162 (dotimes (i (min (truncate (- tail head) ,size)
1164 (declare (optimize speed))
1165 (let* ((byte (sap-ref-8 sap head)))
1166 (setf (aref buffer index) ,in-expr)
1169 (setf (fd-stream-ibuf-head stream) head)
1170 ;; Maybe we need to refill the stream buffer.
1171 (cond ( ;; If there was enough data in the stream buffer, we're done.
1173 (return (- index start)))
1174 ( ;; If EOF, we're done in another way.
1175 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1177 (error 'end-of-file :stream stream)
1178 (return (- index start))))
1179 ;; Otherwise we refilled the stream buffer, so fall
1180 ;; through into another pass of the loop.
1182 (def-input-routine ,in-char-function (character ,size sap head)
1183 (let ((byte (sap-ref-8 sap head)))
1185 (defun ,read-c-string-function (sap element-type)
1186 (declare (type system-area-pointer sap)
1187 (type (member character base-char) element-type))
1189 (declare (optimize (speed 3) (safety 0)))
1190 (let* ((stream ,name)
1191 (length (loop for head of-type index upfrom 0 by ,size
1192 for count of-type index upto (1- ARRAY-DIMENSION-LIMIT)
1193 for byte = (sap-ref-8 sap head)
1194 for char of-type character = ,in-expr
1195 until (zerop (char-code char))
1196 finally (return count)))
1197 (string (make-string length :element-type element-type)))
1198 (declare (ignorable stream)
1200 (type string string))
1201 (/show0 before-copy-loop)
1202 (loop for head of-type index upfrom 0 by ,size
1203 for index of-type index below length
1204 for byte = (sap-ref-8 sap head)
1205 for char of-type character = ,in-expr
1206 do (setf (aref string index) char))
1207 string))) ;; last loop rewrite to dotimes?
1208 (defun ,output-c-string-function (string)
1209 (declare (type simple-string string))
1211 (declare (optimize (speed 3) (safety 0)))
1212 (let* ((length (length string))
1213 (buffer (make-array (* (1+ length) ,size) :element-type '(unsigned-byte 8)))
1214 (sap (sb!sys:vector-sap buffer))
1217 (declare (type index length tail)
1218 (type system-area-pointer sap))
1220 (let* ((byte (aref string i))
1221 (bits (char-code byte)))
1222 (declare (ignorable byte bits))
1226 (byte (code-char bits)))
1227 (declare (ignorable bits byte))
1230 (setf *external-formats*
1231 (cons '(,external-format ,in-function ,in-char-function ,out-function
1232 ,@(mapcar #'(lambda (buffering)
1233 (intern (format nil format (string buffering))))
1234 '(:none :line :full))
1235 nil ; no resync-function
1236 ,size-function ,read-c-string-function ,output-c-string-function)
1237 *external-formats*)))))
1239 (defmacro define-external-format/variable-width
1240 (external-format output-restart out-size-expr
1241 out-expr in-size-expr in-expr)
1242 (let* ((name (first external-format))
1243 (out-function (symbolicate "OUTPUT-BYTES/" name))
1244 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1245 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1246 (in-char-function (symbolicate "INPUT-CHAR/" name))
1247 (resync-function (symbolicate "RESYNC/" name))
1248 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1249 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1250 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name)))
1252 (defun ,size-function (byte)
1253 (declare (ignorable byte))
1255 (defun ,out-function (stream string flush-p start end)
1256 (let ((start (or start 0))
1257 (end (or end (length string))))
1258 (declare (type index start end))
1259 (when (and (not (fd-stream-dual-channel-p stream))
1260 (> (fd-stream-ibuf-tail stream)
1261 (fd-stream-ibuf-head stream)))
1262 (file-position stream (file-position stream)))
1263 (unless (<= 0 start end (length string))
1264 (signal-bounding-indices-bad-error string start end))
1267 (setf (fd-stream-obuf-tail stream)
1268 (string-dispatch (simple-base-string
1270 (simple-array character)
1273 (let ((len (fd-stream-obuf-length stream))
1274 (sap (fd-stream-obuf-sap stream))
1275 (tail (fd-stream-obuf-tail stream)))
1276 (declare (type index tail)
1277 ;; STRING bounds have already been checked.
1278 (optimize (safety 0)))
1280 (,@(if output-restart
1281 `(catch 'output-nothing)
1284 ((or (= start end) (< (- len tail) 4)))
1285 (let* ((byte (aref string start))
1286 (bits (char-code byte))
1287 (size ,out-size-expr))
1291 ;; Exited from the loop normally
1293 ;; Exited via CATCH. Skip the current character
1294 ;; and try the inner loop again.
1297 (flush-output-buffer stream)))
1299 (flush-output-buffer stream))))
1300 (def-output-routines/variable-width (,format
1307 (if (char= byte #\Newline)
1308 (setf (fd-stream-char-pos stream) 0)
1309 (incf (fd-stream-char-pos stream)))
1310 (let ((bits (char-code byte))
1311 (sap (fd-stream-obuf-sap stream))
1312 (tail (fd-stream-obuf-tail stream)))
1314 (defun ,in-function (stream buffer start requested eof-error-p
1315 &aux (total-copied 0))
1316 (declare (type fd-stream stream))
1317 (declare (type index start requested total-copied))
1318 (declare (type (simple-array character (#.+ansi-stream-in-buffer-length+)) buffer))
1319 (let ((unread (fd-stream-unread stream)))
1321 (setf (aref buffer start) unread)
1322 (setf (fd-stream-unread stream) nil)
1323 (setf (fd-stream-listen stream) nil)
1324 (incf total-copied)))
1327 (let* ((head (fd-stream-ibuf-head stream))
1328 (tail (fd-stream-ibuf-tail stream))
1329 (sap (fd-stream-ibuf-sap stream))
1330 (decode-break-reason nil))
1331 (declare (type index head tail))
1332 ;; Copy data from stream buffer into user's buffer.
1333 (do ((size nil nil))
1334 ((or (= tail head) (= requested total-copied)))
1335 (setf decode-break-reason
1336 (block decode-break-reason
1337 (let ((byte (sap-ref-8 sap head)))
1338 (declare (ignorable byte))
1339 (setq size ,in-size-expr)
1340 (when (> size (- tail head))
1342 (setf (aref buffer (+ start total-copied)) ,in-expr)
1346 (setf (fd-stream-ibuf-head stream) head)
1347 (when decode-break-reason
1348 ;; If we've already read some characters on when the invalid
1349 ;; code sequence is detected, we return immediately. The
1350 ;; handling of the error is deferred until the next call
1351 ;; (where this check will be false). This allows establishing
1352 ;; high-level handlers for decode errors (for example
1353 ;; automatically resyncing in Lisp comments).
1354 (when (plusp total-copied)
1355 (return-from ,in-function total-copied))
1356 (when (stream-decoding-error-and-handle
1357 stream decode-break-reason)
1359 (error 'end-of-file :stream stream)
1360 (return-from ,in-function total-copied)))
1361 (setf head (fd-stream-ibuf-head stream))
1362 (setf tail (fd-stream-ibuf-tail stream))))
1363 (setf (fd-stream-ibuf-head stream) head)
1364 ;; Maybe we need to refill the stream buffer.
1365 (cond ( ;; If there were enough data in the stream buffer, we're done.
1366 (= total-copied requested)
1367 (return total-copied))
1368 ( ;; If EOF, we're done in another way.
1369 (or (eq decode-break-reason 'eof)
1370 (null (catch 'eof-input-catcher
1371 (refill-buffer/fd stream))))
1373 (error 'end-of-file :stream stream)
1374 (return total-copied)))
1375 ;; Otherwise we refilled the stream buffer, so fall
1376 ;; through into another pass of the loop.
1378 (def-input-routine/variable-width ,in-char-function (character
1382 (let ((byte (sap-ref-8 sap head)))
1383 (declare (ignorable byte))
1385 (defun ,resync-function (stream)
1386 (loop (input-at-least stream 2)
1387 (incf (fd-stream-ibuf-head stream))
1388 (unless (block decode-break-reason
1389 (let* ((sap (fd-stream-ibuf-sap stream))
1390 (head (fd-stream-ibuf-head stream))
1391 (byte (sap-ref-8 sap head))
1392 (size ,in-size-expr))
1393 (declare (ignorable byte))
1394 (input-at-least stream size)
1395 (let ((sap (fd-stream-ibuf-sap stream))
1396 (head (fd-stream-ibuf-head stream)))
1400 (defun ,read-c-string-function (sap element-type)
1401 (declare (type system-area-pointer sap))
1403 (declare (optimize (speed 3) (safety 0)))
1404 (let* ((stream ,name)
1405 (size 0) (head 0) (byte 0) (char nil)
1406 (decode-break-reason nil)
1407 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1408 (setf decode-break-reason
1409 (block decode-break-reason
1410 (setf byte (sap-ref-8 sap head)
1415 (when decode-break-reason
1416 (c-string-decoding-error ,name decode-break-reason))
1417 (when (zerop (char-code char))
1419 (string (make-string length :element-type element-type)))
1420 (declare (ignorable stream)
1421 (type index head length) ;; size
1422 (type (unsigned-byte 8) byte)
1423 (type (or null character) char)
1424 (type string string))
1426 (dotimes (index length string)
1427 (setf decode-break-reason
1428 (block decode-break-reason
1429 (setf byte (sap-ref-8 sap head)
1434 (when decode-break-reason
1435 (c-string-decoding-error ,name decode-break-reason))
1436 (setf (aref string index) char)))))
1438 (defun ,output-c-string-function (string)
1439 (declare (type simple-string string))
1441 (declare (optimize (speed 3) (safety 0)))
1442 (let* ((length (length string))
1443 (char-length (make-array (1+ length) :element-type 'index))
1445 (+ (loop for i of-type index below length
1446 for byte of-type character = (aref string i)
1447 for bits = (char-code byte)
1448 sum (setf (aref char-length i)
1449 (the index ,out-size-expr)))
1450 (let* ((byte (code-char 0))
1451 (bits (char-code byte)))
1452 (declare (ignorable byte bits))
1453 (setf (aref char-length length)
1454 (the index ,out-size-expr)))))
1456 (buffer (make-array buffer-length :element-type '(unsigned-byte 8)))
1457 (sap (sb!sys:vector-sap buffer))
1459 (declare (type index length buffer-length tail)
1460 (type system-area-pointer sap)
1463 (loop for i of-type index below length
1464 for byte of-type character = (aref string i)
1465 for bits = (char-code byte)
1466 for size of-type index = (aref char-length i)
1471 (byte (code-char bits))
1472 (size (aref char-length length)))
1473 (declare (ignorable bits byte size))
1477 (setf *external-formats*
1478 (cons '(,external-format ,in-function ,in-char-function ,out-function
1479 ,@(mapcar #'(lambda (buffering)
1480 (intern (format nil format (string buffering))))
1481 '(:none :line :full))
1483 ,size-function ,read-c-string-function ,output-c-string-function)
1484 *external-formats*)))))
1486 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1487 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1488 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1489 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1492 (external-format-encoding-error stream bits)
1493 (setf (sap-ref-8 sap tail) bits))
1496 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1497 :iso-646 :iso-646-us :|646|)
1500 (external-format-encoding-error stream bits)
1501 (setf (sap-ref-8 sap tail) bits))
1504 (let* ((table (let ((s (make-string 256)))
1505 (map-into s #'code-char
1506 '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1507 #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1508 #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1509 #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1510 #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1511 #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1512 #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1513 #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1514 #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1515 #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1516 #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1517 #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1518 #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1519 #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1520 #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1521 #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1523 (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1524 (loop for char across table for i from 0
1525 do (aver (= 0 (aref rt (char-code char))))
1526 do (setf (aref rt (char-code char)) i))
1528 (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1531 (external-format-encoding-error stream bits)
1532 (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1537 (let ((latin-9-table (let ((table (make-string 256)))
1540 (setf (aref table i) (code-char i)))
1541 (setf (aref table #xa4) (code-char #x20ac))
1542 (setf (aref table #xa6) (code-char #x0160))
1543 (setf (aref table #xa8) (code-char #x0161))
1544 (setf (aref table #xb4) (code-char #x017d))
1545 (setf (aref table #xb8) (code-char #x017e))
1546 (setf (aref table #xbc) (code-char #x0152))
1547 (setf (aref table #xbd) (code-char #x0153))
1548 (setf (aref table #xbe) (code-char #x0178))
1550 (latin-9-reverse-1 (make-array 16
1551 :element-type '(unsigned-byte 21)
1552 :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1553 (latin-9-reverse-2 (make-array 16
1554 :element-type '(unsigned-byte 8)
1555 :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1556 (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1558 (setf (sap-ref-8 sap tail)
1560 (if (= bits (char-code (aref latin-9-table bits)))
1562 (external-format-encoding-error stream byte))
1563 (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1564 (aref latin-9-reverse-2 (logand bits 15))
1565 (external-format-encoding-error stream byte))))
1566 (aref latin-9-table byte)))
1568 (define-external-format/variable-width (:utf-8 :utf8) nil
1569 (let ((bits (char-code byte)))
1570 (cond ((< bits #x80) 1)
1572 ((< bits #x10000) 3)
1575 (1 (setf (sap-ref-8 sap tail) bits))
1576 (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1577 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 0) bits))))
1578 (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1579 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 6) bits))
1580 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1581 (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1582 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 12) bits))
1583 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1584 (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1585 (cond ((< byte #x80) 1)
1586 ((< byte #xc2) (return-from decode-break-reason 1))
1590 (code-char (ecase size
1592 (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1593 (unless (<= #x80 byte2 #xbf)
1594 (return-from decode-break-reason 2))
1595 (dpb byte (byte 5 6) byte2)))
1596 (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1597 (byte3 (sap-ref-8 sap (+ 2 head))))
1598 (unless (and (<= #x80 byte2 #xbf)
1599 (<= #x80 byte3 #xbf))
1600 (return-from decode-break-reason 3))
1601 (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1602 (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1603 (byte3 (sap-ref-8 sap (+ 2 head)))
1604 (byte4 (sap-ref-8 sap (+ 3 head))))
1605 (unless (and (<= #x80 byte2 #xbf)
1606 (<= #x80 byte3 #xbf)
1607 (<= #x80 byte4 #xbf))
1608 (return-from decode-break-reason 4))
1609 (dpb byte (byte 3 18)
1610 (dpb byte2 (byte 6 12)
1611 (dpb byte3 (byte 6 6) byte4))))))))
1613 ;;;; utility functions (misc routines, etc)
1615 ;;; Fill in the various routine slots for the given type. INPUT-P and
1616 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1617 ;;; set prior to calling this routine.
1618 (defun set-fd-stream-routines (fd-stream element-type external-format
1619 input-p output-p buffer-p)
1620 (let* ((target-type (case element-type
1621 (unsigned-byte '(unsigned-byte 8))
1622 (signed-byte '(signed-byte 8))
1623 (:default 'character)
1625 (character-stream-p (subtypep target-type 'character))
1626 (bivalent-stream-p (eq element-type :default))
1627 normalized-external-format
1628 (bin-routine #'ill-bin)
1631 (cin-routine #'ill-in)
1634 (input-type nil) ;calculated from bin-type/cin-type
1635 (input-size nil) ;calculated from bin-size/cin-size
1636 (read-n-characters #'ill-in)
1637 (bout-routine #'ill-bout)
1640 (cout-routine #'ill-out)
1645 (output-bytes #'ill-bout))
1647 ;; drop buffers when direction changes
1648 (when (and (fd-stream-obuf-sap fd-stream) (not output-p))
1649 (with-available-buffers-lock ()
1650 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1651 (setf (fd-stream-obuf-sap fd-stream) nil)))
1652 (when (and (fd-stream-ibuf-sap fd-stream) (not input-p))
1653 (with-available-buffers-lock ()
1654 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1655 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1657 (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
1658 (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
1659 (setf (fd-stream-ibuf-tail fd-stream) 0))
1661 (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
1662 (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
1663 (setf (fd-stream-obuf-tail fd-stream) 0)
1664 (setf (fd-stream-char-pos fd-stream) 0))
1666 (when (and character-stream-p
1667 (eq external-format :default))
1668 (/show0 "/getting default external format")
1669 (setf external-format (default-external-format)))
1672 (when (or (not character-stream-p) bivalent-stream-p)
1673 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1674 normalized-external-format)
1675 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1679 (error "could not find any input routine for ~S" target-type)))
1680 (when character-stream-p
1681 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1682 normalized-external-format)
1683 (pick-input-routine target-type external-format))
1685 (error "could not find any input routine for ~S" target-type)))
1686 (setf (fd-stream-in fd-stream) cin-routine
1687 (fd-stream-bin fd-stream) bin-routine)
1688 ;; character type gets preferential treatment
1689 (setf input-size (or cin-size bin-size))
1690 (setf input-type (or cin-type bin-type))
1691 (when normalized-external-format
1692 (setf (fd-stream-external-format fd-stream)
1693 normalized-external-format))
1694 (when (= (or cin-size 1) (or bin-size 1) 1)
1695 (setf (fd-stream-n-bin fd-stream) ;XXX
1696 (if (and character-stream-p (not bivalent-stream-p))
1698 #'fd-stream-read-n-bytes))
1699 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1700 ;; for character and (unsigned-byte 8) streams. In these
1701 ;; cases, fast-read-* will read from the
1702 ;; ansi-stream-(c)in-buffer, saving function calls.
1703 ;; Otherwise, the various data-reading functions in the stream
1704 ;; structure will be called.
1706 (not bivalent-stream-p)
1707 ;; temporary disable on :io streams
1709 (cond (character-stream-p
1710 (setf (ansi-stream-cin-buffer fd-stream)
1711 (make-array +ansi-stream-in-buffer-length+
1712 :element-type 'character)))
1713 ((equal target-type '(unsigned-byte 8))
1714 (setf (ansi-stream-in-buffer fd-stream)
1715 (make-array +ansi-stream-in-buffer-length+
1716 :element-type '(unsigned-byte 8))))))))
1719 (when (or (not character-stream-p) bivalent-stream-p)
1720 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1721 normalized-external-format)
1722 (pick-output-routine (if bivalent-stream-p
1725 (fd-stream-buffering fd-stream)
1727 (unless bout-routine
1728 (error "could not find any output routine for ~S buffered ~S"
1729 (fd-stream-buffering fd-stream)
1731 (when character-stream-p
1732 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1733 normalized-external-format)
1734 (pick-output-routine target-type
1735 (fd-stream-buffering fd-stream)
1737 (unless cout-routine
1738 (error "could not find any output routine for ~S buffered ~S"
1739 (fd-stream-buffering fd-stream)
1741 (when normalized-external-format
1742 (setf (fd-stream-external-format fd-stream)
1743 normalized-external-format))
1744 (when character-stream-p
1745 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1746 (setf (fd-stream-out fd-stream) cout-routine
1747 (fd-stream-bout fd-stream) bout-routine
1748 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1749 #'fd-sout #'ill-out))
1750 (setf output-size (or cout-size bout-size))
1751 (setf output-type (or cout-type bout-type)))
1753 (when (and input-size output-size
1754 (not (eq input-size output-size)))
1755 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1756 input-type input-size
1757 output-type output-size))
1758 (setf (fd-stream-element-size fd-stream)
1759 (or input-size output-size))
1761 (setf (fd-stream-element-type fd-stream)
1762 (cond ((equal input-type output-type)
1768 ((subtypep input-type output-type)
1770 ((subtypep output-type input-type)
1773 (error "Input type (~S) and output type (~S) are unrelated?"
1777 ;;; Handle miscellaneous operations on FD-STREAM.
1778 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1779 (declare (ignore arg2))
1782 (labels ((do-listen ()
1783 (or (not (eql (fd-stream-ibuf-head fd-stream)
1784 (fd-stream-ibuf-tail fd-stream)))
1785 (fd-stream-listen fd-stream)
1787 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1789 ;; If the read can block, LISTEN will certainly return NIL.
1790 (if (sysread-may-block-p fd-stream)
1792 ;; Otherwise select(2) and CL:LISTEN have slightly
1793 ;; different semantics. The former returns that an FD
1794 ;; is readable when a read operation wouldn't block.
1795 ;; That includes EOF. However, LISTEN must return NIL
1797 (progn (catch 'eof-input-catcher
1798 ;; r-b/f too calls select, but it shouldn't
1799 ;; block as long as read can return once w/o
1801 (refill-buffer/fd fd-stream))
1802 ;; At this point either IBUF-HEAD != IBUF-TAIL
1803 ;; and FD-STREAM-LISTEN is NIL, in which case
1804 ;; we should return T, or IBUF-HEAD ==
1805 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1806 ;; which case we should return :EOF for this
1807 ;; call and all future LISTEN call on this stream.
1808 ;; Call ourselves again to determine which case
1813 (setf (fd-stream-unread fd-stream) arg1)
1814 (setf (fd-stream-listen fd-stream) t))
1816 (cond (arg1 ; We got us an abort on our hands.
1817 (when (fd-stream-handler fd-stream)
1818 (sb!sys:remove-fd-handler (fd-stream-handler fd-stream))
1819 (setf (fd-stream-handler fd-stream) nil))
1820 ;; We can't do anything unless we know what file were
1821 ;; dealing with, and we don't want to do anything
1822 ;; strange unless we were writing to the file.
1823 (when (and (fd-stream-file fd-stream)
1824 (fd-stream-obuf-sap fd-stream))
1825 (if (fd-stream-original fd-stream)
1826 ;; If the original is EQ to file we are appending
1827 ;; and can just close the file without renaming.
1828 (unless (eq (fd-stream-original fd-stream)
1829 (fd-stream-file fd-stream))
1830 ;; We have a handle on the original, just revert.
1831 (multiple-value-bind (okay err)
1832 (sb!unix:unix-rename (fd-stream-original fd-stream)
1833 (fd-stream-file fd-stream))
1835 (simple-stream-perror
1836 "couldn't restore ~S to its original contents"
1839 ;; We can't restore the original, and aren't
1840 ;; appending, so nuke that puppy.
1842 ;; FIXME: This is currently the fate of superseded
1843 ;; files, and according to the CLOSE spec this is
1844 ;; wrong. However, there seems to be no clean way to
1845 ;; do that that doesn't involve either copying the
1846 ;; data (bad if the :abort resulted from a full
1847 ;; disk), or renaming the old file temporarily
1848 ;; (probably bad because stream opening becomes more
1850 (multiple-value-bind (okay err)
1851 (sb!unix:unix-unlink (fd-stream-file fd-stream))
1853 (error 'simple-file-error
1854 :pathname (fd-stream-file fd-stream)
1856 "~@<couldn't remove ~S: ~2I~_~A~:>"
1857 :format-arguments (list (fd-stream-file fd-stream)
1858 (strerror err))))))))
1860 (fd-stream-misc-routine fd-stream :finish-output)
1861 (when (and (fd-stream-original fd-stream)
1862 (fd-stream-delete-original fd-stream))
1863 (multiple-value-bind (okay err)
1864 (sb!unix:unix-unlink (fd-stream-original fd-stream))
1866 (error 'simple-file-error
1867 :pathname (fd-stream-original fd-stream)
1869 "~@<couldn't delete ~S during close of ~S: ~
1872 (list (fd-stream-original fd-stream)
1874 (strerror err))))))))
1875 (when (fboundp 'cancel-finalization)
1876 (cancel-finalization fd-stream))
1877 (sb!unix:unix-close (fd-stream-fd fd-stream))
1878 (when (fd-stream-obuf-sap fd-stream)
1879 (with-available-buffers-lock ()
1880 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1881 (setf (fd-stream-obuf-sap fd-stream) nil)))
1882 (when (fd-stream-ibuf-sap fd-stream)
1883 (with-available-buffers-lock ()
1884 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1885 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1886 (sb!impl::set-closed-flame fd-stream))
1888 (setf (fd-stream-unread fd-stream) nil)
1889 (setf (fd-stream-ibuf-head fd-stream) 0)
1890 (setf (fd-stream-ibuf-tail fd-stream) 0)
1893 (sb!win32:fd-clear-input (fd-stream-fd fd-stream))
1894 (setf (fd-stream-listen fd-stream) nil))
1896 (catch 'eof-input-catcher
1897 (loop until (sysread-may-block-p fd-stream)
1899 (refill-buffer/fd fd-stream)
1900 (setf (fd-stream-ibuf-head fd-stream) 0)
1901 (setf (fd-stream-ibuf-tail fd-stream) 0))
1904 (flush-output-buffer fd-stream))
1906 (flush-output-buffer fd-stream)
1908 ((null (fd-stream-output-later fd-stream)))
1909 (sb!sys:serve-all-events)))
1911 (fd-stream-element-type fd-stream))
1913 (fd-stream-external-format fd-stream))
1915 (= 1 (the (member 0 1)
1916 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
1920 (fd-stream-char-pos fd-stream))
1922 (unless (fd-stream-file fd-stream)
1923 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
1924 ;; "should signal an error of type TYPE-ERROR if stream is not
1925 ;; a stream associated with a file". Too bad there's no very
1926 ;; appropriate value for the EXPECTED-TYPE slot..
1927 (error 'simple-type-error
1929 :expected-type 'fd-stream
1930 :format-control "~S is not a stream associated with a file."
1931 :format-arguments (list fd-stream)))
1932 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
1933 atime mtime ctime blksize blocks)
1934 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
1935 (declare (ignore ino nlink uid gid rdev
1936 atime mtime ctime blksize blocks))
1938 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
1941 (truncate size (fd-stream-element-size fd-stream)))))
1942 (:file-string-length
1944 (character (fd-stream-character-size fd-stream arg1))
1945 (string (fd-stream-string-size fd-stream arg1))))
1947 (fd-stream-file-position fd-stream arg1))))
1949 (defun fd-stream-file-position (stream &optional newpos)
1950 (declare (type fd-stream stream)
1951 (type (or (alien sb!unix:off-t) (member nil :start :end)) newpos))
1953 (sb!sys:without-interrupts
1954 ;; First, find the position of the UNIX file descriptor in the file.
1955 (multiple-value-bind (posn errno)
1956 (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)
1957 (declare (type (or (alien sb!unix:off-t) null) posn))
1958 (cond ((integerp posn)
1959 ;; Adjust for buffered output: If there is any output
1960 ;; buffered, the *real* file position will be larger
1961 ;; than reported by lseek() because lseek() obviously
1962 ;; cannot take into account output we have not sent
1964 (dolist (later (fd-stream-output-later stream))
1965 (incf posn (- (caddr later)
1967 (incf posn (fd-stream-obuf-tail stream))
1968 ;; Adjust for unread input: If there is any input
1969 ;; read from UNIX but not supplied to the user of the
1970 ;; stream, the *real* file position will smaller than
1971 ;; reported, because we want to look like the unread
1972 ;; stuff is still available.
1973 (decf posn (- (fd-stream-ibuf-tail stream)
1974 (fd-stream-ibuf-head stream)))
1975 (when (fd-stream-unread stream)
1977 ;; Divide bytes by element size.
1978 (truncate posn (fd-stream-element-size stream)))
1979 ((eq errno sb!unix:espipe)
1982 (sb!sys:with-interrupts
1983 (simple-stream-perror "failure in Unix lseek() on ~S"
1986 (let ((offset 0) origin)
1987 (declare (type (alien sb!unix:off-t) offset))
1988 ;; Make sure we don't have any output pending, because if we
1989 ;; move the file pointer before writing this stuff, it will be
1990 ;; written in the wrong location.
1991 (flush-output-buffer stream)
1993 ((null (fd-stream-output-later stream)))
1994 (sb!sys:serve-all-events))
1995 ;; Clear out any pending input to force the next read to go to
1997 (setf (fd-stream-unread stream) nil)
1998 (setf (fd-stream-ibuf-head stream) 0)
1999 (setf (fd-stream-ibuf-tail stream) 0)
2000 ;; Trash cached value for listen, so that we check next time.
2001 (setf (fd-stream-listen stream) nil)
2003 (cond ((eq newpos :start)
2004 (setf offset 0 origin sb!unix:l_set))
2006 (setf offset 0 origin sb!unix:l_xtnd))
2007 ((typep newpos '(alien sb!unix:off-t))
2008 (setf offset (* newpos (fd-stream-element-size stream))
2009 origin sb!unix:l_set))
2011 (error "invalid position given to FILE-POSITION: ~S" newpos)))
2012 (multiple-value-bind (posn errno)
2013 (sb!unix:unix-lseek (fd-stream-fd stream) offset origin)
2014 (cond ((typep posn '(alien sb!unix:off-t))
2016 ((eq errno sb!unix:espipe)
2019 (simple-stream-perror "error in Unix lseek() on ~S"
2023 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2025 ;;; Create a stream for the given Unix file descriptor.
2027 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2028 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2029 ;;; default to allowing input.
2031 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2033 ;;; BUFFERING indicates the kind of buffering to use.
2035 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2036 ;;; NIL (the default), then wait forever. When we time out, we signal
2039 ;;; FILE is the name of the file (will be returned by PATHNAME).
2041 ;;; NAME is used to identify the stream when printed.
2042 (defun make-fd-stream (fd
2045 (output nil output-p)
2046 (element-type 'base-char)
2048 (external-format :default)
2057 (format nil "file ~A" file)
2058 (format nil "descriptor ~W" fd)))
2060 (declare (type index fd) (type (or index null) timeout)
2061 (type (member :none :line :full) buffering))
2062 (cond ((not (or input-p output-p))
2064 ((not (or input output))
2065 (error "File descriptor must be opened either for input or output.")))
2066 (let ((stream (%make-fd-stream :fd fd
2070 :delete-original delete-original
2072 :buffering buffering
2073 :dual-channel-p dual-channel-p
2074 :external-format external-format
2076 (set-fd-stream-routines stream element-type external-format
2077 input output input-buffer-p)
2078 (when (and auto-close (fboundp 'finalize))
2081 (sb!unix:unix-close fd)
2083 (format *terminal-io* "** closed file descriptor ~W **~%"
2087 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2088 ;;; :RENAME-AND-DELETE and :RENAME options.
2089 (defun pick-backup-name (name)
2090 (declare (type simple-string name))
2091 (concatenate 'simple-string name ".bak"))
2093 ;;; Ensure that the given arg is one of the given list of valid
2094 ;;; things. Allow the user to fix any problems.
2095 (defun ensure-one-of (item list what)
2096 (unless (member item list)
2097 (error 'simple-type-error
2099 :expected-type `(member ,@list)
2100 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2101 :format-arguments (list item what list))))
2103 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2104 ;;; access, since we don't want to trash unwritable files even if we
2105 ;;; technically can. We return true if we succeed in renaming.
2106 (defun rename-the-old-one (namestring original)
2107 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2108 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2109 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2112 (error 'simple-file-error
2113 :pathname namestring
2115 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2116 :format-arguments (list namestring original (strerror err))))))
2118 (defun open (filename
2121 (element-type 'base-char)
2122 (if-exists nil if-exists-given)
2123 (if-does-not-exist nil if-does-not-exist-given)
2124 (external-format :default)
2125 &aux ; Squelch assignment warning.
2126 (direction direction)
2127 (if-does-not-exist if-does-not-exist)
2128 (if-exists if-exists))
2130 "Return a stream which reads from or writes to FILENAME.
2132 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2133 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2134 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2135 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2136 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2137 See the manual for details."
2139 ;; Calculate useful stuff.
2140 (multiple-value-bind (input output mask)
2142 (:input (values t nil sb!unix:o_rdonly))
2143 (:output (values nil t sb!unix:o_wronly))
2144 (:io (values t t sb!unix:o_rdwr))
2145 (:probe (values t nil sb!unix:o_rdonly)))
2146 (declare (type index mask))
2147 (let* ((pathname (merge-pathnames filename))
2149 (cond ((unix-namestring pathname input))
2150 ((and input (eq if-does-not-exist :create))
2151 (unix-namestring pathname nil))
2152 ((and (eq direction :io) (not if-does-not-exist-given))
2153 (unix-namestring pathname nil)))))
2154 ;; Process if-exists argument if we are doing any output.
2156 (unless if-exists-given
2158 (if (eq (pathname-version pathname) :newest)
2161 (ensure-one-of if-exists
2162 '(:error :new-version :rename
2163 :rename-and-delete :overwrite
2164 :append :supersede nil)
2167 ((:new-version :error nil)
2168 (setf mask (logior mask sb!unix:o_excl)))
2169 ((:rename :rename-and-delete)
2170 (setf mask (logior mask sb!unix:o_creat)))
2172 (setf mask (logior mask sb!unix:o_trunc)))
2174 (setf mask (logior mask sb!unix:o_append)))))
2176 (setf if-exists :ignore-this-arg)))
2178 (unless if-does-not-exist-given
2179 (setf if-does-not-exist
2180 (cond ((eq direction :input) :error)
2182 (member if-exists '(:overwrite :append)))
2184 ((eq direction :probe)
2188 (ensure-one-of if-does-not-exist
2189 '(:error :create nil)
2191 (if (eq if-does-not-exist :create)
2192 (setf mask (logior mask sb!unix:o_creat)))
2194 (let ((original (case if-exists
2195 ((:rename :rename-and-delete)
2196 (pick-backup-name namestring))
2197 ((:append :overwrite)
2198 ;; KLUDGE: Provent CLOSE from deleting
2199 ;; appending streams when called with :ABORT T
2201 (delete-original (eq if-exists :rename-and-delete))
2203 (when (and original (not (eq original namestring)))
2204 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2205 ;; whether the file already exists, make sure the original
2206 ;; file is not a directory, and keep the mode.
2209 (multiple-value-bind (okay err/dev inode orig-mode)
2210 (sb!unix:unix-stat namestring)
2211 (declare (ignore inode)
2212 (type (or index null) orig-mode))
2215 (when (and output (= (logand orig-mode #o170000)
2217 (error 'simple-file-error
2218 :pathname namestring
2220 "can't open ~S for output: is a directory"
2221 :format-arguments (list namestring)))
2222 (setf mode (logand orig-mode #o777))
2224 ((eql err/dev sb!unix:enoent)
2227 (simple-file-perror "can't find ~S"
2231 (rename-the-old-one namestring original))
2233 (setf delete-original nil)
2234 ;; In order to use :SUPERSEDE instead, we have to make
2235 ;; sure SB!UNIX:O_CREAT corresponds to
2236 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2237 ;; because of IF-EXISTS being :RENAME.
2238 (unless (eq if-does-not-exist :create)
2240 (logior (logandc2 mask sb!unix:o_creat)
2242 (setf if-exists :supersede))))
2244 ;; Now we can try the actual Unix open(2).
2245 (multiple-value-bind (fd errno)
2247 (sb!unix:unix-open namestring mask mode)
2248 (values nil sb!unix:enoent))
2249 (labels ((open-error (format-control &rest format-arguments)
2250 (error 'simple-file-error
2252 :format-control format-control
2253 :format-arguments format-arguments))
2254 (vanilla-open-error ()
2255 (simple-file-perror "error opening ~S" pathname errno)))
2258 ((:input :output :io)
2262 :element-type element-type
2263 :external-format external-format
2266 :delete-original delete-original
2273 (%make-fd-stream :name namestring
2276 :element-type element-type)))
2279 ((eql errno sb!unix:enoent)
2280 (case if-does-not-exist
2281 (:error (vanilla-open-error))
2283 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2286 ((and (eql errno sb!unix:eexist) (null if-exists))
2289 (vanilla-open-error)))))))))
2293 ;;; the stream connected to the controlling terminal, or NIL if there is none
2296 ;;; the stream connected to the standard input (file descriptor 0)
2299 ;;; the stream connected to the standard output (file descriptor 1)
2302 ;;; the stream connected to the standard error output (file descriptor 2)
2305 ;;; This is called when the cold load is first started up, and may also
2306 ;;; be called in an attempt to recover from nested errors.
2307 (defun stream-cold-init-or-reset ()
2309 (setf *terminal-io* (make-synonym-stream '*tty*))
2310 (setf *standard-output* (make-synonym-stream '*stdout*))
2311 (setf *standard-input* (make-synonym-stream '*stdin*))
2312 (setf *error-output* (make-synonym-stream '*stderr*))
2313 (setf *query-io* (make-synonym-stream '*terminal-io*))
2314 (setf *debug-io* *query-io*)
2315 (setf *trace-output* *standard-output*)
2318 ;;; This is called whenever a saved core is restarted.
2319 (defun stream-reinit ()
2320 (setf *available-buffers* nil)
2321 (with-output-to-string (*error-output*)
2323 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2324 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2326 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2327 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2329 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2330 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2331 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2332 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2336 :name "the terminal"
2341 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2342 (princ (get-output-stream-string *error-output*) *stderr*))
2347 ;;; the Unix way to beep
2348 (defun beep (stream)
2349 (write-char (code-char bell-char-code) stream)
2350 (finish-output stream))
2352 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2353 ;;; by the filesys stuff to get and set the file name.
2355 ;;; FIXME: misleading name, screwy interface
2356 (defun file-name (stream &optional new-name)
2357 (when (typep stream 'fd-stream)
2359 (setf (fd-stream-pathname stream) new-name)
2360 (setf (fd-stream-file stream)
2361 (unix-namestring new-name nil))
2364 (fd-stream-pathname stream)))))