1 ;;;; streams for UNIX file descriptors
3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!IMPL")
16 ;;;; Streams hold BUFFER objects, which contain a SAP, size of the
17 ;;;; memory area the SAP stands for (LENGTH bytes), and HEAD and TAIL
18 ;;;; indexes which delimit the "valid", or "active" area of the
19 ;;;; memory. HEAD is inclusive, TAIL is exclusive.
21 ;;;; Buffers get allocated lazily, and are recycled by returning them
22 ;;;; to the *AVAILABLE-BUFFERS* list. Every buffer has it's own
23 ;;;; finalizer, to take care of releasing the SAP memory when a stream
24 ;;;; is not properly closed.
26 ;;;; The code aims to provide a limited form of thread and interrupt
27 ;;;; safety: parallel writes and reads may lose output or input, cause
28 ;;;; interleaved IO, etc -- but they should not corrupt memory. The
29 ;;;; key to doing this is to read buffer state once, and update the
30 ;;;; state based on the read state:
32 ;;;; (let ((tail (buffer-tail buffer)))
34 ;;;; (setf (buffer-tail buffer) (+ tail n)))
38 ;;;; (let ((tail (buffer-tail buffer)))
40 ;;;; (incf (buffer-tail buffer) n))
43 (defstruct (buffer (:constructor %make-buffer
(sap length
)))
44 (sap (missing-arg) :type system-area-pointer
:read-only t
)
45 (length (missing-arg) :type index
:read-only t
)
48 (declaim (freeze-type buffer
))
50 (defvar *available-buffers
* ()
52 "List of available buffers.")
54 (defvar *available-buffers-lock
* (sb!thread
:make-mutex
55 :name
"lock for *AVAILABLE-BUFFERS*")
57 "Mutex for access to *AVAILABLE-BUFFERS*.")
59 (defmacro with-available-buffers-lock
((&optional
) &body body
)
60 ;; CALL-WITH-SYSTEM-MUTEX because streams are low-level enough to be
61 ;; async signal safe, and in particular a C-c that brings up the
62 ;; debugger while holding the mutex would lose badly.
63 `(sb!thread
::with-system-mutex
(*available-buffers-lock
*)
66 (defconstant +bytes-per-buffer
+ (* 4 1024)
68 "Default number of bytes per buffer.")
70 (defun alloc-buffer (&optional
(size +bytes-per-buffer
+))
71 ;; Don't want to allocate & unwind before the finalizer is in place.
73 (let* ((sap (allocate-system-memory size
))
74 (buffer (%make-buffer sap size
)))
75 (when (zerop (sap-int sap
))
76 (error "Could not allocate ~D bytes for buffer." size
))
77 (finalize buffer
(lambda ()
78 (deallocate-system-memory sap size
))
83 ;; Don't go for the lock if there is nothing to be had -- sure,
84 ;; another thread might just release one before we get it, but that
85 ;; is not worth the cost of locking. Also release the lock before
86 ;; allocation, since it's going to take a while.
87 (if *available-buffers
*
88 (or (with-available-buffers-lock ()
89 (pop *available-buffers
*))
93 (declaim (inline reset-buffer
))
94 (defun reset-buffer (buffer)
95 (setf (buffer-head buffer
) 0
96 (buffer-tail buffer
) 0)
99 (defun release-buffer (buffer)
100 (reset-buffer buffer
)
101 (with-available-buffers-lock ()
102 (push buffer
*available-buffers
*)))
105 ;;;; the FD-STREAM structure
107 ;;; Coarsely characterizes the element type of an FD-STREAM w.r.t.
108 ;;; its SUBTYPEP relations to the relevant CHARACTER and
109 ;;; ([UN]SIGNED-BYTE 8) types. This coarse characterization enables
110 ;;; dispatching on the element type as needed by {READ,WRITE}-SEQUENCE
111 ;;; without calling SUBTYPEP.
112 (deftype stream-element-mode
()
113 '(member character unsigned-byte signed-byte
:bivalent
))
115 (defstruct (fd-stream
116 (:constructor %make-fd-stream
)
117 (:conc-name fd-stream-
)
118 (:predicate fd-stream-p
)
119 (:include ansi-stream
120 (misc #'fd-stream-misc-routine
))
123 ;; the name of this stream
125 ;; the file this stream is for
127 ;; the backup file namestring for the old file, for :IF-EXISTS
128 ;; :RENAME or :RENAME-AND-DELETE.
129 (original nil
:type
(or simple-string null
))
130 (delete-original nil
) ; for :if-exists :rename-and-delete
131 ;;; the number of bytes per element
132 (element-size 1 :type index
)
133 ;; the type of element being transfered
134 (element-type 'base-char
)
135 ;; coarse characterization of the element type. see description of
136 ;; STREAM-ELEMENT-MODE type.
137 (element-mode :bivalent
:type stream-element-mode
)
138 ;; the Unix file descriptor
139 (fd -
1 :type
#!-win32 fixnum
#!+win32 sb
!vm
:signed-word
)
140 ;; What do we know about the FD?
141 (fd-type :unknown
:type keyword
)
142 ;; controls when the output buffer is flushed
143 (buffering :full
:type
(member :full
:line
:none
))
144 ;; controls whether the input buffer must be cleared before output
145 ;; (must be done for files, not for sockets, pipes and other data
146 ;; sources where input and output aren't related). non-NIL means
147 ;; don't clear input buffer.
149 ;; character position if known -- this may run into bignums, but
150 ;; we probably should flip it into null then for efficiency's sake...
151 (output-column nil
:type
(or unsigned-byte null
))
152 ;; T if input is waiting on FD. :EOF if we hit EOF.
153 (listen nil
:type
(member nil t
:eof
))
154 ;; T if serve-event is allowed when this stream blocks
155 (serve-events nil
:type boolean
)
158 (instead (make-array 0 :element-type
'character
:adjustable t
:fill-pointer t
) :type
(array character
(*)))
159 (ibuf nil
:type
(or buffer null
))
160 (eof-forced-p nil
:type
(member t nil
))
163 (obuf nil
:type
(or buffer null
))
165 ;; output flushed, but not written due to non-blocking io?
168 ;; timeout specified for this stream as seconds or NIL if none
169 (timeout nil
:type
(or single-float null
))
170 ;; pathname of the file this stream is opened to (returned by PATHNAME)
171 (pathname nil
:type
(or pathname null
))
172 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
173 (external-format :latin-1
)
174 ;; fixed width, or function to call with a character
175 (char-size 1 :type
(or fixnum function
))
176 (output-bytes #'ill-out
:type function
))
178 (defun fd-stream-bivalent-p (stream)
179 (eq (fd-stream-element-mode stream
) :bivalent
))
181 (def!method print-object
((fd-stream fd-stream
) stream
)
182 (declare (type stream stream
))
183 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
184 (format stream
"for ~S" (fd-stream-name fd-stream
))))
186 ;;; This is a separate buffer management function, as it wants to be
187 ;;; clever about locking -- grabbing the lock just once.
188 (defun release-fd-stream-buffers (fd-stream)
189 (let ((ibuf (fd-stream-ibuf fd-stream
))
190 (obuf (fd-stream-obuf fd-stream
))
191 (queue (loop for item in
(fd-stream-output-queue fd-stream
)
193 collect
(reset-buffer item
))))
195 (push (reset-buffer ibuf
) queue
))
197 (push (reset-buffer obuf
) queue
))
198 ;; ...so, anything found?
200 ;; detach from stream
201 (setf (fd-stream-ibuf fd-stream
) nil
202 (fd-stream-obuf fd-stream
) nil
203 (fd-stream-output-queue fd-stream
) nil
)
204 ;; splice to *available-buffers*
205 (with-available-buffers-lock ()
206 (setf *available-buffers
* (nconc queue
*available-buffers
*))))))
208 ;;;; FORM-TRACKING-STREAM
210 ;; The compiler uses this to record for each input subform the start and
211 ;; end positions as character offsets. Measuring in characters rather than
212 ;; bytes is both better suited to the task - in that it is consistent with
213 ;; reporting of "point" by Emacs - and faster than querying FILE-POSITION.
214 ;; The slowness of FILE-POSITION on an FD-STREAM is due to making a system
215 ;; call every time, to ensure that the case of an append-only stream works
216 ;; correctly (where the OS forces all writes to the end), and other factors.
218 (defstruct (form-tracking-stream
219 (:constructor %make-form-tracking-stream
)
221 (misc #'tracking-stream-misc
)
224 ;; a function which is called for events on this stream.
225 (observer (lambda (x y z
) (declare (ignore x y z
))) :type function
)
226 ;; A vector of the character position of each #\Newline seen
227 (newlines (make-array 10 :fill-pointer
0 :adjustable t
))
228 (last-newline -
1 :type index-or-minus-1
)
229 ;; Better than reporting that a reader error occurred at a position
230 ;; before any whitespace (or equivalently, a macro producing no value),
231 ;; we can note the position at the first "good" character.
232 (form-start-byte-pos)
233 (form-start-char-pos))
235 (defun line/col-from-charpos
236 (stream &optional
(charpos (ansi-stream-input-char-pos stream
)))
237 (let* ((newlines (form-tracking-stream-newlines stream
))
238 (index (position charpos newlines
:test
#'>= :from-end t
)))
239 ;; Line numbers traditionally begin at 1, columns at 0.
241 ;; INDEX is 1 less than the number of newlines seen
242 ;; up to and including this startpos.
243 ;; e.g. index=0 => 1 newline seen => line=2
245 ;; 1 char after the newline = column 0
246 (- charpos
(aref newlines index
) 1))
247 ;; zero newlines were seen
250 ;;;; CORE OUTPUT FUNCTIONS
252 ;;; Buffer the section of THING delimited by START and END by copying
253 ;;; to output buffer(s) of stream.
254 (defun buffer-output (stream thing start end
)
255 (declare (index start end
))
257 (error ":END before :START!"))
259 ;; Copy bytes from THING to buffers.
260 (flet ((copy-to-buffer (buffer tail count
)
261 (declare (buffer buffer
) (index tail count
))
263 (let ((sap (buffer-sap buffer
)))
266 (system-area-ub8-copy thing start sap tail count
))
267 ((simple-unboxed-array (*))
268 (copy-ub8-to-system-area thing start sap tail count
))))
269 ;; Not INCF! If another thread has moved tail from under
270 ;; us, we don't want to accidentally increment tail
271 ;; beyond buffer-length.
272 (setf (buffer-tail buffer
) (+ count tail
))
275 ;; First copy is special: the buffer may already contain
276 ;; something, or be even full.
277 (let* ((obuf (fd-stream-obuf stream
))
278 (tail (buffer-tail obuf
))
279 (space (- (buffer-length obuf
) tail
)))
281 (copy-to-buffer obuf tail
(min space
(- end start
)))
282 (go :more-output-p
)))
284 ;; Later copies should always have an empty buffer, since
285 ;; they are freshly flushed, but if another thread is
286 ;; stomping on the same buffer that might not be the case.
287 (let* ((obuf (flush-output-buffer stream
))
288 (tail (buffer-tail obuf
))
289 (space (- (buffer-length obuf
) tail
)))
290 (copy-to-buffer obuf tail
(min space
(- end start
))))
293 (go :flush-and-fill
))))))
295 ;;; Flush the current output buffer of the stream, ensuring that the
296 ;;; new buffer is empty. Returns (for convenience) the new output
297 ;;; buffer -- which may or may not be EQ to the old one. If the is no
298 ;;; queued output we try to write the buffer immediately -- otherwise
299 ;;; we queue it for later.
300 (defun flush-output-buffer (stream)
301 (let ((obuf (fd-stream-obuf stream
)))
303 (let ((head (buffer-head obuf
))
304 (tail (buffer-tail obuf
)))
305 (cond ((eql head tail
)
306 ;; Buffer is already empty -- just ensure that is is
307 ;; set to zero as well.
309 ((fd-stream-output-queue stream
)
310 ;; There is already stuff on the queue -- go directly
313 (%queue-and-replace-output-buffer stream
))
315 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
316 ;; whatever is left over. Otherwise wait until we can write.
318 (synchronize-stream-output stream
)
320 (let ((length (- tail head
)))
321 (multiple-value-bind (count errno
)
322 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
324 (flet ((queue-or-wait ()
325 (if (fd-stream-serve-events stream
)
326 (return (%queue-and-replace-output-buffer stream
))
327 (or (wait-until-fd-usable (fd-stream-fd stream
) :output
328 (fd-stream-timeout stream
)
330 (signal-timeout 'io-timeout
333 :seconds
(fd-stream-timeout stream
))))))
334 (cond ((eql count length
)
335 ;; Complete write -- we can use the same buffer.
336 (return (reset-buffer obuf
)))
338 ;; Partial write -- update buffer status and
341 (setf (buffer-head obuf
) head
)
344 ((eql errno sb
!unix
:ewouldblock
)
345 ;; Blocking, queue or wair.
347 ;; if interrupted on win32, just try again
348 #!+win32
((eql errno sb
!unix
:eintr
))
350 (simple-stream-perror "Couldn't write to ~s"
351 stream errno
)))))))))))))
353 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
354 (defun %queue-and-replace-output-buffer
(stream)
355 (aver (fd-stream-serve-events stream
))
356 (let ((queue (fd-stream-output-queue stream
))
357 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
359 ;; Important: before putting the buffer on queue, give the stream
360 ;; a new one. If we get an interrupt and unwind losing the buffer
361 ;; is relatively OK, but having the same buffer in two places
363 (setf (fd-stream-obuf stream
) new
)
367 (setf (fd-stream-output-queue stream
) later
)))
368 (unless (fd-stream-handler stream
)
369 (setf (fd-stream-handler stream
)
370 (add-fd-handler (fd-stream-fd stream
)
373 (declare (ignore fd
))
374 (write-output-from-queue stream
)))))
377 ;;; This is called by the FD-HANDLER for the stream when output is
379 (defun write-output-from-queue (stream)
380 (aver (fd-stream-serve-events stream
))
381 (synchronize-stream-output stream
)
385 (let* ((buffer (pop (fd-stream-output-queue stream
)))
386 (head (buffer-head buffer
))
387 (length (- (buffer-tail buffer
) head
)))
388 (declare (index head length
))
390 (multiple-value-bind (count errno
)
391 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
393 (cond ((eql count length
)
394 ;; Complete write, see if we can do another right
395 ;; away, or remove the handler if we're done.
396 (release-buffer buffer
)
397 (cond ((fd-stream-output-queue stream
)
401 (let ((handler (fd-stream-handler stream
)))
403 (setf (fd-stream-handler stream
) nil
)
404 (remove-fd-handler handler
)))))
406 ;; Partial write. Update buffer status and requeue.
407 (aver (< count length
))
408 ;; Do not use INCF! Another thread might have moved head.
409 (setf (buffer-head buffer
) (+ head count
))
410 (push buffer
(fd-stream-output-queue stream
)))
412 ;; We tried to do multiple writes, and finally our
413 ;; luck ran out. Requeue.
414 (push buffer
(fd-stream-output-queue stream
)))
416 ;; Could not write on the first try at all!
418 (simple-stream-perror "Couldn't write to ~S." stream errno
)
420 (if (= errno sb
!unix
:ewouldblock
)
421 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
422 (simple-stream-perror "Couldn't write to ~S"
426 ;;; Try to write THING directly to STREAM without buffering, if
427 ;;; possible. If direct write doesn't happen, buffer.
428 (defun write-or-buffer-output (stream thing start end
)
429 (declare (index start end
))
430 (cond ((fd-stream-output-queue stream
)
431 (buffer-output stream thing start end
))
433 (error ":END before :START!"))
435 (let ((length (- end start
)))
436 (synchronize-stream-output stream
)
437 (multiple-value-bind (count errno
)
438 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
439 (cond ((eql count length
)
440 ;; Complete write -- done!
443 (aver (< count length
))
444 ;; Partial write -- buffer the rest.
445 (buffer-output stream thing
(+ start count
) end
))
447 ;; Could not write -- buffer or error.
449 (simple-stream-perror "couldn't write to ~s" stream errno
)
451 (if (= errno sb
!unix
:ewouldblock
)
452 (buffer-output stream thing start end
)
453 (simple-stream-perror "couldn't write to ~s" stream errno
)))))))))
455 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
456 ;;; this is not something we want to export. Nikodemus thinks the
457 ;;; right thing is to support a low-level non-stream like IO layer,
458 ;;; akin to java.nio.
459 (declaim (inline output-raw-bytes
))
460 (define-deprecated-function :late
"1.0.8.16" output-raw-bytes write-sequence
461 (stream thing
&optional start end
)
462 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
464 ;;;; output routines and related noise
466 (defvar *output-routines
* ()
468 "List of all available output routines. Each element is a list of the
469 element-type output, the kind of buffering, the function name, and the number
470 of bytes per element.")
472 ;;; common idioms for reporting low-level stream and file problems
473 (defun simple-stream-perror (note-format stream errno
)
474 (error 'simple-stream-error
476 :format-control
"~@<~?: ~2I~_~A~:>"
477 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
478 (defun simple-file-perror (note-format pathname errno
)
479 (error 'simple-file-error
481 :format-control
"~@<~?: ~2I~_~A~:>"
483 (list note-format
(list pathname
) (strerror errno
))))
485 (defun c-string-encoding-error (external-format code
)
486 (error 'c-string-encoding-error
487 :external-format external-format
489 (defun c-string-decoding-error (external-format sap offset count
)
490 (error 'c-string-decoding-error
491 :external-format external-format
492 :octets
(sap-ref-octets sap offset count
)))
494 ;;; Returning true goes into end of file handling, false will enter another
495 ;;; round of input buffer filling followed by re-entering character decode.
496 (defun stream-decoding-error-and-handle (stream octet-count
)
498 (error 'stream-decoding-error
499 :external-format
(stream-external-format stream
)
501 :octets
(let ((buffer (fd-stream-ibuf stream
)))
502 (sap-ref-octets (buffer-sap buffer
)
506 :report
(lambda (stream)
508 "~@<Attempt to resync the stream at a ~
509 character boundary and continue.~@:>"))
510 (fd-stream-resync stream
)
512 (force-end-of-file ()
513 :report
(lambda (stream)
514 (format stream
"~@<Force an end of file.~@:>"))
515 (setf (fd-stream-eof-forced-p stream
) t
))
516 (input-replacement (string)
517 :report
(lambda (stream)
518 (format stream
"~@<Use string as replacement input, ~
519 attempt to resync at a character ~
520 boundary and continue.~@:>"))
521 :interactive
(lambda ()
522 (format *query-io
* "~@<Enter a string: ~@:>")
523 (finish-output *query-io
*)
524 (list (read *query-io
*)))
525 (let ((string (reverse (string string
)))
526 (instead (fd-stream-instead stream
)))
527 (dotimes (i (length string
))
528 (vector-push-extend (char string i
) instead
))
529 (fd-stream-resync stream
)
530 (when (> (length string
) 0)
531 (setf (fd-stream-listen stream
) t
)))
534 (defun stream-encoding-error-and-handle (stream code
)
536 (error 'stream-encoding-error
537 :external-format
(stream-external-format stream
)
541 :report
(lambda (stream)
542 (format stream
"~@<Skip output of this character.~@:>"))
543 (throw 'output-nothing nil
))
544 (output-replacement (string)
545 :report
(lambda (stream)
546 (format stream
"~@<Output replacement string.~@:>"))
547 :interactive
(lambda ()
548 (format *query-io
* "~@<Enter a string: ~@:>")
549 (finish-output *query-io
*)
550 (list (read *query-io
*)))
551 (let ((string (string string
)))
552 (fd-sout stream
(string string
) 0 (length string
)))
553 (throw 'output-nothing nil
))))
555 (defun external-format-encoding-error (stream code
)
557 (stream-encoding-error-and-handle stream code
)
558 (c-string-encoding-error stream code
)))
560 (defun synchronize-stream-output (stream)
561 ;; If we're reading and writing on the same file, flush buffered
562 ;; input and rewind file position accordingly.
563 (unless (fd-stream-dual-channel-p stream
)
564 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
565 (unless (eql 0 adjust
)
566 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
568 (defun fd-stream-output-finished-p (stream)
569 (let ((obuf (fd-stream-obuf stream
)))
571 (and (zerop (buffer-tail obuf
))
572 (not (fd-stream-output-queue stream
))))))
574 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
576 (let ((stream-var (gensym "STREAM")))
577 `(let* ((,stream-var
,stream
)
578 (obuf (fd-stream-obuf ,stream-var
))
579 (tail (buffer-tail obuf
))
581 ,(unless (eq (car buffering
) :none
)
582 `(when (< (buffer-length obuf
) (+ tail size
))
583 (setf obuf
(flush-output-buffer ,stream-var
)
584 tail
(buffer-tail obuf
))))
585 ,(unless (eq (car buffering
) :none
)
586 ;; FIXME: Why this here? Doesn't seem necessary.
587 `(synchronize-stream-output ,stream-var
))
589 `(catch 'output-nothing
591 (setf (buffer-tail obuf
) (+ tail size
)))
594 (setf (buffer-tail obuf
) (+ tail size
))))
595 ,(ecase (car buffering
)
597 `(flush-output-buffer ,stream-var
))
599 `(when (eql byte
#\Newline
)
600 (flush-output-buffer ,stream-var
)))
604 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
605 (let ((stream-var (gensym "STREAM")))
606 `(let* ((,stream-var
,stream
)
607 (obuf (fd-stream-obuf ,stream-var
))
608 (tail (buffer-tail obuf
)))
609 ,(unless (eq (car buffering
) :none
)
610 `(when (< (buffer-length obuf
) (+ tail
,size
))
611 (setf obuf
(flush-output-buffer ,stream-var
)
612 tail
(buffer-tail obuf
))))
613 ;; FIXME: Why this here? Doesn't seem necessary.
614 ,(unless (eq (car buffering
) :none
)
615 `(synchronize-stream-output ,stream-var
))
617 `(catch 'output-nothing
619 (setf (buffer-tail obuf
) (+ tail
,size
)))
622 (setf (buffer-tail obuf
) (+ tail
,size
))))
623 ,(ecase (car buffering
)
625 `(flush-output-buffer ,stream-var
))
627 `(when (eql byte
#\Newline
)
628 (flush-output-buffer ,stream-var
)))
632 (defmacro def-output-routines
/variable-width
633 ((name-fmt size restart external-format
&rest bufferings
)
635 (declare (optimize (speed 1)))
640 (intern (format nil name-fmt
(string (car buffering
))))))
642 (defun ,function
(stream byte
)
643 (declare (ignorable byte
))
644 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
646 (setf *output-routines
*
647 (nconc *output-routines
*
655 (cdr buffering
)))))))
658 ;;; Define output routines that output numbers SIZE bytes long for the
659 ;;; given bufferings. Use BODY to do the actual output.
660 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
662 (declare (optimize (speed 1)))
667 (intern (format nil name-fmt
(string (car buffering
))))))
669 (defun ,function
(stream byte
)
670 (output-wrapper (stream ,size
,buffering
,restart
)
672 (setf *output-routines
*
673 (nconc *output-routines
*
681 (cdr buffering
)))))))
684 ;;; FIXME: is this used anywhere any more?
685 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
691 (if (eql byte
#\Newline
)
692 (setf (fd-stream-output-column stream
) 0)
693 (incf (fd-stream-output-column stream
)))
694 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
697 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
700 (:none
(unsigned-byte 8))
701 (:full
(unsigned-byte 8)))
702 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
705 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
708 (:none
(signed-byte 8))
709 (:full
(signed-byte 8)))
710 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
713 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
716 (:none
(unsigned-byte 16))
717 (:full
(unsigned-byte 16)))
718 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
721 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
724 (:none
(signed-byte 16))
725 (:full
(signed-byte 16)))
726 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
729 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
732 (:none
(unsigned-byte 32))
733 (:full
(unsigned-byte 32)))
734 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
737 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
740 (:none
(signed-byte 32))
741 (:full
(signed-byte 32)))
742 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
747 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
750 (:none
(unsigned-byte 64))
751 (:full
(unsigned-byte 64)))
752 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
754 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
757 (:none
(signed-byte 64))
758 (:full
(signed-byte 64)))
759 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
762 ;;; the routine to use to output a string. If the stream is
763 ;;; unbuffered, slam the string down the file descriptor, otherwise
764 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
765 ;;; checking to see where the last newline was.
766 (defun fd-sout (stream thing start end
)
767 (declare (type fd-stream stream
) (type string thing
))
768 (let ((start (or start
0))
769 (end (or end
(length (the vector thing
)))))
770 (declare (fixnum start end
))
772 (string-dispatch (simple-base-string
774 (simple-array character
(*))
777 (position #\newline thing
:from-end t
778 :start start
:end end
))))
779 (if (and (typep thing
'base-string
)
780 (eq (fd-stream-external-format-keyword stream
) :latin-1
))
781 (ecase (fd-stream-buffering stream
)
783 (buffer-output stream thing start end
))
785 (buffer-output stream thing start end
)
787 (flush-output-buffer stream
)))
789 (write-or-buffer-output stream thing start end
)))
790 (ecase (fd-stream-buffering stream
)
791 (:full
(funcall (fd-stream-output-bytes stream
)
792 stream thing nil start end
))
793 (:line
(funcall (fd-stream-output-bytes stream
)
794 stream thing last-newline start end
))
795 (:none
(funcall (fd-stream-output-bytes stream
)
796 stream thing t start end
))))
798 (setf (fd-stream-output-column stream
) (- end last-newline
1))
799 (incf (fd-stream-output-column stream
) (- end start
))))))
801 (defstruct (external-format
802 (:constructor %make-external-format
)
804 (:predicate external-format-p
)
805 (:copier %copy-external-format
))
806 ;; All the names that can refer to this external format. The first
807 ;; one is the canonical name.
808 (names (missing-arg) :type list
:read-only t
)
809 (default-replacement-character (missing-arg) :type character
)
810 (read-n-chars-fun (missing-arg) :type function
)
811 (read-char-fun (missing-arg) :type function
)
812 (write-n-bytes-fun (missing-arg) :type function
)
813 (write-char-none-buffered-fun (missing-arg) :type function
)
814 (write-char-line-buffered-fun (missing-arg) :type function
)
815 (write-char-full-buffered-fun (missing-arg) :type function
)
816 ;; Can be nil for fixed-width formats.
817 (resync-fun nil
:type
(or function null
))
818 (bytes-for-char-fun (missing-arg) :type function
)
819 (read-c-string-fun (missing-arg) :type function
)
820 (write-c-string-fun (missing-arg) :type function
)
821 ;; We indirect through symbols in these functions so that a
822 ;; developer working on the octets code can easily redefine things
823 ;; and use the new function definition without redefining the
824 ;; external format as well. The slots above don't do any
825 ;; indirection because a developer working with those slots would be
826 ;; redefining the external format anyway.
827 (octets-to-string-fun (missing-arg) :type function
)
828 (string-to-octets-fun (missing-arg) :type function
))
830 (defun ef-char-size (ef-entry)
831 (if (variable-width-external-format-p ef-entry
)
832 (bytes-for-char-fun ef-entry
)
833 (funcall (bytes-for-char-fun ef-entry
) #\x
)))
835 (defun wrap-external-format-functions (external-format fun
)
836 (let ((result (%copy-external-format external-format
)))
837 (macrolet ((frob (accessor)
838 `(setf (,accessor result
) (funcall fun
(,accessor result
)))))
839 (frob ef-read-n-chars-fun
)
840 (frob ef-read-char-fun
)
841 (frob ef-write-n-bytes-fun
)
842 (frob ef-write-char-none-buffered-fun
)
843 (frob ef-write-char-line-buffered-fun
)
844 (frob ef-write-char-full-buffered-fun
)
846 (frob ef-bytes-for-char-fun
)
847 (frob ef-read-c-string-fun
)
848 (frob ef-write-c-string-fun
)
849 (frob ef-octets-to-string-fun
)
850 (frob ef-string-to-octets-fun
))
853 (defvar *external-formats
* (make-hash-table)
855 "Hashtable of all available external formats. The table maps from
856 external-format names to EXTERNAL-FORMAT structures.")
858 (defun get-external-format-or-lose (external-format)
859 (or (get-external-format external-format
)
860 (error "Undefined external-format: ~S" external-format
)))
862 (defun external-format-keyword (external-format)
863 (typecase external-format
864 (keyword external-format
)
865 ((cons keyword
) (car external-format
))))
867 (defun fd-stream-external-format-keyword (stream)
868 (external-format-keyword (fd-stream-external-format stream
)))
870 (defun canonize-external-format (external-format entry
)
871 (typecase external-format
872 (keyword (first (ef-names entry
)))
873 ((cons keyword
) (cons (first (ef-names entry
)) (rest external-format
)))))
875 ;;; Find an output routine to use given the type and buffering. Return
876 ;;; as multiple values the routine, the real type transfered, and the
877 ;;; number of bytes per element.
878 (defun pick-output-routine (type buffering
&optional external-format
)
879 (when (subtypep type
'character
)
880 (let ((entry (get-external-format-or-lose external-format
)))
881 (return-from pick-output-routine
882 (values (ecase buffering
883 (:none
(ef-write-char-none-buffered-fun entry
))
884 (:line
(ef-write-char-line-buffered-fun entry
))
885 (:full
(ef-write-char-full-buffered-fun entry
)))
888 (ef-write-n-bytes-fun entry
)
890 (canonize-external-format external-format entry
)))))
891 (dolist (entry *output-routines
*)
892 (when (and (subtypep type
(first entry
))
893 (eq buffering
(second entry
))
894 (or (not (fifth entry
))
895 (eq external-format
(fifth entry
))))
896 (return-from pick-output-routine
897 (values (symbol-function (third entry
))
900 ;; KLUDGE: dealing with the buffering here leads to excessive code
903 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
904 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
905 if
(subtypep type
`(unsigned-byte ,i
))
906 do
(return-from pick-output-routine
910 (lambda (stream byte
)
911 (output-wrapper (stream (/ i
8) (:none
) nil
)
912 (loop for j from
0 below
(/ i
8)
913 do
(setf (sap-ref-8 (buffer-sap obuf
)
915 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
917 (lambda (stream byte
)
918 (output-wrapper (stream (/ i
8) (:full
) nil
)
919 (loop for j from
0 below
(/ i
8)
920 do
(setf (sap-ref-8 (buffer-sap obuf
)
922 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
925 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
926 if
(subtypep type
`(signed-byte ,i
))
927 do
(return-from pick-output-routine
931 (lambda (stream byte
)
932 (output-wrapper (stream (/ i
8) (:none
) nil
)
933 (loop for j from
0 below
(/ i
8)
934 do
(setf (sap-ref-8 (buffer-sap obuf
)
936 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
938 (lambda (stream byte
)
939 (output-wrapper (stream (/ i
8) (:full
) nil
)
940 (loop for j from
0 below
(/ i
8)
941 do
(setf (sap-ref-8 (buffer-sap obuf
)
943 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
947 ;;;; input routines and related noise
949 ;;; a list of all available input routines. Each element is a list of
950 ;;; the element-type input, the function name, and the number of bytes
952 (defvar *input-routines
* ())
954 ;;; Return whether a primitive partial read operation on STREAM's FD
955 ;;; would (probably) block. Signal a `simple-stream-error' if the
956 ;;; system call implementing this operation fails.
958 ;;; It is "may" instead of "would" because "would" is not quite
959 ;;; correct on win32. However, none of the places that use it require
960 ;;; further assurance than "may" versus "will definitely not".
961 (defun sysread-may-block-p (stream)
963 ;; This answers T at EOF on win32, I think.
964 (not (sb!win32
:fd-listen
(fd-stream-fd stream
)))
966 (not (sb!unix
:unix-simple-poll
(fd-stream-fd stream
) :input
0)))
968 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
969 ;;; then fill the input buffer, and return the number of bytes read. Throws
970 ;;; to EOF-INPUT-CATCHER if the eof was reached.
971 (defun refill-input-buffer (stream)
972 (let ((fd (fd-stream-fd stream
))
979 ;; Check for blocking input before touching the stream if we are to
980 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
981 ;; read(). Regular files should never block, so we can elide the check.
982 (if (and (neq :regular
(fd-stream-fd-type stream
))
983 (sysread-may-block-p stream
))
986 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
987 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
989 (closed-flame stream
)
991 (simple-stream-perror "couldn't read from ~S" stream errno
)
993 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
994 ;; to wait for input if read tells us EWOULDBLOCK.
995 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
)
996 (fd-stream-serve-events stream
))
997 (signal-timeout 'io-timeout
1000 :seconds
(fd-stream-timeout stream
)))
1002 ;; Since the read should not block, we'll disable the
1003 ;; interrupts here, so that we don't accidentally unwind and
1004 ;; leave the stream in an inconsistent state.
1006 ;; Execute the nlx outside without-interrupts to ensure the
1007 ;; resulting thunk is stack-allocatable.
1008 ((lambda (return-reason)
1009 (ecase return-reason
1010 ((nil)) ; fast path normal cases
1011 ((:wait-for-input
) (go #!-win32
:wait-for-input
#!+win32
:main
))
1012 ((:closed-flame
) (go :closed-flame
))
1013 ((:read-error
) (go :read-error
))))
1015 ;; Check the buffer: if it is null, then someone has closed
1016 ;; the stream from underneath us. This is not ment to fix
1017 ;; multithreaded races, but to deal with interrupt handlers
1018 ;; closing the stream.
1021 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
1022 (sap (buffer-sap ibuf
))
1023 (length (buffer-length ibuf
))
1024 (head (buffer-head ibuf
))
1025 (tail (buffer-tail ibuf
)))
1026 (declare (index length head tail
)
1027 (inline sb
!unix
:unix-read
))
1028 (unless (zerop head
)
1029 (cond ((eql head tail
)
1030 ;; Buffer is empty, but not at yet reset -- make it so.
1033 (reset-buffer ibuf
))
1035 ;; Buffer has things in it, but they are not at the
1036 ;; head -- move them there.
1037 (let ((n (- tail head
)))
1038 (system-area-ub8-copy sap head sap
0 n
)
1040 (buffer-head ibuf
) head
1042 (buffer-tail ibuf
) tail
)))))
1043 (setf (fd-stream-listen stream
) nil
)
1044 (setf (values count errno
)
1045 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
1048 #!+win32 sb
!unix
:eintr
1049 #!-win32 sb
!unix
:ewouldblock
)
1050 (return :wait-for-input
)
1051 (return :read-error
)))
1053 (setf (fd-stream-listen stream
) :eof
)
1054 (/show0
"THROWing EOF-INPUT-CATCHER")
1055 (throw 'eof-input-catcher nil
))
1057 ;; Success! (Do not use INCF, for sake of other threads.)
1058 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
1061 ;;; Make sure there are at least BYTES number of bytes in the input
1062 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1063 (defmacro input-at-least
(stream bytes
)
1064 (let ((stream-var (gensym "STREAM"))
1065 (bytes-var (gensym "BYTES"))
1066 (buffer-var (gensym "IBUF")))
1067 `(let* ((,stream-var
,stream
)
1069 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
1071 (when (>= (- (buffer-tail ,buffer-var
)
1072 (buffer-head ,buffer-var
))
1075 (refill-input-buffer ,stream-var
)))))
1077 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
1079 (let ((stream-var (gensym "STREAM"))
1080 (retry-var (gensym "RETRY"))
1081 (element-var (gensym "ELT")))
1082 `(let* ((,stream-var
,stream
)
1083 (ibuf (fd-stream-ibuf ,stream-var
))
1086 (when (fd-stream-eof-forced-p ,stream-var
)
1087 (setf (fd-stream-eof-forced-p ,stream-var
) nil
)
1088 (return-from use-instead
1089 (eof-or-lose ,stream-var
,eof-error
,eof-value
)))
1090 (let ((,element-var nil
)
1091 (decode-break-reason nil
))
1092 (do ((,retry-var t
))
1094 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1095 (let* ((instead (fd-stream-instead ,stream-var
))
1096 (result (vector-pop instead
))
1097 (pointer (fill-pointer instead
)))
1099 (setf (fd-stream-listen ,stream-var
) nil
))
1100 (return-from use-instead result
))
1102 (catch 'eof-input-catcher
1103 (setf decode-break-reason
1104 (block decode-break-reason
1105 (input-at-least ,stream-var
,(if (consp bytes
)
1107 `(setq size
,bytes
)))
1108 (let* ((byte (sap-ref-8 (buffer-sap ibuf
) (buffer-head ibuf
))))
1109 (declare (ignorable byte
))
1110 ,@(when (consp bytes
)
1111 `((let ((sap (buffer-sap ibuf
))
1112 (head (buffer-head ibuf
)))
1113 (declare (ignorable sap head
))
1114 (setq size
,(cadr bytes
))
1115 (input-at-least ,stream-var size
))))
1116 (setq ,element-var
(locally ,@read-forms
))
1117 (setq ,retry-var nil
))
1119 (when decode-break-reason
1120 (when (stream-decoding-error-and-handle
1121 stream decode-break-reason
)
1122 (setq ,retry-var nil
)
1123 (throw 'eof-input-catcher nil
)))
1125 (let ((octet-count (- (buffer-tail ibuf
)
1126 (buffer-head ibuf
))))
1127 (when (or (zerop octet-count
)
1128 (and (not ,element-var
)
1129 (not decode-break-reason
)
1130 (stream-decoding-error-and-handle
1131 stream octet-count
)))
1132 (setq ,retry-var nil
))))))
1134 (incf (buffer-head ibuf
) size
)
1137 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1139 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1140 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
1141 (let ((stream-var (gensym "STREAM"))
1142 (element-var (gensym "ELT")))
1143 `(let* ((,stream-var
,stream
)
1144 (ibuf (fd-stream-ibuf ,stream-var
)))
1145 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1146 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var
)
1148 (catch 'eof-input-catcher
1149 (input-at-least ,stream-var
,bytes
)
1150 (locally ,@read-forms
))))
1152 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1155 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1157 (defmacro def-input-routine
/variable-width
(name
1158 (type external-format size sap head
)
1161 (defun ,name
(stream eof-error eof-value
)
1162 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1163 (let ((,sap
(buffer-sap ibuf
))
1164 (,head
(buffer-head ibuf
)))
1166 (setf *input-routines
*
1167 (nconc *input-routines
*
1168 (list (list ',type
',name
1 ',external-format
))))))
1170 (defmacro def-input-routine
(name
1171 (type size sap head
)
1174 (defun ,name
(stream eof-error eof-value
)
1175 (input-wrapper (stream ,size eof-error eof-value
)
1176 (let ((,sap
(buffer-sap ibuf
))
1177 (,head
(buffer-head ibuf
)))
1179 (setf *input-routines
*
1180 (nconc *input-routines
*
1181 (list (list ',type
',name
',size nil
))))))
1183 ;;; STREAM-IN routine for reading a string char
1184 (def-input-routine input-character
1185 (character 1 sap head
)
1186 (code-char (sap-ref-8 sap head
)))
1188 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1189 (def-input-routine input-unsigned-8bit-byte
1190 ((unsigned-byte 8) 1 sap head
)
1191 (sap-ref-8 sap head
))
1193 ;;; STREAM-IN routine for reading a signed 8 bit number
1194 (def-input-routine input-signed-8bit-number
1195 ((signed-byte 8) 1 sap head
)
1196 (signed-sap-ref-8 sap head
))
1198 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1199 (def-input-routine input-unsigned-16bit-byte
1200 ((unsigned-byte 16) 2 sap head
)
1201 (sap-ref-16 sap head
))
1203 ;;; STREAM-IN routine for reading a signed 16 bit number
1204 (def-input-routine input-signed-16bit-byte
1205 ((signed-byte 16) 2 sap head
)
1206 (signed-sap-ref-16 sap head
))
1208 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1209 (def-input-routine input-unsigned-32bit-byte
1210 ((unsigned-byte 32) 4 sap head
)
1211 (sap-ref-32 sap head
))
1213 ;;; STREAM-IN routine for reading a signed 32 bit number
1214 (def-input-routine input-signed-32bit-byte
1215 ((signed-byte 32) 4 sap head
)
1216 (signed-sap-ref-32 sap head
))
1220 (def-input-routine input-unsigned-64bit-byte
1221 ((unsigned-byte 64) 8 sap head
)
1222 (sap-ref-64 sap head
))
1223 (def-input-routine input-signed-64bit-byte
1224 ((signed-byte 64) 8 sap head
)
1225 (signed-sap-ref-64 sap head
)))
1227 ;;; Find an input routine to use given the type. Return as multiple
1228 ;;; values the routine, the real type transfered, and the number of
1229 ;;; bytes per element (and for character types string input routine).
1230 (defun pick-input-routine (type &optional external-format
)
1231 (when (subtypep type
'character
)
1232 (let ((entry (get-external-format-or-lose external-format
)))
1233 (return-from pick-input-routine
1234 (values (ef-read-char-fun entry
)
1237 (ef-read-n-chars-fun entry
)
1238 (ef-char-size entry
)
1239 (canonize-external-format external-format entry
)))))
1240 (dolist (entry *input-routines
*)
1241 (when (and (subtypep type
(first entry
))
1242 (or (not (fourth entry
))
1243 (eq external-format
(fourth entry
))))
1244 (return-from pick-input-routine
1245 (values (symbol-function (second entry
))
1248 ;; FIXME: let's do it the hard way, then (but ignore things like
1249 ;; endianness, efficiency, and the necessary coupling between these
1250 ;; and the output routines). -- CSR, 2004-02-09
1251 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1252 if
(subtypep type
`(unsigned-byte ,i
))
1253 do
(return-from pick-input-routine
1255 (lambda (stream eof-error eof-value
)
1256 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1257 (let ((sap (buffer-sap ibuf
))
1258 (head (buffer-head ibuf
)))
1259 (loop for j from
0 below
(/ i
8)
1263 (sap-ref-8 sap
(+ head j
))))
1264 finally
(return result
)))))
1267 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1268 if
(subtypep type
`(signed-byte ,i
))
1269 do
(return-from pick-input-routine
1271 (lambda (stream eof-error eof-value
)
1272 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1273 (let ((sap (buffer-sap ibuf
))
1274 (head (buffer-head ibuf
)))
1275 (loop for j from
0 below
(/ i
8)
1279 (sap-ref-8 sap
(+ head j
))))
1280 finally
(return (if (logbitp (1- i
) result
)
1281 (dpb result
(byte i
0) -
1)
1286 ;;; the N-BIN method for FD-STREAMs
1288 ;;; Note that this blocks in UNIX-READ. It is generally used where
1289 ;;; there is a definite amount of reading to be done, so blocking
1290 ;;; isn't too problematical.
1291 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1292 &aux
(total-copied 0))
1293 (declare (type fd-stream stream
))
1294 (declare (type index start requested total-copied
))
1295 (aver (= (length (fd-stream-instead stream
)) 0))
1298 (let* ((remaining-request (- requested total-copied
))
1299 (ibuf (fd-stream-ibuf stream
))
1300 (head (buffer-head ibuf
))
1301 (tail (buffer-tail ibuf
))
1302 (available (- tail head
))
1303 (n-this-copy (min remaining-request available
))
1304 (this-start (+ start total-copied
))
1305 (this-end (+ this-start n-this-copy
))
1306 (sap (buffer-sap ibuf
)))
1307 (declare (type index remaining-request head tail available
))
1308 (declare (type index n-this-copy
))
1309 ;; Copy data from stream buffer into user's buffer.
1310 (%byte-blt sap head buffer this-start this-end
)
1311 (incf (buffer-head ibuf
) n-this-copy
)
1312 (incf total-copied n-this-copy
)
1313 ;; Maybe we need to refill the stream buffer.
1314 (cond (;; If there were enough data in the stream buffer, we're done.
1315 (eql total-copied requested
)
1316 (return total-copied
))
1317 (;; If EOF, we're done in another way.
1318 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1320 (error 'end-of-file
:stream stream
)
1321 (return total-copied
)))
1322 ;; Otherwise we refilled the stream buffer, so fall
1323 ;; through into another pass of the loop.
1326 (defun fd-stream-resync (stream)
1327 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1329 (funcall (ef-resync-fun entry
) stream
))))
1331 (defun get-fd-stream-character-sizer (stream)
1332 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1334 (ef-bytes-for-char-fun entry
))))
1336 (defun fd-stream-character-size (stream char
)
1337 (let ((sizer (get-fd-stream-character-sizer stream
)))
1338 (when sizer
(funcall sizer char
))))
1340 (defun fd-stream-string-size (stream string
)
1341 (let ((sizer (get-fd-stream-character-sizer stream
)))
1343 (loop for char across string summing
(funcall sizer char
)))))
1345 (defun find-external-format (external-format)
1346 (when external-format
1347 (get-external-format external-format
)))
1349 (defun variable-width-external-format-p (ef-entry)
1350 (and ef-entry
(not (null (ef-resync-fun ef-entry
)))))
1352 (defun bytes-for-char-fun (ef-entry)
1353 (if ef-entry
(ef-bytes-for-char-fun ef-entry
) (constantly 1)))
1355 (defmacro define-unibyte-mapping-external-format
1356 (canonical-name (&rest other-names
) &body exceptions
)
1357 (let ((->code-name
(symbolicate canonical-name
'-
>code-mapper
))
1358 (code->-name
(symbolicate 'code-
> canonical-name
'-mapper
))
1359 (get-bytes-name (symbolicate 'get- canonical-name
'-bytes
))
1360 (string->-name
(symbolicate 'string-
> canonical-name
))
1361 (define-string*-name
(symbolicate 'define- canonical-name
'-
>string
*))
1362 (string*-name
(symbolicate canonical-name
'-
>string
*))
1363 (define-string-name (symbolicate 'define- canonical-name
'-
>string
))
1364 (string-name (symbolicate canonical-name
'-
>string
))
1365 (->string-aref-name
(symbolicate canonical-name
'-
>string-aref
)))
1367 (define-unibyte-mapper ,-
>code-name
,code-
>-name
1369 (declaim (inline ,get-bytes-name
))
1370 (defun ,get-bytes-name
(string pos
)
1371 (declare (optimize speed
(safety 0))
1372 (type simple-string string
)
1373 (type array-range pos
))
1374 (get-latin-bytes #',code-
>-name
,canonical-name string pos
))
1375 (defun ,string-
>-name
(string sstart send null-padding
)
1376 (declare (optimize speed
(safety 0))
1377 (type simple-string string
)
1378 (type array-range sstart send
))
1379 (values (string->latin% string sstart send
#',get-bytes-name null-padding
)))
1380 (defmacro ,define-string
*-name
(accessor type
)
1381 (declare (ignore type
))
1382 (let ((name (make-od-name ',string
*-name accessor
)))
1384 (defun ,name
(string sstart send array astart aend
)
1385 (,(make-od-name 'latin-
>string
* accessor
)
1386 string sstart send array astart aend
#',',-
>code-name
)))))
1387 (instantiate-octets-definition ,define-string
*-name
)
1388 (defmacro ,define-string-name
(accessor type
)
1389 (declare (ignore type
))
1390 (let ((name (make-od-name ',string-name accessor
)))
1392 (defun ,name
(array astart aend
)
1393 (,(make-od-name 'latin-
>string accessor
)
1394 array astart aend
#',',-
>code-name
)))))
1395 (instantiate-octets-definition ,define-string-name
)
1396 (define-unibyte-external-format ,canonical-name
,other-names
1397 (let ((octet (,code-
>-name bits
)))
1399 (setf (sap-ref-8 sap tail
) octet
)
1400 (external-format-encoding-error stream bits
)))
1401 (let ((code (,-
>code-name byte
)))
1404 (return-from decode-break-reason
1)))
1408 (defmacro define-unibyte-external-format
1409 (canonical-name (&rest other-names
)
1410 out-form in-form octets-to-string-symbol string-to-octets-symbol
)
1411 `(define-external-format/variable-width
(,canonical-name
,@other-names
)
1416 ,octets-to-string-symbol
1417 ,string-to-octets-symbol
))
1419 (defmacro define-external-format
/variable-width
1420 (external-format output-restart replacement-character
1421 out-size-expr out-expr in-size-expr in-expr
1422 octets-to-string-sym string-to-octets-sym
)
1423 (let* ((name (first external-format
))
1424 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1425 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1426 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1427 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1428 (resync-function (symbolicate "RESYNC/" name
))
1429 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1430 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1431 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1432 (n-buffer (gensym "BUFFER")))
1434 (defun ,size-function
(byte)
1435 (declare (ignorable byte
))
1437 (defun ,out-function
(stream string flush-p start end
)
1438 (let ((start (or start
0))
1439 (end (or end
(length string
))))
1440 (declare (type index start end
))
1441 (synchronize-stream-output stream
)
1442 (unless (<= 0 start end
(length string
))
1443 (sequence-bounding-indices-bad-error string start end
))
1446 (let ((obuf (fd-stream-obuf stream
)))
1447 (string-dispatch (simple-base-string
1448 #!+sb-unicode
(simple-array character
(*))
1451 (let ((len (buffer-length obuf
))
1452 (sap (buffer-sap obuf
))
1454 (tail (buffer-tail obuf
)))
1455 (declare (type index tail
)
1456 ;; STRING bounds have already been checked.
1457 (optimize (safety 0)))
1458 (,@(if output-restart
1459 `(catch 'output-nothing
)
1462 ((or (= start end
) (< (- len tail
) 4)))
1463 (let* ((byte (aref string start
))
1464 (bits (char-code byte
))
1465 (size ,out-size-expr
))
1468 (setf (buffer-tail obuf
) tail
)
1471 ;; Exited via CATCH: skip the current character.
1475 (flush-output-buffer stream
)))
1477 (flush-output-buffer stream
))))
1478 (def-output-routines/variable-width
(,format
1485 (if (eql byte
#\Newline
)
1486 (setf (fd-stream-output-column stream
) 0)
1487 (incf (fd-stream-output-column stream
)))
1488 (let ((bits (char-code byte
))
1489 (sap (buffer-sap obuf
))
1490 (tail (buffer-tail obuf
)))
1492 (defun ,in-function
(stream buffer start requested eof-error-p
1493 &aux
(total-copied 0))
1494 (declare (type fd-stream stream
)
1495 (type index start requested total-copied
)
1497 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1499 (when (fd-stream-eof-forced-p stream
)
1500 (setf (fd-stream-eof-forced-p stream
) nil
)
1501 (return-from ,in-function
0))
1502 (do ((instead (fd-stream-instead stream
)))
1503 ((= (fill-pointer instead
) 0)
1504 (setf (fd-stream-listen stream
) nil
))
1505 (setf (aref buffer
(+ start total-copied
)) (vector-pop instead
))
1507 (when (= requested total-copied
)
1508 (when (= (fill-pointer instead
) 0)
1509 (setf (fd-stream-listen stream
) nil
))
1510 (return-from ,in-function total-copied
)))
1513 (let* ((ibuf (fd-stream-ibuf stream
))
1514 (head (buffer-head ibuf
))
1515 (tail (buffer-tail ibuf
))
1516 (sap (buffer-sap ibuf
))
1517 (decode-break-reason nil
))
1518 (declare (type index head tail
))
1519 ;; Copy data from stream buffer into user's buffer.
1520 (do ((size nil nil
))
1521 ((or (= tail head
) (= requested total-copied
)))
1522 (setf decode-break-reason
1523 (block decode-break-reason
1524 ,@(when (consp in-size-expr
)
1525 `((when (> ,(car in-size-expr
) (- tail head
))
1527 (let ((byte (sap-ref-8 sap head
)))
1528 (declare (ignorable byte
))
1529 (setq size
,(if (consp in-size-expr
) (cadr in-size-expr
) in-size-expr
))
1530 (when (> size
(- tail head
))
1532 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1536 (setf (buffer-head ibuf
) head
)
1537 (when decode-break-reason
1538 ;; If we've already read some characters on when the invalid
1539 ;; code sequence is detected, we return immediately. The
1540 ;; handling of the error is deferred until the next call
1541 ;; (where this check will be false). This allows establishing
1542 ;; high-level handlers for decode errors (for example
1543 ;; automatically resyncing in Lisp comments).
1544 (when (plusp total-copied
)
1545 (return-from ,in-function total-copied
))
1546 (when (stream-decoding-error-and-handle
1547 stream decode-break-reason
)
1549 (error 'end-of-file
:stream stream
)
1550 (return-from ,in-function total-copied
)))
1551 ;; we might have been given stuff to use instead, so
1552 ;; we have to return (and trust our caller to know
1553 ;; what to do about TOTAL-COPIED being 0).
1554 (return-from ,in-function total-copied
)))
1555 (setf (buffer-head ibuf
) head
)
1556 ;; Maybe we need to refill the stream buffer.
1557 (cond ( ;; If was data in the stream buffer, we're done.
1558 (plusp total-copied
)
1559 (return total-copied
))
1560 ( ;; If EOF, we're done in another way.
1561 (or (eq decode-break-reason
'eof
)
1562 (null (catch 'eof-input-catcher
1563 (refill-input-buffer stream
))))
1565 (error 'end-of-file
:stream stream
)
1566 (return total-copied
)))
1567 ;; Otherwise we refilled the stream buffer, so fall
1568 ;; through into another pass of the loop.
1570 (def-input-routine/variable-width
,in-char-function
(character
1574 (let ((byte (sap-ref-8 sap head
)))
1575 (declare (ignorable byte
))
1577 (defun ,resync-function
(stream)
1578 (let ((ibuf (fd-stream-ibuf stream
))
1580 (catch 'eof-input-catcher
1582 (incf (buffer-head ibuf
))
1583 (input-at-least stream
,(if (consp in-size-expr
) (car in-size-expr
) `(setq size
,in-size-expr
)))
1584 (unless (block decode-break-reason
1585 (let* ((sap (buffer-sap ibuf
))
1586 (head (buffer-head ibuf
))
1587 (byte (sap-ref-8 sap head
)))
1588 (declare (ignorable byte
))
1589 ,@(when (consp in-size-expr
)
1590 `((setq size
,(cadr in-size-expr
))
1591 (input-at-least stream size
)))
1592 (setf head
(buffer-head ibuf
))
1596 (defun ,read-c-string-function
(sap element-type
)
1597 (declare (type system-area-pointer sap
))
1599 (declare (optimize (speed 3) (safety 0)))
1600 (let* ((stream ,name
)
1601 (size 0) (head 0) (byte 0) (char nil
)
1602 (decode-break-reason nil
)
1603 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1604 (setf decode-break-reason
1605 (block decode-break-reason
1606 (setf byte
(sap-ref-8 sap head
)
1607 size
,(if (consp in-size-expr
)
1613 (when decode-break-reason
1614 (c-string-decoding-error
1615 ,name sap head decode-break-reason
))
1616 (when (zerop (char-code char
))
1618 (string (make-string length
:element-type element-type
)))
1619 (declare (ignorable stream
)
1620 (type index head length
) ;; size
1621 (type (unsigned-byte 8) byte
)
1622 (type (or null character
) char
)
1623 (type string string
))
1625 (dotimes (index length string
)
1626 (setf decode-break-reason
1627 (block decode-break-reason
1628 (setf byte
(sap-ref-8 sap head
)
1629 size
,(if (consp in-size-expr
)
1635 (when decode-break-reason
1636 (c-string-decoding-error
1637 ,name sap head decode-break-reason
))
1638 (setf (aref string index
) char
)))))
1640 (defun ,output-c-string-function
(string)
1641 (declare (type simple-string string
))
1643 (declare (optimize (speed 3) (safety 0)))
1644 (let* ((length (length string
))
1645 (char-length (make-array (1+ length
) :element-type
'index
))
1647 (+ (loop for i of-type index below length
1648 for byte of-type character
= (aref string i
)
1649 for bits
= (char-code byte
)
1650 sum
(setf (aref char-length i
)
1651 (the index
,out-size-expr
)) of-type index
)
1652 (let* ((byte (code-char 0))
1653 (bits (char-code byte
)))
1654 (declare (ignorable byte bits
))
1655 (setf (aref char-length length
)
1656 (the index
,out-size-expr
)))))
1658 (,n-buffer
(make-array buffer-length
1659 :element-type
'(unsigned-byte 8)))
1661 (declare (type index length buffer-length tail
)
1664 (with-pinned-objects (,n-buffer
)
1665 (let ((sap (vector-sap ,n-buffer
)))
1666 (declare (system-area-pointer sap
))
1667 (loop for i of-type index below length
1668 for byte of-type character
= (aref string i
)
1669 for bits
= (char-code byte
)
1670 for size of-type index
= (aref char-length i
)
1675 (byte (code-char bits
))
1676 (size (aref char-length length
)))
1677 (declare (ignorable bits byte size
))
1681 (let ((entry (%make-external-format
1682 :names
',external-format
1683 :default-replacement-character
,replacement-character
1684 :read-n-chars-fun
#',in-function
1685 :read-char-fun
#',in-char-function
1686 :write-n-bytes-fun
#',out-function
1687 ,@(mapcan #'(lambda (buffering)
1688 (list (intern (format nil
"WRITE-CHAR-~A-BUFFERED-FUN" buffering
) :keyword
)
1689 `#',(intern (format nil format
(string buffering
)))))
1690 '(:none
:line
:full
))
1691 :resync-fun
#',resync-function
1692 :bytes-for-char-fun
#',size-function
1693 :read-c-string-fun
#',read-c-string-function
1694 :write-c-string-fun
#',output-c-string-function
1695 :octets-to-string-fun
(lambda (&rest rest
)
1696 (declare (dynamic-extent rest
))
1697 (apply ',octets-to-string-sym rest
))
1698 :string-to-octets-fun
(lambda (&rest rest
)
1699 (declare (dynamic-extent rest
))
1700 (apply ',string-to-octets-sym rest
)))))
1701 (dolist (ef ',external-format
)
1702 (setf (gethash ef
*external-formats
*) entry
))))))
1704 ;;;; utility functions (misc routines, etc)
1706 ;;; Fill in the various routine slots for the given type. INPUT-P and
1707 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1708 ;;; set prior to calling this routine.
1709 (defun set-fd-stream-routines (fd-stream element-type external-format
1710 input-p output-p buffer-p
)
1711 (let* ((target-type (case element-type
1712 (unsigned-byte '(unsigned-byte 8))
1713 (signed-byte '(signed-byte 8))
1714 (:default
'character
)
1716 (character-stream-p (subtypep target-type
'character
))
1717 (bivalent-stream-p (eq element-type
:default
))
1718 normalized-external-format
1720 (bin-routine #'ill-bin
)
1723 (cin-routine #'ill-in
)
1726 (input-type nil
) ;calculated from bin-type/cin-type
1727 (input-size nil
) ;calculated from bin-size/cin-size
1728 (read-n-characters #'ill-in
)
1729 (bout-routine #'ill-bout
)
1732 (cout-routine #'ill-out
)
1737 (output-bytes #'ill-bout
))
1739 ;; Ensure that we have buffers in the desired direction(s) only,
1740 ;; getting new ones and dropping/resetting old ones as necessary.
1741 (let ((obuf (fd-stream-obuf fd-stream
)))
1745 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1747 (setf (fd-stream-obuf fd-stream
) nil
)
1748 (release-buffer obuf
))))
1750 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1754 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1756 (setf (fd-stream-ibuf fd-stream
) nil
)
1757 (release-buffer ibuf
))))
1759 ;; FIXME: Why only for output? Why unconditionally?
1761 (setf (fd-stream-output-column fd-stream
) 0))
1763 (when (and character-stream-p
(eq external-format
:default
))
1764 (/show0
"/getting default external format")
1765 (setf external-format
(default-external-format)))
1768 (when (or (not character-stream-p
) bivalent-stream-p
)
1769 (setf (values bin-routine bin-type bin-size read-n-characters
1770 char-size normalized-external-format
)
1771 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1775 (error "could not find any input routine for ~S" target-type
)))
1776 (when character-stream-p
1777 (setf (values cin-routine cin-type cin-size read-n-characters
1778 char-size normalized-external-format
)
1779 (pick-input-routine target-type external-format
))
1781 (error "could not find any input routine for ~S" target-type
)))
1782 (setf (fd-stream-in fd-stream
) cin-routine
1783 (fd-stream-bin fd-stream
) bin-routine
)
1784 ;; character type gets preferential treatment
1785 (setf input-size
(or cin-size bin-size
))
1786 (setf input-type
(or cin-type bin-type
))
1787 (when normalized-external-format
1788 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1789 (fd-stream-char-size fd-stream
) char-size
))
1790 (when (= (or cin-size
1) (or bin-size
1) 1)
1791 (setf (fd-stream-n-bin fd-stream
) ;XXX
1792 (if (and character-stream-p
(not bivalent-stream-p
))
1794 #'fd-stream-read-n-bytes
))
1795 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1796 ;; for character and (unsigned-byte 8) streams. In these
1797 ;; cases, fast-read-* will read from the
1798 ;; ansi-stream-(c)in-buffer, saving function calls.
1799 ;; Otherwise, the various data-reading functions in the stream
1800 ;; structure will be called.
1802 (not bivalent-stream-p
)
1803 ;; temporary disable on :io streams
1805 (cond (character-stream-p
1806 (setf (ansi-stream-cin-buffer fd-stream
)
1807 (make-array +ansi-stream-in-buffer-length
+
1808 :element-type
'character
)))
1809 ((equal target-type
'(unsigned-byte 8))
1810 (setf (ansi-stream-in-buffer fd-stream
)
1811 (make-array +ansi-stream-in-buffer-length
+
1812 :element-type
'(unsigned-byte 8))))))))
1815 (when (or (not character-stream-p
) bivalent-stream-p
)
1816 (setf (values bout-routine bout-type bout-size output-bytes
1817 char-size normalized-external-format
)
1818 (let ((buffering (fd-stream-buffering fd-stream
)))
1819 (if bivalent-stream-p
1820 (pick-output-routine '(unsigned-byte 8)
1821 (if (eq :line buffering
)
1825 (pick-output-routine target-type buffering external-format
))))
1826 (unless bout-routine
1827 (error "could not find any output routine for ~S buffered ~S"
1828 (fd-stream-buffering fd-stream
)
1830 (when character-stream-p
1831 (setf (values cout-routine cout-type cout-size output-bytes
1832 char-size normalized-external-format
)
1833 (pick-output-routine target-type
1834 (fd-stream-buffering fd-stream
)
1836 (unless cout-routine
1837 (error "could not find any output routine for ~S buffered ~S"
1838 (fd-stream-buffering fd-stream
)
1840 (when normalized-external-format
1841 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1842 (fd-stream-char-size fd-stream
) char-size
))
1843 (when character-stream-p
1844 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1845 (setf (fd-stream-out fd-stream
) cout-routine
1846 (fd-stream-bout fd-stream
) bout-routine
1847 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1848 #'fd-sout
#'ill-out
))
1849 (setf output-size
(or cout-size bout-size
))
1850 (setf output-type
(or cout-type bout-type
)))
1852 (when (and input-size output-size
1853 (not (eq input-size output-size
)))
1854 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1855 input-type input-size
1856 output-type output-size
))
1857 (setf (fd-stream-element-size fd-stream
)
1858 (or input-size output-size
))
1860 (setf (fd-stream-element-type fd-stream
)
1861 (cond ((equal input-type output-type
)
1867 ((subtypep input-type output-type
)
1869 ((subtypep output-type input-type
)
1872 (error "Input type (~S) and output type (~S) are unrelated?"
1876 ;;; Handles the resource-release aspects of stream closing, and marks
1878 (defun release-fd-stream-resources (fd-stream)
1881 ;; Drop handlers first.
1882 (when (fd-stream-handler fd-stream
)
1883 (remove-fd-handler (fd-stream-handler fd-stream
))
1884 (setf (fd-stream-handler fd-stream
) nil
))
1885 ;; Disable interrupts so that a asynch unwind will not leave
1886 ;; us with a dangling finalizer (that would close the same
1887 ;; --possibly reassigned-- FD again), or a stream with a closed
1888 ;; FD that appears open.
1889 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1890 (set-closed-flame fd-stream
)
1891 (cancel-finalization fd-stream
))
1892 ;; On error unwind from WITHOUT-INTERRUPTS.
1893 (serious-condition (e)
1895 ;; Release all buffers. If this is undone, or interrupted,
1896 ;; we're still safe: buffers have finalizers of their own.
1897 (release-fd-stream-buffers fd-stream
))
1899 ;;; Flushes the current input buffer and any supplied replacements,
1900 ;;; and returns the input buffer, and the amount of of flushed input
1902 (defun flush-input-buffer (stream)
1903 (let ((unread (length (fd-stream-instead stream
))))
1904 (setf (fill-pointer (fd-stream-instead stream
)) 0)
1905 (let ((ibuf (fd-stream-ibuf stream
)))
1907 (let ((head (buffer-head ibuf
))
1908 (tail (buffer-tail ibuf
)))
1909 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1910 (values nil unread
)))))
1912 (defun fd-stream-clear-input (stream)
1913 (flush-input-buffer stream
)
1916 (sb!win32
:fd-clear-input
(fd-stream-fd stream
))
1917 (setf (fd-stream-listen stream
) nil
))
1919 (catch 'eof-input-catcher
1920 (loop until
(sysread-may-block-p stream
)
1922 (refill-input-buffer stream
)
1923 (reset-buffer (fd-stream-ibuf stream
)))
1926 ;;; Handle miscellaneous operations on FD-STREAM.
1927 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
1928 (declare (ignore arg2
))
1931 (labels ((do-listen ()
1932 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1933 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
1934 (fd-stream-listen fd-stream
)
1936 (sb!win32
:fd-listen
(fd-stream-fd fd-stream
))
1938 ;; If the read can block, LISTEN will certainly return NIL.
1939 (if (sysread-may-block-p fd-stream
)
1941 ;; Otherwise select(2) and CL:LISTEN have slightly
1942 ;; different semantics. The former returns that an FD
1943 ;; is readable when a read operation wouldn't block.
1944 ;; That includes EOF. However, LISTEN must return NIL
1946 (progn (catch 'eof-input-catcher
1947 ;; r-b/f too calls select, but it shouldn't
1948 ;; block as long as read can return once w/o
1950 (refill-input-buffer fd-stream
))
1951 ;; At this point either IBUF-HEAD != IBUF-TAIL
1952 ;; and FD-STREAM-LISTEN is NIL, in which case
1953 ;; we should return T, or IBUF-HEAD ==
1954 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1955 ;; which case we should return :EOF for this
1956 ;; call and all future LISTEN call on this stream.
1957 ;; Call ourselves again to determine which case
1962 (decf (buffer-head (fd-stream-ibuf fd-stream
))
1963 (fd-stream-character-size fd-stream arg1
)))
1965 ;; Drop input buffers
1966 (setf (ansi-stream-in-index fd-stream
) +ansi-stream-in-buffer-length
+
1967 (ansi-stream-cin-buffer fd-stream
) nil
1968 (ansi-stream-in-buffer fd-stream
) nil
)
1970 ;; We got us an abort on our hands.
1971 (let ((outputp (fd-stream-obuf fd-stream
))
1972 (file (fd-stream-file fd-stream
))
1973 (orig (fd-stream-original fd-stream
)))
1974 ;; This takes care of the important stuff -- everything
1975 ;; rest is cleaning up the file-system, which we cannot
1976 ;; do on some platforms as long as the file is open.
1977 (release-fd-stream-resources fd-stream
)
1978 ;; We can't do anything unless we know what file were
1979 ;; dealing with, and we don't want to do anything
1980 ;; strange unless we were writing to the file.
1981 (when (and outputp file
)
1983 ;; If the original is EQ to file we are appending to
1984 ;; and can just close the file without renaming.
1985 (unless (eq orig file
)
1986 ;; We have a handle on the original, just revert.
1987 (multiple-value-bind (okay err
)
1988 (sb!unix
:unix-rename orig file
)
1989 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1990 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1993 (error 'simple-stream-error
1995 "~@<Couldn't restore ~S to its original contents ~
1996 from ~S while closing ~S: ~2I~_~A~:>"
1998 (list file orig fd-stream
(strerror err
))
1999 :stream fd-stream
))))
2000 ;; We can't restore the original, and aren't
2001 ;; appending, so nuke that puppy.
2003 ;; FIXME: This is currently the fate of superseded
2004 ;; files, and according to the CLOSE spec this is
2005 ;; wrong. However, there seems to be no clean way to
2006 ;; do that that doesn't involve either copying the
2007 ;; data (bad if the :abort resulted from a full
2008 ;; disk), or renaming the old file temporarily
2009 ;; (probably bad because stream opening becomes more
2011 (multiple-value-bind (okay err
)
2012 (sb!unix
:unix-unlink file
)
2014 (error 'simple-file-error
2017 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2019 (list file fd-stream
(strerror err
)))))))))
2021 (finish-fd-stream-output fd-stream
)
2022 (let ((orig (fd-stream-original fd-stream
)))
2023 (when (and orig
(fd-stream-delete-original fd-stream
))
2024 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2026 (error 'simple-file-error
2029 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2031 (list orig fd-stream
(strerror err
)))))))
2032 ;; In case of no-abort close, don't *really* close the
2033 ;; stream until the last moment -- the cleaning up of the
2034 ;; original can be done first.
2035 (release-fd-stream-resources fd-stream
))))
2037 (fd-stream-clear-input fd-stream
))
2039 (flush-output-buffer fd-stream
))
2041 (finish-fd-stream-output fd-stream
))
2043 (fd-stream-element-type fd-stream
))
2045 (fd-stream-external-format fd-stream
))
2047 (plusp (the (integer 0)
2048 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2052 (fd-stream-output-column fd-stream
))
2054 (unless (fd-stream-file fd-stream
)
2055 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2056 ;; "should signal an error of type TYPE-ERROR if stream is not
2057 ;; a stream associated with a file". Too bad there's no very
2058 ;; appropriate value for the EXPECTED-TYPE slot..
2059 (error 'simple-type-error
2061 :expected-type
'fd-stream
2062 :format-control
"~S is not a stream associated with a file."
2063 :format-arguments
(list fd-stream
)))
2065 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2066 atime mtime ctime blksize blocks
)
2067 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2068 (declare (ignore ino nlink uid gid rdev
2069 atime mtime ctime blksize blocks
))
2071 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2074 (truncate size
(fd-stream-element-size fd-stream
))))
2076 (let* ((handle (fd-stream-fd fd-stream
))
2077 (element-size (fd-stream-element-size fd-stream
)))
2078 (multiple-value-bind (got native-size
)
2079 (sb!win32
:get-file-size-ex handle
0)
2081 ;; Might be a block device, in which case we fall back to
2082 ;; a non-atomic workaround:
2083 (let* ((here (sb!unix
:unix-lseek handle
0 sb
!unix
:l_incr
))
2084 (there (sb!unix
:unix-lseek handle
0 sb
!unix
:l_xtnd
)))
2085 (when (and here there
)
2086 (sb!unix
:unix-lseek handle here sb
!unix
:l_set
)
2087 (truncate there element-size
)))
2088 (truncate native-size element-size
)))))
2089 (:file-string-length
2091 (character (fd-stream-character-size fd-stream arg1
))
2092 (string (fd-stream-string-size fd-stream arg1
))))
2095 (fd-stream-set-file-position fd-stream arg1
)
2096 (fd-stream-get-file-position fd-stream
)))))
2098 ;; FIXME: Think about this.
2100 ;; (defun finish-fd-stream-output (fd-stream)
2101 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2102 ;; (loop while (fd-stream-output-queue fd-stream)
2103 ;; ;; FIXME: SIGINT while waiting for a timeout will
2104 ;; ;; cause a timeout here.
2105 ;; do (when (and (not (serve-event timeout)) timeout)
2106 ;; (signal-timeout 'io-timeout
2107 ;; :stream fd-stream
2108 ;; :direction :write
2109 ;; :seconds timeout)))))
2111 (defun finish-fd-stream-output (stream)
2112 (flush-output-buffer stream
)
2114 ((null (fd-stream-output-queue stream
)))
2115 (aver (fd-stream-serve-events stream
))
2116 (serve-all-events)))
2118 (defun fd-stream-get-file-position (stream)
2119 (declare (fd-stream stream
))
2121 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2122 (declare (type (or (alien sb
!unix
:unix-offset
) null
) posn
))
2123 ;; We used to return NIL for errno==ESPIPE, and signal an error
2124 ;; in other failure cases. However, CLHS says to return NIL if
2125 ;; the position cannot be determined -- so that's what we do.
2126 (when (integerp posn
)
2127 ;; Adjust for buffered output: If there is any output
2128 ;; buffered, the *real* file position will be larger
2129 ;; than reported by lseek() because lseek() obviously
2130 ;; cannot take into account output we have not sent
2132 (dolist (buffer (fd-stream-output-queue stream
))
2133 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2134 (let ((obuf (fd-stream-obuf stream
)))
2136 (incf posn
(buffer-tail obuf
))))
2137 ;; Adjust for unread input: If there is any input
2138 ;; read from UNIX but not supplied to the user of the
2139 ;; stream, the *real* file position will smaller than
2140 ;; reported, because we want to look like the unread
2141 ;; stuff is still available.
2142 (let ((ibuf (fd-stream-ibuf stream
)))
2144 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2145 ;; Divide bytes by element size.
2146 (truncate posn
(fd-stream-element-size stream
))))))
2148 (defun fd-stream-set-file-position (stream position-spec
)
2149 (declare (fd-stream stream
))
2150 (check-type position-spec
2151 (or (alien sb
!unix
:unix-offset
) (member nil
:start
:end
))
2152 "valid file position designator")
2155 ;; Make sure we don't have any output pending, because if we
2156 ;; move the file pointer before writing this stuff, it will be
2157 ;; written in the wrong location.
2158 (finish-fd-stream-output stream
)
2159 ;; Disable interrupts so that interrupt handlers doing output
2162 (unless (fd-stream-output-finished-p stream
)
2163 ;; We got interrupted and more output came our way during
2164 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2165 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2166 ;; so we prefer to do things like this...
2168 ;; Clear out any pending input to force the next read to go to
2170 (flush-input-buffer stream
)
2171 ;; Trash cached value for listen, so that we check next time.
2172 (setf (fd-stream-listen stream
) nil
)
2174 (multiple-value-bind (offset origin
)
2177 (values 0 sb
!unix
:l_set
))
2179 (values 0 sb
!unix
:l_xtnd
))
2181 (values (* position-spec
(fd-stream-element-size stream
))
2183 (declare (type (alien sb
!unix
:unix-offset
) offset
))
2184 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2186 ;; CLHS says to return true if the file-position was set
2187 ;; successfully, and NIL otherwise. We are to signal an error
2188 ;; only if the given position was out of bounds, and that is
2189 ;; dealt with above. In times past we used to return NIL for
2190 ;; errno==ESPIPE, and signal an error in other cases.
2192 ;; FIXME: We are still liable to signal an error if flushing
2194 (return-from fd-stream-set-file-position
2195 (typep posn
'(alien sb
!unix
:unix-offset
))))))))
2198 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2200 ;;; Create a stream for the given Unix file descriptor.
2202 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2203 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2204 ;;; default to allowing input.
2206 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2208 ;;; BUFFERING indicates the kind of buffering to use.
2210 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2211 ;;; NIL (the default), then wait forever. When we time out, we signal
2214 ;;; FILE is the name of the file (will be returned by PATHNAME).
2216 ;;; NAME is used to identify the stream when printed.
2218 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2219 ;;; handle blocking IO on the stream.
2220 (defun make-fd-stream (fd
2224 (output nil output-p
)
2225 (element-type 'base-char
)
2227 (external-format :default
)
2237 (format nil
"file ~A" file
)
2238 (format nil
"descriptor ~W" fd
)))
2240 (declare (type index fd
) (type (or real null
) timeout
)
2241 (type (member :none
:line
:full
) buffering
))
2242 (cond ((not (or input-p output-p
))
2244 ((not (or input output
))
2245 (error "File descriptor must be opened either for input or output.")))
2246 (let* ((constructor (ecase class
2247 (fd-stream '%make-fd-stream
)
2248 (form-tracking-stream '%make-form-tracking-stream
)))
2249 (element-mode (stream-element-type-stream-element-mode element-type
))
2250 (stream (funcall constructor
2253 #!-win32
(sb!unix
:fd-type fd
)
2255 #!+win32
(if serve-events
2261 :delete-original delete-original
2263 :buffering buffering
2264 :dual-channel-p dual-channel-p
2265 :element-mode element-mode
2266 :serve-events serve-events
2269 (coerce timeout
'single-float
)
2271 (set-fd-stream-routines stream element-type external-format
2272 input output input-buffer-p
)
2276 (sb!unix
:unix-close fd
)
2278 (format *terminal-io
* "** closed file descriptor ~W **~%"
2283 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2284 ;;; :RENAME-AND-DELETE and :RENAME options.
2285 (defun pick-backup-name (name)
2286 (declare (type simple-string name
))
2287 (concatenate 'simple-string name
".bak"))
2289 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2290 ;;; access, since we don't want to trash unwritable files even if we
2291 ;;; technically can. We return true if we succeed in renaming.
2292 (defun rename-the-old-one (namestring original
)
2293 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2294 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2295 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2298 (error 'simple-file-error
2299 :pathname namestring
2301 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2302 :format-arguments
(list namestring original
(strerror err
))))))
2304 (defun open (filename
2307 (element-type 'base-char
)
2308 (if-exists nil if-exists-given
)
2309 (if-does-not-exist nil if-does-not-exist-given
)
2310 (external-format :default
)
2311 ;; :class is a private option - use it at your own risk
2313 &aux
; Squelch assignment warning.
2314 (direction direction
)
2315 (if-does-not-exist if-does-not-exist
)
2316 (if-exists if-exists
))
2318 "Return a stream which reads from or writes to FILENAME.
2320 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2321 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2322 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2323 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2324 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2325 See the manual for details."
2327 ;; Calculate useful stuff.
2328 (multiple-value-bind (input output mask
)
2330 (:input
(values t nil sb
!unix
:o_rdonly
))
2331 (:output
(values nil t sb
!unix
:o_wronly
))
2332 (:io
(values t t sb
!unix
:o_rdwr
))
2333 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2334 (declare (type index mask
))
2335 (let* ( ;; PATHNAME is the pathname we associate with the stream.
2336 (pathname (merge-pathnames filename
))
2337 (physical (physicalize-pathname pathname
))
2338 (truename (probe-file physical
))
2339 ;; NAMESTRING is the native namestring we open the file with.
2340 (namestring (cond (truename
2341 (native-namestring truename
:as-file t
))
2343 (and input
(eq if-does-not-exist
:create
))
2344 (and (eq direction
:io
)
2345 (not if-does-not-exist-given
)))
2346 (native-namestring physical
:as-file t
)))))
2347 (flet ((open-error (format-control &rest format-arguments
)
2348 (error 'simple-file-error
2350 :format-control format-control
2351 :format-arguments format-arguments
)))
2352 ;; Process if-exists argument if we are doing any output.
2354 (unless if-exists-given
2356 (if (eq (pathname-version pathname
) :newest
)
2360 ((:new-version
:error nil
)
2361 (setf mask
(logior mask sb
!unix
:o_excl
)))
2362 ((:rename
:rename-and-delete
)
2363 (setf mask
(logior mask sb
!unix
:o_creat
)))
2365 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2367 (setf mask
(logior mask sb
!unix
:o_append
)))))
2369 (setf if-exists
:ignore-this-arg
)))
2371 (unless if-does-not-exist-given
2372 (setf if-does-not-exist
2373 (cond ((eq direction
:input
) :error
)
2375 (member if-exists
'(:overwrite
:append
)))
2377 ((eq direction
:probe
)
2381 (cond ((and if-exists-given
2383 (eq if-exists
:new-version
))
2384 (open-error "OPEN :IF-EXISTS :NEW-VERSION is not supported ~
2385 when a new version must be created."))
2386 ((eq if-does-not-exist
:create
)
2387 (setf mask
(logior mask sb
!unix
:o_creat
)))
2388 ((not (member if-exists
'(:error nil
))))
2389 ;; Both if-does-not-exist and if-exists now imply
2390 ;; that there will be no opening of files, and either
2391 ;; an error would be signalled, or NIL returned
2392 ((and (not if-exists
) (not if-does-not-exist
))
2394 ((and if-exists if-does-not-exist
)
2395 (open-error "OPEN :IF-DOES-NOT-EXIST ~s ~
2396 :IF-EXISTS ~s will always signal an error."
2397 if-does-not-exist if-exists
))
2400 (open-error "File exists ~s." pathname
)
2401 (return-from open
)))
2403 (open-error "File does not exist ~s." pathname
))
2405 (return-from open
)))
2406 (let ((original (case if-exists
2407 ((:rename
:rename-and-delete
)
2408 (pick-backup-name namestring
))
2409 ((:append
:overwrite
)
2410 ;; KLUDGE: Prevent CLOSE from deleting
2411 ;; appending streams when called with :ABORT T
2413 (delete-original (eq if-exists
:rename-and-delete
))
2415 (when (and original
(not (eq original namestring
)))
2416 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2417 ;; whether the file already exists, make sure the original
2418 ;; file is not a directory, and keep the mode.
2421 (multiple-value-bind (okay err
/dev inode orig-mode
)
2422 (sb!unix
:unix-stat namestring
)
2423 (declare (ignore inode
)
2424 (type (or index null
) orig-mode
))
2427 (when (and output
(= (logand orig-mode
#o170000
)
2429 (error 'simple-file-error
2432 "can't open ~S for output: is a directory"
2433 :format-arguments
(list namestring
)))
2434 (setf mode
(logand orig-mode
#o777
))
2436 ((eql err
/dev sb
!unix
:enoent
)
2439 (simple-file-perror "can't find ~S"
2443 (rename-the-old-one namestring original
))
2445 (setf delete-original nil
)
2446 ;; In order to use :SUPERSEDE instead, we have to make
2447 ;; sure SB!UNIX:O_CREAT corresponds to
2448 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2449 ;; because of IF-EXISTS being :RENAME.
2450 (unless (eq if-does-not-exist
:create
)
2452 (logior (logandc2 mask sb
!unix
:o_creat
)
2454 (setf if-exists
:supersede
))))
2456 ;; Now we can try the actual Unix open(2).
2457 (multiple-value-bind (fd errno
)
2459 (sb!unix
:unix-open namestring mask mode
)
2460 (values nil sb
!unix
:enoent
))
2461 (flet ((vanilla-open-error ()
2462 (simple-file-perror "error opening ~S" pathname errno
)))
2465 ((:input
:output
:io
)
2466 ;; For O_APPEND opened files, lseek returns 0 until first write.
2467 ;; So we jump ahead here.
2468 (when (eq if-exists
:append
)
2469 (sb!unix
:unix-lseek fd
0 sb
!unix
:l_xtnd
))
2474 :element-type element-type
2475 :external-format external-format
2478 :delete-original delete-original
2486 (%make-fd-stream
:name namestring
2489 :element-type element-type
)))
2492 ((eql errno sb
!unix
:enoent
)
2493 (case if-does-not-exist
2494 (:error
(vanilla-open-error))
2496 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2499 ((and (eql errno sb
!unix
:eexist
) (null if-exists
))
2502 (vanilla-open-error))))))))))
2506 ;;; the stream connected to the controlling terminal, or NIL if there is none
2509 ;;; the stream connected to the standard input (file descriptor 0)
2512 ;;; the stream connected to the standard output (file descriptor 1)
2515 ;;; the stream connected to the standard error output (file descriptor 2)
2518 ;;; This is called when the cold load is first started up, and may also
2519 ;;; be called in an attempt to recover from nested errors.
2520 (defun stream-cold-init-or-reset ()
2521 ;; FIXME: on gencgc the 4 standard fd-streams {stdin,stdout,stderr,tty}
2522 ;; and these synonym streams are baked into +pseudo-static-generation+.
2523 ;; Is that inadvertent?
2525 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2526 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2527 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2528 (setf *error-output
* (make-synonym-stream '*stderr
*))
2529 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2530 (setf *debug-io
* *query-io
*)
2531 (setf *trace-output
* *standard-output
*)
2534 (defun stream-deinit ()
2535 ;; Unbind to make sure we're not accidently dealing with it
2536 ;; before we're ready (or after we think it's been deinitialized).
2537 (with-available-buffers-lock ()
2538 (without-package-locks
2539 (makunbound '*available-buffers
*))))
2541 (defun stdstream-external-format (fd outputp
)
2542 #!-win32
(declare (ignore fd outputp
))
2543 (let* ((keyword #!+win32
(if (and (/= fd -
1)
2548 (sb!win32
::console-output-codepage
)
2549 (sb!win32
::console-input-codepage
)))
2550 #!-win32
(default-external-format))
2551 (ef (get-external-format keyword
))
2552 (replacement (ef-default-replacement-character ef
)))
2553 `(,keyword
:replacement
,replacement
)))
2555 ;;; This is called whenever a saved core is restarted.
2556 (defun stream-reinit (&optional init-buffers-p
)
2557 (when init-buffers-p
2558 (with-available-buffers-lock ()
2559 (aver (not (boundp '*available-buffers
*)))
2560 (setf *available-buffers
* nil
)))
2561 (with-simple-output-to-string (*error-output
*)
2562 (multiple-value-bind (in out err
)
2563 #!-win32
(values 0 1 2)
2564 #!+win32
(sb!win32
::get-std-handles
)
2566 (nul-stream (name inputp outputp
)
2567 (let* ((nul-name #.
(coerce "NUL" 'simple-base-string
))
2570 ((and inputp outputp
)
2571 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdwr
0))
2573 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdonly
0))
2575 (sb!win32
:unixlike-open nul-name sb
!unix
:o_wronly
0))
2577 ;; Not quite sure what to do in this case.
2585 :element-type
:default
2586 :serve-events inputp
2588 :external-format
(stdstream-external-format nul-handle outputp
))))
2589 (stdio-stream (handle name inputp outputp
)
2593 ;; If no actual handle was present, create a stream to NUL
2594 (nul-stream name inputp outputp
))
2602 :element-type
:default
2603 :serve-events inputp
2604 :external-format
(stdstream-external-format handle outputp
))))))
2605 (setf *stdin
* (stdio-stream in
"standard input" t nil
)
2606 *stdout
* (stdio-stream out
"standard output" nil t
)
2607 *stderr
* (stdio-stream err
"standard error" nil t
))))
2609 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))
2611 ;; FIXME: what is this call to COERCE doing? XC can't dump non-base-strings.
2612 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2613 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2616 (make-fd-stream tty
:name
"the terminal"
2617 :input t
:output t
:buffering
:line
2618 :external-format
(stdstream-external-format
2622 (make-two-way-stream *stdin
* *stdout
*))))
2623 (princ (get-output-stream-string *error-output
*) *stderr
*))
2628 ;;; the Unix way to beep
2629 (defun beep (stream)
2630 (write-char (code-char bell-char-code
) stream
)
2631 (finish-output stream
))
2633 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2634 ;;; by the filesys stuff to get and set the file name.
2636 ;;; FIXME: misleading name, screwy interface
2637 (defun file-name (stream &optional new-name
)
2638 (when (typep stream
'fd-stream
)
2640 (setf (fd-stream-pathname stream
) new-name
)
2641 (setf (fd-stream-file stream
)
2642 (native-namestring (physicalize-pathname new-name
)
2646 (fd-stream-pathname stream
)))))
2648 ;; Fix the INPUT-CHAR-POS slot of STREAM after having consumed characters
2649 ;; from the CIN-BUFFER. This operation is done upon exit from a FAST-READ-CHAR
2650 ;; loop, and for each buffer refill inside the loop.
2651 (defun update-input-char-pos (stream &optional
(end +ansi-stream-in-buffer-length
+))
2652 (do ((chars (ansi-stream-cin-buffer stream
))
2653 (pos (form-tracking-stream-input-char-pos stream
))
2654 (i (ansi-stream-in-index stream
) (1+ i
)))
2656 (setf (form-tracking-stream-input-char-pos stream
) pos
))
2657 (let ((char (aref chars i
)))
2658 (when (and (eql char
#\Newline
)
2659 ;; record it only if it wasn't unread and re-read
2660 (> pos
(form-tracking-stream-last-newline stream
)))
2661 (vector-push-extend pos
(form-tracking-stream-newlines stream
))
2662 (setf (form-tracking-stream-last-newline stream
) pos
))
2665 (defun tracking-stream-misc (stream operation
&optional arg1 arg2
)
2666 ;; The :UNREAD operation will never be invoked because STREAM has a buffer,
2667 ;; so unreading is implemented entirely within ANSI-STREAM-UNREAD-CHAR.
2668 ;; But we do need to prevent attempts to change the absolute position.
2672 (error 'simple-stream-error
2673 :format-control
"~S is not positionable"
2674 :format-arguments
(list stream
))
2675 (fd-stream-get-file-position stream
)))
2676 (t ; call next method
2677 (fd-stream-misc-routine stream operation arg1 arg2
))))
2679 ;; Using (get-std-handle-or-null +std-error-handle+) instead of the file
2680 ;; descriptor might make this work on win32, but I don't know.
2682 (macrolet ((stderr () 2))
2683 (!defglobal
*!cold-stderr-buf
* " ")
2684 (defun !make-cold-stderr-stream
()
2686 :out
(lambda (stream ch
)
2687 (declare (ignore stream
))
2688 (let ((b (truly-the (simple-base-string 1) *!cold-stderr-buf
*)))
2689 (setf (char b
0) ch
)
2690 (sb!unix
:unix-write
(stderr) b
0 1)))
2691 :sout
(lambda (stream string start end
)
2692 (declare (ignore stream
))
2693 (flet ((out (s start len
)
2694 (sb!unix
:unix-write
(stderr) s start len
)))
2695 (if (typep string
'simple-base-string
)
2696 (out string start
(- end start
))
2697 (let ((n (- end start
)))
2698 ;; will croak if there is any non-BASE-CHAR in the string
2699 (out (replace (make-array n
:element-type
'base-char
)
2700 string
:start2 start
) 0 n
)))))
2701 :misc
(constantly nil
))))