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 (defstruct (fd-stream
108 (:constructor %make-fd-stream
)
109 (:conc-name fd-stream-
)
110 (:predicate fd-stream-p
)
111 (:include ansi-stream
112 (misc #'fd-stream-misc-routine
))
115 ;; the name of this stream
117 ;; the file this stream is for
119 ;; the backup file namestring for the old file, for :IF-EXISTS
120 ;; :RENAME or :RENAME-AND-DELETE.
121 (original nil
:type
(or simple-string null
))
122 (delete-original nil
) ; for :if-exists :rename-and-delete
123 ;;; the number of bytes per element
124 (element-size 1 :type index
)
125 ;; the type of element being transfered
126 (element-type 'base-char
)
127 ;; the Unix file descriptor
128 (fd -
1 :type
#!-win32 fixnum
#!+win32 sb
!vm
:signed-word
)
129 ;; What do we know about the FD?
130 (fd-type :unknown
:type keyword
)
131 ;; controls when the output buffer is flushed
132 (buffering :full
:type
(member :full
:line
:none
))
133 ;; controls whether the input buffer must be cleared before output
134 ;; (must be done for files, not for sockets, pipes and other data
135 ;; sources where input and output aren't related). non-NIL means
136 ;; don't clear input buffer.
138 ;; character position if known -- this may run into bignums, but
139 ;; we probably should flip it into null then for efficiency's sake...
140 (output-column nil
:type
(or unsigned-byte null
))
141 ;; T if input is waiting on FD. :EOF if we hit EOF.
142 (listen nil
:type
(member nil t
:eof
))
143 ;; T if serve-event is allowed when this stream blocks
144 (serve-events nil
:type boolean
)
147 (instead (make-array 0 :element-type
'character
:adjustable t
:fill-pointer t
) :type
(array character
(*)))
148 (ibuf nil
:type
(or buffer null
))
149 (eof-forced-p nil
:type
(member t nil
))
152 (obuf nil
:type
(or buffer null
))
154 ;; output flushed, but not written due to non-blocking io?
157 ;; timeout specified for this stream as seconds or NIL if none
158 (timeout nil
:type
(or single-float null
))
159 ;; pathname of the file this stream is opened to (returned by PATHNAME)
160 (pathname nil
:type
(or pathname null
))
161 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
162 (external-format :latin-1
)
163 ;; fixed width, or function to call with a character
164 (char-size 1 :type
(or fixnum function
))
165 (output-bytes #'ill-out
:type function
)
166 ;; a boolean indicating whether the stream is bivalent. For
167 ;; internal use only.
168 (bivalent-p nil
:type boolean
))
169 (def!method print-object
((fd-stream fd-stream
) stream
)
170 (declare (type stream stream
))
171 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
172 (format stream
"for ~S" (fd-stream-name fd-stream
))))
174 ;;; This is a separate buffer management function, as it wants to be
175 ;;; clever about locking -- grabbing the lock just once.
176 (defun release-fd-stream-buffers (fd-stream)
177 (let ((ibuf (fd-stream-ibuf fd-stream
))
178 (obuf (fd-stream-obuf fd-stream
))
179 (queue (loop for item in
(fd-stream-output-queue fd-stream
)
181 collect
(reset-buffer item
))))
183 (push (reset-buffer ibuf
) queue
))
185 (push (reset-buffer obuf
) queue
))
186 ;; ...so, anything found?
188 ;; detach from stream
189 (setf (fd-stream-ibuf fd-stream
) nil
190 (fd-stream-obuf fd-stream
) nil
191 (fd-stream-output-queue fd-stream
) nil
)
192 ;; splice to *available-buffers*
193 (with-available-buffers-lock ()
194 (setf *available-buffers
* (nconc queue
*available-buffers
*))))))
196 ;;;; FORM-TRACKING-STREAM
198 ;; The compiler uses this to record for each input subform the start and
199 ;; end positions as character offsets. Measuring in characters rather than
200 ;; bytes is both better suited to the task - in that it is consistent with
201 ;; reporting of "point" by Emacs - and faster than querying FILE-POSITION.
202 ;; The slowness of FILE-POSITION on an FD-STREAM is due to making a system
203 ;; call every time, to ensure that the case of an append-only stream works
204 ;; correctly (where the OS forces all writes to the end), and other factors.
206 (defstruct (form-tracking-stream
207 (:constructor %make-form-tracking-stream
)
209 (misc #'tracking-stream-misc
)
212 ;; a function which is called for events on this stream.
213 (observer (lambda (x y z
) (declare (ignore x y z
))) :type function
)
214 ;; A vector of the character position of each #\Newline seen
215 (newlines (make-array 10 :fill-pointer
0 :adjustable t
))
216 (last-newline -
1 :type index-or-minus-1
)
217 ;; Better than reporting that a reader error occurred at a position
218 ;; before any whitespace (or equivalently, a macro producing no value),
219 ;; we can note the position at the first "good" character.
220 (form-start-byte-pos)
221 (form-start-char-pos))
223 (defun line/col-from-charpos
224 (stream &optional
(charpos (ansi-stream-input-char-pos stream
)))
225 (let* ((newlines (form-tracking-stream-newlines stream
))
226 (index (position charpos newlines
:test
#'>= :from-end t
)))
227 ;; Line numbers traditionally begin at 1, columns at 0.
229 ;; INDEX is 1 less than the number of newlines seen
230 ;; up to and including this startpos.
231 ;; e.g. index=0 => 1 newline seen => line=2
233 ;; 1 char after the newline = column 0
234 (- charpos
(aref newlines index
) 1))
235 ;; zero newlines were seen
238 ;;;; CORE OUTPUT FUNCTIONS
240 ;;; Buffer the section of THING delimited by START and END by copying
241 ;;; to output buffer(s) of stream.
242 (defun buffer-output (stream thing start end
)
243 (declare (index start end
))
245 (error ":END before :START!"))
247 ;; Copy bytes from THING to buffers.
248 (flet ((copy-to-buffer (buffer tail count
)
249 (declare (buffer buffer
) (index tail count
))
251 (let ((sap (buffer-sap buffer
)))
254 (system-area-ub8-copy thing start sap tail count
))
255 ((simple-unboxed-array (*))
256 (copy-ub8-to-system-area thing start sap tail count
))))
257 ;; Not INCF! If another thread has moved tail from under
258 ;; us, we don't want to accidentally increment tail
259 ;; beyond buffer-length.
260 (setf (buffer-tail buffer
) (+ count tail
))
263 ;; First copy is special: the buffer may already contain
264 ;; something, or be even full.
265 (let* ((obuf (fd-stream-obuf stream
))
266 (tail (buffer-tail obuf
))
267 (space (- (buffer-length obuf
) tail
)))
269 (copy-to-buffer obuf tail
(min space
(- end start
)))
270 (go :more-output-p
)))
272 ;; Later copies should always have an empty buffer, since
273 ;; they are freshly flushed, but if another thread is
274 ;; stomping on the same buffer that might not be the case.
275 (let* ((obuf (flush-output-buffer stream
))
276 (tail (buffer-tail obuf
))
277 (space (- (buffer-length obuf
) tail
)))
278 (copy-to-buffer obuf tail
(min space
(- end start
))))
281 (go :flush-and-fill
))))))
283 ;;; Flush the current output buffer of the stream, ensuring that the
284 ;;; new buffer is empty. Returns (for convenience) the new output
285 ;;; buffer -- which may or may not be EQ to the old one. If the is no
286 ;;; queued output we try to write the buffer immediately -- otherwise
287 ;;; we queue it for later.
288 (defun flush-output-buffer (stream)
289 (let ((obuf (fd-stream-obuf stream
)))
291 (let ((head (buffer-head obuf
))
292 (tail (buffer-tail obuf
)))
293 (cond ((eql head tail
)
294 ;; Buffer is already empty -- just ensure that is is
295 ;; set to zero as well.
297 ((fd-stream-output-queue stream
)
298 ;; There is already stuff on the queue -- go directly
301 (%queue-and-replace-output-buffer stream
))
303 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
304 ;; whatever is left over. Otherwise wait until we can write.
306 (synchronize-stream-output stream
)
308 (let ((length (- tail head
)))
309 (multiple-value-bind (count errno
)
310 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
312 (flet ((queue-or-wait ()
313 (if (fd-stream-serve-events stream
)
314 (return (%queue-and-replace-output-buffer stream
))
315 (or (wait-until-fd-usable (fd-stream-fd stream
) :output
316 (fd-stream-timeout stream
)
318 (signal-timeout 'io-timeout
321 :seconds
(fd-stream-timeout stream
))))))
322 (cond ((eql count length
)
323 ;; Complete write -- we can use the same buffer.
324 (return (reset-buffer obuf
)))
326 ;; Partial write -- update buffer status and
329 (setf (buffer-head obuf
) head
)
332 ((eql errno sb
!unix
:ewouldblock
)
333 ;; Blocking, queue or wair.
335 ;; if interrupted on win32, just try again
336 #!+win32
((eql errno sb
!unix
:eintr
))
338 (simple-stream-perror "Couldn't write to ~s"
339 stream errno
)))))))))))))
341 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
342 (defun %queue-and-replace-output-buffer
(stream)
343 (aver (fd-stream-serve-events stream
))
344 (let ((queue (fd-stream-output-queue stream
))
345 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
347 ;; Important: before putting the buffer on queue, give the stream
348 ;; a new one. If we get an interrupt and unwind losing the buffer
349 ;; is relatively OK, but having the same buffer in two places
351 (setf (fd-stream-obuf stream
) new
)
355 (setf (fd-stream-output-queue stream
) later
)))
356 (unless (fd-stream-handler stream
)
357 (setf (fd-stream-handler stream
)
358 (add-fd-handler (fd-stream-fd stream
)
361 (declare (ignore fd
))
362 (write-output-from-queue stream
)))))
365 ;;; This is called by the FD-HANDLER for the stream when output is
367 (defun write-output-from-queue (stream)
368 (aver (fd-stream-serve-events stream
))
369 (synchronize-stream-output stream
)
373 (let* ((buffer (pop (fd-stream-output-queue stream
)))
374 (head (buffer-head buffer
))
375 (length (- (buffer-tail buffer
) head
)))
376 (declare (index head length
))
378 (multiple-value-bind (count errno
)
379 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
381 (cond ((eql count length
)
382 ;; Complete write, see if we can do another right
383 ;; away, or remove the handler if we're done.
384 (release-buffer buffer
)
385 (cond ((fd-stream-output-queue stream
)
389 (let ((handler (fd-stream-handler stream
)))
391 (setf (fd-stream-handler stream
) nil
)
392 (remove-fd-handler handler
)))))
394 ;; Partial write. Update buffer status and requeue.
395 (aver (< count length
))
396 ;; Do not use INCF! Another thread might have moved head.
397 (setf (buffer-head buffer
) (+ head count
))
398 (push buffer
(fd-stream-output-queue stream
)))
400 ;; We tried to do multiple writes, and finally our
401 ;; luck ran out. Requeue.
402 (push buffer
(fd-stream-output-queue stream
)))
404 ;; Could not write on the first try at all!
406 (simple-stream-perror "Couldn't write to ~S." stream errno
)
408 (if (= errno sb
!unix
:ewouldblock
)
409 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
410 (simple-stream-perror "Couldn't write to ~S"
414 ;;; Try to write THING directly to STREAM without buffering, if
415 ;;; possible. If direct write doesn't happen, buffer.
416 (defun write-or-buffer-output (stream thing start end
)
417 (declare (index start end
))
418 (cond ((fd-stream-output-queue stream
)
419 (buffer-output stream thing start end
))
421 (error ":END before :START!"))
423 (let ((length (- end start
)))
424 (synchronize-stream-output stream
)
425 (multiple-value-bind (count errno
)
426 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
427 (cond ((eql count length
)
428 ;; Complete write -- done!
431 (aver (< count length
))
432 ;; Partial write -- buffer the rest.
433 (buffer-output stream thing
(+ start count
) end
))
435 ;; Could not write -- buffer or error.
437 (simple-stream-perror "couldn't write to ~s" stream errno
)
439 (if (= errno sb
!unix
:ewouldblock
)
440 (buffer-output stream thing start end
)
441 (simple-stream-perror "couldn't write to ~s" stream errno
)))))))))
443 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
444 ;;; this is not something we want to export. Nikodemus thinks the
445 ;;; right thing is to support a low-level non-stream like IO layer,
446 ;;; akin to java.nio.
447 (declaim (inline output-raw-bytes
))
448 (define-deprecated-function :late
"1.0.8.16" output-raw-bytes write-sequence
449 (stream thing
&optional start end
)
450 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
452 ;;;; output routines and related noise
454 (defvar *output-routines
* ()
456 "List of all available output routines. Each element is a list of the
457 element-type output, the kind of buffering, the function name, and the number
458 of bytes per element.")
460 ;;; common idioms for reporting low-level stream and file problems
461 (defun simple-stream-perror (note-format stream errno
)
462 (error 'simple-stream-error
464 :format-control
"~@<~?: ~2I~_~A~:>"
465 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
466 (defun simple-file-perror (note-format pathname errno
)
467 (error 'simple-file-error
469 :format-control
"~@<~?: ~2I~_~A~:>"
471 (list note-format
(list pathname
) (strerror errno
))))
473 (defun c-string-encoding-error (external-format code
)
474 (error 'c-string-encoding-error
475 :external-format external-format
477 (defun c-string-decoding-error (external-format sap offset count
)
478 (error 'c-string-decoding-error
479 :external-format external-format
480 :octets
(sap-ref-octets sap offset count
)))
482 ;;; Returning true goes into end of file handling, false will enter another
483 ;;; round of input buffer filling followed by re-entering character decode.
484 (defun stream-decoding-error-and-handle (stream octet-count
)
486 (error 'stream-decoding-error
487 :external-format
(stream-external-format stream
)
489 :octets
(let ((buffer (fd-stream-ibuf stream
)))
490 (sap-ref-octets (buffer-sap buffer
)
494 :report
(lambda (stream)
496 "~@<Attempt to resync the stream at a ~
497 character boundary and continue.~@:>"))
498 (fd-stream-resync stream
)
500 (force-end-of-file ()
501 :report
(lambda (stream)
502 (format stream
"~@<Force an end of file.~@:>"))
503 (setf (fd-stream-eof-forced-p stream
) t
))
504 (input-replacement (string)
505 :report
(lambda (stream)
506 (format stream
"~@<Use string as replacement input, ~
507 attempt to resync at a character ~
508 boundary and continue.~@:>"))
509 :interactive
(lambda ()
510 (format *query-io
* "~@<Enter a string: ~@:>")
511 (finish-output *query-io
*)
512 (list (read *query-io
*)))
513 (let ((string (reverse (string string
)))
514 (instead (fd-stream-instead stream
)))
515 (dotimes (i (length string
))
516 (vector-push-extend (char string i
) instead
))
517 (fd-stream-resync stream
)
518 (when (> (length string
) 0)
519 (setf (fd-stream-listen stream
) t
)))
522 (defun stream-encoding-error-and-handle (stream code
)
524 (error 'stream-encoding-error
525 :external-format
(stream-external-format stream
)
529 :report
(lambda (stream)
530 (format stream
"~@<Skip output of this character.~@:>"))
531 (throw 'output-nothing nil
))
532 (output-replacement (string)
533 :report
(lambda (stream)
534 (format stream
"~@<Output replacement string.~@:>"))
535 :interactive
(lambda ()
536 (format *query-io
* "~@<Enter a string: ~@:>")
537 (finish-output *query-io
*)
538 (list (read *query-io
*)))
539 (let ((string (string string
)))
540 (fd-sout stream
(string string
) 0 (length string
)))
541 (throw 'output-nothing nil
))))
543 (defun external-format-encoding-error (stream code
)
545 (stream-encoding-error-and-handle stream code
)
546 (c-string-encoding-error stream code
)))
548 (defun synchronize-stream-output (stream)
549 ;; If we're reading and writing on the same file, flush buffered
550 ;; input and rewind file position accordingly.
551 (unless (fd-stream-dual-channel-p stream
)
552 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
553 (unless (eql 0 adjust
)
554 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
556 (defun fd-stream-output-finished-p (stream)
557 (let ((obuf (fd-stream-obuf stream
)))
559 (and (zerop (buffer-tail obuf
))
560 (not (fd-stream-output-queue stream
))))))
562 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
564 (let ((stream-var (gensym "STREAM")))
565 `(let* ((,stream-var
,stream
)
566 (obuf (fd-stream-obuf ,stream-var
))
567 (tail (buffer-tail obuf
))
569 ,(unless (eq (car buffering
) :none
)
570 `(when (< (buffer-length obuf
) (+ tail size
))
571 (setf obuf
(flush-output-buffer ,stream-var
)
572 tail
(buffer-tail obuf
))))
573 ,(unless (eq (car buffering
) :none
)
574 ;; FIXME: Why this here? Doesn't seem necessary.
575 `(synchronize-stream-output ,stream-var
))
577 `(catch 'output-nothing
579 (setf (buffer-tail obuf
) (+ tail size
)))
582 (setf (buffer-tail obuf
) (+ tail size
))))
583 ,(ecase (car buffering
)
585 `(flush-output-buffer ,stream-var
))
587 `(when (eql byte
#\Newline
)
588 (flush-output-buffer ,stream-var
)))
592 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
593 (let ((stream-var (gensym "STREAM")))
594 `(let* ((,stream-var
,stream
)
595 (obuf (fd-stream-obuf ,stream-var
))
596 (tail (buffer-tail obuf
)))
597 ,(unless (eq (car buffering
) :none
)
598 `(when (< (buffer-length obuf
) (+ tail
,size
))
599 (setf obuf
(flush-output-buffer ,stream-var
)
600 tail
(buffer-tail obuf
))))
601 ;; FIXME: Why this here? Doesn't seem necessary.
602 ,(unless (eq (car buffering
) :none
)
603 `(synchronize-stream-output ,stream-var
))
605 `(catch 'output-nothing
607 (setf (buffer-tail obuf
) (+ tail
,size
)))
610 (setf (buffer-tail obuf
) (+ tail
,size
))))
611 ,(ecase (car buffering
)
613 `(flush-output-buffer ,stream-var
))
615 `(when (eql byte
#\Newline
)
616 (flush-output-buffer ,stream-var
)))
620 (defmacro def-output-routines
/variable-width
621 ((name-fmt size restart external-format
&rest bufferings
)
623 (declare (optimize (speed 1)))
628 (intern (format nil name-fmt
(string (car buffering
))))))
630 (defun ,function
(stream byte
)
631 (declare (ignorable byte
))
632 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
634 (setf *output-routines
*
635 (nconc *output-routines
*
643 (cdr buffering
)))))))
646 ;;; Define output routines that output numbers SIZE bytes long for the
647 ;;; given bufferings. Use BODY to do the actual output.
648 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
650 (declare (optimize (speed 1)))
655 (intern (format nil name-fmt
(string (car buffering
))))))
657 (defun ,function
(stream byte
)
658 (output-wrapper (stream ,size
,buffering
,restart
)
660 (setf *output-routines
*
661 (nconc *output-routines
*
669 (cdr buffering
)))))))
672 ;;; FIXME: is this used anywhere any more?
673 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
679 (if (eql byte
#\Newline
)
680 (setf (fd-stream-output-column stream
) 0)
681 (incf (fd-stream-output-column stream
)))
682 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
685 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
688 (:none
(unsigned-byte 8))
689 (:full
(unsigned-byte 8)))
690 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
693 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
696 (:none
(signed-byte 8))
697 (:full
(signed-byte 8)))
698 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
701 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
704 (:none
(unsigned-byte 16))
705 (:full
(unsigned-byte 16)))
706 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
709 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
712 (:none
(signed-byte 16))
713 (:full
(signed-byte 16)))
714 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
717 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
720 (:none
(unsigned-byte 32))
721 (:full
(unsigned-byte 32)))
722 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
725 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
728 (:none
(signed-byte 32))
729 (:full
(signed-byte 32)))
730 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
733 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
735 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
738 (:none
(unsigned-byte 64))
739 (:full
(unsigned-byte 64)))
740 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
742 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
745 (:none
(signed-byte 64))
746 (:full
(signed-byte 64)))
747 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
750 ;;; the routine to use to output a string. If the stream is
751 ;;; unbuffered, slam the string down the file descriptor, otherwise
752 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
753 ;;; checking to see where the last newline was.
754 (defun fd-sout (stream thing start end
)
755 (declare (type fd-stream stream
) (type string thing
))
756 (let ((start (or start
0))
757 (end (or end
(length (the vector thing
)))))
758 (declare (fixnum start end
))
760 (string-dispatch (simple-base-string
762 (simple-array character
(*))
765 (position #\newline thing
:from-end t
766 :start start
:end end
))))
767 (if (and (typep thing
'base-string
)
768 (eq (fd-stream-external-format-keyword stream
) :latin-1
))
769 (ecase (fd-stream-buffering stream
)
771 (buffer-output stream thing start end
))
773 (buffer-output stream thing start end
)
775 (flush-output-buffer stream
)))
777 (write-or-buffer-output stream thing start end
)))
778 (ecase (fd-stream-buffering stream
)
779 (:full
(funcall (fd-stream-output-bytes stream
)
780 stream thing nil start end
))
781 (:line
(funcall (fd-stream-output-bytes stream
)
782 stream thing last-newline start end
))
783 (:none
(funcall (fd-stream-output-bytes stream
)
784 stream thing t start end
))))
786 (setf (fd-stream-output-column stream
) (- end last-newline
1))
787 (incf (fd-stream-output-column stream
) (- end start
))))))
789 (defstruct (external-format
790 (:constructor %make-external-format
)
792 (:predicate external-format-p
)
793 (:copier %copy-external-format
))
794 ;; All the names that can refer to this external format. The first
795 ;; one is the canonical name.
796 (names (missing-arg) :type list
:read-only t
)
797 (default-replacement-character (missing-arg) :type character
)
798 (read-n-chars-fun (missing-arg) :type function
)
799 (read-char-fun (missing-arg) :type function
)
800 (write-n-bytes-fun (missing-arg) :type function
)
801 (write-char-none-buffered-fun (missing-arg) :type function
)
802 (write-char-line-buffered-fun (missing-arg) :type function
)
803 (write-char-full-buffered-fun (missing-arg) :type function
)
804 ;; Can be nil for fixed-width formats.
805 (resync-fun nil
:type
(or function null
))
806 (bytes-for-char-fun (missing-arg) :type function
)
807 (read-c-string-fun (missing-arg) :type function
)
808 (write-c-string-fun (missing-arg) :type function
)
809 ;; We indirect through symbols in these functions so that a
810 ;; developer working on the octets code can easily redefine things
811 ;; and use the new function definition without redefining the
812 ;; external format as well. The slots above don't do any
813 ;; indirection because a developer working with those slots would be
814 ;; redefining the external format anyway.
815 (octets-to-string-fun (missing-arg) :type function
)
816 (string-to-octets-fun (missing-arg) :type function
))
818 (defun ef-char-size (ef-entry)
819 (if (variable-width-external-format-p ef-entry
)
820 (bytes-for-char-fun ef-entry
)
821 (funcall (bytes-for-char-fun ef-entry
) #\x
)))
823 (defun wrap-external-format-functions (external-format fun
)
824 (let ((result (%copy-external-format external-format
)))
825 (macrolet ((frob (accessor)
826 `(setf (,accessor result
) (funcall fun
(,accessor result
)))))
827 (frob ef-read-n-chars-fun
)
828 (frob ef-read-char-fun
)
829 (frob ef-write-n-bytes-fun
)
830 (frob ef-write-char-none-buffered-fun
)
831 (frob ef-write-char-line-buffered-fun
)
832 (frob ef-write-char-full-buffered-fun
)
834 (frob ef-bytes-for-char-fun
)
835 (frob ef-read-c-string-fun
)
836 (frob ef-write-c-string-fun
)
837 (frob ef-octets-to-string-fun
)
838 (frob ef-string-to-octets-fun
))
841 (defvar *external-formats
* (make-hash-table)
843 "Hashtable of all available external formats. The table maps from
844 external-format names to EXTERNAL-FORMAT structures.")
846 (defun get-external-format (external-format)
847 (flet ((keyword-external-format (keyword)
848 (declare (type keyword keyword
))
849 (gethash keyword
*external-formats
*))
850 (replacement-handlerify (entry replacement
)
852 (wrap-external-format-functions
857 (declare (dynamic-extent rest
))
859 ((stream-decoding-error
862 (invoke-restart 'input-replacement replacement
)))
863 (stream-encoding-error
866 (invoke-restart 'output-replacement replacement
)))
867 (octets-encoding-error
868 (lambda (c) (use-value replacement c
)))
869 (octet-decoding-error
870 (lambda (c) (use-value replacement c
))))
871 (apply fun rest
)))))))))
872 (typecase external-format
873 (keyword (keyword-external-format external-format
))
875 (let ((entry (keyword-external-format (car external-format
)))
876 (replacement (getf (cdr external-format
) :replacement
)))
878 (replacement-handlerify entry replacement
)
881 (defun get-external-format-or-lose (external-format)
882 (or (get-external-format external-format
)
883 (error "Undefined external-format: ~S" external-format
)))
885 (defun external-format-keyword (external-format)
886 (typecase external-format
887 (keyword external-format
)
888 ((cons keyword
) (car external-format
))))
890 (defun fd-stream-external-format-keyword (stream)
891 (external-format-keyword (fd-stream-external-format stream
)))
893 (defun canonize-external-format (external-format entry
)
894 (typecase external-format
895 (keyword (first (ef-names entry
)))
896 ((cons keyword
) (cons (first (ef-names entry
)) (rest external-format
)))))
898 ;;; Find an output routine to use given the type and buffering. Return
899 ;;; as multiple values the routine, the real type transfered, and the
900 ;;; number of bytes per element.
901 (defun pick-output-routine (type buffering
&optional external-format
)
902 (when (subtypep type
'character
)
903 (let ((entry (get-external-format-or-lose external-format
)))
904 (return-from pick-output-routine
905 (values (ecase buffering
906 (:none
(ef-write-char-none-buffered-fun entry
))
907 (:line
(ef-write-char-line-buffered-fun entry
))
908 (:full
(ef-write-char-full-buffered-fun entry
)))
911 (ef-write-n-bytes-fun entry
)
913 (canonize-external-format external-format entry
)))))
914 (dolist (entry *output-routines
*)
915 (when (and (subtypep type
(first entry
))
916 (eq buffering
(second entry
))
917 (or (not (fifth entry
))
918 (eq external-format
(fifth entry
))))
919 (return-from pick-output-routine
920 (values (symbol-function (third entry
))
923 ;; KLUDGE: dealing with the buffering here leads to excessive code
926 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
927 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
928 if
(subtypep type
`(unsigned-byte ,i
))
929 do
(return-from pick-output-routine
933 (lambda (stream byte
)
934 (output-wrapper (stream (/ i
8) (:none
) nil
)
935 (loop for j from
0 below
(/ i
8)
936 do
(setf (sap-ref-8 (buffer-sap obuf
)
938 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
940 (lambda (stream byte
)
941 (output-wrapper (stream (/ i
8) (:full
) nil
)
942 (loop for j from
0 below
(/ i
8)
943 do
(setf (sap-ref-8 (buffer-sap obuf
)
945 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
948 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
949 if
(subtypep type
`(signed-byte ,i
))
950 do
(return-from pick-output-routine
954 (lambda (stream byte
)
955 (output-wrapper (stream (/ i
8) (:none
) nil
)
956 (loop for j from
0 below
(/ i
8)
957 do
(setf (sap-ref-8 (buffer-sap obuf
)
959 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
961 (lambda (stream byte
)
962 (output-wrapper (stream (/ i
8) (:full
) nil
)
963 (loop for j from
0 below
(/ i
8)
964 do
(setf (sap-ref-8 (buffer-sap obuf
)
966 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
970 ;;;; input routines and related noise
972 ;;; a list of all available input routines. Each element is a list of
973 ;;; the element-type input, the function name, and the number of bytes
975 (defvar *input-routines
* ())
977 ;;; Return whether a primitive partial read operation on STREAM's FD
978 ;;; would (probably) block. Signal a `simple-stream-error' if the
979 ;;; system call implementing this operation fails.
981 ;;; It is "may" instead of "would" because "would" is not quite
982 ;;; correct on win32. However, none of the places that use it require
983 ;;; further assurance than "may" versus "will definitely not".
984 (defun sysread-may-block-p (stream)
986 ;; This answers T at EOF on win32, I think.
987 (not (sb!win32
:fd-listen
(fd-stream-fd stream
)))
989 (not (sb!unix
:unix-simple-poll
(fd-stream-fd stream
) :input
0)))
991 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
992 ;;; then fill the input buffer, and return the number of bytes read. Throws
993 ;;; to EOF-INPUT-CATCHER if the eof was reached.
994 (defun refill-input-buffer (stream)
995 (let ((fd (fd-stream-fd stream
))
1002 ;; Check for blocking input before touching the stream if we are to
1003 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
1004 ;; read(). Regular files should never block, so we can elide the check.
1005 (if (and (neq :regular
(fd-stream-fd-type stream
))
1006 (sysread-may-block-p stream
))
1007 (go :wait-for-input
)
1009 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
1010 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
1012 (closed-flame stream
)
1014 (simple-stream-perror "couldn't read from ~S" stream errno
)
1016 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
1017 ;; to wait for input if read tells us EWOULDBLOCK.
1018 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
)
1019 (fd-stream-serve-events stream
))
1020 (signal-timeout 'io-timeout
1023 :seconds
(fd-stream-timeout stream
)))
1025 ;; Since the read should not block, we'll disable the
1026 ;; interrupts here, so that we don't accidentally unwind and
1027 ;; leave the stream in an inconsistent state.
1029 ;; Execute the nlx outside without-interrupts to ensure the
1030 ;; resulting thunk is stack-allocatable.
1031 ((lambda (return-reason)
1032 (ecase return-reason
1033 ((nil)) ; fast path normal cases
1034 ((:wait-for-input
) (go #!-win32
:wait-for-input
#!+win32
:main
))
1035 ((:closed-flame
) (go :closed-flame
))
1036 ((:read-error
) (go :read-error
))))
1038 ;; Check the buffer: if it is null, then someone has closed
1039 ;; the stream from underneath us. This is not ment to fix
1040 ;; multithreaded races, but to deal with interrupt handlers
1041 ;; closing the stream.
1044 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
1045 (sap (buffer-sap ibuf
))
1046 (length (buffer-length ibuf
))
1047 (head (buffer-head ibuf
))
1048 (tail (buffer-tail ibuf
)))
1049 (declare (index length head tail
)
1050 (inline sb
!unix
:unix-read
))
1051 (unless (zerop head
)
1052 (cond ((eql head tail
)
1053 ;; Buffer is empty, but not at yet reset -- make it so.
1056 (reset-buffer ibuf
))
1058 ;; Buffer has things in it, but they are not at the
1059 ;; head -- move them there.
1060 (let ((n (- tail head
)))
1061 (system-area-ub8-copy sap head sap
0 n
)
1063 (buffer-head ibuf
) head
1065 (buffer-tail ibuf
) tail
)))))
1066 (setf (fd-stream-listen stream
) nil
)
1067 (setf (values count errno
)
1068 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
1071 #!+win32 sb
!unix
:eintr
1072 #!-win32 sb
!unix
:ewouldblock
)
1073 (return :wait-for-input
)
1074 (return :read-error
)))
1076 (setf (fd-stream-listen stream
) :eof
)
1077 (/show0
"THROWing EOF-INPUT-CATCHER")
1078 (throw 'eof-input-catcher nil
))
1080 ;; Success! (Do not use INCF, for sake of other threads.)
1081 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
1084 ;;; Make sure there are at least BYTES number of bytes in the input
1085 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1086 (defmacro input-at-least
(stream bytes
)
1087 (let ((stream-var (gensym "STREAM"))
1088 (bytes-var (gensym "BYTES"))
1089 (buffer-var (gensym "IBUF")))
1090 `(let* ((,stream-var
,stream
)
1092 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
1094 (when (>= (- (buffer-tail ,buffer-var
)
1095 (buffer-head ,buffer-var
))
1098 (refill-input-buffer ,stream-var
)))))
1100 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
1102 (let ((stream-var (gensym "STREAM"))
1103 (retry-var (gensym "RETRY"))
1104 (element-var (gensym "ELT")))
1105 `(let* ((,stream-var
,stream
)
1106 (ibuf (fd-stream-ibuf ,stream-var
))
1109 (when (fd-stream-eof-forced-p ,stream-var
)
1110 (setf (fd-stream-eof-forced-p ,stream-var
) nil
)
1111 (return-from use-instead
1112 (eof-or-lose ,stream-var
,eof-error
,eof-value
)))
1113 (let ((,element-var nil
)
1114 (decode-break-reason nil
))
1115 (do ((,retry-var t
))
1117 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1118 (let* ((instead (fd-stream-instead ,stream-var
))
1119 (result (vector-pop instead
))
1120 (pointer (fill-pointer instead
)))
1122 (setf (fd-stream-listen ,stream-var
) nil
))
1123 (return-from use-instead result
))
1125 (catch 'eof-input-catcher
1126 (setf decode-break-reason
1127 (block decode-break-reason
1128 (input-at-least ,stream-var
,(if (consp bytes
)
1130 `(setq size
,bytes
)))
1131 (let* ((byte (sap-ref-8 (buffer-sap ibuf
) (buffer-head ibuf
))))
1132 (declare (ignorable byte
))
1133 ,@(when (consp bytes
)
1134 `((let ((sap (buffer-sap ibuf
))
1135 (head (buffer-head ibuf
)))
1136 (declare (ignorable sap head
))
1137 (setq size
,(cadr bytes
))
1138 (input-at-least ,stream-var size
))))
1139 (setq ,element-var
(locally ,@read-forms
))
1140 (setq ,retry-var nil
))
1142 (when decode-break-reason
1143 (when (stream-decoding-error-and-handle
1144 stream decode-break-reason
)
1145 (setq ,retry-var nil
)
1146 (throw 'eof-input-catcher nil
)))
1148 (let ((octet-count (- (buffer-tail ibuf
)
1149 (buffer-head ibuf
))))
1150 (when (or (zerop octet-count
)
1151 (and (not ,element-var
)
1152 (not decode-break-reason
)
1153 (stream-decoding-error-and-handle
1154 stream octet-count
)))
1155 (setq ,retry-var nil
))))))
1157 (incf (buffer-head ibuf
) size
)
1160 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1162 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1163 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
1164 (let ((stream-var (gensym "STREAM"))
1165 (element-var (gensym "ELT")))
1166 `(let* ((,stream-var
,stream
)
1167 (ibuf (fd-stream-ibuf ,stream-var
)))
1168 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1169 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var
)
1171 (catch 'eof-input-catcher
1172 (input-at-least ,stream-var
,bytes
)
1173 (locally ,@read-forms
))))
1175 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1178 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1180 (defmacro def-input-routine
/variable-width
(name
1181 (type external-format size sap head
)
1184 (defun ,name
(stream eof-error eof-value
)
1185 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1186 (let ((,sap
(buffer-sap ibuf
))
1187 (,head
(buffer-head ibuf
)))
1189 (setf *input-routines
*
1190 (nconc *input-routines
*
1191 (list (list ',type
',name
1 ',external-format
))))))
1193 (defmacro def-input-routine
(name
1194 (type size sap head
)
1197 (defun ,name
(stream eof-error eof-value
)
1198 (input-wrapper (stream ,size eof-error eof-value
)
1199 (let ((,sap
(buffer-sap ibuf
))
1200 (,head
(buffer-head ibuf
)))
1202 (setf *input-routines
*
1203 (nconc *input-routines
*
1204 (list (list ',type
',name
',size nil
))))))
1206 ;;; STREAM-IN routine for reading a string char
1207 (def-input-routine input-character
1208 (character 1 sap head
)
1209 (code-char (sap-ref-8 sap head
)))
1211 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1212 (def-input-routine input-unsigned-8bit-byte
1213 ((unsigned-byte 8) 1 sap head
)
1214 (sap-ref-8 sap head
))
1216 ;;; STREAM-IN routine for reading a signed 8 bit number
1217 (def-input-routine input-signed-8bit-number
1218 ((signed-byte 8) 1 sap head
)
1219 (signed-sap-ref-8 sap head
))
1221 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1222 (def-input-routine input-unsigned-16bit-byte
1223 ((unsigned-byte 16) 2 sap head
)
1224 (sap-ref-16 sap head
))
1226 ;;; STREAM-IN routine for reading a signed 16 bit number
1227 (def-input-routine input-signed-16bit-byte
1228 ((signed-byte 16) 2 sap head
)
1229 (signed-sap-ref-16 sap head
))
1231 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1232 (def-input-routine input-unsigned-32bit-byte
1233 ((unsigned-byte 32) 4 sap head
)
1234 (sap-ref-32 sap head
))
1236 ;;; STREAM-IN routine for reading a signed 32 bit number
1237 (def-input-routine input-signed-32bit-byte
1238 ((signed-byte 32) 4 sap head
)
1239 (signed-sap-ref-32 sap head
))
1241 #+#.
(cl:if
(cl:= sb
!vm
:n-word-bits
64) '(and) '(or))
1243 (def-input-routine input-unsigned-64bit-byte
1244 ((unsigned-byte 64) 8 sap head
)
1245 (sap-ref-64 sap head
))
1246 (def-input-routine input-signed-64bit-byte
1247 ((signed-byte 64) 8 sap head
)
1248 (signed-sap-ref-64 sap head
)))
1250 ;;; Find an input routine to use given the type. Return as multiple
1251 ;;; values the routine, the real type transfered, and the number of
1252 ;;; bytes per element (and for character types string input routine).
1253 (defun pick-input-routine (type &optional external-format
)
1254 (when (subtypep type
'character
)
1255 (let ((entry (get-external-format-or-lose external-format
)))
1256 (return-from pick-input-routine
1257 (values (ef-read-char-fun entry
)
1260 (ef-read-n-chars-fun entry
)
1261 (ef-char-size entry
)
1262 (canonize-external-format external-format entry
)))))
1263 (dolist (entry *input-routines
*)
1264 (when (and (subtypep type
(first entry
))
1265 (or (not (fourth entry
))
1266 (eq external-format
(fourth entry
))))
1267 (return-from pick-input-routine
1268 (values (symbol-function (second entry
))
1271 ;; FIXME: let's do it the hard way, then (but ignore things like
1272 ;; endianness, efficiency, and the necessary coupling between these
1273 ;; and the output routines). -- CSR, 2004-02-09
1274 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1275 if
(subtypep type
`(unsigned-byte ,i
))
1276 do
(return-from pick-input-routine
1278 (lambda (stream eof-error eof-value
)
1279 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1280 (let ((sap (buffer-sap ibuf
))
1281 (head (buffer-head ibuf
)))
1282 (loop for j from
0 below
(/ i
8)
1286 (sap-ref-8 sap
(+ head j
))))
1287 finally
(return result
)))))
1290 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1291 if
(subtypep type
`(signed-byte ,i
))
1292 do
(return-from pick-input-routine
1294 (lambda (stream eof-error eof-value
)
1295 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1296 (let ((sap (buffer-sap ibuf
))
1297 (head (buffer-head ibuf
)))
1298 (loop for j from
0 below
(/ i
8)
1302 (sap-ref-8 sap
(+ head j
))))
1303 finally
(return (if (logbitp (1- i
) result
)
1304 (dpb result
(byte i
0) -
1)
1309 ;;; the N-BIN method for FD-STREAMs
1311 ;;; Note that this blocks in UNIX-READ. It is generally used where
1312 ;;; there is a definite amount of reading to be done, so blocking
1313 ;;; isn't too problematical.
1314 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1315 &aux
(total-copied 0))
1316 (declare (type fd-stream stream
))
1317 (declare (type index start requested total-copied
))
1318 (aver (= (length (fd-stream-instead stream
)) 0))
1321 (let* ((remaining-request (- requested total-copied
))
1322 (ibuf (fd-stream-ibuf stream
))
1323 (head (buffer-head ibuf
))
1324 (tail (buffer-tail ibuf
))
1325 (available (- tail head
))
1326 (n-this-copy (min remaining-request available
))
1327 (this-start (+ start total-copied
))
1328 (this-end (+ this-start n-this-copy
))
1329 (sap (buffer-sap ibuf
)))
1330 (declare (type index remaining-request head tail available
))
1331 (declare (type index n-this-copy
))
1332 ;; Copy data from stream buffer into user's buffer.
1333 (%byte-blt sap head buffer this-start this-end
)
1334 (incf (buffer-head ibuf
) n-this-copy
)
1335 (incf total-copied n-this-copy
)
1336 ;; Maybe we need to refill the stream buffer.
1337 (cond (;; If there were enough data in the stream buffer, we're done.
1338 (eql total-copied requested
)
1339 (return total-copied
))
1340 (;; If EOF, we're done in another way.
1341 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1343 (error 'end-of-file
:stream stream
)
1344 (return total-copied
)))
1345 ;; Otherwise we refilled the stream buffer, so fall
1346 ;; through into another pass of the loop.
1349 (defun fd-stream-resync (stream)
1350 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1352 (funcall (ef-resync-fun entry
) stream
))))
1354 (defun get-fd-stream-character-sizer (stream)
1355 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1357 (ef-bytes-for-char-fun entry
))))
1359 (defun fd-stream-character-size (stream char
)
1360 (let ((sizer (get-fd-stream-character-sizer stream
)))
1361 (when sizer
(funcall sizer char
))))
1363 (defun fd-stream-string-size (stream string
)
1364 (let ((sizer (get-fd-stream-character-sizer stream
)))
1366 (loop for char across string summing
(funcall sizer char
)))))
1368 (defun find-external-format (external-format)
1369 (when external-format
1370 (get-external-format external-format
)))
1372 (defun variable-width-external-format-p (ef-entry)
1373 (and ef-entry
(not (null (ef-resync-fun ef-entry
)))))
1375 (defun bytes-for-char-fun (ef-entry)
1376 (if ef-entry
(ef-bytes-for-char-fun ef-entry
) (constantly 1)))
1378 (defmacro define-unibyte-mapping-external-format
1379 (canonical-name (&rest other-names
) &body exceptions
)
1380 (let ((->code-name
(symbolicate canonical-name
'-
>code-mapper
))
1381 (code->-name
(symbolicate 'code-
> canonical-name
'-mapper
))
1382 (get-bytes-name (symbolicate 'get- canonical-name
'-bytes
))
1383 (string->-name
(symbolicate 'string-
> canonical-name
))
1384 (define-string*-name
(symbolicate 'define- canonical-name
'-
>string
*))
1385 (string*-name
(symbolicate canonical-name
'-
>string
*))
1386 (define-string-name (symbolicate 'define- canonical-name
'-
>string
))
1387 (string-name (symbolicate canonical-name
'-
>string
))
1388 (->string-aref-name
(symbolicate canonical-name
'-
>string-aref
)))
1390 (define-unibyte-mapper ,-
>code-name
,code-
>-name
1392 (declaim (inline ,get-bytes-name
))
1393 (defun ,get-bytes-name
(string pos
)
1394 (declare (optimize speed
(safety 0))
1395 (type simple-string string
)
1396 (type array-range pos
))
1397 (get-latin-bytes #',code-
>-name
,canonical-name string pos
))
1398 (defun ,string-
>-name
(string sstart send null-padding
)
1399 (declare (optimize speed
(safety 0))
1400 (type simple-string string
)
1401 (type array-range sstart send
))
1402 (values (string->latin% string sstart send
#',get-bytes-name null-padding
)))
1403 (defmacro ,define-string
*-name
(accessor type
)
1404 (declare (ignore type
))
1405 (let ((name (make-od-name ',string
*-name accessor
)))
1407 (defun ,name
(string sstart send array astart aend
)
1408 (,(make-od-name 'latin-
>string
* accessor
)
1409 string sstart send array astart aend
#',',-
>code-name
)))))
1410 (instantiate-octets-definition ,define-string
*-name
)
1411 (defmacro ,define-string-name
(accessor type
)
1412 (declare (ignore type
))
1413 (let ((name (make-od-name ',string-name accessor
)))
1415 (defun ,name
(array astart aend
)
1416 (,(make-od-name 'latin-
>string accessor
)
1417 array astart aend
#',',-
>code-name
)))))
1418 (instantiate-octets-definition ,define-string-name
)
1419 (define-unibyte-external-format ,canonical-name
,other-names
1420 (let ((octet (,code-
>-name bits
)))
1422 (setf (sap-ref-8 sap tail
) octet
)
1423 (external-format-encoding-error stream bits
)))
1424 (let ((code (,-
>code-name byte
)))
1427 (return-from decode-break-reason
1)))
1431 (defmacro define-unibyte-external-format
1432 (canonical-name (&rest other-names
)
1433 out-form in-form octets-to-string-symbol string-to-octets-symbol
)
1434 `(define-external-format/variable-width
(,canonical-name
,@other-names
)
1439 ,octets-to-string-symbol
1440 ,string-to-octets-symbol
))
1442 (defmacro define-external-format
/variable-width
1443 (external-format output-restart replacement-character
1444 out-size-expr out-expr in-size-expr in-expr
1445 octets-to-string-sym string-to-octets-sym
)
1446 (let* ((name (first external-format
))
1447 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1448 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1449 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1450 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1451 (resync-function (symbolicate "RESYNC/" name
))
1452 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1453 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1454 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1455 (n-buffer (gensym "BUFFER")))
1457 (defun ,size-function
(byte)
1458 (declare (ignorable byte
))
1460 (defun ,out-function
(stream string flush-p start end
)
1461 (let ((start (or start
0))
1462 (end (or end
(length string
))))
1463 (declare (type index start end
))
1464 (synchronize-stream-output stream
)
1465 (unless (<= 0 start end
(length string
))
1466 (sequence-bounding-indices-bad-error string start end
))
1469 (let ((obuf (fd-stream-obuf stream
)))
1470 (string-dispatch (simple-base-string
1471 #!+sb-unicode
(simple-array character
(*))
1474 (let ((len (buffer-length obuf
))
1475 (sap (buffer-sap obuf
))
1477 (tail (buffer-tail obuf
)))
1478 (declare (type index tail
)
1479 ;; STRING bounds have already been checked.
1480 (optimize (safety 0)))
1481 (,@(if output-restart
1482 `(catch 'output-nothing
)
1485 ((or (= start end
) (< (- len tail
) 4)))
1486 (let* ((byte (aref string start
))
1487 (bits (char-code byte
))
1488 (size ,out-size-expr
))
1491 (setf (buffer-tail obuf
) tail
)
1494 ;; Exited via CATCH: skip the current character.
1498 (flush-output-buffer stream
)))
1500 (flush-output-buffer stream
))))
1501 (def-output-routines/variable-width
(,format
1508 (if (eql byte
#\Newline
)
1509 (setf (fd-stream-output-column stream
) 0)
1510 (incf (fd-stream-output-column stream
)))
1511 (let ((bits (char-code byte
))
1512 (sap (buffer-sap obuf
))
1513 (tail (buffer-tail obuf
)))
1515 (defun ,in-function
(stream buffer start requested eof-error-p
1516 &aux
(total-copied 0))
1517 (declare (type fd-stream stream
)
1518 (type index start requested total-copied
)
1520 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1522 (when (fd-stream-eof-forced-p stream
)
1523 (setf (fd-stream-eof-forced-p stream
) nil
)
1524 (return-from ,in-function
0))
1525 (do ((instead (fd-stream-instead stream
)))
1526 ((= (fill-pointer instead
) 0)
1527 (setf (fd-stream-listen stream
) nil
))
1528 (setf (aref buffer
(+ start total-copied
)) (vector-pop instead
))
1530 (when (= requested total-copied
)
1531 (when (= (fill-pointer instead
) 0)
1532 (setf (fd-stream-listen stream
) nil
))
1533 (return-from ,in-function total-copied
)))
1536 (let* ((ibuf (fd-stream-ibuf stream
))
1537 (head (buffer-head ibuf
))
1538 (tail (buffer-tail ibuf
))
1539 (sap (buffer-sap ibuf
))
1540 (decode-break-reason nil
))
1541 (declare (type index head tail
))
1542 ;; Copy data from stream buffer into user's buffer.
1543 (do ((size nil nil
))
1544 ((or (= tail head
) (= requested total-copied
)))
1545 (setf decode-break-reason
1546 (block decode-break-reason
1547 ,@(when (consp in-size-expr
)
1548 `((when (> ,(car in-size-expr
) (- tail head
))
1550 (let ((byte (sap-ref-8 sap head
)))
1551 (declare (ignorable byte
))
1552 (setq size
,(if (consp in-size-expr
) (cadr in-size-expr
) in-size-expr
))
1553 (when (> size
(- tail head
))
1555 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1559 (setf (buffer-head ibuf
) head
)
1560 (when decode-break-reason
1561 ;; If we've already read some characters on when the invalid
1562 ;; code sequence is detected, we return immediately. The
1563 ;; handling of the error is deferred until the next call
1564 ;; (where this check will be false). This allows establishing
1565 ;; high-level handlers for decode errors (for example
1566 ;; automatically resyncing in Lisp comments).
1567 (when (plusp total-copied
)
1568 (return-from ,in-function total-copied
))
1569 (when (stream-decoding-error-and-handle
1570 stream decode-break-reason
)
1572 (error 'end-of-file
:stream stream
)
1573 (return-from ,in-function total-copied
)))
1574 ;; we might have been given stuff to use instead, so
1575 ;; we have to return (and trust our caller to know
1576 ;; what to do about TOTAL-COPIED being 0).
1577 (return-from ,in-function total-copied
)))
1578 (setf (buffer-head ibuf
) head
)
1579 ;; Maybe we need to refill the stream buffer.
1580 (cond ( ;; If was data in the stream buffer, we're done.
1581 (plusp total-copied
)
1582 (return total-copied
))
1583 ( ;; If EOF, we're done in another way.
1584 (or (eq decode-break-reason
'eof
)
1585 (null (catch 'eof-input-catcher
1586 (refill-input-buffer stream
))))
1588 (error 'end-of-file
:stream stream
)
1589 (return total-copied
)))
1590 ;; Otherwise we refilled the stream buffer, so fall
1591 ;; through into another pass of the loop.
1593 (def-input-routine/variable-width
,in-char-function
(character
1597 (let ((byte (sap-ref-8 sap head
)))
1598 (declare (ignorable byte
))
1600 (defun ,resync-function
(stream)
1601 (let ((ibuf (fd-stream-ibuf stream
))
1603 (catch 'eof-input-catcher
1605 (incf (buffer-head ibuf
))
1606 (input-at-least stream
,(if (consp in-size-expr
) (car in-size-expr
) `(setq size
,in-size-expr
)))
1607 (unless (block decode-break-reason
1608 (let* ((sap (buffer-sap ibuf
))
1609 (head (buffer-head ibuf
))
1610 (byte (sap-ref-8 sap head
)))
1611 (declare (ignorable byte
))
1612 ,@(when (consp in-size-expr
)
1613 `((setq size
,(cadr in-size-expr
))
1614 (input-at-least stream size
)))
1615 (setf head
(buffer-head ibuf
))
1619 (defun ,read-c-string-function
(sap element-type
)
1620 (declare (type system-area-pointer sap
))
1622 (declare (optimize (speed 3) (safety 0)))
1623 (let* ((stream ,name
)
1624 (size 0) (head 0) (byte 0) (char nil
)
1625 (decode-break-reason nil
)
1626 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1627 (setf decode-break-reason
1628 (block decode-break-reason
1629 (setf byte
(sap-ref-8 sap head
)
1630 size
,(if (consp in-size-expr
)
1636 (when decode-break-reason
1637 (c-string-decoding-error
1638 ,name sap head decode-break-reason
))
1639 (when (zerop (char-code char
))
1641 (string (make-string length
:element-type element-type
)))
1642 (declare (ignorable stream
)
1643 (type index head length
) ;; size
1644 (type (unsigned-byte 8) byte
)
1645 (type (or null character
) char
)
1646 (type string string
))
1648 (dotimes (index length string
)
1649 (setf decode-break-reason
1650 (block decode-break-reason
1651 (setf byte
(sap-ref-8 sap head
)
1652 size
,(if (consp in-size-expr
)
1658 (when decode-break-reason
1659 (c-string-decoding-error
1660 ,name sap head decode-break-reason
))
1661 (setf (aref string index
) char
)))))
1663 (defun ,output-c-string-function
(string)
1664 (declare (type simple-string string
))
1666 (declare (optimize (speed 3) (safety 0)))
1667 (let* ((length (length string
))
1668 (char-length (make-array (1+ length
) :element-type
'index
))
1670 (+ (loop for i of-type index below length
1671 for byte of-type character
= (aref string i
)
1672 for bits
= (char-code byte
)
1673 sum
(setf (aref char-length i
)
1674 (the index
,out-size-expr
)) of-type index
)
1675 (let* ((byte (code-char 0))
1676 (bits (char-code byte
)))
1677 (declare (ignorable byte bits
))
1678 (setf (aref char-length length
)
1679 (the index
,out-size-expr
)))))
1681 (,n-buffer
(make-array buffer-length
1682 :element-type
'(unsigned-byte 8)))
1684 (declare (type index length buffer-length tail
)
1687 (with-pinned-objects (,n-buffer
)
1688 (let ((sap (vector-sap ,n-buffer
)))
1689 (declare (system-area-pointer sap
))
1690 (loop for i of-type index below length
1691 for byte of-type character
= (aref string i
)
1692 for bits
= (char-code byte
)
1693 for size of-type index
= (aref char-length i
)
1698 (byte (code-char bits
))
1699 (size (aref char-length length
)))
1700 (declare (ignorable bits byte size
))
1704 (let ((entry (%make-external-format
1705 :names
',external-format
1706 :default-replacement-character
,replacement-character
1707 :read-n-chars-fun
#',in-function
1708 :read-char-fun
#',in-char-function
1709 :write-n-bytes-fun
#',out-function
1710 ,@(mapcan #'(lambda (buffering)
1711 (list (intern (format nil
"WRITE-CHAR-~A-BUFFERED-FUN" buffering
) :keyword
)
1712 `#',(intern (format nil format
(string buffering
)))))
1713 '(:none
:line
:full
))
1714 :resync-fun
#',resync-function
1715 :bytes-for-char-fun
#',size-function
1716 :read-c-string-fun
#',read-c-string-function
1717 :write-c-string-fun
#',output-c-string-function
1718 :octets-to-string-fun
(lambda (&rest rest
)
1719 (declare (dynamic-extent rest
))
1720 (apply ',octets-to-string-sym rest
))
1721 :string-to-octets-fun
(lambda (&rest rest
)
1722 (declare (dynamic-extent rest
))
1723 (apply ',string-to-octets-sym rest
)))))
1724 (dolist (ef ',external-format
)
1725 (setf (gethash ef
*external-formats
*) entry
))))))
1727 ;;;; utility functions (misc routines, etc)
1729 ;;; Fill in the various routine slots for the given type. INPUT-P and
1730 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1731 ;;; set prior to calling this routine.
1732 (defun set-fd-stream-routines (fd-stream element-type external-format
1733 input-p output-p buffer-p
)
1734 (let* ((target-type (case element-type
1735 (unsigned-byte '(unsigned-byte 8))
1736 (signed-byte '(signed-byte 8))
1737 (:default
'character
)
1739 (character-stream-p (subtypep target-type
'character
))
1740 (bivalent-stream-p (eq element-type
:default
))
1741 normalized-external-format
1743 (bin-routine #'ill-bin
)
1746 (cin-routine #'ill-in
)
1749 (input-type nil
) ;calculated from bin-type/cin-type
1750 (input-size nil
) ;calculated from bin-size/cin-size
1751 (read-n-characters #'ill-in
)
1752 (bout-routine #'ill-bout
)
1755 (cout-routine #'ill-out
)
1760 (output-bytes #'ill-bout
))
1762 ;; Ensure that we have buffers in the desired direction(s) only,
1763 ;; getting new ones and dropping/resetting old ones as necessary.
1764 (let ((obuf (fd-stream-obuf fd-stream
)))
1768 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1770 (setf (fd-stream-obuf fd-stream
) nil
)
1771 (release-buffer obuf
))))
1773 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1777 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1779 (setf (fd-stream-ibuf fd-stream
) nil
)
1780 (release-buffer ibuf
))))
1782 ;; FIXME: Why only for output? Why unconditionally?
1784 (setf (fd-stream-output-column fd-stream
) 0))
1786 (when (and character-stream-p
(eq external-format
:default
))
1787 (/show0
"/getting default external format")
1788 (setf external-format
(default-external-format)))
1791 (when (or (not character-stream-p
) bivalent-stream-p
)
1792 (setf (values bin-routine bin-type bin-size read-n-characters
1793 char-size normalized-external-format
)
1794 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1798 (error "could not find any input routine for ~S" target-type
)))
1799 (when character-stream-p
1800 (setf (values cin-routine cin-type cin-size read-n-characters
1801 char-size normalized-external-format
)
1802 (pick-input-routine target-type external-format
))
1804 (error "could not find any input routine for ~S" target-type
)))
1805 (setf (fd-stream-in fd-stream
) cin-routine
1806 (fd-stream-bin fd-stream
) bin-routine
)
1807 ;; character type gets preferential treatment
1808 (setf input-size
(or cin-size bin-size
))
1809 (setf input-type
(or cin-type bin-type
))
1810 (when normalized-external-format
1811 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1812 (fd-stream-char-size fd-stream
) char-size
))
1813 (when (= (or cin-size
1) (or bin-size
1) 1)
1814 (setf (fd-stream-n-bin fd-stream
) ;XXX
1815 (if (and character-stream-p
(not bivalent-stream-p
))
1817 #'fd-stream-read-n-bytes
))
1818 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1819 ;; for character and (unsigned-byte 8) streams. In these
1820 ;; cases, fast-read-* will read from the
1821 ;; ansi-stream-(c)in-buffer, saving function calls.
1822 ;; Otherwise, the various data-reading functions in the stream
1823 ;; structure will be called.
1825 (not bivalent-stream-p
)
1826 ;; temporary disable on :io streams
1828 (cond (character-stream-p
1829 (setf (ansi-stream-cin-buffer fd-stream
)
1830 (make-array +ansi-stream-in-buffer-length
+
1831 :element-type
'character
)))
1832 ((equal target-type
'(unsigned-byte 8))
1833 (setf (ansi-stream-in-buffer fd-stream
)
1834 (make-array +ansi-stream-in-buffer-length
+
1835 :element-type
'(unsigned-byte 8))))))))
1838 (when (or (not character-stream-p
) bivalent-stream-p
)
1839 (setf (values bout-routine bout-type bout-size output-bytes
1840 char-size normalized-external-format
)
1841 (let ((buffering (fd-stream-buffering fd-stream
)))
1842 (if bivalent-stream-p
1843 (pick-output-routine '(unsigned-byte 8)
1844 (if (eq :line buffering
)
1848 (pick-output-routine target-type buffering external-format
))))
1849 (unless bout-routine
1850 (error "could not find any output routine for ~S buffered ~S"
1851 (fd-stream-buffering fd-stream
)
1853 (when character-stream-p
1854 (setf (values cout-routine cout-type cout-size output-bytes
1855 char-size normalized-external-format
)
1856 (pick-output-routine target-type
1857 (fd-stream-buffering fd-stream
)
1859 (unless cout-routine
1860 (error "could not find any output routine for ~S buffered ~S"
1861 (fd-stream-buffering fd-stream
)
1863 (when normalized-external-format
1864 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1865 (fd-stream-char-size fd-stream
) char-size
))
1866 (when character-stream-p
1867 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1868 (setf (fd-stream-out fd-stream
) cout-routine
1869 (fd-stream-bout fd-stream
) bout-routine
1870 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1871 #'fd-sout
#'ill-out
))
1872 (setf output-size
(or cout-size bout-size
))
1873 (setf output-type
(or cout-type bout-type
)))
1875 (when (and input-size output-size
1876 (not (eq input-size output-size
)))
1877 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1878 input-type input-size
1879 output-type output-size
))
1880 (setf (fd-stream-element-size fd-stream
)
1881 (or input-size output-size
))
1883 (setf (fd-stream-element-type fd-stream
)
1884 (cond ((equal input-type output-type
)
1890 ((subtypep input-type output-type
)
1892 ((subtypep output-type input-type
)
1895 (error "Input type (~S) and output type (~S) are unrelated?"
1899 ;;; Handles the resource-release aspects of stream closing, and marks
1901 (defun release-fd-stream-resources (fd-stream)
1904 ;; Drop handlers first.
1905 (when (fd-stream-handler fd-stream
)
1906 (remove-fd-handler (fd-stream-handler fd-stream
))
1907 (setf (fd-stream-handler fd-stream
) nil
))
1908 ;; Disable interrupts so that a asynch unwind will not leave
1909 ;; us with a dangling finalizer (that would close the same
1910 ;; --possibly reassigned-- FD again), or a stream with a closed
1911 ;; FD that appears open.
1912 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1913 (set-closed-flame fd-stream
)
1914 (cancel-finalization fd-stream
))
1915 ;; On error unwind from WITHOUT-INTERRUPTS.
1916 (serious-condition (e)
1918 ;; Release all buffers. If this is undone, or interrupted,
1919 ;; we're still safe: buffers have finalizers of their own.
1920 (release-fd-stream-buffers fd-stream
))
1922 ;;; Flushes the current input buffer and any supplied replacements,
1923 ;;; and returns the input buffer, and the amount of of flushed input
1925 (defun flush-input-buffer (stream)
1926 (let ((unread (length (fd-stream-instead stream
))))
1927 (setf (fill-pointer (fd-stream-instead stream
)) 0)
1928 (let ((ibuf (fd-stream-ibuf stream
)))
1930 (let ((head (buffer-head ibuf
))
1931 (tail (buffer-tail ibuf
)))
1932 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1933 (values nil unread
)))))
1935 (defun fd-stream-clear-input (stream)
1936 (flush-input-buffer stream
)
1939 (sb!win32
:fd-clear-input
(fd-stream-fd stream
))
1940 (setf (fd-stream-listen stream
) nil
))
1942 (catch 'eof-input-catcher
1943 (loop until
(sysread-may-block-p stream
)
1945 (refill-input-buffer stream
)
1946 (reset-buffer (fd-stream-ibuf stream
)))
1949 ;;; Handle miscellaneous operations on FD-STREAM.
1950 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
1951 (declare (ignore arg2
))
1954 (labels ((do-listen ()
1955 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1956 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
1957 (fd-stream-listen fd-stream
)
1959 (sb!win32
:fd-listen
(fd-stream-fd fd-stream
))
1961 ;; If the read can block, LISTEN will certainly return NIL.
1962 (if (sysread-may-block-p fd-stream
)
1964 ;; Otherwise select(2) and CL:LISTEN have slightly
1965 ;; different semantics. The former returns that an FD
1966 ;; is readable when a read operation wouldn't block.
1967 ;; That includes EOF. However, LISTEN must return NIL
1969 (progn (catch 'eof-input-catcher
1970 ;; r-b/f too calls select, but it shouldn't
1971 ;; block as long as read can return once w/o
1973 (refill-input-buffer fd-stream
))
1974 ;; At this point either IBUF-HEAD != IBUF-TAIL
1975 ;; and FD-STREAM-LISTEN is NIL, in which case
1976 ;; we should return T, or IBUF-HEAD ==
1977 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1978 ;; which case we should return :EOF for this
1979 ;; call and all future LISTEN call on this stream.
1980 ;; Call ourselves again to determine which case
1985 (decf (buffer-head (fd-stream-ibuf fd-stream
))
1986 (fd-stream-character-size fd-stream arg1
)))
1988 ;; Drop input buffers
1989 (setf (ansi-stream-in-index fd-stream
) +ansi-stream-in-buffer-length
+
1990 (ansi-stream-cin-buffer fd-stream
) nil
1991 (ansi-stream-in-buffer fd-stream
) nil
)
1993 ;; We got us an abort on our hands.
1994 (let ((outputp (fd-stream-obuf fd-stream
))
1995 (file (fd-stream-file fd-stream
))
1996 (orig (fd-stream-original fd-stream
)))
1997 ;; This takes care of the important stuff -- everything
1998 ;; rest is cleaning up the file-system, which we cannot
1999 ;; do on some platforms as long as the file is open.
2000 (release-fd-stream-resources fd-stream
)
2001 ;; We can't do anything unless we know what file were
2002 ;; dealing with, and we don't want to do anything
2003 ;; strange unless we were writing to the file.
2004 (when (and outputp file
)
2006 ;; If the original is EQ to file we are appending to
2007 ;; and can just close the file without renaming.
2008 (unless (eq orig file
)
2009 ;; We have a handle on the original, just revert.
2010 (multiple-value-bind (okay err
)
2011 (sb!unix
:unix-rename orig file
)
2012 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2013 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2016 (error 'simple-stream-error
2018 "~@<Couldn't restore ~S to its original contents ~
2019 from ~S while closing ~S: ~2I~_~A~:>"
2021 (list file orig fd-stream
(strerror err
))
2022 :stream fd-stream
))))
2023 ;; We can't restore the original, and aren't
2024 ;; appending, so nuke that puppy.
2026 ;; FIXME: This is currently the fate of superseded
2027 ;; files, and according to the CLOSE spec this is
2028 ;; wrong. However, there seems to be no clean way to
2029 ;; do that that doesn't involve either copying the
2030 ;; data (bad if the :abort resulted from a full
2031 ;; disk), or renaming the old file temporarily
2032 ;; (probably bad because stream opening becomes more
2034 (multiple-value-bind (okay err
)
2035 (sb!unix
:unix-unlink file
)
2037 (error 'simple-file-error
2040 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2042 (list file fd-stream
(strerror err
)))))))))
2044 (finish-fd-stream-output fd-stream
)
2045 (let ((orig (fd-stream-original fd-stream
)))
2046 (when (and orig
(fd-stream-delete-original fd-stream
))
2047 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2049 (error 'simple-file-error
2052 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2054 (list orig fd-stream
(strerror err
)))))))
2055 ;; In case of no-abort close, don't *really* close the
2056 ;; stream until the last moment -- the cleaning up of the
2057 ;; original can be done first.
2058 (release-fd-stream-resources fd-stream
))))
2060 (fd-stream-clear-input fd-stream
))
2062 (flush-output-buffer fd-stream
))
2064 (finish-fd-stream-output fd-stream
))
2066 (fd-stream-element-type fd-stream
))
2068 (fd-stream-external-format fd-stream
))
2070 (plusp (the (integer 0)
2071 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2075 (fd-stream-output-column fd-stream
))
2077 (unless (fd-stream-file fd-stream
)
2078 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2079 ;; "should signal an error of type TYPE-ERROR if stream is not
2080 ;; a stream associated with a file". Too bad there's no very
2081 ;; appropriate value for the EXPECTED-TYPE slot..
2082 (error 'simple-type-error
2084 :expected-type
'fd-stream
2085 :format-control
"~S is not a stream associated with a file."
2086 :format-arguments
(list fd-stream
)))
2088 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2089 atime mtime ctime blksize blocks
)
2090 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2091 (declare (ignore ino nlink uid gid rdev
2092 atime mtime ctime blksize blocks
))
2094 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2097 (truncate size
(fd-stream-element-size fd-stream
))))
2099 (let* ((handle (fd-stream-fd fd-stream
))
2100 (element-size (fd-stream-element-size fd-stream
)))
2101 (multiple-value-bind (got native-size
)
2102 (sb!win32
:get-file-size-ex handle
0)
2104 ;; Might be a block device, in which case we fall back to
2105 ;; a non-atomic workaround:
2106 (let* ((here (sb!unix
:unix-lseek handle
0 sb
!unix
:l_incr
))
2107 (there (sb!unix
:unix-lseek handle
0 sb
!unix
:l_xtnd
)))
2108 (when (and here there
)
2109 (sb!unix
:unix-lseek handle here sb
!unix
:l_set
)
2110 (truncate there element-size
)))
2111 (truncate native-size element-size
)))))
2112 (:file-string-length
2114 (character (fd-stream-character-size fd-stream arg1
))
2115 (string (fd-stream-string-size fd-stream arg1
))))
2118 (fd-stream-set-file-position fd-stream arg1
)
2119 (fd-stream-get-file-position fd-stream
)))))
2121 ;; FIXME: Think about this.
2123 ;; (defun finish-fd-stream-output (fd-stream)
2124 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2125 ;; (loop while (fd-stream-output-queue fd-stream)
2126 ;; ;; FIXME: SIGINT while waiting for a timeout will
2127 ;; ;; cause a timeout here.
2128 ;; do (when (and (not (serve-event timeout)) timeout)
2129 ;; (signal-timeout 'io-timeout
2130 ;; :stream fd-stream
2131 ;; :direction :write
2132 ;; :seconds timeout)))))
2134 (defun finish-fd-stream-output (stream)
2135 (flush-output-buffer stream
)
2137 ((null (fd-stream-output-queue stream
)))
2138 (aver (fd-stream-serve-events stream
))
2139 (serve-all-events)))
2141 (defun fd-stream-get-file-position (stream)
2142 (declare (fd-stream stream
))
2144 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2145 (declare (type (or (alien sb
!unix
:unix-offset
) null
) posn
))
2146 ;; We used to return NIL for errno==ESPIPE, and signal an error
2147 ;; in other failure cases. However, CLHS says to return NIL if
2148 ;; the position cannot be determined -- so that's what we do.
2149 (when (integerp posn
)
2150 ;; Adjust for buffered output: If there is any output
2151 ;; buffered, the *real* file position will be larger
2152 ;; than reported by lseek() because lseek() obviously
2153 ;; cannot take into account output we have not sent
2155 (dolist (buffer (fd-stream-output-queue stream
))
2156 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2157 (let ((obuf (fd-stream-obuf stream
)))
2159 (incf posn
(buffer-tail obuf
))))
2160 ;; Adjust for unread input: If there is any input
2161 ;; read from UNIX but not supplied to the user of the
2162 ;; stream, the *real* file position will smaller than
2163 ;; reported, because we want to look like the unread
2164 ;; stuff is still available.
2165 (let ((ibuf (fd-stream-ibuf stream
)))
2167 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2168 ;; Divide bytes by element size.
2169 (truncate posn
(fd-stream-element-size stream
))))))
2171 (defun fd-stream-set-file-position (stream position-spec
)
2172 (declare (fd-stream stream
))
2173 (check-type position-spec
2174 (or (alien sb
!unix
:unix-offset
) (member nil
:start
:end
))
2175 "valid file position designator")
2178 ;; Make sure we don't have any output pending, because if we
2179 ;; move the file pointer before writing this stuff, it will be
2180 ;; written in the wrong location.
2181 (finish-fd-stream-output stream
)
2182 ;; Disable interrupts so that interrupt handlers doing output
2185 (unless (fd-stream-output-finished-p stream
)
2186 ;; We got interrupted and more output came our way during
2187 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2188 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2189 ;; so we prefer to do things like this...
2191 ;; Clear out any pending input to force the next read to go to
2193 (flush-input-buffer stream
)
2194 ;; Trash cached value for listen, so that we check next time.
2195 (setf (fd-stream-listen stream
) nil
)
2197 (multiple-value-bind (offset origin
)
2200 (values 0 sb
!unix
:l_set
))
2202 (values 0 sb
!unix
:l_xtnd
))
2204 (values (* position-spec
(fd-stream-element-size stream
))
2206 (declare (type (alien sb
!unix
:unix-offset
) offset
))
2207 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2209 ;; CLHS says to return true if the file-position was set
2210 ;; successfully, and NIL otherwise. We are to signal an error
2211 ;; only if the given position was out of bounds, and that is
2212 ;; dealt with above. In times past we used to return NIL for
2213 ;; errno==ESPIPE, and signal an error in other cases.
2215 ;; FIXME: We are still liable to signal an error if flushing
2217 (return-from fd-stream-set-file-position
2218 (typep posn
'(alien sb
!unix
:unix-offset
))))))))
2221 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2223 ;;; Create a stream for the given Unix file descriptor.
2225 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2226 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2227 ;;; default to allowing input.
2229 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2231 ;;; BUFFERING indicates the kind of buffering to use.
2233 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2234 ;;; NIL (the default), then wait forever. When we time out, we signal
2237 ;;; FILE is the name of the file (will be returned by PATHNAME).
2239 ;;; NAME is used to identify the stream when printed.
2241 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2242 ;;; handle blocking IO on the stream.
2243 (defun make-fd-stream (fd
2247 (output nil output-p
)
2248 (element-type 'base-char
)
2250 (external-format :default
)
2260 (format nil
"file ~A" file
)
2261 (format nil
"descriptor ~W" fd
)))
2263 (declare (type index fd
) (type (or real null
) timeout
)
2264 (type (member :none
:line
:full
) buffering
))
2265 (cond ((not (or input-p output-p
))
2267 ((not (or input output
))
2268 (error "File descriptor must be opened either for input or output.")))
2269 (let ((stream (funcall (ecase class
2270 (fd-stream '%make-fd-stream
)
2271 (form-tracking-stream '%make-form-tracking-stream
))
2274 #!-win32
(sb!unix
:fd-type fd
)
2276 #!+win32
(if serve-events
2282 :delete-original delete-original
2284 :buffering buffering
2285 :dual-channel-p dual-channel-p
2286 :bivalent-p
(eq element-type
:default
)
2287 :serve-events serve-events
2290 (coerce timeout
'single-float
)
2292 (set-fd-stream-routines stream element-type external-format
2293 input output input-buffer-p
)
2297 (sb!unix
:unix-close fd
)
2299 (format *terminal-io
* "** closed file descriptor ~W **~%"
2304 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2305 ;;; :RENAME-AND-DELETE and :RENAME options.
2306 (defun pick-backup-name (name)
2307 (declare (type simple-string name
))
2308 (concatenate 'simple-string name
".bak"))
2310 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2311 ;;; access, since we don't want to trash unwritable files even if we
2312 ;;; technically can. We return true if we succeed in renaming.
2313 (defun rename-the-old-one (namestring original
)
2314 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2315 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2316 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2319 (error 'simple-file-error
2320 :pathname namestring
2322 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2323 :format-arguments
(list namestring original
(strerror err
))))))
2325 (defun open (filename
2328 (element-type 'base-char
)
2329 (if-exists nil if-exists-given
)
2330 (if-does-not-exist nil if-does-not-exist-given
)
2331 (external-format :default
)
2332 ;; :class is a private option - use it at your own risk
2334 &aux
; Squelch assignment warning.
2335 (direction direction
)
2336 (if-does-not-exist if-does-not-exist
)
2337 (if-exists if-exists
))
2339 "Return a stream which reads from or writes to FILENAME.
2341 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2342 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2343 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2344 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2345 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2346 See the manual for details."
2348 ;; Calculate useful stuff.
2349 (multiple-value-bind (input output mask
)
2351 (:input
(values t nil sb
!unix
:o_rdonly
))
2352 (:output
(values nil t sb
!unix
:o_wronly
))
2353 (:io
(values t t sb
!unix
:o_rdwr
))
2354 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2355 (declare (type index mask
))
2356 (let* ( ;; PATHNAME is the pathname we associate with the stream.
2357 (pathname (merge-pathnames filename
))
2358 (physical (physicalize-pathname pathname
))
2359 (truename (probe-file physical
))
2360 ;; NAMESTRING is the native namestring we open the file with.
2361 (namestring (cond (truename
2362 (native-namestring truename
:as-file t
))
2364 (and input
(eq if-does-not-exist
:create
))
2365 (and (eq direction
:io
)
2366 (not if-does-not-exist-given
)))
2367 (native-namestring physical
:as-file t
)))))
2368 (flet ((open-error (format-control &rest format-arguments
)
2369 (error 'simple-file-error
2371 :format-control format-control
2372 :format-arguments format-arguments
)))
2373 ;; Process if-exists argument if we are doing any output.
2375 (unless if-exists-given
2377 (if (eq (pathname-version pathname
) :newest
)
2381 ((:new-version
:error nil
)
2382 (setf mask
(logior mask sb
!unix
:o_excl
)))
2383 ((:rename
:rename-and-delete
)
2384 (setf mask
(logior mask sb
!unix
:o_creat
)))
2386 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2388 (setf mask
(logior mask sb
!unix
:o_append
)))))
2390 (setf if-exists
:ignore-this-arg
)))
2392 (unless if-does-not-exist-given
2393 (setf if-does-not-exist
2394 (cond ((eq direction
:input
) :error
)
2396 (member if-exists
'(:overwrite
:append
)))
2398 ((eq direction
:probe
)
2402 (cond ((and if-exists-given
2404 (eq if-exists
:new-version
))
2405 (open-error "OPEN :IF-EXISTS :NEW-VERSION is not supported ~
2406 when a new version must be created."))
2407 ((eq if-does-not-exist
:create
)
2408 (setf mask
(logior mask sb
!unix
:o_creat
)))
2409 ((not (member if-exists
'(:error nil
))))
2410 ;; Both if-does-not-exist and if-exists now imply
2411 ;; that there will be no opening of files, and either
2412 ;; an error would be signalled, or NIL returned
2413 ((and (not if-exists
) (not if-does-not-exist
))
2415 ((and if-exists if-does-not-exist
)
2416 (open-error "OPEN :IF-DOES-NOT-EXIST ~s ~
2417 :IF-EXISTS ~s will always signal an error."
2418 if-does-not-exist if-exists
))
2421 (open-error "File exists ~s." pathname
)
2422 (return-from open
)))
2424 (open-error "File does not exist ~s." pathname
))
2426 (return-from open
)))
2427 (let ((original (case if-exists
2428 ((:rename
:rename-and-delete
)
2429 (pick-backup-name namestring
))
2430 ((:append
:overwrite
)
2431 ;; KLUDGE: Prevent CLOSE from deleting
2432 ;; appending streams when called with :ABORT T
2434 (delete-original (eq if-exists
:rename-and-delete
))
2436 (when (and original
(not (eq original namestring
)))
2437 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2438 ;; whether the file already exists, make sure the original
2439 ;; file is not a directory, and keep the mode.
2442 (multiple-value-bind (okay err
/dev inode orig-mode
)
2443 (sb!unix
:unix-stat namestring
)
2444 (declare (ignore inode
)
2445 (type (or index null
) orig-mode
))
2448 (when (and output
(= (logand orig-mode
#o170000
)
2450 (error 'simple-file-error
2453 "can't open ~S for output: is a directory"
2454 :format-arguments
(list namestring
)))
2455 (setf mode
(logand orig-mode
#o777
))
2457 ((eql err
/dev sb
!unix
:enoent
)
2460 (simple-file-perror "can't find ~S"
2464 (rename-the-old-one namestring original
))
2466 (setf delete-original nil
)
2467 ;; In order to use :SUPERSEDE instead, we have to make
2468 ;; sure SB!UNIX:O_CREAT corresponds to
2469 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2470 ;; because of IF-EXISTS being :RENAME.
2471 (unless (eq if-does-not-exist
:create
)
2473 (logior (logandc2 mask sb
!unix
:o_creat
)
2475 (setf if-exists
:supersede
))))
2477 ;; Now we can try the actual Unix open(2).
2478 (multiple-value-bind (fd errno
)
2480 (sb!unix
:unix-open namestring mask mode
)
2481 (values nil sb
!unix
:enoent
))
2482 (flet ((vanilla-open-error ()
2483 (simple-file-perror "error opening ~S" pathname errno
)))
2486 ((:input
:output
:io
)
2487 ;; For O_APPEND opened files, lseek returns 0 until first write.
2488 ;; So we jump ahead here.
2489 (when (eq if-exists
:append
)
2490 (sb!unix
:unix-lseek fd
0 sb
!unix
:l_xtnd
))
2495 :element-type element-type
2496 :external-format external-format
2499 :delete-original delete-original
2507 (%make-fd-stream
:name namestring
2510 :element-type element-type
)))
2513 ((eql errno sb
!unix
:enoent
)
2514 (case if-does-not-exist
2515 (:error
(vanilla-open-error))
2517 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2520 ((and (eql errno sb
!unix
:eexist
) (null if-exists
))
2523 (vanilla-open-error))))))))))
2527 ;;; the stream connected to the controlling terminal, or NIL if there is none
2530 ;;; the stream connected to the standard input (file descriptor 0)
2533 ;;; the stream connected to the standard output (file descriptor 1)
2536 ;;; the stream connected to the standard error output (file descriptor 2)
2539 ;;; This is called when the cold load is first started up, and may also
2540 ;;; be called in an attempt to recover from nested errors.
2541 (defun stream-cold-init-or-reset ()
2542 ;; FIXME: on gencgc the 4 standard fd-streams {stdin,stdout,stderr,tty}
2543 ;; and these synonym streams are baked into +pseudo-static-generation+.
2544 ;; Is that inadvertent?
2546 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2547 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2548 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2549 (setf *error-output
* (make-synonym-stream '*stderr
*))
2550 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2551 (setf *debug-io
* *query-io
*)
2552 (setf *trace-output
* *standard-output
*)
2555 (defun stream-deinit ()
2556 ;; Unbind to make sure we're not accidently dealing with it
2557 ;; before we're ready (or after we think it's been deinitialized).
2558 (with-available-buffers-lock ()
2559 (without-package-locks
2560 (makunbound '*available-buffers
*))))
2562 (defun stdstream-external-format (fd outputp
)
2563 #!-win32
(declare (ignore fd outputp
))
2564 (let* ((keyword #!+win32
(if (and (/= fd -
1)
2569 (sb!win32
::console-output-codepage
)
2570 (sb!win32
::console-input-codepage
)))
2571 #!-win32
(default-external-format))
2572 (ef (get-external-format keyword
))
2573 (replacement (ef-default-replacement-character ef
)))
2574 `(,keyword
:replacement
,replacement
)))
2576 ;;; This is called whenever a saved core is restarted.
2577 (defun stream-reinit (&optional init-buffers-p
)
2578 (when init-buffers-p
2579 (with-available-buffers-lock ()
2580 (aver (not (boundp '*available-buffers
*)))
2581 (setf *available-buffers
* nil
)))
2582 (with-simple-output-to-string (*error-output
*)
2583 (multiple-value-bind (in out err
)
2584 #!-win32
(values 0 1 2)
2585 #!+win32
(sb!win32
::get-std-handles
)
2587 (nul-stream (name inputp outputp
)
2588 (let* ((nul-name #.
(coerce "NUL" 'simple-base-string
))
2591 ((and inputp outputp
)
2592 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdwr
0))
2594 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdonly
0))
2596 (sb!win32
:unixlike-open nul-name sb
!unix
:o_wronly
0))
2598 ;; Not quite sure what to do in this case.
2606 :element-type
:default
2607 :serve-events inputp
2609 :external-format
(stdstream-external-format nul-handle outputp
))))
2610 (stdio-stream (handle name inputp outputp
)
2614 ;; If no actual handle was present, create a stream to NUL
2615 (nul-stream name inputp outputp
))
2623 :element-type
:default
2624 :serve-events inputp
2625 :external-format
(stdstream-external-format handle outputp
))))))
2626 (setf *stdin
* (stdio-stream in
"standard input" t nil
)
2627 *stdout
* (stdio-stream out
"standard output" nil t
)
2628 *stderr
* (stdio-stream err
"standard error" nil t
))))
2630 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))
2632 ;; FIXME: what is this call to COERCE doing? XC can't dump non-base-strings.
2633 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2634 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2637 (make-fd-stream tty
:name
"the terminal"
2638 :input t
:output t
:buffering
:line
2639 :external-format
(stdstream-external-format
2643 (make-two-way-stream *stdin
* *stdout
*))))
2644 (princ (get-output-stream-string *error-output
*) *stderr
*))
2649 ;;; the Unix way to beep
2650 (defun beep (stream)
2651 (write-char (code-char bell-char-code
) stream
)
2652 (finish-output stream
))
2654 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2655 ;;; by the filesys stuff to get and set the file name.
2657 ;;; FIXME: misleading name, screwy interface
2658 (defun file-name (stream &optional new-name
)
2659 (when (typep stream
'fd-stream
)
2661 (setf (fd-stream-pathname stream
) new-name
)
2662 (setf (fd-stream-file stream
)
2663 (native-namestring (physicalize-pathname new-name
)
2667 (fd-stream-pathname stream
)))))
2669 ;; Placing this definition (formerly in "toplevel") after the important
2670 ;; stream types are known produces smaller+faster code than it did before.
2671 (defun stream-output-stream (stream)
2676 (stream-output-stream
2677 (symbol-value (synonym-stream-symbol stream
))))
2679 (stream-output-stream
2680 (two-way-stream-output-stream stream
)))
2684 ;; Fix the INPUT-CHAR-POS slot of STREAM after having consumed characters
2685 ;; from the CIN-BUFFER. This operation is done upon exit from a FAST-READ-CHAR
2686 ;; loop, and for each buffer refill inside the loop.
2687 (defun update-input-char-pos (stream &optional
(end +ansi-stream-in-buffer-length
+))
2688 (do ((chars (ansi-stream-cin-buffer stream
))
2689 (pos (form-tracking-stream-input-char-pos stream
))
2690 (i (ansi-stream-in-index stream
) (1+ i
)))
2692 (setf (form-tracking-stream-input-char-pos stream
) pos
))
2693 (let ((char (aref chars i
)))
2694 (when (and (eql char
#\Newline
)
2695 ;; record it only if it wasn't unread and re-read
2696 (> pos
(form-tracking-stream-last-newline stream
)))
2697 (vector-push-extend pos
(form-tracking-stream-newlines stream
))
2698 (setf (form-tracking-stream-last-newline stream
) pos
))
2701 (defun tracking-stream-misc (stream operation
&optional arg1 arg2
)
2702 ;; The :UNREAD operation will never be invoked because STREAM has a buffer,
2703 ;; so unreading is implemented entirely within ANSI-STREAM-UNREAD-CHAR.
2704 ;; But we do need to prevent attempts to change the absolute position.
2708 (error 'simple-stream-error
2709 :format-control
"~S is not positionable"
2710 :format-arguments
(list stream
))
2711 (fd-stream-get-file-position stream
)))
2712 (t ; call next method
2713 (fd-stream-misc-routine stream operation arg1 arg2
))))
2715 ;; Using (get-std-handle-or-null +std-error-handle+) instead of the file
2716 ;; descriptor might make this work on win32, but I don't know.
2718 (macrolet ((stderr () 2))
2719 (!defglobal
*!cold-stderr-buf
* " ")
2720 (defun !make-cold-stderr-stream
()
2722 :out
(lambda (stream ch
)
2723 (declare (ignore stream
))
2724 (let ((b (truly-the (simple-base-string 1) *!cold-stderr-buf
*)))
2725 (setf (char b
0) ch
)
2726 (sb!unix
:unix-write
(stderr) b
0 1)))
2727 :sout
(lambda (stream string start end
)
2728 (declare (ignore stream
))
2729 (flet ((out (s start len
)
2730 (sb!unix
:unix-write
(stderr) s start len
)))
2731 (if (typep string
'simple-base-string
)
2732 (out string start
(- end start
))
2733 (let ((n (- end start
)))
2734 ;; will croak if there is any non-BASE-CHAR in the string
2735 (out (replace (make-array n
:element-type
'base-char
)
2736 string
:start2 start
) 0 n
)))))
2737 :misc
(constantly nil
))))