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