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)
81 (char-pos nil :type (or index null))
82 ;; T if input is waiting on FD. :EOF if we hit EOF.
83 (listen nil :type (member nil t :eof))
87 (ibuf-sap nil :type (or system-area-pointer null))
88 (ibuf-length nil :type (or index null))
89 (ibuf-head 0 :type index)
90 (ibuf-tail 0 :type index)
93 (obuf-sap nil :type (or system-area-pointer null))
94 (obuf-length nil :type (or index null))
95 (obuf-tail 0 :type index)
97 ;; output flushed, but not written due to non-blocking io?
100 ;; timeout specified for this stream, or NIL if none
101 (timeout nil :type (or index null))
102 ;; pathname of the file this stream is opened to (returned by PATHNAME)
103 (pathname nil :type (or pathname null))
104 (external-format :default)
105 (output-bytes #'ill-out :type function))
106 (def!method print-object ((fd-stream fd-stream) stream)
107 (declare (type stream stream))
108 (print-unreadable-object (fd-stream stream :type t :identity t)
109 (format stream "for ~S" (fd-stream-name fd-stream))))
111 ;;;; output routines and related noise
113 (defvar *output-routines* ()
115 "List of all available output routines. Each element is a list of the
116 element-type output, the kind of buffering, the function name, and the number
117 of bytes per element.")
119 ;;; common idioms for reporting low-level stream and file problems
120 (defun simple-stream-perror (note-format stream errno)
121 (error 'simple-stream-error
123 :format-control "~@<~?: ~2I~_~A~:>"
124 :format-arguments (list note-format (list stream) (strerror errno))))
125 (defun simple-file-perror (note-format pathname errno)
126 (error 'simple-file-error
128 :format-control "~@<~?: ~2I~_~A~:>"
130 (list note-format (list pathname) (strerror errno))))
132 (defun stream-decoding-error (stream octets)
133 (error 'stream-decoding-error
135 ;; FIXME: dunno how to get at OCTETS currently, or even if
136 ;; that's the right thing to report.
138 (defun stream-encoding-error (stream code)
139 (error 'stream-encoding-error
143 (defun c-string-encoding-error (external-format code)
144 (error 'c-string-encoding-error
145 :external-format external-format
148 (defun c-string-decoding-error (external-format octets)
149 (error 'c-string-decoding-error
150 :external-format external-format
153 ;;; Returning true goes into end of file handling, false will enter another
154 ;;; round of input buffer filling followed by re-entering character decode.
155 (defun stream-decoding-error-and-handle (stream octet-count)
157 (stream-decoding-error stream
158 (let ((sap (fd-stream-ibuf-sap stream))
159 (head (fd-stream-ibuf-head stream)))
160 (loop for i from 0 below octet-count
161 collect (sap-ref-8 sap (+ head i)))))
163 :report (lambda (stream)
165 "~@<Attempt to resync the stream at a character ~
166 character boundary and continue.~@:>"))
167 (fd-stream-resync stream)
169 (force-end-of-file ()
170 :report (lambda (stream)
171 (format stream "~@<Force an end of file.~@:>"))
174 (defun stream-encoding-error-and-handle (stream code)
176 (stream-encoding-error stream code)
178 :report (lambda (stream)
179 (format stream "~@<Skip output of this character.~@:>"))
180 (throw 'output-nothing nil))))
182 (defun external-format-encoding-error (stream code)
184 (stream-encoding-error-and-handle stream code)
185 (c-string-encoding-error stream code)))
187 (defun external-format-decoding-error (stream octet-count)
189 (stream-decoding-error stream octet-count)
190 (c-string-decoding-error stream octet-count)))
192 ;;; This is called by the server when we can write to the given file
193 ;;; descriptor. Attempt to write the data again. If it worked, remove
194 ;;; the data from the OUTPUT-LATER list. If it didn't work, something
196 (defun frob-output-later (stream)
197 (let* ((stuff (pop (fd-stream-output-later stream)))
201 (reuse-sap (cadddr stuff))
202 (length (- end start)))
203 (declare (type index start end length))
204 (multiple-value-bind (count errno)
205 (sb!unix:unix-write (fd-stream-fd stream)
210 (if #!-win32 (= errno sb!unix:ewouldblock) #!+win32 t #!-win32
211 (error "Write would have blocked, but SERVER told us to go.")
212 (simple-stream-perror "couldn't write to ~S" stream errno)))
213 ((eql count length) ; Hot damn, it worked.
215 (with-available-buffers-lock ()
216 (push base *available-buffers*))))
217 ((not (null count)) ; sorta worked..
219 (the index (+ start count))
221 (fd-stream-output-later stream))))))
222 (unless (fd-stream-output-later stream)
223 (sb!sys:remove-fd-handler (fd-stream-handler stream))
224 (setf (fd-stream-handler stream) nil)))
226 ;;; Arange to output the string when we can write on the file descriptor.
227 (defun output-later (stream base start end reuse-sap)
228 (cond ((null (fd-stream-output-later stream))
229 (setf (fd-stream-output-later stream)
230 (list (list base start end reuse-sap)))
231 (setf (fd-stream-handler stream)
232 (sb!sys:add-fd-handler (fd-stream-fd stream)
235 (declare (ignore fd))
236 (frob-output-later stream)))))
238 (nconc (fd-stream-output-later stream)
239 (list (list base start end reuse-sap)))))
241 (let ((new-buffer (next-available-buffer)))
242 (setf (fd-stream-obuf-sap stream) new-buffer)
243 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
245 ;;; Output the given noise. Check to see whether there are any pending
246 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
247 ;;; this would block, queue it.
248 (defun frob-output (stream base start end reuse-sap)
249 (declare (type fd-stream stream)
250 (type (or system-area-pointer (simple-array * (*))) base)
251 (type index start end))
252 (if (not (null (fd-stream-output-later stream))) ; something buffered.
254 (output-later stream base start end reuse-sap)
255 ;; ### check to see whether any of this noise can be output
257 (let ((length (- end start)))
258 (multiple-value-bind (count errno)
259 (sb!unix:unix-write (fd-stream-fd stream) base start length)
261 (if #!-win32 (= errno sb!unix:ewouldblock) #!+win32 t #!-win32
262 (output-later stream base start end reuse-sap)
263 (simple-stream-perror "couldn't write to ~S"
266 ((not (eql count length))
267 (output-later stream base (the index (+ start count))
270 ;;; Flush any data in the output buffer.
271 (defun flush-output-buffer (stream)
272 (let ((length (fd-stream-obuf-tail stream)))
274 (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
275 (setf (fd-stream-obuf-tail stream) 0))))
277 (defmacro output-wrapper/variable-width ((stream size buffering restart)
279 (let ((stream-var (gensym)))
280 `(let ((,stream-var ,stream)
282 ,(unless (eq (car buffering) :none)
283 `(when (< (fd-stream-obuf-length ,stream-var)
284 (+ (fd-stream-obuf-tail ,stream-var)
286 (flush-output-buffer ,stream-var)))
287 ,(unless (eq (car buffering) :none)
288 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
289 (> (fd-stream-ibuf-tail ,stream-var)
290 (fd-stream-ibuf-head ,stream-var)))
291 (file-position ,stream-var (file-position ,stream-var))))
293 `(catch 'output-nothing
295 (incf (fd-stream-obuf-tail ,stream-var) size))
298 (incf (fd-stream-obuf-tail ,stream-var) size)))
299 ,(ecase (car buffering)
301 `(flush-output-buffer ,stream-var))
303 `(when (eq (char-code byte) (char-code #\Newline))
304 (flush-output-buffer ,stream-var)))
308 (defmacro output-wrapper ((stream size buffering restart) &body body)
309 (let ((stream-var (gensym)))
310 `(let ((,stream-var ,stream))
311 ,(unless (eq (car buffering) :none)
312 `(when (< (fd-stream-obuf-length ,stream-var)
313 (+ (fd-stream-obuf-tail ,stream-var)
315 (flush-output-buffer ,stream-var)))
316 ,(unless (eq (car buffering) :none)
317 `(when (and (not (fd-stream-dual-channel-p ,stream-var))
318 (> (fd-stream-ibuf-tail ,stream-var)
319 (fd-stream-ibuf-head ,stream-var)))
320 (file-position ,stream-var (file-position ,stream-var))))
322 `(catch 'output-nothing
324 (incf (fd-stream-obuf-tail ,stream-var) ,size))
327 (incf (fd-stream-obuf-tail ,stream-var) ,size)))
328 ,(ecase (car buffering)
330 `(flush-output-buffer ,stream-var))
332 `(when (eq (char-code byte) (char-code #\Newline))
333 (flush-output-buffer ,stream-var)))
337 (defmacro def-output-routines/variable-width
338 ((name-fmt size restart external-format &rest bufferings)
340 (declare (optimize (speed 1)))
345 (intern (format nil name-fmt (string (car buffering))))))
347 (defun ,function (stream byte)
348 (declare (ignorable byte))
349 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
351 (setf *output-routines*
352 (nconc *output-routines*
360 (cdr buffering)))))))
363 ;;; Define output routines that output numbers SIZE bytes long for the
364 ;;; given bufferings. Use BODY to do the actual output.
365 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
367 (declare (optimize (speed 1)))
372 (intern (format nil name-fmt (string (car buffering))))))
374 (defun ,function (stream byte)
375 (output-wrapper (stream ,size ,buffering ,restart)
377 (setf *output-routines*
378 (nconc *output-routines*
386 (cdr buffering)))))))
389 ;;; FIXME: is this used anywhere any more?
390 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
396 (if (char= byte #\Newline)
397 (setf (fd-stream-char-pos stream) 0)
398 (incf (fd-stream-char-pos stream)))
399 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
402 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
405 (:none (unsigned-byte 8))
406 (:full (unsigned-byte 8)))
407 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
410 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
413 (:none (signed-byte 8))
414 (:full (signed-byte 8)))
415 (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
416 (fd-stream-obuf-tail stream))
419 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
422 (:none (unsigned-byte 16))
423 (:full (unsigned-byte 16)))
424 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
427 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
430 (:none (signed-byte 16))
431 (:full (signed-byte 16)))
432 (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
433 (fd-stream-obuf-tail stream))
436 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
439 (:none (unsigned-byte 32))
440 (:full (unsigned-byte 32)))
441 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
444 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
447 (:none (signed-byte 32))
448 (:full (signed-byte 32)))
449 (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
450 (fd-stream-obuf-tail stream))
453 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
455 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
458 (:none (unsigned-byte 64))
459 (:full (unsigned-byte 64)))
460 (setf (sap-ref-64 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
462 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
465 (:none (signed-byte 64))
466 (:full (signed-byte 64)))
467 (setf (signed-sap-ref-64 (fd-stream-obuf-sap stream)
468 (fd-stream-obuf-tail stream))
471 ;;; Do the actual output. If there is space to buffer the string,
472 ;;; buffer it. If the string would normally fit in the buffer, but
473 ;;; doesn't because of other stuff in the buffer, flush the old noise
474 ;;; out of the buffer and put the string in it. Otherwise we have a
475 ;;; very long string, so just send it directly (after flushing the
476 ;;; buffer, of course).
477 (defun output-raw-bytes (fd-stream thing &optional start end)
479 "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
480 THING is a SAP, END must be supplied (as length won't work)."
481 (let ((start (or start 0))
482 (end (or end (length (the (simple-array * (*)) thing)))))
483 (declare (type index start end))
484 (when (and (not (fd-stream-dual-channel-p fd-stream))
485 (> (fd-stream-ibuf-tail fd-stream)
486 (fd-stream-ibuf-head fd-stream)))
487 (file-position fd-stream (file-position fd-stream)))
488 (let* ((len (fd-stream-obuf-length fd-stream))
489 (tail (fd-stream-obuf-tail fd-stream))
491 (bytes (- end start))
492 (newtail (+ tail bytes)))
493 (cond ((minusp bytes) ; error case
494 (error ":END before :START!"))
495 ((zerop bytes)) ; easy case
497 (if (system-area-pointer-p thing)
498 (system-area-ub8-copy thing start
499 (fd-stream-obuf-sap fd-stream)
502 ;; FIXME: There should be some type checking somewhere to
503 ;; verify that THING here is a vector, not just <not a SAP>.
504 (copy-ub8-to-system-area thing start
505 (fd-stream-obuf-sap fd-stream)
508 (setf (fd-stream-obuf-tail fd-stream) newtail))
510 (flush-output-buffer fd-stream)
511 (if (system-area-pointer-p thing)
512 (system-area-ub8-copy thing
514 (fd-stream-obuf-sap fd-stream)
517 ;; FIXME: There should be some type checking somewhere to
518 ;; verify that THING here is a vector, not just <not a SAP>.
519 (copy-ub8-to-system-area thing
521 (fd-stream-obuf-sap fd-stream)
524 (setf (fd-stream-obuf-tail fd-stream) bytes))
526 (flush-output-buffer fd-stream)
527 (frob-output fd-stream thing start end nil))))))
529 ;;; the routine to use to output a string. If the stream is
530 ;;; unbuffered, slam the string down the file descriptor, otherwise
531 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
532 ;;; checking to see where the last newline was.
534 ;;; Note: some bozos (the FASL dumper) call write-string with things
535 ;;; other than strings. Therefore, we must make sure we have a string
536 ;;; before calling POSITION on it.
537 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
538 ;;; cover for them here. -- WHN 20000203
539 (defun fd-sout (stream thing start end)
540 (let ((start (or start 0))
541 (end (or end (length (the vector thing)))))
542 (declare (fixnum start end))
545 (string-dispatch (simple-base-string
547 (simple-array character)
550 (and (find #\newline thing :start start :end end)
551 ;; FIXME why do we need both calls?
552 ;; Is find faster forwards than
553 ;; position is backwards?
554 (position #\newline thing
558 (if (and (typep thing 'base-string)
559 (eq (fd-stream-external-format stream) :latin-1))
560 (ecase (fd-stream-buffering stream)
562 (output-raw-bytes stream thing start end))
564 (output-raw-bytes stream thing start end)
566 (flush-output-buffer stream)))
568 (frob-output stream thing start end nil)))
569 (ecase (fd-stream-buffering stream)
570 (:full (funcall (fd-stream-output-bytes stream)
571 stream thing nil start end))
572 (:line (funcall (fd-stream-output-bytes stream)
573 stream thing last-newline start end))
574 (:none (funcall (fd-stream-output-bytes stream)
575 stream thing t start end))))
577 (setf (fd-stream-char-pos stream)
578 (- end last-newline 1))
579 (incf (fd-stream-char-pos stream)
581 (ecase (fd-stream-buffering stream)
583 (output-raw-bytes stream thing start end))
585 (frob-output stream thing start end nil))))))
587 (defvar *external-formats* ()
589 "List of all available external formats. Each element is a list of the
590 element-type, string input function name, character input function name,
591 and string output function name.")
593 (defun get-external-format (external-format)
594 (dolist (entry *external-formats*)
595 (when (member external-format (first entry))
598 (defun get-external-format-function (external-format index)
599 (let ((entry (get-external-format external-format)))
600 (when entry (nth index entry))))
602 ;;; Find an output routine to use given the type and buffering. Return
603 ;;; as multiple values the routine, the real type transfered, and the
604 ;;; number of bytes per element.
605 (defun pick-output-routine (type buffering &optional external-format)
606 (when (subtypep type 'character)
607 (let ((entry (get-external-format external-format)))
609 (return-from pick-output-routine
610 (values (symbol-function (nth (ecase buffering
617 (symbol-function (fourth entry))
618 (first (first entry)))))))
619 (dolist (entry *output-routines*)
620 (when (and (subtypep type (first entry))
621 (eq buffering (second entry))
622 (or (not (fifth entry))
623 (eq external-format (fifth entry))))
624 (return-from pick-output-routine
625 (values (symbol-function (third entry))
628 ;; KLUDGE: dealing with the buffering here leads to excessive code
631 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
632 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
633 if (subtypep type `(unsigned-byte ,i))
634 do (return-from pick-output-routine
638 (lambda (stream byte)
639 (output-wrapper (stream (/ i 8) (:none) nil)
640 (loop for j from 0 below (/ i 8)
642 (fd-stream-obuf-sap stream)
643 (+ j (fd-stream-obuf-tail stream)))
644 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
646 (lambda (stream byte)
647 (output-wrapper (stream (/ i 8) (:full) 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)))))))
655 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
656 if (subtypep type `(signed-byte ,i))
657 do (return-from pick-output-routine
661 (lambda (stream byte)
662 (output-wrapper (stream (/ i 8) (:none) nil)
663 (loop for j from 0 below (/ i 8)
665 (fd-stream-obuf-sap stream)
666 (+ j (fd-stream-obuf-tail stream)))
667 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
669 (lambda (stream byte)
670 (output-wrapper (stream (/ i 8) (:full) 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)))))))
679 ;;;; input routines and related noise
681 ;;; a list of all available input routines. Each element is a list of
682 ;;; the element-type input, the function name, and the number of bytes
684 (defvar *input-routines* ())
686 ;;; Return whether a primitive partial read operation on STREAM's FD
687 ;;; would (probably) block. Signal a `simple-stream-error' if the
688 ;;; system call implementing this operation fails.
690 ;;; It is "may" instead of "would" because "would" is not quite
691 ;;; correct on win32. However, none of the places that use it require
692 ;;; further assurance than "may" versus "will definitely not".
693 (defun sysread-may-block-p (stream)
695 ;; This answers T at EOF on win32, I think.
696 (not (sb!win32:fd-listen (fd-stream-fd stream)))
698 (sb!unix:with-restarted-syscall (count errno)
699 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
700 (sb!unix:fd-zero read-fds)
701 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
702 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
703 (sb!alien:addr read-fds)
709 (simple-stream-perror "couldn't check whether ~S is readable"
713 ;;; Fill the input buffer, and return the number of bytes read. Throw
714 ;;; to EOF-INPUT-CATCHER if the eof was reached. Drop into
715 ;;; SYSTEM:SERVER if necessary.
716 (defun refill-buffer/fd (stream)
717 (let ((fd (fd-stream-fd stream))
718 (ibuf-sap (fd-stream-ibuf-sap stream))
719 (buflen (fd-stream-ibuf-length stream))
720 (head (fd-stream-ibuf-head stream))
721 (tail (fd-stream-ibuf-tail stream)))
722 (declare (type index head tail))
724 (cond ((eql head tail)
727 (setf (fd-stream-ibuf-head stream) 0)
728 (setf (fd-stream-ibuf-tail stream) 0))
731 (system-area-ub8-copy ibuf-sap head
734 (setf (fd-stream-ibuf-head stream) 0)
735 (setf (fd-stream-ibuf-tail stream) tail))))
736 (setf (fd-stream-listen stream) nil)
737 ;;This isn't quite the same on win32. Then again, neither was
738 ;;(not (sb!win32:fd-listen fd)), as was originally here. See
739 ;;comment in `sysread-may-block-p'.
740 (when (sysread-may-block-p stream)
741 (unless (sb!sys:wait-until-fd-usable
742 fd :input (fd-stream-timeout stream))
743 (error 'io-timeout :stream stream :direction :read)))
744 (multiple-value-bind (count errno)
745 (sb!unix:unix-read fd
746 (sb!sys:int-sap (+ (sb!sys:sap-int ibuf-sap) tail))
749 (if #!-win32 (eql errno sb!unix:ewouldblock) #!+win32 t #!-win32
751 (unless (sb!sys:wait-until-fd-usable
752 fd :input (fd-stream-timeout stream))
753 (error 'io-timeout :stream stream :direction :read))
754 (refill-buffer/fd stream))
755 (simple-stream-perror "couldn't read from ~S" stream errno)))
757 (setf (fd-stream-listen stream) :eof)
758 (/show0 "THROWing EOF-INPUT-CATCHER")
759 (throw 'eof-input-catcher nil))
761 (incf (fd-stream-ibuf-tail stream) count)
764 ;;; Make sure there are at least BYTES number of bytes in the input
765 ;;; buffer. Keep calling REFILL-BUFFER/FD until that condition is met.
766 (defmacro input-at-least (stream bytes)
767 (let ((stream-var (gensym))
768 (bytes-var (gensym)))
769 `(let ((,stream-var ,stream)
772 (when (>= (- (fd-stream-ibuf-tail ,stream-var)
773 (fd-stream-ibuf-head ,stream-var))
776 (refill-buffer/fd ,stream-var)))))
778 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
780 (let ((stream-var (gensym))
782 (element-var (gensym)))
783 `(let ((,stream-var ,stream)
785 (if (fd-stream-unread ,stream-var)
787 (fd-stream-unread ,stream-var)
788 (setf (fd-stream-unread ,stream-var) nil)
789 (setf (fd-stream-listen ,stream-var) nil))
790 (let ((,element-var nil)
791 (decode-break-reason nil))
795 (catch 'eof-input-catcher
796 (setf decode-break-reason
797 (block decode-break-reason
798 (input-at-least ,stream-var 1)
799 (let* ((byte (sap-ref-8 (fd-stream-ibuf-sap
803 (declare (ignorable byte))
805 (input-at-least ,stream-var size)
806 (setq ,element-var (locally ,@read-forms))
807 (setq ,retry-var nil))
809 (when decode-break-reason
810 (stream-decoding-error-and-handle stream
811 decode-break-reason))
813 (let ((octet-count (- (fd-stream-ibuf-tail ,stream-var)
814 (fd-stream-ibuf-head ,stream-var))))
815 (when (or (zerop octet-count)
816 (and (not ,element-var)
817 (not decode-break-reason)
818 (stream-decoding-error-and-handle
819 stream octet-count)))
820 (setq ,retry-var nil)))))
822 (incf (fd-stream-ibuf-head ,stream-var) size)
825 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
827 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
828 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
829 (let ((stream-var (gensym))
830 (element-var (gensym)))
831 `(let ((,stream-var ,stream))
832 (if (fd-stream-unread ,stream-var)
834 (fd-stream-unread ,stream-var)
835 (setf (fd-stream-unread ,stream-var) nil)
836 (setf (fd-stream-listen ,stream-var) nil))
838 (catch 'eof-input-catcher
839 (input-at-least ,stream-var ,bytes)
840 (locally ,@read-forms))))
842 (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
845 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
847 (defmacro def-input-routine/variable-width (name
848 (type external-format size sap head)
851 (defun ,name (stream eof-error eof-value)
852 (input-wrapper/variable-width (stream ,size eof-error eof-value)
853 (let ((,sap (fd-stream-ibuf-sap stream))
854 (,head (fd-stream-ibuf-head stream)))
856 (setf *input-routines*
857 (nconc *input-routines*
858 (list (list ',type ',name 1 ',external-format))))))
860 (defmacro def-input-routine (name
864 (defun ,name (stream eof-error eof-value)
865 (input-wrapper (stream ,size eof-error eof-value)
866 (let ((,sap (fd-stream-ibuf-sap stream))
867 (,head (fd-stream-ibuf-head stream)))
869 (setf *input-routines*
870 (nconc *input-routines*
871 (list (list ',type ',name ',size nil))))))
873 ;;; STREAM-IN routine for reading a string char
874 (def-input-routine input-character
875 (character 1 sap head)
876 (code-char (sap-ref-8 sap head)))
878 ;;; STREAM-IN routine for reading an unsigned 8 bit number
879 (def-input-routine input-unsigned-8bit-byte
880 ((unsigned-byte 8) 1 sap head)
881 (sap-ref-8 sap head))
883 ;;; STREAM-IN routine for reading a signed 8 bit number
884 (def-input-routine input-signed-8bit-number
885 ((signed-byte 8) 1 sap head)
886 (signed-sap-ref-8 sap head))
888 ;;; STREAM-IN routine for reading an unsigned 16 bit number
889 (def-input-routine input-unsigned-16bit-byte
890 ((unsigned-byte 16) 2 sap head)
891 (sap-ref-16 sap head))
893 ;;; STREAM-IN routine for reading a signed 16 bit number
894 (def-input-routine input-signed-16bit-byte
895 ((signed-byte 16) 2 sap head)
896 (signed-sap-ref-16 sap head))
898 ;;; STREAM-IN routine for reading a unsigned 32 bit number
899 (def-input-routine input-unsigned-32bit-byte
900 ((unsigned-byte 32) 4 sap head)
901 (sap-ref-32 sap head))
903 ;;; STREAM-IN routine for reading a signed 32 bit number
904 (def-input-routine input-signed-32bit-byte
905 ((signed-byte 32) 4 sap head)
906 (signed-sap-ref-32 sap head))
908 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
910 (def-input-routine input-unsigned-64bit-byte
911 ((unsigned-byte 64) 8 sap head)
912 (sap-ref-64 sap head))
913 (def-input-routine input-signed-64bit-byte
914 ((signed-byte 64) 8 sap head)
915 (signed-sap-ref-64 sap head)))
917 ;;; Find an input routine to use given the type. Return as multiple
918 ;;; values the routine, the real type transfered, and the number of
919 ;;; bytes per element (and for character types string input routine).
920 (defun pick-input-routine (type &optional external-format)
921 (when (subtypep type 'character)
922 (dolist (entry *external-formats*)
923 (when (member external-format (first entry))
924 (return-from pick-input-routine
925 (values (symbol-function (third entry))
928 (symbol-function (second entry))
929 (first (first entry)))))))
930 (dolist (entry *input-routines*)
931 (when (and (subtypep type (first entry))
932 (or (not (fourth entry))
933 (eq external-format (fourth entry))))
934 (return-from pick-input-routine
935 (values (symbol-function (second entry))
938 ;; FIXME: let's do it the hard way, then (but ignore things like
939 ;; endianness, efficiency, and the necessary coupling between these
940 ;; and the output routines). -- CSR, 2004-02-09
941 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
942 if (subtypep type `(unsigned-byte ,i))
943 do (return-from pick-input-routine
945 (lambda (stream eof-error eof-value)
946 (input-wrapper (stream (/ i 8) eof-error eof-value)
947 (let ((sap (fd-stream-ibuf-sap stream))
948 (head (fd-stream-ibuf-head stream)))
949 (loop for j from 0 below (/ i 8)
953 (sap-ref-8 sap (+ head j))))
954 finally (return result)))))
957 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
958 if (subtypep type `(signed-byte ,i))
959 do (return-from pick-input-routine
961 (lambda (stream eof-error eof-value)
962 (input-wrapper (stream (/ i 8) eof-error eof-value)
963 (let ((sap (fd-stream-ibuf-sap stream))
964 (head (fd-stream-ibuf-head stream)))
965 (loop for j from 0 below (/ i 8)
969 (sap-ref-8 sap (+ head j))))
970 finally (return (if (logbitp (1- i) result)
971 (dpb result (byte i 0) -1)
976 ;;; Return a string constructed from SAP, START, and END.
977 (defun string-from-sap (sap start end)
978 (declare (type index start end))
979 (let* ((length (- end start))
980 (string (make-string length)))
981 (copy-ub8-from-system-area sap start
986 ;;; the N-BIN method for FD-STREAMs
988 ;;; Note that this blocks in UNIX-READ. It is generally used where
989 ;;; there is a definite amount of reading to be done, so blocking
990 ;;; isn't too problematical.
991 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
992 &aux (total-copied 0))
993 (declare (type fd-stream stream))
994 (declare (type index start requested total-copied))
995 (let ((unread (fd-stream-unread stream)))
997 ;; AVERs designed to fail when we have more complicated
998 ;; character representations.
999 (aver (typep unread 'base-char))
1000 (aver (= (fd-stream-element-size stream) 1))
1001 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1004 (system-area-pointer
1005 (setf (sap-ref-8 buffer start) (char-code unread)))
1006 ((simple-unboxed-array (*))
1007 (setf (aref buffer start) unread)))
1008 (setf (fd-stream-unread stream) nil)
1009 (setf (fd-stream-listen stream) nil)
1010 (incf total-copied)))
1013 (let* ((remaining-request (- requested total-copied))
1014 (head (fd-stream-ibuf-head stream))
1015 (tail (fd-stream-ibuf-tail stream))
1016 (available (- tail head))
1017 (n-this-copy (min remaining-request available))
1018 (this-start (+ start total-copied))
1019 (this-end (+ this-start n-this-copy))
1020 (sap (fd-stream-ibuf-sap stream)))
1021 (declare (type index remaining-request head tail available))
1022 (declare (type index n-this-copy))
1023 ;; Copy data from stream buffer into user's buffer.
1024 (%byte-blt sap head buffer this-start this-end)
1025 (incf (fd-stream-ibuf-head stream) n-this-copy)
1026 (incf total-copied n-this-copy)
1027 ;; Maybe we need to refill the stream buffer.
1028 (cond (;; If there were enough data in the stream buffer, we're done.
1029 (= total-copied requested)
1030 (return total-copied))
1031 (;; If EOF, we're done in another way.
1032 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1034 (error 'end-of-file :stream stream)
1035 (return total-copied)))
1036 ;; Otherwise we refilled the stream buffer, so fall
1037 ;; through into another pass of the loop.
1040 (defun fd-stream-resync (stream)
1041 (dolist (entry *external-formats*)
1042 (when (member (fd-stream-external-format stream) (first entry))
1043 (return-from fd-stream-resync
1044 (funcall (symbol-function (eighth entry)) stream)))))
1046 (defun get-fd-stream-character-sizer (stream)
1047 (dolist (entry *external-formats*)
1048 (when (member (fd-stream-external-format stream) (first entry))
1049 (return-from get-fd-stream-character-sizer (ninth entry)))))
1051 (defun fd-stream-character-size (stream char)
1052 (let ((sizer (get-fd-stream-character-sizer stream)))
1053 (when sizer (funcall sizer char))))
1055 (defun fd-stream-string-size (stream string)
1056 (let ((sizer (get-fd-stream-character-sizer stream)))
1058 (loop for char across string summing (funcall sizer char)))))
1060 (defun find-external-format (external-format)
1061 (when external-format
1062 (find external-format *external-formats* :test #'member :key #'car)))
1064 (defun variable-width-external-format-p (ef-entry)
1065 (when (eighth ef-entry) t))
1067 (defun bytes-for-char-fun (ef-entry)
1068 (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1070 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1071 (defmacro define-external-format (external-format size output-restart
1073 (let* ((name (first external-format))
1074 (out-function (symbolicate "OUTPUT-BYTES/" name))
1075 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1076 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1077 (in-char-function (symbolicate "INPUT-CHAR/" name))
1078 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1079 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1080 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name)))
1082 (defun ,size-function (byte)
1083 (declare (ignore byte))
1085 (defun ,out-function (stream string flush-p start end)
1086 (let ((start (or start 0))
1087 (end (or end (length string))))
1088 (declare (type index start end))
1089 (when (and (not (fd-stream-dual-channel-p stream))
1090 (> (fd-stream-ibuf-tail stream)
1091 (fd-stream-ibuf-head stream)))
1092 (file-position stream (file-position stream)))
1093 (unless (<= 0 start end (length string))
1094 (signal-bounding-indices-bad-error string start end))
1097 (setf (fd-stream-obuf-tail stream)
1098 (string-dispatch (simple-base-string
1100 (simple-array character)
1103 (let ((len (fd-stream-obuf-length stream))
1104 (sap (fd-stream-obuf-sap stream))
1105 (tail (fd-stream-obuf-tail stream)))
1106 (declare (type index tail)
1107 ;; STRING bounds have already been checked.
1108 (optimize (safety 0)))
1110 (,@(if output-restart
1111 `(catch 'output-nothing)
1114 ((or (= start end) (< (- len tail) 4)))
1115 (let* ((byte (aref string start))
1116 (bits (char-code byte)))
1120 ;; Exited from the loop normally
1122 ;; Exited via CATCH. Skip the current character
1123 ;; and try the inner loop again.
1126 (flush-output-buffer stream)))
1128 (flush-output-buffer stream))))
1129 (def-output-routines (,format
1135 (if (char= byte #\Newline)
1136 (setf (fd-stream-char-pos stream) 0)
1137 (incf (fd-stream-char-pos stream)))
1138 (let ((bits (char-code byte))
1139 (sap (fd-stream-obuf-sap stream))
1140 (tail (fd-stream-obuf-tail stream)))
1142 (defun ,in-function (stream buffer start requested eof-error-p
1143 &aux (index start) (end (+ start requested)))
1144 (declare (type fd-stream stream))
1145 (declare (type index start requested index end))
1146 (declare (type (simple-array character (#.+ansi-stream-in-buffer-length+)) buffer))
1147 (let ((unread (fd-stream-unread stream)))
1149 (setf (aref buffer index) unread)
1150 (setf (fd-stream-unread stream) nil)
1151 (setf (fd-stream-listen stream) nil)
1155 (let* ((head (fd-stream-ibuf-head stream))
1156 (tail (fd-stream-ibuf-tail stream))
1157 (sap (fd-stream-ibuf-sap stream)))
1158 (declare (type index head tail)
1159 (type system-area-pointer sap))
1160 ;; Copy data from stream buffer into user's buffer.
1161 (dotimes (i (min (truncate (- tail head) ,size)
1163 (declare (optimize speed))
1164 (let* ((byte (sap-ref-8 sap head)))
1165 (setf (aref buffer index) ,in-expr)
1168 (setf (fd-stream-ibuf-head stream) head)
1169 ;; Maybe we need to refill the stream buffer.
1170 (cond ( ;; If there was enough data in the stream buffer, we're done.
1172 (return (- index start)))
1173 ( ;; If EOF, we're done in another way.
1174 (null (catch 'eof-input-catcher (refill-buffer/fd stream)))
1176 (error 'end-of-file :stream stream)
1177 (return (- index start))))
1178 ;; Otherwise we refilled the stream buffer, so fall
1179 ;; through into another pass of the loop.
1181 (def-input-routine ,in-char-function (character ,size sap head)
1182 (let ((byte (sap-ref-8 sap head)))
1184 (defun ,read-c-string-function (sap element-type)
1185 (declare (type system-area-pointer sap)
1186 (type (member character base-char) element-type))
1188 (declare (optimize (speed 3) (safety 0)))
1189 (let* ((stream ,name)
1190 (length (loop for head of-type index upfrom 0 by ,size
1191 for count of-type index upto (1- ARRAY-DIMENSION-LIMIT)
1192 for byte = (sap-ref-8 sap head)
1193 for char of-type character = ,in-expr
1194 until (zerop (char-code char))
1195 finally (return count)))
1196 (string (make-string length :element-type element-type)))
1197 (declare (ignorable stream)
1199 (type string string))
1200 (/show0 before-copy-loop)
1201 (loop for head of-type index upfrom 0 by ,size
1202 for index of-type index below length
1203 for byte = (sap-ref-8 sap head)
1204 for char of-type character = ,in-expr
1205 do (setf (aref string index) char))
1206 string))) ;; last loop rewrite to dotimes?
1207 (defun ,output-c-string-function (string)
1208 (declare (type simple-string string))
1210 (declare (optimize (speed 3) (safety 0)))
1211 (let* ((length (length string))
1212 (buffer (make-array (* (1+ length) ,size) :element-type '(unsigned-byte 8)))
1213 (sap (sb!sys:vector-sap buffer))
1216 (declare (type index length tail)
1217 (type system-area-pointer sap))
1219 (let* ((byte (aref string i))
1220 (bits (char-code byte)))
1221 (declare (ignorable byte bits))
1225 (byte (code-char bits)))
1226 (declare (ignorable bits byte))
1229 (setf *external-formats*
1230 (cons '(,external-format ,in-function ,in-char-function ,out-function
1231 ,@(mapcar #'(lambda (buffering)
1232 (intern (format nil format (string buffering))))
1233 '(:none :line :full))
1234 nil ; no resync-function
1235 ,size-function ,read-c-string-function ,output-c-string-function)
1236 *external-formats*)))))
1238 (defmacro define-external-format/variable-width
1239 (external-format output-restart out-size-expr
1240 out-expr in-size-expr in-expr)
1241 (let* ((name (first external-format))
1242 (out-function (symbolicate "OUTPUT-BYTES/" name))
1243 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1244 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1245 (in-char-function (symbolicate "INPUT-CHAR/" name))
1246 (resync-function (symbolicate "RESYNC/" name))
1247 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1248 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1249 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name)))
1251 (defun ,size-function (byte)
1252 (declare (ignorable byte))
1254 (defun ,out-function (stream string flush-p start end)
1255 (let ((start (or start 0))
1256 (end (or end (length string))))
1257 (declare (type index start end))
1258 (when (and (not (fd-stream-dual-channel-p stream))
1259 (> (fd-stream-ibuf-tail stream)
1260 (fd-stream-ibuf-head stream)))
1261 (file-position stream (file-position stream)))
1262 (unless (<= 0 start end (length string))
1263 (signal-bounding-indices-bad-error string start end))
1266 (setf (fd-stream-obuf-tail stream)
1267 (string-dispatch (simple-base-string
1269 (simple-array character)
1272 (let ((len (fd-stream-obuf-length stream))
1273 (sap (fd-stream-obuf-sap stream))
1274 (tail (fd-stream-obuf-tail stream)))
1275 (declare (type index tail)
1276 ;; STRING bounds have already been checked.
1277 (optimize (safety 0)))
1279 (,@(if output-restart
1280 `(catch 'output-nothing)
1283 ((or (= start end) (< (- len tail) 4)))
1284 (let* ((byte (aref string start))
1285 (bits (char-code byte))
1286 (size ,out-size-expr))
1290 ;; Exited from the loop normally
1292 ;; Exited via CATCH. Skip the current character
1293 ;; and try the inner loop again.
1296 (flush-output-buffer stream)))
1298 (flush-output-buffer stream))))
1299 (def-output-routines/variable-width (,format
1306 (if (char= byte #\Newline)
1307 (setf (fd-stream-char-pos stream) 0)
1308 (incf (fd-stream-char-pos stream)))
1309 (let ((bits (char-code byte))
1310 (sap (fd-stream-obuf-sap stream))
1311 (tail (fd-stream-obuf-tail stream)))
1313 (defun ,in-function (stream buffer start requested eof-error-p
1314 &aux (total-copied 0))
1315 (declare (type fd-stream stream))
1316 (declare (type index start requested total-copied))
1317 (declare (type (simple-array character (#.+ansi-stream-in-buffer-length+)) buffer))
1318 (let ((unread (fd-stream-unread stream)))
1320 (setf (aref buffer start) unread)
1321 (setf (fd-stream-unread stream) nil)
1322 (setf (fd-stream-listen stream) nil)
1323 (incf total-copied)))
1326 (let* ((head (fd-stream-ibuf-head stream))
1327 (tail (fd-stream-ibuf-tail stream))
1328 (sap (fd-stream-ibuf-sap stream))
1329 (decode-break-reason nil))
1330 (declare (type index head tail))
1331 ;; Copy data from stream buffer into user's buffer.
1332 (do ((size nil nil))
1333 ((or (= tail head) (= requested total-copied)))
1334 (setf decode-break-reason
1335 (block decode-break-reason
1336 (let ((byte (sap-ref-8 sap head)))
1337 (declare (ignorable byte))
1338 (setq size ,in-size-expr)
1339 (when (> size (- tail head))
1341 (setf (aref buffer (+ start total-copied)) ,in-expr)
1345 (setf (fd-stream-ibuf-head stream) head)
1346 (when decode-break-reason
1347 ;; If we've already read some characters on when the invalid
1348 ;; code sequence is detected, we return immediately. The
1349 ;; handling of the error is deferred until the next call
1350 ;; (where this check will be false). This allows establishing
1351 ;; high-level handlers for decode errors (for example
1352 ;; automatically resyncing in Lisp comments).
1353 (when (plusp total-copied)
1354 (return-from ,in-function total-copied))
1355 (when (stream-decoding-error-and-handle
1356 stream decode-break-reason)
1358 (error 'end-of-file :stream stream)
1359 (return-from ,in-function total-copied)))
1360 (setf head (fd-stream-ibuf-head stream))
1361 (setf tail (fd-stream-ibuf-tail stream))))
1362 (setf (fd-stream-ibuf-head stream) head)
1363 ;; Maybe we need to refill the stream buffer.
1364 (cond ( ;; If there were enough data in the stream buffer, we're done.
1365 (= total-copied requested)
1366 (return total-copied))
1367 ( ;; If EOF, we're done in another way.
1368 (or (eq decode-break-reason 'eof)
1369 (null (catch 'eof-input-catcher
1370 (refill-buffer/fd stream))))
1372 (error 'end-of-file :stream stream)
1373 (return total-copied)))
1374 ;; Otherwise we refilled the stream buffer, so fall
1375 ;; through into another pass of the loop.
1377 (def-input-routine/variable-width ,in-char-function (character
1381 (let ((byte (sap-ref-8 sap head)))
1382 (declare (ignorable byte))
1384 (defun ,resync-function (stream)
1385 (loop (input-at-least stream 2)
1386 (incf (fd-stream-ibuf-head stream))
1387 (unless (block decode-break-reason
1388 (let* ((sap (fd-stream-ibuf-sap stream))
1389 (head (fd-stream-ibuf-head stream))
1390 (byte (sap-ref-8 sap head))
1391 (size ,in-size-expr))
1392 (declare (ignorable byte))
1393 (input-at-least stream size)
1394 (let ((sap (fd-stream-ibuf-sap stream))
1395 (head (fd-stream-ibuf-head stream)))
1399 (defun ,read-c-string-function (sap element-type)
1400 (declare (type system-area-pointer sap))
1402 (declare (optimize (speed 3) (safety 0)))
1403 (let* ((stream ,name)
1404 (size 0) (head 0) (byte 0) (char nil)
1405 (decode-break-reason nil)
1406 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1407 (setf decode-break-reason
1408 (block decode-break-reason
1409 (setf byte (sap-ref-8 sap head)
1414 (when decode-break-reason
1415 (c-string-decoding-error ,name decode-break-reason))
1416 (when (zerop (char-code char))
1418 (string (make-string length :element-type element-type)))
1419 (declare (ignorable stream)
1420 (type index head length) ;; size
1421 (type (unsigned-byte 8) byte)
1422 (type (or null character) char)
1423 (type string string))
1425 (dotimes (index length string)
1426 (setf decode-break-reason
1427 (block decode-break-reason
1428 (setf byte (sap-ref-8 sap head)
1433 (when decode-break-reason
1434 (c-string-decoding-error ,name decode-break-reason))
1435 (setf (aref string index) char)))))
1437 (defun ,output-c-string-function (string)
1438 (declare (type simple-string string))
1440 (declare (optimize (speed 3) (safety 0)))
1441 (let* ((length (length string))
1442 (char-length (make-array (1+ length) :element-type 'index))
1444 (+ (loop for i of-type index below length
1445 for byte of-type character = (aref string i)
1446 for bits = (char-code byte)
1447 sum (setf (aref char-length i)
1448 (the index ,out-size-expr)))
1449 (let* ((byte (code-char 0))
1450 (bits (char-code byte)))
1451 (declare (ignorable byte bits))
1452 (setf (aref char-length length)
1453 (the index ,out-size-expr)))))
1455 (buffer (make-array buffer-length :element-type '(unsigned-byte 8)))
1456 (sap (sb!sys:vector-sap buffer))
1458 (declare (type index length buffer-length tail)
1459 (type system-area-pointer sap)
1462 (loop for i of-type index below length
1463 for byte of-type character = (aref string i)
1464 for bits = (char-code byte)
1465 for size of-type index = (aref char-length i)
1470 (byte (code-char bits))
1471 (size (aref char-length length)))
1472 (declare (ignorable bits byte size))
1476 (setf *external-formats*
1477 (cons '(,external-format ,in-function ,in-char-function ,out-function
1478 ,@(mapcar #'(lambda (buffering)
1479 (intern (format nil format (string buffering))))
1480 '(:none :line :full))
1482 ,size-function ,read-c-string-function ,output-c-string-function)
1483 *external-formats*)))))
1485 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1486 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1487 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1488 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1491 (external-format-encoding-error stream bits)
1492 (setf (sap-ref-8 sap tail) bits))
1495 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1496 :iso-646 :iso-646-us :|646|)
1499 (external-format-encoding-error stream bits)
1500 (setf (sap-ref-8 sap tail) bits))
1503 (let* ((table (let ((s (make-string 256)))
1504 (map-into s #'code-char
1505 '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1506 #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1507 #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1508 #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1509 #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1510 #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1511 #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1512 #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1513 #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1514 #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1515 #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1516 #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1517 #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1518 #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1519 #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1520 #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1522 (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1523 (loop for char across table for i from 0
1524 do (aver (= 0 (aref rt (char-code char))))
1525 do (setf (aref rt (char-code char)) i))
1527 (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1530 (external-format-encoding-error stream bits)
1531 (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1536 (let ((latin-9-table (let ((table (make-string 256)))
1539 (setf (aref table i) (code-char i)))
1540 (setf (aref table #xa4) (code-char #x20ac))
1541 (setf (aref table #xa6) (code-char #x0160))
1542 (setf (aref table #xa8) (code-char #x0161))
1543 (setf (aref table #xb4) (code-char #x017d))
1544 (setf (aref table #xb8) (code-char #x017e))
1545 (setf (aref table #xbc) (code-char #x0152))
1546 (setf (aref table #xbd) (code-char #x0153))
1547 (setf (aref table #xbe) (code-char #x0178))
1549 (latin-9-reverse-1 (make-array 16
1550 :element-type '(unsigned-byte 21)
1551 :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1552 (latin-9-reverse-2 (make-array 16
1553 :element-type '(unsigned-byte 8)
1554 :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1555 (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1557 (setf (sap-ref-8 sap tail)
1559 (if (= bits (char-code (aref latin-9-table bits)))
1561 (external-format-encoding-error stream byte))
1562 (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1563 (aref latin-9-reverse-2 (logand bits 15))
1564 (external-format-encoding-error stream byte))))
1565 (aref latin-9-table byte)))
1567 (define-external-format/variable-width (:utf-8 :utf8) nil
1568 (let ((bits (char-code byte)))
1569 (cond ((< bits #x80) 1)
1571 ((< bits #x10000) 3)
1574 (1 (setf (sap-ref-8 sap tail) bits))
1575 (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1576 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 0) bits))))
1577 (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1578 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 6) bits))
1579 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1580 (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1581 (sap-ref-8 sap (1+ tail)) (logior #x80 (ldb (byte 6 12) bits))
1582 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1583 (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1584 (cond ((< byte #x80) 1)
1585 ((< byte #xc2) (return-from decode-break-reason 1))
1589 (code-char (ecase size
1591 (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1592 (unless (<= #x80 byte2 #xbf)
1593 (return-from decode-break-reason 2))
1594 (dpb byte (byte 5 6) byte2)))
1595 (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1596 (byte3 (sap-ref-8 sap (+ 2 head))))
1597 (unless (and (<= #x80 byte2 #xbf)
1598 (<= #x80 byte3 #xbf))
1599 (return-from decode-break-reason 3))
1600 (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1601 (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1602 (byte3 (sap-ref-8 sap (+ 2 head)))
1603 (byte4 (sap-ref-8 sap (+ 3 head))))
1604 (unless (and (<= #x80 byte2 #xbf)
1605 (<= #x80 byte3 #xbf)
1606 (<= #x80 byte4 #xbf))
1607 (return-from decode-break-reason 4))
1608 (dpb byte (byte 3 18)
1609 (dpb byte2 (byte 6 12)
1610 (dpb byte3 (byte 6 6) byte4))))))))
1612 ;;;; utility functions (misc routines, etc)
1614 ;;; Fill in the various routine slots for the given type. INPUT-P and
1615 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1616 ;;; set prior to calling this routine.
1617 (defun set-fd-stream-routines (fd-stream element-type external-format
1618 input-p output-p buffer-p)
1619 (let* ((target-type (case element-type
1620 (unsigned-byte '(unsigned-byte 8))
1621 (signed-byte '(signed-byte 8))
1622 (:default 'character)
1624 (character-stream-p (subtypep target-type 'character))
1625 (bivalent-stream-p (eq element-type :default))
1626 normalized-external-format
1627 (bin-routine #'ill-bin)
1630 (cin-routine #'ill-in)
1633 (input-type nil) ;calculated from bin-type/cin-type
1634 (input-size nil) ;calculated from bin-size/cin-size
1635 (read-n-characters #'ill-in)
1636 (bout-routine #'ill-bout)
1639 (cout-routine #'ill-out)
1644 (output-bytes #'ill-bout))
1646 ;; drop buffers when direction changes
1647 (when (and (fd-stream-obuf-sap fd-stream) (not output-p))
1648 (with-available-buffers-lock ()
1649 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1650 (setf (fd-stream-obuf-sap fd-stream) nil)))
1651 (when (and (fd-stream-ibuf-sap fd-stream) (not input-p))
1652 (with-available-buffers-lock ()
1653 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1654 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1656 (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
1657 (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
1658 (setf (fd-stream-ibuf-tail fd-stream) 0))
1660 (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
1661 (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
1662 (setf (fd-stream-obuf-tail fd-stream) 0)
1663 (setf (fd-stream-char-pos fd-stream) 0))
1665 (when (and character-stream-p
1666 (eq external-format :default))
1667 (/show0 "/getting default external format")
1668 (setf external-format (default-external-format)))
1671 (when (or (not character-stream-p) bivalent-stream-p)
1672 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1673 normalized-external-format)
1674 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1678 (error "could not find any input routine for ~S" target-type)))
1679 (when character-stream-p
1680 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1681 normalized-external-format)
1682 (pick-input-routine target-type external-format))
1684 (error "could not find any input routine for ~S" target-type)))
1685 (setf (fd-stream-in fd-stream) cin-routine
1686 (fd-stream-bin fd-stream) bin-routine)
1687 ;; character type gets preferential treatment
1688 (setf input-size (or cin-size bin-size))
1689 (setf input-type (or cin-type bin-type))
1690 (when normalized-external-format
1691 (setf (fd-stream-external-format fd-stream)
1692 normalized-external-format))
1693 (when (= (or cin-size 1) (or bin-size 1) 1)
1694 (setf (fd-stream-n-bin fd-stream) ;XXX
1695 (if (and character-stream-p (not bivalent-stream-p))
1697 #'fd-stream-read-n-bytes))
1698 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1699 ;; for character and (unsigned-byte 8) streams. In these
1700 ;; cases, fast-read-* will read from the
1701 ;; ansi-stream-(c)in-buffer, saving function calls.
1702 ;; Otherwise, the various data-reading functions in the stream
1703 ;; structure will be called.
1705 (not bivalent-stream-p)
1706 ;; temporary disable on :io streams
1708 (cond (character-stream-p
1709 (setf (ansi-stream-cin-buffer fd-stream)
1710 (make-array +ansi-stream-in-buffer-length+
1711 :element-type 'character)))
1712 ((equal target-type '(unsigned-byte 8))
1713 (setf (ansi-stream-in-buffer fd-stream)
1714 (make-array +ansi-stream-in-buffer-length+
1715 :element-type '(unsigned-byte 8))))))))
1718 (when (or (not character-stream-p) bivalent-stream-p)
1719 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1720 normalized-external-format)
1721 (pick-output-routine (if bivalent-stream-p
1724 (fd-stream-buffering fd-stream)
1726 (unless bout-routine
1727 (error "could not find any output routine for ~S buffered ~S"
1728 (fd-stream-buffering fd-stream)
1730 (when character-stream-p
1731 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1732 normalized-external-format)
1733 (pick-output-routine target-type
1734 (fd-stream-buffering fd-stream)
1736 (unless cout-routine
1737 (error "could not find any output routine for ~S buffered ~S"
1738 (fd-stream-buffering fd-stream)
1740 (when normalized-external-format
1741 (setf (fd-stream-external-format fd-stream)
1742 normalized-external-format))
1743 (when character-stream-p
1744 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1745 (setf (fd-stream-out fd-stream) cout-routine
1746 (fd-stream-bout fd-stream) bout-routine
1747 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1748 #'fd-sout #'ill-out))
1749 (setf output-size (or cout-size bout-size))
1750 (setf output-type (or cout-type bout-type)))
1752 (when (and input-size output-size
1753 (not (eq input-size output-size)))
1754 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1755 input-type input-size
1756 output-type output-size))
1757 (setf (fd-stream-element-size fd-stream)
1758 (or input-size output-size))
1760 (setf (fd-stream-element-type fd-stream)
1761 (cond ((equal input-type output-type)
1767 ((subtypep input-type output-type)
1769 ((subtypep output-type input-type)
1772 (error "Input type (~S) and output type (~S) are unrelated?"
1776 ;;; Handle miscellaneous operations on FD-STREAM.
1777 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1778 (declare (ignore arg2))
1781 (labels ((do-listen ()
1782 (or (not (eql (fd-stream-ibuf-head fd-stream)
1783 (fd-stream-ibuf-tail fd-stream)))
1784 (fd-stream-listen fd-stream)
1786 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1788 ;; If the read can block, LISTEN will certainly return NIL.
1789 (if (sysread-may-block-p fd-stream)
1791 ;; Otherwise select(2) and CL:LISTEN have slightly
1792 ;; different semantics. The former returns that an FD
1793 ;; is readable when a read operation wouldn't block.
1794 ;; That includes EOF. However, LISTEN must return NIL
1796 (progn (catch 'eof-input-catcher
1797 ;; r-b/f too calls select, but it shouldn't
1798 ;; block as long as read can return once w/o
1800 (refill-buffer/fd fd-stream))
1801 ;; At this point either IBUF-HEAD != IBUF-TAIL
1802 ;; and FD-STREAM-LISTEN is NIL, in which case
1803 ;; we should return T, or IBUF-HEAD ==
1804 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1805 ;; which case we should return :EOF for this
1806 ;; call and all future LISTEN call on this stream.
1807 ;; Call ourselves again to determine which case
1812 (setf (fd-stream-unread fd-stream) arg1)
1813 (setf (fd-stream-listen fd-stream) t))
1815 (cond (arg1 ; We got us an abort on our hands.
1816 (when (fd-stream-handler fd-stream)
1817 (sb!sys:remove-fd-handler (fd-stream-handler fd-stream))
1818 (setf (fd-stream-handler fd-stream) nil))
1819 ;; We can't do anything unless we know what file were
1820 ;; dealing with, and we don't want to do anything
1821 ;; strange unless we were writing to the file.
1822 (when (and (fd-stream-file fd-stream)
1823 (fd-stream-obuf-sap fd-stream))
1824 (if (fd-stream-original fd-stream)
1825 ;; If the original is EQ to file we are appending
1826 ;; and can just close the file without renaming.
1827 (unless (eq (fd-stream-original fd-stream)
1828 (fd-stream-file fd-stream))
1829 ;; We have a handle on the original, just revert.
1830 (multiple-value-bind (okay err)
1831 (sb!unix:unix-rename (fd-stream-original fd-stream)
1832 (fd-stream-file fd-stream))
1834 (simple-stream-perror
1835 "couldn't restore ~S to its original contents"
1838 ;; We can't restore the original, and aren't
1839 ;; appending, so nuke that puppy.
1841 ;; FIXME: This is currently the fate of superseded
1842 ;; files, and according to the CLOSE spec this is
1843 ;; wrong. However, there seems to be no clean way to
1844 ;; do that that doesn't involve either copying the
1845 ;; data (bad if the :abort resulted from a full
1846 ;; disk), or renaming the old file temporarily
1847 ;; (probably bad because stream opening becomes more
1849 (multiple-value-bind (okay err)
1850 (sb!unix:unix-unlink (fd-stream-file fd-stream))
1852 (error 'simple-file-error
1853 :pathname (fd-stream-file fd-stream)
1855 "~@<couldn't remove ~S: ~2I~_~A~:>"
1856 :format-arguments (list (fd-stream-file fd-stream)
1857 (strerror err))))))))
1859 (fd-stream-misc-routine fd-stream :finish-output)
1860 (when (and (fd-stream-original fd-stream)
1861 (fd-stream-delete-original fd-stream))
1862 (multiple-value-bind (okay err)
1863 (sb!unix:unix-unlink (fd-stream-original fd-stream))
1865 (error 'simple-file-error
1866 :pathname (fd-stream-original fd-stream)
1868 "~@<couldn't delete ~S during close of ~S: ~
1871 (list (fd-stream-original fd-stream)
1873 (strerror err))))))))
1874 (when (fboundp 'cancel-finalization)
1875 (cancel-finalization fd-stream))
1876 (sb!unix:unix-close (fd-stream-fd fd-stream))
1877 (when (fd-stream-obuf-sap fd-stream)
1878 (with-available-buffers-lock ()
1879 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
1880 (setf (fd-stream-obuf-sap fd-stream) nil)))
1881 (when (fd-stream-ibuf-sap fd-stream)
1882 (with-available-buffers-lock ()
1883 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
1884 (setf (fd-stream-ibuf-sap fd-stream) nil)))
1885 (sb!impl::set-closed-flame fd-stream))
1887 (setf (fd-stream-unread fd-stream) nil)
1888 (setf (fd-stream-ibuf-head fd-stream) 0)
1889 (setf (fd-stream-ibuf-tail fd-stream) 0)
1892 (sb!win32:fd-clear-input (fd-stream-fd fd-stream))
1893 (setf (fd-stream-listen fd-stream) nil))
1895 (catch 'eof-input-catcher
1896 (loop until (sysread-may-block-p fd-stream)
1898 (refill-buffer/fd fd-stream)
1899 (setf (fd-stream-ibuf-head fd-stream) 0)
1900 (setf (fd-stream-ibuf-tail fd-stream) 0))
1903 (flush-output-buffer fd-stream))
1905 (flush-output-buffer fd-stream)
1907 ((null (fd-stream-output-later fd-stream)))
1908 (sb!sys:serve-all-events)))
1910 (fd-stream-element-type fd-stream))
1912 (fd-stream-external-format fd-stream))
1914 (= 1 (the (member 0 1)
1915 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
1919 (fd-stream-char-pos fd-stream))
1921 (unless (fd-stream-file fd-stream)
1922 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
1923 ;; "should signal an error of type TYPE-ERROR if stream is not
1924 ;; a stream associated with a file". Too bad there's no very
1925 ;; appropriate value for the EXPECTED-TYPE slot..
1926 (error 'simple-type-error
1928 :expected-type 'fd-stream
1929 :format-control "~S is not a stream associated with a file."
1930 :format-arguments (list fd-stream)))
1931 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
1932 atime mtime ctime blksize blocks)
1933 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
1934 (declare (ignore ino nlink uid gid rdev
1935 atime mtime ctime blksize blocks))
1937 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
1940 (truncate size (fd-stream-element-size fd-stream)))))
1941 (:file-string-length
1943 (character (fd-stream-character-size fd-stream arg1))
1944 (string (fd-stream-string-size fd-stream arg1))))
1946 (fd-stream-file-position fd-stream arg1))))
1948 (defun fd-stream-file-position (stream &optional newpos)
1949 (declare (type fd-stream stream)
1950 (type (or (alien sb!unix:off-t) (member nil :start :end)) newpos))
1952 (sb!sys:without-interrupts
1953 ;; First, find the position of the UNIX file descriptor in the file.
1954 (multiple-value-bind (posn errno)
1955 (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)
1956 (declare (type (or (alien sb!unix:off-t) null) posn))
1957 (cond ((integerp posn)
1958 ;; Adjust for buffered output: If there is any output
1959 ;; buffered, the *real* file position will be larger
1960 ;; than reported by lseek() because lseek() obviously
1961 ;; cannot take into account output we have not sent
1963 (dolist (later (fd-stream-output-later stream))
1964 (incf posn (- (caddr later)
1966 (incf posn (fd-stream-obuf-tail stream))
1967 ;; Adjust for unread input: If there is any input
1968 ;; read from UNIX but not supplied to the user of the
1969 ;; stream, the *real* file position will smaller than
1970 ;; reported, because we want to look like the unread
1971 ;; stuff is still available.
1972 (decf posn (- (fd-stream-ibuf-tail stream)
1973 (fd-stream-ibuf-head stream)))
1974 (when (fd-stream-unread stream)
1976 ;; Divide bytes by element size.
1977 (truncate posn (fd-stream-element-size stream)))
1978 ((eq errno sb!unix:espipe)
1981 (sb!sys:with-interrupts
1982 (simple-stream-perror "failure in Unix lseek() on ~S"
1985 (let ((offset 0) origin)
1986 (declare (type (alien sb!unix:off-t) offset))
1987 ;; Make sure we don't have any output pending, because if we
1988 ;; move the file pointer before writing this stuff, it will be
1989 ;; written in the wrong location.
1990 (flush-output-buffer stream)
1992 ((null (fd-stream-output-later stream)))
1993 (sb!sys:serve-all-events))
1994 ;; Clear out any pending input to force the next read to go to
1996 (setf (fd-stream-unread stream) nil)
1997 (setf (fd-stream-ibuf-head stream) 0)
1998 (setf (fd-stream-ibuf-tail stream) 0)
1999 ;; Trash cached value for listen, so that we check next time.
2000 (setf (fd-stream-listen stream) nil)
2002 (cond ((eq newpos :start)
2003 (setf offset 0 origin sb!unix:l_set))
2005 (setf offset 0 origin sb!unix:l_xtnd))
2006 ((typep newpos '(alien sb!unix:off-t))
2007 (setf offset (* newpos (fd-stream-element-size stream))
2008 origin sb!unix:l_set))
2010 (error "invalid position given to FILE-POSITION: ~S" newpos)))
2011 (multiple-value-bind (posn errno)
2012 (sb!unix:unix-lseek (fd-stream-fd stream) offset origin)
2013 (cond ((typep posn '(alien sb!unix:off-t))
2015 ((eq errno sb!unix:espipe)
2018 (simple-stream-perror "error in Unix lseek() on ~S"
2022 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2024 ;;; Create a stream for the given Unix file descriptor.
2026 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2027 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2028 ;;; default to allowing input.
2030 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2032 ;;; BUFFERING indicates the kind of buffering to use.
2034 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2035 ;;; NIL (the default), then wait forever. When we time out, we signal
2038 ;;; FILE is the name of the file (will be returned by PATHNAME).
2040 ;;; NAME is used to identify the stream when printed.
2041 (defun make-fd-stream (fd
2044 (output nil output-p)
2045 (element-type 'base-char)
2047 (external-format :default)
2056 (format nil "file ~A" file)
2057 (format nil "descriptor ~W" fd)))
2059 (declare (type index fd) (type (or index null) timeout)
2060 (type (member :none :line :full) buffering))
2061 (cond ((not (or input-p output-p))
2063 ((not (or input output))
2064 (error "File descriptor must be opened either for input or output.")))
2065 (let ((stream (%make-fd-stream :fd fd
2069 :delete-original delete-original
2071 :buffering buffering
2072 :dual-channel-p dual-channel-p
2073 :external-format external-format
2075 (set-fd-stream-routines stream element-type external-format
2076 input output input-buffer-p)
2077 (when (and auto-close (fboundp 'finalize))
2080 (sb!unix:unix-close fd)
2082 (format *terminal-io* "** closed file descriptor ~W **~%"
2086 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2087 ;;; :RENAME-AND-DELETE and :RENAME options.
2088 (defun pick-backup-name (name)
2089 (declare (type simple-string name))
2090 (concatenate 'simple-string name ".bak"))
2092 ;;; Ensure that the given arg is one of the given list of valid
2093 ;;; things. Allow the user to fix any problems.
2094 (defun ensure-one-of (item list what)
2095 (unless (member item list)
2096 (error 'simple-type-error
2098 :expected-type `(member ,@list)
2099 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2100 :format-arguments (list item what list))))
2102 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2103 ;;; access, since we don't want to trash unwritable files even if we
2104 ;;; technically can. We return true if we succeed in renaming.
2105 (defun rename-the-old-one (namestring original)
2106 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2107 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2108 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2111 (error 'simple-file-error
2112 :pathname namestring
2114 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2115 :format-arguments (list namestring original (strerror err))))))
2117 (defun open (filename
2120 (element-type 'base-char)
2121 (if-exists nil if-exists-given)
2122 (if-does-not-exist nil if-does-not-exist-given)
2123 (external-format :default)
2124 &aux ; Squelch assignment warning.
2125 (direction direction)
2126 (if-does-not-exist if-does-not-exist)
2127 (if-exists if-exists))
2129 "Return a stream which reads from or writes to FILENAME.
2131 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2132 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2133 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2134 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2135 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2136 See the manual for details."
2138 ;; Calculate useful stuff.
2139 (multiple-value-bind (input output mask)
2141 (:input (values t nil sb!unix:o_rdonly))
2142 (:output (values nil t sb!unix:o_wronly))
2143 (:io (values t t sb!unix:o_rdwr))
2144 (:probe (values t nil sb!unix:o_rdonly)))
2145 (declare (type index mask))
2146 (let* ((pathname (merge-pathnames filename))
2148 (cond ((unix-namestring pathname input))
2149 ((and input (eq if-does-not-exist :create))
2150 (unix-namestring pathname nil))
2151 ((and (eq direction :io) (not if-does-not-exist-given))
2152 (unix-namestring pathname nil)))))
2153 ;; Process if-exists argument if we are doing any output.
2155 (unless if-exists-given
2157 (if (eq (pathname-version pathname) :newest)
2160 (ensure-one-of if-exists
2161 '(:error :new-version :rename
2162 :rename-and-delete :overwrite
2163 :append :supersede nil)
2166 ((:new-version :error nil)
2167 (setf mask (logior mask sb!unix:o_excl)))
2168 ((:rename :rename-and-delete)
2169 (setf mask (logior mask sb!unix:o_creat)))
2171 (setf mask (logior mask sb!unix:o_trunc)))
2173 (setf mask (logior mask sb!unix:o_append)))))
2175 (setf if-exists :ignore-this-arg)))
2177 (unless if-does-not-exist-given
2178 (setf if-does-not-exist
2179 (cond ((eq direction :input) :error)
2181 (member if-exists '(:overwrite :append)))
2183 ((eq direction :probe)
2187 (ensure-one-of if-does-not-exist
2188 '(:error :create nil)
2190 (if (eq if-does-not-exist :create)
2191 (setf mask (logior mask sb!unix:o_creat)))
2193 (let ((original (case if-exists
2194 ((:rename :rename-and-delete)
2195 (pick-backup-name namestring))
2196 ((:append :overwrite)
2197 ;; KLUDGE: Provent CLOSE from deleting
2198 ;; appending streams when called with :ABORT T
2200 (delete-original (eq if-exists :rename-and-delete))
2202 (when (and original (not (eq original namestring)))
2203 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2204 ;; whether the file already exists, make sure the original
2205 ;; file is not a directory, and keep the mode.
2208 (multiple-value-bind (okay err/dev inode orig-mode)
2209 (sb!unix:unix-stat namestring)
2210 (declare (ignore inode)
2211 (type (or index null) orig-mode))
2214 (when (and output (= (logand orig-mode #o170000)
2216 (error 'simple-file-error
2217 :pathname namestring
2219 "can't open ~S for output: is a directory"
2220 :format-arguments (list namestring)))
2221 (setf mode (logand orig-mode #o777))
2223 ((eql err/dev sb!unix:enoent)
2226 (simple-file-perror "can't find ~S"
2230 (rename-the-old-one namestring original))
2232 (setf delete-original nil)
2233 ;; In order to use :SUPERSEDE instead, we have to make
2234 ;; sure SB!UNIX:O_CREAT corresponds to
2235 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2236 ;; because of IF-EXISTS being :RENAME.
2237 (unless (eq if-does-not-exist :create)
2239 (logior (logandc2 mask sb!unix:o_creat)
2241 (setf if-exists :supersede))))
2243 ;; Now we can try the actual Unix open(2).
2244 (multiple-value-bind (fd errno)
2246 (sb!unix:unix-open namestring mask mode)
2247 (values nil sb!unix:enoent))
2248 (labels ((open-error (format-control &rest format-arguments)
2249 (error 'simple-file-error
2251 :format-control format-control
2252 :format-arguments format-arguments))
2253 (vanilla-open-error ()
2254 (simple-file-perror "error opening ~S" pathname errno)))
2257 ((:input :output :io)
2261 :element-type element-type
2262 :external-format external-format
2265 :delete-original delete-original
2272 (%make-fd-stream :name namestring
2275 :element-type element-type)))
2278 ((eql errno sb!unix:enoent)
2279 (case if-does-not-exist
2280 (:error (vanilla-open-error))
2282 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2285 ((and (eql errno sb!unix:eexist) (null if-exists))
2288 (vanilla-open-error)))))))))
2292 ;;; the stream connected to the controlling terminal, or NIL if there is none
2295 ;;; the stream connected to the standard input (file descriptor 0)
2298 ;;; the stream connected to the standard output (file descriptor 1)
2301 ;;; the stream connected to the standard error output (file descriptor 2)
2304 ;;; This is called when the cold load is first started up, and may also
2305 ;;; be called in an attempt to recover from nested errors.
2306 (defun stream-cold-init-or-reset ()
2308 (setf *terminal-io* (make-synonym-stream '*tty*))
2309 (setf *standard-output* (make-synonym-stream '*stdout*))
2310 (setf *standard-input* (make-synonym-stream '*stdin*))
2311 (setf *error-output* (make-synonym-stream '*stderr*))
2312 (setf *query-io* (make-synonym-stream '*terminal-io*))
2313 (setf *debug-io* *query-io*)
2314 (setf *trace-output* *standard-output*)
2317 ;;; This is called whenever a saved core is restarted.
2318 (defun stream-reinit ()
2319 (setf *available-buffers* nil)
2320 (with-output-to-string (*error-output*)
2322 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2323 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2325 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2326 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2328 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2329 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2330 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2331 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2335 :name "the terminal"
2340 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2341 (princ (get-output-stream-string *error-output*) *stderr*))
2346 ;;; the Unix way to beep
2347 (defun beep (stream)
2348 (write-char (code-char bell-char-code) stream)
2349 (finish-output stream))
2351 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2352 ;;; by the filesys stuff to get and set the file name.
2354 ;;; FIXME: misleading name, screwy interface
2355 (defun file-name (stream &optional new-name)
2356 (when (typep stream 'fd-stream)
2358 (setf (fd-stream-pathname stream) new-name)
2359 (setf (fd-stream-file stream)
2360 (unix-namestring new-name nil))
2363 (fd-stream-pathname stream)))))