0.9.15.31: RUN-PROGRAM win32 patch
[sbcl.git] / src / code / run-program.lisp
1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs\r
2 ;;;; from inside SBCL\r
3 \r
4 ;;;; This software is part of the SBCL system. See the README file for\r
5 ;;;; more information.\r
6 ;;;;\r
7 ;;;; This software is derived from the CMU CL system, which was\r
8 ;;;; written at Carnegie Mellon University and released into the\r
9 ;;;; public domain. The software is in the public domain and is\r
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS\r
11 ;;;; files for more information.\r
12 \r
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)\r
14 \f\r
15 ;;;; hacking the Unix environment\r
16 ;;;;\r
17 ;;;; In the original CMU CL code that LOAD-FOREIGN is derived from, the\r
18 ;;;; Unix environment (as in "man environ") was represented as an\r
19 ;;;; alist from keywords to strings, so that e.g. the Unix environment\r
20 ;;;;   "SHELL=/bin/bash" "HOME=/root" "PAGER=less"\r
21 ;;;; was represented as\r
22 ;;;;   ((:SHELL . "/bin/bash") (:HOME . "/root") (:PAGER "less"))\r
23 ;;;; This had a few problems in principle: the mapping into\r
24 ;;;; keyword symbols smashed the case of environment\r
25 ;;;; variables, and the whole mapping depended on the presence of\r
26 ;;;; #\= characters in the environment strings. In practice these\r
27 ;;;; problems weren't hugely important, since conventionally environment\r
28 ;;;; variables are uppercase strings followed by #\= followed by\r
29 ;;;; arbitrary data. However, since it's so manifestly not The Right\r
30 ;;;; Thing to make code which breaks unnecessarily on input which\r
31 ;;;; doesn't follow what is, after all, only a tradition, we've switched\r
32 ;;;; formats in SBCL, so that the fundamental environment list\r
33 ;;;; is just a list of strings, with a one-to-one-correspondence\r
34 ;;;; to the C-level representation. I.e., in the example above,\r
35 ;;;; the SBCL representation is\r
36 ;;;;   '("SHELL=/bin/bash" "HOME=/root" "PAGER=less")\r
37 ;;;; CMU CL's implementation is currently supported to help with porting.\r
38 ;;;;\r
39 ;;;; It's not obvious that this code belongs here (instead of e.g. in\r
40 ;;;; unix.lisp), since it has only a weak logical connection with\r
41 ;;;; RUN-PROGRAM. However, physically it's convenient to put it here.\r
42 ;;;; It's not needed at cold init, so we *can* put it in this\r
43 ;;;; warm-loaded file. And by putting it in this warm-loaded file, we\r
44 ;;;; make it easy for it to get to the C-level 'environ' variable.\r
45 ;;;; which (at least in sbcl-0.6.10 on Red Hat Linux 6.2) is not\r
46 ;;;; visible at GENESIS time.\r
47 \r
48 #-win32\r
49 (progn\r
50   (define-alien-routine wrapped-environ (* c-string))\r
51   (defun posix-environ ()\r
52     "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."\r
53     (c-strings->string-list (wrapped-environ))))\r
54 \r
55 ;#+win32 (sb-alien:define-alien-routine msvcrt-environ (* c-string))\r
56 \r
57 ;;; Convert as best we can from an SBCL representation of a Unix\r
58 ;;; environment to a CMU CL representation.\r
59 ;;;\r
60 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))\r
61 ;;; WARNING:\r
62 ;;;   smashing case of "Bletch=fub" in conversion to CMU-CL-style\r
63 ;;;     environment alist\r
64 ;;; WARNING:\r
65 ;;;   no #\= in "Noggin", eliding it in CMU-CL-style environment alist\r
66 ;;; ((:BLETCH . "fub") (:YES . "No!"))\r
67 (defun unix-environment-cmucl-from-sbcl (sbcl)\r
68   (mapcan\r
69    (lambda (string)\r
70      (declare (type simple-base-string string))\r
71      (let ((=-pos (position #\= string :test #'equal)))\r
72        (if =-pos\r
73            (list\r
74             (let* ((key-as-string (subseq string 0 =-pos))\r
75                    (key-as-upcase-string (string-upcase key-as-string))\r
76                    (key (keywordicate key-as-upcase-string))\r
77                    (val (subseq string (1+ =-pos))))\r
78               (unless (string= key-as-string key-as-upcase-string)\r
79                 (warn "smashing case of ~S in conversion to CMU-CL-style ~\r
80                       environment alist"\r
81                       string))\r
82               (cons key val)))\r
83            (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"\r
84                  string))))\r
85    sbcl))\r
86 \r
87 ;;; Convert from a CMU CL representation of a Unix environment to a\r
88 ;;; SBCL representation.\r
89 (defun unix-environment-sbcl-from-cmucl (cmucl)\r
90   (mapcar\r
91    (lambda (cons)\r
92      (destructuring-bind (key . val) cons\r
93        (declare (type keyword key) (type simple-base-string val))\r
94        (concatenate 'simple-base-string (symbol-name key) "=" val)))\r
95    cmucl))\r
96 \f\r
97 ;;;; Import wait3(2) from Unix.\r
98 \r
99 #-win32\r
100 (define-alien-routine ("wait3" c-wait3) sb-alien:int\r
101   (status sb-alien:int :out)\r
102   (options sb-alien:int)\r
103   (rusage sb-alien:int))\r
104 \r
105 #-win32\r
106 (defun wait3 (&optional do-not-hang check-for-stopped)\r
107   #+sb-doc\r
108   "Return any available status information on child process. "\r
109   (multiple-value-bind (pid status)\r
110       (c-wait3 (logior (if do-not-hang\r
111                            sb-unix:wnohang\r
112                            0)\r
113                        (if check-for-stopped\r
114                            sb-unix:wuntraced\r
115                            0))\r
116                0)\r
117     (cond ((or (minusp pid)\r
118                (zerop pid))\r
119            nil)\r
120           ((eql (ldb (byte 8 0) status)\r
121                 sb-unix:wstopped)\r
122            (values pid\r
123                    :stopped\r
124                    (ldb (byte 8 8) status)))\r
125           ((zerop (ldb (byte 7 0) status))\r
126            (values pid\r
127                    :exited\r
128                    (ldb (byte 8 8) status)))\r
129           (t\r
130            (let ((signal (ldb (byte 7 0) status)))\r
131              (values pid\r
132                      (if (position signal\r
133                                    #.(vector\r
134                                       sb-unix:sigstop\r
135                                       sb-unix:sigtstp\r
136                                       sb-unix:sigttin\r
137                                       sb-unix:sigttou))\r
138                          :stopped\r
139                          :signaled)\r
140                      signal\r
141                      (not (zerop (ldb (byte 1 7) status)))))))))\r
142 \f\r
143 ;;;; process control stuff\r
144 (defvar *active-processes* nil\r
145   #+sb-doc\r
146   "List of process structures for all active processes.")\r
147 \r
148 #-win32\r
149 (defvar *active-processes-lock*\r
150   (sb-thread:make-mutex :name "Lock for active processes."))\r
151 \r
152 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a\r
153 ;;; mutex is needed. More importantly the sigchld signal handler also\r
154 ;;; accesses it, that's why we need without-interrupts.\r
155 (defmacro with-active-processes-lock (() &body body)\r
156   #-win32\r
157   `(without-interrupts\r
158     (sb-thread:with-mutex (*active-processes-lock*)\r
159       ,@body))\r
160   #+win32\r
161   `(progn ,@body))\r
162 \r
163 (defstruct (process (:copier nil))\r
164   pid                 ; PID of child process\r
165   %status             ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED\r
166   exit-code           ; either exit code or signal\r
167   core-dumped         ; T if a core image was dumped\r
168   #-win32 pty                 ; stream to child's pty, or NIL\r
169   input               ; stream to child's input, or NIL\r
170   output              ; stream from child's output, or NIL\r
171   error               ; stream from child's error output, or NIL\r
172   status-hook         ; closure to call when PROC changes status\r
173   plist               ; a place for clients to stash things\r
174   cookie)             ; list of the number of pipes from the subproc\r
175 \r
176 (defmethod print-object ((process process) stream)\r
177   (print-unreadable-object (process stream :type t)\r
178     (let ((status (process-status process)))\r
179      (if (eq :exited status)\r
180          (format stream "~S ~S" status (process-exit-code process))\r
181          (format stream "~S ~S" (process-pid process) status)))\r
182     process))\r
183 \r
184 #+sb-doc\r
185 (setf (documentation 'process-p 'function)\r
186       "T if OBJECT is a PROCESS, NIL otherwise.")\r
187 \r
188 #+sb-doc\r
189 (setf (documentation 'process-pid 'function) "The pid of the child process.")\r
190 \r
191 #+win32\r
192 (define-alien-routine ("GetExitCodeProcess@8" get-exit-code-process)\r
193     int\r
194   (handle unsigned) (exit-code unsigned :out))\r
195 \r
196 (defun process-status (process)\r
197   #+sb-doc\r
198   "Return the current status of PROCESS.  The result is one of :RUNNING,\r
199    :STOPPED, :EXITED, or :SIGNALED."\r
200   (get-processes-status-changes)\r
201   (process-%status process))\r
202 \r
203 #+sb-doc\r
204 (setf (documentation 'process-exit-code 'function)\r
205       "The exit code or the signal of a stopped process.")\r
206 \r
207 #+sb-doc\r
208 (setf (documentation 'process-core-dumped 'function)\r
209       "T if a core image was dumped by the process.")\r
210 \r
211 #+sb-doc\r
212 (setf (documentation 'process-pty 'function)\r
213       "The pty stream of the process or NIL.")\r
214 \r
215 #+sb-doc\r
216 (setf (documentation 'process-input 'function)\r
217       "The input stream of the process or NIL.")\r
218 \r
219 #+sb-doc\r
220 (setf (documentation 'process-output 'function)\r
221       "The output stream of the process or NIL.")\r
222 \r
223 #+sb-doc\r
224 (setf (documentation 'process-error 'function)\r
225       "The error stream of the process or NIL.")\r
226 \r
227 #+sb-doc\r
228 (setf (documentation 'process-status-hook  'function)\r
229       "A function that is called when PROCESS changes its status.\r
230 The function is called with PROCESS as its only argument.")\r
231 \r
232 #+sb-doc\r
233 (setf (documentation 'process-plist  'function)\r
234       "A place for clients to stash things.")\r
235 \r
236 (defun process-wait (process &optional check-for-stopped)\r
237   #+sb-doc\r
238   "Wait for PROCESS to quit running for some reason. When\r
239 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns\r
240 PROCESS."\r
241   (loop\r
242       (case (process-status process)\r
243         (:running)\r
244         (:stopped\r
245          (when check-for-stopped\r
246            (return)))\r
247         (t\r
248          (when (zerop (car (process-cookie process)))\r
249            (return))))\r
250       (sb-sys:serve-all-events 1))\r
251   process)\r
252 \r
253 #-(or hpux win32)\r
254 ;;; Find the current foreground process group id.\r
255 (defun find-current-foreground-process (proc)\r
256   (with-alien ((result sb-alien:int))\r
257     (multiple-value-bind\r
258           (wonp error)\r
259         (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))\r
260                             sb-unix:TIOCGPGRP\r
261                             (alien-sap (sb-alien:addr result)))\r
262       (unless wonp\r
263         (error "TIOCPGRP ioctl failed: ~S" (strerror error)))\r
264       result))\r
265   (process-pid proc))\r
266 \r
267 #-win32\r
268 (defun process-kill (process signal &optional (whom :pid))\r
269   #+sb-doc\r
270   "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If\r
271    WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is\r
272    :PTY-PROCESS-GROUP deliver the signal to whichever process group is\r
273    currently in the foreground."\r
274   (let ((pid (ecase whom\r
275                ((:pid :process-group)\r
276                 (process-pid process))\r
277                (:pty-process-group\r
278                 #-hpux\r
279                 (find-current-foreground-process process)))))\r
280     (multiple-value-bind\r
281           (okay errno)\r
282         (case whom\r
283           #+hpux\r
284           (:pty-process-group\r
285            (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))\r
286                                sb-unix:TIOCSIGSEND\r
287                                (sb-sys:int-sap\r
288                                 signal)))\r
289           ((:process-group #-hpux :pty-process-group)\r
290            (sb-unix:unix-killpg pid signal))\r
291           (t\r
292            (sb-unix:unix-kill pid signal)))\r
293       (cond ((not okay)\r
294              (values nil errno))\r
295             ((and (eql pid (process-pid process))\r
296                   (= signal sb-unix:sigcont))\r
297              (setf (process-%status process) :running)\r
298              (setf (process-exit-code process) nil)\r
299              (when (process-status-hook process)\r
300                (funcall (process-status-hook process) process))\r
301              t)\r
302             (t\r
303              t)))))\r
304 \r
305 (defun process-alive-p (process)\r
306   #+sb-doc\r
307   "Return T if PROCESS is still alive, NIL otherwise."\r
308   (let ((status (process-status process)))\r
309     (if (or (eq status :running)\r
310             (eq status :stopped))\r
311         t\r
312         nil)))\r
313 \r
314 (defun process-close (process)\r
315   #+sb-doc\r
316   "Close all streams connected to PROCESS and stop maintaining the\r
317 status slot."\r
318   (macrolet ((frob (stream abort)\r
319                `(when ,stream (close ,stream :abort ,abort))))\r
320     #-win32\r
321     (frob (process-pty process) t)   ; Don't FLUSH-OUTPUT to dead process,\r
322     (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.\r
323     (frob (process-output process) nil)\r
324     (frob (process-error process) nil))\r
325   ;; FIXME: Given that the status-slot is no longer updated,\r
326   ;; maybe it should be set to :CLOSED, or similar?\r
327   (with-active-processes-lock ()\r
328    (setf *active-processes* (delete process *active-processes*)))\r
329   process)\r
330 \r
331 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes\r
332 #-win32\r
333 (defun sigchld-handler (ignore1 ignore2 ignore3)\r
334   (declare (ignore ignore1 ignore2 ignore3))\r
335   (get-processes-status-changes))\r
336 \r
337 (defun get-processes-status-changes ()\r
338   #-win32\r
339   (loop\r
340    (multiple-value-bind (pid what code core)\r
341        (wait3 t t)\r
342      (unless pid\r
343        (return))\r
344      (let ((proc (with-active-processes-lock ()\r
345                    (find pid *active-processes* :key #'process-pid))))\r
346        (when proc\r
347          (setf (process-%status proc) what)\r
348          (setf (process-exit-code proc) code)\r
349          (setf (process-core-dumped proc) core)\r
350          (when (process-status-hook proc)\r
351            (funcall (process-status-hook proc) proc))\r
352          (when (position what #(:exited :signaled))\r
353            (with-active-processes-lock ()\r
354              (setf *active-processes*\r
355                    (delete proc *active-processes*))))))))\r
356   #+win32\r
357   (let (exited)\r
358     (with-active-processes-lock ()\r
359       (setf *active-processes*\r
360             (delete-if (lambda (proc)\r
361                          (multiple-value-bind (ok code)\r
362                              (get-exit-code-process (process-pid proc))\r
363                            (when (and (plusp ok) (/= code 259))\r
364                              (setf (process-%status proc) :exited\r
365                                    (process-exit-code proc) code)\r
366                              (when (process-status-hook proc)\r
367                                (push proc exited))\r
368                              t)))\r
369                        *active-processes*)))\r
370     ;; Can't call the hooks before all the processes have been deal\r
371     ;; with, as calling a hook may cause re-entry to\r
372     ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,\r
373     ;; but in the Windows implementation is would be deeply bad.\r
374     (dolist (proc exited)\r
375       (let ((hook (process-status-hook proc)))\r
376         (when hook\r
377           (funcall hook proc))))))\r
378 \f\r
379 ;;;; RUN-PROGRAM and close friends\r
380 \r
381 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error\r
382 (defvar *close-on-error* nil)\r
383 \r
384 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent\r
385 (defvar *close-in-parent* nil)\r
386 \r
387 ;;; list of handlers installed by RUN-PROGRAM\r
388 #-win32\r
389 (defvar *handlers-installed* nil)\r
390 \r
391 ;;; Find an unused pty. Return three values: the file descriptor for\r
392 ;;; the master side of the pty, the file descriptor for the slave side\r
393 ;;; of the pty, and the name of the tty device for the slave side.\r
394 #-win32\r
395 (defun find-a-pty ()\r
396   (dolist (char '(#\p #\q))\r
397     (dotimes (digit 16)\r
398       (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit) 'base-string))\r
399              (master-fd (sb-unix:unix-open master-name\r
400                                            sb-unix:o_rdwr\r
401                                            #o666)))\r
402         (when master-fd\r
403           (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit) 'base-string))\r
404                  (slave-fd (sb-unix:unix-open slave-name\r
405                                               sb-unix:o_rdwr\r
406                                               #o666)))\r
407             (when slave-fd\r
408               (return-from find-a-pty\r
409                 (values master-fd\r
410                         slave-fd\r
411                         slave-name)))\r
412             (sb-unix:unix-close master-fd))))))\r
413   (error "could not find a pty"))\r
414 \r
415 #-win32\r
416 (defun open-pty (pty cookie)\r
417   (when pty\r
418     (multiple-value-bind\r
419           (master slave name)\r
420         (find-a-pty)\r
421       (push master *close-on-error*)\r
422       (push slave *close-in-parent*)\r
423       (when (streamp pty)\r
424         (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)\r
425           (unless new-fd\r
426             (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))\r
427           (push new-fd *close-on-error*)\r
428           (copy-descriptor-to-stream new-fd pty cookie)))\r
429       (values name\r
430               (sb-sys:make-fd-stream master :input t :output t\r
431                                      :element-type :default\r
432                                      :dual-channel-p t)))))\r
433 \r
434 (defmacro round-bytes-to-words (n)\r
435   `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))\r
436 \r
437 (defun string-list-to-c-strvec (string-list)\r
438   ;; Make a pass over STRING-LIST to calculate the amount of memory\r
439   ;; needed to hold the strvec.\r
440   (let ((string-bytes 0)\r
441         ;; We need an extra for the null, and an extra 'cause exect\r
442         ;; clobbers argv[-1].\r
443         (vec-bytes (* #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)\r
444                       (+ (length string-list) 2))))\r
445     (declare (fixnum string-bytes vec-bytes))\r
446     (dolist (s string-list)\r
447       (enforce-type s simple-string)\r
448       (incf string-bytes (round-bytes-to-words (1+ (length s)))))\r
449     ;; Now allocate the memory and fill it in.\r
450     (let* ((total-bytes (+ string-bytes vec-bytes))\r
451            (vec-sap (sb-sys:allocate-system-memory total-bytes))\r
452            (string-sap (sap+ vec-sap vec-bytes))\r
453            (i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)))\r
454       (declare (type (and unsigned-byte fixnum) total-bytes i)\r
455                (type sb-sys:system-area-pointer vec-sap string-sap))\r
456       (dolist (s string-list)\r
457         (declare (simple-string s))\r
458         (let ((n (length s)))\r
459           ;; Blast the string into place.\r
460           (sb-kernel:copy-ub8-to-system-area (the simple-base-string\r
461                                                ;; FIXME\r
462                                                (coerce s 'simple-base-string))\r
463                                              0\r
464                                              string-sap 0\r
465                                              (1+ n))\r
466           ;; Blast the pointer to the string into place.\r
467           (setf (sap-ref-sap vec-sap i) string-sap)\r
468           (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))\r
469           (incf i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits))))\r
470       ;; Blast in the last null pointer.\r
471       (setf (sap-ref-sap vec-sap i) (int-sap 0))\r
472       (values vec-sap (sap+ vec-sap #.(/ sb-vm::n-machine-word-bits\r
473                                          sb-vm::n-byte-bits))\r
474               total-bytes))))\r
475 \r
476 (defmacro with-c-strvec ((var str-list) &body body)\r
477   (with-unique-names (sap size)\r
478     `(multiple-value-bind\r
479       (,sap ,var ,size)\r
480       (string-list-to-c-strvec ,str-list)\r
481       (unwind-protect\r
482            (progn\r
483              ,@body)\r
484         (sb-sys:deallocate-system-memory ,sap ,size)))))\r
485 \r
486 #-win32\r
487 (sb-alien:define-alien-routine spawn sb-alien:int\r
488   (program sb-alien:c-string)\r
489   (argv (* sb-alien:c-string))\r
490   (envp (* sb-alien:c-string))\r
491   (pty-name sb-alien:c-string)\r
492   (stdin sb-alien:int)\r
493   (stdout sb-alien:int)\r
494   (stderr sb-alien:int))\r
495 \r
496 #+win32\r
497 (sb-alien:define-alien-routine spawn sb-win32::handle\r
498   (program sb-alien:c-string)\r
499   (argv (* sb-alien:c-string))\r
500   (stdin sb-alien:int)\r
501   (stdout sb-alien:int)\r
502   (stderr sb-alien:int)\r
503   (wait sb-alien:int))\r
504 \r
505 ;;; Is UNIX-FILENAME the name of a file that we can execute?\r
506 (defun unix-filename-is-executable-p (unix-filename)\r
507   (let ((filename (coerce unix-filename 'base-string)))\r
508     (values (and (eq (sb-unix:unix-file-kind filename) :file)\r
509                  #-win32\r
510                  (sb-unix:unix-access filename sb-unix:x_ok)))))\r
511 \r
512 (defun find-executable-in-search-path (pathname &optional\r
513                                        (search-path (posix-getenv "PATH")))\r
514   #+sb-doc\r
515   "Find the first executable file matching PATHNAME in any of the\r
516 colon-separated list of pathnames SEARCH-PATH"\r
517   (let ((program #-win32 pathname\r
518                  #+win32 (merge-pathnames pathname (make-pathname :type "exe"))))\r
519    (loop for end =  (position #-win32 #\: #+win32 #\; search-path\r
520                               :start (if end (1+ end) 0))\r
521          and start = 0 then (and end (1+ end))\r
522          while start\r
523          ;; <Krystof> the truename of a file naming a directory is the\r
524          ;; directory, at least until pfdietz comes along and says why\r
525          ;; that's noncompliant  -- CSR, c. 2003-08-10\r
526          for truename = (probe-file (subseq search-path start end))\r
527          for fullpath = (when truename\r
528                           (unix-namestring (merge-pathnames program truename)))\r
529          when (and fullpath (unix-filename-is-executable-p fullpath))\r
530          return fullpath)))\r
531 \r
532 ;;; FIXME: There shouldn't be two semiredundant versions of the\r
533 ;;; documentation. Since this is a public extension function, the\r
534 ;;; documentation should be in the doc string. So all information from\r
535 ;;; this comment should be merged into the doc string, and then this\r
536 ;;; comment can go away.\r
537 ;;;\r
538 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.\r
539 ;;; Strange stuff happens to keep the Unix state of the world\r
540 ;;; coherent.\r
541 ;;;\r
542 ;;; The child process needs to get its input from somewhere, and send\r
543 ;;; its output (both standard and error) to somewhere. We have to do\r
544 ;;; different things depending on where these somewheres really are.\r
545 ;;;\r
546 ;;; For input, there are five options:\r
547 ;;;  -- T: Just leave fd 0 alone. Pretty simple.\r
548 ;;;  -- "file": Read from the file. We need to open the file and\r
549 ;;;     pull the descriptor out of the stream. The parent should close\r
550 ;;;     this stream after the child is up and running to free any\r
551 ;;;     storage used in the parent.\r
552 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.\r
553 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use\r
554 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the\r
555 ;;;     writeable descriptor, and pass the readable descriptor to\r
556 ;;;     the child. The parent must close the readable descriptor for\r
557 ;;;     EOF to be passed up correctly.\r
558 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out\r
559 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy\r
560 ;;;     everything across.\r
561 ;;;\r
562 ;;; For output, there are five options:\r
563 ;;;  -- T: Leave descriptor 1 alone.\r
564 ;;;  -- "file": dump output to the file.\r
565 ;;;  -- NIL: dump output to /dev/null.\r
566 ;;;  -- :STREAM: return a stream that can be read from.\r
567 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.\r
568 ;;;     Otherwise, copy stuff from output to stream.\r
569 ;;;\r
570 ;;; For error, there are all the same options as output plus:\r
571 ;;;  -- :OUTPUT: redirect to the same place as output.\r
572 ;;;\r
573 ;;; RUN-PROGRAM returns a PROCESS structure for the process if\r
574 ;;; the fork worked, and NIL if it did not.\r
575 \r
576 #-win32\r
577 (defun run-program (program args\r
578                     &key\r
579                     (env nil env-p)\r
580                     (environment (if env-p\r
581                                      (unix-environment-sbcl-from-cmucl env)\r
582                                      (posix-environ))\r
583                                  environment-p)\r
584                     (wait t)\r
585                     search\r
586                     pty\r
587                     input\r
588                     if-input-does-not-exist\r
589                     output\r
590                     (if-output-exists :error)\r
591                     (error :output)\r
592                     (if-error-exists :error)\r
593                     status-hook)\r
594   #+sb-doc\r
595   "RUN-PROGRAM creates a new Unix process running the Unix program\r
596 found in the file specified by the PROGRAM argument. ARGS are the\r
597 standard arguments that can be passed to a Unix program. For no\r
598 arguments, use NIL (which means that just the name of the program is\r
599 passed as arg 0).\r
600 \r
601 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp\r
602 Users Manual for details about the PROCESS structure.\r
603 \r
604    Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):\r
605 \r
606    - The SBCL implementation of RUN-PROGRAM, like Perl and many other\r
607      programs, but unlike the original CMU CL implementation, copies\r
608      the Unix environment by default.\r
609 \r
610    - Running Unix programs from a setuid process, or in any other\r
611      situation where the Unix environment is under the control of someone\r
612      else, is a mother lode of security problems. If you are contemplating\r
613      doing this, read about it first. (The Perl community has a lot of good\r
614      documentation about this and other security issues in script-like\r
615      programs.)\r
616 \r
617    The &KEY arguments have the following meanings:\r
618 \r
619    :ENVIRONMENT\r
620       a list of SIMPLE-BASE-STRINGs describing the new Unix environment\r
621       (as in \"man environ\"). The default is to copy the environment of\r
622       the current process.\r
623    :ENV\r
624       an alternative lossy representation of the new Unix environment,\r
625       for compatibility with CMU CL\r
626    :SEARCH\r
627       Look for PROGRAM in each of the directories along the $PATH\r
628       environment variable.  Otherwise an absolute pathname is required.\r
629       (See also FIND-EXECUTABLE-IN-SEARCH-PATH)\r
630    :WAIT\r
631       If non-NIL (default), wait until the created process finishes.  If\r
632       NIL, continue running Lisp until the program finishes.\r
633    :PTY\r
634       Either T, NIL, or a stream.  Unless NIL, the subprocess is established\r
635       under a PTY.  If :pty is a stream, all output to this pty is sent to\r
636       this stream, otherwise the PROCESS-PTY slot is filled in with a stream\r
637       connected to pty that can read output and write input.\r
638    :INPUT\r
639       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard\r
640       input for the current process is inherited.  If NIL, /dev/null\r
641       is used.  If a pathname, the file so specified is used.  If a stream,\r
642       all the input is read from that stream and send to the subprocess.  If\r
643       :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends\r
644       its output to the process. Defaults to NIL.\r
645    :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)\r
646       can be one of:\r
647          :ERROR to generate an error\r
648          :CREATE to create an empty file\r
649          NIL (the default) to return NIL from RUN-PROGRAM\r
650    :OUTPUT\r
651       Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard\r
652       output for the current process is inherited.  If NIL, /dev/null\r
653       is used.  If a pathname, the file so specified is used.  If a stream,\r
654       all the output from the process is written to this stream. If\r
655       :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can\r
656       be read to get the output. Defaults to NIL.\r
657    :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)\r
658       can be one of:\r
659          :ERROR (the default) to generate an error\r
660          :SUPERSEDE to supersede the file with output from the program\r
661          :APPEND to append output from the program to the file\r
662          NIL to return NIL from RUN-PROGRAM, without doing anything\r
663    :ERROR and :IF-ERROR-EXISTS\r
664       Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be\r
665       specified as :OUTPUT in which case all error output is routed to the\r
666       same place as normal output.\r
667    :STATUS-HOOK\r
668       This is a function the system calls whenever the status of the\r
669       process changes.  The function takes the process as an argument."\r
670   (when (and env-p environment-p)\r
671     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))\r
672   ;; Make sure that the interrupt handler is installed.\r
673   (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)\r
674   ;; Prepend the program to the argument list.\r
675   (push (namestring program) args)\r
676   (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to\r
677         ;; communicate cleanup info.\r
678         *close-on-error*\r
679         *close-in-parent*\r
680         *handlers-installed*\r
681         ;; Establish PROC at this level so that we can return it.\r
682         proc\r
683         ;; It's friendly to allow the caller to pass any string\r
684         ;; designator, but internally we'd like SIMPLE-STRINGs.\r
685         (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))\r
686     (unwind-protect\r
687          (let ((pfile\r
688                 (if search\r
689                     (find-executable-in-search-path program)\r
690                     (unix-namestring program)))\r
691                (cookie (list 0)))\r
692            (unless pfile\r
693              (error "no such program: ~S" program))\r
694            (unless (unix-filename-is-executable-p pfile)\r
695              (error "not executable: ~S" program))\r
696            (multiple-value-bind (stdin input-stream)\r
697                (get-descriptor-for input cookie\r
698                                    :direction :input\r
699                                    :if-does-not-exist if-input-does-not-exist)\r
700              (multiple-value-bind (stdout output-stream)\r
701                  (get-descriptor-for output cookie\r
702                                      :direction :output\r
703                                      :if-exists if-output-exists)\r
704                (multiple-value-bind (stderr error-stream)\r
705                    (if (eq error :output)\r
706                        (values stdout output-stream)\r
707                        (get-descriptor-for error cookie\r
708                                            :direction :output\r
709                                            :if-exists if-error-exists))\r
710                  (multiple-value-bind (pty-name pty-stream)\r
711                      (open-pty pty cookie)\r
712                    ;; Make sure we are not notified about the child\r
713                    ;; death before we have installed the PROCESS\r
714                    ;; structure in *ACTIVE-PROCESSES*.\r
715                    (with-active-processes-lock ()\r
716                     (with-c-strvec (args-vec simple-args)\r
717                       (with-c-strvec (environment-vec environment)\r
718                         (let ((child-pid\r
719                                (without-gcing\r
720                                 (spawn pfile args-vec environment-vec pty-name\r
721                                        stdin stdout stderr))))\r
722                           (when (< child-pid 0)\r
723                             (error "couldn't fork child process: ~A"\r
724                                    (strerror)))\r
725                           (setf proc (make-process :pid child-pid\r
726                                                    :%status :running\r
727                                                    :pty pty-stream\r
728                                                    :input input-stream\r
729                                                    :output output-stream\r
730                                                    :error error-stream\r
731                                                    :status-hook status-hook\r
732                                                    :cookie cookie))\r
733                           (push proc *active-processes*))))))))))\r
734       (dolist (fd *close-in-parent*)\r
735         (sb-unix:unix-close fd))\r
736       (unless proc\r
737         (dolist (fd *close-on-error*)\r
738           (sb-unix:unix-close fd))\r
739         (dolist (handler *handlers-installed*)\r
740           (sb-sys:remove-fd-handler handler))))\r
741     (when (and wait proc)\r
742       (process-wait proc))\r
743     proc))\r
744 \r
745 #+win32\r
746 (defun run-program (program args\r
747                     &key\r
748                     (wait t)\r
749                     search\r
750                     input\r
751                     if-input-does-not-exist\r
752                     output\r
753                     (if-output-exists :error)\r
754                     (error :output)\r
755                     (if-error-exists :error)\r
756                     status-hook)\r
757   "RUN-PROGRAM creates a new process specified by the PROGRAM\r
758 argument. ARGS are the standard arguments that can be passed to a\r
759 program. For no arguments, use NIL (which means that just the name of\r
760 the program is passed as arg 0).\r
761 \r
762 RUN-PROGRAM will return a PROCESS structure. See the CMU\r
763 Common Lisp Users Manual for details about the PROCESS structure.\r
764 \r
765    The &KEY arguments have the following meanings:\r
766      :SEARCH\r
767         Look for PROGRAM in each of the directories along the $PATH\r
768         environment variable.  Otherwise an absolute pathname is required.\r
769         (See also FIND-EXECUTABLE-IN-SEARCH-PATH)\r
770      :WAIT\r
771         If non-NIL (default), wait until the created process finishes.  If\r
772         NIL, continue running Lisp until the program finishes.\r
773      :INPUT\r
774         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard\r
775         input for the current process is inherited.  If NIL, nul\r
776         is used.  If a pathname, the file so specified is used.  If a stream,\r
777         all the input is read from that stream and send to the subprocess.  If\r
778         :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends\r
779         its output to the process. Defaults to NIL.\r
780      :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)\r
781         can be one of:\r
782            :ERROR to generate an error\r
783            :CREATE to create an empty file\r
784            NIL (the default) to return NIL from RUN-PROGRAM\r
785      :OUTPUT\r
786         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard\r
787         output for the current process is inherited.  If NIL, nul\r
788         is used.  If a pathname, the file so specified is used.  If a stream,\r
789         all the output from the process is written to this stream. If\r
790         :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can\r
791         be read to get the output. Defaults to NIL.\r
792      :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)\r
793         can be one of:\r
794            :ERROR (the default) to generate an error\r
795            :SUPERSEDE to supersede the file with output from the program\r
796            :APPEND to append output from the program to the file\r
797            NIL to return NIL from RUN-PROGRAM, without doing anything\r
798      :ERROR and :IF-ERROR-EXISTS\r
799         Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be\r
800         specified as :OUTPUT in which case all error output is routed to the\r
801         same place as normal output.\r
802      :STATUS-HOOK\r
803         This is a function the system calls whenever the status of the\r
804         process changes.  The function takes the process as an argument."\r
805   ;; Prepend the program to the argument list.\r
806   (push (namestring program) args)\r
807   (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to\r
808         ;; communicate cleanup info.\r
809         *close-on-error*\r
810         *close-in-parent*\r
811         ;; Establish PROC at this level so that we can return it.\r
812         proc\r
813         ;; It's friendly to allow the caller to pass any string\r
814         ;; designator, but internally we'd like SIMPLE-STRINGs.\r
815         (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))\r
816     (unwind-protect\r
817          (let ((pfile\r
818                 (if search\r
819                     (find-executable-in-search-path program)\r
820                     (unix-namestring program)))\r
821                (cookie (list 0)))\r
822            (unless pfile\r
823              (error "No such program: ~S" program))\r
824            (unless (unix-filename-is-executable-p pfile)\r
825              (error "Not an executable: ~S" program))\r
826            (multiple-value-bind (stdin input-stream)\r
827                (get-descriptor-for input cookie\r
828                                    :direction :input\r
829                                    :if-does-not-exist if-input-does-not-exist)\r
830              (multiple-value-bind (stdout output-stream)\r
831                  (get-descriptor-for output cookie\r
832                                      :direction :output\r
833                                      :if-exists if-output-exists)\r
834                (multiple-value-bind (stderr error-stream)\r
835                    (if (eq error :output)\r
836                        (values stdout output-stream)\r
837                        (get-descriptor-for error cookie\r
838                                            :direction :output\r
839                                            :if-exists if-error-exists))\r
840                     (with-c-strvec (args-vec simple-args)\r
841                           (let ((handle (without-gcing\r
842                                          (spawn pfile args-vec\r
843                                                 stdin stdout stderr\r
844                                                 (if wait 1 0)))))\r
845                             (when (< handle 0)\r
846                               (error "Couldn't spawn program: ~A" (strerror)))\r
847                             (setf proc\r
848                                   (if wait \r
849                                       (make-process :pid handle\r
850                                                     :%status :exited\r
851                                                     :input input-stream\r
852                                                     :output output-stream\r
853                                                     :error error-stream\r
854                                                     :status-hook status-hook\r
855                                                     :cookie cookie\r
856                                                     :exit-code handle)\r
857                                       (make-process :pid handle\r
858                                                     :%status :running\r
859                                                     :input input-stream\r
860                                                     :output output-stream\r
861                                                     :error error-stream\r
862                                                     :status-hook status-hook\r
863                                                     :cookie cookie)))\r
864                             (push proc *active-processes*)))))))\r
865       (dolist (fd *close-in-parent*)\r
866         (sb-unix:unix-close fd)))\r
867     (unless proc\r
868       (dolist (fd *close-on-error*)\r
869         (sb-unix:unix-close fd)))\r
870 \r
871     proc))\r
872 \r
873 ;;; Install a handler for any input that shows up on the file\r
874 ;;; descriptor. The handler reads the data and writes it to the\r
875 ;;; stream.\r
876 (defun copy-descriptor-to-stream (descriptor stream cookie)\r
877   (incf (car cookie))\r
878   (let ((string (make-string 256 :element-type 'base-char))\r
879         handler)\r
880     (setf handler\r
881           (sb-sys:add-fd-handler\r
882            descriptor\r
883            :input (lambda (fd)\r
884                     (declare (ignore fd))\r
885                     (loop\r
886                      (unless handler\r
887                        (return))\r
888                      (multiple-value-bind\r
889                          (result readable/errno)\r
890                          (sb-unix:unix-select (1+ descriptor)\r
891                                               (ash 1 descriptor)\r
892                                               0 0 0)\r
893                        (cond ((null result)\r
894                               (error "~@<couldn't select on sub-process: ~\r
895                                            ~2I~_~A~:>"\r
896                                      (strerror readable/errno)))\r
897                              ((zerop result)\r
898                               (return))))\r
899                      (sb-alien:with-alien ((buf (sb-alien:array\r
900                                                  sb-alien:char\r
901                                                  256)))\r
902                        (multiple-value-bind\r
903                            (count errno)\r
904                            (sb-unix:unix-read descriptor\r
905                                               (alien-sap buf)\r
906                                               256)\r
907                            (cond (#-win32(or (and (null count)\r
908                                                   (eql errno sb-unix:eio))\r
909                                              (eql count 0))\r
910                                          #+win32(<= count 0)\r
911                                 (sb-sys:remove-fd-handler handler)\r
912                                 (setf handler nil)\r
913                                 (decf (car cookie))\r
914                                 (sb-unix:unix-close descriptor)\r
915                                 (return))\r
916                                ((null count)\r
917                                 (sb-sys:remove-fd-handler handler)\r
918                                 (setf handler nil)\r
919                                 (decf (car cookie))\r
920                                 (error\r
921                                  "~@<couldn't read input from sub-process: ~\r
922                                      ~2I~_~A~:>"\r
923                                  (strerror errno)))\r
924                                (t\r
925                                 (sb-kernel:copy-ub8-from-system-area\r
926                                  (alien-sap buf) 0\r
927                                  string 0\r
928                                  count)\r
929                                 (write-string string stream\r
930                                               :end count)))))))))))\r
931 \r
932 (defun get-stream-fd (stream direction)\r
933   (typecase stream\r
934     (sb-sys:fd-stream\r
935      (values (sb-sys:fd-stream-fd stream) nil))\r
936     (synonym-stream\r
937      (get-stream-fd (symbol-value (synonym-stream-symbol stream)) direction))\r
938     (two-way-stream\r
939      (ecase direction\r
940        (:input\r
941         (get-stream-fd (two-way-stream-input-stream stream) direction))\r
942        (:output\r
943         (get-stream-fd (two-way-stream-output-stream stream) direction))))))\r
944 \r
945 ;;; Find a file descriptor to use for object given the direction.\r
946 ;;; Returns the descriptor. If object is :STREAM, returns the created\r
947 ;;; stream as the second value.\r
948 (defun get-descriptor-for (object\r
949                            cookie\r
950                            &rest keys\r
951                            &key direction\r
952                            &allow-other-keys)\r
953   (cond ((eq object t)\r
954          ;; No new descriptor is needed.\r
955          (values -1 nil))\r
956         ((eq object nil)\r
957          ;; Use /dev/null.\r
958          (multiple-value-bind\r
959                (fd errno)\r
960              (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)\r
961                                 #+win32 #.(coerce "nul" 'base-string)\r
962                                 (case direction\r
963                                   (:input sb-unix:o_rdonly)\r
964                                   (:output sb-unix:o_wronly)\r
965                                   (t sb-unix:o_rdwr))\r
966                                 #o666)\r
967            (unless fd\r
968              (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"\r
969                     #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"\r
970                     (strerror errno)))\r
971            (push fd *close-in-parent*)\r
972            (values fd nil)))\r
973         ((eq object :stream)\r
974          (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)\r
975            (unless read-fd\r
976              (error "couldn't create pipe: ~A" (strerror write-fd)))\r
977            (case direction\r
978              (:input\r
979               (push read-fd *close-in-parent*)\r
980               (push write-fd *close-on-error*)\r
981               (let ((stream (sb-sys:make-fd-stream write-fd :output t\r
982                                                    :element-type :default)))\r
983                 (values read-fd stream)))\r
984              (:output\r
985               (push read-fd *close-on-error*)\r
986               (push write-fd *close-in-parent*)\r
987               (let ((stream (sb-sys:make-fd-stream read-fd :input t\r
988                                                    :element-type :default)))\r
989                 (values write-fd stream)))\r
990              (t\r
991               (sb-unix:unix-close read-fd)\r
992               (sb-unix:unix-close write-fd)\r
993               (error "Direction must be either :INPUT or :OUTPUT, not ~S."\r
994                      direction)))))\r
995         ((or (pathnamep object) (stringp object))\r
996          (with-open-stream (file (apply #'open object keys))\r
997            (multiple-value-bind\r
998                  (fd errno)\r
999                (sb-unix:unix-dup (sb-sys:fd-stream-fd file))\r
1000              (cond (fd\r
1001                     (push fd *close-in-parent*)\r
1002                     (values fd nil))\r
1003                    (t\r
1004                     (error "couldn't duplicate file descriptor: ~A"\r
1005                            (strerror errno)))))))\r
1006         ((streamp object)\r
1007          (ecase direction\r
1008            (:input\r
1009             (or (get-stream-fd object :input)\r
1010                 ;; FIXME: We could use a better way of setting up\r
1011                 ;; temporary files\r
1012                 (dotimes (count\r
1013                            256\r
1014                           (error "could not open a temporary file in /tmp"))\r
1015                   (let* ((name (coerce (format nil "/tmp/.run-program-~D" count)\r
1016                                        'base-string))\r
1017                          (fd (sb-unix:unix-open name\r
1018                                                 (logior sb-unix:o_rdwr\r
1019                                                         sb-unix:o_creat\r
1020                                                         sb-unix:o_excl)\r
1021                                                 #o666)))\r
1022                     (sb-unix:unix-unlink name)\r
1023                     (when fd\r
1024                       (let ((newline (string #\Newline)))\r
1025                         (loop\r
1026                            (multiple-value-bind\r
1027                                  (line no-cr)\r
1028                                (read-line object nil nil)\r
1029                              (unless line\r
1030                                (return))\r
1031                              (sb-unix:unix-write\r
1032                               fd\r
1033                               ;; FIXME: this really should be\r
1034                               ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).\r
1035                               ;; RUN-PROGRAM should take an\r
1036                               ;; external-format argument, which should\r
1037                               ;; be passed down to here.  Something\r
1038                               ;; similar should happen on :OUTPUT, too.\r
1039                               (map '(vector (unsigned-byte 8)) #'char-code line)\r
1040                               0 (length line))\r
1041                              (if no-cr\r
1042                                  (return)\r
1043                                  (sb-unix:unix-write fd newline 0 1)))))\r
1044                       (sb-unix:unix-lseek fd 0 sb-unix:l_set)\r
1045                       (push fd *close-in-parent*)\r
1046                       (return (values fd nil)))))))\r
1047            (:output\r
1048             (or (get-stream-fd object :output)\r
1049                 (multiple-value-bind (read-fd write-fd)\r
1050                     (sb-unix:unix-pipe)\r
1051                   (unless read-fd\r
1052                     (error "couldn't create pipe: ~S" (strerror write-fd)))\r
1053                   (copy-descriptor-to-stream read-fd object cookie)\r
1054                   (push read-fd *close-on-error*)\r
1055                   (push write-fd *close-in-parent*)\r
1056                   (values write-fd nil))))))\r
1057         (t\r
1058          (error "invalid option to RUN-PROGRAM: ~S" object))))\r