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