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
))
849 ;; Check for blocking input before touching the stream, as if
850 ;; we happen to wait we are liable to be interrupted, and the
851 ;; interrupt handler may use the same stream.
852 (if (sysread-may-block-p stream
)
855 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
856 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
858 (closed-flame stream
)
860 (simple-stream-perror "couldn't read from ~S" stream errno
)
862 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
863 ;; to wait for input if read tells us EWOULDBLOCK.
864 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
))
865 (signal-timeout 'io-timeout
:stream stream
:direction
:read
866 :seconds
(fd-stream-timeout stream
)))
868 ;; Since the read should not block, we'll disable the
869 ;; interrupts here, so that we don't accidentally unwind and
870 ;; leave the stream in an inconsistent state.
872 ;; Check the buffer: if it is null, then someone has closed
873 ;; the stream from underneath us. This is not ment to fix
874 ;; multithreaded races, but to deal with interrupt handlers
875 ;; closing the stream.
876 (let* ((ibuf (or (fd-stream-ibuf stream
) (go :closed-flame
)))
877 (sap (buffer-sap ibuf
))
878 (length (buffer-length ibuf
))
879 (head (buffer-head ibuf
))
880 (tail (buffer-tail ibuf
)))
881 (declare (index length head tail
))
883 (cond ((eql head tail
)
884 ;; Buffer is empty, but not at yet reset -- make it so.
889 ;; Buffer has things in it, but they are not at the head
890 ;; -- move them there.
891 (let ((n (- tail head
)))
892 (system-area-ub8-copy sap head sap
0 n
)
894 (buffer-head ibuf
) head
896 (buffer-tail ibuf
) tail
)))))
897 (setf (fd-stream-listen stream
) nil
)
898 (setf (values count errno
)
899 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
904 (if (eql errno sb
!unix
:ewouldblock
)
908 (setf (fd-stream-listen stream
) :eof
)
909 (/show0
"THROWing EOF-INPUT-CATCHER")
910 (throw 'eof-input-catcher nil
))
912 ;; Success! (Do not use INCF, for sake of other threads.)
913 (setf (buffer-tail ibuf
) (+ count tail
)))))))
916 ;;; Make sure there are at least BYTES number of bytes in the input
917 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
918 (defmacro input-at-least
(stream bytes
)
919 (let ((stream-var (gensym "STREAM"))
920 (bytes-var (gensym "BYTES"))
921 (buffer-var (gensym "IBUF")))
922 `(let* ((,stream-var
,stream
)
924 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
926 (when (>= (- (buffer-tail ,buffer-var
)
927 (buffer-head ,buffer-var
))
930 (refill-input-buffer ,stream-var
)))))
932 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
934 (let ((stream-var (gensym "STREAM"))
935 (retry-var (gensym "RETRY"))
936 (element-var (gensym "ELT")))
937 `(let* ((,stream-var
,stream
)
938 (ibuf (fd-stream-ibuf ,stream-var
))
940 (if (fd-stream-unread ,stream-var
)
942 (fd-stream-unread ,stream-var
)
943 (setf (fd-stream-unread ,stream-var
) nil
)
944 (setf (fd-stream-listen ,stream-var
) nil
))
945 (let ((,element-var nil
)
946 (decode-break-reason nil
))
950 (catch 'eof-input-catcher
951 (setf decode-break-reason
952 (block decode-break-reason
953 (input-at-least ,stream-var
1)
954 (let* ((byte (sap-ref-8 (buffer-sap ibuf
)
955 (buffer-head ibuf
))))
956 (declare (ignorable byte
))
958 (input-at-least ,stream-var size
)
959 (setq ,element-var
(locally ,@read-forms
))
960 (setq ,retry-var nil
))
962 (when decode-break-reason
963 (stream-decoding-error-and-handle stream
964 decode-break-reason
))
966 (let ((octet-count (- (buffer-tail ibuf
)
967 (buffer-head ibuf
))))
968 (when (or (zerop octet-count
)
969 (and (not ,element-var
)
970 (not decode-break-reason
)
971 (stream-decoding-error-and-handle
972 stream octet-count
)))
973 (setq ,retry-var nil
)))))
975 (incf (buffer-head ibuf
) size
)
978 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
980 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
981 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
982 (let ((stream-var (gensym "STREAM"))
983 (element-var (gensym "ELT")))
984 `(let* ((,stream-var
,stream
)
985 (ibuf (fd-stream-ibuf ,stream-var
)))
986 (if (fd-stream-unread ,stream-var
)
988 (fd-stream-unread ,stream-var
)
989 (setf (fd-stream-unread ,stream-var
) nil
)
990 (setf (fd-stream-listen ,stream-var
) nil
))
992 (catch 'eof-input-catcher
993 (input-at-least ,stream-var
,bytes
)
994 (locally ,@read-forms
))))
996 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
999 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1001 (defmacro def-input-routine
/variable-width
(name
1002 (type external-format size sap head
)
1005 (defun ,name
(stream eof-error eof-value
)
1006 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1007 (let ((,sap
(buffer-sap ibuf
))
1008 (,head
(buffer-head ibuf
)))
1010 (setf *input-routines
*
1011 (nconc *input-routines
*
1012 (list (list ',type
',name
1 ',external-format
))))))
1014 (defmacro def-input-routine
(name
1015 (type size sap head
)
1018 (defun ,name
(stream eof-error eof-value
)
1019 (input-wrapper (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
',size nil
))))))
1027 ;;; STREAM-IN routine for reading a string char
1028 (def-input-routine input-character
1029 (character 1 sap head
)
1030 (code-char (sap-ref-8 sap head
)))
1032 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1033 (def-input-routine input-unsigned-8bit-byte
1034 ((unsigned-byte 8) 1 sap head
)
1035 (sap-ref-8 sap head
))
1037 ;;; STREAM-IN routine for reading a signed 8 bit number
1038 (def-input-routine input-signed-8bit-number
1039 ((signed-byte 8) 1 sap head
)
1040 (signed-sap-ref-8 sap head
))
1042 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1043 (def-input-routine input-unsigned-16bit-byte
1044 ((unsigned-byte 16) 2 sap head
)
1045 (sap-ref-16 sap head
))
1047 ;;; STREAM-IN routine for reading a signed 16 bit number
1048 (def-input-routine input-signed-16bit-byte
1049 ((signed-byte 16) 2 sap head
)
1050 (signed-sap-ref-16 sap head
))
1052 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1053 (def-input-routine input-unsigned-32bit-byte
1054 ((unsigned-byte 32) 4 sap head
)
1055 (sap-ref-32 sap head
))
1057 ;;; STREAM-IN routine for reading a signed 32 bit number
1058 (def-input-routine input-signed-32bit-byte
1059 ((signed-byte 32) 4 sap head
)
1060 (signed-sap-ref-32 sap head
))
1062 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
1064 (def-input-routine input-unsigned-64bit-byte
1065 ((unsigned-byte 64) 8 sap head
)
1066 (sap-ref-64 sap head
))
1067 (def-input-routine input-signed-64bit-byte
1068 ((signed-byte 64) 8 sap head
)
1069 (signed-sap-ref-64 sap head
)))
1071 ;;; Find an input routine to use given the type. Return as multiple
1072 ;;; values the routine, the real type transfered, and the number of
1073 ;;; bytes per element (and for character types string input routine).
1074 (defun pick-input-routine (type &optional external-format
)
1075 (when (subtypep type
'character
)
1076 (dolist (entry *external-formats
*)
1077 (when (member external-format
(first entry
))
1078 (return-from pick-input-routine
1079 (values (symbol-function (third entry
))
1082 (symbol-function (second entry
))
1083 (first (first entry
)))))))
1084 (dolist (entry *input-routines
*)
1085 (when (and (subtypep type
(first entry
))
1086 (or (not (fourth entry
))
1087 (eq external-format
(fourth entry
))))
1088 (return-from pick-input-routine
1089 (values (symbol-function (second entry
))
1092 ;; FIXME: let's do it the hard way, then (but ignore things like
1093 ;; endianness, efficiency, and the necessary coupling between these
1094 ;; and the output routines). -- CSR, 2004-02-09
1095 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1096 if
(subtypep type
`(unsigned-byte ,i
))
1097 do
(return-from pick-input-routine
1099 (lambda (stream eof-error eof-value
)
1100 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1101 (let ((sap (buffer-sap ibuf
))
1102 (head (buffer-head ibuf
)))
1103 (loop for j from
0 below
(/ i
8)
1107 (sap-ref-8 sap
(+ head j
))))
1108 finally
(return result
)))))
1111 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1112 if
(subtypep type
`(signed-byte ,i
))
1113 do
(return-from pick-input-routine
1115 (lambda (stream eof-error eof-value
)
1116 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1117 (let ((sap (buffer-sap ibuf
))
1118 (head (buffer-head ibuf
)))
1119 (loop for j from
0 below
(/ i
8)
1123 (sap-ref-8 sap
(+ head j
))))
1124 finally
(return (if (logbitp (1- i
) result
)
1125 (dpb result
(byte i
0) -
1)
1130 ;;; the N-BIN method for FD-STREAMs
1132 ;;; Note that this blocks in UNIX-READ. It is generally used where
1133 ;;; there is a definite amount of reading to be done, so blocking
1134 ;;; isn't too problematical.
1135 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1136 &aux
(total-copied 0))
1137 (declare (type fd-stream stream
))
1138 (declare (type index start requested total-copied
))
1139 (let ((unread (fd-stream-unread stream
)))
1141 ;; AVERs designed to fail when we have more complicated
1142 ;; character representations.
1143 (aver (typep unread
'base-char
))
1144 (aver (= (fd-stream-element-size stream
) 1))
1145 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1148 (system-area-pointer
1149 (setf (sap-ref-8 buffer start
) (char-code unread
)))
1150 ((simple-unboxed-array (*))
1151 (setf (aref buffer start
) unread
)))
1152 (setf (fd-stream-unread stream
) nil
)
1153 (setf (fd-stream-listen stream
) nil
)
1154 (incf total-copied
)))
1157 (let* ((remaining-request (- requested total-copied
))
1158 (ibuf (fd-stream-ibuf stream
))
1159 (head (buffer-head ibuf
))
1160 (tail (buffer-tail ibuf
))
1161 (available (- tail head
))
1162 (n-this-copy (min remaining-request available
))
1163 (this-start (+ start total-copied
))
1164 (this-end (+ this-start n-this-copy
))
1165 (sap (buffer-sap ibuf
)))
1166 (declare (type index remaining-request head tail available
))
1167 (declare (type index n-this-copy
))
1168 ;; Copy data from stream buffer into user's buffer.
1169 (%byte-blt sap head buffer this-start this-end
)
1170 (incf (buffer-head ibuf
) n-this-copy
)
1171 (incf total-copied n-this-copy
)
1172 ;; Maybe we need to refill the stream buffer.
1173 (cond (;; If there were enough data in the stream buffer, we're done.
1174 (eql total-copied requested
)
1175 (return total-copied
))
1176 (;; If EOF, we're done in another way.
1177 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1179 (error 'end-of-file
:stream stream
)
1180 (return total-copied
)))
1181 ;; Otherwise we refilled the stream buffer, so fall
1182 ;; through into another pass of the loop.
1185 (defun fd-stream-resync (stream)
1186 (dolist (entry *external-formats
*)
1187 (when (member (fd-stream-external-format stream
) (first entry
))
1188 (return-from fd-stream-resync
1189 (funcall (symbol-function (eighth entry
)) stream
)))))
1191 (defun get-fd-stream-character-sizer (stream)
1192 (dolist (entry *external-formats
*)
1193 (when (member (fd-stream-external-format stream
) (first entry
))
1194 (return-from get-fd-stream-character-sizer
(ninth entry
)))))
1196 (defun fd-stream-character-size (stream char
)
1197 (let ((sizer (get-fd-stream-character-sizer stream
)))
1198 (when sizer
(funcall sizer char
))))
1200 (defun fd-stream-string-size (stream string
)
1201 (let ((sizer (get-fd-stream-character-sizer stream
)))
1203 (loop for char across string summing
(funcall sizer char
)))))
1205 (defun find-external-format (external-format)
1206 (when external-format
1207 (find external-format
*external-formats
* :test
#'member
:key
#'car
)))
1209 (defun variable-width-external-format-p (ef-entry)
1210 (when (eighth ef-entry
) t
))
1212 (defun bytes-for-char-fun (ef-entry)
1213 (if ef-entry
(symbol-function (ninth ef-entry
)) (constantly 1)))
1215 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1216 (defmacro define-external-format
(external-format size output-restart
1218 (let* ((name (first external-format
))
1219 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1220 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1221 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1222 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1223 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1224 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1225 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1226 (n-buffer (gensym "BUFFER")))
1228 (defun ,size-function
(byte)
1229 (declare (ignore byte
))
1231 (defun ,out-function
(stream string flush-p start end
)
1232 (let ((start (or start
0))
1233 (end (or end
(length string
))))
1234 (declare (type index start end
))
1235 (synchronize-stream-output stream
)
1236 (unless (<= 0 start end
(length string
))
1237 (signal-bounding-indices-bad-error string start end
))
1240 (let ((obuf (fd-stream-obuf stream
)))
1241 (setf (buffer-tail obuf
)
1242 (string-dispatch (simple-base-string
1244 (simple-array character
(*))
1247 (let ((sap (buffer-sap obuf
))
1248 (len (buffer-length obuf
))
1250 (tail (buffer-tail obuf
)))
1251 (declare (type index tail
)
1252 ;; STRING bounds have already been checked.
1253 (optimize (safety 0)))
1255 (,@(if output-restart
1256 `(catch 'output-nothing
)
1259 ((or (= start end
) (< (- len tail
) 4)))
1260 (let* ((byte (aref string start
))
1261 (bits (char-code byte
)))
1265 ;; Exited from the loop normally
1267 ;; Exited via CATCH. Skip the current character
1268 ;; and try the inner loop again.
1271 (flush-output-buffer stream
)))
1273 (flush-output-buffer stream
))))
1274 (def-output-routines (,format
1280 (if (eql byte
#\Newline
)
1281 (setf (fd-stream-char-pos stream
) 0)
1282 (incf (fd-stream-char-pos stream
)))
1283 (let* ((obuf (fd-stream-obuf stream
))
1284 (bits (char-code byte
))
1285 (sap (buffer-sap obuf
))
1286 (tail (buffer-tail obuf
)))
1288 (defun ,in-function
(stream buffer start requested eof-error-p
1289 &aux
(index start
) (end (+ start requested
)))
1290 (declare (type fd-stream stream
)
1291 (type index start requested index end
)
1293 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1295 (let ((unread (fd-stream-unread stream
)))
1297 (setf (aref buffer index
) unread
)
1298 (setf (fd-stream-unread stream
) nil
)
1299 (setf (fd-stream-listen stream
) nil
)
1303 (let* ((ibuf (fd-stream-ibuf stream
))
1304 (head (buffer-head ibuf
))
1305 (tail (buffer-tail ibuf
))
1306 (sap (buffer-sap ibuf
)))
1307 (declare (type index head tail
)
1308 (type system-area-pointer sap
))
1309 ;; Copy data from stream buffer into user's buffer.
1310 (dotimes (i (min (truncate (- tail head
) ,size
)
1312 (declare (optimize speed
))
1313 (let* ((byte (sap-ref-8 sap head
)))
1314 (setf (aref buffer index
) ,in-expr
)
1317 (setf (buffer-head ibuf
) head
)
1318 ;; Maybe we need to refill the stream buffer.
1319 (cond ( ;; If there was enough data in the stream buffer, we're done.
1321 (return (- index start
)))
1322 ( ;; If EOF, we're done in another way.
1323 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1325 (error 'end-of-file
:stream stream
)
1326 (return (- index start
))))
1327 ;; Otherwise we refilled the stream buffer, so fall
1328 ;; through into another pass of the loop.
1330 (def-input-routine ,in-char-function
(character ,size sap head
)
1331 (let ((byte (sap-ref-8 sap head
)))
1333 (defun ,read-c-string-function
(sap element-type
)
1334 (declare (type system-area-pointer sap
)
1335 (type (member character base-char
) element-type
))
1337 (declare (optimize (speed 3) (safety 0)))
1338 (let* ((stream ,name
)
1340 (loop for head of-type index upfrom
0 by
,size
1341 for count of-type index upto
(1- array-dimension-limit
)
1342 for byte
= (sap-ref-8 sap head
)
1343 for char of-type character
= ,in-expr
1344 until
(zerop (char-code char
))
1345 finally
(return count
)))
1346 ;; Inline the common cases
1347 (string (make-string length
:element-type element-type
)))
1348 (declare (ignorable stream
)
1350 (type simple-string string
))
1351 (/show0 before-copy-loop
)
1352 (loop for head of-type index upfrom
0 by
,size
1353 for index of-type index below length
1354 for byte
= (sap-ref-8 sap head
)
1355 for char of-type character
= ,in-expr
1356 do
(setf (aref string index
) char
))
1357 string
))) ;; last loop rewrite to dotimes?
1358 (defun ,output-c-string-function
(string)
1359 (declare (type simple-string string
))
1361 (declare (optimize (speed 3) (safety 0)))
1362 (let* ((length (length string
))
1363 (,n-buffer
(make-array (* (1+ length
) ,size
)
1364 :element-type
'(unsigned-byte 8)))
1367 (declare (type index length tail
))
1368 (with-pinned-objects (,n-buffer
)
1369 (let ((sap (vector-sap ,n-buffer
)))
1370 (declare (system-area-pointer sap
))
1372 (let* ((byte (aref string i
))
1373 (bits (char-code byte
)))
1374 (declare (ignorable byte bits
))
1378 (byte (code-char bits
)))
1379 (declare (ignorable bits byte
))
1382 (setf *external-formats
*
1383 (cons '(,external-format
,in-function
,in-char-function
,out-function
1384 ,@(mapcar #'(lambda (buffering)
1385 (intern (format nil format
(string buffering
))))
1386 '(:none
:line
:full
))
1387 nil
; no resync-function
1388 ,size-function
,read-c-string-function
,output-c-string-function
)
1389 *external-formats
*)))))
1391 (defmacro define-external-format
/variable-width
1392 (external-format output-restart out-size-expr
1393 out-expr in-size-expr in-expr
)
1394 (let* ((name (first external-format
))
1395 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1396 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1397 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1398 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1399 (resync-function (symbolicate "RESYNC/" name
))
1400 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1401 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1402 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1403 (n-buffer (gensym "BUFFER")))
1405 (defun ,size-function
(byte)
1406 (declare (ignorable byte
))
1408 (defun ,out-function
(stream string flush-p start end
)
1409 (let ((start (or start
0))
1410 (end (or end
(length string
))))
1411 (declare (type index start end
))
1412 (synchronize-stream-output stream
)
1413 (unless (<= 0 start end
(length string
))
1414 (signal-bounding-indices-bad-error string start end
))
1417 (let ((obuf (fd-stream-obuf stream
)))
1418 (setf (buffer-tail obuf
)
1419 (string-dispatch (simple-base-string
1421 (simple-array character
(*))
1424 (let ((len (buffer-length obuf
))
1425 (sap (buffer-sap obuf
))
1427 (tail (buffer-tail obuf
)))
1428 (declare (type index tail
)
1429 ;; STRING bounds have already been checked.
1430 (optimize (safety 0)))
1432 (,@(if output-restart
1433 `(catch 'output-nothing
)
1436 ((or (= start end
) (< (- len tail
) 4)))
1437 (let* ((byte (aref string start
))
1438 (bits (char-code byte
))
1439 (size ,out-size-expr
))
1443 ;; Exited from the loop normally
1445 ;; Exited via CATCH. Skip the current character
1446 ;; and try the inner loop again.
1449 (flush-output-buffer stream
)))
1451 (flush-output-buffer stream
))))
1452 (def-output-routines/variable-width
(,format
1459 (if (eql byte
#\Newline
)
1460 (setf (fd-stream-char-pos stream
) 0)
1461 (incf (fd-stream-char-pos stream
)))
1462 (let ((bits (char-code byte
))
1463 (sap (buffer-sap obuf
))
1464 (tail (buffer-tail obuf
)))
1466 (defun ,in-function
(stream buffer start requested eof-error-p
1467 &aux
(total-copied 0))
1468 (declare (type fd-stream stream
)
1469 (type index start requested total-copied
)
1471 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1473 (let ((unread (fd-stream-unread stream
)))
1475 (setf (aref buffer start
) unread
)
1476 (setf (fd-stream-unread stream
) nil
)
1477 (setf (fd-stream-listen stream
) nil
)
1478 (incf total-copied
)))
1481 (let* ((ibuf (fd-stream-ibuf stream
))
1482 (head (buffer-head ibuf
))
1483 (tail (buffer-tail ibuf
))
1484 (sap (buffer-sap ibuf
))
1485 (decode-break-reason nil
))
1486 (declare (type index head tail
))
1487 ;; Copy data from stream buffer into user's buffer.
1488 (do ((size nil nil
))
1489 ((or (= tail head
) (= requested total-copied
)))
1490 (setf decode-break-reason
1491 (block decode-break-reason
1492 (let ((byte (sap-ref-8 sap head
)))
1493 (declare (ignorable byte
))
1494 (setq size
,in-size-expr
)
1495 (when (> size
(- tail head
))
1497 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1501 (setf (buffer-head ibuf
) head
)
1502 (when decode-break-reason
1503 ;; If we've already read some characters on when the invalid
1504 ;; code sequence is detected, we return immediately. The
1505 ;; handling of the error is deferred until the next call
1506 ;; (where this check will be false). This allows establishing
1507 ;; high-level handlers for decode errors (for example
1508 ;; automatically resyncing in Lisp comments).
1509 (when (plusp total-copied
)
1510 (return-from ,in-function total-copied
))
1511 (when (stream-decoding-error-and-handle
1512 stream decode-break-reason
)
1514 (error 'end-of-file
:stream stream
)
1515 (return-from ,in-function total-copied
)))
1516 (setf head
(buffer-head ibuf
))
1517 (setf tail
(buffer-tail ibuf
))))
1518 (setf (buffer-head ibuf
) head
)
1519 ;; Maybe we need to refill the stream buffer.
1520 (cond ( ;; If there were enough data in the stream buffer, we're done.
1521 (= total-copied requested
)
1522 (return total-copied
))
1523 ( ;; If EOF, we're done in another way.
1524 (or (eq decode-break-reason
'eof
)
1525 (null (catch 'eof-input-catcher
1526 (refill-input-buffer stream
))))
1528 (error 'end-of-file
:stream stream
)
1529 (return total-copied
)))
1530 ;; Otherwise we refilled the stream buffer, so fall
1531 ;; through into another pass of the loop.
1533 (def-input-routine/variable-width
,in-char-function
(character
1537 (let ((byte (sap-ref-8 sap head
)))
1538 (declare (ignorable byte
))
1540 (defun ,resync-function
(stream)
1541 (let ((ibuf (fd-stream-ibuf stream
)))
1543 (input-at-least stream
2)
1544 (incf (buffer-head ibuf
))
1545 (unless (block decode-break-reason
1546 (let* ((sap (buffer-sap ibuf
))
1547 (head (buffer-head ibuf
))
1548 (byte (sap-ref-8 sap head
))
1549 (size ,in-size-expr
))
1550 (declare (ignorable byte
))
1551 (input-at-least stream size
)
1552 (setf head
(buffer-head ibuf
))
1556 (defun ,read-c-string-function
(sap element-type
)
1557 (declare (type system-area-pointer sap
))
1559 (declare (optimize (speed 3) (safety 0)))
1560 (let* ((stream ,name
)
1561 (size 0) (head 0) (byte 0) (char nil
)
1562 (decode-break-reason nil
)
1563 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1564 (setf decode-break-reason
1565 (block decode-break-reason
1566 (setf byte
(sap-ref-8 sap head
)
1571 (when decode-break-reason
1572 (c-string-decoding-error ,name decode-break-reason
))
1573 (when (zerop (char-code char
))
1575 (string (make-string length
:element-type element-type
)))
1576 (declare (ignorable stream
)
1577 (type index head length
) ;; size
1578 (type (unsigned-byte 8) byte
)
1579 (type (or null character
) char
)
1580 (type string string
))
1582 (dotimes (index length string
)
1583 (setf decode-break-reason
1584 (block decode-break-reason
1585 (setf byte
(sap-ref-8 sap head
)
1590 (when decode-break-reason
1591 (c-string-decoding-error ,name decode-break-reason
))
1592 (setf (aref string index
) char
)))))
1594 (defun ,output-c-string-function
(string)
1595 (declare (type simple-string string
))
1597 (declare (optimize (speed 3) (safety 0)))
1598 (let* ((length (length string
))
1599 (char-length (make-array (1+ length
) :element-type
'index
))
1601 (+ (loop for i of-type index below length
1602 for byte of-type character
= (aref string i
)
1603 for bits
= (char-code byte
)
1604 sum
(setf (aref char-length i
)
1605 (the index
,out-size-expr
)))
1606 (let* ((byte (code-char 0))
1607 (bits (char-code byte
)))
1608 (declare (ignorable byte bits
))
1609 (setf (aref char-length length
)
1610 (the index
,out-size-expr
)))))
1612 (,n-buffer
(make-array buffer-length
1613 :element-type
'(unsigned-byte 8)))
1615 (declare (type index length buffer-length tail
)
1618 (with-pinned-objects (,n-buffer
)
1619 (let ((sap (vector-sap ,n-buffer
)))
1620 (declare (system-area-pointer sap
))
1621 (loop for i of-type index below length
1622 for byte of-type character
= (aref string i
)
1623 for bits
= (char-code byte
)
1624 for size of-type index
= (aref char-length i
)
1629 (byte (code-char bits
))
1630 (size (aref char-length length
)))
1631 (declare (ignorable bits byte size
))
1635 (setf *external-formats
*
1636 (cons '(,external-format
,in-function
,in-char-function
,out-function
1637 ,@(mapcar #'(lambda (buffering)
1638 (intern (format nil format
(string buffering
))))
1639 '(:none
:line
:full
))
1641 ,size-function
,read-c-string-function
,output-c-string-function
)
1642 *external-formats
*)))))
1644 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1645 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1646 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1647 (define-external-format (:latin-1
:latin1
:iso-8859-1
:iso8859-1
)
1650 (external-format-encoding-error stream bits
)
1651 (setf (sap-ref-8 sap tail
) bits
))
1654 (define-external-format (:ascii
:us-ascii
:ansi_x3.4-
1968
1655 :iso-646
:iso-646-us
:|
646|
)
1658 (external-format-encoding-error stream bits
)
1659 (setf (sap-ref-8 sap tail
) bits
))
1662 (let* ((table (let ((s (make-string 256)))
1663 (map-into s
#'code-char
1664 '(#x00
#x01
#x02
#x03
#x9c
#x09
#x86
#x7f
#x97
#x8d
#x8e
#x0b
#x0c
#x0d
#x0e
#x0f
1665 #x10
#x11
#x12
#x13
#x9d
#x85
#x08
#x87
#x18
#x19
#x92
#x8f
#x1c
#x1d
#x1e
#x1f
1666 #x80
#x81
#x82
#x83
#x84
#x0a
#x17
#x1b
#x88
#x89
#x8a
#x8b
#x8c
#x05
#x06
#x07
1667 #x90
#x91
#x16
#x93
#x94
#x95
#x96
#x04
#x98
#x99
#x9a
#x9b
#x14
#x15
#x9e
#x1a
1668 #x20
#xa0
#xe2
#xe4
#xe0
#xe1
#xe3
#xe5
#xe7
#xf1
#xa2
#x2e
#x3c
#x28
#x2b
#x7c
1669 #x26
#xe9
#xea
#xeb
#xe8
#xed
#xee
#xef
#xec
#xdf
#x21
#x24
#x2a
#x29
#x3b
#xac
1670 #x2d
#x2f
#xc2
#xc4
#xc0
#xc1
#xc3
#xc5
#xc7
#xd1
#xa6
#x2c
#x25
#x5f
#x3e
#x3f
1671 #xf8
#xc9
#xca
#xcb
#xc8
#xcd
#xce
#xcf
#xcc
#x60
#x3a
#x23
#x40
#x27
#x3d
#x22
1672 #xd8
#x61
#x62
#x63
#x64
#x65
#x66
#x67
#x68
#x69
#xab
#xbb
#xf0
#xfd
#xfe
#xb1
1673 #xb0
#x6a
#x6b
#x6c
#x6d
#x6e
#x6f
#x70
#x71
#x72
#xaa
#xba
#xe6
#xb8
#xc6
#xa4
1674 #xb5
#x7e
#x73
#x74
#x75
#x76
#x77
#x78
#x79
#x7a
#xa1
#xbf
#xd0
#xdd
#xde
#xae
1675 #x5e
#xa3
#xa5
#xb7
#xa9
#xa7
#xb6
#xbc
#xbd
#xbe
#x5b
#x5d
#xaf
#xa8
#xb4
#xd7
1676 #x7b
#x41
#x42
#x43
#x44
#x45
#x46
#x47
#x48
#x49
#xad
#xf4
#xf6
#xf2
#xf3
#xf5
1677 #x7d
#x4a
#x4b
#x4c
#x4d
#x4e
#x4f
#x50
#x51
#x52
#xb9
#xfb
#xfc
#xf9
#xfa
#xff
1678 #x5c
#xf7
#x53
#x54
#x55
#x56
#x57
#x58
#x59
#x5a
#xb2
#xd4
#xd6
#xd2
#xd3
#xd5
1679 #x30
#x31
#x32
#x33
#x34
#x35
#x36
#x37
#x38
#x39
#xb3
#xdb
#xdc
#xd9
#xda
#x9f
))
1681 (reverse-table (let ((rt (make-array 256 :element-type
'(unsigned-byte 8) :initial-element
0)))
1682 (loop for char across table for i from
0
1683 do
(aver (= 0 (aref rt
(char-code char
))))
1684 do
(setf (aref rt
(char-code char
)) i
))
1686 (define-external-format (:ebcdic-us
:ibm-037
:ibm037
)
1689 (external-format-encoding-error stream bits
)
1690 (setf (sap-ref-8 sap tail
) (aref reverse-table bits
)))
1695 (let ((latin-9-table (let ((table (make-string 256)))
1698 (setf (aref table i
) (code-char i
)))
1699 (setf (aref table
#xa4
) (code-char #x20ac
))
1700 (setf (aref table
#xa6
) (code-char #x0160
))
1701 (setf (aref table
#xa8
) (code-char #x0161
))
1702 (setf (aref table
#xb4
) (code-char #x017d
))
1703 (setf (aref table
#xb8
) (code-char #x017e
))
1704 (setf (aref table
#xbc
) (code-char #x0152
))
1705 (setf (aref table
#xbd
) (code-char #x0153
))
1706 (setf (aref table
#xbe
) (code-char #x0178
))
1708 (latin-9-reverse-1 (make-array 16
1709 :element-type
'(unsigned-byte 21)
1710 :initial-contents
'(#x0160
#x0161
#x0152
#x0153
0 0 0 0 #x0178
0 0 0 #x20ac
#x017d
#x017e
0)))
1711 (latin-9-reverse-2 (make-array 16
1712 :element-type
'(unsigned-byte 8)
1713 :initial-contents
'(#xa6
#xa8
#xbc
#xbd
0 0 0 0 #xbe
0 0 0 #xa4
#xb4
#xb8
0))))
1714 (define-external-format (:latin-9
:latin9
:iso-8859-15
:iso8859-15
)
1716 (setf (sap-ref-8 sap tail
)
1718 (if (= bits
(char-code (aref latin-9-table bits
)))
1720 (external-format-encoding-error stream byte
))
1721 (if (= (aref latin-9-reverse-1
(logand bits
15)) bits
)
1722 (aref latin-9-reverse-2
(logand bits
15))
1723 (external-format-encoding-error stream byte
))))
1724 (aref latin-9-table byte
)))
1726 (define-external-format/variable-width
(:utf-8
:utf8
) nil
1727 (let ((bits (char-code byte
)))
1728 (cond ((< bits
#x80
) 1)
1730 ((< bits
#x10000
) 3)
1733 (1 (setf (sap-ref-8 sap tail
) bits
))
1734 (2 (setf (sap-ref-8 sap tail
) (logior #xc0
(ldb (byte 5 6) bits
))
1735 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 0) bits
))))
1736 (3 (setf (sap-ref-8 sap tail
) (logior #xe0
(ldb (byte 4 12) bits
))
1737 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 6) bits
))
1738 (sap-ref-8 sap
(+ 2 tail
)) (logior #x80
(ldb (byte 6 0) bits
))))
1739 (4 (setf (sap-ref-8 sap tail
) (logior #xf0
(ldb (byte 3 18) bits
))
1740 (sap-ref-8 sap
(+ 1 tail
)) (logior #x80
(ldb (byte 6 12) bits
))
1741 (sap-ref-8 sap
(+ 2 tail
)) (logior #x80
(ldb (byte 6 6) bits
))
1742 (sap-ref-8 sap
(+ 3 tail
)) (logior #x80
(ldb (byte 6 0) bits
)))))
1743 (cond ((< byte
#x80
) 1)
1744 ((< byte
#xc2
) (return-from decode-break-reason
1))
1748 (code-char (ecase size
1750 (2 (let ((byte2 (sap-ref-8 sap
(1+ head
))))
1751 (unless (<= #x80 byte2
#xbf
)
1752 (return-from decode-break-reason
2))
1753 (dpb byte
(byte 5 6) byte2
)))
1754 (3 (let ((byte2 (sap-ref-8 sap
(1+ head
)))
1755 (byte3 (sap-ref-8 sap
(+ 2 head
))))
1756 (unless (and (<= #x80 byte2
#xbf
)
1757 (<= #x80 byte3
#xbf
))
1758 (return-from decode-break-reason
3))
1759 (dpb byte
(byte 4 12) (dpb byte2
(byte 6 6) byte3
))))
1760 (4 (let ((byte2 (sap-ref-8 sap
(1+ head
)))
1761 (byte3 (sap-ref-8 sap
(+ 2 head
)))
1762 (byte4 (sap-ref-8 sap
(+ 3 head
))))
1763 (unless (and (<= #x80 byte2
#xbf
)
1764 (<= #x80 byte3
#xbf
)
1765 (<= #x80 byte4
#xbf
))
1766 (return-from decode-break-reason
4))
1767 (dpb byte
(byte 3 18)
1768 (dpb byte2
(byte 6 12)
1769 (dpb byte3
(byte 6 6) byte4
))))))))
1771 ;;;; utility functions (misc routines, etc)
1773 ;;; Fill in the various routine slots for the given type. INPUT-P and
1774 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1775 ;;; set prior to calling this routine.
1776 (defun set-fd-stream-routines (fd-stream element-type external-format
1777 input-p output-p buffer-p
)
1778 (let* ((target-type (case element-type
1779 (unsigned-byte '(unsigned-byte 8))
1780 (signed-byte '(signed-byte 8))
1781 (:default
'character
)
1783 (character-stream-p (subtypep target-type
'character
))
1784 (bivalent-stream-p (eq element-type
:default
))
1785 normalized-external-format
1786 (bin-routine #'ill-bin
)
1789 (cin-routine #'ill-in
)
1792 (input-type nil
) ;calculated from bin-type/cin-type
1793 (input-size nil
) ;calculated from bin-size/cin-size
1794 (read-n-characters #'ill-in
)
1795 (bout-routine #'ill-bout
)
1798 (cout-routine #'ill-out
)
1803 (output-bytes #'ill-bout
))
1805 ;; Ensure that we have buffers in the desired direction(s) only,
1806 ;; getting new ones and dropping/resetting old ones as necessary.
1807 (let ((obuf (fd-stream-obuf fd-stream
)))
1811 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1813 (setf (fd-stream-obuf fd-stream
) nil
)
1814 (release-buffer obuf
))))
1816 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1820 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1822 (setf (fd-stream-ibuf fd-stream
) nil
)
1823 (release-buffer ibuf
))))
1825 ;; FIXME: Why only for output? Why unconditionally?
1827 (setf (fd-stream-char-pos fd-stream
) 0))
1829 (when (and character-stream-p
1830 (eq external-format
:default
))
1831 (/show0
"/getting default external format")
1832 (setf external-format
(default-external-format)))
1835 (when (or (not character-stream-p
) bivalent-stream-p
)
1836 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1837 normalized-external-format
)
1838 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1842 (error "could not find any input routine for ~S" target-type
)))
1843 (when character-stream-p
1844 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1845 normalized-external-format
)
1846 (pick-input-routine target-type external-format
))
1848 (error "could not find any input routine for ~S" target-type
)))
1849 (setf (fd-stream-in fd-stream
) cin-routine
1850 (fd-stream-bin fd-stream
) bin-routine
)
1851 ;; character type gets preferential treatment
1852 (setf input-size
(or cin-size bin-size
))
1853 (setf input-type
(or cin-type bin-type
))
1854 (when normalized-external-format
1855 (setf (fd-stream-external-format fd-stream
)
1856 normalized-external-format
))
1857 (when (= (or cin-size
1) (or bin-size
1) 1)
1858 (setf (fd-stream-n-bin fd-stream
) ;XXX
1859 (if (and character-stream-p
(not bivalent-stream-p
))
1861 #'fd-stream-read-n-bytes
))
1862 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1863 ;; for character and (unsigned-byte 8) streams. In these
1864 ;; cases, fast-read-* will read from the
1865 ;; ansi-stream-(c)in-buffer, saving function calls.
1866 ;; Otherwise, the various data-reading functions in the stream
1867 ;; structure will be called.
1869 (not bivalent-stream-p
)
1870 ;; temporary disable on :io streams
1872 (cond (character-stream-p
1873 (setf (ansi-stream-cin-buffer fd-stream
)
1874 (make-array +ansi-stream-in-buffer-length
+
1875 :element-type
'character
)))
1876 ((equal target-type
'(unsigned-byte 8))
1877 (setf (ansi-stream-in-buffer fd-stream
)
1878 (make-array +ansi-stream-in-buffer-length
+
1879 :element-type
'(unsigned-byte 8))))))))
1882 (when (or (not character-stream-p
) bivalent-stream-p
)
1883 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1884 normalized-external-format
)
1885 (pick-output-routine (if bivalent-stream-p
1888 (fd-stream-buffering fd-stream
)
1890 (unless bout-routine
1891 (error "could not find any output routine for ~S buffered ~S"
1892 (fd-stream-buffering fd-stream
)
1894 (when character-stream-p
1895 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1896 normalized-external-format
)
1897 (pick-output-routine target-type
1898 (fd-stream-buffering fd-stream
)
1900 (unless cout-routine
1901 (error "could not find any output routine for ~S buffered ~S"
1902 (fd-stream-buffering fd-stream
)
1904 (when normalized-external-format
1905 (setf (fd-stream-external-format fd-stream
)
1906 normalized-external-format
))
1907 (when character-stream-p
1908 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1909 (setf (fd-stream-out fd-stream
) cout-routine
1910 (fd-stream-bout fd-stream
) bout-routine
1911 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1912 #'fd-sout
#'ill-out
))
1913 (setf output-size
(or cout-size bout-size
))
1914 (setf output-type
(or cout-type bout-type
)))
1916 (when (and input-size output-size
1917 (not (eq input-size output-size
)))
1918 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1919 input-type input-size
1920 output-type output-size
))
1921 (setf (fd-stream-element-size fd-stream
)
1922 (or input-size output-size
))
1924 (setf (fd-stream-element-type fd-stream
)
1925 (cond ((equal input-type output-type
)
1931 ((subtypep input-type output-type
)
1933 ((subtypep output-type input-type
)
1936 (error "Input type (~S) and output type (~S) are unrelated?"
1940 ;;; Handles the resource-release aspects of stream closing.
1941 (defun release-fd-stream-resources (fd-stream)
1944 ;; Disable interrupts so that a asynch unwind will not leave
1945 ;; us with a dangling finalizer (that would close the same
1946 ;; --possibly reassigned-- FD again).
1947 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1948 (when (fboundp 'cancel-finalization
)
1949 (cancel-finalization fd-stream
)))
1950 ;; On error unwind from WITHOUT-INTERRUPTS.
1951 (serious-condition (e)
1954 ;; Release all buffers. If this is undone, or interrupted,
1955 ;; we're still safe: buffers have finalizers of their own.
1956 (release-fd-stream-buffers fd-stream
))
1958 ;;; Flushes the current input buffer and unread chatacter, and returns
1959 ;;; the input buffer, and the amount of of flushed input in bytes.
1960 (defun flush-input-buffer (stream)
1961 (let ((unread (if (fd-stream-unread stream
)
1964 (setf (fd-stream-unread stream
) nil
)
1965 (let ((ibuf (fd-stream-ibuf stream
)))
1967 (let ((head (buffer-head ibuf
))
1968 (tail (buffer-tail ibuf
)))
1969 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1970 (values nil unread
)))))
1972 (defun fd-stream-clear-input (stream)
1973 (flush-input-buffer stream
)
1976 (sb!win32
:fd-clear-input
(fd-stream-fd stream
))
1977 (setf (fd-stream-listen stream
) nil
))
1979 (catch 'eof-input-catcher
1980 (loop until
(sysread-may-block-p stream
)
1982 (refill-input-buffer stream
)
1983 (reset-buffer (fd-stream-ibuf stream
)))
1986 ;;; Handle miscellaneous operations on FD-STREAM.
1987 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
1988 (declare (ignore arg2
))
1991 (labels ((do-listen ()
1992 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1993 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
1994 (fd-stream-listen fd-stream
)
1996 (sb!win32
:fd-listen
(fd-stream-fd fd-stream
))
1998 ;; If the read can block, LISTEN will certainly return NIL.
1999 (if (sysread-may-block-p fd-stream
)
2001 ;; Otherwise select(2) and CL:LISTEN have slightly
2002 ;; different semantics. The former returns that an FD
2003 ;; is readable when a read operation wouldn't block.
2004 ;; That includes EOF. However, LISTEN must return NIL
2006 (progn (catch 'eof-input-catcher
2007 ;; r-b/f too calls select, but it shouldn't
2008 ;; block as long as read can return once w/o
2010 (refill-input-buffer fd-stream
))
2011 ;; At this point either IBUF-HEAD != IBUF-TAIL
2012 ;; and FD-STREAM-LISTEN is NIL, in which case
2013 ;; we should return T, or IBUF-HEAD ==
2014 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2015 ;; which case we should return :EOF for this
2016 ;; call and all future LISTEN call on this stream.
2017 ;; Call ourselves again to determine which case
2022 (setf (fd-stream-unread fd-stream
) arg1
)
2023 (setf (fd-stream-listen fd-stream
) t
))
2025 (cond (arg1 ; We got us an abort on our hands.
2026 (when (fd-stream-handler fd-stream
)
2027 (remove-fd-handler (fd-stream-handler fd-stream
))
2028 (setf (fd-stream-handler fd-stream
) nil
))
2029 ;; We can't do anything unless we know what file were
2030 ;; dealing with, and we don't want to do anything
2031 ;; strange unless we were writing to the file.
2032 (when (and (fd-stream-file fd-stream
) (fd-stream-obuf fd-stream
))
2033 (if (fd-stream-original fd-stream
)
2034 ;; If the original is EQ to file we are appending
2035 ;; and can just close the file without renaming.
2036 (unless (eq (fd-stream-original fd-stream
)
2037 (fd-stream-file fd-stream
))
2038 ;; We have a handle on the original, just revert.
2039 (multiple-value-bind (okay err
)
2040 (sb!unix
:unix-rename
(fd-stream-original fd-stream
)
2041 (fd-stream-file fd-stream
))
2043 (simple-stream-perror
2044 "couldn't restore ~S to its original contents"
2047 ;; We can't restore the original, and aren't
2048 ;; appending, so nuke that puppy.
2050 ;; FIXME: This is currently the fate of superseded
2051 ;; files, and according to the CLOSE spec this is
2052 ;; wrong. However, there seems to be no clean way to
2053 ;; do that that doesn't involve either copying the
2054 ;; data (bad if the :abort resulted from a full
2055 ;; disk), or renaming the old file temporarily
2056 ;; (probably bad because stream opening becomes more
2058 (multiple-value-bind (okay err
)
2059 (sb!unix
:unix-unlink
(fd-stream-file fd-stream
))
2061 (error 'simple-file-error
2062 :pathname
(fd-stream-file fd-stream
)
2064 "~@<couldn't remove ~S: ~2I~_~A~:>"
2065 :format-arguments
(list (fd-stream-file fd-stream
)
2066 (strerror err
))))))))
2068 (finish-fd-stream-output fd-stream
)
2069 (when (and (fd-stream-original fd-stream
)
2070 (fd-stream-delete-original fd-stream
))
2071 (multiple-value-bind (okay err
)
2072 (sb!unix
:unix-unlink
(fd-stream-original fd-stream
))
2074 (error 'simple-file-error
2075 :pathname
(fd-stream-original fd-stream
)
2077 "~@<couldn't delete ~S during close of ~S: ~
2080 (list (fd-stream-original fd-stream
)
2082 (strerror err
))))))))
2083 (release-fd-stream-resources fd-stream
)
2084 ;; Mark as closed. FIXME: Maybe this should be the first thing done?
2085 (sb!impl
::set-closed-flame fd-stream
))
2087 (fd-stream-clear-input fd-stream
))
2089 (flush-output-buffer fd-stream
))
2091 (finish-fd-stream-output fd-stream
))
2093 (fd-stream-element-type fd-stream
))
2095 (fd-stream-external-format fd-stream
))
2097 (= 1 (the (member 0 1)
2098 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2102 (fd-stream-char-pos fd-stream
))
2104 (unless (fd-stream-file fd-stream
)
2105 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2106 ;; "should signal an error of type TYPE-ERROR if stream is not
2107 ;; a stream associated with a file". Too bad there's no very
2108 ;; appropriate value for the EXPECTED-TYPE slot..
2109 (error 'simple-type-error
2111 :expected-type
'fd-stream
2112 :format-control
"~S is not a stream associated with a file."
2113 :format-arguments
(list fd-stream
)))
2114 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2115 atime mtime ctime blksize blocks
)
2116 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2117 (declare (ignore ino nlink uid gid rdev
2118 atime mtime ctime blksize blocks
))
2120 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2123 (truncate size
(fd-stream-element-size fd-stream
)))))
2124 (:file-string-length
2126 (character (fd-stream-character-size fd-stream arg1
))
2127 (string (fd-stream-string-size fd-stream arg1
))))
2130 (fd-stream-set-file-position fd-stream arg1
)
2131 (fd-stream-get-file-position fd-stream
)))))
2133 ;; FIXME: Think about this.
2135 ;; (defun finish-fd-stream-output (fd-stream)
2136 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2137 ;; (loop while (fd-stream-output-queue fd-stream)
2138 ;; ;; FIXME: SIGINT while waiting for a timeout will
2139 ;; ;; cause a timeout here.
2140 ;; do (when (and (not (serve-event timeout)) timeout)
2141 ;; (signal-timeout 'io-timeout
2142 ;; :stream fd-stream
2143 ;; :direction :write
2144 ;; :seconds timeout)))))
2146 (defun finish-fd-stream-output (stream)
2147 (flush-output-buffer stream
)
2149 ((null (fd-stream-output-queue stream
)))
2150 (serve-all-events)))
2152 (defun fd-stream-get-file-position (stream)
2153 (declare (fd-stream stream
))
2155 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2156 (declare (type (or (alien sb
!unix
:off-t
) null
) posn
))
2157 ;; We used to return NIL for errno==ESPIPE, and signal an error
2158 ;; in other failure cases. However, CLHS says to return NIL if
2159 ;; the position cannot be determined -- so that's what we do.
2160 (when (integerp posn
)
2161 ;; Adjust for buffered output: If there is any output
2162 ;; buffered, the *real* file position will be larger
2163 ;; than reported by lseek() because lseek() obviously
2164 ;; cannot take into account output we have not sent
2166 (dolist (buffer (fd-stream-output-queue stream
))
2167 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2168 (let ((obuf (fd-stream-obuf stream
)))
2170 (incf posn
(buffer-tail obuf
))))
2171 ;; Adjust for unread input: If there is any input
2172 ;; read from UNIX but not supplied to the user of the
2173 ;; stream, the *real* file position will smaller than
2174 ;; reported, because we want to look like the unread
2175 ;; stuff is still available.
2176 (let ((ibuf (fd-stream-ibuf stream
)))
2178 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2179 (when (fd-stream-unread stream
)
2181 ;; Divide bytes by element size.
2182 (truncate posn
(fd-stream-element-size stream
))))))
2184 (defun fd-stream-set-file-position (stream position-spec
)
2185 (declare (fd-stream stream
))
2186 (check-type position-spec
2187 (or (alien sb
!unix
:off-t
) (member nil
:start
:end
))
2188 "valid file position designator")
2191 ;; Make sure we don't have any output pending, because if we
2192 ;; move the file pointer before writing this stuff, it will be
2193 ;; written in the wrong location.
2194 (finish-fd-stream-output stream
)
2195 ;; Disable interrupts so that interrupt handlers doing output
2198 (unless (fd-stream-output-finished-p stream
)
2199 ;; We got interrupted and more output came our way during
2200 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2201 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2202 ;; so we prefer to do things like this...
2204 ;; Clear out any pending input to force the next read to go to
2206 (flush-input-buffer stream
)
2207 ;; Trash cached value for listen, so that we check next time.
2208 (setf (fd-stream-listen stream
) nil
)
2210 (multiple-value-bind (offset origin
)
2213 (values 0 sb
!unix
:l_set
))
2215 (values 0 sb
!unix
:l_xtnd
))
2217 (values (* position-spec
(fd-stream-element-size stream
))
2219 (declare (type (alien sb
!unix
:off-t
) offset
))
2220 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2222 ;; CLHS says to return true if the file-position was set
2223 ;; succesfully, and NIL otherwise. We are to signal an error
2224 ;; only if the given position was out of bounds, and that is
2225 ;; dealt with above. In times past we used to return NIL for
2226 ;; errno==ESPIPE, and signal an error in other cases.
2228 ;; FIXME: We are still liable to signal an error if flushing
2230 (return-from fd-stream-set-file-position
2231 (typep posn
'(alien sb
!unix
:off-t
))))))))
2234 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2236 ;;; Create a stream for the given Unix file descriptor.
2238 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2239 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2240 ;;; default to allowing input.
2242 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2244 ;;; BUFFERING indicates the kind of buffering to use.
2246 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2247 ;;; NIL (the default), then wait forever. When we time out, we signal
2250 ;;; FILE is the name of the file (will be returned by PATHNAME).
2252 ;;; NAME is used to identify the stream when printed.
2253 (defun make-fd-stream (fd
2256 (output nil output-p
)
2257 (element-type 'base-char
)
2259 (external-format :default
)
2268 (format nil
"file ~A" file
)
2269 (format nil
"descriptor ~W" fd
)))
2271 (declare (type index fd
) (type (or real null
) timeout
)
2272 (type (member :none
:line
:full
) buffering
))
2273 (cond ((not (or input-p output-p
))
2275 ((not (or input output
))
2276 (error "File descriptor must be opened either for input or output.")))
2277 (let ((stream (%make-fd-stream
:fd fd
2281 :delete-original delete-original
2283 :buffering buffering
2284 :dual-channel-p dual-channel-p
2285 :external-format external-format
2288 (coerce timeout
'single-float
)
2290 (set-fd-stream-routines stream element-type external-format
2291 input output input-buffer-p
)
2292 (when (and auto-close
(fboundp 'finalize
))
2295 (sb!unix
:unix-close fd
)
2297 (format *terminal-io
* "** closed file descriptor ~W **~%"
2302 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2303 ;;; :RENAME-AND-DELETE and :RENAME options.
2304 (defun pick-backup-name (name)
2305 (declare (type simple-string name
))
2306 (concatenate 'simple-string name
".bak"))
2308 ;;; Ensure that the given arg is one of the given list of valid
2309 ;;; things. Allow the user to fix any problems.
2310 (defun ensure-one-of (item list what
)
2311 (unless (member item list
)
2312 (error 'simple-type-error
2314 :expected-type
`(member ,@list
)
2315 :format-control
"~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2316 :format-arguments
(list item what list
))))
2318 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2319 ;;; access, since we don't want to trash unwritable files even if we
2320 ;;; technically can. We return true if we succeed in renaming.
2321 (defun rename-the-old-one (namestring original
)
2322 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2323 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2324 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2327 (error 'simple-file-error
2328 :pathname namestring
2330 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2331 :format-arguments
(list namestring original
(strerror err
))))))
2333 (defun open (filename
2336 (element-type 'base-char
)
2337 (if-exists nil if-exists-given
)
2338 (if-does-not-exist nil if-does-not-exist-given
)
2339 (external-format :default
)
2340 &aux
; Squelch assignment warning.
2341 (direction direction
)
2342 (if-does-not-exist if-does-not-exist
)
2343 (if-exists if-exists
))
2345 "Return a stream which reads from or writes to FILENAME.
2347 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2348 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2349 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2350 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2351 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2352 See the manual for details."
2354 ;; Calculate useful stuff.
2355 (multiple-value-bind (input output mask
)
2357 (:input
(values t nil sb
!unix
:o_rdonly
))
2358 (:output
(values nil t sb
!unix
:o_wronly
))
2359 (:io
(values t t sb
!unix
:o_rdwr
))
2360 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2361 (declare (type index mask
))
2362 (let* ((pathname (merge-pathnames filename
))
2364 (cond ((unix-namestring pathname input
))
2365 ((and input
(eq if-does-not-exist
:create
))
2366 (unix-namestring pathname nil
))
2367 ((and (eq direction
:io
) (not if-does-not-exist-given
))
2368 (unix-namestring pathname nil
)))))
2369 ;; Process if-exists argument if we are doing any output.
2371 (unless if-exists-given
2373 (if (eq (pathname-version pathname
) :newest
)
2376 (ensure-one-of if-exists
2377 '(:error
:new-version
:rename
2378 :rename-and-delete
:overwrite
2379 :append
:supersede nil
)
2382 ((:new-version
:error nil
)
2383 (setf mask
(logior mask sb
!unix
:o_excl
)))
2384 ((:rename
:rename-and-delete
)
2385 (setf mask
(logior mask sb
!unix
:o_creat
)))
2387 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2389 (setf mask
(logior mask sb
!unix
:o_append
)))))
2391 (setf if-exists
:ignore-this-arg
)))
2393 (unless if-does-not-exist-given
2394 (setf if-does-not-exist
2395 (cond ((eq direction
:input
) :error
)
2397 (member if-exists
'(:overwrite
:append
)))
2399 ((eq direction
:probe
)
2403 (ensure-one-of if-does-not-exist
2404 '(:error
:create nil
)
2406 (if (eq if-does-not-exist
:create
)
2407 (setf mask
(logior mask sb
!unix
:o_creat
)))
2409 (let ((original (case if-exists
2410 ((:rename
:rename-and-delete
)
2411 (pick-backup-name namestring
))
2412 ((:append
:overwrite
)
2413 ;; KLUDGE: Provent CLOSE from deleting
2414 ;; appending streams when called with :ABORT T
2416 (delete-original (eq if-exists
:rename-and-delete
))
2418 (when (and original
(not (eq original namestring
)))
2419 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2420 ;; whether the file already exists, make sure the original
2421 ;; file is not a directory, and keep the mode.
2424 (multiple-value-bind (okay err
/dev inode orig-mode
)
2425 (sb!unix
:unix-stat namestring
)
2426 (declare (ignore inode
)
2427 (type (or index null
) orig-mode
))
2430 (when (and output
(= (logand orig-mode
#o170000
)
2432 (error 'simple-file-error
2433 :pathname namestring
2435 "can't open ~S for output: is a directory"
2436 :format-arguments
(list namestring
)))
2437 (setf mode
(logand orig-mode
#o777
))
2439 ((eql err
/dev sb
!unix
:enoent
)
2442 (simple-file-perror "can't find ~S"
2446 (rename-the-old-one namestring original
))
2448 (setf delete-original nil
)
2449 ;; In order to use :SUPERSEDE instead, we have to make
2450 ;; sure SB!UNIX:O_CREAT corresponds to
2451 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2452 ;; because of IF-EXISTS being :RENAME.
2453 (unless (eq if-does-not-exist
:create
)
2455 (logior (logandc2 mask sb
!unix
:o_creat
)
2457 (setf if-exists
:supersede
))))
2459 ;; Now we can try the actual Unix open(2).
2460 (multiple-value-bind (fd errno
)
2462 (sb!unix
:unix-open namestring mask mode
)
2463 (values nil sb
!unix
:enoent
))
2464 (labels ((open-error (format-control &rest format-arguments
)
2465 (error 'simple-file-error
2467 :format-control format-control
2468 :format-arguments format-arguments
))
2469 (vanilla-open-error ()
2470 (simple-file-perror "error opening ~S" pathname errno
)))
2473 ((:input
:output
:io
)
2477 :element-type element-type
2478 :external-format external-format
2481 :delete-original delete-original
2488 (%make-fd-stream
:name namestring
2491 :element-type element-type
)))
2494 ((eql errno sb
!unix
:enoent
)
2495 (case if-does-not-exist
2496 (:error
(vanilla-open-error))
2498 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2501 ((and (eql errno sb
!unix
:eexist
) (null if-exists
))
2504 (vanilla-open-error)))))))))
2508 ;;; the stream connected to the controlling terminal, or NIL if there is none
2511 ;;; the stream connected to the standard input (file descriptor 0)
2514 ;;; the stream connected to the standard output (file descriptor 1)
2517 ;;; the stream connected to the standard error output (file descriptor 2)
2520 ;;; This is called when the cold load is first started up, and may also
2521 ;;; be called in an attempt to recover from nested errors.
2522 (defun stream-cold-init-or-reset ()
2524 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2525 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2526 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2527 (setf *error-output
* (make-synonym-stream '*stderr
*))
2528 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2529 (setf *debug-io
* *query-io
*)
2530 (setf *trace-output
* *standard-output
*)
2533 (defun stream-deinit ()
2534 ;; Unbind to make sure we're not accidently dealing with it
2535 ;; before we're ready (or after we think it's been deinitialized).
2536 (with-available-buffers-lock ()
2537 (without-package-locks
2538 (makunbound '*available-buffers
*))))
2540 ;;; This is called whenever a saved core is restarted.
2541 (defun stream-reinit (&optional init-buffers-p
)
2542 (when init-buffers-p
2543 (with-available-buffers-lock ()
2544 (aver (not (boundp '*available-buffers
*)))
2545 (setf *available-buffers
* nil
)))
2546 (with-output-to-string (*error-output
*)
2548 (make-fd-stream 0 :name
"standard input" :input t
:buffering
:line
2549 #!+win32
:external-format
#!+win32
(sb!win32
::console-input-codepage
)))
2551 (make-fd-stream 1 :name
"standard output" :output t
:buffering
:line
2552 #!+win32
:external-format
#!+win32
(sb!win32
::console-output-codepage
)))
2554 (make-fd-stream 2 :name
"standard error" :output t
:buffering
:line
2555 #!+win32
:external-format
#!+win32
(sb!win32
::console-output-codepage
)))
2556 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2557 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2561 :name
"the terminal"
2566 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))))
2567 (princ (get-output-stream-string *error-output
*) *stderr
*))
2572 ;;; the Unix way to beep
2573 (defun beep (stream)
2574 (write-char (code-char bell-char-code
) stream
)
2575 (finish-output stream
))
2577 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2578 ;;; by the filesys stuff to get and set the file name.
2580 ;;; FIXME: misleading name, screwy interface
2581 (defun file-name (stream &optional new-name
)
2582 (when (typep stream
'fd-stream
)
2584 (setf (fd-stream-pathname stream
) new-name
)
2585 (setf (fd-stream-file stream
)
2586 (unix-namestring new-name nil
))
2589 (fd-stream-pathname stream
)))))