fix APROPOS/APROPOS-LIST and inherited symbols
[sbcl.git] / src / code / fd-stream.lisp
blob5c4e76e736543db5441c878ee30cb342b57f4c97
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-lock* (sb!thread:make-mutex
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-MUTEX because streams are low-level enough to be
62 ;; async signal safe, and in particular a C-c that brings up the
63 ;; debugger while holding the mutex would lose badly.
64 `(sb!thread::with-system-mutex (*available-buffers-lock*)
65 ,@body))
67 (defconstant +bytes-per-buffer+ (* 4 1024)
68 #!+sb-doc
69 "Default number of bytes per buffer.")
71 (defun alloc-buffer (&optional (size +bytes-per-buffer+))
72 ;; Don't want to allocate & unwind before the finalizer is in place.
73 (without-interrupts
74 (let* ((sap (allocate-system-memory size))
75 (buffer (%make-buffer sap size)))
76 (when (zerop (sap-int sap))
77 (error "Could not allocate ~D bytes for buffer." size))
78 (finalize buffer (lambda ()
79 (deallocate-system-memory sap size))
80 :dont-save t)
81 buffer)))
83 (defun get-buffer ()
84 ;; Don't go for the lock if there is nothing to be had -- sure,
85 ;; another thread might just release one before we get it, but that
86 ;; is not worth the cost of locking. Also release the lock before
87 ;; allocation, since it's going to take a while.
88 (if *available-buffers*
89 (or (with-available-buffers-lock ()
90 (pop *available-buffers*))
91 (alloc-buffer))
92 (alloc-buffer)))
94 (declaim (inline reset-buffer))
95 (defun reset-buffer (buffer)
96 (setf (buffer-head buffer) 0
97 (buffer-tail buffer) 0)
98 buffer)
100 (defun release-buffer (buffer)
101 (reset-buffer buffer)
102 (with-available-buffers-lock ()
103 (push buffer *available-buffers*)))
106 ;;;; the FD-STREAM structure
108 (defstruct (fd-stream
109 (:constructor %make-fd-stream)
110 (:conc-name fd-stream-)
111 (:predicate fd-stream-p)
112 (:include ansi-stream
113 (misc #'fd-stream-misc-routine))
114 (:copier nil))
116 ;; the name of this stream
117 (name nil)
118 ;; the file this stream is for
119 (file nil)
120 ;; the backup file namestring for the old file, for :IF-EXISTS
121 ;; :RENAME or :RENAME-AND-DELETE.
122 (original nil :type (or simple-string null))
123 (delete-original nil) ; for :if-exists :rename-and-delete
124 ;;; the number of bytes per element
125 (element-size 1 :type index)
126 ;; the type of element being transfered
127 (element-type 'base-char)
128 ;; the Unix file descriptor
129 (fd -1 :type #!-win32 fixnum #!+win32 sb!vm:signed-word)
130 ;; What do we know about the FD?
131 (fd-type :unknown :type keyword)
132 ;; controls when the output buffer is flushed
133 (buffering :full :type (member :full :line :none))
134 ;; controls whether the input buffer must be cleared before output
135 ;; (must be done for files, not for sockets, pipes and other data
136 ;; sources where input and output aren't related). non-NIL means
137 ;; don't clear input buffer.
138 (dual-channel-p nil)
139 ;; character position if known -- this may run into bignums, but
140 ;; we probably should flip it into null then for efficiency's sake...
141 (char-pos nil :type (or unsigned-byte null))
142 ;; T if input is waiting on FD. :EOF if we hit EOF.
143 (listen nil :type (member nil t :eof))
144 ;; T if serve-event is allowed when this stream blocks
145 (serve-events nil :type boolean)
147 ;; the input buffer
148 (instead (make-array 0 :element-type 'character :adjustable t :fill-pointer t) :type (array character (*)))
149 (ibuf nil :type (or buffer null))
150 (eof-forced-p nil :type (member t nil))
152 ;; the output buffer
153 (obuf nil :type (or buffer null))
155 ;; output flushed, but not written due to non-blocking io?
156 (output-queue nil)
157 (handler nil)
158 ;; timeout specified for this stream as seconds or NIL if none
159 (timeout nil :type (or single-float null))
160 ;; pathname of the file this stream is opened to (returned by PATHNAME)
161 (pathname nil :type (or pathname null))
162 ;; Not :DEFAULT, because we want to match CHAR-SIZE!
163 (external-format :latin-1)
164 ;; fixed width, or function to call with a character
165 (char-size 1 :type (or fixnum function))
166 (output-bytes #'ill-out :type function)
167 ;; a boolean indicating whether the stream is bivalent. For
168 ;; internal use only.
169 (bivalent-p nil :type boolean))
170 (def!method print-object ((fd-stream fd-stream) stream)
171 (declare (type stream stream))
172 (print-unreadable-object (fd-stream stream :type t :identity t)
173 (format stream "for ~S" (fd-stream-name fd-stream))))
175 ;;; This is a separate buffer management function, as it wants to be
176 ;;; clever about locking -- grabbing the lock just once.
177 (defun release-fd-stream-buffers (fd-stream)
178 (let ((ibuf (fd-stream-ibuf fd-stream))
179 (obuf (fd-stream-obuf fd-stream))
180 (queue (loop for item in (fd-stream-output-queue fd-stream)
181 when (buffer-p item)
182 collect (reset-buffer item))))
183 (when ibuf
184 (push (reset-buffer ibuf) queue))
185 (when obuf
186 (push (reset-buffer obuf) queue))
187 ;; ...so, anything found?
188 (when queue
189 ;; detach from stream
190 (setf (fd-stream-ibuf fd-stream) nil
191 (fd-stream-obuf fd-stream) nil
192 (fd-stream-output-queue fd-stream) nil)
193 ;; splice to *available-buffers*
194 (with-available-buffers-lock ()
195 (setf *available-buffers* (nconc queue *available-buffers*))))))
197 ;;;; CORE OUTPUT FUNCTIONS
199 ;;; Buffer the section of THING delimited by START and END by copying
200 ;;; to output buffer(s) of stream.
201 (defun buffer-output (stream thing start end)
202 (declare (index start end))
203 (when (< end start)
204 (error ":END before :START!"))
205 (when (> end start)
206 ;; Copy bytes from THING to buffers.
207 (flet ((copy-to-buffer (buffer tail count)
208 (declare (buffer buffer) (index tail count))
209 (aver (plusp count))
210 (let ((sap (buffer-sap buffer)))
211 (etypecase thing
212 (system-area-pointer
213 (system-area-ub8-copy thing start sap tail count))
214 ((simple-unboxed-array (*))
215 (copy-ub8-to-system-area thing start sap tail count))))
216 ;; Not INCF! If another thread has moved tail from under
217 ;; us, we don't want to accidentally increment tail
218 ;; beyond buffer-length.
219 (setf (buffer-tail buffer) (+ count tail))
220 (incf start count)))
221 (tagbody
222 ;; First copy is special: the buffer may already contain
223 ;; something, or be even full.
224 (let* ((obuf (fd-stream-obuf stream))
225 (tail (buffer-tail obuf))
226 (space (- (buffer-length obuf) tail)))
227 (when (plusp space)
228 (copy-to-buffer obuf tail (min space (- end start)))
229 (go :more-output-p)))
230 :flush-and-fill
231 ;; Later copies should always have an empty buffer, since
232 ;; they are freshly flushed, but if another thread is
233 ;; stomping on the same buffer that might not be the case.
234 (let* ((obuf (flush-output-buffer stream))
235 (tail (buffer-tail obuf))
236 (space (- (buffer-length obuf) tail)))
237 (copy-to-buffer obuf tail (min space (- end start))))
238 :more-output-p
239 (when (> end start)
240 (go :flush-and-fill))))))
242 ;;; Flush the current output buffer of the stream, ensuring that the
243 ;;; new buffer is empty. Returns (for convenience) the new output
244 ;;; buffer -- which may or may not be EQ to the old one. If the is no
245 ;;; queued output we try to write the buffer immediately -- otherwise
246 ;;; we queue it for later.
247 (defun flush-output-buffer (stream)
248 (let ((obuf (fd-stream-obuf stream)))
249 (when obuf
250 (let ((head (buffer-head obuf))
251 (tail (buffer-tail obuf)))
252 (cond ((eql head tail)
253 ;; Buffer is already empty -- just ensure that is is
254 ;; set to zero as well.
255 (reset-buffer obuf))
256 ((fd-stream-output-queue stream)
257 ;; There is already stuff on the queue -- go directly
258 ;; there.
259 (aver (< head tail))
260 (%queue-and-replace-output-buffer stream))
262 ;; Try a non-blocking write, if SERVE-EVENT is allowed, queue
263 ;; whatever is left over. Otherwise wait until we can write.
264 (aver (< head tail))
265 (synchronize-stream-output stream)
266 (loop
267 (let ((length (- tail head)))
268 (multiple-value-bind (count errno)
269 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap obuf)
270 head length)
271 (flet ((queue-or-wait ()
272 (if (fd-stream-serve-events stream)
273 (return (%queue-and-replace-output-buffer stream))
274 (or (wait-until-fd-usable (fd-stream-fd stream) :output
275 (fd-stream-timeout stream)
276 nil)
277 (signal-timeout 'io-timeout
278 :stream stream
279 :direction :output
280 :seconds (fd-stream-timeout stream))))))
281 (cond ((eql count length)
282 ;; Complete write -- we can use the same buffer.
283 (return (reset-buffer obuf)))
284 (count
285 ;; Partial write -- update buffer status and
286 ;; queue or wait.
287 (incf head count)
288 (setf (buffer-head obuf) head)
289 (queue-or-wait))
290 #!-win32
291 ((eql errno sb!unix:ewouldblock)
292 ;; Blocking, queue or wair.
293 (queue-or-wait))
294 ;; if interrupted on win32, just try again
295 #!+win32 ((eql errno sb!unix:eintr))
297 (simple-stream-perror "Couldn't write to ~s"
298 stream errno)))))))))))))
300 ;;; Helper for FLUSH-OUTPUT-BUFFER -- returns the new buffer.
301 (defun %queue-and-replace-output-buffer (stream)
302 (aver (fd-stream-serve-events stream))
303 (let ((queue (fd-stream-output-queue stream))
304 (later (list (or (fd-stream-obuf stream) (bug "Missing obuf."))))
305 (new (get-buffer)))
306 ;; Important: before putting the buffer on queue, give the stream
307 ;; a new one. If we get an interrupt and unwind losing the buffer
308 ;; is relatively OK, but having the same buffer in two places
309 ;; would be bad.
310 (setf (fd-stream-obuf stream) new)
311 (cond (queue
312 (nconc queue later))
314 (setf (fd-stream-output-queue stream) later)))
315 (unless (fd-stream-handler stream)
316 (setf (fd-stream-handler stream)
317 (add-fd-handler (fd-stream-fd stream)
318 :output
319 (lambda (fd)
320 (declare (ignore fd))
321 (write-output-from-queue stream)))))
322 new))
324 ;;; This is called by the FD-HANDLER for the stream when output is
325 ;;; possible.
326 (defun write-output-from-queue (stream)
327 (aver (fd-stream-serve-events stream))
328 (synchronize-stream-output stream)
329 (let (not-first-p)
330 (tagbody
331 :pop-buffer
332 (let* ((buffer (pop (fd-stream-output-queue stream)))
333 (head (buffer-head buffer))
334 (length (- (buffer-tail buffer) head)))
335 (declare (index head length))
336 (aver (>= length 0))
337 (multiple-value-bind (count errno)
338 (sb!unix:unix-write (fd-stream-fd stream) (buffer-sap buffer)
339 head length)
340 (cond ((eql count length)
341 ;; Complete write, see if we can do another right
342 ;; away, or remove the handler if we're done.
343 (release-buffer buffer)
344 (cond ((fd-stream-output-queue stream)
345 (setf not-first-p t)
346 (go :pop-buffer))
348 (let ((handler (fd-stream-handler stream)))
349 (aver handler)
350 (setf (fd-stream-handler stream) nil)
351 (remove-fd-handler handler)))))
352 (count
353 ;; Partial write. Update buffer status and requeue.
354 (aver (< count length))
355 ;; Do not use INCF! Another thread might have moved head.
356 (setf (buffer-head buffer) (+ head count))
357 (push buffer (fd-stream-output-queue stream)))
358 (not-first-p
359 ;; We tried to do multiple writes, and finally our
360 ;; luck ran out. Requeue.
361 (push buffer (fd-stream-output-queue stream)))
363 ;; Could not write on the first try at all!
364 #!+win32
365 (simple-stream-perror "Couldn't write to ~S." stream errno)
366 #!-win32
367 (if (= errno sb!unix:ewouldblock)
368 (bug "Unexpected blocking in WRITE-OUTPUT-FROM-QUEUE.")
369 (simple-stream-perror "Couldn't write to ~S"
370 stream errno))))))))
371 nil)
373 ;;; Try to write THING directly to STREAM without buffering, if
374 ;;; possible. If direct write doesn't happen, buffer.
375 (defun write-or-buffer-output (stream thing start end)
376 (declare (index start end))
377 (cond ((fd-stream-output-queue stream)
378 (buffer-output stream thing start end))
379 ((< end start)
380 (error ":END before :START!"))
381 ((> end start)
382 (let ((length (- end start)))
383 (synchronize-stream-output stream)
384 (multiple-value-bind (count errno)
385 (sb!unix:unix-write (fd-stream-fd stream) thing start length)
386 (cond ((eql count length)
387 ;; Complete write -- done!
389 (count
390 (aver (< count length))
391 ;; Partial write -- buffer the rest.
392 (buffer-output stream thing (+ start count) end))
394 ;; Could not write -- buffer or error.
395 #!+win32
396 (simple-stream-perror "couldn't write to ~s" stream errno)
397 #!-win32
398 (if (= errno sb!unix:ewouldblock)
399 (buffer-output stream thing start end)
400 (simple-stream-perror "couldn't write to ~s" stream errno)))))))))
402 ;;; Deprecated -- can go away after 1.1 or so. Deprecated because
403 ;;; this is not something we want to export. Nikodemus thinks the
404 ;;; right thing is to support a low-level non-stream like IO layer,
405 ;;; akin to java.nio.
406 (declaim (inline output-raw-bytes))
407 (define-deprecated-function :late "1.0.8.16" output-raw-bytes write-sequence
408 (stream thing &optional start end)
409 (write-or-buffer-output stream thing (or start 0) (or end (length thing))))
411 ;;;; output routines and related noise
413 (defvar *output-routines* ()
414 #!+sb-doc
415 "List of all available output routines. Each element is a list of the
416 element-type output, the kind of buffering, the function name, and the number
417 of bytes per element.")
419 ;;; common idioms for reporting low-level stream and file problems
420 (defun simple-stream-perror (note-format stream errno)
421 (error 'simple-stream-error
422 :stream stream
423 :format-control "~@<~?: ~2I~_~A~:>"
424 :format-arguments (list note-format (list stream) (strerror errno))))
425 (defun simple-file-perror (note-format pathname errno)
426 (error 'simple-file-error
427 :pathname pathname
428 :format-control "~@<~?: ~2I~_~A~:>"
429 :format-arguments
430 (list note-format (list pathname) (strerror errno))))
432 (defun c-string-encoding-error (external-format code)
433 (error 'c-string-encoding-error
434 :external-format external-format
435 :code code))
436 (defun c-string-decoding-error (external-format sap offset count)
437 (error 'c-string-decoding-error
438 :external-format external-format
439 :octets (sap-ref-octets sap offset count)))
441 ;;; Returning true goes into end of file handling, false will enter another
442 ;;; round of input buffer filling followed by re-entering character decode.
443 (defun stream-decoding-error-and-handle (stream octet-count)
444 (restart-case
445 (error 'stream-decoding-error
446 :external-format (stream-external-format stream)
447 :stream stream
448 :octets (let ((buffer (fd-stream-ibuf stream)))
449 (sap-ref-octets (buffer-sap buffer)
450 (buffer-head buffer)
451 octet-count)))
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 (setf (fd-stream-eof-forced-p stream) t))
463 (input-replacement (string)
464 :report (lambda (stream)
465 (format stream "~@<Use string as replacement input, ~
466 attempt to resync at a character ~
467 boundary and continue.~@:>"))
468 :interactive (lambda ()
469 (format *query-io* "~@<Enter a string: ~@:>")
470 (finish-output *query-io*)
471 (list (read *query-io*)))
472 (let ((string (reverse (string string)))
473 (instead (fd-stream-instead stream)))
474 (dotimes (i (length string))
475 (vector-push-extend (char string i) instead))
476 (fd-stream-resync stream)
477 (when (> (length string) 0)
478 (setf (fd-stream-listen stream) t)))
479 nil)))
481 (defun stream-encoding-error-and-handle (stream code)
482 (restart-case
483 (error 'stream-encoding-error
484 :external-format (stream-external-format stream)
485 :stream stream
486 :code code)
487 (output-nothing ()
488 :report (lambda (stream)
489 (format stream "~@<Skip output of this character.~@:>"))
490 (throw 'output-nothing nil))
491 (output-replacement (string)
492 :report (lambda (stream)
493 (format stream "~@<Output replacement string.~@:>"))
494 :interactive (lambda ()
495 (format *query-io* "~@<Enter a string: ~@:>")
496 (finish-output *query-io*)
497 (list (read *query-io*)))
498 (let ((string (string string)))
499 (fd-sout stream (string string) 0 (length string)))
500 (throw 'output-nothing nil))))
502 (defun external-format-encoding-error (stream code)
503 (if (streamp stream)
504 (stream-encoding-error-and-handle stream code)
505 (c-string-encoding-error stream code)))
507 (defun synchronize-stream-output (stream)
508 ;; If we're reading and writing on the same file, flush buffered
509 ;; input and rewind file position accordingly.
510 (unless (fd-stream-dual-channel-p stream)
511 (let ((adjust (nth-value 1 (flush-input-buffer stream))))
512 (unless (eql 0 adjust)
513 (sb!unix:unix-lseek (fd-stream-fd stream) (- adjust) sb!unix:l_incr)))))
515 (defun fd-stream-output-finished-p (stream)
516 (let ((obuf (fd-stream-obuf stream)))
517 (or (not obuf)
518 (and (zerop (buffer-tail obuf))
519 (not (fd-stream-output-queue stream))))))
521 (defmacro output-wrapper/variable-width ((stream size buffering restart)
522 &body body)
523 (let ((stream-var (gensym "STREAM")))
524 `(let* ((,stream-var ,stream)
525 (obuf (fd-stream-obuf ,stream-var))
526 (tail (buffer-tail obuf))
527 (size ,size))
528 ,(unless (eq (car buffering) :none)
529 `(when (< (buffer-length obuf) (+ tail size))
530 (setf obuf (flush-output-buffer ,stream-var)
531 tail (buffer-tail obuf))))
532 ,(unless (eq (car buffering) :none)
533 ;; FIXME: Why this here? Doesn't seem necessary.
534 `(synchronize-stream-output ,stream-var))
535 ,(if restart
536 `(catch 'output-nothing
537 ,@body
538 (setf (buffer-tail obuf) (+ tail size)))
539 `(progn
540 ,@body
541 (setf (buffer-tail obuf) (+ tail size))))
542 ,(ecase (car buffering)
543 (:none
544 `(flush-output-buffer ,stream-var))
545 (:line
546 `(when (eql byte #\Newline)
547 (flush-output-buffer ,stream-var)))
548 (:full))
549 (values))))
551 (defmacro output-wrapper ((stream size buffering restart) &body body)
552 (let ((stream-var (gensym "STREAM")))
553 `(let* ((,stream-var ,stream)
554 (obuf (fd-stream-obuf ,stream-var))
555 (tail (buffer-tail obuf)))
556 ,(unless (eq (car buffering) :none)
557 `(when (< (buffer-length obuf) (+ tail ,size))
558 (setf obuf (flush-output-buffer ,stream-var)
559 tail (buffer-tail obuf))))
560 ;; FIXME: Why this here? Doesn't seem necessary.
561 ,(unless (eq (car buffering) :none)
562 `(synchronize-stream-output ,stream-var))
563 ,(if restart
564 `(catch 'output-nothing
565 ,@body
566 (setf (buffer-tail obuf) (+ tail ,size)))
567 `(progn
568 ,@body
569 (setf (buffer-tail obuf) (+ tail ,size))))
570 ,(ecase (car buffering)
571 (:none
572 `(flush-output-buffer ,stream-var))
573 (:line
574 `(when (eql byte #\Newline)
575 (flush-output-buffer ,stream-var)))
576 (:full))
577 (values))))
579 (defmacro def-output-routines/variable-width
580 ((name-fmt size restart external-format &rest bufferings)
581 &body body)
582 (declare (optimize (speed 1)))
583 (cons 'progn
584 (mapcar
585 (lambda (buffering)
586 (let ((function
587 (intern (format nil name-fmt (string (car buffering))))))
588 `(progn
589 (defun ,function (stream byte)
590 (declare (ignorable byte))
591 (output-wrapper/variable-width (stream ,size ,buffering ,restart)
592 ,@body))
593 (setf *output-routines*
594 (nconc *output-routines*
595 ',(mapcar
596 (lambda (type)
597 (list type
598 (car buffering)
599 function
601 external-format))
602 (cdr buffering)))))))
603 bufferings)))
605 ;;; Define output routines that output numbers SIZE bytes long for the
606 ;;; given bufferings. Use BODY to do the actual output.
607 (defmacro def-output-routines ((name-fmt size restart &rest bufferings)
608 &body body)
609 (declare (optimize (speed 1)))
610 (cons 'progn
611 (mapcar
612 (lambda (buffering)
613 (let ((function
614 (intern (format nil name-fmt (string (car buffering))))))
615 `(progn
616 (defun ,function (stream byte)
617 (output-wrapper (stream ,size ,buffering ,restart)
618 ,@body))
619 (setf *output-routines*
620 (nconc *output-routines*
621 ',(mapcar
622 (lambda (type)
623 (list type
624 (car buffering)
625 function
626 size
627 nil))
628 (cdr buffering)))))))
629 bufferings)))
631 ;;; FIXME: is this used anywhere any more?
632 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
635 (:none character)
636 (:line character)
637 (:full character))
638 (if (eql byte #\Newline)
639 (setf (fd-stream-char-pos stream) 0)
640 (incf (fd-stream-char-pos stream)))
641 (setf (sap-ref-8 (buffer-sap obuf) tail)
642 (char-code byte)))
644 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
647 (:none (unsigned-byte 8))
648 (:full (unsigned-byte 8)))
649 (setf (sap-ref-8 (buffer-sap obuf) tail)
650 byte))
652 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
655 (:none (signed-byte 8))
656 (:full (signed-byte 8)))
657 (setf (signed-sap-ref-8 (buffer-sap obuf) tail)
658 byte))
660 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
663 (:none (unsigned-byte 16))
664 (:full (unsigned-byte 16)))
665 (setf (sap-ref-16 (buffer-sap obuf) tail)
666 byte))
668 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
671 (:none (signed-byte 16))
672 (:full (signed-byte 16)))
673 (setf (signed-sap-ref-16 (buffer-sap obuf) tail)
674 byte))
676 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
679 (:none (unsigned-byte 32))
680 (:full (unsigned-byte 32)))
681 (setf (sap-ref-32 (buffer-sap obuf) tail)
682 byte))
684 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
687 (:none (signed-byte 32))
688 (:full (signed-byte 32)))
689 (setf (signed-sap-ref-32 (buffer-sap obuf) tail)
690 byte))
692 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
693 (progn
694 (def-output-routines ("OUTPUT-UNSIGNED-LONG-LONG-~A-BUFFERED"
697 (:none (unsigned-byte 64))
698 (:full (unsigned-byte 64)))
699 (setf (sap-ref-64 (buffer-sap obuf) tail)
700 byte))
701 (def-output-routines ("OUTPUT-SIGNED-LONG-LONG-~A-BUFFERED"
704 (:none (signed-byte 64))
705 (:full (signed-byte 64)))
706 (setf (signed-sap-ref-64 (buffer-sap obuf) tail)
707 byte)))
709 ;;; the routine to use to output a string. If the stream is
710 ;;; unbuffered, slam the string down the file descriptor, otherwise
711 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
712 ;;; checking to see where the last newline was.
713 (defun fd-sout (stream thing start end)
714 (declare (type fd-stream stream) (type string thing))
715 (let ((start (or start 0))
716 (end (or end (length (the vector thing)))))
717 (declare (fixnum start end))
718 (let ((last-newline
719 (string-dispatch (simple-base-string
720 #!+sb-unicode
721 (simple-array character (*))
722 string)
723 thing
724 (position #\newline thing :from-end t
725 :start start :end end))))
726 (if (and (typep thing 'base-string)
727 (eq (fd-stream-external-format-keyword stream) :latin-1))
728 (ecase (fd-stream-buffering stream)
729 (:full
730 (buffer-output stream thing start end))
731 (:line
732 (buffer-output stream thing start end)
733 (when last-newline
734 (flush-output-buffer stream)))
735 (:none
736 (write-or-buffer-output stream thing start end)))
737 (ecase (fd-stream-buffering stream)
738 (:full (funcall (fd-stream-output-bytes stream)
739 stream thing nil start end))
740 (:line (funcall (fd-stream-output-bytes stream)
741 stream thing last-newline start end))
742 (:none (funcall (fd-stream-output-bytes stream)
743 stream thing t start end))))
744 (if last-newline
745 (setf (fd-stream-char-pos stream) (- end last-newline 1))
746 (incf (fd-stream-char-pos stream) (- end start))))))
748 (defstruct (external-format
749 (:constructor %make-external-format)
750 (:conc-name ef-)
751 (:predicate external-format-p)
752 (:copier %copy-external-format))
753 ;; All the names that can refer to this external format. The first
754 ;; one is the canonical name.
755 (names (missing-arg) :type list :read-only t)
756 (default-replacement-character (missing-arg) :type character)
757 (read-n-chars-fun (missing-arg) :type function)
758 (read-char-fun (missing-arg) :type function)
759 (write-n-bytes-fun (missing-arg) :type function)
760 (write-char-none-buffered-fun (missing-arg) :type function)
761 (write-char-line-buffered-fun (missing-arg) :type function)
762 (write-char-full-buffered-fun (missing-arg) :type function)
763 ;; Can be nil for fixed-width formats.
764 (resync-fun nil :type (or function null))
765 (bytes-for-char-fun (missing-arg) :type function)
766 (read-c-string-fun (missing-arg) :type function)
767 (write-c-string-fun (missing-arg) :type function)
768 ;; We indirect through symbols in these functions so that a
769 ;; developer working on the octets code can easily redefine things
770 ;; and use the new function definition without redefining the
771 ;; external format as well. The slots above don't do any
772 ;; indirection because a developer working with those slots would be
773 ;; redefining the external format anyway.
774 (octets-to-string-fun (missing-arg) :type function)
775 (string-to-octets-fun (missing-arg) :type function))
777 (defun ef-char-size (ef-entry)
778 (if (variable-width-external-format-p ef-entry)
779 (bytes-for-char-fun ef-entry)
780 (funcall (bytes-for-char-fun ef-entry) #\x)))
782 (defun wrap-external-format-functions (external-format fun)
783 (let ((result (%copy-external-format external-format)))
784 (macrolet ((frob (accessor)
785 `(setf (,accessor result) (funcall fun (,accessor result)))))
786 (frob ef-read-n-chars-fun)
787 (frob ef-read-char-fun)
788 (frob ef-write-n-bytes-fun)
789 (frob ef-write-char-none-buffered-fun)
790 (frob ef-write-char-line-buffered-fun)
791 (frob ef-write-char-full-buffered-fun)
792 (frob ef-resync-fun)
793 (frob ef-bytes-for-char-fun)
794 (frob ef-read-c-string-fun)
795 (frob ef-write-c-string-fun)
796 (frob ef-octets-to-string-fun)
797 (frob ef-string-to-octets-fun))
798 result))
800 (defvar *external-formats* (make-hash-table)
801 #!+sb-doc
802 "Hashtable of all available external formats. The table maps from
803 external-format names to EXTERNAL-FORMAT structures.")
805 (defun get-external-format (external-format)
806 (flet ((keyword-external-format (keyword)
807 (declare (type keyword keyword))
808 (gethash keyword *external-formats*))
809 (replacement-handlerify (entry replacement)
810 (when entry
811 (wrap-external-format-functions
812 entry
813 (lambda (fun)
814 (and fun
815 (lambda (&rest rest)
816 (declare (dynamic-extent rest))
817 (handler-bind
818 ((stream-decoding-error
819 (lambda (c)
820 (declare (ignore c))
821 (invoke-restart 'input-replacement replacement)))
822 (stream-encoding-error
823 (lambda (c)
824 (declare (ignore c))
825 (invoke-restart 'output-replacement replacement)))
826 (octets-encoding-error
827 (lambda (c) (use-value replacement c)))
828 (octet-decoding-error
829 (lambda (c) (use-value replacement c))))
830 (apply fun rest)))))))))
831 (typecase external-format
832 (keyword (keyword-external-format external-format))
833 ((cons keyword)
834 (let ((entry (keyword-external-format (car external-format)))
835 (replacement (getf (cdr external-format) :replacement)))
836 (if replacement
837 (replacement-handlerify entry replacement)
838 entry))))))
840 (defun get-external-format-or-lose (external-format)
841 (or (get-external-format external-format)
842 (error "Undefined external-format: ~S" external-format)))
844 (defun external-format-keyword (external-format)
845 (typecase external-format
846 (keyword external-format)
847 ((cons keyword) (car external-format))))
849 (defun fd-stream-external-format-keyword (stream)
850 (external-format-keyword (fd-stream-external-format stream)))
852 (defun canonize-external-format (external-format entry)
853 (typecase external-format
854 (keyword (first (ef-names entry)))
855 ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
857 ;;; Find an output routine to use given the type and buffering. Return
858 ;;; as multiple values the routine, the real type transfered, and the
859 ;;; number of bytes per element.
860 (defun pick-output-routine (type buffering &optional external-format)
861 (when (subtypep type 'character)
862 (let ((entry (get-external-format-or-lose external-format)))
863 (return-from pick-output-routine
864 (values (ecase buffering
865 (:none (ef-write-char-none-buffered-fun entry))
866 (:line (ef-write-char-line-buffered-fun entry))
867 (:full (ef-write-char-full-buffered-fun entry)))
868 'character
870 (ef-write-n-bytes-fun entry)
871 (ef-char-size entry)
872 (canonize-external-format external-format entry)))))
873 (dolist (entry *output-routines*)
874 (when (and (subtypep type (first entry))
875 (eq buffering (second entry))
876 (or (not (fifth entry))
877 (eq external-format (fifth entry))))
878 (return-from pick-output-routine
879 (values (symbol-function (third entry))
880 (first entry)
881 (fourth entry)))))
882 ;; KLUDGE: dealing with the buffering here leads to excessive code
883 ;; explosion.
885 ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
886 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
887 if (subtypep type `(unsigned-byte ,i))
888 do (return-from pick-output-routine
889 (values
890 (ecase buffering
891 (:none
892 (lambda (stream byte)
893 (output-wrapper (stream (/ i 8) (:none) nil)
894 (loop for j from 0 below (/ i 8)
895 do (setf (sap-ref-8 (buffer-sap obuf)
896 (+ j tail))
897 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
898 (:full
899 (lambda (stream byte)
900 (output-wrapper (stream (/ i 8) (:full) nil)
901 (loop for j from 0 below (/ i 8)
902 do (setf (sap-ref-8 (buffer-sap obuf)
903 (+ j tail))
904 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
905 `(unsigned-byte ,i)
906 (/ i 8))))
907 (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
908 if (subtypep type `(signed-byte ,i))
909 do (return-from pick-output-routine
910 (values
911 (ecase buffering
912 (:none
913 (lambda (stream byte)
914 (output-wrapper (stream (/ i 8) (:none) nil)
915 (loop for j from 0 below (/ i 8)
916 do (setf (sap-ref-8 (buffer-sap obuf)
917 (+ j tail))
918 (ldb (byte 8 (- i 8 (* j 8))) byte))))))
919 (:full
920 (lambda (stream byte)
921 (output-wrapper (stream (/ i 8) (:full) nil)
922 (loop for j from 0 below (/ i 8)
923 do (setf (sap-ref-8 (buffer-sap obuf)
924 (+ j tail))
925 (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
926 `(signed-byte ,i)
927 (/ i 8)))))
929 ;;;; input routines and related noise
931 ;;; a list of all available input routines. Each element is a list of
932 ;;; the element-type input, the function name, and the number of bytes
933 ;;; per element.
934 (defvar *input-routines* ())
936 ;;; Return whether a primitive partial read operation on STREAM's FD
937 ;;; would (probably) block. Signal a `simple-stream-error' if the
938 ;;; system call implementing this operation fails.
940 ;;; It is "may" instead of "would" because "would" is not quite
941 ;;; correct on win32. However, none of the places that use it require
942 ;;; further assurance than "may" versus "will definitely not".
943 (defun sysread-may-block-p (stream)
944 #!+win32
945 ;; This answers T at EOF on win32, I think.
946 (not (sb!win32:fd-listen (fd-stream-fd stream)))
947 #!-win32
948 (not (sb!unix:unix-simple-poll (fd-stream-fd stream) :input 0)))
950 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
951 ;;; then fill the input buffer, and return the number of bytes read. Throws
952 ;;; to EOF-INPUT-CATCHER if the eof was reached.
953 (defun refill-input-buffer (stream)
954 (dx-let ((fd (fd-stream-fd stream))
955 (errno 0)
956 (count 0))
957 (tagbody
958 #!+win32
959 (go :main)
961 ;; Check for blocking input before touching the stream if we are to
962 ;; serve events: if the FD is blocking, we don't want to try an uninterruptible
963 ;; read(). Regular files should never block, so we can elide the check.
964 (if (and (neq :regular (fd-stream-fd-type stream))
965 (sysread-may-block-p stream))
966 (go :wait-for-input)
967 (go :main))
968 ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
969 ;; we can signal errors outside the WITHOUT-INTERRUPTS.
970 :closed-flame
971 (closed-flame stream)
972 :read-error
973 (simple-stream-perror "couldn't read from ~S" stream errno)
974 :wait-for-input
975 ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
976 ;; to wait for input if read tells us EWOULDBLOCK.
977 (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream)
978 (fd-stream-serve-events stream))
979 (signal-timeout 'io-timeout
980 :stream stream
981 :direction :input
982 :seconds (fd-stream-timeout stream)))
983 :main
984 ;; Since the read should not block, we'll disable the
985 ;; interrupts here, so that we don't accidentally unwind and
986 ;; leave the stream in an inconsistent state.
988 ;; Execute the nlx outside without-interrupts to ensure the
989 ;; resulting thunk is stack-allocatable.
990 ((lambda (return-reason)
991 (ecase return-reason
992 ((nil)) ; fast path normal cases
993 ((:wait-for-input) (go #!-win32 :wait-for-input #!+win32 :main))
994 ((:closed-flame) (go :closed-flame))
995 ((:read-error) (go :read-error))))
996 (without-interrupts
997 ;; Check the buffer: if it is null, then someone has closed
998 ;; the stream from underneath us. This is not ment to fix
999 ;; multithreaded races, but to deal with interrupt handlers
1000 ;; closing the stream.
1001 (block nil
1002 (prog1 nil
1003 (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1004 (sap (buffer-sap ibuf))
1005 (length (buffer-length ibuf))
1006 (head (buffer-head ibuf))
1007 (tail (buffer-tail ibuf)))
1008 (declare (index length head tail)
1009 (inline sb!unix:unix-read))
1010 (unless (zerop head)
1011 (cond ((eql head tail)
1012 ;; Buffer is empty, but not at yet reset -- make it so.
1013 (setf head 0
1014 tail 0)
1015 (reset-buffer ibuf))
1017 ;; Buffer has things in it, but they are not at the
1018 ;; head -- move them there.
1019 (let ((n (- tail head)))
1020 (system-area-ub8-copy sap head sap 0 n)
1021 (setf head 0
1022 (buffer-head ibuf) head
1023 tail n
1024 (buffer-tail ibuf) tail)))))
1025 (setf (fd-stream-listen stream) nil)
1026 (setf (values count errno)
1027 (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1028 (cond ((null count)
1029 (if (eql errno
1030 #!+win32 sb!unix:eintr
1031 #!-win32 sb!unix:ewouldblock)
1032 (return :wait-for-input)
1033 (return :read-error)))
1034 ((zerop count)
1035 (setf (fd-stream-listen stream) :eof)
1036 (/show0 "THROWing EOF-INPUT-CATCHER")
1037 (throw 'eof-input-catcher nil))
1039 ;; Success! (Do not use INCF, for sake of other threads.)
1040 (setf (buffer-tail ibuf) (+ count tail))))))))))
1041 count))
1043 ;;; Make sure there are at least BYTES number of bytes in the input
1044 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1045 (defmacro input-at-least (stream bytes)
1046 (let ((stream-var (gensym "STREAM"))
1047 (bytes-var (gensym "BYTES"))
1048 (buffer-var (gensym "IBUF")))
1049 `(let* ((,stream-var ,stream)
1050 (,bytes-var ,bytes)
1051 (,buffer-var (fd-stream-ibuf ,stream-var)))
1052 (loop
1053 (when (>= (- (buffer-tail ,buffer-var)
1054 (buffer-head ,buffer-var))
1055 ,bytes-var)
1056 (return))
1057 (refill-input-buffer ,stream-var)))))
1059 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1060 &body read-forms)
1061 (let ((stream-var (gensym "STREAM"))
1062 (retry-var (gensym "RETRY"))
1063 (element-var (gensym "ELT")))
1064 `(let* ((,stream-var ,stream)
1065 (ibuf (fd-stream-ibuf ,stream-var))
1066 (size nil))
1067 (block use-instead
1068 (when (fd-stream-eof-forced-p ,stream-var)
1069 (setf (fd-stream-eof-forced-p ,stream-var) nil)
1070 (return-from use-instead
1071 (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1072 (let ((,element-var nil)
1073 (decode-break-reason nil))
1074 (do ((,retry-var t))
1075 ((not ,retry-var))
1076 (if (> (length (fd-stream-instead ,stream-var)) 0)
1077 (let* ((instead (fd-stream-instead ,stream-var))
1078 (result (vector-pop instead))
1079 (pointer (fill-pointer instead)))
1080 (when (= pointer 0)
1081 (setf (fd-stream-listen ,stream-var) nil))
1082 (return-from use-instead result))
1083 (unless
1084 (catch 'eof-input-catcher
1085 (setf decode-break-reason
1086 (block decode-break-reason
1087 (input-at-least ,stream-var ,(if (consp bytes)
1088 (car bytes)
1089 `(setq size ,bytes)))
1090 (let* ((byte (sap-ref-8 (buffer-sap ibuf) (buffer-head ibuf))))
1091 (declare (ignorable byte))
1092 ,@(when (consp bytes)
1093 `((let ((sap (buffer-sap ibuf))
1094 (head (buffer-head ibuf)))
1095 (declare (ignorable sap head))
1096 (setq size ,(cadr bytes))
1097 (input-at-least ,stream-var size))))
1098 (setq ,element-var (locally ,@read-forms))
1099 (setq ,retry-var nil))
1100 nil))
1101 (when decode-break-reason
1102 (when (stream-decoding-error-and-handle
1103 stream decode-break-reason)
1104 (setq ,retry-var nil)
1105 (throw 'eof-input-catcher nil)))
1107 (let ((octet-count (- (buffer-tail ibuf)
1108 (buffer-head ibuf))))
1109 (when (or (zerop octet-count)
1110 (and (not ,element-var)
1111 (not decode-break-reason)
1112 (stream-decoding-error-and-handle
1113 stream octet-count)))
1114 (setq ,retry-var nil))))))
1115 (cond (,element-var
1116 (incf (buffer-head ibuf) size)
1117 ,element-var)
1119 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1121 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1122 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1123 (let ((stream-var (gensym "STREAM"))
1124 (element-var (gensym "ELT")))
1125 `(let* ((,stream-var ,stream)
1126 (ibuf (fd-stream-ibuf ,stream-var)))
1127 (if (> (length (fd-stream-instead ,stream-var)) 0)
1128 (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1129 (let ((,element-var
1130 (catch 'eof-input-catcher
1131 (input-at-least ,stream-var ,bytes)
1132 (locally ,@read-forms))))
1133 (cond (,element-var
1134 (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1135 ,element-var)
1137 (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1139 (defmacro def-input-routine/variable-width (name
1140 (type external-format size sap head)
1141 &rest body)
1142 `(progn
1143 (defun ,name (stream eof-error eof-value)
1144 (input-wrapper/variable-width (stream ,size eof-error eof-value)
1145 (let ((,sap (buffer-sap ibuf))
1146 (,head (buffer-head ibuf)))
1147 ,@body)))
1148 (setf *input-routines*
1149 (nconc *input-routines*
1150 (list (list ',type ',name 1 ',external-format))))))
1152 (defmacro def-input-routine (name
1153 (type size sap head)
1154 &rest body)
1155 `(progn
1156 (defun ,name (stream eof-error eof-value)
1157 (input-wrapper (stream ,size eof-error eof-value)
1158 (let ((,sap (buffer-sap ibuf))
1159 (,head (buffer-head ibuf)))
1160 ,@body)))
1161 (setf *input-routines*
1162 (nconc *input-routines*
1163 (list (list ',type ',name ',size nil))))))
1165 ;;; STREAM-IN routine for reading a string char
1166 (def-input-routine input-character
1167 (character 1 sap head)
1168 (code-char (sap-ref-8 sap head)))
1170 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1171 (def-input-routine input-unsigned-8bit-byte
1172 ((unsigned-byte 8) 1 sap head)
1173 (sap-ref-8 sap head))
1175 ;;; STREAM-IN routine for reading a signed 8 bit number
1176 (def-input-routine input-signed-8bit-number
1177 ((signed-byte 8) 1 sap head)
1178 (signed-sap-ref-8 sap head))
1180 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1181 (def-input-routine input-unsigned-16bit-byte
1182 ((unsigned-byte 16) 2 sap head)
1183 (sap-ref-16 sap head))
1185 ;;; STREAM-IN routine for reading a signed 16 bit number
1186 (def-input-routine input-signed-16bit-byte
1187 ((signed-byte 16) 2 sap head)
1188 (signed-sap-ref-16 sap head))
1190 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1191 (def-input-routine input-unsigned-32bit-byte
1192 ((unsigned-byte 32) 4 sap head)
1193 (sap-ref-32 sap head))
1195 ;;; STREAM-IN routine for reading a signed 32 bit number
1196 (def-input-routine input-signed-32bit-byte
1197 ((signed-byte 32) 4 sap head)
1198 (signed-sap-ref-32 sap head))
1200 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1201 (progn
1202 (def-input-routine input-unsigned-64bit-byte
1203 ((unsigned-byte 64) 8 sap head)
1204 (sap-ref-64 sap head))
1205 (def-input-routine input-signed-64bit-byte
1206 ((signed-byte 64) 8 sap head)
1207 (signed-sap-ref-64 sap head)))
1209 ;;; Find an input routine to use given the type. Return as multiple
1210 ;;; values the routine, the real type transfered, and the number of
1211 ;;; bytes per element (and for character types string input routine).
1212 (defun pick-input-routine (type &optional external-format)
1213 (when (subtypep type 'character)
1214 (let ((entry (get-external-format-or-lose external-format)))
1215 (return-from pick-input-routine
1216 (values (ef-read-char-fun entry)
1217 'character
1219 (ef-read-n-chars-fun entry)
1220 (ef-char-size entry)
1221 (canonize-external-format external-format entry)))))
1222 (dolist (entry *input-routines*)
1223 (when (and (subtypep type (first entry))
1224 (or (not (fourth entry))
1225 (eq external-format (fourth entry))))
1226 (return-from pick-input-routine
1227 (values (symbol-function (second entry))
1228 (first entry)
1229 (third entry)))))
1230 ;; FIXME: let's do it the hard way, then (but ignore things like
1231 ;; endianness, efficiency, and the necessary coupling between these
1232 ;; and the output routines). -- CSR, 2004-02-09
1233 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1234 if (subtypep type `(unsigned-byte ,i))
1235 do (return-from pick-input-routine
1236 (values
1237 (lambda (stream eof-error eof-value)
1238 (input-wrapper (stream (/ i 8) eof-error eof-value)
1239 (let ((sap (buffer-sap ibuf))
1240 (head (buffer-head ibuf)))
1241 (loop for j from 0 below (/ i 8)
1242 with result = 0
1243 do (setf result
1244 (+ (* 256 result)
1245 (sap-ref-8 sap (+ head j))))
1246 finally (return result)))))
1247 `(unsigned-byte ,i)
1248 (/ i 8))))
1249 (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1250 if (subtypep type `(signed-byte ,i))
1251 do (return-from pick-input-routine
1252 (values
1253 (lambda (stream eof-error eof-value)
1254 (input-wrapper (stream (/ i 8) eof-error eof-value)
1255 (let ((sap (buffer-sap ibuf))
1256 (head (buffer-head ibuf)))
1257 (loop for j from 0 below (/ i 8)
1258 with result = 0
1259 do (setf result
1260 (+ (* 256 result)
1261 (sap-ref-8 sap (+ head j))))
1262 finally (return (if (logbitp (1- i) result)
1263 (dpb result (byte i 0) -1)
1264 result))))))
1265 `(signed-byte ,i)
1266 (/ i 8)))))
1268 ;;; the N-BIN method for FD-STREAMs
1270 ;;; Note that this blocks in UNIX-READ. It is generally used where
1271 ;;; there is a definite amount of reading to be done, so blocking
1272 ;;; isn't too problematical.
1273 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1274 &aux (total-copied 0))
1275 (declare (type fd-stream stream))
1276 (declare (type index start requested total-copied))
1277 (aver (= (length (fd-stream-instead stream)) 0))
1278 (do ()
1279 (nil)
1280 (let* ((remaining-request (- requested total-copied))
1281 (ibuf (fd-stream-ibuf stream))
1282 (head (buffer-head ibuf))
1283 (tail (buffer-tail ibuf))
1284 (available (- tail head))
1285 (n-this-copy (min remaining-request available))
1286 (this-start (+ start total-copied))
1287 (this-end (+ this-start n-this-copy))
1288 (sap (buffer-sap ibuf)))
1289 (declare (type index remaining-request head tail available))
1290 (declare (type index n-this-copy))
1291 ;; Copy data from stream buffer into user's buffer.
1292 (%byte-blt sap head buffer this-start this-end)
1293 (incf (buffer-head ibuf) n-this-copy)
1294 (incf total-copied n-this-copy)
1295 ;; Maybe we need to refill the stream buffer.
1296 (cond (;; If there were enough data in the stream buffer, we're done.
1297 (eql total-copied requested)
1298 (return total-copied))
1299 (;; If EOF, we're done in another way.
1300 (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1301 (if eof-error-p
1302 (error 'end-of-file :stream stream)
1303 (return total-copied)))
1304 ;; Otherwise we refilled the stream buffer, so fall
1305 ;; through into another pass of the loop.
1306 ))))
1308 (defun fd-stream-resync (stream)
1309 (let ((entry (get-external-format (fd-stream-external-format stream))))
1310 (when entry
1311 (funcall (ef-resync-fun entry) stream))))
1313 (defun get-fd-stream-character-sizer (stream)
1314 (let ((entry (get-external-format (fd-stream-external-format stream))))
1315 (when entry
1316 (ef-bytes-for-char-fun entry))))
1318 (defun fd-stream-character-size (stream char)
1319 (let ((sizer (get-fd-stream-character-sizer stream)))
1320 (when sizer (funcall sizer char))))
1322 (defun fd-stream-string-size (stream string)
1323 (let ((sizer (get-fd-stream-character-sizer stream)))
1324 (when sizer
1325 (loop for char across string summing (funcall sizer char)))))
1327 (defun find-external-format (external-format)
1328 (when external-format
1329 (get-external-format external-format)))
1331 (defun variable-width-external-format-p (ef-entry)
1332 (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1334 (defun bytes-for-char-fun (ef-entry)
1335 (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1337 (defmacro define-unibyte-mapping-external-format
1338 (canonical-name (&rest other-names) &body exceptions)
1339 (let ((->code-name (symbolicate canonical-name '->code-mapper))
1340 (code->-name (symbolicate 'code-> canonical-name '-mapper))
1341 (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1342 (string->-name (symbolicate 'string-> canonical-name))
1343 (define-string*-name (symbolicate 'define- canonical-name '->string*))
1344 (string*-name (symbolicate canonical-name '->string*))
1345 (define-string-name (symbolicate 'define- canonical-name '->string))
1346 (string-name (symbolicate canonical-name '->string))
1347 (->string-aref-name (symbolicate canonical-name '->string-aref)))
1348 `(progn
1349 (define-unibyte-mapper ,->code-name ,code->-name
1350 ,@exceptions)
1351 (declaim (inline ,get-bytes-name))
1352 (defun ,get-bytes-name (string pos)
1353 (declare (optimize speed (safety 0))
1354 (type simple-string string)
1355 (type array-range pos))
1356 (get-latin-bytes #',code->-name ,canonical-name string pos))
1357 (defun ,string->-name (string sstart send null-padding)
1358 (declare (optimize speed (safety 0))
1359 (type simple-string string)
1360 (type array-range sstart send))
1361 (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1362 (defmacro ,define-string*-name (accessor type)
1363 (declare (ignore type))
1364 (let ((name (make-od-name ',string*-name accessor)))
1365 `(progn
1366 (defun ,name (string sstart send array astart aend)
1367 (,(make-od-name 'latin->string* accessor)
1368 string sstart send array astart aend #',',->code-name)))))
1369 (instantiate-octets-definition ,define-string*-name)
1370 (defmacro ,define-string-name (accessor type)
1371 (declare (ignore type))
1372 (let ((name (make-od-name ',string-name accessor)))
1373 `(progn
1374 (defun ,name (array astart aend)
1375 (,(make-od-name 'latin->string accessor)
1376 array astart aend #',',->code-name)))))
1377 (instantiate-octets-definition ,define-string-name)
1378 (define-unibyte-external-format ,canonical-name ,other-names
1379 (let ((octet (,code->-name bits)))
1380 (if octet
1381 (setf (sap-ref-8 sap tail) octet)
1382 (external-format-encoding-error stream bits)))
1383 (let ((code (,->code-name byte)))
1384 (if code
1385 (code-char code)
1386 (return-from decode-break-reason 1)))
1387 ,->string-aref-name
1388 ,string->-name))))
1390 (defmacro define-unibyte-external-format
1391 (canonical-name (&rest other-names)
1392 out-form in-form octets-to-string-symbol string-to-octets-symbol)
1393 `(define-external-format/variable-width (,canonical-name ,@other-names)
1394 t #\? 1
1395 ,out-form
1397 ,in-form
1398 ,octets-to-string-symbol
1399 ,string-to-octets-symbol))
1401 (defmacro define-external-format/variable-width
1402 (external-format output-restart replacement-character
1403 out-size-expr out-expr in-size-expr in-expr
1404 octets-to-string-sym string-to-octets-sym)
1405 (let* ((name (first external-format))
1406 (out-function (symbolicate "OUTPUT-BYTES/" name))
1407 (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1408 (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1409 (in-char-function (symbolicate "INPUT-CHAR/" name))
1410 (resync-function (symbolicate "RESYNC/" name))
1411 (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1412 (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1413 (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1414 (n-buffer (gensym "BUFFER")))
1415 `(progn
1416 (defun ,size-function (byte)
1417 (declare (ignorable byte))
1418 ,out-size-expr)
1419 (defun ,out-function (stream string flush-p start end)
1420 (let ((start (or start 0))
1421 (end (or end (length string))))
1422 (declare (type index start end))
1423 (synchronize-stream-output stream)
1424 (unless (<= 0 start end (length string))
1425 (sequence-bounding-indices-bad-error string start end))
1426 (do ()
1427 ((= end start))
1428 (let ((obuf (fd-stream-obuf stream)))
1429 (string-dispatch (simple-base-string
1430 #!+sb-unicode (simple-array character (*))
1431 string)
1432 string
1433 (let ((len (buffer-length obuf))
1434 (sap (buffer-sap obuf))
1435 ;; FIXME: Rename
1436 (tail (buffer-tail obuf)))
1437 (declare (type index tail)
1438 ;; STRING bounds have already been checked.
1439 (optimize (safety 0)))
1440 (,@(if output-restart
1441 `(catch 'output-nothing)
1442 `(progn))
1443 (do* ()
1444 ((or (= start end) (< (- len tail) 4)))
1445 (let* ((byte (aref string start))
1446 (bits (char-code byte))
1447 (size ,out-size-expr))
1448 ,out-expr
1449 (incf tail size)
1450 (setf (buffer-tail obuf) tail)
1451 (incf start)))
1452 (go flush))
1453 ;; Exited via CATCH: skip the current character.
1454 (incf start))))
1455 flush
1456 (when (< start end)
1457 (flush-output-buffer stream)))
1458 (when flush-p
1459 (flush-output-buffer stream))))
1460 (def-output-routines/variable-width (,format
1461 ,out-size-expr
1462 ,output-restart
1463 ,external-format
1464 (:none character)
1465 (:line character)
1466 (:full character))
1467 (if (eql byte #\Newline)
1468 (setf (fd-stream-char-pos stream) 0)
1469 (incf (fd-stream-char-pos stream)))
1470 (let ((bits (char-code byte))
1471 (sap (buffer-sap obuf))
1472 (tail (buffer-tail obuf)))
1473 ,out-expr))
1474 (defun ,in-function (stream buffer start requested eof-error-p
1475 &aux (total-copied 0))
1476 (declare (type fd-stream stream)
1477 (type index start requested total-copied)
1478 (type
1479 (simple-array character (#.+ansi-stream-in-buffer-length+))
1480 buffer))
1481 (when (fd-stream-eof-forced-p stream)
1482 (setf (fd-stream-eof-forced-p stream) nil)
1483 (return-from ,in-function 0))
1484 (do ((instead (fd-stream-instead stream)))
1485 ((= (fill-pointer instead) 0)
1486 (setf (fd-stream-listen stream) nil))
1487 (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1488 (incf total-copied)
1489 (when (= requested total-copied)
1490 (when (= (fill-pointer instead) 0)
1491 (setf (fd-stream-listen stream) nil))
1492 (return-from ,in-function total-copied)))
1493 (do ()
1494 (nil)
1495 (let* ((ibuf (fd-stream-ibuf stream))
1496 (head (buffer-head ibuf))
1497 (tail (buffer-tail ibuf))
1498 (sap (buffer-sap ibuf))
1499 (decode-break-reason nil))
1500 (declare (type index head tail))
1501 ;; Copy data from stream buffer into user's buffer.
1502 (do ((size nil nil))
1503 ((or (= tail head) (= requested total-copied)))
1504 (setf decode-break-reason
1505 (block decode-break-reason
1506 ,@(when (consp in-size-expr)
1507 `((when (> ,(car in-size-expr) (- tail head))
1508 (return))))
1509 (let ((byte (sap-ref-8 sap head)))
1510 (declare (ignorable byte))
1511 (setq size ,(if (consp in-size-expr) (cadr in-size-expr) in-size-expr))
1512 (when (> size (- tail head))
1513 (return))
1514 (setf (aref buffer (+ start total-copied)) ,in-expr)
1515 (incf total-copied)
1516 (incf head size))
1517 nil))
1518 (setf (buffer-head ibuf) head)
1519 (when decode-break-reason
1520 ;; If we've already read some characters on when the invalid
1521 ;; code sequence is detected, we return immediately. The
1522 ;; handling of the error is deferred until the next call
1523 ;; (where this check will be false). This allows establishing
1524 ;; high-level handlers for decode errors (for example
1525 ;; automatically resyncing in Lisp comments).
1526 (when (plusp total-copied)
1527 (return-from ,in-function total-copied))
1528 (when (stream-decoding-error-and-handle
1529 stream decode-break-reason)
1530 (if eof-error-p
1531 (error 'end-of-file :stream stream)
1532 (return-from ,in-function total-copied)))
1533 ;; we might have been given stuff to use instead, so
1534 ;; we have to return (and trust our caller to know
1535 ;; what to do about TOTAL-COPIED being 0).
1536 (return-from ,in-function total-copied)))
1537 (setf (buffer-head ibuf) head)
1538 ;; Maybe we need to refill the stream buffer.
1539 (cond ( ;; If was data in the stream buffer, we're done.
1540 (plusp total-copied)
1541 (return total-copied))
1542 ( ;; If EOF, we're done in another way.
1543 (or (eq decode-break-reason 'eof)
1544 (null (catch 'eof-input-catcher
1545 (refill-input-buffer stream))))
1546 (if eof-error-p
1547 (error 'end-of-file :stream stream)
1548 (return total-copied)))
1549 ;; Otherwise we refilled the stream buffer, so fall
1550 ;; through into another pass of the loop.
1551 ))))
1552 (def-input-routine/variable-width ,in-char-function (character
1553 ,external-format
1554 ,in-size-expr
1555 sap head)
1556 (let ((byte (sap-ref-8 sap head)))
1557 (declare (ignorable byte))
1558 ,in-expr))
1559 (defun ,resync-function (stream)
1560 (let ((ibuf (fd-stream-ibuf stream))
1561 size)
1562 (catch 'eof-input-catcher
1563 (loop
1564 (incf (buffer-head ibuf))
1565 (input-at-least stream ,(if (consp in-size-expr) (car in-size-expr) `(setq size ,in-size-expr)))
1566 (unless (block decode-break-reason
1567 (let* ((sap (buffer-sap ibuf))
1568 (head (buffer-head ibuf))
1569 (byte (sap-ref-8 sap head)))
1570 (declare (ignorable byte))
1571 ,@(when (consp in-size-expr)
1572 `((setq size ,(cadr in-size-expr))
1573 (input-at-least stream size)))
1574 (setf head (buffer-head ibuf))
1575 ,in-expr)
1576 nil)
1577 (return))))))
1578 (defun ,read-c-string-function (sap element-type)
1579 (declare (type system-area-pointer sap))
1580 (locally
1581 (declare (optimize (speed 3) (safety 0)))
1582 (let* ((stream ,name)
1583 (size 0) (head 0) (byte 0) (char nil)
1584 (decode-break-reason nil)
1585 (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1586 (setf decode-break-reason
1587 (block decode-break-reason
1588 (setf byte (sap-ref-8 sap head)
1589 size ,(if (consp in-size-expr)
1590 (cadr in-size-expr)
1591 in-size-expr)
1592 char ,in-expr)
1593 (incf head size)
1594 nil))
1595 (when decode-break-reason
1596 (c-string-decoding-error
1597 ,name sap head decode-break-reason))
1598 (when (zerop (char-code char))
1599 (return count))))
1600 (string (make-string length :element-type element-type)))
1601 (declare (ignorable stream)
1602 (type index head length) ;; size
1603 (type (unsigned-byte 8) byte)
1604 (type (or null character) char)
1605 (type string string))
1606 (setf head 0)
1607 (dotimes (index length string)
1608 (setf decode-break-reason
1609 (block decode-break-reason
1610 (setf byte (sap-ref-8 sap head)
1611 size ,(if (consp in-size-expr)
1612 (cadr in-size-expr)
1613 in-size-expr)
1614 char ,in-expr)
1615 (incf head size)
1616 nil))
1617 (when decode-break-reason
1618 (c-string-decoding-error
1619 ,name sap head decode-break-reason))
1620 (setf (aref string index) char)))))
1622 (defun ,output-c-string-function (string)
1623 (declare (type simple-string string))
1624 (locally
1625 (declare (optimize (speed 3) (safety 0)))
1626 (let* ((length (length string))
1627 (char-length (make-array (1+ length) :element-type 'index))
1628 (buffer-length
1629 (+ (loop for i of-type index below length
1630 for byte of-type character = (aref string i)
1631 for bits = (char-code byte)
1632 sum (setf (aref char-length i)
1633 (the index ,out-size-expr)) of-type index)
1634 (let* ((byte (code-char 0))
1635 (bits (char-code byte)))
1636 (declare (ignorable byte bits))
1637 (setf (aref char-length length)
1638 (the index ,out-size-expr)))))
1639 (tail 0)
1640 (,n-buffer (make-array buffer-length
1641 :element-type '(unsigned-byte 8)))
1642 stream)
1643 (declare (type index length buffer-length tail)
1644 (type null stream)
1645 (ignorable stream))
1646 (with-pinned-objects (,n-buffer)
1647 (let ((sap (vector-sap ,n-buffer)))
1648 (declare (system-area-pointer sap))
1649 (loop for i of-type index below length
1650 for byte of-type character = (aref string i)
1651 for bits = (char-code byte)
1652 for size of-type index = (aref char-length i)
1653 do (prog1
1654 ,out-expr
1655 (incf tail size)))
1656 (let* ((bits 0)
1657 (byte (code-char bits))
1658 (size (aref char-length length)))
1659 (declare (ignorable bits byte size))
1660 ,out-expr)))
1661 ,n-buffer)))
1663 (let ((entry (%make-external-format
1664 :names ',external-format
1665 :default-replacement-character ,replacement-character
1666 :read-n-chars-fun #',in-function
1667 :read-char-fun #',in-char-function
1668 :write-n-bytes-fun #',out-function
1669 ,@(mapcan #'(lambda (buffering)
1670 (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1671 `#',(intern (format nil format (string buffering)))))
1672 '(:none :line :full))
1673 :resync-fun #',resync-function
1674 :bytes-for-char-fun #',size-function
1675 :read-c-string-fun #',read-c-string-function
1676 :write-c-string-fun #',output-c-string-function
1677 :octets-to-string-fun (lambda (&rest rest)
1678 (declare (dynamic-extent rest))
1679 (apply ',octets-to-string-sym rest))
1680 :string-to-octets-fun (lambda (&rest rest)
1681 (declare (dynamic-extent rest))
1682 (apply ',string-to-octets-sym rest)))))
1683 (dolist (ef ',external-format)
1684 (setf (gethash ef *external-formats*) entry))))))
1686 ;;;; utility functions (misc routines, etc)
1688 ;;; Fill in the various routine slots for the given type. INPUT-P and
1689 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1690 ;;; set prior to calling this routine.
1691 (defun set-fd-stream-routines (fd-stream element-type external-format
1692 input-p output-p buffer-p)
1693 (let* ((target-type (case element-type
1694 (unsigned-byte '(unsigned-byte 8))
1695 (signed-byte '(signed-byte 8))
1696 (:default 'character)
1697 (t element-type)))
1698 (character-stream-p (subtypep target-type 'character))
1699 (bivalent-stream-p (eq element-type :default))
1700 normalized-external-format
1701 char-size
1702 (bin-routine #'ill-bin)
1703 (bin-type nil)
1704 (bin-size nil)
1705 (cin-routine #'ill-in)
1706 (cin-type nil)
1707 (cin-size nil)
1708 (input-type nil) ;calculated from bin-type/cin-type
1709 (input-size nil) ;calculated from bin-size/cin-size
1710 (read-n-characters #'ill-in)
1711 (bout-routine #'ill-bout)
1712 (bout-type nil)
1713 (bout-size nil)
1714 (cout-routine #'ill-out)
1715 (cout-type nil)
1716 (cout-size nil)
1717 (output-type nil)
1718 (output-size nil)
1719 (output-bytes #'ill-bout))
1721 ;; Ensure that we have buffers in the desired direction(s) only,
1722 ;; getting new ones and dropping/resetting old ones as necessary.
1723 (let ((obuf (fd-stream-obuf fd-stream)))
1724 (if output-p
1725 (if obuf
1726 (reset-buffer obuf)
1727 (setf (fd-stream-obuf fd-stream) (get-buffer)))
1728 (when obuf
1729 (setf (fd-stream-obuf fd-stream) nil)
1730 (release-buffer obuf))))
1732 (let ((ibuf (fd-stream-ibuf fd-stream)))
1733 (if input-p
1734 (if ibuf
1735 (reset-buffer ibuf)
1736 (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1737 (when ibuf
1738 (setf (fd-stream-ibuf fd-stream) nil)
1739 (release-buffer ibuf))))
1741 ;; FIXME: Why only for output? Why unconditionally?
1742 (when output-p
1743 (setf (fd-stream-char-pos fd-stream) 0))
1745 (when (and character-stream-p (eq external-format :default))
1746 (/show0 "/getting default external format")
1747 (setf external-format (default-external-format)))
1749 (when input-p
1750 (when (or (not character-stream-p) bivalent-stream-p)
1751 (setf (values bin-routine bin-type bin-size read-n-characters
1752 char-size normalized-external-format)
1753 (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1754 target-type)
1755 external-format))
1756 (unless bin-routine
1757 (error "could not find any input routine for ~S" target-type)))
1758 (when character-stream-p
1759 (setf (values cin-routine cin-type cin-size read-n-characters
1760 char-size normalized-external-format)
1761 (pick-input-routine target-type external-format))
1762 (unless cin-routine
1763 (error "could not find any input routine for ~S" target-type)))
1764 (setf (fd-stream-in fd-stream) cin-routine
1765 (fd-stream-bin fd-stream) bin-routine)
1766 ;; character type gets preferential treatment
1767 (setf input-size (or cin-size bin-size))
1768 (setf input-type (or cin-type bin-type))
1769 (when normalized-external-format
1770 (setf (fd-stream-external-format fd-stream) normalized-external-format
1771 (fd-stream-char-size fd-stream) char-size))
1772 (when (= (or cin-size 1) (or bin-size 1) 1)
1773 (setf (fd-stream-n-bin fd-stream) ;XXX
1774 (if (and character-stream-p (not bivalent-stream-p))
1775 read-n-characters
1776 #'fd-stream-read-n-bytes))
1777 ;; Sometimes turn on fast-read-char/fast-read-byte. Switch on
1778 ;; for character and (unsigned-byte 8) streams. In these
1779 ;; cases, fast-read-* will read from the
1780 ;; ansi-stream-(c)in-buffer, saving function calls.
1781 ;; Otherwise, the various data-reading functions in the stream
1782 ;; structure will be called.
1783 (when (and buffer-p
1784 (not bivalent-stream-p)
1785 ;; temporary disable on :io streams
1786 (not output-p))
1787 (cond (character-stream-p
1788 (setf (ansi-stream-cin-buffer fd-stream)
1789 (make-array +ansi-stream-in-buffer-length+
1790 :element-type 'character)))
1791 ((equal target-type '(unsigned-byte 8))
1792 (setf (ansi-stream-in-buffer fd-stream)
1793 (make-array +ansi-stream-in-buffer-length+
1794 :element-type '(unsigned-byte 8))))))))
1796 (when output-p
1797 (when (or (not character-stream-p) bivalent-stream-p)
1798 (setf (values bout-routine bout-type bout-size output-bytes
1799 char-size normalized-external-format)
1800 (let ((buffering (fd-stream-buffering fd-stream)))
1801 (if bivalent-stream-p
1802 (pick-output-routine '(unsigned-byte 8)
1803 (if (eq :line buffering)
1804 :full
1805 buffering)
1806 external-format)
1807 (pick-output-routine target-type buffering external-format))))
1808 (unless bout-routine
1809 (error "could not find any output routine for ~S buffered ~S"
1810 (fd-stream-buffering fd-stream)
1811 target-type)))
1812 (when character-stream-p
1813 (setf (values cout-routine cout-type cout-size output-bytes
1814 char-size normalized-external-format)
1815 (pick-output-routine target-type
1816 (fd-stream-buffering fd-stream)
1817 external-format))
1818 (unless cout-routine
1819 (error "could not find any output routine for ~S buffered ~S"
1820 (fd-stream-buffering fd-stream)
1821 target-type)))
1822 (when normalized-external-format
1823 (setf (fd-stream-external-format fd-stream) normalized-external-format
1824 (fd-stream-char-size fd-stream) char-size))
1825 (when character-stream-p
1826 (setf (fd-stream-output-bytes fd-stream) output-bytes))
1827 (setf (fd-stream-out fd-stream) cout-routine
1828 (fd-stream-bout fd-stream) bout-routine
1829 (fd-stream-sout fd-stream) (if (eql cout-size 1)
1830 #'fd-sout #'ill-out))
1831 (setf output-size (or cout-size bout-size))
1832 (setf output-type (or cout-type bout-type)))
1834 (when (and input-size output-size
1835 (not (eq input-size output-size)))
1836 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1837 input-type input-size
1838 output-type output-size))
1839 (setf (fd-stream-element-size fd-stream)
1840 (or input-size output-size))
1842 (setf (fd-stream-element-type fd-stream)
1843 (cond ((equal input-type output-type)
1844 input-type)
1845 ((null output-type)
1846 input-type)
1847 ((null input-type)
1848 output-type)
1849 ((subtypep input-type output-type)
1850 input-type)
1851 ((subtypep output-type input-type)
1852 output-type)
1854 (error "Input type (~S) and output type (~S) are unrelated?"
1855 input-type
1856 output-type))))))
1858 ;;; Handles the resource-release aspects of stream closing, and marks
1859 ;;; it as closed.
1860 (defun release-fd-stream-resources (fd-stream)
1861 (handler-case
1862 (without-interrupts
1863 ;; Drop handlers first.
1864 (when (fd-stream-handler fd-stream)
1865 (remove-fd-handler (fd-stream-handler fd-stream))
1866 (setf (fd-stream-handler fd-stream) nil))
1867 ;; Disable interrupts so that a asynch unwind will not leave
1868 ;; us with a dangling finalizer (that would close the same
1869 ;; --possibly reassigned-- FD again), or a stream with a closed
1870 ;; FD that appears open.
1871 (sb!unix:unix-close (fd-stream-fd fd-stream))
1872 (set-closed-flame fd-stream)
1873 (cancel-finalization fd-stream))
1874 ;; On error unwind from WITHOUT-INTERRUPTS.
1875 (serious-condition (e)
1876 (error e)))
1877 ;; Release all buffers. If this is undone, or interrupted,
1878 ;; we're still safe: buffers have finalizers of their own.
1879 (release-fd-stream-buffers fd-stream))
1881 ;;; Flushes the current input buffer and any supplied replacements,
1882 ;;; and returns the input buffer, and the amount of of flushed input
1883 ;;; in bytes.
1884 (defun flush-input-buffer (stream)
1885 (let ((unread (length (fd-stream-instead stream))))
1886 (setf (fill-pointer (fd-stream-instead stream)) 0)
1887 (let ((ibuf (fd-stream-ibuf stream)))
1888 (if ibuf
1889 (let ((head (buffer-head ibuf))
1890 (tail (buffer-tail ibuf)))
1891 (values (reset-buffer ibuf) (- (+ unread tail) head)))
1892 (values nil unread)))))
1894 (defun fd-stream-clear-input (stream)
1895 (flush-input-buffer stream)
1896 #!+win32
1897 (progn
1898 (sb!win32:fd-clear-input (fd-stream-fd stream))
1899 (setf (fd-stream-listen stream) nil))
1900 #!-win32
1901 (catch 'eof-input-catcher
1902 (loop until (sysread-may-block-p stream)
1904 (refill-input-buffer stream)
1905 (reset-buffer (fd-stream-ibuf stream)))
1908 ;;; Handle miscellaneous operations on FD-STREAM.
1909 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1910 (declare (ignore arg2))
1911 (case operation
1912 (:listen
1913 (labels ((do-listen ()
1914 (let ((ibuf (fd-stream-ibuf fd-stream)))
1915 (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1916 (fd-stream-listen fd-stream)
1917 #!+win32
1918 (sb!win32:fd-listen (fd-stream-fd fd-stream))
1919 #!-win32
1920 ;; If the read can block, LISTEN will certainly return NIL.
1921 (if (sysread-may-block-p fd-stream)
1923 ;; Otherwise select(2) and CL:LISTEN have slightly
1924 ;; different semantics. The former returns that an FD
1925 ;; is readable when a read operation wouldn't block.
1926 ;; That includes EOF. However, LISTEN must return NIL
1927 ;; at EOF.
1928 (progn (catch 'eof-input-catcher
1929 ;; r-b/f too calls select, but it shouldn't
1930 ;; block as long as read can return once w/o
1931 ;; blocking
1932 (refill-input-buffer fd-stream))
1933 ;; At this point either IBUF-HEAD != IBUF-TAIL
1934 ;; and FD-STREAM-LISTEN is NIL, in which case
1935 ;; we should return T, or IBUF-HEAD ==
1936 ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1937 ;; which case we should return :EOF for this
1938 ;; call and all future LISTEN call on this stream.
1939 ;; Call ourselves again to determine which case
1940 ;; applies.
1941 (do-listen)))))))
1942 (do-listen)))
1943 (:unread
1944 (decf (buffer-head (fd-stream-ibuf fd-stream))
1945 (fd-stream-character-size fd-stream arg1)))
1946 (:close
1947 ;; Drop input buffers
1948 (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1949 (ansi-stream-cin-buffer fd-stream) nil
1950 (ansi-stream-in-buffer fd-stream) nil)
1951 (cond (arg1
1952 ;; We got us an abort on our hands.
1953 (let ((outputp (fd-stream-obuf fd-stream))
1954 (file (fd-stream-file fd-stream))
1955 (orig (fd-stream-original fd-stream)))
1956 ;; This takes care of the important stuff -- everything
1957 ;; rest is cleaning up the file-system, which we cannot
1958 ;; do on some platforms as long as the file is open.
1959 (release-fd-stream-resources fd-stream)
1960 ;; We can't do anything unless we know what file were
1961 ;; dealing with, and we don't want to do anything
1962 ;; strange unless we were writing to the file.
1963 (when (and outputp file)
1964 (if orig
1965 ;; If the original is EQ to file we are appending to
1966 ;; and can just close the file without renaming.
1967 (unless (eq orig file)
1968 ;; We have a handle on the original, just revert.
1969 (multiple-value-bind (okay err)
1970 (sb!unix:unix-rename orig file)
1971 ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1972 ;; others are SIMPLE-FILE-ERRORS? Surely they should
1973 ;; all be the same?
1974 (unless okay
1975 (error 'simple-stream-error
1976 :format-control
1977 "~@<Couldn't restore ~S to its original contents ~
1978 from ~S while closing ~S: ~2I~_~A~:>"
1979 :format-arguments
1980 (list file orig fd-stream (strerror err))
1981 :stream fd-stream))))
1982 ;; We can't restore the original, and aren't
1983 ;; appending, so nuke that puppy.
1985 ;; FIXME: This is currently the fate of superseded
1986 ;; files, and according to the CLOSE spec this is
1987 ;; wrong. However, there seems to be no clean way to
1988 ;; do that that doesn't involve either copying the
1989 ;; data (bad if the :abort resulted from a full
1990 ;; disk), or renaming the old file temporarily
1991 ;; (probably bad because stream opening becomes more
1992 ;; racy).
1993 (multiple-value-bind (okay err)
1994 (sb!unix:unix-unlink file)
1995 (unless okay
1996 (error 'simple-file-error
1997 :pathname file
1998 :format-control
1999 "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
2000 :format-arguments
2001 (list file fd-stream (strerror err)))))))))
2003 (finish-fd-stream-output fd-stream)
2004 (let ((orig (fd-stream-original fd-stream)))
2005 (when (and orig (fd-stream-delete-original fd-stream))
2006 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
2007 (unless okay
2008 (error 'simple-file-error
2009 :pathname orig
2010 :format-control
2011 "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
2012 :format-arguments
2013 (list orig fd-stream (strerror err)))))))
2014 ;; In case of no-abort close, don't *really* close the
2015 ;; stream until the last moment -- the cleaning up of the
2016 ;; original can be done first.
2017 (release-fd-stream-resources fd-stream))))
2018 (:clear-input
2019 (fd-stream-clear-input fd-stream))
2020 (:force-output
2021 (flush-output-buffer fd-stream))
2022 (:finish-output
2023 (finish-fd-stream-output fd-stream))
2024 (:element-type
2025 (fd-stream-element-type fd-stream))
2026 (:external-format
2027 (fd-stream-external-format fd-stream))
2028 (:interactive-p
2029 (plusp (the (integer 0)
2030 (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2031 (:line-length
2033 (:charpos
2034 (fd-stream-char-pos fd-stream))
2035 (:file-length
2036 (unless (fd-stream-file fd-stream)
2037 ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2038 ;; "should signal an error of type TYPE-ERROR if stream is not
2039 ;; a stream associated with a file". Too bad there's no very
2040 ;; appropriate value for the EXPECTED-TYPE slot..
2041 (error 'simple-type-error
2042 :datum fd-stream
2043 :expected-type 'fd-stream
2044 :format-control "~S is not a stream associated with a file."
2045 :format-arguments (list fd-stream)))
2046 #!-win32
2047 (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2048 atime mtime ctime blksize blocks)
2049 (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2050 (declare (ignore ino nlink uid gid rdev
2051 atime mtime ctime blksize blocks))
2052 (unless okay
2053 (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2054 (if (zerop mode)
2056 (truncate size (fd-stream-element-size fd-stream))))
2057 #!+win32
2058 (let* ((handle (fd-stream-fd fd-stream))
2059 (element-size (fd-stream-element-size fd-stream)))
2060 (multiple-value-bind (got native-size)
2061 (sb!win32:get-file-size-ex handle 0)
2062 (if (zerop got)
2063 ;; Might be a block device, in which case we fall back to
2064 ;; a non-atomic workaround:
2065 (let* ((here (sb!unix:unix-lseek handle 0 sb!unix:l_incr))
2066 (there (sb!unix:unix-lseek handle 0 sb!unix:l_xtnd)))
2067 (when (and here there)
2068 (sb!unix:unix-lseek handle here sb!unix:l_set)
2069 (truncate there element-size)))
2070 (truncate native-size element-size)))))
2071 (:file-string-length
2072 (etypecase arg1
2073 (character (fd-stream-character-size fd-stream arg1))
2074 (string (fd-stream-string-size fd-stream arg1))))
2075 (:file-position
2076 (if arg1
2077 (fd-stream-set-file-position fd-stream arg1)
2078 (fd-stream-get-file-position fd-stream)))))
2080 ;; FIXME: Think about this.
2082 ;; (defun finish-fd-stream-output (fd-stream)
2083 ;; (let ((timeout (fd-stream-timeout fd-stream)))
2084 ;; (loop while (fd-stream-output-queue fd-stream)
2085 ;; ;; FIXME: SIGINT while waiting for a timeout will
2086 ;; ;; cause a timeout here.
2087 ;; do (when (and (not (serve-event timeout)) timeout)
2088 ;; (signal-timeout 'io-timeout
2089 ;; :stream fd-stream
2090 ;; :direction :write
2091 ;; :seconds timeout)))))
2093 (defun finish-fd-stream-output (stream)
2094 (flush-output-buffer stream)
2095 (do ()
2096 ((null (fd-stream-output-queue stream)))
2097 (aver (fd-stream-serve-events stream))
2098 (serve-all-events)))
2100 (defun fd-stream-get-file-position (stream)
2101 (declare (fd-stream stream))
2102 (without-interrupts
2103 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2104 (declare (type (or (alien sb!unix:unix-offset) null) posn))
2105 ;; We used to return NIL for errno==ESPIPE, and signal an error
2106 ;; in other failure cases. However, CLHS says to return NIL if
2107 ;; the position cannot be determined -- so that's what we do.
2108 (when (integerp posn)
2109 ;; Adjust for buffered output: If there is any output
2110 ;; buffered, the *real* file position will be larger
2111 ;; than reported by lseek() because lseek() obviously
2112 ;; cannot take into account output we have not sent
2113 ;; yet.
2114 (dolist (buffer (fd-stream-output-queue stream))
2115 (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2116 (let ((obuf (fd-stream-obuf stream)))
2117 (when obuf
2118 (incf posn (buffer-tail obuf))))
2119 ;; Adjust for unread input: If there is any input
2120 ;; read from UNIX but not supplied to the user of the
2121 ;; stream, the *real* file position will smaller than
2122 ;; reported, because we want to look like the unread
2123 ;; stuff is still available.
2124 (let ((ibuf (fd-stream-ibuf stream)))
2125 (when ibuf
2126 (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2127 ;; Divide bytes by element size.
2128 (truncate posn (fd-stream-element-size stream))))))
2130 (defun fd-stream-set-file-position (stream position-spec)
2131 (declare (fd-stream stream))
2132 (check-type position-spec
2133 (or (alien sb!unix:unix-offset) (member nil :start :end))
2134 "valid file position designator")
2135 (tagbody
2136 :again
2137 ;; Make sure we don't have any output pending, because if we
2138 ;; move the file pointer before writing this stuff, it will be
2139 ;; written in the wrong location.
2140 (finish-fd-stream-output stream)
2141 ;; Disable interrupts so that interrupt handlers doing output
2142 ;; won't screw us.
2143 (without-interrupts
2144 (unless (fd-stream-output-finished-p stream)
2145 ;; We got interrupted and more output came our way during
2146 ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2147 ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2148 ;; so we prefer to do things like this...
2149 (go :again))
2150 ;; Clear out any pending input to force the next read to go to
2151 ;; the disk.
2152 (flush-input-buffer stream)
2153 ;; Trash cached value for listen, so that we check next time.
2154 (setf (fd-stream-listen stream) nil)
2155 ;; Now move it.
2156 (multiple-value-bind (offset origin)
2157 (case position-spec
2158 (:start
2159 (values 0 sb!unix:l_set))
2160 (:end
2161 (values 0 sb!unix:l_xtnd))
2163 (values (* position-spec (fd-stream-element-size stream))
2164 sb!unix:l_set)))
2165 (declare (type (alien sb!unix:unix-offset) offset))
2166 (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2167 offset origin)))
2168 ;; CLHS says to return true if the file-position was set
2169 ;; succesfully, and NIL otherwise. We are to signal an error
2170 ;; only if the given position was out of bounds, and that is
2171 ;; dealt with above. In times past we used to return NIL for
2172 ;; errno==ESPIPE, and signal an error in other cases.
2174 ;; FIXME: We are still liable to signal an error if flushing
2175 ;; output fails.
2176 (return-from fd-stream-set-file-position
2177 (typep posn '(alien sb!unix:unix-offset))))))))
2180 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2182 ;;; Create a stream for the given Unix file descriptor.
2184 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2185 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2186 ;;; default to allowing input.
2188 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2190 ;;; BUFFERING indicates the kind of buffering to use.
2192 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2193 ;;; NIL (the default), then wait forever. When we time out, we signal
2194 ;;; IO-TIMEOUT.
2196 ;;; FILE is the name of the file (will be returned by PATHNAME).
2198 ;;; NAME is used to identify the stream when printed.
2200 ;;; If SERVE-EVENTS is true, SERVE-EVENT machinery is used to
2201 ;;; handle blocking IO on the stream.
2202 (defun make-fd-stream (fd
2203 &key
2204 (input nil input-p)
2205 (output nil output-p)
2206 (element-type 'base-char)
2207 (buffering :full)
2208 (external-format :default)
2209 serve-events
2210 timeout
2211 file
2212 original
2213 delete-original
2214 pathname
2215 input-buffer-p
2216 dual-channel-p
2217 (name (if file
2218 (format nil "file ~A" file)
2219 (format nil "descriptor ~W" fd)))
2220 auto-close)
2221 (declare (type index fd) (type (or real null) timeout)
2222 (type (member :none :line :full) buffering))
2223 (cond ((not (or input-p output-p))
2224 (setf input t))
2225 ((not (or input output))
2226 (error "File descriptor must be opened either for input or output.")))
2227 (let ((stream (%make-fd-stream :fd fd
2228 :fd-type
2229 #!-win32 (sb!unix:fd-type fd)
2230 ;; KLUDGE.
2231 #!+win32 (if serve-events
2232 :unknown
2233 :regular)
2234 :name name
2235 :file file
2236 :original original
2237 :delete-original delete-original
2238 :pathname pathname
2239 :buffering buffering
2240 :dual-channel-p dual-channel-p
2241 :bivalent-p (eq element-type :default)
2242 :serve-events serve-events
2243 :timeout
2244 (if timeout
2245 (coerce timeout 'single-float)
2246 nil))))
2247 (set-fd-stream-routines stream element-type external-format
2248 input output input-buffer-p)
2249 (when auto-close
2250 (finalize stream
2251 (lambda ()
2252 (sb!unix:unix-close fd)
2253 #!+sb-show
2254 (format *terminal-io* "** closed file descriptor ~W **~%"
2255 fd))
2256 :dont-save t))
2257 stream))
2259 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2260 ;;; :RENAME-AND-DELETE and :RENAME options.
2261 (defun pick-backup-name (name)
2262 (declare (type simple-string name))
2263 (concatenate 'simple-string name ".bak"))
2265 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2266 ;;; access, since we don't want to trash unwritable files even if we
2267 ;;; technically can. We return true if we succeed in renaming.
2268 (defun rename-the-old-one (namestring original)
2269 (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2270 (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2271 (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2272 (if okay
2274 (error 'simple-file-error
2275 :pathname namestring
2276 :format-control
2277 "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2278 :format-arguments (list namestring original (strerror err))))))
2280 (defun open (filename
2281 &key
2282 (direction :input)
2283 (element-type 'base-char)
2284 (if-exists nil if-exists-given)
2285 (if-does-not-exist nil if-does-not-exist-given)
2286 (external-format :default)
2287 &aux ; Squelch assignment warning.
2288 (direction direction)
2289 (if-does-not-exist if-does-not-exist)
2290 (if-exists if-exists))
2291 #!+sb-doc
2292 "Return a stream which reads from or writes to FILENAME.
2293 Defined keywords:
2294 :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2295 :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2296 :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2297 :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2298 :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2299 See the manual for details."
2301 ;; Calculate useful stuff.
2302 (multiple-value-bind (input output mask)
2303 (ecase direction
2304 (:input (values t nil sb!unix:o_rdonly))
2305 (:output (values nil t sb!unix:o_wronly))
2306 (:io (values t t sb!unix:o_rdwr))
2307 (:probe (values t nil sb!unix:o_rdonly)))
2308 (declare (type index mask))
2309 (let* ( ;; PATHNAME is the pathname we associate with the stream.
2310 (pathname (merge-pathnames filename))
2311 (physical (physicalize-pathname pathname))
2312 (truename (probe-file physical))
2313 ;; NAMESTRING is the native namestring we open the file with.
2314 (namestring (cond (truename
2315 (native-namestring truename :as-file t))
2316 ((or (not input)
2317 (and input (eq if-does-not-exist :create))
2318 (and (eq direction :io)
2319 (not if-does-not-exist-given)))
2320 (native-namestring physical :as-file t)))))
2321 (flet ((open-error (format-control &rest format-arguments)
2322 (error 'simple-file-error
2323 :pathname pathname
2324 :format-control format-control
2325 :format-arguments format-arguments)))
2326 ;; Process if-exists argument if we are doing any output.
2327 (cond (output
2328 (unless if-exists-given
2329 (setf if-exists
2330 (if (eq (pathname-version pathname) :newest)
2331 :new-version
2332 :error)))
2333 (case if-exists
2334 ((:new-version :error nil)
2335 (setf mask (logior mask sb!unix:o_excl)))
2336 ((:rename :rename-and-delete)
2337 (setf mask (logior mask sb!unix:o_creat)))
2338 ((:supersede)
2339 (setf mask (logior mask sb!unix:o_trunc)))
2340 (:append
2341 (setf mask (logior mask sb!unix:o_append)))))
2343 (setf if-exists :ignore-this-arg)))
2345 (unless if-does-not-exist-given
2346 (setf if-does-not-exist
2347 (cond ((eq direction :input) :error)
2348 ((and output
2349 (member if-exists '(:overwrite :append)))
2350 :error)
2351 ((eq direction :probe)
2352 nil)
2354 :create))))
2355 (cond ((and if-exists-given
2356 truename
2357 (eq if-exists :new-version))
2358 (open-error "OPEN :IF-EXISTS :NEW-VERSION is not supported ~
2359 when a new version must be created."))
2360 ((eq if-does-not-exist :create)
2361 (setf mask (logior mask sb!unix:o_creat)))
2362 ((not (member if-exists '(:error nil))))
2363 ;; Both if-does-not-exist and if-exists now imply
2364 ;; that there will be no opening of files, and either
2365 ;; an error would be signalled, or NIL returned
2366 ((and (not if-exists) (not if-does-not-exist))
2367 (return-from open))
2368 ((and if-exists if-does-not-exist)
2369 (open-error "OPEN :IF-DOES-NOT-EXIST ~s ~
2370 :IF-EXISTS ~s will always signal an error."
2371 if-does-not-exist if-exists))
2372 (truename
2373 (if if-exists
2374 (open-error "File exists ~s." pathname)
2375 (return-from open)))
2376 (if-does-not-exist
2377 (open-error "File does not exist ~s." pathname))
2379 (return-from open)))
2380 (let ((original (case if-exists
2381 ((:rename :rename-and-delete)
2382 (pick-backup-name namestring))
2383 ((:append :overwrite)
2384 ;; KLUDGE: Prevent CLOSE from deleting
2385 ;; appending streams when called with :ABORT T
2386 namestring)))
2387 (delete-original (eq if-exists :rename-and-delete))
2388 (mode #o666))
2389 (when (and original (not (eq original namestring)))
2390 ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2391 ;; whether the file already exists, make sure the original
2392 ;; file is not a directory, and keep the mode.
2393 (let ((exists
2394 (and namestring
2395 (multiple-value-bind (okay err/dev inode orig-mode)
2396 (sb!unix:unix-stat namestring)
2397 (declare (ignore inode)
2398 (type (or index null) orig-mode))
2399 (cond
2400 (okay
2401 (when (and output (= (logand orig-mode #o170000)
2402 #o40000))
2403 (error 'simple-file-error
2404 :pathname pathname
2405 :format-control
2406 "can't open ~S for output: is a directory"
2407 :format-arguments (list namestring)))
2408 (setf mode (logand orig-mode #o777))
2410 ((eql err/dev sb!unix:enoent)
2411 nil)
2413 (simple-file-perror "can't find ~S"
2414 namestring
2415 err/dev)))))))
2416 (unless (and exists
2417 (rename-the-old-one namestring original))
2418 (setf original nil)
2419 (setf delete-original nil)
2420 ;; In order to use :SUPERSEDE instead, we have to make
2421 ;; sure SB!UNIX:O_CREAT corresponds to
2422 ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2423 ;; because of IF-EXISTS being :RENAME.
2424 (unless (eq if-does-not-exist :create)
2425 (setf mask
2426 (logior (logandc2 mask sb!unix:o_creat)
2427 sb!unix:o_trunc)))
2428 (setf if-exists :supersede))))
2430 ;; Now we can try the actual Unix open(2).
2431 (multiple-value-bind (fd errno)
2432 (if namestring
2433 (sb!unix:unix-open namestring mask mode)
2434 (values nil sb!unix:enoent))
2435 (flet ((vanilla-open-error ()
2436 (simple-file-perror "error opening ~S" pathname errno)))
2437 (cond ((numberp fd)
2438 (case direction
2439 ((:input :output :io)
2440 ;; For O_APPEND opened files, lseek returns 0 until first write.
2441 ;; So we jump ahead here.
2442 (when (eq if-exists :append)
2443 (sb!unix:unix-lseek fd 0 sb!unix:l_xtnd))
2444 (make-fd-stream fd
2445 :input input
2446 :output output
2447 :element-type element-type
2448 :external-format external-format
2449 :file namestring
2450 :original original
2451 :delete-original delete-original
2452 :pathname pathname
2453 :dual-channel-p nil
2454 :serve-events nil
2455 :input-buffer-p t
2456 :auto-close t))
2457 (:probe
2458 (let ((stream
2459 (%make-fd-stream :name namestring
2460 :fd fd
2461 :pathname pathname
2462 :element-type element-type)))
2463 (close stream)
2464 stream))))
2465 ((eql errno sb!unix:enoent)
2466 (case if-does-not-exist
2467 (:error (vanilla-open-error))
2468 (:create
2469 (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2470 pathname))
2471 (t nil)))
2472 ((and (eql errno sb!unix:eexist) (null if-exists))
2473 nil)
2475 (vanilla-open-error))))))))))
2477 ;;;; initialization
2479 ;;; the stream connected to the controlling terminal, or NIL if there is none
2480 (defvar *tty*)
2482 ;;; the stream connected to the standard input (file descriptor 0)
2483 (defvar *stdin*)
2485 ;;; the stream connected to the standard output (file descriptor 1)
2486 (defvar *stdout*)
2488 ;;; the stream connected to the standard error output (file descriptor 2)
2489 (defvar *stderr*)
2491 ;;; This is called when the cold load is first started up, and may also
2492 ;;; be called in an attempt to recover from nested errors.
2493 (defun stream-cold-init-or-reset ()
2494 ;; FIXME: on gencgc the 4 standard fd-streams {stdin,stdout,stderr,tty}
2495 ;; and these synonym streams are baked into +pseudo-static-generation+.
2496 ;; Is that inadvertent?
2497 (stream-reinit)
2498 (setf *terminal-io* (make-synonym-stream '*tty*))
2499 (setf *standard-output* (make-synonym-stream '*stdout*))
2500 (setf *standard-input* (make-synonym-stream '*stdin*))
2501 (setf *error-output* (make-synonym-stream '*stderr*))
2502 (setf *query-io* (make-synonym-stream '*terminal-io*))
2503 (setf *debug-io* *query-io*)
2504 (setf *trace-output* *standard-output*)
2505 (values))
2507 (defun stream-deinit ()
2508 ;; Unbind to make sure we're not accidently dealing with it
2509 ;; before we're ready (or after we think it's been deinitialized).
2510 (with-available-buffers-lock ()
2511 (without-package-locks
2512 (makunbound '*available-buffers*))))
2514 (defun stdstream-external-format (fd outputp)
2515 #!-win32 (declare (ignore fd outputp))
2516 (let* ((keyword #!+win32 (if (and (/= fd -1)
2517 (logbitp 0 fd)
2518 (logbitp 1 fd))
2519 :ucs-2
2520 (if outputp
2521 (sb!win32::console-output-codepage)
2522 (sb!win32::console-input-codepage)))
2523 #!-win32 (default-external-format))
2524 (ef (get-external-format keyword))
2525 (replacement (ef-default-replacement-character ef)))
2526 `(,keyword :replacement ,replacement)))
2528 ;;; This is called whenever a saved core is restarted.
2529 (defun stream-reinit (&optional init-buffers-p)
2530 (when init-buffers-p
2531 (with-available-buffers-lock ()
2532 (aver (not (boundp '*available-buffers*)))
2533 (setf *available-buffers* nil)))
2534 (with-output-to-string (*error-output*)
2535 (multiple-value-bind (in out err)
2536 #!-win32 (values 0 1 2)
2537 #!+win32 (sb!win32::get-std-handles)
2538 (labels (#!+win32
2539 (nul-stream (name inputp outputp)
2540 (let* ((nul-name #.(coerce "NUL" 'simple-base-string))
2541 (nul-handle
2542 (cond
2543 ((and inputp outputp)
2544 (sb!win32:unixlike-open nul-name sb!unix:o_rdwr 0))
2545 (inputp
2546 (sb!win32:unixlike-open nul-name sb!unix:o_rdonly 0))
2547 (outputp
2548 (sb!win32:unixlike-open nul-name sb!unix:o_wronly 0))
2550 ;; Not quite sure what to do in this case.
2551 nil))))
2552 (make-fd-stream
2553 nul-handle
2554 :name name
2555 :input inputp
2556 :output outputp
2557 :buffering :line
2558 :element-type :default
2559 :serve-events inputp
2560 :auto-close t
2561 :external-format (stdstream-external-format nul-handle outputp))))
2562 (stdio-stream (handle name inputp outputp)
2563 (cond
2564 #!+win32
2565 ((null handle)
2566 ;; If no actual handle was present, create a stream to NUL
2567 (nul-stream name inputp outputp))
2569 (make-fd-stream
2570 handle
2571 :name name
2572 :input inputp
2573 :output outputp
2574 :buffering :line
2575 :element-type :default
2576 :serve-events inputp
2577 :external-format (stdstream-external-format handle outputp))))))
2578 (setf *stdin* (stdio-stream in "standard input" t nil)
2579 *stdout* (stdio-stream out "standard output" nil t)
2580 *stderr* (stdio-stream err "standard error" nil t))))
2581 #!+win32
2582 (setf *tty* (make-two-way-stream *stdin* *stdout*))
2583 #!-win32
2584 ;; FIXME: what is this call to COERCE doing? XC can't dump non-base-strings.
2585 (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2586 (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2587 (setf *tty*
2588 (if tty
2589 (make-fd-stream tty :name "the terminal"
2590 :input t :output t :buffering :line
2591 :external-format (stdstream-external-format
2592 tty t)
2593 :serve-events t
2594 :auto-close t)
2595 (make-two-way-stream *stdin* *stdout*))))
2596 (princ (get-output-stream-string *error-output*) *stderr*))
2597 (values))
2599 ;;;; miscellany
2601 ;;; the Unix way to beep
2602 (defun beep (stream)
2603 (write-char (code-char bell-char-code) stream)
2604 (finish-output stream))
2606 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2607 ;;; by the filesys stuff to get and set the file name.
2609 ;;; FIXME: misleading name, screwy interface
2610 (defun file-name (stream &optional new-name)
2611 (when (typep stream 'fd-stream)
2612 (cond (new-name
2613 (setf (fd-stream-pathname stream) new-name)
2614 (setf (fd-stream-file stream)
2615 (native-namestring (physicalize-pathname new-name)
2616 :as-file t))
2619 (fd-stream-pathname stream)))))
2621 ;; Placing this definition (formerly in "toplevel") after the important
2622 ;; stream types are known produces smaller+faster code than it did before.
2623 (defun stream-output-stream (stream)
2624 (typecase stream
2625 (fd-stream
2626 stream)
2627 (synonym-stream
2628 (stream-output-stream
2629 (symbol-value (synonym-stream-symbol stream))))
2630 (two-way-stream
2631 (stream-output-stream
2632 (two-way-stream-output-stream stream)))
2634 stream)))
2636 ;; Using (get-std-handle-or-null +std-error-handle+) instead of the file
2637 ;; descriptor might make this work on win32, but I don't know.
2638 #!-win32
2639 (macrolet ((stderr () 2))
2640 (!defglobal !*cold-stderr-buf* " ")
2641 (defun !make-cold-stderr-stream ()
2642 (%make-fd-stream
2643 :out (lambda (stream ch)
2644 (declare (ignore stream))
2645 (let ((b (truly-the (simple-base-string 1) !*cold-stderr-buf*)))
2646 (setf (char b 0) ch)
2647 (sb!unix:unix-write (stderr) b 0 1)))
2648 :sout (lambda (stream string start end)
2649 (declare (ignore stream))
2650 (flet ((out (s start len)
2651 (sb!unix:unix-write (stderr) s start len)))
2652 (if (typep string 'simple-base-string)
2653 (out string start (- end start))
2654 (let ((n (- end start)))
2655 ;; will croak if there is any non-BASE-CHAR in the string
2656 (out (replace (make-array n :element-type 'base-char)
2657 string :start2 start) 0 n)))))
2658 :misc (constantly nil))))