0.8.1.48
[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 manipulation routines
15
16 ;;; FIXME: Is it really good to maintain this pool separate from the
17 ;;; GC and the C malloc logic?
18 (defvar *available-buffers* ()
19   #!+sb-doc
20   "List of available buffers. Each buffer is an sap pointing to
21   bytes-per-buffer of memory.")
22
23 (defconstant bytes-per-buffer (* 4 1024)
24   #!+sb-doc
25   "Number of bytes per buffer.")
26
27 ;;; Return the next available buffer, creating one if necessary.
28 #!-sb-fluid (declaim (inline next-available-buffer))
29 (defun next-available-buffer ()
30   (if *available-buffers*
31       (pop *available-buffers*)
32       (allocate-system-memory bytes-per-buffer)))
33 \f
34 ;;;; the FILE-STREAM structure
35
36 (defstruct (file-stream
37             (:constructor %make-fd-stream)
38             ;; KLUDGE: in an ideal world, maybe we'd rewrite
39             ;; everything to use FILE-STREAM rather than simply
40             ;; providing this hack for compatibility with the old
41             ;; code.  However, CVS doesn't deal terribly well with
42             ;; file renaming, so for now we use this
43             ;; backward-compatibility feature.
44             (:conc-name fd-stream-)
45             (:predicate fd-stream-p)
46             (:include ansi-stream
47                       (misc #'fd-stream-misc-routine))
48             (:copier nil))
49
50   ;; the name of this stream
51   (name nil)
52   ;; the file this stream is for
53   (file nil)
54   ;; the backup file namestring for the old file, for :IF-EXISTS
55   ;; :RENAME or :RENAME-AND-DELETE.
56   (original nil :type (or simple-string null))
57   (delete-original nil)       ; for :if-exists :rename-and-delete
58   ;;; the number of bytes per element
59   (element-size 1 :type index)
60   ;; the type of element being transfered
61   (element-type 'base-char)   
62   ;; the Unix file descriptor
63   (fd -1 :type fixnum)        
64   ;; controls when the output buffer is flushed
65   (buffering :full :type (member :full :line :none))
66   ;; character position (if known)
67   (char-pos nil :type (or index null))
68   ;; T if input is waiting on FD. :EOF if we hit EOF.
69   (listen nil :type (member nil t :eof))
70
71   ;; the input buffer
72   (unread nil)
73   (ibuf-sap nil :type (or system-area-pointer null))
74   (ibuf-length nil :type (or index null))
75   (ibuf-head 0 :type index)
76   (ibuf-tail 0 :type index)
77
78   ;; the output buffer
79   (obuf-sap nil :type (or system-area-pointer null))
80   (obuf-length nil :type (or index null))
81   (obuf-tail 0 :type index)
82
83   ;; output flushed, but not written due to non-blocking io?
84   (output-later nil)
85   (handler nil)
86   ;; timeout specified for this stream, or NIL if none
87   (timeout nil :type (or index null))
88   ;; pathname of the file this stream is opened to (returned by PATHNAME)
89   (pathname nil :type (or pathname null)))
90 (def!method print-object ((fd-stream file-stream) stream)
91   (declare (type stream stream))
92   (print-unreadable-object (fd-stream stream :type t :identity t)
93     (format stream "for ~S" (fd-stream-name fd-stream))))
94 \f
95 ;;;; output routines and related noise
96
97 (defvar *output-routines* ()
98   #!+sb-doc
99   "List of all available output routines. Each element is a list of the
100   element-type output, the kind of buffering, the function name, and the number
101   of bytes per element.")
102
103 ;;; common idioms for reporting low-level stream and file problems
104 (defun simple-stream-perror (note-format stream errno)
105   (error 'simple-stream-error
106          :stream stream
107          :format-control "~@<~?: ~2I~_~A~:>"
108          :format-arguments (list note-format (list stream) (strerror errno))))
109 (defun simple-file-perror (note-format pathname errno)
110   (error 'simple-file-error
111          :pathname pathname
112          :format-control "~@<~?: ~2I~_~A~:>"
113          :format-arguments
114          (list note-format (list pathname) (strerror errno))))
115
116 ;;; This is called by the server when we can write to the given file
117 ;;; descriptor. Attempt to write the data again. If it worked, remove
118 ;;; the data from the OUTPUT-LATER list. If it didn't work, something
119 ;;; is wrong.
120 (defun frob-output-later (stream)
121   (let* ((stuff (pop (fd-stream-output-later stream)))
122          (base (car stuff))
123          (start (cadr stuff))
124          (end (caddr stuff))
125          (reuse-sap (cadddr stuff))
126          (length (- end start)))
127     (declare (type index start end length))
128     (multiple-value-bind (count errno)
129         (sb!unix:unix-write (fd-stream-fd stream)
130                             base
131                             start
132                             length)
133       (cond ((not count)
134              (if (= errno sb!unix:ewouldblock)
135                  (error "Write would have blocked, but SERVER told us to go.")
136                  (simple-stream-perror "couldn't write to ~S" stream errno)))
137             ((eql count length) ; Hot damn, it worked.
138              (when reuse-sap
139                (push base *available-buffers*)))
140             ((not (null count)) ; sorta worked..
141              (push (list base
142                          (the index (+ start count))
143                          end)
144                    (fd-stream-output-later stream))))))
145   (unless (fd-stream-output-later stream)
146     (sb!sys:remove-fd-handler (fd-stream-handler stream))
147     (setf (fd-stream-handler stream) nil)))
148
149 ;;; Arange to output the string when we can write on the file descriptor.
150 (defun output-later (stream base start end reuse-sap)
151   (cond ((null (fd-stream-output-later stream))
152          (setf (fd-stream-output-later stream)
153                (list (list base start end reuse-sap)))
154          (setf (fd-stream-handler stream)
155                (sb!sys:add-fd-handler (fd-stream-fd stream)
156                                       :output
157                                       (lambda (fd)
158                                         (declare (ignore fd))
159                                         (frob-output-later stream)))))
160         (t
161          (nconc (fd-stream-output-later stream)
162                 (list (list base start end reuse-sap)))))
163   (when reuse-sap
164     (let ((new-buffer (next-available-buffer)))
165       (setf (fd-stream-obuf-sap stream) new-buffer)
166       (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
167
168 ;;; Output the given noise. Check to see whether there are any pending
169 ;;; writes. If so, just queue this one. Otherwise, try to write it. If
170 ;;; this would block, queue it.
171 (defun frob-output (stream base start end reuse-sap)
172   (declare (type file-stream stream)
173            (type (or system-area-pointer (simple-array * (*))) base)
174            (type index start end))
175   (if (not (null (fd-stream-output-later stream))) ; something buffered.
176       (progn
177         (output-later stream base start end reuse-sap)
178         ;; ### check to see whether any of this noise can be output
179         )
180       (let ((length (- end start)))
181         (multiple-value-bind (count errno)
182             (sb!unix:unix-write (fd-stream-fd stream) base start length)
183           (cond ((not count)
184                  (if (= errno sb!unix:ewouldblock)
185                      (output-later stream base start end reuse-sap)
186                      (simple-stream-perror "couldn't write to ~S"
187                                            stream
188                                            errno)))
189                 ((not (eql count length))
190                  (output-later stream base (the index (+ start count))
191                                end reuse-sap)))))))
192
193 ;;; Flush any data in the output buffer.
194 (defun flush-output-buffer (stream)
195   (let ((length (fd-stream-obuf-tail stream)))
196     (unless (= length 0)
197       (frob-output stream (fd-stream-obuf-sap stream) 0 length t)
198       (setf (fd-stream-obuf-tail stream) 0))))
199
200 ;;; Define output routines that output numbers SIZE bytes long for the
201 ;;; given bufferings. Use BODY to do the actual output.
202 (defmacro def-output-routines ((name-fmt size &rest bufferings) &body body)
203   (declare (optimize (speed 1)))
204   (cons 'progn
205         (mapcar
206             (lambda (buffering)
207               (let ((function
208                      (intern (let ((*print-case* :upcase))
209                                (format nil name-fmt (car buffering))))))
210                 `(progn
211                    (defun ,function (stream byte)
212                      ,(unless (eq (car buffering) :none)
213                         `(when (< (fd-stream-obuf-length stream)
214                                   (+ (fd-stream-obuf-tail stream)
215                                      ,size))
216                            (flush-output-buffer stream)))
217                      ,@body
218                      (incf (fd-stream-obuf-tail stream) ,size)
219                      ,(ecase (car buffering)
220                         (:none
221                          `(flush-output-buffer stream))
222                         (:line
223                          `(when (eq (char-code byte) (char-code #\Newline))
224                             (flush-output-buffer stream)))
225                         (:full
226                          ))
227                      (values))
228                    (setf *output-routines*
229                          (nconc *output-routines*
230                                 ',(mapcar
231                                    (lambda (type)
232                                      (list type
233                                            (car buffering)
234                                            function
235                                            size))
236                                    (cdr buffering)))))))
237             bufferings)))
238
239 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
240                       1
241                       (:none character)
242                       (:line character)
243                       (:full character))
244   (if (and (base-char-p byte) (char= byte #\Newline))
245       (setf (fd-stream-char-pos stream) 0)
246       (incf (fd-stream-char-pos stream)))
247   (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
248         (char-code byte)))
249
250 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
251                       1
252                       (:none (unsigned-byte 8))
253                       (:full (unsigned-byte 8)))
254   (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
255         byte))
256
257 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
258                       1
259                       (:none (signed-byte 8))
260                       (:full (signed-byte 8)))
261   (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
262                           (fd-stream-obuf-tail stream))
263         byte))
264
265 (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
266                       2
267                       (:none (unsigned-byte 16))
268                       (:full (unsigned-byte 16)))
269   (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
270         byte))
271
272 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
273                       2
274                       (:none (signed-byte 16))
275                       (:full (signed-byte 16)))
276   (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
277                            (fd-stream-obuf-tail stream))
278         byte))
279
280 (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
281                       4
282                       (:none (unsigned-byte 32))
283                       (:full (unsigned-byte 32)))
284   (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
285         byte))
286
287 (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
288                       4
289                       (:none (signed-byte 32))
290                       (:full (signed-byte 32)))
291   (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
292                            (fd-stream-obuf-tail stream))
293         byte))
294
295 ;;; Do the actual output. If there is space to buffer the string,
296 ;;; buffer it. If the string would normally fit in the buffer, but
297 ;;; doesn't because of other stuff in the buffer, flush the old noise
298 ;;; out of the buffer and put the string in it. Otherwise we have a
299 ;;; very long string, so just send it directly (after flushing the
300 ;;; buffer, of course).
301 (defun output-raw-bytes (fd-stream thing &optional start end)
302   #!+sb-doc
303   "Output THING to FD-STREAM. THING can be any kind of vector or a SAP. If
304   THING is a SAP, END must be supplied (as length won't work)."
305   (let ((start (or start 0))
306         (end (or end (length (the (simple-array * (*)) thing)))))
307     (declare (type index start end))
308     (let* ((len (fd-stream-obuf-length fd-stream))
309            (tail (fd-stream-obuf-tail fd-stream))
310            (space (- len tail))
311            (bytes (- end start))
312            (newtail (+ tail bytes)))
313       (cond ((minusp bytes) ; error case
314              (error ":END before :START!"))
315             ((zerop bytes)) ; easy case
316             ((<= bytes space)
317              (if (system-area-pointer-p thing)
318                  (system-area-copy thing
319                                    (* start sb!vm:n-byte-bits)
320                                    (fd-stream-obuf-sap fd-stream)
321                                    (* tail sb!vm:n-byte-bits)
322                                    (* bytes sb!vm:n-byte-bits))
323                  ;; FIXME: There should be some type checking somewhere to
324                  ;; verify that THING here is a vector, not just <not a SAP>.
325                  (copy-to-system-area thing
326                                       (+ (* start sb!vm:n-byte-bits)
327                                          (* sb!vm:vector-data-offset
328                                             sb!vm:n-word-bits))
329                                       (fd-stream-obuf-sap fd-stream)
330                                       (* tail sb!vm:n-byte-bits)
331                                       (* bytes sb!vm:n-byte-bits)))
332              (setf (fd-stream-obuf-tail fd-stream) newtail))
333             ((<= bytes len)
334              (flush-output-buffer fd-stream)
335              (if (system-area-pointer-p thing)
336                  (system-area-copy thing
337                                    (* start sb!vm:n-byte-bits)
338                                    (fd-stream-obuf-sap fd-stream)
339                                    0
340                                    (* bytes sb!vm:n-byte-bits))
341                  ;; FIXME: There should be some type checking somewhere to
342                  ;; verify that THING here is a vector, not just <not a SAP>.
343                  (copy-to-system-area thing
344                                       (+ (* start sb!vm:n-byte-bits)
345                                          (* sb!vm:vector-data-offset
346                                             sb!vm:n-word-bits))
347                                       (fd-stream-obuf-sap fd-stream)
348                                       0
349                                       (* bytes sb!vm:n-byte-bits)))
350              (setf (fd-stream-obuf-tail fd-stream) bytes))
351             (t
352              (flush-output-buffer fd-stream)
353              (frob-output fd-stream thing start end nil))))))
354
355 ;;; the routine to use to output a string. If the stream is
356 ;;; unbuffered, slam the string down the file descriptor, otherwise
357 ;;; use OUTPUT-RAW-BYTES to buffer the string. Update charpos by
358 ;;; checking to see where the last newline was.
359 ;;;
360 ;;; Note: some bozos (the FASL dumper) call write-string with things
361 ;;; other than strings. Therefore, we must make sure we have a string
362 ;;; before calling POSITION on it.
363 ;;; KLUDGE: It would be better to fix the bozos instead of trying to
364 ;;; cover for them here. -- WHN 20000203
365 (defun fd-sout (stream thing start end)
366   (let ((start (or start 0))
367         (end (or end (length (the vector thing)))))
368     (declare (fixnum start end))
369     (if (stringp thing)
370         (let ((last-newline (and (find #\newline (the simple-string thing)
371                                        :start start :end end)
372                                  ;; FIXME why do we need both calls?
373                                  ;; Is find faster forwards than
374                                  ;; position is backwards?
375                                  (position #\newline (the simple-string thing)
376                                            :from-end t
377                                            :start start
378                                            :end end))))
379           (ecase (fd-stream-buffering stream)
380             (:full
381              (output-raw-bytes stream thing start end))
382             (:line
383              (output-raw-bytes stream thing start end)
384              (when last-newline
385                (flush-output-buffer stream)))
386             (:none
387              (frob-output stream thing start end nil)))
388           (if last-newline
389               (setf (fd-stream-char-pos stream)
390                     (- end last-newline 1))
391               (incf (fd-stream-char-pos stream)
392                     (- end start))))
393         (ecase (fd-stream-buffering stream)
394           ((:line :full)
395            (output-raw-bytes stream thing start end))
396           (:none
397            (frob-output stream thing start end nil))))))
398
399 ;;; Find an output routine to use given the type and buffering. Return
400 ;;; as multiple values the routine, the real type transfered, and the
401 ;;; number of bytes per element.
402 (defun pick-output-routine (type buffering)
403   (dolist (entry *output-routines*)
404     (when (and (subtypep type (car entry))
405                (eq buffering (cadr entry)))
406       (return (values (symbol-function (caddr entry))
407                       (car entry)
408                       (cadddr entry))))))
409 \f
410 ;;;; input routines and related noise
411
412 ;;; a list of all available input routines. Each element is a list of
413 ;;; the element-type input, the function name, and the number of bytes
414 ;;; per element.
415 (defvar *input-routines* ())
416
417 ;;; Fill the input buffer, and return the first character. Throw to
418 ;;; EOF-INPUT-CATCHER if the eof was reached. Drop into SYSTEM:SERVER
419 ;;; if necessary.
420 (defun frob-input (stream)
421   (let ((fd (fd-stream-fd stream))
422         (ibuf-sap (fd-stream-ibuf-sap stream))
423         (buflen (fd-stream-ibuf-length stream))
424         (head (fd-stream-ibuf-head stream))
425         (tail (fd-stream-ibuf-tail stream)))
426     (declare (type index head tail))
427     (unless (zerop head)
428       (cond ((eql head tail)
429              (setf head 0)
430              (setf tail 0)
431              (setf (fd-stream-ibuf-head stream) 0)
432              (setf (fd-stream-ibuf-tail stream) 0))
433             (t
434              (decf tail head)
435              (system-area-copy ibuf-sap (* head sb!vm:n-byte-bits)
436                                ibuf-sap 0 (* tail sb!vm:n-byte-bits))
437              (setf head 0)
438              (setf (fd-stream-ibuf-head stream) 0)
439              (setf (fd-stream-ibuf-tail stream) tail))))
440     (setf (fd-stream-listen stream) nil)
441     (multiple-value-bind (count errno)
442         ;; FIXME: Judging from compiler warnings, this WITH-ALIEN form expands
443         ;; into something which uses the not-yet-defined type
444         ;;   (SB!ALIEN-INTERNALS:ALIEN (* (SB!ALIEN:STRUCT SB!UNIX:FD-SET))).
445         ;; This is probably inefficient and unsafe and generally bad, so
446         ;; try to find some way to make that type known before
447         ;; this is compiled.
448         (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
449           (sb!unix:fd-zero read-fds)
450           (sb!unix:fd-set fd read-fds)
451           (sb!unix:unix-fast-select (1+ fd)
452                                     (sb!alien:addr read-fds)
453                                     nil
454                                     nil
455                                     0
456                                     0))
457       (case count
458         (1)
459         (0
460          (unless (sb!sys:wait-until-fd-usable
461                   fd :input (fd-stream-timeout stream))
462            (error 'io-timeout :stream stream :direction :read)))
463         (t
464          (simple-stream-perror "couldn't check whether ~S is readable"
465                                stream
466                                errno))))
467     (multiple-value-bind (count errno)
468         (sb!unix:unix-read fd
469                            (sb!sys:int-sap (+ (sb!sys:sap-int ibuf-sap) tail))
470                            (- buflen tail))
471       (cond ((null count)
472              (if (eql errno sb!unix:ewouldblock)
473                  (progn
474                    (unless (sb!sys:wait-until-fd-usable
475                             fd :input (fd-stream-timeout stream))
476                      (error 'io-timeout :stream stream :direction :read))
477                    (frob-input stream))
478                  (simple-stream-perror "couldn't read from ~S" stream errno)))
479             ((zerop count)
480              (setf (fd-stream-listen stream) :eof)
481              (/show0 "THROWing EOF-INPUT-CATCHER")
482              (throw 'eof-input-catcher nil))
483             (t
484              (incf (fd-stream-ibuf-tail stream) count))))))
485                         
486 ;;; Make sure there are at least BYTES number of bytes in the input
487 ;;; buffer. Keep calling FROB-INPUT until that condition is met.
488 (defmacro input-at-least (stream bytes)
489   (let ((stream-var (gensym))
490         (bytes-var (gensym)))
491     `(let ((,stream-var ,stream)
492            (,bytes-var ,bytes))
493        (loop
494          (when (>= (- (fd-stream-ibuf-tail ,stream-var)
495                       (fd-stream-ibuf-head ,stream-var))
496                    ,bytes-var)
497            (return))
498          (frob-input ,stream-var)))))
499
500 ;;; a macro to wrap around all input routines to handle EOF-ERROR noise
501 (defmacro input-wrapper ((stream bytes eof-error eof-value) &body read-forms)
502   (let ((stream-var (gensym))
503         (element-var (gensym)))
504     `(let ((,stream-var ,stream))
505        (if (fd-stream-unread ,stream-var)
506            (prog1
507                (fd-stream-unread ,stream-var)
508              (setf (fd-stream-unread ,stream-var) nil)
509              (setf (fd-stream-listen ,stream-var) nil))
510            (let ((,element-var
511                   (catch 'eof-input-catcher
512                     (input-at-least ,stream-var ,bytes)
513                     ,@read-forms)))
514              (cond (,element-var
515                     (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
516                     ,element-var)
517                    (t
518                     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
519
520 (defmacro def-input-routine (name
521                              (type size sap head)
522                              &rest body)
523   `(progn
524      (defun ,name (stream eof-error eof-value)
525        (input-wrapper (stream ,size eof-error eof-value)
526          (let ((,sap (fd-stream-ibuf-sap stream))
527                (,head (fd-stream-ibuf-head stream)))
528            ,@body)))
529      (setf *input-routines*
530            (nconc *input-routines*
531                   (list (list ',type ',name ',size))))))
532
533 ;;; STREAM-IN routine for reading a string char
534 (def-input-routine input-character
535                    (character 1 sap head)
536   (code-char (sap-ref-8 sap head)))
537
538 ;;; STREAM-IN routine for reading an unsigned 8 bit number
539 (def-input-routine input-unsigned-8bit-byte
540                    ((unsigned-byte 8) 1 sap head)
541   (sap-ref-8 sap head))
542
543 ;;; STREAM-IN routine for reading a signed 8 bit number
544 (def-input-routine input-signed-8bit-number
545                    ((signed-byte 8) 1 sap head)
546   (signed-sap-ref-8 sap head))
547
548 ;;; STREAM-IN routine for reading an unsigned 16 bit number
549 (def-input-routine input-unsigned-16bit-byte
550                    ((unsigned-byte 16) 2 sap head)
551   (sap-ref-16 sap head))
552
553 ;;; STREAM-IN routine for reading a signed 16 bit number
554 (def-input-routine input-signed-16bit-byte
555                    ((signed-byte 16) 2 sap head)
556   (signed-sap-ref-16 sap head))
557
558 ;;; STREAM-IN routine for reading a unsigned 32 bit number
559 (def-input-routine input-unsigned-32bit-byte
560                    ((unsigned-byte 32) 4 sap head)
561   (sap-ref-32 sap head))
562
563 ;;; STREAM-IN routine for reading a signed 32 bit number
564 (def-input-routine input-signed-32bit-byte
565                    ((signed-byte 32) 4 sap head)
566   (signed-sap-ref-32 sap head))
567
568 ;;; Find an input routine to use given the type. Return as multiple
569 ;;; values the routine, the real type transfered, and the number of
570 ;;; bytes per element.
571 (defun pick-input-routine (type)
572   (dolist (entry *input-routines*)
573     (when (subtypep type (car entry))
574       (return (values (symbol-function (cadr entry))
575                       (car entry)
576                       (caddr entry))))))
577
578 ;;; Return a string constructed from SAP, START, and END.
579 (defun string-from-sap (sap start end)
580   (declare (type index start end))
581   (let* ((length (- end start))
582          (string (make-string length)))
583     (copy-from-system-area sap (* start sb!vm:n-byte-bits)
584                            string (* sb!vm:vector-data-offset
585                                      sb!vm:n-word-bits)
586                            (* length sb!vm:n-byte-bits))
587     string))
588
589 ;;; the N-BIN method for FD-STREAMs
590 ;;;
591 ;;; Note that this blocks in UNIX-READ. It is generally used where
592 ;;; there is a definite amount of reading to be done, so blocking
593 ;;; isn't too problematical.
594 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
595   (declare (type file-stream stream))
596   (declare (type index start requested))
597   (do ((total-copied 0))
598       (nil)
599     (declare (type index total-copied))
600     (let* ((remaining-request (- requested total-copied))
601            (head (fd-stream-ibuf-head stream))
602            (tail (fd-stream-ibuf-tail stream))
603            (available (- tail head))
604            (n-this-copy (min remaining-request available))
605            (this-start (+ start total-copied))
606            (this-end (+ this-start n-this-copy))
607            (sap (fd-stream-ibuf-sap stream)))
608       (declare (type index remaining-request head tail available))
609       (declare (type index n-this-copy))
610       ;; Copy data from stream buffer into user's buffer. 
611       (%byte-blt sap head buffer this-start this-end)
612       (incf (fd-stream-ibuf-head stream) n-this-copy)
613       (incf total-copied n-this-copy)
614       ;; Maybe we need to refill the stream buffer.
615       (cond (;; If there were enough data in the stream buffer, we're done.
616              (= total-copied requested)
617              (return total-copied))
618             (;; If EOF, we're done in another way.
619              (zerop (refill-fd-stream-buffer stream))
620              (if eof-error-p
621                  (error 'end-of-file :stream stream)
622                  (return total-copied)))
623             ;; Otherwise we refilled the stream buffer, so fall
624             ;; through into another pass of the loop.
625             ))))
626
627 ;;; Try to refill the stream buffer. Return the number of bytes read.
628 ;;; (For EOF, the return value will be zero, otherwise positive.)
629 (defun refill-fd-stream-buffer (stream)
630   ;; We don't have any logic to preserve leftover bytes in the buffer,
631   ;; so we should only be called when the buffer is empty.
632   (aver (= (fd-stream-ibuf-head stream) (fd-stream-ibuf-tail stream)))
633   (multiple-value-bind (count err)
634       (sb!unix:unix-read (fd-stream-fd stream)
635                          (fd-stream-ibuf-sap stream)
636                          (fd-stream-ibuf-length stream))
637     (declare (type (or index null) count))
638     (when (null count)
639       (simple-stream-perror "couldn't read from ~S" stream err))
640     (setf (fd-stream-listen stream) nil
641           (fd-stream-ibuf-head stream) 0
642           (fd-stream-ibuf-tail stream) count)
643     count))
644 \f
645 ;;;; utility functions (misc routines, etc)
646
647 ;;; Fill in the various routine slots for the given type. INPUT-P and
648 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
649 ;;; set prior to calling this routine.
650 (defun set-fd-stream-routines (fd-stream type input-p output-p buffer-p)
651   (let ((target-type (case type
652                        ((:default unsigned-byte)
653                         '(unsigned-byte 8))
654                        (signed-byte
655                         '(signed-byte 8))
656                        (t
657                         type)))
658         (input-type nil)
659         (output-type nil)
660         (input-size nil)
661         (output-size nil))
662
663     (when (fd-stream-obuf-sap fd-stream)
664       (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
665       (setf (fd-stream-obuf-sap fd-stream) nil))
666     (when (fd-stream-ibuf-sap fd-stream)
667       (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
668       (setf (fd-stream-ibuf-sap fd-stream) nil))
669
670     (when input-p
671       (multiple-value-bind (routine type size)
672           (pick-input-routine target-type)
673         (unless routine
674           (error "could not find any input routine for ~S" target-type))
675         (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
676         (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
677         (setf (fd-stream-ibuf-tail fd-stream) 0)
678         (if (subtypep type 'character)
679             (setf (fd-stream-in fd-stream) routine
680                   (fd-stream-bin fd-stream) #'ill-bin)
681             (setf (fd-stream-in fd-stream) #'ill-in
682                   (fd-stream-bin fd-stream) routine))
683         (when (eql size 1)
684           (setf (fd-stream-n-bin fd-stream) #'fd-stream-read-n-bytes)
685           (when (and buffer-p
686                      ;; We only create this buffer for streams of type
687                      ;; (unsigned-byte 8).  Because there's no buffer, the
688                      ;; other element-types will dispatch to the appropriate
689                      ;; input (output) routine in fast-read-byte.
690                      (or (eq type 'unsigned-byte)
691                          (eq type :default)))
692             (setf (ansi-stream-in-buffer fd-stream)
693                   (make-array +ansi-stream-in-buffer-length+
694                               :element-type '(unsigned-byte 8)))))
695         (setf input-size size)
696         (setf input-type type)))
697
698     (when output-p
699       (multiple-value-bind (routine type size)
700           (pick-output-routine target-type (fd-stream-buffering fd-stream))
701         (unless routine
702           (error "could not find any output routine for ~S buffered ~S"
703                  (fd-stream-buffering fd-stream)
704                  target-type))
705         (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
706         (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
707         (setf (fd-stream-obuf-tail fd-stream) 0)
708         (if (subtypep type 'character)
709           (setf (fd-stream-out fd-stream) routine
710                 (fd-stream-bout fd-stream) #'ill-bout)
711           (setf (fd-stream-out fd-stream)
712                 (or (if (eql size 1)
713                       (pick-output-routine 'base-char
714                                            (fd-stream-buffering fd-stream)))
715                     #'ill-out)
716                 (fd-stream-bout fd-stream) routine))
717         (setf (fd-stream-sout fd-stream)
718               (if (eql size 1) #'fd-sout #'ill-out))
719         (setf (fd-stream-char-pos fd-stream) 0)
720         (setf output-size size)
721         (setf output-type type)))
722
723     (when (and input-size output-size
724                (not (eq input-size output-size)))
725       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
726              input-type input-size
727              output-type output-size))
728     (setf (fd-stream-element-size fd-stream)
729           (or input-size output-size))
730
731     (setf (fd-stream-element-type fd-stream)
732           (cond ((equal input-type output-type)
733                  input-type)
734                 ((null output-type)
735                  input-type)
736                 ((null input-type)
737                  output-type)
738                 ((subtypep input-type output-type)
739                  input-type)
740                 ((subtypep output-type input-type)
741                  output-type)
742                 (t
743                  (error "Input type (~S) and output type (~S) are unrelated?"
744                         input-type
745                         output-type))))))
746
747 ;;; Handle miscellaneous operations on FD-STREAM.
748 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
749   (declare (ignore arg2))
750   (case operation
751     (:listen
752      (or (not (eql (fd-stream-ibuf-head fd-stream)
753                    (fd-stream-ibuf-tail fd-stream)))
754          (fd-stream-listen fd-stream)
755          (setf (fd-stream-listen fd-stream)
756                (eql (sb!alien:with-alien ((read-fds (sb!alien:struct
757                                                      sb!unix:fd-set)))
758                       (sb!unix:fd-zero read-fds)
759                       (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
760                       (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
761                                                 (sb!alien:addr read-fds)
762                                                 nil nil 0 0))
763                     1))))
764     (:unread
765      (setf (fd-stream-unread fd-stream) arg1)
766      (setf (fd-stream-listen fd-stream) t))
767     (:close
768      (cond (arg1
769             ;; We got us an abort on our hands.
770             (when (fd-stream-handler fd-stream)
771                   (sb!sys:remove-fd-handler (fd-stream-handler fd-stream))
772                   (setf (fd-stream-handler fd-stream) nil))
773             (when (and (fd-stream-file fd-stream)
774                        (fd-stream-obuf-sap fd-stream))
775               ;; We can't do anything unless we know what file were
776               ;; dealing with, and we don't want to do anything
777               ;; strange unless we were writing to the file.
778               (if (fd-stream-original fd-stream)
779                   ;; We have a handle on the original, just revert.
780                   (multiple-value-bind (okay err)
781                       (sb!unix:unix-rename (fd-stream-original fd-stream)
782                                            (fd-stream-file fd-stream))
783                     (unless okay
784                       (simple-stream-perror
785                        "couldn't restore ~S to its original contents"
786                        fd-stream
787                        err)))
788                   ;; We can't restore the original, so nuke that puppy.
789                   (multiple-value-bind (okay err)
790                       (sb!unix:unix-unlink (fd-stream-file fd-stream))
791                     (unless okay
792                       (error 'simple-file-error
793                              :pathname (fd-stream-file fd-stream)
794                              :format-control
795                              "~@<couldn't remove ~S: ~2I~_~A~:>"
796                              :format-arguments (list (fd-stream-file fd-stream)
797                                                      (strerror err))))))))
798            (t
799             (fd-stream-misc-routine fd-stream :finish-output)
800             (when (and (fd-stream-original fd-stream)
801                        (fd-stream-delete-original fd-stream))
802               (multiple-value-bind (okay err)
803                   (sb!unix:unix-unlink (fd-stream-original fd-stream))
804                 (unless okay
805                   (error 'simple-file-error
806                          :pathname (fd-stream-original fd-stream)
807                          :format-control 
808                          "~@<couldn't delete ~S during close of ~S: ~
809                           ~2I~_~A~:>"
810                          :format-arguments
811                          (list (fd-stream-original fd-stream)
812                                fd-stream
813                                (strerror err))))))))
814      (when (fboundp 'cancel-finalization)
815        (cancel-finalization fd-stream))
816      (sb!unix:unix-close (fd-stream-fd fd-stream))
817      (when (fd-stream-obuf-sap fd-stream)
818        (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
819        (setf (fd-stream-obuf-sap fd-stream) nil))
820      (when (fd-stream-ibuf-sap fd-stream)
821        (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
822        (setf (fd-stream-ibuf-sap fd-stream) nil))
823      (sb!impl::set-closed-flame fd-stream))
824     (:clear-input
825      (setf (fd-stream-unread fd-stream) nil)
826      (setf (fd-stream-ibuf-head fd-stream) 0)
827      (setf (fd-stream-ibuf-tail fd-stream) 0)
828      (catch 'eof-input-catcher
829        (loop
830         (let ((count (sb!alien:with-alien ((read-fds (sb!alien:struct
831                                                       sb!unix:fd-set)))
832                        (sb!unix:fd-zero read-fds)
833                        (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
834                        (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
835                                                  (sb!alien:addr read-fds)
836                                                  nil
837                                                  nil
838                                                  0
839                                                  0))))
840           (cond ((eql count 1)
841                  (frob-input fd-stream)
842                  (setf (fd-stream-ibuf-head fd-stream) 0)
843                  (setf (fd-stream-ibuf-tail fd-stream) 0))
844                 (t
845                  (return t)))))))
846     (:force-output
847      (flush-output-buffer fd-stream))
848     (:finish-output
849      (flush-output-buffer fd-stream)
850      (do ()
851          ((null (fd-stream-output-later fd-stream)))
852        (sb!sys:serve-all-events)))
853     (:element-type
854      (fd-stream-element-type fd-stream))
855     (:interactive-p
856       ;; FIXME: sb!unix:unix-isatty is undefined.
857      (= 1 (the (member 0 1)
858             (sb!unix:unix-isatty (fd-stream-fd fd-stream)))))
859     (:line-length
860      80)
861     (:charpos
862      (fd-stream-char-pos fd-stream))
863     (:file-length
864      (unless (fd-stream-file fd-stream)
865        ;; This is a TYPE-ERROR because ANSI's species FILE-LENGTH
866        ;; "should signal an error of type TYPE-ERROR if stream is not
867        ;; a stream associated with a file". Too bad there's no very
868        ;; appropriate value for the EXPECTED-TYPE slot..
869        (error 'simple-type-error
870               :datum fd-stream
871               :expected-type 'file-stream
872               :format-control "~S is not a stream associated with a file."
873               :format-arguments (list fd-stream)))
874      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
875                            atime mtime ctime blksize blocks)
876          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
877        (declare (ignore ino nlink uid gid rdev
878                         atime mtime ctime blksize blocks))
879        (unless okay
880          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
881        (if (zerop mode)
882            nil
883            (truncate size (fd-stream-element-size fd-stream)))))
884     (:file-position
885      (fd-stream-file-position fd-stream arg1))))
886
887 (defun fd-stream-file-position (stream &optional newpos)
888   (declare (type file-stream stream)
889            (type (or index (member nil :start :end)) newpos))
890   (if (null newpos)
891       (sb!sys:without-interrupts
892         ;; First, find the position of the UNIX file descriptor in the file.
893         (multiple-value-bind (posn errno)
894             (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)
895           (declare (type (or index null) posn))
896           (cond ((fixnump posn)
897                  ;; Adjust for buffered output: If there is any output
898                  ;; buffered, the *real* file position will be larger
899                  ;; than reported by lseek() because lseek() obviously
900                  ;; cannot take into account output we have not sent
901                  ;; yet.
902                  (dolist (later (fd-stream-output-later stream))
903                    (incf posn (- (the index (caddr later))
904                                  (the index (cadr later)))))
905                  (incf posn (fd-stream-obuf-tail stream))
906                  ;; Adjust for unread input: If there is any input
907                  ;; read from UNIX but not supplied to the user of the
908                  ;; stream, the *real* file position will smaller than
909                  ;; reported, because we want to look like the unread
910                  ;; stuff is still available.
911                  (decf posn (- (fd-stream-ibuf-tail stream)
912                                (fd-stream-ibuf-head stream)))
913                  (when (fd-stream-unread stream)
914                    (decf posn))
915                  ;; Divide bytes by element size.
916                  (truncate posn (fd-stream-element-size stream)))
917                 ((eq errno sb!unix:espipe)
918                  nil)
919                 (t
920                  (sb!sys:with-interrupts
921                    (simple-stream-perror "failure in Unix lseek() on ~S"
922                                          stream
923                                          errno))))))
924       (let ((offset 0) origin)
925         (declare (type index offset))
926         ;; Make sure we don't have any output pending, because if we
927         ;; move the file pointer before writing this stuff, it will be
928         ;; written in the wrong location.
929         (flush-output-buffer stream)
930         (do ()
931             ((null (fd-stream-output-later stream)))
932           (sb!sys:serve-all-events))
933         ;; Clear out any pending input to force the next read to go to
934         ;; the disk.
935         (setf (fd-stream-unread stream) nil)
936         (setf (fd-stream-ibuf-head stream) 0)
937         (setf (fd-stream-ibuf-tail stream) 0)
938         ;; Trash cached value for listen, so that we check next time.
939         (setf (fd-stream-listen stream) nil)
940         ;; Now move it.
941         (cond ((eq newpos :start)
942                (setf offset 0 origin sb!unix:l_set))
943               ((eq newpos :end)
944                (setf offset 0 origin sb!unix:l_xtnd))
945               ((typep newpos 'index)
946                (setf offset (* newpos (fd-stream-element-size stream))
947                      origin sb!unix:l_set))
948               (t
949                (error "invalid position given to FILE-POSITION: ~S" newpos)))
950         (multiple-value-bind (posn errno)
951             (sb!unix:unix-lseek (fd-stream-fd stream) offset origin)
952           (cond ((typep posn 'fixnum)
953                  t)
954                 ((eq errno sb!unix:espipe)
955                  nil)
956                 (t
957                  (simple-stream-perror "error in Unix lseek() on ~S"
958                                        stream
959                                        errno)))))))
960 \f
961 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
962
963 ;;; Create a stream for the given Unix file descriptor.
964 ;;;
965 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
966 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
967 ;;; default to allowing input.
968 ;;;
969 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
970 ;;;
971 ;;; BUFFERING indicates the kind of buffering to use.
972 ;;;
973 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
974 ;;; NIL (the default), then wait forever. When we time out, we signal
975 ;;; IO-TIMEOUT.
976 ;;;
977 ;;; FILE is the name of the file (will be returned by PATHNAME).
978 ;;;
979 ;;; NAME is used to identify the stream when printed.
980 (defun make-fd-stream (fd
981                        &key
982                        (input nil input-p)
983                        (output nil output-p)
984                        (element-type 'base-char)
985                        (buffering :full)
986                        timeout
987                        file
988                        original
989                        delete-original
990                        pathname
991                        input-buffer-p
992                        (name (if file
993                                  (format nil "file ~S" file)
994                                  (format nil "descriptor ~W" fd)))
995                        auto-close)
996   (declare (type index fd) (type (or index null) timeout)
997            (type (member :none :line :full) buffering))
998   (cond ((not (or input-p output-p))
999          (setf input t))
1000         ((not (or input output))
1001          (error "File descriptor must be opened either for input or output.")))
1002   (let ((stream (%make-fd-stream :fd fd
1003                                  :name name
1004                                  :file file
1005                                  :original original
1006                                  :delete-original delete-original
1007                                  :pathname pathname
1008                                  :buffering buffering
1009                                  :timeout timeout)))
1010     (set-fd-stream-routines stream element-type input output input-buffer-p)
1011     (when (and auto-close (fboundp 'finalize))
1012       (finalize stream
1013                 (lambda ()
1014                   (sb!unix:unix-close fd)
1015                   #!+sb-show
1016                   (format *terminal-io* "** closed file descriptor ~W **~%"
1017                           fd))))
1018     stream))
1019
1020 ;;; Pick a name to use for the backup file for the :IF-EXISTS
1021 ;;; :RENAME-AND-DELETE and :RENAME options.
1022 (defun pick-backup-name (name)
1023   (declare (type simple-base-string name))
1024   (concatenate 'simple-base-string name ".bak"))
1025
1026 ;;; Ensure that the given arg is one of the given list of valid
1027 ;;; things. Allow the user to fix any problems.
1028 (defun ensure-one-of (item list what)
1029   (unless (member item list)
1030     (error 'simple-type-error
1031            :datum item
1032            :expected-type `(member ,@list)
1033            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
1034            :format-arguments (list item what list))))
1035
1036 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
1037 ;;; access, since we don't want to trash unwritable files even if we
1038 ;;; technically can. We return true if we succeed in renaming.
1039 (defun rename-the-old-one (namestring original)
1040   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
1041     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
1042   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
1043     (if okay
1044         t
1045         (error 'simple-file-error
1046                :pathname namestring
1047                :format-control 
1048                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
1049                :format-arguments (list namestring original (strerror err))))))
1050
1051 (defun open (filename
1052              &key
1053              (direction :input)
1054              (element-type 'base-char)
1055              (if-exists nil if-exists-given)
1056              (if-does-not-exist nil if-does-not-exist-given)
1057              (external-format :default)
1058              &aux ; Squelch assignment warning.
1059              (direction direction)
1060              (if-does-not-exist if-does-not-exist)
1061              (if-exists if-exists))
1062   #!+sb-doc
1063   "Return a stream which reads from or writes to FILENAME.
1064   Defined keywords:
1065    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
1066    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
1067    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
1068                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
1069    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or NIL
1070   See the manual for details."
1071
1072   ;; Calculate useful stuff.
1073   (multiple-value-bind (input output mask)
1074       (case direction
1075         (:input  (values   t nil sb!unix:o_rdonly))
1076         (:output (values nil   t sb!unix:o_wronly))
1077         (:io     (values   t   t sb!unix:o_rdwr))
1078         (:probe  (values   t nil sb!unix:o_rdonly)))
1079     (declare (type index mask))
1080     (let* ((pathname (merge-pathnames filename))
1081            (namestring
1082             (cond ((unix-namestring pathname input))
1083                   ((and input (eq if-does-not-exist :create))
1084                    (unix-namestring pathname nil)))))
1085       ;; Process if-exists argument if we are doing any output.
1086       (cond (output
1087              (unless if-exists-given
1088                (setf if-exists
1089                      (if (eq (pathname-version pathname) :newest)
1090                          :new-version
1091                          :error)))
1092              (ensure-one-of if-exists
1093                             '(:error :new-version :rename
1094                                      :rename-and-delete :overwrite
1095                                      :append :supersede nil)
1096                             :if-exists)
1097              (case if-exists
1098                ((:error nil)
1099                 (setf mask (logior mask sb!unix:o_excl)))
1100                ((:rename :rename-and-delete)
1101                 (setf mask (logior mask sb!unix:o_creat)))
1102                ((:new-version :supersede)
1103                 (setf mask (logior mask sb!unix:o_trunc)))
1104                (:append
1105                 (setf mask (logior mask sb!unix:o_append)))))
1106             (t
1107              (setf if-exists :ignore-this-arg)))
1108
1109       (unless if-does-not-exist-given
1110         (setf if-does-not-exist
1111               (cond ((eq direction :input) :error)
1112                     ((and output
1113                           (member if-exists '(:overwrite :append)))
1114                      :error)
1115                     ((eq direction :probe)
1116                      nil)
1117                     (t
1118                      :create))))
1119       (ensure-one-of if-does-not-exist
1120                      '(:error :create nil)
1121                      :if-does-not-exist)
1122       (if (eq if-does-not-exist :create)
1123         (setf mask (logior mask sb!unix:o_creat)))
1124
1125       (let ((original (if (member if-exists
1126                                   '(:rename :rename-and-delete))
1127                           (pick-backup-name namestring)))
1128             (delete-original (eq if-exists :rename-and-delete))
1129             (mode #o666))
1130         (when original
1131           ;; We are doing a :RENAME or :RENAME-AND-DELETE. Determine
1132           ;; whether the file already exists, make sure the original
1133           ;; file is not a directory, and keep the mode.
1134           (let ((exists
1135                  (and namestring
1136                       (multiple-value-bind (okay err/dev inode orig-mode)
1137                           (sb!unix:unix-stat namestring)
1138                         (declare (ignore inode)
1139                                  (type (or index null) orig-mode))
1140                         (cond
1141                          (okay
1142                           (when (and output (= (logand orig-mode #o170000)
1143                                                #o40000))
1144                             (error 'simple-file-error
1145                                    :pathname namestring
1146                                    :format-control
1147                                    "can't open ~S for output: is a directory"
1148                                    :format-arguments (list namestring)))
1149                           (setf mode (logand orig-mode #o777))
1150                           t)
1151                          ((eql err/dev sb!unix:enoent)
1152                           nil)
1153                          (t
1154                           (simple-file-perror "can't find ~S"
1155                                               namestring
1156                                               err/dev)))))))
1157             (unless (and exists
1158                          (rename-the-old-one namestring original))
1159               (setf original nil)
1160               (setf delete-original nil)
1161               ;; In order to use :SUPERSEDE instead, we have to make
1162               ;; sure SB!UNIX:O_CREAT corresponds to
1163               ;; IF-DOES-NOT-EXIST. SB!UNIX:O_CREAT was set before
1164               ;; because of IF-EXISTS being :RENAME.
1165               (unless (eq if-does-not-exist :create)
1166                 (setf mask
1167                       (logior (logandc2 mask sb!unix:o_creat)
1168                               sb!unix:o_trunc)))
1169               (setf if-exists :supersede))))
1170
1171         ;; Now we can try the actual Unix open(2).
1172         (multiple-value-bind (fd errno)
1173             (if namestring
1174                 (sb!unix:unix-open namestring mask mode)
1175                 (values nil sb!unix:enoent))
1176           (labels ((open-error (format-control &rest format-arguments)
1177                      (error 'simple-file-error
1178                             :pathname pathname
1179                             :format-control format-control
1180                             :format-arguments format-arguments))
1181                    (vanilla-open-error ()
1182                      (simple-file-perror "error opening ~S" pathname errno)))
1183             (cond ((numberp fd)
1184                    (case direction
1185                      ((:input :output :io)
1186                       (make-fd-stream fd
1187                                       :input input
1188                                       :output output
1189                                       :element-type element-type
1190                                       :file namestring
1191                                       :original original
1192                                       :delete-original delete-original
1193                                       :pathname pathname
1194                                       :input-buffer-p t
1195                                       :auto-close t))
1196                      (:probe
1197                       (let ((stream
1198                              (%make-fd-stream :name namestring
1199                                               :fd fd
1200                                               :pathname pathname
1201                                               :element-type element-type)))
1202                         (close stream)
1203                         stream))))
1204                   ((eql errno sb!unix:enoent)
1205                    (case if-does-not-exist
1206                      (:error (vanilla-open-error))
1207                      (:create
1208                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
1209                                   pathname))
1210                      (t nil)))
1211                   ((and (eql errno sb!unix:eexist) if-exists)
1212                    nil)
1213                   (t
1214                    (vanilla-open-error)))))))))
1215 \f
1216 ;;;; initialization
1217
1218 ;;; the stream connected to the controlling terminal, or NIL if there is none
1219 (defvar *tty*)
1220
1221 ;;; the stream connected to the standard input (file descriptor 0)
1222 (defvar *stdin*)
1223
1224 ;;; the stream connected to the standard output (file descriptor 1)
1225 (defvar *stdout*)
1226
1227 ;;; the stream connected to the standard error output (file descriptor 2)
1228 (defvar *stderr*)
1229
1230 ;;; This is called when the cold load is first started up, and may also
1231 ;;; be called in an attempt to recover from nested errors.
1232 (defun stream-cold-init-or-reset ()
1233   (stream-reinit)
1234   (setf *terminal-io* (make-synonym-stream '*tty*))
1235   (setf *standard-output* (make-synonym-stream '*stdout*))
1236   (setf *standard-input* (make-synonym-stream '*stdin*))
1237   (setf *error-output* (make-synonym-stream '*stderr*))
1238   (setf *query-io* (make-synonym-stream '*terminal-io*))
1239   (setf *debug-io* *query-io*)
1240   (setf *trace-output* *standard-output*)
1241   (values))
1242
1243 ;;; This is called whenever a saved core is restarted.
1244 (defun stream-reinit ()
1245   (setf *available-buffers* nil)
1246   (setf *stdin*
1247         (make-fd-stream 0 :name "standard input" :input t :buffering :line))
1248   (setf *stdout*
1249         (make-fd-stream 1 :name "standard output" :output t :buffering :line))
1250   (setf *stderr*
1251         (make-fd-stream 2 :name "standard error" :output t :buffering :line))
1252   (let ((tty (sb!unix:unix-open "/dev/tty" sb!unix:o_rdwr #o666)))
1253     (if tty
1254         (setf *tty*
1255               (make-fd-stream tty
1256                               :name "the terminal"
1257                               :input t
1258                               :output t
1259                               :buffering :line
1260                               :auto-close t))
1261         (setf *tty* (make-two-way-stream *stdin* *stdout*))))
1262   (values))
1263 \f
1264 ;;;; miscellany
1265
1266 ;;; the Unix way to beep
1267 (defun beep (stream)
1268   (write-char (code-char bell-char-code) stream)
1269   (finish-output stream))
1270
1271 ;;; This is kind of like FILE-POSITION, but is an internal hack used
1272 ;;; by the filesys stuff to get and set the file name.
1273 ;;;
1274 ;;; FIXME: misleading name, screwy interface
1275 (defun file-name (stream &optional new-name)
1276   (when (typep stream 'file-stream)
1277       (cond (new-name
1278              (setf (fd-stream-pathname stream) new-name)
1279              (setf (fd-stream-file stream)
1280                    (unix-namestring new-name nil))
1281              t)
1282             (t
1283              (fd-stream-pathname stream)))))
1284 \f
1285 ;;;; international character support (which is trivial for our simple
1286 ;;;; character sets)
1287
1288 ;;;; (Those who do Lisp only in English might not remember that ANSI
1289 ;;;; requires these functions to be exported from package
1290 ;;;; COMMON-LISP.)
1291
1292 (defun file-string-length (stream object)
1293   (declare (type (or string character) object) (type file-stream stream))
1294   #!+sb-doc
1295   "Return the delta in STREAM's FILE-POSITION that would be caused by writing
1296    OBJECT to STREAM. Non-trivial only in implementations that support
1297    international character sets."
1298   (declare (ignore stream))
1299   (etypecase object
1300     (character 1)
1301     (string (length object))))
1302
1303 (defun stream-external-format (stream)
1304   (declare (type file-stream stream) (ignore stream))
1305   #!+sb-doc
1306   "Return :DEFAULT."
1307   :default)