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