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