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 ;; What do we know about the FD?
161 (fd-type :unknown :type keyword)
162 ;; controls when the output buffer is flushed
163 (buffering :full :type (member :full :line :none))
164 ;; controls whether the input buffer must be cleared before output
165 ;; (must be done for files, not for sockets, pipes and other data
166 ;; sources where input and output aren't related). non-NIL means
167 ;; don't clear input buffer.
169 ;; character position if known -- this may run into bignums, but
170 ;; we probably should flip it into null then for efficiency's sake...
171 (char-pos nil :type (or unsigned-byte null))
172 ;; T if input is waiting on FD. :EOF if we hit EOF.
173 (listen nil :type (member nil t :eof))
174 ;; T if serve-event is allowed when this stream blocks
175 (serve-events nil :type boolean)
178 (instead (make-array 0 :element-type 'character :adjustable t :fill-pointer t) :type (array character (*)))
179 (ibuf nil :type (or buffer null))
180 (eof-forced-p nil :type (member t nil))
183 (obuf nil :type (or buffer null))
185 ;; output flushed, but not written due to non-blocking io?
188 ;; timeout specified for this stream as seconds or NIL if none
189 (timeout nil :type (or single-float null))
190 ;; pathname of the file this stream is opened to (returned by PATHNAME)
191 (pathname nil :type (or pathname null))
192 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
193 (external-format :latin-1)
194 ;; fixed width, or function to call with a character
195 (char-size 1 :type (or fixnum function))
196 (output-bytes #'ill-out :type function)
197 ;; a boolean indicating whether the stream is bivalent. For
198 ;; internal use only.
199 (bivalent-p nil :type boolean))
200 (def!method print-object ((fd-stream fd-stream) stream)
201 (declare (type stream stream))
202 (print-unreadable-object (fd-stream stream :type t :identity t)
203 (format stream "for ~S" (fd-stream-name fd-stream))))
205 ;;;; CORE OUTPUT FUNCTIONS
207 ;;; Buffer the section of THING delimited by START and END by copying
208 ;;; to output buffer(s) of stream.
209 (defun buffer-output (stream thing start end)
210 (declare (index start end))
212 (error ":END before :START!"))
214 ;; Copy bytes from THING to buffers.
215 (flet ((copy-to-buffer (buffer tail count)
216 (declare (buffer buffer) (index tail count))
218 (let ((sap (buffer-sap buffer)))
221 (system-area-ub8-copy thing start sap tail count))
222 ((simple-unboxed-array (*))
223 (copy-ub8-to-system-area thing start sap tail count))))
224 ;; Not INCF! If another thread has moved tail from under
225 ;; us, we don't want to accidentally increment tail
226 ;; beyond buffer-length.
227 (setf (buffer-tail buffer) (+ count tail))
230 ;; First copy is special: the buffer may already contain
231 ;; something, or be even full.
232 (let* ((obuf (fd-stream-obuf stream))
233 (tail (buffer-tail obuf))
234 (space (- (buffer-length obuf) tail)))
236 (copy-to-buffer obuf tail (min space (- end start)))
237 (go :more-output-p)))
239 ;; Later copies should always have an empty buffer, since
240 ;; they are freshly flushed, but if another thread is
241 ;; stomping on the same buffer that might not be the case.
242 (let* ((obuf (flush-output-buffer stream))
243 (tail (buffer-tail obuf))
244 (space (- (buffer-length obuf) tail)))
245 (copy-to-buffer obuf tail (min space (- end start))))
248 (go :flush-and-fill))))))
250 ;;; Flush the current output buffer of the stream, ensuring that the
251 ;;; new buffer is empty. Returns (for convenience) the new output
252 ;;; buffer -- which may or may not be EQ to the old one. If the is no
253 ;;; queued output we try to write the buffer immediately -- otherwise
254 ;;; we queue it for later.
255 (defun flush-output-buffer (stream)
256 (let ((obuf (fd-stream-obuf stream)))
258 (let ((head (buffer-head obuf))
259 (tail (buffer-tail obuf)))
260 (cond ((eql head tail)
261 ;; Buffer is already empty -- just ensure that is is
262 ;; set to zero as well.
264 ((fd-stream-output-queue stream)
265 ;; There is already stuff on the queue -- go directly
268 (%queue-and-replace-output-buffer stream))
270 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
271 ;; whatever is left over. Otherwise wait until we can write.
273 (synchronize-stream-output stream)
275 (let ((length (- tail head)))
276 (multiple-value-bind (count errno)
277 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
279 (flet ((queue-or-wait ()
280 (if (fd-stream-serve-events stream)
281 (return (%queue-and-replace-output-buffer stream))
282 (or (wait-until-fd-usable (fd-stream-fd stream) :output
283 (fd-stream-timeout stream)
285 (signal-timeout 'io-timeout
288 :seconds (fd-stream-timeout stream))))))
289 (cond ((eql count length)
290 ;; Complete write -- we can use the same buffer.
291 (return (reset-buffer obuf)))
293 ;; Partial write -- update buffer status and
296 (setf (buffer-head obuf) head)
299 ((eql errno sb!unix:ewouldblock)
300 ;; Blocking, queue or wair.
303 (simple-stream-perror "Couldn't write to ~s"
304 stream errno)))))))))))))
306 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
307 (defun %queue-and-replace-output-buffer (stream)
308 (aver (fd-stream-serve-events stream))
309 (let ((queue (fd-stream-output-queue stream))
310 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
312 ;; Important: before putting the buffer on queue, give the stream
313 ;; a new one. If we get an interrupt and unwind losing the buffer
314 ;; is relatively OK, but having the same buffer in two places
316 (setf (fd-stream-obuf stream) new)
320 (setf (fd-stream-output-queue stream) later)))
321 (unless (fd-stream-handler stream)
322 (setf (fd-stream-handler stream)
323 (add-fd-handler (fd-stream-fd stream)
326 (declare (ignore fd))
327 (write-output-from-queue stream)))))
330 ;;; This is called by the FD-HANDLER for the stream when output is
332 (defun write-output-from-queue (stream)
333 (aver (fd-stream-serve-events stream))
334 (synchronize-stream-output stream)
338 (let* ((buffer (pop (fd-stream-output-queue stream)))
339 (head (buffer-head buffer))
340 (length (- (buffer-tail buffer) head)))
341 (declare (index head length))
343 (multiple-value-bind (count errno)
344 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
346 (cond ((eql count length)
347 ;; Complete write, see if we can do another right
348 ;; away, or remove the handler if we're done.
349 (release-buffer buffer)
350 (cond ((fd-stream-output-queue stream)
354 (let ((handler (fd-stream-handler stream)))
356 (setf (fd-stream-handler stream) nil)
357 (remove-fd-handler handler)))))
359 ;; Partial write. Update buffer status and requeue.
360 (aver (< count length))
361 ;; Do not use INCF! Another thread might have moved head.
362 (setf (buffer-head buffer) (+ head count))
363 (push buffer (fd-stream-output-queue stream)))
365 ;; We tried to do multiple writes, and finally our
366 ;; luck ran out. Requeue.
367 (push buffer (fd-stream-output-queue stream)))
369 ;; Could not write on the first try at all!
371 (simple-stream-perror "Couldn't write to ~S." stream errno)
373 (if (= errno sb!unix:ewouldblock)
374 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
375 (simple-stream-perror "Couldn't write to ~S"
379 ;;; Try to write THING directly to STREAM without buffering, if
380 ;;; possible. If direct write doesn't happen, buffer.
381 (defun write-or-buffer-output (stream thing start end)
382 (declare (index start end))
383 (cond ((fd-stream-output-queue stream)
384 (buffer-output stream thing start end))
386 (error ":END before :START!"))
388 (let ((length (- end start)))
389 (synchronize-stream-output stream)
390 (multiple-value-bind (count errno)
391 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
392 (cond ((eql count length)
393 ;; Complete write -- done!
396 (aver (< count length))
397 ;; Partial write -- buffer the rest.
398 (buffer-output stream thing (+ start count) end))
400 ;; Could not write -- buffer or error.
402 (simple-stream-perror "couldn't write to ~s" stream errno)
404 (if (= errno sb!unix:ewouldblock)
405 (buffer-output stream thing start end)
406 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
408 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
409 ;;; this is not something we want to export. Nikodemus thinks the
410 ;;; right thing is to support a low-level non-stream like IO layer,
411 ;;; akin to java.nio.
412 (declaim (inline output-raw-bytes))
413 (define-deprecated-function :late "1.0.8.16" output-raw-bytes write-sequence
414 (stream thing &optional start end)
415 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
417 ;;;; output routines and related noise
419 (defvar *output-routines* ()
421 "List of all available output routines. Each element is a list of the
422 element-type output, the kind of buffering, the function name, and the number
423 of bytes per element.")
425 ;;; common idioms for reporting low-level stream and file problems
426 (defun simple-stream-perror (note-format stream errno)
427 (error 'simple-stream-error
429 :format-control "~@<~?: ~2I~_~A~:>"
430 :format-arguments (list note-format (list stream) (strerror errno))))
431 (defun simple-file-perror (note-format pathname errno)
432 (error 'simple-file-error
434 :format-control "~@<~?: ~2I~_~A~:>"
436 (list note-format (list pathname) (strerror errno))))
438 (defun stream-decoding-error (stream octets)
439 (error 'stream-decoding-error
440 :external-format (stream-external-format stream)
442 ;; FIXME: dunno how to get at OCTETS currently, or even if
443 ;; that's the right thing to report.
445 (defun stream-encoding-error (stream code)
446 (error 'stream-encoding-error
447 :external-format (stream-external-format stream)
451 (defun c-string-encoding-error (external-format code)
452 (error 'c-string-encoding-error
453 :external-format external-format
456 (defun c-string-decoding-error (external-format octets)
457 (error 'c-string-decoding-error
458 :external-format external-format
461 ;;; Returning true goes into end of file handling, false will enter another
462 ;;; round of input buffer filling followed by re-entering character decode.
463 (defun stream-decoding-error-and-handle (stream octet-count)
465 (stream-decoding-error stream
466 (let* ((buffer (fd-stream-ibuf stream))
467 (sap (buffer-sap buffer))
468 (head (buffer-head buffer)))
469 (loop for i from 0 below octet-count
470 collect (sap-ref-8 sap (+ head i)))))
472 :report (lambda (stream)
474 "~@<Attempt to resync the stream at a ~
475 character boundary and continue.~@:>"))
476 (fd-stream-resync stream)
478 (force-end-of-file ()
479 :report (lambda (stream)
480 (format stream "~@<Force an end of file.~@:>"))
481 (setf (fd-stream-eof-forced-p stream) t))
482 (input-replacement (string)
483 :report (lambda (stream)
484 (format stream "~@<Use string as replacement input, ~
485 attempt to resync at a character ~
486 boundary and continue.~@:>"))
487 :interactive (lambda ()
488 (format *query-io* "~@<Enter a string: ~@:>")
489 (finish-output *query-io*)
490 (list (read *query-io*)))
491 (let ((string (reverse (string string)))
492 (instead (fd-stream-instead stream)))
493 (dotimes (i (length string))
494 (vector-push-extend (char string i) instead))
495 (fd-stream-resync stream)
496 (when (> (length string) 0)
497 (setf (fd-stream-listen stream) t)))
500 (defun stream-encoding-error-and-handle (stream code)
502 (stream-encoding-error stream code)
504 :report (lambda (stream)
505 (format stream "~@<Skip output of this character.~@:>"))
506 (throw 'output-nothing nil))
507 (output-replacement (string)
508 :report (lambda (stream)
509 (format stream "~@<Output replacement string.~@:>"))
510 :interactive (lambda ()
511 (format *query-io* "~@<Enter a string: ~@:>")
512 (finish-output *query-io*)
513 (list (read *query-io*)))
514 (let ((string (string string)))
515 (fd-sout stream (string string) 0 (length string)))
516 (throw 'output-nothing nil))))
518 (defun external-format-encoding-error (stream code)
520 (stream-encoding-error-and-handle stream code)
521 (c-string-encoding-error stream code)))
523 (defun synchronize-stream-output (stream)
524 ;; If we're reading and writing on the same file, flush buffered
525 ;; input and rewind file position accordingly.
526 (unless (fd-stream-dual-channel-p stream)
527 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
528 (unless (eql 0 adjust)
529 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
531 (defun fd-stream-output-finished-p (stream)
532 (let ((obuf (fd-stream-obuf stream)))
534 (and (zerop (buffer-tail obuf))
535 (not (fd-stream-output-queue stream))))))
537 (defmacro output-wrapper/variable-width ((stream size buffering restart)
539 (let ((stream-var (gensym "STREAM")))
540 `(let* ((,stream-var ,stream)
541 (obuf (fd-stream-obuf ,stream-var))
542 (tail (buffer-tail obuf))
544 ,(unless (eq (car buffering) :none)
545 `(when (<= (buffer-length obuf) (+ tail size))
546 (setf obuf (flush-output-buffer ,stream-var)
547 tail (buffer-tail obuf))))
548 ,(unless (eq (car buffering) :none)
549 ;; FIXME: Why this here? Doesn't seem necessary.
550 `(synchronize-stream-output ,stream-var))
552 `(catch 'output-nothing
554 (setf (buffer-tail obuf) (+ tail size)))
557 (setf (buffer-tail obuf) (+ tail size))))
558 ,(ecase (car buffering)
560 `(flush-output-buffer ,stream-var))
562 `(when (eql byte #\Newline)
563 (flush-output-buffer ,stream-var)))
567 (defmacro output-wrapper ((stream size buffering restart) &body body)
568 (let ((stream-var (gensym "STREAM")))
569 `(let* ((,stream-var ,stream)
570 (obuf (fd-stream-obuf ,stream-var))
571 (tail (buffer-tail obuf)))
572 ,(unless (eq (car buffering) :none)
573 `(when (<= (buffer-length obuf) (+ tail ,size))
574 (setf obuf (flush-output-buffer ,stream-var)
575 tail (buffer-tail obuf))))
576 ;; FIXME: Why this here? Doesn't seem necessary.
577 ,(unless (eq (car buffering) :none)
578 `(synchronize-stream-output ,stream-var))
580 `(catch 'output-nothing
582 (setf (buffer-tail obuf) (+ tail ,size)))
585 (setf (buffer-tail obuf) (+ tail ,size))))
586 ,(ecase (car buffering)
588 `(flush-output-buffer ,stream-var))
590 `(when (eql byte #\Newline)
591 (flush-output-buffer ,stream-var)))
595 (defmacro def-output-routines/variable-width
596 ((name-fmt size restart external-format &rest bufferings)
598 (declare (optimize (speed 1)))
603 (intern (format nil name-fmt (string (car buffering))))))
605 (defun ,function (stream byte)
606 (declare (ignorable byte))
607 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
609 (setf *output-routines*
610 (nconc *output-routines*
618 (cdr buffering)))))))
621 ;;; Define output routines that output numbers SIZE bytes long for the
622 ;;; given bufferings. Use BODY to do the actual output.
623 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
625 (declare (optimize (speed 1)))
630 (intern (format nil name-fmt (string (car buffering))))))
632 (defun ,function (stream byte)
633 (output-wrapper (stream ,size ,buffering ,restart)
635 (setf *output-routines*
636 (nconc *output-routines*
644 (cdr buffering)))))))
647 ;;; FIXME: is this used anywhere any more?
648 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
654 (if (eql byte #\Newline)
655 (setf (fd-stream-char-pos stream) 0)
656 (incf (fd-stream-char-pos stream)))
657 (setf (sap-ref-8 (buffer-sap obuf) tail)
660 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
663 (:none (unsigned-byte 8))
664 (:full (unsigned-byte 8)))
665 (setf (sap-ref-8 (buffer-sap obuf) tail)
668 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
671 (:none (signed-byte 8))
672 (:full (signed-byte 8)))
673 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
676 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
679 (:none (unsigned-byte 16))
680 (:full (unsigned-byte 16)))
681 (setf (sap-ref-16 (buffer-sap obuf) tail)
684 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
687 (:none (signed-byte 16))
688 (:full (signed-byte 16)))
689 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
692 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
695 (:none (unsigned-byte 32))
696 (:full (unsigned-byte 32)))
697 (setf (sap-ref-32 (buffer-sap obuf) tail)
700 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
703 (:none (signed-byte 32))
704 (:full (signed-byte 32)))
705 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
708 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
710 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
713 (:none (unsigned-byte 64))
714 (:full (unsigned-byte 64)))
715 (setf (sap-ref-64 (buffer-sap obuf) tail)
717 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
720 (:none (signed-byte 64))
721 (:full (signed-byte 64)))
722 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
725 ;;; the routine to use to output a string. If the stream is
726 ;;; unbuffered, slam the string down the file descriptor, otherwise
727 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
728 ;;; checking to see where the last newline was.
729 (defun fd-sout (stream thing start end)
730 (declare (type fd-stream stream) (type string thing))
731 (let ((start (or start 0))
732 (end (or end (length (the vector thing)))))
733 (declare (fixnum start end))
735 (string-dispatch (simple-base-string
737 (simple-array character (*))
740 (position #\newline thing :from-end t
741 :start start :end end))))
742 (if (and (typep thing 'base-string)
743 (eq (fd-stream-external-format-keyword stream) :latin-1))
744 (ecase (fd-stream-buffering stream)
746 (buffer-output stream thing start end))
748 (buffer-output stream thing start end)
750 (flush-output-buffer stream)))
752 (write-or-buffer-output stream thing start end)))
753 (ecase (fd-stream-buffering stream)
754 (:full (funcall (fd-stream-output-bytes stream)
755 stream thing nil start end))
756 (:line (funcall (fd-stream-output-bytes stream)
757 stream thing last-newline start end))
758 (:none (funcall (fd-stream-output-bytes stream)
759 stream thing t start end))))
761 (setf (fd-stream-char-pos stream) (- end last-newline 1))
762 (incf (fd-stream-char-pos stream) (- end start))))))
764 (defstruct (external-format
765 (:constructor %make-external-format)
767 (:predicate external-format-p)
768 (:copier %copy-external-format))
769 ;; All the names that can refer to this external format. The first
770 ;; one is the canonical name.
771 (names (missing-arg) :type list :read-only t)
772 (default-replacement-character (missing-arg) :type character)
773 (read-n-chars-fun (missing-arg) :type function)
774 (read-char-fun (missing-arg) :type function)
775 (write-n-bytes-fun (missing-arg) :type function)
776 (write-char-none-buffered-fun (missing-arg) :type function)
777 (write-char-line-buffered-fun (missing-arg) :type function)
778 (write-char-full-buffered-fun (missing-arg) :type function)
779 ;; Can be nil for fixed-width formats.
780 (resync-fun nil :type (or function null))
781 (bytes-for-char-fun (missing-arg) :type function)
782 (read-c-string-fun (missing-arg) :type function)
783 (write-c-string-fun (missing-arg) :type function)
784 ;; We indirect through symbols in these functions so that a
785 ;; developer working on the octets code can easily redefine things
786 ;; and use the new function definition without redefining the
787 ;; external format as well. The slots above don't do any
788 ;; indirection because a developer working with those slots would be
789 ;; redefining the external format anyway.
790 (octets-to-string-fun (missing-arg) :type function)
791 (string-to-octets-fun (missing-arg) :type function))
793 (defun ef-char-size (ef-entry)
794 (if (variable-width-external-format-p ef-entry)
795 (bytes-for-char-fun ef-entry)
796 (funcall (bytes-for-char-fun ef-entry) #\x)))
798 (defun wrap-external-format-functions (external-format fun)
799 (let ((result (%copy-external-format external-format)))
800 (macrolet ((frob (accessor)
801 `(setf (,accessor result) (funcall fun (,accessor result)))))
802 (frob ef-read-n-chars-fun)
803 (frob ef-read-char-fun)
804 (frob ef-write-n-bytes-fun)
805 (frob ef-write-char-none-buffered-fun)
806 (frob ef-write-char-line-buffered-fun)
807 (frob ef-write-char-full-buffered-fun)
809 (frob ef-bytes-for-char-fun)
810 (frob ef-read-c-string-fun)
811 (frob ef-write-c-string-fun)
812 (frob ef-octets-to-string-fun)
813 (frob ef-string-to-octets-fun))
816 (defvar *external-formats* (make-hash-table)
818 "Hashtable of all available external formats. The table maps from
819 external-format names to EXTERNAL-FORMAT structures.")
821 (defun get-external-format (external-format)
822 (flet ((keyword-external-format (keyword)
823 (declare (type keyword keyword))
824 (gethash keyword *external-formats*))
825 (replacement-handlerify (entry replacement)
827 (wrap-external-format-functions
832 (declare (dynamic-extent rest))
834 ((stream-decoding-error
837 (invoke-restart 'input-replacement replacement)))
838 (stream-encoding-error
841 (invoke-restart 'output-replacement replacement)))
842 (octets-encoding-error
843 (lambda (c) (use-value replacement c)))
844 (octet-decoding-error
845 (lambda (c) (use-value replacement c))))
846 (apply fun rest)))))))))
847 (typecase external-format
848 (keyword (keyword-external-format external-format))
850 (let ((entry (keyword-external-format (car external-format)))
851 (replacement (getf (cdr external-format) :replacement)))
853 (replacement-handlerify entry replacement)
856 (defun get-external-format-or-lose (external-format)
857 (or (get-external-format external-format)
858 (error "Undefined external-format: ~S" external-format)))
860 (defun external-format-keyword (external-format)
861 (typecase external-format
862 (keyword external-format)
863 ((cons keyword) (car external-format))))
865 (defun fd-stream-external-format-keyword (stream)
866 (external-format-keyword (fd-stream-external-format stream)))
868 (defun canonize-external-format (external-format entry)
869 (typecase external-format
870 (keyword (first (ef-names entry)))
871 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
873 ;;; Find an output routine to use given the type and buffering. Return
874 ;;; as multiple values the routine, the real type transfered, and the
875 ;;; number of bytes per element.
876 (defun pick-output-routine (type buffering &optional external-format)
877 (when (subtypep type 'character)
878 (let ((entry (get-external-format-or-lose external-format)))
879 (return-from pick-output-routine
880 (values (ecase buffering
881 (:none (ef-write-char-none-buffered-fun entry))
882 (:line (ef-write-char-line-buffered-fun entry))
883 (:full (ef-write-char-full-buffered-fun entry)))
886 (ef-write-n-bytes-fun entry)
888 (canonize-external-format external-format entry)))))
889 (dolist (entry *output-routines*)
890 (when (and (subtypep type (first entry))
891 (eq buffering (second entry))
892 (or (not (fifth entry))
893 (eq external-format (fifth entry))))
894 (return-from pick-output-routine
895 (values (symbol-function (third entry))
898 ;; KLUDGE: dealing with the buffering here leads to excessive code
901 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
902 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
903 if (subtypep type `(unsigned-byte ,i))
904 do (return-from pick-output-routine
908 (lambda (stream byte)
909 (output-wrapper (stream (/ i 8) (:none) nil)
910 (loop for j from 0 below (/ i 8)
911 do (setf (sap-ref-8 (buffer-sap obuf)
913 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
915 (lambda (stream byte)
916 (output-wrapper (stream (/ i 8) (:full) nil)
917 (loop for j from 0 below (/ i 8)
918 do (setf (sap-ref-8 (buffer-sap obuf)
920 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
923 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
924 if (subtypep type `(signed-byte ,i))
925 do (return-from pick-output-routine
929 (lambda (stream byte)
930 (output-wrapper (stream (/ i 8) (:none) nil)
931 (loop for j from 0 below (/ i 8)
932 do (setf (sap-ref-8 (buffer-sap obuf)
934 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
936 (lambda (stream byte)
937 (output-wrapper (stream (/ i 8) (:full) nil)
938 (loop for j from 0 below (/ i 8)
939 do (setf (sap-ref-8 (buffer-sap obuf)
941 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
945 ;;;; input routines and related noise
947 ;;; a list of all available input routines. Each element is a list of
948 ;;; the element-type input, the function name, and the number of bytes
950 (defvar *input-routines* ())
952 ;;; Return whether a primitive partial read operation on STREAM's FD
953 ;;; would (probably) block. Signal a `simple-stream-error' if the
954 ;;; system call implementing this operation fails.
956 ;;; It is "may" instead of "would" because "would" is not quite
957 ;;; correct on win32. However, none of the places that use it require
958 ;;; further assurance than "may" versus "will definitely not".
959 (defun sysread-may-block-p (stream)
961 ;; This answers T at EOF on win32, I think.
962 (not (sb!win32:fd-listen (fd-stream-fd stream)))
964 (not (sb!unix:unix-simple-poll (fd-stream-fd stream) :input 0)))
966 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
967 ;;; then fill the input buffer, and return the number of bytes read. Throws
968 ;;; to EOF-INPUT-CATCHER if the eof was reached.
969 (defun refill-input-buffer (stream)
970 (dx-let ((fd (fd-stream-fd stream))
974 ;; Check for blocking input before touching the stream if we are to
975 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
976 ;; read(). Regular files should never block, so we can elide the check.
977 (if (and (neq :regular (fd-stream-fd-type stream))
978 (sysread-may-block-p stream))
981 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
982 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
984 (closed-flame stream)
986 (simple-stream-perror "couldn't read from ~S" stream errno)
988 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
989 ;; to wait for input if read tells us EWOULDBLOCK.
990 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream)
991 (fd-stream-serve-events stream))
992 (signal-timeout 'io-timeout
995 :seconds (fd-stream-timeout stream)))
997 ;; Since the read should not block, we'll disable the
998 ;; interrupts here, so that we don't accidentally unwind and
999 ;; leave the stream in an inconsistent state.
1001 ;; Execute the nlx outside without-interrupts to ensure the
1002 ;; resulting thunk is stack-allocatable.
1003 ((lambda (return-reason)
1004 (ecase return-reason
1005 ((nil)) ; fast path normal cases
1006 ((:wait-for-input) (go :wait-for-input))
1007 ((:closed-flame) (go :closed-flame))
1008 ((:read-error) (go :read-error))))
1010 ;; Check the buffer: if it is null, then someone has closed
1011 ;; the stream from underneath us. This is not ment to fix
1012 ;; multithreaded races, but to deal with interrupt handlers
1013 ;; closing the stream.
1016 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1017 (sap (buffer-sap ibuf))
1018 (length (buffer-length ibuf))
1019 (head (buffer-head ibuf))
1020 (tail (buffer-tail ibuf)))
1021 (declare (index length head tail)
1022 (inline sb!unix:unix-read))
1023 (unless (zerop head)
1024 (cond ((eql head tail)
1025 ;; Buffer is empty, but not at yet reset -- make it so.
1028 (reset-buffer ibuf))
1030 ;; Buffer has things in it, but they are not at the
1031 ;; head -- move them there.
1032 (let ((n (- tail head)))
1033 (system-area-ub8-copy sap head sap 0 n)
1035 (buffer-head ibuf) head
1037 (buffer-tail ibuf) tail)))))
1038 (setf (fd-stream-listen stream) nil)
1039 (setf (values count errno)
1040 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1043 (return :read-error)
1045 (if (eql errno sb!unix:ewouldblock)
1046 (return :wait-for-input)
1047 (return :read-error)))
1049 (setf (fd-stream-listen stream) :eof)
1050 (/show0 "THROWing EOF-INPUT-CATCHER")
1051 (throw 'eof-input-catcher nil))
1053 ;; Success! (Do not use INCF, for sake of other threads.)
1054 (setf (buffer-tail ibuf) (+ count tail))))))))))
1057 ;;; Make sure there are at least BYTES number of bytes in the input
1058 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1059 (defmacro input-at-least (stream bytes)
1060 (let ((stream-var (gensym "STREAM"))
1061 (bytes-var (gensym "BYTES"))
1062 (buffer-var (gensym "IBUF")))
1063 `(let* ((,stream-var ,stream)
1065 (,buffer-var (fd-stream-ibuf ,stream-var)))
1067 (when (>= (- (buffer-tail ,buffer-var)
1068 (buffer-head ,buffer-var))
1071 (refill-input-buffer ,stream-var)))))
1073 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1075 (let ((stream-var (gensym "STREAM"))
1076 (retry-var (gensym "RETRY"))
1077 (element-var (gensym "ELT")))
1078 `(let* ((,stream-var ,stream)
1079 (ibuf (fd-stream-ibuf ,stream-var))
1082 (when (fd-stream-eof-forced-p ,stream-var)
1083 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1084 (return-from use-instead
1085 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1086 (let ((,element-var nil)
1087 (decode-break-reason nil))
1088 (do ((,retry-var t))
1090 (if (> (length (fd-stream-instead ,stream-var)) 0)
1091 (let* ((instead (fd-stream-instead ,stream-var))
1092 (result (vector-pop instead))
1093 (pointer (fill-pointer instead)))
1095 (setf (fd-stream-listen ,stream-var) nil))
1096 (return-from use-instead result))
1098 (catch 'eof-input-catcher
1099 (setf decode-break-reason
1100 (block decode-break-reason
1101 (input-at-least ,stream-var ,(if (consp bytes) (car bytes) `(setq size ,bytes)))
1102 (let* ((byte (sap-ref-8 (buffer-sap ibuf) (buffer-head ibuf))))
1103 (declare (ignorable byte))
1104 ,@(when (consp bytes)
1105 `((let ((sap (buffer-sap ibuf))
1106 (head (buffer-head ibuf)))
1107 (declare (ignorable sap head))
1108 (setq size ,(cadr bytes))
1109 (input-at-least ,stream-var size))))
1110 (setq ,element-var (locally ,@read-forms))
1111 (setq ,retry-var nil))
1113 (when decode-break-reason
1114 (when (stream-decoding-error-and-handle
1115 stream decode-break-reason)
1116 (setq ,retry-var nil)
1117 (throw 'eof-input-catcher nil)))
1119 (let ((octet-count (- (buffer-tail ibuf)
1120 (buffer-head ibuf))))
1121 (when (or (zerop octet-count)
1122 (and (not ,element-var)
1123 (not decode-break-reason)
1124 (stream-decoding-error-and-handle
1125 stream octet-count)))
1126 (setq ,retry-var nil))))))
1128 (incf (buffer-head ibuf) size)
1131 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1133 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1134 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1135 (let ((stream-var (gensym "STREAM"))
1136 (element-var (gensym "ELT")))
1137 `(let* ((,stream-var ,stream)
1138 (ibuf (fd-stream-ibuf ,stream-var)))
1139 (if (> (length (fd-stream-instead ,stream-var)) 0)
1140 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1142 (catch 'eof-input-catcher
1143 (input-at-least ,stream-var ,bytes)
1144 (locally ,@read-forms))))
1146 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1149 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1151 (defmacro def-input-routine/variable-width (name
1152 (type external-format size sap head)
1155 (defun ,name (stream eof-error eof-value)
1156 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1157 (let ((,sap (buffer-sap ibuf))
1158 (,head (buffer-head ibuf)))
1160 (setf *input-routines*
1161 (nconc *input-routines*
1162 (list (list ',type ',name 1 ',external-format))))))
1164 (defmacro def-input-routine (name
1165 (type size sap head)
1168 (defun ,name (stream eof-error eof-value)
1169 (input-wrapper (stream ,size eof-error eof-value)
1170 (let ((,sap (buffer-sap ibuf))
1171 (,head (buffer-head ibuf)))
1173 (setf *input-routines*
1174 (nconc *input-routines*
1175 (list (list ',type ',name ',size nil))))))
1177 ;;; STREAM-IN routine for reading a string char
1178 (def-input-routine input-character
1179 (character 1 sap head)
1180 (code-char (sap-ref-8 sap head)))
1182 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1183 (def-input-routine input-unsigned-8bit-byte
1184 ((unsigned-byte 8) 1 sap head)
1185 (sap-ref-8 sap head))
1187 ;;; STREAM-IN routine for reading a signed 8 bit number
1188 (def-input-routine input-signed-8bit-number
1189 ((signed-byte 8) 1 sap head)
1190 (signed-sap-ref-8 sap head))
1192 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1193 (def-input-routine input-unsigned-16bit-byte
1194 ((unsigned-byte 16) 2 sap head)
1195 (sap-ref-16 sap head))
1197 ;;; STREAM-IN routine for reading a signed 16 bit number
1198 (def-input-routine input-signed-16bit-byte
1199 ((signed-byte 16) 2 sap head)
1200 (signed-sap-ref-16 sap head))
1202 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1203 (def-input-routine input-unsigned-32bit-byte
1204 ((unsigned-byte 32) 4 sap head)
1205 (sap-ref-32 sap head))
1207 ;;; STREAM-IN routine for reading a signed 32 bit number
1208 (def-input-routine input-signed-32bit-byte
1209 ((signed-byte 32) 4 sap head)
1210 (signed-sap-ref-32 sap head))
1212 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1214 (def-input-routine input-unsigned-64bit-byte
1215 ((unsigned-byte 64) 8 sap head)
1216 (sap-ref-64 sap head))
1217 (def-input-routine input-signed-64bit-byte
1218 ((signed-byte 64) 8 sap head)
1219 (signed-sap-ref-64 sap head)))
1221 ;;; Find an input routine to use given the type. Return as multiple
1222 ;;; values the routine, the real type transfered, and the number of
1223 ;;; bytes per element (and for character types string input routine).
1224 (defun pick-input-routine (type &optional external-format)
1225 (when (subtypep type 'character)
1226 (let ((entry (get-external-format-or-lose external-format)))
1227 (return-from pick-input-routine
1228 (values (ef-read-char-fun entry)
1231 (ef-read-n-chars-fun entry)
1232 (ef-char-size entry)
1233 (canonize-external-format external-format entry)))))
1234 (dolist (entry *input-routines*)
1235 (when (and (subtypep type (first entry))
1236 (or (not (fourth entry))
1237 (eq external-format (fourth entry))))
1238 (return-from pick-input-routine
1239 (values (symbol-function (second entry))
1242 ;; FIXME: let's do it the hard way, then (but ignore things like
1243 ;; endianness, efficiency, and the necessary coupling between these
1244 ;; and the output routines). -- CSR, 2004-02-09
1245 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1246 if (subtypep type `(unsigned-byte ,i))
1247 do (return-from pick-input-routine
1249 (lambda (stream eof-error eof-value)
1250 (input-wrapper (stream (/ i 8) eof-error eof-value)
1251 (let ((sap (buffer-sap ibuf))
1252 (head (buffer-head ibuf)))
1253 (loop for j from 0 below (/ i 8)
1257 (sap-ref-8 sap (+ head j))))
1258 finally (return result)))))
1261 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1262 if (subtypep type `(signed-byte ,i))
1263 do (return-from pick-input-routine
1265 (lambda (stream eof-error eof-value)
1266 (input-wrapper (stream (/ i 8) eof-error eof-value)
1267 (let ((sap (buffer-sap ibuf))
1268 (head (buffer-head ibuf)))
1269 (loop for j from 0 below (/ i 8)
1273 (sap-ref-8 sap (+ head j))))
1274 finally (return (if (logbitp (1- i) result)
1275 (dpb result (byte i 0) -1)
1280 ;;; the N-BIN method for FD-STREAMs
1282 ;;; Note that this blocks in UNIX-READ. It is generally used where
1283 ;;; there is a definite amount of reading to be done, so blocking
1284 ;;; isn't too problematical.
1285 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1286 &aux (total-copied 0))
1287 (declare (type fd-stream stream))
1288 (declare (type index start requested total-copied))
1289 (aver (= (length (fd-stream-instead stream)) 0))
1292 (let* ((remaining-request (- requested total-copied))
1293 (ibuf (fd-stream-ibuf stream))
1294 (head (buffer-head ibuf))
1295 (tail (buffer-tail ibuf))
1296 (available (- tail head))
1297 (n-this-copy (min remaining-request available))
1298 (this-start (+ start total-copied))
1299 (this-end (+ this-start n-this-copy))
1300 (sap (buffer-sap ibuf)))
1301 (declare (type index remaining-request head tail available))
1302 (declare (type index n-this-copy))
1303 ;; Copy data from stream buffer into user's buffer.
1304 (%byte-blt sap head buffer this-start this-end)
1305 (incf (buffer-head ibuf) n-this-copy)
1306 (incf total-copied n-this-copy)
1307 ;; Maybe we need to refill the stream buffer.
1308 (cond (;; If there were enough data in the stream buffer, we're done.
1309 (eql total-copied requested)
1310 (return total-copied))
1311 (;; If EOF, we're done in another way.
1312 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1314 (error 'end-of-file :stream stream)
1315 (return total-copied)))
1316 ;; Otherwise we refilled the stream buffer, so fall
1317 ;; through into another pass of the loop.
1320 (defun fd-stream-resync (stream)
1321 (let ((entry (get-external-format (fd-stream-external-format stream))))
1323 (funcall (ef-resync-fun entry) stream))))
1325 (defun get-fd-stream-character-sizer (stream)
1326 (let ((entry (get-external-format (fd-stream-external-format stream))))
1328 (ef-bytes-for-char-fun entry))))
1330 (defun fd-stream-character-size (stream char)
1331 (let ((sizer (get-fd-stream-character-sizer stream)))
1332 (when sizer (funcall sizer char))))
1334 (defun fd-stream-string-size (stream string)
1335 (let ((sizer (get-fd-stream-character-sizer stream)))
1337 (loop for char across string summing (funcall sizer char)))))
1339 (defun find-external-format (external-format)
1340 (when external-format
1341 (get-external-format external-format)))
1343 (defun variable-width-external-format-p (ef-entry)
1344 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1346 (defun bytes-for-char-fun (ef-entry)
1347 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1349 (defmacro define-unibyte-mapping-external-format
1350 (canonical-name (&rest other-names) &body exceptions)
1351 (let ((->code-name (symbolicate canonical-name '->code-mapper))
1352 (code->-name (symbolicate 'code-> canonical-name '-mapper))
1353 (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1354 (string->-name (symbolicate 'string-> canonical-name))
1355 (define-string*-name (symbolicate 'define- canonical-name '->string*))
1356 (string*-name (symbolicate canonical-name '->string*))
1357 (define-string-name (symbolicate 'define- canonical-name '->string))
1358 (string-name (symbolicate canonical-name '->string))
1359 (->string-aref-name (symbolicate canonical-name '->string-aref)))
1361 (define-unibyte-mapper ,->code-name ,code->-name
1363 (declaim (inline ,get-bytes-name))
1364 (defun ,get-bytes-name (string pos)
1365 (declare (optimize speed (safety 0))
1366 (type simple-string string)
1367 (type array-range pos))
1368 (get-latin-bytes #',code->-name ,canonical-name string pos))
1369 (defun ,string->-name (string sstart send null-padding)
1370 (declare (optimize speed (safety 0))
1371 (type simple-string string)
1372 (type array-range sstart send))
1373 (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1374 (defmacro ,define-string*-name (accessor type)
1375 (declare (ignore type))
1376 (let ((name (make-od-name ',string*-name accessor)))
1378 (defun ,name (string sstart send array astart aend)
1379 (,(make-od-name 'latin->string* accessor)
1380 string sstart send array astart aend #',',->code-name)))))
1381 (instantiate-octets-definition ,define-string*-name)
1382 (defmacro ,define-string-name (accessor type)
1383 (declare (ignore type))
1384 (let ((name (make-od-name ',string-name accessor)))
1386 (defun ,name (array astart aend)
1387 (,(make-od-name 'latin->string accessor)
1388 array astart aend #',',->code-name)))))
1389 (instantiate-octets-definition ,define-string-name)
1390 (define-unibyte-external-format ,canonical-name ,other-names
1391 (let ((octet (,code->-name bits)))
1393 (setf (sap-ref-8 sap tail) octet)
1394 (external-format-encoding-error stream bits)))
1395 (let ((code (,->code-name byte)))
1398 (return-from decode-break-reason 1)))
1402 (defmacro define-unibyte-external-format
1403 (canonical-name (&rest other-names)
1404 out-form in-form octets-to-string-symbol string-to-octets-symbol)
1405 `(define-external-format/variable-width (,canonical-name ,@other-names)
1410 ,octets-to-string-symbol
1411 ,string-to-octets-symbol))
1413 (defmacro define-external-format/variable-width
1414 (external-format output-restart replacement-character
1415 out-size-expr out-expr in-size-expr in-expr
1416 octets-to-string-sym string-to-octets-sym)
1417 (let* ((name (first external-format))
1418 (out-function (symbolicate "OUTPUT-BYTES/" name))
1419 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1420 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1421 (in-char-function (symbolicate "INPUT-CHAR/" name))
1422 (resync-function (symbolicate "RESYNC/" name))
1423 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1424 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1425 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1426 (n-buffer (gensym "BUFFER")))
1428 (defun ,size-function (byte)
1429 (declare (ignorable byte))
1431 (defun ,out-function (stream string flush-p start end)
1432 (let ((start (or start 0))
1433 (end (or end (length string))))
1434 (declare (type index start end))
1435 (synchronize-stream-output stream)
1436 (unless (<= 0 start end (length string))
1437 (sequence-bounding-indices-bad-error string start end))
1440 (let ((obuf (fd-stream-obuf stream)))
1441 (string-dispatch (simple-base-string
1442 #!+sb-unicode (simple-array character (*))
1445 (let ((len (buffer-length obuf))
1446 (sap (buffer-sap obuf))
1448 (tail (buffer-tail obuf)))
1449 (declare (type index tail)
1450 ;; STRING bounds have already been checked.
1451 (optimize (safety 0)))
1452 (,@(if output-restart
1453 `(catch 'output-nothing)
1456 ((or (= start end) (< (- len tail) 4)))
1457 (let* ((byte (aref string start))
1458 (bits (char-code byte))
1459 (size ,out-size-expr))
1462 (setf (buffer-tail obuf) tail)
1465 ;; Exited via CATCH: skip the current character.
1469 (flush-output-buffer stream)))
1471 (flush-output-buffer stream))))
1472 (def-output-routines/variable-width (,format
1479 (if (eql byte #\Newline)
1480 (setf (fd-stream-char-pos stream) 0)
1481 (incf (fd-stream-char-pos stream)))
1482 (let ((bits (char-code byte))
1483 (sap (buffer-sap obuf))
1484 (tail (buffer-tail obuf)))
1486 (defun ,in-function (stream buffer start requested eof-error-p
1487 &aux (total-copied 0))
1488 (declare (type fd-stream stream)
1489 (type index start requested total-copied)
1491 (simple-array character (#.+ansi-stream-in-buffer-length+))
1493 (when (fd-stream-eof-forced-p stream)
1494 (setf (fd-stream-eof-forced-p stream) nil)
1495 (return-from ,in-function 0))
1496 (do ((instead (fd-stream-instead stream)))
1497 ((= (fill-pointer instead) 0)
1498 (setf (fd-stream-listen stream) nil))
1499 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1501 (when (= requested total-copied)
1502 (when (= (fill-pointer instead) 0)
1503 (setf (fd-stream-listen stream) nil))
1504 (return-from ,in-function total-copied)))
1507 (let* ((ibuf (fd-stream-ibuf stream))
1508 (head (buffer-head ibuf))
1509 (tail (buffer-tail ibuf))
1510 (sap (buffer-sap ibuf))
1511 (decode-break-reason nil))
1512 (declare (type index head tail))
1513 ;; Copy data from stream buffer into user's buffer.
1514 (do ((size nil nil))
1515 ((or (= tail head) (= requested total-copied)))
1516 (setf decode-break-reason
1517 (block decode-break-reason
1518 ,@(when (consp in-size-expr)
1519 `((when (> ,(car in-size-expr) (- tail head))
1521 (let ((byte (sap-ref-8 sap head)))
1522 (declare (ignorable byte))
1523 (setq size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr))
1524 (when (> size (- tail head))
1526 (setf (aref buffer (+ start total-copied)) ,in-expr)
1530 (setf (buffer-head ibuf) head)
1531 (when decode-break-reason
1532 ;; If we've already read some characters on when the invalid
1533 ;; code sequence is detected, we return immediately. The
1534 ;; handling of the error is deferred until the next call
1535 ;; (where this check will be false). This allows establishing
1536 ;; high-level handlers for decode errors (for example
1537 ;; automatically resyncing in Lisp comments).
1538 (when (plusp total-copied)
1539 (return-from ,in-function total-copied))
1540 (when (stream-decoding-error-and-handle
1541 stream decode-break-reason)
1543 (error 'end-of-file :stream stream)
1544 (return-from ,in-function total-copied)))
1545 ;; we might have been given stuff to use instead, so
1546 ;; we have to return (and trust our caller to know
1547 ;; what to do about TOTAL-COPIED being 0).
1548 (return-from ,in-function total-copied)))
1549 (setf (buffer-head ibuf) head)
1550 ;; Maybe we need to refill the stream buffer.
1551 (cond ( ;; If was data in the stream buffer, we're done.
1552 (plusp total-copied)
1553 (return total-copied))
1554 ( ;; If EOF, we're done in another way.
1555 (or (eq decode-break-reason 'eof)
1556 (null (catch 'eof-input-catcher
1557 (refill-input-buffer stream))))
1559 (error 'end-of-file :stream stream)
1560 (return total-copied)))
1561 ;; Otherwise we refilled the stream buffer, so fall
1562 ;; through into another pass of the loop.
1564 (def-input-routine/variable-width ,in-char-function (character
1568 (let ((byte (sap-ref-8 sap head)))
1569 (declare (ignorable byte))
1571 (defun ,resync-function (stream)
1572 (let ((ibuf (fd-stream-ibuf stream))
1574 (catch 'eof-input-catcher
1576 (incf (buffer-head ibuf))
1577 (input-at-least stream ,(if (consp in-size-expr) (car in-size-expr) `(setq size ,in-size-expr)))
1578 (unless (block decode-break-reason
1579 (let* ((sap (buffer-sap ibuf))
1580 (head (buffer-head ibuf))
1581 (byte (sap-ref-8 sap head)))
1582 (declare (ignorable byte))
1583 ,@(when (consp in-size-expr)
1584 `((setq size ,(cadr in-size-expr))
1585 (input-at-least stream size)))
1586 (setf head (buffer-head ibuf))
1590 (defun ,read-c-string-function (sap element-type)
1591 (declare (type system-area-pointer sap))
1593 (declare (optimize (speed 3) (safety 0)))
1594 (let* ((stream ,name)
1595 (size 0) (head 0) (byte 0) (char nil)
1596 (decode-break-reason nil)
1597 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1598 (setf decode-break-reason
1599 (block decode-break-reason
1600 (setf byte (sap-ref-8 sap head)
1601 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1605 (when decode-break-reason
1606 (c-string-decoding-error ,name decode-break-reason))
1607 (when (zerop (char-code char))
1609 (string (make-string length :element-type element-type)))
1610 (declare (ignorable stream)
1611 (type index head length) ;; size
1612 (type (unsigned-byte 8) byte)
1613 (type (or null character) char)
1614 (type string string))
1616 (dotimes (index length string)
1617 (setf decode-break-reason
1618 (block decode-break-reason
1619 (setf byte (sap-ref-8 sap head)
1620 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1624 (when decode-break-reason
1625 (c-string-decoding-error ,name decode-break-reason))
1626 (setf (aref string index) char)))))
1628 (defun ,output-c-string-function (string)
1629 (declare (type simple-string string))
1631 (declare (optimize (speed 3) (safety 0)))
1632 (let* ((length (length string))
1633 (char-length (make-array (1+ length) :element-type 'index))
1635 (+ (loop for i of-type index below length
1636 for byte of-type character = (aref string i)
1637 for bits = (char-code byte)
1638 sum (setf (aref char-length i)
1639 (the index ,out-size-expr)))
1640 (let* ((byte (code-char 0))
1641 (bits (char-code byte)))
1642 (declare (ignorable byte bits))
1643 (setf (aref char-length length)
1644 (the index ,out-size-expr)))))
1646 (,n-buffer (make-array buffer-length
1647 :element-type '(unsigned-byte 8)))
1649 (declare (type index length buffer-length tail)
1652 (with-pinned-objects (,n-buffer)
1653 (let ((sap (vector-sap ,n-buffer)))
1654 (declare (system-area-pointer sap))
1655 (loop for i of-type index below length
1656 for byte of-type character = (aref string i)
1657 for bits = (char-code byte)
1658 for size of-type index = (aref char-length i)
1663 (byte (code-char bits))
1664 (size (aref char-length length)))
1665 (declare (ignorable bits byte size))
1669 (let ((entry (%make-external-format
1670 :names ',external-format
1671 :default-replacement-character ,replacement-character
1672 :read-n-chars-fun #',in-function
1673 :read-char-fun #',in-char-function
1674 :write-n-bytes-fun #',out-function
1675 ,@(mapcan #'(lambda (buffering)
1676 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1677 `#',(intern (format nil format (string buffering)))))
1678 '(:none :line :full))
1679 :resync-fun #',resync-function
1680 :bytes-for-char-fun #',size-function
1681 :read-c-string-fun #',read-c-string-function
1682 :write-c-string-fun #',output-c-string-function
1683 :octets-to-string-fun (lambda (&rest rest)
1684 (declare (dynamic-extent rest))
1685 (apply ',octets-to-string-sym rest))
1686 :string-to-octets-fun (lambda (&rest rest)
1687 (declare (dynamic-extent rest))
1688 (apply ',string-to-octets-sym rest)))))
1689 (dolist (ef ',external-format)
1690 (setf (gethash ef *external-formats*) entry))))))
1692 ;;;; utility functions (misc routines, etc)
1694 ;;; Fill in the various routine slots for the given type. INPUT-P and
1695 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1696 ;;; set prior to calling this routine.
1697 (defun set-fd-stream-routines (fd-stream element-type external-format
1698 input-p output-p buffer-p)
1699 (let* ((target-type (case element-type
1700 (unsigned-byte '(unsigned-byte 8))
1701 (signed-byte '(signed-byte 8))
1702 (:default 'character)
1704 (character-stream-p (subtypep target-type 'character))
1705 (bivalent-stream-p (eq element-type :default))
1706 normalized-external-format
1708 (bin-routine #'ill-bin)
1711 (cin-routine #'ill-in)
1714 (input-type nil) ;calculated from bin-type/cin-type
1715 (input-size nil) ;calculated from bin-size/cin-size
1716 (read-n-characters #'ill-in)
1717 (bout-routine #'ill-bout)
1720 (cout-routine #'ill-out)
1725 (output-bytes #'ill-bout))
1727 ;; Ensure that we have buffers in the desired direction(s) only,
1728 ;; getting new ones and dropping/resetting old ones as necessary.
1729 (let ((obuf (fd-stream-obuf fd-stream)))
1733 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1735 (setf (fd-stream-obuf fd-stream) nil)
1736 (release-buffer obuf))))
1738 (let ((ibuf (fd-stream-ibuf fd-stream)))
1742 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1744 (setf (fd-stream-ibuf fd-stream) nil)
1745 (release-buffer ibuf))))
1747 ;; FIXME: Why only for output? Why unconditionally?
1749 (setf (fd-stream-char-pos fd-stream) 0))
1751 (when (and character-stream-p (eq external-format :default))
1752 (/show0 "/getting default external format")
1753 (setf external-format (default-external-format)))
1756 (when (or (not character-stream-p) bivalent-stream-p)
1757 (setf (values bin-routine bin-type bin-size read-n-characters
1758 char-size normalized-external-format)
1759 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1763 (error "could not find any input routine for ~S" target-type)))
1764 (when character-stream-p
1765 (setf (values cin-routine cin-type cin-size read-n-characters
1766 char-size normalized-external-format)
1767 (pick-input-routine target-type external-format))
1769 (error "could not find any input routine for ~S" target-type)))
1770 (setf (fd-stream-in fd-stream) cin-routine
1771 (fd-stream-bin fd-stream) bin-routine)
1772 ;; character type gets preferential treatment
1773 (setf input-size (or cin-size bin-size))
1774 (setf input-type (or cin-type bin-type))
1775 (when normalized-external-format
1776 (setf (fd-stream-external-format fd-stream) normalized-external-format
1777 (fd-stream-char-size fd-stream) char-size))
1778 (when (= (or cin-size 1) (or bin-size 1) 1)
1779 (setf (fd-stream-n-bin fd-stream) ;XXX
1780 (if (and character-stream-p (not bivalent-stream-p))
1782 #'fd-stream-read-n-bytes))
1783 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1784 ;; for character and (unsigned-byte 8) streams. In these
1785 ;; cases, fast-read-* will read from the
1786 ;; ansi-stream-(c)in-buffer, saving function calls.
1787 ;; Otherwise, the various data-reading functions in the stream
1788 ;; structure will be called.
1790 (not bivalent-stream-p)
1791 ;; temporary disable on :io streams
1793 (cond (character-stream-p
1794 (setf (ansi-stream-cin-buffer fd-stream)
1795 (make-array +ansi-stream-in-buffer-length+
1796 :element-type 'character)))
1797 ((equal target-type '(unsigned-byte 8))
1798 (setf (ansi-stream-in-buffer fd-stream)
1799 (make-array +ansi-stream-in-buffer-length+
1800 :element-type '(unsigned-byte 8))))))))
1803 (when (or (not character-stream-p) bivalent-stream-p)
1804 (setf (values bout-routine bout-type bout-size output-bytes
1805 char-size normalized-external-format)
1806 (let ((buffering (fd-stream-buffering fd-stream)))
1807 (if bivalent-stream-p
1808 (pick-output-routine '(unsigned-byte 8)
1809 (if (eq :line buffering)
1813 (pick-output-routine target-type buffering external-format))))
1814 (unless bout-routine
1815 (error "could not find any output routine for ~S buffered ~S"
1816 (fd-stream-buffering fd-stream)
1818 (when character-stream-p
1819 (setf (values cout-routine cout-type cout-size output-bytes
1820 char-size normalized-external-format)
1821 (pick-output-routine target-type
1822 (fd-stream-buffering fd-stream)
1824 (unless cout-routine
1825 (error "could not find any output routine for ~S buffered ~S"
1826 (fd-stream-buffering fd-stream)
1828 (when normalized-external-format
1829 (setf (fd-stream-external-format fd-stream) normalized-external-format
1830 (fd-stream-char-size fd-stream) char-size))
1831 (when character-stream-p
1832 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1833 (setf (fd-stream-out fd-stream) cout-routine
1834 (fd-stream-bout fd-stream) bout-routine
1835 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1836 #'fd-sout #'ill-out))
1837 (setf output-size (or cout-size bout-size))
1838 (setf output-type (or cout-type bout-type)))
1840 (when (and input-size output-size
1841 (not (eq input-size output-size)))
1842 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1843 input-type input-size
1844 output-type output-size))
1845 (setf (fd-stream-element-size fd-stream)
1846 (or input-size output-size))
1848 (setf (fd-stream-element-type fd-stream)
1849 (cond ((equal input-type output-type)
1855 ((subtypep input-type output-type)
1857 ((subtypep output-type input-type)
1860 (error "Input type (~S) and output type (~S) are unrelated?"
1864 ;;; Handles the resource-release aspects of stream closing, and marks
1866 (defun release-fd-stream-resources (fd-stream)
1869 ;; Drop handlers first.
1870 (when (fd-stream-handler fd-stream)
1871 (remove-fd-handler (fd-stream-handler fd-stream))
1872 (setf (fd-stream-handler fd-stream) nil))
1873 ;; Disable interrupts so that a asynch unwind will not leave
1874 ;; us with a dangling finalizer (that would close the same
1875 ;; --possibly reassigned-- FD again), or a stream with a closed
1876 ;; FD that appears open.
1877 (sb!unix:unix-close (fd-stream-fd fd-stream))
1878 (set-closed-flame fd-stream)
1879 (when (fboundp 'cancel-finalization)
1880 (cancel-finalization fd-stream)))
1881 ;; On error unwind from WITHOUT-INTERRUPTS.
1882 (serious-condition (e)
1884 ;; Release all buffers. If this is undone, or interrupted,
1885 ;; we're still safe: buffers have finalizers of their own.
1886 (release-fd-stream-buffers fd-stream))
1888 ;;; Flushes the current input buffer and any supplied replacements,
1889 ;;; and returns the input buffer, and the amount of of flushed input
1891 (defun flush-input-buffer (stream)
1892 (let ((unread (length (fd-stream-instead stream))))
1893 (setf (fill-pointer (fd-stream-instead stream)) 0)
1894 (let ((ibuf (fd-stream-ibuf stream)))
1896 (let ((head (buffer-head ibuf))
1897 (tail (buffer-tail ibuf)))
1898 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1899 (values nil unread)))))
1901 (defun fd-stream-clear-input (stream)
1902 (flush-input-buffer stream)
1905 (sb!win32:fd-clear-input (fd-stream-fd stream))
1906 (setf (fd-stream-listen stream) nil))
1908 (catch 'eof-input-catcher
1909 (loop until (sysread-may-block-p stream)
1911 (refill-input-buffer stream)
1912 (reset-buffer (fd-stream-ibuf stream)))
1915 ;;; Handle miscellaneous operations on FD-STREAM.
1916 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1917 (declare (ignore arg2))
1920 (labels ((do-listen ()
1921 (let ((ibuf (fd-stream-ibuf fd-stream)))
1922 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1923 (fd-stream-listen fd-stream)
1925 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1927 ;; If the read can block, LISTEN will certainly return NIL.
1928 (if (sysread-may-block-p fd-stream)
1930 ;; Otherwise select(2) and CL:LISTEN have slightly
1931 ;; different semantics. The former returns that an FD
1932 ;; is readable when a read operation wouldn't block.
1933 ;; That includes EOF. However, LISTEN must return NIL
1935 (progn (catch 'eof-input-catcher
1936 ;; r-b/f too calls select, but it shouldn't
1937 ;; block as long as read can return once w/o
1939 (refill-input-buffer fd-stream))
1940 ;; At this point either IBUF-HEAD != IBUF-TAIL
1941 ;; and FD-STREAM-LISTEN is NIL, in which case
1942 ;; we should return T, or IBUF-HEAD ==
1943 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1944 ;; which case we should return :EOF for this
1945 ;; call and all future LISTEN call on this stream.
1946 ;; Call ourselves again to determine which case
1951 (decf (buffer-head (fd-stream-ibuf fd-stream))
1952 (fd-stream-character-size fd-stream arg1)))
1954 ;; Drop input buffers
1955 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1956 (ansi-stream-cin-buffer fd-stream) nil
1957 (ansi-stream-in-buffer fd-stream) nil)
1959 ;; We got us an abort on our hands.
1960 (let ((outputp (fd-stream-obuf fd-stream))
1961 (file (fd-stream-file fd-stream))
1962 (orig (fd-stream-original fd-stream)))
1963 ;; This takes care of the important stuff -- everything
1964 ;; rest is cleaning up the file-system, which we cannot
1965 ;; do on some platforms as long as the file is open.
1966 (release-fd-stream-resources fd-stream)
1967 ;; We can't do anything unless we know what file were
1968 ;; dealing with, and we don't want to do anything
1969 ;; strange unless we were writing to the file.
1970 (when (and outputp file)
1972 ;; If the original is EQ to file we are appending to
1973 ;; and can just close the file without renaming.
1974 (unless (eq orig file)
1975 ;; We have a handle on the original, just revert.
1976 (multiple-value-bind (okay err)
1977 (sb!unix:unix-rename orig file)
1978 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1979 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1982 (error 'simple-stream-error
1984 "~@<Couldn't restore ~S to its original contents ~
1985 from ~S while closing ~S: ~2I~_~A~:>"
1987 (list file orig fd-stream (strerror err))
1988 :stream fd-stream))))
1989 ;; We can't restore the original, and aren't
1990 ;; appending, so nuke that puppy.
1992 ;; FIXME: This is currently the fate of superseded
1993 ;; files, and according to the CLOSE spec this is
1994 ;; wrong. However, there seems to be no clean way to
1995 ;; do that that doesn't involve either copying the
1996 ;; data (bad if the :abort resulted from a full
1997 ;; disk), or renaming the old file temporarily
1998 ;; (probably bad because stream opening becomes more
2000 (multiple-value-bind (okay err)
2001 (sb!unix:unix-unlink file)
2003 (error 'simple-file-error
2006 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2008 (list file fd-stream (strerror err)))))))))
2010 (finish-fd-stream-output fd-stream)
2011 (let ((orig (fd-stream-original fd-stream)))
2012 (when (and orig (fd-stream-delete-original fd-stream))
2013 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2015 (error 'simple-file-error
2018 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2020 (list orig fd-stream (strerror err)))))))
2021 ;; In case of no-abort close, don't *really* close the
2022 ;; stream until the last moment -- the cleaning up of the
2023 ;; original can be done first.
2024 (release-fd-stream-resources fd-stream))))
2026 (fd-stream-clear-input fd-stream))
2028 (flush-output-buffer fd-stream))
2030 (finish-fd-stream-output fd-stream))
2032 (fd-stream-element-type fd-stream))
2034 (fd-stream-external-format fd-stream))
2036 (= 1 (the (member 0 1)
2037 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2041 (fd-stream-char-pos fd-stream))
2043 (unless (fd-stream-file fd-stream)
2044 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2045 ;; "should signal an error of type TYPE-ERROR if stream is not
2046 ;; a stream associated with a file". Too bad there's no very
2047 ;; appropriate value for the EXPECTED-TYPE slot..
2048 (error 'simple-type-error
2050 :expected-type 'fd-stream
2051 :format-control "~S is not a stream associated with a file."
2052 :format-arguments (list fd-stream)))
2053 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2054 atime mtime ctime blksize blocks)
2055 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2056 (declare (ignore ino nlink uid gid rdev
2057 atime mtime ctime blksize blocks))
2059 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2062 (truncate size (fd-stream-element-size fd-stream)))))
2063 (:file-string-length
2065 (character (fd-stream-character-size fd-stream arg1))
2066 (string (fd-stream-string-size fd-stream arg1))))
2069 (fd-stream-set-file-position fd-stream arg1)
2070 (fd-stream-get-file-position fd-stream)))))
2072 ;; FIXME: Think about this.
2074 ;; (defun finish-fd-stream-output (fd-stream)
2075 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2076 ;; (loop while (fd-stream-output-queue fd-stream)
2077 ;; ;; FIXME: SIGINT while waiting for a timeout will
2078 ;; ;; cause a timeout here.
2079 ;; do (when (and (not (serve-event timeout)) timeout)
2080 ;; (signal-timeout 'io-timeout
2081 ;; :stream fd-stream
2082 ;; :direction :write
2083 ;; :seconds timeout)))))
2085 (defun finish-fd-stream-output (stream)
2086 (flush-output-buffer stream)
2088 ((null (fd-stream-output-queue stream)))
2089 (aver (fd-stream-serve-events stream))
2090 (serve-all-events)))
2092 (defun fd-stream-get-file-position (stream)
2093 (declare (fd-stream stream))
2095 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2096 (declare (type (or (alien sb!unix:off-t) null) posn))
2097 ;; We used to return NIL for errno==ESPIPE, and signal an error
2098 ;; in other failure cases. However, CLHS says to return NIL if
2099 ;; the position cannot be determined -- so that's what we do.
2100 (when (integerp posn)
2101 ;; Adjust for buffered output: If there is any output
2102 ;; buffered, the *real* file position will be larger
2103 ;; than reported by lseek() because lseek() obviously
2104 ;; cannot take into account output we have not sent
2106 (dolist (buffer (fd-stream-output-queue stream))
2107 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2108 (let ((obuf (fd-stream-obuf stream)))
2110 (incf posn (buffer-tail obuf))))
2111 ;; Adjust for unread input: If there is any input
2112 ;; read from UNIX but not supplied to the user of the
2113 ;; stream, the *real* file position will smaller than
2114 ;; reported, because we want to look like the unread
2115 ;; stuff is still available.
2116 (let ((ibuf (fd-stream-ibuf stream)))
2118 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2119 ;; Divide bytes by element size.
2120 (truncate posn (fd-stream-element-size stream))))))
2122 (defun fd-stream-set-file-position (stream position-spec)
2123 (declare (fd-stream stream))
2124 (check-type position-spec
2125 (or (alien sb!unix:off-t) (member nil :start :end))
2126 "valid file position designator")
2129 ;; Make sure we don't have any output pending, because if we
2130 ;; move the file pointer before writing this stuff, it will be
2131 ;; written in the wrong location.
2132 (finish-fd-stream-output stream)
2133 ;; Disable interrupts so that interrupt handlers doing output
2136 (unless (fd-stream-output-finished-p stream)
2137 ;; We got interrupted and more output came our way during
2138 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2139 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2140 ;; so we prefer to do things like this...
2142 ;; Clear out any pending input to force the next read to go to
2144 (flush-input-buffer stream)
2145 ;; Trash cached value for listen, so that we check next time.
2146 (setf (fd-stream-listen stream) nil)
2148 (multiple-value-bind (offset origin)
2151 (values 0 sb!unix:l_set))
2153 (values 0 sb!unix:l_xtnd))
2155 (values (* position-spec (fd-stream-element-size stream))
2157 (declare (type (alien sb!unix:off-t) offset))
2158 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2160 ;; CLHS says to return true if the file-position was set
2161 ;; succesfully, and NIL otherwise. We are to signal an error
2162 ;; only if the given position was out of bounds, and that is
2163 ;; dealt with above. In times past we used to return NIL for
2164 ;; errno==ESPIPE, and signal an error in other cases.
2166 ;; FIXME: We are still liable to signal an error if flushing
2168 (return-from fd-stream-set-file-position
2169 (typep posn '(alien sb!unix:off-t))))))))
2172 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2174 ;;; Create a stream for the given Unix file descriptor.
2176 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2177 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2178 ;;; default to allowing input.
2180 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2182 ;;; BUFFERING indicates the kind of buffering to use.
2184 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2185 ;;; NIL (the default), then wait forever. When we time out, we signal
2188 ;;; FILE is the name of the file (will be returned by PATHNAME).
2190 ;;; NAME is used to identify the stream when printed.
2192 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2193 ;;; handle blocking IO on the stream.
2194 (defun make-fd-stream (fd
2197 (output nil output-p)
2198 (element-type 'base-char)
2200 (external-format :default)
2210 (format nil "file ~A" file)
2211 (format nil "descriptor ~W" fd)))
2213 (declare (type index fd) (type (or real null) timeout)
2214 (type (member :none :line :full) buffering))
2215 (cond ((not (or input-p output-p))
2217 ((not (or input output))
2218 (error "File descriptor must be opened either for input or output.")))
2219 (let ((stream (%make-fd-stream :fd fd
2221 #!-win32 (sb!unix:fd-type fd)
2223 #!+win32 (if serve-events
2229 :delete-original delete-original
2231 :buffering buffering
2232 :dual-channel-p dual-channel-p
2233 :bivalent-p (eq element-type :default)
2234 :serve-events serve-events
2237 (coerce timeout 'single-float)
2239 (set-fd-stream-routines stream element-type external-format
2240 input output input-buffer-p)
2241 (when (and auto-close (fboundp 'finalize))
2244 (sb!unix:unix-close fd)
2246 (format *terminal-io* "** closed file descriptor ~W **~%"
2251 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2252 ;;; :RENAME-AND-DELETE and :RENAME options.
2253 (defun pick-backup-name (name)
2254 (declare (type simple-string name))
2255 (concatenate 'simple-string name ".bak"))
2257 ;;; Ensure that the given arg is one of the given list of valid
2258 ;;; things. Allow the user to fix any problems.
2259 (defun ensure-one-of (item list what)
2260 (unless (member item list)
2261 (error 'simple-type-error
2263 :expected-type `(member ,@list)
2264 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2265 :format-arguments (list item what list))))
2267 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2268 ;;; access, since we don't want to trash unwritable files even if we
2269 ;;; technically can. We return true if we succeed in renaming.
2270 (defun rename-the-old-one (namestring original)
2271 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2272 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2273 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2276 (error 'simple-file-error
2277 :pathname namestring
2279 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2280 :format-arguments (list namestring original (strerror err))))))
2282 (defun open (filename
2285 (element-type 'base-char)
2286 (if-exists nil if-exists-given)
2287 (if-does-not-exist nil if-does-not-exist-given)
2288 (external-format :default)
2289 &aux ; Squelch assignment warning.
2290 (direction direction)
2291 (if-does-not-exist if-does-not-exist)
2292 (if-exists if-exists))
2294 "Return a stream which reads from or writes to FILENAME.
2296 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2297 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2298 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2299 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2300 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2301 See the manual for details."
2303 ;; Calculate useful stuff.
2304 (multiple-value-bind (input output mask)
2306 (:input (values t nil sb!unix:o_rdonly))
2307 (:output (values nil t sb!unix:o_wronly))
2308 (:io (values t t sb!unix:o_rdwr))
2309 (:probe (values t nil sb!unix:o_rdonly)))
2310 (declare (type index mask))
2311 (let* (;; PATHNAME is the pathname we associate with the stream.
2312 (pathname (merge-pathnames filename))
2313 (physical (physicalize-pathname pathname))
2314 (truename (probe-file physical))
2315 ;; NAMESTRING is the native namestring we open the file with.
2316 (namestring (cond (truename
2317 (native-namestring truename :as-file t))
2319 (and input (eq if-does-not-exist :create))
2320 (and (eq direction :io) (not if-does-not-exist-given)))
2321 (native-namestring physical :as-file t)))))
2322 ;; Process if-exists argument if we are doing any output.
2324 (unless if-exists-given
2326 (if (eq (pathname-version pathname) :newest)
2329 (ensure-one-of if-exists
2330 '(:error :new-version :rename
2331 :rename-and-delete :overwrite
2332 :append :supersede nil)
2335 ((:new-version :error nil)
2336 (setf mask (logior mask sb!unix:o_excl)))
2337 ((:rename :rename-and-delete)
2338 (setf mask (logior mask sb!unix:o_creat)))
2340 (setf mask (logior mask sb!unix:o_trunc)))
2342 (setf mask (logior mask sb!unix:o_append)))))
2344 (setf if-exists :ignore-this-arg)))
2346 (unless if-does-not-exist-given
2347 (setf if-does-not-exist
2348 (cond ((eq direction :input) :error)
2350 (member if-exists '(:overwrite :append)))
2352 ((eq direction :probe)
2356 (ensure-one-of if-does-not-exist
2357 '(:error :create nil)
2359 (if (eq if-does-not-exist :create)
2360 (setf mask (logior mask sb!unix:o_creat)))
2362 (let ((original (case if-exists
2363 ((:rename :rename-and-delete)
2364 (pick-backup-name namestring))
2365 ((:append :overwrite)
2366 ;; KLUDGE: Provent CLOSE from deleting
2367 ;; appending streams when called with :ABORT T
2369 (delete-original (eq if-exists :rename-and-delete))
2371 (when (and original (not (eq original namestring)))
2372 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2373 ;; whether the file already exists, make sure the original
2374 ;; file is not a directory, and keep the mode.
2377 (multiple-value-bind (okay err/dev inode orig-mode)
2378 (sb!unix:unix-stat namestring)
2379 (declare (ignore inode)
2380 (type (or index null) orig-mode))
2383 (when (and output (= (logand orig-mode #o170000)
2385 (error 'simple-file-error
2388 "can't open ~S for output: is a directory"
2389 :format-arguments (list namestring)))
2390 (setf mode (logand orig-mode #o777))
2392 ((eql err/dev sb!unix:enoent)
2395 (simple-file-perror "can't find ~S"
2399 (rename-the-old-one namestring original))
2401 (setf delete-original nil)
2402 ;; In order to use :SUPERSEDE instead, we have to make
2403 ;; sure SB!UNIX:O_CREAT corresponds to
2404 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2405 ;; because of IF-EXISTS being :RENAME.
2406 (unless (eq if-does-not-exist :create)
2408 (logior (logandc2 mask sb!unix:o_creat)
2410 (setf if-exists :supersede))))
2412 ;; Now we can try the actual Unix open(2).
2413 (multiple-value-bind (fd errno)
2415 (sb!unix:unix-open namestring mask mode)
2416 (values nil sb!unix:enoent))
2417 (labels ((open-error (format-control &rest format-arguments)
2418 (error 'simple-file-error
2420 :format-control format-control
2421 :format-arguments format-arguments))
2422 (vanilla-open-error ()
2423 (simple-file-perror "error opening ~S" pathname errno)))
2426 ((:input :output :io)
2427 ;; For O_APPEND opened files, lseek returns 0 until first write.
2428 ;; So we jump ahead here.
2429 (when (eq if-exists :append)
2430 (sb!unix:unix-lseek fd 0 sb!unix:l_xtnd))
2434 :element-type element-type
2435 :external-format external-format
2438 :delete-original delete-original
2446 (%make-fd-stream :name namestring
2449 :element-type element-type)))
2452 ((eql errno sb!unix:enoent)
2453 (case if-does-not-exist
2454 (:error (vanilla-open-error))
2456 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2459 ((and (eql errno sb!unix:eexist) (null if-exists))
2462 (vanilla-open-error)))))))))
2466 ;;; the stream connected to the controlling terminal, or NIL if there is none
2469 ;;; the stream connected to the standard input (file descriptor 0)
2472 ;;; the stream connected to the standard output (file descriptor 1)
2475 ;;; the stream connected to the standard error output (file descriptor 2)
2478 ;;; This is called when the cold load is first started up, and may also
2479 ;;; be called in an attempt to recover from nested errors.
2480 (defun stream-cold-init-or-reset ()
2482 (setf *terminal-io* (make-synonym-stream '*tty*))
2483 (setf *standard-output* (make-synonym-stream '*stdout*))
2484 (setf *standard-input* (make-synonym-stream '*stdin*))
2485 (setf *error-output* (make-synonym-stream '*stderr*))
2486 (setf *query-io* (make-synonym-stream '*terminal-io*))
2487 (setf *debug-io* *query-io*)
2488 (setf *trace-output* *standard-output*)
2491 (defun stream-deinit ()
2492 ;; Unbind to make sure we're not accidently dealing with it
2493 ;; before we're ready (or after we think it's been deinitialized).
2494 (with-available-buffers-lock ()
2495 (without-package-locks
2496 (makunbound '*available-buffers*))))
2498 (defun stdstream-external-format (outputp)
2499 (declare (ignorable outputp))
2500 (let* ((keyword #!+win32 (if outputp (sb!win32::console-output-codepage) (sb!win32::console-input-codepage))
2501 #!-win32 (default-external-format))
2502 (ef (get-external-format keyword))
2503 (replacement (ef-default-replacement-character ef)))
2504 `(,keyword :replacement ,replacement)))
2506 ;;; This is called whenever a saved core is restarted.
2507 (defun stream-reinit (&optional init-buffers-p)
2508 (when init-buffers-p
2509 (with-available-buffers-lock ()
2510 (aver (not (boundp '*available-buffers*)))
2511 (setf *available-buffers* nil)))
2512 (with-output-to-string (*error-output*)
2514 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2515 :element-type :default
2517 :external-format (stdstream-external-format nil)))
2519 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2520 :element-type :default
2521 :external-format (stdstream-external-format t)))
2523 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2524 :element-type :default
2525 :external-format (stdstream-external-format t)))
2526 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2527 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2530 (make-fd-stream tty :name "the terminal"
2531 :input t :output t :buffering :line
2532 :external-format (stdstream-external-format t)
2535 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2536 (princ (get-output-stream-string *error-output*) *stderr*))
2541 ;;; the Unix way to beep
2542 (defun beep (stream)
2543 (write-char (code-char bell-char-code) stream)
2544 (finish-output stream))
2546 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2547 ;;; by the filesys stuff to get and set the file name.
2549 ;;; FIXME: misleading name, screwy interface
2550 (defun file-name (stream &optional new-name)
2551 (when (typep stream 'fd-stream)
2553 (setf (fd-stream-pathname stream) new-name)
2554 (setf (fd-stream-file stream)
2555 (native-namestring (physicalize-pathname new-name)
2559 (fd-stream-pathname stream)))))