home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / pcl / src-16f.lha / code / fd-stream.lisp < prev    next >
Encoding:
Text File  |  1992-05-30  |  47.2 KB  |  1,500 lines

  1. ;;; -*- Log: code.log; Package: LISP -*-
  2. ;;;
  3. ;;; **********************************************************************
  4. ;;; This code was written as part of the CMU Common Lisp project at
  5. ;;; Carnegie Mellon University, and has been placed in the public domain.
  6. ;;; If you want to use this code or any part of CMU Common Lisp, please contact
  7. ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
  8. ;;;
  9. (ext:file-comment
  10.   "$Header: fd-stream.lisp,v 1.21 92/03/09 20:17:39 wlott Exp $")
  11. ;;;
  12. ;;; **********************************************************************
  13. ;;;
  14. ;;; Streams for UNIX file descriptors.
  15. ;;;
  16. ;;; Written by William Lott, July 1989 - January 1990.
  17. ;;; Some tuning by Rob MacLachlan.
  18. ;;; 
  19. ;;; **********************************************************************
  20.  
  21.  
  22. (in-package "SYSTEM")
  23.  
  24. (export '(fd-stream fd-stream-p fd-stream-fd make-fd-stream
  25.           io-timeout beep *beep-function* output-raw-bytes
  26.       *tty* *stdin* *stdout* *stderr*))
  27.  
  28.  
  29. (in-package "EXTENSIONS")
  30.  
  31. (export '(*backup-extension*))
  32.  
  33.  
  34. (in-package "LISP")
  35.  
  36.  
  37. ;;;; Buffer manipulation routines.
  38.  
  39. (defvar *available-buffers* ()
  40.   "List of available buffers.  Each buffer is an sap pointing to
  41.   bytes-per-buffer of memory.")
  42.  
  43. (defconstant bytes-per-buffer (* 4 1024)
  44.   "Number of bytes per buffer.")
  45.  
  46. ;;; NEXT-AVAILABLE-BUFFER -- Internal.
  47. ;;;
  48. ;;; Returns the next available buffer, creating one if necessary.
  49. ;;;
  50. (proclaim '(inline next-available-buffer))
  51. ;;;
  52. (defun next-available-buffer ()
  53.   (if *available-buffers*
  54.       (pop *available-buffers*)
  55.       (allocate-system-memory bytes-per-buffer)))
  56.  
  57.  
  58. ;;;; The FD-STREAM structure.
  59.  
  60. (defstruct (fd-stream
  61.         (:print-function %print-fd-stream)
  62.         (:constructor %make-fd-stream)
  63.         (:include stream
  64.               (misc #'fd-stream-misc-routine)))
  65.  
  66.   (name nil)              ; The name of this stream
  67.   (file nil)              ; The file this stream is for
  68.   (original nil)          ; The original file (for :if-exists :rename)
  69.   (delete-original nil)          ; for :if-exists :rename-and-delete
  70.   ;;
  71.   ;;; Number of bytes per element.
  72.   (element-size 1 :type index)
  73.   (element-type 'base-char)   ; The type of element being transfered.
  74.   (fd -1 :type fixnum)          ; The file descriptor
  75.   ;;
  76.   ;; Controls when the output buffer is flushed.
  77.   (buffering :full :type (member :full :line :none))
  78.   ;;
  79.   ;; Character position if known.
  80.   (char-pos nil :type (or index null))
  81.   ;;
  82.   ;; T if input is waiting on FD.  :EOF if we hit EOF.
  83.   (listen nil :type (member nil t :eof))
  84.   ;;
  85.   ;; The input buffer.
  86.   (unread nil)
  87.   (ibuf-sap nil :type (or system-area-pointer null))
  88.   (ibuf-length nil :type (or index null))
  89.   (ibuf-head 0 :type index)
  90.   (ibuf-tail 0 :type index)
  91.  
  92.   ;; The output buffer.
  93.   (obuf-sap nil :type (or system-area-pointer null))
  94.   (obuf-length nil :type (or index null))
  95.   (obuf-tail 0 :type index)
  96.  
  97.   ;; Output flushed, but not written due to non-blocking io.
  98.   (output-later nil)
  99.   (handler nil)
  100.   ;;
  101.   ;; Timeout specified for this stream, or NIL if none.
  102.   (timeout nil :type (or index null)))
  103.  
  104. (defun %print-fd-stream (fd-stream stream depth)
  105.   (declare (ignore depth) (stream stream))
  106.   (format stream "#<Stream for ~A>"
  107.       (fd-stream-name fd-stream)))
  108.  
  109.  
  110. (define-condition io-timeout (stream-error) (direction)
  111.   (:report
  112.    (lambda (condition stream)
  113.      (format stream "Timeout ~(~A~)ing ~S."
  114.          (io-timeout-direction condition)
  115.          (stream-error-stream condition)))))
  116.  
  117.  
  118. ;;;; Output routines and related noise.
  119.  
  120. (defvar *output-routines* ()
  121.   "List of all available output routines. Each element is a list of the
  122.   element-type output, the kind of buffering, the function name, and the number
  123.   of bytes per element.")
  124.  
  125. ;;; DO-OUTPUT-LATER -- internal
  126. ;;;
  127. ;;;   Called by the server when we can write to the given file descriptor.
  128. ;;; Attemt to write the data again. If it worked, remove the data from the
  129. ;;; output-later list. If it didn't work, something is wrong.
  130. ;;;
  131. (defun do-output-later (stream)
  132.   (let* ((stuff (pop (fd-stream-output-later stream)))
  133.      (base (car stuff))
  134.      (start (cadr stuff))
  135.      (end (caddr stuff))
  136.      (reuse-sap (cadddr stuff))
  137.      (length (- end start)))
  138.     (declare (type index start end length))
  139.     (multiple-value-bind
  140.     (count errno)
  141.     (unix:unix-write (fd-stream-fd stream)
  142.              base
  143.              start
  144.              length)
  145.       (cond ((not count)
  146.          (if (= errno unix:ewouldblock)
  147.          (error "Write would have blocked, but SERVER told us to go.")
  148.          (error "While writing ~S: ~A"
  149.             stream (unix:get-unix-error-msg errno))))
  150.         ((eql count length) ; Hot damn, it workded.
  151.          (when reuse-sap
  152.            (push base *available-buffers*)))
  153.         ((not (null count)) ; Sorta worked.
  154.          (push (list base
  155.              (+ start count)
  156.              end)
  157.            (fd-stream-output-later stream))))))
  158.   (unless (fd-stream-output-later stream)
  159.     (system:remove-fd-handler (fd-stream-handler stream))
  160.     (setf (fd-stream-handler stream) nil)))
  161.  
  162. ;;; OUTPUT-LATER -- internal
  163. ;;;
  164. ;;;   Arange to output the string when we can write on the file descriptor.
  165. ;;;
  166. (defun output-later (stream base start end reuse-sap)
  167.   (cond ((null (fd-stream-output-later stream))
  168.      (setf (fd-stream-output-later stream)
  169.            (list (list base start end reuse-sap)))
  170.      (setf (fd-stream-handler stream)
  171.            (system:add-fd-handler (fd-stream-fd stream)
  172.                       :output
  173.                       #'(lambda (fd)
  174.                       (declare (ignore fd))
  175.                       (do-output-later stream)))))
  176.     (t
  177.      (nconc (fd-stream-output-later stream)
  178.         (list (list base start end reuse-sap)))))
  179.   (when reuse-sap
  180.     (let ((new-buffer (next-available-buffer)))
  181.       (setf (fd-stream-obuf-sap stream) new-buffer)
  182.       (setf (fd-stream-obuf-length stream) bytes-per-buffer)))) 
  183.  
  184. ;;; DO-OUTPUT -- internal
  185. ;;;
  186. ;;;   Output the given noise. Check to see if there are any pending writes. If
  187. ;;; so, just queue this one. Otherwise, try to write it. If this would block,
  188. ;;; queue it.
  189. ;;;
  190. (defun do-output (stream base start end reuse-sap)
  191.   (declare (type fd-stream stream)
  192.        (type (or system-area-pointer (simple-array * (*))) base)
  193.        (type index start end))
  194.   (if (not (null (fd-stream-output-later stream))) ; something buffered.
  195.       (progn
  196.     (output-later stream base start end reuse-sap)
  197.     ;; ### check to see if any of this noise can be output
  198.     )
  199.       (let ((length (- end start)))
  200.     (multiple-value-bind
  201.         (count errno)
  202.         (unix:unix-write (fd-stream-fd stream) base start length)
  203.       (cond ((not count)
  204.          (if (= errno unix:ewouldblock)
  205.              (output-later stream base start end reuse-sap)
  206.              (error "While writing ~S: ~A"
  207.                 stream (unix:get-unix-error-msg errno))))
  208.         ((not (eql count length))
  209.          (output-later stream base (+ start count) end reuse-sap)))))))
  210.  
  211.  
  212. ;;; FLUSH-OUTPUT-BUFFER -- internal
  213. ;;;
  214. ;;;   Flush any data in the output buffer.
  215. ;;;
  216. (defun flush-output-buffer (stream)
  217.   (let ((length (fd-stream-obuf-tail stream)))
  218.     (unless (= length 0)
  219.       (do-output stream (fd-stream-obuf-sap stream) 0 length t)
  220.       (setf (fd-stream-obuf-tail stream) 0))))
  221.  
  222. ;;; DEF-OUTPUT-ROUTINES -- internal
  223. ;;;
  224. ;;;   Define output routines that output numbers size bytes long for the
  225. ;;; given bufferings. Use body to do the actual output.
  226. ;;;
  227. (defmacro def-output-routines ((name size &rest bufferings) &body body)
  228.   (cons 'progn
  229.     (mapcar
  230.         #'(lambda (buffering)
  231.         (let ((function
  232.                (intern (let ((*print-case* :upcase))
  233.                  (format nil name (car buffering))))))
  234.           `(progn
  235.              (defun ,function (stream byte)
  236.                ,(unless (eq (car buffering) :none)
  237.               `(when (< (fd-stream-obuf-length stream)
  238.                     (+ (fd-stream-obuf-tail stream)
  239.                        ,size))
  240.                  (flush-output-buffer stream)))
  241.                ,@body
  242.                (incf (fd-stream-obuf-tail stream) ,size)
  243.                ,(ecase (car buffering)
  244.               (:none
  245.                `(flush-output-buffer stream))
  246.               (:line
  247.                `(when (eq (char-code byte) (char-code #\Newline))
  248.                   (flush-output-buffer stream)))
  249.               (:full
  250.                ))
  251.                (values))
  252.              (setf *output-routines*
  253.                (nconc *output-routines*
  254.                   ',(mapcar
  255.                     #'(lambda (type)
  256.                         (list type
  257.                           (car buffering)
  258.                           function
  259.                           size))
  260.                       (cdr buffering)))))))
  261.       bufferings)))
  262.  
  263. (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
  264.               1
  265.               (:none character)
  266.               (:line character)
  267.               (:full character))
  268.   (if (eq (char-code byte)
  269.       (char-code #\Newline))
  270.       (setf (fd-stream-char-pos stream) 0)
  271.       (incf (fd-stream-char-pos stream)))
  272.   (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
  273.     (char-code byte)))
  274.  
  275. (def-output-routines ("OUTPUT-BYTE-~A-BUFFERED"
  276.               1
  277.               (:none (signed-byte 8) (unsigned-byte 8))
  278.               (:full (signed-byte 8) (unsigned-byte 8)))
  279.   (when (characterp byte)
  280.     (if (eq (char-code byte)
  281.         (char-code #\Newline))
  282.       (setf (fd-stream-char-pos stream) 0)
  283.       (incf (fd-stream-char-pos stream))))
  284.   (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
  285.     byte))
  286.  
  287. (def-output-routines ("OUTPUT-SHORT-~A-BUFFERED"
  288.               2
  289.               (:none (signed-byte 16) (unsigned-byte 16))
  290.               (:full (signed-byte 16) (unsigned-byte 16)))
  291.   (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
  292.     byte))
  293.  
  294. (def-output-routines ("OUTPUT-LONG-~A-BUFFERED"
  295.               4
  296.               (:none (signed-byte 32) (unsigned-byte 32))
  297.               (:full (signed-byte 32) (unsigned-byte 32)))
  298.   (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
  299.     byte))
  300.  
  301. ;;; OUTPUT-RAW-BYTES -- public
  302. ;;;
  303. ;;;   Does the actual output. If there is space to buffer the string, buffer
  304. ;;; it. If the string would normally fit in the buffer, but doesn't because
  305. ;;; of other stuff in the buffer, flush the old noise out of the buffer and
  306. ;;; put the string in it. Otherwise we have a very long string, so just
  307. ;;; send it directly (after flushing the buffer, of course).
  308. ;;;
  309. (defun output-raw-bytes (stream thing &optional start end)
  310.   "Output THING to stream.  THING can be any kind of vector or a sap.  If THING
  311.   is a SAP, END must be supplied (as length won't work)."
  312.   (let ((start (or start 0))
  313.     (end (or end (length (the (simple-array * (*)) thing)))))
  314.     (declare (type index start end))
  315.     (let* ((len (fd-stream-obuf-length stream))
  316.        (tail (fd-stream-obuf-tail stream))
  317.        (space (- len tail))
  318.        (bytes (- end start))
  319.        (newtail (+ tail bytes)))
  320.       (cond ((minusp bytes) ; Error case
  321.          (cerror "Just go on as if nothing happened..."
  322.              "~S called with :END before :START!"
  323.              'output-raw-bytes))
  324.         ((zerop bytes)) ; Easy case
  325.         ((<= bytes space)
  326.          (if (system-area-pointer-p thing)
  327.          (system-area-copy thing
  328.                    (* start vm:byte-bits)
  329.                    (fd-stream-obuf-sap stream)
  330.                    (* tail vm:byte-bits)
  331.                    (* bytes vm:byte-bits))
  332.          (copy-to-system-area thing
  333.                       (+ (* start vm:byte-bits)
  334.                      (* vm:vector-data-offset vm:word-bits))
  335.                       (fd-stream-obuf-sap stream)
  336.                       (* tail vm:byte-bits)
  337.                       (* bytes vm:byte-bits)))
  338.          (setf (fd-stream-obuf-tail stream) newtail))
  339.         ((<= bytes len)
  340.          (flush-output-buffer stream)
  341.          (if (system-area-pointer-p thing)
  342.          (system-area-copy thing
  343.                    (* start vm:byte-bits)
  344.                    (fd-stream-obuf-sap stream)
  345.                    0
  346.                    (* bytes vm:byte-bits))
  347.          (copy-to-system-area thing
  348.                       (+ (* start vm:byte-bits)
  349.                      (* vm:vector-data-offset vm:word-bits))
  350.                       (fd-stream-obuf-sap stream)
  351.                       0
  352.                       (* bytes vm:byte-bits)))
  353.          (setf (fd-stream-obuf-tail stream) bytes))
  354.         (t
  355.          (flush-output-buffer stream)
  356.          (do-output stream thing start end nil))))))
  357.  
  358. ;;; FD-SOUT -- internal
  359. ;;;
  360. ;;;   Routine to use to output a string. If the stream is unbuffered, slam
  361. ;;; the string down the file descriptor, otherwise use OUTPUT-RAW-BYTES to
  362. ;;; buffer the string. Update charpos by checking to see where the last newline
  363. ;;; was.
  364. ;;;
  365. ;;;   Note: some bozos (the FASL dumper) call write-string with things other
  366. ;;; than strings. Therefore, we must make sure we have a string before calling
  367. ;;; position on it.
  368. ;;; 
  369. (defun fd-sout (stream thing start end)
  370.   (let ((start (or start 0))
  371.     (end (or end (length (the vector thing)))))
  372.     (declare (fixnum start end))
  373.     (if (stringp thing)
  374.     (let ((last-newline (and (find #\newline (the simple-string thing)
  375.                        :start start :end end)
  376.                  (position #\newline (the simple-string thing)
  377.                        :from-end t
  378.                        :start start
  379.                        :end end))))
  380.       (ecase (fd-stream-buffering stream)
  381.         (:full
  382.          (output-raw-bytes stream thing start end))
  383.         (:line
  384.          (output-raw-bytes stream thing start end)
  385.          (when last-newline
  386.            (flush-output-buffer stream)))
  387.         (:none
  388.          (do-output stream thing start end nil)))
  389.       (if last-newline
  390.           (setf (fd-stream-char-pos stream)
  391.             (- end last-newline 1))
  392.           (incf (fd-stream-char-pos stream)
  393.             (- end start))))
  394.     (ecase (fd-stream-buffering stream)
  395.       ((:line :full)
  396.        (output-raw-bytes stream thing start end))
  397.       (:none
  398.        (do-output stream thing start end nil))))))
  399.  
  400. ;;; PICK-OUTPUT-ROUTINE -- internal
  401. ;;;
  402. ;;;   Find an output routine to use given the type and buffering. Return as
  403. ;;; multiple values the routine, the real type transfered, and the number of
  404. ;;; bytes per element.
  405. ;;;
  406. (defun pick-output-routine (type buffering)
  407.   (dolist (entry *output-routines*)
  408.     (when (and (subtypep type (car entry))
  409.            (eq buffering (cadr entry)))
  410.       (return (values (symbol-function (caddr entry))
  411.               (car entry)
  412.               (cadddr entry))))))
  413.  
  414.  
  415. ;;;; Input routines and related noise.
  416.  
  417. (defvar *input-routines* ()
  418.   "List of all available input routines. Each element is a list of the
  419.   element-type input, the function name, and the number of bytes per element.")
  420.  
  421. ;;; DO-INPUT -- internal
  422. ;;;
  423. ;;;   Fills the input buffer, and returns the first character. Throws to
  424. ;;; eof-input-catcher if the eof was reached. Drops into system:server if
  425. ;;; necessary.
  426. ;;;
  427. (defun do-input (stream)
  428.   (let ((fd (fd-stream-fd stream))
  429.     (ibuf-sap (fd-stream-ibuf-sap stream))
  430.     (buflen (fd-stream-ibuf-length stream))
  431.     (head (fd-stream-ibuf-head stream))
  432.     (tail (fd-stream-ibuf-tail stream)))
  433.     (declare (type index head tail))
  434.     (unless (zerop head)
  435.       (cond ((eql head tail)
  436.          (setf head 0)
  437.          (setf tail 0)
  438.          (setf (fd-stream-ibuf-head stream) 0)
  439.          (setf (fd-stream-ibuf-tail stream) 0))
  440.         (t
  441.          (decf tail head)
  442.          (system-area-copy ibuf-sap (* head vm:byte-bits)
  443.                    ibuf-sap 0 (* tail vm:byte-bits))
  444.          (setf head 0)
  445.          (setf (fd-stream-ibuf-head stream) 0)
  446.          (setf (fd-stream-ibuf-tail stream) tail))))
  447.     (setf (fd-stream-listen stream) nil)
  448.     (multiple-value-bind
  449.     (count errno)
  450.     (unix:unix-select (1+ fd) (ash 1 fd) 0 0 0)
  451.       (case count
  452.     (1)
  453.     (0
  454.      (unless (system:wait-until-fd-usable
  455.           fd :input (fd-stream-timeout stream))
  456.        (error 'io-timeout :stream stream :direction :read)))
  457.     (t
  458.      (error "Problem checking to see if ~S is readable: ~A"
  459.         stream
  460.         (unix:get-unix-error-msg errno)))))
  461.     (multiple-value-bind
  462.     (count errno)
  463.     (unix:unix-read fd
  464.             (system:int-sap (+ (system:sap-int ibuf-sap) tail))
  465.             (- buflen tail))
  466.       (cond ((null count)
  467.          (if (eql errno unix:ewouldblock)
  468.          (progn
  469.            (unless (system:wait-until-fd-usable
  470.                 fd :input (fd-stream-timeout stream))
  471.              (error 'io-timeout :stream stream :direction :read))
  472.            (do-input stream))
  473.          (error "Error reading ~S: ~A"
  474.             stream
  475.             (unix:get-unix-error-msg errno))))
  476.         ((zerop count)
  477.          (setf (fd-stream-listen stream) :eof)
  478.          (throw 'eof-input-catcher nil))
  479.         (t
  480.          (incf (fd-stream-ibuf-tail stream) count))))))
  481.             
  482. ;;; INPUT-AT-LEAST -- internal
  483. ;;;
  484. ;;;   Makes sure there are at least ``bytes'' number of bytes in the input
  485. ;;; buffer. Keeps calling do-input until that condition is met.
  486. ;;;
  487. (defmacro input-at-least (stream bytes)
  488.   (let ((stream-var (gensym))
  489.     (bytes-var (gensym)))
  490.     `(let ((,stream-var ,stream)
  491.        (,bytes-var ,bytes))
  492.        (loop
  493.      (when (>= (- (fd-stream-ibuf-tail ,stream-var)
  494.               (fd-stream-ibuf-head ,stream-var))
  495.            ,bytes-var)
  496.        (return))
  497.      (do-input ,stream-var)))))
  498.  
  499. ;;; INPUT-WRAPPER -- intenal
  500. ;;;
  501. ;;;   Macro to wrap around all input routines to handle eof-error noise. This
  502. ;;; should make provisions for filling stream-in-buffer.
  503. ;;;
  504. (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
  505.   (let ((stream-var (gensym))
  506.     (element-var (gensym)))
  507.     `(let ((,stream-var ,stream))
  508.        (if (fd-stream-unread ,stream)
  509.      (prog1
  510.          (fd-stream-unread ,stream)
  511.        (setf (fd-stream-unread ,stream) nil)
  512.        (setf (fd-stream-listen ,stream) nil))
  513.      (let ((,element-var
  514.         (catch 'eof-input-catcher
  515.           (input-at-least ,stream-var ,bytes)
  516.           ,@read-forms)))
  517.        (cond (,element-var
  518.           (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
  519.           ,element-var)
  520.          (,eof-error
  521.           (error "EOF while reading ~S" stream))
  522.          (t
  523.           ,eof-value)))))))
  524.  
  525. ;;; DEF-INPUT-ROUTINE -- internal
  526. ;;;
  527. ;;;   Defines an input routine.
  528. ;;;
  529. (defmacro def-input-routine (name
  530.                  (type size sap head)
  531.                  &rest body)
  532.   `(progn
  533.      (defun ,name (stream eof-error eof-value)
  534.        (input-wrapper (stream ,size eof-error eof-value)
  535.      (let ((,sap (fd-stream-ibuf-sap stream))
  536.            (,head (fd-stream-ibuf-head stream)))
  537.        ,@body)))
  538.      (setf *input-routines*
  539.        (nconc *input-routines*
  540.           (list (list ',type ',name ',size))))))
  541.  
  542. ;;; INPUT-CHARACTER -- internal
  543. ;;;
  544. ;;;   Routine to use in stream-in slot for reading string chars.
  545. ;;;
  546. (def-input-routine input-character
  547.            (character 1 sap head)
  548.   (code-char (sap-ref-8 sap head)))
  549.  
  550. ;;; INPUT-UNSIGNED-8BIT-BYTE -- internal
  551. ;;;
  552. ;;;   Routine to read in an unsigned 8 bit number.
  553. ;;;
  554. (def-input-routine input-unsigned-8bit-byte
  555.            ((unsigned-byte 8) 1 sap head)
  556.   (sap-ref-8 sap head))
  557.  
  558. ;;; INPUT-SIGNED-8BIT-BYTE -- internal
  559. ;;;
  560. ;;;   Routine to read in a signed 8 bit number.
  561. ;;;
  562. (def-input-routine input-signed-8bit-number
  563.            ((signed-byte 8) 1 sap head)
  564.   (signed-sap-ref-8 sap head))
  565.  
  566. ;;; INPUT-UNSIGNED-16BIT-BYTE -- internal
  567. ;;;
  568. ;;;   Routine to read in an unsigned 16 bit number.
  569. ;;;
  570. (def-input-routine input-unsigned-16bit-byte
  571.            ((unsigned-byte 16) 2 sap head)
  572.   (sap-ref-16 sap head))
  573.  
  574. ;;; INPUT-SIGNED-16BIT-BYTE -- internal
  575. ;;;
  576. ;;;   Routine to read in a signed 16 bit number.
  577. ;;;
  578. (def-input-routine input-signed-16bit-byte
  579.            ((signed-byte 16) 2 sap head)
  580.   (signed-sap-ref-16 sap head))
  581.  
  582. ;;; INPUT-UNSIGNED-32BIT-BYTE -- internal
  583. ;;;
  584. ;;;   Routine to read in a unsigned 32 bit number.
  585. ;;;
  586. (def-input-routine input-unsigned-32bit-byte
  587.            ((unsigned-byte 32) 4 sap head)
  588.   (sap-ref-32 sap head))
  589.  
  590. ;;; INPUT-SIGNED-32BIT-BYTE -- internal
  591. ;;;
  592. ;;;   Routine to read in a signed 32 bit number.
  593. ;;;
  594. (def-input-routine input-signed-32bit-byte
  595.            ((signed-byte 32) 4 sap head)
  596.   (signed-sap-ref-32 sap head))
  597.  
  598. ;;; PICK-INPUT-ROUTINE -- internal
  599. ;;;
  600. ;;;   Find an input routine to use given the type. Return as multiple values
  601. ;;; the routine, the real type transfered, and the number of bytes per element.
  602. ;;;
  603. (defun pick-input-routine (type)
  604.   (dolist (entry *input-routines*)
  605.     (when (subtypep type (car entry))
  606.       (return (values (symbol-function (cadr entry))
  607.               (car entry)
  608.               (caddr entry))))))
  609.  
  610. ;;; STRING-FROM-SAP -- internal
  611. ;;;
  612. ;;;   Returns a string constructed from the sap, start, and end.
  613. ;;;
  614. (defun string-from-sap (sap start end)
  615.   (declare (type index start end))
  616.   (let* ((length (- end start))
  617.      (string (make-string length)))
  618.     (copy-from-system-area sap (* start vm:byte-bits)
  619.                string (* vm:vector-data-offset vm:word-bits)
  620.                (* length vm:byte-bits))
  621.     string))
  622.  
  623. ;;; FD-STREAM-READ-LINE -- internal
  624. ;;;
  625. ;;;   Reads a line, returning a simple string. Note: this relies on the fact
  626. ;;; that the input buffer does not change during do-input.
  627. ;;;
  628. (defun fd-stream-read-line (stream eof-error-p eof-value)
  629.   (let ((eof t))
  630.     (values
  631.      (or (let ((sap (fd-stream-ibuf-sap stream))
  632.            (results (when (fd-stream-unread stream)
  633.               (prog1
  634.                   (list (string (fd-stream-unread stream)))
  635.                 (setf (fd-stream-unread stream) nil)
  636.                 (setf (fd-stream-listen stream) nil)))))
  637.        (catch 'eof-input-catcher
  638.          (loop
  639.            (input-at-least stream 1)
  640.            (let* ((head (fd-stream-ibuf-head stream))
  641.               (tail (fd-stream-ibuf-tail stream))
  642.               (newline (do ((index head (1+ index)))
  643.                    ((= index tail) nil)
  644.                  (when (= (sap-ref-8 sap index)
  645.                       (char-code #\newline))
  646.                    (return index))))
  647.               (end (or newline tail)))
  648.          (push (string-from-sap sap head end)
  649.                results)
  650.  
  651.          (when newline
  652.            (setf eof nil)
  653.            (setf (fd-stream-ibuf-head stream)
  654.              (1+ newline))
  655.            (return))
  656.          (setf (fd-stream-ibuf-head stream) end))))
  657.        (cond ((null results)
  658.           nil)
  659.          ((null (cdr results))
  660.           (car results))
  661.          (t
  662.           (apply #'concatenate 'simple-string (nreverse results)))))
  663.      (if eof-error-p
  664.          (error "EOF while reading ~S" stream)
  665.          eof-value))
  666.      eof)))
  667.  
  668. #|
  669. This version waits using server.  I changed to the non-server version because
  670. it allows this method to be used by CLX w/o confusing serve-event.  The
  671. non-server method is also significantly more efficient for large reads.
  672.   -- Ram
  673.  
  674. ;;; FD-STREAM-READ-N-BYTES -- internal
  675. ;;;
  676. ;;; The n-bin routine.
  677. ;;; 
  678. (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
  679.   (let* ((sap (fd-stream-ibuf-sap stream))
  680.      (elsize (fd-stream-element-size stream))
  681.      (offset (* elsize start))
  682.      (bytes (* elsize requested))
  683.      (result
  684.       (catch 'eof-input-catcher
  685.         (loop
  686.           (input-at-least stream 1)
  687.           (let* ((head (fd-stream-ibuf-head stream))
  688.              (tail (fd-stream-ibuf-tail stream))
  689.              (available (- tail head))
  690.              (copy (min available bytes)))
  691.         (if (typep buffer 'system-area-pointer)
  692.             (system-area-copy sap (* head vm:byte-bits)
  693.                       buffer (* offset vm:byte-bits)
  694.                       (* copy vm:byte-bits))
  695.             (copy-from-system-area sap (* head vm:byte-bits)
  696.                        buffer (+ (* offset vm:byte-bits)
  697.                              (* vm:vector-data-offset
  698.                             vm:word-bits))
  699.                        (* copy vm:byte-bits)))
  700.         (incf (fd-stream-ibuf-head stream) copy)
  701.         (incf offset copy)
  702.         (decf bytes copy))
  703.           (when (zerop bytes)
  704.         (return requested))))))
  705.     (cond (result)
  706.       ((not eof-error-p)
  707.        (- requested (/ bytes elsize)))
  708.       (t
  709.        (error "Hit eof on ~S after reading ~D ~D~2:*-bit byte~P~*, ~
  710.            but ~D~2:* ~D-bit byte~P~:* ~[were~;was~:;were~] requested."
  711.           stream
  712.           (- requested (/ bytes elsize))
  713.           (* elsize 8)
  714.           requested)))))
  715. |#
  716.  
  717.  
  718. ;;; FD-STREAM-READ-N-BYTES -- internal
  719. ;;;
  720. ;;;    The N-Bin method for FD-STREAMs.  This doesn't using SERVER; it blocks
  721. ;;; in UNIX-READ.  This allows the method to be used to implementing reading
  722. ;;; for CLX.  It is generally used where there is a definite amount of reading
  723. ;;; to be done, so blocking isn't too problematical.
  724. ;;;
  725. ;;;    We copy buffered data into the buffer.  If there is enough, just return.
  726. ;;; Otherwise, we see if the amount of additional data needed will fit in the
  727. ;;; stream buffer.  If not, inhibit GCing (so we can have a SAP into the Buffer
  728. ;;; argument), and read directly into the user supplied buffer.  Otherwise,
  729. ;;; read a buffer-full into the stream buffer and then copy the amount we need
  730. ;;; out.
  731. ;;;
  732. ;;;    We loop doing the reads until we either get enough bytes or hit EOF.  We
  733. ;;; must loop because some streams (like pipes) may return a partial amount
  734. ;;; without hitting EOF.
  735. ;;; 
  736. (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
  737.   (declare (type stream stream) (type index start requested))
  738.   (let* ((sap (fd-stream-ibuf-sap stream))
  739.      (elsize (fd-stream-element-size stream))
  740.      (offset (* elsize start))
  741.      (requested-bytes (* elsize requested))
  742.      (head (fd-stream-ibuf-head stream))
  743.      (tail (fd-stream-ibuf-tail stream))
  744.      (available (- tail head))
  745.      (copy (min requested-bytes available)))
  746.     (declare (type index elsize offset requested-bytes head tail available
  747.            copy))
  748.     (unless (zerop copy)
  749.       (if (typep buffer 'system-area-pointer)
  750.       (system-area-copy sap (* head vm:byte-bits)
  751.                 buffer (* offset vm:byte-bits)
  752.                 (* copy vm:byte-bits))
  753.       (copy-from-system-area sap (* head vm:byte-bits)
  754.                  buffer (+ (* offset vm:byte-bits)
  755.                        (* vm:vector-data-offset
  756.                           vm:word-bits))
  757.                  (* copy vm:byte-bits)))
  758.       (incf (fd-stream-ibuf-head stream) copy))
  759.     (cond
  760.      ((> requested-bytes available)
  761.       (setf (fd-stream-ibuf-head stream) 0)
  762.       (setf (fd-stream-ibuf-tail stream) 0)
  763.       (setf (fd-stream-listen stream) nil)
  764.       (let ((now-needed (- requested-bytes copy))
  765.         (len (fd-stream-ibuf-length stream)))
  766.     (declare (type index now-needed len))
  767.     (cond
  768.      ((> now-needed len)
  769.       (system:without-gcing
  770.         (loop
  771.           (multiple-value-bind
  772.           (count err)
  773.           (unix:unix-read (fd-stream-fd stream)
  774.                   (sap+ (if (typep buffer 'system-area-pointer)
  775.                         buffer
  776.                         (vector-sap buffer))
  777.                     (+ offset copy))
  778.                   now-needed)
  779.         (declare (type (or index null) count))
  780.         (unless count
  781.           (error "Error reading ~S: ~A" stream
  782.              (unix:get-unix-error-msg err)))
  783.         (when (zerop count)
  784.           (if eof-error-p
  785.               (error "Unexpected eof on ~S." stream)
  786.               (return (- requested (truncate now-needed elsize)))))
  787.         (decf now-needed count)
  788.         (when (zerop now-needed) (return requested))
  789.         (incf offset count)))))
  790.      (t
  791.       (loop
  792.         (multiple-value-bind
  793.         (count err)
  794.         (unix:unix-read (fd-stream-fd stream) sap len)
  795.           (declare (type (or index null) count))
  796.           (unless count
  797.         (error "Error reading ~S: ~A" stream
  798.                (unix:get-unix-error-msg err)))
  799.           (incf (fd-stream-ibuf-tail stream) count)
  800.           (when (zerop count)
  801.         (if eof-error-p
  802.             (error "Unexpected eof on ~S." stream)
  803.             (return (- requested (truncate now-needed elsize)))))
  804.           (let* ((copy (min now-needed count))
  805.              (copy-bits (* copy vm:byte-bits))
  806.              (buffer-start-bits
  807.               (* (+ offset available) vm:byte-bits)))
  808.         (declare (type index copy copy-bits buffer-start-bits))
  809.         (if (typep buffer 'system-area-pointer)
  810.             (system-area-copy sap 0
  811.                       buffer buffer-start-bits
  812.                       copy-bits)
  813.             (copy-from-system-area sap 0 
  814.                        buffer (+ buffer-start-bits
  815.                              (* vm:vector-data-offset
  816.                             vm:word-bits))
  817.                        copy-bits))
  818.         (incf (fd-stream-ibuf-head stream) copy)
  819.         (decf now-needed copy)
  820.         (when (zerop now-needed) (return requested))
  821.         (incf offset copy))))))))
  822.      (t
  823.       requested))))
  824.  
  825.  
  826. ;;;; Utility functions (misc routines, etc)
  827.  
  828. ;;; SET-ROUTINES -- internal
  829. ;;;
  830. ;;;   Fill in the various routine slots for the given type. Input-p and output-p
  831. ;;; indicate what slots to fill. The buffering slot must be set prior to
  832. ;;; calling this routine.
  833. ;;;
  834. (defun set-routines (stream type input-p output-p)
  835.   (let ((target-type (case type
  836.                ((:default unsigned-byte)
  837.             '(unsigned-byte 8))
  838.                (signed-byte
  839.             '(signed-byte 8))
  840.                (t
  841.             type)))
  842.     (input-type nil)
  843.     (output-type nil)
  844.     (input-size nil)
  845.     (output-size nil))
  846.     
  847.     (when (fd-stream-obuf-sap stream)
  848.       (push (fd-stream-obuf-sap stream) *available-buffers*)
  849.       (setf (fd-stream-obuf-sap stream) nil))
  850.     (when (fd-stream-ibuf-sap stream)
  851.       (push (fd-stream-ibuf-sap stream) *available-buffers*)
  852.       (setf (fd-stream-ibuf-sap stream) nil))
  853.     
  854.     (when input-p
  855.       (multiple-value-bind
  856.       (routine type size)
  857.       (pick-input-routine target-type)
  858.     (unless routine
  859.       (error "Could not find any input routine for ~S" target-type))
  860.     (setf (fd-stream-ibuf-sap stream) (next-available-buffer))
  861.     (setf (fd-stream-ibuf-length stream) bytes-per-buffer)
  862.     (setf (fd-stream-ibuf-tail stream) 0)
  863.     (if (subtypep type 'character)
  864.         (setf (fd-stream-in stream) routine
  865.           (fd-stream-bin stream) #'ill-bin
  866.           (fd-stream-n-bin stream) #'ill-bin)
  867.         (setf (fd-stream-in stream) #'ill-in
  868.           (fd-stream-bin stream) routine
  869.           (fd-stream-n-bin stream) #'fd-stream-read-n-bytes))
  870.     (setf input-size size)
  871.     (setf input-type type)))
  872.  
  873.     (when output-p
  874.       (multiple-value-bind
  875.       (routine type size)
  876.       (pick-output-routine target-type (fd-stream-buffering stream))
  877.     (unless routine
  878.       (error "Could not find any output routine for ~S buffered ~S."
  879.          (fd-stream-buffering stream)
  880.          target-type))
  881.     (setf (fd-stream-obuf-sap stream) (next-available-buffer))
  882.     (setf (fd-stream-obuf-length stream) bytes-per-buffer)
  883.     (setf (fd-stream-obuf-tail stream) 0)
  884.     (if (subtypep type 'character)
  885.       (setf (fd-stream-out stream) routine
  886.         (fd-stream-bout stream) #'ill-bout)
  887.       (setf (fd-stream-out stream)
  888.         (or (if (eql size 1)
  889.               (pick-output-routine 'base-char
  890.                        (fd-stream-buffering stream)))
  891.             #'ill-out)
  892.         (fd-stream-bout stream) routine))
  893.     (setf (fd-stream-sout stream)
  894.           (if (eql size 1) #'fd-sout #'ill-out))
  895.     (setf (fd-stream-char-pos stream) 0)
  896.     (setf output-size size)
  897.     (setf output-type type)))
  898.  
  899.     (when (and input-size output-size
  900.            (not (eq input-size output-size)))
  901.       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
  902.          input-type input-size
  903.          output-type output-size))
  904.     (setf (fd-stream-element-size stream)
  905.       (or input-size output-size))
  906.  
  907.     (setf (fd-stream-element-type stream)
  908.       (cond ((equal input-type output-type)
  909.          input-type)
  910.         ((or (null output-type) (subtypep input-type output-type))
  911.          input-type)
  912.         ((subtypep output-type input-type)
  913.          output-type)
  914.         (t
  915.          (error "Input type (~S) and output type (~S) are unrelated?"
  916.             input-type
  917.             output-type))))))
  918.  
  919. ;;; FD-STREAM-MISC-ROUTINE -- input
  920. ;;;
  921. ;;;   Handle the various misc operations on fd-stream.
  922. ;;;
  923. (defun fd-stream-misc-routine (stream operation &optional arg1 arg2)
  924.   (case operation
  925.     (:read-line
  926.      (fd-stream-read-line stream arg1 arg2))
  927.     (:listen
  928.      (or (not (eql (fd-stream-ibuf-head stream)
  929.            (fd-stream-ibuf-tail stream)))
  930.      (fd-stream-listen stream)
  931.      (setf (fd-stream-listen stream)
  932.            (eql (unix:unix-select (1+ (fd-stream-fd stream))
  933.                       (ash 1 (fd-stream-fd stream))
  934.                       0
  935.                       0
  936.                       0)
  937.             1))))
  938.     (:unread
  939.      (setf (fd-stream-unread stream) arg1)
  940.      (setf (fd-stream-listen stream) t))
  941.     (:close
  942.      (cond (arg1
  943.         ;; We got us an abort on our hands.
  944.         (when (and (fd-stream-file stream)
  945.                (fd-stream-obuf-sap stream))
  946.           ;; Can't do anything unless we know what file were dealing with,
  947.           ;; and we don't want to do anything strange unless we were
  948.           ;; writing to the file.
  949.           (if (fd-stream-original stream)
  950.           ;; Have an handle on the original, just revert.
  951.           (multiple-value-bind
  952.               (okay err)
  953.               (unix:unix-rename (fd-stream-original stream)
  954.                     (fd-stream-file stream))
  955.             (unless okay
  956.               (cerror "Go on as if nothing bad happened."
  957.                 "Could not restore ~S to it's original contents: ~A"
  958.                   (fd-stream-file stream)
  959.                   (unix:get-unix-error-msg err))))
  960.           ;; Can't restore the orignal, so nuke that puppy.
  961.           (multiple-value-bind
  962.               (okay err)
  963.               (unix:unix-unlink (fd-stream-file stream))
  964.             (unless okay
  965.               (cerror "Go on as if nothing bad happened."
  966.                   "Could not remove ~S: ~A"
  967.                   (fd-stream-file stream)
  968.                   (unix:get-unix-error-msg err)))))))
  969.        (t
  970.         (fd-stream-misc-routine stream :finish-output)
  971.         (when (and (fd-stream-original stream)
  972.                (fd-stream-delete-original stream))
  973.           (multiple-value-bind
  974.           (okay err)
  975.           (unix:unix-unlink (fd-stream-original stream))
  976.         (unless okay
  977.           (cerror "Go on as if nothing bad happened."
  978.               "Could not delete ~S during close of ~S: ~A"
  979.               (fd-stream-original stream)
  980.               stream
  981.               (unix:get-unix-error-msg err)))))))
  982.      (when (fboundp 'cancel-finalization)
  983.        (cancel-finalization stream))
  984.      (unix:unix-close (fd-stream-fd stream))
  985.      (when (fd-stream-obuf-sap stream)
  986.        (push (fd-stream-obuf-sap stream) *available-buffers*)
  987.        (setf (fd-stream-obuf-sap stream) nil))
  988.      (when (fd-stream-ibuf-sap stream)
  989.        (push (fd-stream-ibuf-sap stream) *available-buffers*)
  990.        (setf (fd-stream-ibuf-sap stream) nil))
  991.      (lisp::set-closed-flame stream))
  992.     (:clear-input
  993.      (setf (fd-stream-ibuf-head stream) 0)
  994.      (setf (fd-stream-ibuf-tail stream) 0)
  995.      (loop
  996.        (let ((count (unix:unix-select (1+ (fd-stream-fd stream))
  997.                       (ash 1 (fd-stream-fd stream))
  998.                       0 0 0)))
  999.      (cond ((eql count 1)
  1000.         (do-input stream)
  1001.         (setf (fd-stream-ibuf-head stream) 0)
  1002.         (setf (fd-stream-ibuf-tail stream) 0))
  1003.            (t
  1004.         (return))))))
  1005.     (:force-output
  1006.      (flush-output-buffer stream))
  1007.     (:finish-output
  1008.      (flush-output-buffer stream)
  1009.      (do ()
  1010.      ((null (fd-stream-output-later stream)))
  1011.        (system:serve-all-events)))
  1012.     (:element-type
  1013.      (fd-stream-element-type stream))
  1014.     (:line-length
  1015.      80)
  1016.     (:charpos
  1017.      (fd-stream-char-pos stream))
  1018.     (:file-length
  1019.      (multiple-value-bind
  1020.      (okay dev ino mode nlink uid gid rdev size
  1021.            atime mtime ctime blksize blocks)
  1022.      (unix:unix-fstat (fd-stream-fd stream))
  1023.        (declare (ignore ino nlink uid gid rdev
  1024.             atime mtime ctime blksize blocks))
  1025.        (unless okay
  1026.      (error "Error fstating ~S: ~A"
  1027.         stream
  1028.         (unix:get-unix-error-msg dev)))
  1029.        (if (zerop mode)
  1030.      nil
  1031.      (truncate size (fd-stream-element-size stream)))))
  1032.     (:file-position
  1033.      (fd-stream-file-position stream arg1))
  1034.     (:file-name
  1035.      (fd-stream-file stream))))
  1036.  
  1037. ;;; FD-STREAM-FILE-POSITION -- internal.
  1038. ;;;
  1039. (defun fd-stream-file-position (stream &optional newpos)
  1040.   (declare (type fd-stream stream)
  1041.        (type (or index (member nil :start :end)) newpos))
  1042.   (if (null newpos)
  1043.       (system:without-interrupts
  1044.     ;; First, find the position of the UNIX file descriptor in the
  1045.     ;; file.
  1046.     (multiple-value-bind
  1047.         (posn errno)
  1048.         (unix:unix-lseek (fd-stream-fd stream) 0 unix:l_incr)
  1049.       (declare (type (or index null) posn))
  1050.       (cond ((fixnump posn)
  1051.          ;; Adjust for buffered output:
  1052.          ;;  If there is any output buffered, the *real* file position
  1053.          ;; will be larger than reported by lseek because lseek
  1054.          ;; obviously cannot take into account output we have not
  1055.          ;; sent yet.
  1056.          (dolist (later (fd-stream-output-later stream))
  1057.            (incf posn (- (the index (caddr later))
  1058.                  (the index (cadr later)))))
  1059.          (incf posn (fd-stream-obuf-tail stream))
  1060.          ;; Adjust for unread input:
  1061.          ;;  If there is any input read from UNIX but not supplied to
  1062.          ;; the user of the stream, the *real* file position will
  1063.          ;; smaller than reported, because we want to look like the
  1064.          ;; unread stuff is still available.
  1065.          (decf posn (- (fd-stream-ibuf-tail stream)
  1066.                    (fd-stream-ibuf-head stream)))
  1067.          (when (fd-stream-unread stream)
  1068.            (decf posn))
  1069.          ;; Divide bytes by element size.
  1070.          (truncate posn (fd-stream-element-size stream)))
  1071.         ((eq errno unix:espipe)
  1072.          nil)
  1073.         (t
  1074.          (system:with-interrupts
  1075.            (error "Error lseek'ing ~S: ~A"
  1076.               stream
  1077.               (unix:get-unix-error-msg errno)))))))
  1078.       (let (offset origin)
  1079.     ;; Make sure we don't have any output pending, because if we move the
  1080.     ;; file pointer before writing this stuff, it will be written in the
  1081.     ;; wrong location.
  1082.     (flush-output-buffer stream)
  1083.     (do ()
  1084.         ((null (fd-stream-output-later stream)))
  1085.       (system:serve-all-events))
  1086.     ;; Clear out any pending input to force the next read to go to the
  1087.     ;; disk.
  1088.     (setf (fd-stream-unread stream) nil)
  1089.     (setf (fd-stream-ibuf-head stream) 0)
  1090.     (setf (fd-stream-ibuf-tail stream) 0)
  1091.     ;; Trash cashed value for listen, so that we check next time.
  1092.     (setf (fd-stream-listen stream) nil)
  1093.     ;; Now move it.
  1094.     (cond ((eq newpos :start)
  1095.            (setf offset 0 origin unix:l_set))
  1096.           ((eq newpos :end)
  1097.            (setf offset 0 origin unix:l_xtnd))
  1098.           ((typep newpos 'index)
  1099.            (setf offset (* newpos (fd-stream-element-size stream))
  1100.              origin unix:l_set))
  1101.           (t
  1102.            (error "Invalid position given to file-position: ~S" newpos)))
  1103.     (multiple-value-bind
  1104.         (posn errno)
  1105.         (unix:unix-lseek (fd-stream-fd stream) offset origin)
  1106.       (cond ((typep posn 'fixnum)
  1107.          t)
  1108.         ((eq errno unix:espipe)
  1109.          nil)
  1110.         (t
  1111.          (error "Error lseek'ing ~S: ~A"
  1112.             stream
  1113.             (unix:get-unix-error-msg errno))))))))
  1114.  
  1115.  
  1116.  
  1117. ;;;; Creation routines (MAKE-FD-STREAM and OPEN)
  1118.  
  1119. ;;; MAKE-FD-STREAM -- Public.
  1120. ;;;
  1121. ;;; Returns a FD-STREAM on the given file.
  1122. ;;;
  1123. (defun make-fd-stream (fd
  1124.                &key
  1125.                (input nil input-p)
  1126.                (output nil output-p)
  1127.                (element-type 'base-char)
  1128.                (buffering :full)
  1129.                timeout
  1130.                file
  1131.                original
  1132.                delete-original
  1133.                (name (if file
  1134.                  (format nil "file ~S" file)
  1135.                  (format nil "descriptor ~D" fd)))
  1136.                auto-close)
  1137.   (declare (type index fd) (type (or index null) timeout)
  1138.        (type (member :none :line :full) buffering))
  1139.   "Create a stream for the given unix file descriptor.
  1140.   If input is non-nil, allow input operations.
  1141.   If output is non-nil, allow output operations.
  1142.   If neither input nor output are specified, default to allowing input.
  1143.   Element-type indicates the element type to use (as for open).
  1144.   Buffering indicates the kind of buffering to use.
  1145.   Timeout (if true) is the number of seconds to wait for input.  If NIL (the
  1146.     default), then wait forever.  When we time out, we signal IO-TIMEOUT.
  1147.   File is the name of the file (will be returned by PATHNAME).
  1148.   Name is used to identify the stream when printed."
  1149.   (cond ((not (or input-p output-p))
  1150.      (setf input t))
  1151.     ((not (or input output))
  1152.      (error "File descriptor must be opened either for input or output.")))
  1153.   (let ((stream (%make-fd-stream :fd fd
  1154.                  :name name
  1155.                  :file file
  1156.                  :original original
  1157.                  :delete-original delete-original
  1158.                  :buffering buffering
  1159.                  :timeout timeout)))
  1160.     (set-routines stream element-type input output)
  1161.     (when (and auto-close (fboundp 'finalize))
  1162.       (finalize stream
  1163.         #'(lambda ()
  1164.             (unix:unix-close fd)
  1165.             (format *terminal-io* "** Closed file descriptor ~D~%"
  1166.                 fd))))
  1167.     stream))
  1168.  
  1169. ;;; PICK-PACKUP-NAME -- internal
  1170. ;;;
  1171. ;;; Pick a name to use for the backup file.
  1172. ;;;
  1173. (defvar *backup-extension* ".BAK"
  1174.   "This is a string that OPEN tacks on the end of a file namestring to produce
  1175.    a name for the :if-exists :rename-and-delete and :rename options.  Also,
  1176.    this can be a function that takes a namestring and returns a complete
  1177.    namestring.")
  1178. ;;;
  1179. (defun pick-backup-name (name)
  1180.   (declare (type simple-string name))
  1181.   (let ((ext *backup-extension*))
  1182.     (etypecase ext
  1183.       (simple-string (concatenate 'simple-string name ext))
  1184.       (function (funcall ext name)))))
  1185.  
  1186. ;;; ASSURE-ONE-OF -- internal
  1187. ;;;
  1188. ;;; Assure that the given arg is one of the given list of valid things.
  1189. ;;; Allow the user to fix any problems.
  1190. ;;; 
  1191. (defun assure-one-of (item list what)
  1192.   (unless (member item list)
  1193.     (loop
  1194.       (cerror "Enter new value for ~*~S"
  1195.           "~S is invalid for ~S. Must be one of~{ ~S~}"
  1196.           item
  1197.           what
  1198.           list)
  1199.       (format (the stream *query-io*) "Enter new value for ~S: " what)
  1200.       (force-output *query-io*)
  1201.       (setf item (read *query-io*))
  1202.       (when (member item list)
  1203.     (return))))
  1204.   item)
  1205.  
  1206. ;;; DO-OLD-RENAME  --  Internal
  1207. ;;;
  1208. ;;;    Rename Namestring to Original.  First, check if we have write access,
  1209. ;;; since we don't want to trash unwritable files even if we technically can.
  1210. ;;; We return true if we suceed in renaming.
  1211. ;;;
  1212. (defun do-old-rename (namestring original)
  1213.   (unless (unix:unix-access namestring unix:w_ok)
  1214.     (cerror "Try to rename it anyway." "File ~S is not writable." namestring))
  1215.   (multiple-value-bind
  1216.       (okay err)
  1217.       (unix:unix-rename namestring original)
  1218.     (cond (okay t)
  1219.       (t
  1220.        (cerror "Use :SUPERSEDE instead."
  1221.            "Could not rename ~S to ~S: ~A."
  1222.            namestring
  1223.            original
  1224.            (unix:get-unix-error-msg err))
  1225.        nil))))
  1226.  
  1227.  
  1228. ;;; OPEN -- public
  1229. ;;;
  1230. ;;;   Open the given file.
  1231. ;;;
  1232. (defun open (filename
  1233.          &key
  1234.          (direction :input)
  1235.          (element-type 'base-char)
  1236.          (if-exists nil if-exists-given)
  1237.          (if-does-not-exist nil if-does-not-exist-given))
  1238.   "Return a stream which reads from or writes to Filename.
  1239.   Defined keywords:
  1240.    :direction - one of :input, :output, :io, or :probe
  1241.    :element-type - Type of object to read or write, default BASE-CHAR
  1242.    :if-exists - one of :error, :new-version, :rename, :rename-and-delete,
  1243.                        :overwrite, :append, :supersede or nil
  1244.    :if-does-not-exist - one of :error, :create or nil
  1245.   See the manual for details."
  1246.   ;; First, make sure that DIRECTION is valid. Allow it to be changed if not.
  1247.   (setf direction
  1248.     (assure-one-of direction
  1249.                '(:input :output :io :probe)
  1250.                :direction))
  1251.  
  1252.   ;; Calculate useful stuff.
  1253.   (multiple-value-bind
  1254.       (input output mask)
  1255.       (case direction
  1256.     (:input (values t nil unix:o_rdonly))
  1257.     (:output (values nil t unix:o_wronly))
  1258.     (:io (values t t unix:o_rdwr))
  1259.     (:probe (values t nil unix:o_rdonly)))
  1260.     (declare (type index mask))
  1261.     (let* ((pathname (pathname filename))
  1262.        (namestring (unix-namestring pathname input)))
  1263.       ;; Process if-exists argument if we are doing any output.
  1264.       (cond (output
  1265.          (unless if-exists-given
  1266.            (setf if-exists
  1267.              (if (eq (pathname-version pathname) :newest)
  1268.                :new-version
  1269.                :error)))
  1270.          (setf if-exists
  1271.            (assure-one-of if-exists
  1272.                   '(:error :new-version :rename
  1273.                     :rename-and-delete :overwrite
  1274.                     :append :supersede nil)
  1275.                   :if-exists))
  1276.          (case if-exists
  1277.            ((:error nil)
  1278.         (setf mask (logior mask unix:o_excl)))
  1279.            ((:rename :rename-and-delete)
  1280.         (setf mask (logior mask unix:o_creat)))
  1281.            ((:new-version :supersede)
  1282.         (setf mask (logior mask unix:o_trunc)))
  1283.            (:append
  1284.         (setf mask (logior mask unix:o_append)))))
  1285.         (t
  1286.          (setf if-exists :ignore-this-arg)))
  1287.       
  1288.       (unless if-does-not-exist-given
  1289.     (setf if-does-not-exist
  1290.           (cond ((eq direction :input) :error)
  1291.             ((and output
  1292.               (member if-exists '(:overwrite :append)))
  1293.              :error)
  1294.             ((eq direction :probe)
  1295.              nil)
  1296.             (t
  1297.              :create))))
  1298.       (setf if-does-not-exist
  1299.         (assure-one-of if-does-not-exist
  1300.                '(:error :create nil)
  1301.                :if-does-not-exist))
  1302.       (if (eq if-does-not-exist :create)
  1303.     (setf mask (logior mask unix:o_creat)))
  1304.        
  1305.       (let ((original (if (member if-exists
  1306.                   '(:rename :rename-and-delete))
  1307.               (pick-backup-name namestring)))
  1308.         (delete-original (eq if-exists :rename-and-delete))
  1309.         (mode #o666))
  1310.     (when original
  1311.       ;; We are doing a :rename or :rename-and-delete.
  1312.       ;; Determine if the file already exists, make sure the original
  1313.       ;; file is not a directory and keep the mode
  1314.       (let ((exists
  1315.          (and namestring
  1316.               (multiple-value-bind
  1317.               (okay err/dev inode orig-mode)
  1318.               (unix:unix-stat namestring)
  1319.             (declare (ignore inode)
  1320.                  (type (or index null) orig-mode))
  1321.             (cond
  1322.              (okay
  1323.               (when (and output (= (logand orig-mode #o170000)
  1324.                            #o40000))
  1325.                 (error "Cannot open ~S for output: Is a directory."
  1326.                    namestring))
  1327.               (setf mode (logand orig-mode #o777))
  1328.               t)
  1329.              ((eql err/dev unix:enoent)
  1330.               nil)
  1331.              (t
  1332.               (error "Cannot find ~S: ~A"
  1333.                  namestring
  1334.                  (unix:get-unix-error-msg err/dev))))))))
  1335.         (unless (and exists
  1336.              (do-old-rename namestring original))
  1337.           (setf original nil)
  1338.           (setf delete-original nil)
  1339.           ;; In order to use SUPERSEDE instead, we have
  1340.           ;; to make sure unix:o_creat corresponds to
  1341.           ;; if-does-not-exist.  unix:o_creat was set
  1342.           ;; before because of if-exists being :rename.
  1343.           (unless (eq if-does-not-exist :create)
  1344.         (setf mask (logior (logandc2 mask unix:o_creat) unix:o_trunc)))
  1345.           (setf if-exists :supersede))))
  1346.     
  1347.     ;; Okay, now we can try the actual open.
  1348.     (loop
  1349.       (multiple-value-bind
  1350.           (fd errno)
  1351.           (if namestring
  1352.           (unix:unix-open namestring mask mode)
  1353.           (values nil unix:enoent))
  1354.         (cond ((numberp fd)
  1355.            (return
  1356.             (case direction
  1357.               ((:input :output :io)
  1358.                (make-fd-stream fd
  1359.                        :input input
  1360.                        :output output
  1361.                        :element-type element-type
  1362.                        :file namestring
  1363.                        :original original
  1364.                        :delete-original delete-original
  1365.                        :auto-close t))
  1366.               (:probe
  1367.                (let ((stream
  1368.                   (%make-fd-stream :name namestring :fd fd
  1369.                            :element-type element-type)))
  1370.              (close stream)
  1371.              stream)))))
  1372.           ((eql errno unix:enoent)
  1373.            (case if-does-not-exist
  1374.              (:error
  1375.               (cerror "Return NIL."
  1376.                   "Error opening ~S, ~A."
  1377.                   pathname
  1378.                   (unix:get-unix-error-msg errno)))
  1379.              (:create
  1380.               (cerror "Return NIL."
  1381.                   "Error creating ~S, path does not exist."
  1382.                   pathname)))
  1383.            (return nil))
  1384.           ((eql errno unix:eexist)
  1385.            (unless (eq nil if-exists)
  1386.              (cerror "Return NIL."
  1387.                  "Error opening ~S, ~A."
  1388.                  pathname
  1389.                  (unix:get-unix-error-msg errno)))
  1390.            (return nil))
  1391.           ((eql errno unix:eacces)
  1392.            (cerror "Try again."
  1393.               "Error opening ~S, ~A."
  1394.               pathname
  1395.               (unix:get-unix-error-msg errno)))
  1396.           (t
  1397.            (cerror "Return NIL."
  1398.                "Error opening ~S, ~A."
  1399.                pathname
  1400.                (unix:get-unix-error-msg errno))
  1401.            (return nil)))))))))
  1402.  
  1403. ;;;; Initialization.
  1404.  
  1405. (defvar *tty* nil
  1406.   "The stream connected to the controlling terminal or NIL if there is none.")
  1407. (defvar *stdin* nil
  1408.   "The stream connected to the standard input (file descriptor 0).")
  1409. (defvar *stdout* nil
  1410.   "The stream connected to the standard output (file descriptor 1).")
  1411. (defvar *stderr* nil
  1412.   "The stream connected to the standard error output (file descriptor 2).")
  1413.  
  1414. ;;; STREAM-INIT -- internal interface
  1415. ;;;
  1416. ;;; Called when the cold load is first started up.
  1417. ;;; 
  1418. (defun stream-init ()
  1419.   (stream-reinit)
  1420.   (setf *terminal-io* (make-synonym-stream '*tty*))
  1421.   (setf *standard-output* (make-synonym-stream '*stdout*))
  1422.   (setf *standard-input*
  1423.     (make-two-way-stream (make-synonym-stream '*stdin*)
  1424.                  *standard-output*))
  1425.   (setf *error-output* (make-synonym-stream '*stderr*))
  1426.   (setf *query-io* (make-synonym-stream '*terminal-io*))
  1427.   (setf *debug-io* *query-io*)
  1428.   (setf *trace-output* *standard-output*)
  1429.   nil)
  1430.  
  1431. ;;; STREAM-REINIT -- internal interface
  1432. ;;;
  1433. ;;; Called whenever a saved core is restarted.
  1434. ;;; 
  1435. (defun stream-reinit ()
  1436.   (setf *available-buffers* nil)
  1437.   (setf *stdin*
  1438.     (make-fd-stream 0 :name "Standard Input" :input t :buffering :line))
  1439.   (setf *stdout*
  1440.     (make-fd-stream 1 :name "Standard Output" :output t :buffering :line))
  1441.   (setf *stderr*
  1442.     (make-fd-stream 2 :name "Standard Error" :output t :buffering :line))
  1443.   (let ((tty (unix:unix-open "/dev/tty" unix:o_rdwr #o666)))
  1444.     (if tty
  1445.     (setf *tty*
  1446.           (make-fd-stream tty :name "the Terminal" :input t :output t
  1447.                   :buffering :line :auto-close t))
  1448.     (setf *tty* (make-two-way-stream *stdin* *stdout*))))
  1449.   nil)
  1450.  
  1451.  
  1452. ;;;; Beeping.
  1453.  
  1454. (defun default-beep-function (stream)
  1455.   (write-char #\bell stream)
  1456.   (finish-output stream))
  1457.  
  1458. (defvar *beep-function* #'default-beep-function
  1459.   "This is called in BEEP to feep the user.  It takes a stream.")
  1460.  
  1461. (defun beep (&optional (stream *terminal-io*))
  1462.   (funcall *beep-function* stream))
  1463.  
  1464.  
  1465. ;;;; File position and file length.
  1466.  
  1467. ;;; File-Position  --  Public
  1468. ;;;
  1469. ;;;    Call the misc method with the :file-position operation.
  1470. ;;;
  1471. (defun file-position (stream &optional position)
  1472.   "With one argument returns the current position within the file
  1473.   File-Stream is open to.  If the second argument is supplied, then
  1474.   this becomes the new file position.  The second argument may also
  1475.   be :start or :end for the start and end of the file, respectively."
  1476.   (unless (streamp stream)
  1477.     (error "Argument ~S is not a stream." stream))
  1478.   (funcall (stream-misc stream) stream :file-position position))
  1479.  
  1480. ;;; File-Length  --  Public
  1481. ;;;
  1482. ;;;    Like File-Position, only use :file-length.
  1483. ;;;
  1484. (defun file-length (stream)
  1485.   "This function returns the length of the file that File-Stream is open to."
  1486.   (unless (streamp stream)
  1487.     (error "Argument ~S is not a stream." stream))
  1488.   (funcall (stream-misc stream) stream :file-length))
  1489.  
  1490. ;;; File-Name  --  internal interface
  1491. ;;;
  1492. ;;;    Kind of like File-Position, but is an internal hack used by the filesys
  1493. ;;; stuff to get and set the file name.
  1494. ;;;
  1495. (defun file-name (stream &optional new-name)
  1496.   (when (fd-stream-p stream)
  1497.     (if new-name
  1498.     (setf (fd-stream-file stream) new-name)
  1499.     (fd-stream-file stream))))
  1500.