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