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 (defglobal *available-buffers
* ()
51 "List of available buffers.")
53 (defconstant +bytes-per-buffer
+ (* 4 1024)
54 "Default number of bytes per buffer.")
56 (defun alloc-buffer (&optional
(size +bytes-per-buffer
+))
57 ;; Don't want to allocate & unwind before the finalizer is in place.
59 (let* ((sap (allocate-system-memory size
))
60 (buffer (%make-buffer sap size
)))
61 (when (zerop (sap-int sap
))
62 (error "Could not allocate ~D bytes for buffer." size
))
63 (finalize buffer
(lambda ()
64 (deallocate-system-memory sap size
))
69 (or (and *available-buffers
* (atomic-pop *available-buffers
*))
72 (declaim (inline reset-buffer
))
73 (defun reset-buffer (buffer)
74 (setf (buffer-head buffer
) 0
75 (buffer-tail buffer
) 0)
78 (defun release-buffer (buffer)
80 (atomic-push buffer
*available-buffers
*))
83 ;;;; the FD-STREAM structure
85 ;;; Coarsely characterizes the element type of an FD-STREAM w.r.t.
86 ;;; its SUBTYPEP relations to the relevant CHARACTER and
87 ;;; ([UN]SIGNED-BYTE 8) types. This coarse characterization enables
88 ;;; dispatching on the element type as needed by {READ,WRITE}-SEQUENCE
89 ;;; without calling SUBTYPEP.
90 (deftype stream-element-mode
()
91 '(member character unsigned-byte signed-byte
:bivalent
))
94 (:constructor %make-fd-stream
)
95 (:conc-name fd-stream-
)
96 (:predicate fd-stream-p
)
98 (misc #'fd-stream-misc-routine
))
101 ;; the name of this stream
103 ;; the file this stream is for
105 ;; the backup file namestring for the old file, for :IF-EXISTS
106 ;; :RENAME or :RENAME-AND-DELETE.
107 (original nil
:type
(or simple-string null
))
108 (delete-original nil
) ; for :if-exists :rename-and-delete
109 ;;; the number of bytes per element
110 (element-size 1 :type index
)
111 ;; the type of element being transfered
112 (element-type 'base-char
)
113 ;; coarse characterization of the element type. see description of
114 ;; STREAM-ELEMENT-MODE type.
115 (element-mode :bivalent
:type stream-element-mode
)
116 ;; the Unix file descriptor
117 (fd -
1 :type
#!-win32 fixnum
#!+win32 sb
!vm
:signed-word
)
118 ;; What do we know about the FD?
119 (fd-type :unknown
:type keyword
)
120 ;; controls when the output buffer is flushed
121 (buffering :full
:type
(member :full
:line
:none
))
122 ;; controls whether the input buffer must be cleared before output
123 ;; (must be done for files, not for sockets, pipes and other data
124 ;; sources where input and output aren't related). non-NIL means
125 ;; don't clear input buffer.
127 ;; character position if known -- this may run into bignums, but
128 ;; we probably should flip it into null then for efficiency's sake...
129 (output-column nil
:type
(or unsigned-byte null
))
130 ;; T if input is waiting on FD. :EOF if we hit EOF.
131 (listen nil
:type
(member nil t
:eof
))
132 ;; T if serve-event is allowed when this stream blocks
133 (serve-events nil
:type boolean
)
136 (instead (make-array 0 :element-type
'character
:adjustable t
:fill-pointer t
) :type
(array character
(*)))
137 (ibuf nil
:type
(or buffer null
))
138 (eof-forced-p nil
:type
(member t nil
))
141 (obuf nil
:type
(or buffer null
))
143 ;; output flushed, but not written due to non-blocking io?
146 ;; timeout specified for this stream as seconds or NIL if none
147 (timeout nil
:type
(or single-float null
))
148 ;; pathname of the file this stream is opened to (returned by PATHNAME)
149 (pathname nil
:type
(or pathname null
))
150 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
151 (external-format :latin-1
)
152 ;; fixed width, or function to call with a character
153 (char-size 1 :type
(or fixnum function
))
154 (output-bytes #'ill-out
:type function
))
156 (defun fd-stream-bivalent-p (stream)
157 (eq (fd-stream-element-mode stream
) :bivalent
))
159 (defmethod print-object ((fd-stream fd-stream
) stream
)
160 (declare (type stream stream
))
161 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
162 (format stream
"for ~S" (fd-stream-name fd-stream
))))
164 ;;; Release all of FD-STREAM's buffers. Originally the intent of this
165 ;;; was to grab a mutex once only, but the buffer pool is lock-free now.
166 (defun release-fd-stream-buffers (fd-stream)
167 (awhen (fd-stream-ibuf fd-stream
)
168 (setf (fd-stream-ibuf fd-stream
) nil
)
170 (awhen (fd-stream-obuf fd-stream
)
171 (setf (fd-stream-obuf fd-stream
) nil
)
173 (dolist (buf (fd-stream-output-queue fd-stream
))
175 (release-buffer buf
)))
176 (setf (fd-stream-output-queue fd-stream
) nil
))
178 ;;;; FORM-TRACKING-STREAM
180 ;; The compiler uses this to record for each input subform the start and
181 ;; end positions as character offsets. Measuring in characters rather than
182 ;; bytes is both better suited to the task - in that it is consistent with
183 ;; reporting of "point" by Emacs - and faster than querying FILE-POSITION.
184 ;; The slowness of FILE-POSITION on an FD-STREAM is due to making a system
185 ;; call every time, to ensure that the case of an append-only stream works
186 ;; correctly (where the OS forces all writes to the end), and other factors.
188 (defstruct (form-tracking-stream
189 (:constructor %make-form-tracking-stream
)
191 (misc #'tracking-stream-misc
)
194 ;; a function which is called for events on this stream.
195 (observer (lambda (x y z
) (declare (ignore x y z
))) :type function
)
196 ;; A vector of the character position of each #\Newline seen
197 (newlines (make-array 10 :fill-pointer
0 :adjustable t
))
198 (last-newline -
1 :type index-or-minus-1
)
199 ;; Better than reporting that a reader error occurred at a position
200 ;; before any whitespace (or equivalently, a macro producing no value),
201 ;; we can note the position at the first "good" character.
202 (form-start-byte-pos)
203 (form-start-char-pos))
205 (defun line/col-from-charpos
206 (stream &optional
(charpos (ansi-stream-input-char-pos stream
)))
207 (let* ((newlines (form-tracking-stream-newlines stream
))
208 (index (position charpos newlines
:test
#'>= :from-end t
)))
209 ;; Line numbers traditionally begin at 1, columns at 0.
211 ;; INDEX is 1 less than the number of newlines seen
212 ;; up to and including this startpos.
213 ;; e.g. index=0 => 1 newline seen => line=2
215 ;; 1 char after the newline = column 0
216 (- charpos
(aref newlines index
) 1))
217 ;; zero newlines were seen
220 ;;;; CORE OUTPUT FUNCTIONS
222 ;;; Buffer the section of THING delimited by START and END by copying
223 ;;; to output buffer(s) of stream.
224 (defun buffer-output (stream thing start end
)
225 (declare (index start end
))
227 (error ":END before :START!"))
229 ;; Copy bytes from THING to buffers.
230 (flet ((copy-to-buffer (buffer tail count
)
231 (declare (buffer buffer
) (index tail count
))
233 (let ((sap (buffer-sap buffer
)))
236 (system-area-ub8-copy thing start sap tail count
))
237 ((simple-unboxed-array (*))
238 (copy-ub8-to-system-area thing start sap tail count
))))
239 ;; Not INCF! If another thread has moved tail from under
240 ;; us, we don't want to accidentally increment tail
241 ;; beyond buffer-length.
242 (setf (buffer-tail buffer
) (+ count tail
))
245 ;; First copy is special: the buffer may already contain
246 ;; something, or be even full.
247 (let* ((obuf (fd-stream-obuf stream
))
248 (tail (buffer-tail obuf
))
249 (space (- (buffer-length obuf
) tail
)))
251 (copy-to-buffer obuf tail
(min space
(- end start
)))
252 (go :more-output-p
)))
254 ;; Later copies should always have an empty buffer, since
255 ;; they are freshly flushed, but if another thread is
256 ;; stomping on the same buffer that might not be the case.
257 (let* ((obuf (flush-output-buffer stream
))
258 (tail (buffer-tail obuf
))
259 (space (- (buffer-length obuf
) tail
)))
260 (copy-to-buffer obuf tail
(min space
(- end start
))))
263 (go :flush-and-fill
))))))
265 ;;; Flush the current output buffer of the stream, ensuring that the
266 ;;; new buffer is empty. Returns (for convenience) the new output
267 ;;; buffer -- which may or may not be EQ to the old one. If the is no
268 ;;; queued output we try to write the buffer immediately -- otherwise
269 ;;; we queue it for later.
270 (defun flush-output-buffer (stream)
271 (let ((obuf (fd-stream-obuf stream
)))
273 (let ((head (buffer-head obuf
))
274 (tail (buffer-tail obuf
)))
275 (cond ((eql head tail
)
276 ;; Buffer is already empty -- just ensure that is is
277 ;; set to zero as well.
279 ((fd-stream-output-queue stream
)
280 ;; There is already stuff on the queue -- go directly
283 (%queue-and-replace-output-buffer stream
))
285 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
286 ;; whatever is left over. Otherwise wait until we can write.
288 (synchronize-stream-output stream
)
290 (let ((length (- tail head
)))
291 (multiple-value-bind (count errno
)
292 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
294 (flet ((queue-or-wait ()
295 (if (fd-stream-serve-events stream
)
296 (return (%queue-and-replace-output-buffer stream
))
297 (or (wait-until-fd-usable (fd-stream-fd stream
) :output
298 (fd-stream-timeout stream
)
300 (signal-timeout 'io-timeout
303 :seconds
(fd-stream-timeout stream
))))))
304 (cond ((eql count length
)
305 ;; Complete write -- we can use the same buffer.
306 (return (reset-buffer obuf
)))
308 ;; Partial write -- update buffer status and
311 (setf (buffer-head obuf
) head
)
314 ((eql errno sb
!unix
:ewouldblock
)
315 ;; Blocking, queue or wair.
317 ;; if interrupted on win32, just try again
318 #!+win32
((eql errno sb
!unix
:eintr
))
320 (simple-stream-perror "Couldn't write to ~s"
321 stream errno
)))))))))))))
323 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
324 (defun %queue-and-replace-output-buffer
(stream)
325 (aver (fd-stream-serve-events stream
))
326 (let ((queue (fd-stream-output-queue stream
))
327 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
329 ;; Important: before putting the buffer on queue, give the stream
330 ;; a new one. If we get an interrupt and unwind losing the buffer
331 ;; is relatively OK, but having the same buffer in two places
333 (setf (fd-stream-obuf stream
) new
)
337 (setf (fd-stream-output-queue stream
) later
)))
338 (unless (fd-stream-handler stream
)
339 (setf (fd-stream-handler stream
)
340 (add-fd-handler (fd-stream-fd stream
)
343 (declare (ignore fd
))
344 (write-output-from-queue stream
)))))
347 ;;; This is called by the FD-HANDLER for the stream when output is
349 (defun write-output-from-queue (stream)
350 (aver (fd-stream-serve-events stream
))
351 (synchronize-stream-output stream
)
355 (let* ((buffer (pop (fd-stream-output-queue stream
)))
356 (head (buffer-head buffer
))
357 (length (- (buffer-tail buffer
) head
)))
358 (declare (index head length
))
360 (multiple-value-bind (count errno
)
361 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
363 (cond ((eql count length
)
364 ;; Complete write, see if we can do another right
365 ;; away, or remove the handler if we're done.
366 (release-buffer buffer
)
367 (cond ((fd-stream-output-queue stream
)
371 (let ((handler (fd-stream-handler stream
)))
373 (setf (fd-stream-handler stream
) nil
)
374 (remove-fd-handler handler
)))))
376 ;; Partial write. Update buffer status and requeue.
377 (aver (< count length
))
378 ;; Do not use INCF! Another thread might have moved head.
379 (setf (buffer-head buffer
) (+ head count
))
380 (push buffer
(fd-stream-output-queue stream
)))
382 ;; We tried to do multiple writes, and finally our
383 ;; luck ran out. Requeue.
384 (push buffer
(fd-stream-output-queue stream
)))
386 ;; Could not write on the first try at all!
388 (simple-stream-perror "Couldn't write to ~S." stream errno
)
390 (if (= errno sb
!unix
:ewouldblock
)
391 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
392 (simple-stream-perror "Couldn't write to ~S"
396 ;;; Try to write THING directly to STREAM without buffering, if
397 ;;; possible. If direct write doesn't happen, buffer.
398 (defun write-or-buffer-output (stream thing start end
)
399 (declare (index start end
))
400 (cond ((fd-stream-output-queue stream
)
401 (buffer-output stream thing start end
))
403 (error ":END before :START!"))
405 (let ((length (- end start
)))
406 (synchronize-stream-output stream
)
407 (multiple-value-bind (count errno
)
408 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
409 (cond ((eql count length
)
410 ;; Complete write -- done!
413 (aver (< count length
))
414 ;; Partial write -- buffer the rest.
415 (buffer-output stream thing
(+ start count
) end
))
417 ;; Could not write -- buffer or error.
419 (simple-stream-perror "couldn't write to ~s" stream errno
)
421 (if (= errno sb
!unix
:ewouldblock
)
422 (buffer-output stream thing start end
)
423 (simple-stream-perror "couldn't write to ~s" stream errno
)))))))))
425 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
426 ;;; this is not something we want to export. Nikodemus thinks the
427 ;;; right thing is to support a low-level non-stream like IO layer,
428 ;;; akin to java.nio.
429 (declaim (inline output-raw-bytes
))
430 (define-deprecated-function :late
"1.0.8.16" output-raw-bytes write-sequence
431 (stream thing
&optional start end
)
432 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
434 ;;;; output routines and related noise
436 (defvar *output-routines
* ()
437 "List of all available output routines. Each element is a list of the
438 element-type output, the kind of buffering, the function name, and the number
439 of bytes per element.")
441 ;;; common idioms for reporting low-level stream and file problems
442 (defun simple-stream-perror (note-format stream errno
)
443 (declare (optimize allow-non-returning-tail-call
))
444 (error 'simple-stream-error
446 :format-control
"~@<~?: ~2I~_~A~:>"
447 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
448 (defun simple-file-perror (note-format pathname errno
)
449 (declare (optimize allow-non-returning-tail-call
))
450 (error 'simple-file-error
452 :format-control
"~@<~?: ~2I~_~A~:>"
454 (list note-format
(list pathname
) (strerror errno
))))
456 (defun c-string-encoding-error (external-format code
)
457 (declare (optimize allow-non-returning-tail-call
))
458 (error 'c-string-encoding-error
459 :external-format external-format
461 (defun c-string-decoding-error (external-format sap offset count
)
462 (declare (optimize allow-non-returning-tail-call
))
463 (error 'c-string-decoding-error
464 :external-format external-format
465 :octets
(sap-ref-octets sap offset count
)))
467 ;;; Returning true goes into end of file handling, false will enter another
468 ;;; round of input buffer filling followed by re-entering character decode.
469 (defun stream-decoding-error-and-handle (stream octet-count
)
471 (error 'stream-decoding-error
472 :external-format
(stream-external-format stream
)
474 :octets
(let ((buffer (fd-stream-ibuf stream
)))
475 (sap-ref-octets (buffer-sap buffer
)
479 :report
(lambda (stream)
481 "~@<Attempt to resync the stream at a ~
482 character boundary and continue.~@:>"))
483 (fd-stream-resync stream
)
485 (force-end-of-file ()
486 :report
(lambda (stream)
487 (format stream
"~@<Force an end of file.~@:>"))
488 (setf (fd-stream-eof-forced-p stream
) t
))
489 (input-replacement (string)
490 :report
(lambda (stream)
491 (format stream
"~@<Use string as replacement input, ~
492 attempt to resync at a character ~
493 boundary and continue.~@:>"))
494 :interactive
(lambda ()
495 (format *query-io
* "~@<Enter a string: ~@:>")
496 (finish-output *query-io
*)
497 (list (read *query-io
*)))
498 (let ((string (reverse (string string
)))
499 (instead (fd-stream-instead stream
)))
500 (dotimes (i (length string
))
501 (vector-push-extend (char string i
) instead
))
502 (fd-stream-resync stream
)
503 (when (> (length string
) 0)
504 (setf (fd-stream-listen stream
) t
)))
507 (defun stream-encoding-error-and-handle (stream code
)
509 (error 'stream-encoding-error
510 :external-format
(stream-external-format stream
)
514 :report
(lambda (stream)
515 (format stream
"~@<Skip output of this character.~@:>"))
516 (throw 'output-nothing nil
))
517 (output-replacement (string)
518 :report
(lambda (stream)
519 (format stream
"~@<Output replacement string.~@:>"))
520 :interactive
(lambda ()
521 (format *query-io
* "~@<Enter a string: ~@:>")
522 (finish-output *query-io
*)
523 (list (read *query-io
*)))
524 (let ((string (string string
)))
525 (fd-sout stream
(string string
) 0 (length string
)))
526 (throw 'output-nothing nil
))))
528 (defun external-format-encoding-error (stream code
)
530 (stream-encoding-error-and-handle stream code
)
531 (c-string-encoding-error stream code
)))
533 (defun synchronize-stream-output (stream)
534 ;; If we're reading and writing on the same file, flush buffered
535 ;; input and rewind file position accordingly.
536 (unless (fd-stream-dual-channel-p stream
)
537 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
538 (unless (eql 0 adjust
)
539 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
541 (defun fd-stream-output-finished-p (stream)
542 (let ((obuf (fd-stream-obuf stream
)))
544 (and (zerop (buffer-tail obuf
))
545 (not (fd-stream-output-queue stream
))))))
547 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
549 (let ((stream-var (gensym "STREAM")))
550 `(let* ((,stream-var
,stream
)
551 (obuf (fd-stream-obuf ,stream-var
))
552 (tail (buffer-tail obuf
))
554 ,(unless (eq (car buffering
) :none
)
555 `(when (< (buffer-length obuf
) (+ tail size
))
556 (setf obuf
(flush-output-buffer ,stream-var
)
557 tail
(buffer-tail obuf
))))
558 ,(unless (eq (car buffering
) :none
)
559 ;; FIXME: Why this here? Doesn't seem necessary.
560 `(synchronize-stream-output ,stream-var
))
562 `(catch 'output-nothing
564 (setf (buffer-tail obuf
) (+ tail size
)))
567 (setf (buffer-tail obuf
) (+ tail size
))))
568 ,(ecase (car buffering
)
570 `(flush-output-buffer ,stream-var
))
572 `(when (eql byte
#\Newline
)
573 (flush-output-buffer ,stream-var
)))
577 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
578 (let ((stream-var (gensym "STREAM")))
579 `(let* ((,stream-var
,stream
)
580 (obuf (fd-stream-obuf ,stream-var
))
581 (tail (buffer-tail obuf
)))
582 ,(unless (eq (car buffering
) :none
)
583 `(when (< (buffer-length obuf
) (+ tail
,size
))
584 (setf obuf
(flush-output-buffer ,stream-var
)
585 tail
(buffer-tail obuf
))))
586 ;; FIXME: Why this here? Doesn't seem necessary.
587 ,(unless (eq (car buffering
) :none
)
588 `(synchronize-stream-output ,stream-var
))
590 `(catch 'output-nothing
592 (setf (buffer-tail obuf
) (+ tail
,size
)))
595 (setf (buffer-tail obuf
) (+ tail
,size
))))
596 ,(ecase (car buffering
)
598 `(flush-output-buffer ,stream-var
))
600 `(when (eql byte
#\Newline
)
601 (flush-output-buffer ,stream-var
)))
605 (defmacro def-output-routines
/variable-width
606 ((name-fmt size restart external-format
&rest bufferings
)
608 (declare (optimize (speed 1)))
613 (intern (format nil name-fmt
(string (car buffering
))))))
615 (defun ,function
(stream byte
)
616 (declare (ignorable byte
))
617 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
619 (setf *output-routines
*
620 (nconc *output-routines
*
628 (cdr buffering
)))))))
631 ;;; Define output routines that output numbers SIZE bytes long for the
632 ;;; given bufferings. Use BODY to do the actual output.
633 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
635 (declare (optimize (speed 1)))
640 (intern (format nil name-fmt
(string (car buffering
))))))
642 (defun ,function
(stream byte
)
643 (output-wrapper (stream ,size
,buffering
,restart
)
645 (setf *output-routines
*
646 (nconc *output-routines
*
654 (cdr buffering
)))))))
657 ;;; FIXME: is this used anywhere any more?
658 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
664 (if (eql byte
#\Newline
)
665 (setf (fd-stream-output-column stream
) 0)
666 (incf (fd-stream-output-column stream
)))
667 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
670 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
673 (:none
(unsigned-byte 8))
674 (:full
(unsigned-byte 8)))
675 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
678 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
681 (:none
(signed-byte 8))
682 (:full
(signed-byte 8)))
683 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
686 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
689 (:none
(unsigned-byte 16))
690 (:full
(unsigned-byte 16)))
691 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
694 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
697 (:none
(signed-byte 16))
698 (:full
(signed-byte 16)))
699 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
702 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
705 (:none
(unsigned-byte 32))
706 (:full
(unsigned-byte 32)))
707 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
710 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
713 (:none
(signed-byte 32))
714 (:full
(signed-byte 32)))
715 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
720 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
723 (:none
(unsigned-byte 64))
724 (:full
(unsigned-byte 64)))
725 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
727 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
730 (:none
(signed-byte 64))
731 (:full
(signed-byte 64)))
732 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
735 ;;; the routine to use to output a string. If the stream is
736 ;;; unbuffered, slam the string down the file descriptor, otherwise
737 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
738 ;;; checking to see where the last newline was.
739 (defun fd-sout (stream thing start end
)
740 (declare (type fd-stream stream
) (type string thing
))
741 (let ((start (or start
0))
742 (end (or end
(length (the vector thing
)))))
743 (declare (fixnum start end
))
745 (string-dispatch (simple-base-string
747 (simple-array character
(*))
750 (position #\newline thing
:from-end t
751 :start start
:end end
))))
752 (if (and (typep thing
'base-string
)
753 (eq (fd-stream-external-format-keyword stream
) :latin-1
))
754 (ecase (fd-stream-buffering stream
)
756 (buffer-output stream thing start end
))
758 (buffer-output stream thing start end
)
760 (flush-output-buffer stream
)))
762 (write-or-buffer-output stream thing start end
)))
763 (ecase (fd-stream-buffering stream
)
764 (:full
(funcall (fd-stream-output-bytes stream
)
765 stream thing nil start end
))
766 (:line
(funcall (fd-stream-output-bytes stream
)
767 stream thing last-newline start end
))
768 (:none
(funcall (fd-stream-output-bytes stream
)
769 stream thing t start end
))))
771 (setf (fd-stream-output-column stream
) (- end last-newline
1))
772 (incf (fd-stream-output-column stream
) (- end start
))))))
774 (defstruct (external-format
775 (:constructor %make-external-format
)
777 (:predicate external-format-p
)
778 (:copier %copy-external-format
))
779 ;; All the names that can refer to this external format. The first
780 ;; one is the canonical name.
781 (names (missing-arg) :type list
:read-only t
)
782 (default-replacement-character (missing-arg) :type character
)
783 (read-n-chars-fun (missing-arg) :type function
)
784 (read-char-fun (missing-arg) :type function
)
785 (write-n-bytes-fun (missing-arg) :type function
)
786 (write-char-none-buffered-fun (missing-arg) :type function
)
787 (write-char-line-buffered-fun (missing-arg) :type function
)
788 (write-char-full-buffered-fun (missing-arg) :type function
)
789 ;; Can be nil for fixed-width formats.
790 (resync-fun nil
:type
(or function null
))
791 (bytes-for-char-fun (missing-arg) :type function
)
792 (read-c-string-fun (missing-arg) :type function
)
793 (write-c-string-fun (missing-arg) :type function
)
794 ;; We indirect through symbols in these functions so that a
795 ;; developer working on the octets code can easily redefine things
796 ;; and use the new function definition without redefining the
797 ;; external format as well. The slots above don't do any
798 ;; indirection because a developer working with those slots would be
799 ;; redefining the external format anyway.
800 (octets-to-string-fun (missing-arg) :type function
)
801 (string-to-octets-fun (missing-arg) :type function
))
803 (defun ef-char-size (ef-entry)
804 (if (variable-width-external-format-p ef-entry
)
805 (bytes-for-char-fun ef-entry
)
806 (funcall (bytes-for-char-fun ef-entry
) #\x
)))
808 (defun sb!alien
::string-to-c-string
(string external-format
)
809 (declare (type simple-string string
))
811 (declare (optimize (speed 3) (safety 0)))
812 (let ((external-format (get-external-format-or-lose external-format
)))
813 (funcall (ef-write-c-string-fun external-format
) string
))))
815 (defun sb!alien
::c-string-to-string
(sap external-format element-type
)
816 (declare (type system-area-pointer sap
))
818 (declare (optimize (speed 3) (safety 0)))
819 (let ((external-format (get-external-format-or-lose external-format
)))
820 (funcall (ef-read-c-string-fun external-format
) sap element-type
))))
822 (defun wrap-external-format-functions (external-format fun
)
823 (let ((result (%copy-external-format external-format
)))
824 (macrolet ((frob (accessor)
825 `(setf (,accessor result
) (funcall fun
(,accessor result
)))))
826 (frob ef-read-n-chars-fun
)
827 (frob ef-read-char-fun
)
828 (frob ef-write-n-bytes-fun
)
829 (frob ef-write-char-none-buffered-fun
)
830 (frob ef-write-char-line-buffered-fun
)
831 (frob ef-write-char-full-buffered-fun
)
833 (frob ef-bytes-for-char-fun
)
834 (frob ef-read-c-string-fun
)
835 (frob ef-write-c-string-fun
)
836 (frob ef-octets-to-string-fun
)
837 (frob ef-string-to-octets-fun
))
840 (defvar *external-formats
* (make-hash-table)
841 "Hashtable of all available external formats. The table maps from
842 external-format names to EXTERNAL-FORMAT structures.")
844 (defun get-external-format-or-lose (external-format)
845 (or (get-external-format external-format
)
846 (error "Undefined external-format: ~S" external-format
)))
848 (defun external-format-keyword (external-format)
849 (typecase external-format
850 (keyword external-format
)
851 ((cons keyword
) (car external-format
))))
853 (defun fd-stream-external-format-keyword (stream)
854 (external-format-keyword (fd-stream-external-format stream
)))
856 (defun canonize-external-format (external-format entry
)
857 (typecase external-format
858 (keyword (first (ef-names entry
)))
859 ((cons keyword
) (cons (first (ef-names entry
)) (rest external-format
)))))
861 ;;; Find an output routine to use given the type and buffering. Return
862 ;;; as multiple values the routine, the real type transfered, and the
863 ;;; number of bytes per element.
864 (defun pick-output-routine (type buffering
&optional external-format
)
865 (when (subtypep type
'character
)
866 (let ((entry (get-external-format-or-lose external-format
)))
867 (return-from pick-output-routine
868 (values (ecase buffering
869 (:none
(ef-write-char-none-buffered-fun entry
))
870 (:line
(ef-write-char-line-buffered-fun entry
))
871 (:full
(ef-write-char-full-buffered-fun entry
)))
874 (ef-write-n-bytes-fun entry
)
876 (canonize-external-format external-format entry
)))))
877 (dolist (entry *output-routines
*)
878 (when (and (subtypep type
(first entry
))
879 (eq buffering
(second entry
))
880 (or (not (fifth entry
))
881 (eq external-format
(fifth entry
))))
882 (return-from pick-output-routine
883 (values (symbol-function (third entry
))
886 ;; KLUDGE: dealing with the buffering here leads to excessive code
889 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
890 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
891 if
(subtypep type
`(unsigned-byte ,i
))
892 do
(return-from pick-output-routine
896 (lambda (stream byte
)
897 (output-wrapper (stream (/ i
8) (:none
) nil
)
898 (loop for j from
0 below
(/ i
8)
899 do
(setf (sap-ref-8 (buffer-sap obuf
)
901 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
903 (lambda (stream byte
)
904 (output-wrapper (stream (/ i
8) (:full
) nil
)
905 (loop for j from
0 below
(/ i
8)
906 do
(setf (sap-ref-8 (buffer-sap obuf
)
908 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
911 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
912 if
(subtypep type
`(signed-byte ,i
))
913 do
(return-from pick-output-routine
917 (lambda (stream byte
)
918 (output-wrapper (stream (/ i
8) (:none
) nil
)
919 (loop for j from
0 below
(/ i
8)
920 do
(setf (sap-ref-8 (buffer-sap obuf
)
922 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
924 (lambda (stream byte
)
925 (output-wrapper (stream (/ i
8) (:full
) nil
)
926 (loop for j from
0 below
(/ i
8)
927 do
(setf (sap-ref-8 (buffer-sap obuf
)
929 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
933 ;;;; input routines and related noise
935 ;;; a list of all available input routines. Each element is a list of
936 ;;; the element-type input, the function name, and the number of bytes
938 (defvar *input-routines
* ())
940 ;;; Return whether a primitive partial read operation on STREAM's FD
941 ;;; would (probably) block. Signal a `simple-stream-error' if the
942 ;;; system call implementing this operation fails.
944 ;;; It is "may" instead of "would" because "would" is not quite
945 ;;; correct on win32. However, none of the places that use it require
946 ;;; further assurance than "may" versus "will definitely not".
947 (defun sysread-may-block-p (stream)
949 ;; This answers T at EOF on win32, I think.
950 (not (sb!win32
:handle-listen
(fd-stream-fd stream
)))
952 (not (sb!unix
:unix-simple-poll
(fd-stream-fd stream
) :input
0)))
954 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
955 ;;; then fill the input buffer, and return the number of bytes read. Throws
956 ;;; to EOF-INPUT-CATCHER if the eof was reached.
957 (defun refill-input-buffer (stream)
958 (let ((fd (fd-stream-fd stream
))
965 ;; Check for blocking input before touching the stream if we are to
966 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
967 ;; read(). Regular files should never block, so we can elide the check.
968 (if (and (neq :regular
(fd-stream-fd-type stream
))
969 (sysread-may-block-p stream
))
972 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
973 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
975 (closed-flame stream
)
977 (simple-stream-perror "couldn't read from ~S" stream errno
)
979 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
980 ;; to wait for input if read tells us EWOULDBLOCK.
981 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
)
982 (fd-stream-serve-events stream
))
983 (signal-timeout 'io-timeout
986 :seconds
(fd-stream-timeout stream
)))
988 ;; Since the read should not block, we'll disable the
989 ;; interrupts here, so that we don't accidentally unwind and
990 ;; leave the stream in an inconsistent state.
992 ;; Execute the nlx outside without-interrupts to ensure the
993 ;; resulting thunk is stack-allocatable.
994 ((lambda (return-reason)
996 ((nil)) ; fast path normal cases
997 ((:wait-for-input
) (go #!-win32
:wait-for-input
#!+win32
:main
))
998 ((:closed-flame
) (go :closed-flame
))
999 ((:read-error
) (go :read-error
))))
1001 ;; Check the buffer: if it is null, then someone has closed
1002 ;; the stream from underneath us. This is not ment to fix
1003 ;; multithreaded races, but to deal with interrupt handlers
1004 ;; closing the stream.
1007 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
1008 (sap (buffer-sap ibuf
))
1009 (length (buffer-length ibuf
))
1010 (head (buffer-head ibuf
))
1011 (tail (buffer-tail ibuf
)))
1012 (declare (index length head tail
)
1013 (inline sb
!unix
:unix-read
))
1014 (unless (zerop head
)
1015 (cond ((eql head tail
)
1016 ;; Buffer is empty, but not at yet reset -- make it so.
1019 (reset-buffer ibuf
))
1021 ;; Buffer has things in it, but they are not at the
1022 ;; head -- move them there.
1023 (let ((n (- tail head
)))
1024 (system-area-ub8-copy sap head sap
0 n
)
1026 (buffer-head ibuf
) head
1028 (buffer-tail ibuf
) tail
)))))
1029 (setf (fd-stream-listen stream
) nil
)
1030 (setf (values count errno
)
1031 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
1034 #!+win32 sb
!unix
:eintr
1035 #!-win32 sb
!unix
:ewouldblock
)
1036 (return :wait-for-input
)
1037 (return :read-error
)))
1039 (setf (fd-stream-listen stream
) :eof
)
1040 (/show0
"THROWing EOF-INPUT-CATCHER")
1041 (throw 'eof-input-catcher nil
))
1043 ;; Success! (Do not use INCF, for sake of other threads.)
1044 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
1047 ;;; Make sure there are at least BYTES number of bytes in the input
1048 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1049 (defmacro input-at-least
(stream bytes
)
1050 (let ((stream-var (gensym "STREAM"))
1051 (bytes-var (gensym "BYTES"))
1052 (buffer-var (gensym "IBUF")))
1053 `(let* ((,stream-var
,stream
)
1055 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
1057 (when (>= (- (buffer-tail ,buffer-var
)
1058 (buffer-head ,buffer-var
))
1061 (refill-input-buffer ,stream-var
)))))
1063 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
1065 (let ((stream-var (gensym "STREAM"))
1066 (retry-var (gensym "RETRY"))
1067 (element-var (gensym "ELT")))
1068 `(let* ((,stream-var
,stream
)
1069 (ibuf (fd-stream-ibuf ,stream-var
))
1072 (when (fd-stream-eof-forced-p ,stream-var
)
1073 (setf (fd-stream-eof-forced-p ,stream-var
) nil
)
1074 (return-from use-instead
1075 (eof-or-lose ,stream-var
,eof-error
,eof-value
)))
1076 (let ((,element-var nil
)
1077 (decode-break-reason nil
))
1078 (do ((,retry-var t
))
1080 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1081 (let* ((instead (fd-stream-instead ,stream-var
))
1082 (result (vector-pop instead
))
1083 (pointer (fill-pointer instead
)))
1085 (setf (fd-stream-listen ,stream-var
) nil
))
1086 (return-from use-instead result
))
1088 (catch 'eof-input-catcher
1089 (setf decode-break-reason
1090 (block decode-break-reason
1091 (input-at-least ,stream-var
,(if (consp bytes
)
1093 `(setq size
,bytes
)))
1094 (let* ((byte (sap-ref-8 (buffer-sap ibuf
) (buffer-head ibuf
))))
1095 (declare (ignorable byte
))
1096 ,@(when (consp bytes
)
1097 `((let ((sap (buffer-sap ibuf
))
1098 (head (buffer-head ibuf
)))
1099 (declare (ignorable sap head
))
1100 (setq size
,(cadr bytes
))
1101 (input-at-least ,stream-var size
))))
1102 (setq ,element-var
(locally ,@read-forms
))
1103 (setq ,retry-var nil
))
1105 (when decode-break-reason
1106 (when (stream-decoding-error-and-handle
1107 stream decode-break-reason
)
1108 (setq ,retry-var nil
)
1109 (throw 'eof-input-catcher nil
)))
1111 (let ((octet-count (- (buffer-tail ibuf
)
1112 (buffer-head ibuf
))))
1113 (when (or (zerop octet-count
)
1114 (and (not ,element-var
)
1115 (not decode-break-reason
)
1116 (stream-decoding-error-and-handle
1117 stream octet-count
)))
1118 (setq ,retry-var nil
))))))
1120 (incf (buffer-head ibuf
) size
)
1123 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1125 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1126 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
1127 (let ((stream-var (gensym "STREAM"))
1128 (element-var (gensym "ELT")))
1129 `(let* ((,stream-var
,stream
)
1130 (ibuf (fd-stream-ibuf ,stream-var
)))
1131 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1132 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var
)
1134 (catch 'eof-input-catcher
1135 (input-at-least ,stream-var
,bytes
)
1136 (locally ,@read-forms
))))
1138 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1141 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1143 (defmacro def-input-routine
/variable-width
(name
1144 (type external-format size sap head
)
1147 (defun ,name
(stream eof-error eof-value
)
1148 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1149 (let ((,sap
(buffer-sap ibuf
))
1150 (,head
(buffer-head ibuf
)))
1152 (setf *input-routines
*
1153 (nconc *input-routines
*
1154 (list (list ',type
',name
1 ',external-format
))))))
1156 (defmacro def-input-routine
(name
1157 (type size sap head
)
1160 (defun ,name
(stream eof-error eof-value
)
1161 (input-wrapper (stream ,size eof-error eof-value
)
1162 (let ((,sap
(buffer-sap ibuf
))
1163 (,head
(buffer-head ibuf
)))
1165 (setf *input-routines
*
1166 (nconc *input-routines
*
1167 (list (list ',type
',name
',size nil
))))))
1169 ;;; STREAM-IN routine for reading a string char
1170 (def-input-routine input-character
1171 (character 1 sap head
)
1172 (code-char (sap-ref-8 sap head
)))
1174 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1175 (def-input-routine input-unsigned-8bit-byte
1176 ((unsigned-byte 8) 1 sap head
)
1177 (sap-ref-8 sap head
))
1179 ;;; STREAM-IN routine for reading a signed 8 bit number
1180 (def-input-routine input-signed-8bit-number
1181 ((signed-byte 8) 1 sap head
)
1182 (signed-sap-ref-8 sap head
))
1184 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1185 (def-input-routine input-unsigned-16bit-byte
1186 ((unsigned-byte 16) 2 sap head
)
1187 (sap-ref-16 sap head
))
1189 ;;; STREAM-IN routine for reading a signed 16 bit number
1190 (def-input-routine input-signed-16bit-byte
1191 ((signed-byte 16) 2 sap head
)
1192 (signed-sap-ref-16 sap head
))
1194 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1195 (def-input-routine input-unsigned-32bit-byte
1196 ((unsigned-byte 32) 4 sap head
)
1197 (sap-ref-32 sap head
))
1199 ;;; STREAM-IN routine for reading a signed 32 bit number
1200 (def-input-routine input-signed-32bit-byte
1201 ((signed-byte 32) 4 sap head
)
1202 (signed-sap-ref-32 sap head
))
1206 (def-input-routine input-unsigned-64bit-byte
1207 ((unsigned-byte 64) 8 sap head
)
1208 (sap-ref-64 sap head
))
1209 (def-input-routine input-signed-64bit-byte
1210 ((signed-byte 64) 8 sap head
)
1211 (signed-sap-ref-64 sap head
)))
1213 ;;; Find an input routine to use given the type. Return as multiple
1214 ;;; values the routine, the real type transfered, and the number of
1215 ;;; bytes per element (and for character types string input routine).
1216 (defun pick-input-routine (type &optional external-format
)
1217 (when (subtypep type
'character
)
1218 (let ((entry (get-external-format-or-lose external-format
)))
1219 (return-from pick-input-routine
1220 (values (ef-read-char-fun entry
)
1223 (ef-read-n-chars-fun entry
)
1224 (ef-char-size entry
)
1225 (canonize-external-format external-format entry
)))))
1226 (dolist (entry *input-routines
*)
1227 (when (and (subtypep type
(first entry
))
1228 (or (not (fourth entry
))
1229 (eq external-format
(fourth entry
))))
1230 (return-from pick-input-routine
1231 (values (symbol-function (second entry
))
1234 ;; FIXME: let's do it the hard way, then (but ignore things like
1235 ;; endianness, efficiency, and the necessary coupling between these
1236 ;; and the output routines). -- CSR, 2004-02-09
1237 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1238 if
(subtypep type
`(unsigned-byte ,i
))
1239 do
(return-from pick-input-routine
1241 (lambda (stream eof-error eof-value
)
1242 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1243 (let ((sap (buffer-sap ibuf
))
1244 (head (buffer-head ibuf
)))
1245 (loop for j from
0 below
(/ i
8)
1249 (sap-ref-8 sap
(+ head j
))))
1250 finally
(return result
)))))
1253 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1254 if
(subtypep type
`(signed-byte ,i
))
1255 do
(return-from pick-input-routine
1257 (lambda (stream eof-error eof-value
)
1258 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1259 (let ((sap (buffer-sap ibuf
))
1260 (head (buffer-head ibuf
)))
1261 (loop for j from
0 below
(/ i
8)
1265 (sap-ref-8 sap
(+ head j
))))
1266 finally
(return (if (logbitp (1- i
) result
)
1267 (dpb result
(byte i
0) -
1)
1272 ;;; the N-BIN method for FD-STREAMs
1274 ;;; Note that this blocks in UNIX-READ. It is generally used where
1275 ;;; there is a definite amount of reading to be done, so blocking
1276 ;;; isn't too problematical.
1277 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1278 &aux
(total-copied 0))
1279 (declare (type fd-stream stream
))
1280 (declare (type index start requested total-copied
))
1281 (aver (= (length (fd-stream-instead stream
)) 0))
1284 (let* ((remaining-request (- requested total-copied
))
1285 (ibuf (fd-stream-ibuf stream
))
1286 (head (buffer-head ibuf
))
1287 (tail (buffer-tail ibuf
))
1288 (available (- tail head
))
1289 (n-this-copy (min remaining-request available
))
1290 (this-start (+ start total-copied
))
1291 (this-end (+ this-start n-this-copy
))
1292 (sap (buffer-sap ibuf
)))
1293 (declare (type index remaining-request head tail available
))
1294 (declare (type index n-this-copy
))
1296 ;; Prevent failure caused by memmove() hitting a write-protected page
1297 ;; and the fault handler losing, since it thinks you're not in Lisp.
1298 ;; This is wasteful, but better than being randomly broken (lp#1366263).
1299 (when (> this-end this-start
)
1301 (system-area-pointer
1302 (setf (sap-ref-8 buffer this-start
) (sap-ref-8 buffer this-start
)
1303 (sap-ref-8 buffer
(1- this-end
)) (sap-ref-8 buffer
(1- this-end
))))
1304 ((simple-array (unsigned-byte 8) (*))
1305 (setf (aref buffer this-start
) (aref buffer this-start
)
1306 (aref buffer
(1- this-end
)) (aref buffer
(1- this-end
))))
1307 ((simple-array * (*))
1308 ;; We might have an array of UNSIGNED-BYTE-32 here, but the
1309 ;; bounding indices act as if it were UNSIGNED-BYTE-8.
1310 ;; This is strange, and in direct contradiction to what %BYTE-BLT
1311 ;; believes it accepts. i.e. according to the comments,
1312 ;; it's for want of error checking that this works at all.
1313 (with-pinned-objects (buffer)
1314 (let ((sap (vector-sap buffer
)))
1315 (setf (sap-ref-8 sap this-start
) (sap-ref-8 sap this-start
)
1316 (sap-ref-8 sap
(1- this-end
)) (sap-ref-8 sap
(1- this-end
))))))))
1317 ;; Copy data from stream buffer into user's buffer.
1318 (%byte-blt sap head buffer this-start this-end
)
1319 (incf (buffer-head ibuf
) n-this-copy
)
1320 (incf total-copied n-this-copy
)
1321 ;; Maybe we need to refill the stream buffer.
1322 (cond (;; If there were enough data in the stream buffer, we're done.
1323 (eql total-copied requested
)
1324 (return total-copied
))
1325 (;; If EOF, we're done in another way.
1326 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1328 (error 'end-of-file
:stream stream
)
1329 (return total-copied
)))
1330 ;; Otherwise we refilled the stream buffer, so fall
1331 ;; through into another pass of the loop.
1334 (defun fd-stream-resync (stream)
1335 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1337 (funcall (ef-resync-fun entry
) stream
))))
1339 (defun get-fd-stream-character-sizer (stream)
1340 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1342 (ef-bytes-for-char-fun entry
))))
1344 (defun fd-stream-character-size (stream char
)
1345 (let ((sizer (get-fd-stream-character-sizer stream
)))
1346 (when sizer
(funcall sizer char
))))
1348 (defun fd-stream-string-size (stream string
)
1349 (let ((sizer (get-fd-stream-character-sizer stream
)))
1351 (loop for char across string summing
(funcall sizer char
)))))
1353 (defun find-external-format (external-format)
1354 (when external-format
1355 (get-external-format external-format
)))
1357 (defun variable-width-external-format-p (ef-entry)
1358 (and ef-entry
(not (null (ef-resync-fun ef-entry
)))))
1360 (defun bytes-for-char-fun (ef-entry)
1361 (if ef-entry
(ef-bytes-for-char-fun ef-entry
) (constantly 1)))
1363 (defmacro define-unibyte-mapping-external-format
1364 (canonical-name (&rest other-names
) &body exceptions
)
1365 (let ((->code-name
(symbolicate canonical-name
'-
>code-mapper
))
1366 (code->-name
(symbolicate 'code-
> canonical-name
'-mapper
))
1367 (get-bytes-name (symbolicate 'get- canonical-name
'-bytes
))
1368 (string->-name
(symbolicate 'string-
> canonical-name
))
1369 (define-string*-name
(symbolicate 'define- canonical-name
'-
>string
*))
1370 (string*-name
(symbolicate canonical-name
'-
>string
*))
1371 (define-string-name (symbolicate 'define- canonical-name
'-
>string
))
1372 (string-name (symbolicate canonical-name
'-
>string
))
1373 (->string-aref-name
(symbolicate canonical-name
'-
>string-aref
)))
1375 (define-unibyte-mapper ,-
>code-name
,code-
>-name
1377 (declaim (inline ,get-bytes-name
))
1378 (defun ,get-bytes-name
(string pos
)
1379 (declare (optimize speed
(safety 0))
1380 (type simple-string string
)
1381 (type array-range pos
))
1382 (get-latin-bytes #',code-
>-name
,canonical-name string pos
))
1383 (defun ,string-
>-name
(string sstart send null-padding
)
1384 (declare (optimize speed
(safety 0))
1385 (type simple-string string
)
1386 (type array-range sstart send
))
1387 (values (string->latin% string sstart send
#',get-bytes-name null-padding
)))
1388 (defmacro ,define-string
*-name
(accessor type
)
1389 (declare (ignore type
))
1390 (let ((name (make-od-name ',string
*-name accessor
)))
1392 (defun ,name
(string sstart send array astart aend
)
1393 (,(make-od-name 'latin-
>string
* accessor
)
1394 string sstart send array astart aend
#',',-
>code-name
)))))
1395 (instantiate-octets-definition ,define-string
*-name
)
1396 (defmacro ,define-string-name
(accessor type
)
1397 (declare (ignore type
))
1398 (let ((name (make-od-name ',string-name accessor
)))
1400 (defun ,name
(array astart aend
)
1401 (,(make-od-name 'latin-
>string accessor
)
1402 array astart aend
#',',-
>code-name
)))))
1403 (instantiate-octets-definition ,define-string-name
)
1404 (define-unibyte-external-format ,canonical-name
,other-names
1405 (let ((octet (,code-
>-name bits
)))
1407 (setf (sap-ref-8 sap tail
) octet
)
1408 (external-format-encoding-error stream bits
)))
1409 (let ((code (,-
>code-name byte
)))
1412 (return-from decode-break-reason
1)))
1416 (defmacro define-unibyte-external-format
1417 (canonical-name (&rest other-names
)
1418 out-form in-form octets-to-string-symbol string-to-octets-symbol
)
1419 `(define-external-format/variable-width
(,canonical-name
,@other-names
)
1424 ,octets-to-string-symbol
1425 ,string-to-octets-symbol
))
1427 (defmacro define-external-format
/variable-width
1428 (external-format output-restart replacement-character
1429 out-size-expr out-expr in-size-expr in-expr
1430 octets-to-string-sym string-to-octets-sym
)
1431 (let* ((name (first external-format
))
1432 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1433 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1434 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1435 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1436 (resync-function (symbolicate "RESYNC/" name
))
1437 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1438 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1439 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1440 (n-buffer (gensym "BUFFER")))
1442 (defun ,size-function
(byte)
1443 (declare (ignorable byte
))
1445 (defun ,out-function
(stream string flush-p start end
)
1446 (let ((start (or start
0))
1447 (end (or end
(length string
))))
1448 (declare (type index start end
))
1449 (synchronize-stream-output stream
)
1450 (unless (<= 0 start end
(length string
))
1451 (sequence-bounding-indices-bad-error string start end
))
1454 (let ((obuf (fd-stream-obuf stream
)))
1455 (string-dispatch (simple-base-string
1456 #!+sb-unicode
(simple-array character
(*))
1459 (let ((len (buffer-length obuf
))
1460 (sap (buffer-sap obuf
))
1462 (tail (buffer-tail obuf
)))
1463 (declare (type index tail
)
1464 ;; STRING bounds have already been checked.
1465 (optimize (safety 0)))
1466 (,@(if output-restart
1467 `(catch 'output-nothing
)
1470 ((or (= start end
) (< (- len tail
) 4)))
1471 (let* ((byte (aref string start
))
1472 (bits (char-code byte
))
1473 (size ,out-size-expr
))
1476 (setf (buffer-tail obuf
) tail
)
1479 ;; Exited via CATCH: skip the current character.
1483 (flush-output-buffer stream
)))
1485 (flush-output-buffer stream
))))
1486 (def-output-routines/variable-width
(,format
1493 (if (eql byte
#\Newline
)
1494 (setf (fd-stream-output-column stream
) 0)
1495 (incf (fd-stream-output-column stream
)))
1496 (let ((bits (char-code byte
))
1497 (sap (buffer-sap obuf
))
1498 (tail (buffer-tail obuf
)))
1500 (defun ,in-function
(stream buffer start requested eof-error-p
1501 &aux
(total-copied 0))
1502 (declare (type fd-stream stream
)
1503 (type index start requested total-copied
)
1505 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1507 (when (fd-stream-eof-forced-p stream
)
1508 (setf (fd-stream-eof-forced-p stream
) nil
)
1509 (return-from ,in-function
0))
1510 (do ((instead (fd-stream-instead stream
)))
1511 ((= (fill-pointer instead
) 0)
1512 (setf (fd-stream-listen stream
) nil
))
1513 (setf (aref buffer
(+ start total-copied
)) (vector-pop instead
))
1515 (when (= requested total-copied
)
1516 (when (= (fill-pointer instead
) 0)
1517 (setf (fd-stream-listen stream
) nil
))
1518 (return-from ,in-function total-copied
)))
1521 (let* ((ibuf (fd-stream-ibuf stream
))
1522 (head (buffer-head ibuf
))
1523 (tail (buffer-tail ibuf
))
1524 (sap (buffer-sap ibuf
))
1525 (decode-break-reason nil
))
1526 (declare (type index head tail
))
1527 ;; Copy data from stream buffer into user's buffer.
1528 (do ((size nil nil
))
1529 ((or (= tail head
) (= requested total-copied
)))
1530 (setf decode-break-reason
1531 (block decode-break-reason
1532 ,@(when (consp in-size-expr
)
1533 `((when (> ,(car in-size-expr
) (- tail head
))
1535 (let ((byte (sap-ref-8 sap head
)))
1536 (declare (ignorable byte
))
1537 (setq size
,(if (consp in-size-expr
) (cadr in-size-expr
) in-size-expr
))
1538 (when (> size
(- tail head
))
1540 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1544 (setf (buffer-head ibuf
) head
)
1545 (when decode-break-reason
1546 ;; If we've already read some characters on when the invalid
1547 ;; code sequence is detected, we return immediately. The
1548 ;; handling of the error is deferred until the next call
1549 ;; (where this check will be false). This allows establishing
1550 ;; high-level handlers for decode errors (for example
1551 ;; automatically resyncing in Lisp comments).
1552 (when (plusp total-copied
)
1553 (return-from ,in-function total-copied
))
1554 (when (stream-decoding-error-and-handle
1555 stream decode-break-reason
)
1557 (error 'end-of-file
:stream stream
)
1558 (return-from ,in-function total-copied
)))
1559 ;; we might have been given stuff to use instead, so
1560 ;; we have to return (and trust our caller to know
1561 ;; what to do about TOTAL-COPIED being 0).
1562 (return-from ,in-function total-copied
)))
1563 (setf (buffer-head ibuf
) head
)
1564 ;; Maybe we need to refill the stream buffer.
1565 (cond ( ;; If was data in the stream buffer, we're done.
1566 (plusp total-copied
)
1567 (return total-copied
))
1568 ( ;; If EOF, we're done in another way.
1569 (or (eq decode-break-reason
'eof
)
1570 (null (catch 'eof-input-catcher
1571 (refill-input-buffer stream
))))
1573 (error 'end-of-file
:stream stream
)
1574 (return total-copied
)))
1575 ;; Otherwise we refilled the stream buffer, so fall
1576 ;; through into another pass of the loop.
1578 (def-input-routine/variable-width
,in-char-function
(character
1582 (let ((byte (sap-ref-8 sap head
)))
1583 (declare (ignorable byte
))
1585 (defun ,resync-function
(stream)
1586 (let ((ibuf (fd-stream-ibuf stream
))
1588 (catch 'eof-input-catcher
1590 (incf (buffer-head ibuf
))
1591 (input-at-least stream
,(if (consp in-size-expr
) (car in-size-expr
) `(setq size
,in-size-expr
)))
1592 (unless (block decode-break-reason
1593 (let* ((sap (buffer-sap ibuf
))
1594 (head (buffer-head ibuf
))
1595 (byte (sap-ref-8 sap head
)))
1596 (declare (ignorable byte
))
1597 ,@(when (consp in-size-expr
)
1598 `((setq size
,(cadr in-size-expr
))
1599 (input-at-least stream size
)))
1600 (setf head
(buffer-head ibuf
))
1604 (defun ,read-c-string-function
(sap element-type
)
1605 (declare (type system-area-pointer sap
))
1607 (declare (optimize (speed 3) (safety 0)))
1608 (let* ((stream ,name
)
1609 (size 0) (head 0) (byte 0) (char nil
)
1610 (decode-break-reason nil
)
1611 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1612 (setf decode-break-reason
1613 (block decode-break-reason
1614 (setf byte
(sap-ref-8 sap head
)
1615 size
,(if (consp in-size-expr
)
1621 (when decode-break-reason
1622 (c-string-decoding-error
1623 ,name sap head decode-break-reason
))
1624 (when (zerop (char-code char
))
1626 (string (make-string length
:element-type element-type
)))
1627 (declare (ignorable stream
)
1628 (type index head length
) ;; size
1629 (type (unsigned-byte 8) byte
)
1630 (type (or null character
) char
)
1631 (type string string
))
1633 (dotimes (index length string
)
1634 (setf decode-break-reason
1635 (block decode-break-reason
1636 (setf byte
(sap-ref-8 sap head
)
1637 size
,(if (consp in-size-expr
)
1643 (when decode-break-reason
1644 (c-string-decoding-error
1645 ,name sap head decode-break-reason
))
1646 (setf (aref string index
) char
)))))
1648 (defun ,output-c-string-function
(string)
1649 (declare (type simple-string string
))
1651 (declare (optimize (speed 3) (safety 0)))
1652 (let* ((length (length string
))
1653 (char-length (make-array (1+ length
) :element-type
'index
))
1655 (+ (loop for i of-type index below length
1656 for byte of-type character
= (aref string i
)
1657 for bits
= (char-code byte
)
1658 sum
(setf (aref char-length i
)
1659 (the index
,out-size-expr
)) of-type index
)
1660 (let* ((byte (code-char 0))
1661 (bits (char-code byte
)))
1662 (declare (ignorable byte bits
))
1663 (setf (aref char-length length
)
1664 (the index
,out-size-expr
)))))
1666 (,n-buffer
(make-array buffer-length
1667 :element-type
'(unsigned-byte 8)))
1669 (declare (type index length buffer-length tail
)
1672 (with-pinned-objects (,n-buffer
)
1673 (let ((sap (vector-sap ,n-buffer
)))
1674 (declare (system-area-pointer sap
))
1675 (loop for i of-type index below length
1676 for byte of-type character
= (aref string i
)
1677 for bits
= (char-code byte
)
1678 for size of-type index
= (aref char-length i
)
1683 (byte (code-char bits
))
1684 (size (aref char-length length
)))
1685 (declare (ignorable bits byte size
))
1689 (let ((entry (%make-external-format
1690 :names
',external-format
1691 :default-replacement-character
,replacement-character
1692 :read-n-chars-fun
#',in-function
1693 :read-char-fun
#',in-char-function
1694 :write-n-bytes-fun
#',out-function
1695 ,@(mapcan #'(lambda (buffering)
1696 (list (intern (format nil
"WRITE-CHAR-~A-BUFFERED-FUN" buffering
) :keyword
)
1697 `#',(intern (format nil format
(string buffering
)))))
1698 '(:none
:line
:full
))
1699 :resync-fun
#',resync-function
1700 :bytes-for-char-fun
#',size-function
1701 :read-c-string-fun
#',read-c-string-function
1702 :write-c-string-fun
#',output-c-string-function
1703 :octets-to-string-fun
(lambda (&rest rest
)
1704 (declare (dynamic-extent rest
))
1705 (apply ',octets-to-string-sym rest
))
1706 :string-to-octets-fun
(lambda (&rest rest
)
1707 (declare (dynamic-extent rest
))
1708 (apply ',string-to-octets-sym rest
)))))
1709 (dolist (ef ',external-format
)
1710 (setf (gethash ef
*external-formats
*) entry
))))))
1712 ;;;; utility functions (misc routines, etc)
1714 ;;; Fill in the various routine slots for the given type. INPUT-P and
1715 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1716 ;;; set prior to calling this routine.
1717 (defun set-fd-stream-routines (fd-stream element-type external-format
1718 input-p output-p buffer-p
)
1719 (let* ((target-type (case element-type
1720 (unsigned-byte '(unsigned-byte 8))
1721 (signed-byte '(signed-byte 8))
1722 (:default
'character
)
1724 (character-stream-p (subtypep target-type
'character
))
1725 (bivalent-stream-p (eq element-type
:default
))
1726 normalized-external-format
1728 (bin-routine #'ill-bin
)
1731 (cin-routine #'ill-in
)
1734 (input-type nil
) ;calculated from bin-type/cin-type
1735 (input-size nil
) ;calculated from bin-size/cin-size
1736 (read-n-characters #'ill-in
)
1737 (bout-routine #'ill-bout
)
1740 (cout-routine #'ill-out
)
1745 (output-bytes #'ill-bout
))
1747 ;; Ensure that we have buffers in the desired direction(s) only,
1748 ;; getting new ones and dropping/resetting old ones as necessary.
1749 (let ((obuf (fd-stream-obuf fd-stream
)))
1753 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1755 (setf (fd-stream-obuf fd-stream
) nil
)
1756 (release-buffer obuf
))))
1758 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1762 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1764 (setf (fd-stream-ibuf fd-stream
) nil
)
1765 (release-buffer ibuf
))))
1767 ;; FIXME: Why only for output? Why unconditionally?
1769 (setf (fd-stream-output-column fd-stream
) 0))
1771 (when (and character-stream-p
(eq external-format
:default
))
1772 (/show0
"/getting default external format")
1773 (setf external-format
(default-external-format)))
1776 (flet ((no-input-routine ()
1777 (error "could not find any input routine for ~
1778 ~/sb!impl:print-type-specifier/"
1780 (when (or (not character-stream-p
) bivalent-stream-p
)
1781 (setf (values bin-routine bin-type bin-size read-n-characters
1782 char-size normalized-external-format
)
1783 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1786 (unless bin-routine
(no-input-routine)))
1787 (when character-stream-p
1788 (setf (values cin-routine cin-type cin-size read-n-characters
1789 char-size normalized-external-format
)
1790 (pick-input-routine target-type external-format
))
1791 (unless cin-routine
(no-input-routine))))
1792 (setf (fd-stream-in fd-stream
) cin-routine
1793 (fd-stream-bin fd-stream
) bin-routine
)
1794 ;; character type gets preferential treatment
1795 (setf input-size
(or cin-size bin-size
))
1796 (setf input-type
(or cin-type bin-type
))
1797 (when normalized-external-format
1798 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1799 (fd-stream-char-size fd-stream
) char-size
))
1800 (when (= (or cin-size
1) (or bin-size
1) 1)
1801 (setf (fd-stream-n-bin fd-stream
) ;XXX
1802 (if (and character-stream-p
(not bivalent-stream-p
))
1804 #'fd-stream-read-n-bytes
))
1805 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1806 ;; for character and (unsigned-byte 8) streams. In these
1807 ;; cases, fast-read-* will read from the
1808 ;; ansi-stream-(c)in-buffer, saving function calls.
1809 ;; Otherwise, the various data-reading functions in the stream
1810 ;; structure will be called.
1812 (not bivalent-stream-p
)
1813 ;; temporary disable on :io streams
1815 (cond (character-stream-p
1816 (setf (ansi-stream-cin-buffer fd-stream
)
1817 (make-array +ansi-stream-in-buffer-length
+
1818 :element-type
'character
)))
1819 ((equal target-type
'(unsigned-byte 8))
1820 (setf (ansi-stream-in-buffer fd-stream
)
1821 (make-array +ansi-stream-in-buffer-length
+
1822 :element-type
'(unsigned-byte 8))))))))
1825 (when (or (not character-stream-p
) bivalent-stream-p
)
1826 (setf (values bout-routine bout-type bout-size output-bytes
1827 char-size normalized-external-format
)
1828 (let ((buffering (fd-stream-buffering fd-stream
)))
1829 (if bivalent-stream-p
1830 (pick-output-routine '(unsigned-byte 8)
1831 (if (eq :line buffering
)
1835 (pick-output-routine target-type buffering external-format
))))
1836 (unless bout-routine
1837 (error "could not find any output routine for ~S buffered ~S"
1838 (fd-stream-buffering fd-stream
)
1840 (when character-stream-p
1841 (setf (values cout-routine cout-type cout-size output-bytes
1842 char-size normalized-external-format
)
1843 (pick-output-routine target-type
1844 (fd-stream-buffering fd-stream
)
1846 (unless cout-routine
1847 (error "could not find any output routine for ~S buffered ~S"
1848 (fd-stream-buffering fd-stream
)
1850 (when normalized-external-format
1851 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1852 (fd-stream-char-size fd-stream
) char-size
))
1853 (when character-stream-p
1854 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1855 (setf (fd-stream-out fd-stream
) cout-routine
1856 (fd-stream-bout fd-stream
) bout-routine
1857 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1858 #'fd-sout
#'ill-out
))
1859 (setf output-size
(or cout-size bout-size
))
1860 (setf output-type
(or cout-type bout-type
)))
1862 (when (and input-size output-size
1863 (not (eq input-size output-size
)))
1864 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1865 input-type input-size
1866 output-type output-size
))
1867 (setf (fd-stream-element-size fd-stream
)
1868 (or input-size output-size
))
1870 (setf (fd-stream-element-type fd-stream
)
1871 (cond ((equal input-type output-type
)
1877 ((subtypep input-type output-type
)
1879 ((subtypep output-type input-type
)
1882 (error "Input type (~/sb!impl:print-type-specifier/) and
1883 output type (~/sb!impl:print-type-specifier/) ~
1885 input-type output-type
))))))
1887 ;;; Handles the resource-release aspects of stream closing, and marks
1889 (defun release-fd-stream-resources (fd-stream)
1892 ;; Drop handlers first.
1893 (when (fd-stream-handler fd-stream
)
1894 (remove-fd-handler (fd-stream-handler fd-stream
))
1895 (setf (fd-stream-handler fd-stream
) nil
))
1896 ;; Disable interrupts so that a asynch unwind will not leave
1897 ;; us with a dangling finalizer (that would close the same
1898 ;; --possibly reassigned-- FD again), or a stream with a closed
1899 ;; FD that appears open.
1900 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1901 (set-closed-flame fd-stream
)
1902 (cancel-finalization fd-stream
))
1903 ;; On error unwind from WITHOUT-INTERRUPTS.
1904 (serious-condition (e)
1906 ;; Release all buffers. If this is undone, or interrupted,
1907 ;; we're still safe: buffers have finalizers of their own.
1908 (release-fd-stream-buffers fd-stream
))
1910 ;;; Flushes the current input buffer and any supplied replacements,
1911 ;;; and returns the input buffer, and the amount of flushed input in
1913 (defun flush-input-buffer (stream)
1914 (let ((unread (length (fd-stream-instead stream
))))
1915 (setf (fill-pointer (fd-stream-instead stream
)) 0)
1916 (let ((ibuf (fd-stream-ibuf stream
)))
1918 (let ((head (buffer-head ibuf
))
1919 (tail (buffer-tail ibuf
)))
1920 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1921 (values nil unread
)))))
1923 (defun fd-stream-clear-input (stream)
1924 (flush-input-buffer stream
)
1927 (sb!win32
:handle-clear-input
(fd-stream-fd stream
))
1928 (setf (fd-stream-listen stream
) nil
))
1930 (catch 'eof-input-catcher
1931 (loop until
(sysread-may-block-p stream
)
1933 (refill-input-buffer stream
)
1934 (reset-buffer (fd-stream-ibuf stream
)))
1937 ;;; Handle miscellaneous operations on FD-STREAM.
1938 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
1939 (declare (ignore arg2
))
1942 (labels ((do-listen ()
1943 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1944 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
1945 (fd-stream-listen fd-stream
)
1947 (sb!win32
:handle-listen
(fd-stream-fd fd-stream
))
1949 ;; If the read can block, LISTEN will certainly return NIL.
1950 (if (sysread-may-block-p fd-stream
)
1952 ;; Otherwise select(2) and CL:LISTEN have slightly
1953 ;; different semantics. The former returns that an FD
1954 ;; is readable when a read operation wouldn't block.
1955 ;; That includes EOF. However, LISTEN must return NIL
1957 (progn (catch 'eof-input-catcher
1958 ;; r-b/f too calls select, but it shouldn't
1959 ;; block as long as read can return once w/o
1961 (refill-input-buffer fd-stream
))
1962 ;; At this point either IBUF-HEAD != IBUF-TAIL
1963 ;; and FD-STREAM-LISTEN is NIL, in which case
1964 ;; we should return T, or IBUF-HEAD ==
1965 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1966 ;; which case we should return :EOF for this
1967 ;; call and all future LISTEN call on this stream.
1968 ;; Call ourselves again to determine which case
1973 (decf (buffer-head (fd-stream-ibuf fd-stream
))
1974 (fd-stream-character-size fd-stream arg1
)))
1976 ;; Drop input buffers
1977 (setf (ansi-stream-in-index fd-stream
) +ansi-stream-in-buffer-length
+
1978 (ansi-stream-cin-buffer fd-stream
) nil
1979 (ansi-stream-in-buffer fd-stream
) nil
)
1981 ;; We got us an abort on our hands.
1982 (let ((outputp (fd-stream-obuf fd-stream
))
1983 (file (fd-stream-file fd-stream
))
1984 (orig (fd-stream-original fd-stream
)))
1985 ;; This takes care of the important stuff -- everything
1986 ;; rest is cleaning up the file-system, which we cannot
1987 ;; do on some platforms as long as the file is open.
1988 (release-fd-stream-resources fd-stream
)
1989 ;; We can't do anything unless we know what file were
1990 ;; dealing with, and we don't want to do anything
1991 ;; strange unless we were writing to the file.
1992 (when (and outputp file
)
1994 ;; If the original is EQ to file we are appending to
1995 ;; and can just close the file without renaming.
1996 (unless (eq orig file
)
1997 ;; We have a handle on the original, just revert.
1998 (multiple-value-bind (okay err
)
1999 (sb!unix
:unix-rename orig file
)
2000 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2001 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2004 (error 'simple-stream-error
2006 "~@<Couldn't restore ~S to its original contents ~
2007 from ~S while closing ~S: ~2I~_~A~:>"
2009 (list file orig fd-stream
(strerror err
))
2010 :stream fd-stream
))))
2011 ;; We can't restore the original, and aren't
2012 ;; appending, so nuke that puppy.
2014 ;; FIXME: This is currently the fate of superseded
2015 ;; files, and according to the CLOSE spec this is
2016 ;; wrong. However, there seems to be no clean way to
2017 ;; do that that doesn't involve either copying the
2018 ;; data (bad if the :abort resulted from a full
2019 ;; disk), or renaming the old file temporarily
2020 ;; (probably bad because stream opening becomes more
2022 (multiple-value-bind (okay err
)
2023 (sb!unix
:unix-unlink file
)
2025 (error 'simple-file-error
2028 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2030 (list file fd-stream
(strerror err
)))))))))
2032 (finish-fd-stream-output fd-stream
)
2033 (let ((orig (fd-stream-original fd-stream
)))
2034 (when (and orig
(fd-stream-delete-original fd-stream
))
2035 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2037 (error 'simple-file-error
2040 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2042 (list orig fd-stream
(strerror err
)))))))
2043 ;; In case of no-abort close, don't *really* close the
2044 ;; stream until the last moment -- the cleaning up of the
2045 ;; original can be done first.
2046 (release-fd-stream-resources fd-stream
))))
2048 (fd-stream-clear-input fd-stream
))
2050 (flush-output-buffer fd-stream
))
2052 (finish-fd-stream-output fd-stream
))
2054 (fd-stream-element-type fd-stream
))
2056 (fd-stream-element-mode fd-stream
))
2058 (fd-stream-external-format fd-stream
))
2060 (plusp (the (integer 0)
2061 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2065 (fd-stream-output-column fd-stream
))
2067 (unless (fd-stream-file fd-stream
)
2068 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2069 ;; "should signal an error of type TYPE-ERROR if stream is not
2070 ;; a stream associated with a file". Too bad there's no very
2071 ;; appropriate value for the EXPECTED-TYPE slot..
2072 (error 'simple-type-error
2074 :expected-type
'fd-stream
2075 :format-control
"~S is not a stream associated with a file."
2076 :format-arguments
(list fd-stream
)))
2078 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2079 atime mtime ctime blksize blocks
)
2080 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2081 (declare (ignore ino nlink uid gid rdev
2082 atime mtime ctime blksize blocks
))
2084 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2087 (truncate size
(fd-stream-element-size fd-stream
))))
2089 (let* ((handle (fd-stream-fd fd-stream
))
2090 (element-size (fd-stream-element-size fd-stream
)))
2091 (multiple-value-bind (got native-size
)
2092 (sb!win32
:get-file-size-ex handle
0)
2094 ;; Might be a block device, in which case we fall back to
2095 ;; a non-atomic workaround:
2096 (let* ((here (sb!unix
:unix-lseek handle
0 sb
!unix
:l_incr
))
2097 (there (sb!unix
:unix-lseek handle
0 sb
!unix
:l_xtnd
)))
2098 (when (and here there
)
2099 (sb!unix
:unix-lseek handle here sb
!unix
:l_set
)
2100 (truncate there element-size
)))
2101 (truncate native-size element-size
)))))
2102 (:file-string-length
2104 (character (fd-stream-character-size fd-stream arg1
))
2105 (string (fd-stream-string-size fd-stream arg1
))))
2108 (fd-stream-set-file-position fd-stream arg1
)
2109 (fd-stream-get-file-position fd-stream
)))))
2111 ;; FIXME: Think about this.
2113 ;; (defun finish-fd-stream-output (fd-stream)
2114 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2115 ;; (loop while (fd-stream-output-queue fd-stream)
2116 ;; ;; FIXME: SIGINT while waiting for a timeout will
2117 ;; ;; cause a timeout here.
2118 ;; do (when (and (not (serve-event timeout)) timeout)
2119 ;; (signal-timeout 'io-timeout
2120 ;; :stream fd-stream
2121 ;; :direction :write
2122 ;; :seconds timeout)))))
2124 (defun finish-fd-stream-output (stream)
2125 (flush-output-buffer stream
)
2127 ((null (fd-stream-output-queue stream
)))
2128 (aver (fd-stream-serve-events stream
))
2129 (serve-all-events)))
2131 (defun fd-stream-get-file-position (stream)
2132 (declare (fd-stream stream
))
2134 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2135 (declare (type (or (alien sb
!unix
:unix-offset
) null
) posn
))
2136 ;; We used to return NIL for errno==ESPIPE, and signal an error
2137 ;; in other failure cases. However, CLHS says to return NIL if
2138 ;; the position cannot be determined -- so that's what we do.
2139 (when (integerp posn
)
2140 ;; Adjust for buffered output: If there is any output
2141 ;; buffered, the *real* file position will be larger
2142 ;; than reported by lseek() because lseek() obviously
2143 ;; cannot take into account output we have not sent
2145 (dolist (buffer (fd-stream-output-queue stream
))
2146 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2147 (let ((obuf (fd-stream-obuf stream
)))
2149 (incf posn
(buffer-tail obuf
))))
2150 ;; Adjust for unread input: If there is any input
2151 ;; read from UNIX but not supplied to the user of the
2152 ;; stream, the *real* file position will smaller than
2153 ;; reported, because we want to look like the unread
2154 ;; stuff is still available.
2155 (let ((ibuf (fd-stream-ibuf stream
)))
2157 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2158 ;; Divide bytes by element size.
2159 (truncate posn
(fd-stream-element-size stream
))))))
2161 (defun fd-stream-set-file-position (stream position-spec
)
2162 (declare (fd-stream stream
))
2163 (check-type position-spec
2164 (or (alien sb
!unix
:unix-offset
) (member nil
:start
:end
))
2165 "valid file position designator")
2168 ;; Make sure we don't have any output pending, because if we
2169 ;; move the file pointer before writing this stuff, it will be
2170 ;; written in the wrong location.
2171 (finish-fd-stream-output stream
)
2172 ;; Disable interrupts so that interrupt handlers doing output
2175 (unless (fd-stream-output-finished-p stream
)
2176 ;; We got interrupted and more output came our way during
2177 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2178 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2179 ;; so we prefer to do things like this...
2181 ;; Clear out any pending input to force the next read to go to
2183 (flush-input-buffer stream
)
2184 ;; Trash cached value for listen, so that we check next time.
2185 (setf (fd-stream-listen stream
) nil
)
2187 (multiple-value-bind (offset origin
)
2190 (values 0 sb
!unix
:l_set
))
2192 (values 0 sb
!unix
:l_xtnd
))
2194 (values (* position-spec
(fd-stream-element-size stream
))
2196 (declare (type (alien sb
!unix
:unix-offset
) offset
))
2197 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2199 ;; CLHS says to return true if the file-position was set
2200 ;; successfully, and NIL otherwise. We are to signal an error
2201 ;; only if the given position was out of bounds, and that is
2202 ;; dealt with above. In times past we used to return NIL for
2203 ;; errno==ESPIPE, and signal an error in other cases.
2205 ;; FIXME: We are still liable to signal an error if flushing
2207 (return-from fd-stream-set-file-position
2208 (typep posn
'(alien sb
!unix
:unix-offset
))))))))
2211 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2213 ;;; Create a stream for the given Unix file descriptor.
2215 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2216 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2217 ;;; default to allowing input.
2219 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2221 ;;; BUFFERING indicates the kind of buffering to use.
2223 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2224 ;;; NIL (the default), then wait forever. When we time out, we signal
2227 ;;; FILE is the name of the file (will be returned by PATHNAME).
2229 ;;; NAME is used to identify the stream when printed.
2231 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2232 ;;; handle blocking IO on the stream.
2233 (defun make-fd-stream (fd
2237 (output nil output-p
)
2238 (element-type 'base-char
)
2240 (external-format :default
)
2250 (format nil
"file ~A" file
)
2251 (format nil
"descriptor ~W" fd
)))
2253 (declare (type index fd
) (type (or real null
) timeout
)
2254 (type (member :none
:line
:full
) buffering
))
2255 (cond ((not (or input-p output-p
))
2257 ((not (or input output
))
2258 (error "File descriptor must be opened either for input or output.")))
2259 (let* ((constructor (ecase class
2260 (fd-stream '%make-fd-stream
)
2261 (form-tracking-stream '%make-form-tracking-stream
)))
2262 (element-mode (stream-element-type-stream-element-mode element-type
))
2263 (stream (funcall constructor
2266 #!-win32
(sb!unix
:fd-type fd
)
2268 #!+win32
(if serve-events
2274 :delete-original delete-original
2276 :buffering buffering
2277 :dual-channel-p dual-channel-p
2278 :element-mode element-mode
2279 :serve-events serve-events
2282 (coerce timeout
'single-float
)
2284 (set-fd-stream-routines stream element-type external-format
2285 input output input-buffer-p
)
2289 (sb!unix
:unix-close fd
)
2291 (format *terminal-io
* "** closed file descriptor ~W **~%"
2296 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2297 ;;; :RENAME-AND-DELETE and :RENAME options.
2298 (defun pick-backup-name (name)
2299 (declare (type simple-string name
))
2300 (concatenate 'simple-string name
".bak"))
2302 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2303 ;;; access, since we don't want to trash unwritable files even if we
2304 ;;; technically can. We return true if we succeed in renaming.
2305 (defun rename-the-old-one (namestring original
)
2306 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2307 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2308 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2311 (error 'simple-file-error
2312 :pathname namestring
2314 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2315 :format-arguments
(list namestring original
(strerror err
))))))
2317 (defun open (filename
2320 (element-type 'base-char
)
2321 (if-exists nil if-exists-given
)
2322 (if-does-not-exist nil if-does-not-exist-given
)
2323 (external-format :default
)
2324 ;; private options - use at your own risk
2328 &aux
; Squelch assignment warning.
2329 (direction direction
)
2330 (if-does-not-exist if-does-not-exist
)
2331 (if-exists if-exists
))
2332 "Return a stream which reads from or writes to FILENAME.
2334 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2335 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2336 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2337 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2338 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2339 See the manual for details."
2341 ;; Calculate useful stuff.
2342 (multiple-value-bind (input output mask
)
2344 (:input
(values t nil sb
!unix
:o_rdonly
))
2345 (:output
(values nil t sb
!unix
:o_wronly
))
2346 (:io
(values t t sb
!unix
:o_rdwr
))
2347 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2348 (declare (type index mask
))
2349 (let* ( ;; PATHNAME is the pathname we associate with the stream.
2350 (pathname (merge-pathnames filename
))
2351 (physical (physicalize-pathname pathname
))
2352 (truename (probe-file physical
))
2353 ;; NAMESTRING is the native namestring we open the file with.
2354 (namestring (cond (truename
2355 (native-namestring truename
:as-file t
))
2357 (and input
(eq if-does-not-exist
:create
))
2358 (and (eq direction
:io
)
2359 (not if-does-not-exist-given
)))
2360 (native-namestring physical
:as-file t
)))))
2361 (flet ((open-error (format-control &rest format-arguments
)
2362 (declare (optimize allow-non-returning-tail-call
))
2363 (error 'simple-file-error
2365 :format-control format-control
2366 :format-arguments format-arguments
)))
2367 ;; Process if-exists argument if we are doing any output.
2369 (unless if-exists-given
2371 (if (eq (pathname-version pathname
) :newest
)
2375 ((:new-version
:error nil
)
2376 (setf mask
(logior mask sb
!unix
:o_excl
)))
2377 ((:rename
:rename-and-delete
)
2378 (setf mask
(logior mask sb
!unix
:o_creat
)))
2380 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2382 (setf mask
(logior mask sb
!unix
:o_append
)))))
2384 (setf if-exists
:ignore-this-arg
)))
2386 (unless if-does-not-exist-given
2387 (setf if-does-not-exist
2388 (cond ((eq direction
:input
) :error
)
2390 (member if-exists
'(:overwrite
:append
)))
2392 ((eq direction
:probe
)
2396 (cond ((and if-exists-given
2398 (eq if-exists
:new-version
))
2399 (open-error "OPEN :IF-EXISTS :NEW-VERSION is not supported ~
2400 when a new version must be created."))
2401 ((eq if-does-not-exist
:create
)
2402 (setf mask
(logior mask sb
!unix
:o_creat
)))
2403 ((not (member if-exists
'(:error nil
))))
2404 ;; Both if-does-not-exist and if-exists now imply
2405 ;; that there will be no opening of files, and either
2406 ;; an error would be signalled, or NIL returned
2407 ((and (not if-exists
) (not if-does-not-exist
))
2409 ((and if-exists if-does-not-exist
)
2410 (open-error "OPEN :IF-DOES-NOT-EXIST ~s ~
2411 :IF-EXISTS ~s will always signal an error."
2412 if-does-not-exist if-exists
))
2415 (open-error "File exists ~s." pathname
)
2416 (return-from open
)))
2418 (open-error "File does not exist ~s." pathname
))
2420 (return-from open
)))
2421 (let ((original (case if-exists
2422 ((:rename
:rename-and-delete
)
2423 (pick-backup-name namestring
))
2424 ((:append
:overwrite
)
2425 ;; KLUDGE: Prevent CLOSE from deleting
2426 ;; appending streams when called with :ABORT T
2428 (delete-original (eq if-exists
:rename-and-delete
))
2430 (when (and original
(not (eq original namestring
)))
2431 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2432 ;; whether the file already exists, make sure the original
2433 ;; file is not a directory, and keep the mode.
2436 (multiple-value-bind (okay err
/dev inode orig-mode
)
2437 (sb!unix
:unix-stat namestring
)
2438 (declare (ignore inode
)
2439 (type (or index null
) orig-mode
))
2442 (when (and output
(= (logand orig-mode
#o170000
)
2444 (error 'simple-file-error
2447 "can't open ~S for output: is a directory"
2448 :format-arguments
(list namestring
)))
2449 (setf mode
(logand orig-mode
#o777
))
2451 ((eql err
/dev sb
!unix
:enoent
)
2454 (simple-file-perror "can't find ~S"
2458 (rename-the-old-one namestring original
))
2460 (setf delete-original nil
)
2461 ;; In order to use :SUPERSEDE instead, we have to make
2462 ;; sure SB!UNIX:O_CREAT corresponds to
2463 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2464 ;; because of IF-EXISTS being :RENAME.
2465 (unless (eq if-does-not-exist
:create
)
2467 (logior (logandc2 mask sb
!unix
:o_creat
)
2469 (setf if-exists
:supersede
))))
2471 ;; Now we can try the actual Unix open(2).
2472 (multiple-value-bind (fd errno
)
2474 (sb!unix
:unix-open namestring mask mode
2475 #!+win32
:overlapped
#!+win32 overlapped
)
2476 (values nil
#!-win32 sb
!unix
:enoent
2477 #!+win32 sb
!win32
::error_file_not_found
))
2478 (flet ((vanilla-open-error ()
2479 (simple-file-perror "error opening ~S" pathname errno
)))
2482 ((:input
:output
:io
)
2483 ;; For O_APPEND opened files, lseek returns 0 until first write.
2484 ;; So we jump ahead here.
2485 (when (eq if-exists
:append
)
2486 (sb!unix
:unix-lseek fd
0 sb
!unix
:l_xtnd
))
2491 :element-type element-type
2492 :external-format external-format
2495 :delete-original delete-original
2503 (%make-fd-stream
:name namestring
2506 :element-type element-type
)))
2509 ((eql errno
#!-win32 sb
!unix
:enoent
2510 #!+win32 sb
!win32
::error_file_not_found
)
2511 (case if-does-not-exist
2512 (:error
(vanilla-open-error))
2514 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2517 ((and (eql errno
#!-win32 sb
!unix
:eexist
2518 #!+win32 sb
!win32
::error_file_exists
)
2522 (vanilla-open-error))))))))))
2526 ;;; the stream connected to the controlling terminal, or NIL if there is none
2529 ;;; the stream connected to the standard input (file descriptor 0)
2532 ;;; the stream connected to the standard output (file descriptor 1)
2535 ;;; the stream connected to the standard error output (file descriptor 2)
2538 ;;; This is called when the cold load is first started up, and may also
2539 ;;; be called in an attempt to recover from nested errors.
2540 (defun stream-cold-init-or-reset ()
2542 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2543 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2544 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2545 (setf *error-output
* (make-synonym-stream '*stderr
*))
2546 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2547 (setf *debug-io
* *query-io
*)
2548 (setf *trace-output
* *standard-output
*)
2551 (defun stream-deinit ()
2552 (setq *tty
* nil
*stdin
* nil
*stdout
* nil
*stderr
* nil
)
2553 ;; Unbind to make sure we're not accidently dealing with it
2554 ;; before we're ready (or after we think it's been deinitialized).
2555 (%makunbound
'*available-buffers
*))
2557 (defun stdstream-external-format (fd)
2558 #!-win32
(declare (ignore fd
))
2559 (let* ((keyword (cond #!+(and win32 sb-unicode
)
2560 ((sb!win32
::console-handle-p fd
)
2563 (default-external-format))))
2564 (ef (get-external-format keyword
))
2565 (replacement (ef-default-replacement-character ef
)))
2566 `(,keyword
:replacement
,replacement
)))
2568 ;;; This is called whenever a saved core is restarted.
2569 (defun stream-reinit (&optional init-buffers-p
)
2570 (when init-buffers-p
2571 (aver (not (boundp '*available-buffers
*)))
2572 (setf *available-buffers
* nil
))
2573 (with-simple-output-to-string (*error-output
*)
2574 (multiple-value-bind (in out err
)
2575 #!-win32
(values 0 1 2)
2576 #!+win32
(sb!win32
::get-std-handles
)
2578 (nul-stream (name inputp outputp
)
2579 (let* ((nul-name #.
(coerce "NUL" 'simple-base-string
))
2582 ((and inputp outputp
)
2583 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdwr
))
2585 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdonly
))
2587 (sb!win32
:unixlike-open nul-name sb
!unix
:o_wronly
))
2589 ;; Not quite sure what to do in this case.
2597 :element-type
:default
2598 :serve-events inputp
2600 :external-format
(stdstream-external-format nul-handle
))))
2601 (stdio-stream (handle name inputp outputp
)
2605 ;; If no actual handle was present, create a stream to NUL
2606 (nul-stream name inputp outputp
))
2614 :element-type
:default
2615 :serve-events inputp
2616 :external-format
(stdstream-external-format handle
))))))
2617 (setf *stdin
* (stdio-stream in
"standard input" t nil
)
2618 *stdout
* (stdio-stream out
"standard output" nil t
)
2619 *stderr
* (stdio-stream err
"standard error" nil t
))))
2621 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))
2623 ;; FIXME: what is this call to COERCE doing? XC can't dump non-base-strings.
2624 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2625 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2628 (make-fd-stream tty
:name
"the terminal"
2629 :input t
:output t
:buffering
:line
2630 :external-format
(stdstream-external-format tty
)
2633 (make-two-way-stream *stdin
* *stdout
*))))
2634 (princ (get-output-stream-string *error-output
*) *stderr
*))
2639 ;;; the Unix way to beep
2640 (defun beep (stream)
2641 (write-char (code-char bell-char-code
) stream
)
2642 (finish-output stream
))
2644 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2645 ;;; by the filesys stuff to get and set the file name.
2647 ;;; FIXME: misleading name, screwy interface
2648 (defun file-name (stream &optional new-name
)
2649 (when (typep stream
'fd-stream
)
2651 (setf (fd-stream-pathname stream
) new-name
)
2652 (setf (fd-stream-file stream
)
2653 (native-namestring (physicalize-pathname new-name
)
2657 (fd-stream-pathname stream
)))))
2659 ;; Fix the INPUT-CHAR-POS slot of STREAM after having consumed characters
2660 ;; from the CIN-BUFFER. This operation is done upon exit from a FAST-READ-CHAR
2661 ;; loop, and for each buffer refill inside the loop.
2662 (defun update-input-char-pos (stream &optional
(end +ansi-stream-in-buffer-length
+))
2663 (do ((chars (ansi-stream-cin-buffer stream
))
2664 (pos (form-tracking-stream-input-char-pos stream
))
2665 (i (ansi-stream-in-index stream
) (1+ i
)))
2667 (setf (form-tracking-stream-input-char-pos stream
) pos
))
2668 (let ((char (aref chars i
)))
2669 (when (and (eql char
#\Newline
)
2670 ;; record it only if it wasn't unread and re-read
2671 (> pos
(form-tracking-stream-last-newline stream
)))
2672 (vector-push-extend pos
(form-tracking-stream-newlines stream
))
2673 (setf (form-tracking-stream-last-newline stream
) pos
))
2676 (defun tracking-stream-misc (stream operation
&optional arg1 arg2
)
2677 ;; The :UNREAD operation will never be invoked because STREAM has a buffer,
2678 ;; so unreading is implemented entirely within ANSI-STREAM-UNREAD-CHAR.
2679 ;; But we do need to prevent attempts to change the absolute position.
2683 (error 'simple-stream-error
2684 :format-control
"~S is not positionable"
2685 :format-arguments
(list stream
))
2686 (fd-stream-get-file-position stream
)))
2687 (t ; call next method
2688 (fd-stream-misc-routine stream operation arg1 arg2
))))
2690 ;; Using (get-std-handle-or-null +std-error-handle+) instead of the file
2691 ;; descriptor might make this work on win32, but I don't know.
2693 (defun !make-cold-stderr-stream
() (make-broadcast-stream))
2695 (macrolet ((stderr () 2))
2696 (!defglobal
*!cold-stderr-buf
* " ")
2697 (defun !make-cold-stderr-stream
()
2699 :out
(lambda (stream ch
)
2700 (declare (ignore stream
))
2701 (let ((b (truly-the (simple-base-string 1) *!cold-stderr-buf
*)))
2702 (setf (char b
0) ch
)
2703 (sb!unix
:unix-write
(stderr) b
0 1)))
2704 :sout
(lambda (stream string start end
)
2705 (declare (ignore stream
))
2706 (flet ((out (s start len
)
2707 (sb!unix
:unix-write
(stderr) s start len
)))
2708 (if (typep string
'simple-base-string
)
2709 (out string start
(- end start
))
2710 (let ((n (- end start
)))
2711 ;; will croak if there is any non-BASE-CHAR in the string
2712 (out (replace (make-array n
:element-type
'base-char
)
2713 string
:start2 start
) 0 n
)))))
2714 :misc
(constantly nil
))))