1.0.32.21: compress most unibyte-external-format definitions
[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   (read-n-chars-fun (missing-arg) :type function)
758   (read-char-fun (missing-arg) :type function)
759   (write-n-bytes-fun (missing-arg) :type function)
760   (write-char-none-buffered-fun (missing-arg) :type function)
761   (write-char-line-buffered-fun (missing-arg) :type function)
762   (write-char-full-buffered-fun (missing-arg) :type function)
763   ;; Can be nil for fixed-width formats.
764   (resync-fun nil :type (or function null))
765   (bytes-for-char-fun (missing-arg) :type function)
766   (read-c-string-fun (missing-arg) :type function)
767   (write-c-string-fun (missing-arg) :type function)
768   ;; We indirect through symbols in these functions so that a
769   ;; developer working on the octets code can easily redefine things
770   ;; and use the new function definition without redefining the
771   ;; external format as well.  The slots above don't do any
772   ;; indirection because a developer working with those slots would be
773   ;; redefining the external format anyway.
774   (octets-to-string-fun (missing-arg) :type function)
775   (string-to-octets-fun (missing-arg) :type function))
776
777 (defun wrap-external-format-functions (external-format fun)
778   (let ((result (%copy-external-format external-format)))
779     (macrolet ((frob (accessor)
780                  `(setf (,accessor result) (funcall fun (,accessor result)))))
781       (frob ef-read-n-chars-fun)
782       (frob ef-read-char-fun)
783       (frob ef-write-n-bytes-fun)
784       (frob ef-write-char-none-buffered-fun)
785       (frob ef-write-char-line-buffered-fun)
786       (frob ef-write-char-full-buffered-fun)
787       (frob ef-resync-fun)
788       (frob ef-bytes-for-char-fun)
789       (frob ef-read-c-string-fun)
790       (frob ef-write-c-string-fun)
791       (frob ef-octets-to-string-fun)
792       (frob ef-string-to-octets-fun))
793     result))
794
795 (defvar *external-formats* (make-hash-table)
796   #!+sb-doc
797   "Hashtable of all available external formats. The table maps from
798   external-format names to EXTERNAL-FORMAT structures.")
799
800 (defun get-external-format (external-format)
801   (flet ((keyword-external-format (keyword)
802            (declare (type keyword keyword))
803            (gethash keyword *external-formats*))
804          (replacement-handlerify (entry replacement)
805            (when entry
806              (wrap-external-format-functions
807               entry
808               (lambda (fun)
809                 (and fun
810                      (lambda (&rest rest)
811                        (declare (dynamic-extent rest))
812                        (handler-bind
813                            ((stream-decoding-error
814                              (lambda (c)
815                                (declare (ignore c))
816                                (invoke-restart 'input-replacement replacement)))
817                             (stream-encoding-error
818                              (lambda (c)
819                                (declare (ignore c))
820                                (invoke-restart 'output-replacement replacement)))
821                             (octets-encoding-error
822                              (lambda (c) (use-value replacement c)))
823                             (octet-decoding-error
824                              (lambda (c) (use-value replacement c))))
825                          (apply fun rest)))))))))
826     (typecase external-format
827       (keyword (keyword-external-format external-format))
828       ((cons keyword)
829        (let ((entry (keyword-external-format (car external-format)))
830              (replacement (getf (cdr external-format) :replacement)))
831          (if replacement
832              (replacement-handlerify entry replacement)
833              entry))))))
834
835 (defun get-external-format-or-lose (external-format)
836   (or (get-external-format external-format)
837       (error "Undefined external-format ~A" external-format)))
838
839 (defun external-format-keyword (external-format)
840   (typecase external-format
841     (keyword external-format)
842     ((cons keyword) (car external-format))))
843
844 (defun fd-stream-external-format-keyword (stream)
845   (external-format-keyword (fd-stream-external-format stream)))
846
847 (defun canonize-external-format (external-format entry)
848   (typecase external-format
849     (keyword (first (ef-names entry)))
850     ((cons keyword) (cons (first (ef-names entry)) (rest external-format)))))
851
852 ;;; Find an output routine to use given the type and buffering. Return
853 ;;; as multiple values the routine, the real type transfered, and the
854 ;;; number of bytes per element.
855 (defun pick-output-routine (type buffering &optional external-format)
856   (when (subtypep type 'character)
857     (let ((entry (get-external-format external-format)))
858       (when entry
859         (return-from pick-output-routine
860           (values (ecase buffering
861                     (:none (ef-write-char-none-buffered-fun entry))
862                     (:line (ef-write-char-line-buffered-fun entry))
863                     (:full (ef-write-char-full-buffered-fun entry)))
864                   'character
865                   1
866                   (ef-write-n-bytes-fun entry)
867                   (canonize-external-format external-format entry))))))
868   (dolist (entry *output-routines*)
869     (when (and (subtypep type (first entry))
870                (eq buffering (second entry))
871                (or (not (fifth entry))
872                    (eq external-format (fifth entry))))
873       (return-from pick-output-routine
874         (values (symbol-function (third entry))
875                 (first entry)
876                 (fourth entry)))))
877   ;; KLUDGE: dealing with the buffering here leads to excessive code
878   ;; explosion.
879   ;;
880   ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
881   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
882         if (subtypep type `(unsigned-byte ,i))
883         do (return-from pick-output-routine
884              (values
885               (ecase buffering
886                 (:none
887                  (lambda (stream byte)
888                    (output-wrapper (stream (/ i 8) (:none) nil)
889                      (loop for j from 0 below (/ i 8)
890                            do (setf (sap-ref-8 (buffer-sap obuf)
891                                                (+ j tail))
892                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
893                 (:full
894                  (lambda (stream byte)
895                    (output-wrapper (stream (/ i 8) (:full) nil)
896                      (loop for j from 0 below (/ i 8)
897                            do (setf (sap-ref-8 (buffer-sap obuf)
898                                                (+ j tail))
899                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
900               `(unsigned-byte ,i)
901               (/ i 8))))
902   (loop for i from 40 by 8 to 1024 ; ARB (KLUDGE)
903         if (subtypep type `(signed-byte ,i))
904         do (return-from pick-output-routine
905              (values
906               (ecase buffering
907                 (:none
908                  (lambda (stream byte)
909                    (output-wrapper (stream (/ i 8) (:none) nil)
910                      (loop for j from 0 below (/ i 8)
911                            do (setf (sap-ref-8 (buffer-sap obuf)
912                                                (+ j tail))
913                                     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
914                 (:full
915                  (lambda (stream byte)
916                    (output-wrapper (stream (/ i 8) (:full) nil)
917                      (loop for j from 0 below (/ i 8)
918                            do (setf (sap-ref-8 (buffer-sap obuf)
919                                                (+ j tail))
920                                     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
921               `(signed-byte ,i)
922               (/ i 8)))))
923 \f
924 ;;;; input routines and related noise
925
926 ;;; a list of all available input routines. Each element is a list of
927 ;;; the element-type input, the function name, and the number of bytes
928 ;;; per element.
929 (defvar *input-routines* ())
930
931 ;;; Return whether a primitive partial read operation on STREAM's FD
932 ;;; would (probably) block.  Signal a `simple-stream-error' if the
933 ;;; system call implementing this operation fails.
934 ;;;
935 ;;; It is "may" instead of "would" because "would" is not quite
936 ;;; correct on win32.  However, none of the places that use it require
937 ;;; further assurance than "may" versus "will definitely not".
938 (defun sysread-may-block-p (stream)
939   #!+win32
940   ;; This answers T at EOF on win32, I think.
941   (not (sb!win32:fd-listen (fd-stream-fd stream)))
942   #!-win32
943   (sb!unix:with-restarted-syscall (count errno)
944     (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
945       (sb!unix:fd-zero read-fds)
946       (sb!unix:fd-set (fd-stream-fd stream) read-fds)
947       (sb!unix:unix-fast-select (1+ (fd-stream-fd stream))
948                                 (sb!alien:addr read-fds)
949                                 nil nil 0 0))
950     (case count
951       ((1) nil)
952       ((0) t)
953       (otherwise
954        (simple-stream-perror "couldn't check whether ~S is readable"
955                              stream
956                              errno)))))
957
958 ;;; If the read would block wait (using SERVE-EVENT) till input is available,
959 ;;; then fill the input buffer, and return the number of bytes read. Throws
960 ;;; to EOF-INPUT-CATCHER if the eof was reached.
961 (defun refill-input-buffer (stream)
962   (dx-let ((fd (fd-stream-fd stream))
963            (errno 0)
964            (count 0))
965     (tagbody
966        ;; Check for blocking input before touching the stream, as if
967        ;; we happen to wait we are liable to be interrupted, and the
968        ;; interrupt handler may use the same stream.
969        (if (sysread-may-block-p stream)
970            (go :wait-for-input)
971            (go :main))
972        ;; These (:CLOSED-FLAME and :READ-ERROR) tags are here so what
973        ;; we can signal errors outside the WITHOUT-INTERRUPTS.
974      :closed-flame
975        (closed-flame stream)
976      :read-error
977        (simple-stream-perror "couldn't read from ~S" stream errno)
978      :wait-for-input
979        ;; This tag is here so we can unwind outside the WITHOUT-INTERRUPTS
980        ;; to wait for input if read tells us EWOULDBLOCK.
981        (unless (wait-until-fd-usable fd :input (fd-stream-timeout stream))
982          (signal-timeout 'io-timeout :stream stream :direction :read
983                          :seconds (fd-stream-timeout stream)))
984      :main
985        ;; Since the read should not block, we'll disable the
986        ;; interrupts here, so that we don't accidentally unwind and
987        ;; leave the stream in an inconsistent state.
988
989        ;; Execute the nlx outside without-interrupts to ensure the
990        ;; resulting thunk is stack-allocatable.
991        ((lambda (return-reason)
992           (ecase return-reason
993             ((nil))             ; fast path normal cases
994             ((:wait-for-input) (go :wait-for-input))
995             ((:closed-flame)   (go :closed-flame))
996             ((:read-error)     (go :read-error))))
997         (without-interrupts
998           ;; Check the buffer: if it is null, then someone has closed
999           ;; the stream from underneath us. This is not ment to fix
1000           ;; multithreaded races, but to deal with interrupt handlers
1001           ;; closing the stream.
1002           (block nil
1003             (prog1 nil
1004               (let* ((ibuf (or (fd-stream-ibuf stream) (return :closed-flame)))
1005                      (sap (buffer-sap ibuf))
1006                      (length (buffer-length ibuf))
1007                      (head (buffer-head ibuf))
1008                      (tail (buffer-tail ibuf)))
1009                 (declare (index length head tail)
1010                          (inline sb!unix:unix-read))
1011                 (unless (zerop head)
1012                   (cond ((eql head tail)
1013                          ;; Buffer is empty, but not at yet reset -- make it so.
1014                          (setf head 0
1015                                tail 0)
1016                          (reset-buffer ibuf))
1017                         (t
1018                          ;; Buffer has things in it, but they are not at the
1019                          ;; head -- move them there.
1020                          (let ((n (- tail head)))
1021                            (system-area-ub8-copy sap head sap 0 n)
1022                            (setf head 0
1023                                  (buffer-head ibuf) head
1024                                  tail n
1025                                  (buffer-tail ibuf) tail)))))
1026                 (setf (fd-stream-listen stream) nil)
1027                 (setf (values count errno)
1028                       (sb!unix:unix-read fd (sap+ sap tail) (- length tail)))
1029                 (cond ((null count)
1030                        #!+win32
1031                        (return :read-error)
1032                        #!-win32
1033                        (if (eql errno sb!unix:ewouldblock)
1034                            (return :wait-for-input)
1035                            (return :read-error)))
1036                       ((zerop count)
1037                        (setf (fd-stream-listen stream) :eof)
1038                        (/show0 "THROWing EOF-INPUT-CATCHER")
1039                        (throw 'eof-input-catcher nil))
1040                       (t
1041                        ;; Success! (Do not use INCF, for sake of other threads.)
1042                        (setf (buffer-tail ibuf) (+ count tail))))))))))
1043     count))
1044
1045 ;;; Make sure there are at least BYTES number of bytes in the input
1046 ;;; buffer. Keep calling REFILL-INPUT-BUFFER until that condition is met.
1047 (defmacro input-at-least (stream bytes)
1048   (let ((stream-var (gensym "STREAM"))
1049         (bytes-var (gensym "BYTES"))
1050         (buffer-var (gensym "IBUF")))
1051     `(let* ((,stream-var ,stream)
1052             (,bytes-var ,bytes)
1053             (,buffer-var (fd-stream-ibuf ,stream-var)))
1054        (loop
1055          (when (>= (- (buffer-tail ,buffer-var)
1056                       (buffer-head ,buffer-var))
1057                    ,bytes-var)
1058            (return))
1059          (refill-input-buffer ,stream-var)))))
1060
1061 (defmacro input-wrapper/variable-width ((stream bytes eof-error eof-value)
1062                                         &body read-forms)
1063   (let ((stream-var (gensym "STREAM"))
1064         (retry-var (gensym "RETRY"))
1065         (element-var (gensym "ELT")))
1066     `(let* ((,stream-var ,stream)
1067             (ibuf (fd-stream-ibuf ,stream-var))
1068             (size nil))
1069        (block use-instead
1070          (when (fd-stream-eof-forced-p ,stream-var)
1071            (setf (fd-stream-eof-forced-p ,stream-var) nil)
1072            (return-from use-instead
1073              (eof-or-lose ,stream-var ,eof-error ,eof-value)))
1074          (let ((,element-var nil)
1075                (decode-break-reason nil))
1076            (do ((,retry-var t))
1077                ((not ,retry-var))
1078              (if (> (length (fd-stream-instead ,stream-var)) 0)
1079                  (let* ((instead (fd-stream-instead ,stream-var))
1080                         (result (vector-pop instead))
1081                         (pointer (fill-pointer instead)))
1082                    (when (= pointer 0)
1083                      (setf (fd-stream-listen ,stream-var) nil))
1084                    (return-from use-instead result))
1085                  (unless
1086                      (catch 'eof-input-catcher
1087                        (setf decode-break-reason
1088                              (block decode-break-reason
1089                                (input-at-least ,stream-var 1)
1090                                (let* ((byte (sap-ref-8 (buffer-sap ibuf)
1091                                                        (buffer-head ibuf))))
1092                                  (declare (ignorable byte))
1093                                  (setq size ,bytes)
1094                                  (input-at-least ,stream-var size)
1095                                  (setq ,element-var (locally ,@read-forms))
1096                                  (setq ,retry-var nil))
1097                                nil))
1098                        (when decode-break-reason
1099                          (when (stream-decoding-error-and-handle
1100                                 stream decode-break-reason)
1101                            (setq ,retry-var nil)
1102                            (throw 'eof-input-catcher nil)))
1103                        t)
1104                    (let ((octet-count (- (buffer-tail ibuf)
1105                                          (buffer-head ibuf))))
1106                      (when (or (zerop octet-count)
1107                                (and (not ,element-var)
1108                                     (not decode-break-reason)
1109                                     (stream-decoding-error-and-handle
1110                                      stream octet-count)))
1111                        (setq ,retry-var nil))))))
1112            (cond (,element-var
1113                   (incf (buffer-head ibuf) size)
1114                   ,element-var)
1115                  (t
1116                   (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1117
1118 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
1119 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
1120   (let ((stream-var (gensym "STREAM"))
1121         (element-var (gensym "ELT")))
1122     `(let* ((,stream-var ,stream)
1123             (ibuf (fd-stream-ibuf ,stream-var)))
1124        (if (> (length (fd-stream-instead ,stream-var)) 0)
1125            (bug "INSTEAD not empty in INPUT-WRAPPER for ~S" ,stream-var)
1126            (let ((,element-var
1127                   (catch 'eof-input-catcher
1128                     (input-at-least ,stream-var ,bytes)
1129                     (locally ,@read-forms))))
1130              (cond (,element-var
1131                     (incf (buffer-head (fd-stream-ibuf ,stream-var)) ,bytes)
1132                     ,element-var)
1133                    (t
1134                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
1135
1136 (defmacro def-input-routine/variable-width (name
1137                                             (type external-format size sap head)
1138                                             &rest body)
1139   `(progn
1140      (defun ,name (stream eof-error eof-value)
1141        (input-wrapper/variable-width (stream ,size eof-error eof-value)
1142          (let ((,sap (buffer-sap ibuf))
1143                (,head (buffer-head ibuf)))
1144            ,@body)))
1145      (setf *input-routines*
1146            (nconc *input-routines*
1147                   (list (list ',type ',name 1 ',external-format))))))
1148
1149 (defmacro def-input-routine (name
1150                              (type size sap head)
1151                              &rest body)
1152   `(progn
1153      (defun ,name (stream eof-error eof-value)
1154        (input-wrapper (stream ,size eof-error eof-value)
1155          (let ((,sap (buffer-sap ibuf))
1156                (,head (buffer-head ibuf)))
1157            ,@body)))
1158      (setf *input-routines*
1159            (nconc *input-routines*
1160                   (list (list ',type ',name ',size nil))))))
1161
1162 ;;; STREAM-IN routine for reading a string char
1163 (def-input-routine input-character
1164                    (character 1 sap head)
1165   (code-char (sap-ref-8 sap head)))
1166
1167 ;;; STREAM-IN routine for reading an unsigned 8 bit number
1168 (def-input-routine input-unsigned-8bit-byte
1169                    ((unsigned-byte 8) 1 sap head)
1170   (sap-ref-8 sap head))
1171
1172 ;;; STREAM-IN routine for reading a signed 8 bit number
1173 (def-input-routine input-signed-8bit-number
1174                    ((signed-byte 8) 1 sap head)
1175   (signed-sap-ref-8 sap head))
1176
1177 ;;; STREAM-IN routine for reading an unsigned 16 bit number
1178 (def-input-routine input-unsigned-16bit-byte
1179                    ((unsigned-byte 16) 2 sap head)
1180   (sap-ref-16 sap head))
1181
1182 ;;; STREAM-IN routine for reading a signed 16 bit number
1183 (def-input-routine input-signed-16bit-byte
1184                    ((signed-byte 16) 2 sap head)
1185   (signed-sap-ref-16 sap head))
1186
1187 ;;; STREAM-IN routine for reading a unsigned 32 bit number
1188 (def-input-routine input-unsigned-32bit-byte
1189                    ((unsigned-byte 32) 4 sap head)
1190   (sap-ref-32 sap head))
1191
1192 ;;; STREAM-IN routine for reading a signed 32 bit number
1193 (def-input-routine input-signed-32bit-byte
1194                    ((signed-byte 32) 4 sap head)
1195   (signed-sap-ref-32 sap head))
1196
1197 #+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
1198 (progn
1199   (def-input-routine input-unsigned-64bit-byte
1200       ((unsigned-byte 64) 8 sap head)
1201     (sap-ref-64 sap head))
1202   (def-input-routine input-signed-64bit-byte
1203       ((signed-byte 64) 8 sap head)
1204     (signed-sap-ref-64 sap head)))
1205
1206 ;;; Find an input routine to use given the type. Return as multiple
1207 ;;; values the routine, the real type transfered, and the number of
1208 ;;; bytes per element (and for character types string input routine).
1209 (defun pick-input-routine (type &optional external-format)
1210   (when (subtypep type 'character)
1211     (let ((entry (get-external-format external-format)))
1212       (when entry
1213         (return-from pick-input-routine
1214           (values (ef-read-char-fun entry)
1215                   'character
1216                   1
1217                   (ef-read-n-chars-fun entry)
1218                   (canonize-external-format external-format entry))))))
1219   (dolist (entry *input-routines*)
1220     (when (and (subtypep type (first entry))
1221                (or (not (fourth entry))
1222                    (eq external-format (fourth entry))))
1223       (return-from pick-input-routine
1224         (values (symbol-function (second entry))
1225                 (first entry)
1226                 (third entry)))))
1227   ;; FIXME: let's do it the hard way, then (but ignore things like
1228   ;; endianness, efficiency, and the necessary coupling between these
1229   ;; and the output routines).  -- CSR, 2004-02-09
1230   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1231         if (subtypep type `(unsigned-byte ,i))
1232         do (return-from pick-input-routine
1233              (values
1234               (lambda (stream eof-error eof-value)
1235                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1236                   (let ((sap (buffer-sap ibuf))
1237                         (head (buffer-head ibuf)))
1238                     (loop for j from 0 below (/ i 8)
1239                           with result = 0
1240                           do (setf result
1241                                    (+ (* 256 result)
1242                                       (sap-ref-8 sap (+ head j))))
1243                           finally (return result)))))
1244               `(unsigned-byte ,i)
1245               (/ i 8))))
1246   (loop for i from 40 by 8 to 1024 ; ARB (well, KLUDGE really)
1247         if (subtypep type `(signed-byte ,i))
1248         do (return-from pick-input-routine
1249              (values
1250               (lambda (stream eof-error eof-value)
1251                 (input-wrapper (stream (/ i 8) eof-error eof-value)
1252                   (let ((sap (buffer-sap ibuf))
1253                         (head (buffer-head ibuf)))
1254                     (loop for j from 0 below (/ i 8)
1255                           with result = 0
1256                           do (setf result
1257                                    (+ (* 256 result)
1258                                       (sap-ref-8 sap (+ head j))))
1259                           finally (return (if (logbitp (1- i) result)
1260                                               (dpb result (byte i 0) -1)
1261                                               result))))))
1262               `(signed-byte ,i)
1263               (/ i 8)))))
1264
1265 ;;; the N-BIN method for FD-STREAMs
1266 ;;;
1267 ;;; Note that this blocks in UNIX-READ. It is generally used where
1268 ;;; there is a definite amount of reading to be done, so blocking
1269 ;;; isn't too problematical.
1270 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p
1271                                &aux (total-copied 0))
1272   (declare (type fd-stream stream))
1273   (declare (type index start requested total-copied))
1274   (aver (= (length (fd-stream-instead stream)) 0))
1275   (do ()
1276       (nil)
1277     (let* ((remaining-request (- requested total-copied))
1278            (ibuf (fd-stream-ibuf stream))
1279            (head (buffer-head ibuf))
1280            (tail (buffer-tail ibuf))
1281            (available (- tail head))
1282            (n-this-copy (min remaining-request available))
1283            (this-start (+ start total-copied))
1284            (this-end (+ this-start n-this-copy))
1285            (sap (buffer-sap ibuf)))
1286       (declare (type index remaining-request head tail available))
1287       (declare (type index n-this-copy))
1288       ;; Copy data from stream buffer into user's buffer.
1289       (%byte-blt sap head buffer this-start this-end)
1290       (incf (buffer-head ibuf) n-this-copy)
1291       (incf total-copied n-this-copy)
1292       ;; Maybe we need to refill the stream buffer.
1293       (cond (;; If there were enough data in the stream buffer, we're done.
1294              (eql total-copied requested)
1295              (return total-copied))
1296             (;; If EOF, we're done in another way.
1297              (null (catch 'eof-input-catcher (refill-input-buffer stream)))
1298              (if eof-error-p
1299                  (error 'end-of-file :stream stream)
1300                  (return total-copied)))
1301             ;; Otherwise we refilled the stream buffer, so fall
1302             ;; through into another pass of the loop.
1303             ))))
1304
1305 (defun fd-stream-resync (stream)
1306   (let ((entry (get-external-format (fd-stream-external-format stream))))
1307     (when entry
1308       (funcall (ef-resync-fun entry) stream))))
1309
1310 (defun get-fd-stream-character-sizer (stream)
1311   (let ((entry (get-external-format (fd-stream-external-format stream))))
1312     (when entry
1313       (ef-bytes-for-char-fun entry))))
1314
1315 (defun fd-stream-character-size (stream char)
1316   (let ((sizer (get-fd-stream-character-sizer stream)))
1317     (when sizer (funcall sizer char))))
1318
1319 (defun fd-stream-string-size (stream string)
1320   (let ((sizer (get-fd-stream-character-sizer stream)))
1321     (when sizer
1322       (loop for char across string summing (funcall sizer char)))))
1323
1324 (defun find-external-format (external-format)
1325   (when external-format
1326     (get-external-format external-format)))
1327
1328 (defun variable-width-external-format-p (ef-entry)
1329   (and ef-entry (not (null (ef-resync-fun ef-entry)))))
1330
1331 (defun bytes-for-char-fun (ef-entry)
1332   (if ef-entry (ef-bytes-for-char-fun ef-entry) (constantly 1)))
1333
1334 (defmacro define-unibyte-mapping-external-format
1335     (canonical-name (&rest other-names) &body exceptions)
1336   (let ((->code-name (symbolicate canonical-name '->code-mapper))
1337         (code->-name (symbolicate 'code-> canonical-name '-mapper))
1338         (get-bytes-name (symbolicate 'get- canonical-name '-bytes))
1339         (string->-name (symbolicate 'string-> canonical-name))
1340         (define-string*-name (symbolicate 'define- canonical-name '->string*))
1341         (string*-name (symbolicate canonical-name '->string*))
1342         (define-string-name (symbolicate 'define- canonical-name '->string))
1343         (string-name (symbolicate canonical-name '->string))
1344         (->string-aref-name (symbolicate canonical-name '->string-aref)))
1345     `(progn
1346        (define-unibyte-mapper ,->code-name ,code->-name
1347          ,@exceptions)
1348        (declaim (inline ,get-bytes-name))
1349        (defun ,get-bytes-name (string pos)
1350          (declare (optimize speed (safety 0))
1351                   (type simple-string string)
1352                   (type array-range pos))
1353          (get-latin-bytes #',code->-name ,canonical-name string pos))
1354        (defun ,string->-name (string sstart send null-padding)
1355          (declare (optimize speed (safety 0))
1356                   (type simple-string string)
1357                   (type array-range sstart send))
1358          (values (string->latin% string sstart send #',get-bytes-name null-padding)))
1359        (defmacro ,define-string*-name (accessor type)
1360          (declare (ignore type))
1361          (let ((name (make-od-name ',string*-name accessor)))
1362            `(progn
1363               (defun ,name (string sstart send array astart aend)
1364                 (,(make-od-name 'latin->string* accessor)
1365                   string sstart send array astart aend #',',->code-name)))))
1366        (instantiate-octets-definition ,define-string*-name)
1367        (defmacro ,define-string-name (accessor type)
1368          (declare (ignore type))
1369          (let ((name (make-od-name ',string-name accessor)))
1370            `(progn
1371               (defun ,name (array astart aend)
1372                 (,(make-od-name 'latin->string accessor)
1373                   array astart aend #',',->code-name)))))
1374        (instantiate-octets-definition ,define-string-name)
1375        (define-unibyte-external-format ,canonical-name ,other-names
1376          (let ((octet (,code->-name bits)))
1377            (if octet
1378                (setf (sap-ref-8 sap tail) octet)
1379                (external-format-encoding-error stream bits)))
1380          (let ((code (,->code-name byte)))
1381            (if code
1382                (code-char code)
1383                (return-from decode-break-reason 1)))
1384          ,->string-aref-name
1385          ,string->-name))))
1386
1387 (defmacro define-unibyte-external-format
1388     (canonical-name (&rest other-names)
1389      out-form in-form octets-to-string-symbol string-to-octets-symbol)
1390   `(define-external-format/variable-width (,canonical-name ,@other-names)
1391      t 1
1392      ,out-form
1393      1
1394      ,in-form
1395      ,octets-to-string-symbol
1396      ,string-to-octets-symbol))
1397
1398 (defmacro define-external-format/variable-width
1399     (external-format output-restart out-size-expr
1400      out-expr in-size-expr in-expr
1401      octets-to-string-sym string-to-octets-sym)
1402   (let* ((name (first external-format))
1403          (out-function (symbolicate "OUTPUT-BYTES/" name))
1404          (format (format nil "OUTPUT-CHAR-~A-~~A-BUFFERED" (string name)))
1405          (in-function (symbolicate "FD-STREAM-READ-N-CHARACTERS/" name))
1406          (in-char-function (symbolicate "INPUT-CHAR/" name))
1407          (resync-function (symbolicate "RESYNC/" name))
1408          (size-function (symbolicate "BYTES-FOR-CHAR/" name))
1409          (read-c-string-function (symbolicate "READ-FROM-C-STRING/" name))
1410          (output-c-string-function (symbolicate "OUTPUT-TO-C-STRING/" name))
1411          (n-buffer (gensym "BUFFER")))
1412     `(progn
1413       (defun ,size-function (byte)
1414         (declare (ignorable byte))
1415         ,out-size-expr)
1416       (defun ,out-function (stream string flush-p start end)
1417         (let ((start (or start 0))
1418               (end (or end (length string))))
1419           (declare (type index start end))
1420           (synchronize-stream-output stream)
1421           (unless (<= 0 start end (length string))
1422             (sequence-bounding-indices-bad-error string start end))
1423           (do ()
1424               ((= end start))
1425             (let ((obuf (fd-stream-obuf stream)))
1426               (string-dispatch (simple-base-string
1427                                 #!+sb-unicode (simple-array character (*))
1428                                 string)
1429                   string
1430                 (let ((len (buffer-length obuf))
1431                       (sap (buffer-sap obuf))
1432                       ;; FIXME: Rename
1433                       (tail (buffer-tail obuf)))
1434                   (declare (type index tail)
1435                            ;; STRING bounds have already been checked.
1436                            (optimize (safety 0)))
1437                   (,@(if output-restart
1438                          `(catch 'output-nothing)
1439                          `(progn))
1440                      (do* ()
1441                           ((or (= start end) (< (- len tail) 4)))
1442                        (let* ((byte (aref string start))
1443                               (bits (char-code byte))
1444                               (size ,out-size-expr))
1445                          ,out-expr
1446                          (incf tail size)
1447                          (setf (buffer-tail obuf) tail)
1448                          (incf start)))
1449                      (go flush))
1450                   ;; Exited via CATCH: skip the current character.
1451                   (incf start))))
1452            flush
1453             (when (< start end)
1454               (flush-output-buffer stream)))
1455           (when flush-p
1456             (flush-output-buffer stream))))
1457       (def-output-routines/variable-width (,format
1458                                            ,out-size-expr
1459                                            ,output-restart
1460                                            ,external-format
1461                                            (:none character)
1462                                            (:line character)
1463                                            (:full character))
1464           (if (eql byte #\Newline)
1465               (setf (fd-stream-char-pos stream) 0)
1466               (incf (fd-stream-char-pos stream)))
1467         (let ((bits (char-code byte))
1468               (sap (buffer-sap obuf))
1469               (tail (buffer-tail obuf)))
1470           ,out-expr))
1471       (defun ,in-function (stream buffer start requested eof-error-p
1472                            &aux (total-copied 0))
1473         (declare (type fd-stream stream)
1474                  (type index start requested total-copied)
1475                  (type
1476                   (simple-array character (#.+ansi-stream-in-buffer-length+))
1477                   buffer))
1478         (when (fd-stream-eof-forced-p stream)
1479           (setf (fd-stream-eof-forced-p stream) nil)
1480           (return-from ,in-function 0))
1481         (do ((instead (fd-stream-instead stream)))
1482             ((= (fill-pointer instead) 0)
1483              (setf (fd-stream-listen stream) nil))
1484           (setf (aref buffer (+ start total-copied)) (vector-pop instead))
1485           (incf total-copied)
1486           (when (= requested total-copied)
1487             (return-from ,in-function total-copied)))
1488         (do ()
1489             (nil)
1490           (let* ((ibuf (fd-stream-ibuf stream))
1491                  (head (buffer-head ibuf))
1492                  (tail (buffer-tail ibuf))
1493                  (sap (buffer-sap ibuf))
1494                  (decode-break-reason nil))
1495             (declare (type index head tail))
1496             ;; Copy data from stream buffer into user's buffer.
1497             (do ((size nil nil))
1498                 ((or (= tail head) (= requested total-copied)))
1499               (setf decode-break-reason
1500                     (block decode-break-reason
1501                       (let ((byte (sap-ref-8 sap head)))
1502                         (declare (ignorable byte))
1503                         (setq size ,in-size-expr)
1504                         (when (> size (- tail head))
1505                           (return))
1506                         (setf (aref buffer (+ start total-copied)) ,in-expr)
1507                         (incf total-copied)
1508                         (incf head size))
1509                       nil))
1510               (setf (buffer-head ibuf) head)
1511               (when decode-break-reason
1512                 ;; If we've already read some characters on when the invalid
1513                 ;; code sequence is detected, we return immediately. The
1514                 ;; handling of the error is deferred until the next call
1515                 ;; (where this check will be false). This allows establishing
1516                 ;; high-level handlers for decode errors (for example
1517                 ;; automatically resyncing in Lisp comments).
1518                 (when (plusp total-copied)
1519                   (return-from ,in-function total-copied))
1520                 (when (stream-decoding-error-and-handle
1521                        stream decode-break-reason)
1522                   (if eof-error-p
1523                       (error 'end-of-file :stream stream)
1524                       (return-from ,in-function total-copied)))
1525                 ;; we might have been given stuff to use instead, so
1526                 ;; we have to return (and trust our caller to know
1527                 ;; what to do about TOTAL-COPIED being 0).
1528                 (return-from ,in-function total-copied)))
1529             (setf (buffer-head ibuf) head)
1530             ;; Maybe we need to refill the stream buffer.
1531             (cond ( ;; If there were enough data in the stream buffer, we're done.
1532                    (= total-copied requested)
1533                    (return total-copied))
1534                   ( ;; If EOF, we're done in another way.
1535                    (or (eq decode-break-reason 'eof)
1536                        (null (catch 'eof-input-catcher
1537                                (refill-input-buffer stream))))
1538                    (if eof-error-p
1539                        (error 'end-of-file :stream stream)
1540                        (return total-copied)))
1541                   ;; Otherwise we refilled the stream buffer, so fall
1542                   ;; through into another pass of the loop.
1543                   ))))
1544       (def-input-routine/variable-width ,in-char-function (character
1545                                                            ,external-format
1546                                                            ,in-size-expr
1547                                                            sap head)
1548         (let ((byte (sap-ref-8 sap head)))
1549           (declare (ignorable byte))
1550           ,in-expr))
1551       (defun ,resync-function (stream)
1552         (let ((ibuf (fd-stream-ibuf stream)))
1553           (catch 'eof-input-catcher
1554             (loop
1555                (incf (buffer-head ibuf))
1556                (input-at-least stream 1)
1557                (unless (block decode-break-reason
1558                          (let* ((sap (buffer-sap ibuf))
1559                                 (head (buffer-head ibuf))
1560                                 (byte (sap-ref-8 sap head))
1561                                 (size ,in-size-expr))
1562                            (declare (ignorable byte))
1563                            (input-at-least stream size)
1564                            (setf head (buffer-head ibuf))
1565                            ,in-expr)
1566                          nil)
1567                  (return))))))
1568       (defun ,read-c-string-function (sap element-type)
1569         (declare (type system-area-pointer sap))
1570         (locally
1571             (declare (optimize (speed 3) (safety 0)))
1572           (let* ((stream ,name)
1573                  (size 0) (head 0) (byte 0) (char nil)
1574                  (decode-break-reason nil)
1575                  (length (dotimes (count (1- ARRAY-DIMENSION-LIMIT) count)
1576                            (setf decode-break-reason
1577                                  (block decode-break-reason
1578                                    (setf byte (sap-ref-8 sap head)
1579                                          size ,in-size-expr
1580                                          char ,in-expr)
1581                                    (incf head size)
1582                                    nil))
1583                            (when decode-break-reason
1584                              (c-string-decoding-error ,name decode-break-reason))
1585                            (when (zerop (char-code char))
1586                              (return count))))
1587                  (string (make-string length :element-type element-type)))
1588             (declare (ignorable stream)
1589                      (type index head length) ;; size
1590                      (type (unsigned-byte 8) byte)
1591                      (type (or null character) char)
1592                      (type string string))
1593             (setf head 0)
1594             (dotimes (index length string)
1595               (setf decode-break-reason
1596                     (block decode-break-reason
1597                       (setf byte (sap-ref-8 sap head)
1598                             size ,in-size-expr
1599                             char ,in-expr)
1600                       (incf head size)
1601                       nil))
1602               (when decode-break-reason
1603                 (c-string-decoding-error ,name decode-break-reason))
1604               (setf (aref string index) char)))))
1605
1606       (defun ,output-c-string-function (string)
1607         (declare (type simple-string string))
1608         (locally
1609             (declare (optimize (speed 3) (safety 0)))
1610           (let* ((length (length string))
1611                  (char-length (make-array (1+ length) :element-type 'index))
1612                  (buffer-length
1613                   (+ (loop for i of-type index below length
1614                         for byte of-type character = (aref string i)
1615                         for bits = (char-code byte)
1616                         sum (setf (aref char-length i)
1617                                   (the index ,out-size-expr)))
1618                      (let* ((byte (code-char 0))
1619                             (bits (char-code byte)))
1620                        (declare (ignorable byte bits))
1621                        (setf (aref char-length length)
1622                              (the index ,out-size-expr)))))
1623                  (tail 0)
1624                  (,n-buffer (make-array buffer-length
1625                                         :element-type '(unsigned-byte 8)))
1626                  stream)
1627             (declare (type index length buffer-length tail)
1628                      (type null stream)
1629                      (ignorable stream))
1630             (with-pinned-objects (,n-buffer)
1631               (let ((sap (vector-sap ,n-buffer)))
1632                 (declare (system-area-pointer sap))
1633                 (loop for i of-type index below length
1634                       for byte of-type character = (aref string i)
1635                       for bits = (char-code byte)
1636                       for size of-type index = (aref char-length i)
1637                       do (prog1
1638                              ,out-expr
1639                            (incf tail size)))
1640                 (let* ((bits 0)
1641                        (byte (code-char bits))
1642                        (size (aref char-length length)))
1643                   (declare (ignorable bits byte size))
1644                   ,out-expr)))
1645             ,n-buffer)))
1646
1647       (let ((entry (%make-external-format
1648                     :names ',external-format
1649                     :read-n-chars-fun #',in-function
1650                     :read-char-fun #',in-char-function
1651                     :write-n-bytes-fun #',out-function
1652                     ,@(mapcan #'(lambda (buffering)
1653                                   (list (intern (format nil "WRITE-CHAR-~A-BUFFERED-FUN" buffering) :keyword)
1654                                         `#',(intern (format nil format (string buffering)))))
1655                               '(:none :line :full))
1656                     :resync-fun #',resync-function
1657                     :bytes-for-char-fun #',size-function
1658                     :read-c-string-fun #',read-c-string-function
1659                     :write-c-string-fun #',output-c-string-function
1660                     :octets-to-string-fun (lambda (&rest rest)
1661                                             (declare (dynamic-extent rest))
1662                                             (apply ',octets-to-string-sym rest))
1663                     :string-to-octets-fun (lambda (&rest rest)
1664                                             (declare (dynamic-extent rest))
1665                                             (apply ',string-to-octets-sym rest)))))
1666         (dolist (ef ',external-format)
1667           (setf (gethash ef *external-formats*) entry))))))
1668 \f
1669 ;;;; utility functions (misc routines, etc)
1670
1671 ;;; Fill in the various routine slots for the given type. INPUT-P and
1672 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
1673 ;;; set prior to calling this routine.
1674 (defun set-fd-stream-routines (fd-stream element-type external-format
1675                                input-p output-p buffer-p)
1676   (let* ((target-type (case element-type
1677                         (unsigned-byte '(unsigned-byte 8))
1678                         (signed-byte '(signed-byte 8))
1679                         (:default 'character)
1680                         (t element-type)))
1681          (character-stream-p (subtypep target-type 'character))
1682          (bivalent-stream-p (eq element-type :default))
1683          normalized-external-format
1684          (bin-routine #'ill-bin)
1685          (bin-type nil)
1686          (bin-size nil)
1687          (cin-routine #'ill-in)
1688          (cin-type nil)
1689          (cin-size nil)
1690          (input-type nil)           ;calculated from bin-type/cin-type
1691          (input-size nil)           ;calculated from bin-size/cin-size
1692          (read-n-characters #'ill-in)
1693          (bout-routine #'ill-bout)
1694          (bout-type nil)
1695          (bout-size nil)
1696          (cout-routine #'ill-out)
1697          (cout-type nil)
1698          (cout-size nil)
1699          (output-type nil)
1700          (output-size nil)
1701          (output-bytes #'ill-bout))
1702
1703     ;; Ensure that we have buffers in the desired direction(s) only,
1704     ;; getting new ones and dropping/resetting old ones as necessary.
1705     (let ((obuf (fd-stream-obuf fd-stream)))
1706       (if output-p
1707           (if obuf
1708               (reset-buffer obuf)
1709               (setf (fd-stream-obuf fd-stream) (get-buffer)))
1710           (when obuf
1711             (setf (fd-stream-obuf fd-stream) nil)
1712             (release-buffer obuf))))
1713
1714     (let ((ibuf (fd-stream-ibuf fd-stream)))
1715       (if input-p
1716           (if ibuf
1717               (reset-buffer ibuf)
1718               (setf (fd-stream-ibuf fd-stream) (get-buffer)))
1719           (when ibuf
1720             (setf (fd-stream-ibuf fd-stream) nil)
1721             (release-buffer ibuf))))
1722
1723     ;; FIXME: Why only for output? Why unconditionally?
1724     (when output-p
1725       (setf (fd-stream-char-pos fd-stream) 0))
1726
1727     (when (and character-stream-p
1728                (eq external-format :default))
1729       (/show0 "/getting default external format")
1730       (setf external-format (default-external-format)))
1731
1732     (when input-p
1733       (when (or (not character-stream-p) bivalent-stream-p)
1734         (multiple-value-setq (bin-routine bin-type bin-size read-n-characters
1735                                           normalized-external-format)
1736           (pick-input-routine (if bivalent-stream-p '(unsigned-byte 8)
1737                                   target-type)
1738                               external-format))
1739         (unless bin-routine
1740           (error "could not find any input routine for ~S" target-type)))
1741       (when character-stream-p
1742         (multiple-value-setq (cin-routine cin-type cin-size read-n-characters
1743                                           normalized-external-format)
1744           (pick-input-routine target-type external-format))
1745         (unless cin-routine
1746           (error "could not find any input routine for ~S" target-type)))
1747       (setf (fd-stream-in fd-stream) cin-routine
1748             (fd-stream-bin fd-stream) bin-routine)
1749       ;; character type gets preferential treatment
1750       (setf input-size (or cin-size bin-size))
1751       (setf input-type (or cin-type bin-type))
1752       (when normalized-external-format
1753         (setf (fd-stream-external-format fd-stream)
1754               normalized-external-format))
1755       (when (= (or cin-size 1) (or bin-size 1) 1)
1756         (setf (fd-stream-n-bin fd-stream) ;XXX
1757               (if (and character-stream-p (not bivalent-stream-p))
1758                   read-n-characters
1759                   #'fd-stream-read-n-bytes))
1760         ;; Sometimes turn on fast-read-char/fast-read-byte.  Switch on
1761         ;; for character and (unsigned-byte 8) streams.  In these
1762         ;; cases, fast-read-* will read from the
1763         ;; ansi-stream-(c)in-buffer, saving function calls.
1764         ;; Otherwise, the various data-reading functions in the stream
1765         ;; structure will be called.
1766         (when (and buffer-p
1767                    (not bivalent-stream-p)
1768                    ;; temporary disable on :io streams
1769                    (not output-p))
1770           (cond (character-stream-p
1771                  (setf (ansi-stream-cin-buffer fd-stream)
1772                        (make-array +ansi-stream-in-buffer-length+
1773                                    :element-type 'character)))
1774                 ((equal target-type '(unsigned-byte 8))
1775                  (setf (ansi-stream-in-buffer fd-stream)
1776                        (make-array +ansi-stream-in-buffer-length+
1777                                    :element-type '(unsigned-byte 8))))))))
1778
1779     (when output-p
1780       (when (or (not character-stream-p) bivalent-stream-p)
1781         (multiple-value-setq (bout-routine bout-type bout-size output-bytes
1782                                            normalized-external-format)
1783           (pick-output-routine (if bivalent-stream-p
1784                                    '(unsigned-byte 8)
1785                                    target-type)
1786                                (fd-stream-buffering fd-stream)
1787                                external-format))
1788         (unless bout-routine
1789           (error "could not find any output routine for ~S buffered ~S"
1790                  (fd-stream-buffering fd-stream)
1791                  target-type)))
1792       (when character-stream-p
1793         (multiple-value-setq (cout-routine cout-type cout-size output-bytes
1794                                            normalized-external-format)
1795           (pick-output-routine target-type
1796                                (fd-stream-buffering fd-stream)
1797                                external-format))
1798         (unless cout-routine
1799           (error "could not find any output routine for ~S buffered ~S"
1800                  (fd-stream-buffering fd-stream)
1801                  target-type)))
1802       (when normalized-external-format
1803         (setf (fd-stream-external-format fd-stream)
1804               normalized-external-format))
1805       (when character-stream-p
1806         (setf (fd-stream-output-bytes fd-stream) output-bytes))
1807       (setf (fd-stream-out fd-stream) cout-routine
1808             (fd-stream-bout fd-stream) bout-routine
1809             (fd-stream-sout fd-stream) (if (eql cout-size 1)
1810                                            #'fd-sout #'ill-out))
1811       (setf output-size (or cout-size bout-size))
1812       (setf output-type (or cout-type bout-type)))
1813
1814     (when (and input-size output-size
1815                (not (eq input-size output-size)))
1816       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1817              input-type input-size
1818              output-type output-size))
1819     (setf (fd-stream-element-size fd-stream)
1820           (or input-size output-size))
1821
1822     (setf (fd-stream-element-type fd-stream)
1823           (cond ((equal input-type output-type)
1824                  input-type)
1825                 ((null output-type)
1826                  input-type)
1827                 ((null input-type)
1828                  output-type)
1829                 ((subtypep input-type output-type)
1830                  input-type)
1831                 ((subtypep output-type input-type)
1832                  output-type)
1833                 (t
1834                  (error "Input type (~S) and output type (~S) are unrelated?"
1835                         input-type
1836                         output-type))))))
1837
1838 ;;; Handles the resource-release aspects of stream closing, and marks
1839 ;;; it as closed.
1840 (defun release-fd-stream-resources (fd-stream)
1841   (handler-case
1842       (without-interrupts
1843         ;; Drop handlers first.
1844         (when (fd-stream-handler fd-stream)
1845           (remove-fd-handler (fd-stream-handler fd-stream))
1846           (setf (fd-stream-handler fd-stream) nil))
1847         ;; Disable interrupts so that a asynch unwind will not leave
1848         ;; us with a dangling finalizer (that would close the same
1849         ;; --possibly reassigned-- FD again), or a stream with a closed
1850         ;; FD that appears open.
1851         (sb!unix:unix-close (fd-stream-fd fd-stream))
1852         (set-closed-flame fd-stream)
1853         (when (fboundp 'cancel-finalization)
1854           (cancel-finalization fd-stream)))
1855     ;; On error unwind from WITHOUT-INTERRUPTS.
1856     (serious-condition (e)
1857       (error e)))
1858   ;; Release all buffers. If this is undone, or interrupted,
1859   ;; we're still safe: buffers have finalizers of their own.
1860   (release-fd-stream-buffers fd-stream))
1861
1862 ;;; Flushes the current input buffer and any supplied replacements,
1863 ;;; and returns the input buffer, and the amount of of flushed input
1864 ;;; in bytes.
1865 (defun flush-input-buffer (stream)
1866   (let ((unread (length (fd-stream-instead stream))))
1867     (setf (fill-pointer (fd-stream-instead stream)) 0)
1868     (let ((ibuf (fd-stream-ibuf stream)))
1869       (if ibuf
1870           (let ((head (buffer-head ibuf))
1871                 (tail (buffer-tail ibuf)))
1872             (values (reset-buffer ibuf) (- (+ unread tail) head)))
1873           (values nil unread)))))
1874
1875 (defun fd-stream-clear-input (stream)
1876   (flush-input-buffer stream)
1877   #!+win32
1878   (progn
1879     (sb!win32:fd-clear-input (fd-stream-fd stream))
1880     (setf (fd-stream-listen stream) nil))
1881   #!-win32
1882   (catch 'eof-input-catcher
1883     (loop until (sysread-may-block-p stream)
1884           do
1885           (refill-input-buffer stream)
1886           (reset-buffer (fd-stream-ibuf stream)))
1887     t))
1888
1889 ;;; Handle miscellaneous operations on FD-STREAM.
1890 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
1891   (declare (ignore arg2))
1892   (case operation
1893     (:listen
1894      (labels ((do-listen ()
1895                 (let ((ibuf (fd-stream-ibuf fd-stream)))
1896                   (or (not (eql (buffer-head ibuf) (buffer-tail ibuf)))
1897                       (fd-stream-listen fd-stream)
1898                       #!+win32
1899                       (sb!win32:fd-listen (fd-stream-fd fd-stream))
1900                       #!-win32
1901                       ;; If the read can block, LISTEN will certainly return NIL.
1902                       (if (sysread-may-block-p fd-stream)
1903                           nil
1904                           ;; Otherwise select(2) and CL:LISTEN have slightly
1905                           ;; different semantics.  The former returns that an FD
1906                           ;; is readable when a read operation wouldn't block.
1907                           ;; That includes EOF.  However, LISTEN must return NIL
1908                           ;; at EOF.
1909                           (progn (catch 'eof-input-catcher
1910                                    ;; r-b/f too calls select, but it shouldn't
1911                                    ;; block as long as read can return once w/o
1912                                    ;; blocking
1913                                    (refill-input-buffer fd-stream))
1914                                  ;; At this point either IBUF-HEAD != IBUF-TAIL
1915                                  ;; and FD-STREAM-LISTEN is NIL, in which case
1916                                  ;; we should return T, or IBUF-HEAD ==
1917                                  ;; IBUF-TAIL and FD-STREAM-LISTEN is :EOF, in
1918                                  ;; which case we should return :EOF for this
1919                                  ;; call and all future LISTEN call on this stream.
1920                                  ;; Call ourselves again to determine which case
1921                                  ;; applies.
1922                                  (do-listen)))))))
1923        (do-listen)))
1924     (:unread
1925      (decf (buffer-head (fd-stream-ibuf fd-stream))
1926            (fd-stream-character-size fd-stream arg1))
1927      (setf (fd-stream-listen fd-stream) t))
1928     (:close
1929      ;; Drop input buffers
1930      (setf (ansi-stream-in-index fd-stream) +ansi-stream-in-buffer-length+
1931            (ansi-stream-cin-buffer fd-stream) nil
1932            (ansi-stream-in-buffer fd-stream) nil)
1933      (cond (arg1
1934             ;; We got us an abort on our hands.
1935             (let ((outputp (fd-stream-obuf fd-stream))
1936                   (file (fd-stream-file fd-stream))
1937                   (orig (fd-stream-original fd-stream)))
1938               ;; This takes care of the important stuff -- everything
1939               ;; rest is cleaning up the file-system, which we cannot
1940               ;; do on some platforms as long as the file is open.
1941               (release-fd-stream-resources fd-stream)
1942               ;; We can't do anything unless we know what file were
1943               ;; dealing with, and we don't want to do anything
1944               ;; strange unless we were writing to the file.
1945               (when (and outputp file)
1946                 (if orig
1947                     ;; If the original is EQ to file we are appending to
1948                     ;; and can just close the file without renaming.
1949                     (unless (eq orig file)
1950                       ;; We have a handle on the original, just revert.
1951                       (multiple-value-bind (okay err)
1952                           (sb!unix:unix-rename orig file)
1953                         ;; FIXME: Why is this a SIMPLE-STREAM-ERROR, and the
1954                         ;; others are SIMPLE-FILE-ERRORS? Surely they should
1955                         ;; all be the same?
1956                         (unless okay
1957                           (error 'simple-stream-error
1958                                  :format-control
1959                                  "~@<Couldn't restore ~S to its original contents ~
1960                                   from ~S while closing ~S: ~2I~_~A~:>"
1961                                  :format-arguments
1962                                  (list file orig fd-stream (strerror err))
1963                                  :stream fd-stream))))
1964                     ;; We can't restore the original, and aren't
1965                     ;; appending, so nuke that puppy.
1966                     ;;
1967                     ;; FIXME: This is currently the fate of superseded
1968                     ;; files, and according to the CLOSE spec this is
1969                     ;; wrong. However, there seems to be no clean way to
1970                     ;; do that that doesn't involve either copying the
1971                     ;; data (bad if the :abort resulted from a full
1972                     ;; disk), or renaming the old file temporarily
1973                     ;; (probably bad because stream opening becomes more
1974                     ;; racy).
1975                     (multiple-value-bind (okay err)
1976                         (sb!unix:unix-unlink file)
1977                       (unless okay
1978                         (error 'simple-file-error
1979                                :pathname file
1980                                :format-control
1981                                "~@<Couldn't remove ~S while closing ~S: ~2I~_~A~:>"
1982                                :format-arguments
1983                                (list file fd-stream (strerror err)))))))))
1984            (t
1985             (finish-fd-stream-output fd-stream)
1986             (let ((orig (fd-stream-original fd-stream)))
1987               (when (and orig (fd-stream-delete-original fd-stream))
1988                 (multiple-value-bind (okay err) (sb!unix:unix-unlink orig)
1989                   (unless okay
1990                     (error 'simple-file-error
1991                            :pathname orig
1992                            :format-control
1993                            "~@<couldn't delete ~S while closing ~S: ~2I~_~A~:>"
1994                            :format-arguments
1995                            (list orig fd-stream (strerror err)))))))
1996             ;; In case of no-abort close, don't *really* close the
1997             ;; stream until the last moment -- the cleaning up of the
1998             ;; original can be done first.
1999             (release-fd-stream-resources fd-stream))))
2000     (:clear-input
2001      (fd-stream-clear-input fd-stream))
2002     (:force-output
2003      (flush-output-buffer fd-stream))
2004     (:finish-output
2005      (finish-fd-stream-output fd-stream))
2006     (:element-type
2007      (fd-stream-element-type fd-stream))
2008     (:external-format
2009      (fd-stream-external-format fd-stream))
2010     (:interactive-p
2011      (= 1 (the (member 0 1)
2012             (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
2013     (:line-length
2014      80)
2015     (:charpos
2016      (fd-stream-char-pos fd-stream))
2017     (:file-length
2018      (unless (fd-stream-file fd-stream)
2019        ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
2020        ;; "should signal an error of type TYPE-ERROR if stream is not
2021        ;; a stream associated with a file". Too bad there's no very
2022        ;; appropriate value for the EXPECTED-TYPE slot..
2023        (error 'simple-type-error
2024               :datum fd-stream
2025               :expected-type 'fd-stream
2026               :format-control "~S is not a stream associated with a file."
2027               :format-arguments (list fd-stream)))
2028      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
2029                                 atime mtime ctime blksize blocks)
2030          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
2031        (declare (ignore ino nlink uid gid rdev
2032                         atime mtime ctime blksize blocks))
2033        (unless okay
2034          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
2035        (if (zerop mode)
2036            nil
2037            (truncate size (fd-stream-element-size fd-stream)))))
2038     (:file-string-length
2039      (etypecase arg1
2040        (character (fd-stream-character-size fd-stream arg1))
2041        (string (fd-stream-string-size fd-stream arg1))))
2042     (:file-position
2043      (if arg1
2044          (fd-stream-set-file-position fd-stream arg1)
2045          (fd-stream-get-file-position fd-stream)))))
2046
2047 ;; FIXME: Think about this.
2048 ;;
2049 ;; (defun finish-fd-stream-output (fd-stream)
2050 ;;   (let ((timeout (fd-stream-timeout fd-stream)))
2051 ;;     (loop while (fd-stream-output-queue fd-stream)
2052 ;;        ;; FIXME: SIGINT while waiting for a timeout will
2053 ;;        ;; cause a timeout here.
2054 ;;        do (when (and (not (serve-event timeout)) timeout)
2055 ;;             (signal-timeout 'io-timeout
2056 ;;                             :stream fd-stream
2057 ;;                             :direction :write
2058 ;;                             :seconds timeout)))))
2059
2060 (defun finish-fd-stream-output (stream)
2061   (flush-output-buffer stream)
2062   (do ()
2063       ((null (fd-stream-output-queue stream)))
2064     (serve-all-events)))
2065
2066 (defun fd-stream-get-file-position (stream)
2067   (declare (fd-stream stream))
2068   (without-interrupts
2069     (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)))
2070       (declare (type (or (alien sb!unix:off-t) null) posn))
2071       ;; We used to return NIL for errno==ESPIPE, and signal an error
2072       ;; in other failure cases. However, CLHS says to return NIL if
2073       ;; the position cannot be determined -- so that's what we do.
2074       (when (integerp posn)
2075         ;; Adjust for buffered output: If there is any output
2076         ;; buffered, the *real* file position will be larger
2077         ;; than reported by lseek() because lseek() obviously
2078         ;; cannot take into account output we have not sent
2079         ;; yet.
2080         (dolist (buffer (fd-stream-output-queue stream))
2081           (incf posn (- (buffer-tail buffer) (buffer-head buffer))))
2082         (let ((obuf (fd-stream-obuf stream)))
2083           (when obuf
2084             (incf posn (buffer-tail obuf))))
2085         ;; Adjust for unread input: If there is any input
2086         ;; read from UNIX but not supplied to the user of the
2087         ;; stream, the *real* file position will smaller than
2088         ;; reported, because we want to look like the unread
2089         ;; stuff is still available.
2090         (let ((ibuf (fd-stream-ibuf stream)))
2091           (when ibuf
2092             (decf posn (- (buffer-tail ibuf) (buffer-head ibuf)))))
2093         ;; Divide bytes by element size.
2094         (truncate posn (fd-stream-element-size stream))))))
2095
2096 (defun fd-stream-set-file-position (stream position-spec)
2097   (declare (fd-stream stream))
2098   (check-type position-spec
2099               (or (alien sb!unix:off-t) (member nil :start :end))
2100               "valid file position designator")
2101   (tagbody
2102    :again
2103      ;; Make sure we don't have any output pending, because if we
2104      ;; move the file pointer before writing this stuff, it will be
2105      ;; written in the wrong location.
2106      (finish-fd-stream-output stream)
2107      ;; Disable interrupts so that interrupt handlers doing output
2108      ;; won't screw us.
2109      (without-interrupts
2110        (unless (fd-stream-output-finished-p stream)
2111          ;; We got interrupted and more output came our way during
2112          ;; the interrupt. Wrapping the FINISH-FD-STREAM-OUTPUT in
2113          ;; WITHOUT-INTERRUPTS gets nasty as it can signal errors,
2114          ;; so we prefer to do things like this...
2115          (go :again))
2116        ;; Clear out any pending input to force the next read to go to
2117        ;; the disk.
2118        (flush-input-buffer stream)
2119        ;; Trash cached value for listen, so that we check next time.
2120        (setf (fd-stream-listen stream) nil)
2121          ;; Now move it.
2122          (multiple-value-bind (offset origin)
2123              (case position-spec
2124                (:start
2125                 (values 0 sb!unix:l_set))
2126                (:end
2127                 (values 0 sb!unix:l_xtnd))
2128                (t
2129                 (values (* position-spec (fd-stream-element-size stream))
2130                         sb!unix:l_set)))
2131            (declare (type (alien sb!unix:off-t) offset))
2132            (let ((posn (sb!unix:unix-lseek (fd-stream-fd stream)
2133                                            offset origin)))
2134              ;; CLHS says to return true if the file-position was set
2135              ;; succesfully, and NIL otherwise. We are to signal an error
2136              ;; only if the given position was out of bounds, and that is
2137              ;; dealt with above. In times past we used to return NIL for
2138              ;; errno==ESPIPE, and signal an error in other cases.
2139              ;;
2140              ;; FIXME: We are still liable to signal an error if flushing
2141              ;; output fails.
2142              (return-from fd-stream-set-file-position
2143                (typep posn '(alien sb!unix:off-t))))))))
2144
2145 \f
2146 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
2147
2148 ;;; Create a stream for the given Unix file descriptor.
2149 ;;;
2150 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
2151 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
2152 ;;; default to allowing input.
2153 ;;;
2154 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
2155 ;;;
2156 ;;; BUFFERING indicates the kind of buffering to use.
2157 ;;;
2158 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
2159 ;;; NIL (the default), then wait forever. When we time out, we signal
2160 ;;; IO-TIMEOUT.
2161 ;;;
2162 ;;; FILE is the name of the file (will be returned by PATHNAME).
2163 ;;;
2164 ;;; NAME is used to identify the stream when printed.
2165 (defun make-fd-stream (fd
2166                        &key
2167                        (input nil input-p)
2168                        (output nil output-p)
2169                        (element-type 'base-char)
2170                        (buffering :full)
2171                        (external-format :default)
2172                        timeout
2173                        file
2174                        original
2175                        delete-original
2176                        pathname
2177                        input-buffer-p
2178                        dual-channel-p
2179                        (name (if file
2180                                  (format nil "file ~A" file)
2181                                  (format nil "descriptor ~W" fd)))
2182                        auto-close)
2183   (declare (type index fd) (type (or real null) timeout)
2184            (type (member :none :line :full) buffering))
2185   (cond ((not (or input-p output-p))
2186          (setf input t))
2187         ((not (or input output))
2188          (error "File descriptor must be opened either for input or output.")))
2189   (let ((stream (%make-fd-stream :fd fd
2190                                  :name name
2191                                  :file file
2192                                  :original original
2193                                  :delete-original delete-original
2194                                  :pathname pathname
2195                                  :buffering buffering
2196                                  :dual-channel-p dual-channel-p
2197                                  :external-format external-format
2198                                  :bivalent-p (eq element-type :default)
2199                                  :char-size (external-format-char-size external-format)
2200                                  :timeout
2201                                  (if timeout
2202                                      (coerce timeout 'single-float)
2203                                      nil))))
2204     (set-fd-stream-routines stream element-type external-format
2205                             input output input-buffer-p)
2206     (when (and auto-close (fboundp 'finalize))
2207       (finalize stream
2208                 (lambda ()
2209                   (sb!unix:unix-close fd)
2210                   #!+sb-show
2211                   (format *terminal-io* "** closed file descriptor ~W **~%"
2212                           fd))
2213                 :dont-save t))
2214     stream))
2215
2216 ;;; Pick a name to use for the backup file for the :IF-EXISTS
2217 ;;; :RENAME-AND-DELETE and :RENAME options.
2218 (defun pick-backup-name (name)
2219   (declare (type simple-string name))
2220   (concatenate 'simple-string name ".bak"))
2221
2222 ;;; Ensure that the given arg is one of the given list of valid
2223 ;;; things. Allow the user to fix any problems.
2224 (defun ensure-one-of (item list what)
2225   (unless (member item list)
2226     (error 'simple-type-error
2227            :datum item
2228            :expected-type `(member ,@list)
2229            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
2230            :format-arguments (list item what list))))
2231
2232 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
2233 ;;; access, since we don't want to trash unwritable files even if we
2234 ;;; technically can. We return true if we succeed in renaming.
2235 (defun rename-the-old-one (namestring original)
2236   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
2237     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
2238   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
2239     (if okay
2240         t
2241         (error 'simple-file-error
2242                :pathname namestring
2243                :format-control
2244                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
2245                :format-arguments (list namestring original (strerror err))))))
2246
2247 (defun open (filename
2248              &key
2249              (direction :input)
2250              (element-type 'base-char)
2251              (if-exists nil if-exists-given)
2252              (if-does-not-exist nil if-does-not-exist-given)
2253              (external-format :default)
2254              &aux ; Squelch assignment warning.
2255              (direction direction)
2256              (if-does-not-exist if-does-not-exist)
2257              (if-exists if-exists))
2258   #!+sb-doc
2259   "Return a stream which reads from or writes to FILENAME.
2260   Defined keywords:
2261    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
2262    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
2263    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
2264                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
2265    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
2266   See the manual for details."
2267
2268   ;; Calculate useful stuff.
2269   (multiple-value-bind (input output mask)
2270       (ecase direction
2271         (:input  (values   t nil sb!unix:o_rdonly))
2272         (:output (values nil   t sb!unix:o_wronly))
2273         (:io     (values   t   t sb!unix:o_rdwr))
2274         (:probe  (values   t nil sb!unix:o_rdonly)))
2275     (declare (type index mask))
2276     (let* (;; PATHNAME is the pathname we associate with the stream.
2277            (pathname (merge-pathnames filename))
2278            (physical (physicalize-pathname pathname))
2279            (truename (probe-file physical))
2280            ;; NAMESTRING is the native namestring we open the file with.
2281            (namestring (cond (truename
2282                               (native-namestring truename :as-file t))
2283                              ((or (not input)
2284                                   (and input (eq if-does-not-exist :create))
2285                                   (and (eq direction :io) (not if-does-not-exist-given)))
2286                               (native-namestring physical :as-file t)))))
2287       ;; Process if-exists argument if we are doing any output.
2288       (cond (output
2289              (unless if-exists-given
2290                (setf if-exists
2291                      (if (eq (pathname-version pathname) :newest)
2292                          :new-version
2293                          :error)))
2294              (ensure-one-of if-exists
2295                             '(:error :new-version :rename
2296                                      :rename-and-delete :overwrite
2297                                      :append :supersede nil)
2298                             :if-exists)
2299              (case if-exists
2300                ((:new-version :error nil)
2301                 (setf mask (logior mask sb!unix:o_excl)))
2302                ((:rename :rename-and-delete)
2303                 (setf mask (logior mask sb!unix:o_creat)))
2304                ((:supersede)
2305                 (setf mask (logior mask sb!unix:o_trunc)))
2306                (:append
2307                 (setf mask (logior mask sb!unix:o_append)))))
2308             (t
2309              (setf if-exists :ignore-this-arg)))
2310
2311       (unless if-does-not-exist-given
2312         (setf if-does-not-exist
2313               (cond ((eq direction :input) :error)
2314                     ((and output
2315                           (member if-exists '(:overwrite :append)))
2316                      :error)
2317                     ((eq direction :probe)
2318                      nil)
2319                     (t
2320                      :create))))
2321       (ensure-one-of if-does-not-exist
2322                      '(:error :create nil)
2323                      :if-does-not-exist)
2324       (if (eq if-does-not-exist :create)
2325         (setf mask (logior mask sb!unix:o_creat)))
2326
2327       (let ((original (case if-exists
2328                         ((:rename :rename-and-delete)
2329                          (pick-backup-name namestring))
2330                         ((:append :overwrite)
2331                          ;; KLUDGE: Provent CLOSE from deleting
2332                          ;; appending streams when called with :ABORT T
2333                          namestring)))
2334             (delete-original (eq if-exists :rename-and-delete))
2335             (mode #o666))
2336         (when (and original (not (eq original namestring)))
2337           ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
2338           ;; whether the file already exists, make sure the original
2339           ;; file is not a directory, and keep the mode.
2340           (let ((exists
2341                  (and namestring
2342                       (multiple-value-bind (okay err/dev inode orig-mode)
2343                           (sb!unix:unix-stat namestring)
2344                         (declare (ignore inode)
2345                                  (type (or index null) orig-mode))
2346                         (cond
2347                          (okay
2348                           (when (and output (= (logand orig-mode #o170000)
2349                                                #o40000))
2350                             (error 'simple-file-error
2351                                    :pathname pathname
2352                                    :format-control
2353                                    "can't open ~S for output: is a directory"
2354                                    :format-arguments (list namestring)))
2355                           (setf mode (logand orig-mode #o777))
2356                           t)
2357                          ((eql err/dev sb!unix:enoent)
2358                           nil)
2359                          (t
2360                           (simple-file-perror "can't find ~S"
2361                                               namestring
2362                                               err/dev)))))))
2363             (unless (and exists
2364                          (rename-the-old-one namestring original))
2365               (setf original nil)
2366               (setf delete-original nil)
2367               ;; In order to use :SUPERSEDE instead, we have to make
2368               ;; sure SB!UNIX:O_CREAT corresponds to
2369               ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
2370               ;; because of IF-EXISTS being :RENAME.
2371               (unless (eq if-does-not-exist :create)
2372                 (setf mask
2373                       (logior (logandc2 mask sb!unix:o_creat)
2374                               sb!unix:o_trunc)))
2375               (setf if-exists :supersede))))
2376
2377         ;; Now we can try the actual Unix open(2).
2378         (multiple-value-bind (fd errno)
2379             (if namestring
2380                 (sb!unix:unix-open namestring mask mode)
2381                 (values nil sb!unix:enoent))
2382           (labels ((open-error (format-control &rest format-arguments)
2383                      (error 'simple-file-error
2384                             :pathname pathname
2385                             :format-control format-control
2386                             :format-arguments format-arguments))
2387                    (vanilla-open-error ()
2388                      (simple-file-perror "error opening ~S" pathname errno)))
2389             (cond ((numberp fd)
2390                    (case direction
2391                      ((:input :output :io)
2392                       (make-fd-stream fd
2393                                       :input input
2394                                       :output output
2395                                       :element-type element-type
2396                                       :external-format external-format
2397                                       :file namestring
2398                                       :original original
2399                                       :delete-original delete-original
2400                                       :pathname pathname
2401                                       :dual-channel-p nil
2402                                       :input-buffer-p t
2403                                       :auto-close t))
2404                      (:probe
2405                       (let ((stream
2406                              (%make-fd-stream :name namestring
2407                                               :fd fd
2408                                               :pathname pathname
2409                                               :element-type element-type)))
2410                         (close stream)
2411                         stream))))
2412                   ((eql errno sb!unix:enoent)
2413                    (case if-does-not-exist
2414                      (:error (vanilla-open-error))
2415                      (:create
2416                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
2417                                   pathname))
2418                      (t nil)))
2419                   ((and (eql errno sb!unix:eexist) (null if-exists))
2420                    nil)
2421                   (t
2422                    (vanilla-open-error)))))))))
2423 \f
2424 ;;;; initialization
2425
2426 ;;; the stream connected to the controlling terminal, or NIL if there is none
2427 (defvar *tty*)
2428
2429 ;;; the stream connected to the standard input (file descriptor 0)
2430 (defvar *stdin*)
2431
2432 ;;; the stream connected to the standard output (file descriptor 1)
2433 (defvar *stdout*)
2434
2435 ;;; the stream connected to the standard error output (file descriptor 2)
2436 (defvar *stderr*)
2437
2438 ;;; This is called when the cold load is first started up, and may also
2439 ;;; be called in an attempt to recover from nested errors.
2440 (defun stream-cold-init-or-reset ()
2441   (stream-reinit)
2442   (setf *terminal-io* (make-synonym-stream '*tty*))
2443   (setf *standard-output* (make-synonym-stream '*stdout*))
2444   (setf *standard-input* (make-synonym-stream '*stdin*))
2445   (setf *error-output* (make-synonym-stream '*stderr*))
2446   (setf *query-io* (make-synonym-stream '*terminal-io*))
2447   (setf *debug-io* *query-io*)
2448   (setf *trace-output* *standard-output*)
2449   (values))
2450
2451 (defun stream-deinit ()
2452   ;; Unbind to make sure we're not accidently dealing with it
2453   ;; before we're ready (or after we think it's been deinitialized).
2454   (with-available-buffers-lock ()
2455     (without-package-locks
2456         (makunbound '*available-buffers*))))
2457
2458 ;;; This is called whenever a saved core is restarted.
2459 (defun stream-reinit (&optional init-buffers-p)
2460   (when init-buffers-p
2461     (with-available-buffers-lock ()
2462       (aver (not (boundp '*available-buffers*)))
2463       (setf *available-buffers* nil)))
2464   (with-output-to-string (*error-output*)
2465     (setf *stdin*
2466           (make-fd-stream 0 :name "standard input" :input t :buffering :line
2467                             #!+win32 :external-format #!+win32 (sb!win32::console-input-codepage)))
2468     (setf *stdout*
2469           (make-fd-stream 1 :name "standard output" :output t :buffering :line
2470                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2471     (setf *stderr*
2472           (make-fd-stream 2 :name "standard error" :output t :buffering :line
2473                             #!+win32 :external-format #!+win32 (sb!win32::console-output-codepage)))
2474     (let* ((ttyname #.(coerce "/dev/tty" 'simple-base-string))
2475            (tty (sb!unix:unix-open ttyname sb!unix:o_rdwr #o666)))
2476       (if tty
2477           (setf *tty*
2478                 (make-fd-stream tty
2479                                 :name "the terminal"
2480                                 :input t
2481                                 :output t
2482                                 :buffering :line
2483                                 :auto-close t))
2484           (setf *tty* (make-two-way-stream *stdin* *stdout*))))
2485     (princ (get-output-stream-string *error-output*) *stderr*))
2486   (values))
2487 \f
2488 ;;;; miscellany
2489
2490 ;;; the Unix way to beep
2491 (defun beep (stream)
2492   (write-char (code-char bell-char-code) stream)
2493   (finish-output stream))
2494
2495 ;;; This is kind of like FILE-POSITION, but is an internal hack used
2496 ;;; by the filesys stuff to get and set the file name.
2497 ;;;
2498 ;;; FIXME: misleading name, screwy interface
2499 (defun file-name (stream &optional new-name)
2500   (when (typep stream 'fd-stream)
2501       (cond (new-name
2502              (setf (fd-stream-pathname stream) new-name)
2503              (setf (fd-stream-file stream)
2504                    (native-namestring (physicalize-pathname new-name)
2505                                       :as-file t))
2506              t)
2507             (t
2508              (fd-stream-pathname stream)))))