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