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

  ViewVC Help
Powered by ViewVC 1.1.5