0.pre7.140:
[sbcl.git] / src / code / run-program.lisp
1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
2 ;;;; from inside SBCL
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)
14 \f
15 ;;;; hacking the Unix environment
16 ;;;;
17 ;;;; In the original CMU CL code that LOAD-FOREIGN is derived from, the
18 ;;;; Unix environment (as in "man environ") was represented as an
19 ;;;; alist from keywords to strings, so that e.g. the Unix environment
20 ;;;;   "SHELL=/bin/bash" "HOME=/root" "PAGER=less"
21 ;;;; was represented as
22 ;;;;   ((:SHELL . "/bin/bash") (:HOME . "/root") (:PAGER "less"))
23 ;;;; This had a few problems in principle: the mapping into
24 ;;;; keyword symbols smashed the case of environment
25 ;;;; variables, and the whole mapping depended on the presence of
26 ;;;; #\= characters in the environment strings. In practice these
27 ;;;; problems weren't hugely important, since conventionally environment
28 ;;;; variables are uppercase strings followed by #\= followed by
29 ;;;; arbitrary data. However, since it's so manifestly not The Right
30 ;;;; Thing to make code which breaks unnecessarily on input which
31 ;;;; doesn't follow what is, after all, only a tradition, we've switched
32 ;;;; formats in SBCL, so that the fundamental environment list
33 ;;;; is just a list of strings, with a one-to-one-correspondence
34 ;;;; to the C-level representation. I.e., in the example above,
35 ;;;; the SBCL representation is
36 ;;;;   '("SHELL=/bin/bash" "HOME=/root" "PAGER=less")
37 ;;;; CMU CL's implementation is currently supported to help with porting.
38 ;;;;
39 ;;;; It's not obvious that this code belongs here (instead of e.g. in
40 ;;;; unix.lisp), since it has only a weak logical connection with
41 ;;;; RUN-PROGRAM. However, physically it's convenient to put it here.
42 ;;;; It's not needed at cold init, so we *can* put it in this
43 ;;;; warm-loaded file. And by putting it in this warm-loaded file, we
44 ;;;; make it easy for it to get to the C-level 'environ' variable.
45 ;;;; which (at least in sbcl-0.6.10 on Red Hat Linux 6.2) is not
46 ;;;; visible at GENESIS time.
47
48 (define-alien-variable "environ" (* c-string))
49 (push (lambda ()
50         ;; We redo this here to protect ourselves from this scenario:
51         ;;   * Build under one version of shared lib, save a core.
52         ;;   * Load core under another version of shared lib. ("Now
53         ;;     where was environ again?" SIGSEGV, etc.)
54         ;; Obviously it's a KLUDGE to do this hack for every alien
55         ;; variable, but as it happens, as of sbcl-0.7.0 this is the
56         ;; only alien variable used to implement SBCL, so it's not
57         ;; worth coming up with a general solution. (A general
58         ;; solution would be nice for users who want to have their
59         ;; alien code be preserved across a save/load cycle, but this
60         ;; problem with alien variables is only one of several
61         ;; problems which'd need to be solved before that can happen.)
62         (define-alien-variable "environ" (* c-string)))
63       *after-save-initializations*)
64
65 (defun posix-environ ()
66   "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
67   (c-strings->string-list environ))
68
69 ;;; Convert as best we can from a SBCL representation of a Unix
70 ;;; environment to a CMU CL representation.
71 ;;;
72 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
73 ;;; WARNING:
74 ;;;   smashing case of "Bletch=fub" in conversion to CMU-CL-style
75 ;;;     environment alist
76 ;;; WARNING:
77 ;;;   no #\= in "Noggin", eliding it in CMU-CL-style environment alist
78 ;;; ((:BLETCH . "fub") (:YES . "No!"))
79 (defun unix-environment-cmucl-from-sbcl (sbcl)
80   (mapcan
81    (lambda (string)
82      (declare (type simple-string string))
83      (let ((=-pos (position #\= string :test #'equal)))
84        (if =-pos
85            (list
86             (let* ((key-as-string (subseq string 0 =-pos))
87                    (key-as-upcase-string (string-upcase key-as-string))
88                    (key (keywordicate key-as-upcase-string))
89                    (val (subseq string (1+ =-pos))))
90               (unless (string= key-as-string key-as-upcase-string)
91                 (warn "smashing case of ~S in conversion to CMU-CL-style ~
92                       environment alist"
93                       string))
94               (cons key val)))
95            (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
96                  string))))
97    sbcl))
98
99 ;;; Convert from a CMU CL representation of a Unix environment to a
100 ;;; SBCL representation.
101 (defun unix-environment-sbcl-from-cmucl (cmucl)
102   (mapcar
103    (lambda (cons)
104      (destructuring-bind (key . val) cons
105        (declare (type keyword key) (type simple-string val))
106        (concatenate 'simple-string (symbol-name key) "=" val)))
107    cmucl))
108 \f
109 ;;;; Import wait3(2) from Unix.
110
111 (sb-alien:define-alien-routine ("wait3" c-wait3) sb-alien:int
112   (status sb-alien:int :out)
113   (options sb-alien:int)
114   (rusage sb-alien:int))
115
116 (defconstant wait-wnohang #-svr4 1 #+svr4 #o100)
117 (defconstant wait-wuntraced #-svr4 2 #+svr4 4)
118 (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
119
120 (defun wait3 (&optional do-not-hang check-for-stopped)
121   "Return any available status information on child process. "
122   (multiple-value-bind (pid status)
123       (c-wait3 (logior (if do-not-hang
124                            wait-wnohang
125                            0)
126                        (if check-for-stopped
127                            wait-wuntraced
128                            0))
129                0)
130     (cond ((or (minusp pid)
131                (zerop pid))
132            nil)
133           ((eql (ldb (byte 8 0) status)
134                 wait-wstopped)
135            (values pid
136                    :stopped
137                    (ldb (byte 8 8) status)))
138           ((zerop (ldb (byte 7 0) status))
139            (values pid
140                    :exited
141                    (ldb (byte 8 8) status)))
142           (t
143            (let ((signal (ldb (byte 7 0) status)))
144              (values pid
145                      (if (position signal
146                                    #.(vector
147                                       (sb-unix:unix-signal-number :sigstop)
148                                       (sb-unix:unix-signal-number :sigtstp)
149                                       (sb-unix:unix-signal-number :sigttin)
150                                       (sb-unix:unix-signal-number :sigttou)))
151                          :stopped
152                          :signaled)
153                      signal
154                      (not (zerop (ldb (byte 1 7) status)))))))))
155 \f
156 ;;;; process control stuff
157
158 (defvar *active-processes* nil
159   "List of process structures for all active processes.")
160
161 (defstruct (process (:copier nil))
162   pid                 ; PID of child process
163   %status             ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
164   exit-code           ; either exit code or signal
165   core-dumped         ; T if a core image was dumped
166   pty                 ; stream to child's pty, or NIL
167   input               ; stream to child's input, or NIL
168   output              ; stream from child's output, or NIL
169   error               ; stream from child's error output, or NIL
170   status-hook         ; closure to call when PROC changes status
171   plist               ; a place for clients to stash things
172   cookie)             ; list of the number of pipes from the subproc
173
174 (defmethod print-object ((process process) stream)
175   (print-unreadable-object (process stream :type t)
176     (format stream
177             "~W ~S"
178             (process-pid process)
179             (process-status process)))
180   process)
181
182 (defun process-status (proc)
183   "Return the current status of process.  The result is one of :RUNNING,
184    :STOPPED, :EXITED, or :SIGNALED."
185   (get-processes-status-changes)
186   (process-%status proc))
187
188 (defun process-wait (proc &optional check-for-stopped)
189   "Wait for PROC to quit running for some reason.  Returns PROC."
190   (loop
191       (case (process-status proc)
192         (:running)
193         (:stopped
194          (when check-for-stopped
195            (return)))
196         (t
197          (when (zerop (car (process-cookie proc)))
198            (return))))
199       (sb-sys:serve-all-events 1))
200   proc)
201
202 #-hpux
203 ;;; Find the current foreground process group id.
204 (defun find-current-foreground-process (proc)
205   (sb-alien:with-alien ((result sb-alien:int))
206     (multiple-value-bind
207           (wonp error)
208         (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
209                             sb-unix:TIOCGPGRP
210                             (sb-alien:alien-sap (sb-alien:addr result)))
211       (unless wonp
212         (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
213       result))
214   (process-pid proc))
215
216 (defun process-kill (proc signal &optional (whom :pid))
217   "Hand SIGNAL to PROC. If WHOM is :PID, use the kill Unix system call. If
218    WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
219    :PTY-PROCESS-GROUP deliver the signal to whichever process group is
220    currently in the foreground."
221   (let ((pid (ecase whom
222                ((:pid :process-group)
223                 (process-pid proc))
224                (:pty-process-group
225                 #-hpux
226                 (find-current-foreground-process proc)))))
227     (multiple-value-bind
228           (okay errno)
229         (case whom
230           #+hpux
231           (:pty-process-group
232            (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
233                                sb-unix:TIOCSIGSEND
234                                (sb-sys:int-sap
235                                 (sb-unix:unix-signal-number signal))))
236           ((:process-group #-hpux :pty-process-group)
237            (sb-unix:unix-killpg pid signal))
238           (t
239            (sb-unix:unix-kill pid signal)))
240       (cond ((not okay)
241              (values nil errno))
242             ((and (eql pid (process-pid proc))
243                   (= (sb-unix:unix-signal-number signal)
244                      (sb-unix:unix-signal-number :sigcont)))
245              (setf (process-%status proc) :running)
246              (setf (process-exit-code proc) nil)
247              (when (process-status-hook proc)
248                (funcall (process-status-hook proc) proc))
249              t)
250             (t
251              t)))))
252
253 (defun process-alive-p (proc)
254   "Return T if the process is still alive, NIL otherwise."
255   (let ((status (process-status proc)))
256     (if (or (eq status :running)
257             (eq status :stopped))
258         t
259         nil)))
260
261 (defun process-close (proc)
262   "Close all streams connected to PROC and stop maintaining the status slot."
263   (macrolet ((frob (stream abort)
264                `(when ,stream (close ,stream :abort ,abort))))
265     (frob (process-pty    proc)   t) ; Don't FLUSH-OUTPUT to dead process, ..
266     (frob (process-input  proc)   t) ; .. 'cause it will generate SIGPIPE.
267     (frob (process-output proc) nil)
268     (frob (process-error  proc) nil))
269   (sb-sys:without-interrupts
270    (setf *active-processes* (delete proc *active-processes*)))
271   proc)
272
273 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
274 (defun sigchld-handler (ignore1 ignore2 ignore3)
275   (declare (ignore ignore1 ignore2 ignore3))
276   (get-processes-status-changes))
277
278 (defun get-processes-status-changes ()
279   (loop
280       (multiple-value-bind (pid what code core)
281           (wait3 t t)
282         (unless pid
283           (return))
284         (let ((proc (find pid *active-processes* :key #'process-pid)))
285           (when proc
286             (setf (process-%status proc) what)
287             (setf (process-exit-code proc) code)
288             (setf (process-core-dumped proc) core)
289             (when (process-status-hook proc)
290               (funcall (process-status-hook proc) proc))
291             (when (position what #(:exited :signaled))
292               (sb-sys:without-interrupts
293                (setf *active-processes*
294                      (delete proc *active-processes*)))))))))
295 \f
296 ;;;; RUN-PROGRAM and close friends
297
298 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
299 (defvar *close-on-error* nil)
300
301 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
302 (defvar *close-in-parent* nil)
303
304 ;;; list of handlers installed by RUN-PROGRAM
305 (defvar *handlers-installed* nil)
306
307 #+FreeBSD
308 (define-alien-type nil
309   (struct sgttyb
310           (sg-ispeed sb-alien:char)     ; input speed
311           (sg-ospeed sb-alien:char)     ; output speed
312           (sg-erase sb-alien:char)      ; erase character
313           (sg-kill sb-alien:char)       ; kill character
314           (sg-flags sb-alien:short)))   ; mode flags
315 #+OpenBSD
316 (define-alien-type nil
317   (struct sgttyb
318           (sg-four sb-alien:int)
319           (sg-chars (array sb-alien:char 4))
320           (sg-flags sb-alien:int)))
321
322 ;;; Find an unused pty. Return three values: the file descriptor for
323 ;;; the master side of the pty, the file descriptor for the slave side
324 ;;; of the pty, and the name of the tty device for the slave side.
325 (defun find-a-pty ()
326   (dolist (char '(#\p #\q))
327     (dotimes (digit 16)
328       (let* ((master-name (format nil "/dev/pty~C~X" char digit))
329              (master-fd (sb-unix:unix-open master-name
330                                            sb-unix:o_rdwr
331                                            #o666)))
332         (when master-fd
333           (let* ((slave-name (format nil "/dev/tty~C~X" char digit))
334                  (slave-fd (sb-unix:unix-open slave-name
335                                               sb-unix:o_rdwr
336                                               #o666)))
337             (when slave-fd
338               ;; comment from classic CMU CL:
339               ;;   Maybe put a vhangup here?
340               ;;
341               ;; FIXME: It seems as though this logic should be in
342               ;; OPEN-PTY, not FIND-A-PTY (both from the comments
343               ;; documenting DEFUN FIND-A-PTY, and from the
344               ;; connotations of the function names).
345               ;;
346               ;; FIXME: It would be nice to have a note, and/or a pointer
347               ;; to some reference material somewhere, explaining
348               ;; why we need this on *BSD and not on Linux.
349               #+bsd
350               (sb-alien:with-alien ((stuff (sb-alien:struct sgttyb)))
351                 (let ((sap (sb-alien:alien-sap stuff)))
352                   (sb-unix:unix-ioctl slave-fd sb-unix:TIOCGETP sap)
353                   (setf (sb-alien:slot stuff 'sg-flags)
354                         ;; This is EVENP|ODDP, the same numeric code
355                         ;; both on FreeBSD and on OpenBSD. -- WHN 20000929
356                         #o300) ; EVENP|ODDP
357                   (sb-unix:unix-ioctl slave-fd sb-unix:TIOCSETP sap)
358                   (sb-unix:unix-ioctl master-fd sb-unix:TIOCGETP sap)
359                   (setf (sb-alien:slot stuff 'sg-flags)
360                         (logand (sb-alien:slot stuff 'sg-flags)
361                                 ;; This is ~ECHO, the same numeric
362                                 ;; code both on FreeBSD and on OpenBSD.
363                                 ;; -- WHN 20000929
364                                 (lognot 8))) ; ~ECHO
365                   (sb-unix:unix-ioctl master-fd sb-unix:TIOCSETP sap)))
366               (return-from find-a-pty
367                 (values master-fd
368                         slave-fd
369                         slave-name)))
370             (sb-unix:unix-close master-fd))))))
371   (error "could not find a pty"))
372
373 (defun open-pty (pty cookie)
374   (when pty
375     (multiple-value-bind
376           (master slave name)
377         (find-a-pty)
378       (push master *close-on-error*)
379       (push slave *close-in-parent*)
380       (when (streamp pty)
381         (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
382           (unless new-fd
383             (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
384           (push new-fd *close-on-error*)
385           (copy-descriptor-to-stream new-fd pty cookie)))
386       (values name
387               (sb-sys:make-fd-stream master :input t :output t)))))
388
389 (defmacro round-bytes-to-words (n)
390   `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
391
392 (defun string-list-to-c-strvec (string-list)
393   ;; Make a pass over STRING-LIST to calculate the amount of memory
394   ;; needed to hold the strvec.
395   (let ((string-bytes 0)
396         ;; We need an extra for the null, and an extra 'cause exect
397         ;; clobbers argv[-1].
398         (vec-bytes (* #-alpha 4 #+alpha 8 (+ (length string-list) 2))))
399     (declare (fixnum string-bytes vec-bytes))
400     (dolist (s string-list)
401       (enforce-type s simple-string)
402       (incf string-bytes (round-bytes-to-words (1+ (length s)))))
403     ;; Now allocate the memory and fill it in.
404     (let* ((total-bytes (+ string-bytes vec-bytes))
405            (vec-sap (sb-sys:allocate-system-memory total-bytes))
406            (string-sap (sap+ vec-sap vec-bytes))
407            (i #-alpha 4 #+alpha 8))
408       (declare (type (and unsigned-byte fixnum) total-bytes i)
409                (type sb-sys:system-area-pointer vec-sap string-sap))
410       (dolist (s string-list)
411         (declare (simple-string s))
412         (let ((n (length s)))
413           ;; Blast the string into place.
414           (sb-kernel:copy-to-system-area (the simple-string s)
415                                          (* sb-vm:vector-data-offset
416                                             sb-vm:n-word-bits)
417                                          string-sap 0
418                                          (* (1+ n) sb-vm:n-byte-bits))
419           ;; Blast the pointer to the string into place.
420           (setf (sap-ref-sap vec-sap i) string-sap)
421           (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
422           (incf i #-alpha 4 #+alpha 8)))
423       ;; Blast in the last null pointer.
424       (setf (sap-ref-sap vec-sap i) (int-sap 0))
425       (values vec-sap (sap+ vec-sap #-alpha 4 #+alpha 8) total-bytes))))
426
427 (defmacro with-c-strvec ((var str-list) &body body)
428   (let ((sap (gensym "SAP-"))
429         (size (gensym "SIZE-")))
430     `(multiple-value-bind
431       (,sap ,var ,size)
432       (string-list-to-c-strvec ,str-list)
433       (unwind-protect
434            (progn
435              ,@body)
436         (sb-sys:deallocate-system-memory ,sap ,size)))))
437
438 (sb-alien:define-alien-routine spawn sb-alien:int
439   (program sb-alien:c-string)
440   (argv (* sb-alien:c-string))
441   (envp (* sb-alien:c-string))
442   (pty-name sb-alien:c-string)
443   (stdin sb-alien:int)
444   (stdout sb-alien:int)
445   (stderr sb-alien:int))
446
447 ;;; Is UNIX-FILENAME the name of a file that we can execute?
448 (defun unix-filename-is-executable-p (unix-filename)
449   (declare (type simple-string unix-filename))
450   (values (and (eq (sb-unix:unix-file-kind unix-filename) :file)
451                (sb-unix:unix-access unix-filename sb-unix:x_ok))))
452
453 ;;; FIXME: There shouldn't be two semiredundant versions of the
454 ;;; documentation. Since this is a public extension function, the
455 ;;; documentation should be in the doc string. So all information from
456 ;;; this comment should be merged into the doc string, and then this
457 ;;; comment can go away.
458 ;;;
459 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
460 ;;; Strange stuff happens to keep the Unix state of the world
461 ;;; coherent.
462 ;;;
463 ;;; The child process needs to get its input from somewhere, and send
464 ;;; its output (both standard and error) to somewhere. We have to do
465 ;;; different things depending on where these somewheres really are.
466 ;;;
467 ;;; For input, there are five options:
468 ;;;  -- T: Just leave fd 0 alone. Pretty simple.
469 ;;;  -- "file": Read from the file. We need to open the file and
470 ;;;     pull the descriptor out of the stream. The parent should close
471 ;;;     this stream after the child is up and running to free any 
472 ;;;     storage used in the parent.
473 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.
474 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use
475 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the
476 ;;;     writeable descriptor, and pass the readable descriptor to
477 ;;;     the child. The parent must close the readable descriptor for
478 ;;;     EOF to be passed up correctly.
479 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out
480 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy 
481 ;;;     everything across.
482 ;;;
483 ;;; For output, there are five options:
484 ;;;  -- T: Leave descriptor 1 alone.
485 ;;;  -- "file": dump output to the file.
486 ;;;  -- NIL: dump output to /dev/null.
487 ;;;  -- :STREAM: return a stream that can be read from.
488 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.
489 ;;;     Otherwise, copy stuff from output to stream.
490 ;;;
491 ;;; For error, there are all the same options as output plus:
492 ;;;  -- :OUTPUT: redirect to the same place as output.
493 ;;;
494 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
495 ;;; the fork worked, and NIL if it did not.
496 (defun run-program (program args
497                     &key
498                     (env nil env-p)
499                     (environment (if env-p
500                                      (unix-environment-sbcl-from-cmucl env)
501                                      (posix-environ))
502                                  environment-p)
503                     (wait t)
504                     pty
505                     input
506                     if-input-does-not-exist
507                     output
508                     (if-output-exists :error)
509                     (error :output)
510                     (if-error-exists :error)
511                     status-hook)
512   "RUN-PROGRAM creates a new Unix process running the Unix program found in
513    the file specified by the PROGRAM argument.  ARGS are the standard
514    arguments that can be passed to a Unix program. For no arguments, use NIL
515    (which means that just the name of the program is passed as arg 0).
516
517    RUN-PROGRAM will either return NIL or a PROCESS structure.  See the CMU
518    Common Lisp Users Manual for details about the PROCESS structure.
519
520    notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
521      1. The SBCL implementation of RUN-PROGRAM, like Perl and many other
522         programs, but unlike the original CMU CL implementation, copies
523         the Unix environment by default.
524      2. Running Unix programs from a setuid process, or in any other
525         situation where the Unix environment is under the control of someone
526         else, is a mother lode of security problems. If you are contemplating
527         doing this, read about it first. (The Perl community has a lot of good
528         documentation about this and other security issues in script-like
529         programs.)
530
531    The &KEY arguments have the following meanings:
532      :ENVIRONMENT
533         a list of SIMPLE-STRINGs describing the new Unix environment (as
534         in \"man environ\"). The default is to copy the environment of
535         the current process.
536      :ENV
537         an alternative lossy representation of the new Unix environment,
538         for compatibility with CMU CL
539      :WAIT
540         If non-NIL (default), wait until the created process finishes.  If
541         NIL, continue running Lisp until the program finishes.
542      :PTY
543         Either T, NIL, or a stream.  Unless NIL, the subprocess is established
544         under a PTY.  If :pty is a stream, all output to this pty is sent to
545         this stream, otherwise the PROCESS-PTY slot is filled in with a stream
546         connected to pty that can read output and write input.
547      :INPUT
548         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
549         input for the current process is inherited.  If NIL, /dev/null
550         is used.  If a pathname, the file so specified is used.  If a stream,
551         all the input is read from that stream and send to the subprocess.  If
552         :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends 
553         its output to the process. Defaults to NIL.
554      :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
555         can be one of:
556            :ERROR to generate an error
557            :CREATE to create an empty file
558            NIL (the default) to return NIL from RUN-PROGRAM
559      :OUTPUT 
560         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
561         output for the current process is inherited.  If NIL, /dev/null
562         is used.  If a pathname, the file so specified is used.  If a stream,
563         all the output from the process is written to this stream. If
564         :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
565         be read to get the output. Defaults to NIL.
566      :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
567         can be one of:
568            :ERROR (the default) to generate an error
569            :SUPERSEDE to supersede the file with output from the program
570            :APPEND to append output from the program to the file 
571            NIL to return NIL from RUN-PROGRAM, without doing anything
572      :ERROR and :IF-ERROR-EXISTS
573         Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
574         specified as :OUTPUT in which case all error output is routed to the
575         same place as normal output.
576      :STATUS-HOOK
577         This is a function the system calls whenever the status of the
578         process changes.  The function takes the process as an argument."
579
580   (when (and env-p environment-p)
581     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
582   ;; Make sure that the interrupt handler is installed.
583   (sb-sys:enable-interrupt :sigchld #'sigchld-handler)
584   ;; Prepend the program to the argument list.
585   (push (namestring program) args)
586   (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
587         ;; communicate cleanup info.
588         *close-on-error*
589         *close-in-parent*
590         *handlers-installed*
591         ;; Establish PROC at this level so that we can return it.
592         proc
593         ;; It's friendly to allow the caller to pass any string
594         ;; designator, but internally we'd like SIMPLE-STRINGs.
595         (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
596     (unwind-protect
597          (let (;; FIXME: The old code here used to do
598                ;;   (MERGE-PATHNAMES PROGRAM "path:"),
599                ;; which is the right idea (searching through the Unix
600                ;; PATH). Unfortunately, there is no logical pathname
601                ;; "path:" defined in sbcl-0.6.10. It would probably be 
602                ;; reasonable to restore Unix PATH searching in SBCL, e.g.
603                ;; with a function FIND-EXECUTABLE-FILE-IN-POSIX-PATH.
604                ;; CMU CL did it with a "PATH:" search list, but CMU CL
605                ;; search lists are a non-ANSI extension that SBCL
606                ;; doesn't support. -- WHN)
607                (pfile (unix-namestring program t))
608                (cookie (list 0)))
609            (unless pfile
610              (error "no such program: ~S" program))
611            (unless (unix-filename-is-executable-p pfile)
612              (error "not executable: ~S" program))
613            (multiple-value-bind (stdin input-stream)
614                (get-descriptor-for input cookie
615                                    :direction :input
616                                    :if-does-not-exist if-input-does-not-exist)
617              (multiple-value-bind (stdout output-stream)
618                  (get-descriptor-for output cookie
619                                      :direction :output
620                                      :if-exists if-output-exists)
621                (multiple-value-bind (stderr error-stream)
622                    (if (eq error :output)
623                        (values stdout output-stream)
624                        (get-descriptor-for error cookie
625                                            :direction :output
626                                            :if-exists if-error-exists))
627                  (multiple-value-bind (pty-name pty-stream)
628                      (open-pty pty cookie)
629                    ;; Make sure we are not notified about the child
630                    ;; death before we have installed the PROCESS
631                    ;; structure in *ACTIVE-PROCESSES*.
632                    (sb-sys:without-interrupts
633                     (with-c-strvec (args-vec simple-args)
634                       (with-c-strvec (environment-vec environment)
635                         (let ((child-pid
636                                (without-gcing
637                                 (spawn pfile args-vec environment-vec pty-name
638                                        stdin stdout stderr))))
639                           (when (< child-pid 0)
640                             (error "couldn't fork child process: ~A"
641                                    (strerror)))
642                           (setf proc (make-process :pid child-pid
643                                                    :%status :running
644                                                    :pty pty-stream
645                                                    :input input-stream
646                                                    :output output-stream
647                                                    :error error-stream
648                                                    :status-hook status-hook
649                                                    :cookie cookie))
650                           (push proc *active-processes*))))))))))
651       (dolist (fd *close-in-parent*)
652         (sb-unix:unix-close fd))
653       (unless proc
654         (dolist (fd *close-on-error*)
655           (sb-unix:unix-close fd))
656         (dolist (handler *handlers-installed*)
657           (sb-sys:remove-fd-handler handler))))
658     (when (and wait proc)
659       (process-wait proc))
660     proc))
661
662 ;;; Install a handler for any input that shows up on the file
663 ;;; descriptor. The handler reads the data and writes it to the
664 ;;; stream.
665 (defun copy-descriptor-to-stream (descriptor stream cookie)
666   (incf (car cookie))
667   (let ((string (make-string 256))
668         handler)
669     (setf handler
670           (sb-sys:add-fd-handler
671            descriptor
672            :input (lambda (fd)
673                     (declare (ignore fd))
674                     (loop
675                      (unless handler
676                        (return))
677                      (multiple-value-bind
678                          (result readable/errno)
679                          (sb-unix:unix-select (1+ descriptor)
680                                               (ash 1 descriptor)
681                                               0 0 0)
682                        (cond ((null result)
683                               (error "~@<couldn't select on sub-process: ~
684                                            ~2I~_~A~:>"
685                                      (strerror readable/errno)))
686                              ((zerop result)
687                               (return))))
688                      (sb-alien:with-alien ((buf (sb-alien:array
689                                                  sb-alien:char
690                                                  256)))
691                        (multiple-value-bind
692                            (count errno)
693                            (sb-unix:unix-read descriptor
694                                               (alien-sap buf)
695                                               256)
696                          (cond ((or (and (null count)
697                                          (eql errno sb-unix:eio))
698                                     (eql count 0))
699                                 (sb-sys:remove-fd-handler handler)
700                                 (setf handler nil)
701                                 (decf (car cookie))
702                                 (sb-unix:unix-close descriptor)
703                                 (return))
704                                ((null count)
705                                 (sb-sys:remove-fd-handler handler)
706                                 (setf handler nil)
707                                 (decf (car cookie))
708                                 (error
709                                  "~@<couldn't read input from sub-process: ~
710                                      ~2I~_~A~:>"
711                                  (strerror errno)))
712                                (t
713                                 (sb-kernel:copy-from-system-area
714                                  (alien-sap buf) 0
715                                  string (* sb-vm:vector-data-offset
716                                            sb-vm:n-word-bits)
717                                  (* count sb-vm:n-byte-bits))
718                                 (write-string string stream
719                                               :end count)))))))))))
720
721 ;;; Find a file descriptor to use for object given the direction.
722 ;;; Returns the descriptor. If object is :STREAM, returns the created
723 ;;; stream as the second value.
724 (defun get-descriptor-for (object
725                            cookie
726                            &rest keys
727                            &key direction
728                            &allow-other-keys)
729   (cond ((eq object t)
730          ;; No new descriptor is needed.
731          (values -1 nil))
732         ((eq object nil)
733          ;; Use /dev/null.
734          (multiple-value-bind
735                (fd errno)
736              (sb-unix:unix-open "/dev/null"
737                                 (case direction
738                                   (:input sb-unix:o_rdonly)
739                                   (:output sb-unix:o_wronly)
740                                   (t sb-unix:o_rdwr))
741                                 #o666)
742            (unless fd
743              (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
744                     (strerror errno)))
745            (push fd *close-in-parent*)
746            (values fd nil)))
747         ((eq object :stream)
748          (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
749            (unless read-fd
750              (error "couldn't create pipe: ~A" (strerror write-fd)))
751            (case direction
752              (:input
753               (push read-fd *close-in-parent*)
754               (push write-fd *close-on-error*)
755               (let ((stream (sb-sys:make-fd-stream write-fd :output t)))
756                 (values read-fd stream)))
757              (:output
758               (push read-fd *close-on-error*)
759               (push write-fd *close-in-parent*)
760               (let ((stream (sb-sys:make-fd-stream read-fd :input t)))
761                 (values write-fd stream)))
762              (t
763               (sb-unix:unix-close read-fd)
764               (sb-unix:unix-close write-fd)
765               (error "Direction must be either :INPUT or :OUTPUT, not ~S."
766                      direction)))))
767         ((or (pathnamep object) (stringp object))
768          (with-open-stream (file (apply #'open object keys))
769            (multiple-value-bind
770                  (fd errno)
771                (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
772              (cond (fd
773                     (push fd *close-in-parent*)
774                     (values fd nil))
775                    (t
776                     (error "couldn't duplicate file descriptor: ~A"
777                            (strerror errno)))))))
778         ((sb-sys:fd-stream-p object)
779          (values (sb-sys:fd-stream-fd object) nil))
780         ((streamp object)
781          (ecase direction
782            (:input
783             ;; FIXME: We could use a better way of setting up
784             ;; temporary files, both here and in LOAD-FOREIGN.
785             (dotimes (count
786                        256
787                       (error "could not open a temporary file in /tmp"))
788               (let* ((name (format nil "/tmp/.run-program-~D" count))
789                      (fd (sb-unix:unix-open name
790                                             (logior sb-unix:o_rdwr
791                                                     sb-unix:o_creat
792                                                     sb-unix:o_excl)
793                                             #o666)))
794                 (sb-unix:unix-unlink name)
795                 (when fd
796                   (let ((newline (string #\Newline)))
797                     (loop
798                         (multiple-value-bind
799                               (line no-cr)
800                             (read-line object nil nil)
801                           (unless line
802                             (return))
803                           (sb-unix:unix-write fd line 0 (length line))
804                           (if no-cr
805                               (return)
806                               (sb-unix:unix-write fd newline 0 1)))))
807                   (sb-unix:unix-lseek fd 0 sb-unix:l_set)
808                   (push fd *close-in-parent*)
809                   (return (values fd nil))))))
810            (:output
811             (multiple-value-bind (read-fd write-fd)
812                 (sb-unix:unix-pipe)
813               (unless read-fd
814                 (error "couldn't create pipe: ~S" (strerror write-fd)))
815               (copy-descriptor-to-stream read-fd object cookie)
816               (push read-fd *close-on-error*)
817               (push write-fd *close-in-parent*)
818               (values write-fd nil)))))
819         (t
820          (error "invalid option to RUN-PROGRAM: ~S" object))))