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