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")
16 ;;;; Streams hold BUFFER objects, which contain a SAP, size of the
17 ;;;; memory area the SAP stands for (LENGTH bytes), and HEAD and TAIL
18 ;;;; indexes which delimit the "valid", or "active" area of the
19 ;;;; memory. HEAD is inclusive, TAIL is exclusive.
21 ;;;; Buffers get allocated lazily, and are recycled by returning them
22 ;;;; to the *AVAILABLE-BUFFERS* list. Every buffer has it's own
23 ;;;; finalizer, to take care of releasing the SAP memory when a stream
24 ;;;; is not properly closed.
26 ;;;; The code aims to provide a limited form of thread and interrupt
27 ;;;; safety: parallel writes and reads may lose output or input, cause
28 ;;;; interleaved IO, etc -- but they should not corrupt memory. The
29 ;;;; key to doing this is to read buffer state once, and update the
30 ;;;; state based on the read state:
32 ;;;; (let ((tail (buffer-tail buffer)))
34 ;;;; (setf (buffer-tail buffer) (+ tail n)))
38 ;;;; (let ((tail (buffer-tail buffer)))
40 ;;;; (incf (buffer-tail buffer) n))
43 (declaim (inline buffer-sap buffer-length buffer-head buffer-tail
44 (setf buffer-head) (setf buffer-tail)))
45 (defstruct (buffer (:constructor %make-buffer (sap length)))
46 (sap (missing-arg) :type system-area-pointer :read-only t)
47 (length (missing-arg) :type index :read-only t)
51 (defvar *available-buffers* ()
53 "List of available buffers.")
55 (defvar *available-buffers-spinlock* (sb!thread::make-spinlock
56 :name "lock for *AVAILABLE-BUFFERS*")
58 "Mutex for access to *AVAILABLE-BUFFERS*.")
60 (defmacro with-available-buffers-lock ((&optional) &body body)
61 ;; CALL-WITH-SYSTEM-SPINLOCK because
63 ;; 1. streams are low-level enough to be async signal safe, and in
64 ;; particular a C-c that brings up the debugger while holding the
65 ;; mutex would lose badly
67 ;; 2. this can potentially be a fairly busy (but also probably
68 ;; uncontended) lock, so we don't want to pay the syscall per
69 ;; release -- hence a spinlock.
71 ;; ...again, once we have smarted locks the spinlock here can become
73 `(sb!thread::with-system-spinlock (*available-buffers-spinlock*)
76 (defconstant +bytes-per-buffer+ (* 4 1024)
78 "Default number of bytes per buffer.")
80 (defun alloc-buffer (&optional (size +bytes-per-buffer+))
81 ;; Don't want to allocate & unwind before the finalizer is in place.
83 (let* ((sap (allocate-system-memory size))
84 (buffer (%make-buffer sap size)))
85 (when (zerop (sap-int sap))
86 (error "Could not allocate ~D bytes for buffer." size))
87 (finalize buffer (lambda ()
88 (deallocate-system-memory sap size))
93 ;; Don't go for the lock if there is nothing to be had -- sure,
94 ;; another thread might just release one before we get it, but that
95 ;; is not worth the cost of locking. Also release the lock before
96 ;; allocation, since it's going to take a while.
97 (if *available-buffers*
98 (or (with-available-buffers-lock ()
99 (pop *available-buffers*))
103 (declaim (inline reset-buffer))
104 (defun reset-buffer (buffer)
105 (setf (buffer-head buffer) 0
106 (buffer-tail buffer) 0)
109 (defun release-buffer (buffer)
110 (reset-buffer buffer)
111 (with-available-buffers-lock ()
112 (push buffer *available-buffers*)))
114 ;;; This is a separate buffer management function, as it wants to be
115 ;;; clever about locking -- grabbing the lock just once.
116 (defun release-fd-stream-buffers (fd-stream)
117 (let ((ibuf (fd-stream-ibuf fd-stream))
118 (obuf (fd-stream-obuf fd-stream))
119 (queue (loop for item in (fd-stream-output-queue fd-stream)
121 collect (reset-buffer item))))
123 (push (reset-buffer ibuf) queue))
125 (push (reset-buffer obuf) queue))
126 ;; ...so, anything found?
128 ;; detach from stream
129 (setf (fd-stream-ibuf fd-stream) nil
130 (fd-stream-obuf fd-stream) nil
131 (fd-stream-output-queue fd-stream) nil)
132 ;; splice to *available-buffers*
133 (with-available-buffers-lock ()
134 (setf *available-buffers* (nconc queue *available-buffers*))))))
136 ;;;; the FD-STREAM structure
138 (defstruct (fd-stream
139 (:constructor %make-fd-stream)
140 (:conc-name fd-stream-)
141 (:predicate fd-stream-p)
142 (:include ansi-stream
143 (misc #'fd-stream-misc-routine))
146 ;; the name of this stream
148 ;; the file this stream is for
150 ;; the backup file namestring for the old file, for :IF-EXISTS
151 ;; :RENAME or :RENAME-AND-DELETE.
152 (original nil :type (or simple-string null))
153 (delete-original nil) ; for :if-exists :rename-and-delete
154 ;;; the number of bytes per element
155 (element-size 1 :type index)
156 ;; the type of element being transfered
157 (element-type 'base-char)
158 ;; the Unix file descriptor
160 ;; controls when the output buffer is flushed
161 (buffering :full :type (member :full :line :none))
162 ;; controls whether the input buffer must be cleared before output
163 ;; (must be done for files, not for sockets, pipes and other data
164 ;; sources where input and output aren't related). non-NIL means
165 ;; don't clear input buffer.
167 ;; character position if known -- this may run into bignums, but
168 ;; we probably should flip it into null then for efficiency's sake...
169 (char-pos nil :type (or unsigned-byte null))
170 ;; T if input is waiting on FD. :EOF if we hit EOF.
171 (listen nil :type (member nil t :eof))
175 (ibuf nil :type (or buffer null))
178 (obuf nil :type (or buffer null))
180 ;; output flushed, but not written due to non-blocking io?
183 ;; timeout specified for this stream as seconds or NIL if none
184 (timeout nil :type (or single-float null))
185 ;; pathname of the file this stream is opened to (returned by PATHNAME)
186 (pathname nil :type (or pathname null))
187 (external-format :default)
188 ;; fixed width, or function to call with a character
189 (char-size 1 :type (or fixnum function))
190 (output-bytes #'ill-out :type function)
191 ;; a boolean indicating whether the stream is bivalent. For
192 ;; internal use only.
193 (bivalent-p nil :type boolean))
194 (def!method print-object ((fd-stream fd-stream) stream)
195 (declare (type stream stream))
196 (print-unreadable-object (fd-stream stream :type t :identity t)
197 (format stream "for ~S" (fd-stream-name fd-stream))))
199 ;;;; CORE OUTPUT FUNCTIONS
201 ;;; Buffer the section of THING delimited by START and END by copying
202 ;;; to output buffer(s) of stream.
203 (defun buffer-output (stream thing start end)
204 (declare (index start end))
206 (error ":END before :START!"))
208 ;; Copy bytes from THING to buffers.
209 (flet ((copy-to-buffer (buffer tail count)
210 (declare (buffer buffer) (index tail count))
212 (let ((sap (buffer-sap buffer)))
215 (system-area-ub8-copy thing start sap tail count))
216 ((simple-unboxed-array (*))
217 (copy-ub8-to-system-area thing start sap tail count))))
218 ;; Not INCF! If another thread has moved tail from under
219 ;; us, we don't want to accidentally increment tail
220 ;; beyond buffer-length.
221 (setf (buffer-tail buffer) (+ count tail))
224 ;; First copy is special: the buffer may already contain
225 ;; something, or be even full.
226 (let* ((obuf (fd-stream-obuf stream))
227 (tail (buffer-tail obuf))
228 (space (- (buffer-length obuf) tail)))
230 (copy-to-buffer obuf tail (min space (- end start)))
231 (go :more-output-p)))
233 ;; Later copies should always have an empty buffer, since
234 ;; they are freshly flushed, but if another thread is
235 ;; stomping on the same buffer that might not be the case.
236 (let* ((obuf (flush-output-buffer stream))
237 (tail (buffer-tail obuf))
238 (space (- (buffer-length obuf) tail)))
239 (copy-to-buffer obuf tail (min space (- end start))))
242 (go :flush-and-fill))))))
244 ;;; Flush the current output buffer of the stream, ensuring that the
245 ;;; new buffer is empty. Returns (for convenience) the new output
246 ;;; buffer -- which may or may not be EQ to the old one. If the is no
247 ;;; queued output we try to write the buffer immediately -- otherwise
248 ;;; we queue it for later.
249 (defun flush-output-buffer (stream)
250 (let ((obuf (fd-stream-obuf stream)))
252 (let ((head (buffer-head obuf))
253 (tail (buffer-tail obuf)))
254 (cond ((eql head tail)
255 ;; Buffer is already empty -- just ensure that is is
256 ;; set to zero as well.
258 ((fd-stream-output-queue stream)
259 ;; There is already stuff on the queue -- go directly
262 (%queue-and-replace-output-buffer stream))
264 ;; Try a non-blocking write, queue whatever is left over.
266 (synchronize-stream-output stream)
267 (let ((length (- tail head)))
268 (multiple-value-bind (count errno)
269 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
271 (cond ((eql count length)
272 ;; Complete write -- we can use the same buffer.
275 ;; Partial write -- update buffer status and queue.
276 ;; Do not use INCF! Another thread might have moved
278 (setf (buffer-head obuf) (+ count head))
279 (%queue-and-replace-output-buffer stream))
281 ((eql errno sb!unix:ewouldblock)
283 (%queue-and-replace-output-buffer stream))
285 (simple-stream-perror "Couldn't write to ~s"
286 stream errno)))))))))))
288 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
289 (defun %queue-and-replace-output-buffer (stream)
290 (let ((queue (fd-stream-output-queue stream))
291 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
293 ;; Important: before putting the buffer on queue, give the stream
294 ;; a new one. If we get an interrupt and unwind losing the buffer
295 ;; is relatively OK, but having the same buffer in two places
297 (setf (fd-stream-obuf stream) new)
301 (setf (fd-stream-output-queue stream) later)))
302 (unless (fd-stream-handler stream)
303 (setf (fd-stream-handler stream)
304 (add-fd-handler (fd-stream-fd stream)
307 (declare (ignore fd))
308 (write-output-from-queue stream)))))
311 ;;; This is called by the FD-HANDLER for the stream when output is
313 (defun write-output-from-queue (stream)
314 (synchronize-stream-output stream)
318 (let* ((buffer (pop (fd-stream-output-queue stream)))
319 (head (buffer-head buffer))
320 (length (- (buffer-tail buffer) head)))
321 (declare (index head length))
323 (multiple-value-bind (count errno)
324 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
326 (cond ((eql count length)
327 ;; Complete write, see if we can do another right
328 ;; away, or remove the handler if we're done.
329 (release-buffer buffer)
330 (cond ((fd-stream-output-queue stream)
334 (let ((handler (fd-stream-handler stream)))
336 (setf (fd-stream-handler stream) nil)
337 (remove-fd-handler handler)))))
339 ;; Partial write. Update buffer status and requeue.
340 (aver (< count length))
341 ;; Do not use INCF! Another thread might have moved head.
342 (setf (buffer-head buffer) (+ head count))
343 (push buffer (fd-stream-output-queue stream)))
345 ;; We tried to do multiple writes, and finally our
346 ;; luck ran out. Requeue.
347 (push buffer (fd-stream-output-queue stream)))
349 ;; Could not write on the first try at all!
351 (simple-stream-perror "Couldn't write to ~S." stream errno)
353 (if (= errno sb!unix:ewouldblock)
354 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
355 (simple-stream-perror "Couldn't write to ~S"
359 ;;; Try to write THING directly to STREAM without buffering, if
360 ;;; possible. If direct write doesn't happen, buffer.
361 (defun write-or-buffer-output (stream thing start end)
362 (declare (index start end))
363 (cond ((fd-stream-output-queue stream)
364 (buffer-output stream thing start end))
366 (error ":END before :START!"))
368 (let ((length (- end start)))
369 (synchronize-stream-output stream)
370 (multiple-value-bind (count errno)
371 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
372 (cond ((eql count length)
373 ;; Complete write -- done!
376 (aver (< count length))
377 ;; Partial write -- buffer the rest.
378 (buffer-output stream thing (+ start count) end))
380 ;; Could not write -- buffer or error.
382 (simple-stream-perror "couldn't write to ~s" stream errno)
384 (if (= errno sb!unix:ewouldblock)
385 (buffer-output stream thing start end)
386 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
388 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
389 ;;; this is not something we want to export. Nikodemus thinks the
390 ;;; right thing is to support a low-level non-stream like IO layer,
391 ;;; akin to java.nio.
392 (defun output-raw-bytes (stream thing &optional start end)
393 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
395 (define-compiler-macro output-raw-bytes (stream thing &optional start end)
396 (deprecation-warning 'output-raw-bytes)
397 (let ((x (gensym "THING")))
399 (write-or-buffer-output ,stream ,x (or ,start 0) (or ,end (length ,x))))))
401 ;;;; output routines and related noise
403 (defvar *output-routines* ()
405 "List of all available output routines. Each element is a list of the
406 element-type output, the kind of buffering, the function name, and the number
407 of bytes per element.")
409 ;;; common idioms for reporting low-level stream and file problems
410 (defun simple-stream-perror (note-format stream errno)
411 (error 'simple-stream-error
413 :format-control "~@<~?: ~2I~_~A~:>"
414 :format-arguments (list note-format (list stream) (strerror errno))))
415 (defun simple-file-perror (note-format pathname errno)
416 (error 'simple-file-error
418 :format-control "~@<~?: ~2I~_~A~:>"
420 (list note-format (list pathname) (strerror errno))))
422 (defun stream-decoding-error (stream octets)
423 (error 'stream-decoding-error
424 :external-format (stream-external-format stream)
426 ;; FIXME: dunno how to get at OCTETS currently, or even if
427 ;; that's the right thing to report.
429 (defun stream-encoding-error (stream code)
430 (error 'stream-encoding-error
431 :external-format (stream-external-format stream)
435 (defun c-string-encoding-error (external-format code)
436 (error 'c-string-encoding-error
437 :external-format external-format
440 (defun c-string-decoding-error (external-format octets)
441 (error 'c-string-decoding-error
442 :external-format external-format
445 ;;; Returning true goes into end of file handling, false will enter another
446 ;;; round of input buffer filling followed by re-entering character decode.
447 (defun stream-decoding-error-and-handle (stream octet-count)
449 (stream-decoding-error stream
450 (let* ((buffer (fd-stream-ibuf stream))
451 (sap (buffer-sap buffer))
452 (head (buffer-head buffer)))
453 (loop for i from 0 below octet-count
454 collect (sap-ref-8 sap (+ head i)))))
456 :report (lambda (stream)
458 "~@<Attempt to resync the stream at a ~
459 character boundary and continue.~@:>"))
460 (fd-stream-resync stream)
462 (force-end-of-file ()
463 :report (lambda (stream)
464 (format stream "~@<Force an end of file.~@:>"))
467 (defun stream-encoding-error-and-handle (stream code)
469 (stream-encoding-error stream code)
471 :report (lambda (stream)
472 (format stream "~@<Skip output of this character.~@:>"))
473 (throw 'output-nothing nil))))
475 (defun external-format-encoding-error (stream code)
477 (stream-encoding-error-and-handle stream code)
478 (c-string-encoding-error stream code)))
480 (defun external-format-decoding-error (stream octet-count)
482 (stream-decoding-error stream octet-count)
483 (c-string-decoding-error stream octet-count)))
485 (defun synchronize-stream-output (stream)
486 ;; If we're reading and writing on the same file, flush buffered
487 ;; input and rewind file position accordingly.
488 (unless (fd-stream-dual-channel-p stream)
489 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
490 (unless (eql 0 adjust)
491 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
493 (defun fd-stream-output-finished-p (stream)
494 (let ((obuf (fd-stream-obuf stream)))
496 (and (zerop (buffer-tail obuf))
497 (not (fd-stream-output-queue stream))))))
499 (defmacro output-wrapper/variable-width ((stream size buffering restart)
501 (let ((stream-var (gensym "STREAM")))
502 `(let* ((,stream-var ,stream)
503 (obuf (fd-stream-obuf ,stream-var))
504 (tail (buffer-tail obuf))
506 ,(unless (eq (car buffering) :none)
507 `(when (<= (buffer-length obuf) (+ tail size))
508 (setf obuf (flush-output-buffer ,stream-var)
509 tail (buffer-tail obuf))))
510 ,(unless (eq (car buffering) :none)
511 ;; FIXME: Why this here? Doesn't seem necessary.
512 `(synchronize-stream-output ,stream-var))
514 `(catch 'output-nothing
516 (setf (buffer-tail obuf) (+ tail size)))
519 (setf (buffer-tail obuf) (+ tail size))))
520 ,(ecase (car buffering)
522 `(flush-output-buffer ,stream-var))
524 `(when (eql byte #\Newline)
525 (flush-output-buffer ,stream-var)))
529 (defmacro output-wrapper ((stream size buffering restart) &body body)
530 (let ((stream-var (gensym "STREAM")))
531 `(let* ((,stream-var ,stream)
532 (obuf (fd-stream-obuf ,stream-var))
533 (tail (buffer-tail obuf)))
534 ,(unless (eq (car buffering) :none)
535 `(when (<= (buffer-length obuf) (+ tail ,size))
536 (setf obuf (flush-output-buffer ,stream-var)
537 tail (buffer-tail obuf))))
538 ;; FIXME: Why this here? Doesn't seem necessary.
539 ,(unless (eq (car buffering) :none)
540 `(synchronize-stream-output ,stream-var))
542 `(catch 'output-nothing
544 (setf (buffer-tail obuf) (+ tail ,size)))
547 (setf (buffer-tail obuf) (+ tail ,size))))
548 ,(ecase (car buffering)
550 `(flush-output-buffer ,stream-var))
552 `(when (eql byte #\Newline)
553 (flush-output-buffer ,stream-var)))
557 (defmacro def-output-routines/variable-width
558 ((name-fmt size restart external-format &rest bufferings)
560 (declare (optimize (speed 1)))
565 (intern (format nil name-fmt (string (car buffering))))))
567 (defun ,function (stream byte)
568 (declare (ignorable byte))
569 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
571 (setf *output-routines*
572 (nconc *output-routines*
580 (cdr buffering)))))))
583 ;;; Define output routines that output numbers SIZE bytes long for the
584 ;;; given bufferings. Use BODY to do the actual output.
585 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
587 (declare (optimize (speed 1)))
592 (intern (format nil name-fmt (string (car buffering))))))
594 (defun ,function (stream byte)
595 (output-wrapper (stream ,size ,buffering ,restart)
597 (setf *output-routines*
598 (nconc *output-routines*
606 (cdr buffering)))))))
609 ;;; FIXME: is this used anywhere any more?
610 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
616 (if (eql byte #\Newline)
617 (setf (fd-stream-char-pos stream) 0)
618 (incf (fd-stream-char-pos stream)))
619 (setf (sap-ref-8 (buffer-sap obuf) tail)
622 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
625 (:none (unsigned-byte 8))
626 (:full (unsigned-byte 8)))
627 (setf (sap-ref-8 (buffer-sap obuf) tail)
630 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
633 (:none (signed-byte 8))
634 (:full (signed-byte 8)))
635 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
638 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
641 (:none (unsigned-byte 16))
642 (:full (unsigned-byte 16)))
643 (setf (sap-ref-16 (buffer-sap obuf) tail)
646 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
649 (:none (signed-byte 16))
650 (:full (signed-byte 16)))
651 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
654 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
657 (:none (unsigned-byte 32))
658 (:full (unsigned-byte 32)))
659 (setf (sap-ref-32 (buffer-sap obuf) tail)
662 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
665 (:none (signed-byte 32))
666 (:full (signed-byte 32)))
667 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
670 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
672 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
675 (:none (unsigned-byte 64))
676 (:full (unsigned-byte 64)))
677 (setf (sap-ref-64 (buffer-sap obuf) tail)
679 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
682 (:none (signed-byte 64))
683 (:full (signed-byte 64)))
684 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
687 ;;; the routine to use to output a string. If the stream is
688 ;;; unbuffered, slam the string down the file descriptor, otherwise
689 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
690 ;;; checking to see where the last newline was.
691 (defun fd-sout (stream thing start end)
692 (declare (type fd-stream stream) (type string thing))
693 (let ((start (or start 0))
694 (end (or end (length (the vector thing)))))
695 (declare (fixnum start end))
697 (string-dispatch (simple-base-string
699 (simple-array character (*))
702 (position #\newline thing :from-end t
703 :start start :end end))))
704 (if (and (typep thing 'base-string)
705 (eq (fd-stream-external-format stream) :latin-1))
706 (ecase (fd-stream-buffering stream)
708 (buffer-output stream thing start end))
710 (buffer-output stream thing start end)
712 (flush-output-buffer stream)))
714 (write-or-buffer-output stream thing start end)))
715 (ecase (fd-stream-buffering stream)
716 (:full (funcall (fd-stream-output-bytes stream)
717 stream thing nil start end))
718 (:line (funcall (fd-stream-output-bytes stream)
719 stream thing last-newline start end))
720 (:none (funcall (fd-stream-output-bytes stream)
721 stream thing t start end))))
723 (setf (fd-stream-char-pos stream) (- end last-newline 1))
724 (incf (fd-stream-char-pos stream) (- end start))))))
726 (defvar *external-formats* ()
728 "List of all available external formats. Each element is a list of the
729 element-type, string input function name, character input function name,
730 and string output function name.")
732 (defun get-external-format (external-format)
733 (dolist (entry *external-formats*)
734 (when (member external-format (first entry))
737 (defun get-external-format-function (external-format index)
738 (let ((entry (get-external-format external-format)))
739 (when entry (nth index entry))))
741 ;;; Find an output routine to use given the type and buffering. Return
742 ;;; as multiple values the routine, the real type transfered, and the
743 ;;; number of bytes per element.
744 (defun pick-output-routine (type buffering &optional external-format)
745 (when (subtypep type 'character)
746 (let ((entry (get-external-format external-format)))
748 (return-from pick-output-routine
749 (values (symbol-function (nth (ecase buffering
756 (symbol-function (fourth entry))
757 (first (first entry)))))))
758 (dolist (entry *output-routines*)
759 (when (and (subtypep type (first entry))
760 (eq buffering (second entry))
761 (or (not (fifth entry))
762 (eq external-format (fifth entry))))
763 (return-from pick-output-routine
764 (values (symbol-function (third entry))
767 ;; KLUDGE: dealing with the buffering here leads to excessive code
770 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
771 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
772 if (subtypep type `(unsigned-byte ,i))
773 do (return-from pick-output-routine
777 (lambda (stream byte)
778 (output-wrapper (stream (/ i 8) (:none) nil)
779 (loop for j from 0 below (/ i 8)
780 do (setf (sap-ref-8 (buffer-sap obuf)
782 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
784 (lambda (stream byte)
785 (output-wrapper (stream (/ i 8) (:full) nil)
786 (loop for j from 0 below (/ i 8)
787 do (setf (sap-ref-8 (buffer-sap obuf)
789 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
792 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
793 if (subtypep type `(signed-byte ,i))
794 do (return-from pick-output-routine
798 (lambda (stream byte)
799 (output-wrapper (stream (/ i 8) (:none) nil)
800 (loop for j from 0 below (/ i 8)
801 do (setf (sap-ref-8 (buffer-sap obuf)
803 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
805 (lambda (stream byte)
806 (output-wrapper (stream (/ i 8) (:full) nil)
807 (loop for j from 0 below (/ i 8)
808 do (setf (sap-ref-8 (buffer-sap obuf)
810 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
814 ;;;; input routines and related noise
816 ;;; a list of all available input routines. Each element is a list of
817 ;;; the element-type input, the function name, and the number of bytes
819 (defvar *input-routines* ())
821 ;;; Return whether a primitive partial read operation on STREAM's FD
822 ;;; would (probably) block. Signal a `simple-stream-error' if the
823 ;;; system call implementing this operation fails.
825 ;;; It is "may" instead of "would" because "would" is not quite
826 ;;; correct on win32. However, none of the places that use it require
827 ;;; further assurance than "may" versus "will definitely not".
828 (defun sysread-may-block-p (stream)
830 ;; This answers T at EOF on win32, I think.
831 (not (sb!win32:fd-listen (fd-stream-fd stream)))
833 (sb!unix:with-restarted-syscall (count errno)
834 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
835 (sb!unix:fd-zero read-fds)
836 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
837 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
838 (sb!alien:addr read-fds)
844 (simple-stream-perror "couldn't check whether ~S is readable"
848 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
849 ;;; then fill the input buffer, and return the number of bytes read. Throws
850 ;;; to EOF-INPUT-CATCHER if the eof was reached.
851 (defun refill-input-buffer (stream)
852 (dx-let ((fd (fd-stream-fd stream))
856 ;; Check for blocking input before touching the stream, as if
857 ;; we happen to wait we are liable to be interrupted, and the
858 ;; interrupt handler may use the same stream.
859 (if (sysread-may-block-p stream)
862 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
863 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
865 (closed-flame stream)
867 (simple-stream-perror "couldn't read from ~S" stream errno)
869 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
870 ;; to wait for input if read tells us EWOULDBLOCK.
871 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
872 (signal-timeout 'io-timeout :stream stream :direction :read
873 :seconds (fd-stream-timeout stream)))
875 ;; Since the read should not block, we'll disable the
876 ;; interrupts here, so that we don't accidentally unwind and
877 ;; leave the stream in an inconsistent state.
879 ;; Execute the nlx outside without-interrupts to ensure the
880 ;; resulting thunk is stack-allocatable.
881 ((lambda (return-reason)
883 ((nil)) ; fast path normal cases
884 ((:wait-for-input) (go :wait-for-input))
885 ((:closed-flame) (go :closed-flame))
886 ((:read-error) (go :read-error))))
888 ;; Check the buffer: if it is null, then someone has closed
889 ;; the stream from underneath us. This is not ment to fix
890 ;; multithreaded races, but to deal with interrupt handlers
891 ;; closing the stream.
894 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
895 (sap (buffer-sap ibuf))
896 (length (buffer-length ibuf))
897 (head (buffer-head ibuf))
898 (tail (buffer-tail ibuf)))
899 (declare (index length head tail)
900 (inline sb!unix:unix-read))
902 (cond ((eql head tail)
903 ;; Buffer is empty, but not at yet reset -- make it so.
908 ;; Buffer has things in it, but they are not at the
909 ;; head -- move them there.
910 (let ((n (- tail head)))
911 (system-area-ub8-copy sap head sap 0 n)
913 (buffer-head ibuf) head
915 (buffer-tail ibuf) tail)))))
916 (setf (fd-stream-listen stream) nil)
917 (setf (values count errno)
918 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
923 (if (eql errno sb!unix:ewouldblock)
924 (return :wait-for-input)
925 (return :read-error)))
927 (setf (fd-stream-listen stream) :eof)
928 (/show0 "THROWing EOF-INPUT-CATCHER")
929 (throw 'eof-input-catcher nil))
931 ;; Success! (Do not use INCF, for sake of other threads.)
932 (setf (buffer-tail ibuf) (+ count tail))))))))))
935 ;;; Make sure there are at least BYTES number of bytes in the input
936 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
937 (defmacro input-at-least (stream bytes)
938 (let ((stream-var (gensym "STREAM"))
939 (bytes-var (gensym "BYTES"))
940 (buffer-var (gensym "IBUF")))
941 `(let* ((,stream-var ,stream)
943 (,buffer-var (fd-stream-ibuf ,stream-var)))
945 (when (>= (- (buffer-tail ,buffer-var)
946 (buffer-head ,buffer-var))
949 (refill-input-buffer ,stream-var)))))
951 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
953 (let ((stream-var (gensym "STREAM"))
954 (retry-var (gensym "RETRY"))
955 (element-var (gensym "ELT")))
956 `(let* ((,stream-var ,stream)
957 (ibuf (fd-stream-ibuf ,stream-var))
959 (if (fd-stream-unread ,stream-var)
961 (fd-stream-unread ,stream-var)
962 (setf (fd-stream-unread ,stream-var) nil)
963 (setf (fd-stream-listen ,stream-var) nil))
964 (let ((,element-var nil)
965 (decode-break-reason nil))
969 (catch 'eof-input-catcher
970 (setf decode-break-reason
971 (block decode-break-reason
972 (input-at-least ,stream-var 1)
973 (let* ((byte (sap-ref-8 (buffer-sap ibuf)
974 (buffer-head ibuf))))
975 (declare (ignorable byte))
977 (input-at-least ,stream-var size)
978 (setq ,element-var (locally ,@read-forms))
979 (setq ,retry-var nil))
981 (when decode-break-reason
982 (stream-decoding-error-and-handle stream
983 decode-break-reason))
985 (let ((octet-count (- (buffer-tail ibuf)
986 (buffer-head ibuf))))
987 (when (or (zerop octet-count)
988 (and (not ,element-var)
989 (not decode-break-reason)
990 (stream-decoding-error-and-handle
991 stream octet-count)))
992 (setq ,retry-var nil)))))
994 (incf (buffer-head ibuf) size)
997 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
999 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1000 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1001 (let ((stream-var (gensym "STREAM"))
1002 (element-var (gensym "ELT")))
1003 `(let* ((,stream-var ,stream)
1004 (ibuf (fd-stream-ibuf ,stream-var)))
1005 (if (fd-stream-unread ,stream-var)
1007 (fd-stream-unread ,stream-var)
1008 (setf (fd-stream-unread ,stream-var) nil)
1009 (setf (fd-stream-listen ,stream-var) nil))
1011 (catch 'eof-input-catcher
1012 (input-at-least ,stream-var ,bytes)
1013 (locally ,@read-forms))))
1015 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1018 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1020 (defmacro def-input-routine/variable-width (name
1021 (type external-format size sap head)
1024 (defun ,name (stream eof-error eof-value)
1025 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1026 (let ((,sap (buffer-sap ibuf))
1027 (,head (buffer-head ibuf)))
1029 (setf *input-routines*
1030 (nconc *input-routines*
1031 (list (list ',type ',name 1 ',external-format))))))
1033 (defmacro def-input-routine (name
1034 (type size sap head)
1037 (defun ,name (stream eof-error eof-value)
1038 (input-wrapper (stream ,size eof-error eof-value)
1039 (let ((,sap (buffer-sap ibuf))
1040 (,head (buffer-head ibuf)))
1042 (setf *input-routines*
1043 (nconc *input-routines*
1044 (list (list ',type ',name ',size nil))))))
1046 ;;; STREAM-IN routine for reading a string char
1047 (def-input-routine input-character
1048 (character 1 sap head)
1049 (code-char (sap-ref-8 sap head)))
1051 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1052 (def-input-routine input-unsigned-8bit-byte
1053 ((unsigned-byte 8) 1 sap head)
1054 (sap-ref-8 sap head))
1056 ;;; STREAM-IN routine for reading a signed 8 bit number
1057 (def-input-routine input-signed-8bit-number
1058 ((signed-byte 8) 1 sap head)
1059 (signed-sap-ref-8 sap head))
1061 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1062 (def-input-routine input-unsigned-16bit-byte
1063 ((unsigned-byte 16) 2 sap head)
1064 (sap-ref-16 sap head))
1066 ;;; STREAM-IN routine for reading a signed 16 bit number
1067 (def-input-routine input-signed-16bit-byte
1068 ((signed-byte 16) 2 sap head)
1069 (signed-sap-ref-16 sap head))
1071 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1072 (def-input-routine input-unsigned-32bit-byte
1073 ((unsigned-byte 32) 4 sap head)
1074 (sap-ref-32 sap head))
1076 ;;; STREAM-IN routine for reading a signed 32 bit number
1077 (def-input-routine input-signed-32bit-byte
1078 ((signed-byte 32) 4 sap head)
1079 (signed-sap-ref-32 sap head))
1081 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1083 (def-input-routine input-unsigned-64bit-byte
1084 ((unsigned-byte 64) 8 sap head)
1085 (sap-ref-64 sap head))
1086 (def-input-routine input-signed-64bit-byte
1087 ((signed-byte 64) 8 sap head)
1088 (signed-sap-ref-64 sap head)))
1090 ;;; Find an input routine to use given the type. Return as multiple
1091 ;;; values the routine, the real type transfered, and the number of
1092 ;;; bytes per element (and for character types string input routine).
1093 (defun pick-input-routine (type &optional external-format)
1094 (when (subtypep type 'character)
1095 (dolist (entry *external-formats*)
1096 (when (member external-format (first entry))
1097 (return-from pick-input-routine
1098 (values (symbol-function (third entry))
1101 (symbol-function (second entry))
1102 (first (first entry)))))))
1103 (dolist (entry *input-routines*)
1104 (when (and (subtypep type (first entry))
1105 (or (not (fourth entry))
1106 (eq external-format (fourth entry))))
1107 (return-from pick-input-routine
1108 (values (symbol-function (second entry))
1111 ;; FIXME: let's do it the hard way, then (but ignore things like
1112 ;; endianness, efficiency, and the necessary coupling between these
1113 ;; and the output routines). -- CSR, 2004-02-09
1114 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1115 if (subtypep type `(unsigned-byte ,i))
1116 do (return-from pick-input-routine
1118 (lambda (stream eof-error eof-value)
1119 (input-wrapper (stream (/ i 8) eof-error eof-value)
1120 (let ((sap (buffer-sap ibuf))
1121 (head (buffer-head ibuf)))
1122 (loop for j from 0 below (/ i 8)
1126 (sap-ref-8 sap (+ head j))))
1127 finally (return result)))))
1130 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1131 if (subtypep type `(signed-byte ,i))
1132 do (return-from pick-input-routine
1134 (lambda (stream eof-error eof-value)
1135 (input-wrapper (stream (/ i 8) eof-error eof-value)
1136 (let ((sap (buffer-sap ibuf))
1137 (head (buffer-head ibuf)))
1138 (loop for j from 0 below (/ i 8)
1142 (sap-ref-8 sap (+ head j))))
1143 finally (return (if (logbitp (1- i) result)
1144 (dpb result (byte i 0) -1)
1149 ;;; the N-BIN method for FD-STREAMs
1151 ;;; Note that this blocks in UNIX-READ. It is generally used where
1152 ;;; there is a definite amount of reading to be done, so blocking
1153 ;;; isn't too problematical.
1154 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1155 &aux (total-copied 0))
1156 (declare (type fd-stream stream))
1157 (declare (type index start requested total-copied))
1158 (let ((unread (fd-stream-unread stream)))
1160 ;; AVERs designed to fail when we have more complicated
1161 ;; character representations.
1162 (aver (typep unread 'base-char))
1163 (aver (= (fd-stream-element-size stream) 1))
1164 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1167 (system-area-pointer
1168 (setf (sap-ref-8 buffer start) (char-code unread)))
1169 ((simple-unboxed-array (*))
1170 (setf (aref buffer start) unread)))
1171 (setf (fd-stream-unread stream) nil)
1172 (setf (fd-stream-listen stream) nil)
1173 (incf total-copied)))
1176 (let* ((remaining-request (- requested total-copied))
1177 (ibuf (fd-stream-ibuf stream))
1178 (head (buffer-head ibuf))
1179 (tail (buffer-tail ibuf))
1180 (available (- tail head))
1181 (n-this-copy (min remaining-request available))
1182 (this-start (+ start total-copied))
1183 (this-end (+ this-start n-this-copy))
1184 (sap (buffer-sap ibuf)))
1185 (declare (type index remaining-request head tail available))
1186 (declare (type index n-this-copy))
1187 ;; Copy data from stream buffer into user's buffer.
1188 (%byte-blt sap head buffer this-start this-end)
1189 (incf (buffer-head ibuf) n-this-copy)
1190 (incf total-copied n-this-copy)
1191 ;; Maybe we need to refill the stream buffer.
1192 (cond (;; If there were enough data in the stream buffer, we're done.
1193 (eql total-copied requested)
1194 (return total-copied))
1195 (;; If EOF, we're done in another way.
1196 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1198 (error 'end-of-file :stream stream)
1199 (return total-copied)))
1200 ;; Otherwise we refilled the stream buffer, so fall
1201 ;; through into another pass of the loop.
1204 (defun fd-stream-resync (stream)
1205 (dolist (entry *external-formats*)
1206 (when (member (fd-stream-external-format stream) (first entry))
1207 (return-from fd-stream-resync
1208 (funcall (symbol-function (eighth entry)) stream)))))
1210 (defun get-fd-stream-character-sizer (stream)
1211 (dolist (entry *external-formats*)
1212 (when (member (fd-stream-external-format stream) (first entry))
1213 (return-from get-fd-stream-character-sizer (ninth entry)))))
1215 (defun fd-stream-character-size (stream char)
1216 (let ((sizer (get-fd-stream-character-sizer stream)))
1217 (when sizer (funcall sizer char))))
1219 (defun fd-stream-string-size (stream string)
1220 (let ((sizer (get-fd-stream-character-sizer stream)))
1222 (loop for char across string summing (funcall sizer char)))))
1224 (defun find-external-format (external-format)
1225 (when external-format
1226 (find external-format *external-formats* :test #'member :key #'car)))
1228 (defun variable-width-external-format-p (ef-entry)
1229 (when (eighth ef-entry) t))
1231 (defun bytes-for-char-fun (ef-entry)
1232 (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1234 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1235 (defmacro define-external-format (external-format size output-restart
1237 (let* ((name (first external-format))
1238 (out-function (symbolicate "OUTPUT-BYTES/" name))
1239 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1240 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1241 (in-char-function (symbolicate "INPUT-CHAR/" name))
1242 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1243 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1244 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1245 (n-buffer (gensym "BUFFER")))
1247 (defun ,size-function (byte)
1248 (declare (ignore byte))
1250 (defun ,out-function (stream string flush-p start end)
1251 (let ((start (or start 0))
1252 (end (or end (length string))))
1253 (declare (type index start end))
1254 (synchronize-stream-output stream)
1255 (unless (<= 0 start end (length string))
1256 (sequence-bounding-indices-bad-error string start end))
1259 (let ((obuf (fd-stream-obuf stream)))
1260 (setf (buffer-tail obuf)
1261 (string-dispatch (simple-base-string
1263 (simple-array character (*))
1266 (let ((sap (buffer-sap obuf))
1267 (len (buffer-length obuf))
1269 (tail (buffer-tail obuf)))
1270 (declare (type index tail)
1271 ;; STRING bounds have already been checked.
1272 (optimize (safety 0)))
1274 (,@(if output-restart
1275 `(catch 'output-nothing)
1278 ((or (= start end) (< (- len tail) 4)))
1279 (let* ((byte (aref string start))
1280 (bits (char-code byte)))
1284 ;; Exited from the loop normally
1286 ;; Exited via CATCH. Skip the current character
1287 ;; and try the inner loop again.
1290 (flush-output-buffer stream)))
1292 (flush-output-buffer stream))))
1293 (def-output-routines (,format
1299 (if (eql byte #\Newline)
1300 (setf (fd-stream-char-pos stream) 0)
1301 (incf (fd-stream-char-pos stream)))
1302 (let* ((obuf (fd-stream-obuf stream))
1303 (bits (char-code byte))
1304 (sap (buffer-sap obuf))
1305 (tail (buffer-tail obuf)))
1307 (defun ,in-function (stream buffer start requested eof-error-p
1308 &aux (index start) (end (+ start requested)))
1309 (declare (type fd-stream stream)
1310 (type index start requested index end)
1312 (simple-array character (#.+ansi-stream-in-buffer-length+))
1314 (let ((unread (fd-stream-unread stream)))
1316 (setf (aref buffer index) unread)
1317 (setf (fd-stream-unread stream) nil)
1318 (setf (fd-stream-listen stream) nil)
1322 (let* ((ibuf (fd-stream-ibuf stream))
1323 (head (buffer-head ibuf))
1324 (tail (buffer-tail ibuf))
1325 (sap (buffer-sap ibuf)))
1326 (declare (type index head tail)
1327 (type system-area-pointer sap))
1328 ;; Copy data from stream buffer into user's buffer.
1329 (dotimes (i (min (truncate (- tail head) ,size)
1331 (declare (optimize speed))
1332 (let* ((byte (sap-ref-8 sap head)))
1333 (setf (aref buffer index) ,in-expr)
1336 (setf (buffer-head ibuf) head)
1337 ;; Maybe we need to refill the stream buffer.
1338 (cond ( ;; If there was enough data in the stream buffer, we're done.
1340 (return (- index start)))
1341 ( ;; If EOF, we're done in another way.
1342 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1344 (error 'end-of-file :stream stream)
1345 (return (- index start))))
1346 ;; Otherwise we refilled the stream buffer, so fall
1347 ;; through into another pass of the loop.
1349 (def-input-routine ,in-char-function (character ,size sap head)
1350 (let ((byte (sap-ref-8 sap head)))
1352 (defun ,read-c-string-function (sap element-type)
1353 (declare (type system-area-pointer sap)
1354 (type (member character base-char) element-type))
1356 (declare (optimize (speed 3) (safety 0)))
1357 (let* ((stream ,name)
1359 (loop for head of-type index upfrom 0 by ,size
1360 for count of-type index upto (1- array-dimension-limit)
1361 for byte = (sap-ref-8 sap head)
1362 for char of-type character = ,in-expr
1363 until (zerop (char-code char))
1364 finally (return count)))
1365 ;; Inline the common cases
1366 (string (make-string length :element-type element-type)))
1367 (declare (ignorable stream)
1369 (type simple-string string))
1370 (/show0 before-copy-loop)
1371 (loop for head of-type index upfrom 0 by ,size
1372 for index of-type index below length
1373 for byte = (sap-ref-8 sap head)
1374 for char of-type character = ,in-expr
1375 do (setf (aref string index) char))
1376 string))) ;; last loop rewrite to dotimes?
1377 (defun ,output-c-string-function (string)
1378 (declare (type simple-string string))
1380 (declare (optimize (speed 3) (safety 0)))
1381 (let* ((length (length string))
1382 (,n-buffer (make-array (* (1+ length) ,size)
1383 :element-type '(unsigned-byte 8)))
1386 (declare (type index length tail))
1387 (with-pinned-objects (,n-buffer)
1388 (let ((sap (vector-sap ,n-buffer)))
1389 (declare (system-area-pointer sap))
1391 (let* ((byte (aref string i))
1392 (bits (char-code byte)))
1393 (declare (ignorable byte bits))
1397 (byte (code-char bits)))
1398 (declare (ignorable bits byte))
1401 (setf *external-formats*
1402 (cons '(,external-format ,in-function ,in-char-function ,out-function
1403 ,@(mapcar #'(lambda (buffering)
1404 (intern (format nil format (string buffering))))
1405 '(:none :line :full))
1406 nil ; no resync-function
1407 ,size-function ,read-c-string-function ,output-c-string-function)
1408 *external-formats*)))))
1410 (defmacro define-external-format/variable-width
1411 (external-format output-restart out-size-expr
1412 out-expr in-size-expr in-expr)
1413 (let* ((name (first external-format))
1414 (out-function (symbolicate "OUTPUT-BYTES/" name))
1415 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1416 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1417 (in-char-function (symbolicate "INPUT-CHAR/" name))
1418 (resync-function (symbolicate "RESYNC/" name))
1419 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1420 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1421 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1422 (n-buffer (gensym "BUFFER")))
1424 (defun ,size-function (byte)
1425 (declare (ignorable byte))
1427 (defun ,out-function (stream string flush-p start end)
1428 (let ((start (or start 0))
1429 (end (or end (length string))))
1430 (declare (type index start end))
1431 (synchronize-stream-output stream)
1432 (unless (<= 0 start end (length string))
1433 (sequence-bounding-indices-bad string start end))
1436 (let ((obuf (fd-stream-obuf stream)))
1437 (setf (buffer-tail obuf)
1438 (string-dispatch (simple-base-string
1440 (simple-array character (*))
1443 (let ((len (buffer-length obuf))
1444 (sap (buffer-sap obuf))
1446 (tail (buffer-tail obuf)))
1447 (declare (type index tail)
1448 ;; STRING bounds have already been checked.
1449 (optimize (safety 0)))
1451 (,@(if output-restart
1452 `(catch 'output-nothing)
1455 ((or (= start end) (< (- len tail) 4)))
1456 (let* ((byte (aref string start))
1457 (bits (char-code byte))
1458 (size ,out-size-expr))
1462 ;; Exited from the loop normally
1464 ;; Exited via CATCH. Skip the current character
1465 ;; and try the inner loop again.
1468 (flush-output-buffer stream)))
1470 (flush-output-buffer stream))))
1471 (def-output-routines/variable-width (,format
1478 (if (eql byte #\Newline)
1479 (setf (fd-stream-char-pos stream) 0)
1480 (incf (fd-stream-char-pos stream)))
1481 (let ((bits (char-code byte))
1482 (sap (buffer-sap obuf))
1483 (tail (buffer-tail obuf)))
1485 (defun ,in-function (stream buffer start requested eof-error-p
1486 &aux (total-copied 0))
1487 (declare (type fd-stream stream)
1488 (type index start requested total-copied)
1490 (simple-array character (#.+ansi-stream-in-buffer-length+))
1492 (let ((unread (fd-stream-unread stream)))
1494 (setf (aref buffer start) unread)
1495 (setf (fd-stream-unread stream) nil)
1496 (setf (fd-stream-listen stream) nil)
1497 (incf total-copied)))
1500 (let* ((ibuf (fd-stream-ibuf stream))
1501 (head (buffer-head ibuf))
1502 (tail (buffer-tail ibuf))
1503 (sap (buffer-sap ibuf))
1504 (decode-break-reason nil))
1505 (declare (type index head tail))
1506 ;; Copy data from stream buffer into user's buffer.
1507 (do ((size nil nil))
1508 ((or (= tail head) (= requested total-copied)))
1509 (setf decode-break-reason
1510 (block decode-break-reason
1511 (let ((byte (sap-ref-8 sap head)))
1512 (declare (ignorable byte))
1513 (setq size ,in-size-expr)
1514 (when (> size (- tail head))
1516 (setf (aref buffer (+ start total-copied)) ,in-expr)
1520 (setf (buffer-head ibuf) head)
1521 (when decode-break-reason
1522 ;; If we've already read some characters on when the invalid
1523 ;; code sequence is detected, we return immediately. The
1524 ;; handling of the error is deferred until the next call
1525 ;; (where this check will be false). This allows establishing
1526 ;; high-level handlers for decode errors (for example
1527 ;; automatically resyncing in Lisp comments).
1528 (when (plusp total-copied)
1529 (return-from ,in-function total-copied))
1530 (when (stream-decoding-error-and-handle
1531 stream decode-break-reason)
1533 (error 'end-of-file :stream stream)
1534 (return-from ,in-function total-copied)))
1535 (setf head (buffer-head ibuf))
1536 (setf tail (buffer-tail ibuf))))
1537 (setf (buffer-head ibuf) head)
1538 ;; Maybe we need to refill the stream buffer.
1539 (cond ( ;; If there were enough data in the stream buffer, we're done.
1540 (= total-copied requested)
1541 (return total-copied))
1542 ( ;; If EOF, we're done in another way.
1543 (or (eq decode-break-reason 'eof)
1544 (null (catch 'eof-input-catcher
1545 (refill-input-buffer stream))))
1547 (error 'end-of-file :stream stream)
1548 (return total-copied)))
1549 ;; Otherwise we refilled the stream buffer, so fall
1550 ;; through into another pass of the loop.
1552 (def-input-routine/variable-width ,in-char-function (character
1556 (let ((byte (sap-ref-8 sap head)))
1557 (declare (ignorable byte))
1559 (defun ,resync-function (stream)
1560 (let ((ibuf (fd-stream-ibuf stream)))
1562 (input-at-least stream 2)
1563 (incf (buffer-head ibuf))
1564 (unless (block decode-break-reason
1565 (let* ((sap (buffer-sap ibuf))
1566 (head (buffer-head ibuf))
1567 (byte (sap-ref-8 sap head))
1568 (size ,in-size-expr))
1569 (declare (ignorable byte))
1570 (input-at-least stream size)
1571 (setf head (buffer-head ibuf))
1575 (defun ,read-c-string-function (sap element-type)
1576 (declare (type system-area-pointer sap))
1578 (declare (optimize (speed 3) (safety 0)))
1579 (let* ((stream ,name)
1580 (size 0) (head 0) (byte 0) (char nil)
1581 (decode-break-reason nil)
1582 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1583 (setf decode-break-reason
1584 (block decode-break-reason
1585 (setf byte (sap-ref-8 sap head)
1590 (when decode-break-reason
1591 (c-string-decoding-error ,name decode-break-reason))
1592 (when (zerop (char-code char))
1594 (string (make-string length :element-type element-type)))
1595 (declare (ignorable stream)
1596 (type index head length) ;; size
1597 (type (unsigned-byte 8) byte)
1598 (type (or null character) char)
1599 (type string string))
1601 (dotimes (index length string)
1602 (setf decode-break-reason
1603 (block decode-break-reason
1604 (setf byte (sap-ref-8 sap head)
1609 (when decode-break-reason
1610 (c-string-decoding-error ,name decode-break-reason))
1611 (setf (aref string index) char)))))
1613 (defun ,output-c-string-function (string)
1614 (declare (type simple-string string))
1616 (declare (optimize (speed 3) (safety 0)))
1617 (let* ((length (length string))
1618 (char-length (make-array (1+ length) :element-type 'index))
1620 (+ (loop for i of-type index below length
1621 for byte of-type character = (aref string i)
1622 for bits = (char-code byte)
1623 sum (setf (aref char-length i)
1624 (the index ,out-size-expr)))
1625 (let* ((byte (code-char 0))
1626 (bits (char-code byte)))
1627 (declare (ignorable byte bits))
1628 (setf (aref char-length length)
1629 (the index ,out-size-expr)))))
1631 (,n-buffer (make-array buffer-length
1632 :element-type '(unsigned-byte 8)))
1634 (declare (type index length buffer-length tail)
1637 (with-pinned-objects (,n-buffer)
1638 (let ((sap (vector-sap ,n-buffer)))
1639 (declare (system-area-pointer sap))
1640 (loop for i of-type index below length
1641 for byte of-type character = (aref string i)
1642 for bits = (char-code byte)
1643 for size of-type index = (aref char-length i)
1648 (byte (code-char bits))
1649 (size (aref char-length length)))
1650 (declare (ignorable bits byte size))
1654 (setf *external-formats*
1655 (cons '(,external-format ,in-function ,in-char-function ,out-function
1656 ,@(mapcar #'(lambda (buffering)
1657 (intern (format nil format (string buffering))))
1658 '(:none :line :full))
1660 ,size-function ,read-c-string-function ,output-c-string-function)
1661 *external-formats*)))))
1663 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1664 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1665 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1666 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1669 (external-format-encoding-error stream bits)
1670 (setf (sap-ref-8 sap tail) bits))
1673 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1674 :iso-646 :iso-646-us :|646|)
1677 (external-format-encoding-error stream bits)
1678 (setf (sap-ref-8 sap tail) bits))
1682 (let ((latin-9-table (let ((table (make-string 256)))
1685 (setf (aref table i) (code-char i)))
1686 (setf (aref table #xa4) (code-char #x20ac))
1687 (setf (aref table #xa6) (code-char #x0160))
1688 (setf (aref table #xa8) (code-char #x0161))
1689 (setf (aref table #xb4) (code-char #x017d))
1690 (setf (aref table #xb8) (code-char #x017e))
1691 (setf (aref table #xbc) (code-char #x0152))
1692 (setf (aref table #xbd) (code-char #x0153))
1693 (setf (aref table #xbe) (code-char #x0178))
1695 (latin-9-reverse-1 (make-array 16
1696 :element-type '(unsigned-byte 21)
1697 :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1698 (latin-9-reverse-2 (make-array 16
1699 :element-type '(unsigned-byte 8)
1700 :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1701 (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1703 (setf (sap-ref-8 sap tail)
1705 (if (= bits (char-code (aref latin-9-table bits)))
1707 (external-format-encoding-error stream byte))
1708 (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1709 (aref latin-9-reverse-2 (logand bits 15))
1710 (external-format-encoding-error stream byte))))
1711 (aref latin-9-table byte)))
1713 (define-external-format/variable-width (:utf-8 :utf8) nil
1714 (let ((bits (char-code byte)))
1715 (cond ((< bits #x80) 1)
1717 ((< bits #x10000) 3)
1720 (1 (setf (sap-ref-8 sap tail) bits))
1721 (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1722 (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1723 (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1724 (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 6) bits))
1725 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1726 (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1727 (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 12) bits))
1728 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1729 (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1730 (cond ((< byte #x80) 1)
1731 ((< byte #xc2) (return-from decode-break-reason 1))
1735 (code-char (ecase size
1737 (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1738 (unless (<= #x80 byte2 #xbf)
1739 (return-from decode-break-reason 2))
1740 (dpb byte (byte 5 6) byte2)))
1741 (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1742 (byte3 (sap-ref-8 sap (+ 2 head))))
1743 (unless (and (<= #x80 byte2 #xbf)
1744 (<= #x80 byte3 #xbf))
1745 (return-from decode-break-reason 3))
1746 (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1747 (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1748 (byte3 (sap-ref-8 sap (+ 2 head)))
1749 (byte4 (sap-ref-8 sap (+ 3 head))))
1750 (unless (and (<= #x80 byte2 #xbf)
1751 (<= #x80 byte3 #xbf)
1752 (<= #x80 byte4 #xbf))
1753 (return-from decode-break-reason 4))
1754 (dpb byte (byte 3 18)
1755 (dpb byte2 (byte 6 12)
1756 (dpb byte3 (byte 6 6) byte4))))))))
1758 ;;;; utility functions (misc routines, etc)
1760 ;;; Fill in the various routine slots for the given type. INPUT-P and
1761 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1762 ;;; set prior to calling this routine.
1763 (defun set-fd-stream-routines (fd-stream element-type external-format
1764 input-p output-p buffer-p)
1765 (let* ((target-type (case element-type
1766 (unsigned-byte '(unsigned-byte 8))
1767 (signed-byte '(signed-byte 8))
1768 (:default 'character)
1770 (character-stream-p (subtypep target-type 'character))
1771 (bivalent-stream-p (eq element-type :default))
1772 normalized-external-format
1773 (bin-routine #'ill-bin)
1776 (cin-routine #'ill-in)
1779 (input-type nil) ;calculated from bin-type/cin-type
1780 (input-size nil) ;calculated from bin-size/cin-size
1781 (read-n-characters #'ill-in)
1782 (bout-routine #'ill-bout)
1785 (cout-routine #'ill-out)
1790 (output-bytes #'ill-bout))
1792 ;; Ensure that we have buffers in the desired direction(s) only,
1793 ;; getting new ones and dropping/resetting old ones as necessary.
1794 (let ((obuf (fd-stream-obuf fd-stream)))
1798 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1800 (setf (fd-stream-obuf fd-stream) nil)
1801 (release-buffer obuf))))
1803 (let ((ibuf (fd-stream-ibuf fd-stream)))
1807 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1809 (setf (fd-stream-ibuf fd-stream) nil)
1810 (release-buffer ibuf))))
1812 ;; FIXME: Why only for output? Why unconditionally?
1814 (setf (fd-stream-char-pos fd-stream) 0))
1816 (when (and character-stream-p
1817 (eq external-format :default))
1818 (/show0 "/getting default external format")
1819 (setf external-format (default-external-format)))
1822 (when (or (not character-stream-p) bivalent-stream-p)
1823 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1824 normalized-external-format)
1825 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1829 (error "could not find any input routine for ~S" target-type)))
1830 (when character-stream-p
1831 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1832 normalized-external-format)
1833 (pick-input-routine target-type external-format))
1835 (error "could not find any input routine for ~S" target-type)))
1836 (setf (fd-stream-in fd-stream) cin-routine
1837 (fd-stream-bin fd-stream) bin-routine)
1838 ;; character type gets preferential treatment
1839 (setf input-size (or cin-size bin-size))
1840 (setf input-type (or cin-type bin-type))
1841 (when normalized-external-format
1842 (setf (fd-stream-external-format fd-stream)
1843 normalized-external-format))
1844 (when (= (or cin-size 1) (or bin-size 1) 1)
1845 (setf (fd-stream-n-bin fd-stream) ;XXX
1846 (if (and character-stream-p (not bivalent-stream-p))
1848 #'fd-stream-read-n-bytes))
1849 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1850 ;; for character and (unsigned-byte 8) streams. In these
1851 ;; cases, fast-read-* will read from the
1852 ;; ansi-stream-(c)in-buffer, saving function calls.
1853 ;; Otherwise, the various data-reading functions in the stream
1854 ;; structure will be called.
1856 (not bivalent-stream-p)
1857 ;; temporary disable on :io streams
1859 (cond (character-stream-p
1860 (setf (ansi-stream-cin-buffer fd-stream)
1861 (make-array +ansi-stream-in-buffer-length+
1862 :element-type 'character)))
1863 ((equal target-type '(unsigned-byte 8))
1864 (setf (ansi-stream-in-buffer fd-stream)
1865 (make-array +ansi-stream-in-buffer-length+
1866 :element-type '(unsigned-byte 8))))))))
1869 (when (or (not character-stream-p) bivalent-stream-p)
1870 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1871 normalized-external-format)
1872 (pick-output-routine (if bivalent-stream-p
1875 (fd-stream-buffering fd-stream)
1877 (unless bout-routine
1878 (error "could not find any output routine for ~S buffered ~S"
1879 (fd-stream-buffering fd-stream)
1881 (when character-stream-p
1882 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1883 normalized-external-format)
1884 (pick-output-routine target-type
1885 (fd-stream-buffering fd-stream)
1887 (unless cout-routine
1888 (error "could not find any output routine for ~S buffered ~S"
1889 (fd-stream-buffering fd-stream)
1891 (when normalized-external-format
1892 (setf (fd-stream-external-format fd-stream)
1893 normalized-external-format))
1894 (when character-stream-p
1895 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1896 (setf (fd-stream-out fd-stream) cout-routine
1897 (fd-stream-bout fd-stream) bout-routine
1898 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1899 #'fd-sout #'ill-out))
1900 (setf output-size (or cout-size bout-size))
1901 (setf output-type (or cout-type bout-type)))
1903 (when (and input-size output-size
1904 (not (eq input-size output-size)))
1905 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1906 input-type input-size
1907 output-type output-size))
1908 (setf (fd-stream-element-size fd-stream)
1909 (or input-size output-size))
1911 (setf (fd-stream-element-type fd-stream)
1912 (cond ((equal input-type output-type)
1918 ((subtypep input-type output-type)
1920 ((subtypep output-type input-type)
1923 (error "Input type (~S) and output type (~S) are unrelated?"
1927 ;;; Handles the resource-release aspects of stream closing, and marks
1929 (defun release-fd-stream-resources (fd-stream)
1932 ;; Drop handlers first.
1933 (when (fd-stream-handler fd-stream)
1934 (remove-fd-handler (fd-stream-handler fd-stream))
1935 (setf (fd-stream-handler fd-stream) nil))
1936 ;; Disable interrupts so that a asynch unwind will not leave
1937 ;; us with a dangling finalizer (that would close the same
1938 ;; --possibly reassigned-- FD again), or a stream with a closed
1939 ;; FD that appears open.
1940 (sb!unix:unix-close (fd-stream-fd fd-stream))
1941 (set-closed-flame fd-stream)
1942 (when (fboundp 'cancel-finalization)
1943 (cancel-finalization fd-stream)))
1944 ;; On error unwind from WITHOUT-INTERRUPTS.
1945 (serious-condition (e)
1947 ;; Release all buffers. If this is undone, or interrupted,
1948 ;; we're still safe: buffers have finalizers of their own.
1949 (release-fd-stream-buffers fd-stream))
1951 ;;; Flushes the current input buffer and unread chatacter, and returns
1952 ;;; the input buffer, and the amount of of flushed input in bytes.
1953 (defun flush-input-buffer (stream)
1954 (let ((unread (if (fd-stream-unread stream)
1957 (setf (fd-stream-unread stream) nil)
1958 (let ((ibuf (fd-stream-ibuf stream)))
1960 (let ((head (buffer-head ibuf))
1961 (tail (buffer-tail ibuf)))
1962 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1963 (values nil unread)))))
1965 (defun fd-stream-clear-input (stream)
1966 (flush-input-buffer stream)
1969 (sb!win32:fd-clear-input (fd-stream-fd stream))
1970 (setf (fd-stream-listen stream) nil))
1972 (catch 'eof-input-catcher
1973 (loop until (sysread-may-block-p stream)
1975 (refill-input-buffer stream)
1976 (reset-buffer (fd-stream-ibuf stream)))
1979 ;;; Handle miscellaneous operations on FD-STREAM.
1980 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1981 (declare (ignore arg2))
1984 (labels ((do-listen ()
1985 (let ((ibuf (fd-stream-ibuf fd-stream)))
1986 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1987 (fd-stream-listen fd-stream)
1989 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1991 ;; If the read can block, LISTEN will certainly return NIL.
1992 (if (sysread-may-block-p fd-stream)
1994 ;; Otherwise select(2) and CL:LISTEN have slightly
1995 ;; different semantics. The former returns that an FD
1996 ;; is readable when a read operation wouldn't block.
1997 ;; That includes EOF. However, LISTEN must return NIL
1999 (progn (catch 'eof-input-catcher
2000 ;; r-b/f too calls select, but it shouldn't
2001 ;; block as long as read can return once w/o
2003 (refill-input-buffer fd-stream))
2004 ;; At this point either IBUF-HEAD != IBUF-TAIL
2005 ;; and FD-STREAM-LISTEN is NIL, in which case
2006 ;; we should return T, or IBUF-HEAD ==
2007 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2008 ;; which case we should return :EOF for this
2009 ;; call and all future LISTEN call on this stream.
2010 ;; Call ourselves again to determine which case
2015 ;; If the stream is bivalent, the user might follow an
2016 ;; unread-char with a read-byte. In this case, the bookkeeping
2017 ;; is simpler if we adjust the buffer head by the number of code
2018 ;; units in the character.
2019 ;; FIXME: there has to be a proper way to check for bivalence,
2021 (if (fd-stream-bivalent-p fd-stream)
2022 (decf (buffer-head (fd-stream-ibuf fd-stream))
2023 (fd-stream-character-size fd-stream arg1))
2024 (setf (fd-stream-unread fd-stream) arg1))
2025 (setf (fd-stream-listen fd-stream) t))
2027 ;; Drop input buffers
2028 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
2029 (ansi-stream-cin-buffer fd-stream) nil
2030 (ansi-stream-in-buffer fd-stream) nil)
2032 ;; We got us an abort on our hands.
2033 (let ((outputp (fd-stream-obuf fd-stream))
2034 (file (fd-stream-file fd-stream))
2035 (orig (fd-stream-original fd-stream)))
2036 ;; This takes care of the important stuff -- everything
2037 ;; rest is cleaning up the file-system, which we cannot
2038 ;; do on some platforms as long as the file is open.
2039 (release-fd-stream-resources fd-stream)
2040 ;; We can't do anything unless we know what file were
2041 ;; dealing with, and we don't want to do anything
2042 ;; strange unless we were writing to the file.
2043 (when (and outputp file)
2045 ;; If the original is EQ to file we are appending to
2046 ;; and can just close the file without renaming.
2047 (unless (eq orig file)
2048 ;; We have a handle on the original, just revert.
2049 (multiple-value-bind (okay err)
2050 (sb!unix:unix-rename orig file)
2051 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2052 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2055 (error 'simple-stream-error
2057 "~@<Couldn't restore ~S to its original contents ~
2058 from ~S while closing ~S: ~2I~_~A~:>"
2060 (list file orig fd-stream (strerror err))
2061 :stream fd-stream))))
2062 ;; We can't restore the original, and aren't
2063 ;; appending, so nuke that puppy.
2065 ;; FIXME: This is currently the fate of superseded
2066 ;; files, and according to the CLOSE spec this is
2067 ;; wrong. However, there seems to be no clean way to
2068 ;; do that that doesn't involve either copying the
2069 ;; data (bad if the :abort resulted from a full
2070 ;; disk), or renaming the old file temporarily
2071 ;; (probably bad because stream opening becomes more
2073 (multiple-value-bind (okay err)
2074 (sb!unix:unix-unlink file)
2076 (error 'simple-file-error
2079 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2081 (list file fd-stream (strerror err)))))))))
2083 (finish-fd-stream-output fd-stream)
2084 (let ((orig (fd-stream-original fd-stream)))
2085 (when (and orig (fd-stream-delete-original fd-stream))
2086 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2088 (error 'simple-file-error
2091 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2093 (list orig fd-stream (strerror err)))))))
2094 ;; In case of no-abort close, don't *really* close the
2095 ;; stream until the last moment -- the cleaning up of the
2096 ;; original can be done first.
2097 (release-fd-stream-resources fd-stream))))
2099 (fd-stream-clear-input fd-stream))
2101 (flush-output-buffer fd-stream))
2103 (finish-fd-stream-output fd-stream))
2105 (fd-stream-element-type fd-stream))
2107 (fd-stream-external-format fd-stream))
2109 (= 1 (the (member 0 1)
2110 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2114 (fd-stream-char-pos fd-stream))
2116 (unless (fd-stream-file fd-stream)
2117 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2118 ;; "should signal an error of type TYPE-ERROR if stream is not
2119 ;; a stream associated with a file". Too bad there's no very
2120 ;; appropriate value for the EXPECTED-TYPE slot..
2121 (error 'simple-type-error
2123 :expected-type 'fd-stream
2124 :format-control "~S is not a stream associated with a file."
2125 :format-arguments (list fd-stream)))
2126 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2127 atime mtime ctime blksize blocks)
2128 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2129 (declare (ignore ino nlink uid gid rdev
2130 atime mtime ctime blksize blocks))
2132 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2135 (truncate size (fd-stream-element-size fd-stream)))))
2136 (:file-string-length
2138 (character (fd-stream-character-size fd-stream arg1))
2139 (string (fd-stream-string-size fd-stream arg1))))
2142 (fd-stream-set-file-position fd-stream arg1)
2143 (fd-stream-get-file-position fd-stream)))))
2145 ;; FIXME: Think about this.
2147 ;; (defun finish-fd-stream-output (fd-stream)
2148 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2149 ;; (loop while (fd-stream-output-queue fd-stream)
2150 ;; ;; FIXME: SIGINT while waiting for a timeout will
2151 ;; ;; cause a timeout here.
2152 ;; do (when (and (not (serve-event timeout)) timeout)
2153 ;; (signal-timeout 'io-timeout
2154 ;; :stream fd-stream
2155 ;; :direction :write
2156 ;; :seconds timeout)))))
2158 (defun finish-fd-stream-output (stream)
2159 (flush-output-buffer stream)
2161 ((null (fd-stream-output-queue stream)))
2162 (serve-all-events)))
2164 (defun fd-stream-get-file-position (stream)
2165 (declare (fd-stream stream))
2167 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2168 (declare (type (or (alien sb!unix:off-t) null) posn))
2169 ;; We used to return NIL for errno==ESPIPE, and signal an error
2170 ;; in other failure cases. However, CLHS says to return NIL if
2171 ;; the position cannot be determined -- so that's what we do.
2172 (when (integerp posn)
2173 ;; Adjust for buffered output: If there is any output
2174 ;; buffered, the *real* file position will be larger
2175 ;; than reported by lseek() because lseek() obviously
2176 ;; cannot take into account output we have not sent
2178 (dolist (buffer (fd-stream-output-queue stream))
2179 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2180 (let ((obuf (fd-stream-obuf stream)))
2182 (incf posn (buffer-tail obuf))))
2183 ;; Adjust for unread input: If there is any input
2184 ;; read from UNIX but not supplied to the user of the
2185 ;; stream, the *real* file position will smaller than
2186 ;; reported, because we want to look like the unread
2187 ;; stuff is still available.
2188 (let ((ibuf (fd-stream-ibuf stream)))
2190 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2191 (when (fd-stream-unread stream)
2193 ;; Divide bytes by element size.
2194 (truncate posn (fd-stream-element-size stream))))))
2196 (defun fd-stream-set-file-position (stream position-spec)
2197 (declare (fd-stream stream))
2198 (check-type position-spec
2199 (or (alien sb!unix:off-t) (member nil :start :end))
2200 "valid file position designator")
2203 ;; Make sure we don't have any output pending, because if we
2204 ;; move the file pointer before writing this stuff, it will be
2205 ;; written in the wrong location.
2206 (finish-fd-stream-output stream)
2207 ;; Disable interrupts so that interrupt handlers doing output
2210 (unless (fd-stream-output-finished-p stream)
2211 ;; We got interrupted and more output came our way during
2212 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2213 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2214 ;; so we prefer to do things like this...
2216 ;; Clear out any pending input to force the next read to go to
2218 (flush-input-buffer stream)
2219 ;; Trash cached value for listen, so that we check next time.
2220 (setf (fd-stream-listen stream) nil)
2222 (multiple-value-bind (offset origin)
2225 (values 0 sb!unix:l_set))
2227 (values 0 sb!unix:l_xtnd))
2229 (values (* position-spec (fd-stream-element-size stream))
2231 (declare (type (alien sb!unix:off-t) offset))
2232 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2234 ;; CLHS says to return true if the file-position was set
2235 ;; succesfully, and NIL otherwise. We are to signal an error
2236 ;; only if the given position was out of bounds, and that is
2237 ;; dealt with above. In times past we used to return NIL for
2238 ;; errno==ESPIPE, and signal an error in other cases.
2240 ;; FIXME: We are still liable to signal an error if flushing
2242 (return-from fd-stream-set-file-position
2243 (typep posn '(alien sb!unix:off-t))))))))
2246 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2248 ;;; Create a stream for the given Unix file descriptor.
2250 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2251 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2252 ;;; default to allowing input.
2254 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2256 ;;; BUFFERING indicates the kind of buffering to use.
2258 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2259 ;;; NIL (the default), then wait forever. When we time out, we signal
2262 ;;; FILE is the name of the file (will be returned by PATHNAME).
2264 ;;; NAME is used to identify the stream when printed.
2265 (defun make-fd-stream (fd
2268 (output nil output-p)
2269 (element-type 'base-char)
2271 (external-format :default)
2280 (format nil "file ~A" file)
2281 (format nil "descriptor ~W" fd)))
2283 (declare (type index fd) (type (or real null) timeout)
2284 (type (member :none :line :full) buffering))
2285 (cond ((not (or input-p output-p))
2287 ((not (or input output))
2288 (error "File descriptor must be opened either for input or output.")))
2289 (let ((stream (%make-fd-stream :fd fd
2293 :delete-original delete-original
2295 :buffering buffering
2296 :dual-channel-p dual-channel-p
2297 :external-format external-format
2298 :bivalent-p (eq element-type :default)
2299 :char-size (external-format-char-size external-format)
2302 (coerce timeout 'single-float)
2304 (set-fd-stream-routines stream element-type external-format
2305 input output input-buffer-p)
2306 (when (and auto-close (fboundp 'finalize))
2309 (sb!unix:unix-close fd)
2311 (format *terminal-io* "** closed file descriptor ~W **~%"
2316 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2317 ;;; :RENAME-AND-DELETE and :RENAME options.
2318 (defun pick-backup-name (name)
2319 (declare (type simple-string name))
2320 (concatenate 'simple-string name ".bak"))
2322 ;;; Ensure that the given arg is one of the given list of valid
2323 ;;; things. Allow the user to fix any problems.
2324 (defun ensure-one-of (item list what)
2325 (unless (member item list)
2326 (error 'simple-type-error
2328 :expected-type `(member ,@list)
2329 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2330 :format-arguments (list item what list))))
2332 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2333 ;;; access, since we don't want to trash unwritable files even if we
2334 ;;; technically can. We return true if we succeed in renaming.
2335 (defun rename-the-old-one (namestring original)
2336 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2337 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2338 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2341 (error 'simple-file-error
2342 :pathname namestring
2344 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2345 :format-arguments (list namestring original (strerror err))))))
2347 (defun open (filename
2350 (element-type 'base-char)
2351 (if-exists nil if-exists-given)
2352 (if-does-not-exist nil if-does-not-exist-given)
2353 (external-format :default)
2354 &aux ; Squelch assignment warning.
2355 (direction direction)
2356 (if-does-not-exist if-does-not-exist)
2357 (if-exists if-exists))
2359 "Return a stream which reads from or writes to FILENAME.
2361 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2362 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2363 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2364 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2365 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2366 See the manual for details."
2368 ;; Calculate useful stuff.
2369 (multiple-value-bind (input output mask)
2371 (:input (values t nil sb!unix:o_rdonly))
2372 (:output (values nil t sb!unix:o_wronly))
2373 (:io (values t t sb!unix:o_rdwr))
2374 (:probe (values t nil sb!unix:o_rdonly)))
2375 (declare (type index mask))
2376 (let* (;; PATHNAME is the pathname we associate with the stream.
2377 (pathname (merge-pathnames filename))
2378 (physical (physicalize-pathname pathname))
2379 (truename (probe-file physical))
2380 ;; NAMESTRING is the native namestring we open the file with.
2381 (namestring (cond (truename
2382 (native-namestring truename :as-file t))
2384 (and input (eq if-does-not-exist :create))
2385 (and (eq direction :io) (not if-does-not-exist-given)))
2386 (native-namestring physical :as-file t)))))
2387 ;; Process if-exists argument if we are doing any output.
2389 (unless if-exists-given
2391 (if (eq (pathname-version pathname) :newest)
2394 (ensure-one-of if-exists
2395 '(:error :new-version :rename
2396 :rename-and-delete :overwrite
2397 :append :supersede nil)
2400 ((:new-version :error nil)
2401 (setf mask (logior mask sb!unix:o_excl)))
2402 ((:rename :rename-and-delete)
2403 (setf mask (logior mask sb!unix:o_creat)))
2405 (setf mask (logior mask sb!unix:o_trunc)))
2407 (setf mask (logior mask sb!unix:o_append)))))
2409 (setf if-exists :ignore-this-arg)))
2411 (unless if-does-not-exist-given
2412 (setf if-does-not-exist
2413 (cond ((eq direction :input) :error)
2415 (member if-exists '(:overwrite :append)))
2417 ((eq direction :probe)
2421 (ensure-one-of if-does-not-exist
2422 '(:error :create nil)
2424 (if (eq if-does-not-exist :create)
2425 (setf mask (logior mask sb!unix:o_creat)))
2427 (let ((original (case if-exists
2428 ((:rename :rename-and-delete)
2429 (pick-backup-name namestring))
2430 ((:append :overwrite)
2431 ;; KLUDGE: Provent CLOSE from deleting
2432 ;; appending streams when called with :ABORT T
2434 (delete-original (eq if-exists :rename-and-delete))
2436 (when (and original (not (eq original namestring)))
2437 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2438 ;; whether the file already exists, make sure the original
2439 ;; file is not a directory, and keep the mode.
2442 (multiple-value-bind (okay err/dev inode orig-mode)
2443 (sb!unix:unix-stat namestring)
2444 (declare (ignore inode)
2445 (type (or index null) orig-mode))
2448 (when (and output (= (logand orig-mode #o170000)
2450 (error 'simple-file-error
2453 "can't open ~S for output: is a directory"
2454 :format-arguments (list namestring)))
2455 (setf mode (logand orig-mode #o777))
2457 ((eql err/dev sb!unix:enoent)
2460 (simple-file-perror "can't find ~S"
2464 (rename-the-old-one namestring original))
2466 (setf delete-original nil)
2467 ;; In order to use :SUPERSEDE instead, we have to make
2468 ;; sure SB!UNIX:O_CREAT corresponds to
2469 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2470 ;; because of IF-EXISTS being :RENAME.
2471 (unless (eq if-does-not-exist :create)
2473 (logior (logandc2 mask sb!unix:o_creat)
2475 (setf if-exists :supersede))))
2477 ;; Now we can try the actual Unix open(2).
2478 (multiple-value-bind (fd errno)
2480 (sb!unix:unix-open namestring mask mode)
2481 (values nil sb!unix:enoent))
2482 (labels ((open-error (format-control &rest format-arguments)
2483 (error 'simple-file-error
2485 :format-control format-control
2486 :format-arguments format-arguments))
2487 (vanilla-open-error ()
2488 (simple-file-perror "error opening ~S" pathname errno)))
2491 ((:input :output :io)
2495 :element-type element-type
2496 :external-format external-format
2499 :delete-original delete-original
2506 (%make-fd-stream :name namestring
2509 :element-type element-type)))
2512 ((eql errno sb!unix:enoent)
2513 (case if-does-not-exist
2514 (:error (vanilla-open-error))
2516 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2519 ((and (eql errno sb!unix:eexist) (null if-exists))
2522 (vanilla-open-error)))))))))
2526 ;;; the stream connected to the controlling terminal, or NIL if there is none
2529 ;;; the stream connected to the standard input (file descriptor 0)
2532 ;;; the stream connected to the standard output (file descriptor 1)
2535 ;;; the stream connected to the standard error output (file descriptor 2)
2538 ;;; This is called when the cold load is first started up, and may also
2539 ;;; be called in an attempt to recover from nested errors.
2540 (defun stream-cold-init-or-reset ()
2542 (setf *terminal-io* (make-synonym-stream '*tty*))
2543 (setf *standard-output* (make-synonym-stream '*stdout*))
2544 (setf *standard-input* (make-synonym-stream '*stdin*))
2545 (setf *error-output* (make-synonym-stream '*stderr*))
2546 (setf *query-io* (make-synonym-stream '*terminal-io*))
2547 (setf *debug-io* *query-io*)
2548 (setf *trace-output* *standard-output*)
2551 (defun stream-deinit ()
2552 ;; Unbind to make sure we're not accidently dealing with it
2553 ;; before we're ready (or after we think it's been deinitialized).
2554 (with-available-buffers-lock ()
2555 (without-package-locks
2556 (makunbound '*available-buffers*))))
2558 ;;; This is called whenever a saved core is restarted.
2559 (defun stream-reinit (&optional init-buffers-p)
2560 (when init-buffers-p
2561 (with-available-buffers-lock ()
2562 (aver (not (boundp '*available-buffers*)))
2563 (setf *available-buffers* nil)))
2564 (with-output-to-string (*error-output*)
2566 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2567 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2569 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2570 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2572 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2573 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2574 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2575 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2579 :name "the terminal"
2584 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2585 (princ (get-output-stream-string *error-output*) *stderr*))
2590 ;;; the Unix way to beep
2591 (defun beep (stream)
2592 (write-char (code-char bell-char-code) stream)
2593 (finish-output stream))
2595 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2596 ;;; by the filesys stuff to get and set the file name.
2598 ;;; FIXME: misleading name, screwy interface
2599 (defun file-name (stream &optional new-name)
2600 (when (typep stream 'fd-stream)
2602 (setf (fd-stream-pathname stream) new-name)
2603 (setf (fd-stream-file stream)
2604 (native-namestring (physicalize-pathname new-name)
2608 (fd-stream-pathname stream)))))