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