1.0.22.22: (SETF FIND-CLASSOID) to drop DEFTYPE lambda-lists and source-locations
[sbcl/tcr.git] / src / code / fd-stream.lisp
blob771cd10e7c2cfbaeea272a13c5b6a1bf93900a5a
1 ;;;; streams for UNIX file descriptors
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!IMPL")
14 ;;;; BUFFER
15 ;;;;
16 ;;;; Streams hold BUFFER objects, which contain a SAP, size of the
17 ;;;; memory area the SAP stands for (LENGTH bytes), and HEAD and TAIL
18 ;;;; indexes which delimit the "valid", or "active" area of the
19 ;;;; memory. HEAD is inclusive, TAIL is exclusive.
20 ;;;;
21 ;;;; Buffers get allocated lazily, and are recycled by returning them
22 ;;;; to the *AVAILABLE-BUFFERS* list. Every buffer has it's own
23 ;;;; finalizer, to take care of releasing the SAP memory when a stream
24 ;;;; is not properly closed.
25 ;;;;
26 ;;;; The code aims to provide a limited form of thread and interrupt
27 ;;;; safety: parallel writes and reads may lose output or input, cause
28 ;;;; interleaved IO, etc -- but they should not corrupt memory. The
29 ;;;; key to doing this is to read buffer state once, and update the
30 ;;;; state based on the read state:
31 ;;;;
32 ;;;; (let ((tail (buffer-tail buffer)))
33 ;;;; ...
34 ;;;; (setf (buffer-tail buffer) (+ tail n)))
35 ;;;;
36 ;;;; NOT
37 ;;;;
38 ;;;; (let ((tail (buffer-tail buffer)))
39 ;;;; ...
40 ;;;; (incf (buffer-tail buffer) n))
41 ;;;;
43 (declaim (inline buffer-sap buffer-length buffer-head buffer-tail
44 (setf buffer-head) (setf buffer-tail)))
45 (defstruct (buffer (:constructor %make-buffer (sap length)))
46 (sap (missing-arg) :type system-area-pointer :read-only t)
47 (length (missing-arg) :type index :read-only t)
48 (head 0 :type index)
49 (tail 0 :type index))
51 (defvar *available-buffers* ()
52 #!+sb-doc
53 "List of available buffers.")
55 (defvar *available-buffers-spinlock* (sb!thread::make-spinlock
56 :name "lock for *AVAILABLE-BUFFERS*")
57 #!+sb-doc
58 "Mutex for access to *AVAILABLE-BUFFERS*.")
60 (defmacro with-available-buffers-lock ((&optional) &body body)
61 ;; CALL-WITH-SYSTEM-SPINLOCK because
63 ;; 1. streams are low-level enough to be async signal safe, and in
64 ;; particular a C-c that brings up the debugger while holding the
65 ;; mutex would lose badly
67 ;; 2. this can potentially be a fairly busy (but also probably
68 ;; uncontended) lock, so we don't want to pay the syscall per
69 ;; release -- hence a spinlock.
71 ;; ...again, once we have smarted locks the spinlock here can become
72 ;; a mutex.
73 `(sb!thread::with-system-spinlock (*available-buffers-spinlock*)
74 ,@body))
76 (defconstant +bytes-per-buffer+ (* 4 1024)
77 #!+sb-doc
78 "Default number of bytes per buffer.")
80 (defun alloc-buffer (&optional (size +bytes-per-buffer+))
81 ;; Don't want to allocate & unwind before the finalizer is in place.
82 (without-interrupts
83 (let* ((sap (allocate-system-memory size))
84 (buffer (%make-buffer sap size)))
85 (when (zerop (sap-int sap))
86 (error "Could not allocate ~D bytes for buffer." size))
87 (finalize buffer (lambda ()
88 (deallocate-system-memory sap size))
89 :dont-save t)
90 buffer)))
92 (defun get-buffer ()
93 ;; Don't go for the lock if there is nothing to be had -- sure,
94 ;; another thread might just release one before we get it, but that
95 ;; is not worth the cost of locking. Also release the lock before
96 ;; allocation, since it's going to take a while.
97 (if *available-buffers*
98 (or (with-available-buffers-lock ()
99 (pop *available-buffers*))
100 (alloc-buffer))
101 (alloc-buffer)))
103 (declaim (inline reset-buffer))
104 (defun reset-buffer (buffer)
105 (setf (buffer-head buffer) 0
106 (buffer-tail buffer) 0)
107 buffer)
109 (defun release-buffer (buffer)
110 (reset-buffer buffer)
111 (with-available-buffers-lock ()
112 (push buffer *available-buffers*)))
114 ;;; This is a separate buffer management function, as it wants to be
115 ;;; clever about locking -- grabbing the lock just once.
116 (defun release-fd-stream-buffers (fd-stream)
117 (let ((ibuf (fd-stream-ibuf fd-stream))
118 (obuf (fd-stream-obuf fd-stream))
119 (queue (loop for item in (fd-stream-output-queue fd-stream)
120 when (buffer-p item)
121 collect (reset-buffer item))))
122 (when ibuf
123 (push (reset-buffer ibuf) queue))
124 (when obuf
125 (push (reset-buffer obuf) queue))
126 ;; ...so, anything found?
127 (when queue
128 ;; detach from stream
129 (setf (fd-stream-ibuf fd-stream) nil
130 (fd-stream-obuf fd-stream) nil
131 (fd-stream-output-queue fd-stream) nil)
132 ;; splice to *available-buffers*
133 (with-available-buffers-lock ()
134 (setf *available-buffers* (nconc queue *available-buffers*))))))
136 ;;;; the FD-STREAM structure
138 (defstruct (fd-stream
139 (:constructor %make-fd-stream)
140 (:conc-name fd-stream-)
141 (:predicate fd-stream-p)
142 (:include ansi-stream
143 (misc #'fd-stream-misc-routine))
144 (:copier nil))
146 ;; the name of this stream
147 (name nil)
148 ;; the file this stream is for
149 (file nil)
150 ;; the backup file namestring for the old file, for :IF-EXISTS
151 ;; :RENAME or :RENAME-AND-DELETE.
152 (original nil :type (or simple-string null))
153 (delete-original nil) ; for :if-exists :rename-and-delete
154 ;;; the number of bytes per element
155 (element-size 1 :type index)
156 ;; the type of element being transfered
157 (element-type 'base-char)
158 ;; the Unix file descriptor
159 (fd -1 :type fixnum)
160 ;; controls when the output buffer is flushed
161 (buffering :full :type (member :full :line :none))
162 ;; controls whether the input buffer must be cleared before output
163 ;; (must be done for files, not for sockets, pipes and other data
164 ;; sources where input and output aren't related). non-NIL means
165 ;; don't clear input buffer.
166 (dual-channel-p nil)
167 ;; character position if known -- this may run into bignums, but
168 ;; we probably should flip it into null then for efficiency's sake...
169 (char-pos nil :type (or unsigned-byte null))
170 ;; T if input is waiting on FD. :EOF if we hit EOF.
171 (listen nil :type (member nil t :eof))
173 ;; the input buffer
174 (unread nil)
175 (ibuf nil :type (or buffer null))
177 ;; the output buffer
178 (obuf nil :type (or buffer null))
180 ;; output flushed, but not written due to non-blocking io?
181 (output-queue nil)
182 (handler nil)
183 ;; timeout specified for this stream as seconds or NIL if none
184 (timeout nil :type (or single-float null))
185 ;; pathname of the file this stream is opened to (returned by PATHNAME)
186 (pathname nil :type (or pathname null))
187 (external-format :default)
188 ;; fixed width, or function to call with a character
189 (char-size 1 :type (or fixnum function))
190 (output-bytes #'ill-out :type function))
191 (def!method print-object ((fd-stream fd-stream) stream)
192 (declare (type stream stream))
193 (print-unreadable-object (fd-stream stream :type t :identity t)
194 (format stream "for ~S" (fd-stream-name fd-stream))))
196 ;;;; CORE OUTPUT FUNCTIONS
198 ;;; Buffer the section of THING delimited by START and END by copying
199 ;;; to output buffer(s) of stream.
200 (defun buffer-output (stream thing start end)
201 (declare (index start end))
202 (when (< end start)
203 (error ":END before :START!"))
204 (when (> end start)
205 ;; Copy bytes from THING to buffers.
206 (flet ((copy-to-buffer (buffer tail count)
207 (declare (buffer buffer) (index tail count))
208 (aver (plusp count))
209 (let ((sap (buffer-sap buffer)))
210 (etypecase thing
211 (system-area-pointer
212 (system-area-ub8-copy thing start sap tail count))
213 ((simple-unboxed-array (*))
214 (copy-ub8-to-system-area thing start sap tail count))))
215 ;; Not INCF! If another thread has moved tail from under
216 ;; us, we don't want to accidentally increment tail
217 ;; beyond buffer-length.
218 (setf (buffer-tail buffer) (+ count tail))
219 (incf start count)))
220 (tagbody
221 ;; First copy is special: the buffer may already contain
222 ;; something, or be even full.
223 (let* ((obuf (fd-stream-obuf stream))
224 (tail (buffer-tail obuf))
225 (space (- (buffer-length obuf) tail)))
226 (when (plusp space)
227 (copy-to-buffer obuf tail (min space (- end start)))
228 (go :more-output-p)))
229 :flush-and-fill
230 ;; Later copies should always have an empty buffer, since
231 ;; they are freshly flushed, but if another thread is
232 ;; stomping on the same buffer that might not be the case.
233 (let* ((obuf (flush-output-buffer stream))
234 (tail (buffer-tail obuf))
235 (space (- (buffer-length obuf) tail)))
236 (copy-to-buffer obuf tail (min space (- end start))))
237 :more-output-p
238 (when (> end start)
239 (go :flush-and-fill))))))
241 ;;; Flush the current output buffer of the stream, ensuring that the
242 ;;; new buffer is empty. Returns (for convenience) the new output
243 ;;; buffer -- which may or may not be EQ to the old one. If the is no
244 ;;; queued output we try to write the buffer immediately -- otherwise
245 ;;; we queue it for later.
246 (defun flush-output-buffer (stream)
247 (let ((obuf (fd-stream-obuf stream)))
248 (when obuf
249 (let ((head (buffer-head obuf))
250 (tail (buffer-tail obuf)))
251 (cond ((eql head tail)
252 ;; Buffer is already empty -- just ensure that is is
253 ;; set to zero as well.
254 (reset-buffer obuf))
255 ((fd-stream-output-queue stream)
256 ;; There is already stuff on the queue -- go directly
257 ;; there.
258 (aver (< head tail))
259 (%queue-and-replace-output-buffer stream))
261 ;; Try a non-blocking write, queue whatever is left over.
262 (aver (< head tail))
263 (synchronize-stream-output stream)
264 (let ((length (- tail head)))
265 (multiple-value-bind (count errno)
266 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
267 head length)
268 (cond ((eql count length)
269 ;; Complete write -- we can use the same buffer.
270 (reset-buffer obuf))
271 (count
272 ;; Partial write -- update buffer status and queue.
273 ;; Do not use INCF! Another thread might have moved
274 ;; head...
275 (setf (buffer-head obuf) (+ count head))
276 (%queue-and-replace-output-buffer stream))
277 #!-win32
278 ((eql errno sb!unix:ewouldblock)
279 ;; Blocking, queue.
280 (%queue-and-replace-output-buffer stream))
282 (simple-stream-perror "Couldn't write to ~s"
283 stream errno)))))))))))
285 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
286 (defun %queue-and-replace-output-buffer (stream)
287 (let ((queue (fd-stream-output-queue stream))
288 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
289 (new (get-buffer)))
290 ;; Important: before putting the buffer on queue, give the stream
291 ;; a new one. If we get an interrupt and unwind losing the buffer
292 ;; is relatively OK, but having the same buffer in two places
293 ;; would be bad.
294 (setf (fd-stream-obuf stream) new)
295 (cond (queue
296 (nconc queue later))
298 (setf (fd-stream-output-queue stream) later)))
299 (unless (fd-stream-handler stream)
300 (setf (fd-stream-handler stream)
301 (add-fd-handler (fd-stream-fd stream)
302 :output
303 (lambda (fd)
304 (declare (ignore fd))
305 (write-output-from-queue stream)))))
306 new))
308 ;;; This is called by the FD-HANDLER for the stream when output is
309 ;;; possible.
310 (defun write-output-from-queue (stream)
311 (synchronize-stream-output stream)
312 (let (not-first-p)
313 (tagbody
314 :pop-buffer
315 (let* ((buffer (pop (fd-stream-output-queue stream)))
316 (head (buffer-head buffer))
317 (length (- (buffer-tail buffer) head)))
318 (declare (index head length))
319 (aver (>= length 0))
320 (multiple-value-bind (count errno)
321 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
322 head length)
323 (cond ((eql count length)
324 ;; Complete write, see if we can do another right
325 ;; away, or remove the handler if we're done.
326 (release-buffer buffer)
327 (cond ((fd-stream-output-queue stream)
328 (setf not-first-p t)
329 (go :pop-buffer))
331 (let ((handler (fd-stream-handler stream)))
332 (aver handler)
333 (setf (fd-stream-handler stream) nil)
334 (remove-fd-handler handler)))))
335 (count
336 ;; Partial write. Update buffer status and requeue.
337 (aver (< count length))
338 ;; Do not use INCF! Another thread might have moved head.
339 (setf (buffer-head buffer) (+ head count))
340 (push buffer (fd-stream-output-queue stream)))
341 (not-first-p
342 ;; We tried to do multiple writes, and finally our
343 ;; luck ran out. Requeue.
344 (push buffer (fd-stream-output-queue stream)))
346 ;; Could not write on the first try at all!
347 #!+win32
348 (simple-stream-perror "Couldn't write to ~S." stream errno)
349 #!-win32
350 (if (= errno sb!unix:ewouldblock)
351 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
352 (simple-stream-perror "Couldn't write to ~S"
353 stream errno))))))))
354 nil)
356 ;;; Try to write THING directly to STREAM without buffering, if
357 ;;; possible. If direct write doesn't happen, buffer.
358 (defun write-or-buffer-output (stream thing start end)
359 (declare (index start end))
360 (cond ((fd-stream-output-queue stream)
361 (buffer-output stream thing start end))
362 ((< end start)
363 (error ":END before :START!"))
364 ((> end start)
365 (let ((length (- end start)))
366 (synchronize-stream-output stream)
367 (multiple-value-bind (count errno)
368 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
369 (cond ((eql count length)
370 ;; Complete write -- done!
372 (count
373 (aver (< count length))
374 ;; Partial write -- buffer the rest.
375 (buffer-output stream thing (+ start count) end))
377 ;; Could not write -- buffer or error.
378 #!+win32
379 (simple-stream-perror "couldn't write to ~s" stream errno)
380 #!-win32
381 (if (= errno sb!unix:ewouldblock)
382 (buffer-output stream thing start end)
383 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
385 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
386 ;;; this is not something we want to export. Nikodemus thinks the
387 ;;; right thing is to support a low-level non-stream like IO layer,
388 ;;; akin to java.nio.
389 (defun output-raw-bytes (stream thing &optional start end)
390 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
392 (define-compiler-macro output-raw-bytes (stream thing &optional start end)
393 (deprecation-warning 'output-raw-bytes)
394 (let ((x (gensym "THING")))
395 `(let ((,x ,thing))
396 (write-or-buffer-output ,stream ,x (or ,start 0) (or ,end (length ,x))))))
398 ;;;; output routines and related noise
400 (defvar *output-routines* ()
401 #!+sb-doc
402 "List of all available output routines. Each element is a list of the
403 element-type output, the kind of buffering, the function name, and the number
404 of bytes per element.")
406 ;;; common idioms for reporting low-level stream and file problems
407 (defun simple-stream-perror (note-format stream errno)
408 (error 'simple-stream-error
409 :stream stream
410 :format-control "~@<~?: ~2I~_~A~:>"
411 :format-arguments (list note-format (list stream) (strerror errno))))
412 (defun simple-file-perror (note-format pathname errno)
413 (error 'simple-file-error
414 :pathname pathname
415 :format-control "~@<~?: ~2I~_~A~:>"
416 :format-arguments
417 (list note-format (list pathname) (strerror errno))))
419 (defun stream-decoding-error (stream octets)
420 (error 'stream-decoding-error
421 :external-format (stream-external-format stream)
422 :stream stream
423 ;; FIXME: dunno how to get at OCTETS currently, or even if
424 ;; that's the right thing to report.
425 :octets octets))
426 (defun stream-encoding-error (stream code)
427 (error 'stream-encoding-error
428 :external-format (stream-external-format stream)
429 :stream stream
430 :code code))
432 (defun c-string-encoding-error (external-format code)
433 (error 'c-string-encoding-error
434 :external-format external-format
435 :code code))
437 (defun c-string-decoding-error (external-format octets)
438 (error 'c-string-decoding-error
439 :external-format external-format
440 :octets octets))
442 ;;; Returning true goes into end of file handling, false will enter another
443 ;;; round of input buffer filling followed by re-entering character decode.
444 (defun stream-decoding-error-and-handle (stream octet-count)
445 (restart-case
446 (stream-decoding-error stream
447 (let* ((buffer (fd-stream-ibuf stream))
448 (sap (buffer-sap buffer))
449 (head (buffer-head buffer)))
450 (loop for i from 0 below octet-count
451 collect (sap-ref-8 sap (+ head i)))))
452 (attempt-resync ()
453 :report (lambda (stream)
454 (format stream
455 "~@<Attempt to resync the stream at a ~
456 character boundary and continue.~@:>"))
457 (fd-stream-resync stream)
458 nil)
459 (force-end-of-file ()
460 :report (lambda (stream)
461 (format stream "~@<Force an end of file.~@:>"))
462 t)))
464 (defun stream-encoding-error-and-handle (stream code)
465 (restart-case
466 (stream-encoding-error stream code)
467 (output-nothing ()
468 :report (lambda (stream)
469 (format stream "~@<Skip output of this character.~@:>"))
470 (throw 'output-nothing nil))))
472 (defun external-format-encoding-error (stream code)
473 (if (streamp stream)
474 (stream-encoding-error-and-handle stream code)
475 (c-string-encoding-error stream code)))
477 (defun external-format-decoding-error (stream octet-count)
478 (if (streamp stream)
479 (stream-decoding-error stream octet-count)
480 (c-string-decoding-error stream octet-count)))
482 (defun synchronize-stream-output (stream)
483 ;; If we're reading and writing on the same file, flush buffered
484 ;; input and rewind file position accordingly.
485 (unless (fd-stream-dual-channel-p stream)
486 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
487 (unless (eql 0 adjust)
488 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
490 (defun fd-stream-output-finished-p (stream)
491 (let ((obuf (fd-stream-obuf stream)))
492 (or (not obuf)
493 (and (zerop (buffer-tail obuf))
494 (not (fd-stream-output-queue stream))))))
496 (defmacro output-wrapper/variable-width ((stream size buffering restart)
497 &body body)
498 (let ((stream-var (gensym "STREAM")))
499 `(let* ((,stream-var ,stream)
500 (obuf (fd-stream-obuf ,stream-var))
501 (tail (buffer-tail obuf))
502 (size ,size))
503 ,(unless (eq (car buffering) :none)
504 `(when (<= (buffer-length obuf) (+ tail size))
505 (setf obuf (flush-output-buffer ,stream-var)
506 tail (buffer-tail obuf))))
507 ,(unless (eq (car buffering) :none)
508 ;; FIXME: Why this here? Doesn't seem necessary.
509 `(synchronize-stream-output ,stream-var))
510 ,(if restart
511 `(catch 'output-nothing
512 ,@body
513 (setf (buffer-tail obuf) (+ tail size)))
514 `(progn
515 ,@body
516 (setf (buffer-tail obuf) (+ tail size))))
517 ,(ecase (car buffering)
518 (:none
519 `(flush-output-buffer ,stream-var))
520 (:line
521 `(when (eql byte #\Newline)
522 (flush-output-buffer ,stream-var)))
523 (:full))
524 (values))))
526 (defmacro output-wrapper ((stream size buffering restart) &body body)
527 (let ((stream-var (gensym "STREAM")))
528 `(let* ((,stream-var ,stream)
529 (obuf (fd-stream-obuf ,stream-var))
530 (tail (buffer-tail obuf)))
531 ,(unless (eq (car buffering) :none)
532 `(when (<= (buffer-length obuf) (+ tail ,size))
533 (setf obuf (flush-output-buffer ,stream-var)
534 tail (buffer-tail obuf))))
535 ;; FIXME: Why this here? Doesn't seem necessary.
536 ,(unless (eq (car buffering) :none)
537 `(synchronize-stream-output ,stream-var))
538 ,(if restart
539 `(catch 'output-nothing
540 ,@body
541 (setf (buffer-tail obuf) (+ tail ,size)))
542 `(progn
543 ,@body
544 (setf (buffer-tail obuf) (+ tail ,size))))
545 ,(ecase (car buffering)
546 (:none
547 `(flush-output-buffer ,stream-var))
548 (:line
549 `(when (eql byte #\Newline)
550 (flush-output-buffer ,stream-var)))
551 (:full))
552 (values))))
554 (defmacro def-output-routines/variable-width
555 ((name-fmt size restart external-format &rest bufferings)
556 &body body)
557 (declare (optimize (speed 1)))
558 (cons 'progn
559 (mapcar
560 (lambda (buffering)
561 (let ((function
562 (intern (format nil name-fmt (string (car buffering))))))
563 `(progn
564 (defun ,function (stream byte)
565 (declare (ignorable byte))
566 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
567 ,@body))
568 (setf *output-routines*
569 (nconc *output-routines*
570 ',(mapcar
571 (lambda (type)
572 (list type
573 (car buffering)
574 function
576 external-format))
577 (cdr buffering)))))))
578 bufferings)))
580 ;;; Define output routines that output numbers SIZE bytes long for the
581 ;;; given bufferings. Use BODY to do the actual output.
582 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
583 &body body)
584 (declare (optimize (speed 1)))
585 (cons 'progn
586 (mapcar
587 (lambda (buffering)
588 (let ((function
589 (intern (format nil name-fmt (string (car buffering))))))
590 `(progn
591 (defun ,function (stream byte)
592 (output-wrapper (stream ,size ,buffering ,restart)
593 ,@body))
594 (setf *output-routines*
595 (nconc *output-routines*
596 ',(mapcar
597 (lambda (type)
598 (list type
599 (car buffering)
600 function
601 size
602 nil))
603 (cdr buffering)))))))
604 bufferings)))
606 ;;; FIXME: is this used anywhere any more?
607 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
610 (:none character)
611 (:line character)
612 (:full character))
613 (if (eql byte #\Newline)
614 (setf (fd-stream-char-pos stream) 0)
615 (incf (fd-stream-char-pos stream)))
616 (setf (sap-ref-8 (buffer-sap obuf) tail)
617 (char-code byte)))
619 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
622 (:none (unsigned-byte 8))
623 (:full (unsigned-byte 8)))
624 (setf (sap-ref-8 (buffer-sap obuf) tail)
625 byte))
627 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
630 (:none (signed-byte 8))
631 (:full (signed-byte 8)))
632 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
633 byte))
635 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
638 (:none (unsigned-byte 16))
639 (:full (unsigned-byte 16)))
640 (setf (sap-ref-16 (buffer-sap obuf) tail)
641 byte))
643 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
646 (:none (signed-byte 16))
647 (:full (signed-byte 16)))
648 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
649 byte))
651 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
654 (:none (unsigned-byte 32))
655 (:full (unsigned-byte 32)))
656 (setf (sap-ref-32 (buffer-sap obuf) tail)
657 byte))
659 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
662 (:none (signed-byte 32))
663 (:full (signed-byte 32)))
664 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
665 byte))
667 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
668 (progn
669 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
672 (:none (unsigned-byte 64))
673 (:full (unsigned-byte 64)))
674 (setf (sap-ref-64 (buffer-sap obuf) tail)
675 byte))
676 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
679 (:none (signed-byte 64))
680 (:full (signed-byte 64)))
681 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
682 byte)))
684 ;;; the routine to use to output a string. If the stream is
685 ;;; unbuffered, slam the string down the file descriptor, otherwise
686 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
687 ;;; checking to see where the last newline was.
688 (defun fd-sout (stream thing start end)
689 (declare (type fd-stream stream) (type string thing))
690 (let ((start (or start 0))
691 (end (or end (length (the vector thing)))))
692 (declare (fixnum start end))
693 (let ((last-newline
694 (string-dispatch (simple-base-string
695 #!+sb-unicode
696 (simple-array character (*))
697 string)
698 thing
699 (position #\newline thing :from-end t
700 :start start :end end))))
701 (if (and (typep thing 'base-string)
702 (eq (fd-stream-external-format stream) :latin-1))
703 (ecase (fd-stream-buffering stream)
704 (:full
705 (buffer-output stream thing start end))
706 (:line
707 (buffer-output stream thing start end)
708 (when last-newline
709 (flush-output-buffer stream)))
710 (:none
711 (write-or-buffer-output stream thing start end)))
712 (ecase (fd-stream-buffering stream)
713 (:full (funcall (fd-stream-output-bytes stream)
714 stream thing nil start end))
715 (:line (funcall (fd-stream-output-bytes stream)
716 stream thing last-newline start end))
717 (:none (funcall (fd-stream-output-bytes stream)
718 stream thing t start end))))
719 (if last-newline
720 (setf (fd-stream-char-pos stream) (- end last-newline 1))
721 (incf (fd-stream-char-pos stream) (- end start))))))
723 (defvar *external-formats* ()
724 #!+sb-doc
725 "List of all available external formats. Each element is a list of the
726 element-type, string input function name, character input function name,
727 and string output function name.")
729 (defun get-external-format (external-format)
730 (dolist (entry *external-formats*)
731 (when (member external-format (first entry))
732 (return entry))))
734 (defun get-external-format-function (external-format index)
735 (let ((entry (get-external-format external-format)))
736 (when entry (nth index entry))))
738 ;;; Find an output routine to use given the type and buffering. Return
739 ;;; as multiple values the routine, the real type transfered, and the
740 ;;; number of bytes per element.
741 (defun pick-output-routine (type buffering &optional external-format)
742 (when (subtypep type 'character)
743 (let ((entry (get-external-format external-format)))
744 (when entry
745 (return-from pick-output-routine
746 (values (symbol-function (nth (ecase buffering
747 (:none 4)
748 (:line 5)
749 (:full 6))
750 entry))
751 'character
753 (symbol-function (fourth entry))
754 (first (first entry)))))))
755 (dolist (entry *output-routines*)
756 (when (and (subtypep type (first entry))
757 (eq buffering (second entry))
758 (or (not (fifth entry))
759 (eq external-format (fifth entry))))
760 (return-from pick-output-routine
761 (values (symbol-function (third entry))
762 (first entry)
763 (fourth entry)))))
764 ;; KLUDGE: dealing with the buffering here leads to excessive code
765 ;; explosion.
767 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
768 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
769 if (subtypep type `(unsigned-byte ,i))
770 do (return-from pick-output-routine
771 (values
772 (ecase buffering
773 (:none
774 (lambda (stream byte)
775 (output-wrapper (stream (/ i 8) (:none) nil)
776 (loop for j from 0 below (/ i 8)
777 do (setf (sap-ref-8 (buffer-sap obuf)
778 (+ j tail))
779 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
780 (:full
781 (lambda (stream byte)
782 (output-wrapper (stream (/ i 8) (:full) nil)
783 (loop for j from 0 below (/ i 8)
784 do (setf (sap-ref-8 (buffer-sap obuf)
785 (+ j tail))
786 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
787 `(unsigned-byte ,i)
788 (/ i 8))))
789 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
790 if (subtypep type `(signed-byte ,i))
791 do (return-from pick-output-routine
792 (values
793 (ecase buffering
794 (:none
795 (lambda (stream byte)
796 (output-wrapper (stream (/ i 8) (:none) nil)
797 (loop for j from 0 below (/ i 8)
798 do (setf (sap-ref-8 (buffer-sap obuf)
799 (+ j tail))
800 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
801 (:full
802 (lambda (stream byte)
803 (output-wrapper (stream (/ i 8) (:full) nil)
804 (loop for j from 0 below (/ i 8)
805 do (setf (sap-ref-8 (buffer-sap obuf)
806 (+ j tail))
807 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
808 `(signed-byte ,i)
809 (/ i 8)))))
811 ;;;; input routines and related noise
813 ;;; a list of all available input routines. Each element is a list of
814 ;;; the element-type input, the function name, and the number of bytes
815 ;;; per element.
816 (defvar *input-routines* ())
818 ;;; Return whether a primitive partial read operation on STREAM's FD
819 ;;; would (probably) block. Signal a `simple-stream-error' if the
820 ;;; system call implementing this operation fails.
822 ;;; It is "may" instead of "would" because "would" is not quite
823 ;;; correct on win32. However, none of the places that use it require
824 ;;; further assurance than "may" versus "will definitely not".
825 (defun sysread-may-block-p (stream)
826 #!+win32
827 ;; This answers T at EOF on win32, I think.
828 (not (sb!win32:fd-listen (fd-stream-fd stream)))
829 #!-win32
830 (sb!unix:with-restarted-syscall (count errno)
831 (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
832 (sb!unix:fd-zero read-fds)
833 (sb!unix:fd-set (fd-stream-fd stream) read-fds)
834 (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
835 (sb!alien:addr read-fds)
836 nil nil 0 0))
837 (case count
838 ((1) nil)
839 ((0) t)
840 (otherwise
841 (simple-stream-perror "couldn't check whether ~S is readable"
842 stream
843 errno)))))
845 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
846 ;;; then fill the input buffer, and return the number of bytes read. Throws
847 ;;; to EOF-INPUT-CATCHER if the eof was reached.
848 (defun refill-input-buffer (stream)
849 (dx-let ((fd (fd-stream-fd stream))
850 (errno 0)
851 (count 0))
852 (tagbody
853 ;; Check for blocking input before touching the stream, as if
854 ;; we happen to wait we are liable to be interrupted, and the
855 ;; interrupt handler may use the same stream.
856 (if (sysread-may-block-p stream)
857 (go :wait-for-input)
858 (go :main))
859 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
860 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
861 :closed-flame
862 (closed-flame stream)
863 :read-error
864 (simple-stream-perror "couldn't read from ~S" stream errno)
865 :wait-for-input
866 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
867 ;; to wait for input if read tells us EWOULDBLOCK.
868 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
869 (signal-timeout 'io-timeout :stream stream :direction :read
870 :seconds (fd-stream-timeout stream)))
871 :main
872 ;; Since the read should not block, we'll disable the
873 ;; interrupts here, so that we don't accidentally unwind and
874 ;; leave the stream in an inconsistent state.
876 ;; Execute the nlx outside without-interrupts to ensure the
877 ;; resulting thunk is stack-allocatable.
878 ((lambda (return-reason)
879 (ecase return-reason
880 ((nil)) ; fast path normal cases
881 ((:wait-for-input) (go :wait-for-input))
882 ((:closed-flame) (go :closed-flame))
883 ((:read-error) (go :read-error))))
884 (without-interrupts
885 ;; Check the buffer: if it is null, then someone has closed
886 ;; the stream from underneath us. This is not ment to fix
887 ;; multithreaded races, but to deal with interrupt handlers
888 ;; closing the stream.
889 (block nil
890 (prog1 nil
891 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
892 (sap (buffer-sap ibuf))
893 (length (buffer-length ibuf))
894 (head (buffer-head ibuf))
895 (tail (buffer-tail ibuf)))
896 (declare (index length head tail)
897 (inline sb!unix:unix-read))
898 (unless (zerop head)
899 (cond ((eql head tail)
900 ;; Buffer is empty, but not at yet reset -- make it so.
901 (setf head 0
902 tail 0)
903 (reset-buffer ibuf))
905 ;; Buffer has things in it, but they are not at the
906 ;; head -- move them there.
907 (let ((n (- tail head)))
908 (system-area-ub8-copy sap head sap 0 n)
909 (setf head 0
910 (buffer-head ibuf) head
911 tail n
912 (buffer-tail ibuf) tail)))))
913 (setf (fd-stream-listen stream) nil)
914 (setf (values count errno)
915 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
916 (cond ((null count)
917 #!+win32
918 (return :read-error)
919 #!-win32
920 (if (eql errno sb!unix:ewouldblock)
921 (return :wait-for-input)
922 (return :read-error)))
923 ((zerop count)
924 (setf (fd-stream-listen stream) :eof)
925 (/show0 "THROWing EOF-INPUT-CATCHER")
926 (throw 'eof-input-catcher nil))
928 ;; Success! (Do not use INCF, for sake of other threads.)
929 (setf (buffer-tail ibuf) (+ count tail))))))))))
930 count))
932 ;;; Make sure there are at least BYTES number of bytes in the input
933 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
934 (defmacro input-at-least (stream bytes)
935 (let ((stream-var (gensym "STREAM"))
936 (bytes-var (gensym "BYTES"))
937 (buffer-var (gensym "IBUF")))
938 `(let* ((,stream-var ,stream)
939 (,bytes-var ,bytes)
940 (,buffer-var (fd-stream-ibuf ,stream-var)))
941 (loop
942 (when (>= (- (buffer-tail ,buffer-var)
943 (buffer-head ,buffer-var))
944 ,bytes-var)
945 (return))
946 (refill-input-buffer ,stream-var)))))
948 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
949 &body read-forms)
950 (let ((stream-var (gensym "STREAM"))
951 (retry-var (gensym "RETRY"))
952 (element-var (gensym "ELT")))
953 `(let* ((,stream-var ,stream)
954 (ibuf (fd-stream-ibuf ,stream-var))
955 (size nil))
956 (if (fd-stream-unread ,stream-var)
957 (prog1
958 (fd-stream-unread ,stream-var)
959 (setf (fd-stream-unread ,stream-var) nil)
960 (setf (fd-stream-listen ,stream-var) nil))
961 (let ((,element-var nil)
962 (decode-break-reason nil))
963 (do ((,retry-var t))
964 ((not ,retry-var))
965 (unless
966 (catch 'eof-input-catcher
967 (setf decode-break-reason
968 (block decode-break-reason
969 (input-at-least ,stream-var 1)
970 (let* ((byte (sap-ref-8 (buffer-sap ibuf)
971 (buffer-head ibuf))))
972 (declare (ignorable byte))
973 (setq size ,bytes)
974 (input-at-least ,stream-var size)
975 (setq ,element-var (locally ,@read-forms))
976 (setq ,retry-var nil))
977 nil))
978 (when decode-break-reason
979 (stream-decoding-error-and-handle stream
980 decode-break-reason))
982 (let ((octet-count (- (buffer-tail ibuf)
983 (buffer-head ibuf))))
984 (when (or (zerop octet-count)
985 (and (not ,element-var)
986 (not decode-break-reason)
987 (stream-decoding-error-and-handle
988 stream octet-count)))
989 (setq ,retry-var nil)))))
990 (cond (,element-var
991 (incf (buffer-head ibuf) size)
992 ,element-var)
994 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
996 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
997 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
998 (let ((stream-var (gensym "STREAM"))
999 (element-var (gensym "ELT")))
1000 `(let* ((,stream-var ,stream)
1001 (ibuf (fd-stream-ibuf ,stream-var)))
1002 (if (fd-stream-unread ,stream-var)
1003 (prog1
1004 (fd-stream-unread ,stream-var)
1005 (setf (fd-stream-unread ,stream-var) nil)
1006 (setf (fd-stream-listen ,stream-var) nil))
1007 (let ((,element-var
1008 (catch 'eof-input-catcher
1009 (input-at-least ,stream-var ,bytes)
1010 (locally ,@read-forms))))
1011 (cond (,element-var
1012 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1013 ,element-var)
1015 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1017 (defmacro def-input-routine/variable-width (name
1018 (type external-format size sap head)
1019 &rest body)
1020 `(progn
1021 (defun ,name (stream eof-error eof-value)
1022 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1023 (let ((,sap (buffer-sap ibuf))
1024 (,head (buffer-head ibuf)))
1025 ,@body)))
1026 (setf *input-routines*
1027 (nconc *input-routines*
1028 (list (list ',type ',name 1 ',external-format))))))
1030 (defmacro def-input-routine (name
1031 (type size sap head)
1032 &rest body)
1033 `(progn
1034 (defun ,name (stream eof-error eof-value)
1035 (input-wrapper (stream ,size eof-error eof-value)
1036 (let ((,sap (buffer-sap ibuf))
1037 (,head (buffer-head ibuf)))
1038 ,@body)))
1039 (setf *input-routines*
1040 (nconc *input-routines*
1041 (list (list ',type ',name ',size nil))))))
1043 ;;; STREAM-IN routine for reading a string char
1044 (def-input-routine input-character
1045 (character 1 sap head)
1046 (code-char (sap-ref-8 sap head)))
1048 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1049 (def-input-routine input-unsigned-8bit-byte
1050 ((unsigned-byte 8) 1 sap head)
1051 (sap-ref-8 sap head))
1053 ;;; STREAM-IN routine for reading a signed 8 bit number
1054 (def-input-routine input-signed-8bit-number
1055 ((signed-byte 8) 1 sap head)
1056 (signed-sap-ref-8 sap head))
1058 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1059 (def-input-routine input-unsigned-16bit-byte
1060 ((unsigned-byte 16) 2 sap head)
1061 (sap-ref-16 sap head))
1063 ;;; STREAM-IN routine for reading a signed 16 bit number
1064 (def-input-routine input-signed-16bit-byte
1065 ((signed-byte 16) 2 sap head)
1066 (signed-sap-ref-16 sap head))
1068 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1069 (def-input-routine input-unsigned-32bit-byte
1070 ((unsigned-byte 32) 4 sap head)
1071 (sap-ref-32 sap head))
1073 ;;; STREAM-IN routine for reading a signed 32 bit number
1074 (def-input-routine input-signed-32bit-byte
1075 ((signed-byte 32) 4 sap head)
1076 (signed-sap-ref-32 sap head))
1078 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1079 (progn
1080 (def-input-routine input-unsigned-64bit-byte
1081 ((unsigned-byte 64) 8 sap head)
1082 (sap-ref-64 sap head))
1083 (def-input-routine input-signed-64bit-byte
1084 ((signed-byte 64) 8 sap head)
1085 (signed-sap-ref-64 sap head)))
1087 ;;; Find an input routine to use given the type. Return as multiple
1088 ;;; values the routine, the real type transfered, and the number of
1089 ;;; bytes per element (and for character types string input routine).
1090 (defun pick-input-routine (type &optional external-format)
1091 (when (subtypep type 'character)
1092 (dolist (entry *external-formats*)
1093 (when (member external-format (first entry))
1094 (return-from pick-input-routine
1095 (values (symbol-function (third entry))
1096 'character
1098 (symbol-function (second entry))
1099 (first (first entry)))))))
1100 (dolist (entry *input-routines*)
1101 (when (and (subtypep type (first entry))
1102 (or (not (fourth entry))
1103 (eq external-format (fourth entry))))
1104 (return-from pick-input-routine
1105 (values (symbol-function (second entry))
1106 (first entry)
1107 (third entry)))))
1108 ;; FIXME: let's do it the hard way, then (but ignore things like
1109 ;; endianness, efficiency, and the necessary coupling between these
1110 ;; and the output routines). -- CSR, 2004-02-09
1111 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1112 if (subtypep type `(unsigned-byte ,i))
1113 do (return-from pick-input-routine
1114 (values
1115 (lambda (stream eof-error eof-value)
1116 (input-wrapper (stream (/ i 8) eof-error eof-value)
1117 (let ((sap (buffer-sap ibuf))
1118 (head (buffer-head ibuf)))
1119 (loop for j from 0 below (/ i 8)
1120 with result = 0
1121 do (setf result
1122 (+ (* 256 result)
1123 (sap-ref-8 sap (+ head j))))
1124 finally (return result)))))
1125 `(unsigned-byte ,i)
1126 (/ i 8))))
1127 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1128 if (subtypep type `(signed-byte ,i))
1129 do (return-from pick-input-routine
1130 (values
1131 (lambda (stream eof-error eof-value)
1132 (input-wrapper (stream (/ i 8) eof-error eof-value)
1133 (let ((sap (buffer-sap ibuf))
1134 (head (buffer-head ibuf)))
1135 (loop for j from 0 below (/ i 8)
1136 with result = 0
1137 do (setf result
1138 (+ (* 256 result)
1139 (sap-ref-8 sap (+ head j))))
1140 finally (return (if (logbitp (1- i) result)
1141 (dpb result (byte i 0) -1)
1142 result))))))
1143 `(signed-byte ,i)
1144 (/ i 8)))))
1146 ;;; the N-BIN method for FD-STREAMs
1148 ;;; Note that this blocks in UNIX-READ. It is generally used where
1149 ;;; there is a definite amount of reading to be done, so blocking
1150 ;;; isn't too problematical.
1151 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1152 &aux (total-copied 0))
1153 (declare (type fd-stream stream))
1154 (declare (type index start requested total-copied))
1155 (let ((unread (fd-stream-unread stream)))
1156 (when unread
1157 ;; AVERs designed to fail when we have more complicated
1158 ;; character representations.
1159 (aver (typep unread 'base-char))
1160 (aver (= (fd-stream-element-size stream) 1))
1161 ;; KLUDGE: this is a slightly-unrolled-and-inlined version of
1162 ;; %BYTE-BLT
1163 (etypecase buffer
1164 (system-area-pointer
1165 (setf (sap-ref-8 buffer start) (char-code unread)))
1166 ((simple-unboxed-array (*))
1167 (setf (aref buffer start) unread)))
1168 (setf (fd-stream-unread stream) nil)
1169 (setf (fd-stream-listen stream) nil)
1170 (incf total-copied)))
1171 (do ()
1172 (nil)
1173 (let* ((remaining-request (- requested total-copied))
1174 (ibuf (fd-stream-ibuf stream))
1175 (head (buffer-head ibuf))
1176 (tail (buffer-tail ibuf))
1177 (available (- tail head))
1178 (n-this-copy (min remaining-request available))
1179 (this-start (+ start total-copied))
1180 (this-end (+ this-start n-this-copy))
1181 (sap (buffer-sap ibuf)))
1182 (declare (type index remaining-request head tail available))
1183 (declare (type index n-this-copy))
1184 ;; Copy data from stream buffer into user's buffer.
1185 (%byte-blt sap head buffer this-start this-end)
1186 (incf (buffer-head ibuf) n-this-copy)
1187 (incf total-copied n-this-copy)
1188 ;; Maybe we need to refill the stream buffer.
1189 (cond (;; If there were enough data in the stream buffer, we're done.
1190 (eql total-copied requested)
1191 (return total-copied))
1192 (;; If EOF, we're done in another way.
1193 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1194 (if eof-error-p
1195 (error 'end-of-file :stream stream)
1196 (return total-copied)))
1197 ;; Otherwise we refilled the stream buffer, so fall
1198 ;; through into another pass of the loop.
1199 ))))
1201 (defun fd-stream-resync (stream)
1202 (dolist (entry *external-formats*)
1203 (when (member (fd-stream-external-format stream) (first entry))
1204 (return-from fd-stream-resync
1205 (funcall (symbol-function (eighth entry)) stream)))))
1207 (defun get-fd-stream-character-sizer (stream)
1208 (dolist (entry *external-formats*)
1209 (when (member (fd-stream-external-format stream) (first entry))
1210 (return-from get-fd-stream-character-sizer (ninth entry)))))
1212 (defun fd-stream-character-size (stream char)
1213 (let ((sizer (get-fd-stream-character-sizer stream)))
1214 (when sizer (funcall sizer char))))
1216 (defun fd-stream-string-size (stream string)
1217 (let ((sizer (get-fd-stream-character-sizer stream)))
1218 (when sizer
1219 (loop for char across string summing (funcall sizer char)))))
1221 (defun find-external-format (external-format)
1222 (when external-format
1223 (find external-format *external-formats* :test #'member :key #'car)))
1225 (defun variable-width-external-format-p (ef-entry)
1226 (when (eighth ef-entry) t))
1228 (defun bytes-for-char-fun (ef-entry)
1229 (if ef-entry (symbol-function (ninth ef-entry)) (constantly 1)))
1231 ;;; FIXME: OAOOM here vrt. *EXTERNAL-FORMAT-FUNCTIONS* in fd-stream.lisp
1232 (defmacro define-external-format (external-format size output-restart
1233 out-expr in-expr)
1234 (let* ((name (first external-format))
1235 (out-function (symbolicate "OUTPUT-BYTES/" name))
1236 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1237 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1238 (in-char-function (symbolicate "INPUT-CHAR/" name))
1239 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1240 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1241 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1242 (n-buffer (gensym "BUFFER")))
1243 `(progn
1244 (defun ,size-function (byte)
1245 (declare (ignore byte))
1246 ,size)
1247 (defun ,out-function (stream string flush-p start end)
1248 (let ((start (or start 0))
1249 (end (or end (length string))))
1250 (declare (type index start end))
1251 (synchronize-stream-output stream)
1252 (unless (<= 0 start end (length string))
1253 (sequence-bounding-indices-bad-error string start end))
1254 (do ()
1255 ((= end start))
1256 (let ((obuf (fd-stream-obuf stream)))
1257 (setf (buffer-tail obuf)
1258 (string-dispatch (simple-base-string
1259 #!+sb-unicode
1260 (simple-array character (*))
1261 string)
1262 string
1263 (let ((sap (buffer-sap obuf))
1264 (len (buffer-length obuf))
1265 ;; FIXME: rename
1266 (tail (buffer-tail obuf)))
1267 (declare (type index tail)
1268 ;; STRING bounds have already been checked.
1269 (optimize (safety 0)))
1270 (loop
1271 (,@(if output-restart
1272 `(catch 'output-nothing)
1273 `(progn))
1274 (do* ()
1275 ((or (= start end) (< (- len tail) 4)))
1276 (let* ((byte (aref string start))
1277 (bits (char-code byte)))
1278 ,out-expr
1279 (incf tail ,size)
1280 (incf start)))
1281 ;; Exited from the loop normally
1282 (return tail))
1283 ;; Exited via CATCH. Skip the current character
1284 ;; and try the inner loop again.
1285 (incf start))))))
1286 (when (< start end)
1287 (flush-output-buffer stream)))
1288 (when flush-p
1289 (flush-output-buffer stream))))
1290 (def-output-routines (,format
1291 ,size
1292 ,output-restart
1293 (:none character)
1294 (:line character)
1295 (:full character))
1296 (if (eql byte #\Newline)
1297 (setf (fd-stream-char-pos stream) 0)
1298 (incf (fd-stream-char-pos stream)))
1299 (let* ((obuf (fd-stream-obuf stream))
1300 (bits (char-code byte))
1301 (sap (buffer-sap obuf))
1302 (tail (buffer-tail obuf)))
1303 ,out-expr))
1304 (defun ,in-function (stream buffer start requested eof-error-p
1305 &aux (index start) (end (+ start requested)))
1306 (declare (type fd-stream stream)
1307 (type index start requested index end)
1308 (type
1309 (simple-array character (#.+ansi-stream-in-buffer-length+))
1310 buffer))
1311 (let ((unread (fd-stream-unread stream)))
1312 (when unread
1313 (setf (aref buffer index) unread)
1314 (setf (fd-stream-unread stream) nil)
1315 (setf (fd-stream-listen stream) nil)
1316 (incf index)))
1317 (do ()
1318 (nil)
1319 (let* ((ibuf (fd-stream-ibuf stream))
1320 (head (buffer-head ibuf))
1321 (tail (buffer-tail ibuf))
1322 (sap (buffer-sap ibuf)))
1323 (declare (type index head tail)
1324 (type system-area-pointer sap))
1325 ;; Copy data from stream buffer into user's buffer.
1326 (dotimes (i (min (truncate (- tail head) ,size)
1327 (- end index)))
1328 (declare (optimize speed))
1329 (let* ((byte (sap-ref-8 sap head)))
1330 (setf (aref buffer index) ,in-expr)
1331 (incf index)
1332 (incf head ,size)))
1333 (setf (buffer-head ibuf) head)
1334 ;; Maybe we need to refill the stream buffer.
1335 (cond ( ;; If there was enough data in the stream buffer, we're done.
1336 (= index end)
1337 (return (- index start)))
1338 ( ;; If EOF, we're done in another way.
1339 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1340 (if eof-error-p
1341 (error 'end-of-file :stream stream)
1342 (return (- index start))))
1343 ;; Otherwise we refilled the stream buffer, so fall
1344 ;; through into another pass of the loop.
1345 ))))
1346 (def-input-routine ,in-char-function (character ,size sap head)
1347 (let ((byte (sap-ref-8 sap head)))
1348 ,in-expr))
1349 (defun ,read-c-string-function (sap element-type)
1350 (declare (type system-area-pointer sap)
1351 (type (member character base-char) element-type))
1352 (locally
1353 (declare (optimize (speed 3) (safety 0)))
1354 (let* ((stream ,name)
1355 (length
1356 (loop for head of-type index upfrom 0 by ,size
1357 for count of-type index upto (1- array-dimension-limit)
1358 for byte = (sap-ref-8 sap head)
1359 for char of-type character = ,in-expr
1360 until (zerop (char-code char))
1361 finally (return count)))
1362 ;; Inline the common cases
1363 (string (make-string length :element-type element-type)))
1364 (declare (ignorable stream)
1365 (type index length)
1366 (type simple-string string))
1367 (/show0 before-copy-loop)
1368 (loop for head of-type index upfrom 0 by ,size
1369 for index of-type index below length
1370 for byte = (sap-ref-8 sap head)
1371 for char of-type character = ,in-expr
1372 do (setf (aref string index) char))
1373 string))) ;; last loop rewrite to dotimes?
1374 (defun ,output-c-string-function (string)
1375 (declare (type simple-string string))
1376 (locally
1377 (declare (optimize (speed 3) (safety 0)))
1378 (let* ((length (length string))
1379 (,n-buffer (make-array (* (1+ length) ,size)
1380 :element-type '(unsigned-byte 8)))
1381 (tail 0)
1382 (stream ,name))
1383 (declare (type index length tail))
1384 (with-pinned-objects (,n-buffer)
1385 (let ((sap (vector-sap ,n-buffer)))
1386 (declare (system-area-pointer sap))
1387 (dotimes (i length)
1388 (let* ((byte (aref string i))
1389 (bits (char-code byte)))
1390 (declare (ignorable byte bits))
1391 ,out-expr)
1392 (incf tail ,size))
1393 (let* ((bits 0)
1394 (byte (code-char bits)))
1395 (declare (ignorable bits byte))
1396 ,out-expr)))
1397 ,n-buffer)))
1398 (setf *external-formats*
1399 (cons '(,external-format ,in-function ,in-char-function ,out-function
1400 ,@(mapcar #'(lambda (buffering)
1401 (intern (format nil format (string buffering))))
1402 '(:none :line :full))
1403 nil ; no resync-function
1404 ,size-function ,read-c-string-function ,output-c-string-function)
1405 *external-formats*)))))
1407 (defmacro define-external-format/variable-width
1408 (external-format output-restart out-size-expr
1409 out-expr in-size-expr in-expr)
1410 (let* ((name (first external-format))
1411 (out-function (symbolicate "OUTPUT-BYTES/" name))
1412 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1413 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1414 (in-char-function (symbolicate "INPUT-CHAR/" name))
1415 (resync-function (symbolicate "RESYNC/" name))
1416 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1417 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1418 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1419 (n-buffer (gensym "BUFFER")))
1420 `(progn
1421 (defun ,size-function (byte)
1422 (declare (ignorable byte))
1423 ,out-size-expr)
1424 (defun ,out-function (stream string flush-p start end)
1425 (let ((start (or start 0))
1426 (end (or end (length string))))
1427 (declare (type index start end))
1428 (synchronize-stream-output stream)
1429 (unless (<= 0 start end (length string))
1430 (sequence-bounding-indices-bad string start end))
1431 (do ()
1432 ((= end start))
1433 (let ((obuf (fd-stream-obuf stream)))
1434 (setf (buffer-tail obuf)
1435 (string-dispatch (simple-base-string
1436 #!+sb-unicode
1437 (simple-array character (*))
1438 string)
1439 string
1440 (let ((len (buffer-length obuf))
1441 (sap (buffer-sap obuf))
1442 ;; FIXME: Rename
1443 (tail (buffer-tail obuf)))
1444 (declare (type index tail)
1445 ;; STRING bounds have already been checked.
1446 (optimize (safety 0)))
1447 (loop
1448 (,@(if output-restart
1449 `(catch 'output-nothing)
1450 `(progn))
1451 (do* ()
1452 ((or (= start end) (< (- len tail) 4)))
1453 (let* ((byte (aref string start))
1454 (bits (char-code byte))
1455 (size ,out-size-expr))
1456 ,out-expr
1457 (incf tail size)
1458 (incf start)))
1459 ;; Exited from the loop normally
1460 (return tail))
1461 ;; Exited via CATCH. Skip the current character
1462 ;; and try the inner loop again.
1463 (incf start))))))
1464 (when (< start end)
1465 (flush-output-buffer stream)))
1466 (when flush-p
1467 (flush-output-buffer stream))))
1468 (def-output-routines/variable-width (,format
1469 ,out-size-expr
1470 ,output-restart
1471 ,external-format
1472 (:none character)
1473 (:line character)
1474 (:full character))
1475 (if (eql byte #\Newline)
1476 (setf (fd-stream-char-pos stream) 0)
1477 (incf (fd-stream-char-pos stream)))
1478 (let ((bits (char-code byte))
1479 (sap (buffer-sap obuf))
1480 (tail (buffer-tail obuf)))
1481 ,out-expr))
1482 (defun ,in-function (stream buffer start requested eof-error-p
1483 &aux (total-copied 0))
1484 (declare (type fd-stream stream)
1485 (type index start requested total-copied)
1486 (type
1487 (simple-array character (#.+ansi-stream-in-buffer-length+))
1488 buffer))
1489 (let ((unread (fd-stream-unread stream)))
1490 (when unread
1491 (setf (aref buffer start) unread)
1492 (setf (fd-stream-unread stream) nil)
1493 (setf (fd-stream-listen stream) nil)
1494 (incf total-copied)))
1495 (do ()
1496 (nil)
1497 (let* ((ibuf (fd-stream-ibuf stream))
1498 (head (buffer-head ibuf))
1499 (tail (buffer-tail ibuf))
1500 (sap (buffer-sap ibuf))
1501 (decode-break-reason nil))
1502 (declare (type index head tail))
1503 ;; Copy data from stream buffer into user's buffer.
1504 (do ((size nil nil))
1505 ((or (= tail head) (= requested total-copied)))
1506 (setf decode-break-reason
1507 (block decode-break-reason
1508 (let ((byte (sap-ref-8 sap head)))
1509 (declare (ignorable byte))
1510 (setq size ,in-size-expr)
1511 (when (> size (- tail head))
1512 (return))
1513 (setf (aref buffer (+ start total-copied)) ,in-expr)
1514 (incf total-copied)
1515 (incf head size))
1516 nil))
1517 (setf (buffer-head ibuf) head)
1518 (when decode-break-reason
1519 ;; If we've already read some characters on when the invalid
1520 ;; code sequence is detected, we return immediately. The
1521 ;; handling of the error is deferred until the next call
1522 ;; (where this check will be false). This allows establishing
1523 ;; high-level handlers for decode errors (for example
1524 ;; automatically resyncing in Lisp comments).
1525 (when (plusp total-copied)
1526 (return-from ,in-function total-copied))
1527 (when (stream-decoding-error-and-handle
1528 stream decode-break-reason)
1529 (if eof-error-p
1530 (error 'end-of-file :stream stream)
1531 (return-from ,in-function total-copied)))
1532 (setf head (buffer-head ibuf))
1533 (setf tail (buffer-tail ibuf))))
1534 (setf (buffer-head ibuf) head)
1535 ;; Maybe we need to refill the stream buffer.
1536 (cond ( ;; If there were enough data in the stream buffer, we're done.
1537 (= total-copied requested)
1538 (return total-copied))
1539 ( ;; If EOF, we're done in another way.
1540 (or (eq decode-break-reason 'eof)
1541 (null (catch 'eof-input-catcher
1542 (refill-input-buffer stream))))
1543 (if eof-error-p
1544 (error 'end-of-file :stream stream)
1545 (return total-copied)))
1546 ;; Otherwise we refilled the stream buffer, so fall
1547 ;; through into another pass of the loop.
1548 ))))
1549 (def-input-routine/variable-width ,in-char-function (character
1550 ,external-format
1551 ,in-size-expr
1552 sap head)
1553 (let ((byte (sap-ref-8 sap head)))
1554 (declare (ignorable byte))
1555 ,in-expr))
1556 (defun ,resync-function (stream)
1557 (let ((ibuf (fd-stream-ibuf stream)))
1558 (loop
1559 (input-at-least stream 2)
1560 (incf (buffer-head ibuf))
1561 (unless (block decode-break-reason
1562 (let* ((sap (buffer-sap ibuf))
1563 (head (buffer-head ibuf))
1564 (byte (sap-ref-8 sap head))
1565 (size ,in-size-expr))
1566 (declare (ignorable byte))
1567 (input-at-least stream size)
1568 (setf head (buffer-head ibuf))
1569 ,in-expr)
1570 nil)
1571 (return)))))
1572 (defun ,read-c-string-function (sap element-type)
1573 (declare (type system-area-pointer sap))
1574 (locally
1575 (declare (optimize (speed 3) (safety 0)))
1576 (let* ((stream ,name)
1577 (size 0) (head 0) (byte 0) (char nil)
1578 (decode-break-reason nil)
1579 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1580 (setf decode-break-reason
1581 (block decode-break-reason
1582 (setf byte (sap-ref-8 sap head)
1583 size ,in-size-expr
1584 char ,in-expr)
1585 (incf head size)
1586 nil))
1587 (when decode-break-reason
1588 (c-string-decoding-error ,name decode-break-reason))
1589 (when (zerop (char-code char))
1590 (return count))))
1591 (string (make-string length :element-type element-type)))
1592 (declare (ignorable stream)
1593 (type index head length) ;; size
1594 (type (unsigned-byte 8) byte)
1595 (type (or null character) char)
1596 (type string string))
1597 (setf head 0)
1598 (dotimes (index length string)
1599 (setf decode-break-reason
1600 (block decode-break-reason
1601 (setf byte (sap-ref-8 sap head)
1602 size ,in-size-expr
1603 char ,in-expr)
1604 (incf head size)
1605 nil))
1606 (when decode-break-reason
1607 (c-string-decoding-error ,name decode-break-reason))
1608 (setf (aref string index) char)))))
1610 (defun ,output-c-string-function (string)
1611 (declare (type simple-string string))
1612 (locally
1613 (declare (optimize (speed 3) (safety 0)))
1614 (let* ((length (length string))
1615 (char-length (make-array (1+ length) :element-type 'index))
1616 (buffer-length
1617 (+ (loop for i of-type index below length
1618 for byte of-type character = (aref string i)
1619 for bits = (char-code byte)
1620 sum (setf (aref char-length i)
1621 (the index ,out-size-expr)))
1622 (let* ((byte (code-char 0))
1623 (bits (char-code byte)))
1624 (declare (ignorable byte bits))
1625 (setf (aref char-length length)
1626 (the index ,out-size-expr)))))
1627 (tail 0)
1628 (,n-buffer (make-array buffer-length
1629 :element-type '(unsigned-byte 8)))
1630 stream)
1631 (declare (type index length buffer-length tail)
1632 (type null stream)
1633 (ignorable stream))
1634 (with-pinned-objects (,n-buffer)
1635 (let ((sap (vector-sap ,n-buffer)))
1636 (declare (system-area-pointer sap))
1637 (loop for i of-type index below length
1638 for byte of-type character = (aref string i)
1639 for bits = (char-code byte)
1640 for size of-type index = (aref char-length i)
1641 do (prog1
1642 ,out-expr
1643 (incf tail size)))
1644 (let* ((bits 0)
1645 (byte (code-char bits))
1646 (size (aref char-length length)))
1647 (declare (ignorable bits byte size))
1648 ,out-expr)))
1649 ,n-buffer)))
1651 (setf *external-formats*
1652 (cons '(,external-format ,in-function ,in-char-function ,out-function
1653 ,@(mapcar #'(lambda (buffering)
1654 (intern (format nil format (string buffering))))
1655 '(:none :line :full))
1656 ,resync-function
1657 ,size-function ,read-c-string-function ,output-c-string-function)
1658 *external-formats*)))))
1660 ;;; Multiple names for the :ISO{,-}8859-* families are needed because on
1661 ;;; FreeBSD (and maybe other BSD systems), nl_langinfo("LATIN-1") will
1662 ;;; return "ISO8859-1" instead of "ISO-8859-1".
1663 (define-external-format (:latin-1 :latin1 :iso-8859-1 :iso8859-1)
1665 (if (>= bits 256)
1666 (external-format-encoding-error stream bits)
1667 (setf (sap-ref-8 sap tail) bits))
1668 (code-char byte))
1670 (define-external-format (:ascii :us-ascii :ansi_x3.4-1968
1671 :iso-646 :iso-646-us :|646|)
1673 (if (>= bits 128)
1674 (external-format-encoding-error stream bits)
1675 (setf (sap-ref-8 sap tail) bits))
1676 (code-char byte))
1678 (let* ((table (let ((s (make-string 256)))
1679 (map-into s #'code-char
1680 '(#x00 #x01 #x02 #x03 #x9c #x09 #x86 #x7f #x97 #x8d #x8e #x0b #x0c #x0d #x0e #x0f
1681 #x10 #x11 #x12 #x13 #x9d #x85 #x08 #x87 #x18 #x19 #x92 #x8f #x1c #x1d #x1e #x1f
1682 #x80 #x81 #x82 #x83 #x84 #x0a #x17 #x1b #x88 #x89 #x8a #x8b #x8c #x05 #x06 #x07
1683 #x90 #x91 #x16 #x93 #x94 #x95 #x96 #x04 #x98 #x99 #x9a #x9b #x14 #x15 #x9e #x1a
1684 #x20 #xa0 #xe2 #xe4 #xe0 #xe1 #xe3 #xe5 #xe7 #xf1 #xa2 #x2e #x3c #x28 #x2b #x7c
1685 #x26 #xe9 #xea #xeb #xe8 #xed #xee #xef #xec #xdf #x21 #x24 #x2a #x29 #x3b #xac
1686 #x2d #x2f #xc2 #xc4 #xc0 #xc1 #xc3 #xc5 #xc7 #xd1 #xa6 #x2c #x25 #x5f #x3e #x3f
1687 #xf8 #xc9 #xca #xcb #xc8 #xcd #xce #xcf #xcc #x60 #x3a #x23 #x40 #x27 #x3d #x22
1688 #xd8 #x61 #x62 #x63 #x64 #x65 #x66 #x67 #x68 #x69 #xab #xbb #xf0 #xfd #xfe #xb1
1689 #xb0 #x6a #x6b #x6c #x6d #x6e #x6f #x70 #x71 #x72 #xaa #xba #xe6 #xb8 #xc6 #xa4
1690 #xb5 #x7e #x73 #x74 #x75 #x76 #x77 #x78 #x79 #x7a #xa1 #xbf #xd0 #xdd #xde #xae
1691 #x5e #xa3 #xa5 #xb7 #xa9 #xa7 #xb6 #xbc #xbd #xbe #x5b #x5d #xaf #xa8 #xb4 #xd7
1692 #x7b #x41 #x42 #x43 #x44 #x45 #x46 #x47 #x48 #x49 #xad #xf4 #xf6 #xf2 #xf3 #xf5
1693 #x7d #x4a #x4b #x4c #x4d #x4e #x4f #x50 #x51 #x52 #xb9 #xfb #xfc #xf9 #xfa #xff
1694 #x5c #xf7 #x53 #x54 #x55 #x56 #x57 #x58 #x59 #x5a #xb2 #xd4 #xd6 #xd2 #xd3 #xd5
1695 #x30 #x31 #x32 #x33 #x34 #x35 #x36 #x37 #x38 #x39 #xb3 #xdb #xdc #xd9 #xda #x9f))
1697 (reverse-table (let ((rt (make-array 256 :element-type '(unsigned-byte 8) :initial-element 0)))
1698 (loop for char across table for i from 0
1699 do (aver (= 0 (aref rt (char-code char))))
1700 do (setf (aref rt (char-code char)) i))
1701 rt)))
1702 (define-external-format (:ebcdic-us :ibm-037 :ibm037)
1704 (if (>= bits 256)
1705 (external-format-encoding-error stream bits)
1706 (setf (sap-ref-8 sap tail) (aref reverse-table bits)))
1707 (aref table byte)))
1710 #!+sb-unicode
1711 (let ((latin-9-table (let ((table (make-string 256)))
1712 (do ((i 0 (1+ i)))
1713 ((= i 256))
1714 (setf (aref table i) (code-char i)))
1715 (setf (aref table #xa4) (code-char #x20ac))
1716 (setf (aref table #xa6) (code-char #x0160))
1717 (setf (aref table #xa8) (code-char #x0161))
1718 (setf (aref table #xb4) (code-char #x017d))
1719 (setf (aref table #xb8) (code-char #x017e))
1720 (setf (aref table #xbc) (code-char #x0152))
1721 (setf (aref table #xbd) (code-char #x0153))
1722 (setf (aref table #xbe) (code-char #x0178))
1723 table))
1724 (latin-9-reverse-1 (make-array 16
1725 :element-type '(unsigned-byte 21)
1726 :initial-contents '(#x0160 #x0161 #x0152 #x0153 0 0 0 0 #x0178 0 0 0 #x20ac #x017d #x017e 0)))
1727 (latin-9-reverse-2 (make-array 16
1728 :element-type '(unsigned-byte 8)
1729 :initial-contents '(#xa6 #xa8 #xbc #xbd 0 0 0 0 #xbe 0 0 0 #xa4 #xb4 #xb8 0))))
1730 (define-external-format (:latin-9 :latin9 :iso-8859-15 :iso8859-15)
1732 (setf (sap-ref-8 sap tail)
1733 (if (< bits 256)
1734 (if (= bits (char-code (aref latin-9-table bits)))
1735 bits
1736 (external-format-encoding-error stream byte))
1737 (if (= (aref latin-9-reverse-1 (logand bits 15)) bits)
1738 (aref latin-9-reverse-2 (logand bits 15))
1739 (external-format-encoding-error stream byte))))
1740 (aref latin-9-table byte)))
1742 (define-external-format/variable-width (:utf-8 :utf8) nil
1743 (let ((bits (char-code byte)))
1744 (cond ((< bits #x80) 1)
1745 ((< bits #x800) 2)
1746 ((< bits #x10000) 3)
1747 (t 4)))
1748 (ecase size
1749 (1 (setf (sap-ref-8 sap tail) bits))
1750 (2 (setf (sap-ref-8 sap tail) (logior #xc0 (ldb (byte 5 6) bits))
1751 (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1752 (3 (setf (sap-ref-8 sap tail) (logior #xe0 (ldb (byte 4 12) bits))
1753 (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 6) bits))
1754 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 0) bits))))
1755 (4 (setf (sap-ref-8 sap tail) (logior #xf0 (ldb (byte 3 18) bits))
1756 (sap-ref-8 sap (+ 1 tail)) (logior #x80 (ldb (byte 6 12) bits))
1757 (sap-ref-8 sap (+ 2 tail)) (logior #x80 (ldb (byte 6 6) bits))
1758 (sap-ref-8 sap (+ 3 tail)) (logior #x80 (ldb (byte 6 0) bits)))))
1759 (cond ((< byte #x80) 1)
1760 ((< byte #xc2) (return-from decode-break-reason 1))
1761 ((< byte #xe0) 2)
1762 ((< byte #xf0) 3)
1763 (t 4))
1764 (code-char (ecase size
1765 (1 byte)
1766 (2 (let ((byte2 (sap-ref-8 sap (1+ head))))
1767 (unless (<= #x80 byte2 #xbf)
1768 (return-from decode-break-reason 2))
1769 (dpb byte (byte 5 6) byte2)))
1770 (3 (let ((byte2 (sap-ref-8 sap (1+ head)))
1771 (byte3 (sap-ref-8 sap (+ 2 head))))
1772 (unless (and (<= #x80 byte2 #xbf)
1773 (<= #x80 byte3 #xbf))
1774 (return-from decode-break-reason 3))
1775 (dpb byte (byte 4 12) (dpb byte2 (byte 6 6) byte3))))
1776 (4 (let ((byte2 (sap-ref-8 sap (1+ head)))
1777 (byte3 (sap-ref-8 sap (+ 2 head)))
1778 (byte4 (sap-ref-8 sap (+ 3 head))))
1779 (unless (and (<= #x80 byte2 #xbf)
1780 (<= #x80 byte3 #xbf)
1781 (<= #x80 byte4 #xbf))
1782 (return-from decode-break-reason 4))
1783 (dpb byte (byte 3 18)
1784 (dpb byte2 (byte 6 12)
1785 (dpb byte3 (byte 6 6) byte4))))))))
1787 ;;;; utility functions (misc routines, etc)
1789 ;;; Fill in the various routine slots for the given type. INPUT-P and
1790 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1791 ;;; set prior to calling this routine.
1792 (defun set-fd-stream-routines (fd-stream element-type external-format
1793 input-p output-p buffer-p)
1794 (let* ((target-type (case element-type
1795 (unsigned-byte '(unsigned-byte 8))
1796 (signed-byte '(signed-byte 8))
1797 (:default 'character)
1798 (t element-type)))
1799 (character-stream-p (subtypep target-type 'character))
1800 (bivalent-stream-p (eq element-type :default))
1801 normalized-external-format
1802 (bin-routine #'ill-bin)
1803 (bin-type nil)
1804 (bin-size nil)
1805 (cin-routine #'ill-in)
1806 (cin-type nil)
1807 (cin-size nil)
1808 (input-type nil) ;calculated from bin-type/cin-type
1809 (input-size nil) ;calculated from bin-size/cin-size
1810 (read-n-characters #'ill-in)
1811 (bout-routine #'ill-bout)
1812 (bout-type nil)
1813 (bout-size nil)
1814 (cout-routine #'ill-out)
1815 (cout-type nil)
1816 (cout-size nil)
1817 (output-type nil)
1818 (output-size nil)
1819 (output-bytes #'ill-bout))
1821 ;; Ensure that we have buffers in the desired direction(s) only,
1822 ;; getting new ones and dropping/resetting old ones as necessary.
1823 (let ((obuf (fd-stream-obuf fd-stream)))
1824 (if output-p
1825 (if obuf
1826 (reset-buffer obuf)
1827 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1828 (when obuf
1829 (setf (fd-stream-obuf fd-stream) nil)
1830 (release-buffer obuf))))
1832 (let ((ibuf (fd-stream-ibuf fd-stream)))
1833 (if input-p
1834 (if ibuf
1835 (reset-buffer ibuf)
1836 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1837 (when ibuf
1838 (setf (fd-stream-ibuf fd-stream) nil)
1839 (release-buffer ibuf))))
1841 ;; FIXME: Why only for output? Why unconditionally?
1842 (when output-p
1843 (setf (fd-stream-char-pos fd-stream) 0))
1845 (when (and character-stream-p
1846 (eq external-format :default))
1847 (/show0 "/getting default external format")
1848 (setf external-format (default-external-format)))
1850 (when input-p
1851 (when (or (not character-stream-p) bivalent-stream-p)
1852 (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1853 normalized-external-format)
1854 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1855 target-type)
1856 external-format))
1857 (unless bin-routine
1858 (error "could not find any input routine for ~S" target-type)))
1859 (when character-stream-p
1860 (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1861 normalized-external-format)
1862 (pick-input-routine target-type external-format))
1863 (unless cin-routine
1864 (error "could not find any input routine for ~S" target-type)))
1865 (setf (fd-stream-in fd-stream) cin-routine
1866 (fd-stream-bin fd-stream) bin-routine)
1867 ;; character type gets preferential treatment
1868 (setf input-size (or cin-size bin-size))
1869 (setf input-type (or cin-type bin-type))
1870 (when normalized-external-format
1871 (setf (fd-stream-external-format fd-stream)
1872 normalized-external-format))
1873 (when (= (or cin-size 1) (or bin-size 1) 1)
1874 (setf (fd-stream-n-bin fd-stream) ;XXX
1875 (if (and character-stream-p (not bivalent-stream-p))
1876 read-n-characters
1877 #'fd-stream-read-n-bytes))
1878 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1879 ;; for character and (unsigned-byte 8) streams. In these
1880 ;; cases, fast-read-* will read from the
1881 ;; ansi-stream-(c)in-buffer, saving function calls.
1882 ;; Otherwise, the various data-reading functions in the stream
1883 ;; structure will be called.
1884 (when (and buffer-p
1885 (not bivalent-stream-p)
1886 ;; temporary disable on :io streams
1887 (not output-p))
1888 (cond (character-stream-p
1889 (setf (ansi-stream-cin-buffer fd-stream)
1890 (make-array +ansi-stream-in-buffer-length+
1891 :element-type 'character)))
1892 ((equal target-type '(unsigned-byte 8))
1893 (setf (ansi-stream-in-buffer fd-stream)
1894 (make-array +ansi-stream-in-buffer-length+
1895 :element-type '(unsigned-byte 8))))))))
1897 (when output-p
1898 (when (or (not character-stream-p) bivalent-stream-p)
1899 (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1900 normalized-external-format)
1901 (pick-output-routine (if bivalent-stream-p
1902 '(unsigned-byte 8)
1903 target-type)
1904 (fd-stream-buffering fd-stream)
1905 external-format))
1906 (unless bout-routine
1907 (error "could not find any output routine for ~S buffered ~S"
1908 (fd-stream-buffering fd-stream)
1909 target-type)))
1910 (when character-stream-p
1911 (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1912 normalized-external-format)
1913 (pick-output-routine target-type
1914 (fd-stream-buffering fd-stream)
1915 external-format))
1916 (unless cout-routine
1917 (error "could not find any output routine for ~S buffered ~S"
1918 (fd-stream-buffering fd-stream)
1919 target-type)))
1920 (when normalized-external-format
1921 (setf (fd-stream-external-format fd-stream)
1922 normalized-external-format))
1923 (when character-stream-p
1924 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1925 (setf (fd-stream-out fd-stream) cout-routine
1926 (fd-stream-bout fd-stream) bout-routine
1927 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1928 #'fd-sout #'ill-out))
1929 (setf output-size (or cout-size bout-size))
1930 (setf output-type (or cout-type bout-type)))
1932 (when (and input-size output-size
1933 (not (eq input-size output-size)))
1934 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1935 input-type input-size
1936 output-type output-size))
1937 (setf (fd-stream-element-size fd-stream)
1938 (or input-size output-size))
1940 (setf (fd-stream-element-type fd-stream)
1941 (cond ((equal input-type output-type)
1942 input-type)
1943 ((null output-type)
1944 input-type)
1945 ((null input-type)
1946 output-type)
1947 ((subtypep input-type output-type)
1948 input-type)
1949 ((subtypep output-type input-type)
1950 output-type)
1952 (error "Input type (~S) and output type (~S) are unrelated?"
1953 input-type
1954 output-type))))))
1956 ;;; Handles the resource-release aspects of stream closing, and marks
1957 ;;; it as closed.
1958 (defun release-fd-stream-resources (fd-stream)
1959 (handler-case
1960 (without-interrupts
1961 ;; Drop handlers first.
1962 (when (fd-stream-handler fd-stream)
1963 (remove-fd-handler (fd-stream-handler fd-stream))
1964 (setf (fd-stream-handler fd-stream) nil))
1965 ;; Disable interrupts so that a asynch unwind will not leave
1966 ;; us with a dangling finalizer (that would close the same
1967 ;; --possibly reassigned-- FD again), or a stream with a closed
1968 ;; FD that appears open.
1969 (sb!unix:unix-close (fd-stream-fd fd-stream))
1970 (set-closed-flame fd-stream)
1971 (when (fboundp 'cancel-finalization)
1972 (cancel-finalization fd-stream)))
1973 ;; On error unwind from WITHOUT-INTERRUPTS.
1974 (serious-condition (e)
1975 (error e)))
1976 ;; Release all buffers. If this is undone, or interrupted,
1977 ;; we're still safe: buffers have finalizers of their own.
1978 (release-fd-stream-buffers fd-stream))
1980 ;;; Flushes the current input buffer and unread chatacter, and returns
1981 ;;; the input buffer, and the amount of of flushed input in bytes.
1982 (defun flush-input-buffer (stream)
1983 (let ((unread (if (fd-stream-unread stream)
1985 0)))
1986 (setf (fd-stream-unread stream) nil)
1987 (let ((ibuf (fd-stream-ibuf stream)))
1988 (if ibuf
1989 (let ((head (buffer-head ibuf))
1990 (tail (buffer-tail ibuf)))
1991 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1992 (values nil unread)))))
1994 (defun fd-stream-clear-input (stream)
1995 (flush-input-buffer stream)
1996 #!+win32
1997 (progn
1998 (sb!win32:fd-clear-input (fd-stream-fd stream))
1999 (setf (fd-stream-listen stream) nil))
2000 #!-win32
2001 (catch 'eof-input-catcher
2002 (loop until (sysread-may-block-p stream)
2004 (refill-input-buffer stream)
2005 (reset-buffer (fd-stream-ibuf stream)))
2008 ;;; Handle miscellaneous operations on FD-STREAM.
2009 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
2010 (declare (ignore arg2))
2011 (case operation
2012 (:listen
2013 (labels ((do-listen ()
2014 (let ((ibuf (fd-stream-ibuf fd-stream)))
2015 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
2016 (fd-stream-listen fd-stream)
2017 #!+win32
2018 (sb!win32:fd-listen (fd-stream-fd fd-stream))
2019 #!-win32
2020 ;; If the read can block, LISTEN will certainly return NIL.
2021 (if (sysread-may-block-p fd-stream)
2023 ;; Otherwise select(2) and CL:LISTEN have slightly
2024 ;; different semantics. The former returns that an FD
2025 ;; is readable when a read operation wouldn't block.
2026 ;; That includes EOF. However, LISTEN must return NIL
2027 ;; at EOF.
2028 (progn (catch 'eof-input-catcher
2029 ;; r-b/f too calls select, but it shouldn't
2030 ;; block as long as read can return once w/o
2031 ;; blocking
2032 (refill-input-buffer fd-stream))
2033 ;; At this point either IBUF-HEAD != IBUF-TAIL
2034 ;; and FD-STREAM-LISTEN is NIL, in which case
2035 ;; we should return T, or IBUF-HEAD ==
2036 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
2037 ;; which case we should return :EOF for this
2038 ;; call and all future LISTEN call on this stream.
2039 ;; Call ourselves again to determine which case
2040 ;; applies.
2041 (do-listen)))))))
2042 (do-listen)))
2043 (:unread
2044 (setf (fd-stream-unread fd-stream) arg1)
2045 (setf (fd-stream-listen fd-stream) t))
2046 (:close
2047 ;; Drop input buffers
2048 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
2049 (ansi-stream-cin-buffer fd-stream) nil
2050 (ansi-stream-in-buffer fd-stream) nil)
2051 (cond (arg1
2052 ;; We got us an abort on our hands.
2053 (let ((outputp (fd-stream-obuf fd-stream))
2054 (file (fd-stream-file fd-stream))
2055 (orig (fd-stream-original fd-stream)))
2056 ;; This takes care of the important stuff -- everything
2057 ;; rest is cleaning up the file-system, which we cannot
2058 ;; do on some platforms as long as the file is open.
2059 (release-fd-stream-resources fd-stream)
2060 ;; We can't do anything unless we know what file were
2061 ;; dealing with, and we don't want to do anything
2062 ;; strange unless we were writing to the file.
2063 (when (and outputp file)
2064 (if orig
2065 ;; If the original is EQ to file we are appending to
2066 ;; and can just close the file without renaming.
2067 (unless (eq orig file)
2068 ;; We have a handle on the original, just revert.
2069 (multiple-value-bind (okay err)
2070 (sb!unix:unix-rename orig file)
2071 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
2072 ;; others are SIMPLE-FILE-ERRORS? Surely they should
2073 ;; all be the same?
2074 (unless okay
2075 (error 'simple-stream-error
2076 :format-control
2077 "~@<Couldn't restore ~S to its original contents ~
2078 from ~S while closing ~S: ~2I~_~A~:>"
2079 :format-arguments
2080 (list file orig fd-stream (strerror err))
2081 :stream fd-stream))))
2082 ;; We can't restore the original, and aren't
2083 ;; appending, so nuke that puppy.
2085 ;; FIXME: This is currently the fate of superseded
2086 ;; files, and according to the CLOSE spec this is
2087 ;; wrong. However, there seems to be no clean way to
2088 ;; do that that doesn't involve either copying the
2089 ;; data (bad if the :abort resulted from a full
2090 ;; disk), or renaming the old file temporarily
2091 ;; (probably bad because stream opening becomes more
2092 ;; racy).
2093 (multiple-value-bind (okay err)
2094 (sb!unix:unix-unlink file)
2095 (unless okay
2096 (error 'simple-file-error
2097 :pathname file
2098 :format-control
2099 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2100 :format-arguments
2101 (list file fd-stream (strerror err)))))))))
2103 (finish-fd-stream-output fd-stream)
2104 (let ((orig (fd-stream-original fd-stream)))
2105 (when (and orig (fd-stream-delete-original fd-stream))
2106 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2107 (unless okay
2108 (error 'simple-file-error
2109 :pathname orig
2110 :format-control
2111 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2112 :format-arguments
2113 (list orig fd-stream (strerror err)))))))
2114 ;; In case of no-abort close, don't *really* close the
2115 ;; stream until the last moment -- the cleaning up of the
2116 ;; original can be done first.
2117 (release-fd-stream-resources fd-stream))))
2118 (:clear-input
2119 (fd-stream-clear-input fd-stream))
2120 (:force-output
2121 (flush-output-buffer fd-stream))
2122 (:finish-output
2123 (finish-fd-stream-output fd-stream))
2124 (:element-type
2125 (fd-stream-element-type fd-stream))
2126 (:external-format
2127 (fd-stream-external-format fd-stream))
2128 (:interactive-p
2129 (= 1 (the (member 0 1)
2130 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2131 (:line-length
2133 (:charpos
2134 (fd-stream-char-pos fd-stream))
2135 (:file-length
2136 (unless (fd-stream-file fd-stream)
2137 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2138 ;; "should signal an error of type TYPE-ERROR if stream is not
2139 ;; a stream associated with a file". Too bad there's no very
2140 ;; appropriate value for the EXPECTED-TYPE slot..
2141 (error 'simple-type-error
2142 :datum fd-stream
2143 :expected-type 'fd-stream
2144 :format-control "~S is not a stream associated with a file."
2145 :format-arguments (list fd-stream)))
2146 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2147 atime mtime ctime blksize blocks)
2148 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2149 (declare (ignore ino nlink uid gid rdev
2150 atime mtime ctime blksize blocks))
2151 (unless okay
2152 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2153 (if (zerop mode)
2155 (truncate size (fd-stream-element-size fd-stream)))))
2156 (:file-string-length
2157 (etypecase arg1
2158 (character (fd-stream-character-size fd-stream arg1))
2159 (string (fd-stream-string-size fd-stream arg1))))
2160 (:file-position
2161 (if arg1
2162 (fd-stream-set-file-position fd-stream arg1)
2163 (fd-stream-get-file-position fd-stream)))))
2165 ;; FIXME: Think about this.
2167 ;; (defun finish-fd-stream-output (fd-stream)
2168 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2169 ;; (loop while (fd-stream-output-queue fd-stream)
2170 ;; ;; FIXME: SIGINT while waiting for a timeout will
2171 ;; ;; cause a timeout here.
2172 ;; do (when (and (not (serve-event timeout)) timeout)
2173 ;; (signal-timeout 'io-timeout
2174 ;; :stream fd-stream
2175 ;; :direction :write
2176 ;; :seconds timeout)))))
2178 (defun finish-fd-stream-output (stream)
2179 (flush-output-buffer stream)
2180 (do ()
2181 ((null (fd-stream-output-queue stream)))
2182 (serve-all-events)))
2184 (defun fd-stream-get-file-position (stream)
2185 (declare (fd-stream stream))
2186 (without-interrupts
2187 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2188 (declare (type (or (alien sb!unix:off-t) null) posn))
2189 ;; We used to return NIL for errno==ESPIPE, and signal an error
2190 ;; in other failure cases. However, CLHS says to return NIL if
2191 ;; the position cannot be determined -- so that's what we do.
2192 (when (integerp posn)
2193 ;; Adjust for buffered output: If there is any output
2194 ;; buffered, the *real* file position will be larger
2195 ;; than reported by lseek() because lseek() obviously
2196 ;; cannot take into account output we have not sent
2197 ;; yet.
2198 (dolist (buffer (fd-stream-output-queue stream))
2199 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2200 (let ((obuf (fd-stream-obuf stream)))
2201 (when obuf
2202 (incf posn (buffer-tail obuf))))
2203 ;; Adjust for unread input: If there is any input
2204 ;; read from UNIX but not supplied to the user of the
2205 ;; stream, the *real* file position will smaller than
2206 ;; reported, because we want to look like the unread
2207 ;; stuff is still available.
2208 (let ((ibuf (fd-stream-ibuf stream)))
2209 (when ibuf
2210 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2211 (when (fd-stream-unread stream)
2212 (decf posn))
2213 ;; Divide bytes by element size.
2214 (truncate posn (fd-stream-element-size stream))))))
2216 (defun fd-stream-set-file-position (stream position-spec)
2217 (declare (fd-stream stream))
2218 (check-type position-spec
2219 (or (alien sb!unix:off-t) (member nil :start :end))
2220 "valid file position designator")
2221 (tagbody
2222 :again
2223 ;; Make sure we don't have any output pending, because if we
2224 ;; move the file pointer before writing this stuff, it will be
2225 ;; written in the wrong location.
2226 (finish-fd-stream-output stream)
2227 ;; Disable interrupts so that interrupt handlers doing output
2228 ;; won't screw us.
2229 (without-interrupts
2230 (unless (fd-stream-output-finished-p stream)
2231 ;; We got interrupted and more output came our way during
2232 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2233 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2234 ;; so we prefer to do things like this...
2235 (go :again))
2236 ;; Clear out any pending input to force the next read to go to
2237 ;; the disk.
2238 (flush-input-buffer stream)
2239 ;; Trash cached value for listen, so that we check next time.
2240 (setf (fd-stream-listen stream) nil)
2241 ;; Now move it.
2242 (multiple-value-bind (offset origin)
2243 (case position-spec
2244 (:start
2245 (values 0 sb!unix:l_set))
2246 (:end
2247 (values 0 sb!unix:l_xtnd))
2249 (values (* position-spec (fd-stream-element-size stream))
2250 sb!unix:l_set)))
2251 (declare (type (alien sb!unix:off-t) offset))
2252 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2253 offset origin)))
2254 ;; CLHS says to return true if the file-position was set
2255 ;; succesfully, and NIL otherwise. We are to signal an error
2256 ;; only if the given position was out of bounds, and that is
2257 ;; dealt with above. In times past we used to return NIL for
2258 ;; errno==ESPIPE, and signal an error in other cases.
2260 ;; FIXME: We are still liable to signal an error if flushing
2261 ;; output fails.
2262 (return-from fd-stream-set-file-position
2263 (typep posn '(alien sb!unix:off-t))))))))
2266 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2268 ;;; Create a stream for the given Unix file descriptor.
2270 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2271 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2272 ;;; default to allowing input.
2274 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2276 ;;; BUFFERING indicates the kind of buffering to use.
2278 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2279 ;;; NIL (the default), then wait forever. When we time out, we signal
2280 ;;; IO-TIMEOUT.
2282 ;;; FILE is the name of the file (will be returned by PATHNAME).
2284 ;;; NAME is used to identify the stream when printed.
2285 (defun make-fd-stream (fd
2286 &key
2287 (input nil input-p)
2288 (output nil output-p)
2289 (element-type 'base-char)
2290 (buffering :full)
2291 (external-format :default)
2292 timeout
2293 file
2294 original
2295 delete-original
2296 pathname
2297 input-buffer-p
2298 dual-channel-p
2299 (name (if file
2300 (format nil "file ~A" file)
2301 (format nil "descriptor ~W" fd)))
2302 auto-close)
2303 (declare (type index fd) (type (or real null) timeout)
2304 (type (member :none :line :full) buffering))
2305 (cond ((not (or input-p output-p))
2306 (setf input t))
2307 ((not (or input output))
2308 (error "File descriptor must be opened either for input or output.")))
2309 (let ((stream (%make-fd-stream :fd fd
2310 :name name
2311 :file file
2312 :original original
2313 :delete-original delete-original
2314 :pathname pathname
2315 :buffering buffering
2316 :dual-channel-p dual-channel-p
2317 :external-format external-format
2318 :char-size (external-format-char-size external-format)
2319 :timeout
2320 (if timeout
2321 (coerce timeout 'single-float)
2322 nil))))
2323 (set-fd-stream-routines stream element-type external-format
2324 input output input-buffer-p)
2325 (when (and auto-close (fboundp 'finalize))
2326 (finalize stream
2327 (lambda ()
2328 (sb!unix:unix-close fd)
2329 #!+sb-show
2330 (format *terminal-io* "** closed file descriptor ~W **~%"
2331 fd))
2332 :dont-save t))
2333 stream))
2335 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2336 ;;; :RENAME-AND-DELETE and :RENAME options.
2337 (defun pick-backup-name (name)
2338 (declare (type simple-string name))
2339 (concatenate 'simple-string name ".bak"))
2341 ;;; Ensure that the given arg is one of the given list of valid
2342 ;;; things. Allow the user to fix any problems.
2343 (defun ensure-one-of (item list what)
2344 (unless (member item list)
2345 (error 'simple-type-error
2346 :datum item
2347 :expected-type `(member ,@list)
2348 :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2349 :format-arguments (list item what list))))
2351 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2352 ;;; access, since we don't want to trash unwritable files even if we
2353 ;;; technically can. We return true if we succeed in renaming.
2354 (defun rename-the-old-one (namestring original)
2355 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2356 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2357 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2358 (if okay
2360 (error 'simple-file-error
2361 :pathname namestring
2362 :format-control
2363 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2364 :format-arguments (list namestring original (strerror err))))))
2366 (defun open (filename
2367 &key
2368 (direction :input)
2369 (element-type 'base-char)
2370 (if-exists nil if-exists-given)
2371 (if-does-not-exist nil if-does-not-exist-given)
2372 (external-format :default)
2373 &aux ; Squelch assignment warning.
2374 (direction direction)
2375 (if-does-not-exist if-does-not-exist)
2376 (if-exists if-exists))
2377 #!+sb-doc
2378 "Return a stream which reads from or writes to FILENAME.
2379 Defined keywords:
2380 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2381 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2382 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2383 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2384 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2385 See the manual for details."
2387 ;; Calculate useful stuff.
2388 (multiple-value-bind (input output mask)
2389 (ecase direction
2390 (:input (values t nil sb!unix:o_rdonly))
2391 (:output (values nil t sb!unix:o_wronly))
2392 (:io (values t t sb!unix:o_rdwr))
2393 (:probe (values t nil sb!unix:o_rdonly)))
2394 (declare (type index mask))
2395 (let* ((pathname (merge-pathnames filename))
2396 (namestring
2397 (cond ((unix-namestring pathname input))
2398 ((and input (eq if-does-not-exist :create))
2399 (unix-namestring pathname nil))
2400 ((and (eq direction :io) (not if-does-not-exist-given))
2401 (unix-namestring pathname nil)))))
2402 ;; Process if-exists argument if we are doing any output.
2403 (cond (output
2404 (unless if-exists-given
2405 (setf if-exists
2406 (if (eq (pathname-version pathname) :newest)
2407 :new-version
2408 :error)))
2409 (ensure-one-of if-exists
2410 '(:error :new-version :rename
2411 :rename-and-delete :overwrite
2412 :append :supersede nil)
2413 :if-exists)
2414 (case if-exists
2415 ((:new-version :error nil)
2416 (setf mask (logior mask sb!unix:o_excl)))
2417 ((:rename :rename-and-delete)
2418 (setf mask (logior mask sb!unix:o_creat)))
2419 ((:supersede)
2420 (setf mask (logior mask sb!unix:o_trunc)))
2421 (:append
2422 (setf mask (logior mask sb!unix:o_append)))))
2424 (setf if-exists :ignore-this-arg)))
2426 (unless if-does-not-exist-given
2427 (setf if-does-not-exist
2428 (cond ((eq direction :input) :error)
2429 ((and output
2430 (member if-exists '(:overwrite :append)))
2431 :error)
2432 ((eq direction :probe)
2433 nil)
2435 :create))))
2436 (ensure-one-of if-does-not-exist
2437 '(:error :create nil)
2438 :if-does-not-exist)
2439 (if (eq if-does-not-exist :create)
2440 (setf mask (logior mask sb!unix:o_creat)))
2442 (let ((original (case if-exists
2443 ((:rename :rename-and-delete)
2444 (pick-backup-name namestring))
2445 ((:append :overwrite)
2446 ;; KLUDGE: Provent CLOSE from deleting
2447 ;; appending streams when called with :ABORT T
2448 namestring)))
2449 (delete-original (eq if-exists :rename-and-delete))
2450 (mode #o666))
2451 (when (and original (not (eq original namestring)))
2452 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2453 ;; whether the file already exists, make sure the original
2454 ;; file is not a directory, and keep the mode.
2455 (let ((exists
2456 (and namestring
2457 (multiple-value-bind (okay err/dev inode orig-mode)
2458 (sb!unix:unix-stat namestring)
2459 (declare (ignore inode)
2460 (type (or index null) orig-mode))
2461 (cond
2462 (okay
2463 (when (and output (= (logand orig-mode #o170000)
2464 #o40000))
2465 (error 'simple-file-error
2466 :pathname namestring
2467 :format-control
2468 "can't open ~S for output: is a directory"
2469 :format-arguments (list namestring)))
2470 (setf mode (logand orig-mode #o777))
2472 ((eql err/dev sb!unix:enoent)
2473 nil)
2475 (simple-file-perror "can't find ~S"
2476 namestring
2477 err/dev)))))))
2478 (unless (and exists
2479 (rename-the-old-one namestring original))
2480 (setf original nil)
2481 (setf delete-original nil)
2482 ;; In order to use :SUPERSEDE instead, we have to make
2483 ;; sure SB!UNIX:O_CREAT corresponds to
2484 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2485 ;; because of IF-EXISTS being :RENAME.
2486 (unless (eq if-does-not-exist :create)
2487 (setf mask
2488 (logior (logandc2 mask sb!unix:o_creat)
2489 sb!unix:o_trunc)))
2490 (setf if-exists :supersede))))
2492 ;; Now we can try the actual Unix open(2).
2493 (multiple-value-bind (fd errno)
2494 (if namestring
2495 (sb!unix:unix-open namestring mask mode)
2496 (values nil sb!unix:enoent))
2497 (labels ((open-error (format-control &rest format-arguments)
2498 (error 'simple-file-error
2499 :pathname pathname
2500 :format-control format-control
2501 :format-arguments format-arguments))
2502 (vanilla-open-error ()
2503 (simple-file-perror "error opening ~S" pathname errno)))
2504 (cond ((numberp fd)
2505 (case direction
2506 ((:input :output :io)
2507 (make-fd-stream fd
2508 :input input
2509 :output output
2510 :element-type element-type
2511 :external-format external-format
2512 :file namestring
2513 :original original
2514 :delete-original delete-original
2515 :pathname pathname
2516 :dual-channel-p nil
2517 :input-buffer-p t
2518 :auto-close t))
2519 (:probe
2520 (let ((stream
2521 (%make-fd-stream :name namestring
2522 :fd fd
2523 :pathname pathname
2524 :element-type element-type)))
2525 (close stream)
2526 stream))))
2527 ((eql errno sb!unix:enoent)
2528 (case if-does-not-exist
2529 (:error (vanilla-open-error))
2530 (:create
2531 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2532 pathname))
2533 (t nil)))
2534 ((and (eql errno sb!unix:eexist) (null if-exists))
2535 nil)
2537 (vanilla-open-error)))))))))
2539 ;;;; initialization
2541 ;;; the stream connected to the controlling terminal, or NIL if there is none
2542 (defvar *tty*)
2544 ;;; the stream connected to the standard input (file descriptor 0)
2545 (defvar *stdin*)
2547 ;;; the stream connected to the standard output (file descriptor 1)
2548 (defvar *stdout*)
2550 ;;; the stream connected to the standard error output (file descriptor 2)
2551 (defvar *stderr*)
2553 ;;; This is called when the cold load is first started up, and may also
2554 ;;; be called in an attempt to recover from nested errors.
2555 (defun stream-cold-init-or-reset ()
2556 (stream-reinit)
2557 (setf *terminal-io* (make-synonym-stream '*tty*))
2558 (setf *standard-output* (make-synonym-stream '*stdout*))
2559 (setf *standard-input* (make-synonym-stream '*stdin*))
2560 (setf *error-output* (make-synonym-stream '*stderr*))
2561 (setf *query-io* (make-synonym-stream '*terminal-io*))
2562 (setf *debug-io* *query-io*)
2563 (setf *trace-output* *standard-output*)
2564 (values))
2566 (defun stream-deinit ()
2567 ;; Unbind to make sure we're not accidently dealing with it
2568 ;; before we're ready (or after we think it's been deinitialized).
2569 (with-available-buffers-lock ()
2570 (without-package-locks
2571 (makunbound '*available-buffers*))))
2573 ;;; This is called whenever a saved core is restarted.
2574 (defun stream-reinit (&optional init-buffers-p)
2575 (when init-buffers-p
2576 (with-available-buffers-lock ()
2577 (aver (not (boundp '*available-buffers*)))
2578 (setf *available-buffers* nil)))
2579 (with-output-to-string (*error-output*)
2580 (setf *stdin*
2581 (make-fd-stream 0 :name "standard input" :input t :buffering :line
2582 #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2583 (setf *stdout*
2584 (make-fd-stream 1 :name "standard output" :output t :buffering :line
2585 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2586 (setf *stderr*
2587 (make-fd-stream 2 :name "standard error" :output t :buffering :line
2588 #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2589 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2590 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2591 (if tty
2592 (setf *tty*
2593 (make-fd-stream tty
2594 :name "the terminal"
2595 :input t
2596 :output t
2597 :buffering :line
2598 :auto-close t))
2599 (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2600 (princ (get-output-stream-string *error-output*) *stderr*))
2601 (values))
2603 ;;;; miscellany
2605 ;;; the Unix way to beep
2606 (defun beep (stream)
2607 (write-char (code-char bell-char-code) stream)
2608 (finish-output stream))
2610 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2611 ;;; by the filesys stuff to get and set the file name.
2613 ;;; FIXME: misleading name, screwy interface
2614 (defun file-name (stream &optional new-name)
2615 (when (typep stream 'fd-stream)
2616 (cond (new-name
2617 (setf (fd-stream-pathname stream) new-name)
2618 (setf (fd-stream-file stream)
2619 (unix-namestring new-name nil))
2622 (fd-stream-pathname stream)))))