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