a2e45dd92b585a5324b497e9249c207bfddbcd03
[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 ;;; FIXME: Wouldn't it be clearer to just have the structure
15 ;;; definition be DEFSTRUCT FILE-STREAM (instead of DEFSTRUCT
16 ;;; FD-STREAM)? That way we'd have TYPE-OF and PRINT-OBJECT refer to
17 ;;; these objects as FILE-STREAMs (the ANSI name) instead of the
18 ;;; internal implementation name FD-STREAM, and there might be other
19 ;;; benefits as well.
20 (deftype file-stream () 'fd-stream)
21 \f
22 ;;;; buffer manipulation routines
23
24 ;;; FIXME: Is it really good to maintain this pool separate from the
25 ;;; GC and the C malloc logic?
26 (defvar *available-buffers* ()
27   #!+sb-doc
28   "List of available buffers. Each buffer is an sap pointing to
29   bytes-per-buffer of memory.")
30
31 (defconstant bytes-per-buffer (* 4 1024)
32   #!+sb-doc
33   "Number of bytes per buffer.")
34
35 ;;; Return the next available buffer, creating one if necessary.
36 #!-sb-fluid (declaim (inline next-available-buffer))
37 (defun next-available-buffer ()
38   (if *available-buffers*
39       (pop *available-buffers*)
40       (allocate-system-memory bytes-per-buffer)))
41 \f
42 ;;;; the FD-STREAM structure
43
44 (defstruct (fd-stream
45             (:constructor %make-fd-stream)
46             (:include lisp-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 fd-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-stream-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 do-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                                           (do-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 do-output (stream base start end reuse-sap)
172   (declare (type fd-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       (do-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:byte-bits)
320                                    (fd-stream-obuf-sap fd-stream)
321                                    (* tail sb!vm:byte-bits)
322                                    (* bytes sb!vm: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:byte-bits)
327                                          (* sb!vm:vector-data-offset
328                                             sb!vm:word-bits))
329                                       (fd-stream-obuf-sap fd-stream)
330                                       (* tail sb!vm:byte-bits)
331                                       (* bytes sb!vm: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:byte-bits)
338                                    (fd-stream-obuf-sap fd-stream)
339                                    0
340                                    (* bytes sb!vm: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:byte-bits)
345                                          (* sb!vm:vector-data-offset
346                                             sb!vm:word-bits))
347                                       (fd-stream-obuf-sap fd-stream)
348                                       0
349                                       (* bytes sb!vm:byte-bits)))
350              (setf (fd-stream-obuf-tail fd-stream) bytes))
351             (t
352              (flush-output-buffer fd-stream)
353              (do-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                                  (position #\newline (the simple-string thing)
373                                            :from-end t
374                                            :start start
375                                            :end end))))
376           (ecase (fd-stream-buffering stream)
377             (:full
378              (output-raw-bytes stream thing start end))
379             (:line
380              (output-raw-bytes stream thing start end)
381              (when last-newline
382                (flush-output-buffer stream)))
383             (:none
384              (do-output stream thing start end nil)))
385           (if last-newline
386               (setf (fd-stream-char-pos stream)
387                     (- end last-newline 1))
388               (incf (fd-stream-char-pos stream)
389                     (- end start))))
390         (ecase (fd-stream-buffering stream)
391           ((:line :full)
392            (output-raw-bytes stream thing start end))
393           (:none
394            (do-output stream thing start end nil))))))
395
396 ;;; Find an output routine to use given the type and buffering. Return
397 ;;; as multiple values the routine, the real type transfered, and the
398 ;;; number of bytes per element.
399 (defun pick-output-routine (type buffering)
400   (dolist (entry *output-routines*)
401     (when (and (subtypep type (car entry))
402                (eq buffering (cadr entry)))
403       (return (values (symbol-function (caddr entry))
404                       (car entry)
405                       (cadddr entry))))))
406 \f
407 ;;;; input routines and related noise
408
409 ;;; a list of all available input routines. Each element is a list of
410 ;;; the element-type input, the function name, and the number of bytes
411 ;;; per element.
412 (defvar *input-routines* ())
413
414 ;;; Fill the input buffer, and return the first character. Throw to
415 ;;; EOF-INPUT-CATCHER if the eof was reached. Drop into SYSTEM:SERVER
416 ;;; if necessary.
417 (defun do-input (stream)
418   (let ((fd (fd-stream-fd stream))
419         (ibuf-sap (fd-stream-ibuf-sap stream))
420         (buflen (fd-stream-ibuf-length stream))
421         (head (fd-stream-ibuf-head stream))
422         (tail (fd-stream-ibuf-tail stream)))
423     (declare (type index head tail))
424     (unless (zerop head)
425       (cond ((eql head tail)
426              (setf head 0)
427              (setf tail 0)
428              (setf (fd-stream-ibuf-head stream) 0)
429              (setf (fd-stream-ibuf-tail stream) 0))
430             (t
431              (decf tail head)
432              (system-area-copy ibuf-sap (* head sb!vm:byte-bits)
433                                ibuf-sap 0 (* tail sb!vm:byte-bits))
434              (setf head 0)
435              (setf (fd-stream-ibuf-head stream) 0)
436              (setf (fd-stream-ibuf-tail stream) tail))))
437     (setf (fd-stream-listen stream) nil)
438     (multiple-value-bind (count errno)
439         ;; FIXME: Judging from compiler warnings, this WITH-ALIEN form expands
440         ;; into something which uses the not-yet-defined type
441         ;;   (SB!ALIEN-INTERNALS:ALIEN (* (SB!ALIEN:STRUCT SB!UNIX:FD-SET))).
442         ;; This is probably inefficient and unsafe and generally bad, so
443         ;; try to find some way to make that type known before
444         ;; this is compiled.
445         (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set)))
446           (sb!unix:fd-zero read-fds)
447           (sb!unix:fd-set fd read-fds)
448           (sb!unix:unix-fast-select (1+ fd)
449                                     (sb!alien:addr read-fds)
450                                     nil
451                                     nil
452                                     0
453                                     0))
454       (case count
455         (1)
456         (0
457          (unless #!-mp (sb!sys:wait-until-fd-usable
458                        fd :input (fd-stream-timeout stream))
459                  #!+mp (sb!mp:process-wait-until-fd-usable
460                        fd :input (fd-stream-timeout stream))
461            (error 'io-timeout :stream stream :direction :read)))
462         (t
463          (simple-stream-perror "couldn't check whether ~S is readable"
464                                stream
465                                errno))))
466     (multiple-value-bind (count errno)
467         (sb!unix:unix-read fd
468                            (sb!sys:int-sap (+ (sb!sys:sap-int ibuf-sap) tail))
469                            (- buflen tail))
470       (cond ((null count)
471              (if (eql errno sb!unix:ewouldblock)
472                  (progn
473                    (unless #!-mp (sb!sys:wait-until-fd-usable
474                                  fd :input (fd-stream-timeout stream))
475                            #!+mp (sb!mp:process-wait-until-fd-usable
476                                  fd :input (fd-stream-timeout stream))
477                      (error 'io-timeout :stream stream :direction :read))
478                    (do-input stream))
479                  (simple-stream-perror "couldn't read from ~S" stream errno)))
480             ((zerop count)
481              (setf (fd-stream-listen stream) :eof)
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 DO-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          (do-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 ;;; Returns a string constructed from the 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:byte-bits)
584                            string (* sb!vm:vector-data-offset sb!vm:word-bits)
585                            (* length sb!vm:byte-bits))
586     string))
587
588 ;;; the N-BIN method for FD-STREAMs. This blocks in UNIX-READ. It is
589 ;;; generally used where there is a definite amount of reading to be
590 ;;; done, so blocking isn't too problematical.
591 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
592   (declare (type fd-stream stream))
593   (declare (type index start requested))
594   (do ((total-copied 0))
595       (nil)
596     (declare (type index total-copied))
597     (let* ((remaining-request (- requested total-copied))
598            (head (fd-stream-ibuf-head stream))
599            (tail (fd-stream-ibuf-tail stream))
600            (available (- tail head))
601            (this-copy (min remaining-request available))
602            (this-start (+ start total-copied))
603            (sap (fd-stream-ibuf-sap stream)))
604       (declare (type index remaining-request head tail available))
605       (declare (type index this-copy))
606       ;; Copy data from stream buffer into user's buffer. 
607       (if (typep buffer 'system-area-pointer)
608           (system-area-copy sap (* head sb!vm:byte-bits)
609                             buffer (* this-start sb!vm:byte-bits)
610                             (* this-copy sb!vm:byte-bits))
611           (copy-from-system-area sap (* head sb!vm:byte-bits)
612                                  buffer (+ (* this-start sb!vm:byte-bits)
613                                            (* sb!vm:vector-data-offset
614                                               sb!vm:word-bits))
615                                  (* this-copy sb!vm:byte-bits)))
616       (incf (fd-stream-ibuf-head stream) this-copy)
617       (incf total-copied this-copy)
618       ;; Maybe we need to refill the stream buffer.
619       (cond (;; If there were enough data in the stream buffer, we're done.
620              (= total-copied requested)
621              (return total-copied))
622             (;; If EOF, we're done in another way.
623              (zerop (refill-fd-stream-buffer stream))
624              (if eof-error-p
625                  (error 'end-of-file :stream stream)
626                  (return total-copied)))
627             ;; Otherwise we refilled the stream buffer, so fall
628             ;; through into another pass of the loop.
629             ))))
630
631 ;;; Try to refill the stream buffer. Return the number of bytes read.
632 ;;; (For EOF, the return value will be zero, otherwise positive.)
633 (defun refill-fd-stream-buffer (stream)
634   ;; We don't have any logic to preserve leftover bytes in the buffer,
635   ;; so we should only be called when the buffer is empty.
636   (aver (= (fd-stream-ibuf-head stream) (fd-stream-ibuf-tail stream)))
637   (multiple-value-bind (count err)
638       (sb!unix:unix-read (fd-stream-fd stream)
639                          (fd-stream-ibuf-sap stream)
640                          (fd-stream-ibuf-length stream))
641     (declare (type (or index null) count))
642     (when (null count)
643       (simple-stream-perror "couldn't read from ~S" stream err))
644     (setf (fd-stream-listen stream) nil
645           (fd-stream-ibuf-head stream) 0
646           (fd-stream-ibuf-tail stream) count)
647     count))
648 \f
649 ;;;; utility functions (misc routines, etc)
650
651 ;;; Fill in the various routine slots for the given type. INPUT-P and
652 ;;; OUTPUT-P indicate what slots to fill. The buffering slot must be
653 ;;; set prior to calling this routine.
654 (defun set-fd-stream-routines (fd-stream type input-p output-p buffer-p)
655   (let ((target-type (case type
656                        ((:default unsigned-byte)
657                         '(unsigned-byte 8))
658                        (signed-byte
659                         '(signed-byte 8))
660                        (t
661                         type)))
662         (input-type nil)
663         (output-type nil)
664         (input-size nil)
665         (output-size nil))
666
667     (when (fd-stream-obuf-sap fd-stream)
668       (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
669       (setf (fd-stream-obuf-sap fd-stream) nil))
670     (when (fd-stream-ibuf-sap fd-stream)
671       (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
672       (setf (fd-stream-ibuf-sap fd-stream) nil))
673
674     (when input-p
675       (multiple-value-bind (routine type size)
676           (pick-input-routine target-type)
677         (unless routine
678           (error "could not find any input routine for ~S" target-type))
679         (setf (fd-stream-ibuf-sap fd-stream) (next-available-buffer))
680         (setf (fd-stream-ibuf-length fd-stream) bytes-per-buffer)
681         (setf (fd-stream-ibuf-tail fd-stream) 0)
682         (if (subtypep type 'character)
683             (setf (fd-stream-in fd-stream) routine
684                   (fd-stream-bin fd-stream) #'ill-bin)
685             (setf (fd-stream-in fd-stream) #'ill-in
686                   (fd-stream-bin fd-stream) routine))
687         (when (eql size 1)
688           (setf (fd-stream-n-bin fd-stream) #'fd-stream-read-n-bytes)
689           (when buffer-p
690             (setf (lisp-stream-in-buffer fd-stream)
691                   (make-array +in-buffer-length+
692                               :element-type '(unsigned-byte 8)))))
693         (setf input-size size)
694         (setf input-type type)))
695
696     (when output-p
697       (multiple-value-bind (routine type size)
698           (pick-output-routine target-type (fd-stream-buffering fd-stream))
699         (unless routine
700           (error "could not find any output routine for ~S buffered ~S"
701                  (fd-stream-buffering fd-stream)
702                  target-type))
703         (setf (fd-stream-obuf-sap fd-stream) (next-available-buffer))
704         (setf (fd-stream-obuf-length fd-stream) bytes-per-buffer)
705         (setf (fd-stream-obuf-tail fd-stream) 0)
706         (if (subtypep type 'character)
707           (setf (fd-stream-out fd-stream) routine
708                 (fd-stream-bout fd-stream) #'ill-bout)
709           (setf (fd-stream-out fd-stream)
710                 (or (if (eql size 1)
711                       (pick-output-routine 'base-char
712                                            (fd-stream-buffering fd-stream)))
713                     #'ill-out)
714                 (fd-stream-bout fd-stream) routine))
715         (setf (fd-stream-sout fd-stream)
716               (if (eql size 1) #'fd-sout #'ill-out))
717         (setf (fd-stream-char-pos fd-stream) 0)
718         (setf output-size size)
719         (setf output-type type)))
720
721     (when (and input-size output-size
722                (not (eq input-size output-size)))
723       (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
724              input-type input-size
725              output-type output-size))
726     (setf (fd-stream-element-size fd-stream)
727           (or input-size output-size))
728
729     (setf (fd-stream-element-type fd-stream)
730           (cond ((equal input-type output-type)
731                  input-type)
732                 ((null output-type)
733                  input-type)
734                 ((null input-type)
735                  output-type)
736                 ((subtypep input-type output-type)
737                  input-type)
738                 ((subtypep output-type input-type)
739                  output-type)
740                 (t
741                  (error "Input type (~S) and output type (~S) are unrelated?"
742                         input-type
743                         output-type))))))
744
745 ;;; Handle miscellaneous operations on FD-STREAM.
746 (defun fd-stream-misc-routine (fd-stream operation &optional arg1 arg2)
747   (declare (ignore arg2))
748   (case operation
749     (:listen
750      (or (not (eql (fd-stream-ibuf-head fd-stream)
751                    (fd-stream-ibuf-tail fd-stream)))
752          (fd-stream-listen fd-stream)
753          (setf (fd-stream-listen fd-stream)
754                (eql (sb!alien:with-alien ((read-fds (sb!alien:struct
755                                                      sb!unix:fd-set)))
756                       (sb!unix:fd-zero read-fds)
757                       (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
758                       (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
759                                                 (sb!alien:addr read-fds)
760                                                 nil nil 0 0))
761                     1))))
762     (:unread
763      (setf (fd-stream-unread fd-stream) arg1)
764      (setf (fd-stream-listen fd-stream) t))
765     (:close
766      (cond (arg1
767             ;; We got us an abort on our hands.
768             (when (fd-stream-handler fd-stream)
769                   (sb!sys:remove-fd-handler (fd-stream-handler fd-stream))
770                   (setf (fd-stream-handler fd-stream) nil))
771             (when (and (fd-stream-file fd-stream)
772                        (fd-stream-obuf-sap fd-stream))
773               ;; We can't do anything unless we know what file were
774               ;; dealing with, and we don't want to do anything
775               ;; strange unless we were writing to the file.
776               (if (fd-stream-original fd-stream)
777                   ;; We have a handle on the original, just revert.
778                   (multiple-value-bind (okay err)
779                       (sb!unix:unix-rename (fd-stream-original fd-stream)
780                                            (fd-stream-file fd-stream))
781                     (unless okay
782                       (simple-stream-perror
783                        "couldn't restore ~S to its original contents"
784                        fd-stream
785                        err)))
786                   ;; We can't restore the original, so nuke that puppy.
787                   (multiple-value-bind (okay err)
788                       (sb!unix:unix-unlink (fd-stream-file fd-stream))
789                     (unless okay
790                       (error 'simple-file-error
791                              :pathname (fd-stream-file fd-stream)
792                              :format-control
793                              "~@<couldn't remove ~S: ~2I~_~A~:>"
794                              :format-arguments (list (fd-stream-file fd-stream)
795                                                      (strerror err))))))))
796            (t
797             (fd-stream-misc-routine fd-stream :finish-output)
798             (when (and (fd-stream-original fd-stream)
799                        (fd-stream-delete-original fd-stream))
800               (multiple-value-bind (okay err)
801                   (sb!unix:unix-unlink (fd-stream-original fd-stream))
802                 (unless okay
803                   (error 'simple-file-error
804                          :pathname (fd-stream-original fd-stream)
805                          :format-control 
806                          "~@<couldn't delete ~S during close of ~S: ~
807                           ~2I~_~A~:>"
808                          :format-arguments
809                          (list (fd-stream-original fd-stream)
810                                fd-stream
811                                (strerror err))))))))
812      (when (fboundp 'cancel-finalization)
813        (cancel-finalization fd-stream))
814      (sb!unix:unix-close (fd-stream-fd fd-stream))
815      (when (fd-stream-obuf-sap fd-stream)
816        (push (fd-stream-obuf-sap fd-stream) *available-buffers*)
817        (setf (fd-stream-obuf-sap fd-stream) nil))
818      (when (fd-stream-ibuf-sap fd-stream)
819        (push (fd-stream-ibuf-sap fd-stream) *available-buffers*)
820        (setf (fd-stream-ibuf-sap fd-stream) nil))
821      (sb!impl::set-closed-flame fd-stream))
822     (:clear-input
823      (setf (fd-stream-unread fd-stream) nil)
824      (setf (fd-stream-ibuf-head fd-stream) 0)
825      (setf (fd-stream-ibuf-tail fd-stream) 0)
826      (catch 'eof-input-catcher
827        (loop
828         (let ((count (sb!alien:with-alien ((read-fds (sb!alien:struct
829                                                       sb!unix:fd-set)))
830                        (sb!unix:fd-zero read-fds)
831                        (sb!unix:fd-set (fd-stream-fd fd-stream) read-fds)
832                        (sb!unix:unix-fast-select (1+ (fd-stream-fd fd-stream))
833                                                  (sb!alien:addr read-fds)
834                                                  nil
835                                                  nil
836                                                  0
837                                                  0))))
838           (cond ((eql count 1)
839                  (do-input fd-stream)
840                  (setf (fd-stream-ibuf-head fd-stream) 0)
841                  (setf (fd-stream-ibuf-tail fd-stream) 0))
842                 (t
843                  (return t)))))))
844     (:force-output
845      (flush-output-buffer fd-stream))
846     (:finish-output
847      (flush-output-buffer fd-stream)
848      (do ()
849          ((null (fd-stream-output-later fd-stream)))
850        (sb!sys:serve-all-events)))
851     (:element-type
852      (fd-stream-element-type fd-stream))
853     (:interactive-p
854       ;; FIXME: sb!unix:unix-isatty is undefined.
855      (sb!unix:unix-isatty (fd-stream-fd fd-stream)))
856     (:line-length
857      80)
858     (:charpos
859      (fd-stream-char-pos fd-stream))
860     (:file-length
861      (multiple-value-bind (okay dev ino mode nlink uid gid rdev size
862                            atime mtime ctime blksize blocks)
863          (sb!unix:unix-fstat (fd-stream-fd fd-stream))
864        (declare (ignore ino nlink uid gid rdev
865                         atime mtime ctime blksize blocks))
866        (unless okay
867          (simple-stream-perror "failed Unix fstat(2) on ~S" fd-stream dev))
868        (if (zerop mode)
869            nil
870            (truncate size (fd-stream-element-size fd-stream)))))
871     (:file-position
872      (fd-stream-file-position fd-stream arg1))))
873
874 (defun fd-stream-file-position (stream &optional newpos)
875   (declare (type fd-stream stream)
876            (type (or index (member nil :start :end)) newpos))
877   (if (null newpos)
878       (sb!sys:without-interrupts
879         ;; First, find the position of the UNIX file descriptor in the
880         ;; file.
881         (multiple-value-bind (posn errno)
882             (sb!unix:unix-lseek (fd-stream-fd stream) 0 sb!unix:l_incr)
883           (declare (type (or index null) posn))
884           (cond ((fixnump posn)
885                  ;; Adjust for buffered output: If there is any output
886                  ;; buffered, the *real* file position will be larger
887                  ;; than reported by lseek because lseek obviously
888                  ;; cannot take into account output we have not sent
889                  ;; yet.
890                  (dolist (later (fd-stream-output-later stream))
891                    (incf posn (- (the index (caddr later))
892                                  (the index (cadr later)))))
893                  (incf posn (fd-stream-obuf-tail stream))
894                  ;; Adjust for unread input: If there is any input
895                  ;; read from UNIX but not supplied to the user of the
896                  ;; stream, the *real* file position will smaller than
897                  ;; reported, because we want to look like the unread
898                  ;; stuff is still available.
899                  (decf posn (- (fd-stream-ibuf-tail stream)
900                                (fd-stream-ibuf-head stream)))
901                  (when (fd-stream-unread stream)
902                    (decf posn))
903                  ;; Divide bytes by element size.
904                  (truncate posn (fd-stream-element-size stream)))
905                 ((eq errno sb!unix:espipe)
906                  nil)
907                 (t
908                  (sb!sys:with-interrupts
909                    (simple-stream-perror "failure in Unix lseek() on ~S"
910                                          stream
911                                          errno))))))
912       (let ((offset 0) origin)
913         (declare (type index offset))
914         ;; Make sure we don't have any output pending, because if we
915         ;; move the file pointer before writing this stuff, it will be
916         ;; written in the wrong location.
917         (flush-output-buffer stream)
918         (do ()
919             ((null (fd-stream-output-later stream)))
920           (sb!sys:serve-all-events))
921         ;; Clear out any pending input to force the next read to go to
922         ;; the disk.
923         (setf (fd-stream-unread stream) nil)
924         (setf (fd-stream-ibuf-head stream) 0)
925         (setf (fd-stream-ibuf-tail stream) 0)
926         ;; Trash cached value for listen, so that we check next time.
927         (setf (fd-stream-listen stream) nil)
928         ;; Now move it.
929         (cond ((eq newpos :start)
930                (setf offset 0 origin sb!unix:l_set))
931               ((eq newpos :end)
932                (setf offset 0 origin sb!unix:l_xtnd))
933               ((typep newpos 'index)
934                (setf offset (* newpos (fd-stream-element-size stream))
935                      origin sb!unix:l_set))
936               (t
937                (error "invalid position given to FILE-POSITION: ~S" newpos)))
938         (multiple-value-bind (posn errno)
939             (sb!unix:unix-lseek (fd-stream-fd stream) offset origin)
940           (cond ((typep posn 'fixnum)
941                  t)
942                 ((eq errno sb!unix:espipe)
943                  nil)
944                 (t
945                  (simple-stream-perror "error in Unix lseek() on ~S"
946                                        stream
947                                        errno)))))))
948 \f
949 ;;;; creation routines (MAKE-FD-STREAM and OPEN)
950
951 ;;; Create a stream for the given Unix file descriptor.
952 ;;;
953 ;;; If INPUT is non-NIL, allow input operations. If OUTPUT is non-nil,
954 ;;; allow output operations. If neither INPUT nor OUTPUT is specified,
955 ;;; default to allowing input.
956 ;;;
957 ;;; ELEMENT-TYPE indicates the element type to use (as for OPEN).
958 ;;;
959 ;;; BUFFERING indicates the kind of buffering to use.
960 ;;;
961 ;;; TIMEOUT (if true) is the number of seconds to wait for input. If
962 ;;; NIL (the default), then wait forever. When we time out, we signal
963 ;;; IO-TIMEOUT.
964 ;;;
965 ;;; FILE is the name of the file (will be returned by PATHNAME).
966 ;;;
967 ;;; NAME is used to identify the stream when printed.
968 (defun make-fd-stream (fd
969                        &key
970                        (input nil input-p)
971                        (output nil output-p)
972                        (element-type 'base-char)
973                        (buffering :full)
974                        timeout
975                        file
976                        original
977                        delete-original
978                        pathname
979                        input-buffer-p
980                        (name (if file
981                                  (format nil "file ~S" file)
982                                  (format nil "descriptor ~D" fd)))
983                        auto-close)
984   (declare (type index fd) (type (or index null) timeout)
985            (type (member :none :line :full) buffering))
986   (cond ((not (or input-p output-p))
987          (setf input t))
988         ((not (or input output))
989          (error "File descriptor must be opened either for input or output.")))
990   (let ((stream (%make-fd-stream :fd fd
991                                  :name name
992                                  :file file
993                                  :original original
994                                  :delete-original delete-original
995                                  :pathname pathname
996                                  :buffering buffering
997                                  :timeout timeout)))
998     (set-fd-stream-routines stream element-type input output input-buffer-p)
999     (when (and auto-close (fboundp 'finalize))
1000       (finalize stream
1001                 (lambda ()
1002                   (sb!unix:unix-close fd)
1003                   #!+sb-show
1004                   (format *terminal-io* "** closed file descriptor ~D **~%"
1005                           fd))))
1006     stream))
1007
1008 ;;; Pick a name to use for the backup file for the :IF-EXISTS
1009 ;;; :RENAME-AND-DELETE and :RENAME options.
1010 (defun pick-backup-name (name)
1011   (declare (type simple-string name))
1012   (concatenate 'simple-string name ".bak"))
1013
1014 ;;; Ensure that the given arg is one of the given list of valid
1015 ;;; things. Allow the user to fix any problems.
1016 (defun ensure-one-of (item list what)
1017   (unless (member item list)
1018     (error 'simple-type-error
1019            :datum item
1020            :expected-type `(member ,@list)
1021            :format-control "~@<~S is ~_invalid for ~S; ~_need one of~{ ~S~}~:>"
1022            :format-arguments (list item what list))))
1023
1024 ;;; Rename NAMESTRING to ORIGINAL. First, check whether we have write
1025 ;;; access, since we don't want to trash unwritable files even if we
1026 ;;; technically can. We return true if we succeed in renaming.
1027 (defun do-old-rename (namestring original)
1028   (unless (sb!unix:unix-access namestring sb!unix:w_ok)
1029     (error "~@<The file ~2I~_~S ~I~_is not writable.~:>" namestring))
1030   (multiple-value-bind (okay err) (sb!unix:unix-rename namestring original)
1031     (if okay
1032         t
1033         (error 'simple-file-error
1034                :pathname namestring
1035                :format-control 
1036                "~@<couldn't rename ~2I~_~S ~I~_to ~2I~_~S: ~4I~_~A~:>"
1037                :format-arguments (list namestring original (strerror err))))))
1038
1039 (defun open (filename
1040              &key
1041              (direction :input)
1042              (element-type 'base-char)
1043              (if-exists nil if-exists-given)
1044              (if-does-not-exist nil if-does-not-exist-given)
1045              (external-format :default)
1046              &aux ; Squelch assignment warning.
1047              (direction direction)
1048              (if-does-not-exist if-does-not-exist)
1049              (if-exists if-exists))
1050   #!+sb-doc
1051   "Return a stream which reads from or writes to FILENAME.
1052   Defined keywords:
1053    :DIRECTION - one of :INPUT, :OUTPUT, :IO, or :PROBE
1054    :ELEMENT-TYPE - the type of object to read or write, default BASE-CHAR
1055    :IF-EXISTS - one of :ERROR, :NEW-VERSION, :RENAME, :RENAME-AND-DELETE,
1056                        :OVERWRITE, :APPEND, :SUPERSEDE or NIL
1057    :IF-DOES-NOT-EXIST - one of :ERROR, :CREATE or nil
1058   See the manual for details."
1059
1060   (unless (eq external-format :default)
1061     (error "Any external format other than :DEFAULT isn't recognized."))
1062
1063   ;; First, make sure that DIRECTION is valid.
1064   (ensure-one-of direction
1065                  '(:input :output :io :probe)
1066                  :direction)
1067
1068   ;; Calculate useful stuff.
1069   (multiple-value-bind (input output mask)
1070       (case direction
1071         (:input  (values   t nil sb!unix:o_rdonly))
1072         (:output (values nil   t sb!unix:o_wronly))
1073         (:io     (values   t   t sb!unix:o_rdwr))
1074         (:probe  (values   t nil sb!unix:o_rdonly)))
1075     (declare (type index mask))
1076     (let* ((pathname (pathname filename))
1077            (namestring
1078             (cond ((unix-namestring pathname input))
1079                   ((and input (eq if-does-not-exist :create))
1080                    (unix-namestring pathname nil)))))
1081       ;; Process if-exists argument if we are doing any output.
1082       (cond (output
1083              (unless if-exists-given
1084                (setf if-exists
1085                      (if (eq (pathname-version pathname) :newest)
1086                          :new-version
1087                          :error)))
1088              (ensure-one-of if-exists
1089                             '(:error :new-version :rename
1090                                      :rename-and-delete :overwrite
1091                                      :append :supersede nil)
1092                             :if-exists)
1093              (case if-exists
1094                ((:error nil)
1095                 (setf mask (logior mask sb!unix:o_excl)))
1096                ((:rename :rename-and-delete)
1097                 (setf mask (logior mask sb!unix:o_creat)))
1098                ((:new-version :supersede)
1099                 (setf mask (logior mask sb!unix:o_trunc)))
1100                (:append
1101                 (setf mask (logior mask sb!unix:o_append)))))
1102             (t
1103              (setf if-exists :ignore-this-arg)))
1104
1105       (unless if-does-not-exist-given
1106         (setf if-does-not-exist
1107               (cond ((eq direction :input) :error)
1108                     ((and output
1109                           (member if-exists '(:overwrite :append)))
1110                      :error)
1111                     ((eq direction :probe)
1112                      nil)
1113                     (t
1114                      :create))))
1115       (ensure-one-of if-does-not-exist
1116                      '(:error :create nil)
1117                      :if-does-not-exist)
1118       (if (eq if-does-not-exist :create)
1119         (setf mask (logior mask sb!unix:o_creat)))
1120
1121       (let ((original (if (member if-exists
1122                                   '(:rename :rename-and-delete))
1123                           (pick-backup-name namestring)))
1124             (delete-original (eq if-exists :rename-and-delete))
1125             (mode #o666))
1126         (when original
1127           ;; We are doing a :RENAME or :RENAME-AND-DELETE.
1128           ;; Determine whether the file already exists, make sure the original
1129           ;; file is not a directory, and keep the mode.
1130           (let ((exists
1131                  (and namestring
1132                       (multiple-value-bind (okay err/dev inode orig-mode)
1133                           (sb!unix:unix-stat namestring)
1134                         (declare (ignore inode)
1135                                  (type (or index null) orig-mode))
1136                         (cond
1137                          (okay
1138                           (when (and output (= (logand orig-mode #o170000)
1139                                                #o40000))
1140                             (error 'simple-file-error
1141                                    :pathname namestring
1142                                    :format-control
1143                                    "can't open ~S for output: is a directory"
1144                                    :format-arguments (list namestring)))
1145                           (setf mode (logand orig-mode #o777))
1146                           t)
1147                          ((eql err/dev sb!unix:enoent)
1148                           nil)
1149                          (t
1150                           (simple-file-perror "can't find ~S"
1151                                               namestring
1152                                               err/dev)))))))
1153             (unless (and exists
1154                          (do-old-rename namestring original))
1155               (setf original nil)
1156               (setf delete-original nil)
1157               ;; In order to use :SUPERSEDE instead, we have to make sure
1158               ;; SB!UNIX:O_CREAT corresponds to IF-DOES-NOT-EXIST.
1159               ;; SB!UNIX:O_CREAT was set before because of IF-EXISTS being
1160               ;; :RENAME.
1161               (unless (eq if-does-not-exist :create)
1162                 (setf mask
1163                       (logior (logandc2 mask sb!unix:o_creat)
1164                               sb!unix:o_trunc)))
1165               (setf if-exists :supersede))))
1166         
1167         ;; Now we can try the actual Unix open(2).
1168         (multiple-value-bind (fd errno)
1169             (if namestring
1170                 (sb!unix:unix-open namestring mask mode)
1171                 (values nil sb!unix:enoent))
1172           (labels ((open-error (format-control &rest format-arguments)
1173                      (error 'simple-file-error
1174                             :pathname pathname
1175                             :format-control format-control
1176                             :format-arguments format-arguments))
1177                    (vanilla-open-error ()
1178                      (simple-file-perror "error opening ~S" pathname errno)))
1179             (cond ((numberp fd)
1180                    (case direction
1181                      ((:input :output :io)
1182                       (make-fd-stream fd
1183                                       :input input
1184                                       :output output
1185                                       :element-type element-type
1186                                       :file namestring
1187                                       :original original
1188                                       :delete-original delete-original
1189                                       :pathname pathname
1190                                       :input-buffer-p t
1191                                       :auto-close t))
1192                      (:probe
1193                       (let ((stream
1194                              (%make-fd-stream :name namestring
1195                                               :fd fd
1196                                               :pathname pathname
1197                                               :element-type element-type)))
1198                         (close stream)
1199                         stream))))
1200                   ((eql errno sb!unix:enoent)
1201                    (case if-does-not-exist
1202                      (:error (vanilla-open-error))
1203                      (:create
1204                       (open-error "~@<The path ~2I~_~S ~I~_does not exist.~:>"
1205                                   pathname))
1206                      (t nil)))
1207                   ((and (eql errno sb!unix:eexist) if-exists)
1208                    nil)
1209                   (t
1210                    (vanilla-open-error)))))))))
1211 \f
1212 ;;;; initialization
1213
1214 ;;; the stream connected to the controlling terminal, or NIL if there is none
1215 (defvar *tty*)
1216
1217 ;;; the stream connected to the standard input (file descriptor 0)
1218 (defvar *stdin*)
1219
1220 ;;; the stream connected to the standard output (file descriptor 1)
1221 (defvar *stdout*)
1222
1223 ;;; the stream connected to the standard error output (file descriptor 2)
1224 (defvar *stderr*)
1225
1226 ;;; This is called when the cold load is first started up, and may also
1227 ;;; be called in an attempt to recover from nested errors.
1228 (defun stream-cold-init-or-reset ()
1229   (stream-reinit)
1230   (setf *terminal-io* (make-synonym-stream '*tty*))
1231   (setf *standard-output* (make-synonym-stream '*stdout*))
1232   (setf *standard-input*
1233         (#!-high-security
1234          ;; FIXME: Why is *STANDARD-INPUT* a TWO-WAY-STREAM? ANSI says
1235          ;; it's an input stream.
1236          make-two-way-stream
1237          #!+high-security
1238          %make-two-way-stream (make-synonym-stream '*stdin*)
1239                              *standard-output*))
1240   (setf *error-output* (make-synonym-stream '*stderr*))
1241   (setf *query-io* (make-synonym-stream '*terminal-io*))
1242   (setf *debug-io* *query-io*)
1243   (setf *trace-output* *standard-output*)
1244   (values))
1245
1246 ;;; This is called whenever a saved core is restarted.
1247 (defun stream-reinit ()
1248   (setf *available-buffers* nil)
1249   (setf *stdin*
1250         (make-fd-stream 0 :name "standard input" :input t :buffering :line))
1251   (setf *stdout*
1252         (make-fd-stream 1 :name "standard output" :output t :buffering :line))
1253   (setf *stderr*
1254         (make-fd-stream 2 :name "standard error" :output t :buffering :line))
1255   (let ((tty (sb!unix:unix-open "/dev/tty" sb!unix:o_rdwr #o666)))
1256     (if tty
1257         (setf *tty*
1258               (make-fd-stream tty
1259                               :name "the terminal"
1260                               :input t
1261                               :output t
1262                               :buffering :line
1263                               :auto-close t))
1264         (setf *tty* (make-two-way-stream *stdin* *stdout*))))
1265   (values))
1266 \f
1267 ;;;; miscellany
1268
1269 ;;; the Unix way to beep
1270 (defun beep (stream)
1271   (write-char (code-char bell-char-code) stream)
1272   (finish-output stream))
1273
1274 ;;; This is kind of like FILE-POSITION, but is an internal hack used
1275 ;;; by the filesys stuff to get and set the file name.
1276 (defun file-name (stream &optional new-name)
1277   (when (typep stream 'fd-stream)
1278       (cond (new-name
1279              (setf (fd-stream-pathname stream) new-name)
1280              (setf (fd-stream-file stream)
1281                    (unix-namestring new-name nil))
1282              t)
1283             (t
1284              (fd-stream-pathname stream)))))
1285 \f
1286 ;;;; international character support (which is trivial for our simple
1287 ;;;; character sets)
1288
1289 ;;;; (Those who do Lisp only in English might not remember that ANSI
1290 ;;;; requires these functions to be exported from package
1291 ;;;; COMMON-LISP.)
1292
1293 (defun file-string-length (stream object)
1294   (declare (type (or string character) object) (type file-stream stream))
1295   #!+sb-doc
1296   "Return the delta in STREAM's FILE-POSITION that would be caused by writing
1297    OBJECT to STREAM. Non-trivial only in implementations that support
1298    international character sets."
1299   (declare (ignore stream))
1300   (etypecase object
1301     (character 1)
1302     (string (length object))))
1303
1304 (defun stream-external-format (stream)
1305   (declare (type file-stream stream) (ignore stream))
1306   #!+sb-doc
1307   "Return :DEFAULT."
1308   :default)