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 (declaim (inline buffer-sap buffer-length buffer-head buffer-tail
44 (setf buffer-head) (setf buffer-tail)))
45 (defstruct (buffer (:constructor %make-buffer (sap length)))
46 (sap (missing-arg) :type system-area-pointer :read-only t)
47 (length (missing-arg) :type index :read-only t)
51 (defvar *available-buffers* ()
53 "List of available buffers.")
55 (defvar *available-buffers-lock* (sb!thread:make-mutex
56 :name "lock for *AVAILABLE-BUFFERS*")
58 "Mutex for access to *AVAILABLE-BUFFERS*.")
60 (defmacro with-available-buffers-lock ((&optional) &body body)
61 ;; CALL-WITH-SYSTEM-MUTEX because streams are low-level enough to be
62 ;; async signal safe, and in particular a C-c that brings up the
63 ;; debugger while holding the mutex would lose badly.
64 `(sb!thread::with-system-mutex (*available-buffers-lock*)
67 (defconstant +bytes-per-buffer+ (* 4 1024)
69 "Default number of bytes per buffer.")
71 (defun alloc-buffer (&optional (size +bytes-per-buffer+))
72 ;; Don't want to allocate & unwind before the finalizer is in place.
74 (let* ((sap (allocate-system-memory size))
75 (buffer (%make-buffer sap size)))
76 (when (zerop (sap-int sap))
77 (error "Could not allocate ~D bytes for buffer." size))
78 (finalize buffer (lambda ()
79 (deallocate-system-memory sap size))
84 ;; Don't go for the lock if there is nothing to be had -- sure,
85 ;; another thread might just release one before we get it, but that
86 ;; is not worth the cost of locking. Also release the lock before
87 ;; allocation, since it's going to take a while.
88 (if *available-buffers*
89 (or (with-available-buffers-lock ()
90 (pop *available-buffers*))
94 (declaim (inline reset-buffer))
95 (defun reset-buffer (buffer)
96 (setf (buffer-head buffer) 0
97 (buffer-tail buffer) 0)
100 (defun release-buffer (buffer)
101 (reset-buffer buffer)
102 (with-available-buffers-lock ()
103 (push buffer *available-buffers*)))
105 ;;; This is a separate buffer management function, as it wants to be
106 ;;; clever about locking -- grabbing the lock just once.
107 (defun release-fd-stream-buffers (fd-stream)
108 (let ((ibuf (fd-stream-ibuf fd-stream))
109 (obuf (fd-stream-obuf fd-stream))
110 (queue (loop for item in (fd-stream-output-queue fd-stream)
112 collect (reset-buffer item))))
114 (push (reset-buffer ibuf) queue))
116 (push (reset-buffer obuf) queue))
117 ;; ...so, anything found?
119 ;; detach from stream
120 (setf (fd-stream-ibuf fd-stream) nil
121 (fd-stream-obuf fd-stream) nil
122 (fd-stream-output-queue fd-stream) nil)
123 ;; splice to *available-buffers*
124 (with-available-buffers-lock ()
125 (setf *available-buffers* (nconc queue *available-buffers*))))))
127 ;;;; the FD-STREAM structure
129 (defstruct (fd-stream
130 (:constructor %make-fd-stream)
131 (:conc-name fd-stream-)
132 (:predicate fd-stream-p)
133 (:include ansi-stream
134 (misc #'fd-stream-misc-routine))
137 ;; the name of this stream
139 ;; the file this stream is for
141 ;; the backup file namestring for the old file, for :IF-EXISTS
142 ;; :RENAME or :RENAME-AND-DELETE.
143 (original nil :type (or simple-string null))
144 (delete-original nil) ; for :if-exists :rename-and-delete
145 ;;; the number of bytes per element
146 (element-size 1 :type index)
147 ;; the type of element being transfered
148 (element-type 'base-char)
149 ;; the Unix file descriptor
150 (fd -1 :type #!-win32 fixnum #!+win32 sb!vm:signed-word)
151 ;; What do we know about the FD?
152 (fd-type :unknown :type keyword)
153 ;; controls when the output buffer is flushed
154 (buffering :full :type (member :full :line :none))
155 ;; controls whether the input buffer must be cleared before output
156 ;; (must be done for files, not for sockets, pipes and other data
157 ;; sources where input and output aren't related). non-NIL means
158 ;; don't clear input buffer.
160 ;; character position if known -- this may run into bignums, but
161 ;; we probably should flip it into null then for efficiency's sake...
162 (char-pos nil :type (or unsigned-byte null))
163 ;; T if input is waiting on FD. :EOF if we hit EOF.
164 (listen nil :type (member nil t :eof))
165 ;; T if serve-event is allowed when this stream blocks
166 (serve-events nil :type boolean)
169 (instead (make-array 0 :element-type 'character :adjustable t :fill-pointer t) :type (array character (*)))
170 (ibuf nil :type (or buffer null))
171 (eof-forced-p nil :type (member t nil))
174 (obuf nil :type (or buffer null))
176 ;; output flushed, but not written due to non-blocking io?
179 ;; timeout specified for this stream as seconds or NIL if none
180 (timeout nil :type (or single-float null))
181 ;; pathname of the file this stream is opened to (returned by PATHNAME)
182 (pathname nil :type (or pathname null))
183 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
184 (external-format :latin-1)
185 ;; fixed width, or function to call with a character
186 (char-size 1 :type (or fixnum function))
187 (output-bytes #'ill-out :type function)
188 ;; a boolean indicating whether the stream is bivalent. For
189 ;; internal use only.
190 (bivalent-p nil :type boolean))
191 (def!method print-object ((fd-stream fd-stream) stream)
192 (declare (type stream stream))
193 (print-unreadable-object (fd-stream stream :type t :identity t)
194 (format stream "for ~S" (fd-stream-name fd-stream))))
196 ;;;; CORE OUTPUT FUNCTIONS
198 ;;; Buffer the section of THING delimited by START and END by copying
199 ;;; to output buffer(s) of stream.
200 (defun buffer-output (stream thing start end)
201 (declare (index start end))
203 (error ":END before :START!"))
205 ;; Copy bytes from THING to buffers.
206 (flet ((copy-to-buffer (buffer tail count)
207 (declare (buffer buffer) (index tail count))
209 (let ((sap (buffer-sap buffer)))
212 (system-area-ub8-copy thing start sap tail count))
213 ((simple-unboxed-array (*))
214 (copy-ub8-to-system-area thing start sap tail count))))
215 ;; Not INCF! If another thread has moved tail from under
216 ;; us, we don't want to accidentally increment tail
217 ;; beyond buffer-length.
218 (setf (buffer-tail buffer) (+ count tail))
221 ;; First copy is special: the buffer may already contain
222 ;; something, or be even full.
223 (let* ((obuf (fd-stream-obuf stream))
224 (tail (buffer-tail obuf))
225 (space (- (buffer-length obuf) tail)))
227 (copy-to-buffer obuf tail (min space (- end start)))
228 (go :more-output-p)))
230 ;; Later copies should always have an empty buffer, since
231 ;; they are freshly flushed, but if another thread is
232 ;; stomping on the same buffer that might not be the case.
233 (let* ((obuf (flush-output-buffer stream))
234 (tail (buffer-tail obuf))
235 (space (- (buffer-length obuf) tail)))
236 (copy-to-buffer obuf tail (min space (- end start))))
239 (go :flush-and-fill))))))
241 ;;; Flush the current output buffer of the stream, ensuring that the
242 ;;; new buffer is empty. Returns (for convenience) the new output
243 ;;; buffer -- which may or may not be EQ to the old one. If the is no
244 ;;; queued output we try to write the buffer immediately -- otherwise
245 ;;; we queue it for later.
246 (defun flush-output-buffer (stream)
247 (let ((obuf (fd-stream-obuf stream)))
249 (let ((head (buffer-head obuf))
250 (tail (buffer-tail obuf)))
251 (cond ((eql head tail)
252 ;; Buffer is already empty -- just ensure that is is
253 ;; set to zero as well.
255 ((fd-stream-output-queue stream)
256 ;; There is already stuff on the queue -- go directly
259 (%queue-and-replace-output-buffer stream))
261 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
262 ;; whatever is left over. Otherwise wait until we can write.
264 (synchronize-stream-output stream)
266 (let ((length (- tail head)))
267 (multiple-value-bind (count errno)
268 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
270 (flet ((queue-or-wait ()
271 (if (fd-stream-serve-events stream)
272 (return (%queue-and-replace-output-buffer stream))
273 (or (wait-until-fd-usable (fd-stream-fd stream) :output
274 (fd-stream-timeout stream)
276 (signal-timeout 'io-timeout
279 :seconds (fd-stream-timeout stream))))))
280 (cond ((eql count length)
281 ;; Complete write -- we can use the same buffer.
282 (return (reset-buffer obuf)))
284 ;; Partial write -- update buffer status and
287 (setf (buffer-head obuf) head)
290 ((eql errno sb!unix:ewouldblock)
291 ;; Blocking, queue or wair.
293 ;; if interrupted on win32, just try again
294 #!+win32 ((eql errno sb!unix:eintr))
296 (simple-stream-perror "Couldn't write to ~s"
297 stream errno)))))))))))))
299 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
300 (defun %queue-and-replace-output-buffer (stream)
301 (aver (fd-stream-serve-events stream))
302 (let ((queue (fd-stream-output-queue stream))
303 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
305 ;; Important: before putting the buffer on queue, give the stream
306 ;; a new one. If we get an interrupt and unwind losing the buffer
307 ;; is relatively OK, but having the same buffer in two places
309 (setf (fd-stream-obuf stream) new)
313 (setf (fd-stream-output-queue stream) later)))
314 (unless (fd-stream-handler stream)
315 (setf (fd-stream-handler stream)
316 (add-fd-handler (fd-stream-fd stream)
319 (declare (ignore fd))
320 (write-output-from-queue stream)))))
323 ;;; This is called by the FD-HANDLER for the stream when output is
325 (defun write-output-from-queue (stream)
326 (aver (fd-stream-serve-events stream))
327 (synchronize-stream-output stream)
331 (let* ((buffer (pop (fd-stream-output-queue stream)))
332 (head (buffer-head buffer))
333 (length (- (buffer-tail buffer) head)))
334 (declare (index head length))
336 (multiple-value-bind (count errno)
337 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
339 (cond ((eql count length)
340 ;; Complete write, see if we can do another right
341 ;; away, or remove the handler if we're done.
342 (release-buffer buffer)
343 (cond ((fd-stream-output-queue stream)
347 (let ((handler (fd-stream-handler stream)))
349 (setf (fd-stream-handler stream) nil)
350 (remove-fd-handler handler)))))
352 ;; Partial write. Update buffer status and requeue.
353 (aver (< count length))
354 ;; Do not use INCF! Another thread might have moved head.
355 (setf (buffer-head buffer) (+ head count))
356 (push buffer (fd-stream-output-queue stream)))
358 ;; We tried to do multiple writes, and finally our
359 ;; luck ran out. Requeue.
360 (push buffer (fd-stream-output-queue stream)))
362 ;; Could not write on the first try at all!
364 (simple-stream-perror "Couldn't write to ~S." stream errno)
366 (if (= errno sb!unix:ewouldblock)
367 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
368 (simple-stream-perror "Couldn't write to ~S"
372 ;;; Try to write THING directly to STREAM without buffering, if
373 ;;; possible. If direct write doesn't happen, buffer.
374 (defun write-or-buffer-output (stream thing start end)
375 (declare (index start end))
376 (cond ((fd-stream-output-queue stream)
377 (buffer-output stream thing start end))
379 (error ":END before :START!"))
381 (let ((length (- end start)))
382 (synchronize-stream-output stream)
383 (multiple-value-bind (count errno)
384 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
385 (cond ((eql count length)
386 ;; Complete write -- done!
389 (aver (< count length))
390 ;; Partial write -- buffer the rest.
391 (buffer-output stream thing (+ start count) end))
393 ;; Could not write -- buffer or error.
395 (simple-stream-perror "couldn't write to ~s" stream errno)
397 (if (= errno sb!unix:ewouldblock)
398 (buffer-output stream thing start end)
399 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
401 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
402 ;;; this is not something we want to export. Nikodemus thinks the
403 ;;; right thing is to support a low-level non-stream like IO layer,
404 ;;; akin to java.nio.
405 (declaim (inline output-raw-bytes))
406 (define-deprecated-function :late "1.0.8.16" output-raw-bytes write-sequence
407 (stream thing &optional start end)
408 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
410 ;;;; output routines and related noise
412 (defvar *output-routines* ()
414 "List of all available output routines. Each element is a list of the
415 element-type output, the kind of buffering, the function name, and the number
416 of bytes per element.")
418 ;;; common idioms for reporting low-level stream and file problems
419 (defun simple-stream-perror (note-format stream errno)
420 (error 'simple-stream-error
422 :format-control "~@<~?: ~2I~_~A~:>"
423 :format-arguments (list note-format (list stream) (strerror errno))))
424 (defun simple-file-perror (note-format pathname errno)
425 (error 'simple-file-error
427 :format-control "~@<~?: ~2I~_~A~:>"
429 (list note-format (list pathname) (strerror errno))))
431 (defun c-string-encoding-error (external-format code)
432 (error 'c-string-encoding-error
433 :external-format external-format
435 (defun c-string-decoding-error (external-format sap offset count)
436 (error 'c-string-decoding-error
437 :external-format external-format
438 :octets (sap-ref-octets sap offset count)))
440 ;;; Returning true goes into end of file handling, false will enter another
441 ;;; round of input buffer filling followed by re-entering character decode.
442 (defun stream-decoding-error-and-handle (stream octet-count)
444 (error 'stream-decoding-error
445 :external-format (stream-external-format stream)
447 :octets (let ((buffer (fd-stream-ibuf stream)))
448 (sap-ref-octets (buffer-sap buffer)
452 :report (lambda (stream)
454 "~@<Attempt to resync the stream at a ~
455 character boundary and continue.~@:>"))
456 (fd-stream-resync stream)
458 (force-end-of-file ()
459 :report (lambda (stream)
460 (format stream "~@<Force an end of file.~@:>"))
461 (setf (fd-stream-eof-forced-p stream) t))
462 (input-replacement (string)
463 :report (lambda (stream)
464 (format stream "~@<Use string as replacement input, ~
465 attempt to resync at a character ~
466 boundary and continue.~@:>"))
467 :interactive (lambda ()
468 (format *query-io* "~@<Enter a string: ~@:>")
469 (finish-output *query-io*)
470 (list (read *query-io*)))
471 (let ((string (reverse (string string)))
472 (instead (fd-stream-instead stream)))
473 (dotimes (i (length string))
474 (vector-push-extend (char string i) instead))
475 (fd-stream-resync stream)
476 (when (> (length string) 0)
477 (setf (fd-stream-listen stream) t)))
480 (defun stream-encoding-error-and-handle (stream code)
482 (error 'stream-encoding-error
483 :external-format (stream-external-format stream)
487 :report (lambda (stream)
488 (format stream "~@<Skip output of this character.~@:>"))
489 (throw 'output-nothing nil))
490 (output-replacement (string)
491 :report (lambda (stream)
492 (format stream "~@<Output replacement string.~@:>"))
493 :interactive (lambda ()
494 (format *query-io* "~@<Enter a string: ~@:>")
495 (finish-output *query-io*)
496 (list (read *query-io*)))
497 (let ((string (string string)))
498 (fd-sout stream (string string) 0 (length string)))
499 (throw 'output-nothing nil))))
501 (defun external-format-encoding-error (stream code)
503 (stream-encoding-error-and-handle stream code)
504 (c-string-encoding-error stream code)))
506 (defun synchronize-stream-output (stream)
507 ;; If we're reading and writing on the same file, flush buffered
508 ;; input and rewind file position accordingly.
509 (unless (fd-stream-dual-channel-p stream)
510 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
511 (unless (eql 0 adjust)
512 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
514 (defun fd-stream-output-finished-p (stream)
515 (let ((obuf (fd-stream-obuf stream)))
517 (and (zerop (buffer-tail obuf))
518 (not (fd-stream-output-queue stream))))))
520 (defmacro output-wrapper/variable-width ((stream size buffering restart)
522 (let ((stream-var (gensym "STREAM")))
523 `(let* ((,stream-var ,stream)
524 (obuf (fd-stream-obuf ,stream-var))
525 (tail (buffer-tail obuf))
527 ,(unless (eq (car buffering) :none)
528 `(when (<= (buffer-length obuf) (+ tail size))
529 (setf obuf (flush-output-buffer ,stream-var)
530 tail (buffer-tail obuf))))
531 ,(unless (eq (car buffering) :none)
532 ;; FIXME: Why this here? Doesn't seem necessary.
533 `(synchronize-stream-output ,stream-var))
535 `(catch 'output-nothing
537 (setf (buffer-tail obuf) (+ tail size)))
540 (setf (buffer-tail obuf) (+ tail size))))
541 ,(ecase (car buffering)
543 `(flush-output-buffer ,stream-var))
545 `(when (eql byte #\Newline)
546 (flush-output-buffer ,stream-var)))
550 (defmacro output-wrapper ((stream size buffering restart) &body body)
551 (let ((stream-var (gensym "STREAM")))
552 `(let* ((,stream-var ,stream)
553 (obuf (fd-stream-obuf ,stream-var))
554 (tail (buffer-tail obuf)))
555 ,(unless (eq (car buffering) :none)
556 `(when (<= (buffer-length obuf) (+ tail ,size))
557 (setf obuf (flush-output-buffer ,stream-var)
558 tail (buffer-tail obuf))))
559 ;; FIXME: Why this here? Doesn't seem necessary.
560 ,(unless (eq (car buffering) :none)
561 `(synchronize-stream-output ,stream-var))
563 `(catch 'output-nothing
565 (setf (buffer-tail obuf) (+ tail ,size)))
568 (setf (buffer-tail obuf) (+ tail ,size))))
569 ,(ecase (car buffering)
571 `(flush-output-buffer ,stream-var))
573 `(when (eql byte #\Newline)
574 (flush-output-buffer ,stream-var)))
578 (defmacro def-output-routines/variable-width
579 ((name-fmt size restart external-format &rest bufferings)
581 (declare (optimize (speed 1)))
586 (intern (format nil name-fmt (string (car buffering))))))
588 (defun ,function (stream byte)
589 (declare (ignorable byte))
590 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
592 (setf *output-routines*
593 (nconc *output-routines*
601 (cdr buffering)))))))
604 ;;; Define output routines that output numbers SIZE bytes long for the
605 ;;; given bufferings. Use BODY to do the actual output.
606 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
608 (declare (optimize (speed 1)))
613 (intern (format nil name-fmt (string (car buffering))))))
615 (defun ,function (stream byte)
616 (output-wrapper (stream ,size ,buffering ,restart)
618 (setf *output-routines*
619 (nconc *output-routines*
627 (cdr buffering)))))))
630 ;;; FIXME: is this used anywhere any more?
631 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
637 (if (eql byte #\Newline)
638 (setf (fd-stream-char-pos stream) 0)
639 (incf (fd-stream-char-pos stream)))
640 (setf (sap-ref-8 (buffer-sap obuf) tail)
643 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
646 (:none (unsigned-byte 8))
647 (:full (unsigned-byte 8)))
648 (setf (sap-ref-8 (buffer-sap obuf) tail)
651 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
654 (:none (signed-byte 8))
655 (:full (signed-byte 8)))
656 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
659 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
662 (:none (unsigned-byte 16))
663 (:full (unsigned-byte 16)))
664 (setf (sap-ref-16 (buffer-sap obuf) tail)
667 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
670 (:none (signed-byte 16))
671 (:full (signed-byte 16)))
672 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
675 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
678 (:none (unsigned-byte 32))
679 (:full (unsigned-byte 32)))
680 (setf (sap-ref-32 (buffer-sap obuf) tail)
683 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
686 (:none (signed-byte 32))
687 (:full (signed-byte 32)))
688 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
691 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
693 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
696 (:none (unsigned-byte 64))
697 (:full (unsigned-byte 64)))
698 (setf (sap-ref-64 (buffer-sap obuf) tail)
700 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
703 (:none (signed-byte 64))
704 (:full (signed-byte 64)))
705 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
708 ;;; the routine to use to output a string. If the stream is
709 ;;; unbuffered, slam the string down the file descriptor, otherwise
710 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
711 ;;; checking to see where the last newline was.
712 (defun fd-sout (stream thing start end)
713 (declare (type fd-stream stream) (type string thing))
714 (let ((start (or start 0))
715 (end (or end (length (the vector thing)))))
716 (declare (fixnum start end))
718 (string-dispatch (simple-base-string
720 (simple-array character (*))
723 (position #\newline thing :from-end t
724 :start start :end end))))
725 (if (and (typep thing 'base-string)
726 (eq (fd-stream-external-format-keyword stream) :latin-1))
727 (ecase (fd-stream-buffering stream)
729 (buffer-output stream thing start end))
731 (buffer-output stream thing start end)
733 (flush-output-buffer stream)))
735 (write-or-buffer-output stream thing start end)))
736 (ecase (fd-stream-buffering stream)
737 (:full (funcall (fd-stream-output-bytes stream)
738 stream thing nil start end))
739 (:line (funcall (fd-stream-output-bytes stream)
740 stream thing last-newline start end))
741 (:none (funcall (fd-stream-output-bytes stream)
742 stream thing t start end))))
744 (setf (fd-stream-char-pos stream) (- end last-newline 1))
745 (incf (fd-stream-char-pos stream) (- end start))))))
747 (defstruct (external-format
748 (:constructor %make-external-format)
750 (:predicate external-format-p)
751 (:copier %copy-external-format))
752 ;; All the names that can refer to this external format. The first
753 ;; one is the canonical name.
754 (names (missing-arg) :type list :read-only t)
755 (default-replacement-character (missing-arg) :type character)
756 (read-n-chars-fun (missing-arg) :type function)
757 (read-char-fun (missing-arg) :type function)
758 (write-n-bytes-fun (missing-arg) :type function)
759 (write-char-none-buffered-fun (missing-arg) :type function)
760 (write-char-line-buffered-fun (missing-arg) :type function)
761 (write-char-full-buffered-fun (missing-arg) :type function)
762 ;; Can be nil for fixed-width formats.
763 (resync-fun nil :type (or function null))
764 (bytes-for-char-fun (missing-arg) :type function)
765 (read-c-string-fun (missing-arg) :type function)
766 (write-c-string-fun (missing-arg) :type function)
767 ;; We indirect through symbols in these functions so that a
768 ;; developer working on the octets code can easily redefine things
769 ;; and use the new function definition without redefining the
770 ;; external format as well. The slots above don't do any
771 ;; indirection because a developer working with those slots would be
772 ;; redefining the external format anyway.
773 (octets-to-string-fun (missing-arg) :type function)
774 (string-to-octets-fun (missing-arg) :type function))
776 (defun ef-char-size (ef-entry)
777 (if (variable-width-external-format-p ef-entry)
778 (bytes-for-char-fun ef-entry)
779 (funcall (bytes-for-char-fun ef-entry) #\x)))
781 (defun wrap-external-format-functions (external-format fun)
782 (let ((result (%copy-external-format external-format)))
783 (macrolet ((frob (accessor)
784 `(setf (,accessor result) (funcall fun (,accessor result)))))
785 (frob ef-read-n-chars-fun)
786 (frob ef-read-char-fun)
787 (frob ef-write-n-bytes-fun)
788 (frob ef-write-char-none-buffered-fun)
789 (frob ef-write-char-line-buffered-fun)
790 (frob ef-write-char-full-buffered-fun)
792 (frob ef-bytes-for-char-fun)
793 (frob ef-read-c-string-fun)
794 (frob ef-write-c-string-fun)
795 (frob ef-octets-to-string-fun)
796 (frob ef-string-to-octets-fun))
799 (defvar *external-formats* (make-hash-table)
801 "Hashtable of all available external formats. The table maps from
802 external-format names to EXTERNAL-FORMAT structures.")
804 (defun get-external-format (external-format)
805 (flet ((keyword-external-format (keyword)
806 (declare (type keyword keyword))
807 (gethash keyword *external-formats*))
808 (replacement-handlerify (entry replacement)
810 (wrap-external-format-functions
815 (declare (dynamic-extent rest))
817 ((stream-decoding-error
820 (invoke-restart 'input-replacement replacement)))
821 (stream-encoding-error
824 (invoke-restart 'output-replacement replacement)))
825 (octets-encoding-error
826 (lambda (c) (use-value replacement c)))
827 (octet-decoding-error
828 (lambda (c) (use-value replacement c))))
829 (apply fun rest)))))))))
830 (typecase external-format
831 (keyword (keyword-external-format external-format))
833 (let ((entry (keyword-external-format (car external-format)))
834 (replacement (getf (cdr external-format) :replacement)))
836 (replacement-handlerify entry replacement)
839 (defun get-external-format-or-lose (external-format)
840 (or (get-external-format external-format)
841 (error "Undefined external-format: ~S" external-format)))
843 (defun external-format-keyword (external-format)
844 (typecase external-format
845 (keyword external-format)
846 ((cons keyword) (car external-format))))
848 (defun fd-stream-external-format-keyword (stream)
849 (external-format-keyword (fd-stream-external-format stream)))
851 (defun canonize-external-format (external-format entry)
852 (typecase external-format
853 (keyword (first (ef-names entry)))
854 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
856 ;;; Find an output routine to use given the type and buffering. Return
857 ;;; as multiple values the routine, the real type transfered, and the
858 ;;; number of bytes per element.
859 (defun pick-output-routine (type buffering &optional external-format)
860 (when (subtypep type 'character)
861 (let ((entry (get-external-format-or-lose external-format)))
862 (return-from pick-output-routine
863 (values (ecase buffering
864 (:none (ef-write-char-none-buffered-fun entry))
865 (:line (ef-write-char-line-buffered-fun entry))
866 (:full (ef-write-char-full-buffered-fun entry)))
869 (ef-write-n-bytes-fun entry)
871 (canonize-external-format external-format entry)))))
872 (dolist (entry *output-routines*)
873 (when (and (subtypep type (first entry))
874 (eq buffering (second entry))
875 (or (not (fifth entry))
876 (eq external-format (fifth entry))))
877 (return-from pick-output-routine
878 (values (symbol-function (third entry))
881 ;; KLUDGE: dealing with the buffering here leads to excessive code
884 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
885 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
886 if (subtypep type `(unsigned-byte ,i))
887 do (return-from pick-output-routine
891 (lambda (stream byte)
892 (output-wrapper (stream (/ i 8) (:none) nil)
893 (loop for j from 0 below (/ i 8)
894 do (setf (sap-ref-8 (buffer-sap obuf)
896 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
898 (lambda (stream byte)
899 (output-wrapper (stream (/ i 8) (:full) nil)
900 (loop for j from 0 below (/ i 8)
901 do (setf (sap-ref-8 (buffer-sap obuf)
903 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
906 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
907 if (subtypep type `(signed-byte ,i))
908 do (return-from pick-output-routine
912 (lambda (stream byte)
913 (output-wrapper (stream (/ i 8) (:none) nil)
914 (loop for j from 0 below (/ i 8)
915 do (setf (sap-ref-8 (buffer-sap obuf)
917 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
919 (lambda (stream byte)
920 (output-wrapper (stream (/ i 8) (:full) nil)
921 (loop for j from 0 below (/ i 8)
922 do (setf (sap-ref-8 (buffer-sap obuf)
924 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
928 ;;;; input routines and related noise
930 ;;; a list of all available input routines. Each element is a list of
931 ;;; the element-type input, the function name, and the number of bytes
933 (defvar *input-routines* ())
935 ;;; Return whether a primitive partial read operation on STREAM's FD
936 ;;; would (probably) block. Signal a `simple-stream-error' if the
937 ;;; system call implementing this operation fails.
939 ;;; It is "may" instead of "would" because "would" is not quite
940 ;;; correct on win32. However, none of the places that use it require
941 ;;; further assurance than "may" versus "will definitely not".
942 (defun sysread-may-block-p (stream)
944 ;; This answers T at EOF on win32, I think.
945 (not (sb!win32:fd-listen (fd-stream-fd stream)))
947 (not (sb!unix:unix-simple-poll (fd-stream-fd stream) :input 0)))
949 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
950 ;;; then fill the input buffer, and return the number of bytes read. Throws
951 ;;; to EOF-INPUT-CATCHER if the eof was reached.
952 (defun refill-input-buffer (stream)
953 (dx-let ((fd (fd-stream-fd stream))
960 ;; Check for blocking input before touching the stream if we are to
961 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
962 ;; read(). Regular files should never block, so we can elide the check.
963 (if (and (neq :regular (fd-stream-fd-type stream))
964 (sysread-may-block-p stream))
967 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
968 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
970 (closed-flame stream)
972 (simple-stream-perror "couldn't read from ~S" stream errno)
974 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
975 ;; to wait for input if read tells us EWOULDBLOCK.
976 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream)
977 (fd-stream-serve-events stream))
978 (signal-timeout 'io-timeout
981 :seconds (fd-stream-timeout stream)))
983 ;; Since the read should not block, we'll disable the
984 ;; interrupts here, so that we don't accidentally unwind and
985 ;; leave the stream in an inconsistent state.
987 ;; Execute the nlx outside without-interrupts to ensure the
988 ;; resulting thunk is stack-allocatable.
989 ((lambda (return-reason)
991 ((nil)) ; fast path normal cases
992 ((:wait-for-input) (go #!-win32 :wait-for-input #!+win32 :main))
993 ((:closed-flame) (go :closed-flame))
994 ((:read-error) (go :read-error))))
996 ;; Check the buffer: if it is null, then someone has closed
997 ;; the stream from underneath us. This is not ment to fix
998 ;; multithreaded races, but to deal with interrupt handlers
999 ;; closing the stream.
1002 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1003 (sap (buffer-sap ibuf))
1004 (length (buffer-length ibuf))
1005 (head (buffer-head ibuf))
1006 (tail (buffer-tail ibuf)))
1007 (declare (index length head tail)
1008 (inline sb!unix:unix-read))
1009 (unless (zerop head)
1010 (cond ((eql head tail)
1011 ;; Buffer is empty, but not at yet reset -- make it so.
1014 (reset-buffer ibuf))
1016 ;; Buffer has things in it, but they are not at the
1017 ;; head -- move them there.
1018 (let ((n (- tail head)))
1019 (system-area-ub8-copy sap head sap 0 n)
1021 (buffer-head ibuf) head
1023 (buffer-tail ibuf) tail)))))
1024 (setf (fd-stream-listen stream) nil)
1025 (setf (values count errno)
1026 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1029 #!+win32 sb!unix:eintr
1030 #!-win32 sb!unix:ewouldblock)
1031 (return :wait-for-input)
1032 (return :read-error)))
1034 (setf (fd-stream-listen stream) :eof)
1035 (/show0 "THROWing EOF-INPUT-CATCHER")
1036 (throw 'eof-input-catcher nil))
1038 ;; Success! (Do not use INCF, for sake of other threads.)
1039 (setf (buffer-tail ibuf) (+ count tail))))))))))
1042 ;;; Make sure there are at least BYTES number of bytes in the input
1043 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1044 (defmacro input-at-least (stream bytes)
1045 (let ((stream-var (gensym "STREAM"))
1046 (bytes-var (gensym "BYTES"))
1047 (buffer-var (gensym "IBUF")))
1048 `(let* ((,stream-var ,stream)
1050 (,buffer-var (fd-stream-ibuf ,stream-var)))
1052 (when (>= (- (buffer-tail ,buffer-var)
1053 (buffer-head ,buffer-var))
1056 (refill-input-buffer ,stream-var)))))
1058 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1060 (let ((stream-var (gensym "STREAM"))
1061 (retry-var (gensym "RETRY"))
1062 (element-var (gensym "ELT")))
1063 `(let* ((,stream-var ,stream)
1064 (ibuf (fd-stream-ibuf ,stream-var))
1067 (when (fd-stream-eof-forced-p ,stream-var)
1068 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1069 (return-from use-instead
1070 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1071 (let ((,element-var nil)
1072 (decode-break-reason nil))
1073 (do ((,retry-var t))
1075 (if (> (length (fd-stream-instead ,stream-var)) 0)
1076 (let* ((instead (fd-stream-instead ,stream-var))
1077 (result (vector-pop instead))
1078 (pointer (fill-pointer instead)))
1080 (setf (fd-stream-listen ,stream-var) nil))
1081 (return-from use-instead result))
1083 (catch 'eof-input-catcher
1084 (setf decode-break-reason
1085 (block decode-break-reason
1086 (input-at-least ,stream-var ,(if (consp bytes)
1088 `(setq size ,bytes)))
1089 (let* ((byte (sap-ref-8 (buffer-sap ibuf) (buffer-head ibuf))))
1090 (declare (ignorable byte))
1091 ,@(when (consp bytes)
1092 `((let ((sap (buffer-sap ibuf))
1093 (head (buffer-head ibuf)))
1094 (declare (ignorable sap head))
1095 (setq size ,(cadr bytes))
1096 (input-at-least ,stream-var size))))
1097 (setq ,element-var (locally ,@read-forms))
1098 (setq ,retry-var nil))
1100 (when decode-break-reason
1101 (when (stream-decoding-error-and-handle
1102 stream decode-break-reason)
1103 (setq ,retry-var nil)
1104 (throw 'eof-input-catcher nil)))
1106 (let ((octet-count (- (buffer-tail ibuf)
1107 (buffer-head ibuf))))
1108 (when (or (zerop octet-count)
1109 (and (not ,element-var)
1110 (not decode-break-reason)
1111 (stream-decoding-error-and-handle
1112 stream octet-count)))
1113 (setq ,retry-var nil))))))
1115 (incf (buffer-head ibuf) size)
1118 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1120 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1121 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1122 (let ((stream-var (gensym "STREAM"))
1123 (element-var (gensym "ELT")))
1124 `(let* ((,stream-var ,stream)
1125 (ibuf (fd-stream-ibuf ,stream-var)))
1126 (if (> (length (fd-stream-instead ,stream-var)) 0)
1127 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1129 (catch 'eof-input-catcher
1130 (input-at-least ,stream-var ,bytes)
1131 (locally ,@read-forms))))
1133 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1136 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1138 (defmacro def-input-routine/variable-width (name
1139 (type external-format size sap head)
1142 (defun ,name (stream eof-error eof-value)
1143 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1144 (let ((,sap (buffer-sap ibuf))
1145 (,head (buffer-head ibuf)))
1147 (setf *input-routines*
1148 (nconc *input-routines*
1149 (list (list ',type ',name 1 ',external-format))))))
1151 (defmacro def-input-routine (name
1152 (type size sap head)
1155 (defun ,name (stream eof-error eof-value)
1156 (input-wrapper (stream ,size eof-error eof-value)
1157 (let ((,sap (buffer-sap ibuf))
1158 (,head (buffer-head ibuf)))
1160 (setf *input-routines*
1161 (nconc *input-routines*
1162 (list (list ',type ',name ',size nil))))))
1164 ;;; STREAM-IN routine for reading a string char
1165 (def-input-routine input-character
1166 (character 1 sap head)
1167 (code-char (sap-ref-8 sap head)))
1169 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1170 (def-input-routine input-unsigned-8bit-byte
1171 ((unsigned-byte 8) 1 sap head)
1172 (sap-ref-8 sap head))
1174 ;;; STREAM-IN routine for reading a signed 8 bit number
1175 (def-input-routine input-signed-8bit-number
1176 ((signed-byte 8) 1 sap head)
1177 (signed-sap-ref-8 sap head))
1179 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1180 (def-input-routine input-unsigned-16bit-byte
1181 ((unsigned-byte 16) 2 sap head)
1182 (sap-ref-16 sap head))
1184 ;;; STREAM-IN routine for reading a signed 16 bit number
1185 (def-input-routine input-signed-16bit-byte
1186 ((signed-byte 16) 2 sap head)
1187 (signed-sap-ref-16 sap head))
1189 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1190 (def-input-routine input-unsigned-32bit-byte
1191 ((unsigned-byte 32) 4 sap head)
1192 (sap-ref-32 sap head))
1194 ;;; STREAM-IN routine for reading a signed 32 bit number
1195 (def-input-routine input-signed-32bit-byte
1196 ((signed-byte 32) 4 sap head)
1197 (signed-sap-ref-32 sap head))
1199 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1201 (def-input-routine input-unsigned-64bit-byte
1202 ((unsigned-byte 64) 8 sap head)
1203 (sap-ref-64 sap head))
1204 (def-input-routine input-signed-64bit-byte
1205 ((signed-byte 64) 8 sap head)
1206 (signed-sap-ref-64 sap head)))
1208 ;;; Find an input routine to use given the type. Return as multiple
1209 ;;; values the routine, the real type transfered, and the number of
1210 ;;; bytes per element (and for character types string input routine).
1211 (defun pick-input-routine (type &optional external-format)
1212 (when (subtypep type 'character)
1213 (let ((entry (get-external-format-or-lose external-format)))
1214 (return-from pick-input-routine
1215 (values (ef-read-char-fun entry)
1218 (ef-read-n-chars-fun entry)
1219 (ef-char-size entry)
1220 (canonize-external-format external-format entry)))))
1221 (dolist (entry *input-routines*)
1222 (when (and (subtypep type (first entry))
1223 (or (not (fourth entry))
1224 (eq external-format (fourth entry))))
1225 (return-from pick-input-routine
1226 (values (symbol-function (second entry))
1229 ;; FIXME: let's do it the hard way, then (but ignore things like
1230 ;; endianness, efficiency, and the necessary coupling between these
1231 ;; and the output routines). -- CSR, 2004-02-09
1232 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1233 if (subtypep type `(unsigned-byte ,i))
1234 do (return-from pick-input-routine
1236 (lambda (stream eof-error eof-value)
1237 (input-wrapper (stream (/ i 8) eof-error eof-value)
1238 (let ((sap (buffer-sap ibuf))
1239 (head (buffer-head ibuf)))
1240 (loop for j from 0 below (/ i 8)
1244 (sap-ref-8 sap (+ head j))))
1245 finally (return result)))))
1248 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1249 if (subtypep type `(signed-byte ,i))
1250 do (return-from pick-input-routine
1252 (lambda (stream eof-error eof-value)
1253 (input-wrapper (stream (/ i 8) eof-error eof-value)
1254 (let ((sap (buffer-sap ibuf))
1255 (head (buffer-head ibuf)))
1256 (loop for j from 0 below (/ i 8)
1260 (sap-ref-8 sap (+ head j))))
1261 finally (return (if (logbitp (1- i) result)
1262 (dpb result (byte i 0) -1)
1267 ;;; the N-BIN method for FD-STREAMs
1269 ;;; Note that this blocks in UNIX-READ. It is generally used where
1270 ;;; there is a definite amount of reading to be done, so blocking
1271 ;;; isn't too problematical.
1272 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1273 &aux (total-copied 0))
1274 (declare (type fd-stream stream))
1275 (declare (type index start requested total-copied))
1276 (aver (= (length (fd-stream-instead stream)) 0))
1279 (let* ((remaining-request (- requested total-copied))
1280 (ibuf (fd-stream-ibuf stream))
1281 (head (buffer-head ibuf))
1282 (tail (buffer-tail ibuf))
1283 (available (- tail head))
1284 (n-this-copy (min remaining-request available))
1285 (this-start (+ start total-copied))
1286 (this-end (+ this-start n-this-copy))
1287 (sap (buffer-sap ibuf)))
1288 (declare (type index remaining-request head tail available))
1289 (declare (type index n-this-copy))
1290 ;; Copy data from stream buffer into user's buffer.
1291 (%byte-blt sap head buffer this-start this-end)
1292 (incf (buffer-head ibuf) n-this-copy)
1293 (incf total-copied n-this-copy)
1294 ;; Maybe we need to refill the stream buffer.
1295 (cond (;; If there were enough data in the stream buffer, we're done.
1296 (eql total-copied requested)
1297 (return total-copied))
1298 (;; If EOF, we're done in another way.
1299 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1301 (error 'end-of-file :stream stream)
1302 (return total-copied)))
1303 ;; Otherwise we refilled the stream buffer, so fall
1304 ;; through into another pass of the loop.
1307 (defun fd-stream-resync (stream)
1308 (let ((entry (get-external-format (fd-stream-external-format stream))))
1310 (funcall (ef-resync-fun entry) stream))))
1312 (defun get-fd-stream-character-sizer (stream)
1313 (let ((entry (get-external-format (fd-stream-external-format stream))))
1315 (ef-bytes-for-char-fun entry))))
1317 (defun fd-stream-character-size (stream char)
1318 (let ((sizer (get-fd-stream-character-sizer stream)))
1319 (when sizer (funcall sizer char))))
1321 (defun fd-stream-string-size (stream string)
1322 (let ((sizer (get-fd-stream-character-sizer stream)))
1324 (loop for char across string summing (funcall sizer char)))))
1326 (defun find-external-format (external-format)
1327 (when external-format
1328 (get-external-format external-format)))
1330 (defun variable-width-external-format-p (ef-entry)
1331 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1333 (defun bytes-for-char-fun (ef-entry)
1334 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1336 (defmacro define-unibyte-mapping-external-format
1337 (canonical-name (&rest other-names) &body exceptions)
1338 (let ((->code-name (symbolicate canonical-name '->code-mapper))
1339 (code->-name (symbolicate 'code-> canonical-name '-mapper))
1340 (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1341 (string->-name (symbolicate 'string-> canonical-name))
1342 (define-string*-name (symbolicate 'define- canonical-name '->string*))
1343 (string*-name (symbolicate canonical-name '->string*))
1344 (define-string-name (symbolicate 'define- canonical-name '->string))
1345 (string-name (symbolicate canonical-name '->string))
1346 (->string-aref-name (symbolicate canonical-name '->string-aref)))
1348 (define-unibyte-mapper ,->code-name ,code->-name
1350 (declaim (inline ,get-bytes-name))
1351 (defun ,get-bytes-name (string pos)
1352 (declare (optimize speed (safety 0))
1353 (type simple-string string)
1354 (type array-range pos))
1355 (get-latin-bytes #',code->-name ,canonical-name string pos))
1356 (defun ,string->-name (string sstart send null-padding)
1357 (declare (optimize speed (safety 0))
1358 (type simple-string string)
1359 (type array-range sstart send))
1360 (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1361 (defmacro ,define-string*-name (accessor type)
1362 (declare (ignore type))
1363 (let ((name (make-od-name ',string*-name accessor)))
1365 (defun ,name (string sstart send array astart aend)
1366 (,(make-od-name 'latin->string* accessor)
1367 string sstart send array astart aend #',',->code-name)))))
1368 (instantiate-octets-definition ,define-string*-name)
1369 (defmacro ,define-string-name (accessor type)
1370 (declare (ignore type))
1371 (let ((name (make-od-name ',string-name accessor)))
1373 (defun ,name (array astart aend)
1374 (,(make-od-name 'latin->string accessor)
1375 array astart aend #',',->code-name)))))
1376 (instantiate-octets-definition ,define-string-name)
1377 (define-unibyte-external-format ,canonical-name ,other-names
1378 (let ((octet (,code->-name bits)))
1380 (setf (sap-ref-8 sap tail) octet)
1381 (external-format-encoding-error stream bits)))
1382 (let ((code (,->code-name byte)))
1385 (return-from decode-break-reason 1)))
1389 (defmacro define-unibyte-external-format
1390 (canonical-name (&rest other-names)
1391 out-form in-form octets-to-string-symbol string-to-octets-symbol)
1392 `(define-external-format/variable-width (,canonical-name ,@other-names)
1397 ,octets-to-string-symbol
1398 ,string-to-octets-symbol))
1400 (defmacro define-external-format/variable-width
1401 (external-format output-restart replacement-character
1402 out-size-expr out-expr in-size-expr in-expr
1403 octets-to-string-sym string-to-octets-sym)
1404 (let* ((name (first external-format))
1405 (out-function (symbolicate "OUTPUT-BYTES/" name))
1406 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1407 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1408 (in-char-function (symbolicate "INPUT-CHAR/" name))
1409 (resync-function (symbolicate "RESYNC/" name))
1410 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1411 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1412 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1413 (n-buffer (gensym "BUFFER")))
1415 (defun ,size-function (byte)
1416 (declare (ignorable byte))
1418 (defun ,out-function (stream string flush-p start end)
1419 (let ((start (or start 0))
1420 (end (or end (length string))))
1421 (declare (type index start end))
1422 (synchronize-stream-output stream)
1423 (unless (<= 0 start end (length string))
1424 (sequence-bounding-indices-bad-error string start end))
1427 (let ((obuf (fd-stream-obuf stream)))
1428 (string-dispatch (simple-base-string
1429 #!+sb-unicode (simple-array character (*))
1432 (let ((len (buffer-length obuf))
1433 (sap (buffer-sap obuf))
1435 (tail (buffer-tail obuf)))
1436 (declare (type index tail)
1437 ;; STRING bounds have already been checked.
1438 (optimize (safety 0)))
1439 (,@(if output-restart
1440 `(catch 'output-nothing)
1443 ((or (= start end) (< (- len tail) 4)))
1444 (let* ((byte (aref string start))
1445 (bits (char-code byte))
1446 (size ,out-size-expr))
1449 (setf (buffer-tail obuf) tail)
1452 ;; Exited via CATCH: skip the current character.
1456 (flush-output-buffer stream)))
1458 (flush-output-buffer stream))))
1459 (def-output-routines/variable-width (,format
1466 (if (eql byte #\Newline)
1467 (setf (fd-stream-char-pos stream) 0)
1468 (incf (fd-stream-char-pos stream)))
1469 (let ((bits (char-code byte))
1470 (sap (buffer-sap obuf))
1471 (tail (buffer-tail obuf)))
1473 (defun ,in-function (stream buffer start requested eof-error-p
1474 &aux (total-copied 0))
1475 (declare (type fd-stream stream)
1476 (type index start requested total-copied)
1478 (simple-array character (#.+ansi-stream-in-buffer-length+))
1480 (when (fd-stream-eof-forced-p stream)
1481 (setf (fd-stream-eof-forced-p stream) nil)
1482 (return-from ,in-function 0))
1483 (do ((instead (fd-stream-instead stream)))
1484 ((= (fill-pointer instead) 0)
1485 (setf (fd-stream-listen stream) nil))
1486 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1488 (when (= requested total-copied)
1489 (when (= (fill-pointer instead) 0)
1490 (setf (fd-stream-listen stream) nil))
1491 (return-from ,in-function total-copied)))
1494 (let* ((ibuf (fd-stream-ibuf stream))
1495 (head (buffer-head ibuf))
1496 (tail (buffer-tail ibuf))
1497 (sap (buffer-sap ibuf))
1498 (decode-break-reason nil))
1499 (declare (type index head tail))
1500 ;; Copy data from stream buffer into user's buffer.
1501 (do ((size nil nil))
1502 ((or (= tail head) (= requested total-copied)))
1503 (setf decode-break-reason
1504 (block decode-break-reason
1505 ,@(when (consp in-size-expr)
1506 `((when (> ,(car in-size-expr) (- tail head))
1508 (let ((byte (sap-ref-8 sap head)))
1509 (declare (ignorable byte))
1510 (setq size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr))
1511 (when (> size (- tail head))
1513 (setf (aref buffer (+ start total-copied)) ,in-expr)
1517 (setf (buffer-head ibuf) head)
1518 (when decode-break-reason
1519 ;; If we've already read some characters on when the invalid
1520 ;; code sequence is detected, we return immediately. The
1521 ;; handling of the error is deferred until the next call
1522 ;; (where this check will be false). This allows establishing
1523 ;; high-level handlers for decode errors (for example
1524 ;; automatically resyncing in Lisp comments).
1525 (when (plusp total-copied)
1526 (return-from ,in-function total-copied))
1527 (when (stream-decoding-error-and-handle
1528 stream decode-break-reason)
1530 (error 'end-of-file :stream stream)
1531 (return-from ,in-function total-copied)))
1532 ;; we might have been given stuff to use instead, so
1533 ;; we have to return (and trust our caller to know
1534 ;; what to do about TOTAL-COPIED being 0).
1535 (return-from ,in-function total-copied)))
1536 (setf (buffer-head ibuf) head)
1537 ;; Maybe we need to refill the stream buffer.
1538 (cond ( ;; If was data in the stream buffer, we're done.
1539 (plusp total-copied)
1540 (return total-copied))
1541 ( ;; If EOF, we're done in another way.
1542 (or (eq decode-break-reason 'eof)
1543 (null (catch 'eof-input-catcher
1544 (refill-input-buffer stream))))
1546 (error 'end-of-file :stream stream)
1547 (return total-copied)))
1548 ;; Otherwise we refilled the stream buffer, so fall
1549 ;; through into another pass of the loop.
1551 (def-input-routine/variable-width ,in-char-function (character
1555 (let ((byte (sap-ref-8 sap head)))
1556 (declare (ignorable byte))
1558 (defun ,resync-function (stream)
1559 (let ((ibuf (fd-stream-ibuf stream))
1561 (catch 'eof-input-catcher
1563 (incf (buffer-head ibuf))
1564 (input-at-least stream ,(if (consp in-size-expr) (car in-size-expr) `(setq size ,in-size-expr)))
1565 (unless (block decode-break-reason
1566 (let* ((sap (buffer-sap ibuf))
1567 (head (buffer-head ibuf))
1568 (byte (sap-ref-8 sap head)))
1569 (declare (ignorable byte))
1570 ,@(when (consp in-size-expr)
1571 `((setq size ,(cadr in-size-expr))
1572 (input-at-least stream size)))
1573 (setf head (buffer-head ibuf))
1577 (defun ,read-c-string-function (sap element-type)
1578 (declare (type system-area-pointer sap))
1580 (declare (optimize (speed 3) (safety 0)))
1581 (let* ((stream ,name)
1582 (size 0) (head 0) (byte 0) (char nil)
1583 (decode-break-reason nil)
1584 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1585 (setf decode-break-reason
1586 (block decode-break-reason
1587 (setf byte (sap-ref-8 sap head)
1588 size ,(if (consp in-size-expr)
1594 (when decode-break-reason
1595 (c-string-decoding-error
1596 ,name sap head decode-break-reason))
1597 (when (zerop (char-code char))
1599 (string (make-string length :element-type element-type)))
1600 (declare (ignorable stream)
1601 (type index head length) ;; size
1602 (type (unsigned-byte 8) byte)
1603 (type (or null character) char)
1604 (type string string))
1606 (dotimes (index length string)
1607 (setf decode-break-reason
1608 (block decode-break-reason
1609 (setf byte (sap-ref-8 sap head)
1610 size ,(if (consp in-size-expr)
1616 (when decode-break-reason
1617 (c-string-decoding-error
1618 ,name sap head decode-break-reason))
1619 (setf (aref string index) char)))))
1621 (defun ,output-c-string-function (string)
1622 (declare (type simple-string string))
1624 (declare (optimize (speed 3) (safety 0)))
1625 (let* ((length (length string))
1626 (char-length (make-array (1+ length) :element-type 'index))
1628 (+ (loop for i of-type index below length
1629 for byte of-type character = (aref string i)
1630 for bits = (char-code byte)
1631 sum (setf (aref char-length i)
1632 (the index ,out-size-expr)))
1633 (let* ((byte (code-char 0))
1634 (bits (char-code byte)))
1635 (declare (ignorable byte bits))
1636 (setf (aref char-length length)
1637 (the index ,out-size-expr)))))
1639 (,n-buffer (make-array buffer-length
1640 :element-type '(unsigned-byte 8)))
1642 (declare (type index length buffer-length tail)
1645 (with-pinned-objects (,n-buffer)
1646 (let ((sap (vector-sap ,n-buffer)))
1647 (declare (system-area-pointer sap))
1648 (loop for i of-type index below length
1649 for byte of-type character = (aref string i)
1650 for bits = (char-code byte)
1651 for size of-type index = (aref char-length i)
1656 (byte (code-char bits))
1657 (size (aref char-length length)))
1658 (declare (ignorable bits byte size))
1662 (let ((entry (%make-external-format
1663 :names ',external-format
1664 :default-replacement-character ,replacement-character
1665 :read-n-chars-fun #',in-function
1666 :read-char-fun #',in-char-function
1667 :write-n-bytes-fun #',out-function
1668 ,@(mapcan #'(lambda (buffering)
1669 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1670 `#',(intern (format nil format (string buffering)))))
1671 '(:none :line :full))
1672 :resync-fun #',resync-function
1673 :bytes-for-char-fun #',size-function
1674 :read-c-string-fun #',read-c-string-function
1675 :write-c-string-fun #',output-c-string-function
1676 :octets-to-string-fun (lambda (&rest rest)
1677 (declare (dynamic-extent rest))
1678 (apply ',octets-to-string-sym rest))
1679 :string-to-octets-fun (lambda (&rest rest)
1680 (declare (dynamic-extent rest))
1681 (apply ',string-to-octets-sym rest)))))
1682 (dolist (ef ',external-format)
1683 (setf (gethash ef *external-formats*) entry))))))
1685 ;;;; utility functions (misc routines, etc)
1687 ;;; Fill in the various routine slots for the given type. INPUT-P and
1688 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1689 ;;; set prior to calling this routine.
1690 (defun set-fd-stream-routines (fd-stream element-type external-format
1691 input-p output-p buffer-p)
1692 (let* ((target-type (case element-type
1693 (unsigned-byte '(unsigned-byte 8))
1694 (signed-byte '(signed-byte 8))
1695 (:default 'character)
1697 (character-stream-p (subtypep target-type 'character))
1698 (bivalent-stream-p (eq element-type :default))
1699 normalized-external-format
1701 (bin-routine #'ill-bin)
1704 (cin-routine #'ill-in)
1707 (input-type nil) ;calculated from bin-type/cin-type
1708 (input-size nil) ;calculated from bin-size/cin-size
1709 (read-n-characters #'ill-in)
1710 (bout-routine #'ill-bout)
1713 (cout-routine #'ill-out)
1718 (output-bytes #'ill-bout))
1720 ;; Ensure that we have buffers in the desired direction(s) only,
1721 ;; getting new ones and dropping/resetting old ones as necessary.
1722 (let ((obuf (fd-stream-obuf fd-stream)))
1726 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1728 (setf (fd-stream-obuf fd-stream) nil)
1729 (release-buffer obuf))))
1731 (let ((ibuf (fd-stream-ibuf fd-stream)))
1735 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1737 (setf (fd-stream-ibuf fd-stream) nil)
1738 (release-buffer ibuf))))
1740 ;; FIXME: Why only for output? Why unconditionally?
1742 (setf (fd-stream-char-pos fd-stream) 0))
1744 (when (and character-stream-p (eq external-format :default))
1745 (/show0 "/getting default external format")
1746 (setf external-format (default-external-format)))
1749 (when (or (not character-stream-p) bivalent-stream-p)
1750 (setf (values bin-routine bin-type bin-size read-n-characters
1751 char-size normalized-external-format)
1752 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1756 (error "could not find any input routine for ~S" target-type)))
1757 (when character-stream-p
1758 (setf (values cin-routine cin-type cin-size read-n-characters
1759 char-size normalized-external-format)
1760 (pick-input-routine target-type external-format))
1762 (error "could not find any input routine for ~S" target-type)))
1763 (setf (fd-stream-in fd-stream) cin-routine
1764 (fd-stream-bin fd-stream) bin-routine)
1765 ;; character type gets preferential treatment
1766 (setf input-size (or cin-size bin-size))
1767 (setf input-type (or cin-type bin-type))
1768 (when normalized-external-format
1769 (setf (fd-stream-external-format fd-stream) normalized-external-format
1770 (fd-stream-char-size fd-stream) char-size))
1771 (when (= (or cin-size 1) (or bin-size 1) 1)
1772 (setf (fd-stream-n-bin fd-stream) ;XXX
1773 (if (and character-stream-p (not bivalent-stream-p))
1775 #'fd-stream-read-n-bytes))
1776 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1777 ;; for character and (unsigned-byte 8) streams. In these
1778 ;; cases, fast-read-* will read from the
1779 ;; ansi-stream-(c)in-buffer, saving function calls.
1780 ;; Otherwise, the various data-reading functions in the stream
1781 ;; structure will be called.
1783 (not bivalent-stream-p)
1784 ;; temporary disable on :io streams
1786 (cond (character-stream-p
1787 (setf (ansi-stream-cin-buffer fd-stream)
1788 (make-array +ansi-stream-in-buffer-length+
1789 :element-type 'character)))
1790 ((equal target-type '(unsigned-byte 8))
1791 (setf (ansi-stream-in-buffer fd-stream)
1792 (make-array +ansi-stream-in-buffer-length+
1793 :element-type '(unsigned-byte 8))))))))
1796 (when (or (not character-stream-p) bivalent-stream-p)
1797 (setf (values bout-routine bout-type bout-size output-bytes
1798 char-size normalized-external-format)
1799 (let ((buffering (fd-stream-buffering fd-stream)))
1800 (if bivalent-stream-p
1801 (pick-output-routine '(unsigned-byte 8)
1802 (if (eq :line buffering)
1806 (pick-output-routine target-type buffering external-format))))
1807 (unless bout-routine
1808 (error "could not find any output routine for ~S buffered ~S"
1809 (fd-stream-buffering fd-stream)
1811 (when character-stream-p
1812 (setf (values cout-routine cout-type cout-size output-bytes
1813 char-size normalized-external-format)
1814 (pick-output-routine target-type
1815 (fd-stream-buffering fd-stream)
1817 (unless cout-routine
1818 (error "could not find any output routine for ~S buffered ~S"
1819 (fd-stream-buffering fd-stream)
1821 (when normalized-external-format
1822 (setf (fd-stream-external-format fd-stream) normalized-external-format
1823 (fd-stream-char-size fd-stream) char-size))
1824 (when character-stream-p
1825 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1826 (setf (fd-stream-out fd-stream) cout-routine
1827 (fd-stream-bout fd-stream) bout-routine
1828 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1829 #'fd-sout #'ill-out))
1830 (setf output-size (or cout-size bout-size))
1831 (setf output-type (or cout-type bout-type)))
1833 (when (and input-size output-size
1834 (not (eq input-size output-size)))
1835 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1836 input-type input-size
1837 output-type output-size))
1838 (setf (fd-stream-element-size fd-stream)
1839 (or input-size output-size))
1841 (setf (fd-stream-element-type fd-stream)
1842 (cond ((equal input-type output-type)
1848 ((subtypep input-type output-type)
1850 ((subtypep output-type input-type)
1853 (error "Input type (~S) and output type (~S) are unrelated?"
1857 ;;; Handles the resource-release aspects of stream closing, and marks
1859 (defun release-fd-stream-resources (fd-stream)
1862 ;; Drop handlers first.
1863 (when (fd-stream-handler fd-stream)
1864 (remove-fd-handler (fd-stream-handler fd-stream))
1865 (setf (fd-stream-handler fd-stream) nil))
1866 ;; Disable interrupts so that a asynch unwind will not leave
1867 ;; us with a dangling finalizer (that would close the same
1868 ;; --possibly reassigned-- FD again), or a stream with a closed
1869 ;; FD that appears open.
1870 (sb!unix:unix-close (fd-stream-fd fd-stream))
1871 (set-closed-flame fd-stream)
1872 (when (fboundp 'cancel-finalization)
1873 (cancel-finalization fd-stream)))
1874 ;; On error unwind from WITHOUT-INTERRUPTS.
1875 (serious-condition (e)
1877 ;; Release all buffers. If this is undone, or interrupted,
1878 ;; we're still safe: buffers have finalizers of their own.
1879 (release-fd-stream-buffers fd-stream))
1881 ;;; Flushes the current input buffer and any supplied replacements,
1882 ;;; and returns the input buffer, and the amount of of flushed input
1884 (defun flush-input-buffer (stream)
1885 (let ((unread (length (fd-stream-instead stream))))
1886 (setf (fill-pointer (fd-stream-instead stream)) 0)
1887 (let ((ibuf (fd-stream-ibuf stream)))
1889 (let ((head (buffer-head ibuf))
1890 (tail (buffer-tail ibuf)))
1891 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1892 (values nil unread)))))
1894 (defun fd-stream-clear-input (stream)
1895 (flush-input-buffer stream)
1898 (sb!win32:fd-clear-input (fd-stream-fd stream))
1899 (setf (fd-stream-listen stream) nil))
1901 (catch 'eof-input-catcher
1902 (loop until (sysread-may-block-p stream)
1904 (refill-input-buffer stream)
1905 (reset-buffer (fd-stream-ibuf stream)))
1908 ;;; Handle miscellaneous operations on FD-STREAM.
1909 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1910 (declare (ignore arg2))
1913 (labels ((do-listen ()
1914 (let ((ibuf (fd-stream-ibuf fd-stream)))
1915 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1916 (fd-stream-listen fd-stream)
1918 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1920 ;; If the read can block, LISTEN will certainly return NIL.
1921 (if (sysread-may-block-p fd-stream)
1923 ;; Otherwise select(2) and CL:LISTEN have slightly
1924 ;; different semantics. The former returns that an FD
1925 ;; is readable when a read operation wouldn't block.
1926 ;; That includes EOF. However, LISTEN must return NIL
1928 (progn (catch 'eof-input-catcher
1929 ;; r-b/f too calls select, but it shouldn't
1930 ;; block as long as read can return once w/o
1932 (refill-input-buffer fd-stream))
1933 ;; At this point either IBUF-HEAD != IBUF-TAIL
1934 ;; and FD-STREAM-LISTEN is NIL, in which case
1935 ;; we should return T, or IBUF-HEAD ==
1936 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1937 ;; which case we should return :EOF for this
1938 ;; call and all future LISTEN call on this stream.
1939 ;; Call ourselves again to determine which case
1944 (decf (buffer-head (fd-stream-ibuf fd-stream))
1945 (fd-stream-character-size fd-stream arg1)))
1947 ;; Drop input buffers
1948 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1949 (ansi-stream-cin-buffer fd-stream) nil
1950 (ansi-stream-in-buffer fd-stream) nil)
1952 ;; We got us an abort on our hands.
1953 (let ((outputp (fd-stream-obuf fd-stream))
1954 (file (fd-stream-file fd-stream))
1955 (orig (fd-stream-original fd-stream)))
1956 ;; This takes care of the important stuff -- everything
1957 ;; rest is cleaning up the file-system, which we cannot
1958 ;; do on some platforms as long as the file is open.
1959 (release-fd-stream-resources fd-stream)
1960 ;; We can't do anything unless we know what file were
1961 ;; dealing with, and we don't want to do anything
1962 ;; strange unless we were writing to the file.
1963 (when (and outputp file)
1965 ;; If the original is EQ to file we are appending to
1966 ;; and can just close the file without renaming.
1967 (unless (eq orig file)
1968 ;; We have a handle on the original, just revert.
1969 (multiple-value-bind (okay err)
1970 (sb!unix:unix-rename orig file)
1971 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1972 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1975 (error 'simple-stream-error
1977 "~@<Couldn't restore ~S to its original contents ~
1978 from ~S while closing ~S: ~2I~_~A~:>"
1980 (list file orig fd-stream (strerror err))
1981 :stream fd-stream))))
1982 ;; We can't restore the original, and aren't
1983 ;; appending, so nuke that puppy.
1985 ;; FIXME: This is currently the fate of superseded
1986 ;; files, and according to the CLOSE spec this is
1987 ;; wrong. However, there seems to be no clean way to
1988 ;; do that that doesn't involve either copying the
1989 ;; data (bad if the :abort resulted from a full
1990 ;; disk), or renaming the old file temporarily
1991 ;; (probably bad because stream opening becomes more
1993 (multiple-value-bind (okay err)
1994 (sb!unix:unix-unlink file)
1996 (error 'simple-file-error
1999 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2001 (list file fd-stream (strerror err)))))))))
2003 (finish-fd-stream-output fd-stream)
2004 (let ((orig (fd-stream-original fd-stream)))
2005 (when (and orig (fd-stream-delete-original fd-stream))
2006 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2008 (error 'simple-file-error
2011 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2013 (list orig fd-stream (strerror err)))))))
2014 ;; In case of no-abort close, don't *really* close the
2015 ;; stream until the last moment -- the cleaning up of the
2016 ;; original can be done first.
2017 (release-fd-stream-resources fd-stream))))
2019 (fd-stream-clear-input fd-stream))
2021 (flush-output-buffer fd-stream))
2023 (finish-fd-stream-output fd-stream))
2025 (fd-stream-element-type fd-stream))
2027 (fd-stream-external-format fd-stream))
2029 (plusp (the (integer 0)
2030 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2034 (fd-stream-char-pos fd-stream))
2036 (unless (fd-stream-file fd-stream)
2037 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2038 ;; "should signal an error of type TYPE-ERROR if stream is not
2039 ;; a stream associated with a file". Too bad there's no very
2040 ;; appropriate value for the EXPECTED-TYPE slot..
2041 (error 'simple-type-error
2043 :expected-type 'fd-stream
2044 :format-control "~S is not a stream associated with a file."
2045 :format-arguments (list fd-stream)))
2047 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2048 atime mtime ctime blksize blocks)
2049 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2050 (declare (ignore ino nlink uid gid rdev
2051 atime mtime ctime blksize blocks))
2053 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2056 (truncate size (fd-stream-element-size fd-stream))))
2058 (let* ((handle (fd-stream-fd fd-stream))
2059 (element-size (fd-stream-element-size fd-stream)))
2060 (multiple-value-bind (got native-size)
2061 (sb!win32:get-file-size-ex handle 0)
2063 ;; Might be a block device, in which case we fall back to
2064 ;; a non-atomic workaround:
2065 (let* ((here (sb!unix:unix-lseek handle 0 sb!unix:l_incr))
2066 (there (sb!unix:unix-lseek handle 0 sb!unix:l_xtnd)))
2067 (when (and here there)
2068 (sb!unix:unix-lseek handle here sb!unix:l_set)
2069 (truncate there element-size)))
2070 (truncate native-size element-size)))))
2071 (:file-string-length
2073 (character (fd-stream-character-size fd-stream arg1))
2074 (string (fd-stream-string-size fd-stream arg1))))
2077 (fd-stream-set-file-position fd-stream arg1)
2078 (fd-stream-get-file-position fd-stream)))))
2080 ;; FIXME: Think about this.
2082 ;; (defun finish-fd-stream-output (fd-stream)
2083 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2084 ;; (loop while (fd-stream-output-queue fd-stream)
2085 ;; ;; FIXME: SIGINT while waiting for a timeout will
2086 ;; ;; cause a timeout here.
2087 ;; do (when (and (not (serve-event timeout)) timeout)
2088 ;; (signal-timeout 'io-timeout
2089 ;; :stream fd-stream
2090 ;; :direction :write
2091 ;; :seconds timeout)))))
2093 (defun finish-fd-stream-output (stream)
2094 (flush-output-buffer stream)
2096 ((null (fd-stream-output-queue stream)))
2097 (aver (fd-stream-serve-events stream))
2098 (serve-all-events)))
2100 (defun fd-stream-get-file-position (stream)
2101 (declare (fd-stream stream))
2103 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2104 (declare (type (or (alien sb!unix:unix-offset) null) posn))
2105 ;; We used to return NIL for errno==ESPIPE, and signal an error
2106 ;; in other failure cases. However, CLHS says to return NIL if
2107 ;; the position cannot be determined -- so that's what we do.
2108 (when (integerp posn)
2109 ;; Adjust for buffered output: If there is any output
2110 ;; buffered, the *real* file position will be larger
2111 ;; than reported by lseek() because lseek() obviously
2112 ;; cannot take into account output we have not sent
2114 (dolist (buffer (fd-stream-output-queue stream))
2115 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2116 (let ((obuf (fd-stream-obuf stream)))
2118 (incf posn (buffer-tail obuf))))
2119 ;; Adjust for unread input: If there is any input
2120 ;; read from UNIX but not supplied to the user of the
2121 ;; stream, the *real* file position will smaller than
2122 ;; reported, because we want to look like the unread
2123 ;; stuff is still available.
2124 (let ((ibuf (fd-stream-ibuf stream)))
2126 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2127 ;; Divide bytes by element size.
2128 (truncate posn (fd-stream-element-size stream))))))
2130 (defun fd-stream-set-file-position (stream position-spec)
2131 (declare (fd-stream stream))
2132 (check-type position-spec
2133 (or (alien sb!unix:unix-offset) (member nil :start :end))
2134 "valid file position designator")
2137 ;; Make sure we don't have any output pending, because if we
2138 ;; move the file pointer before writing this stuff, it will be
2139 ;; written in the wrong location.
2140 (finish-fd-stream-output stream)
2141 ;; Disable interrupts so that interrupt handlers doing output
2144 (unless (fd-stream-output-finished-p stream)
2145 ;; We got interrupted and more output came our way during
2146 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2147 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2148 ;; so we prefer to do things like this...
2150 ;; Clear out any pending input to force the next read to go to
2152 (flush-input-buffer stream)
2153 ;; Trash cached value for listen, so that we check next time.
2154 (setf (fd-stream-listen stream) nil)
2156 (multiple-value-bind (offset origin)
2159 (values 0 sb!unix:l_set))
2161 (values 0 sb!unix:l_xtnd))
2163 (values (* position-spec (fd-stream-element-size stream))
2165 (declare (type (alien sb!unix:unix-offset) offset))
2166 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2168 ;; CLHS says to return true if the file-position was set
2169 ;; succesfully, and NIL otherwise. We are to signal an error
2170 ;; only if the given position was out of bounds, and that is
2171 ;; dealt with above. In times past we used to return NIL for
2172 ;; errno==ESPIPE, and signal an error in other cases.
2174 ;; FIXME: We are still liable to signal an error if flushing
2176 (return-from fd-stream-set-file-position
2177 (typep posn '(alien sb!unix:unix-offset))))))))
2180 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2182 ;;; Create a stream for the given Unix file descriptor.
2184 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2185 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2186 ;;; default to allowing input.
2188 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2190 ;;; BUFFERING indicates the kind of buffering to use.
2192 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2193 ;;; NIL (the default), then wait forever. When we time out, we signal
2196 ;;; FILE is the name of the file (will be returned by PATHNAME).
2198 ;;; NAME is used to identify the stream when printed.
2200 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2201 ;;; handle blocking IO on the stream.
2202 (defun make-fd-stream (fd
2205 (output nil output-p)
2206 (element-type 'base-char)
2208 (external-format :default)
2218 (format nil "file ~A" file)
2219 (format nil "descriptor ~W" fd)))
2221 (declare (type index fd) (type (or real null) timeout)
2222 (type (member :none :line :full) buffering))
2223 (cond ((not (or input-p output-p))
2225 ((not (or input output))
2226 (error "File descriptor must be opened either for input or output.")))
2227 (let ((stream (%make-fd-stream :fd fd
2229 #!-win32 (sb!unix:fd-type fd)
2231 #!+win32 (if serve-events
2237 :delete-original delete-original
2239 :buffering buffering
2240 :dual-channel-p dual-channel-p
2241 :bivalent-p (eq element-type :default)
2242 :serve-events serve-events
2245 (coerce timeout 'single-float)
2247 (set-fd-stream-routines stream element-type external-format
2248 input output input-buffer-p)
2249 (when (and auto-close (fboundp 'finalize))
2252 (sb!unix:unix-close fd)
2254 (format *terminal-io* "** closed file descriptor ~W **~%"
2259 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2260 ;;; :RENAME-AND-DELETE and :RENAME options.
2261 (defun pick-backup-name (name)
2262 (declare (type simple-string name))
2263 (concatenate 'simple-string name ".bak"))
2265 ;;; Ensure that the given arg is one of the given list of valid
2266 ;;; things. Allow the user to fix any problems.
2267 (defun ensure-one-of (item list what)
2268 (unless (member item list)
2269 (error 'simple-type-error
2271 :expected-type `(member ,@list)
2272 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2273 :format-arguments (list item what list))))
2275 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2276 ;;; access, since we don't want to trash unwritable files even if we
2277 ;;; technically can. We return true if we succeed in renaming.
2278 (defun rename-the-old-one (namestring original)
2279 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2280 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2281 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2284 (error 'simple-file-error
2285 :pathname namestring
2287 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2288 :format-arguments (list namestring original (strerror err))))))
2290 (defun open (filename
2293 (element-type 'base-char)
2294 (if-exists nil if-exists-given)
2295 (if-does-not-exist nil if-does-not-exist-given)
2296 (external-format :default)
2297 &aux ; Squelch assignment warning.
2298 (direction direction)
2299 (if-does-not-exist if-does-not-exist)
2300 (if-exists if-exists))
2302 "Return a stream which reads from or writes to FILENAME.
2304 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2305 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2306 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2307 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2308 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2309 See the manual for details."
2311 ;; Calculate useful stuff.
2312 (multiple-value-bind (input output mask)
2314 (:input (values t nil sb!unix:o_rdonly))
2315 (:output (values nil t sb!unix:o_wronly))
2316 (:io (values t t sb!unix:o_rdwr))
2317 (:probe (values t nil sb!unix:o_rdonly)))
2318 (declare (type index mask))
2319 (let* (;; PATHNAME is the pathname we associate with the stream.
2320 (pathname (merge-pathnames filename))
2321 (physical (physicalize-pathname pathname))
2322 (truename (probe-file physical))
2323 ;; NAMESTRING is the native namestring we open the file with.
2324 (namestring (cond (truename
2325 (native-namestring truename :as-file t))
2327 (and input (eq if-does-not-exist :create))
2328 (and (eq direction :io) (not if-does-not-exist-given)))
2329 (native-namestring physical :as-file t)))))
2330 ;; Process if-exists argument if we are doing any output.
2332 (unless if-exists-given
2334 (if (eq (pathname-version pathname) :newest)
2337 (ensure-one-of if-exists
2338 '(:error :new-version :rename
2339 :rename-and-delete :overwrite
2340 :append :supersede nil)
2343 ((:new-version :error nil)
2344 (setf mask (logior mask sb!unix:o_excl)))
2345 ((:rename :rename-and-delete)
2346 (setf mask (logior mask sb!unix:o_creat)))
2348 (setf mask (logior mask sb!unix:o_trunc)))
2350 (setf mask (logior mask sb!unix:o_append)))))
2352 (setf if-exists :ignore-this-arg)))
2354 (unless if-does-not-exist-given
2355 (setf if-does-not-exist
2356 (cond ((eq direction :input) :error)
2358 (member if-exists '(:overwrite :append)))
2360 ((eq direction :probe)
2364 (ensure-one-of if-does-not-exist
2365 '(:error :create nil)
2367 (if (eq if-does-not-exist :create)
2368 (setf mask (logior mask sb!unix:o_creat)))
2370 (let ((original (case if-exists
2371 ((:rename :rename-and-delete)
2372 (pick-backup-name namestring))
2373 ((:append :overwrite)
2374 ;; KLUDGE: Provent CLOSE from deleting
2375 ;; appending streams when called with :ABORT T
2377 (delete-original (eq if-exists :rename-and-delete))
2379 (when (and original (not (eq original namestring)))
2380 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2381 ;; whether the file already exists, make sure the original
2382 ;; file is not a directory, and keep the mode.
2385 (multiple-value-bind (okay err/dev inode orig-mode)
2386 (sb!unix:unix-stat namestring)
2387 (declare (ignore inode)
2388 (type (or index null) orig-mode))
2391 (when (and output (= (logand orig-mode #o170000)
2393 (error 'simple-file-error
2396 "can't open ~S for output: is a directory"
2397 :format-arguments (list namestring)))
2398 (setf mode (logand orig-mode #o777))
2400 ((eql err/dev sb!unix:enoent)
2403 (simple-file-perror "can't find ~S"
2407 (rename-the-old-one namestring original))
2409 (setf delete-original nil)
2410 ;; In order to use :SUPERSEDE instead, we have to make
2411 ;; sure SB!UNIX:O_CREAT corresponds to
2412 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2413 ;; because of IF-EXISTS being :RENAME.
2414 (unless (eq if-does-not-exist :create)
2416 (logior (logandc2 mask sb!unix:o_creat)
2418 (setf if-exists :supersede))))
2420 ;; Now we can try the actual Unix open(2).
2421 (multiple-value-bind (fd errno)
2423 (sb!unix:unix-open namestring mask mode)
2424 (values nil sb!unix:enoent))
2425 (labels ((open-error (format-control &rest format-arguments)
2426 (error 'simple-file-error
2428 :format-control format-control
2429 :format-arguments format-arguments))
2430 (vanilla-open-error ()
2431 (simple-file-perror "error opening ~S" pathname errno)))
2434 ((:input :output :io)
2435 ;; For O_APPEND opened files, lseek returns 0 until first write.
2436 ;; So we jump ahead here.
2437 (when (eq if-exists :append)
2438 (sb!unix:unix-lseek fd 0 sb!unix:l_xtnd))
2442 :element-type element-type
2443 :external-format external-format
2446 :delete-original delete-original
2454 (%make-fd-stream :name namestring
2457 :element-type element-type)))
2460 ((eql errno sb!unix:enoent)
2461 (case if-does-not-exist
2462 (:error (vanilla-open-error))
2464 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2467 ((and (eql errno sb!unix:eexist) (null if-exists))
2470 (vanilla-open-error)))))))))
2474 ;;; the stream connected to the controlling terminal, or NIL if there is none
2477 ;;; the stream connected to the standard input (file descriptor 0)
2480 ;;; the stream connected to the standard output (file descriptor 1)
2483 ;;; the stream connected to the standard error output (file descriptor 2)
2486 ;;; This is called when the cold load is first started up, and may also
2487 ;;; be called in an attempt to recover from nested errors.
2488 (defun stream-cold-init-or-reset ()
2490 (setf *terminal-io* (make-synonym-stream '*tty*))
2491 (setf *standard-output* (make-synonym-stream '*stdout*))
2492 (setf *standard-input* (make-synonym-stream '*stdin*))
2493 (setf *error-output* (make-synonym-stream '*stderr*))
2494 (setf *query-io* (make-synonym-stream '*terminal-io*))
2495 (setf *debug-io* *query-io*)
2496 (setf *trace-output* *standard-output*)
2499 (defun stream-deinit ()
2500 ;; Unbind to make sure we're not accidently dealing with it
2501 ;; before we're ready (or after we think it's been deinitialized).
2502 (with-available-buffers-lock ()
2503 (without-package-locks
2504 (makunbound '*available-buffers*))))
2506 (defun stdstream-external-format (fd outputp)
2507 #!-win32 (declare (ignore fd outputp))
2508 (let* ((keyword #!+win32 (if (and (/= fd -1)
2513 (sb!win32::console-output-codepage)
2514 (sb!win32::console-input-codepage)))
2515 #!-win32 (default-external-format))
2516 (ef (get-external-format keyword))
2517 (replacement (ef-default-replacement-character ef)))
2518 `(,keyword :replacement ,replacement)))
2520 ;;; This is called whenever a saved core is restarted.
2521 (defun stream-reinit (&optional init-buffers-p)
2522 (when init-buffers-p
2523 (with-available-buffers-lock ()
2524 (aver (not (boundp '*available-buffers*)))
2525 (setf *available-buffers* nil)))
2526 (with-output-to-string (*error-output*)
2527 (multiple-value-bind (in out err)
2528 #!-win32 (values 0 1 2)
2529 #!+win32 (sb!win32::get-std-handles)
2530 (flet ((stdio-stream (handle name inputp outputp)
2537 :element-type :default
2538 :serve-events inputp
2539 :external-format (stdstream-external-format handle outputp))))
2540 (setf *stdin* (stdio-stream in "standard input" t nil))
2541 (setf *stdout* (stdio-stream out "standard output" nil t))
2542 (setf *stderr* (stdio-stream err "standard error" nil t))))
2544 (setf *tty* (make-two-way-stream *stdin* *stdout*))
2546 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2547 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2550 (make-fd-stream tty :name "the terminal"
2551 :input t :output t :buffering :line
2552 :external-format (stdstream-external-format
2554 :serve-events (or #!-win32 t)
2556 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2557 (princ (get-output-stream-string *error-output*) *stderr*))
2562 ;;; the Unix way to beep
2563 (defun beep (stream)
2564 (write-char (code-char bell-char-code) stream)
2565 (finish-output stream))
2567 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2568 ;;; by the filesys stuff to get and set the file name.
2570 ;;; FIXME: misleading name, screwy interface
2571 (defun file-name (stream &optional new-name)
2572 (when (typep stream 'fd-stream)
2574 (setf (fd-stream-pathname stream) new-name)
2575 (setf (fd-stream-file stream)
2576 (native-namestring (physicalize-pathname new-name)
2580 (fd-stream-pathname stream)))))