/[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.93 - (show annotations)
Fri Jan 22 06:14:19 2010 UTC (4 years, 2 months ago) by rtoy
Branch: MAIN
Changes since 1.92: +13 -2 lines
Fix FILE-POSITION for fd-streams with a string buffer.  It was
inadvertently broken when the fast external format work was done.  The
position did not take into account the number of octets that had been
read in but not yet processed.
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 ;;;
7 (ext:file-comment
8 "$Header: /tiger/var/lib/cvsroots/cmucl/src/code/fd-stream.lisp,v 1.93 2010/01/22 06:14:19 rtoy Exp $")
9 ;;;
10 ;;; **********************************************************************
11 ;;;
12 ;;; Streams for UNIX file descriptors.
13 ;;;
14 ;;; Written by William Lott, July 1989 - January 1990.
15 ;;; Some tuning by Rob MacLachlan.
16 ;;;
17 ;;; **********************************************************************
18
19
20 (in-package "SYSTEM")
21
22 (export '(fd-stream fd-stream-p fd-stream-fd make-fd-stream
23 io-timeout beep *beep-function* output-raw-bytes
24 *tty* *stdin* *stdout* *stderr*
25 binary-text-stream))
26
27
28 (in-package "EXTENSIONS")
29
30 (export '(*backup-extension*))
31
32
33 (in-package "LISP")
34
35 (export '(file-stream file-string-length))
36
37
38 ;;;; Buffer manipulation routines.
39
40 (defvar *available-buffers* ()
41 "List of available buffers. Each buffer is an sap pointing to
42 bytes-per-buffer of memory.")
43
44 (defvar lisp::*enable-stream-buffer-p* nil)
45
46 (defconstant bytes-per-buffer (* 4 1024)
47 "Number of bytes per buffer.")
48
49 ;; This limit is rather arbitrary
50 (defconstant max-stream-element-size 1024
51 "The maximum supported byte size for a stream element-type.")
52
53 ;;; NEXT-AVAILABLE-BUFFER -- Internal.
54 ;;;
55 ;;; Returns the next available buffer, creating one if necessary.
56 ;;;
57 (declaim (inline next-available-buffer))
58 ;;;
59 (defun next-available-buffer ()
60 (if *available-buffers*
61 (pop *available-buffers*)
62 (allocate-system-memory bytes-per-buffer)))
63
64 (declaim (inline buffer-sap bref (setf bref) buffer-copy))
65
66 (defun buffer-sap (thing &optional offset)
67 (declare (type simple-stream-buffer thing) (type (or fixnum null) offset)
68 (optimize (speed 3) (space 2) (debug 0) (safety 0)
69 ;; Suppress the note about having to box up the return:
70 (ext:inhibit-warnings 3)))
71 (let ((sap (if (vectorp thing) (sys:vector-sap thing) thing)))
72 (if offset (sys:sap+ sap offset) sap)))
73
74 (defun bref (buffer index)
75 (declare (type simple-stream-buffer buffer)
76 (type (integer 0 #.most-positive-fixnum) index))
77 (sys:sap-ref-8 (buffer-sap buffer) index))
78
79 (defun (setf bref) (octet buffer index)
80 (declare (type (unsigned-byte 8) octet)
81 (type simple-stream-buffer buffer)
82 (type (integer 0 #.most-positive-fixnum) index))
83 (setf (sys:sap-ref-8 (buffer-sap buffer) index) octet))
84
85 (defun buffer-copy (src soff dst doff length)
86 (declare (type simple-stream-buffer src dst)
87 (type fixnum soff doff length))
88 (sys:without-gcing ;; is this necessary??
89 (kernel:system-area-copy (buffer-sap src) (* soff 8)
90 (buffer-sap dst) (* doff 8)
91 (* length 8))))
92
93 #-(or big-endian little-endian)
94 (eval-when (:compile-toplevel)
95 (push (c::backend-byte-order c::*target-backend*) *features*))
96
97 (defun vector-elt-width (vector)
98 ;; Return octet-width of vector elements
99 (etypecase vector
100 ;; (simple-array fixnum (*)) not supported
101 ;; (simple-array base-char (*)) treated specially; don't call this
102 ((simple-array bit (*)) 1/8)
103 ((simple-array (unsigned-byte 2) (*)) 1/4)
104 ((simple-array (unsigned-byte 4) (*)) 1/2)
105 ((simple-array (signed-byte 8) (*)) 1)
106 ((simple-array (unsigned-byte 8) (*)) 1)
107 ((simple-array (signed-byte 16) (*)) 2)
108 ((simple-array (unsigned-byte 16) (*)) 2)
109 ((simple-array (signed-byte 32) (*)) 4)
110 ((simple-array (unsigned-byte 32) (*)) 4)
111 ((simple-array single-float (*)) 4)
112 ((simple-array double-float (*)) 8)
113 ((simple-array (complex single-float) (*)) 8)
114 ((simple-array (complex double-float) (*)) 16)
115 #+long-float
116 ((simple-array long-float (*)) 10)
117 #+long-float
118 ((simple-array (complex long-float) (*)) 20)
119 #+double-double
120 ((simple-array double-double-float (*)) 16)
121 #+double-double
122 ((simple-array (complex double-double-float) (*)) 32)))
123
124 (defun endian-swap-value (vector endian-swap)
125 (case endian-swap
126 (:network-order
127 #+big-endian 0
128 ;; This is needed because the little-endian (x86) architectures
129 ;; store the lowest indexed element in the least significant part
130 ;; of a byte. On a big-endian machine (sparc, ppc), the lowest
131 ;; indexed element is at the most significant part of a byte.
132 #+little-endian
133 (typecase vector
134 ((array (unsigned-byte 4) (*))
135 -1)
136 ((array (unsigned-byte 2) (*))
137 -2)
138 ((array (unsigned-byte 1) (*))
139 -8)
140 (t
141 (1- (vector-elt-width vector)))))
142 (:byte-8 0)
143 (:byte-16 1)
144 (:byte-32 3)
145 (:byte-64 7)
146 (:byte-128 15)
147 ;; additions by Lynn Quam
148 (:machine-endian 0)
149 (:big-endian
150 #+big-endian 0
151 #+little-endian
152 (typecase vector
153 ((array (unsigned-byte 4) (*))
154 -1)
155 ((array (unsigned-byte 2) (*))
156 -2)
157 ((array (unsigned-byte 1) (*))
158 -8)
159 (t
160 (1- (vector-elt-width vector)))))
161 (:little-endian
162 #+big-endian
163 (typecase vector
164 ((array (unsigned-byte 4) (*))
165 -1)
166 ((array (unsigned-byte 2) (*))
167 -2)
168 ((array (unsigned-byte 1) (*))
169 -8)
170 (t
171 (1- (vector-elt-width vector))))
172 #+little-endian 0)
173 (otherwise endian-swap)))
174
175
176 ;;;; The FD-STREAM structure.
177
178 ;;;; Superclass defined by the ANSI Spec
179 (defstruct (file-stream
180 (:include lisp-stream)
181 (:constructor nil)
182 (:copier nil)))
183
184 (defstruct (fd-stream
185 (:print-function %print-fd-stream)
186 (:constructor %make-fd-stream)
187 (:include file-stream
188 (misc #'fd-stream-misc-routine)))
189
190 (name nil) ; The name of this stream
191 (file nil) ; The file this stream is for
192 ;;
193 ;; The backup file namestring for the old file, for :if-exists :rename or
194 ;; :rename-and-delete.
195 (original nil :type (or simple-string null))
196 (delete-original nil) ; for :if-exists :rename-and-delete
197 ;;
198 ;;; Number of bytes per element.
199 (element-size 1 :type index)
200 (element-type 'base-char) ; The type of element being transfered.
201 (fd -1 :type fixnum) ; The file descriptor
202 ;;
203 ;; Controls when the output buffer is flushed.
204 (buffering :full :type (member :full :line :none))
205 ;;
206 ;; Character position if known.
207 (char-pos nil :type (or index null))
208 ;;
209 ;; T if input is waiting on FD. :EOF if we hit EOF.
210 (listen nil :type (member nil t :eof))
211 ;;
212 ;; The input buffer.
213 (unread nil)
214 (ibuf-sap nil :type (or system-area-pointer null))
215 (ibuf-length nil :type (or index null))
216 (ibuf-head 0 :type index)
217 (ibuf-tail 0 :type index)
218
219 ;; The output buffer.
220 (obuf-sap nil :type (or system-area-pointer null))
221 (obuf-length nil :type (or index null))
222 (obuf-tail 0 :type index)
223
224 ;; Output flushed, but not written due to non-blocking io.
225 (output-later nil)
226 (handler nil)
227 ;;
228 ;; Timeout specified for this stream, or NIL if none.
229 (timeout nil :type (or index null))
230 ;;
231 ;; Pathname of the file this stream is opened to (returned by PATHNAME.)
232 (pathname nil :type (or pathname null))
233 ;;
234 ;; External format support
235 ;;
236 ;; @@ I want to use :default here, but keyword pkg isn't set up yet at boot
237 ;; so initialize to NIL and fix it in SET-ROUTINES
238 #+unicode
239 (external-format nil :type (or null keyword cons))
240 ;;
241 ;; State for octets-to-char (for reading from a stream). The
242 ;; contents of the state can be anything and is defined by the
243 ;; external format.
244 #+unicode
245 (oc-state nil)
246 ;;
247 ;; State for char-to-octets (for writing to a stream). The contents
248 ;; of the state can be anything and is defined by the external
249 ;; format. If not NIL, then the CAR is used by char-to-octets to
250 ;; hold some state information, and the CDR is available to the
251 ;; external format to hold whatever state information is needed.
252 #+unicode
253 (co-state nil)
254 #+unicode
255 (last-char-read-size 0 :type index)
256 ;; Saved state needed for (setf stream-external-format) when the
257 ;; fast string-buffer is used.
258 #+unicode
259 (saved-oc-state nil)
260 ;;
261 ;; The number of octets in in-buffer. Normally equal to
262 ;; in-buffer-length, but could be less if we reached the
263 ;; end-of-file.
264 #+unicode
265 (in-length 0 :type index))
266
267 (defun %print-fd-stream (fd-stream stream depth)
268 (declare (ignore depth) (stream stream))
269 (format stream "#<Stream for ~A>"
270 (fd-stream-name fd-stream)))
271
272 ;; CMUCL extension. This is a FD-STREAM, but it allows reading and
273 ;; writing of 8-bit characters and unsigned bytes from the stream.
274 (defstruct (binary-text-stream
275 (:print-function %print-binary-text-stream)
276 (:constructor %make-binary-text-stream)
277 (:include fd-stream)))
278
279 (defun %print-binary-text-stream (fd-stream stream depth)
280 (declare (ignore depth) (stream stream))
281 (format stream "#<Binary-text Stream for ~A>"
282 (fd-stream-name fd-stream)))
283
284 (define-condition io-timeout (stream-error)
285 ((direction :reader io-timeout-direction :initarg :direction))
286 (:report
287 (lambda (condition stream)
288 (declare (stream stream))
289 (format stream "Timeout ~(~A~)ing ~S."
290 (io-timeout-direction condition)
291 (stream-error-stream condition)))))
292
293
294 ;;;; Output routines and related noise.
295
296 (defvar *output-routines* ()
297 "List of all available output routines. Each element is a list of the
298 element-type output, the kind of buffering, the function name, and the number
299 of bytes per element.")
300
301 ;;; DO-OUTPUT-LATER -- internal
302 ;;;
303 ;;; Called by the server when we can write to the given file descriptor.
304 ;;; Attempt to write the data again. If it worked, remove the data from the
305 ;;; output-later list. If it didn't work, something is wrong.
306 ;;;
307 (defun do-output-later (stream)
308 (let* ((stuff (pop (fd-stream-output-later stream)))
309 (base (car stuff))
310 (start (cadr stuff))
311 (end (caddr stuff))
312 (reuse-sap (cadddr stuff))
313 (length (- end start)))
314 (declare (type index start end length))
315 (multiple-value-bind
316 (count errno)
317 (unix:unix-write (fd-stream-fd stream)
318 base
319 start
320 length)
321 (cond ((not count)
322 (if (= errno unix:ewouldblock)
323 (error "Write would have blocked, but SERVER told us to go.")
324 (error "While writing ~S: ~A"
325 stream (unix:get-unix-error-msg errno))))
326 ((eql count length) ; Hot damn, it worked.
327 (when reuse-sap
328 (push base *available-buffers*)))
329 ((not (null count)) ; Sorta worked.
330 (push (list base
331 (the index (+ start count))
332 end)
333 (fd-stream-output-later stream))))))
334 (unless (fd-stream-output-later stream)
335 (system:remove-fd-handler (fd-stream-handler stream))
336 (setf (fd-stream-handler stream) nil)))
337
338 ;;; OUTPUT-LATER -- internal
339 ;;;
340 ;;; Arrange to output the string when we can write on the file descriptor.
341 ;;;
342 (defun output-later (stream base start end reuse-sap)
343 (cond ((null (fd-stream-output-later stream))
344 (setf (fd-stream-output-later stream)
345 (list (list base start end reuse-sap)))
346 (setf (fd-stream-handler stream)
347 (system:add-fd-handler (fd-stream-fd stream)
348 :output
349 #'(lambda (fd)
350 (declare (ignore fd))
351 (do-output-later stream)))))
352 (t
353 (nconc (fd-stream-output-later stream)
354 (list (list base start end reuse-sap)))))
355 (when reuse-sap
356 (let ((new-buffer (next-available-buffer)))
357 (setf (fd-stream-obuf-sap stream) new-buffer)
358 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
359
360 ;;; DO-OUTPUT -- internal
361 ;;;
362 ;;; Output the given noise. Check to see if there are any pending writes. If
363 ;;; so, just queue this one. Otherwise, try to write it. If this would block,
364 ;;; queue it.
365 ;;;
366 (defun do-output (stream base start end reuse-sap)
367 (declare (type fd-stream stream)
368 (type (or system-area-pointer (simple-array * (*))) base)
369 (type index start end))
370 (if (not (null (fd-stream-output-later stream))) ; something buffered.
371 (progn
372 (output-later stream base start end reuse-sap)
373 ;; ### check to see if any of this noise can be output
374 )
375 (let ((length (- end start)))
376 (multiple-value-bind
377 (count errno)
378 (unix:unix-write (fd-stream-fd stream) base start length)
379 (cond ((not count)
380 (if (= errno unix:ewouldblock)
381 (output-later stream base start end reuse-sap)
382 (error 'simple-stream-error
383 :stream stream
384 :format-control "while writing: ~A"
385 :format-arguments (list (unix:get-unix-error-msg errno)))))
386 ((not (eql count length))
387 (output-later stream base (the index (+ start count))
388 end reuse-sap)))))))
389
390 #+unicode
391 (stream::def-ef-macro ef-flush (extfmt lisp stream::+ef-max+ stream::+ef-flush+)
392 `(lambda (stream)
393 (declare (type fd-stream stream))
394 (let* ((tail (fd-stream-obuf-tail stream)))
395 (declare (type index tail))
396 (cond
397 ((stream::ef-flush-state ,(stream::find-external-format extfmt))
398 (stream::flush-state ,extfmt
399 (fd-stream-co-state stream)
400 (lambda (byte)
401 (when (= tail len)
402 (do-output stream sap 0 tail t)
403 (setq sap (fd-stream-obuf-sap stream)
404 tail 0))
405 (setf (bref sap (1- (incf tail))) byte)))
406 (setf (fd-stream-obuf-tail stream) tail))
407 (t
408 ;; No flush-state function, so just output a replacement
409 ;; character. We hack the co-state to what we need for this
410 ;; to work. This should be ok because we're closing the
411 ;; file anyway.
412 (let ((state (fd-stream-co-state stream)))
413 (when (and state (car state))
414 (setf (fd-stream-co-state stream)
415 (cons nil (cdr state)))
416 (funcall (ef-cout (fd-stream-external-format stream))
417 stream (code-char stream::+replacement-character-code+))))))
418 (values))))
419
420 ;;; FLUSH-OUTPUT-BUFFER -- internal
421 ;;;
422 ;;; Flush any data in the output buffer.
423 ;;;
424 (defun flush-output-buffer (stream)
425 (let ((length (fd-stream-obuf-tail stream)))
426 (unless (= length 0)
427 (do-output stream (fd-stream-obuf-sap stream) 0 length t)
428 (setf (fd-stream-obuf-tail stream) 0))))
429
430 ;;; DEF-OUTPUT-ROUTINES -- internal
431 ;;;
432 ;;; Define output routines that output numbers size bytes long for the
433 ;;; given bufferings. Use body to do the actual output.
434 ;;;
435 (defmacro def-output-routines ((name size &rest bufferings) &body body)
436 (declare (optimize (speed 1)))
437 (cons 'progn
438 (mapcar
439 #'(lambda (buffering)
440 (let ((function
441 (intern (let ((*print-case* :upcase))
442 (format nil name (car buffering))))))
443 `(progn
444 (defun ,function (stream byte)
445 ,(unless (eq (car buffering) :none)
446 `(when (< (fd-stream-obuf-length stream)
447 (+ (fd-stream-obuf-tail stream)
448 ,size))
449 (flush-output-buffer stream)))
450 ;;
451 ;; If there is any input read from UNIX but not
452 ;; supplied to the user of the stream, reposition
453 ;; to the real file position as seen from Lisp.
454 ,(unless (eq (car buffering) :none)
455 `(when (> (fd-stream-ibuf-tail stream)
456 (fd-stream-ibuf-head stream))
457 (file-position stream (file-position stream))))
458 ,@body
459 (incf (fd-stream-obuf-tail stream) ,size)
460 ,(ecase (car buffering)
461 (:none
462 `(flush-output-buffer stream))
463 (:line
464 `(when (eql (char-code byte) (char-code #\Newline))
465 (flush-output-buffer stream)))
466 (:full
467 ))
468 (values))
469 (setf *output-routines*
470 (nconc *output-routines*
471 ',(mapcar
472 #'(lambda (type)
473 (list type
474 (car buffering)
475 function
476 size))
477 (cdr buffering)))))))
478 bufferings)))
479
480 #-unicode
481 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
482 1
483 (:none character)
484 (:line character)
485 (:full character))
486 (if (char= byte #\Newline)
487 (setf (fd-stream-char-pos stream) 0)
488 (incf (fd-stream-char-pos stream)))
489 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
490 (char-code byte)))
491
492 #+unicode
493 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
494 1
495 (:none character)
496 (:line character)
497 (:full character))
498 (if (char= byte #\Newline)
499 (setf (fd-stream-char-pos stream) 0)
500 (incf (fd-stream-char-pos stream)))
501 ;; FIXME! We only use the low 8 bits of a character!
502 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
503 (logand #xff (char-code byte))))
504
505 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
506 1
507 (:none (unsigned-byte 8))
508 (:full (unsigned-byte 8)))
509 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
510 byte))
511
512 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
513 1
514 (:none (signed-byte 8))
515 (:full (signed-byte 8)))
516 (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
517 (fd-stream-obuf-tail stream))
518 byte))
519
520 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
521 2
522 (:none (unsigned-byte 16))
523 (:full (unsigned-byte 16)))
524 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
525 byte))
526
527 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
528 2
529 (:none (signed-byte 16))
530 (:full (signed-byte 16)))
531 (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
532 (fd-stream-obuf-tail stream))
533 byte))
534
535 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
536 4
537 (:none (unsigned-byte 32))
538 (:full (unsigned-byte 32)))
539 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
540 byte))
541
542 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
543 4
544 (:none (signed-byte 32))
545 (:full (signed-byte 32)))
546 (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
547 (fd-stream-obuf-tail stream))
548 byte))
549
550 (stream::def-ef-macro ef-cout (extfmt lisp stream::+ef-max+ stream::+ef-cout+)
551 `(lambda (stream char)
552 (declare (type fd-stream stream)
553 (type character char)
554 (optimize (speed 3) (space 0) (debug 0) (safety 0)))
555 ;; If there is any input read from UNIX but not
556 ;; supplied to the user of the stream, reposition
557 ;; to the real file position as seen from Lisp.
558 (when (> (fd-stream-ibuf-tail stream)
559 (fd-stream-ibuf-head stream))
560 (file-position stream (file-position stream)))
561 (let* ((sap (fd-stream-obuf-sap stream))
562 (len (fd-stream-obuf-length stream))
563 (tail (fd-stream-obuf-tail stream)))
564 (declare (type sys:system-area-pointer sap) (type index len tail))
565 (stream::char-to-octets ,extfmt
566 char
567 (fd-stream-co-state stream)
568 (lambda (byte)
569 (when (= tail len)
570 (do-output stream sap 0 tail t)
571 (setq sap (fd-stream-obuf-sap stream)
572 tail 0))
573 (setf (bref sap (1- (incf tail))) byte)))
574 (setf (fd-stream-obuf-tail stream) tail))
575 (if (char= char #\Newline)
576 (setf (fd-stream-char-pos stream) 0)
577 (incf (fd-stream-char-pos stream)))
578 (ecase (fd-stream-buffering stream)
579 (:none (flush-output-buffer stream))
580 (:line (when (char= char #\Newline) (flush-output-buffer stream)))
581 (:full #| do nothing |#))
582 (values)))
583
584
585 ;;; OUTPUT-RAW-BYTES -- public
586 ;;;
587 ;;; Does the actual output. If there is space to buffer the string, buffer
588 ;;; it. If the string would normally fit in the buffer, but doesn't because
589 ;;; of other stuff in the buffer, flush the old noise out of the buffer and
590 ;;; put the string in it. Otherwise we have a very long string, so just
591 ;;; send it directly (after flushing the buffer, of course).
592 ;;;
593 (defun output-raw-bytes (stream thing &optional start end)
594 "Output THING to stream. THING can be any kind of vector or a sap. If THING
595 is a SAP, END must be supplied (as length won't work)."
596 (let ((start (or start 0))
597 (end (or end (length (the (simple-array * (*)) thing)))))
598 (declare (type index start end))
599 ;;
600 ;; If there is any input read from UNIX but not
601 ;; supplied to the user of the stream, reposition
602 ;; to the real file position as seen from Lisp.
603 (when (> (fd-stream-ibuf-tail stream)
604 (fd-stream-ibuf-head stream))
605 (file-position stream (file-position stream)))
606 (let* ((len (fd-stream-obuf-length stream))
607 (tail (fd-stream-obuf-tail stream))
608 (space (- len tail))
609 (bytes (- end start))
610 (newtail (+ tail bytes)))
611 (cond ((minusp bytes) ; Error case
612 (cerror "Just go on as if nothing happened..."
613 "~S called with :END before :START!"
614 'output-raw-bytes))
615 ((zerop bytes)) ; Easy case
616 ((<= bytes space)
617 (if (system-area-pointer-p thing)
618 (system-area-copy thing
619 (* start vm:byte-bits)
620 (fd-stream-obuf-sap stream)
621 (* tail vm:byte-bits)
622 (* bytes vm:byte-bits))
623 (copy-to-system-area thing
624 (+ (* start vm:byte-bits)
625 (* vm:vector-data-offset vm:word-bits))
626 (fd-stream-obuf-sap stream)
627 (* tail vm:byte-bits)
628 (* bytes vm:byte-bits)))
629 (setf (fd-stream-obuf-tail stream) newtail))
630 ((<= bytes len)
631 (flush-output-buffer stream)
632 (if (system-area-pointer-p thing)
633 (system-area-copy thing
634 (* start vm:byte-bits)
635 (fd-stream-obuf-sap stream)
636 0
637 (* bytes vm:byte-bits))
638 (copy-to-system-area thing
639 (+ (* start vm:byte-bits)
640 (* vm:vector-data-offset vm:word-bits))
641 (fd-stream-obuf-sap stream)
642 0
643 (* bytes vm:byte-bits)))
644 (setf (fd-stream-obuf-tail stream) bytes))
645 (t
646 (flush-output-buffer stream)
647 (do-output stream thing start end nil))))))
648
649 ;;; FD-SOUT -- internal
650 ;;;
651 ;;; Routine to use to output a string. If the stream is unbuffered, slam
652 ;;; the string down the file descriptor, otherwise use OUTPUT-RAW-BYTES to
653 ;;; buffer the string. Update charpos by checking to see where the last newline
654 ;;; was.
655 ;;;
656 ;;; Note: some bozos (the FASL dumper) call write-string with things other
657 ;;; than strings. Therefore, we must make sure we have a string before calling
658 ;;; position on it.
659 ;;;
660
661 (stream::def-ef-macro ef-sout (extfmt lisp stream::+ef-max+ stream::+ef-sout+)
662 `(lambda (stream string start end)
663 (declare (type fd-stream stream)
664 (type simple-string string)
665 (type index start end)
666 (optimize (speed 3) (space 0) (safety 0) (debug 0)))
667 ;; If there is any input read from UNIX but not
668 ;; supplied to the user of the stream, reposition
669 ;; to the real file position as seen from Lisp.
670 ;; (maybe the caller should do this?)
671 (when (> (fd-stream-ibuf-tail stream)
672 (fd-stream-ibuf-head stream))
673 (file-position stream (file-position stream)))
674 (let* ((sap (fd-stream-obuf-sap stream))
675 (len (fd-stream-obuf-length stream))
676 (tail (fd-stream-obuf-tail stream)))
677 (declare (type sys:system-area-pointer sap) (type index len tail))
678 (dotimes (i (- end start))
679 (stream::char-to-octets ,extfmt
680 (schar string (+ i start))
681 (fd-stream-co-state stream)
682 (lambda (byte)
683 (when (= tail len)
684 (do-output stream sap 0 tail t)
685 (setq sap (fd-stream-obuf-sap stream)
686 tail 0))
687 (setf (bref sap (1- (incf tail))) byte))))
688 (setf (fd-stream-obuf-tail stream) tail))))
689
690
691 #-unicode
692 (defun fd-sout (stream thing start end)
693 (let ((start (or start 0))
694 (end (or end (length (the vector thing)))))
695 (declare (type index start end))
696 (if (stringp thing)
697 (let ((last-newline (and (find #\newline (the simple-string thing)
698 :start start :end end)
699 (position #\newline (the simple-string thing)
700 :from-end t
701 :start start
702 :end end))))
703 (ecase (fd-stream-buffering stream)
704 (:full
705 (output-raw-bytes stream thing start end))
706 (:line
707 (output-raw-bytes stream thing start end)
708 (when last-newline
709 (flush-output-buffer stream)))
710 (:none
711 (do-output stream thing start end nil)))
712 (if last-newline
713 (setf (fd-stream-char-pos stream)
714 (- end last-newline 1))
715 (incf (fd-stream-char-pos stream)
716 (- end start))))
717 (ecase (fd-stream-buffering stream)
718 ((:line :full)
719 (output-raw-bytes stream thing start end))
720 (:none
721 (do-output stream thing start end nil))))))
722
723 #+unicode
724 ;; Temporary. The final version is defined in fd-stream-extfmt.lisp
725 (defun fd-sout (stream thing start end)
726 (declare (type string thing))
727 (let ((start (or start 0))
728 (end (or end (length (the vector thing)))))
729 (declare (type index start end))
730 (cond
731 ((stringp thing) ; FIXME - remove this test
732 (let ((out (fd-stream-out stream)))
733 (do ((index start (+ index 1)))
734 ((>= index end))
735 (funcall out stream (elt thing index))))))))
736
737 (defmacro output-wrapper ((stream size buffering) &body body)
738 (let ((stream-var (gensym)))
739 `(let ((,stream-var ,stream))
740 ,(unless (eq (car buffering) :none)
741 `(when (< (fd-stream-obuf-length ,stream-var)
742 (+ (fd-stream-obuf-tail ,stream-var)
743 ,size))
744 (flush-output-buffer ,stream-var)))
745 ,(unless (eq (car buffering) :none)
746 `(when (> (fd-stream-ibuf-tail ,stream-var)
747 (fd-stream-ibuf-head ,stream-var))
748 (file-position ,stream-var (file-position ,stream-var))))
749
750 ,@body
751 (incf (fd-stream-obuf-tail ,stream-var) ,size)
752 ,(ecase (car buffering)
753 (:none
754 `(flush-output-buffer ,stream-var))
755 (:line
756 `(when (eq (char-code byte) (char-code #\Newline))
757 (flush-output-buffer ,stream-var)))
758 (:full))
759 (values))))
760
761 ;;; PICK-OUTPUT-ROUTINE -- internal
762 ;;;
763 ;;; Find an output routine to use given the type and buffering. Return as
764 ;;; multiple values the routine, the real type transfered, and the number of
765 ;;; bytes per element.
766 ;;;
767 (defun pick-output-routine (type buffering)
768 (dolist (entry *output-routines*)
769 (when (and (subtypep type (car entry))
770 (eq buffering (cadr entry)))
771 (return-from pick-output-routine
772 (values (symbol-function (caddr entry))
773 (car entry)
774 (cadddr entry)))))
775 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
776 (loop for i from 40 by 8 to max-stream-element-size ; ARB (KLUDGE)
777 if (subtypep type `(unsigned-byte ,i))
778 do (return-from pick-output-routine
779 (values
780 (ecase buffering
781 (:none
782 (lambda (stream byte)
783 (output-wrapper (stream (/ i 8) (:none))
784 (loop for j from 0 below (/ i 8)
785 do (setf (sap-ref-8
786 (fd-stream-obuf-sap stream)
787 (+ j (fd-stream-obuf-tail stream)))
788 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
789 (:full
790 (lambda (stream byte)
791 (output-wrapper (stream (/ i 8) (:full))
792 (loop for j from 0 below (/ i 8)
793 do (setf (sap-ref-8
794 (fd-stream-obuf-sap stream)
795 (+ j (fd-stream-obuf-tail stream)))
796 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
797 `(unsigned-byte ,i)
798 (/ i 8))))
799 (loop for i from 40 by 8 to max-stream-element-size ; ARB (KLUDGE)
800 if (subtypep type `(signed-byte ,i))
801 do (return-from pick-output-routine
802 (values
803 (ecase buffering
804 (:none
805 (lambda (stream byte)
806 (output-wrapper (stream (/ i 8) (:none))
807 (loop for j from 0 below (/ i 8)
808 do (setf (sap-ref-8
809 (fd-stream-obuf-sap stream)
810 (+ j (fd-stream-obuf-tail stream)))
811 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
812 (:full
813 (lambda (stream byte)
814 (output-wrapper (stream (/ i 8) (:full))
815 (loop for j from 0 below (/ i 8)
816 do (setf (sap-ref-8
817 (fd-stream-obuf-sap stream)
818 (+ j (fd-stream-obuf-tail stream)))
819 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
820 `(signed-byte ,i)
821 (/ i 8)))))
822
823 ;;;; Input routines and related noise.
824
825 (defvar *input-routines* ()
826 "List of all available input routines. Each element is a list of the
827 element-type input, the function name, and the number of bytes per element.")
828
829 ;;; DO-INPUT -- internal
830 ;;;
831 ;;; Fills the input buffer, and returns the first character. Throws to
832 ;;; eof-input-catcher if the eof was reached. Drops into system:server if
833 ;;; necessary.
834 ;;;
835 (defun do-input (stream)
836 (let ((fd (fd-stream-fd stream))
837 (ibuf-sap (fd-stream-ibuf-sap stream))
838 (buflen (fd-stream-ibuf-length stream))
839 (head (fd-stream-ibuf-head stream))
840 (lcrs #-unicode 0
841 #+unicode (fd-stream-last-char-read-size stream))
842 (tail (fd-stream-ibuf-tail stream)))
843 (declare (type index head lcrs tail))
844 (unless (zerop head)
845 (cond ((eql head tail)
846 (setf head lcrs)
847 (setf tail lcrs)
848 (setf (fd-stream-ibuf-head stream) lcrs)
849 (setf (fd-stream-ibuf-tail stream) lcrs))
850 (t
851 (decf tail (- head lcrs))
852 (system-area-copy ibuf-sap (* (- head lcrs) vm:byte-bits)
853 ibuf-sap 0 (* tail vm:byte-bits))
854 (setf head lcrs)
855 (setf (fd-stream-ibuf-head stream) lcrs)
856 (setf (fd-stream-ibuf-tail stream) tail))))
857 (setf (fd-stream-listen stream) nil)
858 (multiple-value-bind
859 (count errno)
860 (alien:with-alien ((read-fds (alien:struct unix:fd-set)))
861 (unix:fd-zero read-fds)
862 (unix:fd-set fd read-fds)
863 (unix:unix-fast-select (1+ fd) (alien:addr read-fds) nil nil 0 0))
864 ;; Wait if input is not available or if interrupted.
865 (when (or (eql count 0)
866 (and (not count) (eql errno unix:eintr)))
867 (unless #-mp (system:wait-until-fd-usable
868 fd :input (fd-stream-timeout stream))
869 #+mp (mp:process-wait-until-fd-usable
870 fd :input (fd-stream-timeout stream))
871 (error 'io-timeout :stream stream :direction :read))))
872 (multiple-value-bind
873 (count errno)
874 (unix:unix-read fd
875 (system:int-sap (+ (system:sap-int ibuf-sap) tail))
876 (- buflen tail))
877 (cond ((null count)
878 ;; What kinds of errors do we want to look at and what do
879 ;; we want them to do?
880 (cond ((eql errno unix:ewouldblock)
881 (unless #-mp (system:wait-until-fd-usable
882 fd :input (fd-stream-timeout stream))
883 #+mp (mp:process-wait-until-fd-usable
884 fd :input (fd-stream-timeout stream))
885 (error 'io-timeout :stream stream :direction :read))
886 (do-input stream))
887 ((eql errno unix:econnreset)
888 (error 'socket-error
889 :format-control "Socket connection reset: ~A"
890 :format-arguments (list (unix:get-unix-error-msg errno))
891 :errno errno))
892 (t
893 (error "Error reading ~S: ~A"
894 stream
895 (unix:get-unix-error-msg errno)))))
896 ((zerop count)
897 (setf (fd-stream-listen stream) :eof)
898 (throw 'eof-input-catcher nil))
899 (t
900 (incf (fd-stream-ibuf-tail stream) count))))))
901
902 ;;; INPUT-AT-LEAST -- internal
903 ;;;
904 ;;; Makes sure there are at least ``bytes'' number of bytes in the input
905 ;;; buffer. Keeps calling do-input until that condition is met.
906 ;;;
907 (defmacro input-at-least (stream bytes)
908 (let ((stream-var (gensym))
909 (bytes-var (gensym)))
910 `(let ((,stream-var ,stream)
911 (,bytes-var ,bytes))
912 (loop
913 (when (>= (- (fd-stream-ibuf-tail ,stream-var)
914 (fd-stream-ibuf-head ,stream-var))
915 ,bytes-var)
916 (return))
917 (do-input ,stream-var)))))
918
919 ;;; INPUT-WRAPPER -- internal
920 ;;;
921 ;;; Macro to wrap around all input routines to handle eof-error noise.
922 ;;;
923 (defmacro input-wrapper ((stream bytes eof-error eof-value &optional type) &body read-forms)
924 (let ((stream-var (gensym))
925 (element-var (gensym)))
926 `(let ((,stream-var ,stream))
927 (if (fd-stream-unread ,stream-var) ;;@@
928 (prog1
929 ,(if (eq type 'character)
930 `(fd-stream-unread ,stream-var)
931 `(char-code (fd-stream-unread ,stream-var)))
932 (setf (fd-stream-unread ,stream-var) nil)
933 (setf (fd-stream-listen ,stream-var) nil))
934 (let ((,element-var
935 (catch 'eof-input-catcher
936 (input-at-least ,stream-var ,bytes)
937 ,@read-forms)))
938 (cond (,element-var
939 (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
940 ,element-var)
941 (t
942 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
943
944 ;;; DEF-INPUT-ROUTINE -- internal
945 ;;;
946 ;;; Defines an input routine.
947 ;;;
948 (defmacro def-input-routine (name
949 (type size sap head)
950 &rest body)
951 `(progn
952 (defun ,name (stream eof-error eof-value)
953 (input-wrapper (stream ,size eof-error eof-value ,type)
954 (let ((,sap (fd-stream-ibuf-sap stream))
955 (,head (fd-stream-ibuf-head stream)))
956 ,@body)))
957 (setf *input-routines*
958 (nconc *input-routines*
959 (list (list ',type ',name ',size))))))
960
961 ;;; INPUT-CHARACTER -- internal
962 ;;;
963 ;;; Routine to use in stream-in slot for reading string chars.
964 ;;;
965 (def-input-routine input-character
966 (character 1 sap head)
967 (code-char (sap-ref-8 sap head)))
968
969 ;;; INPUT-UNSIGNED-8BIT-BYTE -- internal
970 ;;;
971 ;;; Routine to read in an unsigned 8 bit number.
972 ;;;
973 (def-input-routine input-unsigned-8bit-byte
974 ((unsigned-byte 8) 1 sap head)
975 (sap-ref-8 sap head))
976
977 ;;; INPUT-SIGNED-8BIT-BYTE -- internal
978 ;;;
979 ;;; Routine to read in a signed 8 bit number.
980 ;;;
981 (def-input-routine input-signed-8bit-number
982 ((signed-byte 8) 1 sap head)
983 (signed-sap-ref-8 sap head))
984
985 ;;; INPUT-UNSIGNED-16BIT-BYTE -- internal
986 ;;;
987 ;;; Routine to read in an unsigned 16 bit number.
988 ;;;
989 (def-input-routine input-unsigned-16bit-byte
990 ((unsigned-byte 16) 2 sap head)
991 (sap-ref-16 sap head))
992
993 ;;; INPUT-SIGNED-16BIT-BYTE -- internal
994 ;;;
995 ;;; Routine to read in a signed 16 bit number.
996 ;;;
997 (def-input-routine input-signed-16bit-byte
998 ((signed-byte 16) 2 sap head)
999 (signed-sap-ref-16 sap head))
1000
1001 ;;; INPUT-UNSIGNED-32BIT-BYTE -- internal
1002 ;;;
1003 ;;; Routine to read in a unsigned 32 bit number.
1004 ;;;
1005 (def-input-routine input-unsigned-32bit-byte
1006 ((unsigned-byte 32) 4 sap head)
1007 (sap-ref-32 sap head))
1008
1009 ;;; INPUT-SIGNED-32BIT-BYTE -- internal
1010 ;;;
1011 ;;; Routine to read in a signed 32 bit number.
1012 ;;;
1013 (def-input-routine input-signed-32bit-byte
1014 ((signed-byte 32) 4 sap head)
1015 (signed-sap-ref-32 sap head))
1016
1017 (stream::def-ef-macro ef-cin (extfmt lisp stream::+ef-max+ stream::+ef-cin+)
1018 `(lambda (stream eof-error-p eof-value)
1019 (declare (type fd-stream stream)
1020 #|(optimize (speed 3) (space 0) (debug 0) (safety 0))|#)
1021 (let* ((head (fd-stream-ibuf-head stream))
1022 (ch (catch 'eof-input-catcher
1023 (stream::octets-to-char ,extfmt
1024 (fd-stream-oc-state stream)
1025 (fd-stream-last-char-read-size stream)
1026 ;;@@ Note: need proper EOF handling...
1027 (progn
1028 (when (= head (fd-stream-ibuf-tail stream))
1029 (let ((sofar (- head (fd-stream-ibuf-head
1030 stream))))
1031 (do-input stream)
1032 (setf head (+ (fd-stream-ibuf-head stream)
1033 sofar))))
1034 (bref (fd-stream-ibuf-sap stream)
1035 (1- (incf head))))
1036 (lambda (n) (decf head n))))))
1037 (declare (type index head))
1038 (if ch
1039 (progn
1040 (setf (fd-stream-ibuf-head stream) head)
1041 ch)
1042 (eof-or-lose stream eof-error-p eof-value)))))
1043
1044 #+(or)
1045 (stream::def-ef-macro ef-sin (extfmt lisp stream::+ef-max+ stream::+ef-sin+)
1046 `(lambda (stream string char start end)
1047 (declare (type fd-stream stream)
1048 (type simple-string string)
1049 (type (or character null) char)
1050 (type index start end)
1051 (optimize (speed 3) (space 0) (debug 0) (safety 0)))
1052 (let ((sap (fd-stream-ibuf-sap stream))
1053 (head (fd-stream-ibuf-head stream))
1054 (tail (fd-stream-ibuf-tail stream))
1055 (curr start))
1056 (declare (type sys:system-area-pointer sap)
1057 (type index head tail curr))
1058 (loop
1059 ;;@@ Fix EOF handling
1060 (let* ((sz 0)
1061 (ch (catch 'eof-input-catcher
1062 (stream::octets-to-char ,extfmt
1063 (fd-stream-oc-state stream)
1064 sz
1065 (progn
1066 (when (= head tail)
1067 (let ((sofar (- head
1068 (fd-stream-ibuf-head
1069 stream))))
1070 (do-input stream)
1071 (setq head
1072 (+ (fd-stream-ibuf-head
1073 stream)
1074 sofar)
1075 tail
1076 (fd-stream-ibuf-tail
1077 stream))))
1078 (bref sap (1- (incf head))))
1079 (lambda (n) (decf head n))))))
1080 (declare (type index sz)
1081 (type (or null character) ch))
1082 (when (null ch)
1083 (return (values (- curr start) :eof)))
1084 (setf (fd-stream-last-char-read-size stream) sz)
1085 (incf (fd-stream-ibuf-head stream) sz)
1086 (when (and char (char= ch char))
1087 (return (values (- curr start) t)))
1088 (setf (schar string (1- (incf curr))) ch)
1089 (when (= curr end)
1090 (return (values (- curr start) nil))))))))
1091
1092 ;;; PICK-INPUT-ROUTINE -- internal
1093 ;;;
1094 ;;; Find an input routine to use given the type. Return as multiple values
1095 ;;; the routine, the real type transfered, and the number of bytes per element.
1096 ;;;
1097 (defun pick-input-routine (type)
1098 (dolist (entry *input-routines*)
1099 (when (subtypep type (car entry))
1100 (return-from pick-input-routine
1101 (values (symbol-function (cadr entry))
1102 (car entry)
1103 (caddr entry)))))
1104 ;; FIXME: let's do it the hard way, then (but ignore things like
1105 ;; endianness, efficiency, and the necessary coupling between these
1106 ;; and the output routines). -- CSR, 2004-02-09
1107 (loop for i from 40 by 8 to max-stream-element-size ; ARB (well, KLUDGE really)
1108 if (subtypep type `(unsigned-byte ,i))
1109 do (return-from pick-input-routine
1110 (values
1111 (lambda (stream eof-error eof-value)
1112 (input-wrapper (stream (/ i 8) eof-error eof-value)
1113 (let ((sap (fd-stream-ibuf-sap stream))
1114 (head (fd-stream-ibuf-head stream)))
1115 (loop for j from 0 below (/ i 8)
1116 with result = 0
1117 do (setf result
1118 (+ (* 256 result)
1119 (sap-ref-8 sap (+ head j))))
1120 finally (return result)))))
1121 `(unsigned-byte ,i)
1122 (/ i 8))))
1123 (loop for i from 40 by 8 to max-stream-element-size ; ARB (well, KLUDGE really)
1124 if (subtypep type `(signed-byte ,i))
1125 do (return-from pick-input-routine
1126 (values
1127 (lambda (stream eof-error eof-value)
1128 (input-wrapper (stream (/ i 8) eof-error eof-value)
1129 (let ((sap (fd-stream-ibuf-sap stream))
1130 (head (fd-stream-ibuf-head stream)))
1131 (loop for j from 0 below (/ i 8)
1132 with result = 0
1133 do (setf result
1134 (+ (* 256 result)
1135 (sap-ref-8 sap (+ head j))))
1136 finally (return (if (logbitp (1- i) result)
1137 (dpb result (byte i 0) -1)
1138 result))))))
1139 `(signed-byte ,i)
1140 (/ i 8)))))
1141
1142 ;;; STRING-FROM-SAP -- internal
1143 ;;;
1144 ;;; Returns a string constructed from the sap, start, and end.
1145 ;;;
1146 (defun string-from-sap (sap start end)
1147 (declare (type index start end))
1148 (let* ((length (- end start))
1149 (string (make-string length)))
1150 (copy-from-system-area sap (* start vm:byte-bits)
1151 string (* vm:vector-data-offset vm:word-bits)
1152 (* length vm:byte-bits))
1153 string))
1154
1155 #|
1156 ;;; FD-STREAM-READ-N-BYTES -- internal
1157 ;;;
1158 ;;; This version waits using server. I changed to the non-server version
1159 ;;; because it allows this method to be used by CLX w/o confusing serve-event.
1160 ;;; The non-server method is also significantly more efficient for large
1161 ;;; reads. -- Ram
1162 ;;;
1163 ;;; The n-bin routine.
1164 ;;;
1165 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
1166 (declare (type stream stream) (type index start requested))
1167 (let* ((sap (fd-stream-ibuf-sap stream))
1168 (elsize (fd-stream-element-size stream))
1169 (offset (* elsize start))
1170 (bytes (* elsize requested))
1171 (result
1172 (catch 'eof-input-catcher
1173 (loop
1174 (input-at-least stream 1)
1175 (let* ((head (fd-stream-ibuf-head stream))
1176 (tail (fd-stream-ibuf-tail stream))
1177 (available (- tail head))
1178 (copy (min available bytes)))
1179 (if (typep buffer 'system-area-pointer)
1180 (system-area-copy sap (* head vm:byte-bits)
1181 buffer (* offset vm:byte-bits)
1182 (* copy vm:byte-bits))
1183 (copy-from-system-area sap (* head vm:byte-bits)
1184 buffer (+ (* offset vm:byte-bits)
1185 (* vm:vector-data-offset
1186 vm:word-bits))
1187 (* copy vm:byte-bits)))
1188 (incf (fd-stream-ibuf-head stream) copy)
1189 (incf offset copy)
1190 (decf bytes copy))
1191 (when (zerop bytes)
1192 (return requested))))))
1193 (or result
1194 (eof-or-lose stream eof-error-p
1195 (- requested (/ bytes elsize))))))
1196 |#
1197
1198
1199 ;;; FD-STREAM-READ-N-BYTES -- internal
1200 ;;;
1201 ;;; The N-Bin method for FD-STREAMs. This doesn't use the SERVER; it blocks
1202 ;;; in UNIX-READ. This allows the method to be used to implement reading
1203 ;;; for CLX. It is generally used where there is a definite amount of reading
1204 ;;; to be done, so blocking isn't too problematical.
1205 ;;;
1206 ;;; We copy buffered data into the buffer. If there is enough, just return.
1207 ;;; Otherwise, we see if the amount of additional data needed will fit in the
1208 ;;; stream buffer. If not, inhibit GCing (so we can have a SAP into the Buffer
1209 ;;; argument), and read directly into the user supplied buffer. Otherwise,
1210 ;;; read a buffer-full into the stream buffer and then copy the amount we need
1211 ;;; out.
1212 ;;;
1213 ;;; We loop doing the reads until we either get enough bytes or hit EOF. We
1214 ;;; must loop when eof-errorp is T because some streams (like pipes) may return
1215 ;;; a partial amount without hitting EOF.
1216 ;;;
1217 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
1218 (declare (type stream stream) (type index start requested))
1219 (let* ((sap (fd-stream-ibuf-sap stream))
1220 (offset start)
1221 (head (fd-stream-ibuf-head stream))
1222 (tail (fd-stream-ibuf-tail stream))
1223 (available (- tail head))
1224 (copy (min requested available)))
1225 (declare (type index offset head tail available copy))
1226 ;;
1227 ;; If something has been unread, put that at buffer + start,
1228 ;; and read the rest to start + 1.
1229 (when (fd-stream-unread stream) ;;@@
1230 (etypecase buffer
1231 (system-area-pointer
1232 (assert (= 1 (fd-stream-element-size stream)))
1233 (setf (sap-ref-8 buffer start) (char-code (read-char stream))))
1234 (string
1235 (setf (aref buffer start) (read-char stream)))
1236 (vector
1237 (setf (aref buffer start) (char-code(read-char stream)))))
1238 (return-from fd-stream-read-n-bytes
1239 (1+ (fd-stream-read-n-bytes stream buffer (1+ start) (1- requested)
1240 eof-error-p))))
1241 ;;
1242 (unless (zerop copy)
1243 (if (typep buffer 'system-area-pointer)
1244 (system-area-copy sap (* head vm:byte-bits)
1245 buffer (* offset vm:byte-bits)
1246 (* copy vm:byte-bits))
1247 (copy-from-system-area sap (* head vm:byte-bits)
1248 buffer (+ (* offset vm:byte-bits)
1249 (* vm:vector-data-offset
1250 vm:word-bits))
1251 (* copy vm:byte-bits)))
1252 (incf (fd-stream-ibuf-head stream) copy))
1253 (cond
1254 ((or (= copy requested)
1255 (and (not eof-error-p) (/= copy 0)))
1256 copy)
1257 (t
1258 (setf (fd-stream-ibuf-head stream) 0)
1259 (setf (fd-stream-ibuf-tail stream) 0)
1260 (setf (fd-stream-listen stream) nil)
1261 (let ((now-needed (- requested copy))
1262 (len (fd-stream-ibuf-length stream)))
1263 (declare (type index now-needed len))
1264 (cond
1265 ((> now-needed len)
1266 ;;
1267 ;; If the desired amount is greater than the stream buffer size, then
1268 ;; read directly into the destination, incrementing the start
1269 ;; accordingly. In this case, we never leave anything in the stream
1270 ;; buffer.
1271 (system:without-gcing
1272 (loop
1273 (multiple-value-bind
1274 (count err)
1275 (unix:unix-read (fd-stream-fd stream)
1276 (sap+ (if (typep buffer 'system-area-pointer)
1277 buffer
1278 (vector-sap buffer))
1279 (+ offset copy))
1280 now-needed)
1281 (declare (type (or index null) count))
1282 (unless count
1283 (error "Error reading ~S: ~A" stream
1284 (unix:get-unix-error-msg err)))
1285 (decf now-needed count)
1286 (if eof-error-p
1287 (when (zerop count)
1288 (error 'end-of-file :stream stream))
1289 (return (- requested now-needed)))
1290 (when (zerop now-needed) (return requested))
1291 (incf offset count)))))
1292 (t
1293 ;;
1294 ;; If we want less than the buffer size, then loop trying to fill the
1295 ;; stream buffer and copying what we get into the destination. When
1296 ;; we have enough, we leave what's left in the stream buffer.
1297 (loop
1298 (multiple-value-bind
1299 (count err)
1300 (unix:unix-read (fd-stream-fd stream) sap len)
1301 (declare (type (or index null) count))
1302 (unless count
1303 (error "Error reading ~S: ~A" stream
1304 (unix:get-unix-error-msg err)))
1305 (when (and eof-error-p (zerop count))
1306 (error 'end-of-file :stream stream))
1307
1308 (let* ((copy (min now-needed count))
1309 (copy-bits (* copy vm:byte-bits))
1310 (buffer-start-bits
1311 (* (+ offset available) vm:byte-bits)))
1312 (declare (type index copy copy-bits buffer-start-bits))
1313 (if (typep buffer 'system-area-pointer)
1314 (system-area-copy sap 0
1315 buffer buffer-start-bits
1316 copy-bits)
1317 (copy-from-system-area sap 0
1318 buffer (+ buffer-start-bits
1319 (* vm:vector-data-offset
1320 vm:word-bits))
1321 copy-bits))
1322
1323 (decf now-needed copy)
1324 (when (or (zerop now-needed) (not eof-error-p))
1325 (setf (fd-stream-ibuf-head stream) copy)
1326 (setf (fd-stream-ibuf-tail stream) count)
1327 (return (- requested now-needed)))
1328 (incf offset copy)))))))))))
1329
1330
1331 ;;;; Utility functions (misc routines, etc)
1332
1333 ;;; SET-ROUTINES -- internal
1334 ;;;
1335 ;;; Fill in the various routine slots for the given type. Input-p and
1336 ;;; output-p indicate what slots to fill. The buffering slot must be set prior
1337 ;;; to calling this routine.
1338 ;;;
1339
1340 (defun set-routines (stream type input-p output-p buffer-p &key binary-stream-p)
1341 (let ((target-type (case type
1342 ((:default unsigned-byte)
1343 '(unsigned-byte 8))
1344 (signed-byte
1345 '(signed-byte 8))
1346 (t
1347 type)))
1348 (input-type nil)
1349 (output-type nil)
1350 (input-size nil)
1351 (output-size nil))
1352
1353 (when (fd-stream-obuf-sap stream)
1354 (push (fd-stream-obuf-sap stream) *available-buffers*)
1355 (setf (fd-stream-obuf-sap stream) nil))
1356 (when (fd-stream-ibuf-sap stream)
1357 (push (fd-stream-ibuf-sap stream) *available-buffers*)
1358 (setf (fd-stream-ibuf-sap stream) nil))
1359
1360 #+unicode
1361 (when (null (fd-stream-external-format stream))
1362 (setf (fd-stream-external-format stream) :default))
1363
1364 (when input-p
1365 (multiple-value-bind
1366 (routine type size)
1367 (pick-input-routine target-type)
1368 (unless routine
1369 (error "Could not find any input routine for ~S" target-type))
1370 (setf (fd-stream-ibuf-sap stream) (next-available-buffer))
1371 (setf (fd-stream-ibuf-length stream) bytes-per-buffer)
1372 (setf (fd-stream-ibuf-tail stream) 0)
1373 (if (subtypep type 'character)
1374 (setf (fd-stream-in stream) routine
1375 (fd-stream-bin stream) #'ill-bin)
1376 (setf (fd-stream-in stream) (if (and binary-stream-p
1377 (eql size 1))
1378 (pick-input-routine 'character)
1379 #'ill-in)
1380 (fd-stream-bin stream) routine))
1381 (when (or (eql size 1)
1382 (eql size 2)
1383 (eql size 4))
1384 ;; Support for n-byte operations on 8-, 16-, and 32-bit streams
1385 (setf (fd-stream-n-bin stream) #'fd-stream-read-n-bytes)
1386 (when (and buffer-p (eql size 1)
1387 (or
1388 ;; FIXME: Do this better. We want to check for
1389 ;; (unsigned-byte 8). The 8 is unnecessary
1390 ;; since we already have size = 1.
1391 (or (eq 'unsigned-byte (and (consp type) (car type)))
1392 (eq type :default))
1393 (eq type 'character)))
1394 ;; We only create this buffer for streams of type
1395 ;; (unsigned-byte 8) or character streams with an external
1396 ;; format of :iso8859-1. Because there's no buffer, the
1397 ;; other element-types will dispatch to the appropriate
1398 ;; input (output) routine in fast-read-byte/fast-read-char.
1399 (when *enable-stream-buffer-p*
1400 (setf (lisp-stream-in-buffer stream)
1401 (make-array in-buffer-length
1402 :element-type '(unsigned-byte 8)))
1403 #+unicode
1404 (when (and (eq type 'character)
1405 (not (eq :iso8859-1 (fd-stream-external-format stream))))
1406 ;; For character streams, we create the string-buffer so
1407 ;; we can convert all available octets at once instead
1408 ;; of for each character. The string is one element
1409 ;; longer than in-buffer-length to leave room for
1410 ;; unreading.
1411 ;;
1412 ;; For ISO8859-1, we don't want this because it's very
1413 ;; easy and quick to convert octets to iso8859-1. (See
1414 ;; FAST-READ-CHAR.)
1415 (setf (lisp-stream-string-buffer stream)
1416 (make-string (1+ in-buffer-length)))
1417 (setf (lisp-stream-string-buffer-len stream) 0)
1418 (setf (lisp-stream-string-index stream) 0)))))
1419 (setf input-size size)
1420 (setf input-type type)))
1421
1422 (when output-p
1423 (multiple-value-bind
1424 (routine type size)
1425 (pick-output-routine target-type (fd-stream-buffering stream))
1426 (unless routine
1427 (error "Could not find any output routine for ~S buffered ~S."
1428 (fd-stream-buffering stream)
1429 target-type))
1430 (setf (fd-stream-obuf-sap stream) (next-available-buffer))
1431 (setf (fd-stream-obuf-length stream) bytes-per-buffer)
1432 (setf (fd-stream-obuf-tail stream) 0)
1433 (if (subtypep type 'character)
1434 (setf (fd-stream-out stream) routine
1435 (fd-stream-bout stream) #'ill-bout)
1436 (setf (fd-stream-out stream)
1437 (or (if (eql size 1)
1438 (pick-output-routine 'base-char
1439 (fd-stream-buffering stream)))
1440 #'ill-out)
1441 (fd-stream-bout stream) routine))
1442 (setf (fd-stream-sout stream)
1443 (if (eql size 1) #'fd-sout #'ill-out))
1444 (setf (fd-stream-char-pos stream) 0)
1445 (setf output-size size)
1446 (setf output-type type)))
1447
1448 (when (and input-size output-size
1449 (not (eql input-size output-size)))
1450 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1451 input-type input-size
1452 output-type output-size))
1453 (setf (fd-stream-element-size stream)
1454 (or input-size output-size))
1455
1456 (setf (fd-stream-element-type stream)
1457 (cond ((equal input-type output-type)
1458 input-type)
1459 ((null output-type)
1460 input-type)
1461 ((null input-type)
1462 output-type)
1463 ((subtypep input-type output-type)
1464 input-type)
1465 ((subtypep output-type input-type)
1466 output-type)
1467 (t
1468 (error "Input type (~S) and output type (~S) are unrelated?"
1469 input-type
1470 output-type))))))
1471
1472 ;;; REVERT-FILE -- internal
1473 ;;;
1474 ;;; Revert a file, if possible; otherwise do nothing. Used during
1475 ;;; CLOSE when the abort flag is set.
1476 ;;;
1477 (defun revert-file (filename original)
1478 (declare (type simple-base-string filename)
1479 (type (or simple-base-string null) original))
1480 (when original
1481 (multiple-value-bind (okay err)
1482 (unix:unix-rename original filename)
1483 (unless okay
1484 (cerror "Go on as if nothing bad happened."
1485 "Could not restore ~S to its original contents: ~A"
1486 filename (unix:get-unix-error-msg err))))))
1487
1488 ;;; DELETE-ORIGINAL -- internal
1489 ;;;
1490 ;;; Delete a backup file. Used during CLOSE.
1491 ;;;
1492 (defun delete-original (filename original)
1493 (declare (type simple-base-string filename)
1494 (type (or simple-base-string null) original))
1495 (when original
1496 (multiple-value-bind (okay err) (unix:unix-unlink original)
1497 (unless okay
1498 (cerror "Go on as if nothing bad happened."
1499 "Could not delete ~S during close of ~S: ~A"
1500 original filename (unix:get-unix-error-msg err))))))
1501
1502 ;;; FD-STREAM-MISC-ROUTINE -- input
1503 ;;;
1504 ;;; Handle the various misc operations on fd-stream.
1505 ;;;
1506 (defun fd-stream-misc-routine (stream operation &optional arg1 arg2)
1507 (declare (ignore arg2))
1508 (case operation
1509 (:listen
1510 (or (not (eql (fd-stream-ibuf-head stream)
1511 (fd-stream-ibuf-tail stream)))
1512 (fd-stream-listen stream)
1513 (setf (fd-stream-listen stream)
1514 (eql (alien:with-alien ((read-fds (alien:struct unix:fd-set)))
1515 (unix:fd-zero read-fds)
1516 (unix:fd-set (fd-stream-fd stream) read-fds)
1517 (unix:unix-fast-select (1+ (fd-stream-fd stream))
1518 (alien:addr read-fds) nil nil
1519 0 0))
1520 1))))
1521 (:unread
1522 #-unicode
1523 (setf (fd-stream-unread stream) arg1)
1524 #+unicode
1525 (cond ((lisp-stream-string-buffer stream)
1526 (if (zerop (lisp-stream-string-index stream))
1527 (setf (fd-stream-unread stream) arg1)
1528 (decf (lisp-stream-string-index stream))))
1529 (t
1530 (if (zerop (fd-stream-last-char-read-size stream))
1531 (setf (fd-stream-unread stream) arg1)
1532 (decf (fd-stream-ibuf-head stream)
1533 (fd-stream-last-char-read-size stream)))))
1534 ;; Paul says:
1535 ;;
1536 ;; Not needed for unicode when unreading is implemented by backing up in
1537 ;; the buffer (e.g., with last-char-read-size...)
1538 ;;
1539 ;; (AFAICS there's nothing wrong with setting it there, but it
1540 ;; screws up read-interactive in my toplevel command thing -
1541 ;; leaves it expecting to read arguments when it shouldn't,
1542 ;; because LISTEN returns T when there's no input pending, but I
1543 ;; don't understand why...)
1544 #-unicode
1545 (setf (fd-stream-listen stream) t))
1546 (:close
1547 (cond (arg1
1548 ;; We got us an abort on our hands.
1549 (when (fd-stream-handler stream)
1550 (system:remove-fd-handler (fd-stream-handler stream))
1551 (setf (fd-stream-handler stream) nil))
1552 (when (and (fd-stream-file stream) (fd-stream-obuf-sap stream))
1553 (revert-file (fd-stream-file stream)
1554 (fd-stream-original stream))))
1555 (t
1556 #+(and unicode (not unicode-bootstrap))
1557 (when (and (output-stream-p stream)
1558 (eq (stream-element-type stream) 'character))
1559 ;; For output character streams, we need to flush out
1560 ;; any state that the external format might have.
1561 #+nil (format *debug-io* "state = ~S~%" (fd-stream-co-state stream))
1562 (funcall (ef-flush (fd-stream-external-format stream))
1563 stream))
1564 (fd-stream-misc-routine stream :finish-output)
1565 (when (fd-stream-delete-original stream)
1566 (delete-original (fd-stream-file stream)
1567 (fd-stream-original stream)))))
1568 (when (fboundp 'cancel-finalization)
1569 (cancel-finalization stream))
1570 (unix:unix-close (fd-stream-fd stream))
1571 (when (fd-stream-obuf-sap stream)
1572 (push (fd-stream-obuf-sap stream) *available-buffers*)
1573 (setf (fd-stream-obuf-sap stream) nil))
1574 (when (fd-stream-ibuf-sap stream)
1575 (push (fd-stream-ibuf-sap stream) *available-buffers*)
1576 (setf (fd-stream-ibuf-sap stream) nil))
1577 (lisp::set-closed-flame stream))
1578 (:clear-input
1579 (setf (fd-stream-unread stream) nil) ;;@@
1580 #+unicode (setf (fd-stream-last-char-read-size stream) 0)
1581 (setf (fd-stream-ibuf-head stream) 0)
1582 (setf (fd-stream-ibuf-tail stream) 0)
1583 (catch 'eof-input-catcher
1584 (loop
1585 (multiple-value-bind
1586 (count errno)
1587 (alien:with-alien ((read-fds (alien:struct unix:fd-set)))
1588 (unix:fd-zero read-fds)
1589 (unix:fd-set (fd-stream-fd stream) read-fds)
1590 (unix:unix-fast-select (1+ (fd-stream-fd stream))
1591 (alien:addr read-fds) nil nil 0 0))
1592 (cond ((eql count 1)
1593 (do-input stream)
1594 (setf (fd-stream-ibuf-head stream) 0)
1595 (setf (fd-stream-ibuf-tail stream) 0))
1596 ((and (not count) (eql errno unix:eintr)))
1597 (t
1598 (return t)))))))
1599 (:force-output
1600 (flush-output-buffer stream))
1601 (:finish-output
1602 (flush-output-buffer stream)
1603 (do ()
1604 ((null (fd-stream-output-later stream)))
1605 (system:serve-all-events)))
1606 (:element-type
1607 (fd-stream-element-type stream))
1608 (:interactive-p
1609 (unix:unix-isatty (fd-stream-fd stream)))
1610 (:line-length
1611 80)
1612 (:charpos
1613 (fd-stream-char-pos stream))
1614 (:file-length
1615 (unless (fd-stream-file stream)
1616 (error 'simple-type-error
1617 :datum stream
1618 :expected-type 'file-stream
1619 :format-control "~s is not a stream associated with a file."
1620 :format-arguments (list stream)))
1621 (multiple-value-bind
1622 (okay dev ino mode nlink uid gid rdev size
1623 atime mtime ctime blksize blocks)
1624 (unix:unix-fstat (fd-stream-fd stream))
1625 (declare (ignore ino nlink uid gid rdev
1626 atime mtime ctime blksize blocks))
1627 (unless okay
1628 (error 'simple-file-error
1629 :format-control "Error fstating ~S: ~A"
1630 :format-arguments (list stream (unix:get-unix-error-msg dev))))
1631 (if (zerop mode)
1632 nil
1633 (values (truncate size (fd-stream-element-size stream))))))
1634 (:file-position
1635 (fd-stream-file-position stream arg1))))
1636
1637
1638 ;;; FD-STREAM-FILE-POSITION -- internal.
1639 ;;;
1640 (defun fd-stream-file-position (stream &optional newpos)
1641 (declare (type fd-stream stream)
1642 (type (or (integer 0) (member nil :start :end)) newpos))
1643 (if (null newpos)
1644 (system:without-interrupts
1645 ;; First, find the position of the UNIX file descriptor in the file.
1646 (multiple-value-bind
1647 (posn errno)
1648 (unix:unix-lseek (fd-stream-fd stream) 0 unix:l_incr)
1649 (declare (type (or (integer 0) null) posn))
1650 (cond (posn
1651 ;; Adjust for buffered output:
1652 ;; If there is any output buffered, the *real* file position
1653 ;; will be larger than reported by lseek because lseek
1654 ;; obviously cannot take into account output we have not
1655 ;; sent yet.
1656 (dolist (later (fd-stream-output-later stream))
1657 (incf posn (- (the index (caddr later))
1658 (the index (cadr later)))))
1659 (incf posn (fd-stream-obuf-tail stream))
1660 ;; Adjust for unread input:
1661 ;; If there is any input read from UNIX but not supplied to
1662 ;; the user of the stream, the *real* file position will
1663 ;; smaller than reported, because we want to look like the
1664 ;; unread stuff is still available.
1665 #-unicode
1666 (decf posn (- (fd-stream-ibuf-tail stream)
1667 (fd-stream-ibuf-head stream)))
1668 #+unicode
1669 (if (fd-stream-string-buffer stream)
1670 (decf posn (- (fd-stream-string-buffer-len stream)
1671 (fd-stream-string-index stream)))
1672 (decf posn (- (fd-stream-ibuf-tail stream)
1673 (fd-stream-ibuf-head stream))))
1674 (when (fd-stream-unread stream) ;;@@
1675 (decf posn))
1676 ;; Divide bytes by element size.
1677 (truncate posn (fd-stream-element-size stream)))
1678 ((eq errno unix:espipe)
1679 nil)
1680 (t
1681 (system:with-interrupts
1682 (error "Error lseek'ing ~S: ~A"
1683 stream
1684 (unix:get-unix-error-msg errno)))))))
1685 (let ((offset 0)
1686 origin)
1687 (declare (type (integer 0) offset))
1688 ;; Make sure we don't have any output pending, because if we move the
1689 ;; file pointer before writing this stuff, it will be written in the
1690 ;; wrong location.
1691 (flush-output-buffer stream)
1692 (do ()
1693 ((null (fd-stream-output-later stream)))
1694 (system:serve-all-events))
1695 ;; Clear out any pending input to force the next read to go to the
1696 ;; disk.
1697 (setf (fd-stream-unread stream) nil) ;;@@
1698 #+unicode
1699 (progn
1700 (setf (fd-stream-last-char-read-size stream) 0)
1701 (setf (fd-stream-string-index stream)
1702 (fd-stream-string-buffer-len stream)))
1703 (setf (fd-stream-ibuf-head stream) 0)
1704 (setf (fd-stream-ibuf-tail stream) 0)
1705 ;; Trash cached value for listen, so that we check next time.
1706 (setf (fd-stream-listen stream) nil)
1707 ;; Now move it.
1708 (cond ((eq newpos :start)
1709 (setf offset 0
1710 origin unix:l_set))
1711 ((eq newpos :end)
1712 (setf offset 0
1713 origin unix:l_xtnd))
1714 ((typep newpos '(integer 0))
1715 (setf offset (* newpos (fd-stream-element-size stream))
1716 origin unix:l_set))
1717 (t
1718 (error "Invalid position given to file-position: ~S" newpos)))
1719 (multiple-value-bind
1720 (posn errno)
1721 (unix:unix-lseek (fd-stream-fd stream) offset origin)
1722 (cond (posn
1723 t)
1724 ((eq errno unix:espipe)
1725 nil)
1726 (t
1727 (error "Error lseek'ing ~S: ~A"
1728 stream
1729 (unix:get-unix-error-msg errno))))))))
1730
1731
1732
1733 ;;;; Creation routines (MAKE-FD-STREAM and OPEN)
1734
1735 ;;; MAKE-FD-STREAM -- Public.
1736 ;;;
1737 ;;; Returns a FD-STREAM on the given file.
1738 ;;;
1739 (defun make-fd-stream (fd
1740 &key
1741 (input nil input-p)
1742 (output nil output-p)
1743 (element-type 'base-char)
1744 (buffering :full)
1745 timeout
1746 file
1747 original
1748 delete-original
1749 pathname
1750 input-buffer-p
1751 (name (if file
1752 (format nil "file ~S" file)
1753 (format nil "descriptor ~D" fd)))
1754 auto-close
1755 (external-format :default)
1756 binary-stream-p)
1757 (declare (type index fd) (type (or index null) timeout)
1758 (type (member :none :line :full) buffering))
1759 "Create a stream for the given unix file descriptor.
1760 If input is non-nil, allow input operations.
1761 If output is non-nil, allow output operations.
1762 If neither input nor output are specified, default to allowing input.
1763 Element-type indicates the element type to use (as for open).
1764 Buffering indicates the kind of buffering to use.
1765 Timeout (if true) is the number of seconds to wait for input. If NIL (the
1766 default), then wait forever. When we time out, we signal IO-TIMEOUT.
1767 File is the name of the file (will be returned by PATHNAME).
1768 Name is used to identify the stream when printed."
1769 (cond ((not (or input-p output-p))
1770 (setf input t))
1771 ((not (or input output))
1772 (error "File descriptor must be opened either for input or output.")))
1773 (let ((stream (if binary-stream-p
1774 (%make-binary-text-stream :fd fd
1775 :name name
1776 :file file
1777 :original original
1778 :delete-original delete-original
1779 :pathname pathname
1780 :buffering buffering
1781 :timeout timeout)
1782 (%make-fd-stream :fd fd
1783 :name name
1784 :file file
1785 :original original
1786 :delete-original delete-original
1787 :pathname pathname
1788 :buffering buffering
1789 :timeout timeout))))
1790 ;; FIXME: setting the external format here should be better
1791 ;; integrated into set-routines. We do it before so that
1792 ;; set-routines can create an in-buffer if appropriate. But we
1793 ;; need to do it after to put the correct input routines for the
1794 ;; external format.
1795 ;;
1796 ;;#-unicode-bootstrap ; fails in stream-reinit otherwise
1797 #+(and unicode (not unicode-bootstrap))
1798 (when lisp::*enable-stream-buffer-p*
1799 (%set-fd-stream-external-format stream external-format nil))
1800 (set-routines stream element-type input output input-buffer-p
1801 :binary-stream-p binary-stream-p)
1802 #+(and unicode (not unicode-bootstrap))
1803 (when lisp::*enable-stream-buffer-p*
1804 (%set-fd-stream-external-format stream external-format nil))
1805 (when (and auto-close (fboundp 'finalize))
1806 (finalize stream
1807 #'(lambda ()
1808 (unix:unix-close fd)
1809 (format *terminal-io* "** Closed ~A~%" name)
1810 (when original
1811 (revert-file file original)))))
1812 stream))
1813
1814
1815 ;;; PICK-BACKUP-NAME -- internal
1816 ;;;
1817 ;;; Pick a name to use for the backup file.
1818 ;;;
1819 (defvar *backup-extension* ".BAK"
1820 "This is a string that OPEN tacks on the end of a file namestring to produce
1821 a name for the :if-exists :rename-and-delete and :rename options. Also,
1822 this can be a function that takes a namestring and returns a complete
1823 namestring.")
1824 ;;;
1825 (defun pick-backup-name (name)
1826 (declare (type simple-string name))
1827 (let ((ext *backup-extension*))
1828 (etypecase ext
1829 (simple-string (concatenate 'simple-string name ext))
1830 (function (funcall ext name)))))
1831
1832 ;;; NEXT-VERSION -- internal
1833 ;;;
1834 ;;; Find the next available versioned name for a file.
1835 ;;;
1836 (defun next-version (name)
1837 (declare (type simple-string name))
1838 (let* ((sep (position #\/ name :from-end t))
1839 (base (if sep (subseq name 0 (1+ sep)) ""))
1840 (dir (unix:open-dir base)))
1841 (multiple-value-bind (name type version)
1842 (extract-name-type-and-version name (if sep (1+ sep) 0) (length name))
1843 (let ((version (if (symbolp version) 1 (1+ version)))
1844 (match (if type
1845 (concatenate 'string name "." type ".~")
1846 (concatenate 'string name ".~"))))
1847 (when dir
1848 (unwind-protect
1849 (loop
1850 (let ((name (unix:read-dir dir)))
1851 (cond ((null name) (return))
1852 ((and (> (length name) (length match))
1853 (string= name match :end1 (length match)))
1854 (multiple-value-bind (v e)
1855 (parse-integer name :start (length match)
1856 :junk-allowed t)
1857 (when (and v
1858 (= (length name) (1+ e))
1859 (char= (schar name e) #\~))
1860 (setq version (max version (1+ v)))))))))
1861 (unix:close-dir dir)))
1862 (concatenate 'string base
1863 match (quick-integer-to-string version) "~")))))
1864
1865 ;;; ASSURE-ONE-OF -- internal
1866 ;;;
1867 ;;; Assure that the given arg is one of the given list of valid things.
1868 ;;; Allow the user to fix any problems.
1869 ;;;
1870 (defun assure-one-of (item list what)
1871 (unless (member item list)
1872 (loop
1873 (cerror "Enter new value for ~*~S"
1874 "~S is invalid for ~S. Must be one of~{ ~S~}"
1875 item
1876 what
1877 list)
1878 (format (the stream *query-io*) "Enter new value for ~S: " what)
1879 (force-output *query-io*)
1880 (setf item (read *query-io*))
1881 (when (member item list)
1882 (return))))
1883 item)
1884
1885 ;;; DO-OLD-RENAME -- Internal
1886 ;;;
1887 ;;; Rename Namestring to Original. First, check if we have write access,
1888 ;;; since we don't want to trash unwritable files even if we technically can.
1889 ;;; We return true if we succeed in renaming.
1890 ;;;
1891 (defun do-old-rename (namestring original)
1892 (unless (unix:unix-access namestring unix:w_ok)
1893 (cerror "Try to rename it anyway." "File ~S is not writable." namestring))
1894 (multiple-value-bind
1895 (okay err)
1896 (unix:unix-rename namestring original)
1897 (cond (okay t)
1898 (t
1899 (cerror "Use :SUPERSEDE instead."
1900 "Could not rename ~S to ~S: ~A."
1901 namestring
1902 original
1903 (unix:get-unix-error-msg err))
1904 nil))))
1905
1906 ;;; FD-OPEN -- Internal
1907 ;;;
1908 ;;; Open a file.
1909 ;;;
1910 (defun fd-open (pathname direction if-exists if-exists-given
1911 if-does-not-exist if-does-not-exist-given)
1912 (declare (type pathname pathname)
1913 (type (member :input :output :io :probe) direction)
1914 (type (member :error :new-version :rename :rename-and-delete
1915 :overwrite :append :supersede nil) if-exists)
1916 (type (member :error :create nil) if-does-not-exist))
1917 (multiple-value-bind (input output mask)
1918 (ecase direction
1919 (:input (values t nil unix:o_rdonly))
1920 (:output (values nil t unix:o_wronly))
1921 (:io (values t t unix:o_rdwr))
1922 (:probe (values t nil unix:o_rdonly)))
1923 (declare (type index mask))
1924 ;; Process if-exists argument if we are doing any output.
1925 (cond (output
1926 (unless if-exists-given
1927 (setf if-exists
1928 (if (eq (pathname-version pathname) :newest)
1929 :new-version
1930 :error)))
1931 (case if-exists
1932 ((:error nil)
1933 (setf mask (logior mask unix:o_excl)))
1934 ((:new-version :rename :rename-and-delete)
1935 (setf mask (logior mask unix:o_creat)))
1936 (:supersede
1937 (setf mask (logior mask unix:o_trunc)))))
1938 (t
1939 (setf if-exists nil))) ; :ignore-this-arg
1940
1941 (unless if-does-not-exist-given
1942 (setf if-does-not-exist
1943 (cond ((eq direction :input) :error)
1944 ((and output
1945 (member if-exists '(:overwrite :append)))
1946 :error)
1947 ((eq direction :probe)
1948 nil)
1949 (t
1950 :create))))
1951 (if (eq if-does-not-exist :create)
1952 (setf mask (logior mask unix:o_creat)))
1953
1954 (let ((name (cond ((unix-namestring pathname input))
1955 ((and input (eq if-does-not-exist :create))
1956 (unix-namestring pathname nil)))))
1957 (let ((original (cond ((eq if-exists :new-version)
1958 (next-version name))
1959 ((member if-exists '(:rename :rename-and-delete))
1960 (pick-backup-name name))))
1961 (delete-original (eq if-exists :rename-and-delete))
1962 (mode #o666))
1963 (when original
1964 ;; We are doing a :rename or :rename-and-delete.
1965 ;; Determine if the file already exists, make sure the original
1966 ;; file is not a directory and keep the mode
1967 (let ((exists
1968 (and name
1969 (multiple-value-bind
1970 (okay err/dev inode orig-mode)
1971 (unix:unix-stat name)
1972 (declare (ignore inode)
1973 (type (or index null) orig-mode))
1974 (cond
1975 (okay
1976 (when (and output (= (logand orig-mode #o170000)
1977 #o40000))
1978 (error 'simple-file-error
1979 :pathname pathname
1980 :format-control
1981 "Cannot open ~S for output: Is a directory."
1982 :format-arguments (list name)))
1983 (setf mode (logand orig-mode #o777))
1984 t)
1985 ((eql err/dev unix:enoent)
1986 nil)
1987 (t
1988 (error 'simple-file-error
1989 :pathname pathname
1990 :format-control "Cannot find ~S: ~A"
1991 :format-arguments
1992 (list name
1993 (unix:get-unix-error-msg err/dev)))))))))
1994 (unless (and exists
1995 (do-old-rename name original))
1996 (setf original nil)
1997 (setf delete-original nil)
1998 ;; In order to use SUPERSEDE instead, we have
1999 ;; to make sure unix:o_creat corresponds to
2000 ;; if-does-not-exist. unix:o_creat was set
2001 ;; before because of if-exists being :rename.
2002 (unless (eq if-does-not-exist :create)
2003 (setf mask (logior (logandc2 mask unix:o_creat)
2004 unix:o_trunc)))
2005 (setf if-exists :supersede))))
2006
2007 ;; Okay, now we can try the actual open.
2008 (loop
2009 (multiple-value-bind (fd errno)
2010 (if name
2011 (unix:unix-open name mask mode)
2012 (values nil unix:enoent))
2013 (cond ((fixnump fd)
2014 (when (eq if-exists :append)
2015 (unix:unix-lseek fd 0 unix:l_xtnd)) ; SEEK_END
2016 (return (values fd name original delete-original)))
2017 ((eql errno unix:enoent)
2018 (case if-does-not-exist
2019 (:error
2020 (cerror "Return NIL."
2021 'simple-file-error
2022 :pathname pathname
2023 :format-control "Error opening ~S, ~A."
2024 :format-arguments
2025 (list pathname
2026 (unix:get-unix-error-msg errno))))
2027 (:create
2028 (cerror "Return NIL."
2029 'simple-file-error
2030 :pathname pathname
2031 :format-control
2032 "Error creating ~S, path does not exist."
2033 :format-arguments (list pathname))))
2034 (return nil))
2035 ((eql errno unix:eexist)
2036 (unless (eq nil if-exists)
2037 (cerror "Return NIL."
2038 'simple-file-error
2039 :pathname pathname
2040 :format-control "Error opening ~S, ~A."
2041 :format-arguments
2042 (list pathname
2043 (unix:get-unix-error-msg errno))))
2044 (return nil))
2045 ((eql errno unix:eacces)
2046 (cerror "Try again."
2047 'simple-file-error
2048 :pathname pathname
2049 :format-control "Error opening ~S, ~A."
2050 :format-arguments
2051 (list pathname
2052 (unix:get-unix-error-msg errno))))
2053 (t
2054 (cerror "Return NIL."
2055 'simple-file-error
2056 :pathname pathname
2057 :format-control "Error opening ~S, ~A."
2058 :format-arguments
2059 (list pathname
2060 (unix:get-unix-error-msg errno)))
2061 (return nil)))))))))
2062
2063 ;;; OPEN-FD-STREAM -- Internal
2064 ;;;
2065 ;;; Open an fd-stream connected to a file.
2066 ;;;
2067 (defun open-fd-stream (pathname &key (direction :input)
2068 (element-type 'base-char)
2069 (if-exists nil if-exists-given)
2070 (if-does-not-exist nil if-does-not-exist-given)
2071 (external-format :default)
2072 class)
2073 (declare (type pathname pathname)
2074 (type (member :input :output :io :probe) direction)
2075 (type (member :error :new-version :rename :rename-and-delete
2076 :overwrite :append :supersede nil) if-exists)
2077 (type (member :error :create nil) if-does-not-exist))
2078 (multiple-value-bind (fd namestring original delete-original)
2079 (fd-open pathname direction if-exists if-exists-given
2080 if-does-not-exist if-does-not-exist-given)
2081 (when fd
2082 (case direction
2083 ((:input :output :io)
2084 ;; We use the :class option to tell us if we want a
2085 ;; binary-text stream or not.
2086 (make-fd-stream fd
2087 :input (member direction '(:input :io))
2088 :output (member direction '(:output :io))
2089 :element-type element-type
2090 :file namestring
2091 :original original
2092 :delete-original delete-original
2093 :pathname pathname
2094 :input-buffer-p t
2095 :auto-close t
2096 :external-format external-format
2097 :binary-stream-p class))
2098 (:probe
2099 (let ((stream (%make-fd-stream :name namestring :fd fd
2100 :pathname pathname
2101 :element-type element-type)))
2102 (close stream)
2103 stream))))))
2104
2105 ;;; OPEN -- public
2106 ;;;
2107 ;;; Open the given file.
2108 ;;;
2109 (defun open (filename &rest options
2110 &key (direction :input)
2111 (element-type 'base-char element-type-given)
2112 (if-exists nil if-exists-given)
2113 (if-does-not-exist nil if-does-not-exist-given)
2114 (external-format :default)
2115 class mapped input-handle output-handle
2116 &allow-other-keys
2117 &aux ; Squelch assignment warning.
2118 (options options)
2119 (direction direction)
2120 (if-does-not-exist if-does-not-exist)
2121 (if-exists if-exists))
2122 "Return a stream which reads from or writes to Filename.
2123 Defined keywords:
2124 :direction - one of :input, :output, :io, or :probe
2125 :element-type - Type of object to read or write, default BASE-CHAR
2126 :if-exists - one of :error, :new-version, :rename, :rename-and-delete,
2127 :overwrite, :append, :supersede or nil
2128 :if-does-not-exist - one of :error, :create or nil
2129 :external-format - an external format name
2130 See the manual for details."
2131 (declare (ignore element-type external-format input-handle output-handle))
2132
2133 ;; OPEN signals a file-error if the filename is wild.
2134 (when (wild-pathname-p filename)
2135 (error 'file-error :pathname filename))
2136
2137 ;; First, make sure that DIRECTION is valid. Allow it to be changed if not.
2138 (setq direction
2139 (assure-one-of direction
2140 '(:input :output :io :probe)
2141 :direction))
2142 (setf (getf options :direction) direction)
2143
2144 (when (and if-exists-given (member direction '(:output :io)))
2145 (setq if-exists
2146 (assure-one-of if-exists
2147 '(:error :new-version :rename
2148 :rename-and-delete :overwrite
2149 :append :supersede nil)
2150 :if-exists))
2151 (setf (getf options :if-exists) if-exists))
2152
2153 (when if-does-not-exist-given
2154 (setq if-does-not-exist
2155 (assure-one-of if-does-not-exist
2156 '(:error :create nil)
2157 :if-does-not-exist))
2158 (setf (getf options :if-does-not-exist) if-does-not-exist))
2159
2160 (let ((filespec (pathname filename))
2161 (options (copy-list options))
2162 (class (or class 'fd-stream)))
2163 (cond ((eq class 'fd-stream)
2164 (remf options :class)
2165 (remf options :mapped)
2166 (remf options :input-handle)
2167 (remf options :output-handle)
2168 (apply #'open-fd-stream filespec options))
2169 ((eq class 'binary-text-stream)
2170 ;; Like fd-stream, but binary and text allowed. This is
2171 ;; indicated by leaving the :class option around for
2172 ;; open-fd-stream to see.
2173 (remf options :mapped)
2174 (remf options :input-handle)
2175 (remf options :output-handle)
2176 (apply #'open-fd-stream filespec options))
2177 ((subtypep class 'stream:simple-stream)
2178 (when element-type-given
2179 (cerror "Do it anyway."
2180 "Can't create simple-streams with an element-type."))
2181 (when (and (eq class 'stream:file-simple-stream) mapped)
2182 (setq class 'stream:mapped-file-simple-stream)
2183 (setf (getf options :class) 'stream:mapped-file-simple-stream))
2184 (when (subtypep class 'stream:file-simple-stream)
2185 (when (eq direction :probe)
2186 (setq class 'stream:probe-simple-stream)))
2187 (apply #'make-instance class :filename filespec options))
2188 ((subtypep class 'ext:fundamental-stream)
2189 (remf options :class)
2190 (remf options :mapped)
2191 (remf options :input-handle)
2192 (remf options :output-handle)
2193 (let ((stream (apply #'open-fd-stream filespec options)))
2194 (when stream
2195 (make-instance class :lisp-stream stream))))
2196 (t
2197 (error "Unable to open streams of class ~S." class)))))
2198
2199 ;;;; Initialization.
2200
2201 (defvar *tty* nil
2202 "The stream connected to the controlling terminal or NIL if there is none.")
2203 (defvar *stdin* nil
2204 "The stream connected to the standard input (file descriptor 0).")
2205 (defvar *stdout* nil
2206 "The stream connected to the standard output (file descriptor 1).")
2207 (defvar *stderr* nil
2208 "The stream connected to the standard error output (file descriptor 2).")
2209
2210 ;;; STREAM-INIT -- internal interface
2211 ;;;
2212 ;;; Called when the cold load is first started up.
2213 ;;;
2214 (defun stream-init ()
2215 (stream-reinit)
2216 (setf *terminal-io* (make-synonym-stream '*tty*))
2217 (setf *standard-output* (make-synonym-stream '*stdout*))
2218 (setf *standard-input*
2219 (make-two-way-stream (make-synonym-stream '*stdin*)
2220 *standard-output*))
2221 (setf *error-output* (make-synonym-stream '*stderr*))
2222 (setf *query-io* (make-synonym-stream '*terminal-io*))
2223 (setf *debug-io* *query-io*)
2224 (setf *trace-output* *standard-output*)
2225 nil)
2226
2227 ;;; STREAM-REINIT -- internal interface
2228 ;;;
2229 ;;; Called whenever a saved core is restarted.
2230 ;;;
2231 (defun stream-reinit ()
2232 (setf *available-buffers* nil)
2233 (setf *stdin*
2234 (make-fd-stream 0 :name "Standard Input" :input t :buffering :line
2235 :external-format :iso8859-1))
2236 (setf *stdout*
2237 (make-fd-stream 1 :name "Standard Output" :output t :buffering :line
2238 :external-format :iso8859-1))
2239 (setf *stderr*
2240 (make-fd-stream 2 :name "Standard Error" :output t :buffering :line
2241 :external-format :iso8859-1))
2242 (let ((tty (and (not *batch-mode*)
2243 (unix:unix-open "/dev/tty" unix:o_rdwr #o666))))
2244 (setf *tty*
2245 (if tty
2246 (make-fd-stream tty :name "the Terminal" :input t :output t
2247 :buffering :line :auto-close t
2248 :external-format :iso8859-1)
2249 (make-two-way-stream *stdin* *stdout*))))
2250 nil)
2251
2252
2253 ;;;; Beeping.
2254
2255 (defun default-beep-function (stream)
2256 (write-char #\bell stream)
2257 (finish-output stream))
2258
2259 (defvar *beep-function* #'default-beep-function
2260 "This is called in BEEP to feep the user. It takes a stream.")
2261
2262 (defun beep (&optional (stream *terminal-io*))
2263 (funcall *beep-function* stream))
2264
2265
2266 ;;; File-Name -- internal interface
2267 ;;;
2268 ;;; Kind of like File-Position, but is an internal hack used by the filesys
2269 ;;; stuff to get and set the file name.
2270 ;;;
2271 (defun file-name (stream &optional new-name)
2272 (typecase stream
2273 (stream:simple-stream
2274 (if new-name
2275 (stream::%file-rename stream new-name)
2276 (stream::%file-name stream)))
2277 (fd-stream
2278 (cond (new-name
2279 (setf (fd-stream-pathname stream) new-name)
2280 (setf (fd-stream-file stream)
2281 (unix-namestring new-name nil))
2282 t)
2283 (t
2284 (fd-stream-pathname stream))))))
2285
2286
2287
2288 #+unicode
2289 (stream::def-ef-macro ef-strlen (extfmt lisp stream::+ef-max+ stream::+ef-str+)
2290 ;; While it would be nice not to have to call CHAR-TO-OCTETS to
2291 ;; figure out the length when the external format has fixed size
2292 ;; outputs, we can't. For example, utf16 will output a BOM, which
2293 ;; wouldn't be reflected in the count if we don't call
2294 ;; CHAR-TO-OCTETS.
2295 `(lambda (stream object &aux (count 0))
2296 (declare (type fd-stream stream)
2297 (type (or character string) object)
2298 (type (and fixnum unsigned-byte) count)
2299 #|(optimize (speed 3) (space 0) (debug 0) (safety 0))|#)
2300 (labels ((efstate (state)
2301 (stream::copy-state ,extfmt state))
2302 (eflen (char)
2303 (stream::char-to-octets ,extfmt char
2304 (fd-stream-co-state stream)
2305 (lambda (byte)
2306 (declare (ignore byte))
2307 (incf count)))))
2308 (let* ((co-state (fd-stream-co-state stream))
2309 (old-ef-state (efstate (cdr (fd-stream-co-state stream))))
2310 (old-state (cons (car co-state) old-ef-state)))
2311 (etypecase object
2312 (character (eflen object))
2313 (string (dovector (ch object) (eflen ch))))
2314 ;; Restore state
2315 (setf (fd-stream-co-state stream) old-state)
2316 count))))
2317
2318
2319 (defun file-string-length (stream object)
2320 (declare (type (or string character) object)
2321 (type (or file-stream broadcast-stream stream:simple-stream) stream))
2322 "Return the delta in Stream's FILE-POSITION that would be caused by writing
2323 Object to Stream. Non-trivial only in implementations that support
2324 international character sets."
2325 (typecase stream
2326 (stream:simple-stream (stream::%file-string-length stream object))
2327 (broadcast-stream
2328 ;; CLHS says we must return 1 in this case
2329 1)
2330 #+unicode
2331 (t (funcall (ef-strlen (fd-stream-external-format stream))
2332 stream object))
2333 #-unicode
2334 (t (etypecase object
2335 (character 1)
2336 (string (length object))))))
2337
2338 #+unicode
2339 (stream::def-ef-macro ef-copy-state (extfmt lisp stream::+ef-max+ stream::+ef-copy-state+)
2340 ;; Return a copy of the state of an external format.
2341 `(lambda (state)
2342 (declare (ignorable state))
2343 (stream::copy-state ,extfmt state)))

  ViewVC Help
Powered by ViewVC 1.1.5