1 ;;;; streams for UNIX file descriptors
3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!IMPL")
16 ;;;; Streams hold BUFFER objects, which contain a SAP, size of the
17 ;;;; memory area the SAP stands for (LENGTH bytes), and HEAD and TAIL
18 ;;;; indexes which delimit the "valid", or "active" area of the
19 ;;;; memory. HEAD is inclusive, TAIL is exclusive.
21 ;;;; Buffers get allocated lazily, and are recycled by returning them
22 ;;;; to the *AVAILABLE-BUFFERS* list. Every buffer has it's own
23 ;;;; finalizer, to take care of releasing the SAP memory when a stream
24 ;;;; is not properly closed.
26 ;;;; The code aims to provide a limited form of thread and interrupt
27 ;;;; safety: parallel writes and reads may lose output or input, cause
28 ;;;; interleaved IO, etc -- but they should not corrupt memory. The
29 ;;;; key to doing this is to read buffer state once, and update the
30 ;;;; state based on the read state:
32 ;;;; (let ((tail (buffer-tail buffer)))
34 ;;;; (setf (buffer-tail buffer) (+ tail n)))
38 ;;;; (let ((tail (buffer-tail buffer)))
40 ;;;; (incf (buffer-tail buffer) n))
43 (defstruct (buffer (:constructor %make-buffer
(sap length
)))
44 (sap (missing-arg) :type system-area-pointer
:read-only t
)
45 (length (missing-arg) :type index
:read-only t
)
48 (declaim (freeze-type buffer
))
50 (defvar *available-buffers
* ()
52 "List of available buffers.")
54 (defvar *available-buffers-lock
* (sb!thread
:make-mutex
55 :name
"lock for *AVAILABLE-BUFFERS*")
57 "Mutex for access to *AVAILABLE-BUFFERS*.")
59 (defmacro with-available-buffers-lock
((&optional
) &body body
)
60 ;; CALL-WITH-SYSTEM-MUTEX because streams are low-level enough to be
61 ;; async signal safe, and in particular a C-c that brings up the
62 ;; debugger while holding the mutex would lose badly.
63 `(sb!thread
::with-system-mutex
(*available-buffers-lock
*)
66 (defconstant +bytes-per-buffer
+ (* 4 1024)
68 "Default number of bytes per buffer.")
70 (defun alloc-buffer (&optional
(size +bytes-per-buffer
+))
71 ;; Don't want to allocate & unwind before the finalizer is in place.
73 (let* ((sap (allocate-system-memory size
))
74 (buffer (%make-buffer sap size
)))
75 (when (zerop (sap-int sap
))
76 (error "Could not allocate ~D bytes for buffer." size
))
77 (finalize buffer
(lambda ()
78 (deallocate-system-memory sap size
))
83 ;; Don't go for the lock if there is nothing to be had -- sure,
84 ;; another thread might just release one before we get it, but that
85 ;; is not worth the cost of locking. Also release the lock before
86 ;; allocation, since it's going to take a while.
87 (if *available-buffers
*
88 (or (with-available-buffers-lock ()
89 (pop *available-buffers
*))
93 (declaim (inline reset-buffer
))
94 (defun reset-buffer (buffer)
95 (setf (buffer-head buffer
) 0
96 (buffer-tail buffer
) 0)
99 (defun release-buffer (buffer)
100 (reset-buffer buffer
)
101 (with-available-buffers-lock ()
102 (push buffer
*available-buffers
*)))
105 ;;;; the FD-STREAM structure
107 ;;; Coarsely characterizes the element type of an FD-STREAM w.r.t.
108 ;;; its SUBTYPEP relations to the relevant CHARACTER and
109 ;;; ([UN]SIGNED-BYTE 8) types. This coarse characterization enables
110 ;;; dispatching on the element type as needed by {READ,WRITE}-SEQUENCE
111 ;;; without calling SUBTYPEP.
112 (deftype stream-element-mode
()
113 '(member character unsigned-byte signed-byte
:bivalent
))
115 (defstruct (fd-stream
116 (:constructor %make-fd-stream
)
117 (:conc-name fd-stream-
)
118 (:predicate fd-stream-p
)
119 (:include ansi-stream
120 (misc #'fd-stream-misc-routine
))
123 ;; the name of this stream
125 ;; the file this stream is for
127 ;; the backup file namestring for the old file, for :IF-EXISTS
128 ;; :RENAME or :RENAME-AND-DELETE.
129 (original nil
:type
(or simple-string null
))
130 (delete-original nil
) ; for :if-exists :rename-and-delete
131 ;;; the number of bytes per element
132 (element-size 1 :type index
)
133 ;; the type of element being transfered
134 (element-type 'base-char
)
135 ;; coarse characterization of the element type. see description of
136 ;; STREAM-ELEMENT-MODE type.
137 (element-mode :bivalent
:type stream-element-mode
)
138 ;; the Unix file descriptor
139 (fd -
1 :type
#!-win32 fixnum
#!+win32 sb
!vm
:signed-word
)
140 ;; What do we know about the FD?
141 (fd-type :unknown
:type keyword
)
142 ;; controls when the output buffer is flushed
143 (buffering :full
:type
(member :full
:line
:none
))
144 ;; controls whether the input buffer must be cleared before output
145 ;; (must be done for files, not for sockets, pipes and other data
146 ;; sources where input and output aren't related). non-NIL means
147 ;; don't clear input buffer.
149 ;; character position if known -- this may run into bignums, but
150 ;; we probably should flip it into null then for efficiency's sake...
151 (output-column nil
:type
(or unsigned-byte null
))
152 ;; T if input is waiting on FD. :EOF if we hit EOF.
153 (listen nil
:type
(member nil t
:eof
))
154 ;; T if serve-event is allowed when this stream blocks
155 (serve-events nil
:type boolean
)
158 (instead (make-array 0 :element-type
'character
:adjustable t
:fill-pointer t
) :type
(array character
(*)))
159 (ibuf nil
:type
(or buffer null
))
160 (eof-forced-p nil
:type
(member t nil
))
163 (obuf nil
:type
(or buffer null
))
165 ;; output flushed, but not written due to non-blocking io?
168 ;; timeout specified for this stream as seconds or NIL if none
169 (timeout nil
:type
(or single-float null
))
170 ;; pathname of the file this stream is opened to (returned by PATHNAME)
171 (pathname nil
:type
(or pathname null
))
172 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
173 (external-format :latin-1
)
174 ;; fixed width, or function to call with a character
175 (char-size 1 :type
(or fixnum function
))
176 (output-bytes #'ill-out
:type function
))
178 (defun fd-stream-bivalent-p (stream)
179 (eq (fd-stream-element-mode stream
) :bivalent
))
181 (defmethod print-object ((fd-stream fd-stream
) stream
)
182 (declare (type stream stream
))
183 (print-unreadable-object (fd-stream stream
:type t
:identity t
)
184 (format stream
"for ~S" (fd-stream-name fd-stream
))))
186 ;;; This is a separate buffer management function, as it wants to be
187 ;;; clever about locking -- grabbing the lock just once.
188 (defun release-fd-stream-buffers (fd-stream)
189 (let ((ibuf (fd-stream-ibuf fd-stream
))
190 (obuf (fd-stream-obuf fd-stream
))
191 (queue (loop for item in
(fd-stream-output-queue fd-stream
)
193 collect
(reset-buffer item
))))
195 (push (reset-buffer ibuf
) queue
))
197 (push (reset-buffer obuf
) queue
))
198 ;; ...so, anything found?
200 ;; detach from stream
201 (setf (fd-stream-ibuf fd-stream
) nil
202 (fd-stream-obuf fd-stream
) nil
203 (fd-stream-output-queue fd-stream
) nil
)
204 ;; splice to *available-buffers*
205 (with-available-buffers-lock ()
206 (setf *available-buffers
* (nconc queue
*available-buffers
*))))))
208 ;;;; FORM-TRACKING-STREAM
210 ;; The compiler uses this to record for each input subform the start and
211 ;; end positions as character offsets. Measuring in characters rather than
212 ;; bytes is both better suited to the task - in that it is consistent with
213 ;; reporting of "point" by Emacs - and faster than querying FILE-POSITION.
214 ;; The slowness of FILE-POSITION on an FD-STREAM is due to making a system
215 ;; call every time, to ensure that the case of an append-only stream works
216 ;; correctly (where the OS forces all writes to the end), and other factors.
218 (defstruct (form-tracking-stream
219 (:constructor %make-form-tracking-stream
)
221 (misc #'tracking-stream-misc
)
224 ;; a function which is called for events on this stream.
225 (observer (lambda (x y z
) (declare (ignore x y z
))) :type function
)
226 ;; A vector of the character position of each #\Newline seen
227 (newlines (make-array 10 :fill-pointer
0 :adjustable t
))
228 (last-newline -
1 :type index-or-minus-1
)
229 ;; Better than reporting that a reader error occurred at a position
230 ;; before any whitespace (or equivalently, a macro producing no value),
231 ;; we can note the position at the first "good" character.
232 (form-start-byte-pos)
233 (form-start-char-pos))
235 (defun line/col-from-charpos
236 (stream &optional
(charpos (ansi-stream-input-char-pos stream
)))
237 (let* ((newlines (form-tracking-stream-newlines stream
))
238 (index (position charpos newlines
:test
#'>= :from-end t
)))
239 ;; Line numbers traditionally begin at 1, columns at 0.
241 ;; INDEX is 1 less than the number of newlines seen
242 ;; up to and including this startpos.
243 ;; e.g. index=0 => 1 newline seen => line=2
245 ;; 1 char after the newline = column 0
246 (- charpos
(aref newlines index
) 1))
247 ;; zero newlines were seen
250 ;;;; CORE OUTPUT FUNCTIONS
252 ;;; Buffer the section of THING delimited by START and END by copying
253 ;;; to output buffer(s) of stream.
254 (defun buffer-output (stream thing start end
)
255 (declare (index start end
))
257 (error ":END before :START!"))
259 ;; Copy bytes from THING to buffers.
260 (flet ((copy-to-buffer (buffer tail count
)
261 (declare (buffer buffer
) (index tail count
))
263 (let ((sap (buffer-sap buffer
)))
266 (system-area-ub8-copy thing start sap tail count
))
267 ((simple-unboxed-array (*))
268 (copy-ub8-to-system-area thing start sap tail count
))))
269 ;; Not INCF! If another thread has moved tail from under
270 ;; us, we don't want to accidentally increment tail
271 ;; beyond buffer-length.
272 (setf (buffer-tail buffer
) (+ count tail
))
275 ;; First copy is special: the buffer may already contain
276 ;; something, or be even full.
277 (let* ((obuf (fd-stream-obuf stream
))
278 (tail (buffer-tail obuf
))
279 (space (- (buffer-length obuf
) tail
)))
281 (copy-to-buffer obuf tail
(min space
(- end start
)))
282 (go :more-output-p
)))
284 ;; Later copies should always have an empty buffer, since
285 ;; they are freshly flushed, but if another thread is
286 ;; stomping on the same buffer that might not be the case.
287 (let* ((obuf (flush-output-buffer stream
))
288 (tail (buffer-tail obuf
))
289 (space (- (buffer-length obuf
) tail
)))
290 (copy-to-buffer obuf tail
(min space
(- end start
))))
293 (go :flush-and-fill
))))))
295 ;;; Flush the current output buffer of the stream, ensuring that the
296 ;;; new buffer is empty. Returns (for convenience) the new output
297 ;;; buffer -- which may or may not be EQ to the old one. If the is no
298 ;;; queued output we try to write the buffer immediately -- otherwise
299 ;;; we queue it for later.
300 (defun flush-output-buffer (stream)
301 (let ((obuf (fd-stream-obuf stream
)))
303 (let ((head (buffer-head obuf
))
304 (tail (buffer-tail obuf
)))
305 (cond ((eql head tail
)
306 ;; Buffer is already empty -- just ensure that is is
307 ;; set to zero as well.
309 ((fd-stream-output-queue stream
)
310 ;; There is already stuff on the queue -- go directly
313 (%queue-and-replace-output-buffer stream
))
315 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
316 ;; whatever is left over. Otherwise wait until we can write.
318 (synchronize-stream-output stream
)
320 (let ((length (- tail head
)))
321 (multiple-value-bind (count errno
)
322 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap obuf
)
324 (flet ((queue-or-wait ()
325 (if (fd-stream-serve-events stream
)
326 (return (%queue-and-replace-output-buffer stream
))
327 (or (wait-until-fd-usable (fd-stream-fd stream
) :output
328 (fd-stream-timeout stream
)
330 (signal-timeout 'io-timeout
333 :seconds
(fd-stream-timeout stream
))))))
334 (cond ((eql count length
)
335 ;; Complete write -- we can use the same buffer.
336 (return (reset-buffer obuf
)))
338 ;; Partial write -- update buffer status and
341 (setf (buffer-head obuf
) head
)
344 ((eql errno sb
!unix
:ewouldblock
)
345 ;; Blocking, queue or wair.
347 ;; if interrupted on win32, just try again
348 #!+win32
((eql errno sb
!unix
:eintr
))
350 (simple-stream-perror "Couldn't write to ~s"
351 stream errno
)))))))))))))
353 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
354 (defun %queue-and-replace-output-buffer
(stream)
355 (aver (fd-stream-serve-events stream
))
356 (let ((queue (fd-stream-output-queue stream
))
357 (later (list (or (fd-stream-obuf stream
) (bug "Missing obuf."))))
359 ;; Important: before putting the buffer on queue, give the stream
360 ;; a new one. If we get an interrupt and unwind losing the buffer
361 ;; is relatively OK, but having the same buffer in two places
363 (setf (fd-stream-obuf stream
) new
)
367 (setf (fd-stream-output-queue stream
) later
)))
368 (unless (fd-stream-handler stream
)
369 (setf (fd-stream-handler stream
)
370 (add-fd-handler (fd-stream-fd stream
)
373 (declare (ignore fd
))
374 (write-output-from-queue stream
)))))
377 ;;; This is called by the FD-HANDLER for the stream when output is
379 (defun write-output-from-queue (stream)
380 (aver (fd-stream-serve-events stream
))
381 (synchronize-stream-output stream
)
385 (let* ((buffer (pop (fd-stream-output-queue stream
)))
386 (head (buffer-head buffer
))
387 (length (- (buffer-tail buffer
) head
)))
388 (declare (index head length
))
390 (multiple-value-bind (count errno
)
391 (sb!unix
:unix-write
(fd-stream-fd stream
) (buffer-sap buffer
)
393 (cond ((eql count length
)
394 ;; Complete write, see if we can do another right
395 ;; away, or remove the handler if we're done.
396 (release-buffer buffer
)
397 (cond ((fd-stream-output-queue stream
)
401 (let ((handler (fd-stream-handler stream
)))
403 (setf (fd-stream-handler stream
) nil
)
404 (remove-fd-handler handler
)))))
406 ;; Partial write. Update buffer status and requeue.
407 (aver (< count length
))
408 ;; Do not use INCF! Another thread might have moved head.
409 (setf (buffer-head buffer
) (+ head count
))
410 (push buffer
(fd-stream-output-queue stream
)))
412 ;; We tried to do multiple writes, and finally our
413 ;; luck ran out. Requeue.
414 (push buffer
(fd-stream-output-queue stream
)))
416 ;; Could not write on the first try at all!
418 (simple-stream-perror "Couldn't write to ~S." stream errno
)
420 (if (= errno sb
!unix
:ewouldblock
)
421 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
422 (simple-stream-perror "Couldn't write to ~S"
426 ;;; Try to write THING directly to STREAM without buffering, if
427 ;;; possible. If direct write doesn't happen, buffer.
428 (defun write-or-buffer-output (stream thing start end
)
429 (declare (index start end
))
430 (cond ((fd-stream-output-queue stream
)
431 (buffer-output stream thing start end
))
433 (error ":END before :START!"))
435 (let ((length (- end start
)))
436 (synchronize-stream-output stream
)
437 (multiple-value-bind (count errno
)
438 (sb!unix
:unix-write
(fd-stream-fd stream
) thing start length
)
439 (cond ((eql count length
)
440 ;; Complete write -- done!
443 (aver (< count length
))
444 ;; Partial write -- buffer the rest.
445 (buffer-output stream thing
(+ start count
) end
))
447 ;; Could not write -- buffer or error.
449 (simple-stream-perror "couldn't write to ~s" stream errno
)
451 (if (= errno sb
!unix
:ewouldblock
)
452 (buffer-output stream thing start end
)
453 (simple-stream-perror "couldn't write to ~s" stream errno
)))))))))
455 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
456 ;;; this is not something we want to export. Nikodemus thinks the
457 ;;; right thing is to support a low-level non-stream like IO layer,
458 ;;; akin to java.nio.
459 (declaim (inline output-raw-bytes
))
460 (define-deprecated-function :late
"1.0.8.16" output-raw-bytes write-sequence
461 (stream thing
&optional start end
)
462 (write-or-buffer-output stream thing
(or start
0) (or end
(length thing
))))
464 ;;;; output routines and related noise
466 (defvar *output-routines
* ()
468 "List of all available output routines. Each element is a list of the
469 element-type output, the kind of buffering, the function name, and the number
470 of bytes per element.")
472 ;;; common idioms for reporting low-level stream and file problems
473 (defun simple-stream-perror (note-format stream errno
)
474 (error 'simple-stream-error
476 :format-control
"~@<~?: ~2I~_~A~:>"
477 :format-arguments
(list note-format
(list stream
) (strerror errno
))))
478 (defun simple-file-perror (note-format pathname errno
)
479 (error 'simple-file-error
481 :format-control
"~@<~?: ~2I~_~A~:>"
483 (list note-format
(list pathname
) (strerror errno
))))
485 (defun c-string-encoding-error (external-format code
)
486 (error 'c-string-encoding-error
487 :external-format external-format
489 (defun c-string-decoding-error (external-format sap offset count
)
490 (error 'c-string-decoding-error
491 :external-format external-format
492 :octets
(sap-ref-octets sap offset count
)))
494 ;;; Returning true goes into end of file handling, false will enter another
495 ;;; round of input buffer filling followed by re-entering character decode.
496 (defun stream-decoding-error-and-handle (stream octet-count
)
498 (error 'stream-decoding-error
499 :external-format
(stream-external-format stream
)
501 :octets
(let ((buffer (fd-stream-ibuf stream
)))
502 (sap-ref-octets (buffer-sap buffer
)
506 :report
(lambda (stream)
508 "~@<Attempt to resync the stream at a ~
509 character boundary and continue.~@:>"))
510 (fd-stream-resync stream
)
512 (force-end-of-file ()
513 :report
(lambda (stream)
514 (format stream
"~@<Force an end of file.~@:>"))
515 (setf (fd-stream-eof-forced-p stream
) t
))
516 (input-replacement (string)
517 :report
(lambda (stream)
518 (format stream
"~@<Use string as replacement input, ~
519 attempt to resync at a character ~
520 boundary and continue.~@:>"))
521 :interactive
(lambda ()
522 (format *query-io
* "~@<Enter a string: ~@:>")
523 (finish-output *query-io
*)
524 (list (read *query-io
*)))
525 (let ((string (reverse (string string
)))
526 (instead (fd-stream-instead stream
)))
527 (dotimes (i (length string
))
528 (vector-push-extend (char string i
) instead
))
529 (fd-stream-resync stream
)
530 (when (> (length string
) 0)
531 (setf (fd-stream-listen stream
) t
)))
534 (defun stream-encoding-error-and-handle (stream code
)
536 (error 'stream-encoding-error
537 :external-format
(stream-external-format stream
)
541 :report
(lambda (stream)
542 (format stream
"~@<Skip output of this character.~@:>"))
543 (throw 'output-nothing nil
))
544 (output-replacement (string)
545 :report
(lambda (stream)
546 (format stream
"~@<Output replacement string.~@:>"))
547 :interactive
(lambda ()
548 (format *query-io
* "~@<Enter a string: ~@:>")
549 (finish-output *query-io
*)
550 (list (read *query-io
*)))
551 (let ((string (string string
)))
552 (fd-sout stream
(string string
) 0 (length string
)))
553 (throw 'output-nothing nil
))))
555 (defun external-format-encoding-error (stream code
)
557 (stream-encoding-error-and-handle stream code
)
558 (c-string-encoding-error stream code
)))
560 (defun synchronize-stream-output (stream)
561 ;; If we're reading and writing on the same file, flush buffered
562 ;; input and rewind file position accordingly.
563 (unless (fd-stream-dual-channel-p stream
)
564 (let ((adjust (nth-value 1 (flush-input-buffer stream
))))
565 (unless (eql 0 adjust
)
566 (sb!unix
:unix-lseek
(fd-stream-fd stream
) (- adjust
) sb
!unix
:l_incr
)))))
568 (defun fd-stream-output-finished-p (stream)
569 (let ((obuf (fd-stream-obuf stream
)))
571 (and (zerop (buffer-tail obuf
))
572 (not (fd-stream-output-queue stream
))))))
574 (defmacro output-wrapper
/variable-width
((stream size buffering restart
)
576 (let ((stream-var (gensym "STREAM")))
577 `(let* ((,stream-var
,stream
)
578 (obuf (fd-stream-obuf ,stream-var
))
579 (tail (buffer-tail obuf
))
581 ,(unless (eq (car buffering
) :none
)
582 `(when (< (buffer-length obuf
) (+ tail size
))
583 (setf obuf
(flush-output-buffer ,stream-var
)
584 tail
(buffer-tail obuf
))))
585 ,(unless (eq (car buffering
) :none
)
586 ;; FIXME: Why this here? Doesn't seem necessary.
587 `(synchronize-stream-output ,stream-var
))
589 `(catch 'output-nothing
591 (setf (buffer-tail obuf
) (+ tail size
)))
594 (setf (buffer-tail obuf
) (+ tail size
))))
595 ,(ecase (car buffering
)
597 `(flush-output-buffer ,stream-var
))
599 `(when (eql byte
#\Newline
)
600 (flush-output-buffer ,stream-var
)))
604 (defmacro output-wrapper
((stream size buffering restart
) &body body
)
605 (let ((stream-var (gensym "STREAM")))
606 `(let* ((,stream-var
,stream
)
607 (obuf (fd-stream-obuf ,stream-var
))
608 (tail (buffer-tail obuf
)))
609 ,(unless (eq (car buffering
) :none
)
610 `(when (< (buffer-length obuf
) (+ tail
,size
))
611 (setf obuf
(flush-output-buffer ,stream-var
)
612 tail
(buffer-tail obuf
))))
613 ;; FIXME: Why this here? Doesn't seem necessary.
614 ,(unless (eq (car buffering
) :none
)
615 `(synchronize-stream-output ,stream-var
))
617 `(catch 'output-nothing
619 (setf (buffer-tail obuf
) (+ tail
,size
)))
622 (setf (buffer-tail obuf
) (+ tail
,size
))))
623 ,(ecase (car buffering
)
625 `(flush-output-buffer ,stream-var
))
627 `(when (eql byte
#\Newline
)
628 (flush-output-buffer ,stream-var
)))
632 (defmacro def-output-routines
/variable-width
633 ((name-fmt size restart external-format
&rest bufferings
)
635 (declare (optimize (speed 1)))
640 (intern (format nil name-fmt
(string (car buffering
))))))
642 (defun ,function
(stream byte
)
643 (declare (ignorable byte
))
644 (output-wrapper/variable-width
(stream ,size
,buffering
,restart
)
646 (setf *output-routines
*
647 (nconc *output-routines
*
655 (cdr buffering
)))))))
658 ;;; Define output routines that output numbers SIZE bytes long for the
659 ;;; given bufferings. Use BODY to do the actual output.
660 (defmacro def-output-routines
((name-fmt size restart
&rest bufferings
)
662 (declare (optimize (speed 1)))
667 (intern (format nil name-fmt
(string (car buffering
))))))
669 (defun ,function
(stream byte
)
670 (output-wrapper (stream ,size
,buffering
,restart
)
672 (setf *output-routines
*
673 (nconc *output-routines
*
681 (cdr buffering
)))))))
684 ;;; FIXME: is this used anywhere any more?
685 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
691 (if (eql byte
#\Newline
)
692 (setf (fd-stream-output-column stream
) 0)
693 (incf (fd-stream-output-column stream
)))
694 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
697 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
700 (:none
(unsigned-byte 8))
701 (:full
(unsigned-byte 8)))
702 (setf (sap-ref-8 (buffer-sap obuf
) tail
)
705 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
708 (:none
(signed-byte 8))
709 (:full
(signed-byte 8)))
710 (setf (signed-sap-ref-8 (buffer-sap obuf
) tail
)
713 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
716 (:none
(unsigned-byte 16))
717 (:full
(unsigned-byte 16)))
718 (setf (sap-ref-16 (buffer-sap obuf
) tail
)
721 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
724 (:none
(signed-byte 16))
725 (:full
(signed-byte 16)))
726 (setf (signed-sap-ref-16 (buffer-sap obuf
) tail
)
729 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
732 (:none
(unsigned-byte 32))
733 (:full
(unsigned-byte 32)))
734 (setf (sap-ref-32 (buffer-sap obuf
) tail
)
737 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
740 (:none
(signed-byte 32))
741 (:full
(signed-byte 32)))
742 (setf (signed-sap-ref-32 (buffer-sap obuf
) tail
)
747 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
750 (:none
(unsigned-byte 64))
751 (:full
(unsigned-byte 64)))
752 (setf (sap-ref-64 (buffer-sap obuf
) tail
)
754 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
757 (:none
(signed-byte 64))
758 (:full
(signed-byte 64)))
759 (setf (signed-sap-ref-64 (buffer-sap obuf
) tail
)
762 ;;; the routine to use to output a string. If the stream is
763 ;;; unbuffered, slam the string down the file descriptor, otherwise
764 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
765 ;;; checking to see where the last newline was.
766 (defun fd-sout (stream thing start end
)
767 (declare (type fd-stream stream
) (type string thing
))
768 (let ((start (or start
0))
769 (end (or end
(length (the vector thing
)))))
770 (declare (fixnum start end
))
772 (string-dispatch (simple-base-string
774 (simple-array character
(*))
777 (position #\newline thing
:from-end t
778 :start start
:end end
))))
779 (if (and (typep thing
'base-string
)
780 (eq (fd-stream-external-format-keyword stream
) :latin-1
))
781 (ecase (fd-stream-buffering stream
)
783 (buffer-output stream thing start end
))
785 (buffer-output stream thing start end
)
787 (flush-output-buffer stream
)))
789 (write-or-buffer-output stream thing start end
)))
790 (ecase (fd-stream-buffering stream
)
791 (:full
(funcall (fd-stream-output-bytes stream
)
792 stream thing nil start end
))
793 (:line
(funcall (fd-stream-output-bytes stream
)
794 stream thing last-newline start end
))
795 (:none
(funcall (fd-stream-output-bytes stream
)
796 stream thing t start end
))))
798 (setf (fd-stream-output-column stream
) (- end last-newline
1))
799 (incf (fd-stream-output-column stream
) (- end start
))))))
801 (defstruct (external-format
802 (:constructor %make-external-format
)
804 (:predicate external-format-p
)
805 (:copier %copy-external-format
))
806 ;; All the names that can refer to this external format. The first
807 ;; one is the canonical name.
808 (names (missing-arg) :type list
:read-only t
)
809 (default-replacement-character (missing-arg) :type character
)
810 (read-n-chars-fun (missing-arg) :type function
)
811 (read-char-fun (missing-arg) :type function
)
812 (write-n-bytes-fun (missing-arg) :type function
)
813 (write-char-none-buffered-fun (missing-arg) :type function
)
814 (write-char-line-buffered-fun (missing-arg) :type function
)
815 (write-char-full-buffered-fun (missing-arg) :type function
)
816 ;; Can be nil for fixed-width formats.
817 (resync-fun nil
:type
(or function null
))
818 (bytes-for-char-fun (missing-arg) :type function
)
819 (read-c-string-fun (missing-arg) :type function
)
820 (write-c-string-fun (missing-arg) :type function
)
821 ;; We indirect through symbols in these functions so that a
822 ;; developer working on the octets code can easily redefine things
823 ;; and use the new function definition without redefining the
824 ;; external format as well. The slots above don't do any
825 ;; indirection because a developer working with those slots would be
826 ;; redefining the external format anyway.
827 (octets-to-string-fun (missing-arg) :type function
)
828 (string-to-octets-fun (missing-arg) :type function
))
830 (defun ef-char-size (ef-entry)
831 (if (variable-width-external-format-p ef-entry
)
832 (bytes-for-char-fun ef-entry
)
833 (funcall (bytes-for-char-fun ef-entry
) #\x
)))
835 (defun sb!alien
::string-to-c-string
(string external-format
)
836 (declare (type simple-string string
))
838 (declare (optimize (speed 3) (safety 0)))
839 (let ((external-format (get-external-format-or-lose external-format
)))
840 (funcall (ef-write-c-string-fun external-format
) string
))))
842 (defun sb!alien
::c-string-to-string
(sap external-format element-type
)
843 (declare (type system-area-pointer sap
))
845 (declare (optimize (speed 3) (safety 0)))
846 (let ((external-format (get-external-format-or-lose external-format
)))
847 (funcall (ef-read-c-string-fun external-format
) sap element-type
))))
849 (defun wrap-external-format-functions (external-format fun
)
850 (let ((result (%copy-external-format external-format
)))
851 (macrolet ((frob (accessor)
852 `(setf (,accessor result
) (funcall fun
(,accessor result
)))))
853 (frob ef-read-n-chars-fun
)
854 (frob ef-read-char-fun
)
855 (frob ef-write-n-bytes-fun
)
856 (frob ef-write-char-none-buffered-fun
)
857 (frob ef-write-char-line-buffered-fun
)
858 (frob ef-write-char-full-buffered-fun
)
860 (frob ef-bytes-for-char-fun
)
861 (frob ef-read-c-string-fun
)
862 (frob ef-write-c-string-fun
)
863 (frob ef-octets-to-string-fun
)
864 (frob ef-string-to-octets-fun
))
867 (defvar *external-formats
* (make-hash-table)
869 "Hashtable of all available external formats. The table maps from
870 external-format names to EXTERNAL-FORMAT structures.")
872 (defun get-external-format-or-lose (external-format)
873 (or (get-external-format external-format
)
874 (error "Undefined external-format: ~S" external-format
)))
876 (defun external-format-keyword (external-format)
877 (typecase external-format
878 (keyword external-format
)
879 ((cons keyword
) (car external-format
))))
881 (defun fd-stream-external-format-keyword (stream)
882 (external-format-keyword (fd-stream-external-format stream
)))
884 (defun canonize-external-format (external-format entry
)
885 (typecase external-format
886 (keyword (first (ef-names entry
)))
887 ((cons keyword
) (cons (first (ef-names entry
)) (rest external-format
)))))
889 ;;; Find an output routine to use given the type and buffering. Return
890 ;;; as multiple values the routine, the real type transfered, and the
891 ;;; number of bytes per element.
892 (defun pick-output-routine (type buffering
&optional external-format
)
893 (when (subtypep type
'character
)
894 (let ((entry (get-external-format-or-lose external-format
)))
895 (return-from pick-output-routine
896 (values (ecase buffering
897 (:none
(ef-write-char-none-buffered-fun entry
))
898 (:line
(ef-write-char-line-buffered-fun entry
))
899 (:full
(ef-write-char-full-buffered-fun entry
)))
902 (ef-write-n-bytes-fun entry
)
904 (canonize-external-format external-format entry
)))))
905 (dolist (entry *output-routines
*)
906 (when (and (subtypep type
(first entry
))
907 (eq buffering
(second entry
))
908 (or (not (fifth entry
))
909 (eq external-format
(fifth entry
))))
910 (return-from pick-output-routine
911 (values (symbol-function (third entry
))
914 ;; KLUDGE: dealing with the buffering here leads to excessive code
917 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
918 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
919 if
(subtypep type
`(unsigned-byte ,i
))
920 do
(return-from pick-output-routine
924 (lambda (stream byte
)
925 (output-wrapper (stream (/ i
8) (:none
) 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
))))))
931 (lambda (stream byte
)
932 (output-wrapper (stream (/ i
8) (:full
) nil
)
933 (loop for j from
0 below
(/ i
8)
934 do
(setf (sap-ref-8 (buffer-sap obuf
)
936 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
939 (loop for i from
40 by
8 to
1024 ; ARB (KLUDGE)
940 if
(subtypep type
`(signed-byte ,i
))
941 do
(return-from pick-output-routine
945 (lambda (stream byte
)
946 (output-wrapper (stream (/ i
8) (:none
) nil
)
947 (loop for j from
0 below
(/ i
8)
948 do
(setf (sap-ref-8 (buffer-sap obuf
)
950 (ldb (byte 8 (- i
8 (* j
8))) byte
))))))
952 (lambda (stream byte
)
953 (output-wrapper (stream (/ i
8) (:full
) nil
)
954 (loop for j from
0 below
(/ i
8)
955 do
(setf (sap-ref-8 (buffer-sap obuf
)
957 (ldb (byte 8 (- i
8 (* j
8))) byte
)))))))
961 ;;;; input routines and related noise
963 ;;; a list of all available input routines. Each element is a list of
964 ;;; the element-type input, the function name, and the number of bytes
966 (defvar *input-routines
* ())
968 ;;; Return whether a primitive partial read operation on STREAM's FD
969 ;;; would (probably) block. Signal a `simple-stream-error' if the
970 ;;; system call implementing this operation fails.
972 ;;; It is "may" instead of "would" because "would" is not quite
973 ;;; correct on win32. However, none of the places that use it require
974 ;;; further assurance than "may" versus "will definitely not".
975 (defun sysread-may-block-p (stream)
977 ;; This answers T at EOF on win32, I think.
978 (not (sb!win32
:fd-listen
(fd-stream-fd stream
)))
980 (not (sb!unix
:unix-simple-poll
(fd-stream-fd stream
) :input
0)))
982 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
983 ;;; then fill the input buffer, and return the number of bytes read. Throws
984 ;;; to EOF-INPUT-CATCHER if the eof was reached.
985 (defun refill-input-buffer (stream)
986 (let ((fd (fd-stream-fd stream
))
993 ;; Check for blocking input before touching the stream if we are to
994 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
995 ;; read(). Regular files should never block, so we can elide the check.
996 (if (and (neq :regular
(fd-stream-fd-type stream
))
997 (sysread-may-block-p stream
))
1000 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
1001 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
1003 (closed-flame stream
)
1005 (simple-stream-perror "couldn't read from ~S" stream errno
)
1007 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
1008 ;; to wait for input if read tells us EWOULDBLOCK.
1009 (unless (wait-until-fd-usable fd
:input
(fd-stream-timeout stream
)
1010 (fd-stream-serve-events stream
))
1011 (signal-timeout 'io-timeout
1014 :seconds
(fd-stream-timeout stream
)))
1016 ;; Since the read should not block, we'll disable the
1017 ;; interrupts here, so that we don't accidentally unwind and
1018 ;; leave the stream in an inconsistent state.
1020 ;; Execute the nlx outside without-interrupts to ensure the
1021 ;; resulting thunk is stack-allocatable.
1022 ((lambda (return-reason)
1023 (ecase return-reason
1024 ((nil)) ; fast path normal cases
1025 ((:wait-for-input
) (go #!-win32
:wait-for-input
#!+win32
:main
))
1026 ((:closed-flame
) (go :closed-flame
))
1027 ((:read-error
) (go :read-error
))))
1029 ;; Check the buffer: if it is null, then someone has closed
1030 ;; the stream from underneath us. This is not ment to fix
1031 ;; multithreaded races, but to deal with interrupt handlers
1032 ;; closing the stream.
1035 (let* ((ibuf (or (fd-stream-ibuf stream
) (return :closed-flame
)))
1036 (sap (buffer-sap ibuf
))
1037 (length (buffer-length ibuf
))
1038 (head (buffer-head ibuf
))
1039 (tail (buffer-tail ibuf
)))
1040 (declare (index length head tail
)
1041 (inline sb
!unix
:unix-read
))
1042 (unless (zerop head
)
1043 (cond ((eql head tail
)
1044 ;; Buffer is empty, but not at yet reset -- make it so.
1047 (reset-buffer ibuf
))
1049 ;; Buffer has things in it, but they are not at the
1050 ;; head -- move them there.
1051 (let ((n (- tail head
)))
1052 (system-area-ub8-copy sap head sap
0 n
)
1054 (buffer-head ibuf
) head
1056 (buffer-tail ibuf
) tail
)))))
1057 (setf (fd-stream-listen stream
) nil
)
1058 (setf (values count errno
)
1059 (sb!unix
:unix-read fd
(sap+ sap tail
) (- length tail
)))
1062 #!+win32 sb
!unix
:eintr
1063 #!-win32 sb
!unix
:ewouldblock
)
1064 (return :wait-for-input
)
1065 (return :read-error
)))
1067 (setf (fd-stream-listen stream
) :eof
)
1068 (/show0
"THROWing EOF-INPUT-CATCHER")
1069 (throw 'eof-input-catcher nil
))
1071 ;; Success! (Do not use INCF, for sake of other threads.)
1072 (setf (buffer-tail ibuf
) (+ count tail
))))))))))
1075 ;;; Make sure there are at least BYTES number of bytes in the input
1076 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1077 (defmacro input-at-least
(stream bytes
)
1078 (let ((stream-var (gensym "STREAM"))
1079 (bytes-var (gensym "BYTES"))
1080 (buffer-var (gensym "IBUF")))
1081 `(let* ((,stream-var
,stream
)
1083 (,buffer-var
(fd-stream-ibuf ,stream-var
)))
1085 (when (>= (- (buffer-tail ,buffer-var
)
1086 (buffer-head ,buffer-var
))
1089 (refill-input-buffer ,stream-var
)))))
1091 (defmacro input-wrapper
/variable-width
((stream bytes eof-error eof-value
)
1093 (let ((stream-var (gensym "STREAM"))
1094 (retry-var (gensym "RETRY"))
1095 (element-var (gensym "ELT")))
1096 `(let* ((,stream-var
,stream
)
1097 (ibuf (fd-stream-ibuf ,stream-var
))
1100 (when (fd-stream-eof-forced-p ,stream-var
)
1101 (setf (fd-stream-eof-forced-p ,stream-var
) nil
)
1102 (return-from use-instead
1103 (eof-or-lose ,stream-var
,eof-error
,eof-value
)))
1104 (let ((,element-var nil
)
1105 (decode-break-reason nil
))
1106 (do ((,retry-var t
))
1108 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1109 (let* ((instead (fd-stream-instead ,stream-var
))
1110 (result (vector-pop instead
))
1111 (pointer (fill-pointer instead
)))
1113 (setf (fd-stream-listen ,stream-var
) nil
))
1114 (return-from use-instead result
))
1116 (catch 'eof-input-catcher
1117 (setf decode-break-reason
1118 (block decode-break-reason
1119 (input-at-least ,stream-var
,(if (consp bytes
)
1121 `(setq size
,bytes
)))
1122 (let* ((byte (sap-ref-8 (buffer-sap ibuf
) (buffer-head ibuf
))))
1123 (declare (ignorable byte
))
1124 ,@(when (consp bytes
)
1125 `((let ((sap (buffer-sap ibuf
))
1126 (head (buffer-head ibuf
)))
1127 (declare (ignorable sap head
))
1128 (setq size
,(cadr bytes
))
1129 (input-at-least ,stream-var size
))))
1130 (setq ,element-var
(locally ,@read-forms
))
1131 (setq ,retry-var nil
))
1133 (when decode-break-reason
1134 (when (stream-decoding-error-and-handle
1135 stream decode-break-reason
)
1136 (setq ,retry-var nil
)
1137 (throw 'eof-input-catcher nil
)))
1139 (let ((octet-count (- (buffer-tail ibuf
)
1140 (buffer-head ibuf
))))
1141 (when (or (zerop octet-count
)
1142 (and (not ,element-var
)
1143 (not decode-break-reason
)
1144 (stream-decoding-error-and-handle
1145 stream octet-count
)))
1146 (setq ,retry-var nil
))))))
1148 (incf (buffer-head ibuf
) size
)
1151 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1153 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1154 (defmacro input-wrapper
((stream bytes eof-error eof-value
) &body read-forms
)
1155 (let ((stream-var (gensym "STREAM"))
1156 (element-var (gensym "ELT")))
1157 `(let* ((,stream-var
,stream
)
1158 (ibuf (fd-stream-ibuf ,stream-var
)))
1159 (if (> (length (fd-stream-instead ,stream-var
)) 0)
1160 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var
)
1162 (catch 'eof-input-catcher
1163 (input-at-least ,stream-var
,bytes
)
1164 (locally ,@read-forms
))))
1166 (incf (buffer-head (fd-stream-ibuf ,stream-var
)) ,bytes
)
1169 (eof-or-lose ,stream-var
,eof-error
,eof-value
))))))))
1171 (defmacro def-input-routine
/variable-width
(name
1172 (type external-format size sap head
)
1175 (defun ,name
(stream eof-error eof-value
)
1176 (input-wrapper/variable-width
(stream ,size eof-error eof-value
)
1177 (let ((,sap
(buffer-sap ibuf
))
1178 (,head
(buffer-head ibuf
)))
1180 (setf *input-routines
*
1181 (nconc *input-routines
*
1182 (list (list ',type
',name
1 ',external-format
))))))
1184 (defmacro def-input-routine
(name
1185 (type size sap head
)
1188 (defun ,name
(stream eof-error eof-value
)
1189 (input-wrapper (stream ,size eof-error eof-value
)
1190 (let ((,sap
(buffer-sap ibuf
))
1191 (,head
(buffer-head ibuf
)))
1193 (setf *input-routines
*
1194 (nconc *input-routines
*
1195 (list (list ',type
',name
',size nil
))))))
1197 ;;; STREAM-IN routine for reading a string char
1198 (def-input-routine input-character
1199 (character 1 sap head
)
1200 (code-char (sap-ref-8 sap head
)))
1202 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1203 (def-input-routine input-unsigned-8bit-byte
1204 ((unsigned-byte 8) 1 sap head
)
1205 (sap-ref-8 sap head
))
1207 ;;; STREAM-IN routine for reading a signed 8 bit number
1208 (def-input-routine input-signed-8bit-number
1209 ((signed-byte 8) 1 sap head
)
1210 (signed-sap-ref-8 sap head
))
1212 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1213 (def-input-routine input-unsigned-16bit-byte
1214 ((unsigned-byte 16) 2 sap head
)
1215 (sap-ref-16 sap head
))
1217 ;;; STREAM-IN routine for reading a signed 16 bit number
1218 (def-input-routine input-signed-16bit-byte
1219 ((signed-byte 16) 2 sap head
)
1220 (signed-sap-ref-16 sap head
))
1222 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1223 (def-input-routine input-unsigned-32bit-byte
1224 ((unsigned-byte 32) 4 sap head
)
1225 (sap-ref-32 sap head
))
1227 ;;; STREAM-IN routine for reading a signed 32 bit number
1228 (def-input-routine input-signed-32bit-byte
1229 ((signed-byte 32) 4 sap head
)
1230 (signed-sap-ref-32 sap head
))
1234 (def-input-routine input-unsigned-64bit-byte
1235 ((unsigned-byte 64) 8 sap head
)
1236 (sap-ref-64 sap head
))
1237 (def-input-routine input-signed-64bit-byte
1238 ((signed-byte 64) 8 sap head
)
1239 (signed-sap-ref-64 sap head
)))
1241 ;;; Find an input routine to use given the type. Return as multiple
1242 ;;; values the routine, the real type transfered, and the number of
1243 ;;; bytes per element (and for character types string input routine).
1244 (defun pick-input-routine (type &optional external-format
)
1245 (when (subtypep type
'character
)
1246 (let ((entry (get-external-format-or-lose external-format
)))
1247 (return-from pick-input-routine
1248 (values (ef-read-char-fun entry
)
1251 (ef-read-n-chars-fun entry
)
1252 (ef-char-size entry
)
1253 (canonize-external-format external-format entry
)))))
1254 (dolist (entry *input-routines
*)
1255 (when (and (subtypep type
(first entry
))
1256 (or (not (fourth entry
))
1257 (eq external-format
(fourth entry
))))
1258 (return-from pick-input-routine
1259 (values (symbol-function (second entry
))
1262 ;; FIXME: let's do it the hard way, then (but ignore things like
1263 ;; endianness, efficiency, and the necessary coupling between these
1264 ;; and the output routines). -- CSR, 2004-02-09
1265 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1266 if
(subtypep type
`(unsigned-byte ,i
))
1267 do
(return-from pick-input-routine
1269 (lambda (stream eof-error eof-value
)
1270 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1271 (let ((sap (buffer-sap ibuf
))
1272 (head (buffer-head ibuf
)))
1273 (loop for j from
0 below
(/ i
8)
1277 (sap-ref-8 sap
(+ head j
))))
1278 finally
(return result
)))))
1281 (loop for i from
40 by
8 to
1024 ; ARB (well, KLUDGE really)
1282 if
(subtypep type
`(signed-byte ,i
))
1283 do
(return-from pick-input-routine
1285 (lambda (stream eof-error eof-value
)
1286 (input-wrapper (stream (/ i
8) eof-error eof-value
)
1287 (let ((sap (buffer-sap ibuf
))
1288 (head (buffer-head ibuf
)))
1289 (loop for j from
0 below
(/ i
8)
1293 (sap-ref-8 sap
(+ head j
))))
1294 finally
(return (if (logbitp (1- i
) result
)
1295 (dpb result
(byte i
0) -
1)
1300 ;;; the N-BIN method for FD-STREAMs
1302 ;;; Note that this blocks in UNIX-READ. It is generally used where
1303 ;;; there is a definite amount of reading to be done, so blocking
1304 ;;; isn't too problematical.
1305 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1306 &aux
(total-copied 0))
1307 (declare (type fd-stream stream
))
1308 (declare (type index start requested total-copied
))
1309 (aver (= (length (fd-stream-instead stream
)) 0))
1312 (let* ((remaining-request (- requested total-copied
))
1313 (ibuf (fd-stream-ibuf stream
))
1314 (head (buffer-head ibuf
))
1315 (tail (buffer-tail ibuf
))
1316 (available (- tail head
))
1317 (n-this-copy (min remaining-request available
))
1318 (this-start (+ start total-copied
))
1319 (this-end (+ this-start n-this-copy
))
1320 (sap (buffer-sap ibuf
)))
1321 (declare (type index remaining-request head tail available
))
1322 (declare (type index n-this-copy
))
1324 ;; Prevent failure caused by memmove() hitting a write-protected page
1325 ;; and the fault handler losing, since it thinks you're not in Lisp.
1326 ;; This is wasteful, but better than being randomly broken (lp#1366263).
1327 (when (> this-end this-start
)
1329 (system-area-pointer
1330 (setf (sap-ref-8 buffer this-start
) (sap-ref-8 buffer this-start
)
1331 (sap-ref-8 buffer
(1- this-end
)) (sap-ref-8 buffer
(1- this-end
))))
1332 ((simple-array (unsigned-byte 8) (*))
1333 (setf (aref buffer this-start
) (aref buffer this-start
)
1334 (aref buffer
(1- this-end
)) (aref buffer
(1- this-end
))))
1335 ((simple-array * (*))
1336 ;; We might have an array of UNSIGNED-BYTE-32 here, but the
1337 ;; bounding indices act as if it were UNSIGNED-BYTE-8.
1338 ;; This is strange, and in direct contradiction to what %BYTE-BLT
1339 ;; believes it accepts. i.e. according to the comments,
1340 ;; it's for want of error checking that this works at all.
1341 (with-pinned-objects (buffer)
1342 (let ((sap (vector-sap buffer
)))
1343 (setf (sap-ref-8 sap this-start
) (sap-ref-8 sap this-start
)
1344 (sap-ref-8 sap
(1- this-end
)) (sap-ref-8 sap
(1- this-end
))))))))
1345 ;; Copy data from stream buffer into user's buffer.
1346 (%byte-blt sap head buffer this-start this-end
)
1347 (incf (buffer-head ibuf
) n-this-copy
)
1348 (incf total-copied n-this-copy
)
1349 ;; Maybe we need to refill the stream buffer.
1350 (cond (;; If there were enough data in the stream buffer, we're done.
1351 (eql total-copied requested
)
1352 (return total-copied
))
1353 (;; If EOF, we're done in another way.
1354 (null (catch 'eof-input-catcher
(refill-input-buffer stream
)))
1356 (error 'end-of-file
:stream stream
)
1357 (return total-copied
)))
1358 ;; Otherwise we refilled the stream buffer, so fall
1359 ;; through into another pass of the loop.
1362 (defun fd-stream-resync (stream)
1363 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1365 (funcall (ef-resync-fun entry
) stream
))))
1367 (defun get-fd-stream-character-sizer (stream)
1368 (let ((entry (get-external-format (fd-stream-external-format stream
))))
1370 (ef-bytes-for-char-fun entry
))))
1372 (defun fd-stream-character-size (stream char
)
1373 (let ((sizer (get-fd-stream-character-sizer stream
)))
1374 (when sizer
(funcall sizer char
))))
1376 (defun fd-stream-string-size (stream string
)
1377 (let ((sizer (get-fd-stream-character-sizer stream
)))
1379 (loop for char across string summing
(funcall sizer char
)))))
1381 (defun find-external-format (external-format)
1382 (when external-format
1383 (get-external-format external-format
)))
1385 (defun variable-width-external-format-p (ef-entry)
1386 (and ef-entry
(not (null (ef-resync-fun ef-entry
)))))
1388 (defun bytes-for-char-fun (ef-entry)
1389 (if ef-entry
(ef-bytes-for-char-fun ef-entry
) (constantly 1)))
1391 (defmacro define-unibyte-mapping-external-format
1392 (canonical-name (&rest other-names
) &body exceptions
)
1393 (let ((->code-name
(symbolicate canonical-name
'-
>code-mapper
))
1394 (code->-name
(symbolicate 'code-
> canonical-name
'-mapper
))
1395 (get-bytes-name (symbolicate 'get- canonical-name
'-bytes
))
1396 (string->-name
(symbolicate 'string-
> canonical-name
))
1397 (define-string*-name
(symbolicate 'define- canonical-name
'-
>string
*))
1398 (string*-name
(symbolicate canonical-name
'-
>string
*))
1399 (define-string-name (symbolicate 'define- canonical-name
'-
>string
))
1400 (string-name (symbolicate canonical-name
'-
>string
))
1401 (->string-aref-name
(symbolicate canonical-name
'-
>string-aref
)))
1403 (define-unibyte-mapper ,-
>code-name
,code-
>-name
1405 (declaim (inline ,get-bytes-name
))
1406 (defun ,get-bytes-name
(string pos
)
1407 (declare (optimize speed
(safety 0))
1408 (type simple-string string
)
1409 (type array-range pos
))
1410 (get-latin-bytes #',code-
>-name
,canonical-name string pos
))
1411 (defun ,string-
>-name
(string sstart send null-padding
)
1412 (declare (optimize speed
(safety 0))
1413 (type simple-string string
)
1414 (type array-range sstart send
))
1415 (values (string->latin% string sstart send
#',get-bytes-name null-padding
)))
1416 (defmacro ,define-string
*-name
(accessor type
)
1417 (declare (ignore type
))
1418 (let ((name (make-od-name ',string
*-name accessor
)))
1420 (defun ,name
(string sstart send array astart aend
)
1421 (,(make-od-name 'latin-
>string
* accessor
)
1422 string sstart send array astart aend
#',',-
>code-name
)))))
1423 (instantiate-octets-definition ,define-string
*-name
)
1424 (defmacro ,define-string-name
(accessor type
)
1425 (declare (ignore type
))
1426 (let ((name (make-od-name ',string-name accessor
)))
1428 (defun ,name
(array astart aend
)
1429 (,(make-od-name 'latin-
>string accessor
)
1430 array astart aend
#',',-
>code-name
)))))
1431 (instantiate-octets-definition ,define-string-name
)
1432 (define-unibyte-external-format ,canonical-name
,other-names
1433 (let ((octet (,code-
>-name bits
)))
1435 (setf (sap-ref-8 sap tail
) octet
)
1436 (external-format-encoding-error stream bits
)))
1437 (let ((code (,-
>code-name byte
)))
1440 (return-from decode-break-reason
1)))
1444 (defmacro define-unibyte-external-format
1445 (canonical-name (&rest other-names
)
1446 out-form in-form octets-to-string-symbol string-to-octets-symbol
)
1447 `(define-external-format/variable-width
(,canonical-name
,@other-names
)
1452 ,octets-to-string-symbol
1453 ,string-to-octets-symbol
))
1455 (defmacro define-external-format
/variable-width
1456 (external-format output-restart replacement-character
1457 out-size-expr out-expr in-size-expr in-expr
1458 octets-to-string-sym string-to-octets-sym
)
1459 (let* ((name (first external-format
))
1460 (out-function (symbolicate "OUTPUT-BYTES/" name
))
1461 (format (format nil
"OUTPUT-CHAR-~A-~~A-BUFFERED" (string name
)))
1462 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name
))
1463 (in-char-function (symbolicate "INPUT-CHAR/" name
))
1464 (resync-function (symbolicate "RESYNC/" name
))
1465 (size-function (symbolicate "BYTES-FOR-CHAR/" name
))
1466 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name
))
1467 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name
))
1468 (n-buffer (gensym "BUFFER")))
1470 (defun ,size-function
(byte)
1471 (declare (ignorable byte
))
1473 (defun ,out-function
(stream string flush-p start end
)
1474 (let ((start (or start
0))
1475 (end (or end
(length string
))))
1476 (declare (type index start end
))
1477 (synchronize-stream-output stream
)
1478 (unless (<= 0 start end
(length string
))
1479 (sequence-bounding-indices-bad-error string start end
))
1482 (let ((obuf (fd-stream-obuf stream
)))
1483 (string-dispatch (simple-base-string
1484 #!+sb-unicode
(simple-array character
(*))
1487 (let ((len (buffer-length obuf
))
1488 (sap (buffer-sap obuf
))
1490 (tail (buffer-tail obuf
)))
1491 (declare (type index tail
)
1492 ;; STRING bounds have already been checked.
1493 (optimize (safety 0)))
1494 (,@(if output-restart
1495 `(catch 'output-nothing
)
1498 ((or (= start end
) (< (- len tail
) 4)))
1499 (let* ((byte (aref string start
))
1500 (bits (char-code byte
))
1501 (size ,out-size-expr
))
1504 (setf (buffer-tail obuf
) tail
)
1507 ;; Exited via CATCH: skip the current character.
1511 (flush-output-buffer stream
)))
1513 (flush-output-buffer stream
))))
1514 (def-output-routines/variable-width
(,format
1521 (if (eql byte
#\Newline
)
1522 (setf (fd-stream-output-column stream
) 0)
1523 (incf (fd-stream-output-column stream
)))
1524 (let ((bits (char-code byte
))
1525 (sap (buffer-sap obuf
))
1526 (tail (buffer-tail obuf
)))
1528 (defun ,in-function
(stream buffer start requested eof-error-p
1529 &aux
(total-copied 0))
1530 (declare (type fd-stream stream
)
1531 (type index start requested total-copied
)
1533 (simple-array character
(#.
+ansi-stream-in-buffer-length
+))
1535 (when (fd-stream-eof-forced-p stream
)
1536 (setf (fd-stream-eof-forced-p stream
) nil
)
1537 (return-from ,in-function
0))
1538 (do ((instead (fd-stream-instead stream
)))
1539 ((= (fill-pointer instead
) 0)
1540 (setf (fd-stream-listen stream
) nil
))
1541 (setf (aref buffer
(+ start total-copied
)) (vector-pop instead
))
1543 (when (= requested total-copied
)
1544 (when (= (fill-pointer instead
) 0)
1545 (setf (fd-stream-listen stream
) nil
))
1546 (return-from ,in-function total-copied
)))
1549 (let* ((ibuf (fd-stream-ibuf stream
))
1550 (head (buffer-head ibuf
))
1551 (tail (buffer-tail ibuf
))
1552 (sap (buffer-sap ibuf
))
1553 (decode-break-reason nil
))
1554 (declare (type index head tail
))
1555 ;; Copy data from stream buffer into user's buffer.
1556 (do ((size nil nil
))
1557 ((or (= tail head
) (= requested total-copied
)))
1558 (setf decode-break-reason
1559 (block decode-break-reason
1560 ,@(when (consp in-size-expr
)
1561 `((when (> ,(car in-size-expr
) (- tail head
))
1563 (let ((byte (sap-ref-8 sap head
)))
1564 (declare (ignorable byte
))
1565 (setq size
,(if (consp in-size-expr
) (cadr in-size-expr
) in-size-expr
))
1566 (when (> size
(- tail head
))
1568 (setf (aref buffer
(+ start total-copied
)) ,in-expr
)
1572 (setf (buffer-head ibuf
) head
)
1573 (when decode-break-reason
1574 ;; If we've already read some characters on when the invalid
1575 ;; code sequence is detected, we return immediately. The
1576 ;; handling of the error is deferred until the next call
1577 ;; (where this check will be false). This allows establishing
1578 ;; high-level handlers for decode errors (for example
1579 ;; automatically resyncing in Lisp comments).
1580 (when (plusp total-copied
)
1581 (return-from ,in-function total-copied
))
1582 (when (stream-decoding-error-and-handle
1583 stream decode-break-reason
)
1585 (error 'end-of-file
:stream stream
)
1586 (return-from ,in-function total-copied
)))
1587 ;; we might have been given stuff to use instead, so
1588 ;; we have to return (and trust our caller to know
1589 ;; what to do about TOTAL-COPIED being 0).
1590 (return-from ,in-function total-copied
)))
1591 (setf (buffer-head ibuf
) head
)
1592 ;; Maybe we need to refill the stream buffer.
1593 (cond ( ;; If was data in the stream buffer, we're done.
1594 (plusp total-copied
)
1595 (return total-copied
))
1596 ( ;; If EOF, we're done in another way.
1597 (or (eq decode-break-reason
'eof
)
1598 (null (catch 'eof-input-catcher
1599 (refill-input-buffer stream
))))
1601 (error 'end-of-file
:stream stream
)
1602 (return total-copied
)))
1603 ;; Otherwise we refilled the stream buffer, so fall
1604 ;; through into another pass of the loop.
1606 (def-input-routine/variable-width
,in-char-function
(character
1610 (let ((byte (sap-ref-8 sap head
)))
1611 (declare (ignorable byte
))
1613 (defun ,resync-function
(stream)
1614 (let ((ibuf (fd-stream-ibuf stream
))
1616 (catch 'eof-input-catcher
1618 (incf (buffer-head ibuf
))
1619 (input-at-least stream
,(if (consp in-size-expr
) (car in-size-expr
) `(setq size
,in-size-expr
)))
1620 (unless (block decode-break-reason
1621 (let* ((sap (buffer-sap ibuf
))
1622 (head (buffer-head ibuf
))
1623 (byte (sap-ref-8 sap head
)))
1624 (declare (ignorable byte
))
1625 ,@(when (consp in-size-expr
)
1626 `((setq size
,(cadr in-size-expr
))
1627 (input-at-least stream size
)))
1628 (setf head
(buffer-head ibuf
))
1632 (defun ,read-c-string-function
(sap element-type
)
1633 (declare (type system-area-pointer sap
))
1635 (declare (optimize (speed 3) (safety 0)))
1636 (let* ((stream ,name
)
1637 (size 0) (head 0) (byte 0) (char nil
)
1638 (decode-break-reason nil
)
1639 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT
) count
)
1640 (setf decode-break-reason
1641 (block decode-break-reason
1642 (setf byte
(sap-ref-8 sap head
)
1643 size
,(if (consp in-size-expr
)
1649 (when decode-break-reason
1650 (c-string-decoding-error
1651 ,name sap head decode-break-reason
))
1652 (when (zerop (char-code char
))
1654 (string (make-string length
:element-type element-type
)))
1655 (declare (ignorable stream
)
1656 (type index head length
) ;; size
1657 (type (unsigned-byte 8) byte
)
1658 (type (or null character
) char
)
1659 (type string string
))
1661 (dotimes (index length string
)
1662 (setf decode-break-reason
1663 (block decode-break-reason
1664 (setf byte
(sap-ref-8 sap head
)
1665 size
,(if (consp in-size-expr
)
1671 (when decode-break-reason
1672 (c-string-decoding-error
1673 ,name sap head decode-break-reason
))
1674 (setf (aref string index
) char
)))))
1676 (defun ,output-c-string-function
(string)
1677 (declare (type simple-string string
))
1679 (declare (optimize (speed 3) (safety 0)))
1680 (let* ((length (length string
))
1681 (char-length (make-array (1+ length
) :element-type
'index
))
1683 (+ (loop for i of-type index below length
1684 for byte of-type character
= (aref string i
)
1685 for bits
= (char-code byte
)
1686 sum
(setf (aref char-length i
)
1687 (the index
,out-size-expr
)) of-type index
)
1688 (let* ((byte (code-char 0))
1689 (bits (char-code byte
)))
1690 (declare (ignorable byte bits
))
1691 (setf (aref char-length length
)
1692 (the index
,out-size-expr
)))))
1694 (,n-buffer
(make-array buffer-length
1695 :element-type
'(unsigned-byte 8)))
1697 (declare (type index length buffer-length tail
)
1700 (with-pinned-objects (,n-buffer
)
1701 (let ((sap (vector-sap ,n-buffer
)))
1702 (declare (system-area-pointer sap
))
1703 (loop for i of-type index below length
1704 for byte of-type character
= (aref string i
)
1705 for bits
= (char-code byte
)
1706 for size of-type index
= (aref char-length i
)
1711 (byte (code-char bits
))
1712 (size (aref char-length length
)))
1713 (declare (ignorable bits byte size
))
1717 (let ((entry (%make-external-format
1718 :names
',external-format
1719 :default-replacement-character
,replacement-character
1720 :read-n-chars-fun
#',in-function
1721 :read-char-fun
#',in-char-function
1722 :write-n-bytes-fun
#',out-function
1723 ,@(mapcan #'(lambda (buffering)
1724 (list (intern (format nil
"WRITE-CHAR-~A-BUFFERED-FUN" buffering
) :keyword
)
1725 `#',(intern (format nil format
(string buffering
)))))
1726 '(:none
:line
:full
))
1727 :resync-fun
#',resync-function
1728 :bytes-for-char-fun
#',size-function
1729 :read-c-string-fun
#',read-c-string-function
1730 :write-c-string-fun
#',output-c-string-function
1731 :octets-to-string-fun
(lambda (&rest rest
)
1732 (declare (dynamic-extent rest
))
1733 (apply ',octets-to-string-sym rest
))
1734 :string-to-octets-fun
(lambda (&rest rest
)
1735 (declare (dynamic-extent rest
))
1736 (apply ',string-to-octets-sym rest
)))))
1737 (dolist (ef ',external-format
)
1738 (setf (gethash ef
*external-formats
*) entry
))))))
1740 ;;;; utility functions (misc routines, etc)
1742 ;;; Fill in the various routine slots for the given type. INPUT-P and
1743 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1744 ;;; set prior to calling this routine.
1745 (defun set-fd-stream-routines (fd-stream element-type external-format
1746 input-p output-p buffer-p
)
1747 (let* ((target-type (case element-type
1748 (unsigned-byte '(unsigned-byte 8))
1749 (signed-byte '(signed-byte 8))
1750 (:default
'character
)
1752 (character-stream-p (subtypep target-type
'character
))
1753 (bivalent-stream-p (eq element-type
:default
))
1754 normalized-external-format
1756 (bin-routine #'ill-bin
)
1759 (cin-routine #'ill-in
)
1762 (input-type nil
) ;calculated from bin-type/cin-type
1763 (input-size nil
) ;calculated from bin-size/cin-size
1764 (read-n-characters #'ill-in
)
1765 (bout-routine #'ill-bout
)
1768 (cout-routine #'ill-out
)
1773 (output-bytes #'ill-bout
))
1775 ;; Ensure that we have buffers in the desired direction(s) only,
1776 ;; getting new ones and dropping/resetting old ones as necessary.
1777 (let ((obuf (fd-stream-obuf fd-stream
)))
1781 (setf (fd-stream-obuf fd-stream
) (get-buffer)))
1783 (setf (fd-stream-obuf fd-stream
) nil
)
1784 (release-buffer obuf
))))
1786 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1790 (setf (fd-stream-ibuf fd-stream
) (get-buffer)))
1792 (setf (fd-stream-ibuf fd-stream
) nil
)
1793 (release-buffer ibuf
))))
1795 ;; FIXME: Why only for output? Why unconditionally?
1797 (setf (fd-stream-output-column fd-stream
) 0))
1799 (when (and character-stream-p
(eq external-format
:default
))
1800 (/show0
"/getting default external format")
1801 (setf external-format
(default-external-format)))
1804 (when (or (not character-stream-p
) bivalent-stream-p
)
1805 (setf (values bin-routine bin-type bin-size read-n-characters
1806 char-size normalized-external-format
)
1807 (pick-input-routine (if bivalent-stream-p
'(unsigned-byte 8)
1811 (error "could not find any input routine for ~S" target-type
)))
1812 (when character-stream-p
1813 (setf (values cin-routine cin-type cin-size read-n-characters
1814 char-size normalized-external-format
)
1815 (pick-input-routine target-type external-format
))
1817 (error "could not find any input routine for ~S" target-type
)))
1818 (setf (fd-stream-in fd-stream
) cin-routine
1819 (fd-stream-bin fd-stream
) bin-routine
)
1820 ;; character type gets preferential treatment
1821 (setf input-size
(or cin-size bin-size
))
1822 (setf input-type
(or cin-type bin-type
))
1823 (when normalized-external-format
1824 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1825 (fd-stream-char-size fd-stream
) char-size
))
1826 (when (= (or cin-size
1) (or bin-size
1) 1)
1827 (setf (fd-stream-n-bin fd-stream
) ;XXX
1828 (if (and character-stream-p
(not bivalent-stream-p
))
1830 #'fd-stream-read-n-bytes
))
1831 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1832 ;; for character and (unsigned-byte 8) streams. In these
1833 ;; cases, fast-read-* will read from the
1834 ;; ansi-stream-(c)in-buffer, saving function calls.
1835 ;; Otherwise, the various data-reading functions in the stream
1836 ;; structure will be called.
1838 (not bivalent-stream-p
)
1839 ;; temporary disable on :io streams
1841 (cond (character-stream-p
1842 (setf (ansi-stream-cin-buffer fd-stream
)
1843 (make-array +ansi-stream-in-buffer-length
+
1844 :element-type
'character
)))
1845 ((equal target-type
'(unsigned-byte 8))
1846 (setf (ansi-stream-in-buffer fd-stream
)
1847 (make-array +ansi-stream-in-buffer-length
+
1848 :element-type
'(unsigned-byte 8))))))))
1851 (when (or (not character-stream-p
) bivalent-stream-p
)
1852 (setf (values bout-routine bout-type bout-size output-bytes
1853 char-size normalized-external-format
)
1854 (let ((buffering (fd-stream-buffering fd-stream
)))
1855 (if bivalent-stream-p
1856 (pick-output-routine '(unsigned-byte 8)
1857 (if (eq :line buffering
)
1861 (pick-output-routine target-type buffering external-format
))))
1862 (unless bout-routine
1863 (error "could not find any output routine for ~S buffered ~S"
1864 (fd-stream-buffering fd-stream
)
1866 (when character-stream-p
1867 (setf (values cout-routine cout-type cout-size output-bytes
1868 char-size normalized-external-format
)
1869 (pick-output-routine target-type
1870 (fd-stream-buffering fd-stream
)
1872 (unless cout-routine
1873 (error "could not find any output routine for ~S buffered ~S"
1874 (fd-stream-buffering fd-stream
)
1876 (when normalized-external-format
1877 (setf (fd-stream-external-format fd-stream
) normalized-external-format
1878 (fd-stream-char-size fd-stream
) char-size
))
1879 (when character-stream-p
1880 (setf (fd-stream-output-bytes fd-stream
) output-bytes
))
1881 (setf (fd-stream-out fd-stream
) cout-routine
1882 (fd-stream-bout fd-stream
) bout-routine
1883 (fd-stream-sout fd-stream
) (if (eql cout-size
1)
1884 #'fd-sout
#'ill-out
))
1885 (setf output-size
(or cout-size bout-size
))
1886 (setf output-type
(or cout-type bout-type
)))
1888 (when (and input-size output-size
1889 (not (eq input-size output-size
)))
1890 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1891 input-type input-size
1892 output-type output-size
))
1893 (setf (fd-stream-element-size fd-stream
)
1894 (or input-size output-size
))
1896 (setf (fd-stream-element-type fd-stream
)
1897 (cond ((equal input-type output-type
)
1903 ((subtypep input-type output-type
)
1905 ((subtypep output-type input-type
)
1908 (error "Input type (~S) and output type (~S) are unrelated?"
1912 ;;; Handles the resource-release aspects of stream closing, and marks
1914 (defun release-fd-stream-resources (fd-stream)
1917 ;; Drop handlers first.
1918 (when (fd-stream-handler fd-stream
)
1919 (remove-fd-handler (fd-stream-handler fd-stream
))
1920 (setf (fd-stream-handler fd-stream
) nil
))
1921 ;; Disable interrupts so that a asynch unwind will not leave
1922 ;; us with a dangling finalizer (that would close the same
1923 ;; --possibly reassigned-- FD again), or a stream with a closed
1924 ;; FD that appears open.
1925 (sb!unix
:unix-close
(fd-stream-fd fd-stream
))
1926 (set-closed-flame fd-stream
)
1927 (cancel-finalization fd-stream
))
1928 ;; On error unwind from WITHOUT-INTERRUPTS.
1929 (serious-condition (e)
1931 ;; Release all buffers. If this is undone, or interrupted,
1932 ;; we're still safe: buffers have finalizers of their own.
1933 (release-fd-stream-buffers fd-stream
))
1935 ;;; Flushes the current input buffer and any supplied replacements,
1936 ;;; and returns the input buffer, and the amount of of flushed input
1938 (defun flush-input-buffer (stream)
1939 (let ((unread (length (fd-stream-instead stream
))))
1940 (setf (fill-pointer (fd-stream-instead stream
)) 0)
1941 (let ((ibuf (fd-stream-ibuf stream
)))
1943 (let ((head (buffer-head ibuf
))
1944 (tail (buffer-tail ibuf
)))
1945 (values (reset-buffer ibuf
) (- (+ unread tail
) head
)))
1946 (values nil unread
)))))
1948 (defun fd-stream-clear-input (stream)
1949 (flush-input-buffer stream
)
1952 (sb!win32
:fd-clear-input
(fd-stream-fd stream
))
1953 (setf (fd-stream-listen stream
) nil
))
1955 (catch 'eof-input-catcher
1956 (loop until
(sysread-may-block-p stream
)
1958 (refill-input-buffer stream
)
1959 (reset-buffer (fd-stream-ibuf stream
)))
1962 ;;; Handle miscellaneous operations on FD-STREAM.
1963 (defun fd-stream-misc-routine (fd-stream operation
&optional arg1 arg2
)
1964 (declare (ignore arg2
))
1967 (labels ((do-listen ()
1968 (let ((ibuf (fd-stream-ibuf fd-stream
)))
1969 (or (not (eql (buffer-head ibuf
) (buffer-tail ibuf
)))
1970 (fd-stream-listen fd-stream
)
1972 (sb!win32
:fd-listen
(fd-stream-fd fd-stream
))
1974 ;; If the read can block, LISTEN will certainly return NIL.
1975 (if (sysread-may-block-p fd-stream
)
1977 ;; Otherwise select(2) and CL:LISTEN have slightly
1978 ;; different semantics. The former returns that an FD
1979 ;; is readable when a read operation wouldn't block.
1980 ;; That includes EOF. However, LISTEN must return NIL
1982 (progn (catch 'eof-input-catcher
1983 ;; r-b/f too calls select, but it shouldn't
1984 ;; block as long as read can return once w/o
1986 (refill-input-buffer fd-stream
))
1987 ;; At this point either IBUF-HEAD != IBUF-TAIL
1988 ;; and FD-STREAM-LISTEN is NIL, in which case
1989 ;; we should return T, or IBUF-HEAD ==
1990 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1991 ;; which case we should return :EOF for this
1992 ;; call and all future LISTEN call on this stream.
1993 ;; Call ourselves again to determine which case
1998 (decf (buffer-head (fd-stream-ibuf fd-stream
))
1999 (fd-stream-character-size fd-stream arg1
)))
2001 ;; Drop input buffers
2002 (setf (ansi-stream-in-index fd-stream
) +ansi-stream-in-buffer-length
+
2003 (ansi-stream-cin-buffer fd-stream
) nil
2004 (ansi-stream-in-buffer fd-stream
) nil
)
2006 ;; We got us an abort on our hands.
2007 (let ((outputp (fd-stream-obuf fd-stream
))
2008 (file (fd-stream-file fd-stream
))
2009 (orig (fd-stream-original fd-stream
)))
2010 ;; This takes care of the important stuff -- everything
2011 ;; rest is cleaning up the file-system, which we cannot
2012 ;; do on some platforms as long as the file is open.
2013 (release-fd-stream-resources fd-stream
)
2014 ;; We can't do anything unless we know what file were
2015 ;; dealing with, and we don't want to do anything
2016 ;; strange unless we were writing to the file.
2017 (when (and outputp file
)
2019 ;; If the original is EQ to file we are appending to
2020 ;; and can just close the file without renaming.
2021 (unless (eq orig file
)
2022 ;; We have a handle on the original, just revert.
2023 (multiple-value-bind (okay err
)
2024 (sb!unix
:unix-rename orig file
)
2025 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2026 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2029 (error 'simple-stream-error
2031 "~@<Couldn't restore ~S to its original contents ~
2032 from ~S while closing ~S: ~2I~_~A~:>"
2034 (list file orig fd-stream
(strerror err
))
2035 :stream fd-stream
))))
2036 ;; We can't restore the original, and aren't
2037 ;; appending, so nuke that puppy.
2039 ;; FIXME: This is currently the fate of superseded
2040 ;; files, and according to the CLOSE spec this is
2041 ;; wrong. However, there seems to be no clean way to
2042 ;; do that that doesn't involve either copying the
2043 ;; data (bad if the :abort resulted from a full
2044 ;; disk), or renaming the old file temporarily
2045 ;; (probably bad because stream opening becomes more
2047 (multiple-value-bind (okay err
)
2048 (sb!unix
:unix-unlink file
)
2050 (error 'simple-file-error
2053 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2055 (list file fd-stream
(strerror err
)))))))))
2057 (finish-fd-stream-output fd-stream
)
2058 (let ((orig (fd-stream-original fd-stream
)))
2059 (when (and orig
(fd-stream-delete-original fd-stream
))
2060 (multiple-value-bind (okay err
) (sb!unix
:unix-unlink orig
)
2062 (error 'simple-file-error
2065 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2067 (list orig fd-stream
(strerror err
)))))))
2068 ;; In case of no-abort close, don't *really* close the
2069 ;; stream until the last moment -- the cleaning up of the
2070 ;; original can be done first.
2071 (release-fd-stream-resources fd-stream
))))
2073 (fd-stream-clear-input fd-stream
))
2075 (flush-output-buffer fd-stream
))
2077 (finish-fd-stream-output fd-stream
))
2079 (fd-stream-element-type fd-stream
))
2081 (fd-stream-element-mode fd-stream
))
2083 (fd-stream-external-format fd-stream
))
2085 (plusp (the (integer 0)
2086 (sb!unix
:unix-isatty
(fd-stream-fd fd-stream
)))))
2090 (fd-stream-output-column fd-stream
))
2092 (unless (fd-stream-file fd-stream
)
2093 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2094 ;; "should signal an error of type TYPE-ERROR if stream is not
2095 ;; a stream associated with a file". Too bad there's no very
2096 ;; appropriate value for the EXPECTED-TYPE slot..
2097 (error 'simple-type-error
2099 :expected-type
'fd-stream
2100 :format-control
"~S is not a stream associated with a file."
2101 :format-arguments
(list fd-stream
)))
2103 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2104 atime mtime ctime blksize blocks
)
2105 (sb!unix
:unix-fstat
(fd-stream-fd fd-stream
))
2106 (declare (ignore ino nlink uid gid rdev
2107 atime mtime ctime blksize blocks
))
2109 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev
))
2112 (truncate size
(fd-stream-element-size fd-stream
))))
2114 (let* ((handle (fd-stream-fd fd-stream
))
2115 (element-size (fd-stream-element-size fd-stream
)))
2116 (multiple-value-bind (got native-size
)
2117 (sb!win32
:get-file-size-ex handle
0)
2119 ;; Might be a block device, in which case we fall back to
2120 ;; a non-atomic workaround:
2121 (let* ((here (sb!unix
:unix-lseek handle
0 sb
!unix
:l_incr
))
2122 (there (sb!unix
:unix-lseek handle
0 sb
!unix
:l_xtnd
)))
2123 (when (and here there
)
2124 (sb!unix
:unix-lseek handle here sb
!unix
:l_set
)
2125 (truncate there element-size
)))
2126 (truncate native-size element-size
)))))
2127 (:file-string-length
2129 (character (fd-stream-character-size fd-stream arg1
))
2130 (string (fd-stream-string-size fd-stream arg1
))))
2133 (fd-stream-set-file-position fd-stream arg1
)
2134 (fd-stream-get-file-position fd-stream
)))))
2136 ;; FIXME: Think about this.
2138 ;; (defun finish-fd-stream-output (fd-stream)
2139 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2140 ;; (loop while (fd-stream-output-queue fd-stream)
2141 ;; ;; FIXME: SIGINT while waiting for a timeout will
2142 ;; ;; cause a timeout here.
2143 ;; do (when (and (not (serve-event timeout)) timeout)
2144 ;; (signal-timeout 'io-timeout
2145 ;; :stream fd-stream
2146 ;; :direction :write
2147 ;; :seconds timeout)))))
2149 (defun finish-fd-stream-output (stream)
2150 (flush-output-buffer stream
)
2152 ((null (fd-stream-output-queue stream
)))
2153 (aver (fd-stream-serve-events stream
))
2154 (serve-all-events)))
2156 (defun fd-stream-get-file-position (stream)
2157 (declare (fd-stream stream
))
2159 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
) 0 sb
!unix
:l_incr
)))
2160 (declare (type (or (alien sb
!unix
:unix-offset
) null
) posn
))
2161 ;; We used to return NIL for errno==ESPIPE, and signal an error
2162 ;; in other failure cases. However, CLHS says to return NIL if
2163 ;; the position cannot be determined -- so that's what we do.
2164 (when (integerp posn
)
2165 ;; Adjust for buffered output: If there is any output
2166 ;; buffered, the *real* file position will be larger
2167 ;; than reported by lseek() because lseek() obviously
2168 ;; cannot take into account output we have not sent
2170 (dolist (buffer (fd-stream-output-queue stream
))
2171 (incf posn
(- (buffer-tail buffer
) (buffer-head buffer
))))
2172 (let ((obuf (fd-stream-obuf stream
)))
2174 (incf posn
(buffer-tail obuf
))))
2175 ;; Adjust for unread input: If there is any input
2176 ;; read from UNIX but not supplied to the user of the
2177 ;; stream, the *real* file position will smaller than
2178 ;; reported, because we want to look like the unread
2179 ;; stuff is still available.
2180 (let ((ibuf (fd-stream-ibuf stream
)))
2182 (decf posn
(- (buffer-tail ibuf
) (buffer-head ibuf
)))))
2183 ;; Divide bytes by element size.
2184 (truncate posn
(fd-stream-element-size stream
))))))
2186 (defun fd-stream-set-file-position (stream position-spec
)
2187 (declare (fd-stream stream
))
2188 (check-type position-spec
2189 (or (alien sb
!unix
:unix-offset
) (member nil
:start
:end
))
2190 "valid file position designator")
2193 ;; Make sure we don't have any output pending, because if we
2194 ;; move the file pointer before writing this stuff, it will be
2195 ;; written in the wrong location.
2196 (finish-fd-stream-output stream
)
2197 ;; Disable interrupts so that interrupt handlers doing output
2200 (unless (fd-stream-output-finished-p stream
)
2201 ;; We got interrupted and more output came our way during
2202 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2203 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2204 ;; so we prefer to do things like this...
2206 ;; Clear out any pending input to force the next read to go to
2208 (flush-input-buffer stream
)
2209 ;; Trash cached value for listen, so that we check next time.
2210 (setf (fd-stream-listen stream
) nil
)
2212 (multiple-value-bind (offset origin
)
2215 (values 0 sb
!unix
:l_set
))
2217 (values 0 sb
!unix
:l_xtnd
))
2219 (values (* position-spec
(fd-stream-element-size stream
))
2221 (declare (type (alien sb
!unix
:unix-offset
) offset
))
2222 (let ((posn (sb!unix
:unix-lseek
(fd-stream-fd stream
)
2224 ;; CLHS says to return true if the file-position was set
2225 ;; successfully, and NIL otherwise. We are to signal an error
2226 ;; only if the given position was out of bounds, and that is
2227 ;; dealt with above. In times past we used to return NIL for
2228 ;; errno==ESPIPE, and signal an error in other cases.
2230 ;; FIXME: We are still liable to signal an error if flushing
2232 (return-from fd-stream-set-file-position
2233 (typep posn
'(alien sb
!unix
:unix-offset
))))))))
2236 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2238 ;;; Create a stream for the given Unix file descriptor.
2240 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2241 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2242 ;;; default to allowing input.
2244 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2246 ;;; BUFFERING indicates the kind of buffering to use.
2248 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2249 ;;; NIL (the default), then wait forever. When we time out, we signal
2252 ;;; FILE is the name of the file (will be returned by PATHNAME).
2254 ;;; NAME is used to identify the stream when printed.
2256 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2257 ;;; handle blocking IO on the stream.
2258 (defun make-fd-stream (fd
2262 (output nil output-p
)
2263 (element-type 'base-char
)
2265 (external-format :default
)
2275 (format nil
"file ~A" file
)
2276 (format nil
"descriptor ~W" fd
)))
2278 (declare (type index fd
) (type (or real null
) timeout
)
2279 (type (member :none
:line
:full
) buffering
))
2280 (cond ((not (or input-p output-p
))
2282 ((not (or input output
))
2283 (error "File descriptor must be opened either for input or output.")))
2284 (let* ((constructor (ecase class
2285 (fd-stream '%make-fd-stream
)
2286 (form-tracking-stream '%make-form-tracking-stream
)))
2287 (element-mode (stream-element-type-stream-element-mode element-type
))
2288 (stream (funcall constructor
2291 #!-win32
(sb!unix
:fd-type fd
)
2293 #!+win32
(if serve-events
2299 :delete-original delete-original
2301 :buffering buffering
2302 :dual-channel-p dual-channel-p
2303 :element-mode element-mode
2304 :serve-events serve-events
2307 (coerce timeout
'single-float
)
2309 (set-fd-stream-routines stream element-type external-format
2310 input output input-buffer-p
)
2314 (sb!unix
:unix-close fd
)
2316 (format *terminal-io
* "** closed file descriptor ~W **~%"
2321 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2322 ;;; :RENAME-AND-DELETE and :RENAME options.
2323 (defun pick-backup-name (name)
2324 (declare (type simple-string name
))
2325 (concatenate 'simple-string name
".bak"))
2327 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2328 ;;; access, since we don't want to trash unwritable files even if we
2329 ;;; technically can. We return true if we succeed in renaming.
2330 (defun rename-the-old-one (namestring original
)
2331 (unless (sb!unix
:unix-access namestring sb
!unix
:w_ok
)
2332 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring
))
2333 (multiple-value-bind (okay err
) (sb!unix
:unix-rename namestring original
)
2336 (error 'simple-file-error
2337 :pathname namestring
2339 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2340 :format-arguments
(list namestring original
(strerror err
))))))
2342 (defun open (filename
2345 (element-type 'base-char
)
2346 (if-exists nil if-exists-given
)
2347 (if-does-not-exist nil if-does-not-exist-given
)
2348 (external-format :default
)
2349 ;; private options - use at your own risk
2353 &aux
; Squelch assignment warning.
2354 (direction direction
)
2355 (if-does-not-exist if-does-not-exist
)
2356 (if-exists if-exists
))
2358 "Return a stream which reads from or writes to FILENAME.
2360 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2361 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2362 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2363 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2364 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2365 See the manual for details."
2367 ;; Calculate useful stuff.
2368 (multiple-value-bind (input output mask
)
2370 (:input
(values t nil sb
!unix
:o_rdonly
))
2371 (:output
(values nil t sb
!unix
:o_wronly
))
2372 (:io
(values t t sb
!unix
:o_rdwr
))
2373 (:probe
(values t nil sb
!unix
:o_rdonly
)))
2374 (declare (type index mask
))
2375 (let* ( ;; PATHNAME is the pathname we associate with the stream.
2376 (pathname (merge-pathnames filename
))
2377 (physical (physicalize-pathname pathname
))
2378 (truename (probe-file physical
))
2379 ;; NAMESTRING is the native namestring we open the file with.
2380 (namestring (cond (truename
2381 (native-namestring truename
:as-file t
))
2383 (and input
(eq if-does-not-exist
:create
))
2384 (and (eq direction
:io
)
2385 (not if-does-not-exist-given
)))
2386 (native-namestring physical
:as-file t
)))))
2387 (flet ((open-error (format-control &rest format-arguments
)
2388 (error 'simple-file-error
2390 :format-control format-control
2391 :format-arguments format-arguments
)))
2392 ;; Process if-exists argument if we are doing any output.
2394 (unless if-exists-given
2396 (if (eq (pathname-version pathname
) :newest
)
2400 ((:new-version
:error nil
)
2401 (setf mask
(logior mask sb
!unix
:o_excl
)))
2402 ((:rename
:rename-and-delete
)
2403 (setf mask
(logior mask sb
!unix
:o_creat
)))
2405 (setf mask
(logior mask sb
!unix
:o_trunc
)))
2407 (setf mask
(logior mask sb
!unix
:o_append
)))))
2409 (setf if-exists
:ignore-this-arg
)))
2411 (unless if-does-not-exist-given
2412 (setf if-does-not-exist
2413 (cond ((eq direction
:input
) :error
)
2415 (member if-exists
'(:overwrite
:append
)))
2417 ((eq direction
:probe
)
2421 (cond ((and if-exists-given
2423 (eq if-exists
:new-version
))
2424 (open-error "OPEN :IF-EXISTS :NEW-VERSION is not supported ~
2425 when a new version must be created."))
2426 ((eq if-does-not-exist
:create
)
2427 (setf mask
(logior mask sb
!unix
:o_creat
)))
2428 ((not (member if-exists
'(:error nil
))))
2429 ;; Both if-does-not-exist and if-exists now imply
2430 ;; that there will be no opening of files, and either
2431 ;; an error would be signalled, or NIL returned
2432 ((and (not if-exists
) (not if-does-not-exist
))
2434 ((and if-exists if-does-not-exist
)
2435 (open-error "OPEN :IF-DOES-NOT-EXIST ~s ~
2436 :IF-EXISTS ~s will always signal an error."
2437 if-does-not-exist if-exists
))
2440 (open-error "File exists ~s." pathname
)
2441 (return-from open
)))
2443 (open-error "File does not exist ~s." pathname
))
2445 (return-from open
)))
2446 (let ((original (case if-exists
2447 ((:rename
:rename-and-delete
)
2448 (pick-backup-name namestring
))
2449 ((:append
:overwrite
)
2450 ;; KLUDGE: Prevent CLOSE from deleting
2451 ;; appending streams when called with :ABORT T
2453 (delete-original (eq if-exists
:rename-and-delete
))
2455 (when (and original
(not (eq original namestring
)))
2456 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2457 ;; whether the file already exists, make sure the original
2458 ;; file is not a directory, and keep the mode.
2461 (multiple-value-bind (okay err
/dev inode orig-mode
)
2462 (sb!unix
:unix-stat namestring
)
2463 (declare (ignore inode
)
2464 (type (or index null
) orig-mode
))
2467 (when (and output
(= (logand orig-mode
#o170000
)
2469 (error 'simple-file-error
2472 "can't open ~S for output: is a directory"
2473 :format-arguments
(list namestring
)))
2474 (setf mode
(logand orig-mode
#o777
))
2476 ((eql err
/dev sb
!unix
:enoent
)
2479 (simple-file-perror "can't find ~S"
2483 (rename-the-old-one namestring original
))
2485 (setf delete-original nil
)
2486 ;; In order to use :SUPERSEDE instead, we have to make
2487 ;; sure SB!UNIX:O_CREAT corresponds to
2488 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2489 ;; because of IF-EXISTS being :RENAME.
2490 (unless (eq if-does-not-exist
:create
)
2492 (logior (logandc2 mask sb
!unix
:o_creat
)
2494 (setf if-exists
:supersede
))))
2496 ;; Now we can try the actual Unix open(2).
2497 (multiple-value-bind (fd errno
)
2499 (sb!unix
:unix-open namestring mask mode
2500 #!+win32
:overlapped
#!+win32 overlapped
)
2501 (values nil
#!-win32 sb
!unix
:enoent
2502 #!+win32 sb
!win32
::error_file_not_found
))
2503 (flet ((vanilla-open-error ()
2504 (simple-file-perror "error opening ~S" pathname errno
)))
2507 ((:input
:output
:io
)
2508 ;; For O_APPEND opened files, lseek returns 0 until first write.
2509 ;; So we jump ahead here.
2510 (when (eq if-exists
:append
)
2511 (sb!unix
:unix-lseek fd
0 sb
!unix
:l_xtnd
))
2516 :element-type element-type
2517 :external-format external-format
2520 :delete-original delete-original
2528 (%make-fd-stream
:name namestring
2531 :element-type element-type
)))
2534 ((eql errno
#!-win32 sb
!unix
:enoent
2535 #!+win32 sb
!win32
::error_file_not_found
)
2536 (case if-does-not-exist
2537 (:error
(vanilla-open-error))
2539 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2542 ((and (eql errno
#!-win32 sb
!unix
:eexist
2543 #!+win32 sb
!win32
::error_already_exists
)
2547 (vanilla-open-error))))))))))
2551 ;;; the stream connected to the controlling terminal, or NIL if there is none
2554 ;;; the stream connected to the standard input (file descriptor 0)
2557 ;;; the stream connected to the standard output (file descriptor 1)
2560 ;;; the stream connected to the standard error output (file descriptor 2)
2563 ;;; This is called when the cold load is first started up, and may also
2564 ;;; be called in an attempt to recover from nested errors.
2565 (defun stream-cold-init-or-reset ()
2566 ;; FIXME: on gencgc the 4 standard fd-streams {stdin,stdout,stderr,tty}
2567 ;; and these synonym streams are baked into +pseudo-static-generation+.
2568 ;; Is that inadvertent?
2570 (setf *terminal-io
* (make-synonym-stream '*tty
*))
2571 (setf *standard-output
* (make-synonym-stream '*stdout
*))
2572 (setf *standard-input
* (make-synonym-stream '*stdin
*))
2573 (setf *error-output
* (make-synonym-stream '*stderr
*))
2574 (setf *query-io
* (make-synonym-stream '*terminal-io
*))
2575 (setf *debug-io
* *query-io
*)
2576 (setf *trace-output
* *standard-output
*)
2579 (defun stream-deinit ()
2580 ;; Unbind to make sure we're not accidently dealing with it
2581 ;; before we're ready (or after we think it's been deinitialized).
2582 (with-available-buffers-lock ()
2583 (without-package-locks
2584 (makunbound '*available-buffers
*))))
2586 (defun stdstream-external-format (fd outputp
)
2587 #!-win32
(declare (ignore fd outputp
))
2588 (let* ((keyword #!+win32
(if (and (/= fd -
1)
2593 (sb!win32
::console-output-codepage
)
2594 (sb!win32
::console-input-codepage
)))
2595 #!-win32
(default-external-format))
2596 (ef (get-external-format keyword
))
2597 (replacement (ef-default-replacement-character ef
)))
2598 `(,keyword
:replacement
,replacement
)))
2600 ;;; This is called whenever a saved core is restarted.
2601 (defun stream-reinit (&optional init-buffers-p
)
2602 (when init-buffers-p
2603 (with-available-buffers-lock ()
2604 (aver (not (boundp '*available-buffers
*)))
2605 (setf *available-buffers
* nil
)))
2606 (with-simple-output-to-string (*error-output
*)
2607 (multiple-value-bind (in out err
)
2608 #!-win32
(values 0 1 2)
2609 #!+win32
(sb!win32
::get-std-handles
)
2611 (nul-stream (name inputp outputp
)
2612 (let* ((nul-name #.
(coerce "NUL" 'simple-base-string
))
2615 ((and inputp outputp
)
2616 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdwr
))
2618 (sb!win32
:unixlike-open nul-name sb
!unix
:o_rdonly
))
2620 (sb!win32
:unixlike-open nul-name sb
!unix
:o_wronly
))
2622 ;; Not quite sure what to do in this case.
2630 :element-type
:default
2631 :serve-events inputp
2633 :external-format
(stdstream-external-format nul-handle outputp
))))
2634 (stdio-stream (handle name inputp outputp
)
2638 ;; If no actual handle was present, create a stream to NUL
2639 (nul-stream name inputp outputp
))
2647 :element-type
:default
2648 :serve-events inputp
2649 :external-format
(stdstream-external-format handle outputp
))))))
2650 (setf *stdin
* (stdio-stream in
"standard input" t nil
)
2651 *stdout
* (stdio-stream out
"standard output" nil t
)
2652 *stderr
* (stdio-stream err
"standard error" nil t
))))
2654 (setf *tty
* (make-two-way-stream *stdin
* *stdout
*))
2656 ;; FIXME: what is this call to COERCE doing? XC can't dump non-base-strings.
2657 (let* ((ttyname #.
(coerce "/dev/tty" 'simple-base-string
))
2658 (tty (sb!unix
:unix-open ttyname sb
!unix
:o_rdwr
#o666
)))
2661 (make-fd-stream tty
:name
"the terminal"
2662 :input t
:output t
:buffering
:line
2663 :external-format
(stdstream-external-format
2667 (make-two-way-stream *stdin
* *stdout
*))))
2668 (princ (get-output-stream-string *error-output
*) *stderr
*))
2673 ;;; the Unix way to beep
2674 (defun beep (stream)
2675 (write-char (code-char bell-char-code
) stream
)
2676 (finish-output stream
))
2678 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2679 ;;; by the filesys stuff to get and set the file name.
2681 ;;; FIXME: misleading name, screwy interface
2682 (defun file-name (stream &optional new-name
)
2683 (when (typep stream
'fd-stream
)
2685 (setf (fd-stream-pathname stream
) new-name
)
2686 (setf (fd-stream-file stream
)
2687 (native-namestring (physicalize-pathname new-name
)
2691 (fd-stream-pathname stream
)))))
2693 ;; Fix the INPUT-CHAR-POS slot of STREAM after having consumed characters
2694 ;; from the CIN-BUFFER. This operation is done upon exit from a FAST-READ-CHAR
2695 ;; loop, and for each buffer refill inside the loop.
2696 (defun update-input-char-pos (stream &optional
(end +ansi-stream-in-buffer-length
+))
2697 (do ((chars (ansi-stream-cin-buffer stream
))
2698 (pos (form-tracking-stream-input-char-pos stream
))
2699 (i (ansi-stream-in-index stream
) (1+ i
)))
2701 (setf (form-tracking-stream-input-char-pos stream
) pos
))
2702 (let ((char (aref chars i
)))
2703 (when (and (eql char
#\Newline
)
2704 ;; record it only if it wasn't unread and re-read
2705 (> pos
(form-tracking-stream-last-newline stream
)))
2706 (vector-push-extend pos
(form-tracking-stream-newlines stream
))
2707 (setf (form-tracking-stream-last-newline stream
) pos
))
2710 (defun tracking-stream-misc (stream operation
&optional arg1 arg2
)
2711 ;; The :UNREAD operation will never be invoked because STREAM has a buffer,
2712 ;; so unreading is implemented entirely within ANSI-STREAM-UNREAD-CHAR.
2713 ;; But we do need to prevent attempts to change the absolute position.
2717 (error 'simple-stream-error
2718 :format-control
"~S is not positionable"
2719 :format-arguments
(list stream
))
2720 (fd-stream-get-file-position stream
)))
2721 (t ; call next method
2722 (fd-stream-misc-routine stream operation arg1 arg2
))))
2724 ;; Using (get-std-handle-or-null +std-error-handle+) instead of the file
2725 ;; descriptor might make this work on win32, but I don't know.
2727 (macrolet ((stderr () 2))
2728 (!defglobal
*!cold-stderr-buf
* " ")
2729 (defun !make-cold-stderr-stream
()
2731 :out
(lambda (stream ch
)
2732 (declare (ignore stream
))
2733 (let ((b (truly-the (simple-base-string 1) *!cold-stderr-buf
*)))
2734 (setf (char b
0) ch
)
2735 (sb!unix
:unix-write
(stderr) b
0 1)))
2736 :sout
(lambda (stream string start end
)
2737 (declare (ignore stream
))
2738 (flet ((out (s start len
)
2739 (sb!unix
:unix-write
(stderr) s start len
)))
2740 (if (typep string
'simple-base-string
)
2741 (out string start
(- end start
))
2742 (let ((n (- end start
)))
2743 ;; will croak if there is any non-BASE-CHAR in the string
2744 (out (replace (make-array n
:element-type
'base-char
)
2745 string
:start2 start
) 0 n
)))))
2746 :misc
(constantly nil
))))