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