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