/[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.92 - (show annotations)
Sun Oct 18 14:21:24 2009 UTC (4 years, 6 months ago) by rtoy
Branch: MAIN
CVS Tags: amd64-dd-start, snapshot-2010-01, snapshot-2009-11, snapshot-2009-12
Branch point for: amd64-dd-branch
Changes since 1.91: +54 -14 lines
Merge changes from unicode-string-buffer-impl-branch which gives
faster reads on external-formats.  This is done by adding an
additional buffer to streams so we can convert the entire in-buffer
into characters all at once.

To build this change, you need to do a cross-compile using
boot-2009-10-1-cross.lisp.  Using that build, do a normal build with
these sources.

For a non-unicode build use boot-2009-10-01.lisp with a 20a
non-unicode build.

code/extfmts.lisp:
o Add another slot to the extfmts for copying the state.
o Modify EF-OCTETS-TO-STRING and OCTETS-TO-STRING to support the
  necesssary changes for fast formats.  This is incompatible with the
  previous version because the string is not grown if needed.

code/fd-stream-extfmt.lisp:
o Set *enable-stream-buffer-p* to T so we have fast streams.

code/fd-stream.lisp:
o Add new slots to support fast strams.
o In SET-ROUTINES, initialize the new slots appropriately.
o Update UNREAD-CHAR to be able to back up in the string buffer to
  unread.
o Add implementation to copy the state of an external format.

code/stream.lisp:
o Change %SET-FD-STREAM-EXTERNAL-FORMAT to be able to change formats
  even if we've already converted the buffer with a different format.
  We reconvert the buffer with the old format until we reach the
  current character.  Then the remaining octets are converted using
  the new format and stored in the string buffer.
o Add FAST-READ-CHAR-STRING-REFILL to refill the string buffer, like
  FAST-READ-CHAR-REFILL does for the octet in-buffer.

code/struct.lisp:
o Add new slots to hold the string buffer, the current index, and
  length.  These are needed for the fast formats.

code/sysmacs.lisp:
o Update PREPARE-FOR-FAST-READ-CHAR, DONE-WITH-FAST-READ-CHAR, and
  FAST-READ-CHAR to support the string buffer.

code/string.lisp:
o Microoptimization of SURROGATEP to reduce the number of branchs.

general-info/release-20b.txt:
o Update with these changes

pcl/simple-streams/external-formats/utf-16-be.lisp:
pcl/simple-streams/external-formats/utf-16-le.lisp:
pcl/simple-streams/external-formats/utf-16.lisp:
o These formats actually have state, so update them to take a handle
  an initial state.  These are needed if the string buffer ends with a
  leading surrogate and the next string buffer starts with a trailing
  surrogate.  The conversion needs to combine the surrogates together.
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.92 2009/10/18 14:21:24 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 (decf posn (- (fd-stream-ibuf-tail stream)
1666 (fd-stream-ibuf-head stream)))
1667 (when (fd-stream-unread stream) ;;@@
1668 (decf posn))
1669 ;; Divide bytes by element size.
1670 (truncate posn (fd-stream-element-size stream)))
1671 ((eq errno unix:espipe)
1672 nil)
1673 (t
1674 (system:with-interrupts
1675 (error "Error lseek'ing ~S: ~A"
1676 stream
1677 (unix:get-unix-error-msg errno)))))))
1678 (let ((offset 0)
1679 origin)
1680 (declare (type (integer 0) offset))
1681 ;; Make sure we don't have any output pending, because if we move the
1682 ;; file pointer before writing this stuff, it will be written in the
1683 ;; wrong location.
1684 (flush-output-buffer stream)
1685 (do ()
1686 ((null (fd-stream-output-later stream)))
1687 (system:serve-all-events))
1688 ;; Clear out any pending input to force the next read to go to the
1689 ;; disk.
1690 (setf (fd-stream-unread stream) nil) ;;@@
1691 #+unicode (setf (fd-stream-last-char-read-size stream) 0)
1692 (setf (fd-stream-ibuf-head stream) 0)
1693 (setf (fd-stream-ibuf-tail stream) 0)
1694 ;; Trash cached value for listen, so that we check next time.
1695 (setf (fd-stream-listen stream) nil)
1696 ;; Now move it.
1697 (cond ((eq newpos :start)
1698 (setf offset 0
1699 origin unix:l_set))
1700 ((eq newpos :end)
1701 (setf offset 0
1702 origin unix:l_xtnd))
1703 ((typep newpos '(integer 0))
1704 (setf offset (* newpos (fd-stream-element-size stream))
1705 origin unix:l_set))
1706 (t
1707 (error "Invalid position given to file-position: ~S" newpos)))
1708 (multiple-value-bind
1709 (posn errno)
1710 (unix:unix-lseek (fd-stream-fd stream) offset origin)
1711 (cond (posn
1712 t)
1713 ((eq errno unix:espipe)
1714 nil)
1715 (t
1716 (error "Error lseek'ing ~S: ~A"
1717 stream
1718 (unix:get-unix-error-msg errno))))))))
1719
1720
1721
1722 ;;;; Creation routines (MAKE-FD-STREAM and OPEN)
1723
1724 ;;; MAKE-FD-STREAM -- Public.
1725 ;;;
1726 ;;; Returns a FD-STREAM on the given file.
1727 ;;;
1728 (defun make-fd-stream (fd
1729 &key
1730 (input nil input-p)
1731 (output nil output-p)
1732 (element-type 'base-char)
1733 (buffering :full)
1734 timeout
1735 file
1736 original
1737 delete-original
1738 pathname
1739 input-buffer-p
1740 (name (if file
1741 (format nil "file ~S" file)
1742 (format nil "descriptor ~D" fd)))
1743 auto-close
1744 (external-format :default)
1745 binary-stream-p)
1746 (declare (type index fd) (type (or index null) timeout)
1747 (type (member :none :line :full) buffering))
1748 "Create a stream for the given unix file descriptor.
1749 If input is non-nil, allow input operations.
1750 If output is non-nil, allow output operations.
1751 If neither input nor output are specified, default to allowing input.
1752 Element-type indicates the element type to use (as for open).
1753 Buffering indicates the kind of buffering to use.
1754 Timeout (if true) is the number of seconds to wait for input. If NIL (the
1755 default), then wait forever. When we time out, we signal IO-TIMEOUT.
1756 File is the name of the file (will be returned by PATHNAME).
1757 Name is used to identify the stream when printed."
1758 (cond ((not (or input-p output-p))
1759 (setf input t))
1760 ((not (or input output))
1761 (error "File descriptor must be opened either for input or output.")))
1762 (let ((stream (if binary-stream-p
1763 (%make-binary-text-stream :fd fd
1764 :name name
1765 :file file
1766 :original original
1767 :delete-original delete-original
1768 :pathname pathname
1769 :buffering buffering
1770 :timeout timeout)
1771 (%make-fd-stream :fd fd
1772 :name name
1773 :file file
1774 :original original
1775 :delete-original delete-original
1776 :pathname pathname
1777 :buffering buffering
1778 :timeout timeout))))
1779 ;; FIXME: setting the external format here should be better
1780 ;; integrated into set-routines. We do it before so that
1781 ;; set-routines can create an in-buffer if appropriate. But we
1782 ;; need to do it after to put the correct input routines for the
1783 ;; external format.
1784 ;;
1785 ;;#-unicode-bootstrap ; fails in stream-reinit otherwise
1786 #+(and unicode (not unicode-bootstrap))
1787 (when lisp::*enable-stream-buffer-p*
1788 (%set-fd-stream-external-format stream external-format nil))
1789 (set-routines stream element-type input output input-buffer-p
1790 :binary-stream-p binary-stream-p)
1791 #+(and unicode (not unicode-bootstrap))
1792 (when lisp::*enable-stream-buffer-p*
1793 (%set-fd-stream-external-format stream external-format nil))
1794 (when (and auto-close (fboundp 'finalize))
1795 (finalize stream
1796 #'(lambda ()
1797 (unix:unix-close fd)
1798 (format *terminal-io* "** Closed ~A~%" name)
1799 (when original
1800 (revert-file file original)))))
1801 stream))
1802
1803
1804 ;;; PICK-BACKUP-NAME -- internal
1805 ;;;
1806 ;;; Pick a name to use for the backup file.
1807 ;;;
1808 (defvar *backup-extension* ".BAK"
1809 "This is a string that OPEN tacks on the end of a file namestring to produce
1810 a name for the :if-exists :rename-and-delete and :rename options. Also,
1811 this can be a function that takes a namestring and returns a complete
1812 namestring.")
1813 ;;;
1814 (defun pick-backup-name (name)
1815 (declare (type simple-string name))
1816 (let ((ext *backup-extension*))
1817 (etypecase ext
1818 (simple-string (concatenate 'simple-string name ext))
1819 (function (funcall ext name)))))
1820
1821 ;;; NEXT-VERSION -- internal
1822 ;;;
1823 ;;; Find the next available versioned name for a file.
1824 ;;;
1825 (defun next-version (name)
1826 (declare (type simple-string name))
1827 (let* ((sep (position #\/ name :from-end t))
1828 (base (if sep (subseq name 0 (1+ sep)) ""))
1829 (dir (unix:open-dir base)))
1830 (multiple-value-bind (name type version)
1831 (extract-name-type-and-version name (if sep (1+ sep) 0) (length name))
1832 (let ((version (if (symbolp version) 1 (1+ version)))
1833 (match (if type
1834 (concatenate 'string name "." type ".~")
1835 (concatenate 'string name ".~"))))
1836 (when dir
1837 (unwind-protect
1838 (loop
1839 (let ((name (unix:read-dir dir)))
1840 (cond ((null name) (return))
1841 ((and (> (length name) (length match))
1842 (string= name match :end1 (length match)))
1843 (multiple-value-bind (v e)
1844 (parse-integer name :start (length match)
1845 :junk-allowed t)
1846 (when (and v
1847 (= (length name) (1+ e))
1848 (char= (schar name e) #\~))
1849 (setq version (max version (1+ v)))))))))
1850 (unix:close-dir dir)))
1851 (concatenate 'string base
1852 match (quick-integer-to-string version) "~")))))
1853
1854 ;;; ASSURE-ONE-OF -- internal
1855 ;;;
1856 ;;; Assure that the given arg is one of the given list of valid things.
1857 ;;; Allow the user to fix any problems.
1858 ;;;
1859 (defun assure-one-of (item list what)
1860 (unless (member item list)
1861 (loop
1862 (cerror "Enter new value for ~*~S"
1863 "~S is invalid for ~S. Must be one of~{ ~S~}"
1864 item
1865 what
1866 list)
1867 (format (the stream *query-io*) "Enter new value for ~S: " what)
1868 (force-output *query-io*)
1869 (setf item (read *query-io*))
1870 (when (member item list)
1871 (return))))
1872 item)
1873
1874 ;;; DO-OLD-RENAME -- Internal
1875 ;;;
1876 ;;; Rename Namestring to Original. First, check if we have write access,
1877 ;;; since we don't want to trash unwritable files even if we technically can.
1878 ;;; We return true if we succeed in renaming.
1879 ;;;
1880 (defun do-old-rename (namestring original)
1881 (unless (unix:unix-access namestring unix:w_ok)
1882 (cerror "Try to rename it anyway." "File ~S is not writable." namestring))
1883 (multiple-value-bind
1884 (okay err)
1885 (unix:unix-rename namestring original)
1886 (cond (okay t)
1887 (t
1888 (cerror "Use :SUPERSEDE instead."
1889 "Could not rename ~S to ~S: ~A."
1890 namestring
1891 original
1892 (unix:get-unix-error-msg err))
1893 nil))))
1894
1895 ;;; FD-OPEN -- Internal
1896 ;;;
1897 ;;; Open a file.
1898 ;;;
1899 (defun fd-open (pathname direction if-exists if-exists-given
1900 if-does-not-exist if-does-not-exist-given)
1901 (declare (type pathname pathname)
1902 (type (member :input :output :io :probe) direction)
1903 (type (member :error :new-version :rename :rename-and-delete
1904 :overwrite :append :supersede nil) if-exists)
1905 (type (member :error :create nil) if-does-not-exist))
1906 (multiple-value-bind (input output mask)
1907 (ecase direction
1908 (:input (values t nil unix:o_rdonly))
1909 (:output (values nil t unix:o_wronly))
1910 (:io (values t t unix:o_rdwr))
1911 (:probe (values t nil unix:o_rdonly)))
1912 (declare (type index mask))
1913 ;; Process if-exists argument if we are doing any output.
1914 (cond (output
1915 (unless if-exists-given
1916 (setf if-exists
1917 (if (eq (pathname-version pathname) :newest)
1918 :new-version
1919 :error)))
1920 (case if-exists
1921 ((:error nil)
1922 (setf mask (logior mask unix:o_excl)))
1923 ((:new-version :rename :rename-and-delete)
1924 (setf mask (logior mask unix:o_creat)))
1925 (:supersede
1926 (setf mask (logior mask unix:o_trunc)))))
1927 (t
1928 (setf if-exists nil))) ; :ignore-this-arg
1929
1930 (unless if-does-not-exist-given
1931 (setf if-does-not-exist
1932 (cond ((eq direction :input) :error)
1933 ((and output
1934 (member if-exists '(:overwrite :append)))
1935 :error)
1936 ((eq direction :probe)
1937 nil)
1938 (t
1939 :create))))
1940 (if (eq if-does-not-exist :create)
1941 (setf mask (logior mask unix:o_creat)))
1942
1943 (let ((name (cond ((unix-namestring pathname input))
1944 ((and input (eq if-does-not-exist :create))
1945 (unix-namestring pathname nil)))))
1946 (let ((original (cond ((eq if-exists :new-version)
1947 (next-version name))
1948 ((member if-exists '(:rename :rename-and-delete))
1949 (pick-backup-name name))))
1950 (delete-original (eq if-exists :rename-and-delete))
1951 (mode #o666))
1952 (when original
1953 ;; We are doing a :rename or :rename-and-delete.
1954 ;; Determine if the file already exists, make sure the original
1955 ;; file is not a directory and keep the mode
1956 (let ((exists
1957 (and name
1958 (multiple-value-bind
1959 (okay err/dev inode orig-mode)
1960 (unix:unix-stat name)
1961 (declare (ignore inode)
1962 (type (or index null) orig-mode))
1963 (cond
1964 (okay
1965 (when (and output (= (logand orig-mode #o170000)
1966 #o40000))
1967 (error 'simple-file-error
1968 :pathname pathname
1969 :format-control
1970 "Cannot open ~S for output: Is a directory."
1971 :format-arguments (list name)))
1972 (setf mode (logand orig-mode #o777))
1973 t)
1974 ((eql err/dev unix:enoent)
1975 nil)
1976 (t
1977 (error 'simple-file-error
1978 :pathname pathname
1979 :format-control "Cannot find ~S: ~A"
1980 :format-arguments
1981 (list name
1982 (unix:get-unix-error-msg err/dev)))))))))
1983 (unless (and exists
1984 (do-old-rename name original))
1985 (setf original nil)
1986 (setf delete-original nil)
1987 ;; In order to use SUPERSEDE instead, we have
1988 ;; to make sure unix:o_creat corresponds to
1989 ;; if-does-not-exist. unix:o_creat was set
1990 ;; before because of if-exists being :rename.
1991 (unless (eq if-does-not-exist :create)
1992 (setf mask (logior (logandc2 mask unix:o_creat)
1993 unix:o_trunc)))
1994 (setf if-exists :supersede))))
1995
1996 ;; Okay, now we can try the actual open.
1997 (loop
1998 (multiple-value-bind (fd errno)
1999 (if name
2000 (unix:unix-open name mask mode)
2001 (values nil unix:enoent))
2002 (cond ((fixnump fd)
2003 (when (eq if-exists :append)
2004 (unix:unix-lseek fd 0 unix:l_xtnd)) ; SEEK_END
2005 (return (values fd name original delete-original)))
2006 ((eql errno unix:enoent)
2007 (case if-does-not-exist
2008 (:error
2009 (cerror "Return NIL."
2010 'simple-file-error
2011 :pathname pathname
2012 :format-control "Error opening ~S, ~A."
2013 :format-arguments
2014 (list pathname
2015 (unix:get-unix-error-msg errno))))
2016 (:create
2017 (cerror "Return NIL."
2018 'simple-file-error
2019 :pathname pathname
2020 :format-control
2021 "Error creating ~S, path does not exist."
2022 :format-arguments (list pathname))))
2023 (return nil))
2024 ((eql errno unix:eexist)
2025 (unless (eq nil if-exists)
2026 (cerror "Return NIL."
2027 'simple-file-error
2028 :pathname pathname
2029 :format-control "Error opening ~S, ~A."
2030 :format-arguments
2031 (list pathname
2032 (unix:get-unix-error-msg errno))))
2033 (return nil))
2034 ((eql errno unix:eacces)
2035 (cerror "Try again."
2036 'simple-file-error
2037 :pathname pathname
2038 :format-control "Error opening ~S, ~A."
2039 :format-arguments
2040 (list pathname
2041 (unix:get-unix-error-msg errno))))
2042 (t
2043 (cerror "Return NIL."
2044 'simple-file-error
2045 :pathname pathname
2046 :format-control "Error opening ~S, ~A."
2047 :format-arguments
2048 (list pathname
2049 (unix:get-unix-error-msg errno)))
2050 (return nil)))))))))
2051
2052 ;;; OPEN-FD-STREAM -- Internal
2053 ;;;
2054 ;;; Open an fd-stream connected to a file.
2055 ;;;
2056 (defun open-fd-stream (pathname &key (direction :input)
2057 (element-type 'base-char)
2058 (if-exists nil if-exists-given)
2059 (if-does-not-exist nil if-does-not-exist-given)
2060 (external-format :default)
2061 class)
2062 (declare (type pathname pathname)
2063 (type (member :input :output :io :probe) direction)
2064 (type (member :error :new-version :rename :rename-and-delete
2065 :overwrite :append :supersede nil) if-exists)
2066 (type (member :error :create nil) if-does-not-exist))
2067 (multiple-value-bind (fd namestring original delete-original)
2068 (fd-open pathname direction if-exists if-exists-given
2069 if-does-not-exist if-does-not-exist-given)
2070 (when fd
2071 (case direction
2072 ((:input :output :io)
2073 ;; We use the :class option to tell us if we want a
2074 ;; binary-text stream or not.
2075 (make-fd-stream fd
2076 :input (member direction '(:input :io))
2077 :output (member direction '(:output :io))
2078 :element-type element-type
2079 :file namestring
2080 :original original
2081 :delete-original delete-original
2082 :pathname pathname
2083 :input-buffer-p t
2084 :auto-close t
2085 :external-format external-format
2086 :binary-stream-p class))
2087 (:probe
2088 (let ((stream (%make-fd-stream :name namestring :fd fd
2089 :pathname pathname
2090 :element-type element-type)))
2091 (close stream)
2092 stream))))))
2093
2094 ;;; OPEN -- public
2095 ;;;
2096 ;;; Open the given file.
2097 ;;;
2098 (defun open (filename &rest options
2099 &key (direction :input)
2100 (element-type 'base-char element-type-given)
2101 (if-exists nil if-exists-given)
2102 (if-does-not-exist nil if-does-not-exist-given)
2103 (external-format :default)
2104 class mapped input-handle output-handle
2105 &allow-other-keys
2106 &aux ; Squelch assignment warning.
2107 (options options)
2108 (direction direction)
2109 (if-does-not-exist if-does-not-exist)
2110 (if-exists if-exists))
2111 "Return a stream which reads from or writes to Filename.
2112 Defined keywords:
2113 :direction - one of :input, :output, :io, or :probe
2114 :element-type - Type of object to read or write, default BASE-CHAR
2115 :if-exists - one of :error, :new-version, :rename, :rename-and-delete,
2116 :overwrite, :append, :supersede or nil
2117 :if-does-not-exist - one of :error, :create or nil
2118 :external-format - an external format name
2119 See the manual for details."
2120 (declare (ignore element-type external-format input-handle output-handle))
2121
2122 ;; OPEN signals a file-error if the filename is wild.
2123 (when (wild-pathname-p filename)
2124 (error 'file-error :pathname filename))
2125
2126 ;; First, make sure that DIRECTION is valid. Allow it to be changed if not.
2127 (setq direction
2128 (assure-one-of direction
2129 '(:input :output :io :probe)
2130 :direction))
2131 (setf (getf options :direction) direction)
2132
2133 (when (and if-exists-given (member direction '(:output :io)))
2134 (setq if-exists
2135 (assure-one-of if-exists
2136 '(:error :new-version :rename
2137 :rename-and-delete :overwrite
2138 :append :supersede nil)
2139 :if-exists))
2140 (setf (getf options :if-exists) if-exists))
2141
2142 (when if-does-not-exist-given
2143 (setq if-does-not-exist
2144 (assure-one-of if-does-not-exist
2145 '(:error :create nil)
2146 :if-does-not-exist))
2147 (setf (getf options :if-does-not-exist) if-does-not-exist))
2148
2149 (let ((filespec (pathname filename))
2150 (options (copy-list options))
2151 (class (or class 'fd-stream)))
2152 (cond ((eq class 'fd-stream)
2153 (remf options :class)
2154 (remf options :mapped)
2155 (remf options :input-handle)
2156 (remf options :output-handle)
2157 (apply #'open-fd-stream filespec options))
2158 ((eq class 'binary-text-stream)
2159 ;; Like fd-stream, but binary and text allowed. This is
2160 ;; indicated by leaving the :class option around for
2161 ;; open-fd-stream to see.
2162 (remf options :mapped)
2163 (remf options :input-handle)
2164 (remf options :output-handle)
2165 (apply #'open-fd-stream filespec options))
2166 ((subtypep class 'stream:simple-stream)
2167 (when element-type-given
2168 (cerror "Do it anyway."
2169 "Can't create simple-streams with an element-type."))
2170 (when (and (eq class 'stream:file-simple-stream) mapped)
2171 (setq class 'stream:mapped-file-simple-stream)
2172 (setf (getf options :class) 'stream:mapped-file-simple-stream))
2173 (when (subtypep class 'stream:file-simple-stream)
2174 (when (eq direction :probe)
2175 (setq class 'stream:probe-simple-stream)))
2176 (apply #'make-instance class :filename filespec options))
2177 ((subtypep class 'ext:fundamental-stream)
2178 (remf options :class)
2179 (remf options :mapped)
2180 (remf options :input-handle)
2181 (remf options :output-handle)
2182 (let ((stream (apply #'open-fd-stream filespec options)))
2183 (when stream
2184 (make-instance class :lisp-stream stream))))
2185 (t
2186 (error "Unable to open streams of class ~S." class)))))
2187
2188 ;;;; Initialization.
2189
2190 (defvar *tty* nil
2191 "The stream connected to the controlling terminal or NIL if there is none.")
2192 (defvar *stdin* nil
2193 "The stream connected to the standard input (file descriptor 0).")
2194 (defvar *stdout* nil
2195 "The stream connected to the standard output (file descriptor 1).")
2196 (defvar *stderr* nil
2197 "The stream connected to the standard error output (file descriptor 2).")
2198
2199 ;;; STREAM-INIT -- internal interface
2200 ;;;
2201 ;;; Called when the cold load is first started up.
2202 ;;;
2203 (defun stream-init ()
2204 (stream-reinit)
2205 (setf *terminal-io* (make-synonym-stream '*tty*))
2206 (setf *standard-output* (make-synonym-stream '*stdout*))
2207 (setf *standard-input*
2208 (make-two-way-stream (make-synonym-stream '*stdin*)
2209 *standard-output*))
2210 (setf *error-output* (make-synonym-stream '*stderr*))
2211 (setf *query-io* (make-synonym-stream '*terminal-io*))
2212 (setf *debug-io* *query-io*)
2213 (setf *trace-output* *standard-output*)
2214 nil)
2215
2216 ;;; STREAM-REINIT -- internal interface
2217 ;;;
2218 ;;; Called whenever a saved core is restarted.
2219 ;;;
2220 (defun stream-reinit ()
2221 (setf *available-buffers* nil)
2222 (setf *stdin*
2223 (make-fd-stream 0 :name "Standard Input" :input t :buffering :line
2224 :external-format :iso8859-1))
2225 (setf *stdout*
2226 (make-fd-stream 1 :name "Standard Output" :output t :buffering :line
2227 :external-format :iso8859-1))
2228 (setf *stderr*
2229 (make-fd-stream 2 :name "Standard Error" :output t :buffering :line
2230 :external-format :iso8859-1))
2231 (let ((tty (and (not *batch-mode*)
2232 (unix:unix-open "/dev/tty" unix:o_rdwr #o666))))
2233 (setf *tty*
2234 (if tty
2235 (make-fd-stream tty :name "the Terminal" :input t :output t
2236 :buffering :line :auto-close t
2237 :external-format :iso8859-1)
2238 (make-two-way-stream *stdin* *stdout*))))
2239 nil)
2240
2241
2242 ;;;; Beeping.
2243
2244 (defun default-beep-function (stream)
2245 (write-char #\bell stream)
2246 (finish-output stream))
2247
2248 (defvar *beep-function* #'default-beep-function
2249 "This is called in BEEP to feep the user. It takes a stream.")
2250
2251 (defun beep (&optional (stream *terminal-io*))
2252 (funcall *beep-function* stream))
2253
2254
2255 ;;; File-Name -- internal interface
2256 ;;;
2257 ;;; Kind of like File-Position, but is an internal hack used by the filesys
2258 ;;; stuff to get and set the file name.
2259 ;;;
2260 (defun file-name (stream &optional new-name)
2261 (typecase stream
2262 (stream:simple-stream
2263 (if new-name
2264 (stream::%file-rename stream new-name)
2265 (stream::%file-name stream)))
2266 (fd-stream
2267 (cond (new-name
2268 (setf (fd-stream-pathname stream) new-name)
2269 (setf (fd-stream-file stream)
2270 (unix-namestring new-name nil))
2271 t)
2272 (t
2273 (fd-stream-pathname stream))))))
2274
2275
2276
2277 #+unicode
2278 (stream::def-ef-macro ef-strlen (extfmt lisp stream::+ef-max+ stream::+ef-str+)
2279 ;; While it would be nice not to have to call CHAR-TO-OCTETS to
2280 ;; figure out the length when the external format has fixed size
2281 ;; outputs, we can't. For example, utf16 will output a BOM, which
2282 ;; wouldn't be reflected in the count if we don't call
2283 ;; CHAR-TO-OCTETS.
2284 `(lambda (stream object &aux (count 0))
2285 (declare (type fd-stream stream)
2286 (type (or character string) object)
2287 (type (and fixnum unsigned-byte) count)
2288 #|(optimize (speed 3) (space 0) (debug 0) (safety 0))|#)
2289 (labels ((efstate (state)
2290 (stream::copy-state ,extfmt state))
2291 (eflen (char)
2292 (stream::char-to-octets ,extfmt char
2293 (fd-stream-co-state stream)
2294 (lambda (byte)
2295 (declare (ignore byte))
2296 (incf count)))))
2297 (let* ((co-state (fd-stream-co-state stream))
2298 (old-ef-state (efstate (cdr (fd-stream-co-state stream))))
2299 (old-state (cons (car co-state) old-ef-state)))
2300 (etypecase object
2301 (character (eflen object))
2302 (string (dovector (ch object) (eflen ch))))
2303 ;; Restore state
2304 (setf (fd-stream-co-state stream) old-state)
2305 count))))
2306
2307
2308 (defun file-string-length (stream object)
2309 (declare (type (or string character) object)
2310 (type (or file-stream broadcast-stream stream:simple-stream) stream))
2311 "Return the delta in Stream's FILE-POSITION that would be caused by writing
2312 Object to Stream. Non-trivial only in implementations that support
2313 international character sets."
2314 (typecase stream
2315 (stream:simple-stream (stream::%file-string-length stream object))
2316 (broadcast-stream
2317 ;; CLHS says we must return 1 in this case
2318 1)
2319 #+unicode
2320 (t (funcall (ef-strlen (fd-stream-external-format stream))
2321 stream object))
2322 #-unicode
2323 (t (etypecase object
2324 (character 1)
2325 (string (length object))))))
2326
2327 #+unicode
2328 (stream::def-ef-macro ef-copy-state (extfmt lisp stream::+ef-max+ stream::+ef-copy-state+)
2329 ;; Return a copy of the state of an external format.
2330 `(lambda (state)
2331 (declare (ignorable state))
2332 (stream::copy-state ,extfmt state)))

  ViewVC Help
Powered by ViewVC 1.1.5