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