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))
172 ;; T if serve-event is allowed when this stream blocks
173 (serve-events nil :type boolean)
176 (instead (make-array 0 :element-type 'character :adjustable t :fill-pointer t) :type (array character (*)))
177 (ibuf nil :type (or buffer null))
178 (eof-forced-p nil :type (member t nil))
181 (obuf nil :type (or buffer null))
183 ;; output flushed, but not written due to non-blocking io?
186 ;; timeout specified for this stream as seconds or NIL if none
187 (timeout nil :type (or single-float null))
188 ;; pathname of the file this stream is opened to (returned by PATHNAME)
189 (pathname nil :type (or pathname null))
190 (external-format :default)
191 ;; fixed width, or function to call with a character
192 (char-size 1 :type (or fixnum function))
193 (output-bytes #'ill-out :type function)
194 ;; a boolean indicating whether the stream is bivalent. For
195 ;; internal use only.
196 (bivalent-p nil :type boolean))
197 (def!method print-object ((fd-stream fd-stream) stream)
198 (declare (type stream stream))
199 (print-unreadable-object (fd-stream stream :type t :identity t)
200 (format stream "for ~S" (fd-stream-name fd-stream))))
202 ;;;; CORE OUTPUT FUNCTIONS
204 ;;; Buffer the section of THING delimited by START and END by copying
205 ;;; to output buffer(s) of stream.
206 (defun buffer-output (stream thing start end)
207 (declare (index start end))
209 (error ":END before :START!"))
211 ;; Copy bytes from THING to buffers.
212 (flet ((copy-to-buffer (buffer tail count)
213 (declare (buffer buffer) (index tail count))
215 (let ((sap (buffer-sap buffer)))
218 (system-area-ub8-copy thing start sap tail count))
219 ((simple-unboxed-array (*))
220 (copy-ub8-to-system-area thing start sap tail count))))
221 ;; Not INCF! If another thread has moved tail from under
222 ;; us, we don't want to accidentally increment tail
223 ;; beyond buffer-length.
224 (setf (buffer-tail buffer) (+ count tail))
227 ;; First copy is special: the buffer may already contain
228 ;; something, or be even full.
229 (let* ((obuf (fd-stream-obuf stream))
230 (tail (buffer-tail obuf))
231 (space (- (buffer-length obuf) tail)))
233 (copy-to-buffer obuf tail (min space (- end start)))
234 (go :more-output-p)))
236 ;; Later copies should always have an empty buffer, since
237 ;; they are freshly flushed, but if another thread is
238 ;; stomping on the same buffer that might not be the case.
239 (let* ((obuf (flush-output-buffer stream))
240 (tail (buffer-tail obuf))
241 (space (- (buffer-length obuf) tail)))
242 (copy-to-buffer obuf tail (min space (- end start))))
245 (go :flush-and-fill))))))
247 ;;; Flush the current output buffer of the stream, ensuring that the
248 ;;; new buffer is empty. Returns (for convenience) the new output
249 ;;; buffer -- which may or may not be EQ to the old one. If the is no
250 ;;; queued output we try to write the buffer immediately -- otherwise
251 ;;; we queue it for later.
252 (defun flush-output-buffer (stream)
253 (let ((obuf (fd-stream-obuf stream)))
255 (let ((head (buffer-head obuf))
256 (tail (buffer-tail obuf)))
257 (cond ((eql head tail)
258 ;; Buffer is already empty -- just ensure that is is
259 ;; set to zero as well.
261 ((fd-stream-output-queue stream)
262 ;; There is already stuff on the queue -- go directly
265 (%queue-and-replace-output-buffer stream))
267 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
268 ;; whatever is left over. Otherwise wait until we can write.
270 (synchronize-stream-output stream)
272 (let ((length (- tail head)))
273 (multiple-value-bind (count errno)
274 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
276 (flet ((queue-or-wait ()
277 (if (fd-stream-serve-events stream)
278 (return (%queue-and-replace-output-buffer stream))
279 (or (wait-until-fd-usable (fd-stream-fd stream) :output
280 (fd-stream-timeout stream)
282 (signal-timeout 'io-timeout
285 :seconds (fd-stream-timeout stream))))))
286 (cond ((eql count length)
287 ;; Complete write -- we can use the same buffer.
288 (return (reset-buffer obuf)))
290 ;; Partial write -- update buffer status and
291 ;; queue or wait. Do not use INCF! Another
292 ;; thread might have moved head...
293 (setf (buffer-head obuf) (+ count head))
296 ((eql errno sb!unix:ewouldblock)
297 ;; Blocking, queue or wair.
300 (simple-stream-perror "Couldn't write to ~s"
301 stream errno)))))))))))))
303 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
304 (defun %queue-and-replace-output-buffer (stream)
305 (aver (fd-stream-serve-events stream))
306 (let ((queue (fd-stream-output-queue stream))
307 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
309 ;; Important: before putting the buffer on queue, give the stream
310 ;; a new one. If we get an interrupt and unwind losing the buffer
311 ;; is relatively OK, but having the same buffer in two places
313 (setf (fd-stream-obuf stream) new)
317 (setf (fd-stream-output-queue stream) later)))
318 (unless (fd-stream-handler stream)
319 (setf (fd-stream-handler stream)
320 (add-fd-handler (fd-stream-fd stream)
323 (declare (ignore fd))
324 (write-output-from-queue stream)))))
327 ;;; This is called by the FD-HANDLER for the stream when output is
329 (defun write-output-from-queue (stream)
330 (aver (fd-stream-serve-events stream))
331 (synchronize-stream-output stream)
335 (let* ((buffer (pop (fd-stream-output-queue stream)))
336 (head (buffer-head buffer))
337 (length (- (buffer-tail buffer) head)))
338 (declare (index head length))
340 (multiple-value-bind (count errno)
341 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
343 (cond ((eql count length)
344 ;; Complete write, see if we can do another right
345 ;; away, or remove the handler if we're done.
346 (release-buffer buffer)
347 (cond ((fd-stream-output-queue stream)
351 (let ((handler (fd-stream-handler stream)))
353 (setf (fd-stream-handler stream) nil)
354 (remove-fd-handler handler)))))
356 ;; Partial write. Update buffer status and requeue.
357 (aver (< count length))
358 ;; Do not use INCF! Another thread might have moved head.
359 (setf (buffer-head buffer) (+ head count))
360 (push buffer (fd-stream-output-queue stream)))
362 ;; We tried to do multiple writes, and finally our
363 ;; luck ran out. Requeue.
364 (push buffer (fd-stream-output-queue stream)))
366 ;; Could not write on the first try at all!
368 (simple-stream-perror "Couldn't write to ~S." stream errno)
370 (if (= errno sb!unix:ewouldblock)
371 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
372 (simple-stream-perror "Couldn't write to ~S"
376 ;;; Try to write THING directly to STREAM without buffering, if
377 ;;; possible. If direct write doesn't happen, buffer.
378 (defun write-or-buffer-output (stream thing start end)
379 (declare (index start end))
380 (cond ((fd-stream-output-queue stream)
381 (buffer-output stream thing start end))
383 (error ":END before :START!"))
385 (let ((length (- end start)))
386 (synchronize-stream-output stream)
387 (multiple-value-bind (count errno)
388 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
389 (cond ((eql count length)
390 ;; Complete write -- done!
393 (aver (< count length))
394 ;; Partial write -- buffer the rest.
395 (buffer-output stream thing (+ start count) end))
397 ;; Could not write -- buffer or error.
399 (simple-stream-perror "couldn't write to ~s" stream errno)
401 (if (= errno sb!unix:ewouldblock)
402 (buffer-output stream thing start end)
403 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
405 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
406 ;;; this is not something we want to export. Nikodemus thinks the
407 ;;; right thing is to support a low-level non-stream like IO layer,
408 ;;; akin to java.nio.
409 (defun output-raw-bytes (stream thing &optional start end)
410 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
412 (define-compiler-macro output-raw-bytes (stream thing &optional start end)
413 (deprecation-warning 'output-raw-bytes)
414 (let ((x (gensym "THING")))
416 (write-or-buffer-output ,stream ,x (or ,start 0) (or ,end (length ,x))))))
418 ;;;; output routines and related noise
420 (defvar *output-routines* ()
422 "List of all available output routines. Each element is a list of the
423 element-type output, the kind of buffering, the function name, and the number
424 of bytes per element.")
426 ;;; common idioms for reporting low-level stream and file problems
427 (defun simple-stream-perror (note-format stream errno)
428 (error 'simple-stream-error
430 :format-control "~@<~?: ~2I~_~A~:>"
431 :format-arguments (list note-format (list stream) (strerror errno))))
432 (defun simple-file-perror (note-format pathname errno)
433 (error 'simple-file-error
435 :format-control "~@<~?: ~2I~_~A~:>"
437 (list note-format (list pathname) (strerror errno))))
439 (defun stream-decoding-error (stream octets)
440 (error 'stream-decoding-error
441 :external-format (stream-external-format stream)
443 ;; FIXME: dunno how to get at OCTETS currently, or even if
444 ;; that's the right thing to report.
446 (defun stream-encoding-error (stream code)
447 (error 'stream-encoding-error
448 :external-format (stream-external-format stream)
452 (defun c-string-encoding-error (external-format code)
453 (error 'c-string-encoding-error
454 :external-format external-format
457 (defun c-string-decoding-error (external-format octets)
458 (error 'c-string-decoding-error
459 :external-format external-format
462 ;;; Returning true goes into end of file handling, false will enter another
463 ;;; round of input buffer filling followed by re-entering character decode.
464 (defun stream-decoding-error-and-handle (stream octet-count)
466 (stream-decoding-error stream
467 (let* ((buffer (fd-stream-ibuf stream))
468 (sap (buffer-sap buffer))
469 (head (buffer-head buffer)))
470 (loop for i from 0 below octet-count
471 collect (sap-ref-8 sap (+ head i)))))
473 :report (lambda (stream)
475 "~@<Attempt to resync the stream at a ~
476 character boundary and continue.~@:>"))
477 (fd-stream-resync stream)
479 (force-end-of-file ()
480 :report (lambda (stream)
481 (format stream "~@<Force an end of file.~@:>"))
482 (setf (fd-stream-eof-forced-p stream) t))
483 (input-replacement (string)
484 :report (lambda (stream)
485 (format stream "~@<Use string as replacement input, ~
486 attempt to resync at a character ~
487 boundary and continue.~@:>"))
488 :interactive (lambda ()
489 (format *query-io* "~@<Enter a string: ~@:>")
490 (finish-output *query-io*)
491 (list (read *query-io*)))
492 (let ((string (reverse (string string)))
493 (instead (fd-stream-instead stream)))
494 (dotimes (i (length string))
495 (vector-push-extend (char string i) instead))
496 (fd-stream-resync stream)
497 (when (> (length string) 0)
498 (setf (fd-stream-listen stream) t)))
501 (defun stream-encoding-error-and-handle (stream code)
503 (stream-encoding-error stream code)
505 :report (lambda (stream)
506 (format stream "~@<Skip output of this character.~@:>"))
507 (throw 'output-nothing nil))
508 (output-replacement (string)
509 :report (lambda (stream)
510 (format stream "~@<Output replacement string.~@:>"))
511 :interactive (lambda ()
512 (format *query-io* "~@<Enter a string: ~@:>")
513 (finish-output *query-io*)
514 (list (read *query-io*)))
515 (let ((string (string string)))
516 (fd-sout stream (string string) 0 (length string)))
517 (throw 'output-nothing nil))))
519 (defun external-format-encoding-error (stream code)
521 (stream-encoding-error-and-handle stream code)
522 (c-string-encoding-error stream code)))
524 (defun synchronize-stream-output (stream)
525 ;; If we're reading and writing on the same file, flush buffered
526 ;; input and rewind file position accordingly.
527 (unless (fd-stream-dual-channel-p stream)
528 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
529 (unless (eql 0 adjust)
530 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
532 (defun fd-stream-output-finished-p (stream)
533 (let ((obuf (fd-stream-obuf stream)))
535 (and (zerop (buffer-tail obuf))
536 (not (fd-stream-output-queue stream))))))
538 (defmacro output-wrapper/variable-width ((stream size buffering restart)
540 (let ((stream-var (gensym "STREAM")))
541 `(let* ((,stream-var ,stream)
542 (obuf (fd-stream-obuf ,stream-var))
543 (tail (buffer-tail obuf))
545 ,(unless (eq (car buffering) :none)
546 `(when (<= (buffer-length obuf) (+ tail size))
547 (setf obuf (flush-output-buffer ,stream-var)
548 tail (buffer-tail obuf))))
549 ,(unless (eq (car buffering) :none)
550 ;; FIXME: Why this here? Doesn't seem necessary.
551 `(synchronize-stream-output ,stream-var))
553 `(catch 'output-nothing
555 (setf (buffer-tail obuf) (+ tail size)))
558 (setf (buffer-tail obuf) (+ tail size))))
559 ,(ecase (car buffering)
561 `(flush-output-buffer ,stream-var))
563 `(when (eql byte #\Newline)
564 (flush-output-buffer ,stream-var)))
568 (defmacro output-wrapper ((stream size buffering restart) &body body)
569 (let ((stream-var (gensym "STREAM")))
570 `(let* ((,stream-var ,stream)
571 (obuf (fd-stream-obuf ,stream-var))
572 (tail (buffer-tail obuf)))
573 ,(unless (eq (car buffering) :none)
574 `(when (<= (buffer-length obuf) (+ tail ,size))
575 (setf obuf (flush-output-buffer ,stream-var)
576 tail (buffer-tail obuf))))
577 ;; FIXME: Why this here? Doesn't seem necessary.
578 ,(unless (eq (car buffering) :none)
579 `(synchronize-stream-output ,stream-var))
581 `(catch 'output-nothing
583 (setf (buffer-tail obuf) (+ tail ,size)))
586 (setf (buffer-tail obuf) (+ tail ,size))))
587 ,(ecase (car buffering)
589 `(flush-output-buffer ,stream-var))
591 `(when (eql byte #\Newline)
592 (flush-output-buffer ,stream-var)))
596 (defmacro def-output-routines/variable-width
597 ((name-fmt size restart external-format &rest bufferings)
599 (declare (optimize (speed 1)))
604 (intern (format nil name-fmt (string (car buffering))))))
606 (defun ,function (stream byte)
607 (declare (ignorable byte))
608 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
610 (setf *output-routines*
611 (nconc *output-routines*
619 (cdr buffering)))))))
622 ;;; Define output routines that output numbers SIZE bytes long for the
623 ;;; given bufferings. Use BODY to do the actual output.
624 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
626 (declare (optimize (speed 1)))
631 (intern (format nil name-fmt (string (car buffering))))))
633 (defun ,function (stream byte)
634 (output-wrapper (stream ,size ,buffering ,restart)
636 (setf *output-routines*
637 (nconc *output-routines*
645 (cdr buffering)))))))
648 ;;; FIXME: is this used anywhere any more?
649 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
655 (if (eql byte #\Newline)
656 (setf (fd-stream-char-pos stream) 0)
657 (incf (fd-stream-char-pos stream)))
658 (setf (sap-ref-8 (buffer-sap obuf) tail)
661 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
664 (:none (unsigned-byte 8))
665 (:full (unsigned-byte 8)))
666 (setf (sap-ref-8 (buffer-sap obuf) tail)
669 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
672 (:none (signed-byte 8))
673 (:full (signed-byte 8)))
674 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
677 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
680 (:none (unsigned-byte 16))
681 (:full (unsigned-byte 16)))
682 (setf (sap-ref-16 (buffer-sap obuf) tail)
685 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
688 (:none (signed-byte 16))
689 (:full (signed-byte 16)))
690 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
693 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
696 (:none (unsigned-byte 32))
697 (:full (unsigned-byte 32)))
698 (setf (sap-ref-32 (buffer-sap obuf) tail)
701 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
704 (:none (signed-byte 32))
705 (:full (signed-byte 32)))
706 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
709 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
711 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
714 (:none (unsigned-byte 64))
715 (:full (unsigned-byte 64)))
716 (setf (sap-ref-64 (buffer-sap obuf) tail)
718 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
721 (:none (signed-byte 64))
722 (:full (signed-byte 64)))
723 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
726 ;;; the routine to use to output a string. If the stream is
727 ;;; unbuffered, slam the string down the file descriptor, otherwise
728 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
729 ;;; checking to see where the last newline was.
730 (defun fd-sout (stream thing start end)
731 (declare (type fd-stream stream) (type string thing))
732 (let ((start (or start 0))
733 (end (or end (length (the vector thing)))))
734 (declare (fixnum start end))
736 (string-dispatch (simple-base-string
738 (simple-array character (*))
741 (position #\newline thing :from-end t
742 :start start :end end))))
743 (if (and (typep thing 'base-string)
744 (eq (fd-stream-external-format-keyword stream) :latin-1))
745 (ecase (fd-stream-buffering stream)
747 (buffer-output stream thing start end))
749 (buffer-output stream thing start end)
751 (flush-output-buffer stream)))
753 (write-or-buffer-output stream thing start end)))
754 (ecase (fd-stream-buffering stream)
755 (:full (funcall (fd-stream-output-bytes stream)
756 stream thing nil start end))
757 (:line (funcall (fd-stream-output-bytes stream)
758 stream thing last-newline start end))
759 (:none (funcall (fd-stream-output-bytes stream)
760 stream thing t start end))))
762 (setf (fd-stream-char-pos stream) (- end last-newline 1))
763 (incf (fd-stream-char-pos stream) (- end start))))))
765 (defstruct (external-format
766 (:constructor %make-external-format)
768 (:predicate external-format-p)
769 (:copier %copy-external-format))
770 ;; All the names that can refer to this external format. The first
771 ;; one is the canonical name.
772 (names (missing-arg) :type list :read-only t)
773 (default-replacement-character (missing-arg) :type character)
774 (read-n-chars-fun (missing-arg) :type function)
775 (read-char-fun (missing-arg) :type function)
776 (write-n-bytes-fun (missing-arg) :type function)
777 (write-char-none-buffered-fun (missing-arg) :type function)
778 (write-char-line-buffered-fun (missing-arg) :type function)
779 (write-char-full-buffered-fun (missing-arg) :type function)
780 ;; Can be nil for fixed-width formats.
781 (resync-fun nil :type (or function null))
782 (bytes-for-char-fun (missing-arg) :type function)
783 (read-c-string-fun (missing-arg) :type function)
784 (write-c-string-fun (missing-arg) :type function)
785 ;; We indirect through symbols in these functions so that a
786 ;; developer working on the octets code can easily redefine things
787 ;; and use the new function definition without redefining the
788 ;; external format as well. The slots above don't do any
789 ;; indirection because a developer working with those slots would be
790 ;; redefining the external format anyway.
791 (octets-to-string-fun (missing-arg) :type function)
792 (string-to-octets-fun (missing-arg) :type function))
794 (defun wrap-external-format-functions (external-format fun)
795 (let ((result (%copy-external-format external-format)))
796 (macrolet ((frob (accessor)
797 `(setf (,accessor result) (funcall fun (,accessor result)))))
798 (frob ef-read-n-chars-fun)
799 (frob ef-read-char-fun)
800 (frob ef-write-n-bytes-fun)
801 (frob ef-write-char-none-buffered-fun)
802 (frob ef-write-char-line-buffered-fun)
803 (frob ef-write-char-full-buffered-fun)
805 (frob ef-bytes-for-char-fun)
806 (frob ef-read-c-string-fun)
807 (frob ef-write-c-string-fun)
808 (frob ef-octets-to-string-fun)
809 (frob ef-string-to-octets-fun))
812 (defvar *external-formats* (make-hash-table)
814 "Hashtable of all available external formats. The table maps from
815 external-format names to EXTERNAL-FORMAT structures.")
817 (defun get-external-format (external-format)
818 (flet ((keyword-external-format (keyword)
819 (declare (type keyword keyword))
820 (gethash keyword *external-formats*))
821 (replacement-handlerify (entry replacement)
823 (wrap-external-format-functions
828 (declare (dynamic-extent rest))
830 ((stream-decoding-error
833 (invoke-restart 'input-replacement replacement)))
834 (stream-encoding-error
837 (invoke-restart 'output-replacement replacement)))
838 (octets-encoding-error
839 (lambda (c) (use-value replacement c)))
840 (octet-decoding-error
841 (lambda (c) (use-value replacement c))))
842 (apply fun rest)))))))))
843 (typecase external-format
844 (keyword (keyword-external-format external-format))
846 (let ((entry (keyword-external-format (car external-format)))
847 (replacement (getf (cdr external-format) :replacement)))
849 (replacement-handlerify entry replacement)
852 (defun get-external-format-or-lose (external-format)
853 (or (get-external-format external-format)
854 (error "Undefined external-format ~A" external-format)))
856 (defun external-format-keyword (external-format)
857 (typecase external-format
858 (keyword external-format)
859 ((cons keyword) (car external-format))))
861 (defun fd-stream-external-format-keyword (stream)
862 (external-format-keyword (fd-stream-external-format stream)))
864 (defun canonize-external-format (external-format entry)
865 (typecase external-format
866 (keyword (first (ef-names entry)))
867 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
869 ;;; Find an output routine to use given the type and buffering. Return
870 ;;; as multiple values the routine, the real type transfered, and the
871 ;;; number of bytes per element.
872 (defun pick-output-routine (type buffering &optional external-format)
873 (when (subtypep type 'character)
874 (let ((entry (get-external-format external-format)))
876 (return-from pick-output-routine
877 (values (ecase buffering
878 (:none (ef-write-char-none-buffered-fun entry))
879 (:line (ef-write-char-line-buffered-fun entry))
880 (:full (ef-write-char-full-buffered-fun entry)))
883 (ef-write-n-bytes-fun entry)
884 (canonize-external-format external-format entry))))))
885 (dolist (entry *output-routines*)
886 (when (and (subtypep type (first entry))
887 (eq buffering (second entry))
888 (or (not (fifth entry))
889 (eq external-format (fifth entry))))
890 (return-from pick-output-routine
891 (values (symbol-function (third entry))
894 ;; KLUDGE: dealing with the buffering here leads to excessive code
897 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
898 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
899 if (subtypep type `(unsigned-byte ,i))
900 do (return-from pick-output-routine
904 (lambda (stream byte)
905 (output-wrapper (stream (/ i 8) (:none) nil)
906 (loop for j from 0 below (/ i 8)
907 do (setf (sap-ref-8 (buffer-sap obuf)
909 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
911 (lambda (stream byte)
912 (output-wrapper (stream (/ i 8) (:full) nil)
913 (loop for j from 0 below (/ i 8)
914 do (setf (sap-ref-8 (buffer-sap obuf)
916 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
919 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
920 if (subtypep type `(signed-byte ,i))
921 do (return-from pick-output-routine
925 (lambda (stream byte)
926 (output-wrapper (stream (/ i 8) (:none) nil)
927 (loop for j from 0 below (/ i 8)
928 do (setf (sap-ref-8 (buffer-sap obuf)
930 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
932 (lambda (stream byte)
933 (output-wrapper (stream (/ i 8) (:full) nil)
934 (loop for j from 0 below (/ i 8)
935 do (setf (sap-ref-8 (buffer-sap obuf)
937 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
941 ;;;; input routines and related noise
943 ;;; a list of all available input routines. Each element is a list of
944 ;;; the element-type input, the function name, and the number of bytes
946 (defvar *input-routines* ())
948 ;;; Return whether a primitive partial read operation on STREAM's FD
949 ;;; would (probably) block. Signal a `simple-stream-error' if the
950 ;;; system call implementing this operation fails.
952 ;;; It is "may" instead of "would" because "would" is not quite
953 ;;; correct on win32. However, none of the places that use it require
954 ;;; further assurance than "may" versus "will definitely not".
955 (defun sysread-may-block-p (stream)
957 ;; This answers T at EOF on win32, I think.
958 (not (sb!win32:fd-listen (fd-stream-fd stream)))
960 (not (sb!unix:unix-simple-poll (fd-stream-fd stream) :input 0)))
962 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
963 ;;; then fill the input buffer, and return the number of bytes read. Throws
964 ;;; to EOF-INPUT-CATCHER if the eof was reached.
965 (defun refill-input-buffer (stream)
966 (dx-let ((fd (fd-stream-fd stream))
970 ;; Check for blocking input before touching the stream if we are to
971 ;; serve events: if the FD is blocking, we don't want to hang on the
972 ;; write if we are to serve events or notice timeouts.
973 (if (and (or (fd-stream-serve-events stream)
974 (fd-stream-timeout stream)
976 (sysread-may-block-p stream))
979 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
980 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
982 (closed-flame stream)
984 (simple-stream-perror "couldn't read from ~S" stream errno)
986 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
987 ;; to wait for input if read tells us EWOULDBLOCK.
988 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream)
989 (fd-stream-serve-events stream))
990 (signal-timeout 'io-timeout
993 :seconds (fd-stream-timeout stream)))
995 ;; Since the read should not block, we'll disable the
996 ;; interrupts here, so that we don't accidentally unwind and
997 ;; leave the stream in an inconsistent state.
999 ;; Execute the nlx outside without-interrupts to ensure the
1000 ;; resulting thunk is stack-allocatable.
1001 ((lambda (return-reason)
1002 (ecase return-reason
1003 ((nil)) ; fast path normal cases
1004 ((:wait-for-input) (go :wait-for-input))
1005 ((:closed-flame) (go :closed-flame))
1006 ((:read-error) (go :read-error))))
1008 ;; Check the buffer: if it is null, then someone has closed
1009 ;; the stream from underneath us. This is not ment to fix
1010 ;; multithreaded races, but to deal with interrupt handlers
1011 ;; closing the stream.
1014 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1015 (sap (buffer-sap ibuf))
1016 (length (buffer-length ibuf))
1017 (head (buffer-head ibuf))
1018 (tail (buffer-tail ibuf)))
1019 (declare (index length head tail)
1020 (inline sb!unix:unix-read))
1021 (unless (zerop head)
1022 (cond ((eql head tail)
1023 ;; Buffer is empty, but not at yet reset -- make it so.
1026 (reset-buffer ibuf))
1028 ;; Buffer has things in it, but they are not at the
1029 ;; head -- move them there.
1030 (let ((n (- tail head)))
1031 (system-area-ub8-copy sap head sap 0 n)
1033 (buffer-head ibuf) head
1035 (buffer-tail ibuf) tail)))))
1036 (setf (fd-stream-listen stream) nil)
1037 (setf (values count errno)
1038 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1041 (return :read-error)
1043 (if (eql errno sb!unix:ewouldblock)
1044 (return :wait-for-input)
1045 (return :read-error)))
1047 (setf (fd-stream-listen stream) :eof)
1048 (/show0 "THROWing EOF-INPUT-CATCHER")
1049 (throw 'eof-input-catcher nil))
1051 ;; Success! (Do not use INCF, for sake of other threads.)
1052 (setf (buffer-tail ibuf) (+ count tail))))))))))
1055 ;;; Make sure there are at least BYTES number of bytes in the input
1056 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1057 (defmacro input-at-least (stream bytes)
1058 (let ((stream-var (gensym "STREAM"))
1059 (bytes-var (gensym "BYTES"))
1060 (buffer-var (gensym "IBUF")))
1061 `(let* ((,stream-var ,stream)
1063 (,buffer-var (fd-stream-ibuf ,stream-var)))
1065 (when (>= (- (buffer-tail ,buffer-var)
1066 (buffer-head ,buffer-var))
1069 (refill-input-buffer ,stream-var)))))
1071 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1073 (let ((stream-var (gensym "STREAM"))
1074 (retry-var (gensym "RETRY"))
1075 (element-var (gensym "ELT")))
1076 `(let* ((,stream-var ,stream)
1077 (ibuf (fd-stream-ibuf ,stream-var))
1080 (when (fd-stream-eof-forced-p ,stream-var)
1081 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1082 (return-from use-instead
1083 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1084 (let ((,element-var nil)
1085 (decode-break-reason nil))
1086 (do ((,retry-var t))
1088 (if (> (length (fd-stream-instead ,stream-var)) 0)
1089 (let* ((instead (fd-stream-instead ,stream-var))
1090 (result (vector-pop instead))
1091 (pointer (fill-pointer instead)))
1093 (setf (fd-stream-listen ,stream-var) nil))
1094 (return-from use-instead result))
1096 (catch 'eof-input-catcher
1097 (setf decode-break-reason
1098 (block decode-break-reason
1099 (input-at-least ,stream-var ,(if (consp bytes) (car bytes) `(setq size ,bytes)))
1100 (let* ((byte (sap-ref-8 (buffer-sap ibuf) (buffer-head ibuf))))
1101 (declare (ignorable byte))
1102 ,@(when (consp bytes)
1103 `((let ((sap (buffer-sap ibuf))
1104 (head (buffer-head ibuf)))
1105 (declare (ignorable sap head))
1106 (setq size ,(cadr bytes))
1107 (input-at-least ,stream-var size))))
1108 (setq ,element-var (locally ,@read-forms))
1109 (setq ,retry-var nil))
1111 (when decode-break-reason
1112 (when (stream-decoding-error-and-handle
1113 stream decode-break-reason)
1114 (setq ,retry-var nil)
1115 (throw 'eof-input-catcher nil)))
1117 (let ((octet-count (- (buffer-tail ibuf)
1118 (buffer-head ibuf))))
1119 (when (or (zerop octet-count)
1120 (and (not ,element-var)
1121 (not decode-break-reason)
1122 (stream-decoding-error-and-handle
1123 stream octet-count)))
1124 (setq ,retry-var nil))))))
1126 (incf (buffer-head ibuf) size)
1129 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1131 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1132 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1133 (let ((stream-var (gensym "STREAM"))
1134 (element-var (gensym "ELT")))
1135 `(let* ((,stream-var ,stream)
1136 (ibuf (fd-stream-ibuf ,stream-var)))
1137 (if (> (length (fd-stream-instead ,stream-var)) 0)
1138 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1140 (catch 'eof-input-catcher
1141 (input-at-least ,stream-var ,bytes)
1142 (locally ,@read-forms))))
1144 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1147 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1149 (defmacro def-input-routine/variable-width (name
1150 (type external-format size sap head)
1153 (defun ,name (stream eof-error eof-value)
1154 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1155 (let ((,sap (buffer-sap ibuf))
1156 (,head (buffer-head ibuf)))
1158 (setf *input-routines*
1159 (nconc *input-routines*
1160 (list (list ',type ',name 1 ',external-format))))))
1162 (defmacro def-input-routine (name
1163 (type size sap head)
1166 (defun ,name (stream eof-error eof-value)
1167 (input-wrapper (stream ,size eof-error eof-value)
1168 (let ((,sap (buffer-sap ibuf))
1169 (,head (buffer-head ibuf)))
1171 (setf *input-routines*
1172 (nconc *input-routines*
1173 (list (list ',type ',name ',size nil))))))
1175 ;;; STREAM-IN routine for reading a string char
1176 (def-input-routine input-character
1177 (character 1 sap head)
1178 (code-char (sap-ref-8 sap head)))
1180 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1181 (def-input-routine input-unsigned-8bit-byte
1182 ((unsigned-byte 8) 1 sap head)
1183 (sap-ref-8 sap head))
1185 ;;; STREAM-IN routine for reading a signed 8 bit number
1186 (def-input-routine input-signed-8bit-number
1187 ((signed-byte 8) 1 sap head)
1188 (signed-sap-ref-8 sap head))
1190 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1191 (def-input-routine input-unsigned-16bit-byte
1192 ((unsigned-byte 16) 2 sap head)
1193 (sap-ref-16 sap head))
1195 ;;; STREAM-IN routine for reading a signed 16 bit number
1196 (def-input-routine input-signed-16bit-byte
1197 ((signed-byte 16) 2 sap head)
1198 (signed-sap-ref-16 sap head))
1200 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1201 (def-input-routine input-unsigned-32bit-byte
1202 ((unsigned-byte 32) 4 sap head)
1203 (sap-ref-32 sap head))
1205 ;;; STREAM-IN routine for reading a signed 32 bit number
1206 (def-input-routine input-signed-32bit-byte
1207 ((signed-byte 32) 4 sap head)
1208 (signed-sap-ref-32 sap head))
1210 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1212 (def-input-routine input-unsigned-64bit-byte
1213 ((unsigned-byte 64) 8 sap head)
1214 (sap-ref-64 sap head))
1215 (def-input-routine input-signed-64bit-byte
1216 ((signed-byte 64) 8 sap head)
1217 (signed-sap-ref-64 sap head)))
1219 ;;; Find an input routine to use given the type. Return as multiple
1220 ;;; values the routine, the real type transfered, and the number of
1221 ;;; bytes per element (and for character types string input routine).
1222 (defun pick-input-routine (type &optional external-format)
1223 (when (subtypep type 'character)
1224 (let ((entry (get-external-format external-format)))
1226 (return-from pick-input-routine
1227 (values (ef-read-char-fun entry)
1230 (ef-read-n-chars-fun entry)
1231 (canonize-external-format external-format entry))))))
1232 (dolist (entry *input-routines*)
1233 (when (and (subtypep type (first entry))
1234 (or (not (fourth entry))
1235 (eq external-format (fourth entry))))
1236 (return-from pick-input-routine
1237 (values (symbol-function (second entry))
1240 ;; FIXME: let's do it the hard way, then (but ignore things like
1241 ;; endianness, efficiency, and the necessary coupling between these
1242 ;; and the output routines). -- CSR, 2004-02-09
1243 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1244 if (subtypep type `(unsigned-byte ,i))
1245 do (return-from pick-input-routine
1247 (lambda (stream eof-error eof-value)
1248 (input-wrapper (stream (/ i 8) eof-error eof-value)
1249 (let ((sap (buffer-sap ibuf))
1250 (head (buffer-head ibuf)))
1251 (loop for j from 0 below (/ i 8)
1255 (sap-ref-8 sap (+ head j))))
1256 finally (return result)))))
1259 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1260 if (subtypep type `(signed-byte ,i))
1261 do (return-from pick-input-routine
1263 (lambda (stream eof-error eof-value)
1264 (input-wrapper (stream (/ i 8) eof-error eof-value)
1265 (let ((sap (buffer-sap ibuf))
1266 (head (buffer-head ibuf)))
1267 (loop for j from 0 below (/ i 8)
1271 (sap-ref-8 sap (+ head j))))
1272 finally (return (if (logbitp (1- i) result)
1273 (dpb result (byte i 0) -1)
1278 ;;; the N-BIN method for FD-STREAMs
1280 ;;; Note that this blocks in UNIX-READ. It is generally used where
1281 ;;; there is a definite amount of reading to be done, so blocking
1282 ;;; isn't too problematical.
1283 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1284 &aux (total-copied 0))
1285 (declare (type fd-stream stream))
1286 (declare (type index start requested total-copied))
1287 (aver (= (length (fd-stream-instead stream)) 0))
1290 (let* ((remaining-request (- requested total-copied))
1291 (ibuf (fd-stream-ibuf stream))
1292 (head (buffer-head ibuf))
1293 (tail (buffer-tail ibuf))
1294 (available (- tail head))
1295 (n-this-copy (min remaining-request available))
1296 (this-start (+ start total-copied))
1297 (this-end (+ this-start n-this-copy))
1298 (sap (buffer-sap ibuf)))
1299 (declare (type index remaining-request head tail available))
1300 (declare (type index n-this-copy))
1301 ;; Copy data from stream buffer into user's buffer.
1302 (%byte-blt sap head buffer this-start this-end)
1303 (incf (buffer-head ibuf) n-this-copy)
1304 (incf total-copied n-this-copy)
1305 ;; Maybe we need to refill the stream buffer.
1306 (cond (;; If there were enough data in the stream buffer, we're done.
1307 (eql total-copied requested)
1308 (return total-copied))
1309 (;; If EOF, we're done in another way.
1310 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1312 (error 'end-of-file :stream stream)
1313 (return total-copied)))
1314 ;; Otherwise we refilled the stream buffer, so fall
1315 ;; through into another pass of the loop.
1318 (defun fd-stream-resync (stream)
1319 (let ((entry (get-external-format (fd-stream-external-format stream))))
1321 (funcall (ef-resync-fun entry) stream))))
1323 (defun get-fd-stream-character-sizer (stream)
1324 (let ((entry (get-external-format (fd-stream-external-format stream))))
1326 (ef-bytes-for-char-fun entry))))
1328 (defun fd-stream-character-size (stream char)
1329 (let ((sizer (get-fd-stream-character-sizer stream)))
1330 (when sizer (funcall sizer char))))
1332 (defun fd-stream-string-size (stream string)
1333 (let ((sizer (get-fd-stream-character-sizer stream)))
1335 (loop for char across string summing (funcall sizer char)))))
1337 (defun find-external-format (external-format)
1338 (when external-format
1339 (get-external-format external-format)))
1341 (defun variable-width-external-format-p (ef-entry)
1342 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1344 (defun bytes-for-char-fun (ef-entry)
1345 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1347 (defmacro define-unibyte-mapping-external-format
1348 (canonical-name (&rest other-names) &body exceptions)
1349 (let ((->code-name (symbolicate canonical-name '->code-mapper))
1350 (code->-name (symbolicate 'code-> canonical-name '-mapper))
1351 (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1352 (string->-name (symbolicate 'string-> canonical-name))
1353 (define-string*-name (symbolicate 'define- canonical-name '->string*))
1354 (string*-name (symbolicate canonical-name '->string*))
1355 (define-string-name (symbolicate 'define- canonical-name '->string))
1356 (string-name (symbolicate canonical-name '->string))
1357 (->string-aref-name (symbolicate canonical-name '->string-aref)))
1359 (define-unibyte-mapper ,->code-name ,code->-name
1361 (declaim (inline ,get-bytes-name))
1362 (defun ,get-bytes-name (string pos)
1363 (declare (optimize speed (safety 0))
1364 (type simple-string string)
1365 (type array-range pos))
1366 (get-latin-bytes #',code->-name ,canonical-name string pos))
1367 (defun ,string->-name (string sstart send null-padding)
1368 (declare (optimize speed (safety 0))
1369 (type simple-string string)
1370 (type array-range sstart send))
1371 (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1372 (defmacro ,define-string*-name (accessor type)
1373 (declare (ignore type))
1374 (let ((name (make-od-name ',string*-name accessor)))
1376 (defun ,name (string sstart send array astart aend)
1377 (,(make-od-name 'latin->string* accessor)
1378 string sstart send array astart aend #',',->code-name)))))
1379 (instantiate-octets-definition ,define-string*-name)
1380 (defmacro ,define-string-name (accessor type)
1381 (declare (ignore type))
1382 (let ((name (make-od-name ',string-name accessor)))
1384 (defun ,name (array astart aend)
1385 (,(make-od-name 'latin->string accessor)
1386 array astart aend #',',->code-name)))))
1387 (instantiate-octets-definition ,define-string-name)
1388 (define-unibyte-external-format ,canonical-name ,other-names
1389 (let ((octet (,code->-name bits)))
1391 (setf (sap-ref-8 sap tail) octet)
1392 (external-format-encoding-error stream bits)))
1393 (let ((code (,->code-name byte)))
1396 (return-from decode-break-reason 1)))
1400 (defmacro define-unibyte-external-format
1401 (canonical-name (&rest other-names)
1402 out-form in-form octets-to-string-symbol string-to-octets-symbol)
1403 `(define-external-format/variable-width (,canonical-name ,@other-names)
1408 ,octets-to-string-symbol
1409 ,string-to-octets-symbol))
1411 (defmacro define-external-format/variable-width
1412 (external-format output-restart replacement-character
1413 out-size-expr out-expr in-size-expr in-expr
1414 octets-to-string-sym string-to-octets-sym)
1415 (let* ((name (first external-format))
1416 (out-function (symbolicate "OUTPUT-BYTES/" name))
1417 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1418 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1419 (in-char-function (symbolicate "INPUT-CHAR/" name))
1420 (resync-function (symbolicate "RESYNC/" name))
1421 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1422 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1423 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1424 (n-buffer (gensym "BUFFER")))
1426 (defun ,size-function (byte)
1427 (declare (ignorable byte))
1429 (defun ,out-function (stream string flush-p start end)
1430 (let ((start (or start 0))
1431 (end (or end (length string))))
1432 (declare (type index start end))
1433 (synchronize-stream-output stream)
1434 (unless (<= 0 start end (length string))
1435 (sequence-bounding-indices-bad-error string start end))
1438 (let ((obuf (fd-stream-obuf stream)))
1439 (string-dispatch (simple-base-string
1440 #!+sb-unicode (simple-array character (*))
1443 (let ((len (buffer-length obuf))
1444 (sap (buffer-sap obuf))
1446 (tail (buffer-tail obuf)))
1447 (declare (type index tail)
1448 ;; STRING bounds have already been checked.
1449 (optimize (safety 0)))
1450 (,@(if output-restart
1451 `(catch 'output-nothing)
1454 ((or (= start end) (< (- len tail) 4)))
1455 (let* ((byte (aref string start))
1456 (bits (char-code byte))
1457 (size ,out-size-expr))
1460 (setf (buffer-tail obuf) tail)
1463 ;; Exited via CATCH: skip the current character.
1467 (flush-output-buffer stream)))
1469 (flush-output-buffer stream))))
1470 (def-output-routines/variable-width (,format
1477 (if (eql byte #\Newline)
1478 (setf (fd-stream-char-pos stream) 0)
1479 (incf (fd-stream-char-pos stream)))
1480 (let ((bits (char-code byte))
1481 (sap (buffer-sap obuf))
1482 (tail (buffer-tail obuf)))
1484 (defun ,in-function (stream buffer start requested eof-error-p
1485 &aux (total-copied 0))
1486 (declare (type fd-stream stream)
1487 (type index start requested total-copied)
1489 (simple-array character (#.+ansi-stream-in-buffer-length+))
1491 (when (fd-stream-eof-forced-p stream)
1492 (setf (fd-stream-eof-forced-p stream) nil)
1493 (return-from ,in-function 0))
1494 (do ((instead (fd-stream-instead stream)))
1495 ((= (fill-pointer instead) 0)
1496 (setf (fd-stream-listen stream) nil))
1497 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1499 (when (= requested total-copied)
1500 (when (= (fill-pointer instead) 0)
1501 (setf (fd-stream-listen stream) nil))
1502 (return-from ,in-function total-copied)))
1505 (let* ((ibuf (fd-stream-ibuf stream))
1506 (head (buffer-head ibuf))
1507 (tail (buffer-tail ibuf))
1508 (sap (buffer-sap ibuf))
1509 (decode-break-reason nil))
1510 (declare (type index head tail))
1511 ;; Copy data from stream buffer into user's buffer.
1512 (do ((size nil nil))
1513 ((or (= tail head) (= requested total-copied)))
1514 (setf decode-break-reason
1515 (block decode-break-reason
1516 ,@(when (consp in-size-expr)
1517 `((when (> ,(car in-size-expr) (- tail head))
1519 (let ((byte (sap-ref-8 sap head)))
1520 (declare (ignorable byte))
1521 (setq size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr))
1522 (when (> size (- tail head))
1524 (setf (aref buffer (+ start total-copied)) ,in-expr)
1528 (setf (buffer-head ibuf) head)
1529 (when decode-break-reason
1530 ;; If we've already read some characters on when the invalid
1531 ;; code sequence is detected, we return immediately. The
1532 ;; handling of the error is deferred until the next call
1533 ;; (where this check will be false). This allows establishing
1534 ;; high-level handlers for decode errors (for example
1535 ;; automatically resyncing in Lisp comments).
1536 (when (plusp total-copied)
1537 (return-from ,in-function total-copied))
1538 (when (stream-decoding-error-and-handle
1539 stream decode-break-reason)
1541 (error 'end-of-file :stream stream)
1542 (return-from ,in-function total-copied)))
1543 ;; we might have been given stuff to use instead, so
1544 ;; we have to return (and trust our caller to know
1545 ;; what to do about TOTAL-COPIED being 0).
1546 (return-from ,in-function total-copied)))
1547 (setf (buffer-head ibuf) head)
1548 ;; Maybe we need to refill the stream buffer.
1549 (cond ( ;; If there were enough data in the stream buffer, we're done.
1550 (= total-copied requested)
1551 (return total-copied))
1552 ( ;; If EOF, we're done in another way.
1553 (or (eq decode-break-reason 'eof)
1554 (null (catch 'eof-input-catcher
1555 (refill-input-buffer stream))))
1557 (error 'end-of-file :stream stream)
1558 (return total-copied)))
1559 ;; Otherwise we refilled the stream buffer, so fall
1560 ;; through into another pass of the loop.
1562 (def-input-routine/variable-width ,in-char-function (character
1566 (let ((byte (sap-ref-8 sap head)))
1567 (declare (ignorable byte))
1569 (defun ,resync-function (stream)
1570 (let ((ibuf (fd-stream-ibuf stream))
1572 (catch 'eof-input-catcher
1574 (incf (buffer-head ibuf))
1575 (input-at-least stream ,(if (consp in-size-expr) (car in-size-expr) `(setq size ,in-size-expr)))
1576 (unless (block decode-break-reason
1577 (let* ((sap (buffer-sap ibuf))
1578 (head (buffer-head ibuf))
1579 (byte (sap-ref-8 sap head)))
1580 (declare (ignorable byte))
1581 ,@(when (consp in-size-expr)
1582 `((setq size ,(cadr in-size-expr))
1583 (input-at-least stream size)))
1584 (setf head (buffer-head ibuf))
1588 (defun ,read-c-string-function (sap element-type)
1589 (declare (type system-area-pointer sap))
1591 (declare (optimize (speed 3) (safety 0)))
1592 (let* ((stream ,name)
1593 (size 0) (head 0) (byte 0) (char nil)
1594 (decode-break-reason nil)
1595 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1596 (setf decode-break-reason
1597 (block decode-break-reason
1598 (setf byte (sap-ref-8 sap head)
1599 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1603 (when decode-break-reason
1604 (c-string-decoding-error ,name decode-break-reason))
1605 (when (zerop (char-code char))
1607 (string (make-string length :element-type element-type)))
1608 (declare (ignorable stream)
1609 (type index head length) ;; size
1610 (type (unsigned-byte 8) byte)
1611 (type (or null character) char)
1612 (type string string))
1614 (dotimes (index length string)
1615 (setf decode-break-reason
1616 (block decode-break-reason
1617 (setf byte (sap-ref-8 sap head)
1618 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1622 (when decode-break-reason
1623 (c-string-decoding-error ,name decode-break-reason))
1624 (setf (aref string index) char)))))
1626 (defun ,output-c-string-function (string)
1627 (declare (type simple-string string))
1629 (declare (optimize (speed 3) (safety 0)))
1630 (let* ((length (length string))
1631 (char-length (make-array (1+ length) :element-type 'index))
1633 (+ (loop for i of-type index below length
1634 for byte of-type character = (aref string i)
1635 for bits = (char-code byte)
1636 sum (setf (aref char-length i)
1637 (the index ,out-size-expr)))
1638 (let* ((byte (code-char 0))
1639 (bits (char-code byte)))
1640 (declare (ignorable byte bits))
1641 (setf (aref char-length length)
1642 (the index ,out-size-expr)))))
1644 (,n-buffer (make-array buffer-length
1645 :element-type '(unsigned-byte 8)))
1647 (declare (type index length buffer-length tail)
1650 (with-pinned-objects (,n-buffer)
1651 (let ((sap (vector-sap ,n-buffer)))
1652 (declare (system-area-pointer sap))
1653 (loop for i of-type index below length
1654 for byte of-type character = (aref string i)
1655 for bits = (char-code byte)
1656 for size of-type index = (aref char-length i)
1661 (byte (code-char bits))
1662 (size (aref char-length length)))
1663 (declare (ignorable bits byte size))
1667 (let ((entry (%make-external-format
1668 :names ',external-format
1669 :default-replacement-character ,replacement-character
1670 :read-n-chars-fun #',in-function
1671 :read-char-fun #',in-char-function
1672 :write-n-bytes-fun #',out-function
1673 ,@(mapcan #'(lambda (buffering)
1674 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1675 `#',(intern (format nil format (string buffering)))))
1676 '(:none :line :full))
1677 :resync-fun #',resync-function
1678 :bytes-for-char-fun #',size-function
1679 :read-c-string-fun #',read-c-string-function
1680 :write-c-string-fun #',output-c-string-function
1681 :octets-to-string-fun (lambda (&rest rest)
1682 (declare (dynamic-extent rest))
1683 (apply ',octets-to-string-sym rest))
1684 :string-to-octets-fun (lambda (&rest rest)
1685 (declare (dynamic-extent rest))
1686 (apply ',string-to-octets-sym rest)))))
1687 (dolist (ef ',external-format)
1688 (setf (gethash ef *external-formats*) entry))))))
1690 ;;;; utility functions (misc routines, etc)
1692 ;;; Fill in the various routine slots for the given type. INPUT-P and
1693 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1694 ;;; set prior to calling this routine.
1695 (defun set-fd-stream-routines (fd-stream element-type external-format
1696 input-p output-p buffer-p)
1697 (let* ((target-type (case element-type
1698 (unsigned-byte '(unsigned-byte 8))
1699 (signed-byte '(signed-byte 8))
1700 (:default 'character)
1702 (character-stream-p (subtypep target-type 'character))
1703 (bivalent-stream-p (eq element-type :default))
1704 normalized-external-format
1705 (bin-routine #'ill-bin)
1708 (cin-routine #'ill-in)
1711 (input-type nil) ;calculated from bin-type/cin-type
1712 (input-size nil) ;calculated from bin-size/cin-size
1713 (read-n-characters #'ill-in)
1714 (bout-routine #'ill-bout)
1717 (cout-routine #'ill-out)
1722 (output-bytes #'ill-bout))
1724 ;; Ensure that we have buffers in the desired direction(s) only,
1725 ;; getting new ones and dropping/resetting old ones as necessary.
1726 (let ((obuf (fd-stream-obuf fd-stream)))
1730 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1732 (setf (fd-stream-obuf fd-stream) nil)
1733 (release-buffer obuf))))
1735 (let ((ibuf (fd-stream-ibuf fd-stream)))
1739 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1741 (setf (fd-stream-ibuf fd-stream) nil)
1742 (release-buffer ibuf))))
1744 ;; FIXME: Why only for output? Why unconditionally?
1746 (setf (fd-stream-char-pos fd-stream) 0))
1748 (when (and character-stream-p
1749 (eq external-format :default))
1750 (/show0 "/getting default external format")
1751 (setf external-format (default-external-format)))
1754 (when (or (not character-stream-p) bivalent-stream-p)
1755 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1756 normalized-external-format)
1757 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1761 (error "could not find any input routine for ~S" target-type)))
1762 (when character-stream-p
1763 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1764 normalized-external-format)
1765 (pick-input-routine target-type external-format))
1767 (error "could not find any input routine for ~S" target-type)))
1768 (setf (fd-stream-in fd-stream) cin-routine
1769 (fd-stream-bin fd-stream) bin-routine)
1770 ;; character type gets preferential treatment
1771 (setf input-size (or cin-size bin-size))
1772 (setf input-type (or cin-type bin-type))
1773 (when normalized-external-format
1774 (setf (fd-stream-external-format fd-stream)
1775 normalized-external-format))
1776 (when (= (or cin-size 1) (or bin-size 1) 1)
1777 (setf (fd-stream-n-bin fd-stream) ;XXX
1778 (if (and character-stream-p (not bivalent-stream-p))
1780 #'fd-stream-read-n-bytes))
1781 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1782 ;; for character and (unsigned-byte 8) streams. In these
1783 ;; cases, fast-read-* will read from the
1784 ;; ansi-stream-(c)in-buffer, saving function calls.
1785 ;; Otherwise, the various data-reading functions in the stream
1786 ;; structure will be called.
1788 (not bivalent-stream-p)
1789 ;; temporary disable on :io streams
1791 (cond (character-stream-p
1792 (setf (ansi-stream-cin-buffer fd-stream)
1793 (make-array +ansi-stream-in-buffer-length+
1794 :element-type 'character)))
1795 ((equal target-type '(unsigned-byte 8))
1796 (setf (ansi-stream-in-buffer fd-stream)
1797 (make-array +ansi-stream-in-buffer-length+
1798 :element-type '(unsigned-byte 8))))))))
1801 (when (or (not character-stream-p) bivalent-stream-p)
1802 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1803 normalized-external-format)
1804 (let ((buffering (fd-stream-buffering fd-stream)))
1805 (if bivalent-stream-p
1806 (pick-output-routine '(unsigned-byte 8)
1807 (if (eq :line buffering)
1811 (pick-output-routine target-type buffering external-format))))
1812 (unless bout-routine
1813 (error "could not find any output routine for ~S buffered ~S"
1814 (fd-stream-buffering fd-stream)
1816 (when character-stream-p
1817 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1818 normalized-external-format)
1819 (pick-output-routine target-type
1820 (fd-stream-buffering fd-stream)
1822 (unless cout-routine
1823 (error "could not find any output routine for ~S buffered ~S"
1824 (fd-stream-buffering fd-stream)
1826 (when normalized-external-format
1827 (setf (fd-stream-external-format fd-stream)
1828 normalized-external-format))
1829 (when character-stream-p
1830 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1831 (setf (fd-stream-out fd-stream) cout-routine
1832 (fd-stream-bout fd-stream) bout-routine
1833 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1834 #'fd-sout #'ill-out))
1835 (setf output-size (or cout-size bout-size))
1836 (setf output-type (or cout-type bout-type)))
1838 (when (and input-size output-size
1839 (not (eq input-size output-size)))
1840 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1841 input-type input-size
1842 output-type output-size))
1843 (setf (fd-stream-element-size fd-stream)
1844 (or input-size output-size))
1846 (setf (fd-stream-element-type fd-stream)
1847 (cond ((equal input-type output-type)
1853 ((subtypep input-type output-type)
1855 ((subtypep output-type input-type)
1858 (error "Input type (~S) and output type (~S) are unrelated?"
1862 ;;; Handles the resource-release aspects of stream closing, and marks
1864 (defun release-fd-stream-resources (fd-stream)
1867 ;; Drop handlers first.
1868 (when (fd-stream-handler fd-stream)
1869 (remove-fd-handler (fd-stream-handler fd-stream))
1870 (setf (fd-stream-handler fd-stream) nil))
1871 ;; Disable interrupts so that a asynch unwind will not leave
1872 ;; us with a dangling finalizer (that would close the same
1873 ;; --possibly reassigned-- FD again), or a stream with a closed
1874 ;; FD that appears open.
1875 (sb!unix:unix-close (fd-stream-fd fd-stream))
1876 (set-closed-flame fd-stream)
1877 (when (fboundp 'cancel-finalization)
1878 (cancel-finalization fd-stream)))
1879 ;; On error unwind from WITHOUT-INTERRUPTS.
1880 (serious-condition (e)
1882 ;; Release all buffers. If this is undone, or interrupted,
1883 ;; we're still safe: buffers have finalizers of their own.
1884 (release-fd-stream-buffers fd-stream))
1886 ;;; Flushes the current input buffer and any supplied replacements,
1887 ;;; and returns the input buffer, and the amount of of flushed input
1889 (defun flush-input-buffer (stream)
1890 (let ((unread (length (fd-stream-instead stream))))
1891 (setf (fill-pointer (fd-stream-instead stream)) 0)
1892 (let ((ibuf (fd-stream-ibuf stream)))
1894 (let ((head (buffer-head ibuf))
1895 (tail (buffer-tail ibuf)))
1896 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1897 (values nil unread)))))
1899 (defun fd-stream-clear-input (stream)
1900 (flush-input-buffer stream)
1903 (sb!win32:fd-clear-input (fd-stream-fd stream))
1904 (setf (fd-stream-listen stream) nil))
1906 (catch 'eof-input-catcher
1907 (loop until (sysread-may-block-p stream)
1909 (refill-input-buffer stream)
1910 (reset-buffer (fd-stream-ibuf stream)))
1913 ;;; Handle miscellaneous operations on FD-STREAM.
1914 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1915 (declare (ignore arg2))
1918 (labels ((do-listen ()
1919 (let ((ibuf (fd-stream-ibuf fd-stream)))
1920 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1921 (fd-stream-listen fd-stream)
1923 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1925 ;; If the read can block, LISTEN will certainly return NIL.
1926 (if (sysread-may-block-p fd-stream)
1928 ;; Otherwise select(2) and CL:LISTEN have slightly
1929 ;; different semantics. The former returns that an FD
1930 ;; is readable when a read operation wouldn't block.
1931 ;; That includes EOF. However, LISTEN must return NIL
1933 (progn (catch 'eof-input-catcher
1934 ;; r-b/f too calls select, but it shouldn't
1935 ;; block as long as read can return once w/o
1937 (refill-input-buffer fd-stream))
1938 ;; At this point either IBUF-HEAD != IBUF-TAIL
1939 ;; and FD-STREAM-LISTEN is NIL, in which case
1940 ;; we should return T, or IBUF-HEAD ==
1941 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1942 ;; which case we should return :EOF for this
1943 ;; call and all future LISTEN call on this stream.
1944 ;; Call ourselves again to determine which case
1949 (decf (buffer-head (fd-stream-ibuf fd-stream))
1950 (fd-stream-character-size fd-stream arg1)))
1952 ;; Drop input buffers
1953 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1954 (ansi-stream-cin-buffer fd-stream) nil
1955 (ansi-stream-in-buffer fd-stream) nil)
1957 ;; We got us an abort on our hands.
1958 (let ((outputp (fd-stream-obuf fd-stream))
1959 (file (fd-stream-file fd-stream))
1960 (orig (fd-stream-original fd-stream)))
1961 ;; This takes care of the important stuff -- everything
1962 ;; rest is cleaning up the file-system, which we cannot
1963 ;; do on some platforms as long as the file is open.
1964 (release-fd-stream-resources fd-stream)
1965 ;; We can't do anything unless we know what file were
1966 ;; dealing with, and we don't want to do anything
1967 ;; strange unless we were writing to the file.
1968 (when (and outputp file)
1970 ;; If the original is EQ to file we are appending to
1971 ;; and can just close the file without renaming.
1972 (unless (eq orig file)
1973 ;; We have a handle on the original, just revert.
1974 (multiple-value-bind (okay err)
1975 (sb!unix:unix-rename orig file)
1976 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1977 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1980 (error 'simple-stream-error
1982 "~@<Couldn't restore ~S to its original contents ~
1983 from ~S while closing ~S: ~2I~_~A~:>"
1985 (list file orig fd-stream (strerror err))
1986 :stream fd-stream))))
1987 ;; We can't restore the original, and aren't
1988 ;; appending, so nuke that puppy.
1990 ;; FIXME: This is currently the fate of superseded
1991 ;; files, and according to the CLOSE spec this is
1992 ;; wrong. However, there seems to be no clean way to
1993 ;; do that that doesn't involve either copying the
1994 ;; data (bad if the :abort resulted from a full
1995 ;; disk), or renaming the old file temporarily
1996 ;; (probably bad because stream opening becomes more
1998 (multiple-value-bind (okay err)
1999 (sb!unix:unix-unlink file)
2001 (error 'simple-file-error
2004 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2006 (list file fd-stream (strerror err)))))))))
2008 (finish-fd-stream-output fd-stream)
2009 (let ((orig (fd-stream-original fd-stream)))
2010 (when (and orig (fd-stream-delete-original fd-stream))
2011 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2013 (error 'simple-file-error
2016 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2018 (list orig fd-stream (strerror err)))))))
2019 ;; In case of no-abort close, don't *really* close the
2020 ;; stream until the last moment -- the cleaning up of the
2021 ;; original can be done first.
2022 (release-fd-stream-resources fd-stream))))
2024 (fd-stream-clear-input fd-stream))
2026 (flush-output-buffer fd-stream))
2028 (finish-fd-stream-output fd-stream))
2030 (fd-stream-element-type fd-stream))
2032 (fd-stream-external-format fd-stream))
2034 (= 1 (the (member 0 1)
2035 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2039 (fd-stream-char-pos fd-stream))
2041 (unless (fd-stream-file fd-stream)
2042 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2043 ;; "should signal an error of type TYPE-ERROR if stream is not
2044 ;; a stream associated with a file". Too bad there's no very
2045 ;; appropriate value for the EXPECTED-TYPE slot..
2046 (error 'simple-type-error
2048 :expected-type 'fd-stream
2049 :format-control "~S is not a stream associated with a file."
2050 :format-arguments (list fd-stream)))
2051 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2052 atime mtime ctime blksize blocks)
2053 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2054 (declare (ignore ino nlink uid gid rdev
2055 atime mtime ctime blksize blocks))
2057 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2060 (truncate size (fd-stream-element-size fd-stream)))))
2061 (:file-string-length
2063 (character (fd-stream-character-size fd-stream arg1))
2064 (string (fd-stream-string-size fd-stream arg1))))
2067 (fd-stream-set-file-position fd-stream arg1)
2068 (fd-stream-get-file-position fd-stream)))))
2070 ;; FIXME: Think about this.
2072 ;; (defun finish-fd-stream-output (fd-stream)
2073 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2074 ;; (loop while (fd-stream-output-queue fd-stream)
2075 ;; ;; FIXME: SIGINT while waiting for a timeout will
2076 ;; ;; cause a timeout here.
2077 ;; do (when (and (not (serve-event timeout)) timeout)
2078 ;; (signal-timeout 'io-timeout
2079 ;; :stream fd-stream
2080 ;; :direction :write
2081 ;; :seconds timeout)))))
2083 (defun finish-fd-stream-output (stream)
2084 (flush-output-buffer stream)
2086 ((null (fd-stream-output-queue stream)))
2087 (aver (fd-stream-serve-events stream))
2088 (serve-all-events)))
2090 (defun fd-stream-get-file-position (stream)
2091 (declare (fd-stream stream))
2093 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2094 (declare (type (or (alien sb!unix:off-t) null) posn))
2095 ;; We used to return NIL for errno==ESPIPE, and signal an error
2096 ;; in other failure cases. However, CLHS says to return NIL if
2097 ;; the position cannot be determined -- so that's what we do.
2098 (when (integerp posn)
2099 ;; Adjust for buffered output: If there is any output
2100 ;; buffered, the *real* file position will be larger
2101 ;; than reported by lseek() because lseek() obviously
2102 ;; cannot take into account output we have not sent
2104 (dolist (buffer (fd-stream-output-queue stream))
2105 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2106 (let ((obuf (fd-stream-obuf stream)))
2108 (incf posn (buffer-tail obuf))))
2109 ;; Adjust for unread input: If there is any input
2110 ;; read from UNIX but not supplied to the user of the
2111 ;; stream, the *real* file position will smaller than
2112 ;; reported, because we want to look like the unread
2113 ;; stuff is still available.
2114 (let ((ibuf (fd-stream-ibuf stream)))
2116 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2117 ;; Divide bytes by element size.
2118 (truncate posn (fd-stream-element-size stream))))))
2120 (defun fd-stream-set-file-position (stream position-spec)
2121 (declare (fd-stream stream))
2122 (check-type position-spec
2123 (or (alien sb!unix:off-t) (member nil :start :end))
2124 "valid file position designator")
2127 ;; Make sure we don't have any output pending, because if we
2128 ;; move the file pointer before writing this stuff, it will be
2129 ;; written in the wrong location.
2130 (finish-fd-stream-output stream)
2131 ;; Disable interrupts so that interrupt handlers doing output
2134 (unless (fd-stream-output-finished-p stream)
2135 ;; We got interrupted and more output came our way during
2136 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2137 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2138 ;; so we prefer to do things like this...
2140 ;; Clear out any pending input to force the next read to go to
2142 (flush-input-buffer stream)
2143 ;; Trash cached value for listen, so that we check next time.
2144 (setf (fd-stream-listen stream) nil)
2146 (multiple-value-bind (offset origin)
2149 (values 0 sb!unix:l_set))
2151 (values 0 sb!unix:l_xtnd))
2153 (values (* position-spec (fd-stream-element-size stream))
2155 (declare (type (alien sb!unix:off-t) offset))
2156 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2158 ;; CLHS says to return true if the file-position was set
2159 ;; succesfully, and NIL otherwise. We are to signal an error
2160 ;; only if the given position was out of bounds, and that is
2161 ;; dealt with above. In times past we used to return NIL for
2162 ;; errno==ESPIPE, and signal an error in other cases.
2164 ;; FIXME: We are still liable to signal an error if flushing
2166 (return-from fd-stream-set-file-position
2167 (typep posn '(alien sb!unix:off-t))))))))
2170 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2172 ;;; Create a stream for the given Unix file descriptor.
2174 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2175 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2176 ;;; default to allowing input.
2178 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2180 ;;; BUFFERING indicates the kind of buffering to use.
2182 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2183 ;;; NIL (the default), then wait forever. When we time out, we signal
2186 ;;; FILE is the name of the file (will be returned by PATHNAME).
2188 ;;; NAME is used to identify the stream when printed.
2190 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2191 ;;; handle blocking IO on the stream.
2192 (defun make-fd-stream (fd
2195 (output nil output-p)
2196 (element-type 'base-char)
2198 (external-format :default)
2208 (format nil "file ~A" file)
2209 (format nil "descriptor ~W" fd)))
2211 (declare (type index fd) (type (or real null) timeout)
2212 (type (member :none :line :full) buffering))
2213 (cond ((not (or input-p output-p))
2215 ((not (or input output))
2216 (error "File descriptor must be opened either for input or output.")))
2217 (let ((stream (%make-fd-stream :fd fd
2221 :delete-original delete-original
2223 :buffering buffering
2224 :dual-channel-p dual-channel-p
2225 :external-format external-format
2226 :bivalent-p (eq element-type :default)
2227 :char-size (external-format-char-size external-format)
2228 :serve-events serve-events
2231 (coerce timeout 'single-float)
2233 (set-fd-stream-routines stream element-type external-format
2234 input output input-buffer-p)
2235 (when (and auto-close (fboundp 'finalize))
2238 (sb!unix:unix-close fd)
2240 (format *terminal-io* "** closed file descriptor ~W **~%"
2245 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2246 ;;; :RENAME-AND-DELETE and :RENAME options.
2247 (defun pick-backup-name (name)
2248 (declare (type simple-string name))
2249 (concatenate 'simple-string name ".bak"))
2251 ;;; Ensure that the given arg is one of the given list of valid
2252 ;;; things. Allow the user to fix any problems.
2253 (defun ensure-one-of (item list what)
2254 (unless (member item list)
2255 (error 'simple-type-error
2257 :expected-type `(member ,@list)
2258 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2259 :format-arguments (list item what list))))
2261 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2262 ;;; access, since we don't want to trash unwritable files even if we
2263 ;;; technically can. We return true if we succeed in renaming.
2264 (defun rename-the-old-one (namestring original)
2265 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2266 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2267 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2270 (error 'simple-file-error
2271 :pathname namestring
2273 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2274 :format-arguments (list namestring original (strerror err))))))
2276 (defun open (filename
2279 (element-type 'base-char)
2280 (if-exists nil if-exists-given)
2281 (if-does-not-exist nil if-does-not-exist-given)
2282 (external-format :default)
2283 &aux ; Squelch assignment warning.
2284 (direction direction)
2285 (if-does-not-exist if-does-not-exist)
2286 (if-exists if-exists))
2288 "Return a stream which reads from or writes to FILENAME.
2290 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2291 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2292 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2293 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2294 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2295 See the manual for details."
2297 ;; Calculate useful stuff.
2298 (multiple-value-bind (input output mask)
2300 (:input (values t nil sb!unix:o_rdonly))
2301 (:output (values nil t sb!unix:o_wronly))
2302 (:io (values t t sb!unix:o_rdwr))
2303 (:probe (values t nil sb!unix:o_rdonly)))
2304 (declare (type index mask))
2305 (let* (;; PATHNAME is the pathname we associate with the stream.
2306 (pathname (merge-pathnames filename))
2307 (physical (physicalize-pathname pathname))
2308 (truename (probe-file physical))
2309 ;; NAMESTRING is the native namestring we open the file with.
2310 (namestring (cond (truename
2311 (native-namestring truename :as-file t))
2313 (and input (eq if-does-not-exist :create))
2314 (and (eq direction :io) (not if-does-not-exist-given)))
2315 (native-namestring physical :as-file t)))))
2316 ;; Process if-exists argument if we are doing any output.
2318 (unless if-exists-given
2320 (if (eq (pathname-version pathname) :newest)
2323 (ensure-one-of if-exists
2324 '(:error :new-version :rename
2325 :rename-and-delete :overwrite
2326 :append :supersede nil)
2329 ((:new-version :error nil)
2330 (setf mask (logior mask sb!unix:o_excl)))
2331 ((:rename :rename-and-delete)
2332 (setf mask (logior mask sb!unix:o_creat)))
2334 (setf mask (logior mask sb!unix:o_trunc)))
2336 (setf mask (logior mask sb!unix:o_append)))))
2338 (setf if-exists :ignore-this-arg)))
2340 (unless if-does-not-exist-given
2341 (setf if-does-not-exist
2342 (cond ((eq direction :input) :error)
2344 (member if-exists '(:overwrite :append)))
2346 ((eq direction :probe)
2350 (ensure-one-of if-does-not-exist
2351 '(:error :create nil)
2353 (if (eq if-does-not-exist :create)
2354 (setf mask (logior mask sb!unix:o_creat)))
2356 (let ((original (case if-exists
2357 ((:rename :rename-and-delete)
2358 (pick-backup-name namestring))
2359 ((:append :overwrite)
2360 ;; KLUDGE: Provent CLOSE from deleting
2361 ;; appending streams when called with :ABORT T
2363 (delete-original (eq if-exists :rename-and-delete))
2365 (when (and original (not (eq original namestring)))
2366 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2367 ;; whether the file already exists, make sure the original
2368 ;; file is not a directory, and keep the mode.
2371 (multiple-value-bind (okay err/dev inode orig-mode)
2372 (sb!unix:unix-stat namestring)
2373 (declare (ignore inode)
2374 (type (or index null) orig-mode))
2377 (when (and output (= (logand orig-mode #o170000)
2379 (error 'simple-file-error
2382 "can't open ~S for output: is a directory"
2383 :format-arguments (list namestring)))
2384 (setf mode (logand orig-mode #o777))
2386 ((eql err/dev sb!unix:enoent)
2389 (simple-file-perror "can't find ~S"
2393 (rename-the-old-one namestring original))
2395 (setf delete-original nil)
2396 ;; In order to use :SUPERSEDE instead, we have to make
2397 ;; sure SB!UNIX:O_CREAT corresponds to
2398 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2399 ;; because of IF-EXISTS being :RENAME.
2400 (unless (eq if-does-not-exist :create)
2402 (logior (logandc2 mask sb!unix:o_creat)
2404 (setf if-exists :supersede))))
2406 ;; Now we can try the actual Unix open(2).
2407 (multiple-value-bind (fd errno)
2409 (sb!unix:unix-open namestring mask mode)
2410 (values nil sb!unix:enoent))
2411 (labels ((open-error (format-control &rest format-arguments)
2412 (error 'simple-file-error
2414 :format-control format-control
2415 :format-arguments format-arguments))
2416 (vanilla-open-error ()
2417 (simple-file-perror "error opening ~S" pathname errno)))
2420 ((:input :output :io)
2424 :element-type element-type
2425 :external-format external-format
2428 :delete-original delete-original
2436 (%make-fd-stream :name namestring
2439 :element-type element-type)))
2442 ((eql errno sb!unix:enoent)
2443 (case if-does-not-exist
2444 (:error (vanilla-open-error))
2446 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2449 ((and (eql errno sb!unix:eexist) (null if-exists))
2452 (vanilla-open-error)))))))))
2456 ;;; the stream connected to the controlling terminal, or NIL if there is none
2459 ;;; the stream connected to the standard input (file descriptor 0)
2462 ;;; the stream connected to the standard output (file descriptor 1)
2465 ;;; the stream connected to the standard error output (file descriptor 2)
2468 ;;; This is called when the cold load is first started up, and may also
2469 ;;; be called in an attempt to recover from nested errors.
2470 (defun stream-cold-init-or-reset ()
2472 (setf *terminal-io* (make-synonym-stream '*tty*))
2473 (setf *standard-output* (make-synonym-stream '*stdout*))
2474 (setf *standard-input* (make-synonym-stream '*stdin*))
2475 (setf *error-output* (make-synonym-stream '*stderr*))
2476 (setf *query-io* (make-synonym-stream '*terminal-io*))
2477 (setf *debug-io* *query-io*)
2478 (setf *trace-output* *standard-output*)
2481 (defun stream-deinit ()
2482 ;; Unbind to make sure we're not accidently dealing with it
2483 ;; before we're ready (or after we think it's been deinitialized).
2484 (with-available-buffers-lock ()
2485 (without-package-locks
2486 (makunbound '*available-buffers*))))
2488 (defun stdstream-external-format (outputp)
2489 (declare (ignorable outputp))
2490 (let* ((keyword #!+win32 (if outputp (sb!win32::console-output-codepage) (sb!win32::console-input-codepage))
2491 #!-win32 (default-external-format))
2492 (ef (get-external-format keyword))
2493 (replacement (ef-default-replacement-character ef)))
2494 `(,keyword :replacement ,replacement)))
2496 ;;; This is called whenever a saved core is restarted.
2497 (defun stream-reinit (&optional init-buffers-p)
2498 (when init-buffers-p
2499 (with-available-buffers-lock ()
2500 (aver (not (boundp '*available-buffers*)))
2501 (setf *available-buffers* nil)))
2502 (with-output-to-string (*error-output*)
2504 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2505 :element-type :default
2507 :external-format (stdstream-external-format nil)))
2509 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2510 :element-type :default
2511 :external-format (stdstream-external-format t)))
2513 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2514 :element-type :default
2515 :external-format (stdstream-external-format t)))
2516 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2517 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2520 (make-fd-stream tty :name "the terminal"
2521 :input t :output t :buffering :line
2522 :external-format (stdstream-external-format t)
2524 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2525 (princ (get-output-stream-string *error-output*) *stderr*))
2530 ;;; the Unix way to beep
2531 (defun beep (stream)
2532 (write-char (code-char bell-char-code) stream)
2533 (finish-output stream))
2535 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2536 ;;; by the filesys stuff to get and set the file name.
2538 ;;; FIXME: misleading name, screwy interface
2539 (defun file-name (stream &optional new-name)
2540 (when (typep stream 'fd-stream)
2542 (setf (fd-stream-pathname stream) new-name)
2543 (setf (fd-stream-file stream)
2544 (native-namestring (physicalize-pathname new-name)
2548 (fd-stream-pathname stream)))))