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))
174 (instead (make-array 0 :element-type 'character :adjustable t :fill-pointer t) :type (array character (*)))
175 (ibuf nil :type (or buffer null))
176 (eof-forced-p nil :type (member t nil))
179 (obuf nil :type (or buffer null))
181 ;; output flushed, but not written due to non-blocking io?
184 ;; timeout specified for this stream as seconds or NIL if none
185 (timeout nil :type (or single-float null))
186 ;; pathname of the file this stream is opened to (returned by PATHNAME)
187 (pathname nil :type (or pathname null))
188 (external-format :default)
189 ;; fixed width, or function to call with a character
190 (char-size 1 :type (or fixnum function))
191 (output-bytes #'ill-out :type function)
192 ;; a boolean indicating whether the stream is bivalent. For
193 ;; internal use only.
194 (bivalent-p nil :type boolean))
195 (def!method print-object ((fd-stream fd-stream) stream)
196 (declare (type stream stream))
197 (print-unreadable-object (fd-stream stream :type t :identity t)
198 (format stream "for ~S" (fd-stream-name fd-stream))))
200 ;;;; CORE OUTPUT FUNCTIONS
202 ;;; Buffer the section of THING delimited by START and END by copying
203 ;;; to output buffer(s) of stream.
204 (defun buffer-output (stream thing start end)
205 (declare (index start end))
207 (error ":END before :START!"))
209 ;; Copy bytes from THING to buffers.
210 (flet ((copy-to-buffer (buffer tail count)
211 (declare (buffer buffer) (index tail count))
213 (let ((sap (buffer-sap buffer)))
216 (system-area-ub8-copy thing start sap tail count))
217 ((simple-unboxed-array (*))
218 (copy-ub8-to-system-area thing start sap tail count))))
219 ;; Not INCF! If another thread has moved tail from under
220 ;; us, we don't want to accidentally increment tail
221 ;; beyond buffer-length.
222 (setf (buffer-tail buffer) (+ count tail))
225 ;; First copy is special: the buffer may already contain
226 ;; something, or be even full.
227 (let* ((obuf (fd-stream-obuf stream))
228 (tail (buffer-tail obuf))
229 (space (- (buffer-length obuf) tail)))
231 (copy-to-buffer obuf tail (min space (- end start)))
232 (go :more-output-p)))
234 ;; Later copies should always have an empty buffer, since
235 ;; they are freshly flushed, but if another thread is
236 ;; stomping on the same buffer that might not be the case.
237 (let* ((obuf (flush-output-buffer stream))
238 (tail (buffer-tail obuf))
239 (space (- (buffer-length obuf) tail)))
240 (copy-to-buffer obuf tail (min space (- end start))))
243 (go :flush-and-fill))))))
245 ;;; Flush the current output buffer of the stream, ensuring that the
246 ;;; new buffer is empty. Returns (for convenience) the new output
247 ;;; buffer -- which may or may not be EQ to the old one. If the is no
248 ;;; queued output we try to write the buffer immediately -- otherwise
249 ;;; we queue it for later.
250 (defun flush-output-buffer (stream)
251 (let ((obuf (fd-stream-obuf stream)))
253 (let ((head (buffer-head obuf))
254 (tail (buffer-tail obuf)))
255 (cond ((eql head tail)
256 ;; Buffer is already empty -- just ensure that is is
257 ;; set to zero as well.
259 ((fd-stream-output-queue stream)
260 ;; There is already stuff on the queue -- go directly
263 (%queue-and-replace-output-buffer stream))
265 ;; Try a non-blocking write, queue whatever is left over.
267 (synchronize-stream-output stream)
268 (let ((length (- tail head)))
269 (multiple-value-bind (count errno)
270 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
272 (cond ((eql count length)
273 ;; Complete write -- we can use the same buffer.
276 ;; Partial write -- update buffer status and queue.
277 ;; Do not use INCF! Another thread might have moved
279 (setf (buffer-head obuf) (+ count head))
280 (%queue-and-replace-output-buffer stream))
282 ((eql errno sb!unix:ewouldblock)
284 (%queue-and-replace-output-buffer stream))
286 (simple-stream-perror "Couldn't write to ~s"
287 stream errno)))))))))))
289 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
290 (defun %queue-and-replace-output-buffer (stream)
291 (let ((queue (fd-stream-output-queue stream))
292 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
294 ;; Important: before putting the buffer on queue, give the stream
295 ;; a new one. If we get an interrupt and unwind losing the buffer
296 ;; is relatively OK, but having the same buffer in two places
298 (setf (fd-stream-obuf stream) new)
302 (setf (fd-stream-output-queue stream) later)))
303 (unless (fd-stream-handler stream)
304 (setf (fd-stream-handler stream)
305 (add-fd-handler (fd-stream-fd stream)
308 (declare (ignore fd))
309 (write-output-from-queue stream)))))
312 ;;; This is called by the FD-HANDLER for the stream when output is
314 (defun write-output-from-queue (stream)
315 (synchronize-stream-output stream)
319 (let* ((buffer (pop (fd-stream-output-queue stream)))
320 (head (buffer-head buffer))
321 (length (- (buffer-tail buffer) head)))
322 (declare (index head length))
324 (multiple-value-bind (count errno)
325 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
327 (cond ((eql count length)
328 ;; Complete write, see if we can do another right
329 ;; away, or remove the handler if we're done.
330 (release-buffer buffer)
331 (cond ((fd-stream-output-queue stream)
335 (let ((handler (fd-stream-handler stream)))
337 (setf (fd-stream-handler stream) nil)
338 (remove-fd-handler handler)))))
340 ;; Partial write. Update buffer status and requeue.
341 (aver (< count length))
342 ;; Do not use INCF! Another thread might have moved head.
343 (setf (buffer-head buffer) (+ head count))
344 (push buffer (fd-stream-output-queue stream)))
346 ;; We tried to do multiple writes, and finally our
347 ;; luck ran out. Requeue.
348 (push buffer (fd-stream-output-queue stream)))
350 ;; Could not write on the first try at all!
352 (simple-stream-perror "Couldn't write to ~S." stream errno)
354 (if (= errno sb!unix:ewouldblock)
355 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
356 (simple-stream-perror "Couldn't write to ~S"
360 ;;; Try to write THING directly to STREAM without buffering, if
361 ;;; possible. If direct write doesn't happen, buffer.
362 (defun write-or-buffer-output (stream thing start end)
363 (declare (index start end))
364 (cond ((fd-stream-output-queue stream)
365 (buffer-output stream thing start end))
367 (error ":END before :START!"))
369 (let ((length (- end start)))
370 (synchronize-stream-output stream)
371 (multiple-value-bind (count errno)
372 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
373 (cond ((eql count length)
374 ;; Complete write -- done!
377 (aver (< count length))
378 ;; Partial write -- buffer the rest.
379 (buffer-output stream thing (+ start count) end))
381 ;; Could not write -- buffer or error.
383 (simple-stream-perror "couldn't write to ~s" stream errno)
385 (if (= errno sb!unix:ewouldblock)
386 (buffer-output stream thing start end)
387 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
389 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
390 ;;; this is not something we want to export. Nikodemus thinks the
391 ;;; right thing is to support a low-level non-stream like IO layer,
392 ;;; akin to java.nio.
393 (defun output-raw-bytes (stream thing &optional start end)
394 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
396 (define-compiler-macro output-raw-bytes (stream thing &optional start end)
397 (deprecation-warning 'output-raw-bytes)
398 (let ((x (gensym "THING")))
400 (write-or-buffer-output ,stream ,x (or ,start 0) (or ,end (length ,x))))))
402 ;;;; output routines and related noise
404 (defvar *output-routines* ()
406 "List of all available output routines. Each element is a list of the
407 element-type output, the kind of buffering, the function name, and the number
408 of bytes per element.")
410 ;;; common idioms for reporting low-level stream and file problems
411 (defun simple-stream-perror (note-format stream errno)
412 (error 'simple-stream-error
414 :format-control "~@<~?: ~2I~_~A~:>"
415 :format-arguments (list note-format (list stream) (strerror errno))))
416 (defun simple-file-perror (note-format pathname errno)
417 (error 'simple-file-error
419 :format-control "~@<~?: ~2I~_~A~:>"
421 (list note-format (list pathname) (strerror errno))))
423 (defun stream-decoding-error (stream octets)
424 (error 'stream-decoding-error
425 :external-format (stream-external-format stream)
427 ;; FIXME: dunno how to get at OCTETS currently, or even if
428 ;; that's the right thing to report.
430 (defun stream-encoding-error (stream code)
431 (error 'stream-encoding-error
432 :external-format (stream-external-format stream)
436 (defun c-string-encoding-error (external-format code)
437 (error 'c-string-encoding-error
438 :external-format external-format
441 (defun c-string-decoding-error (external-format octets)
442 (error 'c-string-decoding-error
443 :external-format external-format
446 ;;; Returning true goes into end of file handling, false will enter another
447 ;;; round of input buffer filling followed by re-entering character decode.
448 (defun stream-decoding-error-and-handle (stream octet-count)
450 (stream-decoding-error stream
451 (let* ((buffer (fd-stream-ibuf stream))
452 (sap (buffer-sap buffer))
453 (head (buffer-head buffer)))
454 (loop for i from 0 below octet-count
455 collect (sap-ref-8 sap (+ head i)))))
457 :report (lambda (stream)
459 "~@<Attempt to resync the stream at a ~
460 character boundary and continue.~@:>"))
461 (fd-stream-resync stream)
463 (force-end-of-file ()
464 :report (lambda (stream)
465 (format stream "~@<Force an end of file.~@:>"))
466 (setf (fd-stream-eof-forced-p stream) t))
467 (input-replacement (string)
468 :report (lambda (stream)
469 (format stream "~@<Use string as replacement input, ~
470 attempt to resync at a character ~
471 boundary and continue.~@:>"))
472 :interactive (lambda ()
473 (format *query-io* "~@<Enter a string: ~@:>")
474 (finish-output *query-io*)
475 (list (read *query-io*)))
476 (let ((string (reverse (string string)))
477 (instead (fd-stream-instead stream)))
478 (dotimes (i (length string))
479 (vector-push-extend (char string i) instead))
480 (fd-stream-resync stream)
481 (when (> (length string) 0)
482 (setf (fd-stream-listen stream) t)))
485 (defun stream-encoding-error-and-handle (stream code)
487 (stream-encoding-error stream code)
489 :report (lambda (stream)
490 (format stream "~@<Skip output of this character.~@:>"))
491 (throw 'output-nothing nil))
492 (output-replacement (string)
493 :report (lambda (stream)
494 (format stream "~@<Output replacement string.~@:>"))
495 :interactive (lambda ()
496 (format *query-io* "~@<Enter a string: ~@:>")
497 (finish-output *query-io*)
498 (list (read *query-io*)))
499 (let ((string (string string)))
500 (fd-sout stream (string string) 0 (length string)))
501 (throw 'output-nothing nil))))
503 (defun external-format-encoding-error (stream code)
505 (stream-encoding-error-and-handle stream code)
506 (c-string-encoding-error stream code)))
508 (defun external-format-decoding-error (stream octet-count)
510 (stream-decoding-error stream octet-count)
511 (c-string-decoding-error stream octet-count)))
513 (defun synchronize-stream-output (stream)
514 ;; If we're reading and writing on the same file, flush buffered
515 ;; input and rewind file position accordingly.
516 (unless (fd-stream-dual-channel-p stream)
517 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
518 (unless (eql 0 adjust)
519 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
521 (defun fd-stream-output-finished-p (stream)
522 (let ((obuf (fd-stream-obuf stream)))
524 (and (zerop (buffer-tail obuf))
525 (not (fd-stream-output-queue stream))))))
527 (defmacro output-wrapper/variable-width ((stream size buffering restart)
529 (let ((stream-var (gensym "STREAM")))
530 `(let* ((,stream-var ,stream)
531 (obuf (fd-stream-obuf ,stream-var))
532 (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 ,(unless (eq (car buffering) :none)
539 ;; FIXME: Why this here? Doesn't seem necessary.
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 output-wrapper ((stream size buffering restart) &body body)
558 (let ((stream-var (gensym "STREAM")))
559 `(let* ((,stream-var ,stream)
560 (obuf (fd-stream-obuf ,stream-var))
561 (tail (buffer-tail obuf)))
562 ,(unless (eq (car buffering) :none)
563 `(when (<= (buffer-length obuf) (+ tail ,size))
564 (setf obuf (flush-output-buffer ,stream-var)
565 tail (buffer-tail obuf))))
566 ;; FIXME: Why this here? Doesn't seem necessary.
567 ,(unless (eq (car buffering) :none)
568 `(synchronize-stream-output ,stream-var))
570 `(catch 'output-nothing
572 (setf (buffer-tail obuf) (+ tail ,size)))
575 (setf (buffer-tail obuf) (+ tail ,size))))
576 ,(ecase (car buffering)
578 `(flush-output-buffer ,stream-var))
580 `(when (eql byte #\Newline)
581 (flush-output-buffer ,stream-var)))
585 (defmacro def-output-routines/variable-width
586 ((name-fmt size restart external-format &rest bufferings)
588 (declare (optimize (speed 1)))
593 (intern (format nil name-fmt (string (car buffering))))))
595 (defun ,function (stream byte)
596 (declare (ignorable byte))
597 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
599 (setf *output-routines*
600 (nconc *output-routines*
608 (cdr buffering)))))))
611 ;;; Define output routines that output numbers SIZE bytes long for the
612 ;;; given bufferings. Use BODY to do the actual output.
613 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
615 (declare (optimize (speed 1)))
620 (intern (format nil name-fmt (string (car buffering))))))
622 (defun ,function (stream byte)
623 (output-wrapper (stream ,size ,buffering ,restart)
625 (setf *output-routines*
626 (nconc *output-routines*
634 (cdr buffering)))))))
637 ;;; FIXME: is this used anywhere any more?
638 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
644 (if (eql byte #\Newline)
645 (setf (fd-stream-char-pos stream) 0)
646 (incf (fd-stream-char-pos stream)))
647 (setf (sap-ref-8 (buffer-sap obuf) tail)
650 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
653 (:none (unsigned-byte 8))
654 (:full (unsigned-byte 8)))
655 (setf (sap-ref-8 (buffer-sap obuf) tail)
658 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
661 (:none (signed-byte 8))
662 (:full (signed-byte 8)))
663 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
666 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
669 (:none (unsigned-byte 16))
670 (:full (unsigned-byte 16)))
671 (setf (sap-ref-16 (buffer-sap obuf) tail)
674 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
677 (:none (signed-byte 16))
678 (:full (signed-byte 16)))
679 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
682 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
685 (:none (unsigned-byte 32))
686 (:full (unsigned-byte 32)))
687 (setf (sap-ref-32 (buffer-sap obuf) tail)
690 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
693 (:none (signed-byte 32))
694 (:full (signed-byte 32)))
695 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
698 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
700 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
703 (:none (unsigned-byte 64))
704 (:full (unsigned-byte 64)))
705 (setf (sap-ref-64 (buffer-sap obuf) tail)
707 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
710 (:none (signed-byte 64))
711 (:full (signed-byte 64)))
712 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
715 ;;; the routine to use to output a string. If the stream is
716 ;;; unbuffered, slam the string down the file descriptor, otherwise
717 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
718 ;;; checking to see where the last newline was.
719 (defun fd-sout (stream thing start end)
720 (declare (type fd-stream stream) (type string thing))
721 (let ((start (or start 0))
722 (end (or end (length (the vector thing)))))
723 (declare (fixnum start end))
725 (string-dispatch (simple-base-string
727 (simple-array character (*))
730 (position #\newline thing :from-end t
731 :start start :end end))))
732 (if (and (typep thing 'base-string)
733 (eq (fd-stream-external-format stream) :latin-1))
734 (ecase (fd-stream-buffering stream)
736 (buffer-output stream thing start end))
738 (buffer-output stream thing start end)
740 (flush-output-buffer stream)))
742 (write-or-buffer-output stream thing start end)))
743 (ecase (fd-stream-buffering stream)
744 (:full (funcall (fd-stream-output-bytes stream)
745 stream thing nil start end))
746 (:line (funcall (fd-stream-output-bytes stream)
747 stream thing last-newline start end))
748 (:none (funcall (fd-stream-output-bytes stream)
749 stream thing t start end))))
751 (setf (fd-stream-char-pos stream) (- end last-newline 1))
752 (incf (fd-stream-char-pos stream) (- end start))))))
754 (defstruct (external-format
755 (:constructor %make-external-format)
757 (:predicate external-format-p)
759 ;; All the names that can refer to this external format. The first
760 ;; one is the canonical name.
761 (names (missing-arg) :type list :read-only t)
762 (read-n-chars-fun (missing-arg) :type function :read-only t)
763 (read-char-fun (missing-arg) :type function :read-only t)
764 (write-n-bytes-fun (missing-arg) :type function :read-only t)
765 (write-char-none-buffered-fun (missing-arg) :type function :read-only t)
766 (write-char-line-buffered-fun (missing-arg) :type function :read-only t)
767 (write-char-full-buffered-fun (missing-arg) :type function :read-only t)
768 ;; Can be nil for fixed-width formats.
769 (resync-fun nil :type (or function null) :read-only t)
770 (bytes-for-char-fun (missing-arg) :type function :read-only t)
771 (read-c-string-fun (missing-arg) :type function :read-only t)
772 (write-c-string-fun (missing-arg) :type function :read-only t)
773 ;; We make these symbols so that a developer working on the octets
774 ;; code can easily redefine things and use the new function definition
775 ;; without redefining the external format as well. The slots above
776 ;; are functions because a developer working with those slots would be
777 ;; redefining the external format anyway.
778 (octets-to-string-sym (missing-arg) :type symbol :read-only t)
779 (string-to-octets-sym (missing-arg) :type symbol :read-only t))
781 (defvar *external-formats* (make-hash-table)
783 "Hashtable of all available external formats. The table maps from
784 external-format names to EXTERNAL-FORMAT structures.")
786 (defun get-external-format (external-format)
787 (gethash external-format *external-formats*))
789 (defun get-external-format-or-lose (external-format)
790 (or (get-external-format external-format)
791 (error "Undefined external-format ~A" external-format)))
793 ;;; Find an output routine to use given the type and buffering. Return
794 ;;; as multiple values the routine, the real type transfered, and the
795 ;;; number of bytes per element.
796 (defun pick-output-routine (type buffering &optional external-format)
797 (when (subtypep type 'character)
798 (let ((entry (get-external-format external-format)))
800 (return-from pick-output-routine
801 (values (ecase buffering
802 (:none (ef-write-char-none-buffered-fun entry))
803 (:line (ef-write-char-line-buffered-fun entry))
804 (:full (ef-write-char-full-buffered-fun entry)))
807 (ef-write-n-bytes-fun entry)
808 (first (ef-names entry)))))))
809 (dolist (entry *output-routines*)
810 (when (and (subtypep type (first entry))
811 (eq buffering (second entry))
812 (or (not (fifth entry))
813 (eq external-format (fifth entry))))
814 (return-from pick-output-routine
815 (values (symbol-function (third entry))
818 ;; KLUDGE: dealing with the buffering here leads to excessive code
821 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
822 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
823 if (subtypep type `(unsigned-byte ,i))
824 do (return-from pick-output-routine
828 (lambda (stream byte)
829 (output-wrapper (stream (/ i 8) (:none) 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))))))
835 (lambda (stream byte)
836 (output-wrapper (stream (/ i 8) (:full) nil)
837 (loop for j from 0 below (/ i 8)
838 do (setf (sap-ref-8 (buffer-sap obuf)
840 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
843 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
844 if (subtypep type `(signed-byte ,i))
845 do (return-from pick-output-routine
849 (lambda (stream byte)
850 (output-wrapper (stream (/ i 8) (:none) nil)
851 (loop for j from 0 below (/ i 8)
852 do (setf (sap-ref-8 (buffer-sap obuf)
854 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
856 (lambda (stream byte)
857 (output-wrapper (stream (/ i 8) (:full) nil)
858 (loop for j from 0 below (/ i 8)
859 do (setf (sap-ref-8 (buffer-sap obuf)
861 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
865 ;;;; input routines and related noise
867 ;;; a list of all available input routines. Each element is a list of
868 ;;; the element-type input, the function name, and the number of bytes
870 (defvar *input-routines* ())
872 ;;; Return whether a primitive partial read operation on STREAM's FD
873 ;;; would (probably) block. Signal a `simple-stream-error' if the
874 ;;; system call implementing this operation fails.
876 ;;; It is "may" instead of "would" because "would" is not quite
877 ;;; correct on win32. However, none of the places that use it require
878 ;;; further assurance than "may" versus "will definitely not".
879 (defun sysread-may-block-p (stream)
881 ;; This answers T at EOF on win32, I think.
882 (not (sb!win32:fd-listen (fd-stream-fd stream)))
884 (sb!unix:with-restarted-syscall (count errno)
885 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
886 (sb!unix:fd-zero read-fds)
887 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
888 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
889 (sb!alien:addr read-fds)
895 (simple-stream-perror "couldn't check whether ~S is readable"
899 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
900 ;;; then fill the input buffer, and return the number of bytes read. Throws
901 ;;; to EOF-INPUT-CATCHER if the eof was reached.
902 (defun refill-input-buffer (stream)
903 (dx-let ((fd (fd-stream-fd stream))
907 ;; Check for blocking input before touching the stream, as if
908 ;; we happen to wait we are liable to be interrupted, and the
909 ;; interrupt handler may use the same stream.
910 (if (sysread-may-block-p stream)
913 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
914 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
916 (closed-flame stream)
918 (simple-stream-perror "couldn't read from ~S" stream errno)
920 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
921 ;; to wait for input if read tells us EWOULDBLOCK.
922 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
923 (signal-timeout 'io-timeout :stream stream :direction :read
924 :seconds (fd-stream-timeout stream)))
926 ;; Since the read should not block, we'll disable the
927 ;; interrupts here, so that we don't accidentally unwind and
928 ;; leave the stream in an inconsistent state.
930 ;; Execute the nlx outside without-interrupts to ensure the
931 ;; resulting thunk is stack-allocatable.
932 ((lambda (return-reason)
934 ((nil)) ; fast path normal cases
935 ((:wait-for-input) (go :wait-for-input))
936 ((:closed-flame) (go :closed-flame))
937 ((:read-error) (go :read-error))))
939 ;; Check the buffer: if it is null, then someone has closed
940 ;; the stream from underneath us. This is not ment to fix
941 ;; multithreaded races, but to deal with interrupt handlers
942 ;; closing the stream.
945 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
946 (sap (buffer-sap ibuf))
947 (length (buffer-length ibuf))
948 (head (buffer-head ibuf))
949 (tail (buffer-tail ibuf)))
950 (declare (index length head tail)
951 (inline sb!unix:unix-read))
953 (cond ((eql head tail)
954 ;; Buffer is empty, but not at yet reset -- make it so.
959 ;; Buffer has things in it, but they are not at the
960 ;; head -- move them there.
961 (let ((n (- tail head)))
962 (system-area-ub8-copy sap head sap 0 n)
964 (buffer-head ibuf) head
966 (buffer-tail ibuf) tail)))))
967 (setf (fd-stream-listen stream) nil)
968 (setf (values count errno)
969 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
974 (if (eql errno sb!unix:ewouldblock)
975 (return :wait-for-input)
976 (return :read-error)))
978 (setf (fd-stream-listen stream) :eof)
979 (/show0 "THROWing EOF-INPUT-CATCHER")
980 (throw 'eof-input-catcher nil))
982 ;; Success! (Do not use INCF, for sake of other threads.)
983 (setf (buffer-tail ibuf) (+ count tail))))))))))
986 ;;; Make sure there are at least BYTES number of bytes in the input
987 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
988 (defmacro input-at-least (stream bytes)
989 (let ((stream-var (gensym "STREAM"))
990 (bytes-var (gensym "BYTES"))
991 (buffer-var (gensym "IBUF")))
992 `(let* ((,stream-var ,stream)
994 (,buffer-var (fd-stream-ibuf ,stream-var)))
996 (when (>= (- (buffer-tail ,buffer-var)
997 (buffer-head ,buffer-var))
1000 (refill-input-buffer ,stream-var)))))
1002 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1004 (let ((stream-var (gensym "STREAM"))
1005 (retry-var (gensym "RETRY"))
1006 (element-var (gensym "ELT")))
1007 `(let* ((,stream-var ,stream)
1008 (ibuf (fd-stream-ibuf ,stream-var))
1011 (when (fd-stream-eof-forced-p ,stream-var)
1012 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1013 (return-from use-instead
1014 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1015 (let ((,element-var nil)
1016 (decode-break-reason nil))
1017 (do ((,retry-var t))
1019 (if (> (length (fd-stream-instead ,stream-var)) 0)
1020 (let* ((instead (fd-stream-instead ,stream-var))
1021 (result (vector-pop instead))
1022 (pointer (fill-pointer instead)))
1024 (setf (fd-stream-listen ,stream-var) nil))
1025 (return-from use-instead result))
1027 (catch 'eof-input-catcher
1028 (setf decode-break-reason
1029 (block decode-break-reason
1030 (input-at-least ,stream-var 1)
1031 (let* ((byte (sap-ref-8 (buffer-sap ibuf)
1032 (buffer-head ibuf))))
1033 (declare (ignorable byte))
1035 (input-at-least ,stream-var size)
1036 (setq ,element-var (locally ,@read-forms))
1037 (setq ,retry-var nil))
1039 (when decode-break-reason
1040 (when (stream-decoding-error-and-handle
1041 stream decode-break-reason)
1042 (setq ,retry-var nil)
1043 (throw 'eof-input-catcher nil)))
1045 (let ((octet-count (- (buffer-tail ibuf)
1046 (buffer-head ibuf))))
1047 (when (or (zerop octet-count)
1048 (and (not ,element-var)
1049 (not decode-break-reason)
1050 (stream-decoding-error-and-handle
1051 stream octet-count)))
1052 (setq ,retry-var nil))))))
1054 (incf (buffer-head ibuf) size)
1057 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1059 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1060 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1061 (let ((stream-var (gensym "STREAM"))
1062 (element-var (gensym "ELT")))
1063 `(let* ((,stream-var ,stream)
1064 (ibuf (fd-stream-ibuf ,stream-var)))
1065 (if (> (length (fd-stream-instead ,stream-var)) 0)
1066 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1068 (catch 'eof-input-catcher
1069 (input-at-least ,stream-var ,bytes)
1070 (locally ,@read-forms))))
1072 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1075 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1077 (defmacro def-input-routine/variable-width (name
1078 (type external-format size sap head)
1081 (defun ,name (stream eof-error eof-value)
1082 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1083 (let ((,sap (buffer-sap ibuf))
1084 (,head (buffer-head ibuf)))
1086 (setf *input-routines*
1087 (nconc *input-routines*
1088 (list (list ',type ',name 1 ',external-format))))))
1090 (defmacro def-input-routine (name
1091 (type size sap head)
1094 (defun ,name (stream eof-error eof-value)
1095 (input-wrapper (stream ,size eof-error eof-value)
1096 (let ((,sap (buffer-sap ibuf))
1097 (,head (buffer-head ibuf)))
1099 (setf *input-routines*
1100 (nconc *input-routines*
1101 (list (list ',type ',name ',size nil))))))
1103 ;;; STREAM-IN routine for reading a string char
1104 (def-input-routine input-character
1105 (character 1 sap head)
1106 (code-char (sap-ref-8 sap head)))
1108 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1109 (def-input-routine input-unsigned-8bit-byte
1110 ((unsigned-byte 8) 1 sap head)
1111 (sap-ref-8 sap head))
1113 ;;; STREAM-IN routine for reading a signed 8 bit number
1114 (def-input-routine input-signed-8bit-number
1115 ((signed-byte 8) 1 sap head)
1116 (signed-sap-ref-8 sap head))
1118 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1119 (def-input-routine input-unsigned-16bit-byte
1120 ((unsigned-byte 16) 2 sap head)
1121 (sap-ref-16 sap head))
1123 ;;; STREAM-IN routine for reading a signed 16 bit number
1124 (def-input-routine input-signed-16bit-byte
1125 ((signed-byte 16) 2 sap head)
1126 (signed-sap-ref-16 sap head))
1128 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1129 (def-input-routine input-unsigned-32bit-byte
1130 ((unsigned-byte 32) 4 sap head)
1131 (sap-ref-32 sap head))
1133 ;;; STREAM-IN routine for reading a signed 32 bit number
1134 (def-input-routine input-signed-32bit-byte
1135 ((signed-byte 32) 4 sap head)
1136 (signed-sap-ref-32 sap head))
1138 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1140 (def-input-routine input-unsigned-64bit-byte
1141 ((unsigned-byte 64) 8 sap head)
1142 (sap-ref-64 sap head))
1143 (def-input-routine input-signed-64bit-byte
1144 ((signed-byte 64) 8 sap head)
1145 (signed-sap-ref-64 sap head)))
1147 ;;; Find an input routine to use given the type. Return as multiple
1148 ;;; values the routine, the real type transfered, and the number of
1149 ;;; bytes per element (and for character types string input routine).
1150 (defun pick-input-routine (type &optional external-format)
1151 (when (subtypep type 'character)
1152 (let ((entry (get-external-format external-format)))
1154 (return-from pick-input-routine
1155 (values (ef-read-char-fun entry)
1158 (ef-read-n-chars-fun entry)
1159 (first (ef-names entry)))))))
1160 (dolist (entry *input-routines*)
1161 (when (and (subtypep type (first entry))
1162 (or (not (fourth entry))
1163 (eq external-format (fourth entry))))
1164 (return-from pick-input-routine
1165 (values (symbol-function (second entry))
1168 ;; FIXME: let's do it the hard way, then (but ignore things like
1169 ;; endianness, efficiency, and the necessary coupling between these
1170 ;; and the output routines). -- CSR, 2004-02-09
1171 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1172 if (subtypep type `(unsigned-byte ,i))
1173 do (return-from pick-input-routine
1175 (lambda (stream eof-error eof-value)
1176 (input-wrapper (stream (/ i 8) eof-error eof-value)
1177 (let ((sap (buffer-sap ibuf))
1178 (head (buffer-head ibuf)))
1179 (loop for j from 0 below (/ i 8)
1183 (sap-ref-8 sap (+ head j))))
1184 finally (return result)))))
1187 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1188 if (subtypep type `(signed-byte ,i))
1189 do (return-from pick-input-routine
1191 (lambda (stream eof-error eof-value)
1192 (input-wrapper (stream (/ i 8) eof-error eof-value)
1193 (let ((sap (buffer-sap ibuf))
1194 (head (buffer-head ibuf)))
1195 (loop for j from 0 below (/ i 8)
1199 (sap-ref-8 sap (+ head j))))
1200 finally (return (if (logbitp (1- i) result)
1201 (dpb result (byte i 0) -1)
1206 ;;; the N-BIN method for FD-STREAMs
1208 ;;; Note that this blocks in UNIX-READ. It is generally used where
1209 ;;; there is a definite amount of reading to be done, so blocking
1210 ;;; isn't too problematical.
1211 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1212 &aux (total-copied 0))
1213 (declare (type fd-stream stream))
1214 (declare (type index start requested total-copied))
1215 (aver (= (length (fd-stream-instead stream)) 0))
1218 (let* ((remaining-request (- requested total-copied))
1219 (ibuf (fd-stream-ibuf stream))
1220 (head (buffer-head ibuf))
1221 (tail (buffer-tail ibuf))
1222 (available (- tail head))
1223 (n-this-copy (min remaining-request available))
1224 (this-start (+ start total-copied))
1225 (this-end (+ this-start n-this-copy))
1226 (sap (buffer-sap ibuf)))
1227 (declare (type index remaining-request head tail available))
1228 (declare (type index n-this-copy))
1229 ;; Copy data from stream buffer into user's buffer.
1230 (%byte-blt sap head buffer this-start this-end)
1231 (incf (buffer-head ibuf) n-this-copy)
1232 (incf total-copied n-this-copy)
1233 ;; Maybe we need to refill the stream buffer.
1234 (cond (;; If there were enough data in the stream buffer, we're done.
1235 (eql total-copied requested)
1236 (return total-copied))
1237 (;; If EOF, we're done in another way.
1238 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1240 (error 'end-of-file :stream stream)
1241 (return total-copied)))
1242 ;; Otherwise we refilled the stream buffer, so fall
1243 ;; through into another pass of the loop.
1246 (defun fd-stream-resync (stream)
1247 (let ((entry (get-external-format (fd-stream-external-format stream))))
1249 (funcall (ef-resync-fun entry) stream))))
1251 (defun get-fd-stream-character-sizer (stream)
1252 (let ((entry (get-external-format (fd-stream-external-format stream))))
1254 (ef-bytes-for-char-fun entry))))
1256 (defun fd-stream-character-size (stream char)
1257 (let ((sizer (get-fd-stream-character-sizer stream)))
1258 (when sizer (funcall sizer char))))
1260 (defun fd-stream-string-size (stream string)
1261 (let ((sizer (get-fd-stream-character-sizer stream)))
1263 (loop for char across string summing (funcall sizer char)))))
1265 (defun find-external-format (external-format)
1266 (when external-format
1267 (get-external-format external-format)))
1269 (defun variable-width-external-format-p (ef-entry)
1270 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1272 (defun bytes-for-char-fun (ef-entry)
1273 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1275 (defmacro define-external-format (external-format size output-restart
1277 octets-to-string-sym
1278 string-to-octets-sym)
1279 (let* ((name (first external-format))
1280 (out-function (symbolicate "OUTPUT-BYTES/" name))
1281 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1282 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1283 (in-char-function (symbolicate "INPUT-CHAR/" name))
1284 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1285 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1286 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1287 (n-buffer (gensym "BUFFER")))
1289 (defun ,size-function (byte)
1290 (declare (ignore byte))
1292 (defun ,out-function (stream string flush-p start end)
1293 (let ((start (or start 0))
1294 (end (or end (length string))))
1295 (declare (type index start end))
1296 (synchronize-stream-output stream)
1297 (unless (<= 0 start end (length string))
1298 (sequence-bounding-indices-bad-error string start end))
1301 (let ((obuf (fd-stream-obuf stream)))
1302 (string-dispatch (simple-base-string
1304 (simple-array character (*))
1307 (let ((sap (buffer-sap obuf))
1308 (len (buffer-length obuf))
1310 (tail (buffer-tail obuf)))
1311 (declare (type index tail)
1312 ;; STRING bounds have already been checked.
1313 (optimize (safety 0)))
1314 (,@(if output-restart
1315 `(catch 'output-nothing)
1318 ((or (= start end) (< (- len tail) 4)))
1319 (let* ((byte (aref string start))
1320 (bits (char-code byte)))
1323 (setf (buffer-tail obuf) tail)
1325 ;; Exited from the loop normally
1327 ;; Exited via CATCH. Skip the current character.
1331 (flush-output-buffer stream)))
1333 (flush-output-buffer stream))))
1334 (def-output-routines (,format
1340 (if (eql byte #\Newline)
1341 (setf (fd-stream-char-pos stream) 0)
1342 (incf (fd-stream-char-pos stream)))
1343 (let* ((obuf (fd-stream-obuf stream))
1344 (bits (char-code byte))
1345 (sap (buffer-sap obuf))
1346 (tail (buffer-tail obuf)))
1348 (defun ,in-function (stream buffer start requested eof-error-p
1349 &aux (index start) (end (+ start requested)))
1350 (declare (type fd-stream stream)
1351 (type index start requested index end)
1353 (simple-array character (#.+ansi-stream-in-buffer-length+))
1355 (when (fd-stream-eof-forced-p stream)
1356 (setf (fd-stream-eof-forced-p stream) nil)
1357 (return-from ,in-function 0))
1358 (do ((instead (fd-stream-instead stream)))
1359 ((= (fill-pointer instead) 0)
1360 (setf (fd-stream-listen stream) nil))
1361 (setf (aref buffer index) (vector-pop instead))
1364 (return-from ,in-function (- index start))))
1367 (let* ((ibuf (fd-stream-ibuf stream))
1368 (head (buffer-head ibuf))
1369 (tail (buffer-tail ibuf))
1370 (sap (buffer-sap ibuf)))
1371 (declare (type index head tail)
1372 (type system-area-pointer sap))
1373 ;; Copy data from stream buffer into user's buffer.
1374 (dotimes (i (min (truncate (- tail head) ,size)
1376 (declare (optimize speed))
1377 (let* ((byte (sap-ref-8 sap head)))
1378 (setf (aref buffer index) ,in-expr)
1381 (setf (buffer-head ibuf) head)
1382 ;; Maybe we need to refill the stream buffer.
1383 (cond ( ;; If there was enough data in the stream buffer, we're done.
1385 (return (- index start)))
1386 ( ;; If EOF, we're done in another way.
1387 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1389 (error 'end-of-file :stream stream)
1390 (return (- index start))))
1391 ;; Otherwise we refilled the stream buffer, so fall
1392 ;; through into another pass of the loop.
1394 (def-input-routine ,in-char-function (character ,size sap head)
1395 (let ((byte (sap-ref-8 sap head)))
1397 (defun ,read-c-string-function (sap element-type)
1398 (declare (type system-area-pointer sap)
1399 (type (member character base-char) element-type))
1401 (declare (optimize (speed 3) (safety 0)))
1402 (let* ((stream ,name)
1404 (loop for head of-type index upfrom 0 by ,size
1405 for count of-type index upto (1- array-dimension-limit)
1406 for byte = (sap-ref-8 sap head)
1407 for char of-type character = ,in-expr
1408 until (zerop (char-code char))
1409 finally (return count)))
1410 ;; Inline the common cases
1411 (string (make-string length :element-type element-type)))
1412 (declare (ignorable stream)
1414 (type simple-string string))
1415 (/show0 before-copy-loop)
1416 (loop for head of-type index upfrom 0 by ,size
1417 for index of-type index below length
1418 for byte = (sap-ref-8 sap head)
1419 for char of-type character = ,in-expr
1420 do (setf (aref string index) char))
1421 string))) ;; last loop rewrite to dotimes?
1422 (defun ,output-c-string-function (string)
1423 (declare (type simple-string string))
1425 (declare (optimize (speed 3) (safety 0)))
1426 (let* ((length (length string))
1427 (,n-buffer (make-array (* (1+ length) ,size)
1428 :element-type '(unsigned-byte 8)))
1431 (declare (type index length tail))
1432 (with-pinned-objects (,n-buffer)
1433 (let ((sap (vector-sap ,n-buffer)))
1434 (declare (system-area-pointer sap))
1436 (let* ((byte (aref string i))
1437 (bits (char-code byte)))
1438 (declare (ignorable byte bits))
1442 (byte (code-char bits)))
1443 (declare (ignorable bits byte))
1446 (let ((entry (%make-external-format
1447 :names ',external-format
1448 :read-n-chars-fun #',in-function
1449 :read-char-fun #',in-char-function
1450 :write-n-bytes-fun #',out-function
1451 ,@(mapcan #'(lambda (buffering)
1452 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1453 `#',(intern (format nil format (string buffering)))))
1454 '(:none :line :full))
1456 :bytes-for-char-fun #',size-function
1457 :read-c-string-fun #',read-c-string-function
1458 :write-c-string-fun #',output-c-string-function
1459 :octets-to-string-sym ',octets-to-string-sym
1460 :string-to-octets-sym ',string-to-octets-sym)))
1461 (dolist (ef ',external-format)
1462 (setf (gethash ef *external-formats*) entry))))))
1464 (defmacro define-external-format/variable-width
1465 (external-format output-restart out-size-expr
1466 out-expr in-size-expr in-expr
1467 octets-to-string-sym string-to-octets-sym)
1468 (let* ((name (first external-format))
1469 (out-function (symbolicate "OUTPUT-BYTES/" name))
1470 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1471 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1472 (in-char-function (symbolicate "INPUT-CHAR/" name))
1473 (resync-function (symbolicate "RESYNC/" name))
1474 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1475 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1476 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1477 (n-buffer (gensym "BUFFER")))
1479 (defun ,size-function (byte)
1480 (declare (ignorable byte))
1482 (defun ,out-function (stream string flush-p start end)
1483 (let ((start (or start 0))
1484 (end (or end (length string))))
1485 (declare (type index start end))
1486 (synchronize-stream-output stream)
1487 (unless (<= 0 start end (length string))
1488 (sequence-bounding-indices-bad-error string start end))
1491 (let ((obuf (fd-stream-obuf stream)))
1492 (string-dispatch (simple-base-string
1493 #!+sb-unicode (simple-array character (*))
1496 (let ((len (buffer-length obuf))
1497 (sap (buffer-sap obuf))
1499 (tail (buffer-tail obuf)))
1500 (declare (type index tail)
1501 ;; STRING bounds have already been checked.
1502 (optimize (safety 0)))
1503 (,@(if output-restart
1504 `(catch 'output-nothing)
1507 ((or (= start end) (< (- len tail) 4)))
1508 (let* ((byte (aref string start))
1509 (bits (char-code byte))
1510 (size ,out-size-expr))
1513 (setf (buffer-tail obuf) tail)
1516 ;; Exited via CATCH: skip the current character.
1520 (flush-output-buffer stream)))
1522 (flush-output-buffer stream))))
1523 (def-output-routines/variable-width (,format
1530 (if (eql byte #\Newline)
1531 (setf (fd-stream-char-pos stream) 0)
1532 (incf (fd-stream-char-pos stream)))
1533 (let ((bits (char-code byte))
1534 (sap (buffer-sap obuf))
1535 (tail (buffer-tail obuf)))
1537 (defun ,in-function (stream buffer start requested eof-error-p
1538 &aux (total-copied 0))
1539 (declare (type fd-stream stream)
1540 (type index start requested total-copied)
1542 (simple-array character (#.+ansi-stream-in-buffer-length+))
1544 (when (fd-stream-eof-forced-p stream)
1545 (setf (fd-stream-eof-forced-p stream) nil)
1546 (return-from ,in-function 0))
1547 (do ((instead (fd-stream-instead stream)))
1548 ((= (fill-pointer instead) 0)
1549 (setf (fd-stream-listen stream) nil))
1550 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1552 (when (= requested total-copied)
1553 (return-from ,in-function total-copied)))
1556 (let* ((ibuf (fd-stream-ibuf stream))
1557 (head (buffer-head ibuf))
1558 (tail (buffer-tail ibuf))
1559 (sap (buffer-sap ibuf))
1560 (decode-break-reason nil))
1561 (declare (type index head tail))
1562 ;; Copy data from stream buffer into user's buffer.
1563 (do ((size nil nil))
1564 ((or (= tail head) (= requested total-copied)))
1565 (setf decode-break-reason
1566 (block decode-break-reason
1567 (let ((byte (sap-ref-8 sap head)))
1568 (declare (ignorable byte))
1569 (setq size ,in-size-expr)
1570 (when (> size (- tail head))
1572 (setf (aref buffer (+ start total-copied)) ,in-expr)
1576 (setf (buffer-head ibuf) head)
1577 (when decode-break-reason
1578 ;; If we've already read some characters on when the invalid
1579 ;; code sequence is detected, we return immediately. The
1580 ;; handling of the error is deferred until the next call
1581 ;; (where this check will be false). This allows establishing
1582 ;; high-level handlers for decode errors (for example
1583 ;; automatically resyncing in Lisp comments).
1584 (when (plusp total-copied)
1585 (return-from ,in-function total-copied))
1586 (when (stream-decoding-error-and-handle
1587 stream decode-break-reason)
1589 (error 'end-of-file :stream stream)
1590 (return-from ,in-function total-copied)))
1591 ;; we might have been given stuff to use instead, so
1592 ;; we have to return (and trust our caller to know
1593 ;; what to do about TOTAL-COPIED being 0).
1594 (return-from ,in-function total-copied)))
1595 (setf (buffer-head ibuf) head)
1596 ;; Maybe we need to refill the stream buffer.
1597 (cond ( ;; If there were enough data in the stream buffer, we're done.
1598 (= total-copied requested)
1599 (return total-copied))
1600 ( ;; If EOF, we're done in another way.
1601 (or (eq decode-break-reason 'eof)
1602 (null (catch 'eof-input-catcher
1603 (refill-input-buffer stream))))
1605 (error 'end-of-file :stream stream)
1606 (return total-copied)))
1607 ;; Otherwise we refilled the stream buffer, so fall
1608 ;; through into another pass of the loop.
1610 (def-input-routine/variable-width ,in-char-function (character
1614 (let ((byte (sap-ref-8 sap head)))
1615 (declare (ignorable byte))
1617 (defun ,resync-function (stream)
1618 (let ((ibuf (fd-stream-ibuf stream)))
1619 (catch 'eof-input-catcher
1621 (incf (buffer-head ibuf))
1622 (input-at-least stream 1)
1623 (unless (block decode-break-reason
1624 (let* ((sap (buffer-sap ibuf))
1625 (head (buffer-head ibuf))
1626 (byte (sap-ref-8 sap head))
1627 (size ,in-size-expr))
1628 (declare (ignorable byte))
1629 (input-at-least stream size)
1630 (setf head (buffer-head ibuf))
1634 (defun ,read-c-string-function (sap element-type)
1635 (declare (type system-area-pointer sap))
1637 (declare (optimize (speed 3) (safety 0)))
1638 (let* ((stream ,name)
1639 (size 0) (head 0) (byte 0) (char nil)
1640 (decode-break-reason nil)
1641 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1642 (setf decode-break-reason
1643 (block decode-break-reason
1644 (setf byte (sap-ref-8 sap head)
1649 (when decode-break-reason
1650 (c-string-decoding-error ,name decode-break-reason))
1651 (when (zerop (char-code char))
1653 (string (make-string length :element-type element-type)))
1654 (declare (ignorable stream)
1655 (type index head length) ;; size
1656 (type (unsigned-byte 8) byte)
1657 (type (or null character) char)
1658 (type string string))
1660 (dotimes (index length string)
1661 (setf decode-break-reason
1662 (block decode-break-reason
1663 (setf byte (sap-ref-8 sap head)
1668 (when decode-break-reason
1669 (c-string-decoding-error ,name decode-break-reason))
1670 (setf (aref string index) char)))))
1672 (defun ,output-c-string-function (string)
1673 (declare (type simple-string string))
1675 (declare (optimize (speed 3) (safety 0)))
1676 (let* ((length (length string))
1677 (char-length (make-array (1+ length) :element-type 'index))
1679 (+ (loop for i of-type index below length
1680 for byte of-type character = (aref string i)
1681 for bits = (char-code byte)
1682 sum (setf (aref char-length i)
1683 (the index ,out-size-expr)))
1684 (let* ((byte (code-char 0))
1685 (bits (char-code byte)))
1686 (declare (ignorable byte bits))
1687 (setf (aref char-length length)
1688 (the index ,out-size-expr)))))
1690 (,n-buffer (make-array buffer-length
1691 :element-type '(unsigned-byte 8)))
1693 (declare (type index length buffer-length tail)
1696 (with-pinned-objects (,n-buffer)
1697 (let ((sap (vector-sap ,n-buffer)))
1698 (declare (system-area-pointer sap))
1699 (loop for i of-type index below length
1700 for byte of-type character = (aref string i)
1701 for bits = (char-code byte)
1702 for size of-type index = (aref char-length i)
1707 (byte (code-char bits))
1708 (size (aref char-length length)))
1709 (declare (ignorable bits byte size))
1713 (let ((entry (%make-external-format
1714 :names ',external-format
1715 :read-n-chars-fun #',in-function
1716 :read-char-fun #',in-char-function
1717 :write-n-bytes-fun #',out-function
1718 ,@(mapcan #'(lambda (buffering)
1719 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1720 `#',(intern (format nil format (string buffering)))))
1721 '(:none :line :full))
1722 :resync-fun #',resync-function
1723 :bytes-for-char-fun #',size-function
1724 :read-c-string-fun #',read-c-string-function
1725 :write-c-string-fun #',output-c-string-function
1726 :octets-to-string-sym ',octets-to-string-sym
1727 :string-to-octets-sym ',string-to-octets-sym)))
1728 (dolist (ef ',external-format)
1729 (setf (gethash ef *external-formats*) entry))))))
1731 ;;;; utility functions (misc routines, etc)
1733 ;;; Fill in the various routine slots for the given type. INPUT-P and
1734 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1735 ;;; set prior to calling this routine.
1736 (defun set-fd-stream-routines (fd-stream element-type external-format
1737 input-p output-p buffer-p)
1738 (let* ((target-type (case element-type
1739 (unsigned-byte '(unsigned-byte 8))
1740 (signed-byte '(signed-byte 8))
1741 (:default 'character)
1743 (character-stream-p (subtypep target-type 'character))
1744 (bivalent-stream-p (eq element-type :default))
1745 normalized-external-format
1746 (bin-routine #'ill-bin)
1749 (cin-routine #'ill-in)
1752 (input-type nil) ;calculated from bin-type/cin-type
1753 (input-size nil) ;calculated from bin-size/cin-size
1754 (read-n-characters #'ill-in)
1755 (bout-routine #'ill-bout)
1758 (cout-routine #'ill-out)
1763 (output-bytes #'ill-bout))
1765 ;; Ensure that we have buffers in the desired direction(s) only,
1766 ;; getting new ones and dropping/resetting old ones as necessary.
1767 (let ((obuf (fd-stream-obuf fd-stream)))
1771 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1773 (setf (fd-stream-obuf fd-stream) nil)
1774 (release-buffer obuf))))
1776 (let ((ibuf (fd-stream-ibuf fd-stream)))
1780 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1782 (setf (fd-stream-ibuf fd-stream) nil)
1783 (release-buffer ibuf))))
1785 ;; FIXME: Why only for output? Why unconditionally?
1787 (setf (fd-stream-char-pos fd-stream) 0))
1789 (when (and character-stream-p
1790 (eq external-format :default))
1791 (/show0 "/getting default external format")
1792 (setf external-format (default-external-format)))
1795 (when (or (not character-stream-p) bivalent-stream-p)
1796 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1797 normalized-external-format)
1798 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1802 (error "could not find any input routine for ~S" target-type)))
1803 (when character-stream-p
1804 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1805 normalized-external-format)
1806 (pick-input-routine target-type external-format))
1808 (error "could not find any input routine for ~S" target-type)))
1809 (setf (fd-stream-in fd-stream) cin-routine
1810 (fd-stream-bin fd-stream) bin-routine)
1811 ;; character type gets preferential treatment
1812 (setf input-size (or cin-size bin-size))
1813 (setf input-type (or cin-type bin-type))
1814 (when normalized-external-format
1815 (setf (fd-stream-external-format fd-stream)
1816 normalized-external-format))
1817 (when (= (or cin-size 1) (or bin-size 1) 1)
1818 (setf (fd-stream-n-bin fd-stream) ;XXX
1819 (if (and character-stream-p (not bivalent-stream-p))
1821 #'fd-stream-read-n-bytes))
1822 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1823 ;; for character and (unsigned-byte 8) streams. In these
1824 ;; cases, fast-read-* will read from the
1825 ;; ansi-stream-(c)in-buffer, saving function calls.
1826 ;; Otherwise, the various data-reading functions in the stream
1827 ;; structure will be called.
1829 (not bivalent-stream-p)
1830 ;; temporary disable on :io streams
1832 (cond (character-stream-p
1833 (setf (ansi-stream-cin-buffer fd-stream)
1834 (make-array +ansi-stream-in-buffer-length+
1835 :element-type 'character)))
1836 ((equal target-type '(unsigned-byte 8))
1837 (setf (ansi-stream-in-buffer fd-stream)
1838 (make-array +ansi-stream-in-buffer-length+
1839 :element-type '(unsigned-byte 8))))))))
1842 (when (or (not character-stream-p) bivalent-stream-p)
1843 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1844 normalized-external-format)
1845 (pick-output-routine (if bivalent-stream-p
1848 (fd-stream-buffering fd-stream)
1850 (unless bout-routine
1851 (error "could not find any output routine for ~S buffered ~S"
1852 (fd-stream-buffering fd-stream)
1854 (when character-stream-p
1855 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1856 normalized-external-format)
1857 (pick-output-routine target-type
1858 (fd-stream-buffering fd-stream)
1860 (unless cout-routine
1861 (error "could not find any output routine for ~S buffered ~S"
1862 (fd-stream-buffering fd-stream)
1864 (when normalized-external-format
1865 (setf (fd-stream-external-format fd-stream)
1866 normalized-external-format))
1867 (when character-stream-p
1868 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1869 (setf (fd-stream-out fd-stream) cout-routine
1870 (fd-stream-bout fd-stream) bout-routine
1871 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1872 #'fd-sout #'ill-out))
1873 (setf output-size (or cout-size bout-size))
1874 (setf output-type (or cout-type bout-type)))
1876 (when (and input-size output-size
1877 (not (eq input-size output-size)))
1878 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1879 input-type input-size
1880 output-type output-size))
1881 (setf (fd-stream-element-size fd-stream)
1882 (or input-size output-size))
1884 (setf (fd-stream-element-type fd-stream)
1885 (cond ((equal input-type output-type)
1891 ((subtypep input-type output-type)
1893 ((subtypep output-type input-type)
1896 (error "Input type (~S) and output type (~S) are unrelated?"
1900 ;;; Handles the resource-release aspects of stream closing, and marks
1902 (defun release-fd-stream-resources (fd-stream)
1905 ;; Drop handlers first.
1906 (when (fd-stream-handler fd-stream)
1907 (remove-fd-handler (fd-stream-handler fd-stream))
1908 (setf (fd-stream-handler fd-stream) nil))
1909 ;; Disable interrupts so that a asynch unwind will not leave
1910 ;; us with a dangling finalizer (that would close the same
1911 ;; --possibly reassigned-- FD again), or a stream with a closed
1912 ;; FD that appears open.
1913 (sb!unix:unix-close (fd-stream-fd fd-stream))
1914 (set-closed-flame fd-stream)
1915 (when (fboundp 'cancel-finalization)
1916 (cancel-finalization fd-stream)))
1917 ;; On error unwind from WITHOUT-INTERRUPTS.
1918 (serious-condition (e)
1920 ;; Release all buffers. If this is undone, or interrupted,
1921 ;; we're still safe: buffers have finalizers of their own.
1922 (release-fd-stream-buffers fd-stream))
1924 ;;; Flushes the current input buffer and any supplied replacements,
1925 ;;; and returns the input buffer, and the amount of of flushed input
1927 (defun flush-input-buffer (stream)
1928 (let ((unread (length (fd-stream-instead stream))))
1929 (setf (fill-pointer (fd-stream-instead stream)) 0)
1930 (let ((ibuf (fd-stream-ibuf stream)))
1932 (let ((head (buffer-head ibuf))
1933 (tail (buffer-tail ibuf)))
1934 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1935 (values nil unread)))))
1937 (defun fd-stream-clear-input (stream)
1938 (flush-input-buffer stream)
1941 (sb!win32:fd-clear-input (fd-stream-fd stream))
1942 (setf (fd-stream-listen stream) nil))
1944 (catch 'eof-input-catcher
1945 (loop until (sysread-may-block-p stream)
1947 (refill-input-buffer stream)
1948 (reset-buffer (fd-stream-ibuf stream)))
1951 ;;; Handle miscellaneous operations on FD-STREAM.
1952 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1953 (declare (ignore arg2))
1956 (labels ((do-listen ()
1957 (let ((ibuf (fd-stream-ibuf fd-stream)))
1958 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1959 (fd-stream-listen fd-stream)
1961 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1963 ;; If the read can block, LISTEN will certainly return NIL.
1964 (if (sysread-may-block-p fd-stream)
1966 ;; Otherwise select(2) and CL:LISTEN have slightly
1967 ;; different semantics. The former returns that an FD
1968 ;; is readable when a read operation wouldn't block.
1969 ;; That includes EOF. However, LISTEN must return NIL
1971 (progn (catch 'eof-input-catcher
1972 ;; r-b/f too calls select, but it shouldn't
1973 ;; block as long as read can return once w/o
1975 (refill-input-buffer fd-stream))
1976 ;; At this point either IBUF-HEAD != IBUF-TAIL
1977 ;; and FD-STREAM-LISTEN is NIL, in which case
1978 ;; we should return T, or IBUF-HEAD ==
1979 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1980 ;; which case we should return :EOF for this
1981 ;; call and all future LISTEN call on this stream.
1982 ;; Call ourselves again to determine which case
1987 (decf (buffer-head (fd-stream-ibuf fd-stream))
1988 (fd-stream-character-size fd-stream arg1))
1989 (setf (fd-stream-listen fd-stream) t))
1991 ;; Drop input buffers
1992 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1993 (ansi-stream-cin-buffer fd-stream) nil
1994 (ansi-stream-in-buffer fd-stream) nil)
1996 ;; We got us an abort on our hands.
1997 (let ((outputp (fd-stream-obuf fd-stream))
1998 (file (fd-stream-file fd-stream))
1999 (orig (fd-stream-original fd-stream)))
2000 ;; This takes care of the important stuff -- everything
2001 ;; rest is cleaning up the file-system, which we cannot
2002 ;; do on some platforms as long as the file is open.
2003 (release-fd-stream-resources fd-stream)
2004 ;; We can't do anything unless we know what file were
2005 ;; dealing with, and we don't want to do anything
2006 ;; strange unless we were writing to the file.
2007 (when (and outputp file)
2009 ;; If the original is EQ to file we are appending to
2010 ;; and can just close the file without renaming.
2011 (unless (eq orig file)
2012 ;; We have a handle on the original, just revert.
2013 (multiple-value-bind (okay err)
2014 (sb!unix:unix-rename orig file)
2015 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2016 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2019 (error 'simple-stream-error
2021 "~@<Couldn't restore ~S to its original contents ~
2022 from ~S while closing ~S: ~2I~_~A~:>"
2024 (list file orig fd-stream (strerror err))
2025 :stream fd-stream))))
2026 ;; We can't restore the original, and aren't
2027 ;; appending, so nuke that puppy.
2029 ;; FIXME: This is currently the fate of superseded
2030 ;; files, and according to the CLOSE spec this is
2031 ;; wrong. However, there seems to be no clean way to
2032 ;; do that that doesn't involve either copying the
2033 ;; data (bad if the :abort resulted from a full
2034 ;; disk), or renaming the old file temporarily
2035 ;; (probably bad because stream opening becomes more
2037 (multiple-value-bind (okay err)
2038 (sb!unix:unix-unlink file)
2040 (error 'simple-file-error
2043 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2045 (list file fd-stream (strerror err)))))))))
2047 (finish-fd-stream-output fd-stream)
2048 (let ((orig (fd-stream-original fd-stream)))
2049 (when (and orig (fd-stream-delete-original fd-stream))
2050 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2052 (error 'simple-file-error
2055 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2057 (list orig fd-stream (strerror err)))))))
2058 ;; In case of no-abort close, don't *really* close the
2059 ;; stream until the last moment -- the cleaning up of the
2060 ;; original can be done first.
2061 (release-fd-stream-resources fd-stream))))
2063 (fd-stream-clear-input fd-stream))
2065 (flush-output-buffer fd-stream))
2067 (finish-fd-stream-output fd-stream))
2069 (fd-stream-element-type fd-stream))
2071 (fd-stream-external-format fd-stream))
2073 (= 1 (the (member 0 1)
2074 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2078 (fd-stream-char-pos fd-stream))
2080 (unless (fd-stream-file fd-stream)
2081 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2082 ;; "should signal an error of type TYPE-ERROR if stream is not
2083 ;; a stream associated with a file". Too bad there's no very
2084 ;; appropriate value for the EXPECTED-TYPE slot..
2085 (error 'simple-type-error
2087 :expected-type 'fd-stream
2088 :format-control "~S is not a stream associated with a file."
2089 :format-arguments (list fd-stream)))
2090 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2091 atime mtime ctime blksize blocks)
2092 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2093 (declare (ignore ino nlink uid gid rdev
2094 atime mtime ctime blksize blocks))
2096 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2099 (truncate size (fd-stream-element-size fd-stream)))))
2100 (:file-string-length
2102 (character (fd-stream-character-size fd-stream arg1))
2103 (string (fd-stream-string-size fd-stream arg1))))
2106 (fd-stream-set-file-position fd-stream arg1)
2107 (fd-stream-get-file-position fd-stream)))))
2109 ;; FIXME: Think about this.
2111 ;; (defun finish-fd-stream-output (fd-stream)
2112 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2113 ;; (loop while (fd-stream-output-queue fd-stream)
2114 ;; ;; FIXME: SIGINT while waiting for a timeout will
2115 ;; ;; cause a timeout here.
2116 ;; do (when (and (not (serve-event timeout)) timeout)
2117 ;; (signal-timeout 'io-timeout
2118 ;; :stream fd-stream
2119 ;; :direction :write
2120 ;; :seconds timeout)))))
2122 (defun finish-fd-stream-output (stream)
2123 (flush-output-buffer stream)
2125 ((null (fd-stream-output-queue stream)))
2126 (serve-all-events)))
2128 (defun fd-stream-get-file-position (stream)
2129 (declare (fd-stream stream))
2131 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2132 (declare (type (or (alien sb!unix:off-t) null) posn))
2133 ;; We used to return NIL for errno==ESPIPE, and signal an error
2134 ;; in other failure cases. However, CLHS says to return NIL if
2135 ;; the position cannot be determined -- so that's what we do.
2136 (when (integerp posn)
2137 ;; Adjust for buffered output: If there is any output
2138 ;; buffered, the *real* file position will be larger
2139 ;; than reported by lseek() because lseek() obviously
2140 ;; cannot take into account output we have not sent
2142 (dolist (buffer (fd-stream-output-queue stream))
2143 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2144 (let ((obuf (fd-stream-obuf stream)))
2146 (incf posn (buffer-tail obuf))))
2147 ;; Adjust for unread input: If there is any input
2148 ;; read from UNIX but not supplied to the user of the
2149 ;; stream, the *real* file position will smaller than
2150 ;; reported, because we want to look like the unread
2151 ;; stuff is still available.
2152 (let ((ibuf (fd-stream-ibuf stream)))
2154 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2155 ;; Divide bytes by element size.
2156 (truncate posn (fd-stream-element-size stream))))))
2158 (defun fd-stream-set-file-position (stream position-spec)
2159 (declare (fd-stream stream))
2160 (check-type position-spec
2161 (or (alien sb!unix:off-t) (member nil :start :end))
2162 "valid file position designator")
2165 ;; Make sure we don't have any output pending, because if we
2166 ;; move the file pointer before writing this stuff, it will be
2167 ;; written in the wrong location.
2168 (finish-fd-stream-output stream)
2169 ;; Disable interrupts so that interrupt handlers doing output
2172 (unless (fd-stream-output-finished-p stream)
2173 ;; We got interrupted and more output came our way during
2174 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2175 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2176 ;; so we prefer to do things like this...
2178 ;; Clear out any pending input to force the next read to go to
2180 (flush-input-buffer stream)
2181 ;; Trash cached value for listen, so that we check next time.
2182 (setf (fd-stream-listen stream) nil)
2184 (multiple-value-bind (offset origin)
2187 (values 0 sb!unix:l_set))
2189 (values 0 sb!unix:l_xtnd))
2191 (values (* position-spec (fd-stream-element-size stream))
2193 (declare (type (alien sb!unix:off-t) offset))
2194 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2196 ;; CLHS says to return true if the file-position was set
2197 ;; succesfully, and NIL otherwise. We are to signal an error
2198 ;; only if the given position was out of bounds, and that is
2199 ;; dealt with above. In times past we used to return NIL for
2200 ;; errno==ESPIPE, and signal an error in other cases.
2202 ;; FIXME: We are still liable to signal an error if flushing
2204 (return-from fd-stream-set-file-position
2205 (typep posn '(alien sb!unix:off-t))))))))
2208 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2210 ;;; Create a stream for the given Unix file descriptor.
2212 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2213 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2214 ;;; default to allowing input.
2216 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2218 ;;; BUFFERING indicates the kind of buffering to use.
2220 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2221 ;;; NIL (the default), then wait forever. When we time out, we signal
2224 ;;; FILE is the name of the file (will be returned by PATHNAME).
2226 ;;; NAME is used to identify the stream when printed.
2227 (defun make-fd-stream (fd
2230 (output nil output-p)
2231 (element-type 'base-char)
2233 (external-format :default)
2242 (format nil "file ~A" file)
2243 (format nil "descriptor ~W" fd)))
2245 (declare (type index fd) (type (or real null) timeout)
2246 (type (member :none :line :full) buffering))
2247 (cond ((not (or input-p output-p))
2249 ((not (or input output))
2250 (error "File descriptor must be opened either for input or output.")))
2251 (let ((stream (%make-fd-stream :fd fd
2255 :delete-original delete-original
2257 :buffering buffering
2258 :dual-channel-p dual-channel-p
2259 :external-format external-format
2260 :bivalent-p (eq element-type :default)
2261 :char-size (external-format-char-size external-format)
2264 (coerce timeout 'single-float)
2266 (set-fd-stream-routines stream element-type external-format
2267 input output input-buffer-p)
2268 (when (and auto-close (fboundp 'finalize))
2271 (sb!unix:unix-close fd)
2273 (format *terminal-io* "** closed file descriptor ~W **~%"
2278 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2279 ;;; :RENAME-AND-DELETE and :RENAME options.
2280 (defun pick-backup-name (name)
2281 (declare (type simple-string name))
2282 (concatenate 'simple-string name ".bak"))
2284 ;;; Ensure that the given arg is one of the given list of valid
2285 ;;; things. Allow the user to fix any problems.
2286 (defun ensure-one-of (item list what)
2287 (unless (member item list)
2288 (error 'simple-type-error
2290 :expected-type `(member ,@list)
2291 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2292 :format-arguments (list item what list))))
2294 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2295 ;;; access, since we don't want to trash unwritable files even if we
2296 ;;; technically can. We return true if we succeed in renaming.
2297 (defun rename-the-old-one (namestring original)
2298 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2299 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2300 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2303 (error 'simple-file-error
2304 :pathname namestring
2306 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2307 :format-arguments (list namestring original (strerror err))))))
2309 (defun open (filename
2312 (element-type 'base-char)
2313 (if-exists nil if-exists-given)
2314 (if-does-not-exist nil if-does-not-exist-given)
2315 (external-format :default)
2316 &aux ; Squelch assignment warning.
2317 (direction direction)
2318 (if-does-not-exist if-does-not-exist)
2319 (if-exists if-exists))
2321 "Return a stream which reads from or writes to FILENAME.
2323 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2324 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2325 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2326 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2327 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2328 See the manual for details."
2330 ;; Calculate useful stuff.
2331 (multiple-value-bind (input output mask)
2333 (:input (values t nil sb!unix:o_rdonly))
2334 (:output (values nil t sb!unix:o_wronly))
2335 (:io (values t t sb!unix:o_rdwr))
2336 (:probe (values t nil sb!unix:o_rdonly)))
2337 (declare (type index mask))
2338 (let* (;; PATHNAME is the pathname we associate with the stream.
2339 (pathname (merge-pathnames filename))
2340 (physical (physicalize-pathname pathname))
2341 (truename (probe-file physical))
2342 ;; NAMESTRING is the native namestring we open the file with.
2343 (namestring (cond (truename
2344 (native-namestring truename :as-file t))
2346 (and input (eq if-does-not-exist :create))
2347 (and (eq direction :io) (not if-does-not-exist-given)))
2348 (native-namestring physical :as-file t)))))
2349 ;; Process if-exists argument if we are doing any output.
2351 (unless if-exists-given
2353 (if (eq (pathname-version pathname) :newest)
2356 (ensure-one-of if-exists
2357 '(:error :new-version :rename
2358 :rename-and-delete :overwrite
2359 :append :supersede nil)
2362 ((:new-version :error nil)
2363 (setf mask (logior mask sb!unix:o_excl)))
2364 ((:rename :rename-and-delete)
2365 (setf mask (logior mask sb!unix:o_creat)))
2367 (setf mask (logior mask sb!unix:o_trunc)))
2369 (setf mask (logior mask sb!unix:o_append)))))
2371 (setf if-exists :ignore-this-arg)))
2373 (unless if-does-not-exist-given
2374 (setf if-does-not-exist
2375 (cond ((eq direction :input) :error)
2377 (member if-exists '(:overwrite :append)))
2379 ((eq direction :probe)
2383 (ensure-one-of if-does-not-exist
2384 '(:error :create nil)
2386 (if (eq if-does-not-exist :create)
2387 (setf mask (logior mask sb!unix:o_creat)))
2389 (let ((original (case if-exists
2390 ((:rename :rename-and-delete)
2391 (pick-backup-name namestring))
2392 ((:append :overwrite)
2393 ;; KLUDGE: Provent CLOSE from deleting
2394 ;; appending streams when called with :ABORT T
2396 (delete-original (eq if-exists :rename-and-delete))
2398 (when (and original (not (eq original namestring)))
2399 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2400 ;; whether the file already exists, make sure the original
2401 ;; file is not a directory, and keep the mode.
2404 (multiple-value-bind (okay err/dev inode orig-mode)
2405 (sb!unix:unix-stat namestring)
2406 (declare (ignore inode)
2407 (type (or index null) orig-mode))
2410 (when (and output (= (logand orig-mode #o170000)
2412 (error 'simple-file-error
2415 "can't open ~S for output: is a directory"
2416 :format-arguments (list namestring)))
2417 (setf mode (logand orig-mode #o777))
2419 ((eql err/dev sb!unix:enoent)
2422 (simple-file-perror "can't find ~S"
2426 (rename-the-old-one namestring original))
2428 (setf delete-original nil)
2429 ;; In order to use :SUPERSEDE instead, we have to make
2430 ;; sure SB!UNIX:O_CREAT corresponds to
2431 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2432 ;; because of IF-EXISTS being :RENAME.
2433 (unless (eq if-does-not-exist :create)
2435 (logior (logandc2 mask sb!unix:o_creat)
2437 (setf if-exists :supersede))))
2439 ;; Now we can try the actual Unix open(2).
2440 (multiple-value-bind (fd errno)
2442 (sb!unix:unix-open namestring mask mode)
2443 (values nil sb!unix:enoent))
2444 (labels ((open-error (format-control &rest format-arguments)
2445 (error 'simple-file-error
2447 :format-control format-control
2448 :format-arguments format-arguments))
2449 (vanilla-open-error ()
2450 (simple-file-perror "error opening ~S" pathname errno)))
2453 ((:input :output :io)
2457 :element-type element-type
2458 :external-format external-format
2461 :delete-original delete-original
2468 (%make-fd-stream :name namestring
2471 :element-type element-type)))
2474 ((eql errno sb!unix:enoent)
2475 (case if-does-not-exist
2476 (:error (vanilla-open-error))
2478 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2481 ((and (eql errno sb!unix:eexist) (null if-exists))
2484 (vanilla-open-error)))))))))
2488 ;;; the stream connected to the controlling terminal, or NIL if there is none
2491 ;;; the stream connected to the standard input (file descriptor 0)
2494 ;;; the stream connected to the standard output (file descriptor 1)
2497 ;;; the stream connected to the standard error output (file descriptor 2)
2500 ;;; This is called when the cold load is first started up, and may also
2501 ;;; be called in an attempt to recover from nested errors.
2502 (defun stream-cold-init-or-reset ()
2504 (setf *terminal-io* (make-synonym-stream '*tty*))
2505 (setf *standard-output* (make-synonym-stream '*stdout*))
2506 (setf *standard-input* (make-synonym-stream '*stdin*))
2507 (setf *error-output* (make-synonym-stream '*stderr*))
2508 (setf *query-io* (make-synonym-stream '*terminal-io*))
2509 (setf *debug-io* *query-io*)
2510 (setf *trace-output* *standard-output*)
2513 (defun stream-deinit ()
2514 ;; Unbind to make sure we're not accidently dealing with it
2515 ;; before we're ready (or after we think it's been deinitialized).
2516 (with-available-buffers-lock ()
2517 (without-package-locks
2518 (makunbound '*available-buffers*))))
2520 ;;; This is called whenever a saved core is restarted.
2521 (defun stream-reinit (&optional init-buffers-p)
2522 (when init-buffers-p
2523 (with-available-buffers-lock ()
2524 (aver (not (boundp '*available-buffers*)))
2525 (setf *available-buffers* nil)))
2526 (with-output-to-string (*error-output*)
2528 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2529 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2531 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2532 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2534 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2535 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2536 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2537 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2541 :name "the terminal"
2546 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2547 (princ (get-output-stream-string *error-output*) *stderr*))
2552 ;;; the Unix way to beep
2553 (defun beep (stream)
2554 (write-char (code-char bell-char-code) stream)
2555 (finish-output stream))
2557 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2558 ;;; by the filesys stuff to get and set the file name.
2560 ;;; FIXME: misleading name, screwy interface
2561 (defun file-name (stream &optional new-name)
2562 (when (typep stream 'fd-stream)
2564 (setf (fd-stream-pathname stream) new-name)
2565 (setf (fd-stream-file stream)
2566 (native-namestring (physicalize-pathname new-name)
2570 (fd-stream-pathname stream)))))