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")
14 ;;;; buffer manipulation routines
16 ;;; FIXME: Is it really good to maintain this pool separate from the
17 ;;; GC and the C malloc logic?
18 (defvar *available-buffers* ()
20 "List of available buffers. Each buffer is an sap pointing to
21 bytes-per-buffer of memory.")
23 (defconstant bytes-per-buffer (* 4 1024)
25 "Number of bytes per buffer.")
27 ;;; Return the next available buffer, creating one if necessary.
28 #!-sb-fluid (declaim (inline next-available-buffer))
29 (defun next-available-buffer ()
30 (if *available-buffers*
31 (pop *available-buffers*)
32 (allocate-system-memory bytes-per-buffer)))
34 ;;;; the FILE-STREAM structure
36 (defstruct (file-stream
37 (:constructor %make-fd-stream)
38 ;; KLUDGE: in an ideal world, maybe we'd rewrite
39 ;; everything to use FILE-STREAM rather than simply
40 ;; providing this hack for compatibility with the old
41 ;; code. However, CVS doesn't deal terribly well with
42 ;; file renaming, so for now we use this
43 ;; backward-compatibility feature.
44 (:conc-name fd-stream-)
45 (:predicate fd-stream-p)
47 (misc #'fd-stream-misc-routine))
50 ;; the name of this stream
52 ;; the file this stream is for
54 ;; the backup file namestring for the old file, for :IF-EXISTS
55 ;; :RENAME or :RENAME-AND-DELETE.
56 (original nil :type (or simple-string null))
57 (delete-original nil) ; for :if-exists :rename-and-delete
58 ;;; the number of bytes per element
59 (element-size 1 :type index)
60 ;; the type of element being transfered
61 (element-type 'base-char)
62 ;; the Unix file descriptor
64 ;; controls when the output buffer is flushed
65 (buffering :full :type (member :full :line :none))
66 ;; character position (if known)
67 (char-pos nil :type (or index null))
68 ;; T if input is waiting on FD. :EOF if we hit EOF.
69 (listen nil :type (member nil t :eof))
73 (ibuf-sap nil :type (or system-area-pointer null))
74 (ibuf-length nil :type (or index null))
75 (ibuf-head 0 :type index)
76 (ibuf-tail 0 :type index)
79 (obuf-sap nil :type (or system-area-pointer null))
80 (obuf-length nil :type (or index null))
81 (obuf-tail 0 :type index)
83 ;; output flushed, but not written due to non-blocking io?
86 ;; timeout specified for this stream, or NIL if none
87 (timeout nil :type (or index null))
88 ;; pathname of the file this stream is opened to (returned by PATHNAME)
89 (pathname nil :type (or pathname null)))
90 (def!method print-object ((fd-stream file-stream) stream)
91 (declare (type stream stream))
92 (print-unreadable-object (fd-stream stream :type t :identity t)
93 (format stream "for ~S" (fd-stream-name fd-stream))))
95 ;;;; output routines and related noise
97 (defvar *output-routines* ()
99 "List of all available output routines. Each element is a list of the
100 element-type output, the kind of buffering, the function name, and the number
101 of bytes per element.")
103 ;;; common idioms for reporting low-level stream and file problems
104 (defun simple-stream-perror (note-format stream errno)
105 (error 'simple-stream-error
107 :format-control "~@<~?: ~2I~_~A~:>"
108 :format-arguments (list note-format (list stream) (strerror errno))))
109 (defun simple-file-perror (note-format pathname errno)
110 (error 'simple-file-error
112 :format-control "~@<~?: ~2I~_~A~:>"
114 (list note-format (list pathname) (strerror errno))))
116 ;;; This is called by the server when we can write to the given file
117 ;;; descriptor. Attempt to write the data again. If it worked, remove
118 ;;; the data from the OUTPUT-LATER list. If it didn't work, something
120 (defun frob-output-later (stream)
121 (let* ((stuff (pop (fd-stream-output-later stream)))
125 (reuse-sap (cadddr stuff))
126 (length (- end start)))
127 (declare (type index start end length))
128 (multiple-value-bind (count errno)
129 (sb!unix:unix-write (fd-stream-fd stream)
134 (if (= errno sb!unix:ewouldblock)
135 (error "Write would have blocked, but SERVER told us to go.")
136 (simple-stream-perror "couldn't write to ~S" stream errno)))
137 ((eql count length) ; Hot damn, it worked.
139 (push base *available-buffers*)))
140 ((not (null count)) ; sorta worked..
142 (the index (+ start count))
144 (fd-stream-output-later stream))))))
145 (unless (fd-stream-output-later stream)
146 (sb!sys:remove-fd-handler (fd-stream-handler stream))
147 (setf (fd-stream-handler stream) nil)))
149 ;;; Arange to output the string when we can write on the file descriptor.
150 (defun output-later (stream base start end reuse-sap)
151 (cond ((null (fd-stream-output-later stream))
152 (setf (fd-stream-output-later stream)
153 (list (list base start end reuse-sap)))
154 (setf (fd-stream-handler stream)
155 (sb!sys:add-fd-handler (fd-stream-fd stream)
158 (declare (ignore fd))
159 (frob-output-later stream)))))
161 (nconc (fd-stream-output-later stream)
162 (list (list base start end reuse-sap)))))
164 (let ((new-buffer (next-available-buffer)))
165 (setf (fd-stream-obuf-sap stream) new-buffer)
166 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
168 ;;; Output the given noise. Check to see whether there are any pending
169 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
170 ;;; this would block, queue it.
171 (defun frob-output (stream base start end reuse-sap)
172 (declare (type file-stream stream)
173 (type (or system-area-pointer (simple-array * (*))) base)
174 (type index start end))
175 (if (not (null (fd-stream-output-later stream))) ; something buffered.
177 (output-later stream base start end reuse-sap)
178 ;; ### check to see whether any of this noise can be output
180 (let ((length (- end start)))
181 (multiple-value-bind (count errno)
182 (sb!unix:unix-write (fd-stream-fd stream) base start length)
184 (if (= errno sb!unix:ewouldblock)
185 (output-later stream base start end reuse-sap)
186 (simple-stream-perror "couldn't write to ~S"
189 ((not (eql count length))
190 (output-later stream base (the index (+ start count))
193 ;;; Flush any data in the output buffer.
194 (defun flush-output-buffer (stream)
195 (let ((length (fd-stream-obuf-tail stream)))
197 (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
198 (setf (fd-stream-obuf-tail stream) 0))))
200 ;;; Define output routines that output numbers SIZE bytes long for the
201 ;;; given bufferings. Use BODY to do the actual output.
202 (defmacro def-output-routines ((name-fmt size &rest bufferings) &body body)
203 (declare (optimize (speed 1)))
208 (intern (let ((*print-case* :upcase))
209 (format nil name-fmt (car buffering))))))
211 (defun ,function (stream byte)
212 ,(unless (eq (car buffering) :none)
213 `(when (< (fd-stream-obuf-length stream)
214 (+ (fd-stream-obuf-tail stream)
216 (flush-output-buffer stream)))
218 (incf (fd-stream-obuf-tail stream) ,size)
219 ,(ecase (car buffering)
221 `(flush-output-buffer stream))
223 `(when (eq (char-code byte) (char-code #\Newline))
224 (flush-output-buffer stream)))
228 (setf *output-routines*
229 (nconc *output-routines*
236 (cdr buffering)))))))
239 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
244 (if (and (base-char-p byte) (char= byte #\Newline))
245 (setf (fd-stream-char-pos stream) 0)
246 (incf (fd-stream-char-pos stream)))
247 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
250 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
252 (:none (unsigned-byte 8))
253 (:full (unsigned-byte 8)))
254 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
257 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
259 (:none (signed-byte 8))
260 (:full (signed-byte 8)))
261 (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
262 (fd-stream-obuf-tail stream))
265 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
267 (:none (unsigned-byte 16))
268 (:full (unsigned-byte 16)))
269 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
272 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
274 (:none (signed-byte 16))
275 (:full (signed-byte 16)))
276 (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
277 (fd-stream-obuf-tail stream))
280 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
282 (:none (unsigned-byte 32))
283 (:full (unsigned-byte 32)))
284 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
287 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
289 (:none (signed-byte 32))
290 (:full (signed-byte 32)))
291 (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
292 (fd-stream-obuf-tail stream))
295 ;;; Do the actual output. If there is space to buffer the string,
296 ;;; buffer it. If the string would normally fit in the buffer, but
297 ;;; doesn't because of other stuff in the buffer, flush the old noise
298 ;;; out of the buffer and put the string in it. Otherwise we have a
299 ;;; very long string, so just send it directly (after flushing the
300 ;;; buffer, of course).
301 (defun output-raw-bytes (fd-stream thing &optional start end)
303 "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
304 THING is a SAP, END must be supplied (as length won't work)."
305 (let ((start (or start 0))
306 (end (or end (length (the (simple-array * (*)) thing)))))
307 (declare (type index start end))
308 (let* ((len (fd-stream-obuf-length fd-stream))
309 (tail (fd-stream-obuf-tail fd-stream))
311 (bytes (- end start))
312 (newtail (+ tail bytes)))
313 (cond ((minusp bytes) ; error case
314 (error ":END before :START!"))
315 ((zerop bytes)) ; easy case
317 (if (system-area-pointer-p thing)
318 (system-area-copy thing
319 (* start sb!vm:n-byte-bits)
320 (fd-stream-obuf-sap fd-stream)
321 (* tail sb!vm:n-byte-bits)
322 (* bytes sb!vm:n-byte-bits))
323 ;; FIXME: There should be some type checking somewhere to
324 ;; verify that THING here is a vector, not just <not a SAP>.
325 (copy-to-system-area thing
326 (+ (* start sb!vm:n-byte-bits)
327 (* sb!vm:vector-data-offset
329 (fd-stream-obuf-sap fd-stream)
330 (* tail sb!vm:n-byte-bits)
331 (* bytes sb!vm:n-byte-bits)))
332 (setf (fd-stream-obuf-tail fd-stream) newtail))
334 (flush-output-buffer fd-stream)
335 (if (system-area-pointer-p thing)
336 (system-area-copy thing
337 (* start sb!vm:n-byte-bits)
338 (fd-stream-obuf-sap fd-stream)
340 (* bytes sb!vm:n-byte-bits))
341 ;; FIXME: There should be some type checking somewhere to
342 ;; verify that THING here is a vector, not just <not a SAP>.
343 (copy-to-system-area thing
344 (+ (* start sb!vm:n-byte-bits)
345 (* sb!vm:vector-data-offset
347 (fd-stream-obuf-sap fd-stream)
349 (* bytes sb!vm:n-byte-bits)))
350 (setf (fd-stream-obuf-tail fd-stream) bytes))
352 (flush-output-buffer fd-stream)
353 (frob-output fd-stream thing start end nil))))))
355 ;;; the routine to use to output a string. If the stream is
356 ;;; unbuffered, slam the string down the file descriptor, otherwise
357 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
358 ;;; checking to see where the last newline was.
360 ;;; Note: some bozos (the FASL dumper) call write-string with things
361 ;;; other than strings. Therefore, we must make sure we have a string
362 ;;; before calling POSITION on it.
363 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
364 ;;; cover for them here. -- WHN 20000203
365 (defun fd-sout (stream thing start end)
366 (let ((start (or start 0))
367 (end (or end (length (the vector thing)))))
368 (declare (fixnum start end))
370 (let ((last-newline (and (find #\newline (the simple-string thing)
371 :start start :end end)
372 ;; FIXME why do we need both calls?
373 ;; Is find faster forwards than
374 ;; position is backwards?
375 (position #\newline (the simple-string thing)
379 (ecase (fd-stream-buffering stream)
381 (output-raw-bytes stream thing start end))
383 (output-raw-bytes stream thing start end)
385 (flush-output-buffer stream)))
387 (frob-output stream thing start end nil)))
389 (setf (fd-stream-char-pos stream)
390 (- end last-newline 1))
391 (incf (fd-stream-char-pos stream)
393 (ecase (fd-stream-buffering stream)
395 (output-raw-bytes stream thing start end))
397 (frob-output stream thing start end nil))))))
399 ;;; Find an output routine to use given the type and buffering. Return
400 ;;; as multiple values the routine, the real type transfered, and the
401 ;;; number of bytes per element.
402 (defun pick-output-routine (type buffering)
403 (dolist (entry *output-routines*)
404 (when (and (subtypep type (car entry))
405 (eq buffering (cadr entry)))
406 (return (values (symbol-function (caddr entry))
410 ;;;; input routines and related noise
412 ;;; a list of all available input routines. Each element is a list of
413 ;;; the element-type input, the function name, and the number of bytes
415 (defvar *input-routines* ())
417 ;;; Fill the input buffer, and return the first character. Throw to
418 ;;; EOF-INPUT-CATCHER if the eof was reached. Drop into SYSTEM:SERVER
420 (defun frob-input (stream)
421 (let ((fd (fd-stream-fd stream))
422 (ibuf-sap (fd-stream-ibuf-sap stream))
423 (buflen (fd-stream-ibuf-length stream))
424 (head (fd-stream-ibuf-head stream))
425 (tail (fd-stream-ibuf-tail stream)))
426 (declare (type index head tail))
428 (cond ((eql head tail)
431 (setf (fd-stream-ibuf-head stream) 0)
432 (setf (fd-stream-ibuf-tail stream) 0))
435 (system-area-copy ibuf-sap (* head sb!vm:n-byte-bits)
436 ibuf-sap 0 (* tail sb!vm:n-byte-bits))
438 (setf (fd-stream-ibuf-head stream) 0)
439 (setf (fd-stream-ibuf-tail stream) tail))))
440 (setf (fd-stream-listen stream) nil)
441 (multiple-value-bind (count errno)
442 ;; FIXME: Judging from compiler warnings, this WITH-ALIEN form expands
443 ;; into something which uses the not-yet-defined type
444 ;; (SB!ALIEN-INTERNALS:ALIEN (* (SB!ALIEN:STRUCT SB!UNIX:FD-SET))).
445 ;; This is probably inefficient and unsafe and generally bad, so
446 ;; try to find some way to make that type known before
448 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
449 (sb!unix:fd-zero read-fds)
450 (sb!unix:fd-set fd read-fds)
451 (sb!unix:unix-fast-select (1+ fd)
452 (sb!alien:addr read-fds)
460 (unless (sb!sys:wait-until-fd-usable
461 fd :input (fd-stream-timeout stream))
462 (error 'io-timeout :stream stream :direction :read)))
464 (simple-stream-perror "couldn't check whether ~S is readable"
467 (multiple-value-bind (count errno)
468 (sb!unix:unix-read fd
469 (sb!sys:int-sap (+ (sb!sys:sap-int ibuf-sap) tail))
472 (if (eql errno sb!unix:ewouldblock)
474 (unless (sb!sys:wait-until-fd-usable
475 fd :input (fd-stream-timeout stream))
476 (error 'io-timeout :stream stream :direction :read))
478 (simple-stream-perror "couldn't read from ~S" stream errno)))
480 (setf (fd-stream-listen stream) :eof)
481 (/show0 "THROWing EOF-INPUT-CATCHER")
482 (throw 'eof-input-catcher nil))
484 (incf (fd-stream-ibuf-tail stream) count))))))
486 ;;; Make sure there are at least BYTES number of bytes in the input
487 ;;; buffer. Keep calling FROB-INPUT until that condition is met.
488 (defmacro input-at-least (stream bytes)
489 (let ((stream-var (gensym))
490 (bytes-var (gensym)))
491 `(let ((,stream-var ,stream)
494 (when (>= (- (fd-stream-ibuf-tail ,stream-var)
495 (fd-stream-ibuf-head ,stream-var))
498 (frob-input ,stream-var)))))
500 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
501 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
502 (let ((stream-var (gensym))
503 (element-var (gensym)))
504 `(let ((,stream-var ,stream))
505 (if (fd-stream-unread ,stream-var)
507 (fd-stream-unread ,stream-var)
508 (setf (fd-stream-unread ,stream-var) nil)
509 (setf (fd-stream-listen ,stream-var) nil))
511 (catch 'eof-input-catcher
512 (input-at-least ,stream-var ,bytes)
515 (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
518 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
520 (defmacro def-input-routine (name
524 (defun ,name (stream eof-error eof-value)
525 (input-wrapper (stream ,size eof-error eof-value)
526 (let ((,sap (fd-stream-ibuf-sap stream))
527 (,head (fd-stream-ibuf-head stream)))
529 (setf *input-routines*
530 (nconc *input-routines*
531 (list (list ',type ',name ',size))))))
533 ;;; STREAM-IN routine for reading a string char
534 (def-input-routine input-character
535 (character 1 sap head)
536 (code-char (sap-ref-8 sap head)))
538 ;;; STREAM-IN routine for reading an unsigned 8 bit number
539 (def-input-routine input-unsigned-8bit-byte
540 ((unsigned-byte 8) 1 sap head)
541 (sap-ref-8 sap head))
543 ;;; STREAM-IN routine for reading a signed 8 bit number
544 (def-input-routine input-signed-8bit-number
545 ((signed-byte 8) 1 sap head)
546 (signed-sap-ref-8 sap head))
548 ;;; STREAM-IN routine for reading an unsigned 16 bit number
549 (def-input-routine input-unsigned-16bit-byte
550 ((unsigned-byte 16) 2 sap head)
551 (sap-ref-16 sap head))
553 ;;; STREAM-IN routine for reading a signed 16 bit number
554 (def-input-routine input-signed-16bit-byte
555 ((signed-byte 16) 2 sap head)
556 (signed-sap-ref-16 sap head))
558 ;;; STREAM-IN routine for reading a unsigned 32 bit number
559 (def-input-routine input-unsigned-32bit-byte
560 ((unsigned-byte 32) 4 sap head)
561 (sap-ref-32 sap head))
563 ;;; STREAM-IN routine for reading a signed 32 bit number
564 (def-input-routine input-signed-32bit-byte
565 ((signed-byte 32) 4 sap head)
566 (signed-sap-ref-32 sap head))
568 ;;; Find an input routine to use given the type. Return as multiple
569 ;;; values the routine, the real type transfered, and the number of
570 ;;; bytes per element.
571 (defun pick-input-routine (type)
572 (dolist (entry *input-routines*)
573 (when (subtypep type (car entry))
574 (return (values (symbol-function (cadr entry))
578 ;;; Return a string constructed from SAP, START, and END.
579 (defun string-from-sap (sap start end)
580 (declare (type index start end))
581 (let* ((length (- end start))
582 (string (make-string length)))
583 (copy-from-system-area sap (* start sb!vm:n-byte-bits)
584 string (* sb!vm:vector-data-offset
586 (* length sb!vm:n-byte-bits))
589 ;;; the N-BIN method for FD-STREAMs
591 ;;; Note that this blocks in UNIX-READ. It is generally used where
592 ;;; there is a definite amount of reading to be done, so blocking
593 ;;; isn't too problematical.
594 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
595 &aux (total-copied 0))
596 (declare (type file-stream stream))
597 (declare (type index start requested total-copied))
598 (let ((unread (fd-stream-unread stream)))
600 ;; AVERs designed to fail when we have more complicated
601 ;; character representations.
602 (aver (typep unread 'base-char))
603 (aver (= (fd-stream-element-size stream) 1))
604 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
608 (setf (sap-ref-8 buffer start) (char-code unread)))
609 ((simple-unboxed-array (*))
610 (setf (aref buffer start) unread)))
611 (setf (fd-stream-unread stream) nil)
612 (setf (fd-stream-listen stream) nil)
613 (incf total-copied)))
616 (let* ((remaining-request (- requested total-copied))
617 (head (fd-stream-ibuf-head stream))
618 (tail (fd-stream-ibuf-tail stream))
619 (available (- tail head))
620 (n-this-copy (min remaining-request available))
621 (this-start (+ start total-copied))
622 (this-end (+ this-start n-this-copy))
623 (sap (fd-stream-ibuf-sap stream)))
624 (declare (type index remaining-request head tail available))
625 (declare (type index n-this-copy))
626 ;; Copy data from stream buffer into user's buffer.
627 (%byte-blt sap head buffer this-start this-end)
628 (incf (fd-stream-ibuf-head stream) n-this-copy)
629 (incf total-copied n-this-copy)
630 ;; Maybe we need to refill the stream buffer.
631 (cond (;; If there were enough data in the stream buffer, we're done.
632 (= total-copied requested)
633 (return total-copied))
634 (;; If EOF, we're done in another way.
635 (zerop (refill-fd-stream-buffer stream))
637 (error 'end-of-file :stream stream)
638 (return total-copied)))
639 ;; Otherwise we refilled the stream buffer, so fall
640 ;; through into another pass of the loop.
643 ;;; Try to refill the stream buffer. Return the number of bytes read.
644 ;;; (For EOF, the return value will be zero, otherwise positive.)
645 (defun refill-fd-stream-buffer (stream)
646 ;; We don't have any logic to preserve leftover bytes in the buffer,
647 ;; so we should only be called when the buffer is empty.
648 (aver (= (fd-stream-ibuf-head stream) (fd-stream-ibuf-tail stream)))
649 (multiple-value-bind (count err)
650 (sb!unix:unix-read (fd-stream-fd stream)
651 (fd-stream-ibuf-sap stream)
652 (fd-stream-ibuf-length stream))
653 (declare (type (or index null) count))
655 (simple-stream-perror "couldn't read from ~S" stream err))
656 (setf (fd-stream-listen stream) nil
657 (fd-stream-ibuf-head stream) 0
658 (fd-stream-ibuf-tail stream) count)
661 ;;;; utility functions (misc routines, etc)
663 ;;; Fill in the various routine slots for the given type. INPUT-P and
664 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
665 ;;; set prior to calling this routine.
666 (defun set-fd-stream-routines (fd-stream type input-p output-p buffer-p)
667 (let ((target-type (case type
668 ((:default unsigned-byte)
679 (when (fd-stream-obuf-sap fd-stream)
680 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
681 (setf (fd-stream-obuf-sap fd-stream) nil))
682 (when (fd-stream-ibuf-sap fd-stream)
683 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
684 (setf (fd-stream-ibuf-sap fd-stream) nil))
687 (multiple-value-bind (routine type size)
688 (pick-input-routine target-type)
690 (error "could not find any input routine for ~S" target-type))
691 (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
692 (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
693 (setf (fd-stream-ibuf-tail fd-stream) 0)
694 (if (subtypep type 'character)
695 (setf (fd-stream-in fd-stream) routine
696 (fd-stream-bin fd-stream) #'ill-bin)
697 (setf (fd-stream-in fd-stream) #'ill-in
698 (fd-stream-bin fd-stream) routine))
700 (setf (fd-stream-n-bin fd-stream) #'fd-stream-read-n-bytes)
702 ;; We only create this buffer for streams of type
703 ;; (unsigned-byte 8). Because there's no buffer, the
704 ;; other element-types will dispatch to the appropriate
705 ;; input (output) routine in fast-read-byte.
706 (equal target-type '(unsigned-byte 8))
708 (or (eq type 'unsigned-byte)
710 (setf (ansi-stream-in-buffer fd-stream)
711 (make-array +ansi-stream-in-buffer-length+
712 :element-type '(unsigned-byte 8)))))
713 (setf input-size size)
714 (setf input-type type)))
717 (multiple-value-bind (routine type size)
718 (pick-output-routine target-type (fd-stream-buffering fd-stream))
720 (error "could not find any output routine for ~S buffered ~S"
721 (fd-stream-buffering fd-stream)
723 (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
724 (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
725 (setf (fd-stream-obuf-tail fd-stream) 0)
726 (if (subtypep type 'character)
727 (setf (fd-stream-out fd-stream) routine
728 (fd-stream-bout fd-stream) #'ill-bout)
729 (setf (fd-stream-out fd-stream)
731 (pick-output-routine 'base-char
732 (fd-stream-buffering fd-stream)))
734 (fd-stream-bout fd-stream) routine))
735 (setf (fd-stream-sout fd-stream)
736 (if (eql size 1) #'fd-sout #'ill-out))
737 (setf (fd-stream-char-pos fd-stream) 0)
738 (setf output-size size)
739 (setf output-type type)))
741 (when (and input-size output-size
742 (not (eq input-size output-size)))
743 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
744 input-type input-size
745 output-type output-size))
746 (setf (fd-stream-element-size fd-stream)
747 (or input-size output-size))
749 (setf (fd-stream-element-type fd-stream)
750 (cond ((equal input-type output-type)
756 ((subtypep input-type output-type)
758 ((subtypep output-type input-type)
761 (error "Input type (~S) and output type (~S) are unrelated?"
765 ;;; Handle miscellaneous operations on FD-STREAM.
766 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
767 (declare (ignore arg2))
770 (or (not (eql (fd-stream-ibuf-head fd-stream)
771 (fd-stream-ibuf-tail fd-stream)))
772 (fd-stream-listen fd-stream)
773 (setf (fd-stream-listen fd-stream)
774 (eql (sb!alien:with-alien ((read-fds (sb!alien:struct
776 (sb!unix:fd-zero read-fds)
777 (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
778 (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
779 (sb!alien:addr read-fds)
783 (setf (fd-stream-unread fd-stream) arg1)
784 (setf (fd-stream-listen fd-stream) t))
787 ;; We got us an abort on our hands.
788 (when (fd-stream-handler fd-stream)
789 (sb!sys:remove-fd-handler (fd-stream-handler fd-stream))
790 (setf (fd-stream-handler fd-stream) nil))
791 (when (and (fd-stream-file fd-stream)
792 (fd-stream-obuf-sap fd-stream))
793 ;; We can't do anything unless we know what file were
794 ;; dealing with, and we don't want to do anything
795 ;; strange unless we were writing to the file.
796 (if (fd-stream-original fd-stream)
797 ;; We have a handle on the original, just revert.
798 (multiple-value-bind (okay err)
799 (sb!unix:unix-rename (fd-stream-original fd-stream)
800 (fd-stream-file fd-stream))
802 (simple-stream-perror
803 "couldn't restore ~S to its original contents"
806 ;; We can't restore the original, so nuke that puppy.
807 (multiple-value-bind (okay err)
808 (sb!unix:unix-unlink (fd-stream-file fd-stream))
810 (error 'simple-file-error
811 :pathname (fd-stream-file fd-stream)
813 "~@<couldn't remove ~S: ~2I~_~A~:>"
814 :format-arguments (list (fd-stream-file fd-stream)
815 (strerror err))))))))
817 (fd-stream-misc-routine fd-stream :finish-output)
818 (when (and (fd-stream-original fd-stream)
819 (fd-stream-delete-original fd-stream))
820 (multiple-value-bind (okay err)
821 (sb!unix:unix-unlink (fd-stream-original fd-stream))
823 (error 'simple-file-error
824 :pathname (fd-stream-original fd-stream)
826 "~@<couldn't delete ~S during close of ~S: ~
829 (list (fd-stream-original fd-stream)
831 (strerror err))))))))
832 (when (fboundp 'cancel-finalization)
833 (cancel-finalization fd-stream))
834 (sb!unix:unix-close (fd-stream-fd fd-stream))
835 (when (fd-stream-obuf-sap fd-stream)
836 (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
837 (setf (fd-stream-obuf-sap fd-stream) nil))
838 (when (fd-stream-ibuf-sap fd-stream)
839 (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
840 (setf (fd-stream-ibuf-sap fd-stream) nil))
841 (sb!impl::set-closed-flame fd-stream))
843 (setf (fd-stream-unread fd-stream) nil)
844 (setf (fd-stream-ibuf-head fd-stream) 0)
845 (setf (fd-stream-ibuf-tail fd-stream) 0)
846 (catch 'eof-input-catcher
848 (let ((count (sb!alien:with-alien ((read-fds (sb!alien:struct
850 (sb!unix:fd-zero read-fds)
851 (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
852 (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
853 (sb!alien:addr read-fds)
859 (frob-input fd-stream)
860 (setf (fd-stream-ibuf-head fd-stream) 0)
861 (setf (fd-stream-ibuf-tail fd-stream) 0))
865 (flush-output-buffer fd-stream))
867 (flush-output-buffer fd-stream)
869 ((null (fd-stream-output-later fd-stream)))
870 (sb!sys:serve-all-events)))
872 (fd-stream-element-type fd-stream))
874 (= 1 (the (member 0 1)
875 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
879 (fd-stream-char-pos fd-stream))
881 (unless (fd-stream-file fd-stream)
882 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
883 ;; "should signal an error of type TYPE-ERROR if stream is not
884 ;; a stream associated with a file". Too bad there's no very
885 ;; appropriate value for the EXPECTED-TYPE slot..
886 (error 'simple-type-error
888 :expected-type 'file-stream
889 :format-control "~S is not a stream associated with a file."
890 :format-arguments (list fd-stream)))
891 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
892 atime mtime ctime blksize blocks)
893 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
894 (declare (ignore ino nlink uid gid rdev
895 atime mtime ctime blksize blocks))
897 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
900 (truncate size (fd-stream-element-size fd-stream)))))
902 (fd-stream-file-position fd-stream arg1))))
904 (defun fd-stream-file-position (stream &optional newpos)
905 (declare (type file-stream stream)
906 (type (or (alien sb!unix:off-t) (member nil :start :end)) newpos))
908 (sb!sys:without-interrupts
909 ;; First, find the position of the UNIX file descriptor in the file.
910 (multiple-value-bind (posn errno)
911 (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)
912 (declare (type (or (alien sb!unix:off-t) null) posn))
913 (cond ((integerp posn)
914 ;; Adjust for buffered output: If there is any output
915 ;; buffered, the *real* file position will be larger
916 ;; than reported by lseek() because lseek() obviously
917 ;; cannot take into account output we have not sent
919 (dolist (later (fd-stream-output-later stream))
920 (incf posn (- (caddr later)
922 (incf posn (fd-stream-obuf-tail stream))
923 ;; Adjust for unread input: If there is any input
924 ;; read from UNIX but not supplied to the user of the
925 ;; stream, the *real* file position will smaller than
926 ;; reported, because we want to look like the unread
927 ;; stuff is still available.
928 (decf posn (- (fd-stream-ibuf-tail stream)
929 (fd-stream-ibuf-head stream)))
930 (when (fd-stream-unread stream)
932 ;; Divide bytes by element size.
933 (truncate posn (fd-stream-element-size stream)))
934 ((eq errno sb!unix:espipe)
937 (sb!sys:with-interrupts
938 (simple-stream-perror "failure in Unix lseek() on ~S"
941 (let ((offset 0) origin)
942 (declare (type (alien sb!unix:off-t) offset))
943 ;; Make sure we don't have any output pending, because if we
944 ;; move the file pointer before writing this stuff, it will be
945 ;; written in the wrong location.
946 (flush-output-buffer stream)
948 ((null (fd-stream-output-later stream)))
949 (sb!sys:serve-all-events))
950 ;; Clear out any pending input to force the next read to go to
952 (setf (fd-stream-unread stream) nil)
953 (setf (fd-stream-ibuf-head stream) 0)
954 (setf (fd-stream-ibuf-tail stream) 0)
955 ;; Trash cached value for listen, so that we check next time.
956 (setf (fd-stream-listen stream) nil)
958 (cond ((eq newpos :start)
959 (setf offset 0 origin sb!unix:l_set))
961 (setf offset 0 origin sb!unix:l_xtnd))
962 ((typep newpos '(alien sb!unix:off-t))
963 (setf offset (* newpos (fd-stream-element-size stream))
964 origin sb!unix:l_set))
966 (error "invalid position given to FILE-POSITION: ~S" newpos)))
967 (multiple-value-bind (posn errno)
968 (sb!unix:unix-lseek (fd-stream-fd stream) offset origin)
969 (cond ((typep posn '(alien sb!unix:off-t))
971 ((eq errno sb!unix:espipe)
974 (simple-stream-perror "error in Unix lseek() on ~S"
978 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
980 ;;; Create a stream for the given Unix file descriptor.
982 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
983 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
984 ;;; default to allowing input.
986 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
988 ;;; BUFFERING indicates the kind of buffering to use.
990 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
991 ;;; NIL (the default), then wait forever. When we time out, we signal
994 ;;; FILE is the name of the file (will be returned by PATHNAME).
996 ;;; NAME is used to identify the stream when printed.
997 (defun make-fd-stream (fd
1000 (output nil output-p)
1001 (element-type 'base-char)
1010 (format nil "file ~S" file)
1011 (format nil "descriptor ~W" fd)))
1013 (declare (type index fd) (type (or index null) timeout)
1014 (type (member :none :line :full) buffering))
1015 (cond ((not (or input-p output-p))
1017 ((not (or input output))
1018 (error "File descriptor must be opened either for input or output.")))
1019 (let ((stream (%make-fd-stream :fd fd
1023 :delete-original delete-original
1025 :buffering buffering
1027 (set-fd-stream-routines stream element-type input output input-buffer-p)
1028 (when (and auto-close (fboundp 'finalize))
1031 (sb!unix:unix-close fd)
1033 (format *terminal-io* "** closed file descriptor ~W **~%"
1037 ;;; Pick a name to use for the backup file for the :IF-EXISTS
1038 ;;; :RENAME-AND-DELETE and :RENAME options.
1039 (defun pick-backup-name (name)
1040 (declare (type simple-base-string name))
1041 (concatenate 'simple-base-string name ".bak"))
1043 ;;; Ensure that the given arg is one of the given list of valid
1044 ;;; things. Allow the user to fix any problems.
1045 (defun ensure-one-of (item list what)
1046 (unless (member item list)
1047 (error 'simple-type-error
1049 :expected-type `(member ,@list)
1050 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
1051 :format-arguments (list item what list))))
1053 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
1054 ;;; access, since we don't want to trash unwritable files even if we
1055 ;;; technically can. We return true if we succeed in renaming.
1056 (defun rename-the-old-one (namestring original)
1057 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
1058 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
1059 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
1062 (error 'simple-file-error
1063 :pathname namestring
1065 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
1066 :format-arguments (list namestring original (strerror err))))))
1068 (defun open (filename
1071 (element-type 'base-char)
1072 (if-exists nil if-exists-given)
1073 (if-does-not-exist nil if-does-not-exist-given)
1074 (external-format :default)
1075 &aux ; Squelch assignment warning.
1076 (direction direction)
1077 (if-does-not-exist if-does-not-exist)
1078 (if-exists if-exists))
1080 "Return a stream which reads from or writes to FILENAME.
1082 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
1083 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
1084 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
1085 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
1086 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
1087 See the manual for details."
1089 ;; Calculate useful stuff.
1090 (multiple-value-bind (input output mask)
1092 (:input (values t nil sb!unix:o_rdonly))
1093 (:output (values nil t sb!unix:o_wronly))
1094 (:io (values t t sb!unix:o_rdwr))
1095 (:probe (values t nil sb!unix:o_rdonly)))
1096 (declare (type index mask))
1097 (let* ((pathname (merge-pathnames filename))
1099 (cond ((unix-namestring pathname input))
1100 ((and input (eq if-does-not-exist :create))
1101 (unix-namestring pathname nil)))))
1102 ;; Process if-exists argument if we are doing any output.
1104 (unless if-exists-given
1106 (if (eq (pathname-version pathname) :newest)
1109 (ensure-one-of if-exists
1110 '(:error :new-version :rename
1111 :rename-and-delete :overwrite
1112 :append :supersede nil)
1116 (setf mask (logior mask sb!unix:o_excl)))
1117 ((:rename :rename-and-delete)
1118 (setf mask (logior mask sb!unix:o_creat)))
1119 ((:new-version :supersede)
1120 (setf mask (logior mask sb!unix:o_trunc)))
1122 (setf mask (logior mask sb!unix:o_append)))))
1124 (setf if-exists :ignore-this-arg)))
1126 (unless if-does-not-exist-given
1127 (setf if-does-not-exist
1128 (cond ((eq direction :input) :error)
1130 (member if-exists '(:overwrite :append)))
1132 ((eq direction :probe)
1136 (ensure-one-of if-does-not-exist
1137 '(:error :create nil)
1139 (if (eq if-does-not-exist :create)
1140 (setf mask (logior mask sb!unix:o_creat)))
1142 (let ((original (if (member if-exists
1143 '(:rename :rename-and-delete))
1144 (pick-backup-name namestring)))
1145 (delete-original (eq if-exists :rename-and-delete))
1148 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
1149 ;; whether the file already exists, make sure the original
1150 ;; file is not a directory, and keep the mode.
1153 (multiple-value-bind (okay err/dev inode orig-mode)
1154 (sb!unix:unix-stat namestring)
1155 (declare (ignore inode)
1156 (type (or index null) orig-mode))
1159 (when (and output (= (logand orig-mode #o170000)
1161 (error 'simple-file-error
1162 :pathname namestring
1164 "can't open ~S for output: is a directory"
1165 :format-arguments (list namestring)))
1166 (setf mode (logand orig-mode #o777))
1168 ((eql err/dev sb!unix:enoent)
1171 (simple-file-perror "can't find ~S"
1175 (rename-the-old-one namestring original))
1177 (setf delete-original nil)
1178 ;; In order to use :SUPERSEDE instead, we have to make
1179 ;; sure SB!UNIX:O_CREAT corresponds to
1180 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
1181 ;; because of IF-EXISTS being :RENAME.
1182 (unless (eq if-does-not-exist :create)
1184 (logior (logandc2 mask sb!unix:o_creat)
1186 (setf if-exists :supersede))))
1188 ;; Now we can try the actual Unix open(2).
1189 (multiple-value-bind (fd errno)
1191 (sb!unix:unix-open namestring mask mode)
1192 (values nil sb!unix:enoent))
1193 (labels ((open-error (format-control &rest format-arguments)
1194 (error 'simple-file-error
1196 :format-control format-control
1197 :format-arguments format-arguments))
1198 (vanilla-open-error ()
1199 (simple-file-perror "error opening ~S" pathname errno)))
1202 ((:input :output :io)
1206 :element-type element-type
1209 :delete-original delete-original
1215 (%make-fd-stream :name namestring
1218 :element-type element-type)))
1221 ((eql errno sb!unix:enoent)
1222 (case if-does-not-exist
1223 (:error (vanilla-open-error))
1225 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
1228 ((and (eql errno sb!unix:eexist) (null if-exists))
1231 (vanilla-open-error)))))))))
1235 ;;; the stream connected to the controlling terminal, or NIL if there is none
1238 ;;; the stream connected to the standard input (file descriptor 0)
1241 ;;; the stream connected to the standard output (file descriptor 1)
1244 ;;; the stream connected to the standard error output (file descriptor 2)
1247 ;;; This is called when the cold load is first started up, and may also
1248 ;;; be called in an attempt to recover from nested errors.
1249 (defun stream-cold-init-or-reset ()
1251 (setf *terminal-io* (make-synonym-stream '*tty*))
1252 (setf *standard-output* (make-synonym-stream '*stdout*))
1253 (setf *standard-input* (make-synonym-stream '*stdin*))
1254 (setf *error-output* (make-synonym-stream '*stderr*))
1255 (setf *query-io* (make-synonym-stream '*terminal-io*))
1256 (setf *debug-io* *query-io*)
1257 (setf *trace-output* *standard-output*)
1260 ;;; This is called whenever a saved core is restarted.
1261 (defun stream-reinit ()
1262 (setf *available-buffers* nil)
1264 (make-fd-stream 0 :name "standard input" :input t :buffering :line))
1266 (make-fd-stream 1 :name "standard output" :output t :buffering :line))
1268 (make-fd-stream 2 :name "standard error" :output t :buffering :line))
1269 (let ((tty (sb!unix:unix-open "/dev/tty" sb!unix:o_rdwr #o666)))
1273 :name "the terminal"
1278 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
1283 ;;; the Unix way to beep
1284 (defun beep (stream)
1285 (write-char (code-char bell-char-code) stream)
1286 (finish-output stream))
1288 ;;; This is kind of like FILE-POSITION, but is an internal hack used
1289 ;;; by the filesys stuff to get and set the file name.
1291 ;;; FIXME: misleading name, screwy interface
1292 (defun file-name (stream &optional new-name)
1293 (when (typep stream 'file-stream)
1295 (setf (fd-stream-pathname stream) new-name)
1296 (setf (fd-stream-file stream)
1297 (unix-namestring new-name nil))
1300 (fd-stream-pathname stream)))))
1302 ;;;; international character support (which is trivial for our simple
1303 ;;;; character sets)
1305 ;;;; (Those who do Lisp only in English might not remember that ANSI
1306 ;;;; requires these functions to be exported from package
1309 (defun file-string-length (stream object)
1310 (declare (type (or string character) object) (type file-stream stream))
1312 "Return the delta in STREAM's FILE-POSITION that would be caused by writing
1313 OBJECT to STREAM. Non-trivial only in implementations that support
1314 international character sets."
1315 (declare (ignore stream))
1318 (string (length object))))
1320 (defun stream-external-format (stream)
1321 (declare (type file-stream stream) (ignore stream))