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