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")
14 ;;;; buffer manipulation routines
16 ;;; FIXME: Is it really good to maintain this pool separate from the
17 ;;; GC and the C malloc logic?
18 (defvar *available-buffers* ()
20 "List of available buffers. Each buffer is an sap pointing to
21 bytes-per-buffer of memory.")
24 (defvar *available-buffers-mutex* (sb!thread:make-mutex
25 :name "lock for *AVAILABLE-BUFFERS*")
27 "Mutex for access to *AVAILABLE-BUFFERS*.")
29 (defmacro with-available-buffers-lock ((&optional) &body body)
30 ;; WITHOUT-INTERRUPTS because streams are low-level enough to be
31 ;; async signal safe, and in particular a C-c that brings up the
32 ;; debugger while holding the mutex would lose badly
34 (sb!thread:with-mutex (*available-buffers-mutex*)
37 (defconstant bytes-per-buffer (* 4 1024)
39 "Number of bytes per buffer.")
41 ;;; Return the next available buffer, creating one if necessary.
42 #!-sb-fluid (declaim (inline next-available-buffer))
43 (defun next-available-buffer ()
44 (with-available-buffers-lock ()
45 (if *available-buffers*
46 (pop *available-buffers*)
47 (allocate-system-memory bytes-per-buffer))))
49 ;;;; the FD-STREAM structure
52 (:constructor %make-fd-stream)
53 (:conc-name fd-stream-)
54 (:predicate fd-stream-p)
56 (misc #'fd-stream-misc-routine))
59 ;; the name of this stream
61 ;; the file this stream is for
63 ;; the backup file namestring for the old file, for :IF-EXISTS
64 ;; :RENAME or :RENAME-AND-DELETE.
65 (original nil :type (or simple-string null))
66 (delete-original nil) ; for :if-exists :rename-and-delete
67 ;;; the number of bytes per element
68 (element-size 1 :type index)
69 ;; the type of element being transfered
70 (element-type 'base-char)
71 ;; the Unix file descriptor
73 ;; controls when the output buffer is flushed
74 (buffering :full :type (member :full :line :none))
75 ;; controls whether the input buffer must be cleared before output
76 ;; (must be done for files, not for sockets, pipes and other data
77 ;; sources where input and output aren't related). non-NIL means
78 ;; don't clear input buffer.
80 ;; character position if known -- this may run into bignums, but
81 ;; we probably should flip it into null then for efficiency's sake...
82 (char-pos nil :type (or unsigned-byte null))
83 ;; T if input is waiting on FD. :EOF if we hit EOF.
84 (listen nil :type (member nil t :eof))
88 (ibuf-sap nil :type (or system-area-pointer null))
89 (ibuf-length nil :type (or index null))
90 (ibuf-head 0 :type index)
91 (ibuf-tail 0 :type index)
94 (obuf-sap nil :type (or system-area-pointer null))
95 (obuf-length nil :type (or index null))
96 (obuf-tail 0 :type index)
98 ;; output flushed, but not written due to non-blocking io?
101 ;; timeout specified for this stream as seconds or NIL if none
102 (timeout nil :type (or single-float null))
103 ;; pathname of the file this stream is opened to (returned by PATHNAME)
104 (pathname nil :type (or pathname null))
105 (external-format :default)
106 (output-bytes #'ill-out :type function))
107 (def!method print-object ((fd-stream fd-stream) stream)
108 (declare (type stream stream))
109 (print-unreadable-object (fd-stream stream :type t :identity t)
110 (format stream "for ~S" (fd-stream-name fd-stream))))
112 ;;;; output routines and related noise
114 (defvar *output-routines* ()
116 "List of all available output routines. Each element is a list of the
117 element-type output, the kind of buffering, the function name, and the number
118 of bytes per element.")
120 ;;; common idioms for reporting low-level stream and file problems
121 (defun simple-stream-perror (note-format stream errno)
122 (error 'simple-stream-error
124 :format-control "~@<~?: ~2I~_~A~:>"
125 :format-arguments (list note-format (list stream) (strerror errno))))
126 (defun simple-file-perror (note-format pathname errno)
127 (error 'simple-file-error
129 :format-control "~@<~?: ~2I~_~A~:>"
131 (list note-format (list pathname) (strerror errno))))
133 (defun stream-decoding-error (stream octets)
134 (error 'stream-decoding-error
136 ;; FIXME: dunno how to get at OCTETS currently, or even if
137 ;; that's the right thing to report.
139 (defun stream-encoding-error (stream code)
140 (error 'stream-encoding-error
144 (defun c-string-encoding-error (external-format code)
145 (error 'c-string-encoding-error
146 :external-format external-format
149 (defun c-string-decoding-error (external-format octets)
150 (error 'c-string-decoding-error
151 :external-format external-format
154 ;;; Returning true goes into end of file handling, false will enter another
155 ;;; round of input buffer filling followed by re-entering character decode.
156 (defun stream-decoding-error-and-handle (stream octet-count)
158 (stream-decoding-error stream
159 (let ((sap (fd-stream-ibuf-sap stream))
160 (head (fd-stream-ibuf-head stream)))
161 (loop for i from 0 below octet-count
162 collect (sap-ref-8 sap (+ head i)))))
164 :report (lambda (stream)
166 "~@<Attempt to resync the stream at a character ~
167 character boundary and continue.~@:>"))
168 (fd-stream-resync stream)
170 (force-end-of-file ()
171 :report (lambda (stream)
172 (format stream "~@<Force an end of file.~@:>"))
175 (defun stream-encoding-error-and-handle (stream code)
177 (stream-encoding-error stream code)
179 :report (lambda (stream)
180 (format stream "~@<Skip output of this character.~@:>"))
181 (throw 'output-nothing nil))))
183 (defun external-format-encoding-error (stream code)
185 (stream-encoding-error-and-handle stream code)
186 (c-string-encoding-error stream code)))
188 (defun external-format-decoding-error (stream octet-count)
190 (stream-decoding-error stream octet-count)
191 (c-string-decoding-error stream octet-count)))
193 ;;; This is called by the server when we can write to the given file
194 ;;; descriptor. Attempt to write the data again. If it worked, remove
195 ;;; the data from the OUTPUT-LATER list. If it didn't work, something
197 (defun frob-output-later (stream)
198 (let* ((stuff (pop (fd-stream-output-later stream)))
202 (reuse-sap (cadddr stuff))
203 (length (- end start)))
204 (declare (type index start end length))
205 (multiple-value-bind (count errno)
206 (sb!unix:unix-write (fd-stream-fd stream)
212 (simple-stream-perror "couldn't write to ~S" stream errno)
214 (if (= errno sb!unix:ewouldblock)
215 (error "Write would have blocked, but SERVER told us to go.")
216 (simple-stream-perror "couldn't write to ~S" stream errno)))
217 ((eql count length) ; Hot damn, it worked.
219 (with-available-buffers-lock ()
220 (push base *available-buffers*))))
221 ((not (null count)) ; sorta worked..
223 (the index (+ start count))
225 (fd-stream-output-later stream))))))
226 (unless (fd-stream-output-later stream)
227 (remove-fd-handler (fd-stream-handler stream))
228 (setf (fd-stream-handler stream) nil)))
230 ;;; Arange to output the string when we can write on the file descriptor.
231 (defun output-later (stream base start end reuse-sap)
232 (cond ((null (fd-stream-output-later stream))
233 (setf (fd-stream-output-later stream)
234 (list (list base start end reuse-sap)))
235 (setf (fd-stream-handler stream)
236 (add-fd-handler (fd-stream-fd stream)
239 (declare (ignore fd))
240 (frob-output-later stream)))))
242 (nconc (fd-stream-output-later stream)
243 (list (list base start end reuse-sap)))))
245 (let ((new-buffer (next-available-buffer)))
246 (setf (fd-stream-obuf-sap stream) new-buffer)
247 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
249 ;;; Output the given noise. Check to see whether there are any pending
250 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
251 ;;; this would block, queue it.
252 (defun frob-output (stream base start end reuse-sap)
253 (declare (type fd-stream stream)
254 (type (or system-area-pointer (simple-array * (*))) base)
255 (type index start end))
256 (if (not (null (fd-stream-output-later stream))) ; something buffered.
257 (output-later stream base start end reuse-sap)
258 ;; ### check to see whether any of this noise can be output
259 (let ((length (- end start)))
260 (multiple-value-bind (count errno)
261 (sb!unix:unix-write (fd-stream-fd stream) base start length)
264 (simple-stream-perror "Couldn't write to ~S" stream errno)
266 (if (= errno sb!unix:ewouldblock)
267 (output-later stream base start end reuse-sap)
268 (simple-stream-perror "Couldn't write to ~S"
270 ((not (eql count length))
271 (output-later stream base (the index (+ start count))
274 ;;; Flush any data in the output buffer.
275 (defun flush-output-buffer (stream)
276 (let ((length (fd-stream-obuf-tail stream)))
278 (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
279 (setf (fd-stream-obuf-tail stream) 0))))
281 (defun fd-stream-output-finished-p (stream)
282 (and (zerop (fd-stream-obuf-tail stream))
283 (not (fd-stream-output-later stream))))
285 (defmacro output-wrapper/variable-width ((stream size buffering restart)
287 (let ((stream-var (gensym)))
288 `(let ((,stream-var ,stream)
290 ,(unless (eq (car buffering) :none)
291 `(when (< (fd-stream-obuf-length ,stream-var)
292 (+ (fd-stream-obuf-tail ,stream-var)
294 (flush-output-buffer ,stream-var)))
295 ,(unless (eq (car buffering) :none)
296 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
297 (> (fd-stream-ibuf-tail ,stream-var)
298 (fd-stream-ibuf-head ,stream-var)))
299 (file-position ,stream-var (file-position ,stream-var))))
301 `(catch 'output-nothing
303 (incf (fd-stream-obuf-tail ,stream-var) size))
306 (incf (fd-stream-obuf-tail ,stream-var) size)))
307 ,(ecase (car buffering)
309 `(flush-output-buffer ,stream-var))
311 `(when (eq (char-code byte) (char-code #\Newline))
312 (flush-output-buffer ,stream-var)))
316 (defmacro output-wrapper ((stream size buffering restart) &body body)
317 (let ((stream-var (gensym)))
318 `(let ((,stream-var ,stream))
319 ,(unless (eq (car buffering) :none)
320 `(when (< (fd-stream-obuf-length ,stream-var)
321 (+ (fd-stream-obuf-tail ,stream-var)
323 (flush-output-buffer ,stream-var)))
324 ,(unless (eq (car buffering) :none)
325 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
326 (> (fd-stream-ibuf-tail ,stream-var)
327 (fd-stream-ibuf-head ,stream-var)))
328 (file-position ,stream-var (file-position ,stream-var))))
330 `(catch 'output-nothing
332 (incf (fd-stream-obuf-tail ,stream-var) ,size))
335 (incf (fd-stream-obuf-tail ,stream-var) ,size)))
336 ,(ecase (car buffering)
338 `(flush-output-buffer ,stream-var))
340 `(when (eq (char-code byte) (char-code #\Newline))
341 (flush-output-buffer ,stream-var)))
345 (defmacro def-output-routines/variable-width
346 ((name-fmt size restart external-format &rest bufferings)
348 (declare (optimize (speed 1)))
353 (intern (format nil name-fmt (string (car buffering))))))
355 (defun ,function (stream byte)
356 (declare (ignorable byte))
357 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
359 (setf *output-routines*
360 (nconc *output-routines*
368 (cdr buffering)))))))
371 ;;; Define output routines that output numbers SIZE bytes long for the
372 ;;; given bufferings. Use BODY to do the actual output.
373 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
375 (declare (optimize (speed 1)))
380 (intern (format nil name-fmt (string (car buffering))))))
382 (defun ,function (stream byte)
383 (output-wrapper (stream ,size ,buffering ,restart)
385 (setf *output-routines*
386 (nconc *output-routines*
394 (cdr buffering)))))))
397 ;;; FIXME: is this used anywhere any more?
398 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
404 (if (char= byte #\Newline)
405 (setf (fd-stream-char-pos stream) 0)
406 (incf (fd-stream-char-pos stream)))
407 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
410 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
413 (:none (unsigned-byte 8))
414 (:full (unsigned-byte 8)))
415 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
418 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
421 (:none (signed-byte 8))
422 (:full (signed-byte 8)))
423 (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
424 (fd-stream-obuf-tail stream))
427 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
430 (:none (unsigned-byte 16))
431 (:full (unsigned-byte 16)))
432 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
435 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
438 (:none (signed-byte 16))
439 (:full (signed-byte 16)))
440 (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
441 (fd-stream-obuf-tail stream))
444 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
447 (:none (unsigned-byte 32))
448 (:full (unsigned-byte 32)))
449 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
452 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
455 (:none (signed-byte 32))
456 (:full (signed-byte 32)))
457 (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
458 (fd-stream-obuf-tail stream))
461 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
463 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
466 (:none (unsigned-byte 64))
467 (:full (unsigned-byte 64)))
468 (setf (sap-ref-64 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
470 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
473 (:none (signed-byte 64))
474 (:full (signed-byte 64)))
475 (setf (signed-sap-ref-64 (fd-stream-obuf-sap stream)
476 (fd-stream-obuf-tail stream))
479 ;;; Do the actual output. If there is space to buffer the string,
480 ;;; buffer it. If the string would normally fit in the buffer, but
481 ;;; doesn't because of other stuff in the buffer, flush the old noise
482 ;;; out of the buffer and put the string in it. Otherwise we have a
483 ;;; very long string, so just send it directly (after flushing the
484 ;;; buffer, of course).
485 (defun output-raw-bytes (fd-stream thing &optional start end)
487 "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
488 THING is a SAP, END must be supplied (as length won't work)."
489 (let ((start (or start 0))
490 (end (or end (length (the (simple-array * (*)) thing)))))
491 (declare (type index start end))
492 (when (and (not (fd-stream-dual-channel-p fd-stream))
493 (> (fd-stream-ibuf-tail fd-stream)
494 (fd-stream-ibuf-head fd-stream)))
495 (file-position fd-stream (file-position fd-stream)))
496 (let* ((len (fd-stream-obuf-length fd-stream))
497 (tail (fd-stream-obuf-tail fd-stream))
499 (bytes (- end start))
500 (newtail (+ tail bytes)))
501 (cond ((minusp bytes) ; error case
502 (error ":END before :START!"))
503 ((zerop bytes)) ; easy case
505 (if (system-area-pointer-p thing)
506 (system-area-ub8-copy thing start
507 (fd-stream-obuf-sap fd-stream)
510 ;; FIXME: There should be some type checking somewhere to
511 ;; verify that THING here is a vector, not just <not a SAP>.
512 (copy-ub8-to-system-area thing start
513 (fd-stream-obuf-sap fd-stream)
516 (setf (fd-stream-obuf-tail fd-stream) newtail))
518 (flush-output-buffer fd-stream)
519 (if (system-area-pointer-p thing)
520 (system-area-ub8-copy thing
522 (fd-stream-obuf-sap fd-stream)
525 ;; FIXME: There should be some type checking somewhere to
526 ;; verify that THING here is a vector, not just <not a SAP>.
527 (copy-ub8-to-system-area thing
529 (fd-stream-obuf-sap fd-stream)
532 (setf (fd-stream-obuf-tail fd-stream) bytes))
534 (flush-output-buffer fd-stream)
535 (frob-output fd-stream thing start end nil))))))
537 ;;; the routine to use to output a string. If the stream is
538 ;;; unbuffered, slam the string down the file descriptor, otherwise
539 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
540 ;;; checking to see where the last newline was.
542 ;;; Note: some bozos (the FASL dumper) call write-string with things
543 ;;; other than strings. Therefore, we must make sure we have a string
544 ;;; before calling POSITION on it.
545 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
546 ;;; cover for them here. -- WHN 20000203
547 (defun fd-sout (stream thing start end)
548 (let ((start (or start 0))
549 (end (or end (length (the vector thing)))))
550 (declare (fixnum start end))
553 (string-dispatch (simple-base-string
555 (simple-array character)
558 (and (find #\newline thing :start start :end end)
559 ;; FIXME why do we need both calls?
560 ;; Is find faster forwards than
561 ;; position is backwards?
562 (position #\newline thing
566 (if (and (typep thing 'base-string)
567 (eq (fd-stream-external-format stream) :latin-1))
568 (ecase (fd-stream-buffering stream)
570 (output-raw-bytes stream thing start end))
572 (output-raw-bytes stream thing start end)
574 (flush-output-buffer stream)))
576 (frob-output stream thing start end nil)))
577 (ecase (fd-stream-buffering stream)
578 (:full (funcall (fd-stream-output-bytes stream)
579 stream thing nil start end))
580 (:line (funcall (fd-stream-output-bytes stream)
581 stream thing last-newline start end))
582 (:none (funcall (fd-stream-output-bytes stream)
583 stream thing t start end))))
585 (setf (fd-stream-char-pos stream)
586 (- end last-newline 1))
587 (incf (fd-stream-char-pos stream)
589 (ecase (fd-stream-buffering stream)
591 (output-raw-bytes stream thing start end))
593 (frob-output stream thing start end nil))))))
595 (defvar *external-formats* ()
597 "List of all available external formats. Each element is a list of the
598 element-type, string input function name, character input function name,
599 and string output function name.")
601 (defun get-external-format (external-format)
602 (dolist (entry *external-formats*)
603 (when (member external-format (first entry))
606 (defun get-external-format-function (external-format index)
607 (let ((entry (get-external-format external-format)))
608 (when entry (nth index entry))))
610 ;;; Find an output routine to use given the type and buffering. Return
611 ;;; as multiple values the routine, the real type transfered, and the
612 ;;; number of bytes per element.
613 (defun pick-output-routine (type buffering &optional external-format)
614 (when (subtypep type 'character)
615 (let ((entry (get-external-format external-format)))
617 (return-from pick-output-routine
618 (values (symbol-function (nth (ecase buffering
625 (symbol-function (fourth entry))
626 (first (first entry)))))))
627 (dolist (entry *output-routines*)
628 (when (and (subtypep type (first entry))
629 (eq buffering (second entry))
630 (or (not (fifth entry))
631 (eq external-format (fifth entry))))
632 (return-from pick-output-routine
633 (values (symbol-function (third entry))
636 ;; KLUDGE: dealing with the buffering here leads to excessive code
639 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
640 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
641 if (subtypep type `(unsigned-byte ,i))
642 do (return-from pick-output-routine
646 (lambda (stream byte)
647 (output-wrapper (stream (/ i 8) (:none) nil)
648 (loop for j from 0 below (/ i 8)
650 (fd-stream-obuf-sap stream)
651 (+ j (fd-stream-obuf-tail stream)))
652 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
654 (lambda (stream byte)
655 (output-wrapper (stream (/ i 8) (:full) nil)
656 (loop for j from 0 below (/ i 8)
658 (fd-stream-obuf-sap stream)
659 (+ j (fd-stream-obuf-tail stream)))
660 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
663 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
664 if (subtypep type `(signed-byte ,i))
665 do (return-from pick-output-routine
669 (lambda (stream byte)
670 (output-wrapper (stream (/ i 8) (:none) nil)
671 (loop for j from 0 below (/ i 8)
673 (fd-stream-obuf-sap stream)
674 (+ j (fd-stream-obuf-tail stream)))
675 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
677 (lambda (stream byte)
678 (output-wrapper (stream (/ i 8) (:full) nil)
679 (loop for j from 0 below (/ i 8)
681 (fd-stream-obuf-sap stream)
682 (+ j (fd-stream-obuf-tail stream)))
683 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
687 ;;;; input routines and related noise
689 ;;; a list of all available input routines. Each element is a list of
690 ;;; the element-type input, the function name, and the number of bytes
692 (defvar *input-routines* ())
694 ;;; Return whether a primitive partial read operation on STREAM's FD
695 ;;; would (probably) block. Signal a `simple-stream-error' if the
696 ;;; system call implementing this operation fails.
698 ;;; It is "may" instead of "would" because "would" is not quite
699 ;;; correct on win32. However, none of the places that use it require
700 ;;; further assurance than "may" versus "will definitely not".
701 (defun sysread-may-block-p (stream)
703 ;; This answers T at EOF on win32, I think.
704 (not (sb!win32:fd-listen (fd-stream-fd stream)))
706 (sb!unix:with-restarted-syscall (count errno)
707 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
708 (sb!unix:fd-zero read-fds)
709 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
710 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
711 (sb!alien:addr read-fds)
717 (simple-stream-perror "couldn't check whether ~S is readable"
721 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
722 ;;; then fill the input buffer, and return the number of bytes read. Throws
723 ;;; to EOF-INPUT-CATCHER if the eof was reached.
724 (defun refill-buffer/fd (stream)
725 (let ((fd (fd-stream-fd stream))
729 ;; Check for blocking input before touching the stream, as if
730 ;; we happen to wait we are liable to be interrupted, and the
731 ;; interrupt handler may use the same stream.
732 (if (sysread-may-block-p stream)
735 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
736 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
738 (closed-flame stream)
740 (simple-stream-perror "couldn't read from ~S" stream errno)
742 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
743 ;; to wait for input if read tells us EWOULDBLOCK.
744 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
745 (signal-timeout 'io-timeout :stream stream :direction :read
746 :seconds (fd-stream-timeout stream)))
748 ;; Since the read should not block, we'll disable the
749 ;; interrupts here, so that we don't accidentally unwind and
750 ;; leave the stream in an inconsistent state.
752 (let ((ibuf-sap (fd-stream-ibuf-sap stream))
753 (buflen (fd-stream-ibuf-length stream))
754 (head (fd-stream-ibuf-head stream))
755 (tail (fd-stream-ibuf-tail stream)))
756 (declare (type index head tail))
757 ;; Check the SAP: if it is null, then someone has closed
758 ;; the stream from underneath us. This is not ment to fix
759 ;; multithreaded races, but to deal with interrupt handlers
760 ;; closing the stream.
764 (cond ((eql head tail)
767 (fd-stream-ibuf-head stream) 0
768 (fd-stream-ibuf-tail stream) 0))
771 (system-area-ub8-copy ibuf-sap head
774 (fd-stream-ibuf-head stream) 0
775 (fd-stream-ibuf-tail stream) tail))))
776 (setf (fd-stream-listen stream) nil)
777 (setf (values count errno)
778 (sb!unix:unix-read fd (int-sap (+ (sap-int ibuf-sap) tail))
784 (if (eql errno sb!unix:ewouldblock)
788 (setf (fd-stream-listen stream) :eof)
789 (/show0 "THROWing EOF-INPUT-CATCHER")
790 (throw 'eof-input-catcher nil))
793 (incf (fd-stream-ibuf-tail stream) count))))))
796 ;;; Make sure there are at least BYTES number of bytes in the input
797 ;;; buffer. Keep calling REFILL-BUFFER/FD until that condition is met.
798 (defmacro input-at-least (stream bytes)
799 (let ((stream-var (gensym))
800 (bytes-var (gensym)))
801 `(let ((,stream-var ,stream)
804 (when (>= (- (fd-stream-ibuf-tail ,stream-var)
805 (fd-stream-ibuf-head ,stream-var))
808 (refill-buffer/fd ,stream-var)))))
810 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
812 (let ((stream-var (gensym))
814 (element-var (gensym)))
815 `(let ((,stream-var ,stream)
817 (if (fd-stream-unread ,stream-var)
819 (fd-stream-unread ,stream-var)
820 (setf (fd-stream-unread ,stream-var) nil)
821 (setf (fd-stream-listen ,stream-var) nil))
822 (let ((,element-var nil)
823 (decode-break-reason nil))
827 (catch 'eof-input-catcher
828 (setf decode-break-reason
829 (block decode-break-reason
830 (input-at-least ,stream-var 1)
831 (let* ((byte (sap-ref-8 (fd-stream-ibuf-sap
835 (declare (ignorable byte))
837 (input-at-least ,stream-var size)
838 (setq ,element-var (locally ,@read-forms))
839 (setq ,retry-var nil))
841 (when decode-break-reason
842 (stream-decoding-error-and-handle stream
843 decode-break-reason))
845 (let ((octet-count (- (fd-stream-ibuf-tail ,stream-var)
846 (fd-stream-ibuf-head ,stream-var))))
847 (when (or (zerop octet-count)
848 (and (not ,element-var)
849 (not decode-break-reason)
850 (stream-decoding-error-and-handle
851 stream octet-count)))
852 (setq ,retry-var nil)))))
854 (incf (fd-stream-ibuf-head ,stream-var) size)
857 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
859 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
860 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
861 (let ((stream-var (gensym))
862 (element-var (gensym)))
863 `(let ((,stream-var ,stream))
864 (if (fd-stream-unread ,stream-var)
866 (fd-stream-unread ,stream-var)
867 (setf (fd-stream-unread ,stream-var) nil)
868 (setf (fd-stream-listen ,stream-var) nil))
870 (catch 'eof-input-catcher
871 (input-at-least ,stream-var ,bytes)
872 (locally ,@read-forms))))
874 (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
877 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
879 (defmacro def-input-routine/variable-width (name
880 (type external-format size sap head)
883 (defun ,name (stream eof-error eof-value)
884 (input-wrapper/variable-width (stream ,size eof-error eof-value)
885 (let ((,sap (fd-stream-ibuf-sap stream))
886 (,head (fd-stream-ibuf-head stream)))
888 (setf *input-routines*
889 (nconc *input-routines*
890 (list (list ',type ',name 1 ',external-format))))))
892 (defmacro def-input-routine (name
896 (defun ,name (stream eof-error eof-value)
897 (input-wrapper (stream ,size eof-error eof-value)
898 (let ((,sap (fd-stream-ibuf-sap stream))
899 (,head (fd-stream-ibuf-head stream)))
901 (setf *input-routines*
902 (nconc *input-routines*
903 (list (list ',type ',name ',size nil))))))
905 ;;; STREAM-IN routine for reading a string char
906 (def-input-routine input-character
907 (character 1 sap head)
908 (code-char (sap-ref-8 sap head)))
910 ;;; STREAM-IN routine for reading an unsigned 8 bit number
911 (def-input-routine input-unsigned-8bit-byte
912 ((unsigned-byte 8) 1 sap head)
913 (sap-ref-8 sap head))
915 ;;; STREAM-IN routine for reading a signed 8 bit number
916 (def-input-routine input-signed-8bit-number
917 ((signed-byte 8) 1 sap head)
918 (signed-sap-ref-8 sap head))
920 ;;; STREAM-IN routine for reading an unsigned 16 bit number
921 (def-input-routine input-unsigned-16bit-byte
922 ((unsigned-byte 16) 2 sap head)
923 (sap-ref-16 sap head))
925 ;;; STREAM-IN routine for reading a signed 16 bit number
926 (def-input-routine input-signed-16bit-byte
927 ((signed-byte 16) 2 sap head)
928 (signed-sap-ref-16 sap head))
930 ;;; STREAM-IN routine for reading a unsigned 32 bit number
931 (def-input-routine input-unsigned-32bit-byte
932 ((unsigned-byte 32) 4 sap head)
933 (sap-ref-32 sap head))
935 ;;; STREAM-IN routine for reading a signed 32 bit number
936 (def-input-routine input-signed-32bit-byte
937 ((signed-byte 32) 4 sap head)
938 (signed-sap-ref-32 sap head))
940 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
942 (def-input-routine input-unsigned-64bit-byte
943 ((unsigned-byte 64) 8 sap head)
944 (sap-ref-64 sap head))
945 (def-input-routine input-signed-64bit-byte
946 ((signed-byte 64) 8 sap head)
947 (signed-sap-ref-64 sap head)))
949 ;;; Find an input routine to use given the type. Return as multiple
950 ;;; values the routine, the real type transfered, and the number of
951 ;;; bytes per element (and for character types string input routine).
952 (defun pick-input-routine (type &optional external-format)
953 (when (subtypep type 'character)
954 (dolist (entry *external-formats*)
955 (when (member external-format (first entry))
956 (return-from pick-input-routine
957 (values (symbol-function (third entry))
960 (symbol-function (second entry))
961 (first (first entry)))))))
962 (dolist (entry *input-routines*)
963 (when (and (subtypep type (first entry))
964 (or (not (fourth entry))
965 (eq external-format (fourth entry))))
966 (return-from pick-input-routine
967 (values (symbol-function (second entry))
970 ;; FIXME: let's do it the hard way, then (but ignore things like
971 ;; endianness, efficiency, and the necessary coupling between these
972 ;; and the output routines). -- CSR, 2004-02-09
973 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
974 if (subtypep type `(unsigned-byte ,i))
975 do (return-from pick-input-routine
977 (lambda (stream eof-error eof-value)
978 (input-wrapper (stream (/ i 8) eof-error eof-value)
979 (let ((sap (fd-stream-ibuf-sap stream))
980 (head (fd-stream-ibuf-head stream)))
981 (loop for j from 0 below (/ i 8)
985 (sap-ref-8 sap (+ head j))))
986 finally (return result)))))
989 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
990 if (subtypep type `(signed-byte ,i))
991 do (return-from pick-input-routine
993 (lambda (stream eof-error eof-value)
994 (input-wrapper (stream (/ i 8) eof-error eof-value)
995 (let ((sap (fd-stream-ibuf-sap stream))
996 (head (fd-stream-ibuf-head stream)))
997 (loop for j from 0 below (/ i 8)
1001 (sap-ref-8 sap (+ head j))))
1002 finally (return (if (logbitp (1- i) result)
1003 (dpb result (byte i 0) -1)
1008 ;;; Return a string constructed from SAP, START, and END.
1009 (defun string-from-sap (sap start end)
1010 (declare (type index start end))
1011 (let* ((length (- end start))
1012 (string (make-string length)))
1013 (copy-ub8-from-system-area sap start
1018 ;;; the N-BIN method for FD-STREAMs
1020 ;;; Note that this blocks in UNIX-READ. It is generally used where
1021 ;;; there is a definite amount of reading to be done, so blocking
1022 ;;; isn't too problematical.
1023 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1024 &aux (total-copied 0))
1025 (declare (type fd-stream stream))
1026 (declare (type index start requested total-copied))
1027 (let ((unread (fd-stream-unread stream)))
1029 ;; AVERs designed to fail when we have more complicated
1030 ;; character representations.
1031 (aver (typep unread 'base-char))
1032 (aver (= (fd-stream-element-size stream) 1))
1033 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1036 (system-area-pointer
1037 (setf (sap-ref-8 buffer start) (char-code unread)))
1038 ((simple-unboxed-array (*))
1039 (setf (aref buffer start) unread)))
1040 (setf (fd-stream-unread stream) nil)
1041 (setf (fd-stream-listen stream) nil)
1042 (incf total-copied)))
1045 (let* ((remaining-request (- requested total-copied))
1046 (head (fd-stream-ibuf-head stream))
1047 (tail (fd-stream-ibuf-tail stream))
1048 (available (- tail head))
1049 (n-this-copy (min remaining-request available))
1050 (this-start (+ start total-copied))
1051 (this-end (+ this-start n-this-copy))
1052 (sap (fd-stream-ibuf-sap stream)))
1053 (declare (type index remaining-request head tail available))
1054 (declare (type index n-this-copy))
1055 ;; Copy data from stream buffer into user's buffer.
1056 (%byte-blt sap head buffer this-start this-end)
1057 (incf (fd-stream-ibuf-head stream) n-this-copy)
1058 (incf total-copied n-this-copy)
1059 ;; Maybe we need to refill the stream buffer.
1060 (cond (;; If there were enough data in the stream buffer, we're done.
1061 (= total-copied requested)
1062 (return total-copied))
1063 (;; If EOF, we're done in another way.
1064 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1066 (error 'end-of-file :stream stream)
1067 (return total-copied)))
1068 ;; Otherwise we refilled the stream buffer, so fall
1069 ;; through into another pass of the loop.
1072 (defun fd-stream-resync (stream)
1073 (dolist (entry *external-formats*)
1074 (when (member (fd-stream-external-format stream) (first entry))
1075 (return-from fd-stream-resync
1076 (funcall (symbol-function (eighth entry)) stream)))))
1078 (defun get-fd-stream-character-sizer (stream)
1079 (dolist (entry *external-formats*)
1080 (when (member (fd-stream-external-format stream) (first entry))
1081 (return-from get-fd-stream-character-sizer (ninth entry)))))
1083 (defun fd-stream-character-size (stream char)
1084 (let ((sizer (get-fd-stream-character-sizer stream)))
1085 (when sizer (funcall sizer char))))
1087 (defun fd-stream-string-size (stream string)
1088 (let ((sizer (get-fd-stream-character-sizer stream)))
1090 (loop for char across string summing (funcall sizer char)))))
1092 (defun find-external-format (external-format)
1093 (when external-format
1094 (find external-format *external-formats* :test #'member :key #'car)))
1096 (defun variable-width-external-format-p (ef-entry)
1097 (when (eighth ef-entry) t))
1099 (defun bytes-for-char-fun (ef-entry)
1100 (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1102 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1103 (defmacro define-external-format (external-format size output-restart
1105 (let* ((name (first external-format))
1106 (out-function (symbolicate "OUTPUT-BYTES/" name))
1107 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1108 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1109 (in-char-function (symbolicate "INPUT-CHAR/" name))
1110 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1111 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1112 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1113 (n-buffer (gensym "BUFFER")))
1115 (defun ,size-function (byte)
1116 (declare (ignore byte))
1118 (defun ,out-function (stream string flush-p start end)
1119 (let ((start (or start 0))
1120 (end (or end (length string))))
1121 (declare (type index start end))
1122 (when (and (not (fd-stream-dual-channel-p stream))
1123 (> (fd-stream-ibuf-tail stream)
1124 (fd-stream-ibuf-head stream)))
1125 (file-position stream (file-position stream)))
1126 (unless (<= 0 start end (length string))
1127 (signal-bounding-indices-bad-error string start end))
1130 (setf (fd-stream-obuf-tail stream)
1131 (string-dispatch (simple-base-string
1133 (simple-array character)
1136 (let ((len (fd-stream-obuf-length stream))
1137 (sap (fd-stream-obuf-sap stream))
1138 (tail (fd-stream-obuf-tail stream)))
1139 (declare (type index tail)
1140 ;; STRING bounds have already been checked.
1141 (optimize (safety 0)))
1143 (,@(if output-restart
1144 `(catch 'output-nothing)
1147 ((or (= start end) (< (- len tail) 4)))
1148 (let* ((byte (aref string start))
1149 (bits (char-code byte)))
1153 ;; Exited from the loop normally
1155 ;; Exited via CATCH. Skip the current character
1156 ;; and try the inner loop again.
1159 (flush-output-buffer stream)))
1161 (flush-output-buffer stream))))
1162 (def-output-routines (,format
1168 (if (char= byte #\Newline)
1169 (setf (fd-stream-char-pos stream) 0)
1170 (incf (fd-stream-char-pos stream)))
1171 (let ((bits (char-code byte))
1172 (sap (fd-stream-obuf-sap stream))
1173 (tail (fd-stream-obuf-tail stream)))
1175 (defun ,in-function (stream buffer start requested eof-error-p
1176 &aux (index start) (end (+ start requested)))
1177 (declare (type fd-stream stream)
1178 (type index start requested index end)
1180 (simple-array character (#.+ansi-stream-in-buffer-length+))
1182 (let ((unread (fd-stream-unread stream)))
1184 (setf (aref buffer index) unread)
1185 (setf (fd-stream-unread stream) nil)
1186 (setf (fd-stream-listen stream) nil)
1190 (let* ((head (fd-stream-ibuf-head stream))
1191 (tail (fd-stream-ibuf-tail stream))
1192 (sap (fd-stream-ibuf-sap stream)))
1193 (declare (type index head tail)
1194 (type system-area-pointer sap))
1195 ;; Copy data from stream buffer into user's buffer.
1196 (dotimes (i (min (truncate (- tail head) ,size)
1198 (declare (optimize speed))
1199 (let* ((byte (sap-ref-8 sap head)))
1200 (setf (aref buffer index) ,in-expr)
1203 (setf (fd-stream-ibuf-head stream) head)
1204 ;; Maybe we need to refill the stream buffer.
1205 (cond ( ;; If there was enough data in the stream buffer, we're done.
1207 (return (- index start)))
1208 ( ;; If EOF, we're done in another way.
1209 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1211 (error 'end-of-file :stream stream)
1212 (return (- index start))))
1213 ;; Otherwise we refilled the stream buffer, so fall
1214 ;; through into another pass of the loop.
1216 (def-input-routine ,in-char-function (character ,size sap head)
1217 (let ((byte (sap-ref-8 sap head)))
1219 (defun ,read-c-string-function (sap element-type)
1220 (declare (type system-area-pointer sap)
1221 (type (member character base-char) element-type))
1223 (declare (optimize (speed 3) (safety 0)))
1224 (let* ((stream ,name)
1226 (loop for head of-type index upfrom 0 by ,size
1227 for count of-type index upto (1- array-dimension-limit)
1228 for byte = (sap-ref-8 sap head)
1229 for char of-type character = ,in-expr
1230 until (zerop (char-code char))
1231 finally (return count)))
1232 ;; Inline the common cases
1233 (string (make-string length :element-type element-type)))
1234 (declare (ignorable stream)
1236 (type simple-string string))
1237 (/show0 before-copy-loop)
1238 (loop for head of-type index upfrom 0 by ,size
1239 for index of-type index below length
1240 for byte = (sap-ref-8 sap head)
1241 for char of-type character = ,in-expr
1242 do (setf (aref string index) char))
1243 string))) ;; last loop rewrite to dotimes?
1244 (defun ,output-c-string-function (string)
1245 (declare (type simple-string string))
1247 (declare (optimize (speed 3) (safety 0)))
1248 (let* ((length (length string))
1249 (,n-buffer (make-array (* (1+ length) ,size)
1250 :element-type '(unsigned-byte 8)))
1251 ;; This SAP-taking may seem unsafe without pinning,
1252 ;; but since the variable name is a gensym OUT-EXPR
1253 ;; cannot close over it even if it tried, so the buffer
1254 ;; will always be either in a register or on stack.
1255 ;; FIXME: But ...this is true on x86oids only!
1256 (sap (vector-sap ,n-buffer))
1259 (declare (type index length tail)
1260 (type system-area-pointer sap))
1262 (let* ((byte (aref string i))
1263 (bits (char-code byte)))
1264 (declare (ignorable byte bits))
1268 (byte (code-char bits)))
1269 (declare (ignorable bits byte))
1272 (setf *external-formats*
1273 (cons '(,external-format ,in-function ,in-char-function ,out-function
1274 ,@(mapcar #'(lambda (buffering)
1275 (intern (format nil format (string buffering))))
1276 '(:none :line :full))
1277 nil ; no resync-function
1278 ,size-function ,read-c-string-function ,output-c-string-function)
1279 *external-formats*)))))
1281 (defmacro define-external-format/variable-width
1282 (external-format output-restart out-size-expr
1283 out-expr in-size-expr in-expr)
1284 (let* ((name (first external-format))
1285 (out-function (symbolicate "OUTPUT-BYTES/" name))
1286 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1287 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1288 (in-char-function (symbolicate "INPUT-CHAR/" name))
1289 (resync-function (symbolicate "RESYNC/" name))
1290 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1291 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1292 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1293 (n-buffer (gensym "BUFFER")))
1295 (defun ,size-function (byte)
1296 (declare (ignorable byte))
1298 (defun ,out-function (stream string flush-p start end)
1299 (let ((start (or start 0))
1300 (end (or end (length string))))
1301 (declare (type index start end))
1302 (when (and (not (fd-stream-dual-channel-p stream))
1303 (> (fd-stream-ibuf-tail stream)
1304 (fd-stream-ibuf-head stream)))
1305 (file-position stream (file-position stream)))
1306 (unless (<= 0 start end (length string))
1307 (signal-bounding-indices-bad-error string start end))
1310 (setf (fd-stream-obuf-tail stream)
1311 (string-dispatch (simple-base-string
1313 (simple-array character)
1316 (let ((len (fd-stream-obuf-length stream))
1317 (sap (fd-stream-obuf-sap stream))
1318 (tail (fd-stream-obuf-tail stream)))
1319 (declare (type index tail)
1320 ;; STRING bounds have already been checked.
1321 (optimize (safety 0)))
1323 (,@(if output-restart
1324 `(catch 'output-nothing)
1327 ((or (= start end) (< (- len tail) 4)))
1328 (let* ((byte (aref string start))
1329 (bits (char-code byte))
1330 (size ,out-size-expr))
1334 ;; Exited from the loop normally
1336 ;; Exited via CATCH. Skip the current character
1337 ;; and try the inner loop again.
1340 (flush-output-buffer stream)))
1342 (flush-output-buffer stream))))
1343 (def-output-routines/variable-width (,format
1350 (if (char= byte #\Newline)
1351 (setf (fd-stream-char-pos stream) 0)
1352 (incf (fd-stream-char-pos stream)))
1353 (let ((bits (char-code byte))
1354 (sap (fd-stream-obuf-sap stream))
1355 (tail (fd-stream-obuf-tail stream)))
1357 (defun ,in-function (stream buffer start requested eof-error-p
1358 &aux (total-copied 0))
1359 (declare (type fd-stream stream)
1360 (type index start requested total-copied)
1362 (simple-array character (#.+ansi-stream-in-buffer-length+))
1364 (let ((unread (fd-stream-unread stream)))
1366 (setf (aref buffer start) unread)
1367 (setf (fd-stream-unread stream) nil)
1368 (setf (fd-stream-listen stream) nil)
1369 (incf total-copied)))
1372 (let* ((head (fd-stream-ibuf-head stream))
1373 (tail (fd-stream-ibuf-tail stream))
1374 (sap (fd-stream-ibuf-sap stream))
1375 (decode-break-reason nil))
1376 (declare (type index head tail))
1377 ;; Copy data from stream buffer into user's buffer.
1378 (do ((size nil nil))
1379 ((or (= tail head) (= requested total-copied)))
1380 (setf decode-break-reason
1381 (block decode-break-reason
1382 (let ((byte (sap-ref-8 sap head)))
1383 (declare (ignorable byte))
1384 (setq size ,in-size-expr)
1385 (when (> size (- tail head))
1387 (setf (aref buffer (+ start total-copied)) ,in-expr)
1391 (setf (fd-stream-ibuf-head stream) head)
1392 (when decode-break-reason
1393 ;; If we've already read some characters on when the invalid
1394 ;; code sequence is detected, we return immediately. The
1395 ;; handling of the error is deferred until the next call
1396 ;; (where this check will be false). This allows establishing
1397 ;; high-level handlers for decode errors (for example
1398 ;; automatically resyncing in Lisp comments).
1399 (when (plusp total-copied)
1400 (return-from ,in-function total-copied))
1401 (when (stream-decoding-error-and-handle
1402 stream decode-break-reason)
1404 (error 'end-of-file :stream stream)
1405 (return-from ,in-function total-copied)))
1406 (setf head (fd-stream-ibuf-head stream))
1407 (setf tail (fd-stream-ibuf-tail stream))))
1408 (setf (fd-stream-ibuf-head stream) head)
1409 ;; Maybe we need to refill the stream buffer.
1410 (cond ( ;; If there were enough data in the stream buffer, we're done.
1411 (= total-copied requested)
1412 (return total-copied))
1413 ( ;; If EOF, we're done in another way.
1414 (or (eq decode-break-reason 'eof)
1415 (null (catch 'eof-input-catcher
1416 (refill-buffer/fd stream))))
1418 (error 'end-of-file :stream stream)
1419 (return total-copied)))
1420 ;; Otherwise we refilled the stream buffer, so fall
1421 ;; through into another pass of the loop.
1423 (def-input-routine/variable-width ,in-char-function (character
1427 (let ((byte (sap-ref-8 sap head)))
1428 (declare (ignorable byte))
1430 (defun ,resync-function (stream)
1431 (loop (input-at-least stream 2)
1432 (incf (fd-stream-ibuf-head stream))
1433 (unless (block decode-break-reason
1434 (let* ((sap (fd-stream-ibuf-sap stream))
1435 (head (fd-stream-ibuf-head stream))
1436 (byte (sap-ref-8 sap head))
1437 (size ,in-size-expr))
1438 (declare (ignorable byte))
1439 (input-at-least stream size)
1440 (let ((sap (fd-stream-ibuf-sap stream))
1441 (head (fd-stream-ibuf-head stream)))
1445 (defun ,read-c-string-function (sap element-type)
1446 (declare (type system-area-pointer sap))
1448 (declare (optimize (speed 3) (safety 0)))
1449 (let* ((stream ,name)
1450 (size 0) (head 0) (byte 0) (char nil)
1451 (decode-break-reason nil)
1452 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1453 (setf decode-break-reason
1454 (block decode-break-reason
1455 (setf byte (sap-ref-8 sap head)
1460 (when decode-break-reason
1461 (c-string-decoding-error ,name decode-break-reason))
1462 (when (zerop (char-code char))
1464 (string (make-string length :element-type element-type)))
1465 (declare (ignorable stream)
1466 (type index head length) ;; size
1467 (type (unsigned-byte 8) byte)
1468 (type (or null character) char)
1469 (type string string))
1471 (dotimes (index length string)
1472 (setf decode-break-reason
1473 (block decode-break-reason
1474 (setf byte (sap-ref-8 sap head)
1479 (when decode-break-reason
1480 (c-string-decoding-error ,name decode-break-reason))
1481 (setf (aref string index) char)))))
1483 (defun ,output-c-string-function (string)
1484 (declare (type simple-string string))
1486 (declare (optimize (speed 3) (safety 0)))
1487 (let* ((length (length string))
1488 (char-length (make-array (1+ length) :element-type 'index))
1490 (+ (loop for i of-type index below length
1491 for byte of-type character = (aref string i)
1492 for bits = (char-code byte)
1493 sum (setf (aref char-length i)
1494 (the index ,out-size-expr)))
1495 (let* ((byte (code-char 0))
1496 (bits (char-code byte)))
1497 (declare (ignorable byte bits))
1498 (setf (aref char-length length)
1499 (the index ,out-size-expr)))))
1501 (,n-buffer (make-array buffer-length
1502 :element-type '(unsigned-byte 8)))
1503 ;; This SAP-taking may seem unsafe without pinning,
1504 ;; but since the variable name is a gensym OUT-EXPR
1505 ;; cannot close over it even if it tried, so the buffer
1506 ;; will always be either in a register or on stack.
1507 ;; FIXME: But ...this is true on x86oids only!
1508 (sap (vector-sap ,n-buffer))
1510 (declare (type index length buffer-length tail)
1511 (type system-area-pointer sap)
1514 (loop for i of-type index below length
1515 for byte of-type character = (aref string i)
1516 for bits = (char-code byte)
1517 for size of-type index = (aref char-length i)
1522 (byte (code-char bits))
1523 (size (aref char-length length)))
1524 (declare (ignorable bits byte size))
1528 (setf *external-formats*
1529 (cons '(,external-format ,in-function ,in-char-function ,out-function
1530 ,@(mapcar #'(lambda (buffering)
1531 (intern (format nil format (string buffering))))
1532 '(:none :line :full))
1534 ,size-function ,read-c-string-function ,output-c-string-function)
1535 *external-formats*)))))
1537 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1538 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1539 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1540 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1543 (external-format-encoding-error stream bits)
1544 (setf (sap-ref-8 sap tail) bits))
1547 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1548 :iso-646 :iso-646-us :|646|)
1551 (external-format-encoding-error stream bits)
1552 (setf (sap-ref-8 sap tail) bits))
1555 (let* ((table (let ((s (make-string 256)))
1556 (map-into s #'code-char
1557 '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1558 #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1559 #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1560 #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1561 #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1562 #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1563 #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1564 #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1565 #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1566 #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1567 #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1568 #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1569 #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1570 #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1571 #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1572 #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1574 (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1575 (loop for char across table for i from 0
1576 do (aver (= 0 (aref rt (char-code char))))
1577 do (setf (aref rt (char-code char)) i))
1579 (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1582 (external-format-encoding-error stream bits)
1583 (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1588 (let ((latin-9-table (let ((table (make-string 256)))
1591 (setf (aref table i) (code-char i)))
1592 (setf (aref table #xa4) (code-char #x20ac))
1593 (setf (aref table #xa6) (code-char #x0160))
1594 (setf (aref table #xa8) (code-char #x0161))
1595 (setf (aref table #xb4) (code-char #x017d))
1596 (setf (aref table #xb8) (code-char #x017e))
1597 (setf (aref table #xbc) (code-char #x0152))
1598 (setf (aref table #xbd) (code-char #x0153))
1599 (setf (aref table #xbe) (code-char #x0178))
1601 (latin-9-reverse-1 (make-array 16
1602 :element-type '(unsigned-byte 21)
1603 :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1604 (latin-9-reverse-2 (make-array 16
1605 :element-type '(unsigned-byte 8)
1606 :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1607 (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1609 (setf (sap-ref-8 sap tail)
1611 (if (= bits (char-code (aref latin-9-table bits)))
1613 (external-format-encoding-error stream byte))
1614 (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1615 (aref latin-9-reverse-2 (logand bits 15))
1616 (external-format-encoding-error stream byte))))
1617 (aref latin-9-table byte)))
1619 (define-external-format/variable-width (:utf-8 :utf8) nil
1620 (let ((bits (char-code byte)))
1621 (cond ((< bits #x80) 1)
1623 ((< bits #x10000) 3)
1626 (1 (setf (sap-ref-8 sap tail) bits))
1627 (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1628 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 0) bits))))
1629 (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1630 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 6) bits))
1631 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1632 (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1633 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 12) bits))
1634 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1635 (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1636 (cond ((< byte #x80) 1)
1637 ((< byte #xc2) (return-from decode-break-reason 1))
1641 (code-char (ecase size
1643 (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1644 (unless (<= #x80 byte2 #xbf)
1645 (return-from decode-break-reason 2))
1646 (dpb byte (byte 5 6) byte2)))
1647 (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1648 (byte3 (sap-ref-8 sap (+ 2 head))))
1649 (unless (and (<= #x80 byte2 #xbf)
1650 (<= #x80 byte3 #xbf))
1651 (return-from decode-break-reason 3))
1652 (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1653 (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1654 (byte3 (sap-ref-8 sap (+ 2 head)))
1655 (byte4 (sap-ref-8 sap (+ 3 head))))
1656 (unless (and (<= #x80 byte2 #xbf)
1657 (<= #x80 byte3 #xbf)
1658 (<= #x80 byte4 #xbf))
1659 (return-from decode-break-reason 4))
1660 (dpb byte (byte 3 18)
1661 (dpb byte2 (byte 6 12)
1662 (dpb byte3 (byte 6 6) byte4))))))))
1664 ;;;; utility functions (misc routines, etc)
1666 ;;; Fill in the various routine slots for the given type. INPUT-P and
1667 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1668 ;;; set prior to calling this routine.
1669 (defun set-fd-stream-routines (fd-stream element-type external-format
1670 input-p output-p buffer-p)
1671 (let* ((target-type (case element-type
1672 (unsigned-byte '(unsigned-byte 8))
1673 (signed-byte '(signed-byte 8))
1674 (:default 'character)
1676 (character-stream-p (subtypep target-type 'character))
1677 (bivalent-stream-p (eq element-type :default))
1678 normalized-external-format
1679 (bin-routine #'ill-bin)
1682 (cin-routine #'ill-in)
1685 (input-type nil) ;calculated from bin-type/cin-type
1686 (input-size nil) ;calculated from bin-size/cin-size
1687 (read-n-characters #'ill-in)
1688 (bout-routine #'ill-bout)
1691 (cout-routine #'ill-out)
1696 (output-bytes #'ill-bout))
1698 ;; drop buffers when direction changes
1699 (when (and (fd-stream-obuf-sap fd-stream) (not output-p))
1700 (with-available-buffers-lock ()
1701 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1702 (setf (fd-stream-obuf-sap fd-stream) nil)))
1703 (when (and (fd-stream-ibuf-sap fd-stream) (not input-p))
1704 (with-available-buffers-lock ()
1705 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1706 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1708 (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
1709 (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
1710 (setf (fd-stream-ibuf-tail fd-stream) 0))
1712 (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
1713 (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
1714 (setf (fd-stream-obuf-tail fd-stream) 0)
1715 (setf (fd-stream-char-pos fd-stream) 0))
1717 (when (and character-stream-p
1718 (eq external-format :default))
1719 (/show0 "/getting default external format")
1720 (setf external-format (default-external-format)))
1723 (when (or (not character-stream-p) bivalent-stream-p)
1724 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1725 normalized-external-format)
1726 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1730 (error "could not find any input routine for ~S" target-type)))
1731 (when character-stream-p
1732 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1733 normalized-external-format)
1734 (pick-input-routine target-type external-format))
1736 (error "could not find any input routine for ~S" target-type)))
1737 (setf (fd-stream-in fd-stream) cin-routine
1738 (fd-stream-bin fd-stream) bin-routine)
1739 ;; character type gets preferential treatment
1740 (setf input-size (or cin-size bin-size))
1741 (setf input-type (or cin-type bin-type))
1742 (when normalized-external-format
1743 (setf (fd-stream-external-format fd-stream)
1744 normalized-external-format))
1745 (when (= (or cin-size 1) (or bin-size 1) 1)
1746 (setf (fd-stream-n-bin fd-stream) ;XXX
1747 (if (and character-stream-p (not bivalent-stream-p))
1749 #'fd-stream-read-n-bytes))
1750 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1751 ;; for character and (unsigned-byte 8) streams. In these
1752 ;; cases, fast-read-* will read from the
1753 ;; ansi-stream-(c)in-buffer, saving function calls.
1754 ;; Otherwise, the various data-reading functions in the stream
1755 ;; structure will be called.
1757 (not bivalent-stream-p)
1758 ;; temporary disable on :io streams
1760 (cond (character-stream-p
1761 (setf (ansi-stream-cin-buffer fd-stream)
1762 (make-array +ansi-stream-in-buffer-length+
1763 :element-type 'character)))
1764 ((equal target-type '(unsigned-byte 8))
1765 (setf (ansi-stream-in-buffer fd-stream)
1766 (make-array +ansi-stream-in-buffer-length+
1767 :element-type '(unsigned-byte 8))))))))
1770 (when (or (not character-stream-p) bivalent-stream-p)
1771 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1772 normalized-external-format)
1773 (pick-output-routine (if bivalent-stream-p
1776 (fd-stream-buffering fd-stream)
1778 (unless bout-routine
1779 (error "could not find any output routine for ~S buffered ~S"
1780 (fd-stream-buffering fd-stream)
1782 (when character-stream-p
1783 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1784 normalized-external-format)
1785 (pick-output-routine target-type
1786 (fd-stream-buffering fd-stream)
1788 (unless cout-routine
1789 (error "could not find any output routine for ~S buffered ~S"
1790 (fd-stream-buffering fd-stream)
1792 (when normalized-external-format
1793 (setf (fd-stream-external-format fd-stream)
1794 normalized-external-format))
1795 (when character-stream-p
1796 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1797 (setf (fd-stream-out fd-stream) cout-routine
1798 (fd-stream-bout fd-stream) bout-routine
1799 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1800 #'fd-sout #'ill-out))
1801 (setf output-size (or cout-size bout-size))
1802 (setf output-type (or cout-type bout-type)))
1804 (when (and input-size output-size
1805 (not (eq input-size output-size)))
1806 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1807 input-type input-size
1808 output-type output-size))
1809 (setf (fd-stream-element-size fd-stream)
1810 (or input-size output-size))
1812 (setf (fd-stream-element-type fd-stream)
1813 (cond ((equal input-type output-type)
1819 ((subtypep input-type output-type)
1821 ((subtypep output-type input-type)
1824 (error "Input type (~S) and output type (~S) are unrelated?"
1828 ;;; Handle miscellaneous operations on FD-STREAM.
1829 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1830 (declare (ignore arg2))
1833 (labels ((do-listen ()
1834 (or (not (eql (fd-stream-ibuf-head fd-stream)
1835 (fd-stream-ibuf-tail fd-stream)))
1836 (fd-stream-listen fd-stream)
1838 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1840 ;; If the read can block, LISTEN will certainly return NIL.
1841 (if (sysread-may-block-p fd-stream)
1843 ;; Otherwise select(2) and CL:LISTEN have slightly
1844 ;; different semantics. The former returns that an FD
1845 ;; is readable when a read operation wouldn't block.
1846 ;; That includes EOF. However, LISTEN must return NIL
1848 (progn (catch 'eof-input-catcher
1849 ;; r-b/f too calls select, but it shouldn't
1850 ;; block as long as read can return once w/o
1852 (refill-buffer/fd fd-stream))
1853 ;; At this point either IBUF-HEAD != IBUF-TAIL
1854 ;; and FD-STREAM-LISTEN is NIL, in which case
1855 ;; we should return T, or IBUF-HEAD ==
1856 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1857 ;; which case we should return :EOF for this
1858 ;; call and all future LISTEN call on this stream.
1859 ;; Call ourselves again to determine which case
1864 (setf (fd-stream-unread fd-stream) arg1)
1865 (setf (fd-stream-listen fd-stream) t))
1867 (cond (arg1 ; We got us an abort on our hands.
1868 (when (fd-stream-handler fd-stream)
1869 (remove-fd-handler (fd-stream-handler fd-stream))
1870 (setf (fd-stream-handler fd-stream) nil))
1871 ;; We can't do anything unless we know what file were
1872 ;; dealing with, and we don't want to do anything
1873 ;; strange unless we were writing to the file.
1874 (when (and (fd-stream-file fd-stream)
1875 (fd-stream-obuf-sap fd-stream))
1876 (if (fd-stream-original fd-stream)
1877 ;; If the original is EQ to file we are appending
1878 ;; and can just close the file without renaming.
1879 (unless (eq (fd-stream-original fd-stream)
1880 (fd-stream-file fd-stream))
1881 ;; We have a handle on the original, just revert.
1882 (multiple-value-bind (okay err)
1883 (sb!unix:unix-rename (fd-stream-original fd-stream)
1884 (fd-stream-file fd-stream))
1886 (simple-stream-perror
1887 "couldn't restore ~S to its original contents"
1890 ;; We can't restore the original, and aren't
1891 ;; appending, so nuke that puppy.
1893 ;; FIXME: This is currently the fate of superseded
1894 ;; files, and according to the CLOSE spec this is
1895 ;; wrong. However, there seems to be no clean way to
1896 ;; do that that doesn't involve either copying the
1897 ;; data (bad if the :abort resulted from a full
1898 ;; disk), or renaming the old file temporarily
1899 ;; (probably bad because stream opening becomes more
1901 (multiple-value-bind (okay err)
1902 (sb!unix:unix-unlink (fd-stream-file fd-stream))
1904 (error 'simple-file-error
1905 :pathname (fd-stream-file fd-stream)
1907 "~@<couldn't remove ~S: ~2I~_~A~:>"
1908 :format-arguments (list (fd-stream-file fd-stream)
1909 (strerror err))))))))
1911 (fd-stream-misc-routine fd-stream :finish-output)
1912 (when (and (fd-stream-original fd-stream)
1913 (fd-stream-delete-original fd-stream))
1914 (multiple-value-bind (okay err)
1915 (sb!unix:unix-unlink (fd-stream-original fd-stream))
1917 (error 'simple-file-error
1918 :pathname (fd-stream-original fd-stream)
1920 "~@<couldn't delete ~S during close of ~S: ~
1923 (list (fd-stream-original fd-stream)
1925 (strerror err))))))))
1926 (when (fboundp 'cancel-finalization)
1927 (cancel-finalization fd-stream))
1928 (sb!unix:unix-close (fd-stream-fd fd-stream))
1929 (when (fd-stream-obuf-sap fd-stream)
1930 (with-available-buffers-lock ()
1931 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1932 (setf (fd-stream-obuf-sap fd-stream) nil)))
1933 (when (fd-stream-ibuf-sap fd-stream)
1934 (with-available-buffers-lock ()
1935 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1936 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1937 (sb!impl::set-closed-flame fd-stream))
1939 (setf (fd-stream-unread fd-stream) nil)
1940 (setf (fd-stream-ibuf-head fd-stream) 0)
1941 (setf (fd-stream-ibuf-tail fd-stream) 0)
1944 (sb!win32:fd-clear-input (fd-stream-fd fd-stream))
1945 (setf (fd-stream-listen fd-stream) nil))
1947 (catch 'eof-input-catcher
1948 (loop until (sysread-may-block-p fd-stream)
1950 (refill-buffer/fd fd-stream)
1951 (setf (fd-stream-ibuf-head fd-stream) 0)
1952 (setf (fd-stream-ibuf-tail fd-stream) 0))
1955 (flush-output-buffer fd-stream))
1957 (finish-fd-stream-output fd-stream))
1959 (fd-stream-element-type fd-stream))
1961 (fd-stream-external-format fd-stream))
1963 (= 1 (the (member 0 1)
1964 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
1968 (fd-stream-char-pos fd-stream))
1970 (unless (fd-stream-file fd-stream)
1971 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
1972 ;; "should signal an error of type TYPE-ERROR if stream is not
1973 ;; a stream associated with a file". Too bad there's no very
1974 ;; appropriate value for the EXPECTED-TYPE slot..
1975 (error 'simple-type-error
1977 :expected-type 'fd-stream
1978 :format-control "~S is not a stream associated with a file."
1979 :format-arguments (list fd-stream)))
1980 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
1981 atime mtime ctime blksize blocks)
1982 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
1983 (declare (ignore ino nlink uid gid rdev
1984 atime mtime ctime blksize blocks))
1986 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
1989 (truncate size (fd-stream-element-size fd-stream)))))
1990 (:file-string-length
1992 (character (fd-stream-character-size fd-stream arg1))
1993 (string (fd-stream-string-size fd-stream arg1))))
1996 (fd-stream-set-file-position fd-stream arg1)
1997 (fd-stream-get-file-position fd-stream)))))
1999 ;; FIXME: Think about this.
2001 ;; (defun finish-fd-stream-output (fd-stream)
2002 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2003 ;; (loop while (fd-stream-output-later fd-stream)
2004 ;; ;; FIXME: SIGINT while waiting for a timeout will
2005 ;; ;; cause a timeout here.
2006 ;; do (when (and (not (serve-event timeout)) timeout)
2007 ;; (signal-timeout 'io-timeout
2008 ;; :stream fd-stream
2009 ;; :direction :write
2010 ;; :seconds timeout)))))
2012 (defun finish-fd-stream-output (stream)
2013 (flush-output-buffer stream)
2015 ((null (fd-stream-output-later stream)))
2016 (serve-all-events)))
2018 (defun fd-stream-get-file-position (stream)
2019 (declare (fd-stream stream))
2021 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2022 (declare (type (or (alien sb!unix:off-t) null) posn))
2023 ;; We used to return NIL for errno==ESPIPE, and signal an error
2024 ;; in other failure cases. However, CLHS says to return NIL if
2025 ;; the position cannot be determined -- so that's what we do.
2026 (when (integerp posn)
2027 ;; Adjust for buffered output: If there is any output
2028 ;; buffered, the *real* file position will be larger
2029 ;; than reported by lseek() because lseek() obviously
2030 ;; cannot take into account output we have not sent
2032 (dolist (later (fd-stream-output-later stream))
2033 (incf posn (- (caddr later) (cadr later))))
2034 (incf posn (fd-stream-obuf-tail stream))
2035 ;; Adjust for unread input: If there is any input
2036 ;; read from UNIX but not supplied to the user of the
2037 ;; stream, the *real* file position will smaller than
2038 ;; reported, because we want to look like the unread
2039 ;; stuff is still available.
2040 (decf posn (- (fd-stream-ibuf-tail stream)
2041 (fd-stream-ibuf-head stream)))
2042 (when (fd-stream-unread stream)
2044 ;; Divide bytes by element size.
2045 (truncate posn (fd-stream-element-size stream))))))
2047 (defun fd-stream-set-file-position (stream position-spec)
2048 (declare (fd-stream stream))
2049 (check-type position-spec
2050 (or (alien sb!unix:off-t) (member nil :start :end))
2051 "valid file position designator")
2054 ;; Make sure we don't have any output pending, because if we
2055 ;; move the file pointer before writing this stuff, it will be
2056 ;; written in the wrong location.
2057 (finish-fd-stream-output stream)
2058 ;; Disable interrupts so that interrupt handlers doing output
2061 (unless (fd-stream-output-finished-p stream)
2062 ;; We got interrupted and more output came our way during
2063 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2064 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2065 ;; so we prefer to do things like this...
2067 ;; Clear out any pending input to force the next read to go to
2069 (setf (fd-stream-unread stream) nil
2070 (fd-stream-ibuf-head stream) 0
2071 (fd-stream-ibuf-tail stream) 0)
2072 ;; Trash cached value for listen, so that we check next time.
2073 (setf (fd-stream-listen stream) nil)
2075 (multiple-value-bind (offset origin)
2078 (values 0 sb!unix:l_set))
2080 (values 0 sb!unix:l_xtnd))
2082 (values (* position-spec (fd-stream-element-size stream))
2084 (declare (type (alien sb!unix:off-t) offset))
2085 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2087 ;; CLHS says to return true if the file-position was set
2088 ;; succesfully, and NIL otherwise. We are to signal an error
2089 ;; only if the given position was out of bounds, and that is
2090 ;; dealt with above. In times past we used to return NIL for
2091 ;; errno==ESPIPE, and signal an error in other cases.
2093 ;; FIXME: We are still liable to signal an error if flushing
2095 (return-from fd-stream-set-file-position
2096 (typep posn '(alien sb!unix:off-t))))))))
2099 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2101 ;;; Create a stream for the given Unix file descriptor.
2103 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2104 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2105 ;;; default to allowing input.
2107 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2109 ;;; BUFFERING indicates the kind of buffering to use.
2111 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2112 ;;; NIL (the default), then wait forever. When we time out, we signal
2115 ;;; FILE is the name of the file (will be returned by PATHNAME).
2117 ;;; NAME is used to identify the stream when printed.
2118 (defun make-fd-stream (fd
2121 (output nil output-p)
2122 (element-type 'base-char)
2124 (external-format :default)
2133 (format nil "file ~A" file)
2134 (format nil "descriptor ~W" fd)))
2136 (declare (type index fd) (type (or real null) timeout)
2137 (type (member :none :line :full) buffering))
2138 (cond ((not (or input-p output-p))
2140 ((not (or input output))
2141 (error "File descriptor must be opened either for input or output.")))
2142 (let ((stream (%make-fd-stream :fd fd
2146 :delete-original delete-original
2148 :buffering buffering
2149 :dual-channel-p dual-channel-p
2150 :external-format external-format
2153 (coerce timeout 'single-float)
2155 (set-fd-stream-routines stream element-type external-format
2156 input output input-buffer-p)
2157 (when (and auto-close (fboundp 'finalize))
2160 (sb!unix:unix-close fd)
2162 (format *terminal-io* "** closed file descriptor ~W **~%"
2166 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2167 ;;; :RENAME-AND-DELETE and :RENAME options.
2168 (defun pick-backup-name (name)
2169 (declare (type simple-string name))
2170 (concatenate 'simple-string name ".bak"))
2172 ;;; Ensure that the given arg is one of the given list of valid
2173 ;;; things. Allow the user to fix any problems.
2174 (defun ensure-one-of (item list what)
2175 (unless (member item list)
2176 (error 'simple-type-error
2178 :expected-type `(member ,@list)
2179 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2180 :format-arguments (list item what list))))
2182 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2183 ;;; access, since we don't want to trash unwritable files even if we
2184 ;;; technically can. We return true if we succeed in renaming.
2185 (defun rename-the-old-one (namestring original)
2186 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2187 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2188 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2191 (error 'simple-file-error
2192 :pathname namestring
2194 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2195 :format-arguments (list namestring original (strerror err))))))
2197 (defun open (filename
2200 (element-type 'base-char)
2201 (if-exists nil if-exists-given)
2202 (if-does-not-exist nil if-does-not-exist-given)
2203 (external-format :default)
2204 &aux ; Squelch assignment warning.
2205 (direction direction)
2206 (if-does-not-exist if-does-not-exist)
2207 (if-exists if-exists))
2209 "Return a stream which reads from or writes to FILENAME.
2211 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2212 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2213 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2214 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2215 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2216 See the manual for details."
2218 ;; Calculate useful stuff.
2219 (multiple-value-bind (input output mask)
2221 (:input (values t nil sb!unix:o_rdonly))
2222 (:output (values nil t sb!unix:o_wronly))
2223 (:io (values t t sb!unix:o_rdwr))
2224 (:probe (values t nil sb!unix:o_rdonly)))
2225 (declare (type index mask))
2226 (let* ((pathname (merge-pathnames filename))
2228 (cond ((unix-namestring pathname input))
2229 ((and input (eq if-does-not-exist :create))
2230 (unix-namestring pathname nil))
2231 ((and (eq direction :io) (not if-does-not-exist-given))
2232 (unix-namestring pathname nil)))))
2233 ;; Process if-exists argument if we are doing any output.
2235 (unless if-exists-given
2237 (if (eq (pathname-version pathname) :newest)
2240 (ensure-one-of if-exists
2241 '(:error :new-version :rename
2242 :rename-and-delete :overwrite
2243 :append :supersede nil)
2246 ((:new-version :error nil)
2247 (setf mask (logior mask sb!unix:o_excl)))
2248 ((:rename :rename-and-delete)
2249 (setf mask (logior mask sb!unix:o_creat)))
2251 (setf mask (logior mask sb!unix:o_trunc)))
2253 (setf mask (logior mask sb!unix:o_append)))))
2255 (setf if-exists :ignore-this-arg)))
2257 (unless if-does-not-exist-given
2258 (setf if-does-not-exist
2259 (cond ((eq direction :input) :error)
2261 (member if-exists '(:overwrite :append)))
2263 ((eq direction :probe)
2267 (ensure-one-of if-does-not-exist
2268 '(:error :create nil)
2270 (if (eq if-does-not-exist :create)
2271 (setf mask (logior mask sb!unix:o_creat)))
2273 (let ((original (case if-exists
2274 ((:rename :rename-and-delete)
2275 (pick-backup-name namestring))
2276 ((:append :overwrite)
2277 ;; KLUDGE: Provent CLOSE from deleting
2278 ;; appending streams when called with :ABORT T
2280 (delete-original (eq if-exists :rename-and-delete))
2282 (when (and original (not (eq original namestring)))
2283 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2284 ;; whether the file already exists, make sure the original
2285 ;; file is not a directory, and keep the mode.
2288 (multiple-value-bind (okay err/dev inode orig-mode)
2289 (sb!unix:unix-stat namestring)
2290 (declare (ignore inode)
2291 (type (or index null) orig-mode))
2294 (when (and output (= (logand orig-mode #o170000)
2296 (error 'simple-file-error
2297 :pathname namestring
2299 "can't open ~S for output: is a directory"
2300 :format-arguments (list namestring)))
2301 (setf mode (logand orig-mode #o777))
2303 ((eql err/dev sb!unix:enoent)
2306 (simple-file-perror "can't find ~S"
2310 (rename-the-old-one namestring original))
2312 (setf delete-original nil)
2313 ;; In order to use :SUPERSEDE instead, we have to make
2314 ;; sure SB!UNIX:O_CREAT corresponds to
2315 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2316 ;; because of IF-EXISTS being :RENAME.
2317 (unless (eq if-does-not-exist :create)
2319 (logior (logandc2 mask sb!unix:o_creat)
2321 (setf if-exists :supersede))))
2323 ;; Now we can try the actual Unix open(2).
2324 (multiple-value-bind (fd errno)
2326 (sb!unix:unix-open namestring mask mode)
2327 (values nil sb!unix:enoent))
2328 (labels ((open-error (format-control &rest format-arguments)
2329 (error 'simple-file-error
2331 :format-control format-control
2332 :format-arguments format-arguments))
2333 (vanilla-open-error ()
2334 (simple-file-perror "error opening ~S" pathname errno)))
2337 ((:input :output :io)
2341 :element-type element-type
2342 :external-format external-format
2345 :delete-original delete-original
2352 (%make-fd-stream :name namestring
2355 :element-type element-type)))
2358 ((eql errno sb!unix:enoent)
2359 (case if-does-not-exist
2360 (:error (vanilla-open-error))
2362 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2365 ((and (eql errno sb!unix:eexist) (null if-exists))
2368 (vanilla-open-error)))))))))
2372 ;;; the stream connected to the controlling terminal, or NIL if there is none
2375 ;;; the stream connected to the standard input (file descriptor 0)
2378 ;;; the stream connected to the standard output (file descriptor 1)
2381 ;;; the stream connected to the standard error output (file descriptor 2)
2384 ;;; This is called when the cold load is first started up, and may also
2385 ;;; be called in an attempt to recover from nested errors.
2386 (defun stream-cold-init-or-reset ()
2388 (setf *terminal-io* (make-synonym-stream '*tty*))
2389 (setf *standard-output* (make-synonym-stream '*stdout*))
2390 (setf *standard-input* (make-synonym-stream '*stdin*))
2391 (setf *error-output* (make-synonym-stream '*stderr*))
2392 (setf *query-io* (make-synonym-stream '*terminal-io*))
2393 (setf *debug-io* *query-io*)
2394 (setf *trace-output* *standard-output*)
2397 ;;; This is called whenever a saved core is restarted.
2398 (defun stream-reinit ()
2399 (setf *available-buffers* nil)
2400 (with-output-to-string (*error-output*)
2402 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2403 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2405 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2406 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2408 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2409 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2410 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2411 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2415 :name "the terminal"
2420 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2421 (princ (get-output-stream-string *error-output*) *stderr*))
2426 ;;; the Unix way to beep
2427 (defun beep (stream)
2428 (write-char (code-char bell-char-code) stream)
2429 (finish-output stream))
2431 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2432 ;;; by the filesys stuff to get and set the file name.
2434 ;;; FIXME: misleading name, screwy interface
2435 (defun file-name (stream &optional new-name)
2436 (when (typep stream 'fd-stream)
2438 (setf (fd-stream-pathname stream) new-name)
2439 (setf (fd-stream-file stream)
2440 (unix-namestring new-name nil))
2443 (fd-stream-pathname stream)))))