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