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