1.0.15.5: handler from COPY-DESCRIPTOR-TO-STREAM to check EINTR from select()
[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 (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) (string val))
94        (concatenate 'simple-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   `(sb-thread::call-with-system-mutex (lambda () ,@body) *active-processes-lock*)
158   #+win32
159   `(progn ,@body))
160
161 (defstruct (process (:copier nil))
162   pid                 ; PID of child process
163   %status             ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
164   exit-code           ; either exit code or signal
165   core-dumped         ; T if a core image was dumped
166   #-win32 pty                 ; stream to child's pty, or NIL
167   input               ; stream to child's input, or NIL
168   output              ; stream from child's output, or NIL
169   error               ; stream from child's error output, or NIL
170   status-hook         ; closure to call when PROC changes status
171   plist               ; a place for clients to stash things
172   cookie)             ; list of the number of pipes from the subproc
173
174 (defmethod print-object ((process process) stream)
175   (print-unreadable-object (process stream :type t)
176     (let ((status (process-status process)))
177      (if (eq :exited status)
178          (format stream "~S ~S" status (process-exit-code process))
179          (format stream "~S ~S" (process-pid process) status)))
180     process))
181
182 #+sb-doc
183 (setf (documentation 'process-p 'function)
184       "T if OBJECT is a PROCESS, NIL otherwise.")
185
186 #+sb-doc
187 (setf (documentation 'process-pid 'function) "The pid of the child process.")
188
189 #+win32
190 (define-alien-routine ("GetExitCodeProcess@8" get-exit-code-process)
191     int
192   (handle unsigned) (exit-code unsigned :out))
193
194 (defun process-status (process)
195   #+sb-doc
196   "Return the current status of PROCESS.  The result is one of :RUNNING,
197    :STOPPED, :EXITED, or :SIGNALED."
198   (get-processes-status-changes)
199   (process-%status process))
200
201 #+sb-doc
202 (setf (documentation 'process-exit-code 'function)
203       "The exit code or the signal of a stopped process.")
204
205 #+sb-doc
206 (setf (documentation 'process-core-dumped 'function)
207       "T if a core image was dumped by the process.")
208
209 #+sb-doc
210 (setf (documentation 'process-pty 'function)
211       "The pty stream of the process or NIL.")
212
213 #+sb-doc
214 (setf (documentation 'process-input 'function)
215       "The input stream of the process or NIL.")
216
217 #+sb-doc
218 (setf (documentation 'process-output 'function)
219       "The output stream of the process or NIL.")
220
221 #+sb-doc
222 (setf (documentation 'process-error 'function)
223       "The error stream of the process or NIL.")
224
225 #+sb-doc
226 (setf (documentation 'process-status-hook  'function)
227       "A function that is called when PROCESS changes its status.
228 The function is called with PROCESS as its only argument.")
229
230 #+sb-doc
231 (setf (documentation 'process-plist  'function)
232       "A place for clients to stash things.")
233
234 (defun process-wait (process &optional check-for-stopped)
235   #+sb-doc
236   "Wait for PROCESS to quit running for some reason. When
237 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
238 PROCESS."
239   (loop
240       (case (process-status process)
241         (:running)
242         (:stopped
243          (when check-for-stopped
244            (return)))
245         (t
246          (when (zerop (car (process-cookie process)))
247            (return))))
248       (sb-sys:serve-all-events 1))
249   process)
250
251 #-(or hpux win32)
252 ;;; Find the current foreground process group id.
253 (defun find-current-foreground-process (proc)
254   (with-alien ((result sb-alien:int))
255     (multiple-value-bind
256           (wonp error)
257         (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
258                             sb-unix:TIOCGPGRP
259                             (alien-sap (sb-alien:addr result)))
260       (unless wonp
261         (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
262       result))
263   (process-pid proc))
264
265 #-win32
266 (defun process-kill (process signal &optional (whom :pid))
267   #+sb-doc
268   "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
269    WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
270    :PTY-PROCESS-GROUP deliver the signal to whichever process group is
271    currently in the foreground."
272   (let ((pid (ecase whom
273                ((:pid :process-group)
274                 (process-pid process))
275                (:pty-process-group
276                 #-hpux
277                 (find-current-foreground-process process)))))
278     (multiple-value-bind
279           (okay errno)
280         (case whom
281           #+hpux
282           (:pty-process-group
283            (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))
284                                sb-unix:TIOCSIGSEND
285                                (sb-sys:int-sap
286                                 signal)))
287           ((:process-group #-hpux :pty-process-group)
288            (sb-unix:unix-killpg pid signal))
289           (t
290            (sb-unix:unix-kill pid signal)))
291       (cond ((not okay)
292              (values nil errno))
293             ((and (eql pid (process-pid process))
294                   (= signal sb-unix:sigcont))
295              (setf (process-%status process) :running)
296              (setf (process-exit-code process) nil)
297              (when (process-status-hook process)
298                (funcall (process-status-hook process) process))
299              t)
300             (t
301              t)))))
302
303 (defun process-alive-p (process)
304   #+sb-doc
305   "Return T if PROCESS is still alive, NIL otherwise."
306   (let ((status (process-status process)))
307     (if (or (eq status :running)
308             (eq status :stopped))
309         t
310         nil)))
311
312 (defun process-close (process)
313   #+sb-doc
314   "Close all streams connected to PROCESS and stop maintaining the
315 status slot."
316   (macrolet ((frob (stream abort)
317                `(when ,stream (close ,stream :abort ,abort))))
318     #-win32
319     (frob (process-pty process) t)   ; Don't FLUSH-OUTPUT to dead process,
320     (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
321     (frob (process-output process) nil)
322     (frob (process-error process) nil))
323   ;; FIXME: Given that the status-slot is no longer updated,
324   ;; maybe it should be set to :CLOSED, or similar?
325   (with-active-processes-lock ()
326    (setf *active-processes* (delete process *active-processes*)))
327   process)
328
329 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
330 #-win32
331 (defun sigchld-handler (ignore1 ignore2 ignore3)
332   (declare (ignore ignore1 ignore2 ignore3))
333   (get-processes-status-changes))
334
335 (defun get-processes-status-changes ()
336   #-win32
337   (loop
338    (multiple-value-bind (pid what code core)
339        (wait3 t t)
340      (unless pid
341        (return))
342      (let ((proc (with-active-processes-lock ()
343                    (find pid *active-processes* :key #'process-pid))))
344        (when proc
345          (setf (process-%status proc) what)
346          (setf (process-exit-code proc) code)
347          (setf (process-core-dumped proc) core)
348          (when (process-status-hook proc)
349            (funcall (process-status-hook proc) proc))
350          (when (position what #(:exited :signaled))
351            (with-active-processes-lock ()
352              (setf *active-processes*
353                    (delete proc *active-processes*))))))))
354   #+win32
355   (let (exited)
356     (with-active-processes-lock ()
357       (setf *active-processes*
358             (delete-if (lambda (proc)
359                          (multiple-value-bind (ok code)
360                              (get-exit-code-process (process-pid proc))
361                            (when (and (plusp ok) (/= code 259))
362                              (setf (process-%status proc) :exited
363                                    (process-exit-code proc) code)
364                              (when (process-status-hook proc)
365                                (push proc exited))
366                              t)))
367                        *active-processes*)))
368     ;; Can't call the hooks before all the processes have been deal
369     ;; with, as calling a hook may cause re-entry to
370     ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,
371     ;; but in the Windows implementation is would be deeply bad.
372     (dolist (proc exited)
373       (let ((hook (process-status-hook proc)))
374         (when hook
375           (funcall hook proc))))))
376 \f
377 ;;;; RUN-PROGRAM and close friends
378
379 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
380 (defvar *close-on-error* nil)
381
382 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
383 (defvar *close-in-parent* nil)
384
385 ;;; list of handlers installed by RUN-PROGRAM.  FIXME: nothing seems
386 ;;; to set this.
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 #-(or win32 openbsd)
394 (progn
395   (define-alien-routine ptsname c-string (fd int))
396   (define-alien-routine grantpt boolean (fd int))
397   (define-alien-routine unlockpt boolean (fd int))
398
399   (defun find-a-pty ()
400     ;; First try to use the Unix98 pty api.
401     (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
402            (master-fd (sb-unix:unix-open master-name
403                                          sb-unix:o_rdwr
404                                          #o666)))
405       (when master-fd
406         (grantpt master-fd)
407         (unlockpt master-fd)
408         (let* ((slave-name (ptsname master-fd))
409                (slave-fd (sb-unix:unix-open slave-name
410                                             sb-unix:o_rdwr
411                                             #o666)))
412           (when slave-fd
413             (return-from find-a-pty
414               (values master-fd
415                       slave-fd
416                       slave-name)))
417           (sb-unix:unix-close master-fd))
418         (error "could not find a pty")))
419     ;; No dice, try using the old-school method.
420     (dolist (char '(#\p #\q))
421       (dotimes (digit 16)
422         (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
423                                     'base-string))
424                (master-fd (sb-unix:unix-open master-name
425                                              sb-unix:o_rdwr
426                                              #o666)))
427           (when master-fd
428             (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
429                                        'base-string))
430                    (slave-fd (sb-unix:unix-open slave-name
431                                                 sb-unix:o_rdwr
432                                                 #o666)))
433               (when slave-fd
434                 (return-from find-a-pty
435                   (values master-fd
436                           slave-fd
437                           slave-name)))
438               (sb-unix:unix-close master-fd))))))
439     (error "could not find a pty")))
440 #+openbsd
441 (progn
442   (define-alien-routine openpty int (amaster int :out) (aslave int :out)
443                         (name (* char)) (termp (* t)) (winp (* t)))
444   (defun find-a-pty ()
445     (with-alien ((name-buf (array char 16)))
446       (multiple-value-bind (return-val master-fd slave-fd)
447           (openpty (cast name-buf (* char)) nil nil)
448         (if (zerop return-val)
449             (values master-fd
450                     slave-fd
451                     (sb-alien::c-string-to-string (alien-sap name-buf)
452                                                   (sb-impl::default-external-format)
453                                                   'character))
454             (error "could not find a pty"))))))
455
456 #-win32
457 (defun open-pty (pty cookie)
458   (when pty
459     (multiple-value-bind
460           (master slave name)
461         (find-a-pty)
462       (push master *close-on-error*)
463       (push slave *close-in-parent*)
464       (when (streamp pty)
465         (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
466           (unless new-fd
467             (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
468           (push new-fd *close-on-error*)
469           (copy-descriptor-to-stream new-fd pty cookie)))
470       (values name
471               (sb-sys:make-fd-stream master :input t :output t
472                                      :element-type :default
473                                      :dual-channel-p t)))))
474
475 (defmacro round-bytes-to-words (n)
476   (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
477     `(logandc2 (the fixnum (+ (the fixnum ,n)
478                               (1- ,bytes-per-word))) (1- ,bytes-per-word))))
479
480 (defun string-list-to-c-strvec (string-list)
481   (let* ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))
482          ;; We need an extra for the null, and an extra 'cause exect
483          ;; clobbers argv[-1].
484          (vec-bytes (* bytes-per-word (+ (length string-list) 2)))
485          (octet-vector-list (mapcar (lambda (s)
486                                       (string-to-octets s :null-terminate t))
487                                     string-list))
488          (string-bytes (reduce #'+ octet-vector-list
489                                :key (lambda (s)
490                                       (round-bytes-to-words (length s)))))
491          (total-bytes (+ string-bytes vec-bytes))
492          ;; Memory to hold the vector of pointers and all the strings.
493          (vec-sap (sb-sys:allocate-system-memory total-bytes))
494          (string-sap (sap+ vec-sap vec-bytes))
495          ;; Index starts from [1]!
496          (vec-index-offset bytes-per-word))
497     (declare (index string-bytes vec-bytes total-bytes)
498              (sb-sys:system-area-pointer vec-sap string-sap))
499     (dolist (octets octet-vector-list)
500       (declare (type (simple-array (unsigned-byte 8) (*)) octets))
501       (let ((size (length octets)))
502         ;; Copy string.
503         (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
504         ;; Put the pointer in the vector.
505         (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
506         ;; Advance string-sap for the next string.
507         (setf string-sap (sap+ string-sap (round-bytes-to-words size)))
508         (incf vec-index-offset bytes-per-word)))
509     ;; Final null pointer.
510     (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
511     (values vec-sap (sap+ vec-sap bytes-per-word) total-bytes)))
512
513 (defmacro with-c-strvec ((var str-list) &body body)
514   (with-unique-names (sap size)
515     `(multiple-value-bind (,sap ,var ,size)
516          (string-list-to-c-strvec ,str-list)
517        (unwind-protect
518             (progn
519               ,@body)
520          (sb-sys:deallocate-system-memory ,sap ,size)))))
521
522 (sb-alien:define-alien-routine spawn
523     #-win32 sb-alien:int
524     #+win32 sb-win32::handle
525   (program sb-alien:c-string)
526   (argv (* sb-alien:c-string))
527   (stdin sb-alien:int)
528   (stdout sb-alien:int)
529   (stderr sb-alien:int)
530   (search sb-alien:int)
531   (envp (* sb-alien:c-string))
532   (pty-name sb-alien:c-string)
533   (wait sb-alien:int))
534
535 ;;; FIXME: There shouldn't be two semiredundant versions of the
536 ;;; documentation. Since this is a public extension function, the
537 ;;; documentation should be in the doc string. So all information from
538 ;;; this comment should be merged into the doc string, and then this
539 ;;; comment can go away.
540 ;;;
541 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
542 ;;; Strange stuff happens to keep the Unix state of the world
543 ;;; coherent.
544 ;;;
545 ;;; The child process needs to get its input from somewhere, and send
546 ;;; its output (both standard and error) to somewhere. We have to do
547 ;;; different things depending on where these somewheres really are.
548 ;;;
549 ;;; For input, there are five options:
550 ;;;  -- T: Just leave fd 0 alone. Pretty simple.
551 ;;;  -- "file": Read from the file. We need to open the file and
552 ;;;     pull the descriptor out of the stream. The parent should close
553 ;;;     this stream after the child is up and running to free any
554 ;;;     storage used in the parent.
555 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.
556 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use
557 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the
558 ;;;     writeable descriptor, and pass the readable descriptor to
559 ;;;     the child. The parent must close the readable descriptor for
560 ;;;     EOF to be passed up correctly.
561 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out
562 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy
563 ;;;     everything across.
564 ;;;
565 ;;; For output, there are five options:
566 ;;;  -- T: Leave descriptor 1 alone.
567 ;;;  -- "file": dump output to the file.
568 ;;;  -- NIL: dump output to /dev/null.
569 ;;;  -- :STREAM: return a stream that can be read from.
570 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.
571 ;;;     Otherwise, copy stuff from output to stream.
572 ;;;
573 ;;; For error, there are all the same options as output plus:
574 ;;;  -- :OUTPUT: redirect to the same place as output.
575 ;;;
576 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
577 ;;; the fork worked, and NIL if it did not.
578 (defun run-program (program args
579                     &key
580                     #-win32 (env nil env-p)
581                     #-win32 (environment
582                              (if env-p
583                                  (unix-environment-sbcl-from-cmucl env)
584                                  (posix-environ))
585                              environment-p)
586                     (wait t)
587                     search
588                     #-win32 pty
589                     input
590                     if-input-does-not-exist
591                     output
592                     (if-output-exists :error)
593                     (error :output)
594                     (if-error-exists :error)
595                     status-hook)
596   #+sb-doc
597   #.(concatenate
598      'string
599      ;; The Texinfoizer is sensitive to whitespace, so mind the
600      ;; placement of the #-win32 pseudosplicings.
601      "RUN-PROGRAM creates a new process specified by the PROGRAM
602 argument. ARGS are the standard arguments that can be passed to a
603 program. For no arguments, use NIL (which means that just the
604 name of the program is passed as arg 0).
605
606 The program arguments and the environment are encoded using the
607 default external format for streams.
608
609 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
610 Users Manual for details about the PROCESS structure."#-win32"
611
612    Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
613
614    - The SBCL implementation of RUN-PROGRAM, like Perl and many other
615      programs, but unlike the original CMU CL implementation, copies
616      the Unix environment by default.
617
618    - Running Unix programs from a setuid process, or in any other
619      situation where the Unix environment is under the control of someone
620      else, is a mother lode of security problems. If you are contemplating
621      doing this, read about it first. (The Perl community has a lot of good
622      documentation about this and other security issues in script-like
623      programs.)""
624
625    The &KEY arguments have the following meanings:
626 "#-win32"
627    :ENVIRONMENT
628       a list of STRINGs describing the new Unix environment
629       (as in \"man environ\"). The default is to copy the environment of
630       the current process.
631    :ENV
632       an alternative lossy representation of the new Unix environment,
633       for compatibility with CMU CL""
634    :SEARCH
635       Look for PROGRAM in each of the directories in the child's $PATH
636       environment variable.  Otherwise an absolute pathname is required.
637    :WAIT
638       If non-NIL (default), wait until the created process finishes.  If
639       NIL, continue running Lisp until the program finishes."#-win32"
640    :PTY
641       Either T, NIL, or a stream.  Unless NIL, the subprocess is established
642       under a PTY.  If :pty is a stream, all output to this pty is sent to
643       this stream, otherwise the PROCESS-PTY slot is filled in with a stream
644       connected to pty that can read output and write input.""
645    :INPUT
646       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
647       input for the current process is inherited.  If NIL, "
648       #-win32"/dev/null"#+win32"nul""
649       is used.  If a pathname, the file so specified is used.  If a stream,
650       all the input is read from that stream and sent to the subprocess.  If
651       :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
652       its output to the process. Defaults to NIL.
653    :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
654       can be one of:
655          :ERROR to generate an error
656          :CREATE to create an empty file
657          NIL (the default) to return NIL from RUN-PROGRAM
658    :OUTPUT
659       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
660       output for the current process is inherited.  If NIL, "
661       #-win32"/dev/null"#+win32"nul""
662       is used.  If a pathname, the file so specified is used.  If a stream,
663       all the output from the process is written to this stream. If
664       :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
665       be read to get the output. Defaults to NIL.
666    :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
667       can be one of:
668          :ERROR (the default) to generate an error
669          :SUPERSEDE to supersede the file with output from the program
670          :APPEND to append output from the program to the file
671          NIL to return NIL from RUN-PROGRAM, without doing anything
672    :ERROR and :IF-ERROR-EXISTS
673       Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
674       specified as :OUTPUT in which case all error output is routed to the
675       same place as normal output.
676    :STATUS-HOOK
677       This is a function the system calls whenever the status of the
678       process changes.  The function takes the process as an argument.")
679   #-win32
680   (when (and env-p environment-p)
681     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
682   ;; Make sure that the interrupt handler is installed.
683   #-win32
684   (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
685   ;; Prepend the program to the argument list.
686   (push (namestring program) args)
687   (labels (;; It's friendly to allow the caller to pass any string
688            ;; designator, but internally we'd like SIMPLE-STRINGs.
689            ;;
690            ;; Huh?  We let users pass in symbols and characters for
691            ;; the arguments, but call NAMESTRING on the program
692            ;; name... -- RMK
693            (simplify-args (args)
694              (loop for arg in args
695                    as escaped-arg = (escape-arg arg)
696                    collect (coerce escaped-arg 'simple-string)))
697            (escape-arg (arg)
698              #-win32 arg
699              ;; Apparently any spaces or double quotes in the arguments
700              ;; need to be escaped on win32.
701              #+win32 (if (position-if
702                           (lambda (c) (find c '(#\" #\Space))) arg)
703                          (write-to-string arg)
704                          arg)))
705     (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
706           ;; communicate cleanup info.
707           *close-on-error*
708           *close-in-parent*
709           ;; Some other binding used only on non-Win32.  FIXME:
710           ;; nothing seems to set this.
711           #-win32 *handlers-installed*
712           ;; Establish PROC at this level so that we can return it.
713           proc
714           (simple-args (simplify-args args))
715           (progname (native-namestring program))
716           ;; Gag.
717           (cookie (list 0)))
718       (unwind-protect
719            ;; Note: despite the WITH-* names, these macros don't
720            ;; expand into UNWIND-PROTECT forms.  They're just
721            ;; syntactic sugar to make the rest of the routine slightly
722            ;; easier to read.
723            (macrolet ((with-fd-and-stream-for (((fd stream) which &rest args)
724                                                &body body)
725                         `(multiple-value-bind (,fd ,stream)
726                              ,(ecase which
727                                 ((:input :output)
728                                  `(get-descriptor-for ,@args))
729                                 (:error
730                                  `(if (eq ,(first args) :output)
731                                       ;; kludge: we expand into
732                                       ;; hard-coded symbols here.
733                                       (values stdout output-stream)
734                                       (get-descriptor-for ,@args))))
735                            ,@body))
736                       (with-open-pty (((pty-name pty-stream) (pty cookie)) &body body)
737                         #+win32 `(declare (ignore ,pty ,cookie))
738                         #+win32 `(let (,pty-name ,pty-stream) ,@body)
739                         #-win32 `(multiple-value-bind (,pty-name ,pty-stream)
740                                      (open-pty ,pty ,cookie)
741                                    ,@body))
742                       (with-args-vec ((vec args) &body body)
743                         `(with-c-strvec (,vec ,args)
744                            ,@body))
745                       (with-environment-vec ((vec env) &body body)
746                         #+win32 `(let (,vec) ,@body)
747                         #-win32 `(with-c-strvec (,vec ,env) ,@body)))
748              (with-fd-and-stream-for ((stdin input-stream) :input
749                                       input cookie
750                                       :direction :input
751                                       :if-does-not-exist if-input-does-not-exist
752                                       :external-format :default
753                                       :wait wait)
754                (with-fd-and-stream-for ((stdout output-stream) :output
755                                         output cookie
756                                         :direction :output
757                                         :if-exists if-output-exists
758                                         :external-format :default)
759                  (with-fd-and-stream-for ((stderr error-stream)  :error
760                                           error cookie
761                                           :direction :output
762                                           :if-exists if-error-exists
763                                           :external-format :default)
764                    (with-open-pty ((pty-name pty-stream) (pty cookie))
765                      ;; Make sure we are not notified about the child
766                      ;; death before we have installed the PROCESS
767                      ;; structure in *ACTIVE-PROCESSES*.
768                      (with-active-processes-lock ()
769                        (with-args-vec (args-vec simple-args)
770                          (with-environment-vec (environment-vec environment)
771                            (let ((child
772                                   (without-gcing
773                                     (spawn progname args-vec
774                                            stdin stdout stderr
775                                            (if search 1 0)
776                                            environment-vec pty-name
777                                            (if wait 1 0)))))
778                              (when (= child -1)
779                                (error "couldn't fork child process: ~A"
780                                       (strerror)))
781                              (setf proc (apply
782                                          #'make-process
783                                          :pid child
784                                          :input input-stream
785                                          :output output-stream
786                                          :error error-stream
787                                          :status-hook status-hook
788                                          :cookie cookie
789                                          #-win32 (list :pty pty-stream
790                                                        :%status :running)
791                                          #+win32 (if wait
792                                                      (list :%status :exited
793                                                            :exit-code child)
794                                                      (list :%status :running))))
795                              (push proc *active-processes*))))))))))
796         (dolist (fd *close-in-parent*)
797           (sb-unix:unix-close fd))
798         (unless proc
799           (dolist (fd *close-on-error*)
800             (sb-unix:unix-close fd))
801           ;; FIXME: nothing seems to set this.
802           #-win32
803           (dolist (handler *handlers-installed*)
804             (sb-sys:remove-fd-handler handler))))
805       #-win32
806       (when (and wait proc)
807         (process-wait proc))
808       proc)))
809
810 ;;; Install a handler for any input that shows up on the file
811 ;;; descriptor. The handler reads the data and writes it to the
812 ;;; stream.
813 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
814   (incf (car cookie))
815   (let* (handler
816          (buf (make-array 256 :element-type '(unsigned-byte 8)))
817          (read-end 0))
818     (setf handler
819           (sb-sys:add-fd-handler
820            descriptor
821            :input
822            (lambda (fd)
823              (declare (ignore fd))
824              (loop
825                 (unless handler
826                   (return))
827                 (multiple-value-bind
828                       (result readable/errno)
829                     (sb-unix:unix-select (1+ descriptor)
830                                          (ash 1 descriptor)
831                                          0 0 0)
832                   (cond ((null result)
833                          (if (eql sb-unix:eintr readable/errno)
834                              (return)
835                              (error "~@<Couldn't select on sub-process: ~
836                                         ~2I~_~A~:>"
837                                     (strerror readable/errno))))
838                         ((zerop result)
839                          (return))))
840                 (multiple-value-bind (count errno)
841                     (with-pinned-objects (buf)
842                       (sb-unix:unix-read descriptor
843                                          (sap+ (vector-sap buf) read-end)
844                                          (- (length buf) read-end)))
845                   (cond
846                     ((and #-win32 (or (and (null count)
847                                            (eql errno sb-unix:eio))
848                                       (eql count 0))
849                           #+win32 (<= count 0))
850                      (sb-sys:remove-fd-handler handler)
851                      (setf handler nil)
852                      (decf (car cookie))
853                      (sb-unix:unix-close descriptor)
854                      (unless (zerop read-end)
855                        ;; Should this be an END-OF-FILE?
856                        (error "~@<non-empty buffer when EOF reached ~
857                                while reading from child: ~S~:>" buf))
858                      (return))
859                     ((null count)
860                      (sb-sys:remove-fd-handler handler)
861                      (setf handler nil)
862                      (decf (car cookie))
863                      (error
864                       "~@<couldn't read input from sub-process: ~
865                                      ~2I~_~A~:>"
866                       (strerror errno)))
867                     (t
868                      (incf read-end count)
869                      (let* ((decode-end read-end)
870                             (string (handler-case
871                                         (octets-to-string
872                                          buf :end read-end
873                                          :external-format external-format)
874                                       (end-of-input-in-character (e)
875                                         (setf decode-end
876                                               (octet-decoding-error-start e))
877                                         (octets-to-string
878                                          buf :end decode-end
879                                          :external-format external-format)))))
880                        (unless (zerop (length string))
881                          (write-string string stream)
882                          (when (/= decode-end (length buf))
883                            (replace buf buf :start2 decode-end :end2 read-end))
884                          (decf read-end decode-end))))))))))))
885
886 ;;; FIXME: something very like this is done in SB-POSIX to treat
887 ;;; streams as file descriptor designators; maybe we can combine these
888 ;;; two?  Additionally, as we have a couple of user-defined streams
889 ;;; libraries, maybe we should have a generic function for doing this,
890 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
891 ;;; maybe also with SB-POSIX)?
892 (defun get-stream-fd-and-external-format (stream direction)
893   (typecase stream
894     (sb-sys:fd-stream
895      (values (sb-sys:fd-stream-fd stream) nil (stream-external-format stream)))
896     (synonym-stream
897      (get-stream-fd-and-external-format
898       (symbol-value (synonym-stream-symbol stream)) direction))
899     (two-way-stream
900      (ecase direction
901        (:input
902         (get-stream-fd-and-external-format
903          (two-way-stream-input-stream stream) direction))
904        (:output
905         (get-stream-fd-and-external-format
906          (two-way-stream-output-stream stream) direction))))))
907
908 \f
909 ;;; Find a file descriptor to use for object given the direction.
910 ;;; Returns the descriptor. If object is :STREAM, returns the created
911 ;;; stream as the second value.
912 (defun get-descriptor-for (object
913                            cookie
914                            &rest keys
915                            &key direction (external-format :default) wait
916                            &allow-other-keys)
917   (declare (ignore wait)) ;This is explained below.
918   ;; Our use of a temporary file dates back to very old CMUCLs, and
919   ;; was probably only ever intended for use with STRING-STREAMs,
920   ;; which are ordinarily smallish.  However, as we've got
921   ;; user-defined stream classes, we can end up trying to copy
922   ;; arbitrarily much data into the temp file, and so are liable to
923   ;; run afoul of disk quotas or to choke on small /tmp file systems.
924   (flet ((make-temp-fd ()
925            (multiple-value-bind (fd name/errno)
926                (sb-unix:sb-mkstemp "/tmp/.run-program-XXXXXX" #o0600)
927              (unless fd
928                (error "could not open a temporary file: ~A"
929                       (strerror name/errno)))
930              (unless (sb-unix:unix-unlink name/errno)
931                (sb-unix:unix-close fd)
932                (error "failed to unlink ~A" name/errno))
933              fd)))
934     (cond ((eq object t)
935            ;; No new descriptor is needed.
936            (values -1 nil))
937           ((eq object nil)
938            ;; Use /dev/null.
939            (multiple-value-bind
940                  (fd errno)
941                (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
942                                   #+win32 #.(coerce "nul" 'base-string)
943                                   (case direction
944                                     (:input sb-unix:o_rdonly)
945                                     (:output sb-unix:o_wronly)
946                                     (t sb-unix:o_rdwr))
947                                   #o666)
948              (unless fd
949                (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
950                       #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
951                       (strerror errno)))
952              (push fd *close-in-parent*)
953              (values fd nil)))
954           ((eq object :stream)
955            (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
956              (unless read-fd
957                (error "couldn't create pipe: ~A" (strerror write-fd)))
958              (case direction
959                (:input
960                 (push read-fd *close-in-parent*)
961                 (push write-fd *close-on-error*)
962                 (let ((stream (sb-sys:make-fd-stream write-fd :output t
963                                                      :element-type :default
964                                                      :external-format
965                                                      external-format)))
966                   (values read-fd stream)))
967                (:output
968                 (push read-fd *close-on-error*)
969                 (push write-fd *close-in-parent*)
970                 (let ((stream (sb-sys:make-fd-stream read-fd :input t
971                                                      :element-type :default
972                                                      :external-format
973                                                      external-format)))
974                   (values write-fd stream)))
975                (t
976                 (sb-unix:unix-close read-fd)
977                 (sb-unix:unix-close write-fd)
978                 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
979                        direction)))))
980           ((or (pathnamep object) (stringp object))
981            ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
982            ;; than munge the &rest list for OPEN, just disable keyword
983            ;; validation there.
984            (with-open-stream (file (apply #'open object :allow-other-keys t
985                                           keys))
986              (multiple-value-bind
987                    (fd errno)
988                  (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
989                (cond (fd
990                       (push fd *close-in-parent*)
991                       (values fd nil))
992                      (t
993                       (error "couldn't duplicate file descriptor: ~A"
994                              (strerror errno)))))))
995           ((streamp object)
996            (ecase direction
997              (:input
998               (block nil
999                 ;; If we can get an fd for the stream, let the child
1000                 ;; process use the fd for its descriptor.  Otherwise,
1001                 ;; we copy data from the stream into a temp file, and
1002                 ;; give the temp file's descriptor to the
1003                 ;; child.
1004                 (multiple-value-bind (fd stream format)
1005                     (get-stream-fd-and-external-format object :input)
1006                   (declare (ignore format))
1007                   (when fd
1008                     (return (values fd stream))))
1009                 ;; FIXME: if we can't get the file descriptor, since
1010                 ;; the stream might be interactive or otherwise
1011                 ;; block-y, we can't know whether we can copy the
1012                 ;; stream's data to a temp file, so if RUN-PROGRAM was
1013                 ;; called with :WAIT NIL, we should probably error.
1014                 ;; However, STRING-STREAMs aren't fd-streams, but
1015                 ;; they're not prone to blocking; any user-defined
1016                 ;; streams that "read" from some in-memory data will
1017                 ;; probably be similar to STRING-STREAMs.  So maybe we
1018                 ;; should add a STREAM-INTERACTIVE-P generic function
1019                 ;; for problems like this?  Anyway, the machinery is
1020                 ;; here, if you feel like filling in the details.
1021                 #|
1022                 (when (and (null wait) #<some undetermined criterion>)
1023                   (error "~@<don't know how to get an fd for ~A, and so ~
1024                              can't ensure that copying its data to the ~
1025                              child process won't hang~:>" object))
1026                 |#
1027                 (let ((fd (make-temp-fd))
1028                       (newline (string #\Newline)))
1029                   (loop
1030                      (multiple-value-bind
1031                            (line no-cr)
1032                          (read-line object nil nil)
1033                        (unless line
1034                          (return))
1035                        (let ((vector (string-to-octets line)))
1036                          (sb-unix:unix-write
1037                           fd vector 0 (length vector)))
1038                        (if no-cr
1039                            (return)
1040                            (sb-unix:unix-write fd newline 0 1))))
1041                   (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1042                   (push fd *close-in-parent*)
1043                   (return (values fd nil)))))
1044              (:output
1045               (block nil
1046                 ;; Similar to the :input trick above, except we
1047                 ;; arrange to copy data from the stream.  This is
1048                 ;; slightly saner than the input case, since we don't
1049                 ;; buffer to a file, but I think we may still lose if
1050                 ;; there's unflushed data in the stream buffer and we
1051                 ;; give the file descriptor to the child.
1052                 (multiple-value-bind (fd stream format)
1053                     (get-stream-fd-and-external-format object :output)
1054                   (declare (ignore format))
1055                   (when fd
1056                     (return (values fd stream))))
1057                 (multiple-value-bind (read-fd write-fd)
1058                     (sb-unix:unix-pipe)
1059                   (unless read-fd
1060                     (error "couldn't create pipe: ~S" (strerror write-fd)))
1061                   (copy-descriptor-to-stream read-fd object cookie
1062                                              external-format)
1063                   (push read-fd *close-on-error*)
1064                   (push write-fd *close-in-parent*)
1065                   (return (values write-fd nil)))))))
1066           (t
1067            (error "invalid option to RUN-PROGRAM: ~S" object)))))