/[cmucl]/src/code/fd-stream.lisp
ViewVC logotype

Contents of /src/code/fd-stream.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.73 - (hide annotations)
Mon Nov 3 16:50:28 2003 UTC (10 years, 5 months ago) by gerd
Branch: MAIN
Changes since 1.72: +9 -1 lines
	(with-open-file (stream "test.123" :direction :output
	                        :if-exists :supersede)
	  (format stream "~S ~S ~S~%" 'these 'are 'symbols))

	(with-open-file (stream "test.123" :direction :io
	                        :if-exists :overwrite)
	  (read stream) (prin1 'insert stream))

	(with-open-file (stream "test.123")
	  (loop for line = (read-line stream nil)
	        until (null line) do (write-line line)))

	Output should be "these insertmbols"
	Output is "these are symbols\ninsert"

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

  ViewVC Help
Powered by ViewVC 1.1.5