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-keyword 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)
758 (:copier %copy-external-format))
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)
763 (read-char-fun (missing-arg) :type function)
764 (write-n-bytes-fun (missing-arg) :type function)
765 (write-char-none-buffered-fun (missing-arg) :type function)
766 (write-char-line-buffered-fun (missing-arg) :type function)
767 (write-char-full-buffered-fun (missing-arg) :type function)
768 ;; Can be nil for fixed-width formats.
769 (resync-fun nil :type (or function null))
770 (bytes-for-char-fun (missing-arg) :type function)
771 (read-c-string-fun (missing-arg) :type function)
772 (write-c-string-fun (missing-arg) :type function)
773 ;; We indirect through symbols in these functions so that a
774 ;; developer working on the octets code can easily redefine things
775 ;; and use the new function definition without redefining the
776 ;; external format as well. The slots above don't do any
777 ;; indirection because a developer working with those slots would be
778 ;; redefining the external format anyway.
779 (octets-to-string-fun (missing-arg) :type function)
780 (string-to-octets-fun (missing-arg) :type function))
782 (defun wrap-external-format-functions (external-format fun)
783 (let ((result (%copy-external-format external-format)))
784 (macrolet ((frob (accessor)
785 `(setf (,accessor result) (funcall fun (,accessor result)))))
786 (frob ef-read-n-chars-fun)
787 (frob ef-read-char-fun)
788 (frob ef-write-n-bytes-fun)
789 (frob ef-write-char-none-buffered-fun)
790 (frob ef-write-char-line-buffered-fun)
791 (frob ef-write-char-full-buffered-fun)
793 (frob ef-bytes-for-char-fun)
794 (frob ef-read-c-string-fun)
795 (frob ef-write-c-string-fun)
796 (frob ef-octets-to-string-fun)
797 (frob ef-string-to-octets-fun))
800 (defvar *external-formats* (make-hash-table)
802 "Hashtable of all available external formats. The table maps from
803 external-format names to EXTERNAL-FORMAT structures.")
805 (defun get-external-format (external-format)
806 (flet ((keyword-external-format (keyword)
807 (declare (type keyword keyword))
808 (gethash keyword *external-formats*))
809 (replacement-handlerify (entry replacement)
811 (wrap-external-format-functions
816 (declare (dynamic-extent rest))
818 ((stream-decoding-error
821 (invoke-restart 'input-replacement replacement)))
822 (stream-encoding-error
825 (invoke-restart 'output-replacement replacement)))
826 (octets-encoding-error
827 (lambda (c) (use-value replacement c)))
828 (octet-decoding-error
829 (lambda (c) (use-value replacement c))))
830 (apply fun rest)))))))))
831 (typecase external-format
832 (keyword (keyword-external-format external-format))
834 (let ((entry (keyword-external-format (car external-format)))
835 (replacement (getf (cdr external-format) :replacement)))
837 (replacement-handlerify entry replacement)
840 (defun get-external-format-or-lose (external-format)
841 (or (get-external-format external-format)
842 (error "Undefined external-format ~A" external-format)))
844 (defun external-format-keyword (external-format)
845 (typecase external-format
846 (keyword external-format)
847 ((cons keyword) (car external-format))))
849 (defun fd-stream-external-format-keyword (stream)
850 (external-format-keyword (fd-stream-external-format stream)))
852 (defun canonize-external-format (external-format entry)
853 (typecase external-format
854 (keyword (first (ef-names entry)))
855 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
857 ;;; Find an output routine to use given the type and buffering. Return
858 ;;; as multiple values the routine, the real type transfered, and the
859 ;;; number of bytes per element.
860 (defun pick-output-routine (type buffering &optional external-format)
861 (when (subtypep type 'character)
862 (let ((entry (get-external-format external-format)))
864 (return-from pick-output-routine
865 (values (ecase buffering
866 (:none (ef-write-char-none-buffered-fun entry))
867 (:line (ef-write-char-line-buffered-fun entry))
868 (:full (ef-write-char-full-buffered-fun entry)))
871 (ef-write-n-bytes-fun entry)
872 (canonize-external-format external-format entry))))))
873 (dolist (entry *output-routines*)
874 (when (and (subtypep type (first entry))
875 (eq buffering (second entry))
876 (or (not (fifth entry))
877 (eq external-format (fifth entry))))
878 (return-from pick-output-routine
879 (values (symbol-function (third entry))
882 ;; KLUDGE: dealing with the buffering here leads to excessive code
885 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
886 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
887 if (subtypep type `(unsigned-byte ,i))
888 do (return-from pick-output-routine
892 (lambda (stream byte)
893 (output-wrapper (stream (/ i 8) (:none) nil)
894 (loop for j from 0 below (/ i 8)
895 do (setf (sap-ref-8 (buffer-sap obuf)
897 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
899 (lambda (stream byte)
900 (output-wrapper (stream (/ i 8) (:full) nil)
901 (loop for j from 0 below (/ i 8)
902 do (setf (sap-ref-8 (buffer-sap obuf)
904 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
907 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
908 if (subtypep type `(signed-byte ,i))
909 do (return-from pick-output-routine
913 (lambda (stream byte)
914 (output-wrapper (stream (/ i 8) (:none) nil)
915 (loop for j from 0 below (/ i 8)
916 do (setf (sap-ref-8 (buffer-sap obuf)
918 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
920 (lambda (stream byte)
921 (output-wrapper (stream (/ i 8) (:full) nil)
922 (loop for j from 0 below (/ i 8)
923 do (setf (sap-ref-8 (buffer-sap obuf)
925 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
929 ;;;; input routines and related noise
931 ;;; a list of all available input routines. Each element is a list of
932 ;;; the element-type input, the function name, and the number of bytes
934 (defvar *input-routines* ())
936 ;;; Return whether a primitive partial read operation on STREAM's FD
937 ;;; would (probably) block. Signal a `simple-stream-error' if the
938 ;;; system call implementing this operation fails.
940 ;;; It is "may" instead of "would" because "would" is not quite
941 ;;; correct on win32. However, none of the places that use it require
942 ;;; further assurance than "may" versus "will definitely not".
943 (defun sysread-may-block-p (stream)
945 ;; This answers T at EOF on win32, I think.
946 (not (sb!win32:fd-listen (fd-stream-fd stream)))
948 (sb!unix:with-restarted-syscall (count errno)
949 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
950 (sb!unix:fd-zero read-fds)
951 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
952 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
953 (sb!alien:addr read-fds)
959 (simple-stream-perror "couldn't check whether ~S is readable"
963 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
964 ;;; then fill the input buffer, and return the number of bytes read. Throws
965 ;;; to EOF-INPUT-CATCHER if the eof was reached.
966 (defun refill-input-buffer (stream)
967 (dx-let ((fd (fd-stream-fd stream))
971 ;; Check for blocking input before touching the stream, as if
972 ;; we happen to wait we are liable to be interrupted, and the
973 ;; interrupt handler may use the same stream.
974 (if (sysread-may-block-p stream)
977 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
978 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
980 (closed-flame stream)
982 (simple-stream-perror "couldn't read from ~S" stream errno)
984 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
985 ;; to wait for input if read tells us EWOULDBLOCK.
986 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
987 (signal-timeout 'io-timeout :stream stream :direction :read
988 :seconds (fd-stream-timeout stream)))
990 ;; Since the read should not block, we'll disable the
991 ;; interrupts here, so that we don't accidentally unwind and
992 ;; leave the stream in an inconsistent state.
994 ;; Execute the nlx outside without-interrupts to ensure the
995 ;; resulting thunk is stack-allocatable.
996 ((lambda (return-reason)
998 ((nil)) ; fast path normal cases
999 ((:wait-for-input) (go :wait-for-input))
1000 ((:closed-flame) (go :closed-flame))
1001 ((:read-error) (go :read-error))))
1003 ;; Check the buffer: if it is null, then someone has closed
1004 ;; the stream from underneath us. This is not ment to fix
1005 ;; multithreaded races, but to deal with interrupt handlers
1006 ;; closing the stream.
1009 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1010 (sap (buffer-sap ibuf))
1011 (length (buffer-length ibuf))
1012 (head (buffer-head ibuf))
1013 (tail (buffer-tail ibuf)))
1014 (declare (index length head tail)
1015 (inline sb!unix:unix-read))
1016 (unless (zerop head)
1017 (cond ((eql head tail)
1018 ;; Buffer is empty, but not at yet reset -- make it so.
1021 (reset-buffer ibuf))
1023 ;; Buffer has things in it, but they are not at the
1024 ;; head -- move them there.
1025 (let ((n (- tail head)))
1026 (system-area-ub8-copy sap head sap 0 n)
1028 (buffer-head ibuf) head
1030 (buffer-tail ibuf) tail)))))
1031 (setf (fd-stream-listen stream) nil)
1032 (setf (values count errno)
1033 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1036 (return :read-error)
1038 (if (eql errno sb!unix:ewouldblock)
1039 (return :wait-for-input)
1040 (return :read-error)))
1042 (setf (fd-stream-listen stream) :eof)
1043 (/show0 "THROWing EOF-INPUT-CATCHER")
1044 (throw 'eof-input-catcher nil))
1046 ;; Success! (Do not use INCF, for sake of other threads.)
1047 (setf (buffer-tail ibuf) (+ count tail))))))))))
1050 ;;; Make sure there are at least BYTES number of bytes in the input
1051 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1052 (defmacro input-at-least (stream bytes)
1053 (let ((stream-var (gensym "STREAM"))
1054 (bytes-var (gensym "BYTES"))
1055 (buffer-var (gensym "IBUF")))
1056 `(let* ((,stream-var ,stream)
1058 (,buffer-var (fd-stream-ibuf ,stream-var)))
1060 (when (>= (- (buffer-tail ,buffer-var)
1061 (buffer-head ,buffer-var))
1064 (refill-input-buffer ,stream-var)))))
1066 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1068 (let ((stream-var (gensym "STREAM"))
1069 (retry-var (gensym "RETRY"))
1070 (element-var (gensym "ELT")))
1071 `(let* ((,stream-var ,stream)
1072 (ibuf (fd-stream-ibuf ,stream-var))
1075 (when (fd-stream-eof-forced-p ,stream-var)
1076 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1077 (return-from use-instead
1078 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1079 (let ((,element-var nil)
1080 (decode-break-reason nil))
1081 (do ((,retry-var t))
1083 (if (> (length (fd-stream-instead ,stream-var)) 0)
1084 (let* ((instead (fd-stream-instead ,stream-var))
1085 (result (vector-pop instead))
1086 (pointer (fill-pointer instead)))
1088 (setf (fd-stream-listen ,stream-var) nil))
1089 (return-from use-instead result))
1091 (catch 'eof-input-catcher
1092 (setf decode-break-reason
1093 (block decode-break-reason
1094 (input-at-least ,stream-var 1)
1095 (let* ((byte (sap-ref-8 (buffer-sap ibuf)
1096 (buffer-head ibuf))))
1097 (declare (ignorable byte))
1099 (input-at-least ,stream-var size)
1100 (setq ,element-var (locally ,@read-forms))
1101 (setq ,retry-var nil))
1103 (when decode-break-reason
1104 (when (stream-decoding-error-and-handle
1105 stream decode-break-reason)
1106 (setq ,retry-var nil)
1107 (throw 'eof-input-catcher nil)))
1109 (let ((octet-count (- (buffer-tail ibuf)
1110 (buffer-head ibuf))))
1111 (when (or (zerop octet-count)
1112 (and (not ,element-var)
1113 (not decode-break-reason)
1114 (stream-decoding-error-and-handle
1115 stream octet-count)))
1116 (setq ,retry-var nil))))))
1118 (incf (buffer-head ibuf) size)
1121 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1123 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1124 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1125 (let ((stream-var (gensym "STREAM"))
1126 (element-var (gensym "ELT")))
1127 `(let* ((,stream-var ,stream)
1128 (ibuf (fd-stream-ibuf ,stream-var)))
1129 (if (> (length (fd-stream-instead ,stream-var)) 0)
1130 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1132 (catch 'eof-input-catcher
1133 (input-at-least ,stream-var ,bytes)
1134 (locally ,@read-forms))))
1136 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1139 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1141 (defmacro def-input-routine/variable-width (name
1142 (type external-format size sap head)
1145 (defun ,name (stream eof-error eof-value)
1146 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1147 (let ((,sap (buffer-sap ibuf))
1148 (,head (buffer-head ibuf)))
1150 (setf *input-routines*
1151 (nconc *input-routines*
1152 (list (list ',type ',name 1 ',external-format))))))
1154 (defmacro def-input-routine (name
1155 (type size sap head)
1158 (defun ,name (stream eof-error eof-value)
1159 (input-wrapper (stream ,size eof-error eof-value)
1160 (let ((,sap (buffer-sap ibuf))
1161 (,head (buffer-head ibuf)))
1163 (setf *input-routines*
1164 (nconc *input-routines*
1165 (list (list ',type ',name ',size nil))))))
1167 ;;; STREAM-IN routine for reading a string char
1168 (def-input-routine input-character
1169 (character 1 sap head)
1170 (code-char (sap-ref-8 sap head)))
1172 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1173 (def-input-routine input-unsigned-8bit-byte
1174 ((unsigned-byte 8) 1 sap head)
1175 (sap-ref-8 sap head))
1177 ;;; STREAM-IN routine for reading a signed 8 bit number
1178 (def-input-routine input-signed-8bit-number
1179 ((signed-byte 8) 1 sap head)
1180 (signed-sap-ref-8 sap head))
1182 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1183 (def-input-routine input-unsigned-16bit-byte
1184 ((unsigned-byte 16) 2 sap head)
1185 (sap-ref-16 sap head))
1187 ;;; STREAM-IN routine for reading a signed 16 bit number
1188 (def-input-routine input-signed-16bit-byte
1189 ((signed-byte 16) 2 sap head)
1190 (signed-sap-ref-16 sap head))
1192 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1193 (def-input-routine input-unsigned-32bit-byte
1194 ((unsigned-byte 32) 4 sap head)
1195 (sap-ref-32 sap head))
1197 ;;; STREAM-IN routine for reading a signed 32 bit number
1198 (def-input-routine input-signed-32bit-byte
1199 ((signed-byte 32) 4 sap head)
1200 (signed-sap-ref-32 sap head))
1202 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1204 (def-input-routine input-unsigned-64bit-byte
1205 ((unsigned-byte 64) 8 sap head)
1206 (sap-ref-64 sap head))
1207 (def-input-routine input-signed-64bit-byte
1208 ((signed-byte 64) 8 sap head)
1209 (signed-sap-ref-64 sap head)))
1211 ;;; Find an input routine to use given the type. Return as multiple
1212 ;;; values the routine, the real type transfered, and the number of
1213 ;;; bytes per element (and for character types string input routine).
1214 (defun pick-input-routine (type &optional external-format)
1215 (when (subtypep type 'character)
1216 (let ((entry (get-external-format external-format)))
1218 (return-from pick-input-routine
1219 (values (ef-read-char-fun entry)
1222 (ef-read-n-chars-fun entry)
1223 (canonize-external-format external-format entry))))))
1224 (dolist (entry *input-routines*)
1225 (when (and (subtypep type (first entry))
1226 (or (not (fourth entry))
1227 (eq external-format (fourth entry))))
1228 (return-from pick-input-routine
1229 (values (symbol-function (second entry))
1232 ;; FIXME: let's do it the hard way, then (but ignore things like
1233 ;; endianness, efficiency, and the necessary coupling between these
1234 ;; and the output routines). -- CSR, 2004-02-09
1235 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1236 if (subtypep type `(unsigned-byte ,i))
1237 do (return-from pick-input-routine
1239 (lambda (stream eof-error eof-value)
1240 (input-wrapper (stream (/ i 8) eof-error eof-value)
1241 (let ((sap (buffer-sap ibuf))
1242 (head (buffer-head ibuf)))
1243 (loop for j from 0 below (/ i 8)
1247 (sap-ref-8 sap (+ head j))))
1248 finally (return result)))))
1251 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1252 if (subtypep type `(signed-byte ,i))
1253 do (return-from pick-input-routine
1255 (lambda (stream eof-error eof-value)
1256 (input-wrapper (stream (/ i 8) eof-error eof-value)
1257 (let ((sap (buffer-sap ibuf))
1258 (head (buffer-head ibuf)))
1259 (loop for j from 0 below (/ i 8)
1263 (sap-ref-8 sap (+ head j))))
1264 finally (return (if (logbitp (1- i) result)
1265 (dpb result (byte i 0) -1)
1270 ;;; the N-BIN method for FD-STREAMs
1272 ;;; Note that this blocks in UNIX-READ. It is generally used where
1273 ;;; there is a definite amount of reading to be done, so blocking
1274 ;;; isn't too problematical.
1275 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1276 &aux (total-copied 0))
1277 (declare (type fd-stream stream))
1278 (declare (type index start requested total-copied))
1279 (aver (= (length (fd-stream-instead stream)) 0))
1282 (let* ((remaining-request (- requested total-copied))
1283 (ibuf (fd-stream-ibuf stream))
1284 (head (buffer-head ibuf))
1285 (tail (buffer-tail ibuf))
1286 (available (- tail head))
1287 (n-this-copy (min remaining-request available))
1288 (this-start (+ start total-copied))
1289 (this-end (+ this-start n-this-copy))
1290 (sap (buffer-sap ibuf)))
1291 (declare (type index remaining-request head tail available))
1292 (declare (type index n-this-copy))
1293 ;; Copy data from stream buffer into user's buffer.
1294 (%byte-blt sap head buffer this-start this-end)
1295 (incf (buffer-head ibuf) n-this-copy)
1296 (incf total-copied n-this-copy)
1297 ;; Maybe we need to refill the stream buffer.
1298 (cond (;; If there were enough data in the stream buffer, we're done.
1299 (eql total-copied requested)
1300 (return total-copied))
1301 (;; If EOF, we're done in another way.
1302 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1304 (error 'end-of-file :stream stream)
1305 (return total-copied)))
1306 ;; Otherwise we refilled the stream buffer, so fall
1307 ;; through into another pass of the loop.
1310 (defun fd-stream-resync (stream)
1311 (let ((entry (get-external-format (fd-stream-external-format stream))))
1313 (funcall (ef-resync-fun entry) stream))))
1315 (defun get-fd-stream-character-sizer (stream)
1316 (let ((entry (get-external-format (fd-stream-external-format stream))))
1318 (ef-bytes-for-char-fun entry))))
1320 (defun fd-stream-character-size (stream char)
1321 (let ((sizer (get-fd-stream-character-sizer stream)))
1322 (when sizer (funcall sizer char))))
1324 (defun fd-stream-string-size (stream string)
1325 (let ((sizer (get-fd-stream-character-sizer stream)))
1327 (loop for char across string summing (funcall sizer char)))))
1329 (defun find-external-format (external-format)
1330 (when external-format
1331 (get-external-format external-format)))
1333 (defun variable-width-external-format-p (ef-entry)
1334 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1336 (defun bytes-for-char-fun (ef-entry)
1337 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1339 (defmacro define-external-format (external-format size output-restart
1341 octets-to-string-sym
1342 string-to-octets-sym)
1343 (let* ((name (first external-format))
1344 (out-function (symbolicate "OUTPUT-BYTES/" name))
1345 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1346 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1347 (in-char-function (symbolicate "INPUT-CHAR/" name))
1348 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1349 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1350 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1351 (n-buffer (gensym "BUFFER")))
1353 (defun ,size-function (byte)
1354 (declare (ignore byte))
1356 (defun ,out-function (stream string flush-p start end)
1357 (let ((start (or start 0))
1358 (end (or end (length string))))
1359 (declare (type index start end))
1360 (synchronize-stream-output stream)
1361 (unless (<= 0 start end (length string))
1362 (sequence-bounding-indices-bad-error string start end))
1365 (let ((obuf (fd-stream-obuf stream)))
1366 (string-dispatch (simple-base-string
1368 (simple-array character (*))
1371 (let ((sap (buffer-sap obuf))
1372 (len (buffer-length obuf))
1374 (tail (buffer-tail obuf)))
1375 (declare (type index tail)
1376 ;; STRING bounds have already been checked.
1377 (optimize (safety 0)))
1378 (,@(if output-restart
1379 `(catch 'output-nothing)
1382 ((or (= start end) (< (- len tail) 4)))
1383 (let* ((byte (aref string start))
1384 (bits (char-code byte)))
1387 (setf (buffer-tail obuf) tail)
1389 ;; Exited from the loop normally
1391 ;; Exited via CATCH. Skip the current character.
1395 (flush-output-buffer stream)))
1397 (flush-output-buffer stream))))
1398 (def-output-routines (,format
1404 (if (eql byte #\Newline)
1405 (setf (fd-stream-char-pos stream) 0)
1406 (incf (fd-stream-char-pos stream)))
1407 (let* ((obuf (fd-stream-obuf stream))
1408 (bits (char-code byte))
1409 (sap (buffer-sap obuf))
1410 (tail (buffer-tail obuf)))
1412 (defun ,in-function (stream buffer start requested eof-error-p
1413 &aux (index start) (end (+ start requested)))
1414 (declare (type fd-stream stream)
1415 (type index start requested index end)
1417 (simple-array character (#.+ansi-stream-in-buffer-length+))
1419 (when (fd-stream-eof-forced-p stream)
1420 (setf (fd-stream-eof-forced-p stream) nil)
1421 (return-from ,in-function 0))
1422 (do ((instead (fd-stream-instead stream)))
1423 ((= (fill-pointer instead) 0)
1424 (setf (fd-stream-listen stream) nil))
1425 (setf (aref buffer index) (vector-pop instead))
1428 (return-from ,in-function (- index start))))
1431 (let* ((ibuf (fd-stream-ibuf stream))
1432 (head (buffer-head ibuf))
1433 (tail (buffer-tail ibuf))
1434 (sap (buffer-sap ibuf)))
1435 (declare (type index head tail)
1436 (type system-area-pointer sap))
1437 ;; Copy data from stream buffer into user's buffer.
1438 (dotimes (i (min (truncate (- tail head) ,size)
1440 (declare (optimize speed))
1441 (let* ((byte (sap-ref-8 sap head)))
1442 (setf (aref buffer index) ,in-expr)
1445 (setf (buffer-head ibuf) head)
1446 ;; Maybe we need to refill the stream buffer.
1447 (cond ( ;; If there was enough data in the stream buffer, we're done.
1449 (return (- index start)))
1450 ( ;; If EOF, we're done in another way.
1451 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1453 (error 'end-of-file :stream stream)
1454 (return (- index start))))
1455 ;; Otherwise we refilled the stream buffer, so fall
1456 ;; through into another pass of the loop.
1458 (def-input-routine ,in-char-function (character ,size sap head)
1459 (let ((byte (sap-ref-8 sap head)))
1461 (defun ,read-c-string-function (sap element-type)
1462 (declare (type system-area-pointer sap)
1463 (type (member character base-char) element-type))
1465 (declare (optimize (speed 3) (safety 0)))
1466 (let* ((stream ,name)
1468 (loop for head of-type index upfrom 0 by ,size
1469 for count of-type index upto (1- array-dimension-limit)
1470 for byte = (sap-ref-8 sap head)
1471 for char of-type character = ,in-expr
1472 until (zerop (char-code char))
1473 finally (return count)))
1474 ;; Inline the common cases
1475 (string (make-string length :element-type element-type)))
1476 (declare (ignorable stream)
1478 (type simple-string string))
1479 (/show0 before-copy-loop)
1480 (loop for head of-type index upfrom 0 by ,size
1481 for index of-type index below length
1482 for byte = (sap-ref-8 sap head)
1483 for char of-type character = ,in-expr
1484 do (setf (aref string index) char))
1485 string))) ;; last loop rewrite to dotimes?
1486 (defun ,output-c-string-function (string)
1487 (declare (type simple-string string))
1489 (declare (optimize (speed 3) (safety 0)))
1490 (let* ((length (length string))
1491 (,n-buffer (make-array (* (1+ length) ,size)
1492 :element-type '(unsigned-byte 8)))
1495 (declare (type index length tail))
1496 (with-pinned-objects (,n-buffer)
1497 (let ((sap (vector-sap ,n-buffer)))
1498 (declare (system-area-pointer sap))
1500 (let* ((byte (aref string i))
1501 (bits (char-code byte)))
1502 (declare (ignorable byte bits))
1506 (byte (code-char bits)))
1507 (declare (ignorable bits byte))
1510 (let ((entry (%make-external-format
1511 :names ',external-format
1512 :read-n-chars-fun #',in-function
1513 :read-char-fun #',in-char-function
1514 :write-n-bytes-fun #',out-function
1515 ,@(mapcan #'(lambda (buffering)
1516 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1517 `#',(intern (format nil format (string buffering)))))
1518 '(:none :line :full))
1520 :bytes-for-char-fun #',size-function
1521 :read-c-string-fun #',read-c-string-function
1522 :write-c-string-fun #',output-c-string-function
1523 :octets-to-string-fun (lambda (&rest rest)
1524 (declare (dynamic-extent rest))
1525 (apply ',octets-to-string-sym rest))
1526 :string-to-octets-fun (lambda (&rest rest)
1527 (declare (dynamic-extent rest))
1528 (apply ',string-to-octets-sym rest)))))
1529 (dolist (ef ',external-format)
1530 (setf (gethash ef *external-formats*) entry))))))
1532 (defmacro define-external-format/variable-width
1533 (external-format output-restart out-size-expr
1534 out-expr in-size-expr in-expr
1535 octets-to-string-sym string-to-octets-sym)
1536 (let* ((name (first external-format))
1537 (out-function (symbolicate "OUTPUT-BYTES/" name))
1538 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1539 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1540 (in-char-function (symbolicate "INPUT-CHAR/" name))
1541 (resync-function (symbolicate "RESYNC/" name))
1542 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1543 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1544 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1545 (n-buffer (gensym "BUFFER")))
1547 (defun ,size-function (byte)
1548 (declare (ignorable byte))
1550 (defun ,out-function (stream string flush-p start end)
1551 (let ((start (or start 0))
1552 (end (or end (length string))))
1553 (declare (type index start end))
1554 (synchronize-stream-output stream)
1555 (unless (<= 0 start end (length string))
1556 (sequence-bounding-indices-bad-error string start end))
1559 (let ((obuf (fd-stream-obuf stream)))
1560 (string-dispatch (simple-base-string
1561 #!+sb-unicode (simple-array character (*))
1564 (let ((len (buffer-length obuf))
1565 (sap (buffer-sap obuf))
1567 (tail (buffer-tail obuf)))
1568 (declare (type index tail)
1569 ;; STRING bounds have already been checked.
1570 (optimize (safety 0)))
1571 (,@(if output-restart
1572 `(catch 'output-nothing)
1575 ((or (= start end) (< (- len tail) 4)))
1576 (let* ((byte (aref string start))
1577 (bits (char-code byte))
1578 (size ,out-size-expr))
1581 (setf (buffer-tail obuf) tail)
1584 ;; Exited via CATCH: skip the current character.
1588 (flush-output-buffer stream)))
1590 (flush-output-buffer stream))))
1591 (def-output-routines/variable-width (,format
1598 (if (eql byte #\Newline)
1599 (setf (fd-stream-char-pos stream) 0)
1600 (incf (fd-stream-char-pos stream)))
1601 (let ((bits (char-code byte))
1602 (sap (buffer-sap obuf))
1603 (tail (buffer-tail obuf)))
1605 (defun ,in-function (stream buffer start requested eof-error-p
1606 &aux (total-copied 0))
1607 (declare (type fd-stream stream)
1608 (type index start requested total-copied)
1610 (simple-array character (#.+ansi-stream-in-buffer-length+))
1612 (when (fd-stream-eof-forced-p stream)
1613 (setf (fd-stream-eof-forced-p stream) nil)
1614 (return-from ,in-function 0))
1615 (do ((instead (fd-stream-instead stream)))
1616 ((= (fill-pointer instead) 0)
1617 (setf (fd-stream-listen stream) nil))
1618 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1620 (when (= requested total-copied)
1621 (return-from ,in-function total-copied)))
1624 (let* ((ibuf (fd-stream-ibuf stream))
1625 (head (buffer-head ibuf))
1626 (tail (buffer-tail ibuf))
1627 (sap (buffer-sap ibuf))
1628 (decode-break-reason nil))
1629 (declare (type index head tail))
1630 ;; Copy data from stream buffer into user's buffer.
1631 (do ((size nil nil))
1632 ((or (= tail head) (= requested total-copied)))
1633 (setf decode-break-reason
1634 (block decode-break-reason
1635 (let ((byte (sap-ref-8 sap head)))
1636 (declare (ignorable byte))
1637 (setq size ,in-size-expr)
1638 (when (> size (- tail head))
1640 (setf (aref buffer (+ start total-copied)) ,in-expr)
1644 (setf (buffer-head ibuf) head)
1645 (when decode-break-reason
1646 ;; If we've already read some characters on when the invalid
1647 ;; code sequence is detected, we return immediately. The
1648 ;; handling of the error is deferred until the next call
1649 ;; (where this check will be false). This allows establishing
1650 ;; high-level handlers for decode errors (for example
1651 ;; automatically resyncing in Lisp comments).
1652 (when (plusp total-copied)
1653 (return-from ,in-function total-copied))
1654 (when (stream-decoding-error-and-handle
1655 stream decode-break-reason)
1657 (error 'end-of-file :stream stream)
1658 (return-from ,in-function total-copied)))
1659 ;; we might have been given stuff to use instead, so
1660 ;; we have to return (and trust our caller to know
1661 ;; what to do about TOTAL-COPIED being 0).
1662 (return-from ,in-function total-copied)))
1663 (setf (buffer-head ibuf) head)
1664 ;; Maybe we need to refill the stream buffer.
1665 (cond ( ;; If there were enough data in the stream buffer, we're done.
1666 (= total-copied requested)
1667 (return total-copied))
1668 ( ;; If EOF, we're done in another way.
1669 (or (eq decode-break-reason 'eof)
1670 (null (catch 'eof-input-catcher
1671 (refill-input-buffer stream))))
1673 (error 'end-of-file :stream stream)
1674 (return total-copied)))
1675 ;; Otherwise we refilled the stream buffer, so fall
1676 ;; through into another pass of the loop.
1678 (def-input-routine/variable-width ,in-char-function (character
1682 (let ((byte (sap-ref-8 sap head)))
1683 (declare (ignorable byte))
1685 (defun ,resync-function (stream)
1686 (let ((ibuf (fd-stream-ibuf stream)))
1687 (catch 'eof-input-catcher
1689 (incf (buffer-head ibuf))
1690 (input-at-least stream 1)
1691 (unless (block decode-break-reason
1692 (let* ((sap (buffer-sap ibuf))
1693 (head (buffer-head ibuf))
1694 (byte (sap-ref-8 sap head))
1695 (size ,in-size-expr))
1696 (declare (ignorable byte))
1697 (input-at-least stream size)
1698 (setf head (buffer-head ibuf))
1702 (defun ,read-c-string-function (sap element-type)
1703 (declare (type system-area-pointer sap))
1705 (declare (optimize (speed 3) (safety 0)))
1706 (let* ((stream ,name)
1707 (size 0) (head 0) (byte 0) (char nil)
1708 (decode-break-reason nil)
1709 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1710 (setf decode-break-reason
1711 (block decode-break-reason
1712 (setf byte (sap-ref-8 sap head)
1717 (when decode-break-reason
1718 (c-string-decoding-error ,name decode-break-reason))
1719 (when (zerop (char-code char))
1721 (string (make-string length :element-type element-type)))
1722 (declare (ignorable stream)
1723 (type index head length) ;; size
1724 (type (unsigned-byte 8) byte)
1725 (type (or null character) char)
1726 (type string string))
1728 (dotimes (index length string)
1729 (setf decode-break-reason
1730 (block decode-break-reason
1731 (setf byte (sap-ref-8 sap head)
1736 (when decode-break-reason
1737 (c-string-decoding-error ,name decode-break-reason))
1738 (setf (aref string index) char)))))
1740 (defun ,output-c-string-function (string)
1741 (declare (type simple-string string))
1743 (declare (optimize (speed 3) (safety 0)))
1744 (let* ((length (length string))
1745 (char-length (make-array (1+ length) :element-type 'index))
1747 (+ (loop for i of-type index below length
1748 for byte of-type character = (aref string i)
1749 for bits = (char-code byte)
1750 sum (setf (aref char-length i)
1751 (the index ,out-size-expr)))
1752 (let* ((byte (code-char 0))
1753 (bits (char-code byte)))
1754 (declare (ignorable byte bits))
1755 (setf (aref char-length length)
1756 (the index ,out-size-expr)))))
1758 (,n-buffer (make-array buffer-length
1759 :element-type '(unsigned-byte 8)))
1761 (declare (type index length buffer-length tail)
1764 (with-pinned-objects (,n-buffer)
1765 (let ((sap (vector-sap ,n-buffer)))
1766 (declare (system-area-pointer sap))
1767 (loop for i of-type index below length
1768 for byte of-type character = (aref string i)
1769 for bits = (char-code byte)
1770 for size of-type index = (aref char-length i)
1775 (byte (code-char bits))
1776 (size (aref char-length length)))
1777 (declare (ignorable bits byte size))
1781 (let ((entry (%make-external-format
1782 :names ',external-format
1783 :read-n-chars-fun #',in-function
1784 :read-char-fun #',in-char-function
1785 :write-n-bytes-fun #',out-function
1786 ,@(mapcan #'(lambda (buffering)
1787 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1788 `#',(intern (format nil format (string buffering)))))
1789 '(:none :line :full))
1790 :resync-fun #',resync-function
1791 :bytes-for-char-fun #',size-function
1792 :read-c-string-fun #',read-c-string-function
1793 :write-c-string-fun #',output-c-string-function
1794 :octets-to-string-fun (lambda (&rest rest)
1795 (declare (dynamic-extent rest))
1796 (apply ',octets-to-string-sym rest))
1797 :string-to-octets-fun (lambda (&rest rest)
1798 (declare (dynamic-extent rest))
1799 (apply ',string-to-octets-sym rest)))))
1800 (dolist (ef ',external-format)
1801 (setf (gethash ef *external-formats*) entry))))))
1803 ;;;; utility functions (misc routines, etc)
1805 ;;; Fill in the various routine slots for the given type. INPUT-P and
1806 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1807 ;;; set prior to calling this routine.
1808 (defun set-fd-stream-routines (fd-stream element-type external-format
1809 input-p output-p buffer-p)
1810 (let* ((target-type (case element-type
1811 (unsigned-byte '(unsigned-byte 8))
1812 (signed-byte '(signed-byte 8))
1813 (:default 'character)
1815 (character-stream-p (subtypep target-type 'character))
1816 (bivalent-stream-p (eq element-type :default))
1817 normalized-external-format
1818 (bin-routine #'ill-bin)
1821 (cin-routine #'ill-in)
1824 (input-type nil) ;calculated from bin-type/cin-type
1825 (input-size nil) ;calculated from bin-size/cin-size
1826 (read-n-characters #'ill-in)
1827 (bout-routine #'ill-bout)
1830 (cout-routine #'ill-out)
1835 (output-bytes #'ill-bout))
1837 ;; Ensure that we have buffers in the desired direction(s) only,
1838 ;; getting new ones and dropping/resetting old ones as necessary.
1839 (let ((obuf (fd-stream-obuf fd-stream)))
1843 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1845 (setf (fd-stream-obuf fd-stream) nil)
1846 (release-buffer obuf))))
1848 (let ((ibuf (fd-stream-ibuf fd-stream)))
1852 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1854 (setf (fd-stream-ibuf fd-stream) nil)
1855 (release-buffer ibuf))))
1857 ;; FIXME: Why only for output? Why unconditionally?
1859 (setf (fd-stream-char-pos fd-stream) 0))
1861 (when (and character-stream-p
1862 (eq external-format :default))
1863 (/show0 "/getting default external format")
1864 (setf external-format (default-external-format)))
1867 (when (or (not character-stream-p) bivalent-stream-p)
1868 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1869 normalized-external-format)
1870 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1874 (error "could not find any input routine for ~S" target-type)))
1875 (when character-stream-p
1876 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1877 normalized-external-format)
1878 (pick-input-routine target-type external-format))
1880 (error "could not find any input routine for ~S" target-type)))
1881 (setf (fd-stream-in fd-stream) cin-routine
1882 (fd-stream-bin fd-stream) bin-routine)
1883 ;; character type gets preferential treatment
1884 (setf input-size (or cin-size bin-size))
1885 (setf input-type (or cin-type bin-type))
1886 (when normalized-external-format
1887 (setf (fd-stream-external-format fd-stream)
1888 normalized-external-format))
1889 (when (= (or cin-size 1) (or bin-size 1) 1)
1890 (setf (fd-stream-n-bin fd-stream) ;XXX
1891 (if (and character-stream-p (not bivalent-stream-p))
1893 #'fd-stream-read-n-bytes))
1894 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1895 ;; for character and (unsigned-byte 8) streams. In these
1896 ;; cases, fast-read-* will read from the
1897 ;; ansi-stream-(c)in-buffer, saving function calls.
1898 ;; Otherwise, the various data-reading functions in the stream
1899 ;; structure will be called.
1901 (not bivalent-stream-p)
1902 ;; temporary disable on :io streams
1904 (cond (character-stream-p
1905 (setf (ansi-stream-cin-buffer fd-stream)
1906 (make-array +ansi-stream-in-buffer-length+
1907 :element-type 'character)))
1908 ((equal target-type '(unsigned-byte 8))
1909 (setf (ansi-stream-in-buffer fd-stream)
1910 (make-array +ansi-stream-in-buffer-length+
1911 :element-type '(unsigned-byte 8))))))))
1914 (when (or (not character-stream-p) bivalent-stream-p)
1915 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1916 normalized-external-format)
1917 (pick-output-routine (if bivalent-stream-p
1920 (fd-stream-buffering fd-stream)
1922 (unless bout-routine
1923 (error "could not find any output routine for ~S buffered ~S"
1924 (fd-stream-buffering fd-stream)
1926 (when character-stream-p
1927 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1928 normalized-external-format)
1929 (pick-output-routine target-type
1930 (fd-stream-buffering fd-stream)
1932 (unless cout-routine
1933 (error "could not find any output routine for ~S buffered ~S"
1934 (fd-stream-buffering fd-stream)
1936 (when normalized-external-format
1937 (setf (fd-stream-external-format fd-stream)
1938 normalized-external-format))
1939 (when character-stream-p
1940 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1941 (setf (fd-stream-out fd-stream) cout-routine
1942 (fd-stream-bout fd-stream) bout-routine
1943 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1944 #'fd-sout #'ill-out))
1945 (setf output-size (or cout-size bout-size))
1946 (setf output-type (or cout-type bout-type)))
1948 (when (and input-size output-size
1949 (not (eq input-size output-size)))
1950 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1951 input-type input-size
1952 output-type output-size))
1953 (setf (fd-stream-element-size fd-stream)
1954 (or input-size output-size))
1956 (setf (fd-stream-element-type fd-stream)
1957 (cond ((equal input-type output-type)
1963 ((subtypep input-type output-type)
1965 ((subtypep output-type input-type)
1968 (error "Input type (~S) and output type (~S) are unrelated?"
1972 ;;; Handles the resource-release aspects of stream closing, and marks
1974 (defun release-fd-stream-resources (fd-stream)
1977 ;; Drop handlers first.
1978 (when (fd-stream-handler fd-stream)
1979 (remove-fd-handler (fd-stream-handler fd-stream))
1980 (setf (fd-stream-handler fd-stream) nil))
1981 ;; Disable interrupts so that a asynch unwind will not leave
1982 ;; us with a dangling finalizer (that would close the same
1983 ;; --possibly reassigned-- FD again), or a stream with a closed
1984 ;; FD that appears open.
1985 (sb!unix:unix-close (fd-stream-fd fd-stream))
1986 (set-closed-flame fd-stream)
1987 (when (fboundp 'cancel-finalization)
1988 (cancel-finalization fd-stream)))
1989 ;; On error unwind from WITHOUT-INTERRUPTS.
1990 (serious-condition (e)
1992 ;; Release all buffers. If this is undone, or interrupted,
1993 ;; we're still safe: buffers have finalizers of their own.
1994 (release-fd-stream-buffers fd-stream))
1996 ;;; Flushes the current input buffer and any supplied replacements,
1997 ;;; and returns the input buffer, and the amount of of flushed input
1999 (defun flush-input-buffer (stream)
2000 (let ((unread (length (fd-stream-instead stream))))
2001 (setf (fill-pointer (fd-stream-instead stream)) 0)
2002 (let ((ibuf (fd-stream-ibuf stream)))
2004 (let ((head (buffer-head ibuf))
2005 (tail (buffer-tail ibuf)))
2006 (values (reset-buffer ibuf) (- (+ unread tail) head)))
2007 (values nil unread)))))
2009 (defun fd-stream-clear-input (stream)
2010 (flush-input-buffer stream)
2013 (sb!win32:fd-clear-input (fd-stream-fd stream))
2014 (setf (fd-stream-listen stream) nil))
2016 (catch 'eof-input-catcher
2017 (loop until (sysread-may-block-p stream)
2019 (refill-input-buffer stream)
2020 (reset-buffer (fd-stream-ibuf stream)))
2023 ;;; Handle miscellaneous operations on FD-STREAM.
2024 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
2025 (declare (ignore arg2))
2028 (labels ((do-listen ()
2029 (let ((ibuf (fd-stream-ibuf fd-stream)))
2030 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
2031 (fd-stream-listen fd-stream)
2033 (sb!win32:fd-listen (fd-stream-fd fd-stream))
2035 ;; If the read can block, LISTEN will certainly return NIL.
2036 (if (sysread-may-block-p fd-stream)
2038 ;; Otherwise select(2) and CL:LISTEN have slightly
2039 ;; different semantics. The former returns that an FD
2040 ;; is readable when a read operation wouldn't block.
2041 ;; That includes EOF. However, LISTEN must return NIL
2043 (progn (catch 'eof-input-catcher
2044 ;; r-b/f too calls select, but it shouldn't
2045 ;; block as long as read can return once w/o
2047 (refill-input-buffer fd-stream))
2048 ;; At this point either IBUF-HEAD != IBUF-TAIL
2049 ;; and FD-STREAM-LISTEN is NIL, in which case
2050 ;; we should return T, or IBUF-HEAD ==
2051 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2052 ;; which case we should return :EOF for this
2053 ;; call and all future LISTEN call on this stream.
2054 ;; Call ourselves again to determine which case
2059 (decf (buffer-head (fd-stream-ibuf fd-stream))
2060 (fd-stream-character-size fd-stream arg1))
2061 (setf (fd-stream-listen fd-stream) t))
2063 ;; Drop input buffers
2064 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
2065 (ansi-stream-cin-buffer fd-stream) nil
2066 (ansi-stream-in-buffer fd-stream) nil)
2068 ;; We got us an abort on our hands.
2069 (let ((outputp (fd-stream-obuf fd-stream))
2070 (file (fd-stream-file fd-stream))
2071 (orig (fd-stream-original fd-stream)))
2072 ;; This takes care of the important stuff -- everything
2073 ;; rest is cleaning up the file-system, which we cannot
2074 ;; do on some platforms as long as the file is open.
2075 (release-fd-stream-resources fd-stream)
2076 ;; We can't do anything unless we know what file were
2077 ;; dealing with, and we don't want to do anything
2078 ;; strange unless we were writing to the file.
2079 (when (and outputp file)
2081 ;; If the original is EQ to file we are appending to
2082 ;; and can just close the file without renaming.
2083 (unless (eq orig file)
2084 ;; We have a handle on the original, just revert.
2085 (multiple-value-bind (okay err)
2086 (sb!unix:unix-rename orig file)
2087 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2088 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2091 (error 'simple-stream-error
2093 "~@<Couldn't restore ~S to its original contents ~
2094 from ~S while closing ~S: ~2I~_~A~:>"
2096 (list file orig fd-stream (strerror err))
2097 :stream fd-stream))))
2098 ;; We can't restore the original, and aren't
2099 ;; appending, so nuke that puppy.
2101 ;; FIXME: This is currently the fate of superseded
2102 ;; files, and according to the CLOSE spec this is
2103 ;; wrong. However, there seems to be no clean way to
2104 ;; do that that doesn't involve either copying the
2105 ;; data (bad if the :abort resulted from a full
2106 ;; disk), or renaming the old file temporarily
2107 ;; (probably bad because stream opening becomes more
2109 (multiple-value-bind (okay err)
2110 (sb!unix:unix-unlink file)
2112 (error 'simple-file-error
2115 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2117 (list file fd-stream (strerror err)))))))))
2119 (finish-fd-stream-output fd-stream)
2120 (let ((orig (fd-stream-original fd-stream)))
2121 (when (and orig (fd-stream-delete-original fd-stream))
2122 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2124 (error 'simple-file-error
2127 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2129 (list orig fd-stream (strerror err)))))))
2130 ;; In case of no-abort close, don't *really* close the
2131 ;; stream until the last moment -- the cleaning up of the
2132 ;; original can be done first.
2133 (release-fd-stream-resources fd-stream))))
2135 (fd-stream-clear-input fd-stream))
2137 (flush-output-buffer fd-stream))
2139 (finish-fd-stream-output fd-stream))
2141 (fd-stream-element-type fd-stream))
2143 (fd-stream-external-format fd-stream))
2145 (= 1 (the (member 0 1)
2146 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2150 (fd-stream-char-pos fd-stream))
2152 (unless (fd-stream-file fd-stream)
2153 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2154 ;; "should signal an error of type TYPE-ERROR if stream is not
2155 ;; a stream associated with a file". Too bad there's no very
2156 ;; appropriate value for the EXPECTED-TYPE slot..
2157 (error 'simple-type-error
2159 :expected-type 'fd-stream
2160 :format-control "~S is not a stream associated with a file."
2161 :format-arguments (list fd-stream)))
2162 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2163 atime mtime ctime blksize blocks)
2164 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2165 (declare (ignore ino nlink uid gid rdev
2166 atime mtime ctime blksize blocks))
2168 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2171 (truncate size (fd-stream-element-size fd-stream)))))
2172 (:file-string-length
2174 (character (fd-stream-character-size fd-stream arg1))
2175 (string (fd-stream-string-size fd-stream arg1))))
2178 (fd-stream-set-file-position fd-stream arg1)
2179 (fd-stream-get-file-position fd-stream)))))
2181 ;; FIXME: Think about this.
2183 ;; (defun finish-fd-stream-output (fd-stream)
2184 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2185 ;; (loop while (fd-stream-output-queue fd-stream)
2186 ;; ;; FIXME: SIGINT while waiting for a timeout will
2187 ;; ;; cause a timeout here.
2188 ;; do (when (and (not (serve-event timeout)) timeout)
2189 ;; (signal-timeout 'io-timeout
2190 ;; :stream fd-stream
2191 ;; :direction :write
2192 ;; :seconds timeout)))))
2194 (defun finish-fd-stream-output (stream)
2195 (flush-output-buffer stream)
2197 ((null (fd-stream-output-queue stream)))
2198 (serve-all-events)))
2200 (defun fd-stream-get-file-position (stream)
2201 (declare (fd-stream stream))
2203 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2204 (declare (type (or (alien sb!unix:off-t) null) posn))
2205 ;; We used to return NIL for errno==ESPIPE, and signal an error
2206 ;; in other failure cases. However, CLHS says to return NIL if
2207 ;; the position cannot be determined -- so that's what we do.
2208 (when (integerp posn)
2209 ;; Adjust for buffered output: If there is any output
2210 ;; buffered, the *real* file position will be larger
2211 ;; than reported by lseek() because lseek() obviously
2212 ;; cannot take into account output we have not sent
2214 (dolist (buffer (fd-stream-output-queue stream))
2215 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2216 (let ((obuf (fd-stream-obuf stream)))
2218 (incf posn (buffer-tail obuf))))
2219 ;; Adjust for unread input: If there is any input
2220 ;; read from UNIX but not supplied to the user of the
2221 ;; stream, the *real* file position will smaller than
2222 ;; reported, because we want to look like the unread
2223 ;; stuff is still available.
2224 (let ((ibuf (fd-stream-ibuf stream)))
2226 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2227 ;; Divide bytes by element size.
2228 (truncate posn (fd-stream-element-size stream))))))
2230 (defun fd-stream-set-file-position (stream position-spec)
2231 (declare (fd-stream stream))
2232 (check-type position-spec
2233 (or (alien sb!unix:off-t) (member nil :start :end))
2234 "valid file position designator")
2237 ;; Make sure we don't have any output pending, because if we
2238 ;; move the file pointer before writing this stuff, it will be
2239 ;; written in the wrong location.
2240 (finish-fd-stream-output stream)
2241 ;; Disable interrupts so that interrupt handlers doing output
2244 (unless (fd-stream-output-finished-p stream)
2245 ;; We got interrupted and more output came our way during
2246 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2247 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2248 ;; so we prefer to do things like this...
2250 ;; Clear out any pending input to force the next read to go to
2252 (flush-input-buffer stream)
2253 ;; Trash cached value for listen, so that we check next time.
2254 (setf (fd-stream-listen stream) nil)
2256 (multiple-value-bind (offset origin)
2259 (values 0 sb!unix:l_set))
2261 (values 0 sb!unix:l_xtnd))
2263 (values (* position-spec (fd-stream-element-size stream))
2265 (declare (type (alien sb!unix:off-t) offset))
2266 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2268 ;; CLHS says to return true if the file-position was set
2269 ;; succesfully, and NIL otherwise. We are to signal an error
2270 ;; only if the given position was out of bounds, and that is
2271 ;; dealt with above. In times past we used to return NIL for
2272 ;; errno==ESPIPE, and signal an error in other cases.
2274 ;; FIXME: We are still liable to signal an error if flushing
2276 (return-from fd-stream-set-file-position
2277 (typep posn '(alien sb!unix:off-t))))))))
2280 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2282 ;;; Create a stream for the given Unix file descriptor.
2284 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2285 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2286 ;;; default to allowing input.
2288 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2290 ;;; BUFFERING indicates the kind of buffering to use.
2292 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2293 ;;; NIL (the default), then wait forever. When we time out, we signal
2296 ;;; FILE is the name of the file (will be returned by PATHNAME).
2298 ;;; NAME is used to identify the stream when printed.
2299 (defun make-fd-stream (fd
2302 (output nil output-p)
2303 (element-type 'base-char)
2305 (external-format :default)
2314 (format nil "file ~A" file)
2315 (format nil "descriptor ~W" fd)))
2317 (declare (type index fd) (type (or real null) timeout)
2318 (type (member :none :line :full) buffering))
2319 (cond ((not (or input-p output-p))
2321 ((not (or input output))
2322 (error "File descriptor must be opened either for input or output.")))
2323 (let ((stream (%make-fd-stream :fd fd
2327 :delete-original delete-original
2329 :buffering buffering
2330 :dual-channel-p dual-channel-p
2331 :external-format external-format
2332 :bivalent-p (eq element-type :default)
2333 :char-size (external-format-char-size external-format)
2336 (coerce timeout 'single-float)
2338 (set-fd-stream-routines stream element-type external-format
2339 input output input-buffer-p)
2340 (when (and auto-close (fboundp 'finalize))
2343 (sb!unix:unix-close fd)
2345 (format *terminal-io* "** closed file descriptor ~W **~%"
2350 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2351 ;;; :RENAME-AND-DELETE and :RENAME options.
2352 (defun pick-backup-name (name)
2353 (declare (type simple-string name))
2354 (concatenate 'simple-string name ".bak"))
2356 ;;; Ensure that the given arg is one of the given list of valid
2357 ;;; things. Allow the user to fix any problems.
2358 (defun ensure-one-of (item list what)
2359 (unless (member item list)
2360 (error 'simple-type-error
2362 :expected-type `(member ,@list)
2363 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2364 :format-arguments (list item what list))))
2366 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2367 ;;; access, since we don't want to trash unwritable files even if we
2368 ;;; technically can. We return true if we succeed in renaming.
2369 (defun rename-the-old-one (namestring original)
2370 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2371 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2372 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2375 (error 'simple-file-error
2376 :pathname namestring
2378 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2379 :format-arguments (list namestring original (strerror err))))))
2381 (defun open (filename
2384 (element-type 'base-char)
2385 (if-exists nil if-exists-given)
2386 (if-does-not-exist nil if-does-not-exist-given)
2387 (external-format :default)
2388 &aux ; Squelch assignment warning.
2389 (direction direction)
2390 (if-does-not-exist if-does-not-exist)
2391 (if-exists if-exists))
2393 "Return a stream which reads from or writes to FILENAME.
2395 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2396 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2397 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2398 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2399 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2400 See the manual for details."
2402 ;; Calculate useful stuff.
2403 (multiple-value-bind (input output mask)
2405 (:input (values t nil sb!unix:o_rdonly))
2406 (:output (values nil t sb!unix:o_wronly))
2407 (:io (values t t sb!unix:o_rdwr))
2408 (:probe (values t nil sb!unix:o_rdonly)))
2409 (declare (type index mask))
2410 (let* (;; PATHNAME is the pathname we associate with the stream.
2411 (pathname (merge-pathnames filename))
2412 (physical (physicalize-pathname pathname))
2413 (truename (probe-file physical))
2414 ;; NAMESTRING is the native namestring we open the file with.
2415 (namestring (cond (truename
2416 (native-namestring truename :as-file t))
2418 (and input (eq if-does-not-exist :create))
2419 (and (eq direction :io) (not if-does-not-exist-given)))
2420 (native-namestring physical :as-file t)))))
2421 ;; Process if-exists argument if we are doing any output.
2423 (unless if-exists-given
2425 (if (eq (pathname-version pathname) :newest)
2428 (ensure-one-of if-exists
2429 '(:error :new-version :rename
2430 :rename-and-delete :overwrite
2431 :append :supersede nil)
2434 ((:new-version :error nil)
2435 (setf mask (logior mask sb!unix:o_excl)))
2436 ((:rename :rename-and-delete)
2437 (setf mask (logior mask sb!unix:o_creat)))
2439 (setf mask (logior mask sb!unix:o_trunc)))
2441 (setf mask (logior mask sb!unix:o_append)))))
2443 (setf if-exists :ignore-this-arg)))
2445 (unless if-does-not-exist-given
2446 (setf if-does-not-exist
2447 (cond ((eq direction :input) :error)
2449 (member if-exists '(:overwrite :append)))
2451 ((eq direction :probe)
2455 (ensure-one-of if-does-not-exist
2456 '(:error :create nil)
2458 (if (eq if-does-not-exist :create)
2459 (setf mask (logior mask sb!unix:o_creat)))
2461 (let ((original (case if-exists
2462 ((:rename :rename-and-delete)
2463 (pick-backup-name namestring))
2464 ((:append :overwrite)
2465 ;; KLUDGE: Provent CLOSE from deleting
2466 ;; appending streams when called with :ABORT T
2468 (delete-original (eq if-exists :rename-and-delete))
2470 (when (and original (not (eq original namestring)))
2471 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2472 ;; whether the file already exists, make sure the original
2473 ;; file is not a directory, and keep the mode.
2476 (multiple-value-bind (okay err/dev inode orig-mode)
2477 (sb!unix:unix-stat namestring)
2478 (declare (ignore inode)
2479 (type (or index null) orig-mode))
2482 (when (and output (= (logand orig-mode #o170000)
2484 (error 'simple-file-error
2487 "can't open ~S for output: is a directory"
2488 :format-arguments (list namestring)))
2489 (setf mode (logand orig-mode #o777))
2491 ((eql err/dev sb!unix:enoent)
2494 (simple-file-perror "can't find ~S"
2498 (rename-the-old-one namestring original))
2500 (setf delete-original nil)
2501 ;; In order to use :SUPERSEDE instead, we have to make
2502 ;; sure SB!UNIX:O_CREAT corresponds to
2503 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2504 ;; because of IF-EXISTS being :RENAME.
2505 (unless (eq if-does-not-exist :create)
2507 (logior (logandc2 mask sb!unix:o_creat)
2509 (setf if-exists :supersede))))
2511 ;; Now we can try the actual Unix open(2).
2512 (multiple-value-bind (fd errno)
2514 (sb!unix:unix-open namestring mask mode)
2515 (values nil sb!unix:enoent))
2516 (labels ((open-error (format-control &rest format-arguments)
2517 (error 'simple-file-error
2519 :format-control format-control
2520 :format-arguments format-arguments))
2521 (vanilla-open-error ()
2522 (simple-file-perror "error opening ~S" pathname errno)))
2525 ((:input :output :io)
2529 :element-type element-type
2530 :external-format external-format
2533 :delete-original delete-original
2540 (%make-fd-stream :name namestring
2543 :element-type element-type)))
2546 ((eql errno sb!unix:enoent)
2547 (case if-does-not-exist
2548 (:error (vanilla-open-error))
2550 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2553 ((and (eql errno sb!unix:eexist) (null if-exists))
2556 (vanilla-open-error)))))))))
2560 ;;; the stream connected to the controlling terminal, or NIL if there is none
2563 ;;; the stream connected to the standard input (file descriptor 0)
2566 ;;; the stream connected to the standard output (file descriptor 1)
2569 ;;; the stream connected to the standard error output (file descriptor 2)
2572 ;;; This is called when the cold load is first started up, and may also
2573 ;;; be called in an attempt to recover from nested errors.
2574 (defun stream-cold-init-or-reset ()
2576 (setf *terminal-io* (make-synonym-stream '*tty*))
2577 (setf *standard-output* (make-synonym-stream '*stdout*))
2578 (setf *standard-input* (make-synonym-stream '*stdin*))
2579 (setf *error-output* (make-synonym-stream '*stderr*))
2580 (setf *query-io* (make-synonym-stream '*terminal-io*))
2581 (setf *debug-io* *query-io*)
2582 (setf *trace-output* *standard-output*)
2585 (defun stream-deinit ()
2586 ;; Unbind to make sure we're not accidently dealing with it
2587 ;; before we're ready (or after we think it's been deinitialized).
2588 (with-available-buffers-lock ()
2589 (without-package-locks
2590 (makunbound '*available-buffers*))))
2592 ;;; This is called whenever a saved core is restarted.
2593 (defun stream-reinit (&optional init-buffers-p)
2594 (when init-buffers-p
2595 (with-available-buffers-lock ()
2596 (aver (not (boundp '*available-buffers*)))
2597 (setf *available-buffers* nil)))
2598 (with-output-to-string (*error-output*)
2600 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2601 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2603 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2604 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2606 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2607 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2608 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2609 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2613 :name "the terminal"
2618 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2619 (princ (get-output-stream-string *error-output*) *stderr*))
2624 ;;; the Unix way to beep
2625 (defun beep (stream)
2626 (write-char (code-char bell-char-code) stream)
2627 (finish-output stream))
2629 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2630 ;;; by the filesys stuff to get and set the file name.
2632 ;;; FIXME: misleading name, screwy interface
2633 (defun file-name (stream &optional new-name)
2634 (when (typep stream 'fd-stream)
2636 (setf (fd-stream-pathname stream) new-name)
2637 (setf (fd-stream-file stream)
2638 (native-namestring (physicalize-pathname new-name)
2642 (fd-stream-pathname stream)))))