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 as seconds or NIL if none
102 (timeout nil :type (or single-float null))
103 ;; pathname of the file this stream is opened to (returned by PATHNAME)
104 (pathname nil :type (or pathname null))
105 (external-format :default)
106 (output-bytes #'ill-out :type function))
107 (def!method print-object ((fd-stream fd-stream) stream)
108 (declare (type stream stream))
109 (print-unreadable-object (fd-stream stream :type t :identity t)
110 (format stream "for ~S" (fd-stream-name fd-stream))))
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)
212 (simple-stream-perror "couldn't write to ~S" stream errno)
214 (if (= errno sb!unix:ewouldblock)
215 (error "Write would have blocked, but SERVER told us to go.")
216 (simple-stream-perror "couldn't write to ~S" stream errno)))
217 ((eql count length) ; Hot damn, it worked.
219 (with-available-buffers-lock ()
220 (push base *available-buffers*))))
221 ((not (null count)) ; sorta worked..
223 (the index (+ start count))
225 (fd-stream-output-later stream))))))
226 (unless (fd-stream-output-later stream)
227 (remove-fd-handler (fd-stream-handler stream))
228 (setf (fd-stream-handler stream) nil)))
230 ;;; Arange to output the string when we can write on the file descriptor.
231 (defun output-later (stream base start end reuse-sap)
232 (cond ((null (fd-stream-output-later stream))
233 (setf (fd-stream-output-later stream)
234 (list (list base start end reuse-sap)))
235 (setf (fd-stream-handler stream)
236 (add-fd-handler (fd-stream-fd stream)
239 (declare (ignore fd))
240 (frob-output-later stream)))))
242 (nconc (fd-stream-output-later stream)
243 (list (list base start end reuse-sap)))))
245 (let ((new-buffer (next-available-buffer)))
246 (setf (fd-stream-obuf-sap stream) new-buffer)
247 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
249 ;;; Output the given noise. Check to see whether there are any pending
250 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
251 ;;; this would block, queue it.
252 (defun frob-output (stream base start end reuse-sap)
253 (declare (type fd-stream stream)
254 (type (or system-area-pointer (simple-array * (*))) base)
255 (type index start end))
256 (if (not (null (fd-stream-output-later stream))) ; something buffered.
257 (output-later stream base start end reuse-sap)
258 ;; ### check to see whether any of this noise can be output
259 (let ((length (- end start)))
260 (multiple-value-bind (count errno)
261 (sb!unix:unix-write (fd-stream-fd stream) base start length)
264 (simple-stream-perror "Couldn't write to ~S" stream errno)
266 (if (= errno sb!unix:ewouldblock)
267 (output-later stream base start end reuse-sap)
268 (simple-stream-perror "Couldn't write to ~S"
270 ((not (eql count length))
271 (output-later stream base (the index (+ start count))
274 ;;; Flush any data in the output buffer.
275 (defun flush-output-buffer (stream)
276 (let ((length (fd-stream-obuf-tail stream)))
278 (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
279 (setf (fd-stream-obuf-tail stream) 0))))
281 (defun fd-stream-output-finished-p (stream)
282 (and (zerop (fd-stream-obuf-tail stream))
283 (not (fd-stream-output-later stream))))
285 (defmacro output-wrapper/variable-width ((stream size buffering restart)
287 (let ((stream-var (gensym)))
288 `(let ((,stream-var ,stream)
290 ,(unless (eq (car buffering) :none)
291 `(when (< (fd-stream-obuf-length ,stream-var)
292 (+ (fd-stream-obuf-tail ,stream-var)
294 (flush-output-buffer ,stream-var)))
295 ,(unless (eq (car buffering) :none)
296 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
297 (> (fd-stream-ibuf-tail ,stream-var)
298 (fd-stream-ibuf-head ,stream-var)))
299 (file-position ,stream-var (file-position ,stream-var))))
301 `(catch 'output-nothing
303 (incf (fd-stream-obuf-tail ,stream-var) size))
306 (incf (fd-stream-obuf-tail ,stream-var) size)))
307 ,(ecase (car buffering)
309 `(flush-output-buffer ,stream-var))
311 `(when (eq (char-code byte) (char-code #\Newline))
312 (flush-output-buffer ,stream-var)))
316 (defmacro output-wrapper ((stream size buffering restart) &body body)
317 (let ((stream-var (gensym)))
318 `(let ((,stream-var ,stream))
319 ,(unless (eq (car buffering) :none)
320 `(when (< (fd-stream-obuf-length ,stream-var)
321 (+ (fd-stream-obuf-tail ,stream-var)
323 (flush-output-buffer ,stream-var)))
324 ,(unless (eq (car buffering) :none)
325 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
326 (> (fd-stream-ibuf-tail ,stream-var)
327 (fd-stream-ibuf-head ,stream-var)))
328 (file-position ,stream-var (file-position ,stream-var))))
330 `(catch 'output-nothing
332 (incf (fd-stream-obuf-tail ,stream-var) ,size))
335 (incf (fd-stream-obuf-tail ,stream-var) ,size)))
336 ,(ecase (car buffering)
338 `(flush-output-buffer ,stream-var))
340 `(when (eq (char-code byte) (char-code #\Newline))
341 (flush-output-buffer ,stream-var)))
345 (defmacro def-output-routines/variable-width
346 ((name-fmt size restart external-format &rest bufferings)
348 (declare (optimize (speed 1)))
353 (intern (format nil name-fmt (string (car buffering))))))
355 (defun ,function (stream byte)
356 (declare (ignorable byte))
357 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
359 (setf *output-routines*
360 (nconc *output-routines*
368 (cdr buffering)))))))
371 ;;; Define output routines that output numbers SIZE bytes long for the
372 ;;; given bufferings. Use BODY to do the actual output.
373 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
375 (declare (optimize (speed 1)))
380 (intern (format nil name-fmt (string (car buffering))))))
382 (defun ,function (stream byte)
383 (output-wrapper (stream ,size ,buffering ,restart)
385 (setf *output-routines*
386 (nconc *output-routines*
394 (cdr buffering)))))))
397 ;;; FIXME: is this used anywhere any more?
398 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
404 (if (char= byte #\Newline)
405 (setf (fd-stream-char-pos stream) 0)
406 (incf (fd-stream-char-pos stream)))
407 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
410 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
413 (:none (unsigned-byte 8))
414 (:full (unsigned-byte 8)))
415 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
418 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
421 (:none (signed-byte 8))
422 (:full (signed-byte 8)))
423 (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
424 (fd-stream-obuf-tail stream))
427 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
430 (:none (unsigned-byte 16))
431 (:full (unsigned-byte 16)))
432 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
435 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
438 (:none (signed-byte 16))
439 (:full (signed-byte 16)))
440 (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
441 (fd-stream-obuf-tail stream))
444 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
447 (:none (unsigned-byte 32))
448 (:full (unsigned-byte 32)))
449 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
452 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
455 (:none (signed-byte 32))
456 (:full (signed-byte 32)))
457 (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
458 (fd-stream-obuf-tail stream))
461 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
463 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
466 (:none (unsigned-byte 64))
467 (:full (unsigned-byte 64)))
468 (setf (sap-ref-64 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
470 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
473 (:none (signed-byte 64))
474 (:full (signed-byte 64)))
475 (setf (signed-sap-ref-64 (fd-stream-obuf-sap stream)
476 (fd-stream-obuf-tail stream))
479 ;;; Do the actual output. If there is space to buffer the string,
480 ;;; buffer it. If the string would normally fit in the buffer, but
481 ;;; doesn't because of other stuff in the buffer, flush the old noise
482 ;;; out of the buffer and put the string in it. Otherwise we have a
483 ;;; very long string, so just send it directly (after flushing the
484 ;;; buffer, of course).
485 (defun output-raw-bytes (fd-stream thing &optional start end)
487 "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
488 THING is a SAP, END must be supplied (as length won't work)."
489 (let ((start (or start 0))
490 (end (or end (length (the (simple-array * (*)) thing)))))
491 (declare (type index start end))
492 (when (and (not (fd-stream-dual-channel-p fd-stream))
493 (> (fd-stream-ibuf-tail fd-stream)
494 (fd-stream-ibuf-head fd-stream)))
495 (file-position fd-stream (file-position fd-stream)))
496 (let* ((len (fd-stream-obuf-length fd-stream))
497 (tail (fd-stream-obuf-tail fd-stream))
499 (bytes (- end start))
500 (newtail (+ tail bytes)))
501 (cond ((minusp bytes) ; error case
502 (error ":END before :START!"))
503 ((zerop bytes)) ; easy case
505 (if (system-area-pointer-p thing)
506 (system-area-ub8-copy thing start
507 (fd-stream-obuf-sap fd-stream)
510 ;; FIXME: There should be some type checking somewhere to
511 ;; verify that THING here is a vector, not just <not a SAP>.
512 (copy-ub8-to-system-area thing start
513 (fd-stream-obuf-sap fd-stream)
516 (setf (fd-stream-obuf-tail fd-stream) newtail))
518 (flush-output-buffer fd-stream)
519 (if (system-area-pointer-p thing)
520 (system-area-ub8-copy thing
522 (fd-stream-obuf-sap fd-stream)
525 ;; FIXME: There should be some type checking somewhere to
526 ;; verify that THING here is a vector, not just <not a SAP>.
527 (copy-ub8-to-system-area thing
529 (fd-stream-obuf-sap fd-stream)
532 (setf (fd-stream-obuf-tail fd-stream) bytes))
534 (flush-output-buffer fd-stream)
535 (frob-output fd-stream thing start end nil))))))
537 ;;; the routine to use to output a string. If the stream is
538 ;;; unbuffered, slam the string down the file descriptor, otherwise
539 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
540 ;;; checking to see where the last newline was.
542 ;;; Note: some bozos (the FASL dumper) call write-string with things
543 ;;; other than strings. Therefore, we must make sure we have a string
544 ;;; before calling POSITION on it.
545 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
546 ;;; cover for them here. -- WHN 20000203
547 (defun fd-sout (stream thing start end)
548 (let ((start (or start 0))
549 (end (or end (length (the vector thing)))))
550 (declare (fixnum start end))
553 (string-dispatch (simple-base-string
555 (simple-array character)
558 (position #\newline thing :from-end t
559 :start start :end end))))
560 (if (and (typep thing 'base-string)
561 (eq (fd-stream-external-format stream) :latin-1))
562 (ecase (fd-stream-buffering stream)
564 (output-raw-bytes stream thing start end))
566 (output-raw-bytes stream thing start end)
568 (flush-output-buffer stream)))
570 (frob-output stream thing start end nil)))
571 (ecase (fd-stream-buffering stream)
572 (:full (funcall (fd-stream-output-bytes stream)
573 stream thing nil start end))
574 (:line (funcall (fd-stream-output-bytes stream)
575 stream thing last-newline start end))
576 (:none (funcall (fd-stream-output-bytes stream)
577 stream thing t start end))))
579 (setf (fd-stream-char-pos stream)
580 (- end last-newline 1))
581 (incf (fd-stream-char-pos stream)
583 (ecase (fd-stream-buffering stream)
585 (output-raw-bytes stream thing start end))
587 (frob-output stream thing start end nil))))))
589 (defvar *external-formats* ()
591 "List of all available external formats. Each element is a list of the
592 element-type, string input function name, character input function name,
593 and string output function name.")
595 (defun get-external-format (external-format)
596 (dolist (entry *external-formats*)
597 (when (member external-format (first entry))
600 (defun get-external-format-function (external-format index)
601 (let ((entry (get-external-format external-format)))
602 (when entry (nth index entry))))
604 ;;; Find an output routine to use given the type and buffering. Return
605 ;;; as multiple values the routine, the real type transfered, and the
606 ;;; number of bytes per element.
607 (defun pick-output-routine (type buffering &optional external-format)
608 (when (subtypep type 'character)
609 (let ((entry (get-external-format external-format)))
611 (return-from pick-output-routine
612 (values (symbol-function (nth (ecase buffering
619 (symbol-function (fourth entry))
620 (first (first entry)))))))
621 (dolist (entry *output-routines*)
622 (when (and (subtypep type (first entry))
623 (eq buffering (second entry))
624 (or (not (fifth entry))
625 (eq external-format (fifth entry))))
626 (return-from pick-output-routine
627 (values (symbol-function (third entry))
630 ;; KLUDGE: dealing with the buffering here leads to excessive code
633 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
634 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
635 if (subtypep type `(unsigned-byte ,i))
636 do (return-from pick-output-routine
640 (lambda (stream byte)
641 (output-wrapper (stream (/ i 8) (:none) nil)
642 (loop for j from 0 below (/ i 8)
644 (fd-stream-obuf-sap stream)
645 (+ j (fd-stream-obuf-tail stream)))
646 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
648 (lambda (stream byte)
649 (output-wrapper (stream (/ i 8) (:full) nil)
650 (loop for j from 0 below (/ i 8)
652 (fd-stream-obuf-sap stream)
653 (+ j (fd-stream-obuf-tail stream)))
654 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
657 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
658 if (subtypep type `(signed-byte ,i))
659 do (return-from pick-output-routine
663 (lambda (stream byte)
664 (output-wrapper (stream (/ i 8) (:none) nil)
665 (loop for j from 0 below (/ i 8)
667 (fd-stream-obuf-sap stream)
668 (+ j (fd-stream-obuf-tail stream)))
669 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
671 (lambda (stream byte)
672 (output-wrapper (stream (/ i 8) (:full) nil)
673 (loop for j from 0 below (/ i 8)
675 (fd-stream-obuf-sap stream)
676 (+ j (fd-stream-obuf-tail stream)))
677 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
681 ;;;; input routines and related noise
683 ;;; a list of all available input routines. Each element is a list of
684 ;;; the element-type input, the function name, and the number of bytes
686 (defvar *input-routines* ())
688 ;;; Return whether a primitive partial read operation on STREAM's FD
689 ;;; would (probably) block. Signal a `simple-stream-error' if the
690 ;;; system call implementing this operation fails.
692 ;;; It is "may" instead of "would" because "would" is not quite
693 ;;; correct on win32. However, none of the places that use it require
694 ;;; further assurance than "may" versus "will definitely not".
695 (defun sysread-may-block-p (stream)
697 ;; This answers T at EOF on win32, I think.
698 (not (sb!win32:fd-listen (fd-stream-fd stream)))
700 (sb!unix:with-restarted-syscall (count errno)
701 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
702 (sb!unix:fd-zero read-fds)
703 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
704 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
705 (sb!alien:addr read-fds)
711 (simple-stream-perror "couldn't check whether ~S is readable"
715 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
716 ;;; then fill the input buffer, and return the number of bytes read. Throws
717 ;;; to EOF-INPUT-CATCHER if the eof was reached.
718 (defun refill-buffer/fd (stream)
719 (let ((fd (fd-stream-fd stream))
723 ;; Check for blocking input before touching the stream, as if
724 ;; we happen to wait we are liable to be interrupted, and the
725 ;; interrupt handler may use the same stream.
726 (if (sysread-may-block-p stream)
729 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
730 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
732 (closed-flame stream)
734 (simple-stream-perror "couldn't read from ~S" stream errno)
736 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
737 ;; to wait for input if read tells us EWOULDBLOCK.
738 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
739 (signal-timeout 'io-timeout :stream stream :direction :read
740 :seconds (fd-stream-timeout stream)))
742 ;; Since the read should not block, we'll disable the
743 ;; interrupts here, so that we don't accidentally unwind and
744 ;; leave the stream in an inconsistent state.
746 (let ((ibuf-sap (fd-stream-ibuf-sap stream))
747 (buflen (fd-stream-ibuf-length stream))
748 (head (fd-stream-ibuf-head stream))
749 (tail (fd-stream-ibuf-tail stream)))
750 (declare (type index head tail))
751 ;; Check the SAP: if it is null, then someone has closed
752 ;; the stream from underneath us. This is not ment to fix
753 ;; multithreaded races, but to deal with interrupt handlers
754 ;; closing the stream.
758 (cond ((eql head tail)
761 (fd-stream-ibuf-head stream) 0
762 (fd-stream-ibuf-tail stream) 0))
765 (system-area-ub8-copy ibuf-sap head
768 (fd-stream-ibuf-head stream) 0
769 (fd-stream-ibuf-tail stream) tail))))
770 (setf (fd-stream-listen stream) nil)
771 (setf (values count errno)
772 (sb!unix:unix-read fd (int-sap (+ (sap-int ibuf-sap) tail))
778 (if (eql errno sb!unix:ewouldblock)
782 (setf (fd-stream-listen stream) :eof)
783 (/show0 "THROWing EOF-INPUT-CATCHER")
784 (throw 'eof-input-catcher nil))
787 (incf (fd-stream-ibuf-tail stream) count))))))
790 ;;; Make sure there are at least BYTES number of bytes in the input
791 ;;; buffer. Keep calling REFILL-BUFFER/FD until that condition is met.
792 (defmacro input-at-least (stream bytes)
793 (let ((stream-var (gensym))
794 (bytes-var (gensym)))
795 `(let ((,stream-var ,stream)
798 (when (>= (- (fd-stream-ibuf-tail ,stream-var)
799 (fd-stream-ibuf-head ,stream-var))
802 (refill-buffer/fd ,stream-var)))))
804 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
806 (let ((stream-var (gensym))
808 (element-var (gensym)))
809 `(let ((,stream-var ,stream)
811 (if (fd-stream-unread ,stream-var)
813 (fd-stream-unread ,stream-var)
814 (setf (fd-stream-unread ,stream-var) nil)
815 (setf (fd-stream-listen ,stream-var) nil))
816 (let ((,element-var nil)
817 (decode-break-reason nil))
821 (catch 'eof-input-catcher
822 (setf decode-break-reason
823 (block decode-break-reason
824 (input-at-least ,stream-var 1)
825 (let* ((byte (sap-ref-8 (fd-stream-ibuf-sap
829 (declare (ignorable byte))
831 (input-at-least ,stream-var size)
832 (setq ,element-var (locally ,@read-forms))
833 (setq ,retry-var nil))
835 (when decode-break-reason
836 (stream-decoding-error-and-handle stream
837 decode-break-reason))
839 (let ((octet-count (- (fd-stream-ibuf-tail ,stream-var)
840 (fd-stream-ibuf-head ,stream-var))))
841 (when (or (zerop octet-count)
842 (and (not ,element-var)
843 (not decode-break-reason)
844 (stream-decoding-error-and-handle
845 stream octet-count)))
846 (setq ,retry-var nil)))))
848 (incf (fd-stream-ibuf-head ,stream-var) size)
851 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
853 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
854 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
855 (let ((stream-var (gensym))
856 (element-var (gensym)))
857 `(let ((,stream-var ,stream))
858 (if (fd-stream-unread ,stream-var)
860 (fd-stream-unread ,stream-var)
861 (setf (fd-stream-unread ,stream-var) nil)
862 (setf (fd-stream-listen ,stream-var) nil))
864 (catch 'eof-input-catcher
865 (input-at-least ,stream-var ,bytes)
866 (locally ,@read-forms))))
868 (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
871 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
873 (defmacro def-input-routine/variable-width (name
874 (type external-format size sap head)
877 (defun ,name (stream eof-error eof-value)
878 (input-wrapper/variable-width (stream ,size eof-error eof-value)
879 (let ((,sap (fd-stream-ibuf-sap stream))
880 (,head (fd-stream-ibuf-head stream)))
882 (setf *input-routines*
883 (nconc *input-routines*
884 (list (list ',type ',name 1 ',external-format))))))
886 (defmacro def-input-routine (name
890 (defun ,name (stream eof-error eof-value)
891 (input-wrapper (stream ,size eof-error eof-value)
892 (let ((,sap (fd-stream-ibuf-sap stream))
893 (,head (fd-stream-ibuf-head stream)))
895 (setf *input-routines*
896 (nconc *input-routines*
897 (list (list ',type ',name ',size nil))))))
899 ;;; STREAM-IN routine for reading a string char
900 (def-input-routine input-character
901 (character 1 sap head)
902 (code-char (sap-ref-8 sap head)))
904 ;;; STREAM-IN routine for reading an unsigned 8 bit number
905 (def-input-routine input-unsigned-8bit-byte
906 ((unsigned-byte 8) 1 sap head)
907 (sap-ref-8 sap head))
909 ;;; STREAM-IN routine for reading a signed 8 bit number
910 (def-input-routine input-signed-8bit-number
911 ((signed-byte 8) 1 sap head)
912 (signed-sap-ref-8 sap head))
914 ;;; STREAM-IN routine for reading an unsigned 16 bit number
915 (def-input-routine input-unsigned-16bit-byte
916 ((unsigned-byte 16) 2 sap head)
917 (sap-ref-16 sap head))
919 ;;; STREAM-IN routine for reading a signed 16 bit number
920 (def-input-routine input-signed-16bit-byte
921 ((signed-byte 16) 2 sap head)
922 (signed-sap-ref-16 sap head))
924 ;;; STREAM-IN routine for reading a unsigned 32 bit number
925 (def-input-routine input-unsigned-32bit-byte
926 ((unsigned-byte 32) 4 sap head)
927 (sap-ref-32 sap head))
929 ;;; STREAM-IN routine for reading a signed 32 bit number
930 (def-input-routine input-signed-32bit-byte
931 ((signed-byte 32) 4 sap head)
932 (signed-sap-ref-32 sap head))
934 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
936 (def-input-routine input-unsigned-64bit-byte
937 ((unsigned-byte 64) 8 sap head)
938 (sap-ref-64 sap head))
939 (def-input-routine input-signed-64bit-byte
940 ((signed-byte 64) 8 sap head)
941 (signed-sap-ref-64 sap head)))
943 ;;; Find an input routine to use given the type. Return as multiple
944 ;;; values the routine, the real type transfered, and the number of
945 ;;; bytes per element (and for character types string input routine).
946 (defun pick-input-routine (type &optional external-format)
947 (when (subtypep type 'character)
948 (dolist (entry *external-formats*)
949 (when (member external-format (first entry))
950 (return-from pick-input-routine
951 (values (symbol-function (third entry))
954 (symbol-function (second entry))
955 (first (first entry)))))))
956 (dolist (entry *input-routines*)
957 (when (and (subtypep type (first entry))
958 (or (not (fourth entry))
959 (eq external-format (fourth entry))))
960 (return-from pick-input-routine
961 (values (symbol-function (second entry))
964 ;; FIXME: let's do it the hard way, then (but ignore things like
965 ;; endianness, efficiency, and the necessary coupling between these
966 ;; and the output routines). -- CSR, 2004-02-09
967 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
968 if (subtypep type `(unsigned-byte ,i))
969 do (return-from pick-input-routine
971 (lambda (stream eof-error eof-value)
972 (input-wrapper (stream (/ i 8) eof-error eof-value)
973 (let ((sap (fd-stream-ibuf-sap stream))
974 (head (fd-stream-ibuf-head stream)))
975 (loop for j from 0 below (/ i 8)
979 (sap-ref-8 sap (+ head j))))
980 finally (return result)))))
983 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
984 if (subtypep type `(signed-byte ,i))
985 do (return-from pick-input-routine
987 (lambda (stream eof-error eof-value)
988 (input-wrapper (stream (/ i 8) eof-error eof-value)
989 (let ((sap (fd-stream-ibuf-sap stream))
990 (head (fd-stream-ibuf-head stream)))
991 (loop for j from 0 below (/ i 8)
995 (sap-ref-8 sap (+ head j))))
996 finally (return (if (logbitp (1- i) result)
997 (dpb result (byte i 0) -1)
1002 ;;; Return a string constructed from SAP, START, and END.
1003 (defun string-from-sap (sap start end)
1004 (declare (type index start end))
1005 (let* ((length (- end start))
1006 (string (make-string length)))
1007 (copy-ub8-from-system-area sap start
1012 ;;; the N-BIN method for FD-STREAMs
1014 ;;; Note that this blocks in UNIX-READ. It is generally used where
1015 ;;; there is a definite amount of reading to be done, so blocking
1016 ;;; isn't too problematical.
1017 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1018 &aux (total-copied 0))
1019 (declare (type fd-stream stream))
1020 (declare (type index start requested total-copied))
1021 (let ((unread (fd-stream-unread stream)))
1023 ;; AVERs designed to fail when we have more complicated
1024 ;; character representations.
1025 (aver (typep unread 'base-char))
1026 (aver (= (fd-stream-element-size stream) 1))
1027 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1030 (system-area-pointer
1031 (setf (sap-ref-8 buffer start) (char-code unread)))
1032 ((simple-unboxed-array (*))
1033 (setf (aref buffer start) unread)))
1034 (setf (fd-stream-unread stream) nil)
1035 (setf (fd-stream-listen stream) nil)
1036 (incf total-copied)))
1039 (let* ((remaining-request (- requested total-copied))
1040 (head (fd-stream-ibuf-head stream))
1041 (tail (fd-stream-ibuf-tail stream))
1042 (available (- tail head))
1043 (n-this-copy (min remaining-request available))
1044 (this-start (+ start total-copied))
1045 (this-end (+ this-start n-this-copy))
1046 (sap (fd-stream-ibuf-sap stream)))
1047 (declare (type index remaining-request head tail available))
1048 (declare (type index n-this-copy))
1049 ;; Copy data from stream buffer into user's buffer.
1050 (%byte-blt sap head buffer this-start this-end)
1051 (incf (fd-stream-ibuf-head stream) n-this-copy)
1052 (incf total-copied n-this-copy)
1053 ;; Maybe we need to refill the stream buffer.
1054 (cond (;; If there were enough data in the stream buffer, we're done.
1055 (= total-copied requested)
1056 (return total-copied))
1057 (;; If EOF, we're done in another way.
1058 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1060 (error 'end-of-file :stream stream)
1061 (return total-copied)))
1062 ;; Otherwise we refilled the stream buffer, so fall
1063 ;; through into another pass of the loop.
1066 (defun fd-stream-resync (stream)
1067 (dolist (entry *external-formats*)
1068 (when (member (fd-stream-external-format stream) (first entry))
1069 (return-from fd-stream-resync
1070 (funcall (symbol-function (eighth entry)) stream)))))
1072 (defun get-fd-stream-character-sizer (stream)
1073 (dolist (entry *external-formats*)
1074 (when (member (fd-stream-external-format stream) (first entry))
1075 (return-from get-fd-stream-character-sizer (ninth entry)))))
1077 (defun fd-stream-character-size (stream char)
1078 (let ((sizer (get-fd-stream-character-sizer stream)))
1079 (when sizer (funcall sizer char))))
1081 (defun fd-stream-string-size (stream string)
1082 (let ((sizer (get-fd-stream-character-sizer stream)))
1084 (loop for char across string summing (funcall sizer char)))))
1086 (defun find-external-format (external-format)
1087 (when external-format
1088 (find external-format *external-formats* :test #'member :key #'car)))
1090 (defun variable-width-external-format-p (ef-entry)
1091 (when (eighth ef-entry) t))
1093 (defun bytes-for-char-fun (ef-entry)
1094 (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1096 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1097 (defmacro define-external-format (external-format size output-restart
1099 (let* ((name (first external-format))
1100 (out-function (symbolicate "OUTPUT-BYTES/" name))
1101 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1102 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1103 (in-char-function (symbolicate "INPUT-CHAR/" name))
1104 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1105 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1106 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1107 (n-buffer (gensym "BUFFER")))
1109 (defun ,size-function (byte)
1110 (declare (ignore byte))
1112 (defun ,out-function (stream string flush-p start end)
1113 (let ((start (or start 0))
1114 (end (or end (length string))))
1115 (declare (type index start end))
1116 (when (and (not (fd-stream-dual-channel-p stream))
1117 (> (fd-stream-ibuf-tail stream)
1118 (fd-stream-ibuf-head stream)))
1119 (file-position stream (file-position stream)))
1120 (unless (<= 0 start end (length string))
1121 (signal-bounding-indices-bad-error string start end))
1124 (setf (fd-stream-obuf-tail stream)
1125 (string-dispatch (simple-base-string
1127 (simple-array character)
1130 (let ((len (fd-stream-obuf-length stream))
1131 (sap (fd-stream-obuf-sap stream))
1132 (tail (fd-stream-obuf-tail stream)))
1133 (declare (type index tail)
1134 ;; STRING bounds have already been checked.
1135 (optimize (safety 0)))
1137 (,@(if output-restart
1138 `(catch 'output-nothing)
1141 ((or (= start end) (< (- len tail) 4)))
1142 (let* ((byte (aref string start))
1143 (bits (char-code byte)))
1147 ;; Exited from the loop normally
1149 ;; Exited via CATCH. Skip the current character
1150 ;; and try the inner loop again.
1153 (flush-output-buffer stream)))
1155 (flush-output-buffer stream))))
1156 (def-output-routines (,format
1162 (if (char= byte #\Newline)
1163 (setf (fd-stream-char-pos stream) 0)
1164 (incf (fd-stream-char-pos stream)))
1165 (let ((bits (char-code byte))
1166 (sap (fd-stream-obuf-sap stream))
1167 (tail (fd-stream-obuf-tail stream)))
1169 (defun ,in-function (stream buffer start requested eof-error-p
1170 &aux (index start) (end (+ start requested)))
1171 (declare (type fd-stream stream)
1172 (type index start requested index end)
1174 (simple-array character (#.+ansi-stream-in-buffer-length+))
1176 (let ((unread (fd-stream-unread stream)))
1178 (setf (aref buffer index) unread)
1179 (setf (fd-stream-unread stream) nil)
1180 (setf (fd-stream-listen stream) nil)
1184 (let* ((head (fd-stream-ibuf-head stream))
1185 (tail (fd-stream-ibuf-tail stream))
1186 (sap (fd-stream-ibuf-sap stream)))
1187 (declare (type index head tail)
1188 (type system-area-pointer sap))
1189 ;; Copy data from stream buffer into user's buffer.
1190 (dotimes (i (min (truncate (- tail head) ,size)
1192 (declare (optimize speed))
1193 (let* ((byte (sap-ref-8 sap head)))
1194 (setf (aref buffer index) ,in-expr)
1197 (setf (fd-stream-ibuf-head stream) head)
1198 ;; Maybe we need to refill the stream buffer.
1199 (cond ( ;; If there was enough data in the stream buffer, we're done.
1201 (return (- index start)))
1202 ( ;; If EOF, we're done in another way.
1203 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1205 (error 'end-of-file :stream stream)
1206 (return (- index start))))
1207 ;; Otherwise we refilled the stream buffer, so fall
1208 ;; through into another pass of the loop.
1210 (def-input-routine ,in-char-function (character ,size sap head)
1211 (let ((byte (sap-ref-8 sap head)))
1213 (defun ,read-c-string-function (sap element-type)
1214 (declare (type system-area-pointer sap)
1215 (type (member character base-char) element-type))
1217 (declare (optimize (speed 3) (safety 0)))
1218 (let* ((stream ,name)
1220 (loop for head of-type index upfrom 0 by ,size
1221 for count of-type index upto (1- array-dimension-limit)
1222 for byte = (sap-ref-8 sap head)
1223 for char of-type character = ,in-expr
1224 until (zerop (char-code char))
1225 finally (return count)))
1226 ;; Inline the common cases
1227 (string (make-string length :element-type element-type)))
1228 (declare (ignorable stream)
1230 (type simple-string string))
1231 (/show0 before-copy-loop)
1232 (loop for head of-type index upfrom 0 by ,size
1233 for index of-type index below length
1234 for byte = (sap-ref-8 sap head)
1235 for char of-type character = ,in-expr
1236 do (setf (aref string index) char))
1237 string))) ;; last loop rewrite to dotimes?
1238 (defun ,output-c-string-function (string)
1239 (declare (type simple-string string))
1241 (declare (optimize (speed 3) (safety 0)))
1242 (let* ((length (length string))
1243 (,n-buffer (make-array (* (1+ length) ,size)
1244 :element-type '(unsigned-byte 8)))
1245 ;; This SAP-taking may seem unsafe without pinning,
1246 ;; but since the variable name is a gensym OUT-EXPR
1247 ;; cannot close over it even if it tried, so the buffer
1248 ;; will always be either in a register or on stack.
1249 ;; FIXME: But ...this is true on x86oids only!
1250 (sap (vector-sap ,n-buffer))
1253 (declare (type index length tail)
1254 (type system-area-pointer sap))
1256 (let* ((byte (aref string i))
1257 (bits (char-code byte)))
1258 (declare (ignorable byte bits))
1262 (byte (code-char bits)))
1263 (declare (ignorable bits byte))
1266 (setf *external-formats*
1267 (cons '(,external-format ,in-function ,in-char-function ,out-function
1268 ,@(mapcar #'(lambda (buffering)
1269 (intern (format nil format (string buffering))))
1270 '(:none :line :full))
1271 nil ; no resync-function
1272 ,size-function ,read-c-string-function ,output-c-string-function)
1273 *external-formats*)))))
1275 (defmacro define-external-format/variable-width
1276 (external-format output-restart out-size-expr
1277 out-expr in-size-expr in-expr)
1278 (let* ((name (first external-format))
1279 (out-function (symbolicate "OUTPUT-BYTES/" name))
1280 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1281 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1282 (in-char-function (symbolicate "INPUT-CHAR/" name))
1283 (resync-function (symbolicate "RESYNC/" name))
1284 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1285 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1286 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1287 (n-buffer (gensym "BUFFER")))
1289 (defun ,size-function (byte)
1290 (declare (ignorable byte))
1292 (defun ,out-function (stream string flush-p start end)
1293 (let ((start (or start 0))
1294 (end (or end (length string))))
1295 (declare (type index start end))
1296 (when (and (not (fd-stream-dual-channel-p stream))
1297 (> (fd-stream-ibuf-tail stream)
1298 (fd-stream-ibuf-head stream)))
1299 (file-position stream (file-position stream)))
1300 (unless (<= 0 start end (length string))
1301 (signal-bounding-indices-bad-error string start end))
1304 (setf (fd-stream-obuf-tail stream)
1305 (string-dispatch (simple-base-string
1307 (simple-array character)
1310 (let ((len (fd-stream-obuf-length stream))
1311 (sap (fd-stream-obuf-sap stream))
1312 (tail (fd-stream-obuf-tail stream)))
1313 (declare (type index tail)
1314 ;; STRING bounds have already been checked.
1315 (optimize (safety 0)))
1317 (,@(if output-restart
1318 `(catch 'output-nothing)
1321 ((or (= start end) (< (- len tail) 4)))
1322 (let* ((byte (aref string start))
1323 (bits (char-code byte))
1324 (size ,out-size-expr))
1328 ;; Exited from the loop normally
1330 ;; Exited via CATCH. Skip the current character
1331 ;; and try the inner loop again.
1334 (flush-output-buffer stream)))
1336 (flush-output-buffer stream))))
1337 (def-output-routines/variable-width (,format
1344 (if (char= byte #\Newline)
1345 (setf (fd-stream-char-pos stream) 0)
1346 (incf (fd-stream-char-pos stream)))
1347 (let ((bits (char-code byte))
1348 (sap (fd-stream-obuf-sap stream))
1349 (tail (fd-stream-obuf-tail stream)))
1351 (defun ,in-function (stream buffer start requested eof-error-p
1352 &aux (total-copied 0))
1353 (declare (type fd-stream stream)
1354 (type index start requested total-copied)
1356 (simple-array character (#.+ansi-stream-in-buffer-length+))
1358 (let ((unread (fd-stream-unread stream)))
1360 (setf (aref buffer start) unread)
1361 (setf (fd-stream-unread stream) nil)
1362 (setf (fd-stream-listen stream) nil)
1363 (incf total-copied)))
1366 (let* ((head (fd-stream-ibuf-head stream))
1367 (tail (fd-stream-ibuf-tail stream))
1368 (sap (fd-stream-ibuf-sap stream))
1369 (decode-break-reason nil))
1370 (declare (type index head tail))
1371 ;; Copy data from stream buffer into user's buffer.
1372 (do ((size nil nil))
1373 ((or (= tail head) (= requested total-copied)))
1374 (setf decode-break-reason
1375 (block decode-break-reason
1376 (let ((byte (sap-ref-8 sap head)))
1377 (declare (ignorable byte))
1378 (setq size ,in-size-expr)
1379 (when (> size (- tail head))
1381 (setf (aref buffer (+ start total-copied)) ,in-expr)
1385 (setf (fd-stream-ibuf-head stream) head)
1386 (when decode-break-reason
1387 ;; If we've already read some characters on when the invalid
1388 ;; code sequence is detected, we return immediately. The
1389 ;; handling of the error is deferred until the next call
1390 ;; (where this check will be false). This allows establishing
1391 ;; high-level handlers for decode errors (for example
1392 ;; automatically resyncing in Lisp comments).
1393 (when (plusp total-copied)
1394 (return-from ,in-function total-copied))
1395 (when (stream-decoding-error-and-handle
1396 stream decode-break-reason)
1398 (error 'end-of-file :stream stream)
1399 (return-from ,in-function total-copied)))
1400 (setf head (fd-stream-ibuf-head stream))
1401 (setf tail (fd-stream-ibuf-tail stream))))
1402 (setf (fd-stream-ibuf-head stream) head)
1403 ;; Maybe we need to refill the stream buffer.
1404 (cond ( ;; If there were enough data in the stream buffer, we're done.
1405 (= total-copied requested)
1406 (return total-copied))
1407 ( ;; If EOF, we're done in another way.
1408 (or (eq decode-break-reason 'eof)
1409 (null (catch 'eof-input-catcher
1410 (refill-buffer/fd stream))))
1412 (error 'end-of-file :stream stream)
1413 (return total-copied)))
1414 ;; Otherwise we refilled the stream buffer, so fall
1415 ;; through into another pass of the loop.
1417 (def-input-routine/variable-width ,in-char-function (character
1421 (let ((byte (sap-ref-8 sap head)))
1422 (declare (ignorable byte))
1424 (defun ,resync-function (stream)
1425 (loop (input-at-least stream 2)
1426 (incf (fd-stream-ibuf-head stream))
1427 (unless (block decode-break-reason
1428 (let* ((sap (fd-stream-ibuf-sap stream))
1429 (head (fd-stream-ibuf-head stream))
1430 (byte (sap-ref-8 sap head))
1431 (size ,in-size-expr))
1432 (declare (ignorable byte))
1433 (input-at-least stream size)
1434 (let ((sap (fd-stream-ibuf-sap stream))
1435 (head (fd-stream-ibuf-head stream)))
1439 (defun ,read-c-string-function (sap element-type)
1440 (declare (type system-area-pointer sap))
1442 (declare (optimize (speed 3) (safety 0)))
1443 (let* ((stream ,name)
1444 (size 0) (head 0) (byte 0) (char nil)
1445 (decode-break-reason nil)
1446 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1447 (setf decode-break-reason
1448 (block decode-break-reason
1449 (setf byte (sap-ref-8 sap head)
1454 (when decode-break-reason
1455 (c-string-decoding-error ,name decode-break-reason))
1456 (when (zerop (char-code char))
1458 (string (make-string length :element-type element-type)))
1459 (declare (ignorable stream)
1460 (type index head length) ;; size
1461 (type (unsigned-byte 8) byte)
1462 (type (or null character) char)
1463 (type string string))
1465 (dotimes (index length string)
1466 (setf decode-break-reason
1467 (block decode-break-reason
1468 (setf byte (sap-ref-8 sap head)
1473 (when decode-break-reason
1474 (c-string-decoding-error ,name decode-break-reason))
1475 (setf (aref string index) char)))))
1477 (defun ,output-c-string-function (string)
1478 (declare (type simple-string string))
1480 (declare (optimize (speed 3) (safety 0)))
1481 (let* ((length (length string))
1482 (char-length (make-array (1+ length) :element-type 'index))
1484 (+ (loop for i of-type index below length
1485 for byte of-type character = (aref string i)
1486 for bits = (char-code byte)
1487 sum (setf (aref char-length i)
1488 (the index ,out-size-expr)))
1489 (let* ((byte (code-char 0))
1490 (bits (char-code byte)))
1491 (declare (ignorable byte bits))
1492 (setf (aref char-length length)
1493 (the index ,out-size-expr)))))
1495 (,n-buffer (make-array buffer-length
1496 :element-type '(unsigned-byte 8)))
1497 ;; This SAP-taking may seem unsafe without pinning,
1498 ;; but since the variable name is a gensym OUT-EXPR
1499 ;; cannot close over it even if it tried, so the buffer
1500 ;; will always be either in a register or on stack.
1501 ;; FIXME: But ...this is true on x86oids only!
1502 (sap (vector-sap ,n-buffer))
1504 (declare (type index length buffer-length tail)
1505 (type system-area-pointer sap)
1508 (loop for i of-type index below length
1509 for byte of-type character = (aref string i)
1510 for bits = (char-code byte)
1511 for size of-type index = (aref char-length i)
1516 (byte (code-char bits))
1517 (size (aref char-length length)))
1518 (declare (ignorable bits byte size))
1522 (setf *external-formats*
1523 (cons '(,external-format ,in-function ,in-char-function ,out-function
1524 ,@(mapcar #'(lambda (buffering)
1525 (intern (format nil format (string buffering))))
1526 '(:none :line :full))
1528 ,size-function ,read-c-string-function ,output-c-string-function)
1529 *external-formats*)))))
1531 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1532 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1533 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1534 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1537 (external-format-encoding-error stream bits)
1538 (setf (sap-ref-8 sap tail) bits))
1541 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1542 :iso-646 :iso-646-us :|646|)
1545 (external-format-encoding-error stream bits)
1546 (setf (sap-ref-8 sap tail) bits))
1549 (let* ((table (let ((s (make-string 256)))
1550 (map-into s #'code-char
1551 '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1552 #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1553 #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1554 #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1555 #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1556 #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1557 #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1558 #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1559 #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1560 #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1561 #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1562 #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1563 #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1564 #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1565 #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1566 #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1568 (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1569 (loop for char across table for i from 0
1570 do (aver (= 0 (aref rt (char-code char))))
1571 do (setf (aref rt (char-code char)) i))
1573 (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1576 (external-format-encoding-error stream bits)
1577 (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1582 (let ((latin-9-table (let ((table (make-string 256)))
1585 (setf (aref table i) (code-char i)))
1586 (setf (aref table #xa4) (code-char #x20ac))
1587 (setf (aref table #xa6) (code-char #x0160))
1588 (setf (aref table #xa8) (code-char #x0161))
1589 (setf (aref table #xb4) (code-char #x017d))
1590 (setf (aref table #xb8) (code-char #x017e))
1591 (setf (aref table #xbc) (code-char #x0152))
1592 (setf (aref table #xbd) (code-char #x0153))
1593 (setf (aref table #xbe) (code-char #x0178))
1595 (latin-9-reverse-1 (make-array 16
1596 :element-type '(unsigned-byte 21)
1597 :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1598 (latin-9-reverse-2 (make-array 16
1599 :element-type '(unsigned-byte 8)
1600 :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1601 (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1603 (setf (sap-ref-8 sap tail)
1605 (if (= bits (char-code (aref latin-9-table bits)))
1607 (external-format-encoding-error stream byte))
1608 (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1609 (aref latin-9-reverse-2 (logand bits 15))
1610 (external-format-encoding-error stream byte))))
1611 (aref latin-9-table byte)))
1613 (define-external-format/variable-width (:utf-8 :utf8) nil
1614 (let ((bits (char-code byte)))
1615 (cond ((< bits #x80) 1)
1617 ((< bits #x10000) 3)
1620 (1 (setf (sap-ref-8 sap tail) bits))
1621 (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1622 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 0) bits))))
1623 (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1624 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 6) bits))
1625 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1626 (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1627 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 12) bits))
1628 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1629 (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1630 (cond ((< byte #x80) 1)
1631 ((< byte #xc2) (return-from decode-break-reason 1))
1635 (code-char (ecase size
1637 (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1638 (unless (<= #x80 byte2 #xbf)
1639 (return-from decode-break-reason 2))
1640 (dpb byte (byte 5 6) byte2)))
1641 (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1642 (byte3 (sap-ref-8 sap (+ 2 head))))
1643 (unless (and (<= #x80 byte2 #xbf)
1644 (<= #x80 byte3 #xbf))
1645 (return-from decode-break-reason 3))
1646 (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1647 (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1648 (byte3 (sap-ref-8 sap (+ 2 head)))
1649 (byte4 (sap-ref-8 sap (+ 3 head))))
1650 (unless (and (<= #x80 byte2 #xbf)
1651 (<= #x80 byte3 #xbf)
1652 (<= #x80 byte4 #xbf))
1653 (return-from decode-break-reason 4))
1654 (dpb byte (byte 3 18)
1655 (dpb byte2 (byte 6 12)
1656 (dpb byte3 (byte 6 6) byte4))))))))
1658 ;;;; utility functions (misc routines, etc)
1660 ;;; Fill in the various routine slots for the given type. INPUT-P and
1661 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1662 ;;; set prior to calling this routine.
1663 (defun set-fd-stream-routines (fd-stream element-type external-format
1664 input-p output-p buffer-p)
1665 (let* ((target-type (case element-type
1666 (unsigned-byte '(unsigned-byte 8))
1667 (signed-byte '(signed-byte 8))
1668 (:default 'character)
1670 (character-stream-p (subtypep target-type 'character))
1671 (bivalent-stream-p (eq element-type :default))
1672 normalized-external-format
1673 (bin-routine #'ill-bin)
1676 (cin-routine #'ill-in)
1679 (input-type nil) ;calculated from bin-type/cin-type
1680 (input-size nil) ;calculated from bin-size/cin-size
1681 (read-n-characters #'ill-in)
1682 (bout-routine #'ill-bout)
1685 (cout-routine #'ill-out)
1690 (output-bytes #'ill-bout))
1692 ;; drop buffers when direction changes
1693 (when (and (fd-stream-obuf-sap fd-stream) (not output-p))
1694 (with-available-buffers-lock ()
1695 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1696 (setf (fd-stream-obuf-sap fd-stream) nil)))
1697 (when (and (fd-stream-ibuf-sap fd-stream) (not input-p))
1698 (with-available-buffers-lock ()
1699 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1700 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1702 (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
1703 (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
1704 (setf (fd-stream-ibuf-tail fd-stream) 0))
1706 (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
1707 (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
1708 (setf (fd-stream-obuf-tail fd-stream) 0)
1709 (setf (fd-stream-char-pos fd-stream) 0))
1711 (when (and character-stream-p
1712 (eq external-format :default))
1713 (/show0 "/getting default external format")
1714 (setf external-format (default-external-format)))
1717 (when (or (not character-stream-p) bivalent-stream-p)
1718 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1719 normalized-external-format)
1720 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1724 (error "could not find any input routine for ~S" target-type)))
1725 (when character-stream-p
1726 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1727 normalized-external-format)
1728 (pick-input-routine target-type external-format))
1730 (error "could not find any input routine for ~S" target-type)))
1731 (setf (fd-stream-in fd-stream) cin-routine
1732 (fd-stream-bin fd-stream) bin-routine)
1733 ;; character type gets preferential treatment
1734 (setf input-size (or cin-size bin-size))
1735 (setf input-type (or cin-type bin-type))
1736 (when normalized-external-format
1737 (setf (fd-stream-external-format fd-stream)
1738 normalized-external-format))
1739 (when (= (or cin-size 1) (or bin-size 1) 1)
1740 (setf (fd-stream-n-bin fd-stream) ;XXX
1741 (if (and character-stream-p (not bivalent-stream-p))
1743 #'fd-stream-read-n-bytes))
1744 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1745 ;; for character and (unsigned-byte 8) streams. In these
1746 ;; cases, fast-read-* will read from the
1747 ;; ansi-stream-(c)in-buffer, saving function calls.
1748 ;; Otherwise, the various data-reading functions in the stream
1749 ;; structure will be called.
1751 (not bivalent-stream-p)
1752 ;; temporary disable on :io streams
1754 (cond (character-stream-p
1755 (setf (ansi-stream-cin-buffer fd-stream)
1756 (make-array +ansi-stream-in-buffer-length+
1757 :element-type 'character)))
1758 ((equal target-type '(unsigned-byte 8))
1759 (setf (ansi-stream-in-buffer fd-stream)
1760 (make-array +ansi-stream-in-buffer-length+
1761 :element-type '(unsigned-byte 8))))))))
1764 (when (or (not character-stream-p) bivalent-stream-p)
1765 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1766 normalized-external-format)
1767 (pick-output-routine (if bivalent-stream-p
1770 (fd-stream-buffering fd-stream)
1772 (unless bout-routine
1773 (error "could not find any output routine for ~S buffered ~S"
1774 (fd-stream-buffering fd-stream)
1776 (when character-stream-p
1777 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1778 normalized-external-format)
1779 (pick-output-routine target-type
1780 (fd-stream-buffering fd-stream)
1782 (unless cout-routine
1783 (error "could not find any output routine for ~S buffered ~S"
1784 (fd-stream-buffering fd-stream)
1786 (when normalized-external-format
1787 (setf (fd-stream-external-format fd-stream)
1788 normalized-external-format))
1789 (when character-stream-p
1790 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1791 (setf (fd-stream-out fd-stream) cout-routine
1792 (fd-stream-bout fd-stream) bout-routine
1793 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1794 #'fd-sout #'ill-out))
1795 (setf output-size (or cout-size bout-size))
1796 (setf output-type (or cout-type bout-type)))
1798 (when (and input-size output-size
1799 (not (eq input-size output-size)))
1800 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1801 input-type input-size
1802 output-type output-size))
1803 (setf (fd-stream-element-size fd-stream)
1804 (or input-size output-size))
1806 (setf (fd-stream-element-type fd-stream)
1807 (cond ((equal input-type output-type)
1813 ((subtypep input-type output-type)
1815 ((subtypep output-type input-type)
1818 (error "Input type (~S) and output type (~S) are unrelated?"
1822 ;;; Handle miscellaneous operations on FD-STREAM.
1823 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1824 (declare (ignore arg2))
1827 (labels ((do-listen ()
1828 (or (not (eql (fd-stream-ibuf-head fd-stream)
1829 (fd-stream-ibuf-tail fd-stream)))
1830 (fd-stream-listen fd-stream)
1832 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1834 ;; If the read can block, LISTEN will certainly return NIL.
1835 (if (sysread-may-block-p fd-stream)
1837 ;; Otherwise select(2) and CL:LISTEN have slightly
1838 ;; different semantics. The former returns that an FD
1839 ;; is readable when a read operation wouldn't block.
1840 ;; That includes EOF. However, LISTEN must return NIL
1842 (progn (catch 'eof-input-catcher
1843 ;; r-b/f too calls select, but it shouldn't
1844 ;; block as long as read can return once w/o
1846 (refill-buffer/fd fd-stream))
1847 ;; At this point either IBUF-HEAD != IBUF-TAIL
1848 ;; and FD-STREAM-LISTEN is NIL, in which case
1849 ;; we should return T, or IBUF-HEAD ==
1850 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1851 ;; which case we should return :EOF for this
1852 ;; call and all future LISTEN call on this stream.
1853 ;; Call ourselves again to determine which case
1858 (setf (fd-stream-unread fd-stream) arg1)
1859 (setf (fd-stream-listen fd-stream) t))
1861 (cond (arg1 ; We got us an abort on our hands.
1862 (when (fd-stream-handler fd-stream)
1863 (remove-fd-handler (fd-stream-handler fd-stream))
1864 (setf (fd-stream-handler fd-stream) nil))
1865 ;; We can't do anything unless we know what file were
1866 ;; dealing with, and we don't want to do anything
1867 ;; strange unless we were writing to the file.
1868 (when (and (fd-stream-file fd-stream)
1869 (fd-stream-obuf-sap fd-stream))
1870 (if (fd-stream-original fd-stream)
1871 ;; If the original is EQ to file we are appending
1872 ;; and can just close the file without renaming.
1873 (unless (eq (fd-stream-original fd-stream)
1874 (fd-stream-file fd-stream))
1875 ;; We have a handle on the original, just revert.
1876 (multiple-value-bind (okay err)
1877 (sb!unix:unix-rename (fd-stream-original fd-stream)
1878 (fd-stream-file fd-stream))
1880 (simple-stream-perror
1881 "couldn't restore ~S to its original contents"
1884 ;; We can't restore the original, and aren't
1885 ;; appending, so nuke that puppy.
1887 ;; FIXME: This is currently the fate of superseded
1888 ;; files, and according to the CLOSE spec this is
1889 ;; wrong. However, there seems to be no clean way to
1890 ;; do that that doesn't involve either copying the
1891 ;; data (bad if the :abort resulted from a full
1892 ;; disk), or renaming the old file temporarily
1893 ;; (probably bad because stream opening becomes more
1895 (multiple-value-bind (okay err)
1896 (sb!unix:unix-unlink (fd-stream-file fd-stream))
1898 (error 'simple-file-error
1899 :pathname (fd-stream-file fd-stream)
1901 "~@<couldn't remove ~S: ~2I~_~A~:>"
1902 :format-arguments (list (fd-stream-file fd-stream)
1903 (strerror err))))))))
1905 (fd-stream-misc-routine fd-stream :finish-output)
1906 (when (and (fd-stream-original fd-stream)
1907 (fd-stream-delete-original fd-stream))
1908 (multiple-value-bind (okay err)
1909 (sb!unix:unix-unlink (fd-stream-original fd-stream))
1911 (error 'simple-file-error
1912 :pathname (fd-stream-original fd-stream)
1914 "~@<couldn't delete ~S during close of ~S: ~
1917 (list (fd-stream-original fd-stream)
1919 (strerror err))))))))
1920 (when (fboundp 'cancel-finalization)
1921 (cancel-finalization fd-stream))
1922 (sb!unix:unix-close (fd-stream-fd fd-stream))
1923 (when (fd-stream-obuf-sap fd-stream)
1924 (with-available-buffers-lock ()
1925 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1926 (setf (fd-stream-obuf-sap fd-stream) nil)))
1927 (when (fd-stream-ibuf-sap fd-stream)
1928 (with-available-buffers-lock ()
1929 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1930 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1931 (sb!impl::set-closed-flame fd-stream))
1933 (setf (fd-stream-unread fd-stream) nil)
1934 (setf (fd-stream-ibuf-head fd-stream) 0)
1935 (setf (fd-stream-ibuf-tail fd-stream) 0)
1938 (sb!win32:fd-clear-input (fd-stream-fd fd-stream))
1939 (setf (fd-stream-listen fd-stream) nil))
1941 (catch 'eof-input-catcher
1942 (loop until (sysread-may-block-p fd-stream)
1944 (refill-buffer/fd fd-stream)
1945 (setf (fd-stream-ibuf-head fd-stream) 0)
1946 (setf (fd-stream-ibuf-tail fd-stream) 0))
1949 (flush-output-buffer fd-stream))
1951 (finish-fd-stream-output fd-stream))
1953 (fd-stream-element-type fd-stream))
1955 (fd-stream-external-format fd-stream))
1957 (= 1 (the (member 0 1)
1958 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
1962 (fd-stream-char-pos fd-stream))
1964 (unless (fd-stream-file fd-stream)
1965 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
1966 ;; "should signal an error of type TYPE-ERROR if stream is not
1967 ;; a stream associated with a file". Too bad there's no very
1968 ;; appropriate value for the EXPECTED-TYPE slot..
1969 (error 'simple-type-error
1971 :expected-type 'fd-stream
1972 :format-control "~S is not a stream associated with a file."
1973 :format-arguments (list fd-stream)))
1974 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
1975 atime mtime ctime blksize blocks)
1976 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
1977 (declare (ignore ino nlink uid gid rdev
1978 atime mtime ctime blksize blocks))
1980 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
1983 (truncate size (fd-stream-element-size fd-stream)))))
1984 (:file-string-length
1986 (character (fd-stream-character-size fd-stream arg1))
1987 (string (fd-stream-string-size fd-stream arg1))))
1990 (fd-stream-set-file-position fd-stream arg1)
1991 (fd-stream-get-file-position fd-stream)))))
1993 ;; FIXME: Think about this.
1995 ;; (defun finish-fd-stream-output (fd-stream)
1996 ;; (let ((timeout (fd-stream-timeout fd-stream)))
1997 ;; (loop while (fd-stream-output-later fd-stream)
1998 ;; ;; FIXME: SIGINT while waiting for a timeout will
1999 ;; ;; cause a timeout here.
2000 ;; do (when (and (not (serve-event timeout)) timeout)
2001 ;; (signal-timeout 'io-timeout
2002 ;; :stream fd-stream
2003 ;; :direction :write
2004 ;; :seconds timeout)))))
2006 (defun finish-fd-stream-output (stream)
2007 (flush-output-buffer stream)
2009 ((null (fd-stream-output-later stream)))
2010 (serve-all-events)))
2012 (defun fd-stream-get-file-position (stream)
2013 (declare (fd-stream stream))
2015 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2016 (declare (type (or (alien sb!unix:off-t) null) posn))
2017 ;; We used to return NIL for errno==ESPIPE, and signal an error
2018 ;; in other failure cases. However, CLHS says to return NIL if
2019 ;; the position cannot be determined -- so that's what we do.
2020 (when (integerp posn)
2021 ;; Adjust for buffered output: If there is any output
2022 ;; buffered, the *real* file position will be larger
2023 ;; than reported by lseek() because lseek() obviously
2024 ;; cannot take into account output we have not sent
2026 (dolist (later (fd-stream-output-later stream))
2027 (incf posn (- (caddr later) (cadr later))))
2028 (incf posn (fd-stream-obuf-tail stream))
2029 ;; Adjust for unread input: If there is any input
2030 ;; read from UNIX but not supplied to the user of the
2031 ;; stream, the *real* file position will smaller than
2032 ;; reported, because we want to look like the unread
2033 ;; stuff is still available.
2034 (decf posn (- (fd-stream-ibuf-tail stream)
2035 (fd-stream-ibuf-head stream)))
2036 (when (fd-stream-unread stream)
2038 ;; Divide bytes by element size.
2039 (truncate posn (fd-stream-element-size stream))))))
2041 (defun fd-stream-set-file-position (stream position-spec)
2042 (declare (fd-stream stream))
2043 (check-type position-spec
2044 (or (alien sb!unix:off-t) (member nil :start :end))
2045 "valid file position designator")
2048 ;; Make sure we don't have any output pending, because if we
2049 ;; move the file pointer before writing this stuff, it will be
2050 ;; written in the wrong location.
2051 (finish-fd-stream-output stream)
2052 ;; Disable interrupts so that interrupt handlers doing output
2055 (unless (fd-stream-output-finished-p stream)
2056 ;; We got interrupted and more output came our way during
2057 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2058 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2059 ;; so we prefer to do things like this...
2061 ;; Clear out any pending input to force the next read to go to
2063 (setf (fd-stream-unread stream) nil
2064 (fd-stream-ibuf-head stream) 0
2065 (fd-stream-ibuf-tail stream) 0)
2066 ;; Trash cached value for listen, so that we check next time.
2067 (setf (fd-stream-listen stream) nil)
2069 (multiple-value-bind (offset origin)
2072 (values 0 sb!unix:l_set))
2074 (values 0 sb!unix:l_xtnd))
2076 (values (* position-spec (fd-stream-element-size stream))
2078 (declare (type (alien sb!unix:off-t) offset))
2079 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2081 ;; CLHS says to return true if the file-position was set
2082 ;; succesfully, and NIL otherwise. We are to signal an error
2083 ;; only if the given position was out of bounds, and that is
2084 ;; dealt with above. In times past we used to return NIL for
2085 ;; errno==ESPIPE, and signal an error in other cases.
2087 ;; FIXME: We are still liable to signal an error if flushing
2089 (return-from fd-stream-set-file-position
2090 (typep posn '(alien sb!unix:off-t))))))))
2093 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2095 ;;; Create a stream for the given Unix file descriptor.
2097 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2098 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2099 ;;; default to allowing input.
2101 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2103 ;;; BUFFERING indicates the kind of buffering to use.
2105 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2106 ;;; NIL (the default), then wait forever. When we time out, we signal
2109 ;;; FILE is the name of the file (will be returned by PATHNAME).
2111 ;;; NAME is used to identify the stream when printed.
2112 (defun make-fd-stream (fd
2115 (output nil output-p)
2116 (element-type 'base-char)
2118 (external-format :default)
2127 (format nil "file ~A" file)
2128 (format nil "descriptor ~W" fd)))
2130 (declare (type index fd) (type (or real null) timeout)
2131 (type (member :none :line :full) buffering))
2132 (cond ((not (or input-p output-p))
2134 ((not (or input output))
2135 (error "File descriptor must be opened either for input or output.")))
2136 (let ((stream (%make-fd-stream :fd fd
2140 :delete-original delete-original
2142 :buffering buffering
2143 :dual-channel-p dual-channel-p
2144 :external-format external-format
2147 (coerce timeout 'single-float)
2149 (set-fd-stream-routines stream element-type external-format
2150 input output input-buffer-p)
2151 (when (and auto-close (fboundp 'finalize))
2154 (sb!unix:unix-close fd)
2156 (format *terminal-io* "** closed file descriptor ~W **~%"
2160 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2161 ;;; :RENAME-AND-DELETE and :RENAME options.
2162 (defun pick-backup-name (name)
2163 (declare (type simple-string name))
2164 (concatenate 'simple-string name ".bak"))
2166 ;;; Ensure that the given arg is one of the given list of valid
2167 ;;; things. Allow the user to fix any problems.
2168 (defun ensure-one-of (item list what)
2169 (unless (member item list)
2170 (error 'simple-type-error
2172 :expected-type `(member ,@list)
2173 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2174 :format-arguments (list item what list))))
2176 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2177 ;;; access, since we don't want to trash unwritable files even if we
2178 ;;; technically can. We return true if we succeed in renaming.
2179 (defun rename-the-old-one (namestring original)
2180 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2181 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2182 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2185 (error 'simple-file-error
2186 :pathname namestring
2188 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2189 :format-arguments (list namestring original (strerror err))))))
2191 (defun open (filename
2194 (element-type 'base-char)
2195 (if-exists nil if-exists-given)
2196 (if-does-not-exist nil if-does-not-exist-given)
2197 (external-format :default)
2198 &aux ; Squelch assignment warning.
2199 (direction direction)
2200 (if-does-not-exist if-does-not-exist)
2201 (if-exists if-exists))
2203 "Return a stream which reads from or writes to FILENAME.
2205 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2206 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2207 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2208 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2209 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2210 See the manual for details."
2212 ;; Calculate useful stuff.
2213 (multiple-value-bind (input output mask)
2215 (:input (values t nil sb!unix:o_rdonly))
2216 (:output (values nil t sb!unix:o_wronly))
2217 (:io (values t t sb!unix:o_rdwr))
2218 (:probe (values t nil sb!unix:o_rdonly)))
2219 (declare (type index mask))
2220 (let* ((pathname (merge-pathnames filename))
2222 (cond ((unix-namestring pathname input))
2223 ((and input (eq if-does-not-exist :create))
2224 (unix-namestring pathname nil))
2225 ((and (eq direction :io) (not if-does-not-exist-given))
2226 (unix-namestring pathname nil)))))
2227 ;; Process if-exists argument if we are doing any output.
2229 (unless if-exists-given
2231 (if (eq (pathname-version pathname) :newest)
2234 (ensure-one-of if-exists
2235 '(:error :new-version :rename
2236 :rename-and-delete :overwrite
2237 :append :supersede nil)
2240 ((:new-version :error nil)
2241 (setf mask (logior mask sb!unix:o_excl)))
2242 ((:rename :rename-and-delete)
2243 (setf mask (logior mask sb!unix:o_creat)))
2245 (setf mask (logior mask sb!unix:o_trunc)))
2247 (setf mask (logior mask sb!unix:o_append)))))
2249 (setf if-exists :ignore-this-arg)))
2251 (unless if-does-not-exist-given
2252 (setf if-does-not-exist
2253 (cond ((eq direction :input) :error)
2255 (member if-exists '(:overwrite :append)))
2257 ((eq direction :probe)
2261 (ensure-one-of if-does-not-exist
2262 '(:error :create nil)
2264 (if (eq if-does-not-exist :create)
2265 (setf mask (logior mask sb!unix:o_creat)))
2267 (let ((original (case if-exists
2268 ((:rename :rename-and-delete)
2269 (pick-backup-name namestring))
2270 ((:append :overwrite)
2271 ;; KLUDGE: Provent CLOSE from deleting
2272 ;; appending streams when called with :ABORT T
2274 (delete-original (eq if-exists :rename-and-delete))
2276 (when (and original (not (eq original namestring)))
2277 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2278 ;; whether the file already exists, make sure the original
2279 ;; file is not a directory, and keep the mode.
2282 (multiple-value-bind (okay err/dev inode orig-mode)
2283 (sb!unix:unix-stat namestring)
2284 (declare (ignore inode)
2285 (type (or index null) orig-mode))
2288 (when (and output (= (logand orig-mode #o170000)
2290 (error 'simple-file-error
2291 :pathname namestring
2293 "can't open ~S for output: is a directory"
2294 :format-arguments (list namestring)))
2295 (setf mode (logand orig-mode #o777))
2297 ((eql err/dev sb!unix:enoent)
2300 (simple-file-perror "can't find ~S"
2304 (rename-the-old-one namestring original))
2306 (setf delete-original nil)
2307 ;; In order to use :SUPERSEDE instead, we have to make
2308 ;; sure SB!UNIX:O_CREAT corresponds to
2309 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2310 ;; because of IF-EXISTS being :RENAME.
2311 (unless (eq if-does-not-exist :create)
2313 (logior (logandc2 mask sb!unix:o_creat)
2315 (setf if-exists :supersede))))
2317 ;; Now we can try the actual Unix open(2).
2318 (multiple-value-bind (fd errno)
2320 (sb!unix:unix-open namestring mask mode)
2321 (values nil sb!unix:enoent))
2322 (labels ((open-error (format-control &rest format-arguments)
2323 (error 'simple-file-error
2325 :format-control format-control
2326 :format-arguments format-arguments))
2327 (vanilla-open-error ()
2328 (simple-file-perror "error opening ~S" pathname errno)))
2331 ((:input :output :io)
2335 :element-type element-type
2336 :external-format external-format
2339 :delete-original delete-original
2346 (%make-fd-stream :name namestring
2349 :element-type element-type)))
2352 ((eql errno sb!unix:enoent)
2353 (case if-does-not-exist
2354 (:error (vanilla-open-error))
2356 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2359 ((and (eql errno sb!unix:eexist) (null if-exists))
2362 (vanilla-open-error)))))))))
2366 ;;; the stream connected to the controlling terminal, or NIL if there is none
2369 ;;; the stream connected to the standard input (file descriptor 0)
2372 ;;; the stream connected to the standard output (file descriptor 1)
2375 ;;; the stream connected to the standard error output (file descriptor 2)
2378 ;;; This is called when the cold load is first started up, and may also
2379 ;;; be called in an attempt to recover from nested errors.
2380 (defun stream-cold-init-or-reset ()
2382 (setf *terminal-io* (make-synonym-stream '*tty*))
2383 (setf *standard-output* (make-synonym-stream '*stdout*))
2384 (setf *standard-input* (make-synonym-stream '*stdin*))
2385 (setf *error-output* (make-synonym-stream '*stderr*))
2386 (setf *query-io* (make-synonym-stream '*terminal-io*))
2387 (setf *debug-io* *query-io*)
2388 (setf *trace-output* *standard-output*)
2391 ;;; This is called whenever a saved core is restarted.
2392 (defun stream-reinit ()
2393 (setf *available-buffers* nil)
2394 (with-output-to-string (*error-output*)
2396 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2397 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2399 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2400 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2402 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2403 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2404 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2405 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2409 :name "the terminal"
2414 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2415 (princ (get-output-stream-string *error-output*) *stderr*))
2420 ;;; the Unix way to beep
2421 (defun beep (stream)
2422 (write-char (code-char bell-char-code) stream)
2423 (finish-output stream))
2425 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2426 ;;; by the filesys stuff to get and set the file name.
2428 ;;; FIXME: misleading name, screwy interface
2429 (defun file-name (stream &optional new-name)
2430 (when (typep stream 'fd-stream)
2432 (setf (fd-stream-pathname stream) new-name)
2433 (setf (fd-stream-file stream)
2434 (unix-namestring new-name nil))
2437 (fd-stream-pathname stream)))))