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-spinlock* (sb!thread::make-spinlock
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-SPINLOCK because
63 ;; 1. streams are low-level enough to be async signal safe, and in
64 ;; particular a C-c that brings up the debugger while holding the
65 ;; mutex would lose badly
67 ;; 2. this can potentially be a fairly busy (but also probably
68 ;; uncontended) lock, so we don't want to pay the syscall per
69 ;; release -- hence a spinlock.
71 ;; ...again, once we have smarted locks the spinlock here can become
73 `(sb!thread::with-system-spinlock (*available-buffers-spinlock*)
76 (defconstant +bytes-per-buffer+ (* 4 1024)
78 "Default number of bytes per buffer.")
80 (defun alloc-buffer (&optional (size +bytes-per-buffer+))
81 ;; Don't want to allocate & unwind before the finalizer is in place.
83 (let* ((sap (allocate-system-memory size))
84 (buffer (%make-buffer sap size)))
85 (when (zerop (sap-int sap))
86 (error "Could not allocate ~D bytes for buffer." size))
87 (finalize buffer (lambda ()
88 (deallocate-system-memory sap size))
93 ;; Don't go for the lock if there is nothing to be had -- sure,
94 ;; another thread might just release one before we get it, but that
95 ;; is not worth the cost of locking. Also release the lock before
96 ;; allocation, since it's going to take a while.
97 (if *available-buffers*
98 (or (with-available-buffers-lock ()
99 (pop *available-buffers*))
103 (declaim (inline reset-buffer))
104 (defun reset-buffer (buffer)
105 (setf (buffer-head buffer) 0
106 (buffer-tail buffer) 0)
109 (defun release-buffer (buffer)
110 (reset-buffer buffer)
111 (with-available-buffers-lock ()
112 (push buffer *available-buffers*)))
114 ;;; This is a separate buffer management function, as it wants to be
115 ;;; clever about locking -- grabbing the lock just once.
116 (defun release-fd-stream-buffers (fd-stream)
117 (let ((ibuf (fd-stream-ibuf fd-stream))
118 (obuf (fd-stream-obuf fd-stream))
119 (queue (loop for item in (fd-stream-output-queue fd-stream)
121 collect (reset-buffer item))))
123 (push (reset-buffer ibuf) queue))
125 (push (reset-buffer obuf) queue))
126 ;; ...so, anything found?
128 ;; detach from stream
129 (setf (fd-stream-ibuf fd-stream) nil
130 (fd-stream-obuf fd-stream) nil
131 (fd-stream-output-queue fd-stream) nil)
132 ;; splice to *available-buffers*
133 (with-available-buffers-lock ()
134 (setf *available-buffers* (nconc queue *available-buffers*))))))
136 ;;;; the FD-STREAM structure
138 (defstruct (fd-stream
139 (:constructor %make-fd-stream)
140 (:conc-name fd-stream-)
141 (:predicate fd-stream-p)
142 (:include ansi-stream
143 (misc #'fd-stream-misc-routine))
146 ;; the name of this stream
148 ;; the file this stream is for
150 ;; the backup file namestring for the old file, for :IF-EXISTS
151 ;; :RENAME or :RENAME-AND-DELETE.
152 (original nil :type (or simple-string null))
153 (delete-original nil) ; for :if-exists :rename-and-delete
154 ;;; the number of bytes per element
155 (element-size 1 :type index)
156 ;; the type of element being transfered
157 (element-type 'base-char)
158 ;; the Unix file descriptor
160 ;; controls when the output buffer is flushed
161 (buffering :full :type (member :full :line :none))
162 ;; controls whether the input buffer must be cleared before output
163 ;; (must be done for files, not for sockets, pipes and other data
164 ;; sources where input and output aren't related). non-NIL means
165 ;; don't clear input buffer.
167 ;; character position if known -- this may run into bignums, but
168 ;; we probably should flip it into null then for efficiency's sake...
169 (char-pos nil :type (or unsigned-byte null))
170 ;; T if input is waiting on FD. :EOF if we hit EOF.
171 (listen nil :type (member nil t :eof))
172 ;; T if serve-event is allowed when this stream blocks
173 (serve-events nil :type boolean)
176 (instead (make-array 0 :element-type 'character :adjustable t :fill-pointer t) :type (array character (*)))
177 (ibuf nil :type (or buffer null))
178 (eof-forced-p nil :type (member t nil))
181 (obuf nil :type (or buffer null))
183 ;; output flushed, but not written due to non-blocking io?
186 ;; timeout specified for this stream as seconds or NIL if none
187 (timeout nil :type (or single-float null))
188 ;; pathname of the file this stream is opened to (returned by PATHNAME)
189 (pathname nil :type (or pathname null))
190 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
191 (external-format :latin-1)
192 ;; fixed width, or function to call with a character
193 (char-size 1 :type (or fixnum function))
194 (output-bytes #'ill-out :type function)
195 ;; a boolean indicating whether the stream is bivalent. For
196 ;; internal use only.
197 (bivalent-p nil :type boolean))
198 (def!method print-object ((fd-stream fd-stream) stream)
199 (declare (type stream stream))
200 (print-unreadable-object (fd-stream stream :type t :identity t)
201 (format stream "for ~S" (fd-stream-name fd-stream))))
203 ;;;; CORE OUTPUT FUNCTIONS
205 ;;; Buffer the section of THING delimited by START and END by copying
206 ;;; to output buffer(s) of stream.
207 (defun buffer-output (stream thing start end)
208 (declare (index start end))
210 (error ":END before :START!"))
212 ;; Copy bytes from THING to buffers.
213 (flet ((copy-to-buffer (buffer tail count)
214 (declare (buffer buffer) (index tail count))
216 (let ((sap (buffer-sap buffer)))
219 (system-area-ub8-copy thing start sap tail count))
220 ((simple-unboxed-array (*))
221 (copy-ub8-to-system-area thing start sap tail count))))
222 ;; Not INCF! If another thread has moved tail from under
223 ;; us, we don't want to accidentally increment tail
224 ;; beyond buffer-length.
225 (setf (buffer-tail buffer) (+ count tail))
228 ;; First copy is special: the buffer may already contain
229 ;; something, or be even full.
230 (let* ((obuf (fd-stream-obuf stream))
231 (tail (buffer-tail obuf))
232 (space (- (buffer-length obuf) tail)))
234 (copy-to-buffer obuf tail (min space (- end start)))
235 (go :more-output-p)))
237 ;; Later copies should always have an empty buffer, since
238 ;; they are freshly flushed, but if another thread is
239 ;; stomping on the same buffer that might not be the case.
240 (let* ((obuf (flush-output-buffer stream))
241 (tail (buffer-tail obuf))
242 (space (- (buffer-length obuf) tail)))
243 (copy-to-buffer obuf tail (min space (- end start))))
246 (go :flush-and-fill))))))
248 ;;; Flush the current output buffer of the stream, ensuring that the
249 ;;; new buffer is empty. Returns (for convenience) the new output
250 ;;; buffer -- which may or may not be EQ to the old one. If the is no
251 ;;; queued output we try to write the buffer immediately -- otherwise
252 ;;; we queue it for later.
253 (defun flush-output-buffer (stream)
254 (let ((obuf (fd-stream-obuf stream)))
256 (let ((head (buffer-head obuf))
257 (tail (buffer-tail obuf)))
258 (cond ((eql head tail)
259 ;; Buffer is already empty -- just ensure that is is
260 ;; set to zero as well.
262 ((fd-stream-output-queue stream)
263 ;; There is already stuff on the queue -- go directly
266 (%queue-and-replace-output-buffer stream))
268 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
269 ;; whatever is left over. Otherwise wait until we can write.
271 (synchronize-stream-output stream)
273 (let ((length (- tail head)))
274 (multiple-value-bind (count errno)
275 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
277 (flet ((queue-or-wait ()
278 (if (fd-stream-serve-events stream)
279 (return (%queue-and-replace-output-buffer stream))
280 (or (wait-until-fd-usable (fd-stream-fd stream) :output
281 (fd-stream-timeout stream)
283 (signal-timeout 'io-timeout
286 :seconds (fd-stream-timeout stream))))))
287 (cond ((eql count length)
288 ;; Complete write -- we can use the same buffer.
289 (return (reset-buffer obuf)))
291 ;; Partial write -- update buffer status and
292 ;; queue or wait. Do not use INCF! Another
293 ;; thread might have moved head...
294 (setf (buffer-head obuf) (+ count head))
297 ((eql errno sb!unix:ewouldblock)
298 ;; Blocking, queue or wair.
301 (simple-stream-perror "Couldn't write to ~s"
302 stream errno)))))))))))))
304 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
305 (defun %queue-and-replace-output-buffer (stream)
306 (aver (fd-stream-serve-events stream))
307 (let ((queue (fd-stream-output-queue stream))
308 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
310 ;; Important: before putting the buffer on queue, give the stream
311 ;; a new one. If we get an interrupt and unwind losing the buffer
312 ;; is relatively OK, but having the same buffer in two places
314 (setf (fd-stream-obuf stream) new)
318 (setf (fd-stream-output-queue stream) later)))
319 (unless (fd-stream-handler stream)
320 (setf (fd-stream-handler stream)
321 (add-fd-handler (fd-stream-fd stream)
324 (declare (ignore fd))
325 (write-output-from-queue stream)))))
328 ;;; This is called by the FD-HANDLER for the stream when output is
330 (defun write-output-from-queue (stream)
331 (aver (fd-stream-serve-events stream))
332 (synchronize-stream-output stream)
336 (let* ((buffer (pop (fd-stream-output-queue stream)))
337 (head (buffer-head buffer))
338 (length (- (buffer-tail buffer) head)))
339 (declare (index head length))
341 (multiple-value-bind (count errno)
342 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
344 (cond ((eql count length)
345 ;; Complete write, see if we can do another right
346 ;; away, or remove the handler if we're done.
347 (release-buffer buffer)
348 (cond ((fd-stream-output-queue stream)
352 (let ((handler (fd-stream-handler stream)))
354 (setf (fd-stream-handler stream) nil)
355 (remove-fd-handler handler)))))
357 ;; Partial write. Update buffer status and requeue.
358 (aver (< count length))
359 ;; Do not use INCF! Another thread might have moved head.
360 (setf (buffer-head buffer) (+ head count))
361 (push buffer (fd-stream-output-queue stream)))
363 ;; We tried to do multiple writes, and finally our
364 ;; luck ran out. Requeue.
365 (push buffer (fd-stream-output-queue stream)))
367 ;; Could not write on the first try at all!
369 (simple-stream-perror "Couldn't write to ~S." stream errno)
371 (if (= errno sb!unix:ewouldblock)
372 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
373 (simple-stream-perror "Couldn't write to ~S"
377 ;;; Try to write THING directly to STREAM without buffering, if
378 ;;; possible. If direct write doesn't happen, buffer.
379 (defun write-or-buffer-output (stream thing start end)
380 (declare (index start end))
381 (cond ((fd-stream-output-queue stream)
382 (buffer-output stream thing start end))
384 (error ":END before :START!"))
386 (let ((length (- end start)))
387 (synchronize-stream-output stream)
388 (multiple-value-bind (count errno)
389 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
390 (cond ((eql count length)
391 ;; Complete write -- done!
394 (aver (< count length))
395 ;; Partial write -- buffer the rest.
396 (buffer-output stream thing (+ start count) end))
398 ;; Could not write -- buffer or error.
400 (simple-stream-perror "couldn't write to ~s" stream errno)
402 (if (= errno sb!unix:ewouldblock)
403 (buffer-output stream thing start end)
404 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
406 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
407 ;;; this is not something we want to export. Nikodemus thinks the
408 ;;; right thing is to support a low-level non-stream like IO layer,
409 ;;; akin to java.nio.
410 (declaim (inline output-raw-bytes))
411 (define-deprecated-function :late "1.0.8.16" output-raw-bytes write-sequence
412 (stream thing &optional start end)
413 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
415 ;;;; output routines and related noise
417 (defvar *output-routines* ()
419 "List of all available output routines. Each element is a list of the
420 element-type output, the kind of buffering, the function name, and the number
421 of bytes per element.")
423 ;;; common idioms for reporting low-level stream and file problems
424 (defun simple-stream-perror (note-format stream errno)
425 (error 'simple-stream-error
427 :format-control "~@<~?: ~2I~_~A~:>"
428 :format-arguments (list note-format (list stream) (strerror errno))))
429 (defun simple-file-perror (note-format pathname errno)
430 (error 'simple-file-error
432 :format-control "~@<~?: ~2I~_~A~:>"
434 (list note-format (list pathname) (strerror errno))))
436 (defun stream-decoding-error (stream octets)
437 (error 'stream-decoding-error
438 :external-format (stream-external-format stream)
440 ;; FIXME: dunno how to get at OCTETS currently, or even if
441 ;; that's the right thing to report.
443 (defun stream-encoding-error (stream code)
444 (error 'stream-encoding-error
445 :external-format (stream-external-format stream)
449 (defun c-string-encoding-error (external-format code)
450 (error 'c-string-encoding-error
451 :external-format external-format
454 (defun c-string-decoding-error (external-format octets)
455 (error 'c-string-decoding-error
456 :external-format external-format
459 ;;; Returning true goes into end of file handling, false will enter another
460 ;;; round of input buffer filling followed by re-entering character decode.
461 (defun stream-decoding-error-and-handle (stream octet-count)
463 (stream-decoding-error stream
464 (let* ((buffer (fd-stream-ibuf stream))
465 (sap (buffer-sap buffer))
466 (head (buffer-head buffer)))
467 (loop for i from 0 below octet-count
468 collect (sap-ref-8 sap (+ head i)))))
470 :report (lambda (stream)
472 "~@<Attempt to resync the stream at a ~
473 character boundary and continue.~@:>"))
474 (fd-stream-resync stream)
476 (force-end-of-file ()
477 :report (lambda (stream)
478 (format stream "~@<Force an end of file.~@:>"))
479 (setf (fd-stream-eof-forced-p stream) t))
480 (input-replacement (string)
481 :report (lambda (stream)
482 (format stream "~@<Use string as replacement input, ~
483 attempt to resync at a character ~
484 boundary and continue.~@:>"))
485 :interactive (lambda ()
486 (format *query-io* "~@<Enter a string: ~@:>")
487 (finish-output *query-io*)
488 (list (read *query-io*)))
489 (let ((string (reverse (string string)))
490 (instead (fd-stream-instead stream)))
491 (dotimes (i (length string))
492 (vector-push-extend (char string i) instead))
493 (fd-stream-resync stream)
494 (when (> (length string) 0)
495 (setf (fd-stream-listen stream) t)))
498 (defun stream-encoding-error-and-handle (stream code)
500 (stream-encoding-error stream code)
502 :report (lambda (stream)
503 (format stream "~@<Skip output of this character.~@:>"))
504 (throw 'output-nothing nil))
505 (output-replacement (string)
506 :report (lambda (stream)
507 (format stream "~@<Output replacement string.~@:>"))
508 :interactive (lambda ()
509 (format *query-io* "~@<Enter a string: ~@:>")
510 (finish-output *query-io*)
511 (list (read *query-io*)))
512 (let ((string (string string)))
513 (fd-sout stream (string string) 0 (length string)))
514 (throw 'output-nothing nil))))
516 (defun external-format-encoding-error (stream code)
518 (stream-encoding-error-and-handle stream code)
519 (c-string-encoding-error stream code)))
521 (defun synchronize-stream-output (stream)
522 ;; If we're reading and writing on the same file, flush buffered
523 ;; input and rewind file position accordingly.
524 (unless (fd-stream-dual-channel-p stream)
525 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
526 (unless (eql 0 adjust)
527 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
529 (defun fd-stream-output-finished-p (stream)
530 (let ((obuf (fd-stream-obuf stream)))
532 (and (zerop (buffer-tail obuf))
533 (not (fd-stream-output-queue stream))))))
535 (defmacro output-wrapper/variable-width ((stream size buffering restart)
537 (let ((stream-var (gensym "STREAM")))
538 `(let* ((,stream-var ,stream)
539 (obuf (fd-stream-obuf ,stream-var))
540 (tail (buffer-tail obuf))
542 ,(unless (eq (car buffering) :none)
543 `(when (<= (buffer-length obuf) (+ tail size))
544 (setf obuf (flush-output-buffer ,stream-var)
545 tail (buffer-tail obuf))))
546 ,(unless (eq (car buffering) :none)
547 ;; FIXME: Why this here? Doesn't seem necessary.
548 `(synchronize-stream-output ,stream-var))
550 `(catch 'output-nothing
552 (setf (buffer-tail obuf) (+ tail size)))
555 (setf (buffer-tail obuf) (+ tail size))))
556 ,(ecase (car buffering)
558 `(flush-output-buffer ,stream-var))
560 `(when (eql byte #\Newline)
561 (flush-output-buffer ,stream-var)))
565 (defmacro output-wrapper ((stream size buffering restart) &body body)
566 (let ((stream-var (gensym "STREAM")))
567 `(let* ((,stream-var ,stream)
568 (obuf (fd-stream-obuf ,stream-var))
569 (tail (buffer-tail obuf)))
570 ,(unless (eq (car buffering) :none)
571 `(when (<= (buffer-length obuf) (+ tail ,size))
572 (setf obuf (flush-output-buffer ,stream-var)
573 tail (buffer-tail obuf))))
574 ;; FIXME: Why this here? Doesn't seem necessary.
575 ,(unless (eq (car buffering) :none)
576 `(synchronize-stream-output ,stream-var))
578 `(catch 'output-nothing
580 (setf (buffer-tail obuf) (+ tail ,size)))
583 (setf (buffer-tail obuf) (+ tail ,size))))
584 ,(ecase (car buffering)
586 `(flush-output-buffer ,stream-var))
588 `(when (eql byte #\Newline)
589 (flush-output-buffer ,stream-var)))
593 (defmacro def-output-routines/variable-width
594 ((name-fmt size restart external-format &rest bufferings)
596 (declare (optimize (speed 1)))
601 (intern (format nil name-fmt (string (car buffering))))))
603 (defun ,function (stream byte)
604 (declare (ignorable byte))
605 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
607 (setf *output-routines*
608 (nconc *output-routines*
616 (cdr buffering)))))))
619 ;;; Define output routines that output numbers SIZE bytes long for the
620 ;;; given bufferings. Use BODY to do the actual output.
621 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
623 (declare (optimize (speed 1)))
628 (intern (format nil name-fmt (string (car buffering))))))
630 (defun ,function (stream byte)
631 (output-wrapper (stream ,size ,buffering ,restart)
633 (setf *output-routines*
634 (nconc *output-routines*
642 (cdr buffering)))))))
645 ;;; FIXME: is this used anywhere any more?
646 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
652 (if (eql byte #\Newline)
653 (setf (fd-stream-char-pos stream) 0)
654 (incf (fd-stream-char-pos stream)))
655 (setf (sap-ref-8 (buffer-sap obuf) tail)
658 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
661 (:none (unsigned-byte 8))
662 (:full (unsigned-byte 8)))
663 (setf (sap-ref-8 (buffer-sap obuf) tail)
666 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
669 (:none (signed-byte 8))
670 (:full (signed-byte 8)))
671 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
674 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
677 (:none (unsigned-byte 16))
678 (:full (unsigned-byte 16)))
679 (setf (sap-ref-16 (buffer-sap obuf) tail)
682 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
685 (:none (signed-byte 16))
686 (:full (signed-byte 16)))
687 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
690 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
693 (:none (unsigned-byte 32))
694 (:full (unsigned-byte 32)))
695 (setf (sap-ref-32 (buffer-sap obuf) tail)
698 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
701 (:none (signed-byte 32))
702 (:full (signed-byte 32)))
703 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
706 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
708 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
711 (:none (unsigned-byte 64))
712 (:full (unsigned-byte 64)))
713 (setf (sap-ref-64 (buffer-sap obuf) tail)
715 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
718 (:none (signed-byte 64))
719 (:full (signed-byte 64)))
720 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
723 ;;; the routine to use to output a string. If the stream is
724 ;;; unbuffered, slam the string down the file descriptor, otherwise
725 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
726 ;;; checking to see where the last newline was.
727 (defun fd-sout (stream thing start end)
728 (declare (type fd-stream stream) (type string thing))
729 (let ((start (or start 0))
730 (end (or end (length (the vector thing)))))
731 (declare (fixnum start end))
733 (string-dispatch (simple-base-string
735 (simple-array character (*))
738 (position #\newline thing :from-end t
739 :start start :end end))))
740 (if (and (typep thing 'base-string)
741 (eq (fd-stream-external-format-keyword stream) :latin-1))
742 (ecase (fd-stream-buffering stream)
744 (buffer-output stream thing start end))
746 (buffer-output stream thing start end)
748 (flush-output-buffer stream)))
750 (write-or-buffer-output stream thing start end)))
751 (ecase (fd-stream-buffering stream)
752 (:full (funcall (fd-stream-output-bytes stream)
753 stream thing nil start end))
754 (:line (funcall (fd-stream-output-bytes stream)
755 stream thing last-newline start end))
756 (:none (funcall (fd-stream-output-bytes stream)
757 stream thing t start end))))
759 (setf (fd-stream-char-pos stream) (- end last-newline 1))
760 (incf (fd-stream-char-pos stream) (- end start))))))
762 (defstruct (external-format
763 (:constructor %make-external-format)
765 (:predicate external-format-p)
766 (:copier %copy-external-format))
767 ;; All the names that can refer to this external format. The first
768 ;; one is the canonical name.
769 (names (missing-arg) :type list :read-only t)
770 (default-replacement-character (missing-arg) :type character)
771 (read-n-chars-fun (missing-arg) :type function)
772 (read-char-fun (missing-arg) :type function)
773 (write-n-bytes-fun (missing-arg) :type function)
774 (write-char-none-buffered-fun (missing-arg) :type function)
775 (write-char-line-buffered-fun (missing-arg) :type function)
776 (write-char-full-buffered-fun (missing-arg) :type function)
777 ;; Can be nil for fixed-width formats.
778 (resync-fun nil :type (or function null))
779 (bytes-for-char-fun (missing-arg) :type function)
780 (read-c-string-fun (missing-arg) :type function)
781 (write-c-string-fun (missing-arg) :type function)
782 ;; We indirect through symbols in these functions so that a
783 ;; developer working on the octets code can easily redefine things
784 ;; and use the new function definition without redefining the
785 ;; external format as well. The slots above don't do any
786 ;; indirection because a developer working with those slots would be
787 ;; redefining the external format anyway.
788 (octets-to-string-fun (missing-arg) :type function)
789 (string-to-octets-fun (missing-arg) :type function))
791 (defun ef-char-size (ef-entry)
792 (if (variable-width-external-format-p ef-entry)
793 (bytes-for-char-fun ef-entry)
794 (funcall (bytes-for-char-fun ef-entry) #\x)))
796 (defun wrap-external-format-functions (external-format fun)
797 (let ((result (%copy-external-format external-format)))
798 (macrolet ((frob (accessor)
799 `(setf (,accessor result) (funcall fun (,accessor result)))))
800 (frob ef-read-n-chars-fun)
801 (frob ef-read-char-fun)
802 (frob ef-write-n-bytes-fun)
803 (frob ef-write-char-none-buffered-fun)
804 (frob ef-write-char-line-buffered-fun)
805 (frob ef-write-char-full-buffered-fun)
807 (frob ef-bytes-for-char-fun)
808 (frob ef-read-c-string-fun)
809 (frob ef-write-c-string-fun)
810 (frob ef-octets-to-string-fun)
811 (frob ef-string-to-octets-fun))
814 (defvar *external-formats* (make-hash-table)
816 "Hashtable of all available external formats. The table maps from
817 external-format names to EXTERNAL-FORMAT structures.")
819 (defun get-external-format (external-format)
820 (flet ((keyword-external-format (keyword)
821 (declare (type keyword keyword))
822 (gethash keyword *external-formats*))
823 (replacement-handlerify (entry replacement)
825 (wrap-external-format-functions
830 (declare (dynamic-extent rest))
832 ((stream-decoding-error
835 (invoke-restart 'input-replacement replacement)))
836 (stream-encoding-error
839 (invoke-restart 'output-replacement replacement)))
840 (octets-encoding-error
841 (lambda (c) (use-value replacement c)))
842 (octet-decoding-error
843 (lambda (c) (use-value replacement c))))
844 (apply fun rest)))))))))
845 (typecase external-format
846 (keyword (keyword-external-format external-format))
848 (let ((entry (keyword-external-format (car external-format)))
849 (replacement (getf (cdr external-format) :replacement)))
851 (replacement-handlerify entry replacement)
854 (defun get-external-format-or-lose (external-format)
855 (or (get-external-format external-format)
856 (error "Undefined external-format: ~S" external-format)))
858 (defun external-format-keyword (external-format)
859 (typecase external-format
860 (keyword external-format)
861 ((cons keyword) (car external-format))))
863 (defun fd-stream-external-format-keyword (stream)
864 (external-format-keyword (fd-stream-external-format stream)))
866 (defun canonize-external-format (external-format entry)
867 (typecase external-format
868 (keyword (first (ef-names entry)))
869 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
871 ;;; Find an output routine to use given the type and buffering. Return
872 ;;; as multiple values the routine, the real type transfered, and the
873 ;;; number of bytes per element.
874 (defun pick-output-routine (type buffering &optional external-format)
875 (when (subtypep type 'character)
876 (let ((entry (get-external-format-or-lose external-format)))
877 (return-from pick-output-routine
878 (values (ecase buffering
879 (:none (ef-write-char-none-buffered-fun entry))
880 (:line (ef-write-char-line-buffered-fun entry))
881 (:full (ef-write-char-full-buffered-fun entry)))
884 (ef-write-n-bytes-fun entry)
886 (canonize-external-format external-format entry)))))
887 (dolist (entry *output-routines*)
888 (when (and (subtypep type (first entry))
889 (eq buffering (second entry))
890 (or (not (fifth entry))
891 (eq external-format (fifth entry))))
892 (return-from pick-output-routine
893 (values (symbol-function (third entry))
896 ;; KLUDGE: dealing with the buffering here leads to excessive code
899 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
900 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
901 if (subtypep type `(unsigned-byte ,i))
902 do (return-from pick-output-routine
906 (lambda (stream byte)
907 (output-wrapper (stream (/ i 8) (:none) nil)
908 (loop for j from 0 below (/ i 8)
909 do (setf (sap-ref-8 (buffer-sap obuf)
911 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
913 (lambda (stream byte)
914 (output-wrapper (stream (/ i 8) (:full) nil)
915 (loop for j from 0 below (/ i 8)
916 do (setf (sap-ref-8 (buffer-sap obuf)
918 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
921 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
922 if (subtypep type `(signed-byte ,i))
923 do (return-from pick-output-routine
927 (lambda (stream byte)
928 (output-wrapper (stream (/ i 8) (:none) nil)
929 (loop for j from 0 below (/ i 8)
930 do (setf (sap-ref-8 (buffer-sap obuf)
932 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
934 (lambda (stream byte)
935 (output-wrapper (stream (/ i 8) (:full) nil)
936 (loop for j from 0 below (/ i 8)
937 do (setf (sap-ref-8 (buffer-sap obuf)
939 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
943 ;;;; input routines and related noise
945 ;;; a list of all available input routines. Each element is a list of
946 ;;; the element-type input, the function name, and the number of bytes
948 (defvar *input-routines* ())
950 ;;; Return whether a primitive partial read operation on STREAM's FD
951 ;;; would (probably) block. Signal a `simple-stream-error' if the
952 ;;; system call implementing this operation fails.
954 ;;; It is "may" instead of "would" because "would" is not quite
955 ;;; correct on win32. However, none of the places that use it require
956 ;;; further assurance than "may" versus "will definitely not".
957 (defun sysread-may-block-p (stream)
959 ;; This answers T at EOF on win32, I think.
960 (not (sb!win32:fd-listen (fd-stream-fd stream)))
962 (not (sb!unix:unix-simple-poll (fd-stream-fd stream) :input 0)))
964 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
965 ;;; then fill the input buffer, and return the number of bytes read. Throws
966 ;;; to EOF-INPUT-CATCHER if the eof was reached.
967 (defun refill-input-buffer (stream)
968 (dx-let ((fd (fd-stream-fd stream))
972 ;; Check for blocking input before touching the stream if we are to
973 ;; serve events: if the FD is blocking, we don't want to hang on the
974 ;; write if we are to serve events or notice timeouts.
975 (if (and (or (fd-stream-serve-events stream)
976 (fd-stream-timeout stream)
978 (sysread-may-block-p stream))
981 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
982 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
984 (closed-flame stream)
986 (simple-stream-perror "couldn't read from ~S" stream errno)
988 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
989 ;; to wait for input if read tells us EWOULDBLOCK.
990 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream)
991 (fd-stream-serve-events stream))
992 (signal-timeout 'io-timeout
995 :seconds (fd-stream-timeout stream)))
997 ;; Since the read should not block, we'll disable the
998 ;; interrupts here, so that we don't accidentally unwind and
999 ;; leave the stream in an inconsistent state.
1001 ;; Execute the nlx outside without-interrupts to ensure the
1002 ;; resulting thunk is stack-allocatable.
1003 ((lambda (return-reason)
1004 (ecase return-reason
1005 ((nil)) ; fast path normal cases
1006 ((:wait-for-input) (go :wait-for-input))
1007 ((:closed-flame) (go :closed-flame))
1008 ((:read-error) (go :read-error))))
1010 ;; Check the buffer: if it is null, then someone has closed
1011 ;; the stream from underneath us. This is not ment to fix
1012 ;; multithreaded races, but to deal with interrupt handlers
1013 ;; closing the stream.
1016 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1017 (sap (buffer-sap ibuf))
1018 (length (buffer-length ibuf))
1019 (head (buffer-head ibuf))
1020 (tail (buffer-tail ibuf)))
1021 (declare (index length head tail)
1022 (inline sb!unix:unix-read))
1023 (unless (zerop head)
1024 (cond ((eql head tail)
1025 ;; Buffer is empty, but not at yet reset -- make it so.
1028 (reset-buffer ibuf))
1030 ;; Buffer has things in it, but they are not at the
1031 ;; head -- move them there.
1032 (let ((n (- tail head)))
1033 (system-area-ub8-copy sap head sap 0 n)
1035 (buffer-head ibuf) head
1037 (buffer-tail ibuf) tail)))))
1038 (setf (fd-stream-listen stream) nil)
1039 (setf (values count errno)
1040 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1043 (return :read-error)
1045 (if (eql errno sb!unix:ewouldblock)
1046 (return :wait-for-input)
1047 (return :read-error)))
1049 (setf (fd-stream-listen stream) :eof)
1050 (/show0 "THROWing EOF-INPUT-CATCHER")
1051 (throw 'eof-input-catcher nil))
1053 ;; Success! (Do not use INCF, for sake of other threads.)
1054 (setf (buffer-tail ibuf) (+ count tail))))))))))
1057 ;;; Make sure there are at least BYTES number of bytes in the input
1058 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1059 (defmacro input-at-least (stream bytes)
1060 (let ((stream-var (gensym "STREAM"))
1061 (bytes-var (gensym "BYTES"))
1062 (buffer-var (gensym "IBUF")))
1063 `(let* ((,stream-var ,stream)
1065 (,buffer-var (fd-stream-ibuf ,stream-var)))
1067 (when (>= (- (buffer-tail ,buffer-var)
1068 (buffer-head ,buffer-var))
1071 (refill-input-buffer ,stream-var)))))
1073 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1075 (let ((stream-var (gensym "STREAM"))
1076 (retry-var (gensym "RETRY"))
1077 (element-var (gensym "ELT")))
1078 `(let* ((,stream-var ,stream)
1079 (ibuf (fd-stream-ibuf ,stream-var))
1082 (when (fd-stream-eof-forced-p ,stream-var)
1083 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1084 (return-from use-instead
1085 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1086 (let ((,element-var nil)
1087 (decode-break-reason nil))
1088 (do ((,retry-var t))
1090 (if (> (length (fd-stream-instead ,stream-var)) 0)
1091 (let* ((instead (fd-stream-instead ,stream-var))
1092 (result (vector-pop instead))
1093 (pointer (fill-pointer instead)))
1095 (setf (fd-stream-listen ,stream-var) nil))
1096 (return-from use-instead result))
1098 (catch 'eof-input-catcher
1099 (setf decode-break-reason
1100 (block decode-break-reason
1101 (input-at-least ,stream-var ,(if (consp bytes) (car bytes) `(setq size ,bytes)))
1102 (let* ((byte (sap-ref-8 (buffer-sap ibuf) (buffer-head ibuf))))
1103 (declare (ignorable byte))
1104 ,@(when (consp bytes)
1105 `((let ((sap (buffer-sap ibuf))
1106 (head (buffer-head ibuf)))
1107 (declare (ignorable sap head))
1108 (setq size ,(cadr bytes))
1109 (input-at-least ,stream-var size))))
1110 (setq ,element-var (locally ,@read-forms))
1111 (setq ,retry-var nil))
1113 (when decode-break-reason
1114 (when (stream-decoding-error-and-handle
1115 stream decode-break-reason)
1116 (setq ,retry-var nil)
1117 (throw 'eof-input-catcher nil)))
1119 (let ((octet-count (- (buffer-tail ibuf)
1120 (buffer-head ibuf))))
1121 (when (or (zerop octet-count)
1122 (and (not ,element-var)
1123 (not decode-break-reason)
1124 (stream-decoding-error-and-handle
1125 stream octet-count)))
1126 (setq ,retry-var nil))))))
1128 (incf (buffer-head ibuf) size)
1131 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1133 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1134 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1135 (let ((stream-var (gensym "STREAM"))
1136 (element-var (gensym "ELT")))
1137 `(let* ((,stream-var ,stream)
1138 (ibuf (fd-stream-ibuf ,stream-var)))
1139 (if (> (length (fd-stream-instead ,stream-var)) 0)
1140 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1142 (catch 'eof-input-catcher
1143 (input-at-least ,stream-var ,bytes)
1144 (locally ,@read-forms))))
1146 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1149 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1151 (defmacro def-input-routine/variable-width (name
1152 (type external-format size sap head)
1155 (defun ,name (stream eof-error eof-value)
1156 (input-wrapper/variable-width (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 1 ',external-format))))))
1164 (defmacro def-input-routine (name
1165 (type size sap head)
1168 (defun ,name (stream eof-error eof-value)
1169 (input-wrapper (stream ,size eof-error eof-value)
1170 (let ((,sap (buffer-sap ibuf))
1171 (,head (buffer-head ibuf)))
1173 (setf *input-routines*
1174 (nconc *input-routines*
1175 (list (list ',type ',name ',size nil))))))
1177 ;;; STREAM-IN routine for reading a string char
1178 (def-input-routine input-character
1179 (character 1 sap head)
1180 (code-char (sap-ref-8 sap head)))
1182 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1183 (def-input-routine input-unsigned-8bit-byte
1184 ((unsigned-byte 8) 1 sap head)
1185 (sap-ref-8 sap head))
1187 ;;; STREAM-IN routine for reading a signed 8 bit number
1188 (def-input-routine input-signed-8bit-number
1189 ((signed-byte 8) 1 sap head)
1190 (signed-sap-ref-8 sap head))
1192 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1193 (def-input-routine input-unsigned-16bit-byte
1194 ((unsigned-byte 16) 2 sap head)
1195 (sap-ref-16 sap head))
1197 ;;; STREAM-IN routine for reading a signed 16 bit number
1198 (def-input-routine input-signed-16bit-byte
1199 ((signed-byte 16) 2 sap head)
1200 (signed-sap-ref-16 sap head))
1202 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1203 (def-input-routine input-unsigned-32bit-byte
1204 ((unsigned-byte 32) 4 sap head)
1205 (sap-ref-32 sap head))
1207 ;;; STREAM-IN routine for reading a signed 32 bit number
1208 (def-input-routine input-signed-32bit-byte
1209 ((signed-byte 32) 4 sap head)
1210 (signed-sap-ref-32 sap head))
1212 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1214 (def-input-routine input-unsigned-64bit-byte
1215 ((unsigned-byte 64) 8 sap head)
1216 (sap-ref-64 sap head))
1217 (def-input-routine input-signed-64bit-byte
1218 ((signed-byte 64) 8 sap head)
1219 (signed-sap-ref-64 sap head)))
1221 ;;; Find an input routine to use given the type. Return as multiple
1222 ;;; values the routine, the real type transfered, and the number of
1223 ;;; bytes per element (and for character types string input routine).
1224 (defun pick-input-routine (type &optional external-format)
1225 (when (subtypep type 'character)
1226 (let ((entry (get-external-format-or-lose external-format)))
1227 (return-from pick-input-routine
1228 (values (ef-read-char-fun entry)
1231 (ef-read-n-chars-fun entry)
1232 (ef-char-size entry)
1233 (canonize-external-format external-format entry)))))
1234 (dolist (entry *input-routines*)
1235 (when (and (subtypep type (first entry))
1236 (or (not (fourth entry))
1237 (eq external-format (fourth entry))))
1238 (return-from pick-input-routine
1239 (values (symbol-function (second entry))
1242 ;; FIXME: let's do it the hard way, then (but ignore things like
1243 ;; endianness, efficiency, and the necessary coupling between these
1244 ;; and the output routines). -- CSR, 2004-02-09
1245 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1246 if (subtypep type `(unsigned-byte ,i))
1247 do (return-from pick-input-routine
1249 (lambda (stream eof-error eof-value)
1250 (input-wrapper (stream (/ i 8) eof-error eof-value)
1251 (let ((sap (buffer-sap ibuf))
1252 (head (buffer-head ibuf)))
1253 (loop for j from 0 below (/ i 8)
1257 (sap-ref-8 sap (+ head j))))
1258 finally (return result)))))
1261 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1262 if (subtypep type `(signed-byte ,i))
1263 do (return-from pick-input-routine
1265 (lambda (stream eof-error eof-value)
1266 (input-wrapper (stream (/ i 8) eof-error eof-value)
1267 (let ((sap (buffer-sap ibuf))
1268 (head (buffer-head ibuf)))
1269 (loop for j from 0 below (/ i 8)
1273 (sap-ref-8 sap (+ head j))))
1274 finally (return (if (logbitp (1- i) result)
1275 (dpb result (byte i 0) -1)
1280 ;;; the N-BIN method for FD-STREAMs
1282 ;;; Note that this blocks in UNIX-READ. It is generally used where
1283 ;;; there is a definite amount of reading to be done, so blocking
1284 ;;; isn't too problematical.
1285 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1286 &aux (total-copied 0))
1287 (declare (type fd-stream stream))
1288 (declare (type index start requested total-copied))
1289 (aver (= (length (fd-stream-instead stream)) 0))
1292 (let* ((remaining-request (- requested total-copied))
1293 (ibuf (fd-stream-ibuf stream))
1294 (head (buffer-head ibuf))
1295 (tail (buffer-tail ibuf))
1296 (available (- tail head))
1297 (n-this-copy (min remaining-request available))
1298 (this-start (+ start total-copied))
1299 (this-end (+ this-start n-this-copy))
1300 (sap (buffer-sap ibuf)))
1301 (declare (type index remaining-request head tail available))
1302 (declare (type index n-this-copy))
1303 ;; Copy data from stream buffer into user's buffer.
1304 (%byte-blt sap head buffer this-start this-end)
1305 (incf (buffer-head ibuf) n-this-copy)
1306 (incf total-copied n-this-copy)
1307 ;; Maybe we need to refill the stream buffer.
1308 (cond (;; If there were enough data in the stream buffer, we're done.
1309 (eql total-copied requested)
1310 (return total-copied))
1311 (;; If EOF, we're done in another way.
1312 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1314 (error 'end-of-file :stream stream)
1315 (return total-copied)))
1316 ;; Otherwise we refilled the stream buffer, so fall
1317 ;; through into another pass of the loop.
1320 (defun fd-stream-resync (stream)
1321 (let ((entry (get-external-format (fd-stream-external-format stream))))
1323 (funcall (ef-resync-fun entry) stream))))
1325 (defun get-fd-stream-character-sizer (stream)
1326 (let ((entry (get-external-format (fd-stream-external-format stream))))
1328 (ef-bytes-for-char-fun entry))))
1330 (defun fd-stream-character-size (stream char)
1331 (let ((sizer (get-fd-stream-character-sizer stream)))
1332 (when sizer (funcall sizer char))))
1334 (defun fd-stream-string-size (stream string)
1335 (let ((sizer (get-fd-stream-character-sizer stream)))
1337 (loop for char across string summing (funcall sizer char)))))
1339 (defun find-external-format (external-format)
1340 (when external-format
1341 (get-external-format external-format)))
1343 (defun variable-width-external-format-p (ef-entry)
1344 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1346 (defun bytes-for-char-fun (ef-entry)
1347 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1349 (defmacro define-unibyte-mapping-external-format
1350 (canonical-name (&rest other-names) &body exceptions)
1351 (let ((->code-name (symbolicate canonical-name '->code-mapper))
1352 (code->-name (symbolicate 'code-> canonical-name '-mapper))
1353 (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1354 (string->-name (symbolicate 'string-> canonical-name))
1355 (define-string*-name (symbolicate 'define- canonical-name '->string*))
1356 (string*-name (symbolicate canonical-name '->string*))
1357 (define-string-name (symbolicate 'define- canonical-name '->string))
1358 (string-name (symbolicate canonical-name '->string))
1359 (->string-aref-name (symbolicate canonical-name '->string-aref)))
1361 (define-unibyte-mapper ,->code-name ,code->-name
1363 (declaim (inline ,get-bytes-name))
1364 (defun ,get-bytes-name (string pos)
1365 (declare (optimize speed (safety 0))
1366 (type simple-string string)
1367 (type array-range pos))
1368 (get-latin-bytes #',code->-name ,canonical-name string pos))
1369 (defun ,string->-name (string sstart send null-padding)
1370 (declare (optimize speed (safety 0))
1371 (type simple-string string)
1372 (type array-range sstart send))
1373 (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1374 (defmacro ,define-string*-name (accessor type)
1375 (declare (ignore type))
1376 (let ((name (make-od-name ',string*-name accessor)))
1378 (defun ,name (string sstart send array astart aend)
1379 (,(make-od-name 'latin->string* accessor)
1380 string sstart send array astart aend #',',->code-name)))))
1381 (instantiate-octets-definition ,define-string*-name)
1382 (defmacro ,define-string-name (accessor type)
1383 (declare (ignore type))
1384 (let ((name (make-od-name ',string-name accessor)))
1386 (defun ,name (array astart aend)
1387 (,(make-od-name 'latin->string accessor)
1388 array astart aend #',',->code-name)))))
1389 (instantiate-octets-definition ,define-string-name)
1390 (define-unibyte-external-format ,canonical-name ,other-names
1391 (let ((octet (,code->-name bits)))
1393 (setf (sap-ref-8 sap tail) octet)
1394 (external-format-encoding-error stream bits)))
1395 (let ((code (,->code-name byte)))
1398 (return-from decode-break-reason 1)))
1402 (defmacro define-unibyte-external-format
1403 (canonical-name (&rest other-names)
1404 out-form in-form octets-to-string-symbol string-to-octets-symbol)
1405 `(define-external-format/variable-width (,canonical-name ,@other-names)
1410 ,octets-to-string-symbol
1411 ,string-to-octets-symbol))
1413 (defmacro define-external-format/variable-width
1414 (external-format output-restart replacement-character
1415 out-size-expr out-expr in-size-expr in-expr
1416 octets-to-string-sym string-to-octets-sym)
1417 (let* ((name (first external-format))
1418 (out-function (symbolicate "OUTPUT-BYTES/" name))
1419 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1420 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1421 (in-char-function (symbolicate "INPUT-CHAR/" name))
1422 (resync-function (symbolicate "RESYNC/" name))
1423 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1424 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1425 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1426 (n-buffer (gensym "BUFFER")))
1428 (defun ,size-function (byte)
1429 (declare (ignorable byte))
1431 (defun ,out-function (stream string flush-p start end)
1432 (let ((start (or start 0))
1433 (end (or end (length string))))
1434 (declare (type index start end))
1435 (synchronize-stream-output stream)
1436 (unless (<= 0 start end (length string))
1437 (sequence-bounding-indices-bad-error string start end))
1440 (let ((obuf (fd-stream-obuf stream)))
1441 (string-dispatch (simple-base-string
1442 #!+sb-unicode (simple-array character (*))
1445 (let ((len (buffer-length obuf))
1446 (sap (buffer-sap obuf))
1448 (tail (buffer-tail obuf)))
1449 (declare (type index tail)
1450 ;; STRING bounds have already been checked.
1451 (optimize (safety 0)))
1452 (,@(if output-restart
1453 `(catch 'output-nothing)
1456 ((or (= start end) (< (- len tail) 4)))
1457 (let* ((byte (aref string start))
1458 (bits (char-code byte))
1459 (size ,out-size-expr))
1462 (setf (buffer-tail obuf) tail)
1465 ;; Exited via CATCH: skip the current character.
1469 (flush-output-buffer stream)))
1471 (flush-output-buffer stream))))
1472 (def-output-routines/variable-width (,format
1479 (if (eql byte #\Newline)
1480 (setf (fd-stream-char-pos stream) 0)
1481 (incf (fd-stream-char-pos stream)))
1482 (let ((bits (char-code byte))
1483 (sap (buffer-sap obuf))
1484 (tail (buffer-tail obuf)))
1486 (defun ,in-function (stream buffer start requested eof-error-p
1487 &aux (total-copied 0))
1488 (declare (type fd-stream stream)
1489 (type index start requested total-copied)
1491 (simple-array character (#.+ansi-stream-in-buffer-length+))
1493 (when (fd-stream-eof-forced-p stream)
1494 (setf (fd-stream-eof-forced-p stream) nil)
1495 (return-from ,in-function 0))
1496 (do ((instead (fd-stream-instead stream)))
1497 ((= (fill-pointer instead) 0)
1498 (setf (fd-stream-listen stream) nil))
1499 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1501 (when (= requested total-copied)
1502 (when (= (fill-pointer instead) 0)
1503 (setf (fd-stream-listen stream) nil))
1504 (return-from ,in-function total-copied)))
1507 (let* ((ibuf (fd-stream-ibuf stream))
1508 (head (buffer-head ibuf))
1509 (tail (buffer-tail ibuf))
1510 (sap (buffer-sap ibuf))
1511 (decode-break-reason nil))
1512 (declare (type index head tail))
1513 ;; Copy data from stream buffer into user's buffer.
1514 (do ((size nil nil))
1515 ((or (= tail head) (= requested total-copied)))
1516 (setf decode-break-reason
1517 (block decode-break-reason
1518 ,@(when (consp in-size-expr)
1519 `((when (> ,(car in-size-expr) (- tail head))
1521 (let ((byte (sap-ref-8 sap head)))
1522 (declare (ignorable byte))
1523 (setq size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr))
1524 (when (> size (- tail head))
1526 (setf (aref buffer (+ start total-copied)) ,in-expr)
1530 (setf (buffer-head ibuf) head)
1531 (when decode-break-reason
1532 ;; If we've already read some characters on when the invalid
1533 ;; code sequence is detected, we return immediately. The
1534 ;; handling of the error is deferred until the next call
1535 ;; (where this check will be false). This allows establishing
1536 ;; high-level handlers for decode errors (for example
1537 ;; automatically resyncing in Lisp comments).
1538 (when (plusp total-copied)
1539 (return-from ,in-function total-copied))
1540 (when (stream-decoding-error-and-handle
1541 stream decode-break-reason)
1543 (error 'end-of-file :stream stream)
1544 (return-from ,in-function total-copied)))
1545 ;; we might have been given stuff to use instead, so
1546 ;; we have to return (and trust our caller to know
1547 ;; what to do about TOTAL-COPIED being 0).
1548 (return-from ,in-function total-copied)))
1549 (setf (buffer-head ibuf) head)
1550 ;; Maybe we need to refill the stream buffer.
1551 (cond ( ;; If was data in the stream buffer, we're done.
1552 (plusp total-copied)
1553 (return total-copied))
1554 ( ;; If EOF, we're done in another way.
1555 (or (eq decode-break-reason 'eof)
1556 (null (catch 'eof-input-catcher
1557 (refill-input-buffer stream))))
1559 (error 'end-of-file :stream stream)
1560 (return total-copied)))
1561 ;; Otherwise we refilled the stream buffer, so fall
1562 ;; through into another pass of the loop.
1564 (def-input-routine/variable-width ,in-char-function (character
1568 (let ((byte (sap-ref-8 sap head)))
1569 (declare (ignorable byte))
1571 (defun ,resync-function (stream)
1572 (let ((ibuf (fd-stream-ibuf stream))
1574 (catch 'eof-input-catcher
1576 (incf (buffer-head ibuf))
1577 (input-at-least stream ,(if (consp in-size-expr) (car in-size-expr) `(setq size ,in-size-expr)))
1578 (unless (block decode-break-reason
1579 (let* ((sap (buffer-sap ibuf))
1580 (head (buffer-head ibuf))
1581 (byte (sap-ref-8 sap head)))
1582 (declare (ignorable byte))
1583 ,@(when (consp in-size-expr)
1584 `((setq size ,(cadr in-size-expr))
1585 (input-at-least stream size)))
1586 (setf head (buffer-head ibuf))
1590 (defun ,read-c-string-function (sap element-type)
1591 (declare (type system-area-pointer sap))
1593 (declare (optimize (speed 3) (safety 0)))
1594 (let* ((stream ,name)
1595 (size 0) (head 0) (byte 0) (char nil)
1596 (decode-break-reason nil)
1597 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1598 (setf decode-break-reason
1599 (block decode-break-reason
1600 (setf byte (sap-ref-8 sap head)
1601 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1605 (when decode-break-reason
1606 (c-string-decoding-error ,name decode-break-reason))
1607 (when (zerop (char-code char))
1609 (string (make-string length :element-type element-type)))
1610 (declare (ignorable stream)
1611 (type index head length) ;; size
1612 (type (unsigned-byte 8) byte)
1613 (type (or null character) char)
1614 (type string string))
1616 (dotimes (index length string)
1617 (setf decode-break-reason
1618 (block decode-break-reason
1619 (setf byte (sap-ref-8 sap head)
1620 size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr)
1624 (when decode-break-reason
1625 (c-string-decoding-error ,name decode-break-reason))
1626 (setf (aref string index) char)))))
1628 (defun ,output-c-string-function (string)
1629 (declare (type simple-string string))
1631 (declare (optimize (speed 3) (safety 0)))
1632 (let* ((length (length string))
1633 (char-length (make-array (1+ length) :element-type 'index))
1635 (+ (loop for i of-type index below length
1636 for byte of-type character = (aref string i)
1637 for bits = (char-code byte)
1638 sum (setf (aref char-length i)
1639 (the index ,out-size-expr)))
1640 (let* ((byte (code-char 0))
1641 (bits (char-code byte)))
1642 (declare (ignorable byte bits))
1643 (setf (aref char-length length)
1644 (the index ,out-size-expr)))))
1646 (,n-buffer (make-array buffer-length
1647 :element-type '(unsigned-byte 8)))
1649 (declare (type index length buffer-length tail)
1652 (with-pinned-objects (,n-buffer)
1653 (let ((sap (vector-sap ,n-buffer)))
1654 (declare (system-area-pointer sap))
1655 (loop for i of-type index below length
1656 for byte of-type character = (aref string i)
1657 for bits = (char-code byte)
1658 for size of-type index = (aref char-length i)
1663 (byte (code-char bits))
1664 (size (aref char-length length)))
1665 (declare (ignorable bits byte size))
1669 (let ((entry (%make-external-format
1670 :names ',external-format
1671 :default-replacement-character ,replacement-character
1672 :read-n-chars-fun #',in-function
1673 :read-char-fun #',in-char-function
1674 :write-n-bytes-fun #',out-function
1675 ,@(mapcan #'(lambda (buffering)
1676 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1677 `#',(intern (format nil format (string buffering)))))
1678 '(:none :line :full))
1679 :resync-fun #',resync-function
1680 :bytes-for-char-fun #',size-function
1681 :read-c-string-fun #',read-c-string-function
1682 :write-c-string-fun #',output-c-string-function
1683 :octets-to-string-fun (lambda (&rest rest)
1684 (declare (dynamic-extent rest))
1685 (apply ',octets-to-string-sym rest))
1686 :string-to-octets-fun (lambda (&rest rest)
1687 (declare (dynamic-extent rest))
1688 (apply ',string-to-octets-sym rest)))))
1689 (dolist (ef ',external-format)
1690 (setf (gethash ef *external-formats*) entry))))))
1692 ;;;; utility functions (misc routines, etc)
1694 ;;; Fill in the various routine slots for the given type. INPUT-P and
1695 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1696 ;;; set prior to calling this routine.
1697 (defun set-fd-stream-routines (fd-stream element-type external-format
1698 input-p output-p buffer-p)
1699 (let* ((target-type (case element-type
1700 (unsigned-byte '(unsigned-byte 8))
1701 (signed-byte '(signed-byte 8))
1702 (:default 'character)
1704 (character-stream-p (subtypep target-type 'character))
1705 (bivalent-stream-p (eq element-type :default))
1706 normalized-external-format
1708 (bin-routine #'ill-bin)
1711 (cin-routine #'ill-in)
1714 (input-type nil) ;calculated from bin-type/cin-type
1715 (input-size nil) ;calculated from bin-size/cin-size
1716 (read-n-characters #'ill-in)
1717 (bout-routine #'ill-bout)
1720 (cout-routine #'ill-out)
1725 (output-bytes #'ill-bout))
1727 ;; Ensure that we have buffers in the desired direction(s) only,
1728 ;; getting new ones and dropping/resetting old ones as necessary.
1729 (let ((obuf (fd-stream-obuf fd-stream)))
1733 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1735 (setf (fd-stream-obuf fd-stream) nil)
1736 (release-buffer obuf))))
1738 (let ((ibuf (fd-stream-ibuf fd-stream)))
1742 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1744 (setf (fd-stream-ibuf fd-stream) nil)
1745 (release-buffer ibuf))))
1747 ;; FIXME: Why only for output? Why unconditionally?
1749 (setf (fd-stream-char-pos fd-stream) 0))
1751 (when (and character-stream-p (eq external-format :default))
1752 (/show0 "/getting default external format")
1753 (setf external-format (default-external-format)))
1756 (when (or (not character-stream-p) bivalent-stream-p)
1757 (setf (values bin-routine bin-type bin-size read-n-characters
1758 char-size normalized-external-format)
1759 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1763 (error "could not find any input routine for ~S" target-type)))
1764 (when character-stream-p
1765 (setf (values cin-routine cin-type cin-size read-n-characters
1766 char-size normalized-external-format)
1767 (pick-input-routine target-type external-format))
1769 (error "could not find any input routine for ~S" target-type)))
1770 (setf (fd-stream-in fd-stream) cin-routine
1771 (fd-stream-bin fd-stream) bin-routine)
1772 ;; character type gets preferential treatment
1773 (setf input-size (or cin-size bin-size))
1774 (setf input-type (or cin-type bin-type))
1775 (when normalized-external-format
1776 (setf (fd-stream-external-format fd-stream) normalized-external-format
1777 (fd-stream-char-size fd-stream) char-size))
1778 (when (= (or cin-size 1) (or bin-size 1) 1)
1779 (setf (fd-stream-n-bin fd-stream) ;XXX
1780 (if (and character-stream-p (not bivalent-stream-p))
1782 #'fd-stream-read-n-bytes))
1783 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1784 ;; for character and (unsigned-byte 8) streams. In these
1785 ;; cases, fast-read-* will read from the
1786 ;; ansi-stream-(c)in-buffer, saving function calls.
1787 ;; Otherwise, the various data-reading functions in the stream
1788 ;; structure will be called.
1790 (not bivalent-stream-p)
1791 ;; temporary disable on :io streams
1793 (cond (character-stream-p
1794 (setf (ansi-stream-cin-buffer fd-stream)
1795 (make-array +ansi-stream-in-buffer-length+
1796 :element-type 'character)))
1797 ((equal target-type '(unsigned-byte 8))
1798 (setf (ansi-stream-in-buffer fd-stream)
1799 (make-array +ansi-stream-in-buffer-length+
1800 :element-type '(unsigned-byte 8))))))))
1803 (when (or (not character-stream-p) bivalent-stream-p)
1804 (setf (values bout-routine bout-type bout-size output-bytes
1805 char-size normalized-external-format)
1806 (let ((buffering (fd-stream-buffering fd-stream)))
1807 (if bivalent-stream-p
1808 (pick-output-routine '(unsigned-byte 8)
1809 (if (eq :line buffering)
1813 (pick-output-routine target-type buffering external-format))))
1814 (unless bout-routine
1815 (error "could not find any output routine for ~S buffered ~S"
1816 (fd-stream-buffering fd-stream)
1818 (when character-stream-p
1819 (setf (values cout-routine cout-type cout-size output-bytes
1820 char-size normalized-external-format)
1821 (pick-output-routine target-type
1822 (fd-stream-buffering fd-stream)
1824 (unless cout-routine
1825 (error "could not find any output routine for ~S buffered ~S"
1826 (fd-stream-buffering fd-stream)
1828 (when normalized-external-format
1829 (setf (fd-stream-external-format fd-stream) normalized-external-format
1830 (fd-stream-char-size fd-stream) char-size))
1831 (when character-stream-p
1832 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1833 (setf (fd-stream-out fd-stream) cout-routine
1834 (fd-stream-bout fd-stream) bout-routine
1835 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1836 #'fd-sout #'ill-out))
1837 (setf output-size (or cout-size bout-size))
1838 (setf output-type (or cout-type bout-type)))
1840 (when (and input-size output-size
1841 (not (eq input-size output-size)))
1842 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1843 input-type input-size
1844 output-type output-size))
1845 (setf (fd-stream-element-size fd-stream)
1846 (or input-size output-size))
1848 (setf (fd-stream-element-type fd-stream)
1849 (cond ((equal input-type output-type)
1855 ((subtypep input-type output-type)
1857 ((subtypep output-type input-type)
1860 (error "Input type (~S) and output type (~S) are unrelated?"
1864 ;;; Handles the resource-release aspects of stream closing, and marks
1866 (defun release-fd-stream-resources (fd-stream)
1869 ;; Drop handlers first.
1870 (when (fd-stream-handler fd-stream)
1871 (remove-fd-handler (fd-stream-handler fd-stream))
1872 (setf (fd-stream-handler fd-stream) nil))
1873 ;; Disable interrupts so that a asynch unwind will not leave
1874 ;; us with a dangling finalizer (that would close the same
1875 ;; --possibly reassigned-- FD again), or a stream with a closed
1876 ;; FD that appears open.
1877 (sb!unix:unix-close (fd-stream-fd fd-stream))
1878 (set-closed-flame fd-stream)
1879 (when (fboundp 'cancel-finalization)
1880 (cancel-finalization fd-stream)))
1881 ;; On error unwind from WITHOUT-INTERRUPTS.
1882 (serious-condition (e)
1884 ;; Release all buffers. If this is undone, or interrupted,
1885 ;; we're still safe: buffers have finalizers of their own.
1886 (release-fd-stream-buffers fd-stream))
1888 ;;; Flushes the current input buffer and any supplied replacements,
1889 ;;; and returns the input buffer, and the amount of of flushed input
1891 (defun flush-input-buffer (stream)
1892 (let ((unread (length (fd-stream-instead stream))))
1893 (setf (fill-pointer (fd-stream-instead stream)) 0)
1894 (let ((ibuf (fd-stream-ibuf stream)))
1896 (let ((head (buffer-head ibuf))
1897 (tail (buffer-tail ibuf)))
1898 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1899 (values nil unread)))))
1901 (defun fd-stream-clear-input (stream)
1902 (flush-input-buffer stream)
1905 (sb!win32:fd-clear-input (fd-stream-fd stream))
1906 (setf (fd-stream-listen stream) nil))
1908 (catch 'eof-input-catcher
1909 (loop until (sysread-may-block-p stream)
1911 (refill-input-buffer stream)
1912 (reset-buffer (fd-stream-ibuf stream)))
1915 ;;; Handle miscellaneous operations on FD-STREAM.
1916 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1917 (declare (ignore arg2))
1920 (labels ((do-listen ()
1921 (let ((ibuf (fd-stream-ibuf fd-stream)))
1922 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1923 (fd-stream-listen fd-stream)
1925 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1927 ;; If the read can block, LISTEN will certainly return NIL.
1928 (if (sysread-may-block-p fd-stream)
1930 ;; Otherwise select(2) and CL:LISTEN have slightly
1931 ;; different semantics. The former returns that an FD
1932 ;; is readable when a read operation wouldn't block.
1933 ;; That includes EOF. However, LISTEN must return NIL
1935 (progn (catch 'eof-input-catcher
1936 ;; r-b/f too calls select, but it shouldn't
1937 ;; block as long as read can return once w/o
1939 (refill-input-buffer fd-stream))
1940 ;; At this point either IBUF-HEAD != IBUF-TAIL
1941 ;; and FD-STREAM-LISTEN is NIL, in which case
1942 ;; we should return T, or IBUF-HEAD ==
1943 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1944 ;; which case we should return :EOF for this
1945 ;; call and all future LISTEN call on this stream.
1946 ;; Call ourselves again to determine which case
1951 (decf (buffer-head (fd-stream-ibuf fd-stream))
1952 (fd-stream-character-size fd-stream arg1)))
1954 ;; Drop input buffers
1955 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1956 (ansi-stream-cin-buffer fd-stream) nil
1957 (ansi-stream-in-buffer fd-stream) nil)
1959 ;; We got us an abort on our hands.
1960 (let ((outputp (fd-stream-obuf fd-stream))
1961 (file (fd-stream-file fd-stream))
1962 (orig (fd-stream-original fd-stream)))
1963 ;; This takes care of the important stuff -- everything
1964 ;; rest is cleaning up the file-system, which we cannot
1965 ;; do on some platforms as long as the file is open.
1966 (release-fd-stream-resources fd-stream)
1967 ;; We can't do anything unless we know what file were
1968 ;; dealing with, and we don't want to do anything
1969 ;; strange unless we were writing to the file.
1970 (when (and outputp file)
1972 ;; If the original is EQ to file we are appending to
1973 ;; and can just close the file without renaming.
1974 (unless (eq orig file)
1975 ;; We have a handle on the original, just revert.
1976 (multiple-value-bind (okay err)
1977 (sb!unix:unix-rename orig file)
1978 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1979 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1982 (error 'simple-stream-error
1984 "~@<Couldn't restore ~S to its original contents ~
1985 from ~S while closing ~S: ~2I~_~A~:>"
1987 (list file orig fd-stream (strerror err))
1988 :stream fd-stream))))
1989 ;; We can't restore the original, and aren't
1990 ;; appending, so nuke that puppy.
1992 ;; FIXME: This is currently the fate of superseded
1993 ;; files, and according to the CLOSE spec this is
1994 ;; wrong. However, there seems to be no clean way to
1995 ;; do that that doesn't involve either copying the
1996 ;; data (bad if the :abort resulted from a full
1997 ;; disk), or renaming the old file temporarily
1998 ;; (probably bad because stream opening becomes more
2000 (multiple-value-bind (okay err)
2001 (sb!unix:unix-unlink file)
2003 (error 'simple-file-error
2006 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2008 (list file fd-stream (strerror err)))))))))
2010 (finish-fd-stream-output fd-stream)
2011 (let ((orig (fd-stream-original fd-stream)))
2012 (when (and orig (fd-stream-delete-original fd-stream))
2013 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2015 (error 'simple-file-error
2018 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2020 (list orig fd-stream (strerror err)))))))
2021 ;; In case of no-abort close, don't *really* close the
2022 ;; stream until the last moment -- the cleaning up of the
2023 ;; original can be done first.
2024 (release-fd-stream-resources fd-stream))))
2026 (fd-stream-clear-input fd-stream))
2028 (flush-output-buffer fd-stream))
2030 (finish-fd-stream-output fd-stream))
2032 (fd-stream-element-type fd-stream))
2034 (fd-stream-external-format fd-stream))
2036 (= 1 (the (member 0 1)
2037 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2041 (fd-stream-char-pos fd-stream))
2043 (unless (fd-stream-file fd-stream)
2044 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2045 ;; "should signal an error of type TYPE-ERROR if stream is not
2046 ;; a stream associated with a file". Too bad there's no very
2047 ;; appropriate value for the EXPECTED-TYPE slot..
2048 (error 'simple-type-error
2050 :expected-type 'fd-stream
2051 :format-control "~S is not a stream associated with a file."
2052 :format-arguments (list fd-stream)))
2053 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2054 atime mtime ctime blksize blocks)
2055 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2056 (declare (ignore ino nlink uid gid rdev
2057 atime mtime ctime blksize blocks))
2059 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2062 (truncate size (fd-stream-element-size fd-stream)))))
2063 (:file-string-length
2065 (character (fd-stream-character-size fd-stream arg1))
2066 (string (fd-stream-string-size fd-stream arg1))))
2069 (fd-stream-set-file-position fd-stream arg1)
2070 (fd-stream-get-file-position fd-stream)))))
2072 ;; FIXME: Think about this.
2074 ;; (defun finish-fd-stream-output (fd-stream)
2075 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2076 ;; (loop while (fd-stream-output-queue fd-stream)
2077 ;; ;; FIXME: SIGINT while waiting for a timeout will
2078 ;; ;; cause a timeout here.
2079 ;; do (when (and (not (serve-event timeout)) timeout)
2080 ;; (signal-timeout 'io-timeout
2081 ;; :stream fd-stream
2082 ;; :direction :write
2083 ;; :seconds timeout)))))
2085 (defun finish-fd-stream-output (stream)
2086 (flush-output-buffer stream)
2088 ((null (fd-stream-output-queue stream)))
2089 (aver (fd-stream-serve-events stream))
2090 (serve-all-events)))
2092 (defun fd-stream-get-file-position (stream)
2093 (declare (fd-stream stream))
2095 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2096 (declare (type (or (alien sb!unix:off-t) null) posn))
2097 ;; We used to return NIL for errno==ESPIPE, and signal an error
2098 ;; in other failure cases. However, CLHS says to return NIL if
2099 ;; the position cannot be determined -- so that's what we do.
2100 (when (integerp posn)
2101 ;; Adjust for buffered output: If there is any output
2102 ;; buffered, the *real* file position will be larger
2103 ;; than reported by lseek() because lseek() obviously
2104 ;; cannot take into account output we have not sent
2106 (dolist (buffer (fd-stream-output-queue stream))
2107 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2108 (let ((obuf (fd-stream-obuf stream)))
2110 (incf posn (buffer-tail obuf))))
2111 ;; Adjust for unread input: If there is any input
2112 ;; read from UNIX but not supplied to the user of the
2113 ;; stream, the *real* file position will smaller than
2114 ;; reported, because we want to look like the unread
2115 ;; stuff is still available.
2116 (let ((ibuf (fd-stream-ibuf stream)))
2118 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2119 ;; Divide bytes by element size.
2120 (truncate posn (fd-stream-element-size stream))))))
2122 (defun fd-stream-set-file-position (stream position-spec)
2123 (declare (fd-stream stream))
2124 (check-type position-spec
2125 (or (alien sb!unix:off-t) (member nil :start :end))
2126 "valid file position designator")
2129 ;; Make sure we don't have any output pending, because if we
2130 ;; move the file pointer before writing this stuff, it will be
2131 ;; written in the wrong location.
2132 (finish-fd-stream-output stream)
2133 ;; Disable interrupts so that interrupt handlers doing output
2136 (unless (fd-stream-output-finished-p stream)
2137 ;; We got interrupted and more output came our way during
2138 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2139 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2140 ;; so we prefer to do things like this...
2142 ;; Clear out any pending input to force the next read to go to
2144 (flush-input-buffer stream)
2145 ;; Trash cached value for listen, so that we check next time.
2146 (setf (fd-stream-listen stream) nil)
2148 (multiple-value-bind (offset origin)
2151 (values 0 sb!unix:l_set))
2153 (values 0 sb!unix:l_xtnd))
2155 (values (* position-spec (fd-stream-element-size stream))
2157 (declare (type (alien sb!unix:off-t) offset))
2158 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2160 ;; CLHS says to return true if the file-position was set
2161 ;; succesfully, and NIL otherwise. We are to signal an error
2162 ;; only if the given position was out of bounds, and that is
2163 ;; dealt with above. In times past we used to return NIL for
2164 ;; errno==ESPIPE, and signal an error in other cases.
2166 ;; FIXME: We are still liable to signal an error if flushing
2168 (return-from fd-stream-set-file-position
2169 (typep posn '(alien sb!unix:off-t))))))))
2172 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2174 ;;; Create a stream for the given Unix file descriptor.
2176 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2177 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2178 ;;; default to allowing input.
2180 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2182 ;;; BUFFERING indicates the kind of buffering to use.
2184 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2185 ;;; NIL (the default), then wait forever. When we time out, we signal
2188 ;;; FILE is the name of the file (will be returned by PATHNAME).
2190 ;;; NAME is used to identify the stream when printed.
2192 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2193 ;;; handle blocking IO on the stream.
2194 (defun make-fd-stream (fd
2197 (output nil output-p)
2198 (element-type 'base-char)
2200 (external-format :default)
2210 (format nil "file ~A" file)
2211 (format nil "descriptor ~W" fd)))
2213 (declare (type index fd) (type (or real null) timeout)
2214 (type (member :none :line :full) buffering))
2215 (cond ((not (or input-p output-p))
2217 ((not (or input output))
2218 (error "File descriptor must be opened either for input or output.")))
2219 (let ((stream (%make-fd-stream :fd fd
2223 :delete-original delete-original
2225 :buffering buffering
2226 :dual-channel-p dual-channel-p
2227 :bivalent-p (eq element-type :default)
2228 :serve-events serve-events
2231 (coerce timeout 'single-float)
2233 (set-fd-stream-routines stream element-type external-format
2234 input output input-buffer-p)
2235 (when (and auto-close (fboundp 'finalize))
2238 (sb!unix:unix-close fd)
2240 (format *terminal-io* "** closed file descriptor ~W **~%"
2245 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2246 ;;; :RENAME-AND-DELETE and :RENAME options.
2247 (defun pick-backup-name (name)
2248 (declare (type simple-string name))
2249 (concatenate 'simple-string name ".bak"))
2251 ;;; Ensure that the given arg is one of the given list of valid
2252 ;;; things. Allow the user to fix any problems.
2253 (defun ensure-one-of (item list what)
2254 (unless (member item list)
2255 (error 'simple-type-error
2257 :expected-type `(member ,@list)
2258 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2259 :format-arguments (list item what list))))
2261 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2262 ;;; access, since we don't want to trash unwritable files even if we
2263 ;;; technically can. We return true if we succeed in renaming.
2264 (defun rename-the-old-one (namestring original)
2265 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2266 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2267 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2270 (error 'simple-file-error
2271 :pathname namestring
2273 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2274 :format-arguments (list namestring original (strerror err))))))
2276 (defun open (filename
2279 (element-type 'base-char)
2280 (if-exists nil if-exists-given)
2281 (if-does-not-exist nil if-does-not-exist-given)
2282 (external-format :default)
2283 &aux ; Squelch assignment warning.
2284 (direction direction)
2285 (if-does-not-exist if-does-not-exist)
2286 (if-exists if-exists))
2288 "Return a stream which reads from or writes to FILENAME.
2290 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2291 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2292 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2293 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2294 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2295 See the manual for details."
2297 ;; Calculate useful stuff.
2298 (multiple-value-bind (input output mask)
2300 (:input (values t nil sb!unix:o_rdonly))
2301 (:output (values nil t sb!unix:o_wronly))
2302 (:io (values t t sb!unix:o_rdwr))
2303 (:probe (values t nil sb!unix:o_rdonly)))
2304 (declare (type index mask))
2305 (let* (;; PATHNAME is the pathname we associate with the stream.
2306 (pathname (merge-pathnames filename))
2307 (physical (physicalize-pathname pathname))
2308 (truename (probe-file physical))
2309 ;; NAMESTRING is the native namestring we open the file with.
2310 (namestring (cond (truename
2311 (native-namestring truename :as-file t))
2313 (and input (eq if-does-not-exist :create))
2314 (and (eq direction :io) (not if-does-not-exist-given)))
2315 (native-namestring physical :as-file t)))))
2316 ;; Process if-exists argument if we are doing any output.
2318 (unless if-exists-given
2320 (if (eq (pathname-version pathname) :newest)
2323 (ensure-one-of if-exists
2324 '(:error :new-version :rename
2325 :rename-and-delete :overwrite
2326 :append :supersede nil)
2329 ((:new-version :error nil)
2330 (setf mask (logior mask sb!unix:o_excl)))
2331 ((:rename :rename-and-delete)
2332 (setf mask (logior mask sb!unix:o_creat)))
2334 (setf mask (logior mask sb!unix:o_trunc)))
2336 (setf mask (logior mask sb!unix:o_append)))))
2338 (setf if-exists :ignore-this-arg)))
2340 (unless if-does-not-exist-given
2341 (setf if-does-not-exist
2342 (cond ((eq direction :input) :error)
2344 (member if-exists '(:overwrite :append)))
2346 ((eq direction :probe)
2350 (ensure-one-of if-does-not-exist
2351 '(:error :create nil)
2353 (if (eq if-does-not-exist :create)
2354 (setf mask (logior mask sb!unix:o_creat)))
2356 (let ((original (case if-exists
2357 ((:rename :rename-and-delete)
2358 (pick-backup-name namestring))
2359 ((:append :overwrite)
2360 ;; KLUDGE: Provent CLOSE from deleting
2361 ;; appending streams when called with :ABORT T
2363 (delete-original (eq if-exists :rename-and-delete))
2365 (when (and original (not (eq original namestring)))
2366 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2367 ;; whether the file already exists, make sure the original
2368 ;; file is not a directory, and keep the mode.
2371 (multiple-value-bind (okay err/dev inode orig-mode)
2372 (sb!unix:unix-stat namestring)
2373 (declare (ignore inode)
2374 (type (or index null) orig-mode))
2377 (when (and output (= (logand orig-mode #o170000)
2379 (error 'simple-file-error
2382 "can't open ~S for output: is a directory"
2383 :format-arguments (list namestring)))
2384 (setf mode (logand orig-mode #o777))
2386 ((eql err/dev sb!unix:enoent)
2389 (simple-file-perror "can't find ~S"
2393 (rename-the-old-one namestring original))
2395 (setf delete-original nil)
2396 ;; In order to use :SUPERSEDE instead, we have to make
2397 ;; sure SB!UNIX:O_CREAT corresponds to
2398 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2399 ;; because of IF-EXISTS being :RENAME.
2400 (unless (eq if-does-not-exist :create)
2402 (logior (logandc2 mask sb!unix:o_creat)
2404 (setf if-exists :supersede))))
2406 ;; Now we can try the actual Unix open(2).
2407 (multiple-value-bind (fd errno)
2409 (sb!unix:unix-open namestring mask mode)
2410 (values nil sb!unix:enoent))
2411 (labels ((open-error (format-control &rest format-arguments)
2412 (error 'simple-file-error
2414 :format-control format-control
2415 :format-arguments format-arguments))
2416 (vanilla-open-error ()
2417 (simple-file-perror "error opening ~S" pathname errno)))
2420 ((:input :output :io)
2424 :element-type element-type
2425 :external-format external-format
2428 :delete-original delete-original
2436 (%make-fd-stream :name namestring
2439 :element-type element-type)))
2442 ((eql errno sb!unix:enoent)
2443 (case if-does-not-exist
2444 (:error (vanilla-open-error))
2446 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2449 ((and (eql errno sb!unix:eexist) (null if-exists))
2452 (vanilla-open-error)))))))))
2456 ;;; the stream connected to the controlling terminal, or NIL if there is none
2459 ;;; the stream connected to the standard input (file descriptor 0)
2462 ;;; the stream connected to the standard output (file descriptor 1)
2465 ;;; the stream connected to the standard error output (file descriptor 2)
2468 ;;; This is called when the cold load is first started up, and may also
2469 ;;; be called in an attempt to recover from nested errors.
2470 (defun stream-cold-init-or-reset ()
2472 (setf *terminal-io* (make-synonym-stream '*tty*))
2473 (setf *standard-output* (make-synonym-stream '*stdout*))
2474 (setf *standard-input* (make-synonym-stream '*stdin*))
2475 (setf *error-output* (make-synonym-stream '*stderr*))
2476 (setf *query-io* (make-synonym-stream '*terminal-io*))
2477 (setf *debug-io* *query-io*)
2478 (setf *trace-output* *standard-output*)
2481 (defun stream-deinit ()
2482 ;; Unbind to make sure we're not accidently dealing with it
2483 ;; before we're ready (or after we think it's been deinitialized).
2484 (with-available-buffers-lock ()
2485 (without-package-locks
2486 (makunbound '*available-buffers*))))
2488 (defun stdstream-external-format (outputp)
2489 (declare (ignorable outputp))
2490 (let* ((keyword #!+win32 (if outputp (sb!win32::console-output-codepage) (sb!win32::console-input-codepage))
2491 #!-win32 (default-external-format))
2492 (ef (get-external-format keyword))
2493 (replacement (ef-default-replacement-character ef)))
2494 `(,keyword :replacement ,replacement)))
2496 ;;; This is called whenever a saved core is restarted.
2497 (defun stream-reinit (&optional init-buffers-p)
2498 (when init-buffers-p
2499 (with-available-buffers-lock ()
2500 (aver (not (boundp '*available-buffers*)))
2501 (setf *available-buffers* nil)))
2502 (with-output-to-string (*error-output*)
2504 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2505 :element-type :default
2507 :external-format (stdstream-external-format nil)))
2509 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2510 :element-type :default
2511 :external-format (stdstream-external-format t)))
2513 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2514 :element-type :default
2515 :external-format (stdstream-external-format t)))
2516 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2517 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2520 (make-fd-stream tty :name "the terminal"
2521 :input t :output t :buffering :line
2522 :external-format (stdstream-external-format t)
2525 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2526 (princ (get-output-stream-string *error-output*) *stderr*))
2531 ;;; the Unix way to beep
2532 (defun beep (stream)
2533 (write-char (code-char bell-char-code) stream)
2534 (finish-output stream))
2536 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2537 ;;; by the filesys stuff to get and set the file name.
2539 ;;; FIXME: misleading name, screwy interface
2540 (defun file-name (stream &optional new-name)
2541 (when (typep stream 'fd-stream)
2543 (setf (fd-stream-pathname stream) new-name)
2544 (setf (fd-stream-file stream)
2545 (native-namestring (physicalize-pathname new-name)
2549 (fd-stream-pathname stream)))))