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