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
))
45 (sap (missing-arg) :type system-area-pointer
:read-only t
)
46 (length (missing-arg) :type index
:read-only t
)
49 (declaim (freeze-type buffer
))
51 (defglobal *available-buffers
* ()
52 "List of available buffers.")
54 (defconstant +bytes-per-buffer
+ (* 4 1024)
55 "Default number of bytes per buffer.")
57 (defun alloc-buffer (&optional
(size +bytes-per-buffer
+))
58 ;; Don't want to allocate & unwind before the finalizer is in place.
60 (let* ((sap (allocate-system-memory size
))
61 (buffer (%make-buffer sap size
)))
62 (when (zerop (sap-int sap
))
63 (error "Could not allocate ~D bytes for buffer." size
))
64 (finalize buffer
(lambda ()
65 (deallocate-system-memory sap size
))
70 (or (and *available-buffers
* (atomic-pop *available-buffers
*))
73 (declaim (inline reset-buffer
))
74 (defun reset-buffer (buffer)
75 (setf (buffer-head buffer
) 0
76 (buffer-tail buffer
) 0)
79 (defun release-buffer (buffer)
81 (atomic-push buffer
*available-buffers
*))
84 ;;;; the FD-STREAM structure
86 ;;; Coarsely characterizes the element type of an FD-STREAM w.r.t.
87 ;;; its SUBTYPEP relations to the relevant CHARACTER and
88 ;;; ([UN]SIGNED-BYTE 8) types. This coarse characterization enables
89 ;;; dispatching on the element type as needed by {READ,WRITE}-SEQUENCE
90 ;;; without calling SUBTYPEP.
91 (deftype stream-element-mode
()
92 '(member character unsigned-byte signed-byte
:bivalent
))
95 (:constructor %make-fd-stream
)
96 (:conc-name fd-stream-
)
97 (:predicate fd-stream-p
)
99 (misc #'fd-stream-misc-routine
))
102 ;; the name of this stream
104 ;; the file this stream is for
106 ;; the backup file namestring for the old file, for :IF-EXISTS
107 ;; :RENAME or :RENAME-AND-DELETE.
108 (original nil
:type
(or simple-string null
))
109 (delete-original nil
) ; for :if-exists :rename-and-delete
110 ;;; the number of bytes per element
111 (element-size 1 :type index
)
112 ;; the type of element being transfered
113 (element-type 'base-char
)
114 ;; coarse characterization of the element type. see description of
115 ;; STREAM-ELEMENT-MODE type.
116 (element-mode :bivalent
:type stream-element-mode
)
117 ;; the Unix file descriptor
118 (fd -
1 :type
#!-win32 fixnum
#!+win32 sb
!vm
:signed-word
)
119 ;; What do we know about the FD?
120 (fd-type :unknown
:type keyword
)
121 ;; controls when the output buffer is flushed
122 (buffering :full
:type
(member :full
:line
:none
))
123 ;; controls whether the input buffer must be cleared before output
124 ;; (must be done for files, not for sockets, pipes and other data
125 ;; sources where input and output aren't related). non-NIL means
126 ;; don't clear input buffer.
128 ;; character position if known -- this may run into bignums, but
129 ;; we probably should flip it into null then for efficiency's sake...
130 (output-column nil
:type
(or (and unsigned-byte
133 ;; T if input is waiting on FD. :EOF if we hit EOF.
134 (listen nil
:type
(member nil t
:eof
))
135 ;; T if serve-event is allowed when this stream blocks
136 (serve-events nil
:type boolean
)
139 (instead (make-array 0 :element-type
'character
:adjustable t
:fill-pointer t
) :type
(array character
(*)))
140 (ibuf nil
:type
(or buffer null
))
141 (eof-forced-p nil
:type
(member t nil
))
144 (obuf nil
:type
(or buffer null
))
146 ;; output flushed, but not written due to non-blocking io?
149 ;; timeout specified for this stream as seconds or NIL if none
150 (timeout nil
:type
(or single-float null
))
151 ;; pathname of the file this stream is opened to (returned by PATHNAME)
152 (pathname nil
:type
(or pathname null
))
153 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
154 (external-format :latin-1
)
155 ;; fixed width, or function to call with a character
156 (char-size 1 :type
(or fixnum function
))
157 (output-bytes #'ill-out
:type function
))
159 (defun fd-stream-bivalent-p (stream)
160 (eq (fd-stream-element-mode stream
) :bivalent
))
162 (defmethod print-object ((fd-stream fd-stream
) stream
)
163 (declare (type stream stream
))
164 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
165 (format stream
"for ~S" (fd-stream-name fd-stream
))))
167 ;;; Release all of FD-STREAM's buffers. Originally the intent of this
168 ;;; was to grab a mutex once only, but the buffer pool is lock-free now.
169 (defun release-fd-stream-buffers (fd-stream)
170 (awhen (fd-stream-ibuf fd-stream
)
171 (setf (fd-stream-ibuf fd-stream
) nil
)
173 (awhen (fd-stream-obuf fd-stream
)
174 (setf (fd-stream-obuf fd-stream
) nil
)
176 (dolist (buf (fd-stream-output-queue fd-stream
))
178 (release-buffer buf
)))
179 (setf (fd-stream-output-queue fd-stream
) nil
))
181 ;;;; FORM-TRACKING-STREAM
183 ;; The compiler uses this to record for each input subform the start and
184 ;; end positions as character offsets. Measuring in characters rather than
185 ;; bytes is both better suited to the task - in that it is consistent with
186 ;; reporting of "point" by Emacs - and faster than querying FILE-POSITION.
187 ;; The slowness of FILE-POSITION on an FD-STREAM is due to making a system
188 ;; call every time, to ensure that the case of an append-only stream works
189 ;; correctly (where the OS forces all writes to the end), and other factors.
191 (defstruct (form-tracking-stream
192 (:constructor %make-form-tracking-stream
)
194 (misc #'tracking-stream-misc
)
197 ;; a function which is called for events on this stream.
198 (observer (lambda (x y z
) (declare (ignore x y z
))) :type function
)
199 ;; A vector of the character position of each #\Newline seen
200 (newlines (make-array 10 :fill-pointer
0 :adjustable t
))
201 (last-newline -
1 :type index-or-minus-1
)
202 ;; Better than reporting that a reader error occurred at a position
203 ;; before any whitespace (or equivalently, a macro producing no value),
204 ;; we can note the position at the first "good" character.
205 (form-start-byte-pos)
206 (form-start-char-pos))
208 (defun line/col-from-charpos
209 (stream &optional
(charpos (ansi-stream-input-char-pos stream
)))
210 (let* ((newlines (form-tracking-stream-newlines stream
))
211 (index (position charpos newlines
:test
#'>= :from-end t
)))
212 ;; Line numbers traditionally begin at 1, columns at 0.
214 ;; INDEX is 1 less than the number of newlines seen
215 ;; up to and including this startpos.
216 ;; e.g. index=0 => 1 newline seen => line=2
218 ;; 1 char after the newline = column 0
219 (- charpos
(aref newlines index
) 1))
220 ;; zero newlines were seen
223 ;;;; CORE OUTPUT FUNCTIONS
225 ;;; Buffer the section of THING delimited by START and END by copying
226 ;;; to output buffer(s) of stream.
227 (defun buffer-output (stream thing start end
)
228 (declare (index start end
))
230 (error ":END before :START!"))
232 ;; Copy bytes from THING to buffers.
233 (flet ((copy-to-buffer (buffer tail count
)
234 (declare (buffer buffer
) (index tail count
))
236 (let ((sap (buffer-sap buffer
)))
239 (system-area-ub8-copy thing start sap tail count
))
240 ((simple-unboxed-array (*))
241 (copy-ub8-to-system-area thing start sap tail count
))))
242 ;; Not INCF! If another thread has moved tail from under
243 ;; us, we don't want to accidentally increment tail
244 ;; beyond buffer-length.
245 (setf (buffer-tail buffer
) (+ count tail
))
248 ;; First copy is special: the buffer may already contain
249 ;; something, or be even full.
250 (let* ((obuf (fd-stream-obuf stream
))
251 (tail (buffer-tail obuf
))
252 (space (- (buffer-length obuf
) tail
)))
254 (copy-to-buffer obuf tail
(min space
(- end start
)))
255 (go :more-output-p
)))
257 ;; Later copies should always have an empty buffer, since
258 ;; they are freshly flushed, but if another thread is
259 ;; stomping on the same buffer that might not be the case.
260 (let* ((obuf (flush-output-buffer stream
))
261 (tail (buffer-tail obuf
))
262 (space (- (buffer-length obuf
) tail
)))
263 (copy-to-buffer obuf tail
(min space
(- end start
))))
266 (go :flush-and-fill
))))))
268 (define-symbol-macro +write-failed
+ "Couldn't write to ~S")
270 ;;; Flush the current output buffer of the stream, ensuring that the
271 ;;; new buffer is empty. Returns (for convenience) the new output
272 ;;; buffer -- which may or may not be EQ to the old one. If the is no
273 ;;; queued output we try to write the buffer immediately -- otherwise
274 ;;; we queue it for later.
275 (defun flush-output-buffer (stream)
276 (let ((obuf (fd-stream-obuf stream
)))
278 (let ((head (buffer-head obuf
))
279 (tail (buffer-tail obuf
)))
280 (cond ((eql head tail
)
281 ;; Buffer is already empty -- just ensure that is is
282 ;; set to zero as well.
284 ((fd-stream-output-queue stream
)
285 ;; There is already stuff on the queue -- go directly
288 (%queue-and-replace-output-buffer stream
))
290 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
291 ;; whatever is left over. Otherwise wait until we can write.
293 (synchronize-stream-output stream
)
295 (let ((length (- tail head
)))
296 (multiple-value-bind (count errno
)
297 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
299 (flet ((queue-or-wait ()
300 (if (fd-stream-serve-events stream
)
301 (return (%queue-and-replace-output-buffer stream
))
302 (or (wait-until-fd-usable (fd-stream-fd stream
) :output
303 (fd-stream-timeout stream
)
305 (signal-timeout 'io-timeout
308 :seconds
(fd-stream-timeout stream
))))))
309 (cond ((eql count length
)
310 ;; Complete write -- we can use the same buffer.
311 (return (reset-buffer obuf
)))
313 ;; Partial write -- update buffer status and
316 (setf (buffer-head obuf
) head
)
319 ((eql errno sb
!unix
:ewouldblock
)
320 ;; Blocking, queue or wair.
322 ;; if interrupted on win32, just try again
323 #!+win32
((eql errno sb
!unix
:eintr
))
325 (simple-stream-perror +write-failed
+
326 stream errno
)))))))))))))
328 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
329 (defun %queue-and-replace-output-buffer
(stream)
330 (aver (fd-stream-serve-events stream
))
331 (let ((queue (fd-stream-output-queue stream
))
332 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
334 ;; Important: before putting the buffer on queue, give the stream
335 ;; a new one. If we get an interrupt and unwind losing the buffer
336 ;; is relatively OK, but having the same buffer in two places
338 (setf (fd-stream-obuf stream
) new
)
342 (setf (fd-stream-output-queue stream
) later
)))
343 (unless (fd-stream-handler stream
)
344 (setf (fd-stream-handler stream
)
345 (add-fd-handler (fd-stream-fd stream
)
348 (declare (ignore fd
))
349 (write-output-from-queue stream
)))))
352 ;;; This is called by the FD-HANDLER for the stream when output is
354 (defun write-output-from-queue (stream)
355 (aver (fd-stream-serve-events stream
))
356 (synchronize-stream-output stream
)
360 (let* ((buffer (pop (fd-stream-output-queue stream
)))
361 (head (buffer-head buffer
))
362 (length (- (buffer-tail buffer
) head
)))
363 (declare (index head length
))
365 (multiple-value-bind (count errno
)
366 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
368 (cond ((eql count length
)
369 ;; Complete write, see if we can do another right
370 ;; away, or remove the handler if we're done.
371 (release-buffer buffer
)
372 (cond ((fd-stream-output-queue stream
)
376 (let ((handler (fd-stream-handler stream
)))
378 (setf (fd-stream-handler stream
) nil
)
379 (remove-fd-handler handler
)))))
381 ;; Partial write. Update buffer status and requeue.
382 (aver (< count length
))
383 ;; Do not use INCF! Another thread might have moved head.
384 (setf (buffer-head buffer
) (+ head count
))
385 (push buffer
(fd-stream-output-queue stream
)))
387 ;; We tried to do multiple writes, and finally our
388 ;; luck ran out. Requeue.
389 (push buffer
(fd-stream-output-queue stream
)))
391 ;; Could not write on the first try at all!
393 (simple-stream-perror +write-failed
+ stream errno
)
395 (if (= errno sb
!unix
:ewouldblock
)
396 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
397 (simple-stream-perror +write-failed
+
401 ;;; Try to write THING directly to STREAM without buffering, if
402 ;;; possible. If direct write doesn't happen, buffer.
403 (defun write-or-buffer-output (stream thing start end
)
404 (declare (index start end
))
405 (cond ((fd-stream-output-queue stream
)
406 (buffer-output stream thing start end
))
408 (error ":END before :START!"))
410 (let ((length (- end start
)))
411 (synchronize-stream-output stream
)
412 (multiple-value-bind (count errno
)
413 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
414 (cond ((eql count length
)
415 ;; Complete write -- done!
418 (aver (< count length
))
419 ;; Partial write -- buffer the rest.
420 (buffer-output stream thing
(+ start count
) end
))
422 ;; Could not write -- buffer or error.
424 (simple-stream-perror +write-failed
+ stream errno
)
426 (if (= errno sb
!unix
:ewouldblock
)
427 (buffer-output stream thing start end
)
428 (simple-stream-perror +write-failed
+ stream errno
)))))))))
430 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
431 ;;; this is not something we want to export. Nikodemus thinks the
432 ;;; right thing is to support a low-level non-stream like IO layer,
433 ;;; akin to java.nio.
434 (declaim (inline output-raw-bytes
))
435 (define-deprecated-function :late
"1.0.8.16" output-raw-bytes write-sequence
436 (stream thing
&optional start end
)
437 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
439 ;;;; output routines and related noise
441 (defvar *output-routines
* ()
442 "List of all available output routines. Each element is a list of the
443 element-type output, the kind of buffering, the function name, and the number
444 of bytes per element.")
446 ;;; common idioms for reporting low-level stream and file problems
447 (defun simple-stream-perror (note-format stream errno
)
448 (declare (optimize allow-non-returning-tail-call
))
449 (error 'simple-stream-error
451 :format-control
"~@<~?: ~2I~_~A~:>"
452 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
453 (defun simple-file-perror (note-format pathname errno
)
454 (declare (optimize allow-non-returning-tail-call
))
455 (error 'simple-file-error
457 :format-control
"~@<~?: ~2I~_~A~:>"
459 (list note-format
(list pathname
) (strerror errno
))))
461 (defun c-string-encoding-error (external-format code
)
462 (declare (optimize allow-non-returning-tail-call
))
463 (error 'c-string-encoding-error
464 :external-format external-format
466 (defun c-string-decoding-error (external-format sap offset count
)
467 (declare (optimize allow-non-returning-tail-call
))
468 (error 'c-string-decoding-error
469 :external-format external-format
470 :octets
(sap-ref-octets sap offset count
)))
472 ;;; Returning true goes into end of file handling, false will enter another
473 ;;; round of input buffer filling followed by re-entering character decode.
474 (defun stream-decoding-error-and-handle (stream octet-count
)
476 (error 'stream-decoding-error
477 :external-format
(stream-external-format stream
)
479 :octets
(let ((buffer (fd-stream-ibuf stream
)))
480 (sap-ref-octets (buffer-sap buffer
)
484 :report
(lambda (stream)
486 "~@<Attempt to resync the stream at a ~
487 character boundary and continue.~@:>"))
488 (fd-stream-resync stream
)
490 (force-end-of-file ()
491 :report
(lambda (stream)
492 (format stream
"~@<Force an end of file.~@:>"))
493 (setf (fd-stream-eof-forced-p stream
) t
))
494 (input-replacement (string)
495 :report
(lambda (stream)
496 (format stream
"~@<Use string as replacement input, ~
497 attempt to resync at a character ~
498 boundary and continue.~@:>"))
499 :interactive
(lambda ()
500 (format *query-io
* "~@<Enter a string: ~@:>")
501 (finish-output *query-io
*)
502 (list (read *query-io
*)))
503 (let ((string (reverse (string string
)))
504 (instead (fd-stream-instead stream
)))
505 (dotimes (i (length string
))
506 (vector-push-extend (char string i
) instead
))
507 (fd-stream-resync stream
)
508 (when (> (length string
) 0)
509 (setf (fd-stream-listen stream
) t
)))
512 (defun stream-encoding-error-and-handle (stream code
)
514 (error 'stream-encoding-error
515 :external-format
(stream-external-format stream
)
519 :report
(lambda (stream)
520 (format stream
"~@<Skip output of this character.~@:>")))
521 (output-replacement (string)
522 :report
(lambda (stream)
523 (format stream
"~@<Output replacement string.~@:>"))
524 :interactive
(lambda ()
525 (format *query-io
* "~@<Enter a string: ~@:>")
526 (finish-output *query-io
*)
527 (list (read *query-io
*)))
528 (let ((string (string string
)))
529 (fd-sout stream
(string string
) 0 (length string
))))))
531 (defun %external-format-encoding-error
(stream code
)
533 (stream-encoding-error-and-handle stream code
)
534 (c-string-encoding-error stream code
)))
536 (defmacro external-format-encoding-error
(stream code
)
537 `(return-from output-nothing
(%external-format-encoding-error
,stream
,code
)))
539 (defun synchronize-stream-output (stream)
540 ;; If we're reading and writing on the same file, flush buffered
541 ;; input and rewind file position accordingly.
542 (unless (or (fd-stream-dual-channel-p stream
)
544 (eq (fd-stream-in stream
) #'ill-in
)
545 (eq (fd-stream-bin stream
) #'ill-bin
)))
546 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
547 (unless (eql 0 adjust
)
548 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
550 (defun fd-stream-output-finished-p (stream)
551 (let ((obuf (fd-stream-obuf stream
)))
553 (and (zerop (buffer-tail obuf
))
554 (not (fd-stream-output-queue stream
))))))
556 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
558 (let ((stream-var (gensym "STREAM")))
559 `(let* ((,stream-var
,stream
)
560 (obuf (fd-stream-obuf ,stream-var
))
561 (tail (buffer-tail obuf
))
563 ,(unless (eq (car buffering
) :none
)
564 `(when (< (buffer-length obuf
) (+ tail size
))
565 (setf obuf
(flush-output-buffer ,stream-var
)
566 tail
(buffer-tail obuf
))))
567 ,(unless (eq (car buffering
) :none
)
568 ;; FIXME: Why this here? Doesn't seem necessary.
569 `(synchronize-stream-output ,stream-var
))
571 `(block output-nothing
573 (setf (buffer-tail obuf
) (+ tail size
)))
576 (setf (buffer-tail obuf
) (+ tail size
))))
577 ,(ecase (car buffering
)
579 `(flush-output-buffer ,stream-var
))
581 `(when (eql byte
#\Newline
)
582 (flush-output-buffer ,stream-var
)))
586 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
587 (let ((stream-var (gensym "STREAM")))
588 `(let* ((,stream-var
,stream
)
589 (obuf (fd-stream-obuf ,stream-var
))
590 (tail (buffer-tail obuf
)))
591 ,(unless (eq (car buffering
) :none
)
592 `(when (< (buffer-length obuf
) (+ tail
,size
))
593 (setf obuf
(flush-output-buffer ,stream-var
)
594 tail
(buffer-tail obuf
))))
595 ;; FIXME: Why this here? Doesn't seem necessary.
596 ,(unless (eq (car buffering
) :none
)
597 `(synchronize-stream-output ,stream-var
))
599 `(block output-nothing
601 (setf (buffer-tail obuf
) (+ tail
,size
)))
604 (setf (buffer-tail obuf
) (+ tail
,size
))))
605 ,(ecase (car buffering
)
607 `(flush-output-buffer ,stream-var
))
609 `(when (eql byte
#\Newline
)
610 (flush-output-buffer ,stream-var
)))
614 (defmacro def-output-routines
/variable-width
615 ((name-fmt size restart external-format
&rest bufferings
)
617 (declare (optimize (speed 1)))
622 (intern (format nil name-fmt
(string (car buffering
))))))
624 (defun ,function
(stream byte
)
625 (declare (ignorable byte
))
626 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
628 (setf *output-routines
*
629 (nconc *output-routines
*
637 (cdr buffering
)))))))
640 ;;; Define output routines that output numbers SIZE bytes long for the
641 ;;; given bufferings. Use BODY to do the actual output.
642 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
644 (declare (optimize (speed 1)))
649 (intern (format nil name-fmt
(string (car buffering
))))))
651 (defun ,function
(stream byte
)
652 (output-wrapper (stream ,size
,buffering
,restart
)
654 (setf *output-routines
*
655 (nconc *output-routines
*
663 (cdr buffering
)))))))
666 ;;; FIXME: is this used anywhere any more?
667 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
673 (if (eql byte
#\Newline
)
674 (setf (fd-stream-output-column stream
) 0)
675 (incf (fd-stream-output-column stream
)))
676 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
679 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
682 (:none
(unsigned-byte 8))
683 (:full
(unsigned-byte 8)))
684 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
687 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
690 (:none
(signed-byte 8))
691 (:full
(signed-byte 8)))
692 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
695 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
698 (:none
(unsigned-byte 16))
699 (:full
(unsigned-byte 16)))
700 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
703 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
706 (:none
(signed-byte 16))
707 (:full
(signed-byte 16)))
708 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
711 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
714 (:none
(unsigned-byte 32))
715 (:full
(unsigned-byte 32)))
716 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
719 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
722 (:none
(signed-byte 32))
723 (:full
(signed-byte 32)))
724 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
729 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
732 (:none
(unsigned-byte 64))
733 (:full
(unsigned-byte 64)))
734 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
736 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
739 (:none
(signed-byte 64))
740 (:full
(signed-byte 64)))
741 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
744 ;;; the routine to use to output a string. If the stream is
745 ;;; unbuffered, slam the string down the file descriptor, otherwise
746 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
747 ;;; checking to see where the last newline was.
748 (defun fd-sout (stream thing start end
)
749 (declare (type fd-stream stream
) (type string thing
))
750 (let ((start (or start
0))
751 (end (or end
(length (the vector thing
)))))
752 (declare (fixnum start end
))
754 (string-dispatch (simple-base-string
756 (simple-array character
(*))
759 (position #\newline thing
:from-end t
760 :start start
:end end
))))
761 (if (and (typep thing
'base-string
)
762 (eq (fd-stream-external-format-keyword stream
) :latin-1
))
763 (ecase (fd-stream-buffering stream
)
765 (buffer-output stream thing start end
))
767 (buffer-output stream thing start end
)
769 (flush-output-buffer stream
)))
771 (write-or-buffer-output stream thing start end
)))
772 (ecase (fd-stream-buffering stream
)
773 (:full
(funcall (fd-stream-output-bytes stream
)
774 stream thing nil start end
))
775 (:line
(funcall (fd-stream-output-bytes stream
)
776 stream thing last-newline start end
))
777 (:none
(funcall (fd-stream-output-bytes stream
)
778 stream thing t start end
))))
780 (setf (fd-stream-output-column stream
) (- end last-newline
1))
781 (incf (fd-stream-output-column stream
) (- end start
))))))
783 (defstruct (external-format
784 (:constructor %make-external-format
)
786 (:predicate external-format-p
)
787 (:copier %copy-external-format
))
788 ;; All the names that can refer to this external format. The first
789 ;; one is the canonical name.
790 (names (missing-arg) :type list
:read-only t
)
791 (default-replacement-character (missing-arg) :type character
)
792 (read-n-chars-fun (missing-arg) :type function
)
793 (read-char-fun (missing-arg) :type function
)
794 (write-n-bytes-fun (missing-arg) :type function
)
795 (write-char-none-buffered-fun (missing-arg) :type function
)
796 (write-char-line-buffered-fun (missing-arg) :type function
)
797 (write-char-full-buffered-fun (missing-arg) :type function
)
798 ;; Can be nil for fixed-width formats.
799 (resync-fun nil
:type
(or function null
))
800 (bytes-for-char-fun (missing-arg) :type function
)
801 (read-c-string-fun (missing-arg) :type function
)
802 (write-c-string-fun (missing-arg) :type function
)
803 ;; We indirect through symbols in these functions so that a
804 ;; developer working on the octets code can easily redefine things
805 ;; and use the new function definition without redefining the
806 ;; external format as well. The slots above don't do any
807 ;; indirection because a developer working with those slots would be
808 ;; redefining the external format anyway.
809 (octets-to-string-fun (missing-arg) :type function
)
810 (string-to-octets-fun (missing-arg) :type function
))
812 (defun ef-char-size (ef-entry)
813 (if (variable-width-external-format-p ef-entry
)
814 (bytes-for-char-fun ef-entry
)
815 (funcall (bytes-for-char-fun ef-entry
) #\x
)))
817 (defun sb!alien
::string-to-c-string
(string external-format
)
818 (declare (type simple-string string
))
820 (declare (optimize (speed 3) (safety 0)))
821 (let ((external-format (get-external-format-or-lose external-format
)))
822 (funcall (ef-write-c-string-fun external-format
) string
))))
824 (defun sb!alien
::c-string-to-string
(sap external-format element-type
)
825 (declare (type system-area-pointer sap
))
827 (declare (optimize (speed 3) (safety 0)))
828 (let ((external-format (get-external-format-or-lose external-format
)))
829 (funcall (ef-read-c-string-fun external-format
) sap element-type
))))
831 (defun wrap-external-format-functions (external-format fun
)
832 (let ((result (%copy-external-format external-format
)))
833 (macrolet ((frob (accessor)
834 `(setf (,accessor result
) (funcall fun
(,accessor result
)))))
835 (frob ef-read-n-chars-fun
)
836 (frob ef-read-char-fun
)
837 (frob ef-write-n-bytes-fun
)
838 (frob ef-write-char-none-buffered-fun
)
839 (frob ef-write-char-line-buffered-fun
)
840 (frob ef-write-char-full-buffered-fun
)
842 (frob ef-bytes-for-char-fun
)
843 (frob ef-read-c-string-fun
)
844 (frob ef-write-c-string-fun
)
845 (frob ef-octets-to-string-fun
)
846 (frob ef-string-to-octets-fun
))
849 (define-load-time-global *external-formats
* (make-hash-table)
850 "Hashtable of all available external formats. The table maps from
851 external-format names to EXTERNAL-FORMAT structures.")
853 (defun get-external-format-or-lose (external-format)
854 (or (get-external-format external-format
)
855 (error "Undefined external-format: ~S" external-format
)))
857 (defun external-format-keyword (external-format)
858 (typecase external-format
859 (keyword external-format
)
860 ((cons keyword
) (car external-format
))))
862 (defun fd-stream-external-format-keyword (stream)
863 (external-format-keyword (fd-stream-external-format stream
)))
865 (defun canonize-external-format (external-format entry
)
866 (typecase external-format
867 (keyword (first (ef-names entry
)))
868 ((cons keyword
) (cons (first (ef-names entry
)) (rest external-format
)))))
870 ;;; Find an output routine to use given the type and buffering. Return
871 ;;; as multiple values the routine, the real type transfered, and the
872 ;;; number of bytes per element.
873 (defun pick-output-routine (type buffering
&optional external-format
)
874 (when (subtypep type
'character
)
875 (let ((entry (get-external-format-or-lose external-format
)))
876 (return-from pick-output-routine
877 (values (ecase buffering
878 (:none
(ef-write-char-none-buffered-fun entry
))
879 (:line
(ef-write-char-line-buffered-fun entry
))
880 (:full
(ef-write-char-full-buffered-fun entry
)))
883 (ef-write-n-bytes-fun entry
)
885 (canonize-external-format external-format entry
)))))
886 (dolist (entry *output-routines
*)
887 (when (and (subtypep type
(first entry
))
888 (eq buffering
(second entry
))
889 (or (not (fifth entry
))
890 (eq external-format
(fifth entry
))))
891 (return-from pick-output-routine
892 (values (symbol-function (third entry
))
895 ;; KLUDGE: dealing with the buffering here leads to excessive code
898 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
899 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
900 if
(subtypep type
`(unsigned-byte ,i
))
901 do
(return-from pick-output-routine
905 (lambda (stream byte
)
906 (output-wrapper (stream (/ i
8) (:none
) nil
)
907 (loop for j from
0 below
(/ i
8)
908 do
(setf (sap-ref-8 (buffer-sap obuf
)
910 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
912 (lambda (stream byte
)
913 (output-wrapper (stream (/ i
8) (:full
) nil
)
914 (loop for j from
0 below
(/ i
8)
915 do
(setf (sap-ref-8 (buffer-sap obuf
)
917 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
920 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
921 if
(subtypep type
`(signed-byte ,i
))
922 do
(return-from pick-output-routine
926 (lambda (stream byte
)
927 (output-wrapper (stream (/ i
8) (:none
) nil
)
928 (loop for j from
0 below
(/ i
8)
929 do
(setf (sap-ref-8 (buffer-sap obuf
)
931 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
933 (lambda (stream byte
)
934 (output-wrapper (stream (/ i
8) (:full
) 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
)))))))
942 ;;;; input routines and related noise
944 ;;; a list of all available input routines. Each element is a list of
945 ;;; the element-type input, the function name, and the number of bytes
947 (defvar *input-routines
* ())
949 ;;; Return whether a primitive partial read operation on STREAM's FD
950 ;;; would (probably) block. Signal a `simple-stream-error' if the
951 ;;; system call implementing this operation fails.
953 ;;; It is "may" instead of "would" because "would" is not quite
954 ;;; correct on win32. However, none of the places that use it require
955 ;;; further assurance than "may" versus "will definitely not".
956 (defun sysread-may-block-p (stream)
958 ;; This answers T at EOF on win32, I think.
959 (not (sb!win32
:handle-listen
(fd-stream-fd stream
)))
961 (not (sb!unix
:unix-simple-poll
(fd-stream-fd stream
) :input
0)))
963 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
964 ;;; then fill the input buffer, and return the number of bytes read. Throws
965 ;;; to EOF-INPUT-CATCHER if the eof was reached.
966 (defun refill-input-buffer (stream)
967 (let ((fd (fd-stream-fd stream
))
974 ;; Check for blocking input before touching the stream if we are to
975 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
976 ;; read(). Regular files should never block, so we can elide the check.
977 (if (and (neq :regular
(fd-stream-fd-type stream
))
978 (sysread-may-block-p stream
))
981 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
982 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
984 (closed-flame stream
)
986 (simple-stream-perror "couldn't read from ~S" stream errno
)
988 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
989 ;; to wait for input if read tells us EWOULDBLOCK.
990 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
)
991 (fd-stream-serve-events stream
))
992 (signal-timeout 'io-timeout
995 :seconds
(fd-stream-timeout stream
)))
997 ;; Since the read should not block, we'll disable the
998 ;; interrupts here, so that we don't accidentally unwind and
999 ;; leave the stream in an inconsistent state.
1001 ;; Execute the nlx outside without-interrupts to ensure the
1002 ;; resulting thunk is stack-allocatable.
1003 ((lambda (return-reason)
1004 (ecase return-reason
1005 ((nil)) ; fast path normal cases
1006 ((:wait-for-input
) (go #!-win32
:wait-for-input
#!+win32
:main
))
1007 ((:closed-flame
) (go :closed-flame
))
1008 ((:read-error
) (go :read-error
))))
1010 ;; Check the buffer: if it is null, then someone has closed
1011 ;; the stream from underneath us. This is not ment to fix
1012 ;; multithreaded races, but to deal with interrupt handlers
1013 ;; closing the stream.
1016 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
1017 (sap (buffer-sap ibuf
))
1018 (length (buffer-length ibuf
))
1019 (head (buffer-head ibuf
))
1020 (tail (buffer-tail ibuf
)))
1021 (declare (index length head tail
)
1022 (inline sb
!unix
:unix-read
))
1023 (unless (zerop head
)
1024 (cond ((eql head tail
)
1025 ;; Buffer is empty, but not at yet reset -- make it so.
1028 (reset-buffer ibuf
))
1030 ;; Buffer has things in it, but they are not at the
1031 ;; head -- move them there.
1032 (let ((n (- tail head
)))
1033 (system-area-ub8-copy sap head sap
0 n
)
1035 (buffer-head ibuf
) head
1037 (buffer-tail ibuf
) tail
)))))
1038 (setf (fd-stream-listen stream
) nil
)
1039 (setf (values count errno
)
1040 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
1043 #!+win32 sb
!unix
:eintr
1044 #!-win32 sb
!unix
:ewouldblock
)
1045 (return :wait-for-input
)
1046 (return :read-error
)))
1048 (setf (fd-stream-listen stream
) :eof
)
1049 (/show0
"THROWing EOF-INPUT-CATCHER")
1050 (throw 'eof-input-catcher nil
))
1052 ;; Success! (Do not use INCF, for sake of other threads.)
1053 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
1056 ;;; Make sure there are at least BYTES number of bytes in the input
1057 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1058 (defmacro input-at-least
(stream bytes
)
1059 (let ((stream-var (gensym "STREAM"))
1060 (bytes-var (gensym "BYTES"))
1061 (buffer-var (gensym "IBUF")))
1062 `(let* ((,stream-var
,stream
)
1064 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
1066 (when (>= (- (buffer-tail ,buffer-var
)
1067 (buffer-head ,buffer-var
))
1070 (refill-input-buffer ,stream-var
)))))
1072 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
1074 (let ((stream-var (gensym "STREAM"))
1075 (retry-var (gensym "RETRY"))
1076 (element-var (gensym "ELT")))
1077 `(let* ((,stream-var
,stream
)
1078 (ibuf (fd-stream-ibuf ,stream-var
))
1081 (when (fd-stream-eof-forced-p ,stream-var
)
1082 (setf (fd-stream-eof-forced-p ,stream-var
) nil
)
1083 (return-from use-instead
1084 (eof-or-lose ,stream-var
,eof-error
,eof-value
)))
1085 (let ((,element-var nil
)
1086 (decode-break-reason nil
))
1087 (do ((,retry-var t
))
1089 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1090 (let* ((instead (fd-stream-instead ,stream-var
))
1091 (result (vector-pop instead
))
1092 (pointer (fill-pointer instead
)))
1094 (setf (fd-stream-listen ,stream-var
) nil
))
1095 (return-from use-instead result
))
1097 (catch 'eof-input-catcher
1098 (setf decode-break-reason
1099 (block decode-break-reason
1100 (input-at-least ,stream-var
,(if (consp bytes
)
1102 `(setq size
,bytes
)))
1103 (let* ((byte (sap-ref-8 (buffer-sap ibuf
) (buffer-head ibuf
))))
1104 (declare (ignorable byte
))
1105 ,@(when (consp bytes
)
1106 `((let ((sap (buffer-sap ibuf
))
1107 (head (buffer-head ibuf
)))
1108 (declare (ignorable sap head
))
1109 (setq size
,(cadr bytes
))
1110 (input-at-least ,stream-var size
))))
1111 (setq ,element-var
(locally ,@read-forms
))
1112 (setq ,retry-var nil
))
1114 (when decode-break-reason
1115 (when (stream-decoding-error-and-handle
1116 stream decode-break-reason
)
1117 (setq ,retry-var nil
)
1118 (throw 'eof-input-catcher nil
)))
1120 (let ((octet-count (- (buffer-tail ibuf
)
1121 (buffer-head ibuf
))))
1122 (when (or (zerop octet-count
)
1123 (and (not ,element-var
)
1124 (not decode-break-reason
)
1125 (stream-decoding-error-and-handle
1126 stream octet-count
)))
1127 (setq ,retry-var nil
))))))
1129 (incf (buffer-head ibuf
) size
)
1132 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1134 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1135 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
1136 (let ((stream-var (gensym "STREAM"))
1137 (element-var (gensym "ELT")))
1138 `(let* ((,stream-var
,stream
)
1139 (ibuf (fd-stream-ibuf ,stream-var
)))
1140 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1141 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var
)
1143 (catch 'eof-input-catcher
1144 (input-at-least ,stream-var
,bytes
)
1145 (locally ,@read-forms
))))
1147 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1150 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1152 (defmacro def-input-routine
/variable-width
(name
1153 (type external-format size sap head
)
1156 (defun ,name
(stream eof-error eof-value
)
1157 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1158 (let ((,sap
(buffer-sap ibuf
))
1159 (,head
(buffer-head ibuf
)))
1161 (setf *input-routines
*
1162 (nconc *input-routines
*
1163 (list (list ',type
',name
1 ',external-format
))))))
1165 (defmacro def-input-routine
(name
1166 (type size sap head
)
1169 (defun ,name
(stream eof-error eof-value
)
1170 (input-wrapper (stream ,size eof-error eof-value
)
1171 (let ((,sap
(buffer-sap ibuf
))
1172 (,head
(buffer-head ibuf
)))
1174 (setf *input-routines
*
1175 (nconc *input-routines
*
1176 (list (list ',type
',name
',size nil
))))))
1178 ;;; STREAM-IN routine for reading a string char
1179 (def-input-routine input-character
1180 (character 1 sap head
)
1181 (code-char (sap-ref-8 sap head
)))
1183 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1184 (def-input-routine input-unsigned-8bit-byte
1185 ((unsigned-byte 8) 1 sap head
)
1186 (sap-ref-8 sap head
))
1188 ;;; STREAM-IN routine for reading a signed 8 bit number
1189 (def-input-routine input-signed-8bit-number
1190 ((signed-byte 8) 1 sap head
)
1191 (signed-sap-ref-8 sap head
))
1193 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1194 (def-input-routine input-unsigned-16bit-byte
1195 ((unsigned-byte 16) 2 sap head
)
1196 (sap-ref-16 sap head
))
1198 ;;; STREAM-IN routine for reading a signed 16 bit number
1199 (def-input-routine input-signed-16bit-byte
1200 ((signed-byte 16) 2 sap head
)
1201 (signed-sap-ref-16 sap head
))
1203 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1204 (def-input-routine input-unsigned-32bit-byte
1205 ((unsigned-byte 32) 4 sap head
)
1206 (sap-ref-32 sap head
))
1208 ;;; STREAM-IN routine for reading a signed 32 bit number
1209 (def-input-routine input-signed-32bit-byte
1210 ((signed-byte 32) 4 sap head
)
1211 (signed-sap-ref-32 sap head
))
1215 (def-input-routine input-unsigned-64bit-byte
1216 ((unsigned-byte 64) 8 sap head
)
1217 (sap-ref-64 sap head
))
1218 (def-input-routine input-signed-64bit-byte
1219 ((signed-byte 64) 8 sap head
)
1220 (signed-sap-ref-64 sap head
)))
1222 ;;; Find an input routine to use given the type. Return as multiple
1223 ;;; values the routine, the real type transfered, and the number of
1224 ;;; bytes per element (and for character types string input routine).
1225 (defun pick-input-routine (type &optional external-format
)
1226 (when (subtypep type
'character
)
1227 (let ((entry (get-external-format-or-lose external-format
)))
1228 (return-from pick-input-routine
1229 (values (ef-read-char-fun entry
)
1232 (ef-read-n-chars-fun entry
)
1233 (ef-char-size entry
)
1234 (canonize-external-format external-format entry
)))))
1235 (dolist (entry *input-routines
*)
1236 (when (and (subtypep type
(first entry
))
1237 (or (not (fourth entry
))
1238 (eq external-format
(fourth entry
))))
1239 (return-from pick-input-routine
1240 (values (symbol-function (second entry
))
1243 ;; FIXME: let's do it the hard way, then (but ignore things like
1244 ;; endianness, efficiency, and the necessary coupling between these
1245 ;; and the output routines). -- CSR, 2004-02-09
1246 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1247 if
(subtypep type
`(unsigned-byte ,i
))
1248 do
(return-from pick-input-routine
1250 (lambda (stream eof-error eof-value
)
1251 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1252 (let ((sap (buffer-sap ibuf
))
1253 (head (buffer-head ibuf
)))
1254 (loop for j from
0 below
(/ i
8)
1258 (sap-ref-8 sap
(+ head j
))))
1259 finally
(return result
)))))
1262 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1263 if
(subtypep type
`(signed-byte ,i
))
1264 do
(return-from pick-input-routine
1266 (lambda (stream eof-error eof-value
)
1267 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1268 (let ((sap (buffer-sap ibuf
))
1269 (head (buffer-head ibuf
)))
1270 (loop for j from
0 below
(/ i
8)
1274 (sap-ref-8 sap
(+ head j
))))
1275 finally
(return (if (logbitp (1- i
) result
)
1276 (dpb result
(byte i
0) -
1)
1281 ;;; the N-BIN method for FD-STREAMs
1283 ;;; Note that this blocks in UNIX-READ. It is generally used where
1284 ;;; there is a definite amount of reading to be done, so blocking
1285 ;;; isn't too problematical.
1286 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1287 &aux
(total-copied 0))
1288 (declare (type fd-stream stream
))
1289 (declare (type index start requested total-copied
))
1290 (aver (= (length (fd-stream-instead stream
)) 0))
1293 (let* ((remaining-request (- requested total-copied
))
1294 (ibuf (fd-stream-ibuf stream
))
1295 (head (buffer-head ibuf
))
1296 (tail (buffer-tail ibuf
))
1297 (available (- tail head
))
1298 (n-this-copy (min remaining-request available
))
1299 (this-start (+ start total-copied
))
1300 (this-end (+ this-start n-this-copy
))
1301 (sap (buffer-sap ibuf
)))
1302 (declare (type index remaining-request head tail available
))
1303 (declare (type index n-this-copy
))
1305 ;; Prevent failure caused by memmove() hitting a write-protected page
1306 ;; and the fault handler losing, since it thinks you're not in Lisp.
1307 ;; This is wasteful, but better than being randomly broken (lp#1366263).
1308 (when (> this-end this-start
)
1310 (system-area-pointer
1311 (setf (sap-ref-8 buffer this-start
) (sap-ref-8 buffer this-start
)
1312 (sap-ref-8 buffer
(1- this-end
)) (sap-ref-8 buffer
(1- this-end
))))
1313 ((simple-array (unsigned-byte 8) (*))
1314 (setf (aref buffer this-start
) (aref buffer this-start
)
1315 (aref buffer
(1- this-end
)) (aref buffer
(1- this-end
))))
1316 ((simple-array * (*))
1317 ;; We might have an array of UNSIGNED-BYTE-32 here, but the
1318 ;; bounding indices act as if it were UNSIGNED-BYTE-8.
1319 ;; This is strange, and in direct contradiction to what %BYTE-BLT
1320 ;; believes it accepts. i.e. according to the comments,
1321 ;; it's for want of error checking that this works at all.
1322 (with-pinned-objects (buffer)
1323 (let ((sap (vector-sap buffer
)))
1324 (setf (sap-ref-8 sap this-start
) (sap-ref-8 sap this-start
)
1325 (sap-ref-8 sap
(1- this-end
)) (sap-ref-8 sap
(1- this-end
))))))))
1326 ;; Copy data from stream buffer into user's buffer.
1327 (%byte-blt sap head buffer this-start this-end
)
1328 (incf (buffer-head ibuf
) n-this-copy
)
1329 (incf total-copied n-this-copy
)
1330 ;; Maybe we need to refill the stream buffer.
1331 (cond (;; If there were enough data in the stream buffer, we're done.
1332 (eql total-copied requested
)
1333 (return total-copied
))
1334 (;; If EOF, we're done in another way.
1335 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1337 (error 'end-of-file
:stream stream
)
1338 (return total-copied
)))
1339 ;; Otherwise we refilled the stream buffer, so fall
1340 ;; through into another pass of the loop.
1343 (defun fd-stream-resync (stream)
1344 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1346 (funcall (ef-resync-fun entry
) stream
))))
1348 (defun get-fd-stream-character-sizer (stream)
1349 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1351 (ef-bytes-for-char-fun entry
))))
1353 (defun fd-stream-character-size (stream char
)
1354 (let ((sizer (get-fd-stream-character-sizer stream
)))
1355 (when sizer
(funcall sizer char
))))
1357 (defun fd-stream-string-size (stream string
)
1358 (let ((sizer (get-fd-stream-character-sizer stream
)))
1360 (loop for char across string summing
(funcall sizer char
)))))
1362 (defun find-external-format (external-format)
1363 (when external-format
1364 (get-external-format external-format
)))
1366 (defun variable-width-external-format-p (ef-entry)
1367 (and ef-entry
(not (null (ef-resync-fun ef-entry
)))))
1369 (defun bytes-for-char-fun (ef-entry)
1370 (if ef-entry
(ef-bytes-for-char-fun ef-entry
) (constantly 1)))
1372 (defmacro define-unibyte-mapping-external-format
1373 (canonical-name (&rest other-names
) &body exceptions
)
1374 (let ((->code-name
(symbolicate canonical-name
'-
>code-mapper
))
1375 (code->-name
(symbolicate 'code-
> canonical-name
'-mapper
))
1376 (get-bytes-name (symbolicate 'get- canonical-name
'-bytes
))
1377 (string->-name
(symbolicate 'string-
> canonical-name
))
1378 (define-string*-name
(symbolicate 'define- canonical-name
'-
>string
*))
1379 (string*-name
(symbolicate canonical-name
'-
>string
*))
1380 (define-string-name (symbolicate 'define- canonical-name
'-
>string
))
1381 (string-name (symbolicate canonical-name
'-
>string
))
1382 (->string-aref-name
(symbolicate canonical-name
'-
>string-aref
)))
1384 (define-unibyte-mapper ,-
>code-name
,code-
>-name
1386 (declaim (inline ,get-bytes-name
))
1387 (defun ,get-bytes-name
(string pos
)
1388 (declare (optimize speed
(safety 0))
1389 (type simple-string string
)
1390 (type array-range pos
))
1391 (get-latin-bytes #',code-
>-name
,canonical-name string pos
))
1392 (defun ,string-
>-name
(string sstart send null-padding
)
1393 (declare (optimize speed
(safety 0))
1394 (type simple-string string
)
1395 (type array-range sstart send
))
1396 (values (string->latin% string sstart send
#',get-bytes-name null-padding
)))
1397 (defmacro ,define-string
*-name
(accessor type
)
1398 (declare (ignore type
))
1399 (let ((name (make-od-name ',string
*-name accessor
)))
1401 (defun ,name
(string sstart send array astart aend
)
1402 (,(make-od-name 'latin-
>string
* accessor
)
1403 string sstart send array astart aend
#',',-
>code-name
)))))
1404 (instantiate-octets-definition ,define-string
*-name
)
1405 (defmacro ,define-string-name
(accessor type
)
1406 (declare (ignore type
))
1407 (let ((name (make-od-name ',string-name accessor
)))
1409 (defun ,name
(array astart aend
)
1410 (,(make-od-name 'latin-
>string accessor
)
1411 array astart aend
#',',-
>code-name
)))))
1412 (instantiate-octets-definition ,define-string-name
)
1413 (define-unibyte-external-format ,canonical-name
,other-names
1414 (let ((octet (,code-
>-name bits
)))
1416 (setf (sap-ref-8 sap tail
) octet
)
1417 (external-format-encoding-error stream bits
)))
1418 (let ((code (,-
>code-name byte
)))
1421 (return-from decode-break-reason
1)))
1425 (defmacro define-unibyte-external-format
1426 (canonical-name (&rest other-names
)
1427 out-form in-form octets-to-string-symbol string-to-octets-symbol
)
1428 `(define-external-format/variable-width
(,canonical-name
,@other-names
)
1433 ,octets-to-string-symbol
1434 ,string-to-octets-symbol
))
1436 (defmacro define-external-format
/variable-width
1437 (external-format output-restart replacement-character
1438 out-size-expr out-expr in-size-expr in-expr
1439 octets-to-string-sym string-to-octets-sym
1440 &key base-string-direct-mapping
)
1441 (let* ((name (first external-format
))
1442 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1443 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1444 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1445 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1446 (resync-function (symbolicate "RESYNC/" name
))
1447 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1448 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1449 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1450 (n-buffer (gensym "BUFFER")))
1452 (defun ,size-function
(byte)
1453 (declare (ignorable byte
))
1455 (defun ,out-function
(stream string flush-p start end
)
1456 (let ((start (or start
0))
1457 (end (or end
(length string
))))
1458 (declare (type index start end
))
1459 (synchronize-stream-output stream
)
1460 (unless (<= 0 start end
(length string
))
1461 (sequence-bounding-indices-bad-error string start end
))
1464 (let ((obuf (fd-stream-obuf stream
)))
1465 (string-dispatch (simple-base-string
1466 #!+sb-unicode
(simple-array character
(*))
1469 (let ((len (buffer-length obuf
))
1470 (sap (buffer-sap obuf
))
1472 (tail (buffer-tail obuf
)))
1473 (declare (type index tail
)
1474 ;; STRING bounds have already been checked.
1475 (optimize (safety 0)))
1476 (,@(if output-restart
1477 `(block output-nothing
)
1480 ((or (= start end
) (< (- len tail
) 4)))
1481 (let* ((byte (aref string start
))
1482 (bits (char-code byte
))
1483 (size ,out-size-expr
))
1486 (setf (buffer-tail obuf
) tail
)
1489 ;; Exited via RETURN-FROM OUTPUT-NOTHING: skip the current character.
1493 (flush-output-buffer stream
)))
1495 (flush-output-buffer stream
))))
1496 (def-output-routines/variable-width
(,format
1503 (if (eql byte
#\Newline
)
1504 (setf (fd-stream-output-column stream
) 0)
1505 (setf (fd-stream-output-column stream
)
1506 (+ (truly-the unsigned-byte
(fd-stream-output-column stream
)) 1)))
1507 (let ((bits (char-code byte
))
1508 (sap (buffer-sap obuf
))
1509 (tail (buffer-tail obuf
)))
1511 (defun ,in-function
(stream buffer start requested eof-error-p
1512 &aux
(total-copied 0))
1513 (declare (type fd-stream stream
)
1514 (type index start requested total-copied
)
1516 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1518 (when (fd-stream-eof-forced-p stream
)
1519 (setf (fd-stream-eof-forced-p stream
) nil
)
1520 (return-from ,in-function
0))
1521 (do ((instead (fd-stream-instead stream
)))
1522 ((= (fill-pointer instead
) 0)
1523 (setf (fd-stream-listen stream
) nil
))
1524 (setf (aref buffer
(+ start total-copied
)) (vector-pop instead
))
1526 (when (= requested total-copied
)
1527 (when (= (fill-pointer instead
) 0)
1528 (setf (fd-stream-listen stream
) nil
))
1529 (return-from ,in-function total-copied
)))
1532 (let* ((ibuf (fd-stream-ibuf stream
))
1533 (head (buffer-head ibuf
))
1534 (tail (buffer-tail ibuf
))
1535 (sap (buffer-sap ibuf
))
1536 (decode-break-reason nil
))
1537 (declare (type index head tail
))
1538 ;; Copy data from stream buffer into user's buffer.
1539 (do ((size nil nil
))
1540 ((or (= tail head
) (= requested total-copied
)))
1541 (setf decode-break-reason
1542 (block decode-break-reason
1543 ,@(when (consp in-size-expr
)
1544 `((when (> ,(car in-size-expr
) (- tail head
))
1546 (let ((byte (sap-ref-8 sap head
)))
1547 (declare (ignorable byte
))
1548 (setq size
,(if (consp in-size-expr
) (cadr in-size-expr
) in-size-expr
))
1549 (when (> size
(- tail head
))
1551 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1555 (setf (buffer-head ibuf
) head
)
1556 (when decode-break-reason
1557 ;; If we've already read some characters on when the invalid
1558 ;; code sequence is detected, we return immediately. The
1559 ;; handling of the error is deferred until the next call
1560 ;; (where this check will be false). This allows establishing
1561 ;; high-level handlers for decode errors (for example
1562 ;; automatically resyncing in Lisp comments).
1563 (when (plusp total-copied
)
1564 (return-from ,in-function total-copied
))
1565 (when (stream-decoding-error-and-handle
1566 stream decode-break-reason
)
1568 (error 'end-of-file
:stream stream
)
1569 (return-from ,in-function total-copied
)))
1570 ;; we might have been given stuff to use instead, so
1571 ;; we have to return (and trust our caller to know
1572 ;; what to do about TOTAL-COPIED being 0).
1573 (return-from ,in-function total-copied
)))
1574 (setf (buffer-head ibuf
) head
)
1575 ;; Maybe we need to refill the stream buffer.
1576 (cond ( ;; If was data in the stream buffer, we're done.
1577 (plusp total-copied
)
1578 (return total-copied
))
1579 ( ;; If EOF, we're done in another way.
1580 (or (eq decode-break-reason
'eof
)
1581 (null (catch 'eof-input-catcher
1582 (refill-input-buffer stream
))))
1584 (error 'end-of-file
:stream stream
)
1585 (return total-copied
)))
1586 ;; Otherwise we refilled the stream buffer, so fall
1587 ;; through into another pass of the loop.
1589 (def-input-routine/variable-width
,in-char-function
(character
1593 (let ((byte (sap-ref-8 sap head
)))
1594 (declare (ignorable byte
))
1596 (defun ,resync-function
(stream)
1597 (let ((ibuf (fd-stream-ibuf stream
))
1599 (catch 'eof-input-catcher
1601 (incf (buffer-head ibuf
))
1602 (input-at-least stream
,(if (consp in-size-expr
) (car in-size-expr
) `(setq size
,in-size-expr
)))
1603 (unless (block decode-break-reason
1604 (let* ((sap (buffer-sap ibuf
))
1605 (head (buffer-head ibuf
))
1606 (byte (sap-ref-8 sap head
)))
1607 (declare (ignorable byte
))
1608 ,@(when (consp in-size-expr
)
1609 `((setq size
,(cadr in-size-expr
))
1610 (input-at-least stream size
)))
1611 (setf head
(buffer-head ibuf
))
1615 (defun ,read-c-string-function
(sap element-type
)
1616 (declare (type system-area-pointer sap
))
1618 (declare (optimize (speed 3) (safety 0)))
1619 (let* ((stream ,name
)
1620 (size 0) (head 0) (byte 0) (char nil
)
1621 (decode-break-reason nil
)
1622 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1623 (setf decode-break-reason
1624 (block decode-break-reason
1625 (setf byte
(sap-ref-8 sap head
)
1626 size
,(if (consp in-size-expr
)
1632 (when decode-break-reason
1633 (c-string-decoding-error
1634 ,name sap head decode-break-reason
))
1635 (when (zerop (char-code char
))
1637 (string (case element-type
1639 (make-string length
:element-type
'base-char
))
1641 (make-string length
:element-type
'character
))
1643 (make-string length
:element-type element-type
)))))
1644 (declare (ignorable stream
)
1645 (type index head length
) ;; size
1646 (type (unsigned-byte 8) byte
)
1647 (type (or null character
) char
)
1648 (type string string
))
1650 (dotimes (index length string
)
1651 (setf decode-break-reason
1652 (block decode-break-reason
1653 (setf byte
(sap-ref-8 sap head
)
1654 size
,(if (consp in-size-expr
)
1660 (when decode-break-reason
1661 (c-string-decoding-error
1662 ,name sap head decode-break-reason
))
1663 (setf (aref string index
) char
)))))
1665 (defun ,output-c-string-function
(string)
1666 (declare (type simple-string string
))
1667 (cond ,@(and base-string-direct-mapping
1668 `(((simple-base-string-p string
)
1672 (declare (optimize (speed 3) (safety 0)))
1673 (block output-nothing
1674 (let* ((length (length string
))
1675 (null-size (let* ((byte (code-char 0))
1676 (bits (char-code byte
)))
1677 (declare (ignorable byte bits
))
1678 (the index
,out-size-expr
)))
1680 (+ (loop for i of-type index below length
1681 for byte of-type character
= (aref string i
)
1682 for bits
= (char-code byte
)
1683 sum
(the index
,out-size-expr
) of-type index
)
1686 (,n-buffer
(make-array buffer-length
1687 :element-type
'(unsigned-byte 8)))
1689 (declare (type index length buffer-length tail
)
1692 (with-pinned-objects (,n-buffer
)
1693 (let ((sap (vector-sap ,n-buffer
)))
1694 (declare (system-area-pointer sap
))
1695 (loop for i of-type index below length
1696 for byte of-type character
= (aref string i
)
1697 for bits
= (char-code byte
)
1698 for size of-type index
= ,out-size-expr
1703 (byte (code-char bits
))
1705 (declare (ignorable bits byte size
))
1709 (let ((entry (%make-external-format
1710 :names
',external-format
1711 :default-replacement-character
,replacement-character
1712 :read-n-chars-fun
#',in-function
1713 :read-char-fun
#',in-char-function
1714 :write-n-bytes-fun
#',out-function
1715 ,@(mapcan #'(lambda (buffering)
1716 (list (intern (format nil
"WRITE-CHAR-~A-BUFFERED-FUN" buffering
) :keyword
)
1717 `#',(intern (format nil format
(string buffering
)))))
1718 '(:none
:line
:full
))
1719 :resync-fun
#',resync-function
1720 :bytes-for-char-fun
#',size-function
1721 :read-c-string-fun
#',read-c-string-function
1722 :write-c-string-fun
#',output-c-string-function
1723 :octets-to-string-fun
(lambda (&rest rest
)
1724 (declare (dynamic-extent rest
))
1725 (apply ',octets-to-string-sym rest
))
1726 :string-to-octets-fun
(lambda (&rest rest
)
1727 (declare (dynamic-extent rest
))
1728 (apply ',string-to-octets-sym rest
)))))
1729 (dolist (ef ',external-format
)
1730 (setf (gethash ef
*external-formats
*) entry
))))))
1732 ;;;; utility functions (misc routines, etc)
1734 ;;; Fill in the various routine slots for the given type. INPUT-P and
1735 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1736 ;;; set prior to calling this routine.
1737 (defun set-fd-stream-routines (fd-stream element-type external-format
1738 input-p output-p buffer-p
)
1739 (let* ((target-type (case element-type
1740 (unsigned-byte '(unsigned-byte 8))
1741 (signed-byte '(signed-byte 8))
1742 (:default
'character
)
1744 (character-stream-p (subtypep target-type
'character
))
1745 (bivalent-stream-p (eq element-type
:default
))
1746 normalized-external-format
1748 (bin-routine #'ill-bin
)
1751 (cin-routine #'ill-in
)
1754 (input-type nil
) ;calculated from bin-type/cin-type
1755 (input-size nil
) ;calculated from bin-size/cin-size
1756 (read-n-characters #'ill-in
)
1757 (bout-routine #'ill-bout
)
1760 (cout-routine #'ill-out
)
1765 (output-bytes #'ill-bout
))
1767 ;; Ensure that we have buffers in the desired direction(s) only,
1768 ;; getting new ones and dropping/resetting old ones as necessary.
1769 (let ((obuf (fd-stream-obuf fd-stream
)))
1773 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1775 (setf (fd-stream-obuf fd-stream
) nil
)
1776 (release-buffer obuf
))))
1778 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1782 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1784 (setf (fd-stream-ibuf fd-stream
) nil
)
1785 (release-buffer ibuf
))))
1787 ;; FIXME: Why only for output? Why unconditionally?
1789 (setf (fd-stream-output-column fd-stream
) 0))
1791 (when (and character-stream-p
(eq external-format
:default
))
1792 (/show0
"/getting default external format")
1793 (setf external-format
(default-external-format)))
1796 (flet ((no-input-routine ()
1797 (error "could not find any input routine for ~
1798 ~/sb!impl:print-type-specifier/"
1800 (when (or (not character-stream-p
) bivalent-stream-p
)
1801 (setf (values bin-routine bin-type bin-size read-n-characters
1802 char-size normalized-external-format
)
1803 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1806 (unless bin-routine
(no-input-routine)))
1807 (when character-stream-p
1808 (setf (values cin-routine cin-type cin-size read-n-characters
1809 char-size normalized-external-format
)
1810 (pick-input-routine target-type external-format
))
1811 (unless cin-routine
(no-input-routine))))
1812 (setf (fd-stream-in fd-stream
) cin-routine
1813 (fd-stream-bin fd-stream
) bin-routine
)
1814 ;; character type gets preferential treatment
1815 (setf input-size
(or cin-size bin-size
))
1816 (setf input-type
(or cin-type bin-type
))
1817 (when normalized-external-format
1818 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1819 (fd-stream-char-size fd-stream
) char-size
))
1820 (when (= (or cin-size
1) (or bin-size
1) 1)
1821 (setf (fd-stream-n-bin fd-stream
) ;XXX
1822 (if (and character-stream-p
(not bivalent-stream-p
))
1824 #'fd-stream-read-n-bytes
))
1825 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1826 ;; for character and (unsigned-byte 8) streams. In these
1827 ;; cases, fast-read-* will read from the
1828 ;; ansi-stream-(c)in-buffer, saving function calls.
1829 ;; Otherwise, the various data-reading functions in the stream
1830 ;; structure will be called.
1832 (not bivalent-stream-p
)
1833 ;; temporary disable on :io streams
1835 (cond (character-stream-p
1836 (setf (ansi-stream-cin-buffer fd-stream
)
1837 (make-array +ansi-stream-in-buffer-length
+
1838 :element-type
'character
)))
1839 ((equal target-type
'(unsigned-byte 8))
1840 (setf (ansi-stream-in-buffer fd-stream
)
1841 (make-array +ansi-stream-in-buffer-length
+
1842 :element-type
'(unsigned-byte 8))))))))
1845 (when (or (not character-stream-p
) bivalent-stream-p
)
1846 (setf (values bout-routine bout-type bout-size output-bytes
1847 char-size normalized-external-format
)
1848 (let ((buffering (fd-stream-buffering fd-stream
)))
1849 (if bivalent-stream-p
1850 (pick-output-routine '(unsigned-byte 8)
1851 (if (eq :line buffering
)
1855 (pick-output-routine target-type buffering external-format
))))
1856 (unless bout-routine
1857 (error "could not find any output routine for ~S buffered ~S"
1858 (fd-stream-buffering fd-stream
)
1860 (when character-stream-p
1861 (setf (values cout-routine cout-type cout-size output-bytes
1862 char-size normalized-external-format
)
1863 (pick-output-routine target-type
1864 (fd-stream-buffering fd-stream
)
1866 (unless cout-routine
1867 (error "could not find any output routine for ~S buffered ~S"
1868 (fd-stream-buffering fd-stream
)
1870 (when normalized-external-format
1871 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1872 (fd-stream-char-size fd-stream
) char-size
))
1873 (when character-stream-p
1874 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1875 (setf (fd-stream-out fd-stream
) cout-routine
1876 (fd-stream-bout fd-stream
) bout-routine
1877 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1878 #'fd-sout
#'ill-out
))
1879 (setf output-size
(or cout-size bout-size
))
1880 (setf output-type
(or cout-type bout-type
)))
1882 (when (and input-size output-size
1883 (not (eq input-size output-size
)))
1884 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1885 input-type input-size
1886 output-type output-size
))
1887 (setf (fd-stream-element-size fd-stream
)
1888 (or input-size output-size
))
1890 (setf (fd-stream-element-type fd-stream
)
1891 (cond ((equal input-type output-type
)
1897 ((subtypep input-type output-type
)
1899 ((subtypep output-type input-type
)
1902 (error "Input type (~/sb!impl:print-type-specifier/) and
1903 output type (~/sb!impl:print-type-specifier/) ~
1905 input-type output-type
))))))
1907 ;;; Handles the resource-release aspects of stream closing, and marks
1909 (defun release-fd-stream-resources (fd-stream)
1912 ;; Drop handlers first.
1913 (when (fd-stream-handler fd-stream
)
1914 (remove-fd-handler (fd-stream-handler fd-stream
))
1915 (setf (fd-stream-handler fd-stream
) nil
))
1916 ;; Disable interrupts so that a asynch unwind will not leave
1917 ;; us with a dangling finalizer (that would close the same
1918 ;; --possibly reassigned-- FD again), or a stream with a closed
1919 ;; FD that appears open.
1920 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1921 (set-closed-flame fd-stream
)
1922 (cancel-finalization fd-stream
))
1923 ;; On error unwind from WITHOUT-INTERRUPTS.
1924 (serious-condition (e)
1926 ;; Release all buffers. If this is undone, or interrupted,
1927 ;; we're still safe: buffers have finalizers of their own.
1928 (release-fd-stream-buffers fd-stream
))
1930 ;;; Flushes the current input buffer and any supplied replacements,
1931 ;;; and returns the input buffer, and the amount of flushed input in
1933 (defun flush-input-buffer (stream)
1934 (let* ((instead (fd-stream-instead stream
))
1935 (unread (length instead
)))
1936 ;; (setf fill-pointer) performs some checks and is slower
1937 (setf (%array-fill-pointer instead
) 0)
1938 (let ((ibuf (fd-stream-ibuf stream
)))
1940 (let ((head (buffer-head ibuf
))
1941 (tail (buffer-tail ibuf
)))
1942 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1943 (values nil unread
)))))
1945 (defun fd-stream-clear-input (stream)
1946 (flush-input-buffer stream
)
1949 (sb!win32
:handle-clear-input
(fd-stream-fd stream
))
1950 (setf (fd-stream-listen stream
) nil
))
1952 (catch 'eof-input-catcher
1953 (loop until
(sysread-may-block-p stream
)
1955 (refill-input-buffer stream
)
1956 (reset-buffer (fd-stream-ibuf stream
)))
1959 ;;; Handle miscellaneous operations on FD-STREAM.
1960 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
1961 (declare (ignore arg2
))
1964 (labels ((do-listen ()
1965 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1966 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
1967 (fd-stream-listen fd-stream
)
1969 (sb!win32
:handle-listen
(fd-stream-fd fd-stream
))
1971 ;; If the read can block, LISTEN will certainly return NIL.
1972 (if (sysread-may-block-p fd-stream
)
1974 ;; Otherwise select(2) and CL:LISTEN have slightly
1975 ;; different semantics. The former returns that an FD
1976 ;; is readable when a read operation wouldn't block.
1977 ;; That includes EOF. However, LISTEN must return NIL
1979 (progn (catch 'eof-input-catcher
1980 ;; r-b/f too calls select, but it shouldn't
1981 ;; block as long as read can return once w/o
1983 (refill-input-buffer fd-stream
))
1984 ;; At this point either IBUF-HEAD != IBUF-TAIL
1985 ;; and FD-STREAM-LISTEN is NIL, in which case
1986 ;; we should return T, or IBUF-HEAD ==
1987 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1988 ;; which case we should return :EOF for this
1989 ;; call and all future LISTEN call on this stream.
1990 ;; Call ourselves again to determine which case
1995 (decf (buffer-head (fd-stream-ibuf fd-stream
))
1996 (fd-stream-character-size fd-stream arg1
)))
1998 ;; Drop input buffers
1999 (setf (ansi-stream-in-index fd-stream
) +ansi-stream-in-buffer-length
+
2000 (ansi-stream-cin-buffer fd-stream
) nil
2001 (ansi-stream-in-buffer fd-stream
) nil
)
2003 ;; We got us an abort on our hands.
2004 (let ((outputp (fd-stream-obuf fd-stream
))
2005 (file (fd-stream-file fd-stream
))
2006 (orig (fd-stream-original fd-stream
)))
2007 ;; This takes care of the important stuff -- everything
2008 ;; rest is cleaning up the file-system, which we cannot
2009 ;; do on some platforms as long as the file is open.
2010 (release-fd-stream-resources fd-stream
)
2011 ;; We can't do anything unless we know what file were
2012 ;; dealing with, and we don't want to do anything
2013 ;; strange unless we were writing to the file.
2014 (when (and outputp file
)
2016 ;; If the original is EQ to file we are appending to
2017 ;; and can just close the file without renaming.
2018 (unless (eq orig file
)
2019 ;; We have a handle on the original, just revert.
2020 (multiple-value-bind (okay err
)
2021 (sb!unix
:unix-rename orig file
)
2022 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2023 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2026 (error 'simple-stream-error
2028 "~@<Couldn't restore ~S to its original contents ~
2029 from ~S while closing ~S: ~2I~_~A~:>"
2031 (list file orig fd-stream
(strerror err
))
2032 :stream fd-stream
))))
2033 ;; We can't restore the original, and aren't
2034 ;; appending, so nuke that puppy.
2036 ;; FIXME: This is currently the fate of superseded
2037 ;; files, and according to the CLOSE spec this is
2038 ;; wrong. However, there seems to be no clean way to
2039 ;; do that that doesn't involve either copying the
2040 ;; data (bad if the :abort resulted from a full
2041 ;; disk), or renaming the old file temporarily
2042 ;; (probably bad because stream opening becomes more
2044 (multiple-value-bind (okay err
)
2045 (sb!unix
:unix-unlink file
)
2047 (error 'simple-file-error
2050 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2052 (list file fd-stream
(strerror err
)))))))))
2054 (finish-fd-stream-output fd-stream
)
2055 (let ((orig (fd-stream-original fd-stream
)))
2056 (when (and orig
(fd-stream-delete-original fd-stream
))
2057 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2059 (error 'simple-file-error
2062 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2064 (list orig fd-stream
(strerror err
)))))))
2065 ;; In case of no-abort close, don't *really* close the
2066 ;; stream until the last moment -- the cleaning up of the
2067 ;; original can be done first.
2068 (release-fd-stream-resources fd-stream
))))
2070 (fd-stream-clear-input fd-stream
))
2072 (flush-output-buffer fd-stream
))
2074 (finish-fd-stream-output fd-stream
))
2076 (fd-stream-element-type fd-stream
))
2078 (fd-stream-element-mode fd-stream
))
2080 (fd-stream-external-format fd-stream
))
2082 (plusp (the (integer 0)
2083 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2087 (fd-stream-output-column fd-stream
))
2089 (unless (fd-stream-file fd-stream
)
2090 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2091 ;; "should signal an error of type TYPE-ERROR if stream is not
2092 ;; a stream associated with a file". Too bad there's no very
2093 ;; appropriate value for the EXPECTED-TYPE slot..
2094 (error 'simple-type-error
2096 :expected-type
'fd-stream
2097 :format-control
"~S is not a stream associated with a file."
2098 :format-arguments
(list fd-stream
)))
2100 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2101 atime mtime ctime blksize blocks
)
2102 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2103 (declare (ignore ino nlink uid gid rdev
2104 atime mtime ctime blksize blocks
))
2106 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2109 (truncate size
(fd-stream-element-size fd-stream
))))
2111 (let* ((handle (fd-stream-fd fd-stream
))
2112 (element-size (fd-stream-element-size fd-stream
)))
2113 (multiple-value-bind (got native-size
)
2114 (sb!win32
:get-file-size-ex handle
0)
2116 ;; Might be a block device, in which case we fall back to
2117 ;; a non-atomic workaround:
2118 (let* ((here (sb!unix
:unix-lseek handle
0 sb
!unix
:l_incr
))
2119 (there (sb!unix
:unix-lseek handle
0 sb
!unix
:l_xtnd
)))
2120 (when (and here there
)
2121 (sb!unix
:unix-lseek handle here sb
!unix
:l_set
)
2122 (truncate there element-size
)))
2123 (truncate native-size element-size
)))))
2124 (:file-string-length
2126 (character (fd-stream-character-size fd-stream arg1
))
2127 (string (fd-stream-string-size fd-stream arg1
))))
2130 (fd-stream-set-file-position fd-stream arg1
)
2131 (fd-stream-get-file-position fd-stream
)))))
2133 ;; FIXME: Think about this.
2135 ;; (defun finish-fd-stream-output (fd-stream)
2136 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2137 ;; (loop while (fd-stream-output-queue fd-stream)
2138 ;; ;; FIXME: SIGINT while waiting for a timeout will
2139 ;; ;; cause a timeout here.
2140 ;; do (when (and (not (serve-event timeout)) timeout)
2141 ;; (signal-timeout 'io-timeout
2142 ;; :stream fd-stream
2143 ;; :direction :write
2144 ;; :seconds timeout)))))
2146 (defun finish-fd-stream-output (stream)
2147 (flush-output-buffer stream
)
2149 ((null (fd-stream-output-queue stream
)))
2150 (aver (fd-stream-serve-events stream
))
2151 (serve-all-events)))
2153 (defun fd-stream-get-file-position (stream)
2154 (declare (fd-stream stream
))
2156 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2157 (declare (type (or (alien sb
!unix
:unix-offset
) null
) posn
))
2158 ;; We used to return NIL for errno==ESPIPE, and signal an error
2159 ;; in other failure cases. However, CLHS says to return NIL if
2160 ;; the position cannot be determined -- so that's what we do.
2161 (when (integerp posn
)
2162 ;; Adjust for buffered output: If there is any output
2163 ;; buffered, the *real* file position will be larger
2164 ;; than reported by lseek() because lseek() obviously
2165 ;; cannot take into account output we have not sent
2167 (dolist (buffer (fd-stream-output-queue stream
))
2168 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2169 (let ((obuf (fd-stream-obuf stream
)))
2171 (incf posn
(buffer-tail obuf
))))
2172 ;; Adjust for unread input: If there is any input
2173 ;; read from UNIX but not supplied to the user of the
2174 ;; stream, the *real* file position will smaller than
2175 ;; reported, because we want to look like the unread
2176 ;; stuff is still available.
2177 (let ((ibuf (fd-stream-ibuf stream
)))
2179 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2180 ;; Divide bytes by element size.
2181 (truncate posn
(fd-stream-element-size stream
))))))
2183 (defun fd-stream-set-file-position (stream position-spec
)
2184 (declare (fd-stream stream
))
2185 (check-type position-spec
2186 (or (alien sb
!unix
:unix-offset
) (member nil
:start
:end
))
2187 "valid file position designator")
2190 ;; Make sure we don't have any output pending, because if we
2191 ;; move the file pointer before writing this stuff, it will be
2192 ;; written in the wrong location.
2193 (finish-fd-stream-output stream
)
2194 ;; Disable interrupts so that interrupt handlers doing output
2197 (unless (fd-stream-output-finished-p stream
)
2198 ;; We got interrupted and more output came our way during
2199 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2200 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2201 ;; so we prefer to do things like this...
2203 ;; Clear out any pending input to force the next read to go to
2205 (flush-input-buffer stream
)
2206 ;; Trash cached value for listen, so that we check next time.
2207 (setf (fd-stream-listen stream
) nil
)
2209 (multiple-value-bind (offset origin
)
2212 (values 0 sb
!unix
:l_set
))
2214 (values 0 sb
!unix
:l_xtnd
))
2216 (values (* position-spec
(fd-stream-element-size stream
))
2218 (declare (type (alien sb
!unix
:unix-offset
) offset
))
2219 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2221 ;; CLHS says to return true if the file-position was set
2222 ;; successfully, and NIL otherwise. We are to signal an error
2223 ;; only if the given position was out of bounds, and that is
2224 ;; dealt with above. In times past we used to return NIL for
2225 ;; errno==ESPIPE, and signal an error in other cases.
2227 ;; FIXME: We are still liable to signal an error if flushing
2229 (return-from fd-stream-set-file-position
2230 (typep posn
'(alien sb
!unix
:unix-offset
))))))))
2233 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2235 ;;; Create a stream for the given Unix file descriptor.
2237 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2238 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2239 ;;; default to allowing input.
2241 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2243 ;;; BUFFERING indicates the kind of buffering to use.
2245 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2246 ;;; NIL (the default), then wait forever. When we time out, we signal
2249 ;;; FILE is the name of the file (will be returned by PATHNAME).
2251 ;;; NAME is used to identify the stream when printed.
2253 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2254 ;;; handle blocking IO on the stream.
2255 (defun make-fd-stream (fd
2259 (output nil output-p
)
2260 (element-type 'base-char
)
2262 (external-format :default
)
2272 (format nil
"file ~A" file
)
2273 (format nil
"descriptor ~W" fd
)))
2275 (declare (type index fd
) (type (or real null
) timeout
)
2276 (type (member :none
:line
:full
) buffering
))
2277 (cond ((not (or input-p output-p
))
2279 ((not (or input output
))
2280 (error "File descriptor must be opened either for input or output.")))
2281 (let* ((constructor (ecase class
2282 (fd-stream '%make-fd-stream
)
2283 (form-tracking-stream '%make-form-tracking-stream
)))
2284 (element-mode (stream-element-type-stream-element-mode element-type
))
2285 (stream (funcall constructor
2288 #!-win32
(sb!unix
:fd-type fd
)
2290 #!+win32
(if serve-events
2296 :delete-original delete-original
2298 :buffering buffering
2299 :dual-channel-p dual-channel-p
2300 :element-mode element-mode
2301 :serve-events serve-events
2304 (coerce timeout
'single-float
)
2306 (set-fd-stream-routines stream element-type external-format
2307 input output input-buffer-p
)
2311 (sb!unix
:unix-close fd
)
2313 (format *terminal-io
* "** closed file descriptor ~W **~%"
2318 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2319 ;;; :RENAME-AND-DELETE and :RENAME options.
2320 (defun pick-backup-name (name)
2321 (declare (type simple-string name
))
2322 (concatenate 'simple-string name
".bak"))
2324 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2325 ;;; access, since we don't want to trash unwritable files even if we
2326 ;;; technically can. We return true if we succeed in renaming.
2327 (defun rename-the-old-one (namestring original
)
2328 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2329 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2330 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2333 (error 'simple-file-error
2334 :pathname namestring
2336 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2337 :format-arguments
(list namestring original
(strerror err
))))))
2339 (defun open (filename
2342 (element-type 'base-char
)
2343 (if-exists nil if-exists-given
)
2344 (if-does-not-exist nil if-does-not-exist-given
)
2345 (external-format :default
)
2346 ;; private options - use at your own risk
2350 &aux
; Squelch assignment warning.
2351 (direction direction
)
2352 (if-does-not-exist if-does-not-exist
)
2353 (if-exists if-exists
))
2354 "Return a stream which reads from or writes to FILENAME.
2356 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2357 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2358 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2359 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2360 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2361 See the manual for details."
2363 ;; Calculate useful stuff.
2364 (multiple-value-bind (input output mask
)
2366 (:input
(values t nil sb
!unix
:o_rdonly
))
2367 (:output
(values nil t sb
!unix
:o_wronly
))
2368 (:io
(values t t sb
!unix
:o_rdwr
))
2369 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2370 (declare (type index mask
))
2371 (let* ( ;; PATHNAME is the pathname we associate with the stream.
2372 (pathname (merge-pathnames filename
))
2373 (physical (physicalize-pathname pathname
))
2374 (truename (probe-file physical
))
2375 ;; NAMESTRING is the native namestring we open the file with.
2376 (namestring (cond (truename
2377 (native-namestring truename
:as-file t
))
2379 (and input
(eq if-does-not-exist
:create
))
2380 (and (eq direction
:io
)
2381 (not if-does-not-exist-given
)))
2382 (native-namestring physical
:as-file t
)))))
2383 (flet ((open-error (format-control &rest format-arguments
)
2384 (declare (optimize allow-non-returning-tail-call
))
2385 (error 'simple-file-error
2387 :format-control format-control
2388 :format-arguments format-arguments
)))
2389 ;; Process if-exists argument if we are doing any output.
2391 (unless if-exists-given
2393 (if (eq (pathname-version pathname
) :newest
)
2397 ((:new-version
:error nil
)
2398 (setf mask
(logior mask sb
!unix
:o_excl
)))
2399 ((:rename
:rename-and-delete
)
2400 (setf mask
(logior mask sb
!unix
:o_creat
)))
2402 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2404 (setf mask
(logior mask sb
!unix
:o_append
)))))
2406 (setf if-exists
:ignore-this-arg
)))
2408 (unless if-does-not-exist-given
2409 (setf if-does-not-exist
2410 (cond ((eq direction
:input
) :error
)
2412 (member if-exists
'(:overwrite
:append
)))
2414 ((eq direction
:probe
)
2418 (cond ((and if-exists-given
2420 (eq if-exists
:new-version
))
2421 (open-error "OPEN :IF-EXISTS :NEW-VERSION is not supported ~
2422 when a new version must be created."))
2423 ((eq if-does-not-exist
:create
)
2424 (setf mask
(logior mask sb
!unix
:o_creat
)))
2425 ((not (member if-exists
'(:error nil
))))
2426 ;; Both if-does-not-exist and if-exists now imply
2427 ;; that there will be no opening of files, and either
2428 ;; an error would be signalled, or NIL returned
2429 ((and (not if-exists
) (not if-does-not-exist
))
2431 ((and if-exists if-does-not-exist
)
2432 (open-error "OPEN :IF-DOES-NOT-EXIST ~s ~
2433 :IF-EXISTS ~s will always signal an error."
2434 if-does-not-exist if-exists
))
2437 (open-error "File exists ~s." pathname
)
2438 (return-from open
)))
2440 (open-error "File does not exist ~s." pathname
))
2442 (return-from open
)))
2443 (let ((original (case if-exists
2444 ((:rename
:rename-and-delete
)
2445 (pick-backup-name namestring
))
2446 ((:append
:overwrite
)
2447 ;; KLUDGE: Prevent CLOSE from deleting
2448 ;; appending streams when called with :ABORT T
2450 (delete-original (eq if-exists
:rename-and-delete
))
2452 (when (and original
(not (eq original namestring
)))
2453 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2454 ;; whether the file already exists, make sure the original
2455 ;; file is not a directory, and keep the mode.
2458 (multiple-value-bind (okay err
/dev inode orig-mode
)
2459 (sb!unix
:unix-stat namestring
)
2460 (declare (ignore inode
)
2461 (type (or index null
) orig-mode
))
2464 (when (and output
(= (logand orig-mode
#o170000
)
2466 (error 'simple-file-error
2469 "can't open ~S for output: is a directory"
2470 :format-arguments
(list namestring
)))
2471 (setf mode
(logand orig-mode
#o777
))
2473 ((eql err
/dev sb
!unix
:enoent
)
2476 (simple-file-perror "can't find ~S"
2480 (rename-the-old-one namestring original
))
2482 (setf delete-original nil
)
2483 ;; In order to use :SUPERSEDE instead, we have to make
2484 ;; sure SB!UNIX:O_CREAT corresponds to
2485 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2486 ;; because of IF-EXISTS being :RENAME.
2487 (unless (eq if-does-not-exist
:create
)
2489 (logior (logandc2 mask sb
!unix
:o_creat
)
2491 (setf if-exists
:supersede
))))
2493 ;; Now we can try the actual Unix open(2).
2494 (multiple-value-bind (fd errno
)
2496 (sb!unix
:unix-open namestring mask mode
2497 #!+win32
:overlapped
#!+win32 overlapped
)
2498 (values nil
#!-win32 sb
!unix
:enoent
2499 #!+win32 sb
!win32
::error_file_not_found
))
2500 (flet ((vanilla-open-error ()
2501 (simple-file-perror "error opening ~S" pathname errno
)))
2504 ((:input
:output
:io
)
2505 ;; For O_APPEND opened files, lseek returns 0 until first write.
2506 ;; So we jump ahead here.
2507 (when (eq if-exists
:append
)
2508 (sb!unix
:unix-lseek fd
0 sb
!unix
:l_xtnd
))
2513 :element-type element-type
2514 :external-format external-format
2517 :delete-original delete-original
2525 (%make-fd-stream
:name namestring
2528 :element-type element-type
)))
2531 ((eql errno
#!-win32 sb
!unix
:enoent
2532 #!+win32 sb
!win32
::error_file_not_found
)
2533 (case if-does-not-exist
2534 (:error
(vanilla-open-error))
2536 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2539 ((and (eql errno
#!-win32 sb
!unix
:eexist
2540 #!+win32 sb
!win32
::error_file_exists
)
2544 (vanilla-open-error))))))))))
2548 ;;; the stream connected to the controlling terminal, or NIL if there is none
2551 ;;; the stream connected to the standard input (file descriptor 0)
2554 ;;; the stream connected to the standard output (file descriptor 1)
2557 ;;; the stream connected to the standard error output (file descriptor 2)
2560 ;;; This is called when the cold load is first started up, and may also
2561 ;;; be called in an attempt to recover from nested errors.
2562 (defun stream-cold-init-or-reset ()
2564 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2565 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2566 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2567 (setf *error-output
* (make-synonym-stream '*stderr
*))
2568 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2569 (setf *debug-io
* *query-io
*)
2570 (setf *trace-output
* *standard-output
*)
2573 (defun stream-deinit ()
2574 (setq *tty
* nil
*stdin
* nil
*stdout
* nil
*stderr
* nil
)
2575 ;; Unbind to make sure we're not accidently dealing with it
2576 ;; before we're ready (or after we think it's been deinitialized).
2577 (%makunbound
'*available-buffers
*))
2579 (defun stdstream-external-format (fd)
2580 #!-win32
(declare (ignore fd
))
2581 (let* ((keyword (cond #!+(and win32 sb-unicode
)
2582 ((sb!win32
::console-handle-p fd
)
2585 (default-external-format))))
2586 (ef (get-external-format keyword
))
2587 (replacement (ef-default-replacement-character ef
)))
2588 `(,keyword
:replacement
,replacement
)))
2590 ;;; This is called whenever a saved core is restarted.
2591 (defun stream-reinit (&optional init-buffers-p
)
2592 (when init-buffers-p
2593 (aver (not (boundp '*available-buffers
*)))
2594 (setf *available-buffers
* nil
))
2595 (with-simple-output-to-string (*error-output
*)
2596 (multiple-value-bind (in out err
)
2597 #!-win32
(values 0 1 2)
2598 #!+win32
(sb!win32
::get-std-handles
)
2600 (nul-stream (name inputp outputp
)
2601 (let* ((nul-name #.
(coerce "NUL" 'simple-base-string
))
2604 ((and inputp outputp
)
2605 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdwr
))
2607 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdonly
))
2609 (sb!win32
:unixlike-open nul-name sb
!unix
:o_wronly
))
2611 ;; Not quite sure what to do in this case.
2619 :element-type
:default
2620 :serve-events inputp
2622 :external-format
(stdstream-external-format nul-handle
))))
2623 (stdio-stream (handle name inputp outputp
)
2627 ;; If no actual handle was present, create a stream to NUL
2628 (nul-stream name inputp outputp
))
2636 :element-type
:default
2637 :serve-events inputp
2638 :external-format
(stdstream-external-format handle
))))))
2639 (setf *stdin
* (stdio-stream in
"standard input" t nil
)
2640 *stdout
* (stdio-stream out
"standard output" nil t
)
2641 *stderr
* (stdio-stream err
"standard error" nil t
))))
2643 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))
2645 ;; FIXME: what is this call to COERCE doing? XC can't dump non-base-strings.
2646 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2647 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2650 (make-fd-stream tty
:name
"the terminal"
2651 :input t
:output t
:buffering
:line
2652 :external-format
(stdstream-external-format tty
)
2655 (make-two-way-stream *stdin
* *stdout
*))))
2656 (princ (get-output-stream-string *error-output
*) *stderr
*))
2661 ;;; the Unix way to beep
2662 (defun beep (stream)
2663 (write-char (code-char bell-char-code
) stream
)
2664 (finish-output stream
))
2666 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2667 ;;; by the filesys stuff to get and set the file name.
2669 ;;; FIXME: misleading name, screwy interface
2670 (defun file-name (stream &optional new-name
)
2671 (when (typep stream
'fd-stream
)
2673 (setf (fd-stream-pathname stream
) new-name
)
2674 (setf (fd-stream-file stream
)
2675 (native-namestring (physicalize-pathname new-name
)
2679 (fd-stream-pathname stream
)))))
2681 ;; Fix the INPUT-CHAR-POS slot of STREAM after having consumed characters
2682 ;; from the CIN-BUFFER. This operation is done upon exit from a FAST-READ-CHAR
2683 ;; loop, and for each buffer refill inside the loop.
2684 (defun update-input-char-pos (stream &optional
(end +ansi-stream-in-buffer-length
+))
2685 (do ((chars (ansi-stream-cin-buffer stream
))
2686 (pos (form-tracking-stream-input-char-pos stream
))
2687 (i (ansi-stream-in-index stream
) (1+ i
)))
2689 (setf (form-tracking-stream-input-char-pos stream
) pos
))
2690 (let ((char (aref chars i
)))
2691 (when (and (eql char
#\Newline
)
2692 ;; record it only if it wasn't unread and re-read
2693 (> pos
(form-tracking-stream-last-newline stream
)))
2694 (vector-push-extend pos
(form-tracking-stream-newlines stream
))
2695 (setf (form-tracking-stream-last-newline stream
) pos
))
2698 (defun tracking-stream-misc (stream operation
&optional arg1 arg2
)
2699 ;; The :UNREAD operation will never be invoked because STREAM has a buffer,
2700 ;; so unreading is implemented entirely within ANSI-STREAM-UNREAD-CHAR.
2701 ;; But we do need to prevent attempts to change the absolute position.
2705 (error 'simple-stream-error
2706 :format-control
"~S is not positionable"
2707 :format-arguments
(list stream
))
2708 (fd-stream-get-file-position stream
)))
2709 (t ; call next method
2710 (fd-stream-misc-routine stream operation arg1 arg2
))))
2712 (!defglobal
*!cold-stderr-buf
* " ")
2714 (defun !make-cold-stderr-stream
()
2717 #!+win32
(sb!win32
::get-std-handle-or-null sb
!win32
::+std-error-handle
+)))
2719 :out
(lambda (stream ch
)
2720 (declare (ignore stream
))
2721 (let ((b (truly-the (simple-base-string 1) *!cold-stderr-buf
*)))
2722 (setf (char b
0) ch
)
2723 (sb!unix
:unix-write stderr b
0 1)))
2724 :sout
(lambda (stream string start end
)
2725 (declare (ignore stream
))
2726 (flet ((out (s start len
)
2727 (sb!unix
:unix-write stderr s start len
)))
2728 (if (typep string
'simple-base-string
)
2729 (out string start
(- end start
))
2730 (let ((n (- end start
)))
2731 ;; will croak if there is any non-BASE-CHAR in the string
2732 (out (replace (make-array n
:element-type
'base-char
)
2733 string
:start2 start
) 0 n
)))))
2734 :misc
(constantly nil
))))