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 (defstruct (external-format
727 (:constructor %make-external-format)
729 (:predicate external-format-p)
731 ;; All the names that can refer to this external format. The first
732 ;; one is the canonical name.
733 (names (missing-arg) :type list :read-only t)
734 (read-n-chars-fun (missing-arg) :type function :read-only t)
735 (read-char-fun (missing-arg) :type function :read-only t)
736 (write-n-bytes-fun (missing-arg) :type function :read-only t)
737 (write-char-none-buffered-fun (missing-arg) :type function :read-only t)
738 (write-char-line-buffered-fun (missing-arg) :type function :read-only t)
739 (write-char-full-buffered-fun (missing-arg) :type function :read-only t)
740 ;; Can be nil for fixed-width formats.
741 (resync-fun nil :type (or function null) :read-only t)
742 (bytes-for-char-fun (missing-arg) :type function :read-only t)
743 (read-c-string-fun (missing-arg) :type function :read-only t)
744 (write-c-string-fun (missing-arg) :type function :read-only t)
745 ;; We make these symbols so that a developer working on the octets
746 ;; code can easily redefine things and use the new function definition
747 ;; without redefining the external format as well. The slots above
748 ;; are functions because a developer working with those slots would be
749 ;; redefining the external format anyway.
750 (octets-to-string-sym (missing-arg) :type symbol :read-only t)
751 (string-to-octets-sym (missing-arg) :type symbol :read-only t))
753 (defvar *external-formats* (make-hash-table)
755 "Hashtable of all available external formats. The table maps from
756 external-format names to EXTERNAL-FORMAT structures.")
758 (defun get-external-format (external-format)
759 (gethash external-format *external-formats*))
761 (defun get-external-format-or-lose (external-format)
762 (or (get-external-format external-format)
763 (error "Undefined external-format ~A" external-format)))
765 ;;; Find an output routine to use given the type and buffering. Return
766 ;;; as multiple values the routine, the real type transfered, and the
767 ;;; number of bytes per element.
768 (defun pick-output-routine (type buffering &optional external-format)
769 (when (subtypep type 'character)
770 (let ((entry (get-external-format external-format)))
772 (return-from pick-output-routine
773 (values (ecase buffering
774 (:none (ef-write-char-none-buffered-fun entry))
775 (:line (ef-write-char-line-buffered-fun entry))
776 (:full (ef-write-char-full-buffered-fun entry)))
779 (ef-write-n-bytes-fun entry)
780 (first (ef-names entry)))))))
781 (dolist (entry *output-routines*)
782 (when (and (subtypep type (first entry))
783 (eq buffering (second entry))
784 (or (not (fifth entry))
785 (eq external-format (fifth entry))))
786 (return-from pick-output-routine
787 (values (symbol-function (third entry))
790 ;; KLUDGE: dealing with the buffering here leads to excessive code
793 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
794 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
795 if (subtypep type `(unsigned-byte ,i))
796 do (return-from pick-output-routine
800 (lambda (stream byte)
801 (output-wrapper (stream (/ i 8) (:none) nil)
802 (loop for j from 0 below (/ i 8)
803 do (setf (sap-ref-8 (buffer-sap obuf)
805 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
807 (lambda (stream byte)
808 (output-wrapper (stream (/ i 8) (:full) nil)
809 (loop for j from 0 below (/ i 8)
810 do (setf (sap-ref-8 (buffer-sap obuf)
812 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
815 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
816 if (subtypep type `(signed-byte ,i))
817 do (return-from pick-output-routine
821 (lambda (stream byte)
822 (output-wrapper (stream (/ i 8) (:none) nil)
823 (loop for j from 0 below (/ i 8)
824 do (setf (sap-ref-8 (buffer-sap obuf)
826 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
828 (lambda (stream byte)
829 (output-wrapper (stream (/ i 8) (:full) nil)
830 (loop for j from 0 below (/ i 8)
831 do (setf (sap-ref-8 (buffer-sap obuf)
833 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
837 ;;;; input routines and related noise
839 ;;; a list of all available input routines. Each element is a list of
840 ;;; the element-type input, the function name, and the number of bytes
842 (defvar *input-routines* ())
844 ;;; Return whether a primitive partial read operation on STREAM's FD
845 ;;; would (probably) block. Signal a `simple-stream-error' if the
846 ;;; system call implementing this operation fails.
848 ;;; It is "may" instead of "would" because "would" is not quite
849 ;;; correct on win32. However, none of the places that use it require
850 ;;; further assurance than "may" versus "will definitely not".
851 (defun sysread-may-block-p (stream)
853 ;; This answers T at EOF on win32, I think.
854 (not (sb!win32:fd-listen (fd-stream-fd stream)))
856 (sb!unix:with-restarted-syscall (count errno)
857 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
858 (sb!unix:fd-zero read-fds)
859 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
860 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
861 (sb!alien:addr read-fds)
867 (simple-stream-perror "couldn't check whether ~S is readable"
871 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
872 ;;; then fill the input buffer, and return the number of bytes read. Throws
873 ;;; to EOF-INPUT-CATCHER if the eof was reached.
874 (defun refill-input-buffer (stream)
875 (dx-let ((fd (fd-stream-fd stream))
879 ;; Check for blocking input before touching the stream, as if
880 ;; we happen to wait we are liable to be interrupted, and the
881 ;; interrupt handler may use the same stream.
882 (if (sysread-may-block-p stream)
885 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
886 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
888 (closed-flame stream)
890 (simple-stream-perror "couldn't read from ~S" stream errno)
892 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
893 ;; to wait for input if read tells us EWOULDBLOCK.
894 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
895 (signal-timeout 'io-timeout :stream stream :direction :read
896 :seconds (fd-stream-timeout stream)))
898 ;; Since the read should not block, we'll disable the
899 ;; interrupts here, so that we don't accidentally unwind and
900 ;; leave the stream in an inconsistent state.
902 ;; Execute the nlx outside without-interrupts to ensure the
903 ;; resulting thunk is stack-allocatable.
904 ((lambda (return-reason)
906 ((nil)) ; fast path normal cases
907 ((:wait-for-input) (go :wait-for-input))
908 ((:closed-flame) (go :closed-flame))
909 ((:read-error) (go :read-error))))
911 ;; Check the buffer: if it is null, then someone has closed
912 ;; the stream from underneath us. This is not ment to fix
913 ;; multithreaded races, but to deal with interrupt handlers
914 ;; closing the stream.
917 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
918 (sap (buffer-sap ibuf))
919 (length (buffer-length ibuf))
920 (head (buffer-head ibuf))
921 (tail (buffer-tail ibuf)))
922 (declare (index length head tail)
923 (inline sb!unix:unix-read))
925 (cond ((eql head tail)
926 ;; Buffer is empty, but not at yet reset -- make it so.
931 ;; Buffer has things in it, but they are not at the
932 ;; head -- move them there.
933 (let ((n (- tail head)))
934 (system-area-ub8-copy sap head sap 0 n)
936 (buffer-head ibuf) head
938 (buffer-tail ibuf) tail)))))
939 (setf (fd-stream-listen stream) nil)
940 (setf (values count errno)
941 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
946 (if (eql errno sb!unix:ewouldblock)
947 (return :wait-for-input)
948 (return :read-error)))
950 (setf (fd-stream-listen stream) :eof)
951 (/show0 "THROWing EOF-INPUT-CATCHER")
952 (throw 'eof-input-catcher nil))
954 ;; Success! (Do not use INCF, for sake of other threads.)
955 (setf (buffer-tail ibuf) (+ count tail))))))))))
958 ;;; Make sure there are at least BYTES number of bytes in the input
959 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
960 (defmacro input-at-least (stream bytes)
961 (let ((stream-var (gensym "STREAM"))
962 (bytes-var (gensym "BYTES"))
963 (buffer-var (gensym "IBUF")))
964 `(let* ((,stream-var ,stream)
966 (,buffer-var (fd-stream-ibuf ,stream-var)))
968 (when (>= (- (buffer-tail ,buffer-var)
969 (buffer-head ,buffer-var))
972 (refill-input-buffer ,stream-var)))))
974 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
976 (let ((stream-var (gensym "STREAM"))
977 (retry-var (gensym "RETRY"))
978 (element-var (gensym "ELT")))
979 `(let* ((,stream-var ,stream)
980 (ibuf (fd-stream-ibuf ,stream-var))
982 (if (fd-stream-unread ,stream-var)
984 (fd-stream-unread ,stream-var)
985 (setf (fd-stream-unread ,stream-var) nil)
986 (setf (fd-stream-listen ,stream-var) nil))
987 (let ((,element-var nil)
988 (decode-break-reason nil))
992 (catch 'eof-input-catcher
993 (setf decode-break-reason
994 (block decode-break-reason
995 (input-at-least ,stream-var 1)
996 (let* ((byte (sap-ref-8 (buffer-sap ibuf)
997 (buffer-head ibuf))))
998 (declare (ignorable byte))
1000 (input-at-least ,stream-var size)
1001 (setq ,element-var (locally ,@read-forms))
1002 (setq ,retry-var nil))
1004 (when decode-break-reason
1005 (stream-decoding-error-and-handle stream
1006 decode-break-reason))
1008 (let ((octet-count (- (buffer-tail ibuf)
1009 (buffer-head ibuf))))
1010 (when (or (zerop octet-count)
1011 (and (not ,element-var)
1012 (not decode-break-reason)
1013 (stream-decoding-error-and-handle
1014 stream octet-count)))
1015 (setq ,retry-var nil)))))
1017 (incf (buffer-head ibuf) size)
1020 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1022 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1023 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1024 (let ((stream-var (gensym "STREAM"))
1025 (element-var (gensym "ELT")))
1026 `(let* ((,stream-var ,stream)
1027 (ibuf (fd-stream-ibuf ,stream-var)))
1028 (if (fd-stream-unread ,stream-var)
1030 (fd-stream-unread ,stream-var)
1031 (setf (fd-stream-unread ,stream-var) nil)
1032 (setf (fd-stream-listen ,stream-var) nil))
1034 (catch 'eof-input-catcher
1035 (input-at-least ,stream-var ,bytes)
1036 (locally ,@read-forms))))
1038 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1041 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1043 (defmacro def-input-routine/variable-width (name
1044 (type external-format size sap head)
1047 (defun ,name (stream eof-error eof-value)
1048 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1049 (let ((,sap (buffer-sap ibuf))
1050 (,head (buffer-head ibuf)))
1052 (setf *input-routines*
1053 (nconc *input-routines*
1054 (list (list ',type ',name 1 ',external-format))))))
1056 (defmacro def-input-routine (name
1057 (type size sap head)
1060 (defun ,name (stream eof-error eof-value)
1061 (input-wrapper (stream ,size eof-error eof-value)
1062 (let ((,sap (buffer-sap ibuf))
1063 (,head (buffer-head ibuf)))
1065 (setf *input-routines*
1066 (nconc *input-routines*
1067 (list (list ',type ',name ',size nil))))))
1069 ;;; STREAM-IN routine for reading a string char
1070 (def-input-routine input-character
1071 (character 1 sap head)
1072 (code-char (sap-ref-8 sap head)))
1074 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1075 (def-input-routine input-unsigned-8bit-byte
1076 ((unsigned-byte 8) 1 sap head)
1077 (sap-ref-8 sap head))
1079 ;;; STREAM-IN routine for reading a signed 8 bit number
1080 (def-input-routine input-signed-8bit-number
1081 ((signed-byte 8) 1 sap head)
1082 (signed-sap-ref-8 sap head))
1084 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1085 (def-input-routine input-unsigned-16bit-byte
1086 ((unsigned-byte 16) 2 sap head)
1087 (sap-ref-16 sap head))
1089 ;;; STREAM-IN routine for reading a signed 16 bit number
1090 (def-input-routine input-signed-16bit-byte
1091 ((signed-byte 16) 2 sap head)
1092 (signed-sap-ref-16 sap head))
1094 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1095 (def-input-routine input-unsigned-32bit-byte
1096 ((unsigned-byte 32) 4 sap head)
1097 (sap-ref-32 sap head))
1099 ;;; STREAM-IN routine for reading a signed 32 bit number
1100 (def-input-routine input-signed-32bit-byte
1101 ((signed-byte 32) 4 sap head)
1102 (signed-sap-ref-32 sap head))
1104 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1106 (def-input-routine input-unsigned-64bit-byte
1107 ((unsigned-byte 64) 8 sap head)
1108 (sap-ref-64 sap head))
1109 (def-input-routine input-signed-64bit-byte
1110 ((signed-byte 64) 8 sap head)
1111 (signed-sap-ref-64 sap head)))
1113 ;;; Find an input routine to use given the type. Return as multiple
1114 ;;; values the routine, the real type transfered, and the number of
1115 ;;; bytes per element (and for character types string input routine).
1116 (defun pick-input-routine (type &optional external-format)
1117 (when (subtypep type 'character)
1118 (let ((entry (get-external-format external-format)))
1120 (return-from pick-input-routine
1121 (values (ef-read-char-fun entry)
1124 (ef-read-n-chars-fun entry)
1125 (first (ef-names entry)))))))
1126 (dolist (entry *input-routines*)
1127 (when (and (subtypep type (first entry))
1128 (or (not (fourth entry))
1129 (eq external-format (fourth entry))))
1130 (return-from pick-input-routine
1131 (values (symbol-function (second entry))
1134 ;; FIXME: let's do it the hard way, then (but ignore things like
1135 ;; endianness, efficiency, and the necessary coupling between these
1136 ;; and the output routines). -- CSR, 2004-02-09
1137 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1138 if (subtypep type `(unsigned-byte ,i))
1139 do (return-from pick-input-routine
1141 (lambda (stream eof-error eof-value)
1142 (input-wrapper (stream (/ i 8) eof-error eof-value)
1143 (let ((sap (buffer-sap ibuf))
1144 (head (buffer-head ibuf)))
1145 (loop for j from 0 below (/ i 8)
1149 (sap-ref-8 sap (+ head j))))
1150 finally (return result)))))
1153 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1154 if (subtypep type `(signed-byte ,i))
1155 do (return-from pick-input-routine
1157 (lambda (stream eof-error eof-value)
1158 (input-wrapper (stream (/ i 8) eof-error eof-value)
1159 (let ((sap (buffer-sap ibuf))
1160 (head (buffer-head ibuf)))
1161 (loop for j from 0 below (/ i 8)
1165 (sap-ref-8 sap (+ head j))))
1166 finally (return (if (logbitp (1- i) result)
1167 (dpb result (byte i 0) -1)
1172 ;;; the N-BIN method for FD-STREAMs
1174 ;;; Note that this blocks in UNIX-READ. It is generally used where
1175 ;;; there is a definite amount of reading to be done, so blocking
1176 ;;; isn't too problematical.
1177 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1178 &aux (total-copied 0))
1179 (declare (type fd-stream stream))
1180 (declare (type index start requested total-copied))
1181 (let ((unread (fd-stream-unread stream)))
1183 ;; AVERs designed to fail when we have more complicated
1184 ;; character representations.
1185 (aver (typep unread 'base-char))
1186 (aver (= (fd-stream-element-size stream) 1))
1187 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1190 (system-area-pointer
1191 (setf (sap-ref-8 buffer start) (char-code unread)))
1192 ((simple-unboxed-array (*))
1193 (setf (aref buffer start) unread)))
1194 (setf (fd-stream-unread stream) nil)
1195 (setf (fd-stream-listen stream) nil)
1196 (incf total-copied)))
1199 (let* ((remaining-request (- requested total-copied))
1200 (ibuf (fd-stream-ibuf stream))
1201 (head (buffer-head ibuf))
1202 (tail (buffer-tail ibuf))
1203 (available (- tail head))
1204 (n-this-copy (min remaining-request available))
1205 (this-start (+ start total-copied))
1206 (this-end (+ this-start n-this-copy))
1207 (sap (buffer-sap ibuf)))
1208 (declare (type index remaining-request head tail available))
1209 (declare (type index n-this-copy))
1210 ;; Copy data from stream buffer into user's buffer.
1211 (%byte-blt sap head buffer this-start this-end)
1212 (incf (buffer-head ibuf) n-this-copy)
1213 (incf total-copied n-this-copy)
1214 ;; Maybe we need to refill the stream buffer.
1215 (cond (;; If there were enough data in the stream buffer, we're done.
1216 (eql total-copied requested)
1217 (return total-copied))
1218 (;; If EOF, we're done in another way.
1219 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1221 (error 'end-of-file :stream stream)
1222 (return total-copied)))
1223 ;; Otherwise we refilled the stream buffer, so fall
1224 ;; through into another pass of the loop.
1227 (defun fd-stream-resync (stream)
1228 (let ((entry (get-external-format (fd-stream-external-format stream))))
1230 (funcall (ef-resync-fun entry) stream))))
1232 (defun get-fd-stream-character-sizer (stream)
1233 (let ((entry (get-external-format (fd-stream-external-format stream))))
1235 (ef-bytes-for-char-fun entry))))
1237 (defun fd-stream-character-size (stream char)
1238 (let ((sizer (get-fd-stream-character-sizer stream)))
1239 (when sizer (funcall sizer char))))
1241 (defun fd-stream-string-size (stream string)
1242 (let ((sizer (get-fd-stream-character-sizer stream)))
1244 (loop for char across string summing (funcall sizer char)))))
1246 (defun find-external-format (external-format)
1247 (when external-format
1248 (get-external-format external-format)))
1250 (defun variable-width-external-format-p (ef-entry)
1251 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1253 (defun bytes-for-char-fun (ef-entry)
1254 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1256 (defmacro define-external-format (external-format size output-restart
1258 octets-to-string-sym
1259 string-to-octets-sym)
1260 (let* ((name (first external-format))
1261 (out-function (symbolicate "OUTPUT-BYTES/" name))
1262 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1263 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1264 (in-char-function (symbolicate "INPUT-CHAR/" name))
1265 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1266 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1267 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1268 (n-buffer (gensym "BUFFER")))
1270 (defun ,size-function (byte)
1271 (declare (ignore byte))
1273 (defun ,out-function (stream string flush-p start end)
1274 (let ((start (or start 0))
1275 (end (or end (length string))))
1276 (declare (type index start end))
1277 (synchronize-stream-output stream)
1278 (unless (<= 0 start end (length string))
1279 (sequence-bounding-indices-bad-error string start end))
1282 (let ((obuf (fd-stream-obuf stream)))
1283 (setf (buffer-tail obuf)
1284 (string-dispatch (simple-base-string
1286 (simple-array character (*))
1289 (let ((sap (buffer-sap obuf))
1290 (len (buffer-length obuf))
1292 (tail (buffer-tail obuf)))
1293 (declare (type index tail)
1294 ;; STRING bounds have already been checked.
1295 (optimize (safety 0)))
1297 (,@(if output-restart
1298 `(catch 'output-nothing)
1301 ((or (= start end) (< (- len tail) 4)))
1302 (let* ((byte (aref string start))
1303 (bits (char-code byte)))
1307 ;; Exited from the loop normally
1309 ;; Exited via CATCH. Skip the current character
1310 ;; and try the inner loop again.
1313 (flush-output-buffer stream)))
1315 (flush-output-buffer stream))))
1316 (def-output-routines (,format
1322 (if (eql byte #\Newline)
1323 (setf (fd-stream-char-pos stream) 0)
1324 (incf (fd-stream-char-pos stream)))
1325 (let* ((obuf (fd-stream-obuf stream))
1326 (bits (char-code byte))
1327 (sap (buffer-sap obuf))
1328 (tail (buffer-tail obuf)))
1330 (defun ,in-function (stream buffer start requested eof-error-p
1331 &aux (index start) (end (+ start requested)))
1332 (declare (type fd-stream stream)
1333 (type index start requested index end)
1335 (simple-array character (#.+ansi-stream-in-buffer-length+))
1337 (let ((unread (fd-stream-unread stream)))
1339 (setf (aref buffer index) unread)
1340 (setf (fd-stream-unread stream) nil)
1341 (setf (fd-stream-listen stream) nil)
1345 (let* ((ibuf (fd-stream-ibuf stream))
1346 (head (buffer-head ibuf))
1347 (tail (buffer-tail ibuf))
1348 (sap (buffer-sap ibuf)))
1349 (declare (type index head tail)
1350 (type system-area-pointer sap))
1351 ;; Copy data from stream buffer into user's buffer.
1352 (dotimes (i (min (truncate (- tail head) ,size)
1354 (declare (optimize speed))
1355 (let* ((byte (sap-ref-8 sap head)))
1356 (setf (aref buffer index) ,in-expr)
1359 (setf (buffer-head ibuf) head)
1360 ;; Maybe we need to refill the stream buffer.
1361 (cond ( ;; If there was enough data in the stream buffer, we're done.
1363 (return (- index start)))
1364 ( ;; If EOF, we're done in another way.
1365 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1367 (error 'end-of-file :stream stream)
1368 (return (- index start))))
1369 ;; Otherwise we refilled the stream buffer, so fall
1370 ;; through into another pass of the loop.
1372 (def-input-routine ,in-char-function (character ,size sap head)
1373 (let ((byte (sap-ref-8 sap head)))
1375 (defun ,read-c-string-function (sap element-type)
1376 (declare (type system-area-pointer sap)
1377 (type (member character base-char) element-type))
1379 (declare (optimize (speed 3) (safety 0)))
1380 (let* ((stream ,name)
1382 (loop for head of-type index upfrom 0 by ,size
1383 for count of-type index upto (1- array-dimension-limit)
1384 for byte = (sap-ref-8 sap head)
1385 for char of-type character = ,in-expr
1386 until (zerop (char-code char))
1387 finally (return count)))
1388 ;; Inline the common cases
1389 (string (make-string length :element-type element-type)))
1390 (declare (ignorable stream)
1392 (type simple-string string))
1393 (/show0 before-copy-loop)
1394 (loop for head of-type index upfrom 0 by ,size
1395 for index of-type index below length
1396 for byte = (sap-ref-8 sap head)
1397 for char of-type character = ,in-expr
1398 do (setf (aref string index) char))
1399 string))) ;; last loop rewrite to dotimes?
1400 (defun ,output-c-string-function (string)
1401 (declare (type simple-string string))
1403 (declare (optimize (speed 3) (safety 0)))
1404 (let* ((length (length string))
1405 (,n-buffer (make-array (* (1+ length) ,size)
1406 :element-type '(unsigned-byte 8)))
1409 (declare (type index length tail))
1410 (with-pinned-objects (,n-buffer)
1411 (let ((sap (vector-sap ,n-buffer)))
1412 (declare (system-area-pointer sap))
1414 (let* ((byte (aref string i))
1415 (bits (char-code byte)))
1416 (declare (ignorable byte bits))
1420 (byte (code-char bits)))
1421 (declare (ignorable bits byte))
1424 (let ((entry (%make-external-format
1425 :names ',external-format
1426 :read-n-chars-fun #',in-function
1427 :read-char-fun #',in-char-function
1428 :write-n-bytes-fun #',out-function
1429 ,@(mapcan #'(lambda (buffering)
1430 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1431 `#',(intern (format nil format (string buffering)))))
1432 '(:none :line :full))
1434 :bytes-for-char-fun #',size-function
1435 :read-c-string-fun #',read-c-string-function
1436 :write-c-string-fun #',output-c-string-function
1437 :octets-to-string-sym ',octets-to-string-sym
1438 :string-to-octets-sym ',string-to-octets-sym)))
1439 (dolist (ef ',external-format)
1440 (setf (gethash ef *external-formats*) entry))))))
1442 (defmacro define-external-format/variable-width
1443 (external-format output-restart out-size-expr
1444 out-expr in-size-expr in-expr
1445 octets-to-string-sym string-to-octets-sym)
1446 (let* ((name (first external-format))
1447 (out-function (symbolicate "OUTPUT-BYTES/" name))
1448 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1449 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1450 (in-char-function (symbolicate "INPUT-CHAR/" name))
1451 (resync-function (symbolicate "RESYNC/" name))
1452 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1453 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1454 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1455 (n-buffer (gensym "BUFFER")))
1457 (defun ,size-function (byte)
1458 (declare (ignorable byte))
1460 (defun ,out-function (stream string flush-p start end)
1461 (let ((start (or start 0))
1462 (end (or end (length string))))
1463 (declare (type index start end))
1464 (synchronize-stream-output stream)
1465 (unless (<= 0 start end (length string))
1466 (sequence-bounding-indices-bad string start end))
1469 (let ((obuf (fd-stream-obuf stream)))
1470 (setf (buffer-tail obuf)
1471 (string-dispatch (simple-base-string
1473 (simple-array character (*))
1476 (let ((len (buffer-length obuf))
1477 (sap (buffer-sap obuf))
1479 (tail (buffer-tail obuf)))
1480 (declare (type index tail)
1481 ;; STRING bounds have already been checked.
1482 (optimize (safety 0)))
1484 (,@(if output-restart
1485 `(catch 'output-nothing)
1488 ((or (= start end) (< (- len tail) 4)))
1489 (let* ((byte (aref string start))
1490 (bits (char-code byte))
1491 (size ,out-size-expr))
1495 ;; Exited from the loop normally
1497 ;; Exited via CATCH. Skip the current character
1498 ;; and try the inner loop again.
1501 (flush-output-buffer stream)))
1503 (flush-output-buffer stream))))
1504 (def-output-routines/variable-width (,format
1511 (if (eql byte #\Newline)
1512 (setf (fd-stream-char-pos stream) 0)
1513 (incf (fd-stream-char-pos stream)))
1514 (let ((bits (char-code byte))
1515 (sap (buffer-sap obuf))
1516 (tail (buffer-tail obuf)))
1518 (defun ,in-function (stream buffer start requested eof-error-p
1519 &aux (total-copied 0))
1520 (declare (type fd-stream stream)
1521 (type index start requested total-copied)
1523 (simple-array character (#.+ansi-stream-in-buffer-length+))
1525 (let ((unread (fd-stream-unread stream)))
1527 (setf (aref buffer start) unread)
1528 (setf (fd-stream-unread stream) nil)
1529 (setf (fd-stream-listen stream) nil)
1530 (incf total-copied)))
1533 (let* ((ibuf (fd-stream-ibuf stream))
1534 (head (buffer-head ibuf))
1535 (tail (buffer-tail ibuf))
1536 (sap (buffer-sap ibuf))
1537 (decode-break-reason nil))
1538 (declare (type index head tail))
1539 ;; Copy data from stream buffer into user's buffer.
1540 (do ((size nil nil))
1541 ((or (= tail head) (= requested total-copied)))
1542 (setf decode-break-reason
1543 (block decode-break-reason
1544 (let ((byte (sap-ref-8 sap head)))
1545 (declare (ignorable byte))
1546 (setq size ,in-size-expr)
1547 (when (> size (- tail head))
1549 (setf (aref buffer (+ start total-copied)) ,in-expr)
1553 (setf (buffer-head ibuf) head)
1554 (when decode-break-reason
1555 ;; If we've already read some characters on when the invalid
1556 ;; code sequence is detected, we return immediately. The
1557 ;; handling of the error is deferred until the next call
1558 ;; (where this check will be false). This allows establishing
1559 ;; high-level handlers for decode errors (for example
1560 ;; automatically resyncing in Lisp comments).
1561 (when (plusp total-copied)
1562 (return-from ,in-function total-copied))
1563 (when (stream-decoding-error-and-handle
1564 stream decode-break-reason)
1566 (error 'end-of-file :stream stream)
1567 (return-from ,in-function total-copied)))
1568 (setf head (buffer-head ibuf))
1569 (setf tail (buffer-tail ibuf))))
1570 (setf (buffer-head ibuf) head)
1571 ;; Maybe we need to refill the stream buffer.
1572 (cond ( ;; If there were enough data in the stream buffer, we're done.
1573 (= total-copied requested)
1574 (return total-copied))
1575 ( ;; If EOF, we're done in another way.
1576 (or (eq decode-break-reason 'eof)
1577 (null (catch 'eof-input-catcher
1578 (refill-input-buffer stream))))
1580 (error 'end-of-file :stream stream)
1581 (return total-copied)))
1582 ;; Otherwise we refilled the stream buffer, so fall
1583 ;; through into another pass of the loop.
1585 (def-input-routine/variable-width ,in-char-function (character
1589 (let ((byte (sap-ref-8 sap head)))
1590 (declare (ignorable byte))
1592 (defun ,resync-function (stream)
1593 (let ((ibuf (fd-stream-ibuf stream)))
1595 (input-at-least stream 2)
1596 (incf (buffer-head ibuf))
1597 (unless (block decode-break-reason
1598 (let* ((sap (buffer-sap ibuf))
1599 (head (buffer-head ibuf))
1600 (byte (sap-ref-8 sap head))
1601 (size ,in-size-expr))
1602 (declare (ignorable byte))
1603 (input-at-least stream size)
1604 (setf head (buffer-head ibuf))
1608 (defun ,read-c-string-function (sap element-type)
1609 (declare (type system-area-pointer sap))
1611 (declare (optimize (speed 3) (safety 0)))
1612 (let* ((stream ,name)
1613 (size 0) (head 0) (byte 0) (char nil)
1614 (decode-break-reason nil)
1615 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1616 (setf decode-break-reason
1617 (block decode-break-reason
1618 (setf byte (sap-ref-8 sap head)
1623 (when decode-break-reason
1624 (c-string-decoding-error ,name decode-break-reason))
1625 (when (zerop (char-code char))
1627 (string (make-string length :element-type element-type)))
1628 (declare (ignorable stream)
1629 (type index head length) ;; size
1630 (type (unsigned-byte 8) byte)
1631 (type (or null character) char)
1632 (type string string))
1634 (dotimes (index length string)
1635 (setf decode-break-reason
1636 (block decode-break-reason
1637 (setf byte (sap-ref-8 sap head)
1642 (when decode-break-reason
1643 (c-string-decoding-error ,name decode-break-reason))
1644 (setf (aref string index) char)))))
1646 (defun ,output-c-string-function (string)
1647 (declare (type simple-string string))
1649 (declare (optimize (speed 3) (safety 0)))
1650 (let* ((length (length string))
1651 (char-length (make-array (1+ length) :element-type 'index))
1653 (+ (loop for i of-type index below length
1654 for byte of-type character = (aref string i)
1655 for bits = (char-code byte)
1656 sum (setf (aref char-length i)
1657 (the index ,out-size-expr)))
1658 (let* ((byte (code-char 0))
1659 (bits (char-code byte)))
1660 (declare (ignorable byte bits))
1661 (setf (aref char-length length)
1662 (the index ,out-size-expr)))))
1664 (,n-buffer (make-array buffer-length
1665 :element-type '(unsigned-byte 8)))
1667 (declare (type index length buffer-length tail)
1670 (with-pinned-objects (,n-buffer)
1671 (let ((sap (vector-sap ,n-buffer)))
1672 (declare (system-area-pointer sap))
1673 (loop for i of-type index below length
1674 for byte of-type character = (aref string i)
1675 for bits = (char-code byte)
1676 for size of-type index = (aref char-length i)
1681 (byte (code-char bits))
1682 (size (aref char-length length)))
1683 (declare (ignorable bits byte size))
1687 (let ((entry (%make-external-format
1688 :names ',external-format
1689 :read-n-chars-fun #',in-function
1690 :read-char-fun #',in-char-function
1691 :write-n-bytes-fun #',out-function
1692 ,@(mapcan #'(lambda (buffering)
1693 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1694 `#',(intern (format nil format (string buffering)))))
1695 '(:none :line :full))
1696 :resync-fun #',resync-function
1697 :bytes-for-char-fun #',size-function
1698 :read-c-string-fun #',read-c-string-function
1699 :write-c-string-fun #',output-c-string-function
1700 :octets-to-string-sym ',octets-to-string-sym
1701 :string-to-octets-sym ',string-to-octets-sym)))
1702 (dolist (ef ',external-format)
1703 (setf (gethash ef *external-formats*) entry))))))
1705 ;;;; utility functions (misc routines, etc)
1707 ;;; Fill in the various routine slots for the given type. INPUT-P and
1708 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1709 ;;; set prior to calling this routine.
1710 (defun set-fd-stream-routines (fd-stream element-type external-format
1711 input-p output-p buffer-p)
1712 (let* ((target-type (case element-type
1713 (unsigned-byte '(unsigned-byte 8))
1714 (signed-byte '(signed-byte 8))
1715 (:default 'character)
1717 (character-stream-p (subtypep target-type 'character))
1718 (bivalent-stream-p (eq element-type :default))
1719 normalized-external-format
1720 (bin-routine #'ill-bin)
1723 (cin-routine #'ill-in)
1726 (input-type nil) ;calculated from bin-type/cin-type
1727 (input-size nil) ;calculated from bin-size/cin-size
1728 (read-n-characters #'ill-in)
1729 (bout-routine #'ill-bout)
1732 (cout-routine #'ill-out)
1737 (output-bytes #'ill-bout))
1739 ;; Ensure that we have buffers in the desired direction(s) only,
1740 ;; getting new ones and dropping/resetting old ones as necessary.
1741 (let ((obuf (fd-stream-obuf fd-stream)))
1745 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1747 (setf (fd-stream-obuf fd-stream) nil)
1748 (release-buffer obuf))))
1750 (let ((ibuf (fd-stream-ibuf fd-stream)))
1754 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1756 (setf (fd-stream-ibuf fd-stream) nil)
1757 (release-buffer ibuf))))
1759 ;; FIXME: Why only for output? Why unconditionally?
1761 (setf (fd-stream-char-pos fd-stream) 0))
1763 (when (and character-stream-p
1764 (eq external-format :default))
1765 (/show0 "/getting default external format")
1766 (setf external-format (default-external-format)))
1769 (when (or (not character-stream-p) bivalent-stream-p)
1770 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1771 normalized-external-format)
1772 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1776 (error "could not find any input routine for ~S" target-type)))
1777 (when character-stream-p
1778 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1779 normalized-external-format)
1780 (pick-input-routine target-type external-format))
1782 (error "could not find any input routine for ~S" target-type)))
1783 (setf (fd-stream-in fd-stream) cin-routine
1784 (fd-stream-bin fd-stream) bin-routine)
1785 ;; character type gets preferential treatment
1786 (setf input-size (or cin-size bin-size))
1787 (setf input-type (or cin-type bin-type))
1788 (when normalized-external-format
1789 (setf (fd-stream-external-format fd-stream)
1790 normalized-external-format))
1791 (when (= (or cin-size 1) (or bin-size 1) 1)
1792 (setf (fd-stream-n-bin fd-stream) ;XXX
1793 (if (and character-stream-p (not bivalent-stream-p))
1795 #'fd-stream-read-n-bytes))
1796 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1797 ;; for character and (unsigned-byte 8) streams. In these
1798 ;; cases, fast-read-* will read from the
1799 ;; ansi-stream-(c)in-buffer, saving function calls.
1800 ;; Otherwise, the various data-reading functions in the stream
1801 ;; structure will be called.
1803 (not bivalent-stream-p)
1804 ;; temporary disable on :io streams
1806 (cond (character-stream-p
1807 (setf (ansi-stream-cin-buffer fd-stream)
1808 (make-array +ansi-stream-in-buffer-length+
1809 :element-type 'character)))
1810 ((equal target-type '(unsigned-byte 8))
1811 (setf (ansi-stream-in-buffer fd-stream)
1812 (make-array +ansi-stream-in-buffer-length+
1813 :element-type '(unsigned-byte 8))))))))
1816 (when (or (not character-stream-p) bivalent-stream-p)
1817 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1818 normalized-external-format)
1819 (pick-output-routine (if bivalent-stream-p
1822 (fd-stream-buffering fd-stream)
1824 (unless bout-routine
1825 (error "could not find any output routine for ~S buffered ~S"
1826 (fd-stream-buffering fd-stream)
1828 (when character-stream-p
1829 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1830 normalized-external-format)
1831 (pick-output-routine target-type
1832 (fd-stream-buffering fd-stream)
1834 (unless cout-routine
1835 (error "could not find any output routine for ~S buffered ~S"
1836 (fd-stream-buffering fd-stream)
1838 (when normalized-external-format
1839 (setf (fd-stream-external-format fd-stream)
1840 normalized-external-format))
1841 (when character-stream-p
1842 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1843 (setf (fd-stream-out fd-stream) cout-routine
1844 (fd-stream-bout fd-stream) bout-routine
1845 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1846 #'fd-sout #'ill-out))
1847 (setf output-size (or cout-size bout-size))
1848 (setf output-type (or cout-type bout-type)))
1850 (when (and input-size output-size
1851 (not (eq input-size output-size)))
1852 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1853 input-type input-size
1854 output-type output-size))
1855 (setf (fd-stream-element-size fd-stream)
1856 (or input-size output-size))
1858 (setf (fd-stream-element-type fd-stream)
1859 (cond ((equal input-type output-type)
1865 ((subtypep input-type output-type)
1867 ((subtypep output-type input-type)
1870 (error "Input type (~S) and output type (~S) are unrelated?"
1874 ;;; Handles the resource-release aspects of stream closing, and marks
1876 (defun release-fd-stream-resources (fd-stream)
1879 ;; Drop handlers first.
1880 (when (fd-stream-handler fd-stream)
1881 (remove-fd-handler (fd-stream-handler fd-stream))
1882 (setf (fd-stream-handler fd-stream) nil))
1883 ;; Disable interrupts so that a asynch unwind will not leave
1884 ;; us with a dangling finalizer (that would close the same
1885 ;; --possibly reassigned-- FD again), or a stream with a closed
1886 ;; FD that appears open.
1887 (sb!unix:unix-close (fd-stream-fd fd-stream))
1888 (set-closed-flame fd-stream)
1889 (when (fboundp 'cancel-finalization)
1890 (cancel-finalization fd-stream)))
1891 ;; On error unwind from WITHOUT-INTERRUPTS.
1892 (serious-condition (e)
1894 ;; Release all buffers. If this is undone, or interrupted,
1895 ;; we're still safe: buffers have finalizers of their own.
1896 (release-fd-stream-buffers fd-stream))
1898 ;;; Flushes the current input buffer and unread chatacter, and returns
1899 ;;; the input buffer, and the amount of of flushed input in bytes.
1900 (defun flush-input-buffer (stream)
1901 (let ((unread (if (fd-stream-unread stream)
1904 (setf (fd-stream-unread stream) nil)
1905 (let ((ibuf (fd-stream-ibuf stream)))
1907 (let ((head (buffer-head ibuf))
1908 (tail (buffer-tail ibuf)))
1909 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1910 (values nil unread)))))
1912 (defun fd-stream-clear-input (stream)
1913 (flush-input-buffer stream)
1916 (sb!win32:fd-clear-input (fd-stream-fd stream))
1917 (setf (fd-stream-listen stream) nil))
1919 (catch 'eof-input-catcher
1920 (loop until (sysread-may-block-p stream)
1922 (refill-input-buffer stream)
1923 (reset-buffer (fd-stream-ibuf stream)))
1926 ;;; Handle miscellaneous operations on FD-STREAM.
1927 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1928 (declare (ignore arg2))
1931 (labels ((do-listen ()
1932 (let ((ibuf (fd-stream-ibuf fd-stream)))
1933 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1934 (fd-stream-listen fd-stream)
1936 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1938 ;; If the read can block, LISTEN will certainly return NIL.
1939 (if (sysread-may-block-p fd-stream)
1941 ;; Otherwise select(2) and CL:LISTEN have slightly
1942 ;; different semantics. The former returns that an FD
1943 ;; is readable when a read operation wouldn't block.
1944 ;; That includes EOF. However, LISTEN must return NIL
1946 (progn (catch 'eof-input-catcher
1947 ;; r-b/f too calls select, but it shouldn't
1948 ;; block as long as read can return once w/o
1950 (refill-input-buffer fd-stream))
1951 ;; At this point either IBUF-HEAD != IBUF-TAIL
1952 ;; and FD-STREAM-LISTEN is NIL, in which case
1953 ;; we should return T, or IBUF-HEAD ==
1954 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1955 ;; which case we should return :EOF for this
1956 ;; call and all future LISTEN call on this stream.
1957 ;; Call ourselves again to determine which case
1962 ;; If the stream is bivalent, the user might follow an
1963 ;; unread-char with a read-byte. In this case, the bookkeeping
1964 ;; is simpler if we adjust the buffer head by the number of code
1965 ;; units in the character.
1966 ;; FIXME: there has to be a proper way to check for bivalence,
1968 (if (fd-stream-bivalent-p fd-stream)
1969 (decf (buffer-head (fd-stream-ibuf fd-stream))
1970 (fd-stream-character-size fd-stream arg1))
1971 (setf (fd-stream-unread fd-stream) arg1))
1972 (setf (fd-stream-listen fd-stream) t))
1974 ;; Drop input buffers
1975 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1976 (ansi-stream-cin-buffer fd-stream) nil
1977 (ansi-stream-in-buffer fd-stream) nil)
1979 ;; We got us an abort on our hands.
1980 (let ((outputp (fd-stream-obuf fd-stream))
1981 (file (fd-stream-file fd-stream))
1982 (orig (fd-stream-original fd-stream)))
1983 ;; This takes care of the important stuff -- everything
1984 ;; rest is cleaning up the file-system, which we cannot
1985 ;; do on some platforms as long as the file is open.
1986 (release-fd-stream-resources fd-stream)
1987 ;; We can't do anything unless we know what file were
1988 ;; dealing with, and we don't want to do anything
1989 ;; strange unless we were writing to the file.
1990 (when (and outputp file)
1992 ;; If the original is EQ to file we are appending to
1993 ;; and can just close the file without renaming.
1994 (unless (eq orig file)
1995 ;; We have a handle on the original, just revert.
1996 (multiple-value-bind (okay err)
1997 (sb!unix:unix-rename orig file)
1998 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1999 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2002 (error 'simple-stream-error
2004 "~@<Couldn't restore ~S to its original contents ~
2005 from ~S while closing ~S: ~2I~_~A~:>"
2007 (list file orig fd-stream (strerror err))
2008 :stream fd-stream))))
2009 ;; We can't restore the original, and aren't
2010 ;; appending, so nuke that puppy.
2012 ;; FIXME: This is currently the fate of superseded
2013 ;; files, and according to the CLOSE spec this is
2014 ;; wrong. However, there seems to be no clean way to
2015 ;; do that that doesn't involve either copying the
2016 ;; data (bad if the :abort resulted from a full
2017 ;; disk), or renaming the old file temporarily
2018 ;; (probably bad because stream opening becomes more
2020 (multiple-value-bind (okay err)
2021 (sb!unix:unix-unlink file)
2023 (error 'simple-file-error
2026 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2028 (list file fd-stream (strerror err)))))))))
2030 (finish-fd-stream-output fd-stream)
2031 (let ((orig (fd-stream-original fd-stream)))
2032 (when (and orig (fd-stream-delete-original fd-stream))
2033 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2035 (error 'simple-file-error
2038 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2040 (list orig fd-stream (strerror err)))))))
2041 ;; In case of no-abort close, don't *really* close the
2042 ;; stream until the last moment -- the cleaning up of the
2043 ;; original can be done first.
2044 (release-fd-stream-resources fd-stream))))
2046 (fd-stream-clear-input fd-stream))
2048 (flush-output-buffer fd-stream))
2050 (finish-fd-stream-output fd-stream))
2052 (fd-stream-element-type fd-stream))
2054 (fd-stream-external-format fd-stream))
2056 (= 1 (the (member 0 1)
2057 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2061 (fd-stream-char-pos fd-stream))
2063 (unless (fd-stream-file fd-stream)
2064 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2065 ;; "should signal an error of type TYPE-ERROR if stream is not
2066 ;; a stream associated with a file". Too bad there's no very
2067 ;; appropriate value for the EXPECTED-TYPE slot..
2068 (error 'simple-type-error
2070 :expected-type 'fd-stream
2071 :format-control "~S is not a stream associated with a file."
2072 :format-arguments (list fd-stream)))
2073 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2074 atime mtime ctime blksize blocks)
2075 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2076 (declare (ignore ino nlink uid gid rdev
2077 atime mtime ctime blksize blocks))
2079 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2082 (truncate size (fd-stream-element-size fd-stream)))))
2083 (:file-string-length
2085 (character (fd-stream-character-size fd-stream arg1))
2086 (string (fd-stream-string-size fd-stream arg1))))
2089 (fd-stream-set-file-position fd-stream arg1)
2090 (fd-stream-get-file-position fd-stream)))))
2092 ;; FIXME: Think about this.
2094 ;; (defun finish-fd-stream-output (fd-stream)
2095 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2096 ;; (loop while (fd-stream-output-queue fd-stream)
2097 ;; ;; FIXME: SIGINT while waiting for a timeout will
2098 ;; ;; cause a timeout here.
2099 ;; do (when (and (not (serve-event timeout)) timeout)
2100 ;; (signal-timeout 'io-timeout
2101 ;; :stream fd-stream
2102 ;; :direction :write
2103 ;; :seconds timeout)))))
2105 (defun finish-fd-stream-output (stream)
2106 (flush-output-buffer stream)
2108 ((null (fd-stream-output-queue stream)))
2109 (serve-all-events)))
2111 (defun fd-stream-get-file-position (stream)
2112 (declare (fd-stream stream))
2114 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2115 (declare (type (or (alien sb!unix:off-t) null) posn))
2116 ;; We used to return NIL for errno==ESPIPE, and signal an error
2117 ;; in other failure cases. However, CLHS says to return NIL if
2118 ;; the position cannot be determined -- so that's what we do.
2119 (when (integerp posn)
2120 ;; Adjust for buffered output: If there is any output
2121 ;; buffered, the *real* file position will be larger
2122 ;; than reported by lseek() because lseek() obviously
2123 ;; cannot take into account output we have not sent
2125 (dolist (buffer (fd-stream-output-queue stream))
2126 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2127 (let ((obuf (fd-stream-obuf stream)))
2129 (incf posn (buffer-tail obuf))))
2130 ;; Adjust for unread input: If there is any input
2131 ;; read from UNIX but not supplied to the user of the
2132 ;; stream, the *real* file position will smaller than
2133 ;; reported, because we want to look like the unread
2134 ;; stuff is still available.
2135 (let ((ibuf (fd-stream-ibuf stream)))
2137 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2138 (when (fd-stream-unread stream)
2140 ;; Divide bytes by element size.
2141 (truncate posn (fd-stream-element-size stream))))))
2143 (defun fd-stream-set-file-position (stream position-spec)
2144 (declare (fd-stream stream))
2145 (check-type position-spec
2146 (or (alien sb!unix:off-t) (member nil :start :end))
2147 "valid file position designator")
2150 ;; Make sure we don't have any output pending, because if we
2151 ;; move the file pointer before writing this stuff, it will be
2152 ;; written in the wrong location.
2153 (finish-fd-stream-output stream)
2154 ;; Disable interrupts so that interrupt handlers doing output
2157 (unless (fd-stream-output-finished-p stream)
2158 ;; We got interrupted and more output came our way during
2159 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2160 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2161 ;; so we prefer to do things like this...
2163 ;; Clear out any pending input to force the next read to go to
2165 (flush-input-buffer stream)
2166 ;; Trash cached value for listen, so that we check next time.
2167 (setf (fd-stream-listen stream) nil)
2169 (multiple-value-bind (offset origin)
2172 (values 0 sb!unix:l_set))
2174 (values 0 sb!unix:l_xtnd))
2176 (values (* position-spec (fd-stream-element-size stream))
2178 (declare (type (alien sb!unix:off-t) offset))
2179 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2181 ;; CLHS says to return true if the file-position was set
2182 ;; succesfully, and NIL otherwise. We are to signal an error
2183 ;; only if the given position was out of bounds, and that is
2184 ;; dealt with above. In times past we used to return NIL for
2185 ;; errno==ESPIPE, and signal an error in other cases.
2187 ;; FIXME: We are still liable to signal an error if flushing
2189 (return-from fd-stream-set-file-position
2190 (typep posn '(alien sb!unix:off-t))))))))
2193 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2195 ;;; Create a stream for the given Unix file descriptor.
2197 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2198 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2199 ;;; default to allowing input.
2201 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2203 ;;; BUFFERING indicates the kind of buffering to use.
2205 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2206 ;;; NIL (the default), then wait forever. When we time out, we signal
2209 ;;; FILE is the name of the file (will be returned by PATHNAME).
2211 ;;; NAME is used to identify the stream when printed.
2212 (defun make-fd-stream (fd
2215 (output nil output-p)
2216 (element-type 'base-char)
2218 (external-format :default)
2227 (format nil "file ~A" file)
2228 (format nil "descriptor ~W" fd)))
2230 (declare (type index fd) (type (or real null) timeout)
2231 (type (member :none :line :full) buffering))
2232 (cond ((not (or input-p output-p))
2234 ((not (or input output))
2235 (error "File descriptor must be opened either for input or output.")))
2236 (let ((stream (%make-fd-stream :fd fd
2240 :delete-original delete-original
2242 :buffering buffering
2243 :dual-channel-p dual-channel-p
2244 :external-format external-format
2245 :bivalent-p (eq element-type :default)
2246 :char-size (external-format-char-size external-format)
2249 (coerce timeout 'single-float)
2251 (set-fd-stream-routines stream element-type external-format
2252 input output input-buffer-p)
2253 (when (and auto-close (fboundp 'finalize))
2256 (sb!unix:unix-close fd)
2258 (format *terminal-io* "** closed file descriptor ~W **~%"
2263 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2264 ;;; :RENAME-AND-DELETE and :RENAME options.
2265 (defun pick-backup-name (name)
2266 (declare (type simple-string name))
2267 (concatenate 'simple-string name ".bak"))
2269 ;;; Ensure that the given arg is one of the given list of valid
2270 ;;; things. Allow the user to fix any problems.
2271 (defun ensure-one-of (item list what)
2272 (unless (member item list)
2273 (error 'simple-type-error
2275 :expected-type `(member ,@list)
2276 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2277 :format-arguments (list item what list))))
2279 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2280 ;;; access, since we don't want to trash unwritable files even if we
2281 ;;; technically can. We return true if we succeed in renaming.
2282 (defun rename-the-old-one (namestring original)
2283 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2284 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2285 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2288 (error 'simple-file-error
2289 :pathname namestring
2291 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2292 :format-arguments (list namestring original (strerror err))))))
2294 (defun open (filename
2297 (element-type 'base-char)
2298 (if-exists nil if-exists-given)
2299 (if-does-not-exist nil if-does-not-exist-given)
2300 (external-format :default)
2301 &aux ; Squelch assignment warning.
2302 (direction direction)
2303 (if-does-not-exist if-does-not-exist)
2304 (if-exists if-exists))
2306 "Return a stream which reads from or writes to FILENAME.
2308 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2309 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2310 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2311 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2312 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2313 See the manual for details."
2315 ;; Calculate useful stuff.
2316 (multiple-value-bind (input output mask)
2318 (:input (values t nil sb!unix:o_rdonly))
2319 (:output (values nil t sb!unix:o_wronly))
2320 (:io (values t t sb!unix:o_rdwr))
2321 (:probe (values t nil sb!unix:o_rdonly)))
2322 (declare (type index mask))
2323 (let* (;; PATHNAME is the pathname we associate with the stream.
2324 (pathname (merge-pathnames filename))
2325 (physical (physicalize-pathname pathname))
2326 (truename (probe-file physical))
2327 ;; NAMESTRING is the native namestring we open the file with.
2328 (namestring (cond (truename
2329 (native-namestring truename :as-file t))
2331 (and input (eq if-does-not-exist :create))
2332 (and (eq direction :io) (not if-does-not-exist-given)))
2333 (native-namestring physical :as-file t)))))
2334 ;; Process if-exists argument if we are doing any output.
2336 (unless if-exists-given
2338 (if (eq (pathname-version pathname) :newest)
2341 (ensure-one-of if-exists
2342 '(:error :new-version :rename
2343 :rename-and-delete :overwrite
2344 :append :supersede nil)
2347 ((:new-version :error nil)
2348 (setf mask (logior mask sb!unix:o_excl)))
2349 ((:rename :rename-and-delete)
2350 (setf mask (logior mask sb!unix:o_creat)))
2352 (setf mask (logior mask sb!unix:o_trunc)))
2354 (setf mask (logior mask sb!unix:o_append)))))
2356 (setf if-exists :ignore-this-arg)))
2358 (unless if-does-not-exist-given
2359 (setf if-does-not-exist
2360 (cond ((eq direction :input) :error)
2362 (member if-exists '(:overwrite :append)))
2364 ((eq direction :probe)
2368 (ensure-one-of if-does-not-exist
2369 '(:error :create nil)
2371 (if (eq if-does-not-exist :create)
2372 (setf mask (logior mask sb!unix:o_creat)))
2374 (let ((original (case if-exists
2375 ((:rename :rename-and-delete)
2376 (pick-backup-name namestring))
2377 ((:append :overwrite)
2378 ;; KLUDGE: Provent CLOSE from deleting
2379 ;; appending streams when called with :ABORT T
2381 (delete-original (eq if-exists :rename-and-delete))
2383 (when (and original (not (eq original namestring)))
2384 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2385 ;; whether the file already exists, make sure the original
2386 ;; file is not a directory, and keep the mode.
2389 (multiple-value-bind (okay err/dev inode orig-mode)
2390 (sb!unix:unix-stat namestring)
2391 (declare (ignore inode)
2392 (type (or index null) orig-mode))
2395 (when (and output (= (logand orig-mode #o170000)
2397 (error 'simple-file-error
2400 "can't open ~S for output: is a directory"
2401 :format-arguments (list namestring)))
2402 (setf mode (logand orig-mode #o777))
2404 ((eql err/dev sb!unix:enoent)
2407 (simple-file-perror "can't find ~S"
2411 (rename-the-old-one namestring original))
2413 (setf delete-original nil)
2414 ;; In order to use :SUPERSEDE instead, we have to make
2415 ;; sure SB!UNIX:O_CREAT corresponds to
2416 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2417 ;; because of IF-EXISTS being :RENAME.
2418 (unless (eq if-does-not-exist :create)
2420 (logior (logandc2 mask sb!unix:o_creat)
2422 (setf if-exists :supersede))))
2424 ;; Now we can try the actual Unix open(2).
2425 (multiple-value-bind (fd errno)
2427 (sb!unix:unix-open namestring mask mode)
2428 (values nil sb!unix:enoent))
2429 (labels ((open-error (format-control &rest format-arguments)
2430 (error 'simple-file-error
2432 :format-control format-control
2433 :format-arguments format-arguments))
2434 (vanilla-open-error ()
2435 (simple-file-perror "error opening ~S" pathname errno)))
2438 ((:input :output :io)
2442 :element-type element-type
2443 :external-format external-format
2446 :delete-original delete-original
2453 (%make-fd-stream :name namestring
2456 :element-type element-type)))
2459 ((eql errno sb!unix:enoent)
2460 (case if-does-not-exist
2461 (:error (vanilla-open-error))
2463 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2466 ((and (eql errno sb!unix:eexist) (null if-exists))
2469 (vanilla-open-error)))))))))
2473 ;;; the stream connected to the controlling terminal, or NIL if there is none
2476 ;;; the stream connected to the standard input (file descriptor 0)
2479 ;;; the stream connected to the standard output (file descriptor 1)
2482 ;;; the stream connected to the standard error output (file descriptor 2)
2485 ;;; This is called when the cold load is first started up, and may also
2486 ;;; be called in an attempt to recover from nested errors.
2487 (defun stream-cold-init-or-reset ()
2489 (setf *terminal-io* (make-synonym-stream '*tty*))
2490 (setf *standard-output* (make-synonym-stream '*stdout*))
2491 (setf *standard-input* (make-synonym-stream '*stdin*))
2492 (setf *error-output* (make-synonym-stream '*stderr*))
2493 (setf *query-io* (make-synonym-stream '*terminal-io*))
2494 (setf *debug-io* *query-io*)
2495 (setf *trace-output* *standard-output*)
2498 (defun stream-deinit ()
2499 ;; Unbind to make sure we're not accidently dealing with it
2500 ;; before we're ready (or after we think it's been deinitialized).
2501 (with-available-buffers-lock ()
2502 (without-package-locks
2503 (makunbound '*available-buffers*))))
2505 ;;; This is called whenever a saved core is restarted.
2506 (defun stream-reinit (&optional init-buffers-p)
2507 (when init-buffers-p
2508 (with-available-buffers-lock ()
2509 (aver (not (boundp '*available-buffers*)))
2510 (setf *available-buffers* nil)))
2511 (with-output-to-string (*error-output*)
2513 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2514 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2516 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2517 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2519 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2520 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2521 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2522 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2526 :name "the terminal"
2531 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2532 (princ (get-output-stream-string *error-output*) *stderr*))
2537 ;;; the Unix way to beep
2538 (defun beep (stream)
2539 (write-char (code-char bell-char-code) stream)
2540 (finish-output stream))
2542 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2543 ;;; by the filesys stuff to get and set the file name.
2545 ;;; FIXME: misleading name, screwy interface
2546 (defun file-name (stream &optional new-name)
2547 (when (typep stream 'fd-stream)
2549 (setf (fd-stream-pathname stream) new-name)
2550 (setf (fd-stream-file stream)
2551 (native-namestring (physicalize-pathname new-name)
2555 (fd-stream-pathname stream)))))