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
::call-with-system-spinlock
(lambda () ,@body
)
74 *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 (output-bytes #'ill-out
:type function
))
189 (def!method print-object
((fd-stream fd-stream
) stream
)
190 (declare (type stream stream
))
191 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
192 (format stream
"for ~S" (fd-stream-name fd-stream
))))
194 ;;;; CORE OUTPUT FUNCTIONS
196 ;;; Buffer the section of THING delimited by START and END by copying
197 ;;; to output buffer(s) of stream.
198 (defun buffer-output (stream thing start end
)
199 (declare (index start end
))
201 (error ":END before :START!"))
203 ;; Copy bytes from THING to buffers.
204 (flet ((copy-to-buffer (buffer tail count
)
205 (declare (buffer buffer
) (index tail count
))
207 (let ((sap (buffer-sap buffer
)))
210 (system-area-ub8-copy thing start sap tail count
))
211 ((simple-unboxed-array (*))
212 (copy-ub8-to-system-area thing start sap tail count
))))
213 ;; Not INCF! If another thread has moved tail from under
214 ;; us, we don't want to accidentally increment tail
215 ;; beyond buffer-length.
216 (setf (buffer-tail buffer
) (+ count tail
))
219 ;; First copy is special: the buffer may already contain
220 ;; something, or be even full.
221 (let* ((obuf (fd-stream-obuf stream
))
222 (tail (buffer-tail obuf
))
223 (space (- (buffer-length obuf
) tail
)))
225 (copy-to-buffer obuf tail
(min space
(- end start
)))
226 (go :more-output-p
)))
228 ;; Later copies should always have an empty buffer, since
229 ;; they are freshly flushed, but if another thread is
230 ;; stomping on the same buffer that might not be the case.
231 (let* ((obuf (flush-output-buffer stream
))
232 (tail (buffer-tail obuf
))
233 (space (- (buffer-length obuf
) tail
)))
234 (copy-to-buffer obuf tail
(min space
(- end start
))))
237 (go :flush-and-fill
))))))
239 ;;; Flush the current output buffer of the stream, ensuring that the
240 ;;; new buffer is empty. Returns (for convenience) the new output
241 ;;; buffer -- which may or may not be EQ to the old one. If the is no
242 ;;; queued output we try to write the buffer immediately -- otherwise
243 ;;; we queue it for later.
244 (defun flush-output-buffer (stream)
245 (let ((obuf (fd-stream-obuf stream
)))
247 (let ((head (buffer-head obuf
))
248 (tail (buffer-tail obuf
)))
249 (cond ((eql head tail
)
250 ;; Buffer is already empty -- just ensure that is is
251 ;; set to zero as well.
253 ((fd-stream-output-queue stream
)
254 ;; There is already stuff on the queue -- go directly
257 (%queue-and-replace-output-buffer stream
))
259 ;; Try a non-blocking write, queue whatever is left over.
261 (synchronize-stream-output stream
)
262 (let ((length (- tail head
)))
263 (multiple-value-bind (count errno
)
264 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
266 (cond ((eql count length
)
267 ;; Complete write -- we can use the same buffer.
270 ;; Partial write -- update buffer status and queue.
271 ;; Do not use INCF! Another thread might have moved
273 (setf (buffer-head obuf
) (+ count head
))
274 (%queue-and-replace-output-buffer stream
))
276 ((eql errno sb
!unix
:ewouldblock
)
278 (%queue-and-replace-output-buffer stream
))
280 (simple-stream-perror "Couldn't write to ~s"
281 stream errno
)))))))))))
283 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
284 (defun %queue-and-replace-output-buffer
(stream)
285 (let ((queue (fd-stream-output-queue stream
))
286 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
288 ;; Important: before putting the buffer on queue, give the stream
289 ;; a new one. If we get an interrupt and unwind losing the buffer
290 ;; is relatively OK, but having the same buffer in two places
292 (setf (fd-stream-obuf stream
) new
)
296 (setf (fd-stream-output-queue stream
) later
)))
297 (unless (fd-stream-handler stream
)
298 (setf (fd-stream-handler stream
)
299 (add-fd-handler (fd-stream-fd stream
)
302 (declare (ignore fd
))
303 (write-output-from-queue stream
)))))
306 ;;; This is called by the FD-HANDLER for the stream when output is
308 (defun write-output-from-queue (stream)
309 (synchronize-stream-output stream
)
313 (let* ((buffer (pop (fd-stream-output-queue stream
)))
314 (head (buffer-head buffer
))
315 (length (- (buffer-tail buffer
) head
)))
316 (declare (index head length
))
318 (multiple-value-bind (count errno
)
319 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
321 (cond ((eql count length
)
322 ;; Complete write, see if we can do another right
323 ;; away, or remove the handler if we're done.
324 (release-buffer buffer
)
325 (cond ((fd-stream-output-queue stream
)
329 (let ((handler (fd-stream-handler stream
)))
331 (setf (fd-stream-handler stream
) nil
)
332 (remove-fd-handler handler
)))))
334 ;; Partial write. Update buffer status and requeue.
335 (aver (< count length
))
336 ;; Do not use INCF! Another thread might have moved head.
337 (setf (buffer-head buffer
) (+ head count
))
338 (push buffer
(fd-stream-output-queue stream
)))
340 ;; We tried to do multiple writes, and finally our
341 ;; luck ran out. Requeue.
342 (push buffer
(fd-stream-output-queue stream
)))
344 ;; Could not write on the first try at all!
346 (simple-stream-perror "Couldn't write to ~S." stream errno
)
348 (if (= errno sb
!unix
:ewouldblock
)
349 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
350 (simple-stream-perror "Couldn't write to ~S"
354 ;;; Try to write THING directly to STREAM without buffering, if
355 ;;; possible. If direct write doesn't happen, buffer.
356 (defun write-or-buffer-output (stream thing start end
)
357 (declare (index start end
))
358 (cond ((fd-stream-output-queue stream
)
359 (buffer-output stream thing start end
))
361 (error ":END before :START!"))
363 (let ((length (- end start
)))
364 (synchronize-stream-output stream
)
365 (multiple-value-bind (count errno
)
366 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
367 (cond ((eql count length
)
368 ;; Complete write -- done!
371 (aver (< count length
))
372 ;; Partial write -- buffer the rest.
373 (buffer-output stream thing
(+ start count
) end
))
375 ;; Could not write -- buffer or error.
377 (simple-stream-perror "couldn't write to ~s" stream errno
)
379 (if (= errno sb
!unix
:ewouldblock
)
380 (buffer-output stream thing start end
)
381 (simple-stream-perror "couldn't write to ~s" stream errno
)))))))))
383 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
384 ;;; this is not something we want to export. Nikodemus thinks the
385 ;;; right thing is to support a low-level non-stream like IO layer,
386 ;;; akin to java.nio.
387 (defun output-raw-bytes (stream thing
&optional start end
)
388 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
390 (define-compiler-macro output-raw-bytes
(stream thing
&optional start end
)
391 (deprecation-warning 'output-raw-bytes
)
392 (let ((x (gensym "THING")))
394 (write-or-buffer-output ,stream
,x
(or ,start
0) (or ,end
(length ,x
))))))
396 ;;;; output routines and related noise
398 (defvar *output-routines
* ()
400 "List of all available output routines. Each element is a list of the
401 element-type output, the kind of buffering, the function name, and the number
402 of bytes per element.")
404 ;;; common idioms for reporting low-level stream and file problems
405 (defun simple-stream-perror (note-format stream errno
)
406 (error 'simple-stream-error
408 :format-control
"~@<~?: ~2I~_~A~:>"
409 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
410 (defun simple-file-perror (note-format pathname errno
)
411 (error 'simple-file-error
413 :format-control
"~@<~?: ~2I~_~A~:>"
415 (list note-format
(list pathname
) (strerror errno
))))
417 (defun stream-decoding-error (stream octets
)
418 (error 'stream-decoding-error
420 ;; FIXME: dunno how to get at OCTETS currently, or even if
421 ;; that's the right thing to report.
423 (defun stream-encoding-error (stream code
)
424 (error 'stream-encoding-error
428 (defun c-string-encoding-error (external-format code
)
429 (error 'c-string-encoding-error
430 :external-format external-format
433 (defun c-string-decoding-error (external-format octets
)
434 (error 'c-string-decoding-error
435 :external-format external-format
438 ;;; Returning true goes into end of file handling, false will enter another
439 ;;; round of input buffer filling followed by re-entering character decode.
440 (defun stream-decoding-error-and-handle (stream octet-count
)
442 (stream-decoding-error stream
443 (let* ((buffer (fd-stream-ibuf stream
))
444 (sap (buffer-sap buffer
))
445 (head (buffer-head buffer
)))
446 (loop for i from
0 below octet-count
447 collect
(sap-ref-8 sap
(+ head i
)))))
449 :report
(lambda (stream)
451 "~@<Attempt to resync the stream at a character ~
452 character boundary and continue.~@:>"))
453 (fd-stream-resync stream
)
455 (force-end-of-file ()
456 :report
(lambda (stream)
457 (format stream
"~@<Force an end of file.~@:>"))
460 (defun stream-encoding-error-and-handle (stream code
)
462 (stream-encoding-error stream code
)
464 :report
(lambda (stream)
465 (format stream
"~@<Skip output of this character.~@:>"))
466 (throw 'output-nothing nil
))))
468 (defun external-format-encoding-error (stream code
)
470 (stream-encoding-error-and-handle stream code
)
471 (c-string-encoding-error stream code
)))
473 (defun external-format-decoding-error (stream octet-count
)
475 (stream-decoding-error stream octet-count
)
476 (c-string-decoding-error stream octet-count
)))
478 (defun synchronize-stream-output (stream)
479 ;; If we're reading and writing on the same file, flush buffered
480 ;; input and rewind file position accordingly.
481 (unless (fd-stream-dual-channel-p stream
)
482 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
483 (unless (eql 0 adjust
)
484 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
486 (defun fd-stream-output-finished-p (stream)
487 (let ((obuf (fd-stream-obuf stream
)))
489 (and (zerop (buffer-tail obuf
))
490 (not (fd-stream-output-queue stream
))))))
492 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
494 (let ((stream-var (gensym "STREAM")))
495 `(let* ((,stream-var
,stream
)
496 (obuf (fd-stream-obuf ,stream-var
))
497 (tail (buffer-tail obuf
))
499 ,(unless (eq (car buffering
) :none
)
500 `(when (<= (buffer-length obuf
) (+ tail size
))
501 (setf obuf
(flush-output-buffer ,stream-var
)
502 tail
(buffer-tail obuf
))))
503 ,(unless (eq (car buffering
) :none
)
504 ;; FIXME: Why this here? Doesn't seem necessary.
505 `(synchronize-stream-output ,stream-var
))
507 `(catch 'output-nothing
509 (setf (buffer-tail obuf
) (+ tail size
)))
512 (setf (buffer-tail obuf
) (+ tail size
))))
513 ,(ecase (car buffering
)
515 `(flush-output-buffer ,stream-var
))
517 `(when (eql byte
#\Newline
)
518 (flush-output-buffer ,stream-var
)))
522 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
523 (let ((stream-var (gensym "STREAM")))
524 `(let* ((,stream-var
,stream
)
525 (obuf (fd-stream-obuf ,stream-var
))
526 (tail (buffer-tail obuf
)))
527 ,(unless (eq (car buffering
) :none
)
528 `(when (<= (buffer-length obuf
) (+ tail
,size
))
529 (setf obuf
(flush-output-buffer ,stream-var
)
530 tail
(buffer-tail obuf
))))
531 ;; FIXME: Why this here? Doesn't seem necessary.
532 ,(unless (eq (car buffering
) :none
)
533 `(synchronize-stream-output ,stream-var
))
535 `(catch 'output-nothing
537 (setf (buffer-tail obuf
) (+ tail
,size
)))
540 (setf (buffer-tail obuf
) (+ tail
,size
))))
541 ,(ecase (car buffering
)
543 `(flush-output-buffer ,stream-var
))
545 `(when (eql byte
#\Newline
)
546 (flush-output-buffer ,stream-var
)))
550 (defmacro def-output-routines
/variable-width
551 ((name-fmt size restart external-format
&rest bufferings
)
553 (declare (optimize (speed 1)))
558 (intern (format nil name-fmt
(string (car buffering
))))))
560 (defun ,function
(stream byte
)
561 (declare (ignorable byte
))
562 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
564 (setf *output-routines
*
565 (nconc *output-routines
*
573 (cdr buffering
)))))))
576 ;;; Define output routines that output numbers SIZE bytes long for the
577 ;;; given bufferings. Use BODY to do the actual output.
578 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
580 (declare (optimize (speed 1)))
585 (intern (format nil name-fmt
(string (car buffering
))))))
587 (defun ,function
(stream byte
)
588 (output-wrapper (stream ,size
,buffering
,restart
)
590 (setf *output-routines
*
591 (nconc *output-routines
*
599 (cdr buffering
)))))))
602 ;;; FIXME: is this used anywhere any more?
603 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
609 (if (eql byte
#\Newline
)
610 (setf (fd-stream-char-pos stream
) 0)
611 (incf (fd-stream-char-pos stream
)))
612 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
615 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
618 (:none
(unsigned-byte 8))
619 (:full
(unsigned-byte 8)))
620 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
623 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
626 (:none
(signed-byte 8))
627 (:full
(signed-byte 8)))
628 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
631 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
634 (:none
(unsigned-byte 16))
635 (:full
(unsigned-byte 16)))
636 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
639 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
642 (:none
(signed-byte 16))
643 (:full
(signed-byte 16)))
644 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
647 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
650 (:none
(unsigned-byte 32))
651 (:full
(unsigned-byte 32)))
652 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
655 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
658 (:none
(signed-byte 32))
659 (:full
(signed-byte 32)))
660 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
663 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
665 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
668 (:none
(unsigned-byte 64))
669 (:full
(unsigned-byte 64)))
670 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
672 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
675 (:none
(signed-byte 64))
676 (:full
(signed-byte 64)))
677 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
680 ;;; the routine to use to output a string. If the stream is
681 ;;; unbuffered, slam the string down the file descriptor, otherwise
682 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
683 ;;; checking to see where the last newline was.
684 (defun fd-sout (stream thing start end
)
685 (declare (type fd-stream stream
) (type string thing
))
686 (let ((start (or start
0))
687 (end (or end
(length (the vector thing
)))))
688 (declare (fixnum start end
))
690 (string-dispatch (simple-base-string
692 (simple-array character
(*))
695 (position #\newline thing
:from-end t
696 :start start
:end end
))))
697 (if (and (typep thing
'base-string
)
698 (eq (fd-stream-external-format stream
) :latin-1
))
699 (ecase (fd-stream-buffering stream
)
701 (buffer-output stream thing start end
))
703 (buffer-output stream thing start end
)
705 (flush-output-buffer stream
)))
707 (write-or-buffer-output stream thing start end
)))
708 (ecase (fd-stream-buffering stream
)
709 (:full
(funcall (fd-stream-output-bytes stream
)
710 stream thing nil start end
))
711 (:line
(funcall (fd-stream-output-bytes stream
)
712 stream thing last-newline start end
))
713 (:none
(funcall (fd-stream-output-bytes stream
)
714 stream thing t start end
))))
716 (setf (fd-stream-char-pos stream
) (- end last-newline
1))
717 (incf (fd-stream-char-pos stream
) (- end start
))))))
719 (defvar *external-formats
* ()
721 "List of all available external formats. Each element is a list of the
722 element-type, string input function name, character input function name,
723 and string output function name.")
725 (defun get-external-format (external-format)
726 (dolist (entry *external-formats
*)
727 (when (member external-format
(first entry
))
730 (defun get-external-format-function (external-format index
)
731 (let ((entry (get-external-format external-format
)))
732 (when entry
(nth index entry
))))
734 ;;; Find an output routine to use given the type and buffering. Return
735 ;;; as multiple values the routine, the real type transfered, and the
736 ;;; number of bytes per element.
737 (defun pick-output-routine (type buffering
&optional external-format
)
738 (when (subtypep type
'character
)
739 (let ((entry (get-external-format external-format
)))
741 (return-from pick-output-routine
742 (values (symbol-function (nth (ecase buffering
749 (symbol-function (fourth entry
))
750 (first (first entry
)))))))
751 (dolist (entry *output-routines
*)
752 (when (and (subtypep type
(first entry
))
753 (eq buffering
(second entry
))
754 (or (not (fifth entry
))
755 (eq external-format
(fifth entry
))))
756 (return-from pick-output-routine
757 (values (symbol-function (third entry
))
760 ;; KLUDGE: dealing with the buffering here leads to excessive code
763 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
764 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
765 if
(subtypep type
`(unsigned-byte ,i
))
766 do
(return-from pick-output-routine
770 (lambda (stream byte
)
771 (output-wrapper (stream (/ i
8) (:none
) nil
)
772 (loop for j from
0 below
(/ i
8)
773 do
(setf (sap-ref-8 (buffer-sap obuf
)
775 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
777 (lambda (stream byte
)
778 (output-wrapper (stream (/ i
8) (:full
) nil
)
779 (loop for j from
0 below
(/ i
8)
780 do
(setf (sap-ref-8 (buffer-sap obuf
)
782 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
785 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
786 if
(subtypep type
`(signed-byte ,i
))
787 do
(return-from pick-output-routine
791 (lambda (stream byte
)
792 (output-wrapper (stream (/ i
8) (:none
) nil
)
793 (loop for j from
0 below
(/ i
8)
794 do
(setf (sap-ref-8 (buffer-sap obuf
)
796 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
798 (lambda (stream byte
)
799 (output-wrapper (stream (/ i
8) (:full
) nil
)
800 (loop for j from
0 below
(/ i
8)
801 do
(setf (sap-ref-8 (buffer-sap obuf
)
803 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
807 ;;;; input routines and related noise
809 ;;; a list of all available input routines. Each element is a list of
810 ;;; the element-type input, the function name, and the number of bytes
812 (defvar *input-routines
* ())
814 ;;; Return whether a primitive partial read operation on STREAM's FD
815 ;;; would (probably) block. Signal a `simple-stream-error' if the
816 ;;; system call implementing this operation fails.
818 ;;; It is "may" instead of "would" because "would" is not quite
819 ;;; correct on win32. However, none of the places that use it require
820 ;;; further assurance than "may" versus "will definitely not".
821 (defun sysread-may-block-p (stream)
823 ;; This answers T at EOF on win32, I think.
824 (not (sb!win32
:fd-listen
(fd-stream-fd stream
)))
826 (sb!unix
:with-restarted-syscall
(count errno
)
827 (sb!alien
:with-alien
((read-fds (sb!alien
:struct sb
!unix
:fd-set
)))
828 (sb!unix
:fd-zero read-fds
)
829 (sb!unix
:fd-set
(fd-stream-fd stream
) read-fds
)
830 (sb!unix
:unix-fast-select
(1+ (fd-stream-fd stream
))
831 (sb!alien
:addr read-fds
)
837 (simple-stream-perror "couldn't check whether ~S is readable"
841 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
842 ;;; then fill the input buffer, and return the number of bytes read. Throws
843 ;;; to EOF-INPUT-CATCHER if the eof was reached.
844 (defun refill-input-buffer (stream)
845 (let ((fd (fd-stream-fd stream
))
848 (declare (dynamic-extent fd errno count
))
850 ;; Check for blocking input before touching the stream, as if
851 ;; we happen to wait we are liable to be interrupted, and the
852 ;; interrupt handler may use the same stream.
853 (if (sysread-may-block-p stream
)
856 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
857 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
859 (closed-flame stream
)
861 (simple-stream-perror "couldn't read from ~S" stream errno
)
863 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
864 ;; to wait for input if read tells us EWOULDBLOCK.
865 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
))
866 (signal-timeout 'io-timeout
:stream stream
:direction
:read
867 :seconds
(fd-stream-timeout stream
)))
869 ;; Since the read should not block, we'll disable the
870 ;; interrupts here, so that we don't accidentally unwind and
871 ;; leave the stream in an inconsistent state.
873 ;; Execute the nlx outside without-interrupts to ensure the
874 ;; resulting thunk is stack-allocatable.
875 ((lambda (return-reason)
877 ((nil)) ; fast path normal cases
878 ((:wait-for-input
) (go :wait-for-input
))
879 ((:closed-flame
) (go :closed-flame
))
880 ((:read-error
) (go :read-error
))))
882 ;; Check the buffer: if it is null, then someone has closed
883 ;; the stream from underneath us. This is not ment to fix
884 ;; multithreaded races, but to deal with interrupt handlers
885 ;; closing the stream.
888 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
889 (sap (buffer-sap ibuf
))
890 (length (buffer-length ibuf
))
891 (head (buffer-head ibuf
))
892 (tail (buffer-tail ibuf
)))
893 (declare (index length head tail
)
894 (inline sb
!unix
:unix-read
))
896 (cond ((eql head tail
)
897 ;; Buffer is empty, but not at yet reset -- make it so.
902 ;; Buffer has things in it, but they are not at the
903 ;; head -- move them there.
904 (let ((n (- tail head
)))
905 (system-area-ub8-copy sap head sap
0 n
)
907 (buffer-head ibuf
) head
909 (buffer-tail ibuf
) tail
)))))
910 (setf (fd-stream-listen stream
) nil
)
911 (setf (values count errno
)
912 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
917 (if (eql errno sb
!unix
:ewouldblock
)
918 (return :wait-for-input
)
919 (return :read-error
)))
921 (setf (fd-stream-listen stream
) :eof
)
922 (/show0
"THROWing EOF-INPUT-CATCHER")
923 (throw 'eof-input-catcher nil
))
925 ;; Success! (Do not use INCF, for sake of other threads.)
926 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
929 ;;; Make sure there are at least BYTES number of bytes in the input
930 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
931 (defmacro input-at-least
(stream bytes
)
932 (let ((stream-var (gensym "STREAM"))
933 (bytes-var (gensym "BYTES"))
934 (buffer-var (gensym "IBUF")))
935 `(let* ((,stream-var
,stream
)
937 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
939 (when (>= (- (buffer-tail ,buffer-var
)
940 (buffer-head ,buffer-var
))
943 (refill-input-buffer ,stream-var
)))))
945 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
947 (let ((stream-var (gensym "STREAM"))
948 (retry-var (gensym "RETRY"))
949 (element-var (gensym "ELT")))
950 `(let* ((,stream-var
,stream
)
951 (ibuf (fd-stream-ibuf ,stream-var
))
953 (if (fd-stream-unread ,stream-var
)
955 (fd-stream-unread ,stream-var
)
956 (setf (fd-stream-unread ,stream-var
) nil
)
957 (setf (fd-stream-listen ,stream-var
) nil
))
958 (let ((,element-var nil
)
959 (decode-break-reason nil
))
963 (catch 'eof-input-catcher
964 (setf decode-break-reason
965 (block decode-break-reason
966 (input-at-least ,stream-var
1)
967 (let* ((byte (sap-ref-8 (buffer-sap ibuf
)
968 (buffer-head ibuf
))))
969 (declare (ignorable byte
))
971 (input-at-least ,stream-var size
)
972 (setq ,element-var
(locally ,@read-forms
))
973 (setq ,retry-var nil
))
975 (when decode-break-reason
976 (stream-decoding-error-and-handle stream
977 decode-break-reason
))
979 (let ((octet-count (- (buffer-tail ibuf
)
980 (buffer-head ibuf
))))
981 (when (or (zerop octet-count
)
982 (and (not ,element-var
)
983 (not decode-break-reason
)
984 (stream-decoding-error-and-handle
985 stream octet-count
)))
986 (setq ,retry-var nil
)))))
988 (incf (buffer-head ibuf
) size
)
991 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
993 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
994 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
995 (let ((stream-var (gensym "STREAM"))
996 (element-var (gensym "ELT")))
997 `(let* ((,stream-var
,stream
)
998 (ibuf (fd-stream-ibuf ,stream-var
)))
999 (if (fd-stream-unread ,stream-var
)
1001 (fd-stream-unread ,stream-var
)
1002 (setf (fd-stream-unread ,stream-var
) nil
)
1003 (setf (fd-stream-listen ,stream-var
) nil
))
1005 (catch 'eof-input-catcher
1006 (input-at-least ,stream-var
,bytes
)
1007 (locally ,@read-forms
))))
1009 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1012 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1014 (defmacro def-input-routine
/variable-width
(name
1015 (type external-format size sap head
)
1018 (defun ,name
(stream eof-error eof-value
)
1019 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1020 (let ((,sap
(buffer-sap ibuf
))
1021 (,head
(buffer-head ibuf
)))
1023 (setf *input-routines
*
1024 (nconc *input-routines
*
1025 (list (list ',type
',name
1 ',external-format
))))))
1027 (defmacro def-input-routine
(name
1028 (type size sap head
)
1031 (defun ,name
(stream eof-error eof-value
)
1032 (input-wrapper (stream ,size eof-error eof-value
)
1033 (let ((,sap
(buffer-sap ibuf
))
1034 (,head
(buffer-head ibuf
)))
1036 (setf *input-routines
*
1037 (nconc *input-routines
*
1038 (list (list ',type
',name
',size nil
))))))
1040 ;;; STREAM-IN routine for reading a string char
1041 (def-input-routine input-character
1042 (character 1 sap head
)
1043 (code-char (sap-ref-8 sap head
)))
1045 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1046 (def-input-routine input-unsigned-8bit-byte
1047 ((unsigned-byte 8) 1 sap head
)
1048 (sap-ref-8 sap head
))
1050 ;;; STREAM-IN routine for reading a signed 8 bit number
1051 (def-input-routine input-signed-8bit-number
1052 ((signed-byte 8) 1 sap head
)
1053 (signed-sap-ref-8 sap head
))
1055 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1056 (def-input-routine input-unsigned-16bit-byte
1057 ((unsigned-byte 16) 2 sap head
)
1058 (sap-ref-16 sap head
))
1060 ;;; STREAM-IN routine for reading a signed 16 bit number
1061 (def-input-routine input-signed-16bit-byte
1062 ((signed-byte 16) 2 sap head
)
1063 (signed-sap-ref-16 sap head
))
1065 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1066 (def-input-routine input-unsigned-32bit-byte
1067 ((unsigned-byte 32) 4 sap head
)
1068 (sap-ref-32 sap head
))
1070 ;;; STREAM-IN routine for reading a signed 32 bit number
1071 (def-input-routine input-signed-32bit-byte
1072 ((signed-byte 32) 4 sap head
)
1073 (signed-sap-ref-32 sap head
))
1075 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
1077 (def-input-routine input-unsigned-64bit-byte
1078 ((unsigned-byte 64) 8 sap head
)
1079 (sap-ref-64 sap head
))
1080 (def-input-routine input-signed-64bit-byte
1081 ((signed-byte 64) 8 sap head
)
1082 (signed-sap-ref-64 sap head
)))
1084 ;;; Find an input routine to use given the type. Return as multiple
1085 ;;; values the routine, the real type transfered, and the number of
1086 ;;; bytes per element (and for character types string input routine).
1087 (defun pick-input-routine (type &optional external-format
)
1088 (when (subtypep type
'character
)
1089 (dolist (entry *external-formats
*)
1090 (when (member external-format
(first entry
))
1091 (return-from pick-input-routine
1092 (values (symbol-function (third entry
))
1095 (symbol-function (second entry
))
1096 (first (first entry
)))))))
1097 (dolist (entry *input-routines
*)
1098 (when (and (subtypep type
(first entry
))
1099 (or (not (fourth entry
))
1100 (eq external-format
(fourth entry
))))
1101 (return-from pick-input-routine
1102 (values (symbol-function (second entry
))
1105 ;; FIXME: let's do it the hard way, then (but ignore things like
1106 ;; endianness, efficiency, and the necessary coupling between these
1107 ;; and the output routines). -- CSR, 2004-02-09
1108 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1109 if
(subtypep type
`(unsigned-byte ,i
))
1110 do
(return-from pick-input-routine
1112 (lambda (stream eof-error eof-value
)
1113 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1114 (let ((sap (buffer-sap ibuf
))
1115 (head (buffer-head ibuf
)))
1116 (loop for j from
0 below
(/ i
8)
1120 (sap-ref-8 sap
(+ head j
))))
1121 finally
(return result
)))))
1124 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1125 if
(subtypep type
`(signed-byte ,i
))
1126 do
(return-from pick-input-routine
1128 (lambda (stream eof-error eof-value
)
1129 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1130 (let ((sap (buffer-sap ibuf
))
1131 (head (buffer-head ibuf
)))
1132 (loop for j from
0 below
(/ i
8)
1136 (sap-ref-8 sap
(+ head j
))))
1137 finally
(return (if (logbitp (1- i
) result
)
1138 (dpb result
(byte i
0) -
1)
1143 ;;; the N-BIN method for FD-STREAMs
1145 ;;; Note that this blocks in UNIX-READ. It is generally used where
1146 ;;; there is a definite amount of reading to be done, so blocking
1147 ;;; isn't too problematical.
1148 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1149 &aux
(total-copied 0))
1150 (declare (type fd-stream stream
))
1151 (declare (type index start requested total-copied
))
1152 (let ((unread (fd-stream-unread stream
)))
1154 ;; AVERs designed to fail when we have more complicated
1155 ;; character representations.
1156 (aver (typep unread
'base-char
))
1157 (aver (= (fd-stream-element-size stream
) 1))
1158 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1161 (system-area-pointer
1162 (setf (sap-ref-8 buffer start
) (char-code unread
)))
1163 ((simple-unboxed-array (*))
1164 (setf (aref buffer start
) unread
)))
1165 (setf (fd-stream-unread stream
) nil
)
1166 (setf (fd-stream-listen stream
) nil
)
1167 (incf total-copied
)))
1170 (let* ((remaining-request (- requested total-copied
))
1171 (ibuf (fd-stream-ibuf stream
))
1172 (head (buffer-head ibuf
))
1173 (tail (buffer-tail ibuf
))
1174 (available (- tail head
))
1175 (n-this-copy (min remaining-request available
))
1176 (this-start (+ start total-copied
))
1177 (this-end (+ this-start n-this-copy
))
1178 (sap (buffer-sap ibuf
)))
1179 (declare (type index remaining-request head tail available
))
1180 (declare (type index n-this-copy
))
1181 ;; Copy data from stream buffer into user's buffer.
1182 (%byte-blt sap head buffer this-start this-end
)
1183 (incf (buffer-head ibuf
) n-this-copy
)
1184 (incf total-copied n-this-copy
)
1185 ;; Maybe we need to refill the stream buffer.
1186 (cond (;; If there were enough data in the stream buffer, we're done.
1187 (eql total-copied requested
)
1188 (return total-copied
))
1189 (;; If EOF, we're done in another way.
1190 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1192 (error 'end-of-file
:stream stream
)
1193 (return total-copied
)))
1194 ;; Otherwise we refilled the stream buffer, so fall
1195 ;; through into another pass of the loop.
1198 (defun fd-stream-resync (stream)
1199 (dolist (entry *external-formats
*)
1200 (when (member (fd-stream-external-format stream
) (first entry
))
1201 (return-from fd-stream-resync
1202 (funcall (symbol-function (eighth entry
)) stream
)))))
1204 (defun get-fd-stream-character-sizer (stream)
1205 (dolist (entry *external-formats
*)
1206 (when (member (fd-stream-external-format stream
) (first entry
))
1207 (return-from get-fd-stream-character-sizer
(ninth entry
)))))
1209 (defun fd-stream-character-size (stream char
)
1210 (let ((sizer (get-fd-stream-character-sizer stream
)))
1211 (when sizer
(funcall sizer char
))))
1213 (defun fd-stream-string-size (stream string
)
1214 (let ((sizer (get-fd-stream-character-sizer stream
)))
1216 (loop for char across string summing
(funcall sizer char
)))))
1218 (defun find-external-format (external-format)
1219 (when external-format
1220 (find external-format
*external-formats
* :test
#'member
:key
#'car
)))
1222 (defun variable-width-external-format-p (ef-entry)
1223 (when (eighth ef-entry
) t
))
1225 (defun bytes-for-char-fun (ef-entry)
1226 (if ef-entry
(symbol-function (ninth ef-entry
)) (constantly 1)))
1228 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1229 (defmacro define-external-format
(external-format size output-restart
1231 (let* ((name (first external-format
))
1232 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1233 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1234 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1235 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1236 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1237 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1238 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1239 (n-buffer (gensym "BUFFER")))
1241 (defun ,size-function
(byte)
1242 (declare (ignore byte
))
1244 (defun ,out-function
(stream string flush-p start end
)
1245 (let ((start (or start
0))
1246 (end (or end
(length string
))))
1247 (declare (type index start end
))
1248 (synchronize-stream-output stream
)
1249 (unless (<= 0 start end
(length string
))
1250 (sequence-bounding-indices-bad-error string start end
))
1253 (let ((obuf (fd-stream-obuf stream
)))
1254 (setf (buffer-tail obuf
)
1255 (string-dispatch (simple-base-string
1257 (simple-array character
(*))
1260 (let ((sap (buffer-sap obuf
))
1261 (len (buffer-length obuf
))
1263 (tail (buffer-tail obuf
)))
1264 (declare (type index tail
)
1265 ;; STRING bounds have already been checked.
1266 (optimize (safety 0)))
1268 (,@(if output-restart
1269 `(catch 'output-nothing
)
1272 ((or (= start end
) (< (- len tail
) 4)))
1273 (let* ((byte (aref string start
))
1274 (bits (char-code byte
)))
1278 ;; Exited from the loop normally
1280 ;; Exited via CATCH. Skip the current character
1281 ;; and try the inner loop again.
1284 (flush-output-buffer stream
)))
1286 (flush-output-buffer stream
))))
1287 (def-output-routines (,format
1293 (if (eql byte
#\Newline
)
1294 (setf (fd-stream-char-pos stream
) 0)
1295 (incf (fd-stream-char-pos stream
)))
1296 (let* ((obuf (fd-stream-obuf stream
))
1297 (bits (char-code byte
))
1298 (sap (buffer-sap obuf
))
1299 (tail (buffer-tail obuf
)))
1301 (defun ,in-function
(stream buffer start requested eof-error-p
1302 &aux
(index start
) (end (+ start requested
)))
1303 (declare (type fd-stream stream
)
1304 (type index start requested index end
)
1306 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1308 (let ((unread (fd-stream-unread stream
)))
1310 (setf (aref buffer index
) unread
)
1311 (setf (fd-stream-unread stream
) nil
)
1312 (setf (fd-stream-listen stream
) nil
)
1316 (let* ((ibuf (fd-stream-ibuf stream
))
1317 (head (buffer-head ibuf
))
1318 (tail (buffer-tail ibuf
))
1319 (sap (buffer-sap ibuf
)))
1320 (declare (type index head tail
)
1321 (type system-area-pointer sap
))
1322 ;; Copy data from stream buffer into user's buffer.
1323 (dotimes (i (min (truncate (- tail head
) ,size
)
1325 (declare (optimize speed
))
1326 (let* ((byte (sap-ref-8 sap head
)))
1327 (setf (aref buffer index
) ,in-expr
)
1330 (setf (buffer-head ibuf
) head
)
1331 ;; Maybe we need to refill the stream buffer.
1332 (cond ( ;; If there was enough data in the stream buffer, we're done.
1334 (return (- index start
)))
1335 ( ;; If EOF, we're done in another way.
1336 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1338 (error 'end-of-file
:stream stream
)
1339 (return (- index start
))))
1340 ;; Otherwise we refilled the stream buffer, so fall
1341 ;; through into another pass of the loop.
1343 (def-input-routine ,in-char-function
(character ,size sap head
)
1344 (let ((byte (sap-ref-8 sap head
)))
1346 (defun ,read-c-string-function
(sap element-type
)
1347 (declare (type system-area-pointer sap
)
1348 (type (member character base-char
) element-type
))
1350 (declare (optimize (speed 3) (safety 0)))
1351 (let* ((stream ,name
)
1353 (loop for head of-type index upfrom
0 by
,size
1354 for count of-type index upto
(1- array-dimension-limit
)
1355 for byte
= (sap-ref-8 sap head
)
1356 for char of-type character
= ,in-expr
1357 until
(zerop (char-code char
))
1358 finally
(return count
)))
1359 ;; Inline the common cases
1360 (string (make-string length
:element-type element-type
)))
1361 (declare (ignorable stream
)
1363 (type simple-string string
))
1364 (/show0 before-copy-loop
)
1365 (loop for head of-type index upfrom
0 by
,size
1366 for index of-type index below length
1367 for byte
= (sap-ref-8 sap head
)
1368 for char of-type character
= ,in-expr
1369 do
(setf (aref string index
) char
))
1370 string
))) ;; last loop rewrite to dotimes?
1371 (defun ,output-c-string-function
(string)
1372 (declare (type simple-string string
))
1374 (declare (optimize (speed 3) (safety 0)))
1375 (let* ((length (length string
))
1376 (,n-buffer
(make-array (* (1+ length
) ,size
)
1377 :element-type
'(unsigned-byte 8)))
1380 (declare (type index length tail
))
1381 (with-pinned-objects (,n-buffer
)
1382 (let ((sap (vector-sap ,n-buffer
)))
1383 (declare (system-area-pointer sap
))
1385 (let* ((byte (aref string i
))
1386 (bits (char-code byte
)))
1387 (declare (ignorable byte bits
))
1391 (byte (code-char bits
)))
1392 (declare (ignorable bits byte
))
1395 (setf *external-formats
*
1396 (cons '(,external-format
,in-function
,in-char-function
,out-function
1397 ,@(mapcar #'(lambda (buffering)
1398 (intern (format nil format
(string buffering
))))
1399 '(:none
:line
:full
))
1400 nil
; no resync-function
1401 ,size-function
,read-c-string-function
,output-c-string-function
)
1402 *external-formats
*)))))
1404 (defmacro define-external-format
/variable-width
1405 (external-format output-restart out-size-expr
1406 out-expr in-size-expr in-expr
)
1407 (let* ((name (first external-format
))
1408 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1409 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1410 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1411 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1412 (resync-function (symbolicate "RESYNC/" name
))
1413 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1414 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1415 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1416 (n-buffer (gensym "BUFFER")))
1418 (defun ,size-function
(byte)
1419 (declare (ignorable byte
))
1421 (defun ,out-function
(stream string flush-p start end
)
1422 (let ((start (or start
0))
1423 (end (or end
(length string
))))
1424 (declare (type index start end
))
1425 (synchronize-stream-output stream
)
1426 (unless (<= 0 start end
(length string
))
1427 (sequence-bounding-indices-bad string start end
))
1430 (let ((obuf (fd-stream-obuf stream
)))
1431 (setf (buffer-tail obuf
)
1432 (string-dispatch (simple-base-string
1434 (simple-array character
(*))
1437 (let ((len (buffer-length obuf
))
1438 (sap (buffer-sap obuf
))
1440 (tail (buffer-tail obuf
)))
1441 (declare (type index tail
)
1442 ;; STRING bounds have already been checked.
1443 (optimize (safety 0)))
1445 (,@(if output-restart
1446 `(catch 'output-nothing
)
1449 ((or (= start end
) (< (- len tail
) 4)))
1450 (let* ((byte (aref string start
))
1451 (bits (char-code byte
))
1452 (size ,out-size-expr
))
1456 ;; Exited from the loop normally
1458 ;; Exited via CATCH. Skip the current character
1459 ;; and try the inner loop again.
1462 (flush-output-buffer stream
)))
1464 (flush-output-buffer stream
))))
1465 (def-output-routines/variable-width
(,format
1472 (if (eql byte
#\Newline
)
1473 (setf (fd-stream-char-pos stream
) 0)
1474 (incf (fd-stream-char-pos stream
)))
1475 (let ((bits (char-code byte
))
1476 (sap (buffer-sap obuf
))
1477 (tail (buffer-tail obuf
)))
1479 (defun ,in-function
(stream buffer start requested eof-error-p
1480 &aux
(total-copied 0))
1481 (declare (type fd-stream stream
)
1482 (type index start requested total-copied
)
1484 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1486 (let ((unread (fd-stream-unread stream
)))
1488 (setf (aref buffer start
) unread
)
1489 (setf (fd-stream-unread stream
) nil
)
1490 (setf (fd-stream-listen stream
) nil
)
1491 (incf total-copied
)))
1494 (let* ((ibuf (fd-stream-ibuf stream
))
1495 (head (buffer-head ibuf
))
1496 (tail (buffer-tail ibuf
))
1497 (sap (buffer-sap ibuf
))
1498 (decode-break-reason nil
))
1499 (declare (type index head tail
))
1500 ;; Copy data from stream buffer into user's buffer.
1501 (do ((size nil nil
))
1502 ((or (= tail head
) (= requested total-copied
)))
1503 (setf decode-break-reason
1504 (block decode-break-reason
1505 (let ((byte (sap-ref-8 sap head
)))
1506 (declare (ignorable byte
))
1507 (setq size
,in-size-expr
)
1508 (when (> size
(- tail head
))
1510 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1514 (setf (buffer-head ibuf
) head
)
1515 (when decode-break-reason
1516 ;; If we've already read some characters on when the invalid
1517 ;; code sequence is detected, we return immediately. The
1518 ;; handling of the error is deferred until the next call
1519 ;; (where this check will be false). This allows establishing
1520 ;; high-level handlers for decode errors (for example
1521 ;; automatically resyncing in Lisp comments).
1522 (when (plusp total-copied
)
1523 (return-from ,in-function total-copied
))
1524 (when (stream-decoding-error-and-handle
1525 stream decode-break-reason
)
1527 (error 'end-of-file
:stream stream
)
1528 (return-from ,in-function total-copied
)))
1529 (setf head
(buffer-head ibuf
))
1530 (setf tail
(buffer-tail ibuf
))))
1531 (setf (buffer-head ibuf
) head
)
1532 ;; Maybe we need to refill the stream buffer.
1533 (cond ( ;; If there were enough data in the stream buffer, we're done.
1534 (= total-copied requested
)
1535 (return total-copied
))
1536 ( ;; If EOF, we're done in another way.
1537 (or (eq decode-break-reason
'eof
)
1538 (null (catch 'eof-input-catcher
1539 (refill-input-buffer stream
))))
1541 (error 'end-of-file
:stream stream
)
1542 (return total-copied
)))
1543 ;; Otherwise we refilled the stream buffer, so fall
1544 ;; through into another pass of the loop.
1546 (def-input-routine/variable-width
,in-char-function
(character
1550 (let ((byte (sap-ref-8 sap head
)))
1551 (declare (ignorable byte
))
1553 (defun ,resync-function
(stream)
1554 (let ((ibuf (fd-stream-ibuf stream
)))
1556 (input-at-least stream
2)
1557 (incf (buffer-head ibuf
))
1558 (unless (block decode-break-reason
1559 (let* ((sap (buffer-sap ibuf
))
1560 (head (buffer-head ibuf
))
1561 (byte (sap-ref-8 sap head
))
1562 (size ,in-size-expr
))
1563 (declare (ignorable byte
))
1564 (input-at-least stream size
)
1565 (setf head
(buffer-head ibuf
))
1569 (defun ,read-c-string-function
(sap element-type
)
1570 (declare (type system-area-pointer sap
))
1572 (declare (optimize (speed 3) (safety 0)))
1573 (let* ((stream ,name
)
1574 (size 0) (head 0) (byte 0) (char nil
)
1575 (decode-break-reason nil
)
1576 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1577 (setf decode-break-reason
1578 (block decode-break-reason
1579 (setf byte
(sap-ref-8 sap head
)
1584 (when decode-break-reason
1585 (c-string-decoding-error ,name decode-break-reason
))
1586 (when (zerop (char-code char
))
1588 (string (make-string length
:element-type element-type
)))
1589 (declare (ignorable stream
)
1590 (type index head length
) ;; size
1591 (type (unsigned-byte 8) byte
)
1592 (type (or null character
) char
)
1593 (type string string
))
1595 (dotimes (index length string
)
1596 (setf decode-break-reason
1597 (block decode-break-reason
1598 (setf byte
(sap-ref-8 sap head
)
1603 (when decode-break-reason
1604 (c-string-decoding-error ,name decode-break-reason
))
1605 (setf (aref string index
) char
)))))
1607 (defun ,output-c-string-function
(string)
1608 (declare (type simple-string string
))
1610 (declare (optimize (speed 3) (safety 0)))
1611 (let* ((length (length string
))
1612 (char-length (make-array (1+ length
) :element-type
'index
))
1614 (+ (loop for i of-type index below length
1615 for byte of-type character
= (aref string i
)
1616 for bits
= (char-code byte
)
1617 sum
(setf (aref char-length i
)
1618 (the index
,out-size-expr
)))
1619 (let* ((byte (code-char 0))
1620 (bits (char-code byte
)))
1621 (declare (ignorable byte bits
))
1622 (setf (aref char-length length
)
1623 (the index
,out-size-expr
)))))
1625 (,n-buffer
(make-array buffer-length
1626 :element-type
'(unsigned-byte 8)))
1628 (declare (type index length buffer-length tail
)
1631 (with-pinned-objects (,n-buffer
)
1632 (let ((sap (vector-sap ,n-buffer
)))
1633 (declare (system-area-pointer sap
))
1634 (loop for i of-type index below length
1635 for byte of-type character
= (aref string i
)
1636 for bits
= (char-code byte
)
1637 for size of-type index
= (aref char-length i
)
1642 (byte (code-char bits
))
1643 (size (aref char-length length
)))
1644 (declare (ignorable bits byte size
))
1648 (setf *external-formats
*
1649 (cons '(,external-format
,in-function
,in-char-function
,out-function
1650 ,@(mapcar #'(lambda (buffering)
1651 (intern (format nil format
(string buffering
))))
1652 '(:none
:line
:full
))
1654 ,size-function
,read-c-string-function
,output-c-string-function
)
1655 *external-formats
*)))))
1657 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1658 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1659 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1660 (define-external-format (:latin-1
:latin1
:iso-8859-1
:iso8859-1
)
1663 (external-format-encoding-error stream bits
)
1664 (setf (sap-ref-8 sap tail
) bits
))
1667 (define-external-format (:ascii
:us-ascii
:ansi_x3.4-
1968
1668 :iso-646
:iso-646-us
:|
646|
)
1671 (external-format-encoding-error stream bits
)
1672 (setf (sap-ref-8 sap tail
) bits
))
1675 (let* ((table (let ((s (make-string 256)))
1676 (map-into s
#'code-char
1677 '(#x00
#x01
#x02
#x03
#x9c
#x09
#x86
#x7f
#x97
#x8d
#x8e
#x0b
#x0c
#x0d
#x0e
#x0f
1678 #x10
#x11
#x12
#x13
#x9d
#x85
#x08
#x87
#x18
#x19
#x92
#x8f
#x1c
#x1d
#x1e
#x1f
1679 #x80
#x81
#x82
#x83
#x84
#x0a
#x17
#x1b
#x88
#x89
#x8a
#x8b
#x8c
#x05
#x06
#x07
1680 #x90
#x91
#x16
#x93
#x94
#x95
#x96
#x04
#x98
#x99
#x9a
#x9b
#x14
#x15
#x9e
#x1a
1681 #x20
#xa0
#xe2
#xe4
#xe0
#xe1
#xe3
#xe5
#xe7
#xf1
#xa2
#x2e
#x3c
#x28
#x2b
#x7c
1682 #x26
#xe9
#xea
#xeb
#xe8
#xed
#xee
#xef
#xec
#xdf
#x21
#x24
#x2a
#x29
#x3b
#xac
1683 #x2d
#x2f
#xc2
#xc4
#xc0
#xc1
#xc3
#xc5
#xc7
#xd1
#xa6
#x2c
#x25
#x5f
#x3e
#x3f
1684 #xf8
#xc9
#xca
#xcb
#xc8
#xcd
#xce
#xcf
#xcc
#x60
#x3a
#x23
#x40
#x27
#x3d
#x22
1685 #xd8
#x61
#x62
#x63
#x64
#x65
#x66
#x67
#x68
#x69
#xab
#xbb
#xf0
#xfd
#xfe
#xb1
1686 #xb0
#x6a
#x6b
#x6c
#x6d
#x6e
#x6f
#x70
#x71
#x72
#xaa
#xba
#xe6
#xb8
#xc6
#xa4
1687 #xb5
#x7e
#x73
#x74
#x75
#x76
#x77
#x78
#x79
#x7a
#xa1
#xbf
#xd0
#xdd
#xde
#xae
1688 #x5e
#xa3
#xa5
#xb7
#xa9
#xa7
#xb6
#xbc
#xbd
#xbe
#x5b
#x5d
#xaf
#xa8
#xb4
#xd7
1689 #x7b
#x41
#x42
#x43
#x44
#x45
#x46
#x47
#x48
#x49
#xad
#xf4
#xf6
#xf2
#xf3
#xf5
1690 #x7d
#x4a
#x4b
#x4c
#x4d
#x4e
#x4f
#x50
#x51
#x52
#xb9
#xfb
#xfc
#xf9
#xfa
#xff
1691 #x5c
#xf7
#x53
#x54
#x55
#x56
#x57
#x58
#x59
#x5a
#xb2
#xd4
#xd6
#xd2
#xd3
#xd5
1692 #x30
#x31
#x32
#x33
#x34
#x35
#x36
#x37
#x38
#x39
#xb3
#xdb
#xdc
#xd9
#xda
#x9f
))
1694 (reverse-table (let ((rt (make-array 256 :element-type
'(unsigned-byte 8) :initial-element
0)))
1695 (loop for char across table for i from
0
1696 do
(aver (= 0 (aref rt
(char-code char
))))
1697 do
(setf (aref rt
(char-code char
)) i
))
1699 (define-external-format (:ebcdic-us
:ibm-037
:ibm037
)
1702 (external-format-encoding-error stream bits
)
1703 (setf (sap-ref-8 sap tail
) (aref reverse-table bits
)))
1708 (let ((latin-9-table (let ((table (make-string 256)))
1711 (setf (aref table i
) (code-char i
)))
1712 (setf (aref table
#xa4
) (code-char #x20ac
))
1713 (setf (aref table
#xa6
) (code-char #x0160
))
1714 (setf (aref table
#xa8
) (code-char #x0161
))
1715 (setf (aref table
#xb4
) (code-char #x017d
))
1716 (setf (aref table
#xb8
) (code-char #x017e
))
1717 (setf (aref table
#xbc
) (code-char #x0152
))
1718 (setf (aref table
#xbd
) (code-char #x0153
))
1719 (setf (aref table
#xbe
) (code-char #x0178
))
1721 (latin-9-reverse-1 (make-array 16
1722 :element-type
'(unsigned-byte 21)
1723 :initial-contents
'(#x0160
#x0161
#x0152
#x0153
0 0 0 0 #x0178
0 0 0 #x20ac
#x017d
#x017e
0)))
1724 (latin-9-reverse-2 (make-array 16
1725 :element-type
'(unsigned-byte 8)
1726 :initial-contents
'(#xa6
#xa8
#xbc
#xbd
0 0 0 0 #xbe
0 0 0 #xa4
#xb4
#xb8
0))))
1727 (define-external-format (:latin-9
:latin9
:iso-8859-15
:iso8859-15
)
1729 (setf (sap-ref-8 sap tail
)
1731 (if (= bits
(char-code (aref latin-9-table bits
)))
1733 (external-format-encoding-error stream byte
))
1734 (if (= (aref latin-9-reverse-1
(logand bits
15)) bits
)
1735 (aref latin-9-reverse-2
(logand bits
15))
1736 (external-format-encoding-error stream byte
))))
1737 (aref latin-9-table byte
)))
1739 (define-external-format/variable-width
(:utf-8
:utf8
) nil
1740 (let ((bits (char-code byte
)))
1741 (cond ((< bits
#x80
) 1)
1743 ((< bits
#x10000
) 3)
1746 (1 (setf (sap-ref-8 sap tail
) bits
))
1747 (2 (setf (sap-ref-8 sap tail
) (logior #xc0
(ldb (byte 5 6) bits
))
1748 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 0) bits
))))
1749 (3 (setf (sap-ref-8 sap tail
) (logior #xe0
(ldb (byte 4 12) bits
))
1750 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 6) bits
))
1751 (sap-ref-8 sap
(+ 2 tail
)) (logior #x80
(ldb (byte 6 0) bits
))))
1752 (4 (setf (sap-ref-8 sap tail
) (logior #xf0
(ldb (byte 3 18) bits
))
1753 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 12) bits
))
1754 (sap-ref-8 sap
(+ 2 tail
)) (logior #x80
(ldb (byte 6 6) bits
))
1755 (sap-ref-8 sap
(+ 3 tail
)) (logior #x80
(ldb (byte 6 0) bits
)))))
1756 (cond ((< byte
#x80
) 1)
1757 ((< byte
#xc2
) (return-from decode-break-reason
1))
1761 (code-char (ecase size
1763 (2 (let ((byte2 (sap-ref-8 sap
(1+ head
))))
1764 (unless (<= #x80 byte2
#xbf
)
1765 (return-from decode-break-reason
2))
1766 (dpb byte
(byte 5 6) byte2
)))
1767 (3 (let ((byte2 (sap-ref-8 sap
(1+ head
)))
1768 (byte3 (sap-ref-8 sap
(+ 2 head
))))
1769 (unless (and (<= #x80 byte2
#xbf
)
1770 (<= #x80 byte3
#xbf
))
1771 (return-from decode-break-reason
3))
1772 (dpb byte
(byte 4 12) (dpb byte2
(byte 6 6) byte3
))))
1773 (4 (let ((byte2 (sap-ref-8 sap
(1+ head
)))
1774 (byte3 (sap-ref-8 sap
(+ 2 head
)))
1775 (byte4 (sap-ref-8 sap
(+ 3 head
))))
1776 (unless (and (<= #x80 byte2
#xbf
)
1777 (<= #x80 byte3
#xbf
)
1778 (<= #x80 byte4
#xbf
))
1779 (return-from decode-break-reason
4))
1780 (dpb byte
(byte 3 18)
1781 (dpb byte2
(byte 6 12)
1782 (dpb byte3
(byte 6 6) byte4
))))))))
1784 ;;;; utility functions (misc routines, etc)
1786 ;;; Fill in the various routine slots for the given type. INPUT-P and
1787 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1788 ;;; set prior to calling this routine.
1789 (defun set-fd-stream-routines (fd-stream element-type external-format
1790 input-p output-p buffer-p
)
1791 (let* ((target-type (case element-type
1792 (unsigned-byte '(unsigned-byte 8))
1793 (signed-byte '(signed-byte 8))
1794 (:default
'character
)
1796 (character-stream-p (subtypep target-type
'character
))
1797 (bivalent-stream-p (eq element-type
:default
))
1798 normalized-external-format
1799 (bin-routine #'ill-bin
)
1802 (cin-routine #'ill-in
)
1805 (input-type nil
) ;calculated from bin-type/cin-type
1806 (input-size nil
) ;calculated from bin-size/cin-size
1807 (read-n-characters #'ill-in
)
1808 (bout-routine #'ill-bout
)
1811 (cout-routine #'ill-out
)
1816 (output-bytes #'ill-bout
))
1818 ;; Ensure that we have buffers in the desired direction(s) only,
1819 ;; getting new ones and dropping/resetting old ones as necessary.
1820 (let ((obuf (fd-stream-obuf fd-stream
)))
1824 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1826 (setf (fd-stream-obuf fd-stream
) nil
)
1827 (release-buffer obuf
))))
1829 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1833 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1835 (setf (fd-stream-ibuf fd-stream
) nil
)
1836 (release-buffer ibuf
))))
1838 ;; FIXME: Why only for output? Why unconditionally?
1840 (setf (fd-stream-char-pos fd-stream
) 0))
1842 (when (and character-stream-p
1843 (eq external-format
:default
))
1844 (/show0
"/getting default external format")
1845 (setf external-format
(default-external-format)))
1848 (when (or (not character-stream-p
) bivalent-stream-p
)
1849 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1850 normalized-external-format
)
1851 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1855 (error "could not find any input routine for ~S" target-type
)))
1856 (when character-stream-p
1857 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1858 normalized-external-format
)
1859 (pick-input-routine target-type external-format
))
1861 (error "could not find any input routine for ~S" target-type
)))
1862 (setf (fd-stream-in fd-stream
) cin-routine
1863 (fd-stream-bin fd-stream
) bin-routine
)
1864 ;; character type gets preferential treatment
1865 (setf input-size
(or cin-size bin-size
))
1866 (setf input-type
(or cin-type bin-type
))
1867 (when normalized-external-format
1868 (setf (fd-stream-external-format fd-stream
)
1869 normalized-external-format
))
1870 (when (= (or cin-size
1) (or bin-size
1) 1)
1871 (setf (fd-stream-n-bin fd-stream
) ;XXX
1872 (if (and character-stream-p
(not bivalent-stream-p
))
1874 #'fd-stream-read-n-bytes
))
1875 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1876 ;; for character and (unsigned-byte 8) streams. In these
1877 ;; cases, fast-read-* will read from the
1878 ;; ansi-stream-(c)in-buffer, saving function calls.
1879 ;; Otherwise, the various data-reading functions in the stream
1880 ;; structure will be called.
1882 (not bivalent-stream-p
)
1883 ;; temporary disable on :io streams
1885 (cond (character-stream-p
1886 (setf (ansi-stream-cin-buffer fd-stream
)
1887 (make-array +ansi-stream-in-buffer-length
+
1888 :element-type
'character
)))
1889 ((equal target-type
'(unsigned-byte 8))
1890 (setf (ansi-stream-in-buffer fd-stream
)
1891 (make-array +ansi-stream-in-buffer-length
+
1892 :element-type
'(unsigned-byte 8))))))))
1895 (when (or (not character-stream-p
) bivalent-stream-p
)
1896 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1897 normalized-external-format
)
1898 (pick-output-routine (if bivalent-stream-p
1901 (fd-stream-buffering fd-stream
)
1903 (unless bout-routine
1904 (error "could not find any output routine for ~S buffered ~S"
1905 (fd-stream-buffering fd-stream
)
1907 (when character-stream-p
1908 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1909 normalized-external-format
)
1910 (pick-output-routine target-type
1911 (fd-stream-buffering fd-stream
)
1913 (unless cout-routine
1914 (error "could not find any output routine for ~S buffered ~S"
1915 (fd-stream-buffering fd-stream
)
1917 (when normalized-external-format
1918 (setf (fd-stream-external-format fd-stream
)
1919 normalized-external-format
))
1920 (when character-stream-p
1921 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1922 (setf (fd-stream-out fd-stream
) cout-routine
1923 (fd-stream-bout fd-stream
) bout-routine
1924 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1925 #'fd-sout
#'ill-out
))
1926 (setf output-size
(or cout-size bout-size
))
1927 (setf output-type
(or cout-type bout-type
)))
1929 (when (and input-size output-size
1930 (not (eq input-size output-size
)))
1931 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1932 input-type input-size
1933 output-type output-size
))
1934 (setf (fd-stream-element-size fd-stream
)
1935 (or input-size output-size
))
1937 (setf (fd-stream-element-type fd-stream
)
1938 (cond ((equal input-type output-type
)
1944 ((subtypep input-type output-type
)
1946 ((subtypep output-type input-type
)
1949 (error "Input type (~S) and output type (~S) are unrelated?"
1953 ;;; Handles the resource-release aspects of stream closing, and marks
1955 (defun release-fd-stream-resources (fd-stream)
1958 ;; Drop handlers first.
1959 (when (fd-stream-handler fd-stream
)
1960 (remove-fd-handler (fd-stream-handler fd-stream
))
1961 (setf (fd-stream-handler fd-stream
) nil
))
1962 ;; Disable interrupts so that a asynch unwind will not leave
1963 ;; us with a dangling finalizer (that would close the same
1964 ;; --possibly reassigned-- FD again), or a stream with a closed
1965 ;; FD that appears open.
1966 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1967 (set-closed-flame fd-stream
)
1968 (when (fboundp 'cancel-finalization
)
1969 (cancel-finalization fd-stream
)))
1970 ;; On error unwind from WITHOUT-INTERRUPTS.
1971 (serious-condition (e)
1973 ;; Release all buffers. If this is undone, or interrupted,
1974 ;; we're still safe: buffers have finalizers of their own.
1975 (release-fd-stream-buffers fd-stream
))
1977 ;;; Flushes the current input buffer and unread chatacter, and returns
1978 ;;; the input buffer, and the amount of of flushed input in bytes.
1979 (defun flush-input-buffer (stream)
1980 (let ((unread (if (fd-stream-unread stream
)
1983 (setf (fd-stream-unread stream
) nil
)
1984 (let ((ibuf (fd-stream-ibuf stream
)))
1986 (let ((head (buffer-head ibuf
))
1987 (tail (buffer-tail ibuf
)))
1988 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1989 (values nil unread
)))))
1991 (defun fd-stream-clear-input (stream)
1992 (flush-input-buffer stream
)
1995 (sb!win32
:fd-clear-input
(fd-stream-fd stream
))
1996 (setf (fd-stream-listen stream
) nil
))
1998 (catch 'eof-input-catcher
1999 (loop until
(sysread-may-block-p stream
)
2001 (refill-input-buffer stream
)
2002 (reset-buffer (fd-stream-ibuf stream
)))
2005 ;;; Handle miscellaneous operations on FD-STREAM.
2006 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
2007 (declare (ignore arg2
))
2010 (labels ((do-listen ()
2011 (let ((ibuf (fd-stream-ibuf fd-stream
)))
2012 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
2013 (fd-stream-listen fd-stream
)
2015 (sb!win32
:fd-listen
(fd-stream-fd fd-stream
))
2017 ;; If the read can block, LISTEN will certainly return NIL.
2018 (if (sysread-may-block-p fd-stream
)
2020 ;; Otherwise select(2) and CL:LISTEN have slightly
2021 ;; different semantics. The former returns that an FD
2022 ;; is readable when a read operation wouldn't block.
2023 ;; That includes EOF. However, LISTEN must return NIL
2025 (progn (catch 'eof-input-catcher
2026 ;; r-b/f too calls select, but it shouldn't
2027 ;; block as long as read can return once w/o
2029 (refill-input-buffer fd-stream
))
2030 ;; At this point either IBUF-HEAD != IBUF-TAIL
2031 ;; and FD-STREAM-LISTEN is NIL, in which case
2032 ;; we should return T, or IBUF-HEAD ==
2033 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2034 ;; which case we should return :EOF for this
2035 ;; call and all future LISTEN call on this stream.
2036 ;; Call ourselves again to determine which case
2041 (setf (fd-stream-unread fd-stream
) arg1
)
2042 (setf (fd-stream-listen fd-stream
) t
))
2044 (cond (arg1 ; We got us an abort on our hands.
2045 (let ((outputp (fd-stream-obuf fd-stream
))
2046 (file (fd-stream-file fd-stream
))
2047 (orig (fd-stream-original fd-stream
)))
2048 ;; This takes care of the important stuff -- everything
2049 ;; rest is cleaning up the file-system, which we cannot
2050 ;; do on some platforms as long as the file is open.
2051 (release-fd-stream-resources fd-stream
)
2052 ;; We can't do anything unless we know what file were
2053 ;; dealing with, and we don't want to do anything
2054 ;; strange unless we were writing to the file.
2055 (when (and outputp file
)
2057 ;; If the original is EQ to file we are appending to
2058 ;; and can just close the file without renaming.
2059 (unless (eq orig file
)
2060 ;; We have a handle on the original, just revert.
2061 (multiple-value-bind (okay err
)
2062 (sb!unix
:unix-rename orig file
)
2063 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2064 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2067 (error 'simple-stream-error
2069 "~@<Couldn't restore ~S to its original contents ~
2070 from ~S while closing ~S: ~2I~_~A~:>"
2072 (list file orig fd-stream
(strerror err
))
2073 :stream fd-stream
))))
2074 ;; We can't restore the original, and aren't
2075 ;; appending, so nuke that puppy.
2077 ;; FIXME: This is currently the fate of superseded
2078 ;; files, and according to the CLOSE spec this is
2079 ;; wrong. However, there seems to be no clean way to
2080 ;; do that that doesn't involve either copying the
2081 ;; data (bad if the :abort resulted from a full
2082 ;; disk), or renaming the old file temporarily
2083 ;; (probably bad because stream opening becomes more
2085 (multiple-value-bind (okay err
)
2086 (sb!unix
:unix-unlink file
)
2088 (error 'simple-file-error
2091 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2093 (list file fd-stream
(strerror err
)))))))))
2095 (finish-fd-stream-output fd-stream
)
2096 (let ((orig (fd-stream-original fd-stream
)))
2097 (when (and orig
(fd-stream-delete-original fd-stream
))
2098 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2100 (error 'simple-file-error
2103 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2105 (list orig fd-stream
(strerror err
)))))))
2106 ;; In case of no-abort close, don't *really* close the
2107 ;; stream until the last moment -- the cleaning up of the
2108 ;; original can be done first.
2109 (release-fd-stream-resources fd-stream
))))
2111 (fd-stream-clear-input fd-stream
))
2113 (flush-output-buffer fd-stream
))
2115 (finish-fd-stream-output fd-stream
))
2117 (fd-stream-element-type fd-stream
))
2119 (fd-stream-external-format fd-stream
))
2121 (= 1 (the (member 0 1)
2122 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2126 (fd-stream-char-pos fd-stream
))
2128 (unless (fd-stream-file fd-stream
)
2129 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2130 ;; "should signal an error of type TYPE-ERROR if stream is not
2131 ;; a stream associated with a file". Too bad there's no very
2132 ;; appropriate value for the EXPECTED-TYPE slot..
2133 (error 'simple-type-error
2135 :expected-type
'fd-stream
2136 :format-control
"~S is not a stream associated with a file."
2137 :format-arguments
(list fd-stream
)))
2138 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2139 atime mtime ctime blksize blocks
)
2140 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2141 (declare (ignore ino nlink uid gid rdev
2142 atime mtime ctime blksize blocks
))
2144 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2147 (truncate size
(fd-stream-element-size fd-stream
)))))
2148 (:file-string-length
2150 (character (fd-stream-character-size fd-stream arg1
))
2151 (string (fd-stream-string-size fd-stream arg1
))))
2154 (fd-stream-set-file-position fd-stream arg1
)
2155 (fd-stream-get-file-position fd-stream
)))))
2157 ;; FIXME: Think about this.
2159 ;; (defun finish-fd-stream-output (fd-stream)
2160 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2161 ;; (loop while (fd-stream-output-queue fd-stream)
2162 ;; ;; FIXME: SIGINT while waiting for a timeout will
2163 ;; ;; cause a timeout here.
2164 ;; do (when (and (not (serve-event timeout)) timeout)
2165 ;; (signal-timeout 'io-timeout
2166 ;; :stream fd-stream
2167 ;; :direction :write
2168 ;; :seconds timeout)))))
2170 (defun finish-fd-stream-output (stream)
2171 (flush-output-buffer stream
)
2173 ((null (fd-stream-output-queue stream
)))
2174 (serve-all-events)))
2176 (defun fd-stream-get-file-position (stream)
2177 (declare (fd-stream stream
))
2179 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2180 (declare (type (or (alien sb
!unix
:off-t
) null
) posn
))
2181 ;; We used to return NIL for errno==ESPIPE, and signal an error
2182 ;; in other failure cases. However, CLHS says to return NIL if
2183 ;; the position cannot be determined -- so that's what we do.
2184 (when (integerp posn
)
2185 ;; Adjust for buffered output: If there is any output
2186 ;; buffered, the *real* file position will be larger
2187 ;; than reported by lseek() because lseek() obviously
2188 ;; cannot take into account output we have not sent
2190 (dolist (buffer (fd-stream-output-queue stream
))
2191 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2192 (let ((obuf (fd-stream-obuf stream
)))
2194 (incf posn
(buffer-tail obuf
))))
2195 ;; Adjust for unread input: If there is any input
2196 ;; read from UNIX but not supplied to the user of the
2197 ;; stream, the *real* file position will smaller than
2198 ;; reported, because we want to look like the unread
2199 ;; stuff is still available.
2200 (let ((ibuf (fd-stream-ibuf stream
)))
2202 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2203 (when (fd-stream-unread stream
)
2205 ;; Divide bytes by element size.
2206 (truncate posn
(fd-stream-element-size stream
))))))
2208 (defun fd-stream-set-file-position (stream position-spec
)
2209 (declare (fd-stream stream
))
2210 (check-type position-spec
2211 (or (alien sb
!unix
:off-t
) (member nil
:start
:end
))
2212 "valid file position designator")
2215 ;; Make sure we don't have any output pending, because if we
2216 ;; move the file pointer before writing this stuff, it will be
2217 ;; written in the wrong location.
2218 (finish-fd-stream-output stream
)
2219 ;; Disable interrupts so that interrupt handlers doing output
2222 (unless (fd-stream-output-finished-p stream
)
2223 ;; We got interrupted and more output came our way during
2224 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2225 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2226 ;; so we prefer to do things like this...
2228 ;; Clear out any pending input to force the next read to go to
2230 (flush-input-buffer stream
)
2231 ;; Trash cached value for listen, so that we check next time.
2232 (setf (fd-stream-listen stream
) nil
)
2234 (multiple-value-bind (offset origin
)
2237 (values 0 sb
!unix
:l_set
))
2239 (values 0 sb
!unix
:l_xtnd
))
2241 (values (* position-spec
(fd-stream-element-size stream
))
2243 (declare (type (alien sb
!unix
:off-t
) offset
))
2244 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2246 ;; CLHS says to return true if the file-position was set
2247 ;; succesfully, and NIL otherwise. We are to signal an error
2248 ;; only if the given position was out of bounds, and that is
2249 ;; dealt with above. In times past we used to return NIL for
2250 ;; errno==ESPIPE, and signal an error in other cases.
2252 ;; FIXME: We are still liable to signal an error if flushing
2254 (return-from fd-stream-set-file-position
2255 (typep posn
'(alien sb
!unix
:off-t
))))))))
2258 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2260 ;;; Create a stream for the given Unix file descriptor.
2262 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2263 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2264 ;;; default to allowing input.
2266 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2268 ;;; BUFFERING indicates the kind of buffering to use.
2270 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2271 ;;; NIL (the default), then wait forever. When we time out, we signal
2274 ;;; FILE is the name of the file (will be returned by PATHNAME).
2276 ;;; NAME is used to identify the stream when printed.
2277 (defun make-fd-stream (fd
2280 (output nil output-p
)
2281 (element-type 'base-char
)
2283 (external-format :default
)
2292 (format nil
"file ~A" file
)
2293 (format nil
"descriptor ~W" fd
)))
2295 (declare (type index fd
) (type (or real null
) timeout
)
2296 (type (member :none
:line
:full
) buffering
))
2297 (cond ((not (or input-p output-p
))
2299 ((not (or input output
))
2300 (error "File descriptor must be opened either for input or output.")))
2301 (let ((stream (%make-fd-stream
:fd fd
2305 :delete-original delete-original
2307 :buffering buffering
2308 :dual-channel-p dual-channel-p
2309 :external-format external-format
2312 (coerce timeout
'single-float
)
2314 (set-fd-stream-routines stream element-type external-format
2315 input output input-buffer-p
)
2316 (when (and auto-close
(fboundp 'finalize
))
2319 (sb!unix
:unix-close fd
)
2321 (format *terminal-io
* "** closed file descriptor ~W **~%"
2326 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2327 ;;; :RENAME-AND-DELETE and :RENAME options.
2328 (defun pick-backup-name (name)
2329 (declare (type simple-string name
))
2330 (concatenate 'simple-string name
".bak"))
2332 ;;; Ensure that the given arg is one of the given list of valid
2333 ;;; things. Allow the user to fix any problems.
2334 (defun ensure-one-of (item list what
)
2335 (unless (member item list
)
2336 (error 'simple-type-error
2338 :expected-type
`(member ,@list
)
2339 :format-control
"~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2340 :format-arguments
(list item what list
))))
2342 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2343 ;;; access, since we don't want to trash unwritable files even if we
2344 ;;; technically can. We return true if we succeed in renaming.
2345 (defun rename-the-old-one (namestring original
)
2346 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2347 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2348 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2351 (error 'simple-file-error
2352 :pathname namestring
2354 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2355 :format-arguments
(list namestring original
(strerror err
))))))
2357 (defun open (filename
2360 (element-type 'base-char
)
2361 (if-exists nil if-exists-given
)
2362 (if-does-not-exist nil if-does-not-exist-given
)
2363 (external-format :default
)
2364 &aux
; Squelch assignment warning.
2365 (direction direction
)
2366 (if-does-not-exist if-does-not-exist
)
2367 (if-exists if-exists
))
2369 "Return a stream which reads from or writes to FILENAME.
2371 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2372 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2373 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2374 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2375 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2376 See the manual for details."
2378 ;; Calculate useful stuff.
2379 (multiple-value-bind (input output mask
)
2381 (:input
(values t nil sb
!unix
:o_rdonly
))
2382 (:output
(values nil t sb
!unix
:o_wronly
))
2383 (:io
(values t t sb
!unix
:o_rdwr
))
2384 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2385 (declare (type index mask
))
2386 (let* ((pathname (merge-pathnames filename
))
2388 (cond ((unix-namestring pathname input
))
2389 ((and input
(eq if-does-not-exist
:create
))
2390 (unix-namestring pathname nil
))
2391 ((and (eq direction
:io
) (not if-does-not-exist-given
))
2392 (unix-namestring pathname nil
)))))
2393 ;; Process if-exists argument if we are doing any output.
2395 (unless if-exists-given
2397 (if (eq (pathname-version pathname
) :newest
)
2400 (ensure-one-of if-exists
2401 '(:error
:new-version
:rename
2402 :rename-and-delete
:overwrite
2403 :append
:supersede nil
)
2406 ((:new-version
:error nil
)
2407 (setf mask
(logior mask sb
!unix
:o_excl
)))
2408 ((:rename
:rename-and-delete
)
2409 (setf mask
(logior mask sb
!unix
:o_creat
)))
2411 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2413 (setf mask
(logior mask sb
!unix
:o_append
)))))
2415 (setf if-exists
:ignore-this-arg
)))
2417 (unless if-does-not-exist-given
2418 (setf if-does-not-exist
2419 (cond ((eq direction
:input
) :error
)
2421 (member if-exists
'(:overwrite
:append
)))
2423 ((eq direction
:probe
)
2427 (ensure-one-of if-does-not-exist
2428 '(:error
:create nil
)
2430 (if (eq if-does-not-exist
:create
)
2431 (setf mask
(logior mask sb
!unix
:o_creat
)))
2433 (let ((original (case if-exists
2434 ((:rename
:rename-and-delete
)
2435 (pick-backup-name namestring
))
2436 ((:append
:overwrite
)
2437 ;; KLUDGE: Provent CLOSE from deleting
2438 ;; appending streams when called with :ABORT T
2440 (delete-original (eq if-exists
:rename-and-delete
))
2442 (when (and original
(not (eq original namestring
)))
2443 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2444 ;; whether the file already exists, make sure the original
2445 ;; file is not a directory, and keep the mode.
2448 (multiple-value-bind (okay err
/dev inode orig-mode
)
2449 (sb!unix
:unix-stat namestring
)
2450 (declare (ignore inode
)
2451 (type (or index null
) orig-mode
))
2454 (when (and output
(= (logand orig-mode
#o170000
)
2456 (error 'simple-file-error
2457 :pathname namestring
2459 "can't open ~S for output: is a directory"
2460 :format-arguments
(list namestring
)))
2461 (setf mode
(logand orig-mode
#o777
))
2463 ((eql err
/dev sb
!unix
:enoent
)
2466 (simple-file-perror "can't find ~S"
2470 (rename-the-old-one namestring original
))
2472 (setf delete-original nil
)
2473 ;; In order to use :SUPERSEDE instead, we have to make
2474 ;; sure SB!UNIX:O_CREAT corresponds to
2475 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2476 ;; because of IF-EXISTS being :RENAME.
2477 (unless (eq if-does-not-exist
:create
)
2479 (logior (logandc2 mask sb
!unix
:o_creat
)
2481 (setf if-exists
:supersede
))))
2483 ;; Now we can try the actual Unix open(2).
2484 (multiple-value-bind (fd errno
)
2486 (sb!unix
:unix-open namestring mask mode
)
2487 (values nil sb
!unix
:enoent
))
2488 (labels ((open-error (format-control &rest format-arguments
)
2489 (error 'simple-file-error
2491 :format-control format-control
2492 :format-arguments format-arguments
))
2493 (vanilla-open-error ()
2494 (simple-file-perror "error opening ~S" pathname errno
)))
2497 ((:input
:output
:io
)
2501 :element-type element-type
2502 :external-format external-format
2505 :delete-original delete-original
2512 (%make-fd-stream
:name namestring
2515 :element-type element-type
)))
2518 ((eql errno sb
!unix
:enoent
)
2519 (case if-does-not-exist
2520 (:error
(vanilla-open-error))
2522 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2525 ((and (eql errno sb
!unix
:eexist
) (null if-exists
))
2528 (vanilla-open-error)))))))))
2532 ;;; the stream connected to the controlling terminal, or NIL if there is none
2535 ;;; the stream connected to the standard input (file descriptor 0)
2538 ;;; the stream connected to the standard output (file descriptor 1)
2541 ;;; the stream connected to the standard error output (file descriptor 2)
2544 ;;; This is called when the cold load is first started up, and may also
2545 ;;; be called in an attempt to recover from nested errors.
2546 (defun stream-cold-init-or-reset ()
2548 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2549 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2550 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2551 (setf *error-output
* (make-synonym-stream '*stderr
*))
2552 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2553 (setf *debug-io
* *query-io
*)
2554 (setf *trace-output
* *standard-output
*)
2557 (defun stream-deinit ()
2558 ;; Unbind to make sure we're not accidently dealing with it
2559 ;; before we're ready (or after we think it's been deinitialized).
2560 (with-available-buffers-lock ()
2561 (without-package-locks
2562 (makunbound '*available-buffers
*))))
2564 ;;; This is called whenever a saved core is restarted.
2565 (defun stream-reinit (&optional init-buffers-p
)
2566 (when init-buffers-p
2567 (with-available-buffers-lock ()
2568 (aver (not (boundp '*available-buffers
*)))
2569 (setf *available-buffers
* nil
)))
2570 (with-output-to-string (*error-output
*)
2572 (make-fd-stream 0 :name
"standard input" :input t
:buffering
:line
2573 #!+win32
:external-format
#!+win32
(sb!win32
::console-input-codepage
)))
2575 (make-fd-stream 1 :name
"standard output" :output t
:buffering
:line
2576 #!+win32
:external-format
#!+win32
(sb!win32
::console-output-codepage
)))
2578 (make-fd-stream 2 :name
"standard error" :output t
:buffering
:line
2579 #!+win32
:external-format
#!+win32
(sb!win32
::console-output-codepage
)))
2580 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2581 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2585 :name
"the terminal"
2590 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))))
2591 (princ (get-output-stream-string *error-output
*) *stderr
*))
2596 ;;; the Unix way to beep
2597 (defun beep (stream)
2598 (write-char (code-char bell-char-code
) stream
)
2599 (finish-output stream
))
2601 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2602 ;;; by the filesys stuff to get and set the file name.
2604 ;;; FIXME: misleading name, screwy interface
2605 (defun file-name (stream &optional new-name
)
2606 (when (typep stream
'fd-stream
)
2608 (setf (fd-stream-pathname stream
) new-name
)
2609 (setf (fd-stream-file stream
)
2610 (unix-namestring new-name nil
))
2613 (fd-stream-pathname stream
)))))