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 synchronize-stream-output (stream)
509 ;; If we're reading and writing on the same file, flush buffered
510 ;; input and rewind file position accordingly.
511 (unless (fd-stream-dual-channel-p stream)
512 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
513 (unless (eql 0 adjust)
514 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
516 (defun fd-stream-output-finished-p (stream)
517 (let ((obuf (fd-stream-obuf stream)))
519 (and (zerop (buffer-tail obuf))
520 (not (fd-stream-output-queue stream))))))
522 (defmacro output-wrapper/variable-width ((stream size buffering restart)
524 (let ((stream-var (gensym "STREAM")))
525 `(let* ((,stream-var ,stream)
526 (obuf (fd-stream-obuf ,stream-var))
527 (tail (buffer-tail obuf))
529 ,(unless (eq (car buffering) :none)
530 `(when (<= (buffer-length obuf) (+ tail size))
531 (setf obuf (flush-output-buffer ,stream-var)
532 tail (buffer-tail obuf))))
533 ,(unless (eq (car buffering) :none)
534 ;; FIXME: Why this here? Doesn't seem necessary.
535 `(synchronize-stream-output ,stream-var))
537 `(catch 'output-nothing
539 (setf (buffer-tail obuf) (+ tail size)))
542 (setf (buffer-tail obuf) (+ tail size))))
543 ,(ecase (car buffering)
545 `(flush-output-buffer ,stream-var))
547 `(when (eql byte #\Newline)
548 (flush-output-buffer ,stream-var)))
552 (defmacro output-wrapper ((stream size buffering restart) &body body)
553 (let ((stream-var (gensym "STREAM")))
554 `(let* ((,stream-var ,stream)
555 (obuf (fd-stream-obuf ,stream-var))
556 (tail (buffer-tail obuf)))
557 ,(unless (eq (car buffering) :none)
558 `(when (<= (buffer-length obuf) (+ tail ,size))
559 (setf obuf (flush-output-buffer ,stream-var)
560 tail (buffer-tail obuf))))
561 ;; FIXME: Why this here? Doesn't seem necessary.
562 ,(unless (eq (car buffering) :none)
563 `(synchronize-stream-output ,stream-var))
565 `(catch 'output-nothing
567 (setf (buffer-tail obuf) (+ tail ,size)))
570 (setf (buffer-tail obuf) (+ tail ,size))))
571 ,(ecase (car buffering)
573 `(flush-output-buffer ,stream-var))
575 `(when (eql byte #\Newline)
576 (flush-output-buffer ,stream-var)))
580 (defmacro def-output-routines/variable-width
581 ((name-fmt size restart external-format &rest bufferings)
583 (declare (optimize (speed 1)))
588 (intern (format nil name-fmt (string (car buffering))))))
590 (defun ,function (stream byte)
591 (declare (ignorable byte))
592 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
594 (setf *output-routines*
595 (nconc *output-routines*
603 (cdr buffering)))))))
606 ;;; Define output routines that output numbers SIZE bytes long for the
607 ;;; given bufferings. Use BODY to do the actual output.
608 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
610 (declare (optimize (speed 1)))
615 (intern (format nil name-fmt (string (car buffering))))))
617 (defun ,function (stream byte)
618 (output-wrapper (stream ,size ,buffering ,restart)
620 (setf *output-routines*
621 (nconc *output-routines*
629 (cdr buffering)))))))
632 ;;; FIXME: is this used anywhere any more?
633 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
639 (if (eql byte #\Newline)
640 (setf (fd-stream-char-pos stream) 0)
641 (incf (fd-stream-char-pos stream)))
642 (setf (sap-ref-8 (buffer-sap obuf) tail)
645 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
648 (:none (unsigned-byte 8))
649 (:full (unsigned-byte 8)))
650 (setf (sap-ref-8 (buffer-sap obuf) tail)
653 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
656 (:none (signed-byte 8))
657 (:full (signed-byte 8)))
658 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
661 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
664 (:none (unsigned-byte 16))
665 (:full (unsigned-byte 16)))
666 (setf (sap-ref-16 (buffer-sap obuf) tail)
669 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
672 (:none (signed-byte 16))
673 (:full (signed-byte 16)))
674 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
677 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
680 (:none (unsigned-byte 32))
681 (:full (unsigned-byte 32)))
682 (setf (sap-ref-32 (buffer-sap obuf) tail)
685 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
688 (:none (signed-byte 32))
689 (:full (signed-byte 32)))
690 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
693 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
695 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
698 (:none (unsigned-byte 64))
699 (:full (unsigned-byte 64)))
700 (setf (sap-ref-64 (buffer-sap obuf) tail)
702 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
705 (:none (signed-byte 64))
706 (:full (signed-byte 64)))
707 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
710 ;;; the routine to use to output a string. If the stream is
711 ;;; unbuffered, slam the string down the file descriptor, otherwise
712 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
713 ;;; checking to see where the last newline was.
714 (defun fd-sout (stream thing start end)
715 (declare (type fd-stream stream) (type string thing))
716 (let ((start (or start 0))
717 (end (or end (length (the vector thing)))))
718 (declare (fixnum start end))
720 (string-dispatch (simple-base-string
722 (simple-array character (*))
725 (position #\newline thing :from-end t
726 :start start :end end))))
727 (if (and (typep thing 'base-string)
728 (eq (fd-stream-external-format-keyword stream) :latin-1))
729 (ecase (fd-stream-buffering stream)
731 (buffer-output stream thing start end))
733 (buffer-output stream thing start end)
735 (flush-output-buffer stream)))
737 (write-or-buffer-output stream thing start end)))
738 (ecase (fd-stream-buffering stream)
739 (:full (funcall (fd-stream-output-bytes stream)
740 stream thing nil start end))
741 (:line (funcall (fd-stream-output-bytes stream)
742 stream thing last-newline start end))
743 (:none (funcall (fd-stream-output-bytes stream)
744 stream thing t start end))))
746 (setf (fd-stream-char-pos stream) (- end last-newline 1))
747 (incf (fd-stream-char-pos stream) (- end start))))))
749 (defstruct (external-format
750 (:constructor %make-external-format)
752 (:predicate external-format-p)
753 (:copier %copy-external-format))
754 ;; All the names that can refer to this external format. The first
755 ;; one is the canonical name.
756 (names (missing-arg) :type list :read-only t)
757 (default-replacement-character (missing-arg) :type character)
758 (read-n-chars-fun (missing-arg) :type function)
759 (read-char-fun (missing-arg) :type function)
760 (write-n-bytes-fun (missing-arg) :type function)
761 (write-char-none-buffered-fun (missing-arg) :type function)
762 (write-char-line-buffered-fun (missing-arg) :type function)
763 (write-char-full-buffered-fun (missing-arg) :type function)
764 ;; Can be nil for fixed-width formats.
765 (resync-fun nil :type (or function null))
766 (bytes-for-char-fun (missing-arg) :type function)
767 (read-c-string-fun (missing-arg) :type function)
768 (write-c-string-fun (missing-arg) :type function)
769 ;; We indirect through symbols in these functions so that a
770 ;; developer working on the octets code can easily redefine things
771 ;; and use the new function definition without redefining the
772 ;; external format as well. The slots above don't do any
773 ;; indirection because a developer working with those slots would be
774 ;; redefining the external format anyway.
775 (octets-to-string-fun (missing-arg) :type function)
776 (string-to-octets-fun (missing-arg) :type function))
778 (defun wrap-external-format-functions (external-format fun)
779 (let ((result (%copy-external-format external-format)))
780 (macrolet ((frob (accessor)
781 `(setf (,accessor result) (funcall fun (,accessor result)))))
782 (frob ef-read-n-chars-fun)
783 (frob ef-read-char-fun)
784 (frob ef-write-n-bytes-fun)
785 (frob ef-write-char-none-buffered-fun)
786 (frob ef-write-char-line-buffered-fun)
787 (frob ef-write-char-full-buffered-fun)
789 (frob ef-bytes-for-char-fun)
790 (frob ef-read-c-string-fun)
791 (frob ef-write-c-string-fun)
792 (frob ef-octets-to-string-fun)
793 (frob ef-string-to-octets-fun))
796 (defvar *external-formats* (make-hash-table)
798 "Hashtable of all available external formats. The table maps from
799 external-format names to EXTERNAL-FORMAT structures.")
801 (defun get-external-format (external-format)
802 (flet ((keyword-external-format (keyword)
803 (declare (type keyword keyword))
804 (gethash keyword *external-formats*))
805 (replacement-handlerify (entry replacement)
807 (wrap-external-format-functions
812 (declare (dynamic-extent rest))
814 ((stream-decoding-error
817 (invoke-restart 'input-replacement replacement)))
818 (stream-encoding-error
821 (invoke-restart 'output-replacement replacement)))
822 (octets-encoding-error
823 (lambda (c) (use-value replacement c)))
824 (octet-decoding-error
825 (lambda (c) (use-value replacement c))))
826 (apply fun rest)))))))))
827 (typecase external-format
828 (keyword (keyword-external-format external-format))
830 (let ((entry (keyword-external-format (car external-format)))
831 (replacement (getf (cdr external-format) :replacement)))
833 (replacement-handlerify entry replacement)
836 (defun get-external-format-or-lose (external-format)
837 (or (get-external-format external-format)
838 (error "Undefined external-format ~A" external-format)))
840 (defun external-format-keyword (external-format)
841 (typecase external-format
842 (keyword external-format)
843 ((cons keyword) (car external-format))))
845 (defun fd-stream-external-format-keyword (stream)
846 (external-format-keyword (fd-stream-external-format stream)))
848 (defun canonize-external-format (external-format entry)
849 (typecase external-format
850 (keyword (first (ef-names entry)))
851 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
853 ;;; Find an output routine to use given the type and buffering. Return
854 ;;; as multiple values the routine, the real type transfered, and the
855 ;;; number of bytes per element.
856 (defun pick-output-routine (type buffering &optional external-format)
857 (when (subtypep type 'character)
858 (let ((entry (get-external-format external-format)))
860 (return-from pick-output-routine
861 (values (ecase buffering
862 (:none (ef-write-char-none-buffered-fun entry))
863 (:line (ef-write-char-line-buffered-fun entry))
864 (:full (ef-write-char-full-buffered-fun entry)))
867 (ef-write-n-bytes-fun entry)
868 (canonize-external-format external-format entry))))))
869 (dolist (entry *output-routines*)
870 (when (and (subtypep type (first entry))
871 (eq buffering (second entry))
872 (or (not (fifth entry))
873 (eq external-format (fifth entry))))
874 (return-from pick-output-routine
875 (values (symbol-function (third entry))
878 ;; KLUDGE: dealing with the buffering here leads to excessive code
881 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
882 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
883 if (subtypep type `(unsigned-byte ,i))
884 do (return-from pick-output-routine
888 (lambda (stream byte)
889 (output-wrapper (stream (/ i 8) (:none) nil)
890 (loop for j from 0 below (/ i 8)
891 do (setf (sap-ref-8 (buffer-sap obuf)
893 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
895 (lambda (stream byte)
896 (output-wrapper (stream (/ i 8) (:full) nil)
897 (loop for j from 0 below (/ i 8)
898 do (setf (sap-ref-8 (buffer-sap obuf)
900 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
903 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
904 if (subtypep type `(signed-byte ,i))
905 do (return-from pick-output-routine
909 (lambda (stream byte)
910 (output-wrapper (stream (/ i 8) (:none) nil)
911 (loop for j from 0 below (/ i 8)
912 do (setf (sap-ref-8 (buffer-sap obuf)
914 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
916 (lambda (stream byte)
917 (output-wrapper (stream (/ i 8) (:full) nil)
918 (loop for j from 0 below (/ i 8)
919 do (setf (sap-ref-8 (buffer-sap obuf)
921 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
925 ;;;; input routines and related noise
927 ;;; a list of all available input routines. Each element is a list of
928 ;;; the element-type input, the function name, and the number of bytes
930 (defvar *input-routines* ())
932 ;;; Return whether a primitive partial read operation on STREAM's FD
933 ;;; would (probably) block. Signal a `simple-stream-error' if the
934 ;;; system call implementing this operation fails.
936 ;;; It is "may" instead of "would" because "would" is not quite
937 ;;; correct on win32. However, none of the places that use it require
938 ;;; further assurance than "may" versus "will definitely not".
939 (defun sysread-may-block-p (stream)
941 ;; This answers T at EOF on win32, I think.
942 (not (sb!win32:fd-listen (fd-stream-fd stream)))
944 (sb!unix:with-restarted-syscall (count errno)
945 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
946 (sb!unix:fd-zero read-fds)
947 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
948 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
949 (sb!alien:addr read-fds)
955 (simple-stream-perror "couldn't check whether ~S is readable"
959 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
960 ;;; then fill the input buffer, and return the number of bytes read. Throws
961 ;;; to EOF-INPUT-CATCHER if the eof was reached.
962 (defun refill-input-buffer (stream)
963 (dx-let ((fd (fd-stream-fd stream))
967 ;; Check for blocking input before touching the stream, as if
968 ;; we happen to wait we are liable to be interrupted, and the
969 ;; interrupt handler may use the same stream.
970 (if (sysread-may-block-p stream)
973 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
974 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
976 (closed-flame stream)
978 (simple-stream-perror "couldn't read from ~S" stream errno)
980 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
981 ;; to wait for input if read tells us EWOULDBLOCK.
982 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
983 (signal-timeout 'io-timeout :stream stream :direction :read
984 :seconds (fd-stream-timeout stream)))
986 ;; Since the read should not block, we'll disable the
987 ;; interrupts here, so that we don't accidentally unwind and
988 ;; leave the stream in an inconsistent state.
990 ;; Execute the nlx outside without-interrupts to ensure the
991 ;; resulting thunk is stack-allocatable.
992 ((lambda (return-reason)
994 ((nil)) ; fast path normal cases
995 ((:wait-for-input) (go :wait-for-input))
996 ((:closed-flame) (go :closed-flame))
997 ((:read-error) (go :read-error))))
999 ;; Check the buffer: if it is null, then someone has closed
1000 ;; the stream from underneath us. This is not ment to fix
1001 ;; multithreaded races, but to deal with interrupt handlers
1002 ;; closing the stream.
1005 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1006 (sap (buffer-sap ibuf))
1007 (length (buffer-length ibuf))
1008 (head (buffer-head ibuf))
1009 (tail (buffer-tail ibuf)))
1010 (declare (index length head tail)
1011 (inline sb!unix:unix-read))
1012 (unless (zerop head)
1013 (cond ((eql head tail)
1014 ;; Buffer is empty, but not at yet reset -- make it so.
1017 (reset-buffer ibuf))
1019 ;; Buffer has things in it, but they are not at the
1020 ;; head -- move them there.
1021 (let ((n (- tail head)))
1022 (system-area-ub8-copy sap head sap 0 n)
1024 (buffer-head ibuf) head
1026 (buffer-tail ibuf) tail)))))
1027 (setf (fd-stream-listen stream) nil)
1028 (setf (values count errno)
1029 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1032 (return :read-error)
1034 (if (eql errno sb!unix:ewouldblock)
1035 (return :wait-for-input)
1036 (return :read-error)))
1038 (setf (fd-stream-listen stream) :eof)
1039 (/show0 "THROWing EOF-INPUT-CATCHER")
1040 (throw 'eof-input-catcher nil))
1042 ;; Success! (Do not use INCF, for sake of other threads.)
1043 (setf (buffer-tail ibuf) (+ count tail))))))))))
1046 ;;; Make sure there are at least BYTES number of bytes in the input
1047 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1048 (defmacro input-at-least (stream bytes)
1049 (let ((stream-var (gensym "STREAM"))
1050 (bytes-var (gensym "BYTES"))
1051 (buffer-var (gensym "IBUF")))
1052 `(let* ((,stream-var ,stream)
1054 (,buffer-var (fd-stream-ibuf ,stream-var)))
1056 (when (>= (- (buffer-tail ,buffer-var)
1057 (buffer-head ,buffer-var))
1060 (refill-input-buffer ,stream-var)))))
1062 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1064 (let ((stream-var (gensym "STREAM"))
1065 (retry-var (gensym "RETRY"))
1066 (element-var (gensym "ELT")))
1067 `(let* ((,stream-var ,stream)
1068 (ibuf (fd-stream-ibuf ,stream-var))
1071 (when (fd-stream-eof-forced-p ,stream-var)
1072 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1073 (return-from use-instead
1074 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1075 (let ((,element-var nil)
1076 (decode-break-reason nil))
1077 (do ((,retry-var t))
1079 (if (> (length (fd-stream-instead ,stream-var)) 0)
1080 (let* ((instead (fd-stream-instead ,stream-var))
1081 (result (vector-pop instead))
1082 (pointer (fill-pointer instead)))
1084 (setf (fd-stream-listen ,stream-var) nil))
1085 (return-from use-instead result))
1087 (catch 'eof-input-catcher
1088 (setf decode-break-reason
1089 (block decode-break-reason
1090 (input-at-least ,stream-var ,(if (consp bytes) (car bytes) `(setq size ,bytes)))
1091 (let* ((byte (sap-ref-8 (buffer-sap ibuf) (buffer-head ibuf))))
1092 (declare (ignorable byte))
1093 ,@(when (consp bytes)
1094 `((let ((sap (buffer-sap ibuf))
1095 (head (buffer-head ibuf)))
1096 (declare (ignorable sap head))
1097 (setq size ,(cadr bytes))
1098 (input-at-least ,stream-var size))))
1099 (setq ,element-var (locally ,@read-forms))
1100 (setq ,retry-var nil))
1102 (when decode-break-reason
1103 (when (stream-decoding-error-and-handle
1104 stream decode-break-reason)
1105 (setq ,retry-var nil)
1106 (throw 'eof-input-catcher nil)))
1108 (let ((octet-count (- (buffer-tail ibuf)
1109 (buffer-head ibuf))))
1110 (when (or (zerop octet-count)
1111 (and (not ,element-var)
1112 (not decode-break-reason)
1113 (stream-decoding-error-and-handle
1114 stream octet-count)))
1115 (setq ,retry-var nil))))))
1117 (incf (buffer-head ibuf) size)
1120 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1122 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1123 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1124 (let ((stream-var (gensym "STREAM"))
1125 (element-var (gensym "ELT")))
1126 `(let* ((,stream-var ,stream)
1127 (ibuf (fd-stream-ibuf ,stream-var)))
1128 (if (> (length (fd-stream-instead ,stream-var)) 0)
1129 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1131 (catch 'eof-input-catcher
1132 (input-at-least ,stream-var ,bytes)
1133 (locally ,@read-forms))))
1135 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1138 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1140 (defmacro def-input-routine/variable-width (name
1141 (type external-format size sap head)
1144 (defun ,name (stream eof-error eof-value)
1145 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1146 (let ((,sap (buffer-sap ibuf))
1147 (,head (buffer-head ibuf)))
1149 (setf *input-routines*
1150 (nconc *input-routines*
1151 (list (list ',type ',name 1 ',external-format))))))
1153 (defmacro def-input-routine (name
1154 (type size sap head)
1157 (defun ,name (stream eof-error eof-value)
1158 (input-wrapper (stream ,size eof-error eof-value)
1159 (let ((,sap (buffer-sap ibuf))
1160 (,head (buffer-head ibuf)))
1162 (setf *input-routines*
1163 (nconc *input-routines*
1164 (list (list ',type ',name ',size nil))))))
1166 ;;; STREAM-IN routine for reading a string char
1167 (def-input-routine input-character
1168 (character 1 sap head)
1169 (code-char (sap-ref-8 sap head)))
1171 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1172 (def-input-routine input-unsigned-8bit-byte
1173 ((unsigned-byte 8) 1 sap head)
1174 (sap-ref-8 sap head))
1176 ;;; STREAM-IN routine for reading a signed 8 bit number
1177 (def-input-routine input-signed-8bit-number
1178 ((signed-byte 8) 1 sap head)
1179 (signed-sap-ref-8 sap head))
1181 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1182 (def-input-routine input-unsigned-16bit-byte
1183 ((unsigned-byte 16) 2 sap head)
1184 (sap-ref-16 sap head))
1186 ;;; STREAM-IN routine for reading a signed 16 bit number
1187 (def-input-routine input-signed-16bit-byte
1188 ((signed-byte 16) 2 sap head)
1189 (signed-sap-ref-16 sap head))
1191 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1192 (def-input-routine input-unsigned-32bit-byte
1193 ((unsigned-byte 32) 4 sap head)
1194 (sap-ref-32 sap head))
1196 ;;; STREAM-IN routine for reading a signed 32 bit number
1197 (def-input-routine input-signed-32bit-byte
1198 ((signed-byte 32) 4 sap head)
1199 (signed-sap-ref-32 sap head))
1201 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1203 (def-input-routine input-unsigned-64bit-byte
1204 ((unsigned-byte 64) 8 sap head)
1205 (sap-ref-64 sap head))
1206 (def-input-routine input-signed-64bit-byte
1207 ((signed-byte 64) 8 sap head)
1208 (signed-sap-ref-64 sap head)))
1210 ;;; Find an input routine to use given the type. Return as multiple
1211 ;;; values the routine, the real type transfered, and the number of
1212 ;;; bytes per element (and for character types string input routine).
1213 (defun pick-input-routine (type &optional external-format)
1214 (when (subtypep type 'character)
1215 (let ((entry (get-external-format external-format)))
1217 (return-from pick-input-routine
1218 (values (ef-read-char-fun entry)
1221 (ef-read-n-chars-fun entry)
1222 (canonize-external-format external-format entry))))))
1223 (dolist (entry *input-routines*)
1224 (when (and (subtypep type (first entry))
1225 (or (not (fourth entry))
1226 (eq external-format (fourth entry))))
1227 (return-from pick-input-routine
1228 (values (symbol-function (second entry))
1231 ;; FIXME: let's do it the hard way, then (but ignore things like
1232 ;; endianness, efficiency, and the necessary coupling between these
1233 ;; and the output routines). -- CSR, 2004-02-09
1234 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1235 if (subtypep type `(unsigned-byte ,i))
1236 do (return-from pick-input-routine
1238 (lambda (stream eof-error eof-value)
1239 (input-wrapper (stream (/ i 8) eof-error eof-value)
1240 (let ((sap (buffer-sap ibuf))
1241 (head (buffer-head ibuf)))
1242 (loop for j from 0 below (/ i 8)
1246 (sap-ref-8 sap (+ head j))))
1247 finally (return result)))))
1250 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1251 if (subtypep type `(signed-byte ,i))
1252 do (return-from pick-input-routine
1254 (lambda (stream eof-error eof-value)
1255 (input-wrapper (stream (/ i 8) eof-error eof-value)
1256 (let ((sap (buffer-sap ibuf))
1257 (head (buffer-head ibuf)))
1258 (loop for j from 0 below (/ i 8)
1262 (sap-ref-8 sap (+ head j))))
1263 finally (return (if (logbitp (1- i) result)
1264 (dpb result (byte i 0) -1)
1269 ;;; the N-BIN method for FD-STREAMs
1271 ;;; Note that this blocks in UNIX-READ. It is generally used where
1272 ;;; there is a definite amount of reading to be done, so blocking
1273 ;;; isn't too problematical.
1274 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1275 &aux (total-copied 0))
1276 (declare (type fd-stream stream))
1277 (declare (type index start requested total-copied))
1278 (aver (= (length (fd-stream-instead stream)) 0))
1281 (let* ((remaining-request (- requested total-copied))
1282 (ibuf (fd-stream-ibuf stream))
1283 (head (buffer-head ibuf))
1284 (tail (buffer-tail ibuf))
1285 (available (- tail head))
1286 (n-this-copy (min remaining-request available))
1287 (this-start (+ start total-copied))
1288 (this-end (+ this-start n-this-copy))
1289 (sap (buffer-sap ibuf)))
1290 (declare (type index remaining-request head tail available))
1291 (declare (type index n-this-copy))
1292 ;; Copy data from stream buffer into user's buffer.
1293 (%byte-blt sap head buffer this-start this-end)
1294 (incf (buffer-head ibuf) n-this-copy)
1295 (incf total-copied n-this-copy)
1296 ;; Maybe we need to refill the stream buffer.
1297 (cond (;; If there were enough data in the stream buffer, we're done.
1298 (eql total-copied requested)
1299 (return total-copied))
1300 (;; If EOF, we're done in another way.
1301 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1303 (error 'end-of-file :stream stream)
1304 (return total-copied)))
1305 ;; Otherwise we refilled the stream buffer, so fall
1306 ;; through into another pass of the loop.
1309 (defun fd-stream-resync (stream)
1310 (let ((entry (get-external-format (fd-stream-external-format stream))))
1312 (funcall (ef-resync-fun entry) stream))))
1314 (defun get-fd-stream-character-sizer (stream)
1315 (let ((entry (get-external-format (fd-stream-external-format stream))))
1317 (ef-bytes-for-char-fun entry))))
1319 (defun fd-stream-character-size (stream char)
1320 (let ((sizer (get-fd-stream-character-sizer stream)))
1321 (when sizer (funcall sizer char))))
1323 (defun fd-stream-string-size (stream string)
1324 (let ((sizer (get-fd-stream-character-sizer stream)))
1326 (loop for char across string summing (funcall sizer char)))))
1328 (defun find-external-format (external-format)
1329 (when external-format
1330 (get-external-format external-format)))
1332 (defun variable-width-external-format-p (ef-entry)
1333 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1335 (defun bytes-for-char-fun (ef-entry)
1336 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1338 (defmacro define-unibyte-mapping-external-format
1339 (canonical-name (&rest other-names) &body exceptions)
1340 (let ((->code-name (symbolicate canonical-name '->code-mapper))
1341 (code->-name (symbolicate 'code-> canonical-name '-mapper))
1342 (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1343 (string->-name (symbolicate 'string-> canonical-name))
1344 (define-string*-name (symbolicate 'define- canonical-name '->string*))
1345 (string*-name (symbolicate canonical-name '->string*))
1346 (define-string-name (symbolicate 'define- canonical-name '->string))
1347 (string-name (symbolicate canonical-name '->string))
1348 (->string-aref-name (symbolicate canonical-name '->string-aref)))
1350 (define-unibyte-mapper ,->code-name ,code->-name
1352 (declaim (inline ,get-bytes-name))
1353 (defun ,get-bytes-name (string pos)
1354 (declare (optimize speed (safety 0))
1355 (type simple-string string)
1356 (type array-range pos))
1357 (get-latin-bytes #',code->-name ,canonical-name string pos))
1358 (defun ,string->-name (string sstart send null-padding)
1359 (declare (optimize speed (safety 0))
1360 (type simple-string string)
1361 (type array-range sstart send))
1362 (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1363 (defmacro ,define-string*-name (accessor type)
1364 (declare (ignore type))
1365 (let ((name (make-od-name ',string*-name accessor)))
1367 (defun ,name (string sstart send array astart aend)
1368 (,(make-od-name 'latin->string* accessor)
1369 string sstart send array astart aend #',',->code-name)))))
1370 (instantiate-octets-definition ,define-string*-name)
1371 (defmacro ,define-string-name (accessor type)
1372 (declare (ignore type))
1373 (let ((name (make-od-name ',string-name accessor)))
1375 (defun ,name (array astart aend)
1376 (,(make-od-name 'latin->string accessor)
1377 array astart aend #',',->code-name)))))
1378 (instantiate-octets-definition ,define-string-name)
1379 (define-unibyte-external-format ,canonical-name ,other-names
1380 (let ((octet (,code->-name bits)))
1382 (setf (sap-ref-8 sap tail) octet)
1383 (external-format-encoding-error stream bits)))
1384 (let ((code (,->code-name byte)))
1387 (return-from decode-break-reason 1)))
1391 (defmacro define-unibyte-external-format
1392 (canonical-name (&rest other-names)
1393 out-form in-form octets-to-string-symbol string-to-octets-symbol)
1394 `(define-external-format/variable-width (,canonical-name ,@other-names)
1399 ,octets-to-string-symbol
1400 ,string-to-octets-symbol))
1402 (defmacro define-external-format/variable-width
1403 (external-format output-restart replacement-character
1404 out-size-expr out-expr in-size-expr in-expr
1405 octets-to-string-sym string-to-octets-sym)
1406 (let* ((name (first external-format))
1407 (out-function (symbolicate "OUTPUT-BYTES/" name))
1408 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1409 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1410 (in-char-function (symbolicate "INPUT-CHAR/" name))
1411 (resync-function (symbolicate "RESYNC/" name))
1412 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1413 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1414 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1415 (n-buffer (gensym "BUFFER")))
1417 (defun ,size-function (byte)
1418 (declare (ignorable byte))
1420 (defun ,out-function (stream string flush-p start end)
1421 (let ((start (or start 0))
1422 (end (or end (length string))))
1423 (declare (type index start end))
1424 (synchronize-stream-output stream)
1425 (unless (<= 0 start end (length string))
1426 (sequence-bounding-indices-bad-error string start end))
1429 (let ((obuf (fd-stream-obuf stream)))
1430 (string-dispatch (simple-base-string
1431 #!+sb-unicode (simple-array character (*))
1434 (let ((len (buffer-length obuf))
1435 (sap (buffer-sap obuf))
1437 (tail (buffer-tail obuf)))
1438 (declare (type index tail)
1439 ;; STRING bounds have already been checked.
1440 (optimize (safety 0)))
1441 (,@(if output-restart
1442 `(catch 'output-nothing)
1445 ((or (= start end) (< (- len tail) 4)))
1446 (let* ((byte (aref string start))
1447 (bits (char-code byte))
1448 (size ,out-size-expr))
1451 (setf (buffer-tail obuf) tail)
1454 ;; Exited via CATCH: skip the current character.
1458 (flush-output-buffer stream)))
1460 (flush-output-buffer stream))))
1461 (def-output-routines/variable-width (,format
1468 (if (eql byte #\Newline)
1469 (setf (fd-stream-char-pos stream) 0)
1470 (incf (fd-stream-char-pos stream)))
1471 (let ((bits (char-code byte))
1472 (sap (buffer-sap obuf))
1473 (tail (buffer-tail obuf)))
1475 (defun ,in-function (stream buffer start requested eof-error-p
1476 &aux (total-copied 0))
1477 (declare (type fd-stream stream)
1478 (type index start requested total-copied)
1480 (simple-array character (#.+ansi-stream-in-buffer-length+))
1482 (when (fd-stream-eof-forced-p stream)
1483 (setf (fd-stream-eof-forced-p stream) nil)
1484 (return-from ,in-function 0))
1485 (do ((instead (fd-stream-instead stream)))
1486 ((= (fill-pointer instead) 0)
1487 (setf (fd-stream-listen stream) nil))
1488 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1490 (when (= requested total-copied)
1491 (when (= (fill-pointer instead) 0)
1492 (setf (fd-stream-listen stream) nil))
1493 (return-from ,in-function total-copied)))
1496 (let* ((ibuf (fd-stream-ibuf stream))
1497 (head (buffer-head ibuf))
1498 (tail (buffer-tail ibuf))
1499 (sap (buffer-sap ibuf))
1500 (decode-break-reason nil))
1501 (declare (type index head tail))
1502 ;; Copy data from stream buffer into user's buffer.
1503 (do ((size nil nil))
1504 ((or (= tail head) (= requested total-copied)))
1505 (setf decode-break-reason
1506 (block decode-break-reason
1507 ,@(when (consp in-size-expr)
1508 `((when (> ,(car in-size-expr) (- tail head))
1510 (let ((byte (sap-ref-8 sap head)))
1511 (declare (ignorable byte))
1512 (setq size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr))
1513 (when (> size (- tail head))
1515 (setf (aref buffer (+ start total-copied)) ,in-expr)
1519 (setf (buffer-head ibuf) head)
1520 (when decode-break-reason
1521 ;; If we've already read some characters on when the invalid
1522 ;; code sequence is detected, we return immediately. The
1523 ;; handling of the error is deferred until the next call
1524 ;; (where this check will be false). This allows establishing
1525 ;; high-level handlers for decode errors (for example
1526 ;; automatically resyncing in Lisp comments).
1527 (when (plusp total-copied)
1528 (return-from ,in-function total-copied))
1529 (when (stream-decoding-error-and-handle
1530 stream decode-break-reason)
1532 (error 'end-of-file :stream stream)
1533 (return-from ,in-function total-copied)))
1534 ;; we might have been given stuff to use instead, so
1535 ;; we have to return (and trust our caller to know
1536 ;; what to do about TOTAL-COPIED being 0).
1537 (return-from ,in-function total-copied)))
1538 (setf (buffer-head ibuf) head)
1539 ;; Maybe we need to refill the stream buffer.
1540 (cond ( ;; If there were enough data in the stream buffer, we're done.
1541 (= total-copied requested)
1542 (return total-copied))
1543 ( ;; If EOF, we're done in another way.
1544 (or (eq decode-break-reason 'eof)
1545 (null (catch 'eof-input-catcher
1546 (refill-input-buffer stream))))
1548 (error 'end-of-file :stream stream)
1549 (return total-copied)))
1550 ;; Otherwise we refilled the stream buffer, so fall
1551 ;; through into another pass of the loop.
1553 (def-input-routine/variable-width ,in-char-function (character
1557 (let ((byte (sap-ref-8 sap head)))
1558 (declare (ignorable byte))
1560 (defun ,resync-function (stream)
1561 (let ((ibuf (fd-stream-ibuf stream))
1563 (catch 'eof-input-catcher
1565 (incf (buffer-head ibuf))
1566 (input-at-least stream ,(if (consp in-size-expr) (car in-size-expr) `(setq size ,in-size-expr)))
1567 (unless (block decode-break-reason
1568 (let* ((sap (buffer-sap ibuf))
1569 (head (buffer-head ibuf))
1570 (byte (sap-ref-8 sap head)))
1571 (declare (ignorable byte))
1572 ,@(when (consp in-size-expr)
1573 `((setq size ,(cadr in-size-expr))
1574 (input-at-least stream size)))
1575 (setf head (buffer-head ibuf))
1579 (defun ,read-c-string-function (sap element-type)
1580 (declare (type system-area-pointer sap))
1582 (declare (optimize (speed 3) (safety 0)))
1583 (let* ((stream ,name)
1584 (size 0) (head 0) (byte 0) (char nil)
1585 (decode-break-reason nil)
1586 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1587 (setf decode-break-reason
1588 (block decode-break-reason
1589 (setf byte (sap-ref-8 sap head)
1590 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1594 (when decode-break-reason
1595 (c-string-decoding-error ,name decode-break-reason))
1596 (when (zerop (char-code char))
1598 (string (make-string length :element-type element-type)))
1599 (declare (ignorable stream)
1600 (type index head length) ;; size
1601 (type (unsigned-byte 8) byte)
1602 (type (or null character) char)
1603 (type string string))
1605 (dotimes (index length string)
1606 (setf decode-break-reason
1607 (block decode-break-reason
1608 (setf byte (sap-ref-8 sap head)
1609 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1613 (when decode-break-reason
1614 (c-string-decoding-error ,name decode-break-reason))
1615 (setf (aref string index) char)))))
1617 (defun ,output-c-string-function (string)
1618 (declare (type simple-string string))
1620 (declare (optimize (speed 3) (safety 0)))
1621 (let* ((length (length string))
1622 (char-length (make-array (1+ length) :element-type 'index))
1624 (+ (loop for i of-type index below length
1625 for byte of-type character = (aref string i)
1626 for bits = (char-code byte)
1627 sum (setf (aref char-length i)
1628 (the index ,out-size-expr)))
1629 (let* ((byte (code-char 0))
1630 (bits (char-code byte)))
1631 (declare (ignorable byte bits))
1632 (setf (aref char-length length)
1633 (the index ,out-size-expr)))))
1635 (,n-buffer (make-array buffer-length
1636 :element-type '(unsigned-byte 8)))
1638 (declare (type index length buffer-length tail)
1641 (with-pinned-objects (,n-buffer)
1642 (let ((sap (vector-sap ,n-buffer)))
1643 (declare (system-area-pointer sap))
1644 (loop for i of-type index below length
1645 for byte of-type character = (aref string i)
1646 for bits = (char-code byte)
1647 for size of-type index = (aref char-length i)
1652 (byte (code-char bits))
1653 (size (aref char-length length)))
1654 (declare (ignorable bits byte size))
1658 (let ((entry (%make-external-format
1659 :names ',external-format
1660 :default-replacement-character ,replacement-character
1661 :read-n-chars-fun #',in-function
1662 :read-char-fun #',in-char-function
1663 :write-n-bytes-fun #',out-function
1664 ,@(mapcan #'(lambda (buffering)
1665 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1666 `#',(intern (format nil format (string buffering)))))
1667 '(:none :line :full))
1668 :resync-fun #',resync-function
1669 :bytes-for-char-fun #',size-function
1670 :read-c-string-fun #',read-c-string-function
1671 :write-c-string-fun #',output-c-string-function
1672 :octets-to-string-fun (lambda (&rest rest)
1673 (declare (dynamic-extent rest))
1674 (apply ',octets-to-string-sym rest))
1675 :string-to-octets-fun (lambda (&rest rest)
1676 (declare (dynamic-extent rest))
1677 (apply ',string-to-octets-sym rest)))))
1678 (dolist (ef ',external-format)
1679 (setf (gethash ef *external-formats*) entry))))))
1681 ;;;; utility functions (misc routines, etc)
1683 ;;; Fill in the various routine slots for the given type. INPUT-P and
1684 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1685 ;;; set prior to calling this routine.
1686 (defun set-fd-stream-routines (fd-stream element-type external-format
1687 input-p output-p buffer-p)
1688 (let* ((target-type (case element-type
1689 (unsigned-byte '(unsigned-byte 8))
1690 (signed-byte '(signed-byte 8))
1691 (:default 'character)
1693 (character-stream-p (subtypep target-type 'character))
1694 (bivalent-stream-p (eq element-type :default))
1695 normalized-external-format
1696 (bin-routine #'ill-bin)
1699 (cin-routine #'ill-in)
1702 (input-type nil) ;calculated from bin-type/cin-type
1703 (input-size nil) ;calculated from bin-size/cin-size
1704 (read-n-characters #'ill-in)
1705 (bout-routine #'ill-bout)
1708 (cout-routine #'ill-out)
1713 (output-bytes #'ill-bout))
1715 ;; Ensure that we have buffers in the desired direction(s) only,
1716 ;; getting new ones and dropping/resetting old ones as necessary.
1717 (let ((obuf (fd-stream-obuf fd-stream)))
1721 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1723 (setf (fd-stream-obuf fd-stream) nil)
1724 (release-buffer obuf))))
1726 (let ((ibuf (fd-stream-ibuf fd-stream)))
1730 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1732 (setf (fd-stream-ibuf fd-stream) nil)
1733 (release-buffer ibuf))))
1735 ;; FIXME: Why only for output? Why unconditionally?
1737 (setf (fd-stream-char-pos fd-stream) 0))
1739 (when (and character-stream-p
1740 (eq external-format :default))
1741 (/show0 "/getting default external format")
1742 (setf external-format (default-external-format)))
1745 (when (or (not character-stream-p) bivalent-stream-p)
1746 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1747 normalized-external-format)
1748 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1752 (error "could not find any input routine for ~S" target-type)))
1753 (when character-stream-p
1754 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1755 normalized-external-format)
1756 (pick-input-routine target-type external-format))
1758 (error "could not find any input routine for ~S" target-type)))
1759 (setf (fd-stream-in fd-stream) cin-routine
1760 (fd-stream-bin fd-stream) bin-routine)
1761 ;; character type gets preferential treatment
1762 (setf input-size (or cin-size bin-size))
1763 (setf input-type (or cin-type bin-type))
1764 (when normalized-external-format
1765 (setf (fd-stream-external-format fd-stream)
1766 normalized-external-format))
1767 (when (= (or cin-size 1) (or bin-size 1) 1)
1768 (setf (fd-stream-n-bin fd-stream) ;XXX
1769 (if (and character-stream-p (not bivalent-stream-p))
1771 #'fd-stream-read-n-bytes))
1772 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1773 ;; for character and (unsigned-byte 8) streams. In these
1774 ;; cases, fast-read-* will read from the
1775 ;; ansi-stream-(c)in-buffer, saving function calls.
1776 ;; Otherwise, the various data-reading functions in the stream
1777 ;; structure will be called.
1779 (not bivalent-stream-p)
1780 ;; temporary disable on :io streams
1782 (cond (character-stream-p
1783 (setf (ansi-stream-cin-buffer fd-stream)
1784 (make-array +ansi-stream-in-buffer-length+
1785 :element-type 'character)))
1786 ((equal target-type '(unsigned-byte 8))
1787 (setf (ansi-stream-in-buffer fd-stream)
1788 (make-array +ansi-stream-in-buffer-length+
1789 :element-type '(unsigned-byte 8))))))))
1792 (when (or (not character-stream-p) bivalent-stream-p)
1793 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1794 normalized-external-format)
1795 (let ((buffering (fd-stream-buffering fd-stream)))
1796 (if bivalent-stream-p
1797 (pick-output-routine '(unsigned-byte 8)
1798 (if (eq :line buffering)
1802 (pick-output-routine target-type buffering external-format))))
1803 (unless bout-routine
1804 (error "could not find any output routine for ~S buffered ~S"
1805 (fd-stream-buffering fd-stream)
1807 (when character-stream-p
1808 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1809 normalized-external-format)
1810 (pick-output-routine target-type
1811 (fd-stream-buffering fd-stream)
1813 (unless cout-routine
1814 (error "could not find any output routine for ~S buffered ~S"
1815 (fd-stream-buffering fd-stream)
1817 (when normalized-external-format
1818 (setf (fd-stream-external-format fd-stream)
1819 normalized-external-format))
1820 (when character-stream-p
1821 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1822 (setf (fd-stream-out fd-stream) cout-routine
1823 (fd-stream-bout fd-stream) bout-routine
1824 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1825 #'fd-sout #'ill-out))
1826 (setf output-size (or cout-size bout-size))
1827 (setf output-type (or cout-type bout-type)))
1829 (when (and input-size output-size
1830 (not (eq input-size output-size)))
1831 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1832 input-type input-size
1833 output-type output-size))
1834 (setf (fd-stream-element-size fd-stream)
1835 (or input-size output-size))
1837 (setf (fd-stream-element-type fd-stream)
1838 (cond ((equal input-type output-type)
1844 ((subtypep input-type output-type)
1846 ((subtypep output-type input-type)
1849 (error "Input type (~S) and output type (~S) are unrelated?"
1853 ;;; Handles the resource-release aspects of stream closing, and marks
1855 (defun release-fd-stream-resources (fd-stream)
1858 ;; Drop handlers first.
1859 (when (fd-stream-handler fd-stream)
1860 (remove-fd-handler (fd-stream-handler fd-stream))
1861 (setf (fd-stream-handler fd-stream) nil))
1862 ;; Disable interrupts so that a asynch unwind will not leave
1863 ;; us with a dangling finalizer (that would close the same
1864 ;; --possibly reassigned-- FD again), or a stream with a closed
1865 ;; FD that appears open.
1866 (sb!unix:unix-close (fd-stream-fd fd-stream))
1867 (set-closed-flame fd-stream)
1868 (when (fboundp 'cancel-finalization)
1869 (cancel-finalization fd-stream)))
1870 ;; On error unwind from WITHOUT-INTERRUPTS.
1871 (serious-condition (e)
1873 ;; Release all buffers. If this is undone, or interrupted,
1874 ;; we're still safe: buffers have finalizers of their own.
1875 (release-fd-stream-buffers fd-stream))
1877 ;;; Flushes the current input buffer and any supplied replacements,
1878 ;;; and returns the input buffer, and the amount of of flushed input
1880 (defun flush-input-buffer (stream)
1881 (let ((unread (length (fd-stream-instead stream))))
1882 (setf (fill-pointer (fd-stream-instead stream)) 0)
1883 (let ((ibuf (fd-stream-ibuf stream)))
1885 (let ((head (buffer-head ibuf))
1886 (tail (buffer-tail ibuf)))
1887 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1888 (values nil unread)))))
1890 (defun fd-stream-clear-input (stream)
1891 (flush-input-buffer stream)
1894 (sb!win32:fd-clear-input (fd-stream-fd stream))
1895 (setf (fd-stream-listen stream) nil))
1897 (catch 'eof-input-catcher
1898 (loop until (sysread-may-block-p stream)
1900 (refill-input-buffer stream)
1901 (reset-buffer (fd-stream-ibuf stream)))
1904 ;;; Handle miscellaneous operations on FD-STREAM.
1905 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1906 (declare (ignore arg2))
1909 (labels ((do-listen ()
1910 (let ((ibuf (fd-stream-ibuf fd-stream)))
1911 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1912 (fd-stream-listen fd-stream)
1914 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1916 ;; If the read can block, LISTEN will certainly return NIL.
1917 (if (sysread-may-block-p fd-stream)
1919 ;; Otherwise select(2) and CL:LISTEN have slightly
1920 ;; different semantics. The former returns that an FD
1921 ;; is readable when a read operation wouldn't block.
1922 ;; That includes EOF. However, LISTEN must return NIL
1924 (progn (catch 'eof-input-catcher
1925 ;; r-b/f too calls select, but it shouldn't
1926 ;; block as long as read can return once w/o
1928 (refill-input-buffer fd-stream))
1929 ;; At this point either IBUF-HEAD != IBUF-TAIL
1930 ;; and FD-STREAM-LISTEN is NIL, in which case
1931 ;; we should return T, or IBUF-HEAD ==
1932 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1933 ;; which case we should return :EOF for this
1934 ;; call and all future LISTEN call on this stream.
1935 ;; Call ourselves again to determine which case
1940 (decf (buffer-head (fd-stream-ibuf fd-stream))
1941 (fd-stream-character-size fd-stream arg1)))
1943 ;; Drop input buffers
1944 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1945 (ansi-stream-cin-buffer fd-stream) nil
1946 (ansi-stream-in-buffer fd-stream) nil)
1948 ;; We got us an abort on our hands.
1949 (let ((outputp (fd-stream-obuf fd-stream))
1950 (file (fd-stream-file fd-stream))
1951 (orig (fd-stream-original fd-stream)))
1952 ;; This takes care of the important stuff -- everything
1953 ;; rest is cleaning up the file-system, which we cannot
1954 ;; do on some platforms as long as the file is open.
1955 (release-fd-stream-resources fd-stream)
1956 ;; We can't do anything unless we know what file were
1957 ;; dealing with, and we don't want to do anything
1958 ;; strange unless we were writing to the file.
1959 (when (and outputp file)
1961 ;; If the original is EQ to file we are appending to
1962 ;; and can just close the file without renaming.
1963 (unless (eq orig file)
1964 ;; We have a handle on the original, just revert.
1965 (multiple-value-bind (okay err)
1966 (sb!unix:unix-rename orig file)
1967 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1968 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1971 (error 'simple-stream-error
1973 "~@<Couldn't restore ~S to its original contents ~
1974 from ~S while closing ~S: ~2I~_~A~:>"
1976 (list file orig fd-stream (strerror err))
1977 :stream fd-stream))))
1978 ;; We can't restore the original, and aren't
1979 ;; appending, so nuke that puppy.
1981 ;; FIXME: This is currently the fate of superseded
1982 ;; files, and according to the CLOSE spec this is
1983 ;; wrong. However, there seems to be no clean way to
1984 ;; do that that doesn't involve either copying the
1985 ;; data (bad if the :abort resulted from a full
1986 ;; disk), or renaming the old file temporarily
1987 ;; (probably bad because stream opening becomes more
1989 (multiple-value-bind (okay err)
1990 (sb!unix:unix-unlink file)
1992 (error 'simple-file-error
1995 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
1997 (list file fd-stream (strerror err)))))))))
1999 (finish-fd-stream-output fd-stream)
2000 (let ((orig (fd-stream-original fd-stream)))
2001 (when (and orig (fd-stream-delete-original fd-stream))
2002 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2004 (error 'simple-file-error
2007 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2009 (list orig fd-stream (strerror err)))))))
2010 ;; In case of no-abort close, don't *really* close the
2011 ;; stream until the last moment -- the cleaning up of the
2012 ;; original can be done first.
2013 (release-fd-stream-resources fd-stream))))
2015 (fd-stream-clear-input fd-stream))
2017 (flush-output-buffer fd-stream))
2019 (finish-fd-stream-output fd-stream))
2021 (fd-stream-element-type fd-stream))
2023 (fd-stream-external-format fd-stream))
2025 (= 1 (the (member 0 1)
2026 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2030 (fd-stream-char-pos fd-stream))
2032 (unless (fd-stream-file fd-stream)
2033 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2034 ;; "should signal an error of type TYPE-ERROR if stream is not
2035 ;; a stream associated with a file". Too bad there's no very
2036 ;; appropriate value for the EXPECTED-TYPE slot..
2037 (error 'simple-type-error
2039 :expected-type 'fd-stream
2040 :format-control "~S is not a stream associated with a file."
2041 :format-arguments (list fd-stream)))
2042 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2043 atime mtime ctime blksize blocks)
2044 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2045 (declare (ignore ino nlink uid gid rdev
2046 atime mtime ctime blksize blocks))
2048 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2051 (truncate size (fd-stream-element-size fd-stream)))))
2052 (:file-string-length
2054 (character (fd-stream-character-size fd-stream arg1))
2055 (string (fd-stream-string-size fd-stream arg1))))
2058 (fd-stream-set-file-position fd-stream arg1)
2059 (fd-stream-get-file-position fd-stream)))))
2061 ;; FIXME: Think about this.
2063 ;; (defun finish-fd-stream-output (fd-stream)
2064 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2065 ;; (loop while (fd-stream-output-queue fd-stream)
2066 ;; ;; FIXME: SIGINT while waiting for a timeout will
2067 ;; ;; cause a timeout here.
2068 ;; do (when (and (not (serve-event timeout)) timeout)
2069 ;; (signal-timeout 'io-timeout
2070 ;; :stream fd-stream
2071 ;; :direction :write
2072 ;; :seconds timeout)))))
2074 (defun finish-fd-stream-output (stream)
2075 (flush-output-buffer stream)
2077 ((null (fd-stream-output-queue stream)))
2078 (serve-all-events)))
2080 (defun fd-stream-get-file-position (stream)
2081 (declare (fd-stream stream))
2083 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2084 (declare (type (or (alien sb!unix:off-t) null) posn))
2085 ;; We used to return NIL for errno==ESPIPE, and signal an error
2086 ;; in other failure cases. However, CLHS says to return NIL if
2087 ;; the position cannot be determined -- so that's what we do.
2088 (when (integerp posn)
2089 ;; Adjust for buffered output: If there is any output
2090 ;; buffered, the *real* file position will be larger
2091 ;; than reported by lseek() because lseek() obviously
2092 ;; cannot take into account output we have not sent
2094 (dolist (buffer (fd-stream-output-queue stream))
2095 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2096 (let ((obuf (fd-stream-obuf stream)))
2098 (incf posn (buffer-tail obuf))))
2099 ;; Adjust for unread input: If there is any input
2100 ;; read from UNIX but not supplied to the user of the
2101 ;; stream, the *real* file position will smaller than
2102 ;; reported, because we want to look like the unread
2103 ;; stuff is still available.
2104 (let ((ibuf (fd-stream-ibuf stream)))
2106 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2107 ;; Divide bytes by element size.
2108 (truncate posn (fd-stream-element-size stream))))))
2110 (defun fd-stream-set-file-position (stream position-spec)
2111 (declare (fd-stream stream))
2112 (check-type position-spec
2113 (or (alien sb!unix:off-t) (member nil :start :end))
2114 "valid file position designator")
2117 ;; Make sure we don't have any output pending, because if we
2118 ;; move the file pointer before writing this stuff, it will be
2119 ;; written in the wrong location.
2120 (finish-fd-stream-output stream)
2121 ;; Disable interrupts so that interrupt handlers doing output
2124 (unless (fd-stream-output-finished-p stream)
2125 ;; We got interrupted and more output came our way during
2126 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2127 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2128 ;; so we prefer to do things like this...
2130 ;; Clear out any pending input to force the next read to go to
2132 (flush-input-buffer stream)
2133 ;; Trash cached value for listen, so that we check next time.
2134 (setf (fd-stream-listen stream) nil)
2136 (multiple-value-bind (offset origin)
2139 (values 0 sb!unix:l_set))
2141 (values 0 sb!unix:l_xtnd))
2143 (values (* position-spec (fd-stream-element-size stream))
2145 (declare (type (alien sb!unix:off-t) offset))
2146 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2148 ;; CLHS says to return true if the file-position was set
2149 ;; succesfully, and NIL otherwise. We are to signal an error
2150 ;; only if the given position was out of bounds, and that is
2151 ;; dealt with above. In times past we used to return NIL for
2152 ;; errno==ESPIPE, and signal an error in other cases.
2154 ;; FIXME: We are still liable to signal an error if flushing
2156 (return-from fd-stream-set-file-position
2157 (typep posn '(alien sb!unix:off-t))))))))
2160 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2162 ;;; Create a stream for the given Unix file descriptor.
2164 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2165 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2166 ;;; default to allowing input.
2168 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2170 ;;; BUFFERING indicates the kind of buffering to use.
2172 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2173 ;;; NIL (the default), then wait forever. When we time out, we signal
2176 ;;; FILE is the name of the file (will be returned by PATHNAME).
2178 ;;; NAME is used to identify the stream when printed.
2179 (defun make-fd-stream (fd
2182 (output nil output-p)
2183 (element-type 'base-char)
2185 (external-format :default)
2194 (format nil "file ~A" file)
2195 (format nil "descriptor ~W" fd)))
2197 (declare (type index fd) (type (or real null) timeout)
2198 (type (member :none :line :full) buffering))
2199 (cond ((not (or input-p output-p))
2201 ((not (or input output))
2202 (error "File descriptor must be opened either for input or output.")))
2203 (let ((stream (%make-fd-stream :fd fd
2207 :delete-original delete-original
2209 :buffering buffering
2210 :dual-channel-p dual-channel-p
2211 :external-format external-format
2212 :bivalent-p (eq element-type :default)
2213 :char-size (external-format-char-size external-format)
2216 (coerce timeout 'single-float)
2218 (set-fd-stream-routines stream element-type external-format
2219 input output input-buffer-p)
2220 (when (and auto-close (fboundp 'finalize))
2223 (sb!unix:unix-close fd)
2225 (format *terminal-io* "** closed file descriptor ~W **~%"
2230 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2231 ;;; :RENAME-AND-DELETE and :RENAME options.
2232 (defun pick-backup-name (name)
2233 (declare (type simple-string name))
2234 (concatenate 'simple-string name ".bak"))
2236 ;;; Ensure that the given arg is one of the given list of valid
2237 ;;; things. Allow the user to fix any problems.
2238 (defun ensure-one-of (item list what)
2239 (unless (member item list)
2240 (error 'simple-type-error
2242 :expected-type `(member ,@list)
2243 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2244 :format-arguments (list item what list))))
2246 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2247 ;;; access, since we don't want to trash unwritable files even if we
2248 ;;; technically can. We return true if we succeed in renaming.
2249 (defun rename-the-old-one (namestring original)
2250 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2251 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2252 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2255 (error 'simple-file-error
2256 :pathname namestring
2258 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2259 :format-arguments (list namestring original (strerror err))))))
2261 (defun open (filename
2264 (element-type 'base-char)
2265 (if-exists nil if-exists-given)
2266 (if-does-not-exist nil if-does-not-exist-given)
2267 (external-format :default)
2268 &aux ; Squelch assignment warning.
2269 (direction direction)
2270 (if-does-not-exist if-does-not-exist)
2271 (if-exists if-exists))
2273 "Return a stream which reads from or writes to FILENAME.
2275 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2276 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2277 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2278 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2279 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2280 See the manual for details."
2282 ;; Calculate useful stuff.
2283 (multiple-value-bind (input output mask)
2285 (:input (values t nil sb!unix:o_rdonly))
2286 (:output (values nil t sb!unix:o_wronly))
2287 (:io (values t t sb!unix:o_rdwr))
2288 (:probe (values t nil sb!unix:o_rdonly)))
2289 (declare (type index mask))
2290 (let* (;; PATHNAME is the pathname we associate with the stream.
2291 (pathname (merge-pathnames filename))
2292 (physical (physicalize-pathname pathname))
2293 (truename (probe-file physical))
2294 ;; NAMESTRING is the native namestring we open the file with.
2295 (namestring (cond (truename
2296 (native-namestring truename :as-file t))
2298 (and input (eq if-does-not-exist :create))
2299 (and (eq direction :io) (not if-does-not-exist-given)))
2300 (native-namestring physical :as-file t)))))
2301 ;; Process if-exists argument if we are doing any output.
2303 (unless if-exists-given
2305 (if (eq (pathname-version pathname) :newest)
2308 (ensure-one-of if-exists
2309 '(:error :new-version :rename
2310 :rename-and-delete :overwrite
2311 :append :supersede nil)
2314 ((:new-version :error nil)
2315 (setf mask (logior mask sb!unix:o_excl)))
2316 ((:rename :rename-and-delete)
2317 (setf mask (logior mask sb!unix:o_creat)))
2319 (setf mask (logior mask sb!unix:o_trunc)))
2321 (setf mask (logior mask sb!unix:o_append)))))
2323 (setf if-exists :ignore-this-arg)))
2325 (unless if-does-not-exist-given
2326 (setf if-does-not-exist
2327 (cond ((eq direction :input) :error)
2329 (member if-exists '(:overwrite :append)))
2331 ((eq direction :probe)
2335 (ensure-one-of if-does-not-exist
2336 '(:error :create nil)
2338 (if (eq if-does-not-exist :create)
2339 (setf mask (logior mask sb!unix:o_creat)))
2341 (let ((original (case if-exists
2342 ((:rename :rename-and-delete)
2343 (pick-backup-name namestring))
2344 ((:append :overwrite)
2345 ;; KLUDGE: Provent CLOSE from deleting
2346 ;; appending streams when called with :ABORT T
2348 (delete-original (eq if-exists :rename-and-delete))
2350 (when (and original (not (eq original namestring)))
2351 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2352 ;; whether the file already exists, make sure the original
2353 ;; file is not a directory, and keep the mode.
2356 (multiple-value-bind (okay err/dev inode orig-mode)
2357 (sb!unix:unix-stat namestring)
2358 (declare (ignore inode)
2359 (type (or index null) orig-mode))
2362 (when (and output (= (logand orig-mode #o170000)
2364 (error 'simple-file-error
2367 "can't open ~S for output: is a directory"
2368 :format-arguments (list namestring)))
2369 (setf mode (logand orig-mode #o777))
2371 ((eql err/dev sb!unix:enoent)
2374 (simple-file-perror "can't find ~S"
2378 (rename-the-old-one namestring original))
2380 (setf delete-original nil)
2381 ;; In order to use :SUPERSEDE instead, we have to make
2382 ;; sure SB!UNIX:O_CREAT corresponds to
2383 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2384 ;; because of IF-EXISTS being :RENAME.
2385 (unless (eq if-does-not-exist :create)
2387 (logior (logandc2 mask sb!unix:o_creat)
2389 (setf if-exists :supersede))))
2391 ;; Now we can try the actual Unix open(2).
2392 (multiple-value-bind (fd errno)
2394 (sb!unix:unix-open namestring mask mode)
2395 (values nil sb!unix:enoent))
2396 (labels ((open-error (format-control &rest format-arguments)
2397 (error 'simple-file-error
2399 :format-control format-control
2400 :format-arguments format-arguments))
2401 (vanilla-open-error ()
2402 (simple-file-perror "error opening ~S" pathname errno)))
2405 ((:input :output :io)
2409 :element-type element-type
2410 :external-format external-format
2413 :delete-original delete-original
2420 (%make-fd-stream :name namestring
2423 :element-type element-type)))
2426 ((eql errno sb!unix:enoent)
2427 (case if-does-not-exist
2428 (:error (vanilla-open-error))
2430 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2433 ((and (eql errno sb!unix:eexist) (null if-exists))
2436 (vanilla-open-error)))))))))
2440 ;;; the stream connected to the controlling terminal, or NIL if there is none
2443 ;;; the stream connected to the standard input (file descriptor 0)
2446 ;;; the stream connected to the standard output (file descriptor 1)
2449 ;;; the stream connected to the standard error output (file descriptor 2)
2452 ;;; This is called when the cold load is first started up, and may also
2453 ;;; be called in an attempt to recover from nested errors.
2454 (defun stream-cold-init-or-reset ()
2456 (setf *terminal-io* (make-synonym-stream '*tty*))
2457 (setf *standard-output* (make-synonym-stream '*stdout*))
2458 (setf *standard-input* (make-synonym-stream '*stdin*))
2459 (setf *error-output* (make-synonym-stream '*stderr*))
2460 (setf *query-io* (make-synonym-stream '*terminal-io*))
2461 (setf *debug-io* *query-io*)
2462 (setf *trace-output* *standard-output*)
2465 (defun stream-deinit ()
2466 ;; Unbind to make sure we're not accidently dealing with it
2467 ;; before we're ready (or after we think it's been deinitialized).
2468 (with-available-buffers-lock ()
2469 (without-package-locks
2470 (makunbound '*available-buffers*))))
2472 (defun stdstream-external-format (outputp)
2473 (declare (ignorable outputp))
2474 (let* ((keyword #!+win32 (if outputp (sb!win32::console-output-codepage) (sb!win32::console-input-codepage))
2475 #!-win32 (default-external-format))
2476 (ef (get-external-format keyword))
2477 (replacement (ef-default-replacement-character ef)))
2478 `(,keyword :replacement ,replacement)))
2480 ;;; This is called whenever a saved core is restarted.
2481 (defun stream-reinit (&optional init-buffers-p)
2482 (when init-buffers-p
2483 (with-available-buffers-lock ()
2484 (aver (not (boundp '*available-buffers*)))
2485 (setf *available-buffers* nil)))
2486 (with-output-to-string (*error-output*)
2488 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2489 :element-type :default
2490 :external-format (stdstream-external-format nil)))
2492 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2493 :element-type :default
2494 :external-format (stdstream-external-format t)))
2496 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2497 :element-type :default
2498 :external-format (stdstream-external-format t)))
2499 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2500 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2503 (make-fd-stream tty :name "the terminal"
2504 :input t :output t :buffering :line
2505 :external-format (stdstream-external-format t)
2507 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2508 (princ (get-output-stream-string *error-output*) *stderr*))
2513 ;;; the Unix way to beep
2514 (defun beep (stream)
2515 (write-char (code-char bell-char-code) stream)
2516 (finish-output stream))
2518 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2519 ;;; by the filesys stuff to get and set the file name.
2521 ;;; FIXME: misleading name, screwy interface
2522 (defun file-name (stream &optional new-name)
2523 (when (typep stream 'fd-stream)
2525 (setf (fd-stream-pathname stream) new-name)
2526 (setf (fd-stream-file stream)
2527 (native-namestring (physicalize-pathname new-name)
2531 (fd-stream-pathname stream)))))