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