1.0.25.33: protect against recursive gcs
[sbcl.git] / src / code / run-program.lisp
1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
2 ;;;; from inside SBCL
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)
14 \f
15 ;;;; hacking the Unix environment
16 ;;;;
17 ;;;; In the original CMU CL code that LOAD-FOREIGN is derived from, the
18 ;;;; Unix environment (as in "man environ") was represented as an
19 ;;;; alist from keywords to strings, so that e.g. the Unix environment
20 ;;;;   "SHELL=/bin/bash" "HOME=/root" "PAGER=less"
21 ;;;; was represented as
22 ;;;;   ((:SHELL . "/bin/bash") (:HOME . "/root") (:PAGER "less"))
23 ;;;; This had a few problems in principle: the mapping into
24 ;;;; keyword symbols smashed the case of environment
25 ;;;; variables, and the whole mapping depended on the presence of
26 ;;;; #\= characters in the environment strings. In practice these
27 ;;;; problems weren't hugely important, since conventionally environment
28 ;;;; variables are uppercase strings followed by #\= followed by
29 ;;;; arbitrary data. However, since it's so manifestly not The Right
30 ;;;; Thing to make code which breaks unnecessarily on input which
31 ;;;; doesn't follow what is, after all, only a tradition, we've switched
32 ;;;; formats in SBCL, so that the fundamental environment list
33 ;;;; is just a list of strings, with a one-to-one-correspondence
34 ;;;; to the C-level representation. I.e., in the example above,
35 ;;;; the SBCL representation is
36 ;;;;   '("SHELL=/bin/bash" "HOME=/root" "PAGER=less")
37 ;;;; CMU CL's implementation is currently supported to help with porting.
38 ;;;;
39 ;;;; It's not obvious that this code belongs here (instead of e.g. in
40 ;;;; unix.lisp), since it has only a weak logical connection with
41 ;;;; RUN-PROGRAM. However, physically it's convenient to put it here.
42 ;;;; It's not needed at cold init, so we *can* put it in this
43 ;;;; warm-loaded file. And by putting it in this warm-loaded file, we
44 ;;;; make it easy for it to get to the C-level 'environ' variable.
45 ;;;; which (at least in sbcl-0.6.10 on Red Hat Linux 6.2) is not
46 ;;;; visible at GENESIS time.
47
48 #-win32
49 (progn
50   (define-alien-routine wrapped-environ (* c-string))
51   (defun posix-environ ()
52     "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
53     (c-strings->string-list (wrapped-environ))))
54
55 ;#+win32 (sb-alien:define-alien-routine msvcrt-environ (* c-string))
56
57 ;;; Convert as best we can from an SBCL representation of a Unix
58 ;;; environment to a CMU CL representation.
59 ;;;
60 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
61 ;;; WARNING:
62 ;;;   smashing case of "Bletch=fub" in conversion to CMU-CL-style
63 ;;;     environment alist
64 ;;; WARNING:
65 ;;;   no #\= in "Noggin", eliding it in CMU-CL-style environment alist
66 ;;; ((:BLETCH . "fub") (:YES . "No!"))
67 (defun unix-environment-cmucl-from-sbcl (sbcl)
68   (mapcan
69    (lambda (string)
70      (declare (string string))
71      (let ((=-pos (position #\= string :test #'equal)))
72        (if =-pos
73            (list
74             (let* ((key-as-string (subseq string 0 =-pos))
75                    (key-as-upcase-string (string-upcase key-as-string))
76                    (key (keywordicate key-as-upcase-string))
77                    (val (subseq string (1+ =-pos))))
78               (unless (string= key-as-string key-as-upcase-string)
79                 (warn "smashing case of ~S in conversion to CMU-CL-style ~
80                       environment alist"
81                       string))
82               (cons key val)))
83            (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
84                  string))))
85    sbcl))
86
87 ;;; Convert from a CMU CL representation of a Unix environment to a
88 ;;; SBCL representation.
89 (defun unix-environment-sbcl-from-cmucl (cmucl)
90   (mapcar
91    (lambda (cons)
92      (destructuring-bind (key . val) cons
93        (declare (type keyword key) (string val))
94        (concatenate 'simple-string (symbol-name key) "=" val)))
95    cmucl))
96 \f
97 ;;;; Import wait3(2) from Unix.
98
99 #-win32
100 (define-alien-routine ("wait3" c-wait3) sb-alien:int
101   (status sb-alien:int :out)
102   (options sb-alien:int)
103   (rusage sb-alien:int))
104
105 #-win32
106 (defun wait3 (&optional do-not-hang check-for-stopped)
107   #+sb-doc
108   "Return any available status information on child process. "
109   (multiple-value-bind (pid status)
110       (c-wait3 (logior (if do-not-hang
111                            sb-unix:wnohang
112                            0)
113                        (if check-for-stopped
114                            sb-unix:wuntraced
115                            0))
116                0)
117     (cond ((or (minusp pid)
118                (zerop pid))
119            nil)
120           ((eql (ldb (byte 8 0) status)
121                 sb-unix:wstopped)
122            (values pid
123                    :stopped
124                    (ldb (byte 8 8) status)))
125           ((zerop (ldb (byte 7 0) status))
126            (values pid
127                    :exited
128                    (ldb (byte 8 8) status)))
129           (t
130            (let ((signal (ldb (byte 7 0) status)))
131              (values pid
132                      (if (position signal
133                                    #.(vector
134                                       sb-unix:sigstop
135                                       sb-unix:sigtstp
136                                       sb-unix:sigttin
137                                       sb-unix:sigttou))
138                          :stopped
139                          :signaled)
140                      signal
141                      (not (zerop (ldb (byte 1 7) status)))))))))
142 \f
143 ;;;; process control stuff
144 (defvar *active-processes* nil
145   #+sb-doc
146   "List of process structures for all active processes.")
147
148 #-win32
149 (defvar *active-processes-lock*
150   (sb-thread:make-mutex :name "Lock for active processes."))
151
152 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
153 ;;; mutex is needed. More importantly the sigchld signal handler also
154 ;;; accesses it, that's why we need without-interrupts.
155 (defmacro with-active-processes-lock (() &body body)
156   #-win32
157   `(sb-thread::with-system-mutex (*active-processes-lock* :allow-with-interrupts t)
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 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
324 #-win32
325 (defun sigchld-handler (ignore1 ignore2 ignore3)
326   (declare (ignore ignore1 ignore2 ignore3))
327   (get-processes-status-changes))
328
329 (defun get-processes-status-changes ()
330   #-win32
331   (loop
332    (multiple-value-bind (pid what code core)
333        (wait3 t t)
334      (unless pid
335        (return))
336      (let ((proc (with-active-processes-lock ()
337                    (find pid *active-processes* :key #'process-pid))))
338        (when proc
339          (setf (process-%status proc) what)
340          (setf (process-exit-code proc) code)
341          (setf (process-core-dumped proc) core)
342          (when (process-status-hook proc)
343            (funcall (process-status-hook proc) proc))
344          (when (position what #(:exited :signaled))
345            (with-active-processes-lock ()
346              (setf *active-processes*
347                    (delete proc *active-processes*))))))))
348   #+win32
349   (let (exited)
350     (with-active-processes-lock ()
351       (setf *active-processes*
352             (delete-if (lambda (proc)
353                          (multiple-value-bind (ok code)
354                              (get-exit-code-process (process-pid proc))
355                            (when (and (plusp ok) (/= code 259))
356                              (setf (process-%status proc) :exited
357                                    (process-exit-code proc) code)
358                              (when (process-status-hook proc)
359                                (push proc exited))
360                              t)))
361                        *active-processes*)))
362     ;; Can't call the hooks before all the processes have been deal
363     ;; with, as calling a hook may cause re-entry to
364     ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,
365     ;; but in the Windows implementation is would be deeply bad.
366     (dolist (proc exited)
367       (let ((hook (process-status-hook proc)))
368         (when hook
369           (funcall hook proc))))))
370 \f
371 ;;;; RUN-PROGRAM and close friends
372
373 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
374 (defvar *close-on-error* nil)
375
376 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
377 (defvar *close-in-parent* nil)
378
379 ;;; list of handlers installed by RUN-PROGRAM.  FIXME: nothing seems
380 ;;; to set this.
381 #-win32
382 (defvar *handlers-installed* nil)
383
384 ;;; Find an unused pty. Return three values: the file descriptor for
385 ;;; the master side of the pty, the file descriptor for the slave side
386 ;;; of the pty, and the name of the tty device for the slave side.
387 #-(or win32 openbsd)
388 (progn
389   (define-alien-routine ptsname c-string (fd int))
390   (define-alien-routine grantpt boolean (fd int))
391   (define-alien-routine unlockpt boolean (fd int))
392
393   (defun find-a-pty ()
394     ;; First try to use the Unix98 pty api.
395     (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
396            (master-fd (sb-unix:unix-open master-name
397                                          sb-unix:o_rdwr
398                                          #o666)))
399       (when master-fd
400         (grantpt master-fd)
401         (unlockpt master-fd)
402         (let* ((slave-name (ptsname master-fd))
403                (slave-fd (sb-unix:unix-open slave-name
404                                             sb-unix:o_rdwr
405                                             #o666)))
406           (when slave-fd
407             (return-from find-a-pty
408               (values master-fd
409                       slave-fd
410                       slave-name)))
411           (sb-unix:unix-close master-fd))
412         (error "could not find a pty")))
413     ;; No dice, try using the old-school method.
414     (dolist (char '(#\p #\q))
415       (dotimes (digit 16)
416         (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
417                                     'base-string))
418                (master-fd (sb-unix:unix-open master-name
419                                              sb-unix:o_rdwr
420                                              #o666)))
421           (when master-fd
422             (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
423                                        'base-string))
424                    (slave-fd (sb-unix:unix-open slave-name
425                                                 sb-unix:o_rdwr
426                                                 #o666)))
427               (when slave-fd
428                 (return-from find-a-pty
429                   (values master-fd
430                           slave-fd
431                           slave-name)))
432               (sb-unix:unix-close master-fd))))))
433     (error "could not find a pty")))
434 #+openbsd
435 (progn
436   (define-alien-routine openpty int (amaster int :out) (aslave int :out)
437                         (name (* char)) (termp (* t)) (winp (* t)))
438   (defun find-a-pty ()
439     (with-alien ((name-buf (array char 16)))
440       (multiple-value-bind (return-val master-fd slave-fd)
441           (openpty (cast name-buf (* char)) nil nil)
442         (if (zerop return-val)
443             (values master-fd
444                     slave-fd
445                     (sb-alien::c-string-to-string (alien-sap name-buf)
446                                                   (sb-impl::default-external-format)
447                                                   'character))
448             (error "could not find a pty"))))))
449
450 #-win32
451 (defun open-pty (pty cookie)
452   (when pty
453     (multiple-value-bind
454           (master slave name)
455         (find-a-pty)
456       (push master *close-on-error*)
457       (push slave *close-in-parent*)
458       (when (streamp pty)
459         (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
460           (unless new-fd
461             (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
462           (push new-fd *close-on-error*)
463           (copy-descriptor-to-stream new-fd pty cookie)))
464       (values name
465               (sb-sys:make-fd-stream master :input t :output t
466                                      :element-type :default
467                                      :dual-channel-p t)))))
468
469 (defmacro round-bytes-to-words (n)
470   (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
471     `(logandc2 (the fixnum (+ (the fixnum ,n)
472                               (1- ,bytes-per-word))) (1- ,bytes-per-word))))
473
474 (defun string-list-to-c-strvec (string-list)
475   (let* ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))
476          ;; We need an extra for the null, and an extra 'cause exect
477          ;; clobbers argv[-1].
478          (vec-bytes (* bytes-per-word (+ (length string-list) 2)))
479          (octet-vector-list (mapcar (lambda (s)
480                                       (string-to-octets s :null-terminate t))
481                                     string-list))
482          (string-bytes (reduce #'+ octet-vector-list
483                                :key (lambda (s)
484                                       (round-bytes-to-words (length s)))))
485          (total-bytes (+ string-bytes vec-bytes))
486          ;; Memory to hold the vector of pointers and all the strings.
487          (vec-sap (sb-sys:allocate-system-memory total-bytes))
488          (string-sap (sap+ vec-sap vec-bytes))
489          ;; Index starts from [1]!
490          (vec-index-offset bytes-per-word))
491     (declare (index string-bytes vec-bytes total-bytes)
492              (sb-sys:system-area-pointer vec-sap string-sap))
493     (dolist (octets octet-vector-list)
494       (declare (type (simple-array (unsigned-byte 8) (*)) octets))
495       (let ((size (length octets)))
496         ;; Copy string.
497         (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
498         ;; Put the pointer in the vector.
499         (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
500         ;; Advance string-sap for the next string.
501         (setf string-sap (sap+ string-sap (round-bytes-to-words size)))
502         (incf vec-index-offset bytes-per-word)))
503     ;; Final null pointer.
504     (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
505     (values vec-sap (sap+ vec-sap bytes-per-word) total-bytes)))
506
507 (defmacro with-c-strvec ((var str-list) &body body)
508   (with-unique-names (sap size)
509     `(multiple-value-bind (,sap ,var ,size)
510          (string-list-to-c-strvec ,str-list)
511        (unwind-protect
512             (progn
513               ,@body)
514          (sb-sys:deallocate-system-memory ,sap ,size)))))
515
516 (sb-alien:define-alien-routine spawn
517     #-win32 sb-alien:int
518     #+win32 sb-win32::handle
519   (program sb-alien:c-string)
520   (argv (* sb-alien:c-string))
521   (stdin sb-alien:int)
522   (stdout sb-alien:int)
523   (stderr sb-alien:int)
524   (search sb-alien:int)
525   (envp (* sb-alien:c-string))
526   (pty-name sb-alien:c-string)
527   (wait sb-alien:int))
528
529 ;;; FIXME: There shouldn't be two semiredundant versions of the
530 ;;; documentation. Since this is a public extension function, the
531 ;;; documentation should be in the doc string. So all information from
532 ;;; this comment should be merged into the doc string, and then this
533 ;;; comment can go away.
534 ;;;
535 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
536 ;;; Strange stuff happens to keep the Unix state of the world
537 ;;; coherent.
538 ;;;
539 ;;; The child process needs to get its input from somewhere, and send
540 ;;; its output (both standard and error) to somewhere. We have to do
541 ;;; different things depending on where these somewheres really are.
542 ;;;
543 ;;; For input, there are five options:
544 ;;;  -- T: Just leave fd 0 alone. Pretty simple.
545 ;;;  -- "file": Read from the file. We need to open the file and
546 ;;;     pull the descriptor out of the stream. The parent should close
547 ;;;     this stream after the child is up and running to free any
548 ;;;     storage used in the parent.
549 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.
550 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use
551 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the
552 ;;;     writeable descriptor, and pass the readable descriptor to
553 ;;;     the child. The parent must close the readable descriptor for
554 ;;;     EOF to be passed up correctly.
555 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out
556 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy
557 ;;;     everything across.
558 ;;;
559 ;;; For output, there are five options:
560 ;;;  -- T: Leave descriptor 1 alone.
561 ;;;  -- "file": dump output to the file.
562 ;;;  -- NIL: dump output to /dev/null.
563 ;;;  -- :STREAM: return a stream that can be read from.
564 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.
565 ;;;     Otherwise, copy stuff from output to stream.
566 ;;;
567 ;;; For error, there are all the same options as output plus:
568 ;;;  -- :OUTPUT: redirect to the same place as output.
569 ;;;
570 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
571 ;;; the fork worked, and NIL if it did not.
572 (defun run-program (program args
573                     &key
574                     #-win32 (env nil env-p)
575                     #-win32 (environment
576                              (if env-p
577                                  (unix-environment-sbcl-from-cmucl env)
578                                  (posix-environ))
579                              environment-p)
580                     (wait t)
581                     search
582                     #-win32 pty
583                     input
584                     if-input-does-not-exist
585                     output
586                     (if-output-exists :error)
587                     (error :output)
588                     (if-error-exists :error)
589                     status-hook)
590   #+sb-doc
591   #.(concatenate
592      'string
593      ;; The Texinfoizer is sensitive to whitespace, so mind the
594      ;; placement of the #-win32 pseudosplicings.
595      "RUN-PROGRAM creates a new process specified by the PROGRAM
596 argument. ARGS are the standard arguments that can be passed to a
597 program. For no arguments, use NIL (which means that just the
598 name of the program is passed as arg 0).
599
600 The program arguments and the environment are encoded using the
601 default external format for streams.
602
603 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
604 Users Manual for details about the PROCESS structure."#-win32"
605
606    Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
607
608    - The SBCL implementation of RUN-PROGRAM, like Perl and many other
609      programs, but unlike the original CMU CL implementation, copies
610      the Unix environment by default.
611
612    - Running Unix programs from a setuid process, or in any other
613      situation where the Unix environment is under the control of someone
614      else, is a mother lode of security problems. If you are contemplating
615      doing this, read about it first. (The Perl community has a lot of good
616      documentation about this and other security issues in script-like
617      programs.)""
618
619    The &KEY arguments have the following meanings:
620 "#-win32"
621    :ENVIRONMENT
622       a list of STRINGs describing the new Unix environment
623       (as in \"man environ\"). The default is to copy the environment of
624       the current process.
625    :ENV
626       an alternative lossy representation of the new Unix environment,
627       for compatibility with CMU CL""
628    :SEARCH
629       Look for PROGRAM in each of the directories in the child's $PATH
630       environment variable.  Otherwise an absolute pathname is required.
631    :WAIT
632       If non-NIL (default), wait until the created process finishes.  If
633       NIL, continue running Lisp until the program finishes."#-win32"
634    :PTY
635       Either T, NIL, or a stream.  Unless NIL, the subprocess is established
636       under a PTY.  If :pty is a stream, all output to this pty is sent to
637       this stream, otherwise the PROCESS-PTY slot is filled in with a stream
638       connected to pty that can read output and write input.""
639    :INPUT
640       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
641       input for the current process is inherited.  If NIL, "
642       #-win32"/dev/null"#+win32"nul""
643       is used.  If a pathname, the file so specified is used.  If a stream,
644       all the input is read from that stream and sent to the subprocess.  If
645       :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
646       its output to the process. Defaults to NIL.
647    :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
648       can be one of:
649          :ERROR to generate an error
650          :CREATE to create an empty file
651          NIL (the default) to return NIL from RUN-PROGRAM
652    :OUTPUT
653       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
654       output for the current process is inherited.  If NIL, "
655       #-win32"/dev/null"#+win32"nul""
656       is used.  If a pathname, the file so specified is used.  If a stream,
657       all the output from the process is written to this stream. If
658       :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
659       be read to get the output. Defaults to NIL.
660    :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
661       can be one of:
662          :ERROR (the default) to generate an error
663          :SUPERSEDE to supersede the file with output from the program
664          :APPEND to append output from the program to the file
665          NIL to return NIL from RUN-PROGRAM, without doing anything
666    :ERROR and :IF-ERROR-EXISTS
667       Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
668       specified as :OUTPUT in which case all error output is routed to the
669       same place as normal output.
670    :STATUS-HOOK
671       This is a function the system calls whenever the status of the
672       process changes.  The function takes the process as an argument.")
673   #-win32
674   (when (and env-p environment-p)
675     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
676   ;; Make sure that the interrupt handler is installed.
677   #-win32
678   (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
679   ;; Prepend the program to the argument list.
680   (push (namestring program) args)
681   (labels (;; It's friendly to allow the caller to pass any string
682            ;; designator, but internally we'd like SIMPLE-STRINGs.
683            ;;
684            ;; Huh?  We let users pass in symbols and characters for
685            ;; the arguments, but call NAMESTRING on the program
686            ;; name... -- RMK
687            (simplify-args (args)
688              (loop for arg in args
689                    as escaped-arg = (escape-arg arg)
690                    collect (coerce escaped-arg 'simple-string)))
691            (escape-arg (arg)
692              #-win32 arg
693              ;; Apparently any spaces or double quotes in the arguments
694              ;; need to be escaped on win32.
695              #+win32 (if (position-if
696                           (lambda (c) (find c '(#\" #\Space))) arg)
697                          (write-to-string arg)
698                          arg)))
699     (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
700           ;; communicate cleanup info.
701           *close-on-error*
702           *close-in-parent*
703           ;; Some other binding used only on non-Win32.  FIXME:
704           ;; nothing seems to set this.
705           #-win32 *handlers-installed*
706           ;; Establish PROC at this level so that we can return it.
707           proc
708           (simple-args (simplify-args args))
709           (progname (native-namestring program))
710           ;; Gag.
711           (cookie (list 0)))
712       (unwind-protect
713            ;; Note: despite the WITH-* names, these macros don't
714            ;; expand into UNWIND-PROTECT forms.  They're just
715            ;; syntactic sugar to make the rest of the routine slightly
716            ;; easier to read.
717            (macrolet ((with-fd-and-stream-for (((fd stream) which &rest args)
718                                                &body body)
719                         `(multiple-value-bind (,fd ,stream)
720                              ,(ecase which
721                                 ((:input :output)
722                                  `(get-descriptor-for ,@args))
723                                 (:error
724                                  `(if (eq ,(first args) :output)
725                                       ;; kludge: we expand into
726                                       ;; hard-coded symbols here.
727                                       (values stdout output-stream)
728                                       (get-descriptor-for ,@args))))
729                            ,@body))
730                       (with-open-pty (((pty-name pty-stream) (pty cookie)) &body body)
731                         #+win32 `(declare (ignore ,pty ,cookie))
732                         #+win32 `(let (,pty-name ,pty-stream) ,@body)
733                         #-win32 `(multiple-value-bind (,pty-name ,pty-stream)
734                                      (open-pty ,pty ,cookie)
735                                    ,@body))
736                       (with-args-vec ((vec args) &body body)
737                         `(with-c-strvec (,vec ,args)
738                            ,@body))
739                       (with-environment-vec ((vec env) &body body)
740                         #+win32 `(let (,vec) ,@body)
741                         #-win32 `(with-c-strvec (,vec ,env) ,@body)))
742              (with-fd-and-stream-for ((stdin input-stream) :input
743                                       input cookie
744                                       :direction :input
745                                       :if-does-not-exist if-input-does-not-exist
746                                       :external-format :default
747                                       :wait wait)
748                (with-fd-and-stream-for ((stdout output-stream) :output
749                                         output cookie
750                                         :direction :output
751                                         :if-exists if-output-exists
752                                         :external-format :default)
753                  (with-fd-and-stream-for ((stderr error-stream)  :error
754                                           error cookie
755                                           :direction :output
756                                           :if-exists if-error-exists
757                                           :external-format :default)
758                    (with-open-pty ((pty-name pty-stream) (pty cookie))
759                      ;; Make sure we are not notified about the child
760                      ;; death before we have installed the PROCESS
761                      ;; structure in *ACTIVE-PROCESSES*.
762                      (with-active-processes-lock ()
763                        (with-args-vec (args-vec simple-args)
764                          (with-environment-vec (environment-vec environment)
765                            (let ((child
766                                   (without-gcing
767                                     (spawn progname args-vec
768                                            stdin stdout stderr
769                                            (if search 1 0)
770                                            environment-vec pty-name
771                                            (if wait 1 0)))))
772                              (when (= child -1)
773                                (error "couldn't fork child process: ~A"
774                                       (strerror)))
775                              (setf proc (apply
776                                          #'make-process
777                                          :pid child
778                                          :input input-stream
779                                          :output output-stream
780                                          :error error-stream
781                                          :status-hook status-hook
782                                          :cookie cookie
783                                          #-win32 (list :pty pty-stream
784                                                        :%status :running)
785                                          #+win32 (if wait
786                                                      (list :%status :exited
787                                                            :exit-code child)
788                                                      (list :%status :running))))
789                              (push proc *active-processes*))))))))))
790         (dolist (fd *close-in-parent*)
791           (sb-unix:unix-close fd))
792         (unless proc
793           (dolist (fd *close-on-error*)
794             (sb-unix:unix-close fd))
795           ;; FIXME: nothing seems to set this.
796           #-win32
797           (dolist (handler *handlers-installed*)
798             (sb-sys:remove-fd-handler handler))))
799       #-win32
800       (when (and wait proc)
801         (process-wait proc))
802       proc)))
803
804 ;;; Install a handler for any input that shows up on the file
805 ;;; descriptor. The handler reads the data and writes it to the
806 ;;; stream.
807 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
808   (incf (car cookie))
809   (let* (handler
810          (buf (make-array 256 :element-type '(unsigned-byte 8)))
811          (read-end 0))
812     (setf handler
813           (sb-sys:add-fd-handler
814            descriptor
815            :input
816            (lambda (fd)
817              (declare (ignore fd))
818              (loop
819                 (unless handler
820                   (return))
821                 (multiple-value-bind
822                       (result readable/errno)
823                     (sb-unix:unix-select (1+ descriptor)
824                                          (ash 1 descriptor)
825                                          0 0 0)
826                   (cond ((null result)
827                          (if (eql sb-unix:eintr readable/errno)
828                              (return)
829                              (error "~@<Couldn't select on sub-process: ~
830                                         ~2I~_~A~:>"
831                                     (strerror readable/errno))))
832                         ((zerop result)
833                          (return))))
834                 (multiple-value-bind (count errno)
835                     (with-pinned-objects (buf)
836                       (sb-unix:unix-read descriptor
837                                          (sap+ (vector-sap buf) read-end)
838                                          (- (length buf) read-end)))
839                   (cond
840                     ((and #-win32 (or (and (null count)
841                                            (eql errno sb-unix:eio))
842                                       (eql count 0))
843                           #+win32 (<= count 0))
844                      (sb-sys:remove-fd-handler handler)
845                      (setf handler nil)
846                      (decf (car cookie))
847                      (sb-unix:unix-close descriptor)
848                      (unless (zerop read-end)
849                        ;; Should this be an END-OF-FILE?
850                        (error "~@<non-empty buffer when EOF reached ~
851                                while reading from child: ~S~:>" buf))
852                      (return))
853                     ((null count)
854                      (sb-sys:remove-fd-handler handler)
855                      (setf handler nil)
856                      (decf (car cookie))
857                      (error
858                       "~@<couldn't read input from sub-process: ~
859                                      ~2I~_~A~:>"
860                       (strerror errno)))
861                     (t
862                      (incf read-end count)
863                      (let* ((decode-end read-end)
864                             (string (handler-case
865                                         (octets-to-string
866                                          buf :end read-end
867                                          :external-format external-format)
868                                       (end-of-input-in-character (e)
869                                         (setf decode-end
870                                               (octet-decoding-error-start e))
871                                         (octets-to-string
872                                          buf :end decode-end
873                                          :external-format external-format)))))
874                        (unless (zerop (length string))
875                          (write-string string stream)
876                          (when (/= decode-end (length buf))
877                            (replace buf buf :start2 decode-end :end2 read-end))
878                          (decf read-end decode-end))))))))))))
879
880 ;;; FIXME: something very like this is done in SB-POSIX to treat
881 ;;; streams as file descriptor designators; maybe we can combine these
882 ;;; two?  Additionally, as we have a couple of user-defined streams
883 ;;; libraries, maybe we should have a generic function for doing this,
884 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
885 ;;; maybe also with SB-POSIX)?
886 (defun get-stream-fd-and-external-format (stream direction)
887   (typecase stream
888     (sb-sys:fd-stream
889      (values (sb-sys:fd-stream-fd stream) nil (stream-external-format stream)))
890     (synonym-stream
891      (get-stream-fd-and-external-format
892       (symbol-value (synonym-stream-symbol stream)) direction))
893     (two-way-stream
894      (ecase direction
895        (:input
896         (get-stream-fd-and-external-format
897          (two-way-stream-input-stream stream) direction))
898        (:output
899         (get-stream-fd-and-external-format
900          (two-way-stream-output-stream stream) direction))))))
901
902 \f
903 ;;; Find a file descriptor to use for object given the direction.
904 ;;; Returns the descriptor. If object is :STREAM, returns the created
905 ;;; stream as the second value.
906 (defun get-descriptor-for (object
907                            cookie
908                            &rest keys
909                            &key direction (external-format :default) wait
910                            &allow-other-keys)
911   (declare (ignore wait)) ;This is explained below.
912   ;; Our use of a temporary file dates back to very old CMUCLs, and
913   ;; was probably only ever intended for use with STRING-STREAMs,
914   ;; which are ordinarily smallish.  However, as we've got
915   ;; user-defined stream classes, we can end up trying to copy
916   ;; arbitrarily much data into the temp file, and so are liable to
917   ;; run afoul of disk quotas or to choke on small /tmp file systems.
918   (flet ((make-temp-fd ()
919            (multiple-value-bind (fd name/errno)
920                (sb-unix:sb-mkstemp "/tmp/.run-program-XXXXXX" #o0600)
921              (unless fd
922                (error "could not open a temporary file: ~A"
923                       (strerror name/errno)))
924              (unless (sb-unix:unix-unlink name/errno)
925                (sb-unix:unix-close fd)
926                (error "failed to unlink ~A" name/errno))
927              fd)))
928     (cond ((eq object t)
929            ;; No new descriptor is needed.
930            (values -1 nil))
931           ((eq object nil)
932            ;; Use /dev/null.
933            (multiple-value-bind
934                  (fd errno)
935                (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
936                                   #+win32 #.(coerce "nul" 'base-string)
937                                   (case direction
938                                     (:input sb-unix:o_rdonly)
939                                     (:output sb-unix:o_wronly)
940                                     (t sb-unix:o_rdwr))
941                                   #o666)
942              (unless fd
943                (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
944                       #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
945                       (strerror errno)))
946              (push fd *close-in-parent*)
947              (values fd nil)))
948           ((eq object :stream)
949            (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
950              (unless read-fd
951                (error "couldn't create pipe: ~A" (strerror write-fd)))
952              (case direction
953                (:input
954                 (push read-fd *close-in-parent*)
955                 (push write-fd *close-on-error*)
956                 (let ((stream (sb-sys:make-fd-stream write-fd :output t
957                                                      :element-type :default
958                                                      :external-format
959                                                      external-format)))
960                   (values read-fd stream)))
961                (:output
962                 (push read-fd *close-on-error*)
963                 (push write-fd *close-in-parent*)
964                 (let ((stream (sb-sys:make-fd-stream read-fd :input t
965                                                      :element-type :default
966                                                      :external-format
967                                                      external-format)))
968                   (values write-fd stream)))
969                (t
970                 (sb-unix:unix-close read-fd)
971                 (sb-unix:unix-close write-fd)
972                 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
973                        direction)))))
974           ((or (pathnamep object) (stringp object))
975            ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
976            ;; than munge the &rest list for OPEN, just disable keyword
977            ;; validation there.
978            (with-open-stream (file (apply #'open object :allow-other-keys t
979                                           keys))
980              (multiple-value-bind
981                    (fd errno)
982                  (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
983                (cond (fd
984                       (push fd *close-in-parent*)
985                       (values fd nil))
986                      (t
987                       (error "couldn't duplicate file descriptor: ~A"
988                              (strerror errno)))))))
989           ((streamp object)
990            (ecase direction
991              (:input
992               (block nil
993                 ;; If we can get an fd for the stream, let the child
994                 ;; process use the fd for its descriptor.  Otherwise,
995                 ;; we copy data from the stream into a temp file, and
996                 ;; give the temp file's descriptor to the
997                 ;; child.
998                 (multiple-value-bind (fd stream format)
999                     (get-stream-fd-and-external-format object :input)
1000                   (declare (ignore format))
1001                   (when fd
1002                     (return (values fd stream))))
1003                 ;; FIXME: if we can't get the file descriptor, since
1004                 ;; the stream might be interactive or otherwise
1005                 ;; block-y, we can't know whether we can copy the
1006                 ;; stream's data to a temp file, so if RUN-PROGRAM was
1007                 ;; called with :WAIT NIL, we should probably error.
1008                 ;; However, STRING-STREAMs aren't fd-streams, but
1009                 ;; they're not prone to blocking; any user-defined
1010                 ;; streams that "read" from some in-memory data will
1011                 ;; probably be similar to STRING-STREAMs.  So maybe we
1012                 ;; should add a STREAM-INTERACTIVE-P generic function
1013                 ;; for problems like this?  Anyway, the machinery is
1014                 ;; here, if you feel like filling in the details.
1015                 #|
1016                 (when (and (null wait) #<some undetermined criterion>)
1017                   (error "~@<don't know how to get an fd for ~A, and so ~
1018                              can't ensure that copying its data to the ~
1019                              child process won't hang~:>" object))
1020                 |#
1021                 (let ((fd (make-temp-fd))
1022                       (newline (string #\Newline)))
1023                   (loop
1024                      (multiple-value-bind
1025                            (line no-cr)
1026                          (read-line object nil nil)
1027                        (unless line
1028                          (return))
1029                        (let ((vector (string-to-octets line)))
1030                          (sb-unix:unix-write
1031                           fd vector 0 (length vector)))
1032                        (if no-cr
1033                            (return)
1034                            (sb-unix:unix-write fd newline 0 1))))
1035                   (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1036                   (push fd *close-in-parent*)
1037                   (return (values fd nil)))))
1038              (:output
1039               (block nil
1040                 ;; Similar to the :input trick above, except we
1041                 ;; arrange to copy data from the stream.  This is
1042                 ;; slightly saner than the input case, since we don't
1043                 ;; buffer to a file, but I think we may still lose if
1044                 ;; there's unflushed data in the stream buffer and we
1045                 ;; give the file descriptor to the child.
1046                 (multiple-value-bind (fd stream format)
1047                     (get-stream-fd-and-external-format object :output)
1048                   (declare (ignore format))
1049                   (when fd
1050                     (return (values fd stream))))
1051                 (multiple-value-bind (read-fd write-fd)
1052                     (sb-unix:unix-pipe)
1053                   (unless read-fd
1054                     (error "couldn't create pipe: ~S" (strerror write-fd)))
1055                   (copy-descriptor-to-stream read-fd object cookie
1056                                              external-format)
1057                   (push read-fd *close-on-error*)
1058                   (push write-fd *close-in-parent*)
1059                   (return (values write-fd nil)))))))
1060           (t
1061            (error "invalid option to RUN-PROGRAM: ~S" object)))))