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
))
175 (ibuf nil
:type
(or buffer null
))
178 (obuf nil
:type
(or buffer null
))
180 ;; output flushed, but not written due to non-blocking io?
183 ;; timeout specified for this stream as seconds or NIL if none
184 (timeout nil
:type
(or single-float null
))
185 ;; pathname of the file this stream is opened to (returned by PATHNAME)
186 (pathname nil
:type
(or pathname null
))
187 (external-format :default
)
188 ;; fixed width, or function to call with a character
189 (char-size 1 :type
(or fixnum function
))
190 (output-bytes #'ill-out
:type function
))
191 (def!method print-object
((fd-stream fd-stream
) stream
)
192 (declare (type stream stream
))
193 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
194 (format stream
"for ~S" (fd-stream-name fd-stream
))))
196 ;;;; CORE OUTPUT FUNCTIONS
198 ;;; Buffer the section of THING delimited by START and END by copying
199 ;;; to output buffer(s) of stream.
200 (defun buffer-output (stream thing start end
)
201 (declare (index start end
))
203 (error ":END before :START!"))
205 ;; Copy bytes from THING to buffers.
206 (flet ((copy-to-buffer (buffer tail count
)
207 (declare (buffer buffer
) (index tail count
))
209 (let ((sap (buffer-sap buffer
)))
212 (system-area-ub8-copy thing start sap tail count
))
213 ((simple-unboxed-array (*))
214 (copy-ub8-to-system-area thing start sap tail count
))))
215 ;; Not INCF! If another thread has moved tail from under
216 ;; us, we don't want to accidentally increment tail
217 ;; beyond buffer-length.
218 (setf (buffer-tail buffer
) (+ count tail
))
221 ;; First copy is special: the buffer may already contain
222 ;; something, or be even full.
223 (let* ((obuf (fd-stream-obuf stream
))
224 (tail (buffer-tail obuf
))
225 (space (- (buffer-length obuf
) tail
)))
227 (copy-to-buffer obuf tail
(min space
(- end start
)))
228 (go :more-output-p
)))
230 ;; Later copies should always have an empty buffer, since
231 ;; they are freshly flushed, but if another thread is
232 ;; stomping on the same buffer that might not be the case.
233 (let* ((obuf (flush-output-buffer stream
))
234 (tail (buffer-tail obuf
))
235 (space (- (buffer-length obuf
) tail
)))
236 (copy-to-buffer obuf tail
(min space
(- end start
))))
239 (go :flush-and-fill
))))))
241 ;;; Flush the current output buffer of the stream, ensuring that the
242 ;;; new buffer is empty. Returns (for convenience) the new output
243 ;;; buffer -- which may or may not be EQ to the old one. If the is no
244 ;;; queued output we try to write the buffer immediately -- otherwise
245 ;;; we queue it for later.
246 (defun flush-output-buffer (stream)
247 (let ((obuf (fd-stream-obuf stream
)))
249 (let ((head (buffer-head obuf
))
250 (tail (buffer-tail obuf
)))
251 (cond ((eql head tail
)
252 ;; Buffer is already empty -- just ensure that is is
253 ;; set to zero as well.
255 ((fd-stream-output-queue stream
)
256 ;; There is already stuff on the queue -- go directly
259 (%queue-and-replace-output-buffer stream
))
261 ;; Try a non-blocking write, queue whatever is left over.
263 (synchronize-stream-output stream
)
264 (let ((length (- tail head
)))
265 (multiple-value-bind (count errno
)
266 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
268 (cond ((eql count length
)
269 ;; Complete write -- we can use the same buffer.
272 ;; Partial write -- update buffer status and queue.
273 ;; Do not use INCF! Another thread might have moved
275 (setf (buffer-head obuf
) (+ count head
))
276 (%queue-and-replace-output-buffer stream
))
278 ((eql errno sb
!unix
:ewouldblock
)
280 (%queue-and-replace-output-buffer stream
))
282 (simple-stream-perror "Couldn't write to ~s"
283 stream errno
)))))))))))
285 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
286 (defun %queue-and-replace-output-buffer
(stream)
287 (let ((queue (fd-stream-output-queue stream
))
288 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
290 ;; Important: before putting the buffer on queue, give the stream
291 ;; a new one. If we get an interrupt and unwind losing the buffer
292 ;; is relatively OK, but having the same buffer in two places
294 (setf (fd-stream-obuf stream
) new
)
298 (setf (fd-stream-output-queue stream
) later
)))
299 (unless (fd-stream-handler stream
)
300 (setf (fd-stream-handler stream
)
301 (add-fd-handler (fd-stream-fd stream
)
304 (declare (ignore fd
))
305 (write-output-from-queue stream
)))))
308 ;;; This is called by the FD-HANDLER for the stream when output is
310 (defun write-output-from-queue (stream)
311 (synchronize-stream-output stream
)
315 (let* ((buffer (pop (fd-stream-output-queue stream
)))
316 (head (buffer-head buffer
))
317 (length (- (buffer-tail buffer
) head
)))
318 (declare (index head length
))
320 (multiple-value-bind (count errno
)
321 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
323 (cond ((eql count length
)
324 ;; Complete write, see if we can do another right
325 ;; away, or remove the handler if we're done.
326 (release-buffer buffer
)
327 (cond ((fd-stream-output-queue stream
)
331 (let ((handler (fd-stream-handler stream
)))
333 (setf (fd-stream-handler stream
) nil
)
334 (remove-fd-handler handler
)))))
336 ;; Partial write. Update buffer status and requeue.
337 (aver (< count length
))
338 ;; Do not use INCF! Another thread might have moved head.
339 (setf (buffer-head buffer
) (+ head count
))
340 (push buffer
(fd-stream-output-queue stream
)))
342 ;; We tried to do multiple writes, and finally our
343 ;; luck ran out. Requeue.
344 (push buffer
(fd-stream-output-queue stream
)))
346 ;; Could not write on the first try at all!
348 (simple-stream-perror "Couldn't write to ~S." stream errno
)
350 (if (= errno sb
!unix
:ewouldblock
)
351 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
352 (simple-stream-perror "Couldn't write to ~S"
356 ;;; Try to write THING directly to STREAM without buffering, if
357 ;;; possible. If direct write doesn't happen, buffer.
358 (defun write-or-buffer-output (stream thing start end
)
359 (declare (index start end
))
360 (cond ((fd-stream-output-queue stream
)
361 (buffer-output stream thing start end
))
363 (error ":END before :START!"))
365 (let ((length (- end start
)))
366 (synchronize-stream-output stream
)
367 (multiple-value-bind (count errno
)
368 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
369 (cond ((eql count length
)
370 ;; Complete write -- done!
373 (aver (< count length
))
374 ;; Partial write -- buffer the rest.
375 (buffer-output stream thing
(+ start count
) end
))
377 ;; Could not write -- buffer or error.
379 (simple-stream-perror "couldn't write to ~s" stream errno
)
381 (if (= errno sb
!unix
:ewouldblock
)
382 (buffer-output stream thing start end
)
383 (simple-stream-perror "couldn't write to ~s" stream errno
)))))))))
385 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
386 ;;; this is not something we want to export. Nikodemus thinks the
387 ;;; right thing is to support a low-level non-stream like IO layer,
388 ;;; akin to java.nio.
389 (defun output-raw-bytes (stream thing
&optional start end
)
390 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
392 (define-compiler-macro output-raw-bytes
(stream thing
&optional start end
)
393 (deprecation-warning 'output-raw-bytes
)
394 (let ((x (gensym "THING")))
396 (write-or-buffer-output ,stream
,x
(or ,start
0) (or ,end
(length ,x
))))))
398 ;;;; output routines and related noise
400 (defvar *output-routines
* ()
402 "List of all available output routines. Each element is a list of the
403 element-type output, the kind of buffering, the function name, and the number
404 of bytes per element.")
406 ;;; common idioms for reporting low-level stream and file problems
407 (defun simple-stream-perror (note-format stream errno
)
408 (error 'simple-stream-error
410 :format-control
"~@<~?: ~2I~_~A~:>"
411 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
412 (defun simple-file-perror (note-format pathname errno
)
413 (error 'simple-file-error
415 :format-control
"~@<~?: ~2I~_~A~:>"
417 (list note-format
(list pathname
) (strerror errno
))))
419 (defun stream-decoding-error (stream octets
)
420 (error 'stream-decoding-error
422 ;; FIXME: dunno how to get at OCTETS currently, or even if
423 ;; that's the right thing to report.
425 (defun stream-encoding-error (stream code
)
426 (error 'stream-encoding-error
430 (defun c-string-encoding-error (external-format code
)
431 (error 'c-string-encoding-error
432 :external-format external-format
435 (defun c-string-decoding-error (external-format octets
)
436 (error 'c-string-decoding-error
437 :external-format external-format
440 ;;; Returning true goes into end of file handling, false will enter another
441 ;;; round of input buffer filling followed by re-entering character decode.
442 (defun stream-decoding-error-and-handle (stream octet-count
)
444 (stream-decoding-error stream
445 (let* ((buffer (fd-stream-ibuf stream
))
446 (sap (buffer-sap buffer
))
447 (head (buffer-head buffer
)))
448 (loop for i from
0 below octet-count
449 collect
(sap-ref-8 sap
(+ head i
)))))
451 :report
(lambda (stream)
453 "~@<Attempt to resync the stream at a character ~
454 character boundary and continue.~@:>"))
455 (fd-stream-resync stream
)
457 (force-end-of-file ()
458 :report
(lambda (stream)
459 (format stream
"~@<Force an end of file.~@:>"))
462 (defun stream-encoding-error-and-handle (stream code
)
464 (stream-encoding-error stream code
)
466 :report
(lambda (stream)
467 (format stream
"~@<Skip output of this character.~@:>"))
468 (throw 'output-nothing nil
))))
470 (defun external-format-encoding-error (stream code
)
472 (stream-encoding-error-and-handle stream code
)
473 (c-string-encoding-error stream code
)))
475 (defun external-format-decoding-error (stream octet-count
)
477 (stream-decoding-error stream octet-count
)
478 (c-string-decoding-error stream octet-count
)))
480 (defun synchronize-stream-output (stream)
481 ;; If we're reading and writing on the same file, flush buffered
482 ;; input and rewind file position accordingly.
483 (unless (fd-stream-dual-channel-p stream
)
484 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
485 (unless (eql 0 adjust
)
486 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
488 (defun fd-stream-output-finished-p (stream)
489 (let ((obuf (fd-stream-obuf stream
)))
491 (and (zerop (buffer-tail obuf
))
492 (not (fd-stream-output-queue stream
))))))
494 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
496 (let ((stream-var (gensym "STREAM")))
497 `(let* ((,stream-var
,stream
)
498 (obuf (fd-stream-obuf ,stream-var
))
499 (tail (buffer-tail obuf
))
501 ,(unless (eq (car buffering
) :none
)
502 `(when (<= (buffer-length obuf
) (+ tail size
))
503 (setf obuf
(flush-output-buffer ,stream-var
)
504 tail
(buffer-tail obuf
))))
505 ,(unless (eq (car buffering
) :none
)
506 ;; FIXME: Why this here? Doesn't seem necessary.
507 `(synchronize-stream-output ,stream-var
))
509 `(catch 'output-nothing
511 (setf (buffer-tail obuf
) (+ tail size
)))
514 (setf (buffer-tail obuf
) (+ tail size
))))
515 ,(ecase (car buffering
)
517 `(flush-output-buffer ,stream-var
))
519 `(when (eql byte
#\Newline
)
520 (flush-output-buffer ,stream-var
)))
524 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
525 (let ((stream-var (gensym "STREAM")))
526 `(let* ((,stream-var
,stream
)
527 (obuf (fd-stream-obuf ,stream-var
))
528 (tail (buffer-tail obuf
)))
529 ,(unless (eq (car buffering
) :none
)
530 `(when (<= (buffer-length obuf
) (+ tail
,size
))
531 (setf obuf
(flush-output-buffer ,stream-var
)
532 tail
(buffer-tail obuf
))))
533 ;; FIXME: Why this here? Doesn't seem necessary.
534 ,(unless (eq (car buffering
) :none
)
535 `(synchronize-stream-output ,stream-var
))
537 `(catch 'output-nothing
539 (setf (buffer-tail obuf
) (+ tail
,size
)))
542 (setf (buffer-tail obuf
) (+ tail
,size
))))
543 ,(ecase (car buffering
)
545 `(flush-output-buffer ,stream-var
))
547 `(when (eql byte
#\Newline
)
548 (flush-output-buffer ,stream-var
)))
552 (defmacro def-output-routines
/variable-width
553 ((name-fmt size restart external-format
&rest bufferings
)
555 (declare (optimize (speed 1)))
560 (intern (format nil name-fmt
(string (car buffering
))))))
562 (defun ,function
(stream byte
)
563 (declare (ignorable byte
))
564 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
566 (setf *output-routines
*
567 (nconc *output-routines
*
575 (cdr buffering
)))))))
578 ;;; Define output routines that output numbers SIZE bytes long for the
579 ;;; given bufferings. Use BODY to do the actual output.
580 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
582 (declare (optimize (speed 1)))
587 (intern (format nil name-fmt
(string (car buffering
))))))
589 (defun ,function
(stream byte
)
590 (output-wrapper (stream ,size
,buffering
,restart
)
592 (setf *output-routines
*
593 (nconc *output-routines
*
601 (cdr buffering
)))))))
604 ;;; FIXME: is this used anywhere any more?
605 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
611 (if (eql byte
#\Newline
)
612 (setf (fd-stream-char-pos stream
) 0)
613 (incf (fd-stream-char-pos stream
)))
614 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
617 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
620 (:none
(unsigned-byte 8))
621 (:full
(unsigned-byte 8)))
622 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
625 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
628 (:none
(signed-byte 8))
629 (:full
(signed-byte 8)))
630 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
633 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
636 (:none
(unsigned-byte 16))
637 (:full
(unsigned-byte 16)))
638 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
641 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
644 (:none
(signed-byte 16))
645 (:full
(signed-byte 16)))
646 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
649 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
652 (:none
(unsigned-byte 32))
653 (:full
(unsigned-byte 32)))
654 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
657 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
660 (:none
(signed-byte 32))
661 (:full
(signed-byte 32)))
662 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
665 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
667 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
670 (:none
(unsigned-byte 64))
671 (:full
(unsigned-byte 64)))
672 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
674 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
677 (:none
(signed-byte 64))
678 (:full
(signed-byte 64)))
679 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
682 ;;; the routine to use to output a string. If the stream is
683 ;;; unbuffered, slam the string down the file descriptor, otherwise
684 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
685 ;;; checking to see where the last newline was.
686 (defun fd-sout (stream thing start end
)
687 (declare (type fd-stream stream
) (type string thing
))
688 (let ((start (or start
0))
689 (end (or end
(length (the vector thing
)))))
690 (declare (fixnum start end
))
692 (string-dispatch (simple-base-string
694 (simple-array character
(*))
697 (position #\newline thing
:from-end t
698 :start start
:end end
))))
699 (if (and (typep thing
'base-string
)
700 (eq (fd-stream-external-format stream
) :latin-1
))
701 (ecase (fd-stream-buffering stream
)
703 (buffer-output stream thing start end
))
705 (buffer-output stream thing start end
)
707 (flush-output-buffer stream
)))
709 (write-or-buffer-output stream thing start end
)))
710 (ecase (fd-stream-buffering stream
)
711 (:full
(funcall (fd-stream-output-bytes stream
)
712 stream thing nil start end
))
713 (:line
(funcall (fd-stream-output-bytes stream
)
714 stream thing last-newline start end
))
715 (:none
(funcall (fd-stream-output-bytes stream
)
716 stream thing t start end
))))
718 (setf (fd-stream-char-pos stream
) (- end last-newline
1))
719 (incf (fd-stream-char-pos stream
) (- end start
))))))
721 (defvar *external-formats
* ()
723 "List of all available external formats. Each element is a list of the
724 element-type, string input function name, character input function name,
725 and string output function name.")
727 (defun get-external-format (external-format)
728 (dolist (entry *external-formats
*)
729 (when (member external-format
(first entry
))
732 (defun get-external-format-function (external-format index
)
733 (let ((entry (get-external-format external-format
)))
734 (when entry
(nth index entry
))))
736 ;;; Find an output routine to use given the type and buffering. Return
737 ;;; as multiple values the routine, the real type transfered, and the
738 ;;; number of bytes per element.
739 (defun pick-output-routine (type buffering
&optional external-format
)
740 (when (subtypep type
'character
)
741 (let ((entry (get-external-format external-format
)))
743 (return-from pick-output-routine
744 (values (symbol-function (nth (ecase buffering
751 (symbol-function (fourth entry
))
752 (first (first entry
)))))))
753 (dolist (entry *output-routines
*)
754 (when (and (subtypep type
(first entry
))
755 (eq buffering
(second entry
))
756 (or (not (fifth entry
))
757 (eq external-format
(fifth entry
))))
758 (return-from pick-output-routine
759 (values (symbol-function (third entry
))
762 ;; KLUDGE: dealing with the buffering here leads to excessive code
765 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
766 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
767 if
(subtypep type
`(unsigned-byte ,i
))
768 do
(return-from pick-output-routine
772 (lambda (stream byte
)
773 (output-wrapper (stream (/ i
8) (:none
) nil
)
774 (loop for j from
0 below
(/ i
8)
775 do
(setf (sap-ref-8 (buffer-sap obuf
)
777 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
779 (lambda (stream byte
)
780 (output-wrapper (stream (/ i
8) (:full
) nil
)
781 (loop for j from
0 below
(/ i
8)
782 do
(setf (sap-ref-8 (buffer-sap obuf
)
784 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
787 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
788 if
(subtypep type
`(signed-byte ,i
))
789 do
(return-from pick-output-routine
793 (lambda (stream byte
)
794 (output-wrapper (stream (/ i
8) (:none
) nil
)
795 (loop for j from
0 below
(/ i
8)
796 do
(setf (sap-ref-8 (buffer-sap obuf
)
798 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
800 (lambda (stream byte
)
801 (output-wrapper (stream (/ i
8) (:full
) nil
)
802 (loop for j from
0 below
(/ i
8)
803 do
(setf (sap-ref-8 (buffer-sap obuf
)
805 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
809 ;;;; input routines and related noise
811 ;;; a list of all available input routines. Each element is a list of
812 ;;; the element-type input, the function name, and the number of bytes
814 (defvar *input-routines
* ())
816 ;;; Return whether a primitive partial read operation on STREAM's FD
817 ;;; would (probably) block. Signal a `simple-stream-error' if the
818 ;;; system call implementing this operation fails.
820 ;;; It is "may" instead of "would" because "would" is not quite
821 ;;; correct on win32. However, none of the places that use it require
822 ;;; further assurance than "may" versus "will definitely not".
823 (defun sysread-may-block-p (stream)
825 ;; This answers T at EOF on win32, I think.
826 (not (sb!win32
:fd-listen
(fd-stream-fd stream
)))
828 (sb!unix
:with-restarted-syscall
(count errno
)
829 (sb!alien
:with-alien
((read-fds (sb!alien
:struct sb
!unix
:fd-set
)))
830 (sb!unix
:fd-zero read-fds
)
831 (sb!unix
:fd-set
(fd-stream-fd stream
) read-fds
)
832 (sb!unix
:unix-fast-select
(1+ (fd-stream-fd stream
))
833 (sb!alien
:addr read-fds
)
839 (simple-stream-perror "couldn't check whether ~S is readable"
843 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
844 ;;; then fill the input buffer, and return the number of bytes read. Throws
845 ;;; to EOF-INPUT-CATCHER if the eof was reached.
846 (defun refill-input-buffer (stream)
847 (dx-let ((fd (fd-stream-fd stream
))
851 ;; Check for blocking input before touching the stream, as if
852 ;; we happen to wait we are liable to be interrupted, and the
853 ;; interrupt handler may use the same stream.
854 (if (sysread-may-block-p stream
)
857 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
858 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
860 (closed-flame stream
)
862 (simple-stream-perror "couldn't read from ~S" stream errno
)
864 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
865 ;; to wait for input if read tells us EWOULDBLOCK.
866 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
))
867 (signal-timeout 'io-timeout
:stream stream
:direction
:read
868 :seconds
(fd-stream-timeout stream
)))
870 ;; Since the read should not block, we'll disable the
871 ;; interrupts here, so that we don't accidentally unwind and
872 ;; leave the stream in an inconsistent state.
874 ;; Execute the nlx outside without-interrupts to ensure the
875 ;; resulting thunk is stack-allocatable.
876 ((lambda (return-reason)
878 ((nil)) ; fast path normal cases
879 ((:wait-for-input
) (go :wait-for-input
))
880 ((:closed-flame
) (go :closed-flame
))
881 ((:read-error
) (go :read-error
))))
883 ;; Check the buffer: if it is null, then someone has closed
884 ;; the stream from underneath us. This is not ment to fix
885 ;; multithreaded races, but to deal with interrupt handlers
886 ;; closing the stream.
889 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
890 (sap (buffer-sap ibuf
))
891 (length (buffer-length ibuf
))
892 (head (buffer-head ibuf
))
893 (tail (buffer-tail ibuf
)))
894 (declare (index length head tail
)
895 (inline sb
!unix
:unix-read
))
897 (cond ((eql head tail
)
898 ;; Buffer is empty, but not at yet reset -- make it so.
903 ;; Buffer has things in it, but they are not at the
904 ;; head -- move them there.
905 (let ((n (- tail head
)))
906 (system-area-ub8-copy sap head sap
0 n
)
908 (buffer-head ibuf
) head
910 (buffer-tail ibuf
) tail
)))))
911 (setf (fd-stream-listen stream
) nil
)
912 (setf (values count errno
)
913 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
918 (if (eql errno sb
!unix
:ewouldblock
)
919 (return :wait-for-input
)
920 (return :read-error
)))
922 (setf (fd-stream-listen stream
) :eof
)
923 (/show0
"THROWing EOF-INPUT-CATCHER")
924 (throw 'eof-input-catcher nil
))
926 ;; Success! (Do not use INCF, for sake of other threads.)
927 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
930 ;;; Make sure there are at least BYTES number of bytes in the input
931 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
932 (defmacro input-at-least
(stream bytes
)
933 (let ((stream-var (gensym "STREAM"))
934 (bytes-var (gensym "BYTES"))
935 (buffer-var (gensym "IBUF")))
936 `(let* ((,stream-var
,stream
)
938 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
940 (when (>= (- (buffer-tail ,buffer-var
)
941 (buffer-head ,buffer-var
))
944 (refill-input-buffer ,stream-var
)))))
946 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
948 (let ((stream-var (gensym "STREAM"))
949 (retry-var (gensym "RETRY"))
950 (element-var (gensym "ELT")))
951 `(let* ((,stream-var
,stream
)
952 (ibuf (fd-stream-ibuf ,stream-var
))
954 (if (fd-stream-unread ,stream-var
)
956 (fd-stream-unread ,stream-var
)
957 (setf (fd-stream-unread ,stream-var
) nil
)
958 (setf (fd-stream-listen ,stream-var
) nil
))
959 (let ((,element-var nil
)
960 (decode-break-reason nil
))
964 (catch 'eof-input-catcher
965 (setf decode-break-reason
966 (block decode-break-reason
967 (input-at-least ,stream-var
1)
968 (let* ((byte (sap-ref-8 (buffer-sap ibuf
)
969 (buffer-head ibuf
))))
970 (declare (ignorable byte
))
972 (input-at-least ,stream-var size
)
973 (setq ,element-var
(locally ,@read-forms
))
974 (setq ,retry-var nil
))
976 (when decode-break-reason
977 (stream-decoding-error-and-handle stream
978 decode-break-reason
))
980 (let ((octet-count (- (buffer-tail ibuf
)
981 (buffer-head ibuf
))))
982 (when (or (zerop octet-count
)
983 (and (not ,element-var
)
984 (not decode-break-reason
)
985 (stream-decoding-error-and-handle
986 stream octet-count
)))
987 (setq ,retry-var nil
)))))
989 (incf (buffer-head ibuf
) size
)
992 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
994 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
995 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
996 (let ((stream-var (gensym "STREAM"))
997 (element-var (gensym "ELT")))
998 `(let* ((,stream-var
,stream
)
999 (ibuf (fd-stream-ibuf ,stream-var
)))
1000 (if (fd-stream-unread ,stream-var
)
1002 (fd-stream-unread ,stream-var
)
1003 (setf (fd-stream-unread ,stream-var
) nil
)
1004 (setf (fd-stream-listen ,stream-var
) nil
))
1006 (catch 'eof-input-catcher
1007 (input-at-least ,stream-var
,bytes
)
1008 (locally ,@read-forms
))))
1010 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1013 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1015 (defmacro def-input-routine
/variable-width
(name
1016 (type external-format size sap head
)
1019 (defun ,name
(stream eof-error eof-value
)
1020 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1021 (let ((,sap
(buffer-sap ibuf
))
1022 (,head
(buffer-head ibuf
)))
1024 (setf *input-routines
*
1025 (nconc *input-routines
*
1026 (list (list ',type
',name
1 ',external-format
))))))
1028 (defmacro def-input-routine
(name
1029 (type size sap head
)
1032 (defun ,name
(stream eof-error eof-value
)
1033 (input-wrapper (stream ,size eof-error eof-value
)
1034 (let ((,sap
(buffer-sap ibuf
))
1035 (,head
(buffer-head ibuf
)))
1037 (setf *input-routines
*
1038 (nconc *input-routines
*
1039 (list (list ',type
',name
',size nil
))))))
1041 ;;; STREAM-IN routine for reading a string char
1042 (def-input-routine input-character
1043 (character 1 sap head
)
1044 (code-char (sap-ref-8 sap head
)))
1046 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1047 (def-input-routine input-unsigned-8bit-byte
1048 ((unsigned-byte 8) 1 sap head
)
1049 (sap-ref-8 sap head
))
1051 ;;; STREAM-IN routine for reading a signed 8 bit number
1052 (def-input-routine input-signed-8bit-number
1053 ((signed-byte 8) 1 sap head
)
1054 (signed-sap-ref-8 sap head
))
1056 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1057 (def-input-routine input-unsigned-16bit-byte
1058 ((unsigned-byte 16) 2 sap head
)
1059 (sap-ref-16 sap head
))
1061 ;;; STREAM-IN routine for reading a signed 16 bit number
1062 (def-input-routine input-signed-16bit-byte
1063 ((signed-byte 16) 2 sap head
)
1064 (signed-sap-ref-16 sap head
))
1066 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1067 (def-input-routine input-unsigned-32bit-byte
1068 ((unsigned-byte 32) 4 sap head
)
1069 (sap-ref-32 sap head
))
1071 ;;; STREAM-IN routine for reading a signed 32 bit number
1072 (def-input-routine input-signed-32bit-byte
1073 ((signed-byte 32) 4 sap head
)
1074 (signed-sap-ref-32 sap head
))
1076 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
1078 (def-input-routine input-unsigned-64bit-byte
1079 ((unsigned-byte 64) 8 sap head
)
1080 (sap-ref-64 sap head
))
1081 (def-input-routine input-signed-64bit-byte
1082 ((signed-byte 64) 8 sap head
)
1083 (signed-sap-ref-64 sap head
)))
1085 ;;; Find an input routine to use given the type. Return as multiple
1086 ;;; values the routine, the real type transfered, and the number of
1087 ;;; bytes per element (and for character types string input routine).
1088 (defun pick-input-routine (type &optional external-format
)
1089 (when (subtypep type
'character
)
1090 (dolist (entry *external-formats
*)
1091 (when (member external-format
(first entry
))
1092 (return-from pick-input-routine
1093 (values (symbol-function (third entry
))
1096 (symbol-function (second entry
))
1097 (first (first entry
)))))))
1098 (dolist (entry *input-routines
*)
1099 (when (and (subtypep type
(first entry
))
1100 (or (not (fourth entry
))
1101 (eq external-format
(fourth entry
))))
1102 (return-from pick-input-routine
1103 (values (symbol-function (second entry
))
1106 ;; FIXME: let's do it the hard way, then (but ignore things like
1107 ;; endianness, efficiency, and the necessary coupling between these
1108 ;; and the output routines). -- CSR, 2004-02-09
1109 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1110 if
(subtypep type
`(unsigned-byte ,i
))
1111 do
(return-from pick-input-routine
1113 (lambda (stream eof-error eof-value
)
1114 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1115 (let ((sap (buffer-sap ibuf
))
1116 (head (buffer-head ibuf
)))
1117 (loop for j from
0 below
(/ i
8)
1121 (sap-ref-8 sap
(+ head j
))))
1122 finally
(return result
)))))
1125 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1126 if
(subtypep type
`(signed-byte ,i
))
1127 do
(return-from pick-input-routine
1129 (lambda (stream eof-error eof-value
)
1130 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1131 (let ((sap (buffer-sap ibuf
))
1132 (head (buffer-head ibuf
)))
1133 (loop for j from
0 below
(/ i
8)
1137 (sap-ref-8 sap
(+ head j
))))
1138 finally
(return (if (logbitp (1- i
) result
)
1139 (dpb result
(byte i
0) -
1)
1144 ;;; the N-BIN method for FD-STREAMs
1146 ;;; Note that this blocks in UNIX-READ. It is generally used where
1147 ;;; there is a definite amount of reading to be done, so blocking
1148 ;;; isn't too problematical.
1149 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1150 &aux
(total-copied 0))
1151 (declare (type fd-stream stream
))
1152 (declare (type index start requested total-copied
))
1153 (let ((unread (fd-stream-unread stream
)))
1155 ;; AVERs designed to fail when we have more complicated
1156 ;; character representations.
1157 (aver (typep unread
'base-char
))
1158 (aver (= (fd-stream-element-size stream
) 1))
1159 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1162 (system-area-pointer
1163 (setf (sap-ref-8 buffer start
) (char-code unread
)))
1164 ((simple-unboxed-array (*))
1165 (setf (aref buffer start
) unread
)))
1166 (setf (fd-stream-unread stream
) nil
)
1167 (setf (fd-stream-listen stream
) nil
)
1168 (incf total-copied
)))
1171 (let* ((remaining-request (- requested total-copied
))
1172 (ibuf (fd-stream-ibuf stream
))
1173 (head (buffer-head ibuf
))
1174 (tail (buffer-tail ibuf
))
1175 (available (- tail head
))
1176 (n-this-copy (min remaining-request available
))
1177 (this-start (+ start total-copied
))
1178 (this-end (+ this-start n-this-copy
))
1179 (sap (buffer-sap ibuf
)))
1180 (declare (type index remaining-request head tail available
))
1181 (declare (type index n-this-copy
))
1182 ;; Copy data from stream buffer into user's buffer.
1183 (%byte-blt sap head buffer this-start this-end
)
1184 (incf (buffer-head ibuf
) n-this-copy
)
1185 (incf total-copied n-this-copy
)
1186 ;; Maybe we need to refill the stream buffer.
1187 (cond (;; If there were enough data in the stream buffer, we're done.
1188 (eql total-copied requested
)
1189 (return total-copied
))
1190 (;; If EOF, we're done in another way.
1191 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1193 (error 'end-of-file
:stream stream
)
1194 (return total-copied
)))
1195 ;; Otherwise we refilled the stream buffer, so fall
1196 ;; through into another pass of the loop.
1199 (defun fd-stream-resync (stream)
1200 (dolist (entry *external-formats
*)
1201 (when (member (fd-stream-external-format stream
) (first entry
))
1202 (return-from fd-stream-resync
1203 (funcall (symbol-function (eighth entry
)) stream
)))))
1205 (defun get-fd-stream-character-sizer (stream)
1206 (dolist (entry *external-formats
*)
1207 (when (member (fd-stream-external-format stream
) (first entry
))
1208 (return-from get-fd-stream-character-sizer
(ninth entry
)))))
1210 (defun fd-stream-character-size (stream char
)
1211 (let ((sizer (get-fd-stream-character-sizer stream
)))
1212 (when sizer
(funcall sizer char
))))
1214 (defun fd-stream-string-size (stream string
)
1215 (let ((sizer (get-fd-stream-character-sizer stream
)))
1217 (loop for char across string summing
(funcall sizer char
)))))
1219 (defun find-external-format (external-format)
1220 (when external-format
1221 (find external-format
*external-formats
* :test
#'member
:key
#'car
)))
1223 (defun variable-width-external-format-p (ef-entry)
1224 (when (eighth ef-entry
) t
))
1226 (defun bytes-for-char-fun (ef-entry)
1227 (if ef-entry
(symbol-function (ninth ef-entry
)) (constantly 1)))
1229 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1230 (defmacro define-external-format
(external-format size output-restart
1232 (let* ((name (first external-format
))
1233 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1234 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1235 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1236 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1237 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1238 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1239 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1240 (n-buffer (gensym "BUFFER")))
1242 (defun ,size-function
(byte)
1243 (declare (ignore byte
))
1245 (defun ,out-function
(stream string flush-p start end
)
1246 (let ((start (or start
0))
1247 (end (or end
(length string
))))
1248 (declare (type index start end
))
1249 (synchronize-stream-output stream
)
1250 (unless (<= 0 start end
(length string
))
1251 (sequence-bounding-indices-bad-error string start end
))
1254 (let ((obuf (fd-stream-obuf stream
)))
1255 (setf (buffer-tail obuf
)
1256 (string-dispatch (simple-base-string
1258 (simple-array character
(*))
1261 (let ((sap (buffer-sap obuf
))
1262 (len (buffer-length obuf
))
1264 (tail (buffer-tail obuf
)))
1265 (declare (type index tail
)
1266 ;; STRING bounds have already been checked.
1267 (optimize (safety 0)))
1269 (,@(if output-restart
1270 `(catch 'output-nothing
)
1273 ((or (= start end
) (< (- len tail
) 4)))
1274 (let* ((byte (aref string start
))
1275 (bits (char-code byte
)))
1279 ;; Exited from the loop normally
1281 ;; Exited via CATCH. Skip the current character
1282 ;; and try the inner loop again.
1285 (flush-output-buffer stream
)))
1287 (flush-output-buffer stream
))))
1288 (def-output-routines (,format
1294 (if (eql byte
#\Newline
)
1295 (setf (fd-stream-char-pos stream
) 0)
1296 (incf (fd-stream-char-pos stream
)))
1297 (let* ((obuf (fd-stream-obuf stream
))
1298 (bits (char-code byte
))
1299 (sap (buffer-sap obuf
))
1300 (tail (buffer-tail obuf
)))
1302 (defun ,in-function
(stream buffer start requested eof-error-p
1303 &aux
(index start
) (end (+ start requested
)))
1304 (declare (type fd-stream stream
)
1305 (type index start requested index end
)
1307 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1309 (let ((unread (fd-stream-unread stream
)))
1311 (setf (aref buffer index
) unread
)
1312 (setf (fd-stream-unread stream
) nil
)
1313 (setf (fd-stream-listen stream
) nil
)
1317 (let* ((ibuf (fd-stream-ibuf stream
))
1318 (head (buffer-head ibuf
))
1319 (tail (buffer-tail ibuf
))
1320 (sap (buffer-sap ibuf
)))
1321 (declare (type index head tail
)
1322 (type system-area-pointer sap
))
1323 ;; Copy data from stream buffer into user's buffer.
1324 (dotimes (i (min (truncate (- tail head
) ,size
)
1326 (declare (optimize speed
))
1327 (let* ((byte (sap-ref-8 sap head
)))
1328 (setf (aref buffer index
) ,in-expr
)
1331 (setf (buffer-head ibuf
) head
)
1332 ;; Maybe we need to refill the stream buffer.
1333 (cond ( ;; If there was enough data in the stream buffer, we're done.
1335 (return (- index start
)))
1336 ( ;; If EOF, we're done in another way.
1337 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1339 (error 'end-of-file
:stream stream
)
1340 (return (- index start
))))
1341 ;; Otherwise we refilled the stream buffer, so fall
1342 ;; through into another pass of the loop.
1344 (def-input-routine ,in-char-function
(character ,size sap head
)
1345 (let ((byte (sap-ref-8 sap head
)))
1347 (defun ,read-c-string-function
(sap element-type
)
1348 (declare (type system-area-pointer sap
)
1349 (type (member character base-char
) element-type
))
1351 (declare (optimize (speed 3) (safety 0)))
1352 (let* ((stream ,name
)
1354 (loop for head of-type index upfrom
0 by
,size
1355 for count of-type index upto
(1- array-dimension-limit
)
1356 for byte
= (sap-ref-8 sap head
)
1357 for char of-type character
= ,in-expr
1358 until
(zerop (char-code char
))
1359 finally
(return count
)))
1360 ;; Inline the common cases
1361 (string (make-string length
:element-type element-type
)))
1362 (declare (ignorable stream
)
1364 (type simple-string string
))
1365 (/show0 before-copy-loop
)
1366 (loop for head of-type index upfrom
0 by
,size
1367 for index of-type index below length
1368 for byte
= (sap-ref-8 sap head
)
1369 for char of-type character
= ,in-expr
1370 do
(setf (aref string index
) char
))
1371 string
))) ;; last loop rewrite to dotimes?
1372 (defun ,output-c-string-function
(string)
1373 (declare (type simple-string string
))
1375 (declare (optimize (speed 3) (safety 0)))
1376 (let* ((length (length string
))
1377 (,n-buffer
(make-array (* (1+ length
) ,size
)
1378 :element-type
'(unsigned-byte 8)))
1381 (declare (type index length tail
))
1382 (with-pinned-objects (,n-buffer
)
1383 (let ((sap (vector-sap ,n-buffer
)))
1384 (declare (system-area-pointer sap
))
1386 (let* ((byte (aref string i
))
1387 (bits (char-code byte
)))
1388 (declare (ignorable byte bits
))
1392 (byte (code-char bits
)))
1393 (declare (ignorable bits byte
))
1396 (setf *external-formats
*
1397 (cons '(,external-format
,in-function
,in-char-function
,out-function
1398 ,@(mapcar #'(lambda (buffering)
1399 (intern (format nil format
(string buffering
))))
1400 '(:none
:line
:full
))
1401 nil
; no resync-function
1402 ,size-function
,read-c-string-function
,output-c-string-function
)
1403 *external-formats
*)))))
1405 (defmacro define-external-format
/variable-width
1406 (external-format output-restart out-size-expr
1407 out-expr in-size-expr in-expr
)
1408 (let* ((name (first external-format
))
1409 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1410 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1411 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1412 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1413 (resync-function (symbolicate "RESYNC/" name
))
1414 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1415 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1416 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1417 (n-buffer (gensym "BUFFER")))
1419 (defun ,size-function
(byte)
1420 (declare (ignorable byte
))
1422 (defun ,out-function
(stream string flush-p start end
)
1423 (let ((start (or start
0))
1424 (end (or end
(length string
))))
1425 (declare (type index start end
))
1426 (synchronize-stream-output stream
)
1427 (unless (<= 0 start end
(length string
))
1428 (sequence-bounding-indices-bad string start end
))
1431 (let ((obuf (fd-stream-obuf stream
)))
1432 (setf (buffer-tail obuf
)
1433 (string-dispatch (simple-base-string
1435 (simple-array character
(*))
1438 (let ((len (buffer-length obuf
))
1439 (sap (buffer-sap obuf
))
1441 (tail (buffer-tail obuf
)))
1442 (declare (type index tail
)
1443 ;; STRING bounds have already been checked.
1444 (optimize (safety 0)))
1446 (,@(if output-restart
1447 `(catch 'output-nothing
)
1450 ((or (= start end
) (< (- len tail
) 4)))
1451 (let* ((byte (aref string start
))
1452 (bits (char-code byte
))
1453 (size ,out-size-expr
))
1457 ;; Exited from the loop normally
1459 ;; Exited via CATCH. Skip the current character
1460 ;; and try the inner loop again.
1463 (flush-output-buffer stream
)))
1465 (flush-output-buffer stream
))))
1466 (def-output-routines/variable-width
(,format
1473 (if (eql byte
#\Newline
)
1474 (setf (fd-stream-char-pos stream
) 0)
1475 (incf (fd-stream-char-pos stream
)))
1476 (let ((bits (char-code byte
))
1477 (sap (buffer-sap obuf
))
1478 (tail (buffer-tail obuf
)))
1480 (defun ,in-function
(stream buffer start requested eof-error-p
1481 &aux
(total-copied 0))
1482 (declare (type fd-stream stream
)
1483 (type index start requested total-copied
)
1485 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1487 (let ((unread (fd-stream-unread stream
)))
1489 (setf (aref buffer start
) unread
)
1490 (setf (fd-stream-unread stream
) nil
)
1491 (setf (fd-stream-listen stream
) nil
)
1492 (incf total-copied
)))
1495 (let* ((ibuf (fd-stream-ibuf stream
))
1496 (head (buffer-head ibuf
))
1497 (tail (buffer-tail ibuf
))
1498 (sap (buffer-sap ibuf
))
1499 (decode-break-reason nil
))
1500 (declare (type index head tail
))
1501 ;; Copy data from stream buffer into user's buffer.
1502 (do ((size nil nil
))
1503 ((or (= tail head
) (= requested total-copied
)))
1504 (setf decode-break-reason
1505 (block decode-break-reason
1506 (let ((byte (sap-ref-8 sap head
)))
1507 (declare (ignorable byte
))
1508 (setq size
,in-size-expr
)
1509 (when (> size
(- tail head
))
1511 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1515 (setf (buffer-head ibuf
) head
)
1516 (when decode-break-reason
1517 ;; If we've already read some characters on when the invalid
1518 ;; code sequence is detected, we return immediately. The
1519 ;; handling of the error is deferred until the next call
1520 ;; (where this check will be false). This allows establishing
1521 ;; high-level handlers for decode errors (for example
1522 ;; automatically resyncing in Lisp comments).
1523 (when (plusp total-copied
)
1524 (return-from ,in-function total-copied
))
1525 (when (stream-decoding-error-and-handle
1526 stream decode-break-reason
)
1528 (error 'end-of-file
:stream stream
)
1529 (return-from ,in-function total-copied
)))
1530 (setf head
(buffer-head ibuf
))
1531 (setf tail
(buffer-tail ibuf
))))
1532 (setf (buffer-head ibuf
) head
)
1533 ;; Maybe we need to refill the stream buffer.
1534 (cond ( ;; If there were enough data in the stream buffer, we're done.
1535 (= total-copied requested
)
1536 (return total-copied
))
1537 ( ;; If EOF, we're done in another way.
1538 (or (eq decode-break-reason
'eof
)
1539 (null (catch 'eof-input-catcher
1540 (refill-input-buffer stream
))))
1542 (error 'end-of-file
:stream stream
)
1543 (return total-copied
)))
1544 ;; Otherwise we refilled the stream buffer, so fall
1545 ;; through into another pass of the loop.
1547 (def-input-routine/variable-width
,in-char-function
(character
1551 (let ((byte (sap-ref-8 sap head
)))
1552 (declare (ignorable byte
))
1554 (defun ,resync-function
(stream)
1555 (let ((ibuf (fd-stream-ibuf stream
)))
1557 (input-at-least stream
2)
1558 (incf (buffer-head ibuf
))
1559 (unless (block decode-break-reason
1560 (let* ((sap (buffer-sap ibuf
))
1561 (head (buffer-head ibuf
))
1562 (byte (sap-ref-8 sap head
))
1563 (size ,in-size-expr
))
1564 (declare (ignorable byte
))
1565 (input-at-least stream size
)
1566 (setf head
(buffer-head ibuf
))
1570 (defun ,read-c-string-function
(sap element-type
)
1571 (declare (type system-area-pointer sap
))
1573 (declare (optimize (speed 3) (safety 0)))
1574 (let* ((stream ,name
)
1575 (size 0) (head 0) (byte 0) (char nil
)
1576 (decode-break-reason nil
)
1577 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1578 (setf decode-break-reason
1579 (block decode-break-reason
1580 (setf byte
(sap-ref-8 sap head
)
1585 (when decode-break-reason
1586 (c-string-decoding-error ,name decode-break-reason
))
1587 (when (zerop (char-code char
))
1589 (string (make-string length
:element-type element-type
)))
1590 (declare (ignorable stream
)
1591 (type index head length
) ;; size
1592 (type (unsigned-byte 8) byte
)
1593 (type (or null character
) char
)
1594 (type string string
))
1596 (dotimes (index length string
)
1597 (setf decode-break-reason
1598 (block decode-break-reason
1599 (setf byte
(sap-ref-8 sap head
)
1604 (when decode-break-reason
1605 (c-string-decoding-error ,name decode-break-reason
))
1606 (setf (aref string index
) char
)))))
1608 (defun ,output-c-string-function
(string)
1609 (declare (type simple-string string
))
1611 (declare (optimize (speed 3) (safety 0)))
1612 (let* ((length (length string
))
1613 (char-length (make-array (1+ length
) :element-type
'index
))
1615 (+ (loop for i of-type index below length
1616 for byte of-type character
= (aref string i
)
1617 for bits
= (char-code byte
)
1618 sum
(setf (aref char-length i
)
1619 (the index
,out-size-expr
)))
1620 (let* ((byte (code-char 0))
1621 (bits (char-code byte
)))
1622 (declare (ignorable byte bits
))
1623 (setf (aref char-length length
)
1624 (the index
,out-size-expr
)))))
1626 (,n-buffer
(make-array buffer-length
1627 :element-type
'(unsigned-byte 8)))
1629 (declare (type index length buffer-length tail
)
1632 (with-pinned-objects (,n-buffer
)
1633 (let ((sap (vector-sap ,n-buffer
)))
1634 (declare (system-area-pointer sap
))
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 for size of-type index
= (aref char-length i
)
1643 (byte (code-char bits
))
1644 (size (aref char-length length
)))
1645 (declare (ignorable bits byte size
))
1649 (setf *external-formats
*
1650 (cons '(,external-format
,in-function
,in-char-function
,out-function
1651 ,@(mapcar #'(lambda (buffering)
1652 (intern (format nil format
(string buffering
))))
1653 '(:none
:line
:full
))
1655 ,size-function
,read-c-string-function
,output-c-string-function
)
1656 *external-formats
*)))))
1658 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1659 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1660 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1661 (define-external-format (:latin-1
:latin1
:iso-8859-1
:iso8859-1
)
1664 (external-format-encoding-error stream bits
)
1665 (setf (sap-ref-8 sap tail
) bits
))
1668 (define-external-format (:ascii
:us-ascii
:ansi_x3.4-
1968
1669 :iso-646
:iso-646-us
:|
646|
)
1672 (external-format-encoding-error stream bits
)
1673 (setf (sap-ref-8 sap tail
) bits
))
1676 (let* ((table (let ((s (make-string 256)))
1677 (map-into s
#'code-char
1678 '(#x00
#x01
#x02
#x03
#x9c
#x09
#x86
#x7f
#x97
#x8d
#x8e
#x0b
#x0c
#x0d
#x0e
#x0f
1679 #x10
#x11
#x12
#x13
#x9d
#x85
#x08
#x87
#x18
#x19
#x92
#x8f
#x1c
#x1d
#x1e
#x1f
1680 #x80
#x81
#x82
#x83
#x84
#x0a
#x17
#x1b
#x88
#x89
#x8a
#x8b
#x8c
#x05
#x06
#x07
1681 #x90
#x91
#x16
#x93
#x94
#x95
#x96
#x04
#x98
#x99
#x9a
#x9b
#x14
#x15
#x9e
#x1a
1682 #x20
#xa0
#xe2
#xe4
#xe0
#xe1
#xe3
#xe5
#xe7
#xf1
#xa2
#x2e
#x3c
#x28
#x2b
#x7c
1683 #x26
#xe9
#xea
#xeb
#xe8
#xed
#xee
#xef
#xec
#xdf
#x21
#x24
#x2a
#x29
#x3b
#xac
1684 #x2d
#x2f
#xc2
#xc4
#xc0
#xc1
#xc3
#xc5
#xc7
#xd1
#xa6
#x2c
#x25
#x5f
#x3e
#x3f
1685 #xf8
#xc9
#xca
#xcb
#xc8
#xcd
#xce
#xcf
#xcc
#x60
#x3a
#x23
#x40
#x27
#x3d
#x22
1686 #xd8
#x61
#x62
#x63
#x64
#x65
#x66
#x67
#x68
#x69
#xab
#xbb
#xf0
#xfd
#xfe
#xb1
1687 #xb0
#x6a
#x6b
#x6c
#x6d
#x6e
#x6f
#x70
#x71
#x72
#xaa
#xba
#xe6
#xb8
#xc6
#xa4
1688 #xb5
#x7e
#x73
#x74
#x75
#x76
#x77
#x78
#x79
#x7a
#xa1
#xbf
#xd0
#xdd
#xde
#xae
1689 #x5e
#xa3
#xa5
#xb7
#xa9
#xa7
#xb6
#xbc
#xbd
#xbe
#x5b
#x5d
#xaf
#xa8
#xb4
#xd7
1690 #x7b
#x41
#x42
#x43
#x44
#x45
#x46
#x47
#x48
#x49
#xad
#xf4
#xf6
#xf2
#xf3
#xf5
1691 #x7d
#x4a
#x4b
#x4c
#x4d
#x4e
#x4f
#x50
#x51
#x52
#xb9
#xfb
#xfc
#xf9
#xfa
#xff
1692 #x5c
#xf7
#x53
#x54
#x55
#x56
#x57
#x58
#x59
#x5a
#xb2
#xd4
#xd6
#xd2
#xd3
#xd5
1693 #x30
#x31
#x32
#x33
#x34
#x35
#x36
#x37
#x38
#x39
#xb3
#xdb
#xdc
#xd9
#xda
#x9f
))
1695 (reverse-table (let ((rt (make-array 256 :element-type
'(unsigned-byte 8) :initial-element
0)))
1696 (loop for char across table for i from
0
1697 do
(aver (= 0 (aref rt
(char-code char
))))
1698 do
(setf (aref rt
(char-code char
)) i
))
1700 (define-external-format (:ebcdic-us
:ibm-037
:ibm037
)
1703 (external-format-encoding-error stream bits
)
1704 (setf (sap-ref-8 sap tail
) (aref reverse-table bits
)))
1709 (let ((latin-9-table (let ((table (make-string 256)))
1712 (setf (aref table i
) (code-char i
)))
1713 (setf (aref table
#xa4
) (code-char #x20ac
))
1714 (setf (aref table
#xa6
) (code-char #x0160
))
1715 (setf (aref table
#xa8
) (code-char #x0161
))
1716 (setf (aref table
#xb4
) (code-char #x017d
))
1717 (setf (aref table
#xb8
) (code-char #x017e
))
1718 (setf (aref table
#xbc
) (code-char #x0152
))
1719 (setf (aref table
#xbd
) (code-char #x0153
))
1720 (setf (aref table
#xbe
) (code-char #x0178
))
1722 (latin-9-reverse-1 (make-array 16
1723 :element-type
'(unsigned-byte 21)
1724 :initial-contents
'(#x0160
#x0161
#x0152
#x0153
0 0 0 0 #x0178
0 0 0 #x20ac
#x017d
#x017e
0)))
1725 (latin-9-reverse-2 (make-array 16
1726 :element-type
'(unsigned-byte 8)
1727 :initial-contents
'(#xa6
#xa8
#xbc
#xbd
0 0 0 0 #xbe
0 0 0 #xa4
#xb4
#xb8
0))))
1728 (define-external-format (:latin-9
:latin9
:iso-8859-15
:iso8859-15
)
1730 (setf (sap-ref-8 sap tail
)
1732 (if (= bits
(char-code (aref latin-9-table bits
)))
1734 (external-format-encoding-error stream byte
))
1735 (if (= (aref latin-9-reverse-1
(logand bits
15)) bits
)
1736 (aref latin-9-reverse-2
(logand bits
15))
1737 (external-format-encoding-error stream byte
))))
1738 (aref latin-9-table byte
)))
1740 (define-external-format/variable-width
(:utf-8
:utf8
) nil
1741 (let ((bits (char-code byte
)))
1742 (cond ((< bits
#x80
) 1)
1744 ((< bits
#x10000
) 3)
1747 (1 (setf (sap-ref-8 sap tail
) bits
))
1748 (2 (setf (sap-ref-8 sap tail
) (logior #xc0
(ldb (byte 5 6) bits
))
1749 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 0) bits
))))
1750 (3 (setf (sap-ref-8 sap tail
) (logior #xe0
(ldb (byte 4 12) bits
))
1751 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 6) bits
))
1752 (sap-ref-8 sap
(+ 2 tail
)) (logior #x80
(ldb (byte 6 0) bits
))))
1753 (4 (setf (sap-ref-8 sap tail
) (logior #xf0
(ldb (byte 3 18) bits
))
1754 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 12) bits
))
1755 (sap-ref-8 sap
(+ 2 tail
)) (logior #x80
(ldb (byte 6 6) bits
))
1756 (sap-ref-8 sap
(+ 3 tail
)) (logior #x80
(ldb (byte 6 0) bits
)))))
1757 (cond ((< byte
#x80
) 1)
1758 ((< byte
#xc2
) (return-from decode-break-reason
1))
1762 (code-char (ecase size
1764 (2 (let ((byte2 (sap-ref-8 sap
(1+ head
))))
1765 (unless (<= #x80 byte2
#xbf
)
1766 (return-from decode-break-reason
2))
1767 (dpb byte
(byte 5 6) byte2
)))
1768 (3 (let ((byte2 (sap-ref-8 sap
(1+ head
)))
1769 (byte3 (sap-ref-8 sap
(+ 2 head
))))
1770 (unless (and (<= #x80 byte2
#xbf
)
1771 (<= #x80 byte3
#xbf
))
1772 (return-from decode-break-reason
3))
1773 (dpb byte
(byte 4 12) (dpb byte2
(byte 6 6) byte3
))))
1774 (4 (let ((byte2 (sap-ref-8 sap
(1+ head
)))
1775 (byte3 (sap-ref-8 sap
(+ 2 head
)))
1776 (byte4 (sap-ref-8 sap
(+ 3 head
))))
1777 (unless (and (<= #x80 byte2
#xbf
)
1778 (<= #x80 byte3
#xbf
)
1779 (<= #x80 byte4
#xbf
))
1780 (return-from decode-break-reason
4))
1781 (dpb byte
(byte 3 18)
1782 (dpb byte2
(byte 6 12)
1783 (dpb byte3
(byte 6 6) byte4
))))))))
1785 ;;;; utility functions (misc routines, etc)
1787 ;;; Fill in the various routine slots for the given type. INPUT-P and
1788 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1789 ;;; set prior to calling this routine.
1790 (defun set-fd-stream-routines (fd-stream element-type external-format
1791 input-p output-p buffer-p
)
1792 (let* ((target-type (case element-type
1793 (unsigned-byte '(unsigned-byte 8))
1794 (signed-byte '(signed-byte 8))
1795 (:default
'character
)
1797 (character-stream-p (subtypep target-type
'character
))
1798 (bivalent-stream-p (eq element-type
:default
))
1799 normalized-external-format
1800 (bin-routine #'ill-bin
)
1803 (cin-routine #'ill-in
)
1806 (input-type nil
) ;calculated from bin-type/cin-type
1807 (input-size nil
) ;calculated from bin-size/cin-size
1808 (read-n-characters #'ill-in
)
1809 (bout-routine #'ill-bout
)
1812 (cout-routine #'ill-out
)
1817 (output-bytes #'ill-bout
))
1819 ;; Ensure that we have buffers in the desired direction(s) only,
1820 ;; getting new ones and dropping/resetting old ones as necessary.
1821 (let ((obuf (fd-stream-obuf fd-stream
)))
1825 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1827 (setf (fd-stream-obuf fd-stream
) nil
)
1828 (release-buffer obuf
))))
1830 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1834 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1836 (setf (fd-stream-ibuf fd-stream
) nil
)
1837 (release-buffer ibuf
))))
1839 ;; FIXME: Why only for output? Why unconditionally?
1841 (setf (fd-stream-char-pos fd-stream
) 0))
1843 (when (and character-stream-p
1844 (eq external-format
:default
))
1845 (/show0
"/getting default external format")
1846 (setf external-format
(default-external-format)))
1849 (when (or (not character-stream-p
) bivalent-stream-p
)
1850 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1851 normalized-external-format
)
1852 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1856 (error "could not find any input routine for ~S" target-type
)))
1857 (when character-stream-p
1858 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1859 normalized-external-format
)
1860 (pick-input-routine target-type external-format
))
1862 (error "could not find any input routine for ~S" target-type
)))
1863 (setf (fd-stream-in fd-stream
) cin-routine
1864 (fd-stream-bin fd-stream
) bin-routine
)
1865 ;; character type gets preferential treatment
1866 (setf input-size
(or cin-size bin-size
))
1867 (setf input-type
(or cin-type bin-type
))
1868 (when normalized-external-format
1869 (setf (fd-stream-external-format fd-stream
)
1870 normalized-external-format
))
1871 (when (= (or cin-size
1) (or bin-size
1) 1)
1872 (setf (fd-stream-n-bin fd-stream
) ;XXX
1873 (if (and character-stream-p
(not bivalent-stream-p
))
1875 #'fd-stream-read-n-bytes
))
1876 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1877 ;; for character and (unsigned-byte 8) streams. In these
1878 ;; cases, fast-read-* will read from the
1879 ;; ansi-stream-(c)in-buffer, saving function calls.
1880 ;; Otherwise, the various data-reading functions in the stream
1881 ;; structure will be called.
1883 (not bivalent-stream-p
)
1884 ;; temporary disable on :io streams
1886 (cond (character-stream-p
1887 (setf (ansi-stream-cin-buffer fd-stream
)
1888 (make-array +ansi-stream-in-buffer-length
+
1889 :element-type
'character
)))
1890 ((equal target-type
'(unsigned-byte 8))
1891 (setf (ansi-stream-in-buffer fd-stream
)
1892 (make-array +ansi-stream-in-buffer-length
+
1893 :element-type
'(unsigned-byte 8))))))))
1896 (when (or (not character-stream-p
) bivalent-stream-p
)
1897 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1898 normalized-external-format
)
1899 (pick-output-routine (if bivalent-stream-p
1902 (fd-stream-buffering fd-stream
)
1904 (unless bout-routine
1905 (error "could not find any output routine for ~S buffered ~S"
1906 (fd-stream-buffering fd-stream
)
1908 (when character-stream-p
1909 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1910 normalized-external-format
)
1911 (pick-output-routine target-type
1912 (fd-stream-buffering fd-stream
)
1914 (unless cout-routine
1915 (error "could not find any output routine for ~S buffered ~S"
1916 (fd-stream-buffering fd-stream
)
1918 (when normalized-external-format
1919 (setf (fd-stream-external-format fd-stream
)
1920 normalized-external-format
))
1921 (when character-stream-p
1922 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1923 (setf (fd-stream-out fd-stream
) cout-routine
1924 (fd-stream-bout fd-stream
) bout-routine
1925 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1926 #'fd-sout
#'ill-out
))
1927 (setf output-size
(or cout-size bout-size
))
1928 (setf output-type
(or cout-type bout-type
)))
1930 (when (and input-size output-size
1931 (not (eq input-size output-size
)))
1932 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1933 input-type input-size
1934 output-type output-size
))
1935 (setf (fd-stream-element-size fd-stream
)
1936 (or input-size output-size
))
1938 (setf (fd-stream-element-type fd-stream
)
1939 (cond ((equal input-type output-type
)
1945 ((subtypep input-type output-type
)
1947 ((subtypep output-type input-type
)
1950 (error "Input type (~S) and output type (~S) are unrelated?"
1954 ;;; Handles the resource-release aspects of stream closing, and marks
1956 (defun release-fd-stream-resources (fd-stream)
1959 ;; Drop handlers first.
1960 (when (fd-stream-handler fd-stream
)
1961 (remove-fd-handler (fd-stream-handler fd-stream
))
1962 (setf (fd-stream-handler fd-stream
) nil
))
1963 ;; Disable interrupts so that a asynch unwind will not leave
1964 ;; us with a dangling finalizer (that would close the same
1965 ;; --possibly reassigned-- FD again), or a stream with a closed
1966 ;; FD that appears open.
1967 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1968 (set-closed-flame fd-stream
)
1969 (when (fboundp 'cancel-finalization
)
1970 (cancel-finalization fd-stream
)))
1971 ;; On error unwind from WITHOUT-INTERRUPTS.
1972 (serious-condition (e)
1974 ;; Release all buffers. If this is undone, or interrupted,
1975 ;; we're still safe: buffers have finalizers of their own.
1976 (release-fd-stream-buffers fd-stream
))
1978 ;;; Flushes the current input buffer and unread chatacter, and returns
1979 ;;; the input buffer, and the amount of of flushed input in bytes.
1980 (defun flush-input-buffer (stream)
1981 (let ((unread (if (fd-stream-unread stream
)
1984 (setf (fd-stream-unread stream
) nil
)
1985 (let ((ibuf (fd-stream-ibuf stream
)))
1987 (let ((head (buffer-head ibuf
))
1988 (tail (buffer-tail ibuf
)))
1989 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1990 (values nil unread
)))))
1992 (defun fd-stream-clear-input (stream)
1993 (flush-input-buffer stream
)
1996 (sb!win32
:fd-clear-input
(fd-stream-fd stream
))
1997 (setf (fd-stream-listen stream
) nil
))
1999 (catch 'eof-input-catcher
2000 (loop until
(sysread-may-block-p stream
)
2002 (refill-input-buffer stream
)
2003 (reset-buffer (fd-stream-ibuf stream
)))
2006 ;;; Handle miscellaneous operations on FD-STREAM.
2007 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
2008 (declare (ignore arg2
))
2011 (labels ((do-listen ()
2012 (let ((ibuf (fd-stream-ibuf fd-stream
)))
2013 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
2014 (fd-stream-listen fd-stream
)
2016 (sb!win32
:fd-listen
(fd-stream-fd fd-stream
))
2018 ;; If the read can block, LISTEN will certainly return NIL.
2019 (if (sysread-may-block-p fd-stream
)
2021 ;; Otherwise select(2) and CL:LISTEN have slightly
2022 ;; different semantics. The former returns that an FD
2023 ;; is readable when a read operation wouldn't block.
2024 ;; That includes EOF. However, LISTEN must return NIL
2026 (progn (catch 'eof-input-catcher
2027 ;; r-b/f too calls select, but it shouldn't
2028 ;; block as long as read can return once w/o
2030 (refill-input-buffer fd-stream
))
2031 ;; At this point either IBUF-HEAD != IBUF-TAIL
2032 ;; and FD-STREAM-LISTEN is NIL, in which case
2033 ;; we should return T, or IBUF-HEAD ==
2034 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2035 ;; which case we should return :EOF for this
2036 ;; call and all future LISTEN call on this stream.
2037 ;; Call ourselves again to determine which case
2042 (setf (fd-stream-unread fd-stream
) arg1
)
2043 (setf (fd-stream-listen fd-stream
) t
))
2045 (cond (arg1 ; We got us an abort on our hands.
2046 (let ((outputp (fd-stream-obuf fd-stream
))
2047 (file (fd-stream-file fd-stream
))
2048 (orig (fd-stream-original fd-stream
)))
2049 ;; This takes care of the important stuff -- everything
2050 ;; rest is cleaning up the file-system, which we cannot
2051 ;; do on some platforms as long as the file is open.
2052 (release-fd-stream-resources fd-stream
)
2053 ;; We can't do anything unless we know what file were
2054 ;; dealing with, and we don't want to do anything
2055 ;; strange unless we were writing to the file.
2056 (when (and outputp file
)
2058 ;; If the original is EQ to file we are appending to
2059 ;; and can just close the file without renaming.
2060 (unless (eq orig file
)
2061 ;; We have a handle on the original, just revert.
2062 (multiple-value-bind (okay err
)
2063 (sb!unix
:unix-rename orig file
)
2064 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2065 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2068 (error 'simple-stream-error
2070 "~@<Couldn't restore ~S to its original contents ~
2071 from ~S while closing ~S: ~2I~_~A~:>"
2073 (list file orig fd-stream
(strerror err
))
2074 :stream fd-stream
))))
2075 ;; We can't restore the original, and aren't
2076 ;; appending, so nuke that puppy.
2078 ;; FIXME: This is currently the fate of superseded
2079 ;; files, and according to the CLOSE spec this is
2080 ;; wrong. However, there seems to be no clean way to
2081 ;; do that that doesn't involve either copying the
2082 ;; data (bad if the :abort resulted from a full
2083 ;; disk), or renaming the old file temporarily
2084 ;; (probably bad because stream opening becomes more
2086 (multiple-value-bind (okay err
)
2087 (sb!unix
:unix-unlink file
)
2089 (error 'simple-file-error
2092 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2094 (list file fd-stream
(strerror err
)))))))))
2096 (finish-fd-stream-output fd-stream
)
2097 (let ((orig (fd-stream-original fd-stream
)))
2098 (when (and orig
(fd-stream-delete-original fd-stream
))
2099 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2101 (error 'simple-file-error
2104 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2106 (list orig fd-stream
(strerror err
)))))))
2107 ;; In case of no-abort close, don't *really* close the
2108 ;; stream until the last moment -- the cleaning up of the
2109 ;; original can be done first.
2110 (release-fd-stream-resources fd-stream
))))
2112 (fd-stream-clear-input fd-stream
))
2114 (flush-output-buffer fd-stream
))
2116 (finish-fd-stream-output fd-stream
))
2118 (fd-stream-element-type fd-stream
))
2120 (fd-stream-external-format fd-stream
))
2122 (= 1 (the (member 0 1)
2123 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2127 (fd-stream-char-pos fd-stream
))
2129 (unless (fd-stream-file fd-stream
)
2130 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2131 ;; "should signal an error of type TYPE-ERROR if stream is not
2132 ;; a stream associated with a file". Too bad there's no very
2133 ;; appropriate value for the EXPECTED-TYPE slot..
2134 (error 'simple-type-error
2136 :expected-type
'fd-stream
2137 :format-control
"~S is not a stream associated with a file."
2138 :format-arguments
(list fd-stream
)))
2139 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2140 atime mtime ctime blksize blocks
)
2141 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2142 (declare (ignore ino nlink uid gid rdev
2143 atime mtime ctime blksize blocks
))
2145 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2148 (truncate size
(fd-stream-element-size fd-stream
)))))
2149 (:file-string-length
2151 (character (fd-stream-character-size fd-stream arg1
))
2152 (string (fd-stream-string-size fd-stream arg1
))))
2155 (fd-stream-set-file-position fd-stream arg1
)
2156 (fd-stream-get-file-position fd-stream
)))))
2158 ;; FIXME: Think about this.
2160 ;; (defun finish-fd-stream-output (fd-stream)
2161 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2162 ;; (loop while (fd-stream-output-queue fd-stream)
2163 ;; ;; FIXME: SIGINT while waiting for a timeout will
2164 ;; ;; cause a timeout here.
2165 ;; do (when (and (not (serve-event timeout)) timeout)
2166 ;; (signal-timeout 'io-timeout
2167 ;; :stream fd-stream
2168 ;; :direction :write
2169 ;; :seconds timeout)))))
2171 (defun finish-fd-stream-output (stream)
2172 (flush-output-buffer stream
)
2174 ((null (fd-stream-output-queue stream
)))
2175 (serve-all-events)))
2177 (defun fd-stream-get-file-position (stream)
2178 (declare (fd-stream stream
))
2180 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2181 (declare (type (or (alien sb
!unix
:off-t
) null
) posn
))
2182 ;; We used to return NIL for errno==ESPIPE, and signal an error
2183 ;; in other failure cases. However, CLHS says to return NIL if
2184 ;; the position cannot be determined -- so that's what we do.
2185 (when (integerp posn
)
2186 ;; Adjust for buffered output: If there is any output
2187 ;; buffered, the *real* file position will be larger
2188 ;; than reported by lseek() because lseek() obviously
2189 ;; cannot take into account output we have not sent
2191 (dolist (buffer (fd-stream-output-queue stream
))
2192 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2193 (let ((obuf (fd-stream-obuf stream
)))
2195 (incf posn
(buffer-tail obuf
))))
2196 ;; Adjust for unread input: If there is any input
2197 ;; read from UNIX but not supplied to the user of the
2198 ;; stream, the *real* file position will smaller than
2199 ;; reported, because we want to look like the unread
2200 ;; stuff is still available.
2201 (let ((ibuf (fd-stream-ibuf stream
)))
2203 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2204 (when (fd-stream-unread stream
)
2206 ;; Divide bytes by element size.
2207 (truncate posn
(fd-stream-element-size stream
))))))
2209 (defun fd-stream-set-file-position (stream position-spec
)
2210 (declare (fd-stream stream
))
2211 (check-type position-spec
2212 (or (alien sb
!unix
:off-t
) (member nil
:start
:end
))
2213 "valid file position designator")
2216 ;; Make sure we don't have any output pending, because if we
2217 ;; move the file pointer before writing this stuff, it will be
2218 ;; written in the wrong location.
2219 (finish-fd-stream-output stream
)
2220 ;; Disable interrupts so that interrupt handlers doing output
2223 (unless (fd-stream-output-finished-p stream
)
2224 ;; We got interrupted and more output came our way during
2225 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2226 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2227 ;; so we prefer to do things like this...
2229 ;; Clear out any pending input to force the next read to go to
2231 (flush-input-buffer stream
)
2232 ;; Trash cached value for listen, so that we check next time.
2233 (setf (fd-stream-listen stream
) nil
)
2235 (multiple-value-bind (offset origin
)
2238 (values 0 sb
!unix
:l_set
))
2240 (values 0 sb
!unix
:l_xtnd
))
2242 (values (* position-spec
(fd-stream-element-size stream
))
2244 (declare (type (alien sb
!unix
:off-t
) offset
))
2245 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2247 ;; CLHS says to return true if the file-position was set
2248 ;; succesfully, and NIL otherwise. We are to signal an error
2249 ;; only if the given position was out of bounds, and that is
2250 ;; dealt with above. In times past we used to return NIL for
2251 ;; errno==ESPIPE, and signal an error in other cases.
2253 ;; FIXME: We are still liable to signal an error if flushing
2255 (return-from fd-stream-set-file-position
2256 (typep posn
'(alien sb
!unix
:off-t
))))))))
2259 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2261 ;;; Create a stream for the given Unix file descriptor.
2263 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2264 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2265 ;;; default to allowing input.
2267 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2269 ;;; BUFFERING indicates the kind of buffering to use.
2271 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2272 ;;; NIL (the default), then wait forever. When we time out, we signal
2275 ;;; FILE is the name of the file (will be returned by PATHNAME).
2277 ;;; NAME is used to identify the stream when printed.
2278 (defun make-fd-stream (fd
2281 (output nil output-p
)
2282 (element-type 'base-char
)
2284 (external-format :default
)
2293 (format nil
"file ~A" file
)
2294 (format nil
"descriptor ~W" fd
)))
2296 (declare (type index fd
) (type (or real null
) timeout
)
2297 (type (member :none
:line
:full
) buffering
))
2298 (cond ((not (or input-p output-p
))
2300 ((not (or input output
))
2301 (error "File descriptor must be opened either for input or output.")))
2302 (let ((stream (%make-fd-stream
:fd fd
2306 :delete-original delete-original
2308 :buffering buffering
2309 :dual-channel-p dual-channel-p
2310 :external-format external-format
2311 :char-size
(external-format-char-size external-format
)
2314 (coerce timeout
'single-float
)
2316 (set-fd-stream-routines stream element-type external-format
2317 input output input-buffer-p
)
2318 (when (and auto-close
(fboundp 'finalize
))
2321 (sb!unix
:unix-close fd
)
2323 (format *terminal-io
* "** closed file descriptor ~W **~%"
2328 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2329 ;;; :RENAME-AND-DELETE and :RENAME options.
2330 (defun pick-backup-name (name)
2331 (declare (type simple-string name
))
2332 (concatenate 'simple-string name
".bak"))
2334 ;;; Ensure that the given arg is one of the given list of valid
2335 ;;; things. Allow the user to fix any problems.
2336 (defun ensure-one-of (item list what
)
2337 (unless (member item list
)
2338 (error 'simple-type-error
2340 :expected-type
`(member ,@list
)
2341 :format-control
"~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2342 :format-arguments
(list item what list
))))
2344 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2345 ;;; access, since we don't want to trash unwritable files even if we
2346 ;;; technically can. We return true if we succeed in renaming.
2347 (defun rename-the-old-one (namestring original
)
2348 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2349 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2350 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2353 (error 'simple-file-error
2354 :pathname namestring
2356 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2357 :format-arguments
(list namestring original
(strerror err
))))))
2359 (defun open (filename
2362 (element-type 'base-char
)
2363 (if-exists nil if-exists-given
)
2364 (if-does-not-exist nil if-does-not-exist-given
)
2365 (external-format :default
)
2366 &aux
; Squelch assignment warning.
2367 (direction direction
)
2368 (if-does-not-exist if-does-not-exist
)
2369 (if-exists if-exists
))
2371 "Return a stream which reads from or writes to FILENAME.
2373 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2374 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2375 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2376 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2377 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2378 See the manual for details."
2380 ;; Calculate useful stuff.
2381 (multiple-value-bind (input output mask
)
2383 (:input
(values t nil sb
!unix
:o_rdonly
))
2384 (:output
(values nil t sb
!unix
:o_wronly
))
2385 (:io
(values t t sb
!unix
:o_rdwr
))
2386 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2387 (declare (type index mask
))
2388 (let* ((pathname (merge-pathnames filename
))
2390 (cond ((unix-namestring pathname input
))
2391 ((and input
(eq if-does-not-exist
:create
))
2392 (unix-namestring pathname nil
))
2393 ((and (eq direction
:io
) (not if-does-not-exist-given
))
2394 (unix-namestring pathname nil
)))))
2395 ;; Process if-exists argument if we are doing any output.
2397 (unless if-exists-given
2399 (if (eq (pathname-version pathname
) :newest
)
2402 (ensure-one-of if-exists
2403 '(:error
:new-version
:rename
2404 :rename-and-delete
:overwrite
2405 :append
:supersede nil
)
2408 ((:new-version
:error nil
)
2409 (setf mask
(logior mask sb
!unix
:o_excl
)))
2410 ((:rename
:rename-and-delete
)
2411 (setf mask
(logior mask sb
!unix
:o_creat
)))
2413 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2415 (setf mask
(logior mask sb
!unix
:o_append
)))))
2417 (setf if-exists
:ignore-this-arg
)))
2419 (unless if-does-not-exist-given
2420 (setf if-does-not-exist
2421 (cond ((eq direction
:input
) :error
)
2423 (member if-exists
'(:overwrite
:append
)))
2425 ((eq direction
:probe
)
2429 (ensure-one-of if-does-not-exist
2430 '(:error
:create nil
)
2432 (if (eq if-does-not-exist
:create
)
2433 (setf mask
(logior mask sb
!unix
:o_creat
)))
2435 (let ((original (case if-exists
2436 ((:rename
:rename-and-delete
)
2437 (pick-backup-name namestring
))
2438 ((:append
:overwrite
)
2439 ;; KLUDGE: Provent CLOSE from deleting
2440 ;; appending streams when called with :ABORT T
2442 (delete-original (eq if-exists
:rename-and-delete
))
2444 (when (and original
(not (eq original namestring
)))
2445 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2446 ;; whether the file already exists, make sure the original
2447 ;; file is not a directory, and keep the mode.
2450 (multiple-value-bind (okay err
/dev inode orig-mode
)
2451 (sb!unix
:unix-stat namestring
)
2452 (declare (ignore inode
)
2453 (type (or index null
) orig-mode
))
2456 (when (and output
(= (logand orig-mode
#o170000
)
2458 (error 'simple-file-error
2459 :pathname namestring
2461 "can't open ~S for output: is a directory"
2462 :format-arguments
(list namestring
)))
2463 (setf mode
(logand orig-mode
#o777
))
2465 ((eql err
/dev sb
!unix
:enoent
)
2468 (simple-file-perror "can't find ~S"
2472 (rename-the-old-one namestring original
))
2474 (setf delete-original nil
)
2475 ;; In order to use :SUPERSEDE instead, we have to make
2476 ;; sure SB!UNIX:O_CREAT corresponds to
2477 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2478 ;; because of IF-EXISTS being :RENAME.
2479 (unless (eq if-does-not-exist
:create
)
2481 (logior (logandc2 mask sb
!unix
:o_creat
)
2483 (setf if-exists
:supersede
))))
2485 ;; Now we can try the actual Unix open(2).
2486 (multiple-value-bind (fd errno
)
2488 (sb!unix
:unix-open namestring mask mode
)
2489 (values nil sb
!unix
:enoent
))
2490 (labels ((open-error (format-control &rest format-arguments
)
2491 (error 'simple-file-error
2493 :format-control format-control
2494 :format-arguments format-arguments
))
2495 (vanilla-open-error ()
2496 (simple-file-perror "error opening ~S" pathname errno
)))
2499 ((:input
:output
:io
)
2503 :element-type element-type
2504 :external-format external-format
2507 :delete-original delete-original
2514 (%make-fd-stream
:name namestring
2517 :element-type element-type
)))
2520 ((eql errno sb
!unix
:enoent
)
2521 (case if-does-not-exist
2522 (:error
(vanilla-open-error))
2524 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2527 ((and (eql errno sb
!unix
:eexist
) (null if-exists
))
2530 (vanilla-open-error)))))))))
2534 ;;; the stream connected to the controlling terminal, or NIL if there is none
2537 ;;; the stream connected to the standard input (file descriptor 0)
2540 ;;; the stream connected to the standard output (file descriptor 1)
2543 ;;; the stream connected to the standard error output (file descriptor 2)
2546 ;;; This is called when the cold load is first started up, and may also
2547 ;;; be called in an attempt to recover from nested errors.
2548 (defun stream-cold-init-or-reset ()
2550 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2551 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2552 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2553 (setf *error-output
* (make-synonym-stream '*stderr
*))
2554 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2555 (setf *debug-io
* *query-io
*)
2556 (setf *trace-output
* *standard-output
*)
2559 (defun stream-deinit ()
2560 ;; Unbind to make sure we're not accidently dealing with it
2561 ;; before we're ready (or after we think it's been deinitialized).
2562 (with-available-buffers-lock ()
2563 (without-package-locks
2564 (makunbound '*available-buffers
*))))
2566 ;;; This is called whenever a saved core is restarted.
2567 (defun stream-reinit (&optional init-buffers-p
)
2568 (when init-buffers-p
2569 (with-available-buffers-lock ()
2570 (aver (not (boundp '*available-buffers
*)))
2571 (setf *available-buffers
* nil
)))
2572 (with-output-to-string (*error-output
*)
2574 (make-fd-stream 0 :name
"standard input" :input t
:buffering
:line
2575 #!+win32
:external-format
#!+win32
(sb!win32
::console-input-codepage
)))
2577 (make-fd-stream 1 :name
"standard output" :output t
:buffering
:line
2578 #!+win32
:external-format
#!+win32
(sb!win32
::console-output-codepage
)))
2580 (make-fd-stream 2 :name
"standard error" :output t
:buffering
:line
2581 #!+win32
:external-format
#!+win32
(sb!win32
::console-output-codepage
)))
2582 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2583 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2587 :name
"the terminal"
2592 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))))
2593 (princ (get-output-stream-string *error-output
*) *stderr
*))
2598 ;;; the Unix way to beep
2599 (defun beep (stream)
2600 (write-char (code-char bell-char-code
) stream
)
2601 (finish-output stream
))
2603 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2604 ;;; by the filesys stuff to get and set the file name.
2606 ;;; FIXME: misleading name, screwy interface
2607 (defun file-name (stream &optional new-name
)
2608 (when (typep stream
'fd-stream
)
2610 (setf (fd-stream-pathname stream
) new-name
)
2611 (setf (fd-stream-file stream
)
2612 (unix-namestring new-name nil
))
2615 (fd-stream-pathname stream
)))))