0.9.10.29
[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                                      :dual-channel-p t)))))
388
389 (defmacro round-bytes-to-words (n)
390   `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
391
392 (defun string-list-to-c-strvec (string-list)
393   ;; Make a pass over STRING-LIST to calculate the amount of memory
394   ;; needed to hold the strvec.
395   (let ((string-bytes 0)
396         ;; We need an extra for the null, and an extra 'cause exect
397         ;; clobbers argv[-1].
398         (vec-bytes (* #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)
399                       (+ (length string-list) 2))))
400     (declare (fixnum string-bytes vec-bytes))
401     (dolist (s string-list)
402       (enforce-type s simple-string)
403       (incf string-bytes (round-bytes-to-words (1+ (length s)))))
404     ;; Now allocate the memory and fill it in.
405     (let* ((total-bytes (+ string-bytes vec-bytes))
406            (vec-sap (sb-sys:allocate-system-memory total-bytes))
407            (string-sap (sap+ vec-sap vec-bytes))
408            (i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)))
409       (declare (type (and unsigned-byte fixnum) total-bytes i)
410                (type sb-sys:system-area-pointer vec-sap string-sap))
411       (dolist (s string-list)
412         (declare (simple-string s))
413         (let ((n (length s)))
414           ;; Blast the string into place.
415           (sb-kernel:copy-ub8-to-system-area (the simple-base-string
416                                                ;; FIXME
417                                                (coerce s 'simple-base-string))
418                                              0
419                                              string-sap 0
420                                              (1+ n))
421           ;; Blast the pointer to the string into place.
422           (setf (sap-ref-sap vec-sap i) string-sap)
423           (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
424           (incf i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits))))
425       ;; Blast in the last null pointer.
426       (setf (sap-ref-sap vec-sap i) (int-sap 0))
427       (values vec-sap (sap+ vec-sap #.(/ sb-vm::n-machine-word-bits
428                                          sb-vm::n-byte-bits))
429               total-bytes))))
430
431 (defmacro with-c-strvec ((var str-list) &body body)
432   (with-unique-names (sap size)
433     `(multiple-value-bind
434       (,sap ,var ,size)
435       (string-list-to-c-strvec ,str-list)
436       (unwind-protect
437            (progn
438              ,@body)
439         (sb-sys:deallocate-system-memory ,sap ,size)))))
440
441 (sb-alien:define-alien-routine spawn sb-alien:int
442   (program sb-alien:c-string)
443   (argv (* sb-alien:c-string))
444   (envp (* sb-alien:c-string))
445   (pty-name sb-alien:c-string)
446   (stdin sb-alien:int)
447   (stdout sb-alien:int)
448   (stderr sb-alien:int))
449
450 ;;; Is UNIX-FILENAME the name of a file that we can execute?
451 (defun unix-filename-is-executable-p (unix-filename)
452   (declare (type simple-string unix-filename))
453   (setf unix-filename (coerce unix-filename 'base-string))
454   (values (and (eq (sb-unix:unix-file-kind unix-filename) :file)
455                (sb-unix:unix-access unix-filename sb-unix:x_ok))))
456
457 (defun find-executable-in-search-path (pathname
458                                        &optional
459                                        (search-path (posix-getenv "PATH")))
460   #!+sb-doc
461   "Find the first executable file matching PATHNAME in any of the
462 colon-separated list of pathnames SEARCH-PATH"
463   (loop for end =  (position #\: search-path :start (if end (1+ end) 0))
464         and start = 0 then (and end (1+ end))
465         while start
466         ;; <Krystof> the truename of a file naming a directory is the
467         ;; directory, at least until pfdietz comes along and says why
468         ;; that's noncompliant  -- CSR, c. 2003-08-10
469         for truename = (probe-file (subseq search-path start end))
470         for fullpath = (when truename (merge-pathnames pathname truename))
471         when (and fullpath
472                   (unix-filename-is-executable-p (namestring fullpath)))
473         return fullpath))
474
475 ;;; FIXME: There shouldn't be two semiredundant versions of the
476 ;;; documentation. Since this is a public extension function, the
477 ;;; documentation should be in the doc string. So all information from
478 ;;; this comment should be merged into the doc string, and then this
479 ;;; comment can go away.
480 ;;;
481 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
482 ;;; Strange stuff happens to keep the Unix state of the world
483 ;;; coherent.
484 ;;;
485 ;;; The child process needs to get its input from somewhere, and send
486 ;;; its output (both standard and error) to somewhere. We have to do
487 ;;; different things depending on where these somewheres really are.
488 ;;;
489 ;;; For input, there are five options:
490 ;;;  -- T: Just leave fd 0 alone. Pretty simple.
491 ;;;  -- "file": Read from the file. We need to open the file and
492 ;;;     pull the descriptor out of the stream. The parent should close
493 ;;;     this stream after the child is up and running to free any
494 ;;;     storage used in the parent.
495 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.
496 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use
497 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the
498 ;;;     writeable descriptor, and pass the readable descriptor to
499 ;;;     the child. The parent must close the readable descriptor for
500 ;;;     EOF to be passed up correctly.
501 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out
502 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy
503 ;;;     everything across.
504 ;;;
505 ;;; For output, there are five options:
506 ;;;  -- T: Leave descriptor 1 alone.
507 ;;;  -- "file": dump output to the file.
508 ;;;  -- NIL: dump output to /dev/null.
509 ;;;  -- :STREAM: return a stream that can be read from.
510 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.
511 ;;;     Otherwise, copy stuff from output to stream.
512 ;;;
513 ;;; For error, there are all the same options as output plus:
514 ;;;  -- :OUTPUT: redirect to the same place as output.
515 ;;;
516 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
517 ;;; the fork worked, and NIL if it did not.
518 (defun run-program (program args
519                     &key
520                     (env nil env-p)
521                     (environment (if env-p
522                                      (unix-environment-sbcl-from-cmucl env)
523                                      (posix-environ))
524                                  environment-p)
525                     (wait t)
526                     search
527                     pty
528                     input
529                     if-input-does-not-exist
530                     output
531                     (if-output-exists :error)
532                     (error :output)
533                     (if-error-exists :error)
534                     status-hook)
535   #!+sb-doc
536   "RUN-PROGRAM creates a new Unix process running the Unix program found in
537    the file specified by the PROGRAM argument.  ARGS are the standard
538    arguments that can be passed to a Unix program. For no arguments, use NIL
539    (which means that just the name of the program is passed as arg 0).
540
541    RUN-PROGRAM will return a PROCESS structure or NIL on failure.
542    See the CMU Common Lisp Users Manual for details about the
543    PROCESS structure.
544
545    Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
546
547    - The SBCL implementation of RUN-PROGRAM, like Perl and many other
548      programs, but unlike the original CMU CL implementation, copies
549      the Unix environment by default.
550
551    - Running Unix programs from a setuid process, or in any other
552      situation where the Unix environment is under the control of someone
553      else, is a mother lode of security problems. If you are contemplating
554      doing this, read about it first. (The Perl community has a lot of good
555      documentation about this and other security issues in script-like
556      programs.)
557
558    The &KEY arguments have the following meanings:
559
560    :ENVIRONMENT
561       a list of SIMPLE-BASE-STRINGs describing the new Unix environment
562       (as in \"man environ\"). The default is to copy the environment of
563       the current process.
564    :ENV
565       an alternative lossy representation of the new Unix environment,
566       for compatibility with CMU CL
567    :SEARCH
568       Look for PROGRAM in each of the directories along the $PATH
569       environment variable.  Otherwise an absolute pathname is required.
570       (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
571    :WAIT
572       If non-NIL (default), wait until the created process finishes.  If
573       NIL, continue running Lisp until the program finishes.
574    :PTY
575       Either T, NIL, or a stream.  Unless NIL, the subprocess is established
576       under a PTY.  If :pty is a stream, all output to this pty is sent to
577       this stream, otherwise the PROCESS-PTY slot is filled in with a stream
578       connected to pty that can read output and write input.
579    :INPUT
580       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
581       input for the current process is inherited.  If NIL, /dev/null
582       is used.  If a pathname, the file so specified is used.  If a stream,
583       all the input is read from that stream and send to the subprocess.  If
584       :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
585       its output to the process. Defaults to NIL.
586    :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
587       can be one of:
588          :ERROR to generate an error
589          :CREATE to create an empty file
590          NIL (the default) to return NIL from RUN-PROGRAM
591    :OUTPUT
592       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
593       output for the current process is inherited.  If NIL, /dev/null
594       is used.  If a pathname, the file so specified is used.  If a stream,
595       all the output from the process is written to this stream. If
596       :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
597       be read to get the output. Defaults to NIL.
598    :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
599       can be one of:
600          :ERROR (the default) to generate an error
601          :SUPERSEDE to supersede the file with output from the program
602          :APPEND to append output from the program to the file
603          NIL to return NIL from RUN-PROGRAM, without doing anything
604    :ERROR and :IF-ERROR-EXISTS
605       Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
606       specified as :OUTPUT in which case all error output is routed to the
607       same place as normal output.
608    :STATUS-HOOK
609       This is a function the system calls whenever the status of the
610       process changes.  The function takes the process as an argument."
611
612   (when (and env-p environment-p)
613     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
614   ;; Make sure that the interrupt handler is installed.
615   (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
616   ;; Prepend the program to the argument list.
617   (push (namestring program) args)
618   (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
619         ;; communicate cleanup info.
620         *close-on-error*
621         *close-in-parent*
622         *handlers-installed*
623         ;; Establish PROC at this level so that we can return it.
624         proc
625         ;; It's friendly to allow the caller to pass any string
626         ;; designator, but internally we'd like SIMPLE-STRINGs.
627         (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
628     (unwind-protect
629          (let ((pfile
630                 (if search
631                     (let ((p (find-executable-in-search-path program)))
632                       (and p (unix-namestring p t)))
633                     (unix-namestring program t)))
634                (cookie (list 0)))
635            (unless pfile
636              (error "no such program: ~S" program))
637            (unless (unix-filename-is-executable-p pfile)
638              (error "not executable: ~S" program))
639            (multiple-value-bind (stdin input-stream)
640                (get-descriptor-for input cookie
641                                    :direction :input
642                                    :if-does-not-exist if-input-does-not-exist)
643              (multiple-value-bind (stdout output-stream)
644                  (get-descriptor-for output cookie
645                                      :direction :output
646                                      :if-exists if-output-exists)
647                (multiple-value-bind (stderr error-stream)
648                    (if (eq error :output)
649                        (values stdout output-stream)
650                        (get-descriptor-for error cookie
651                                            :direction :output
652                                            :if-exists if-error-exists))
653                  (multiple-value-bind (pty-name pty-stream)
654                      (open-pty pty cookie)
655                    ;; Make sure we are not notified about the child
656                    ;; death before we have installed the PROCESS
657                    ;; structure in *ACTIVE-PROCESSES*.
658                    (with-active-processes-lock ()
659                     (with-c-strvec (args-vec simple-args)
660                       (with-c-strvec (environment-vec environment)
661                         (let ((child-pid
662                                (without-gcing
663                                 (spawn pfile args-vec environment-vec pty-name
664                                        stdin stdout stderr))))
665                           (when (< child-pid 0)
666                             (error "couldn't fork child process: ~A"
667                                    (strerror)))
668                           (setf proc (make-process :pid child-pid
669                                                    :%status :running
670                                                    :pty pty-stream
671                                                    :input input-stream
672                                                    :output output-stream
673                                                    :error error-stream
674                                                    :status-hook status-hook
675                                                    :cookie cookie))
676                           (push proc *active-processes*))))))))))
677       (dolist (fd *close-in-parent*)
678         (sb-unix:unix-close fd))
679       (unless proc
680         (dolist (fd *close-on-error*)
681           (sb-unix:unix-close fd))
682         (dolist (handler *handlers-installed*)
683           (sb-sys:remove-fd-handler handler))))
684     (when (and wait proc)
685       (process-wait proc))
686     proc))
687
688 ;;; Install a handler for any input that shows up on the file
689 ;;; descriptor. The handler reads the data and writes it to the
690 ;;; stream.
691 (defun copy-descriptor-to-stream (descriptor stream cookie)
692   (incf (car cookie))
693   (let ((string (make-string 256 :element-type 'base-char))
694         handler)
695     (setf handler
696           (sb-sys:add-fd-handler
697            descriptor
698            :input (lambda (fd)
699                     (declare (ignore fd))
700                     (loop
701                      (unless handler
702                        (return))
703                      (multiple-value-bind
704                          (result readable/errno)
705                          (sb-unix:unix-select (1+ descriptor)
706                                               (ash 1 descriptor)
707                                               0 0 0)
708                        (cond ((null result)
709                               (error "~@<couldn't select on sub-process: ~
710                                            ~2I~_~A~:>"
711                                      (strerror readable/errno)))
712                              ((zerop result)
713                               (return))))
714                      (sb-alien:with-alien ((buf (sb-alien:array
715                                                  sb-alien:char
716                                                  256)))
717                        (multiple-value-bind
718                            (count errno)
719                            (sb-unix:unix-read descriptor
720                                               (alien-sap buf)
721                                               256)
722                          (cond ((or (and (null count)
723                                          (eql errno sb-unix:eio))
724                                     (eql count 0))
725                                 (sb-sys:remove-fd-handler handler)
726                                 (setf handler nil)
727                                 (decf (car cookie))
728                                 (sb-unix:unix-close descriptor)
729                                 (return))
730                                ((null count)
731                                 (sb-sys:remove-fd-handler handler)
732                                 (setf handler nil)
733                                 (decf (car cookie))
734                                 (error
735                                  "~@<couldn't read input from sub-process: ~
736                                      ~2I~_~A~:>"
737                                  (strerror errno)))
738                                (t
739                                 (sb-kernel:copy-ub8-from-system-area
740                                  (alien-sap buf) 0
741                                  string 0
742                                  count)
743                                 (write-string string stream
744                                               :end count)))))))))))
745
746 ;;; Find a file descriptor to use for object given the direction.
747 ;;; Returns the descriptor. If object is :STREAM, returns the created
748 ;;; stream as the second value.
749 (defun get-descriptor-for (object
750                            cookie
751                            &rest keys
752                            &key direction
753                            &allow-other-keys)
754   (cond ((eq object t)
755          ;; No new descriptor is needed.
756          (values -1 nil))
757         ((eq object nil)
758          ;; Use /dev/null.
759          (multiple-value-bind
760                (fd errno)
761              (sb-unix:unix-open #.(coerce "/dev/null" 'base-string)
762                                 (case direction
763                                   (:input sb-unix:o_rdonly)
764                                   (:output sb-unix:o_wronly)
765                                   (t sb-unix:o_rdwr))
766                                 #o666)
767            (unless fd
768              (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
769                     (strerror errno)))
770            (push fd *close-in-parent*)
771            (values fd nil)))
772         ((eq object :stream)
773          (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
774            (unless read-fd
775              (error "couldn't create pipe: ~A" (strerror write-fd)))
776            (case direction
777              (:input
778               (push read-fd *close-in-parent*)
779               (push write-fd *close-on-error*)
780               (let ((stream (sb-sys:make-fd-stream write-fd :output t)))
781                 (values read-fd stream)))
782              (:output
783               (push read-fd *close-on-error*)
784               (push write-fd *close-in-parent*)
785               (let ((stream (sb-sys:make-fd-stream read-fd :input t)))
786                 (values write-fd stream)))
787              (t
788               (sb-unix:unix-close read-fd)
789               (sb-unix:unix-close write-fd)
790               (error "Direction must be either :INPUT or :OUTPUT, not ~S."
791                      direction)))))
792         ((or (pathnamep object) (stringp object))
793          (with-open-stream (file (apply #'open object keys))
794            (multiple-value-bind
795                  (fd errno)
796                (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
797              (cond (fd
798                     (push fd *close-in-parent*)
799                     (values fd nil))
800                    (t
801                     (error "couldn't duplicate file descriptor: ~A"
802                            (strerror errno)))))))
803         ((sb-sys:fd-stream-p object)
804          (values (sb-sys:fd-stream-fd object) nil))
805         ((streamp object)
806          (ecase direction
807            (:input
808             ;; FIXME: We could use a better way of setting up
809             ;; temporary files, both here and in LOAD-FOREIGN.
810             (dotimes (count
811                        256
812                       (error "could not open a temporary file in /tmp"))
813               (let* ((name (coerce (format nil "/tmp/.run-program-~D" count) 'base-string))
814                      (fd (sb-unix:unix-open name
815                                             (logior sb-unix:o_rdwr
816                                                     sb-unix:o_creat
817                                                     sb-unix:o_excl)
818                                             #o666)))
819                 (sb-unix:unix-unlink name)
820                 (when fd
821                   (let ((newline (string #\Newline)))
822                     (loop
823                         (multiple-value-bind
824                               (line no-cr)
825                             (read-line object nil nil)
826                           (unless line
827                             (return))
828                           (sb-unix:unix-write
829                            fd
830                            ;; FIXME: this really should be
831                            ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).
832                            ;; RUN-PROGRAM should take an
833                            ;; external-format argument, which should
834                            ;; be passed down to here.  Something
835                            ;; similar should happen on :OUTPUT, too.
836                            (map '(vector (unsigned-byte 8)) #'char-code line)
837                            0 (length line))
838                           (if no-cr
839                               (return)
840                               (sb-unix:unix-write fd newline 0 1)))))
841                   (sb-unix:unix-lseek fd 0 sb-unix:l_set)
842                   (push fd *close-in-parent*)
843                   (return (values fd nil))))))
844            (:output
845             (multiple-value-bind (read-fd write-fd)
846                 (sb-unix:unix-pipe)
847               (unless read-fd
848                 (error "couldn't create pipe: ~S" (strerror write-fd)))
849               (copy-descriptor-to-stream read-fd object cookie)
850               (push read-fd *close-on-error*)
851               (push write-fd *close-in-parent*)
852               (values write-fd nil)))))
853         (t
854          (error "invalid option to RUN-PROGRAM: ~S" object))))