1.0.12.31: using default external format for RUN-PROGRAM streams
[sbcl/simd.git] / src / code / run-program.lisp
blob10b7fdc59dc7c0d5a1dee83754da60692bb99862
1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
2 ;;;; from inside SBCL
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.
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)
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.
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))))
55 ;#+win32 (sb-alien:define-alien-routine msvcrt-environ (* c-string))
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))
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))
97 ;;;; Import wait3(2) from Unix.
99 #-win32
100 (define-alien-routine ("wait3" c-wait3) sb-alien:int
101 (status sb-alien:int :out)
102 (options sb-alien:int)
103 (rusage sb-alien:int))
105 #-win32
106 (defun wait3 (&optional do-not-hang check-for-stopped)
107 #+sb-doc
108 "Return any available status information on child process. "
109 (multiple-value-bind (pid status)
110 (c-wait3 (logior (if do-not-hang
111 sb-unix:wnohang
113 (if check-for-stopped
114 sb-unix:wuntraced
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)))
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)))))))))
143 ;;;; process control stuff
144 (defvar *active-processes* nil
145 #+sb-doc
146 "List of process structures for all active processes.")
148 #-win32
149 (defvar *active-processes-lock*
150 (sb-thread:make-mutex :name "Lock for active processes."))
152 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
153 ;;; mutex is needed. More importantly the sigchld signal handler also
154 ;;; accesses it, that's why we need without-interrupts.
155 (defmacro with-active-processes-lock (() &body body)
156 #-win32
157 `(sb-thread::call-with-system-mutex (lambda () ,@body) *active-processes-lock*)
158 #+win32
159 `(progn ,@body))
161 (defstruct (process (:copier nil))
162 pid ; PID of child process
163 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
164 exit-code ; either exit code or signal
165 core-dumped ; T if a core image was dumped
166 #-win32 pty ; stream to child's pty, or NIL
167 input ; stream to child's input, or NIL
168 output ; stream from child's output, or NIL
169 error ; stream from child's error output, or NIL
170 status-hook ; closure to call when PROC changes status
171 plist ; a place for clients to stash things
172 cookie) ; list of the number of pipes from the subproc
174 (defmethod print-object ((process process) stream)
175 (print-unreadable-object (process stream :type t)
176 (let ((status (process-status process)))
177 (if (eq :exited status)
178 (format stream "~S ~S" status (process-exit-code process))
179 (format stream "~S ~S" (process-pid process) status)))
180 process))
182 #+sb-doc
183 (setf (documentation 'process-p 'function)
184 "T if OBJECT is a PROCESS, NIL otherwise.")
186 #+sb-doc
187 (setf (documentation 'process-pid 'function) "The pid of the child process.")
189 #+win32
190 (define-alien-routine ("GetExitCodeProcess@8" get-exit-code-process)
192 (handle unsigned) (exit-code unsigned :out))
194 (defun process-status (process)
195 #+sb-doc
196 "Return the current status of PROCESS. The result is one of :RUNNING,
197 :STOPPED, :EXITED, or :SIGNALED."
198 (get-processes-status-changes)
199 (process-%status process))
201 #+sb-doc
202 (setf (documentation 'process-exit-code 'function)
203 "The exit code or the signal of a stopped process.")
205 #+sb-doc
206 (setf (documentation 'process-core-dumped 'function)
207 "T if a core image was dumped by the process.")
209 #+sb-doc
210 (setf (documentation 'process-pty 'function)
211 "The pty stream of the process or NIL.")
213 #+sb-doc
214 (setf (documentation 'process-input 'function)
215 "The input stream of the process or NIL.")
217 #+sb-doc
218 (setf (documentation 'process-output 'function)
219 "The output stream of the process or NIL.")
221 #+sb-doc
222 (setf (documentation 'process-error 'function)
223 "The error stream of the process or NIL.")
225 #+sb-doc
226 (setf (documentation 'process-status-hook 'function)
227 "A function that is called when PROCESS changes its status.
228 The function is called with PROCESS as its only argument.")
230 #+sb-doc
231 (setf (documentation 'process-plist 'function)
232 "A place for clients to stash things.")
234 (defun process-wait (process &optional check-for-stopped)
235 #+sb-doc
236 "Wait for PROCESS to quit running for some reason. When
237 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
238 PROCESS."
239 (loop
240 (case (process-status process)
241 (:running)
242 (:stopped
243 (when check-for-stopped
244 (return)))
246 (when (zerop (car (process-cookie process)))
247 (return))))
248 (sb-sys:serve-all-events 1))
249 process)
251 #-(or hpux win32)
252 ;;; Find the current foreground process group id.
253 (defun find-current-foreground-process (proc)
254 (with-alien ((result sb-alien:int))
255 (multiple-value-bind
256 (wonp error)
257 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
258 sb-unix:TIOCGPGRP
259 (alien-sap (sb-alien:addr result)))
260 (unless wonp
261 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
262 result))
263 (process-pid proc))
265 #-win32
266 (defun process-kill (process signal &optional (whom :pid))
267 #+sb-doc
268 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
269 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
270 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
271 currently in the foreground."
272 (let ((pid (ecase whom
273 ((:pid :process-group)
274 (process-pid process))
275 (:pty-process-group
276 #-hpux
277 (find-current-foreground-process process)))))
278 (multiple-value-bind
279 (okay errno)
280 (case whom
281 #+hpux
282 (:pty-process-group
283 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))
284 sb-unix:TIOCSIGSEND
285 (sb-sys:int-sap
286 signal)))
287 ((:process-group #-hpux :pty-process-group)
288 (sb-unix:unix-killpg pid signal))
290 (sb-unix:unix-kill pid signal)))
291 (cond ((not okay)
292 (values nil errno))
293 ((and (eql pid (process-pid process))
294 (= signal sb-unix:sigcont))
295 (setf (process-%status process) :running)
296 (setf (process-exit-code process) nil)
297 (when (process-status-hook process)
298 (funcall (process-status-hook process) process))
301 t)))))
303 (defun process-alive-p (process)
304 #+sb-doc
305 "Return T if PROCESS is still alive, NIL otherwise."
306 (let ((status (process-status process)))
307 (if (or (eq status :running)
308 (eq status :stopped))
310 nil)))
312 (defun process-close (process)
313 #+sb-doc
314 "Close all streams connected to PROCESS and stop maintaining the
315 status slot."
316 (macrolet ((frob (stream abort)
317 `(when ,stream (close ,stream :abort ,abort))))
318 #-win32
319 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
320 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
321 (frob (process-output process) nil)
322 (frob (process-error process) nil))
323 ;; FIXME: Given that the status-slot is no longer updated,
324 ;; maybe it should be set to :CLOSED, or similar?
325 (with-active-processes-lock ()
326 (setf *active-processes* (delete process *active-processes*)))
327 process)
329 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
330 #-win32
331 (defun sigchld-handler (ignore1 ignore2 ignore3)
332 (declare (ignore ignore1 ignore2 ignore3))
333 (get-processes-status-changes))
335 (defun get-processes-status-changes ()
336 #-win32
337 (loop
338 (multiple-value-bind (pid what code core)
339 (wait3 t t)
340 (unless pid
341 (return))
342 (let ((proc (with-active-processes-lock ()
343 (find pid *active-processes* :key #'process-pid))))
344 (when proc
345 (setf (process-%status proc) what)
346 (setf (process-exit-code proc) code)
347 (setf (process-core-dumped proc) core)
348 (when (process-status-hook proc)
349 (funcall (process-status-hook proc) proc))
350 (when (position what #(:exited :signaled))
351 (with-active-processes-lock ()
352 (setf *active-processes*
353 (delete proc *active-processes*))))))))
354 #+win32
355 (let (exited)
356 (with-active-processes-lock ()
357 (setf *active-processes*
358 (delete-if (lambda (proc)
359 (multiple-value-bind (ok code)
360 (get-exit-code-process (process-pid proc))
361 (when (and (plusp ok) (/= code 259))
362 (setf (process-%status proc) :exited
363 (process-exit-code proc) code)
364 (when (process-status-hook proc)
365 (push proc exited))
366 t)))
367 *active-processes*)))
368 ;; Can't call the hooks before all the processes have been deal
369 ;; with, as calling a hook may cause re-entry to
370 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,
371 ;; but in the Windows implementation is would be deeply bad.
372 (dolist (proc exited)
373 (let ((hook (process-status-hook proc)))
374 (when hook
375 (funcall hook proc))))))
377 ;;;; RUN-PROGRAM and close friends
379 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
380 (defvar *close-on-error* nil)
382 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
383 (defvar *close-in-parent* nil)
385 ;;; list of handlers installed by RUN-PROGRAM. FIXME: nothing seems
386 ;;; to set this.
387 #-win32
388 (defvar *handlers-installed* nil)
390 ;;; Find an unused pty. Return three values: the file descriptor for
391 ;;; the master side of the pty, the file descriptor for the slave side
392 ;;; of the pty, and the name of the tty device for the slave side.
393 #-win32
394 (progn
395 (define-alien-routine ptsname c-string (fd int))
396 (define-alien-routine grantpt boolean (fd int))
397 (define-alien-routine unlockpt boolean (fd int))
399 (defun find-a-pty ()
400 ;; First try to use the Unix98 pty api.
401 (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
402 (master-fd (sb-unix:unix-open master-name
403 sb-unix:o_rdwr
404 #o666)))
405 (when master-fd
406 (grantpt master-fd)
407 (unlockpt master-fd)
408 (let* ((slave-name (ptsname master-fd))
409 (slave-fd (sb-unix:unix-open slave-name
410 sb-unix:o_rdwr
411 #o666)))
412 (when slave-fd
413 (return-from find-a-pty
414 (values master-fd
415 slave-fd
416 slave-name)))
417 (sb-unix:unix-close master-fd))
418 (error "could not find a pty")))
419 ;; No dice, try using the old-school method.
420 (dolist (char '(#\p #\q))
421 (dotimes (digit 16)
422 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
423 'base-string))
424 (master-fd (sb-unix:unix-open master-name
425 sb-unix:o_rdwr
426 #o666)))
427 (when master-fd
428 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
429 'base-string))
430 (slave-fd (sb-unix:unix-open slave-name
431 sb-unix:o_rdwr
432 #o666)))
433 (when slave-fd
434 (return-from find-a-pty
435 (values master-fd
436 slave-fd
437 slave-name)))
438 (sb-unix:unix-close master-fd))))))
439 (error "could not find a pty")))
441 #-win32
442 (defun open-pty (pty cookie)
443 (when pty
444 (multiple-value-bind
445 (master slave name)
446 (find-a-pty)
447 (push master *close-on-error*)
448 (push slave *close-in-parent*)
449 (when (streamp pty)
450 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
451 (unless new-fd
452 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
453 (push new-fd *close-on-error*)
454 (copy-descriptor-to-stream new-fd pty cookie)))
455 (values name
456 (sb-sys:make-fd-stream master :input t :output t
457 :element-type :default
458 :dual-channel-p t)))))
460 (defmacro round-bytes-to-words (n)
461 (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
462 `(logandc2 (the fixnum (+ (the fixnum ,n)
463 (1- ,bytes-per-word))) (1- ,bytes-per-word))))
465 (defun string-list-to-c-strvec (string-list)
466 (let* ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))
467 ;; We need an extra for the null, and an extra 'cause exect
468 ;; clobbers argv[-1].
469 (vec-bytes (* bytes-per-word (+ (length string-list) 2)))
470 (octet-vector-list (mapcar (lambda (s)
471 (string-to-octets s :null-terminate t))
472 string-list))
473 (string-bytes (reduce #'+ octet-vector-list
474 :key (lambda (s)
475 (round-bytes-to-words (length s)))))
476 (total-bytes (+ string-bytes vec-bytes))
477 ;; Memory to hold the vector of pointers and all the strings.
478 (vec-sap (sb-sys:allocate-system-memory total-bytes))
479 (string-sap (sap+ vec-sap vec-bytes))
480 ;; Index starts from [1]!
481 (vec-index-offset bytes-per-word))
482 (declare (index string-bytes vec-bytes total-bytes)
483 (sb-sys:system-area-pointer vec-sap string-sap))
484 (dolist (octets octet-vector-list)
485 (declare (type (simple-array (unsigned-byte 8) (*)) octets))
486 (let ((size (length octets)))
487 ;; Copy string.
488 (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
489 ;; Put the pointer in the vector.
490 (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
491 ;; Advance string-sap for the next string.
492 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ size))))
493 (incf vec-index-offset bytes-per-word)))
494 ;; Final null pointer.
495 (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
496 (values vec-sap (sap+ vec-sap bytes-per-word) total-bytes)))
498 (defmacro with-c-strvec ((var str-list) &body body)
499 (with-unique-names (sap size)
500 `(multiple-value-bind (,sap ,var ,size)
501 (string-list-to-c-strvec ,str-list)
502 (unwind-protect
503 (progn
504 ,@body)
505 (sb-sys:deallocate-system-memory ,sap ,size)))))
507 #-win32
508 (sb-alien:define-alien-routine ("spawn" %spawn) sb-alien:int
509 (program sb-alien:c-string)
510 (argv (* sb-alien:c-string))
511 (envp (* sb-alien:c-string))
512 (pty-name sb-alien:c-string)
513 (stdin sb-alien:int)
514 (stdout sb-alien:int)
515 (stderr sb-alien:int))
517 #+win32
518 (sb-alien:define-alien-routine ("spawn" %spawn) sb-win32::handle
519 (program sb-alien:c-string)
520 (argv (* sb-alien:c-string))
521 (stdin sb-alien:int)
522 (stdout sb-alien:int)
523 (stderr sb-alien:int)
524 (wait sb-alien:int))
526 (defun spawn (program argv stdin stdout stderr envp pty-name wait)
527 #+win32 (declare (ignore envp pty-name))
528 #+win32 (%spawn program argv stdin stdout stderr (if wait 1 0))
529 #-win32 (declare (ignore wait))
530 #-win32 (%spawn program argv envp pty-name stdin stdout stderr))
532 ;;; FIXME: why are we duplicating standard library stuff and not using
533 ;;; execvp(3)? We can extend our internal spawn() routine to take a
534 ;;; flag to say whether to search...
535 ;;; Is UNIX-FILENAME the name of a file that we can execute?
536 (defun unix-filename-is-executable-p (unix-filename)
537 (let ((filename (coerce unix-filename 'string)))
538 (values (and (eq (sb-unix:unix-file-kind filename) :file)
539 #-win32
540 (sb-unix:unix-access filename sb-unix:x_ok)))))
542 (defun find-executable-in-search-path (pathname &optional
543 (search-path (posix-getenv "PATH")))
544 #+sb-doc
545 "Find the first executable file matching PATHNAME in any of the
546 colon-separated list of pathnames SEARCH-PATH"
547 (let ((program #-win32 pathname
548 #+win32 (merge-pathnames pathname (make-pathname :type "exe"))))
549 (loop for end = (position #-win32 #\: #+win32 #\; search-path
550 :start (if end (1+ end) 0))
551 and start = 0 then (and end (1+ end))
552 while start
553 ;; <Krystof> the truename of a file naming a directory is the
554 ;; directory, at least until pfdietz comes along and says why
555 ;; that's noncompliant -- CSR, c. 2003-08-10
556 for truename = (probe-file (subseq search-path start end))
557 for fullpath = (when truename
558 (unix-namestring (merge-pathnames program truename)))
559 when (and fullpath (unix-filename-is-executable-p fullpath))
560 return fullpath)))
562 ;;; FIXME: There shouldn't be two semiredundant versions of the
563 ;;; documentation. Since this is a public extension function, the
564 ;;; documentation should be in the doc string. So all information from
565 ;;; this comment should be merged into the doc string, and then this
566 ;;; comment can go away.
568 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
569 ;;; Strange stuff happens to keep the Unix state of the world
570 ;;; coherent.
572 ;;; The child process needs to get its input from somewhere, and send
573 ;;; its output (both standard and error) to somewhere. We have to do
574 ;;; different things depending on where these somewheres really are.
576 ;;; For input, there are five options:
577 ;;; -- T: Just leave fd 0 alone. Pretty simple.
578 ;;; -- "file": Read from the file. We need to open the file and
579 ;;; pull the descriptor out of the stream. The parent should close
580 ;;; this stream after the child is up and running to free any
581 ;;; storage used in the parent.
582 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
583 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
584 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
585 ;;; writeable descriptor, and pass the readable descriptor to
586 ;;; the child. The parent must close the readable descriptor for
587 ;;; EOF to be passed up correctly.
588 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
589 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
590 ;;; everything across.
592 ;;; For output, there are five options:
593 ;;; -- T: Leave descriptor 1 alone.
594 ;;; -- "file": dump output to the file.
595 ;;; -- NIL: dump output to /dev/null.
596 ;;; -- :STREAM: return a stream that can be read from.
597 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
598 ;;; Otherwise, copy stuff from output to stream.
600 ;;; For error, there are all the same options as output plus:
601 ;;; -- :OUTPUT: redirect to the same place as output.
603 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
604 ;;; the fork worked, and NIL if it did not.
605 (defun run-program (program args
606 &key
607 #-win32 (env nil env-p)
608 #-win32 (environment
609 (if env-p
610 (unix-environment-sbcl-from-cmucl env)
611 (posix-environ))
612 environment-p)
613 (wait t)
614 search
615 #-win32 pty
616 input
617 if-input-does-not-exist
618 output
619 (if-output-exists :error)
620 (error :output)
621 (if-error-exists :error)
622 status-hook)
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).
633 The program arguments and the environment are encoded using the
634 default external format for streams.
636 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
637 Users Manual for details about the PROCESS structure."#-win32"
639 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
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.
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.)""
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 along the $PATH
663 environment variable. Otherwise an absolute pathname is required.
664 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
665 :WAIT
666 If non-NIL (default), wait until the created process finishes. If
667 NIL, continue running Lisp until the program finishes."#-win32"
668 :PTY
669 Either T, NIL, or a stream. Unless NIL, the subprocess is established
670 under a PTY. If :pty is a stream, all output to this pty is sent to
671 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
672 connected to pty that can read output and write input.""
673 :INPUT
674 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
675 input for the current process is inherited. If NIL, "
676 #-win32"/dev/null"#+win32"nul""
677 is used. If a pathname, the file so specified is used. If a stream,
678 all the input is read from that stream and sent to the subprocess. If
679 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
680 its output to the process. Defaults to NIL.
681 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
682 can be one of:
683 :ERROR to generate an error
684 :CREATE to create an empty file
685 NIL (the default) to return NIL from RUN-PROGRAM
686 :OUTPUT
687 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
688 output for the current process is inherited. If NIL, "
689 #-win32"/dev/null"#+win32"nul""
690 is used. If a pathname, the file so specified is used. If a stream,
691 all the output from the process is written to this stream. If
692 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
693 be read to get the output. Defaults to NIL.
694 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
695 can be one of:
696 :ERROR (the default) to generate an error
697 :SUPERSEDE to supersede the file with output from the program
698 :APPEND to append output from the program to the file
699 NIL to return NIL from RUN-PROGRAM, without doing anything
700 :ERROR and :IF-ERROR-EXISTS
701 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
702 specified as :OUTPUT in which case all error output is routed to the
703 same place as normal output.
704 :STATUS-HOOK
705 This is a function the system calls whenever the status of the
706 process changes. The function takes the process as an argument.")
707 #-win32
708 (when (and env-p environment-p)
709 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
710 ;; Make sure that the interrupt handler is installed.
711 #-win32
712 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
713 ;; Prepend the program to the argument list.
714 (push (namestring program) args)
715 (labels (;; It's friendly to allow the caller to pass any string
716 ;; designator, but internally we'd like SIMPLE-STRINGs.
718 ;; Huh? We let users pass in symbols and characters for
719 ;; the arguments, but call NAMESTRING on the program
720 ;; name... -- RMK
721 (simplify-args (args)
722 (loop for arg in args
723 as escaped-arg = (escape-arg arg)
724 collect (coerce escaped-arg 'simple-string)))
725 (escape-arg (arg)
726 #-win32 arg
727 ;; Apparently any spaces or double quotes in the arguments
728 ;; need to be escaped on win32.
729 #+win32 (if (position-if
730 (lambda (c) (find c '(#\" #\Space))) arg)
731 (write-to-string arg)
732 arg)))
733 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
734 ;; communicate cleanup info.
735 *close-on-error*
736 *close-in-parent*
737 ;; Some other binding used only on non-Win32. FIXME:
738 ;; nothing seems to set this.
739 #-win32 *handlers-installed*
740 ;; Establish PROC at this level so that we can return it.
741 proc
742 ;; It's friendly to allow the caller to pass any string
743 ;; designator, but internally we'd like SIMPLE-STRINGs.
744 (simple-args (simplify-args args))
745 ;; See the comment above about execlp(3).
746 (pfile (if search
747 (find-executable-in-search-path program)
748 (unix-namestring program)))
749 ;; Gag.
750 (cookie (list 0)))
751 (unless pfile
752 (error "no such program: ~S" program))
753 (unless (unix-filename-is-executable-p pfile)
754 (error "not executable: ~S" program))
755 (unwind-protect
756 (macrolet ((with-fd-and-stream-for (((fd stream) which &rest args)
757 &body body)
758 `(multiple-value-bind (,fd ,stream)
759 ,(ecase which
760 ((:input :output)
761 `(get-descriptor-for ,@args))
762 (:error
763 `(if (eq ,(first args) :output)
764 ;; kludge: we expand into
765 ;; hard-coded symbols here.
766 (values stdout output-stream)
767 (get-descriptor-for ,@args))))
768 ,@body))
769 (with-open-pty (((pty-name pty-stream) (pty cookie)) &body body)
770 #+win32 `(declare (ignore ,pty ,cookie))
771 #+win32 `(let (,pty-name ,pty-stream) ,@body)
772 #-win32 `(multiple-value-bind (,pty-name ,pty-stream)
773 (open-pty ,pty ,cookie)
774 ,@body))
775 (with-args-vec ((vec args) &body body)
776 `(with-c-strvec (,vec ,args)
777 ,@body))
778 (with-environment-vec ((vec env) &body body)
779 #+win32 `(let (,vec) ,@body)
780 #-win32 `(with-c-strvec (,vec ,env) ,@body)))
781 (with-fd-and-stream-for ((stdin input-stream) :input
782 input cookie
783 :direction :input
784 :if-does-not-exist if-input-does-not-exist
785 :external-format :default)
786 (with-fd-and-stream-for ((stdout output-stream) :output
787 output cookie
788 :direction :output
789 :if-exists if-output-exists
790 :external-format :default)
791 (with-fd-and-stream-for ((stderr error-stream) :error
792 error cookie
793 :direction :output
794 :if-exists if-error-exists
795 :external-format :default)
796 (with-open-pty ((pty-name pty-stream) (pty cookie))
797 ;; Make sure we are not notified about the child
798 ;; death before we have installed the PROCESS
799 ;; structure in *ACTIVE-PROCESSES*.
800 (with-active-processes-lock ()
801 (with-args-vec (args-vec simple-args)
802 (with-environment-vec (environment-vec environment)
803 (let ((child
804 (without-gcing
805 (spawn pfile args-vec
806 stdin stdout stderr
807 environment-vec pty-name wait))))
808 (when (minusp child)
809 (error "couldn't fork child process: ~A"
810 (strerror)))
811 (setf proc (apply
812 #'make-process
813 :pid child
814 :input input-stream
815 :output output-stream
816 :error error-stream
817 :status-hook status-hook
818 :cookie cookie
819 #-win32 (list :pty pty-stream
820 :%status :running)
821 #+win32 (if wait
822 (list :%status :exited
823 :exit-code child)
824 (list :%status :running))))
825 (push proc *active-processes*))))))))))
826 (dolist (fd *close-in-parent*)
827 (sb-unix:unix-close fd))
828 (unless proc
829 (dolist (fd *close-on-error*)
830 (sb-unix:unix-close fd))
831 ;; FIXME: nothing seems to set this.
832 #-win32
833 (dolist (handler *handlers-installed*)
834 (sb-sys:remove-fd-handler handler))))
835 (when (and wait proc)
836 (process-wait proc))
837 proc)))
839 ;;; Install a handler for any input that shows up on the file
840 ;;; descriptor. The handler reads the data and writes it to the
841 ;;; stream.
842 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
843 (incf (car cookie))
844 (let* (handler
845 (buf (make-array 256 :element-type '(unsigned-byte 8)))
846 (read-end 0))
847 (setf handler
848 (sb-sys:add-fd-handler
849 descriptor
850 :input
851 (lambda (fd)
852 (declare (ignore fd))
853 (loop
854 (unless handler
855 (return))
856 (multiple-value-bind
857 (result readable/errno)
858 (sb-unix:unix-select (1+ descriptor)
859 (ash 1 descriptor)
860 0 0 0)
861 (cond ((null result)
862 (error "~@<couldn't select on sub-process: ~
863 ~2I~_~A~:>"
864 (strerror readable/errno)))
865 ((zerop result)
866 (return))))
867 (multiple-value-bind (count errno)
868 (with-pinned-objects (buf)
869 (sb-unix:unix-read descriptor
870 (sap+ (vector-sap buf) read-end)
871 (- (length buf) read-end)))
872 (cond
873 ((and #-win32 (or (and (null count)
874 (eql errno sb-unix:eio))
875 (eql count 0))
876 #+win32 (<= count 0))
877 (sb-sys:remove-fd-handler handler)
878 (setf handler nil)
879 (decf (car cookie))
880 (sb-unix:unix-close descriptor)
881 (return))
882 ((null count)
883 (sb-sys:remove-fd-handler handler)
884 (setf handler nil)
885 (decf (car cookie))
886 (error
887 "~@<couldn't read input from sub-process: ~
888 ~2I~_~A~:>"
889 (strerror errno)))
891 (incf read-end count)
892 (let* ((decode-end (length buf))
893 (string (handler-case
894 (octets-to-string
895 buf :end read-end
896 :external-format external-format)
897 (end-of-input-in-character (e)
898 (setf decode-end
899 (octet-decoding-error-start e))
900 (octets-to-string
901 buf :end decode-end
902 :external-format external-format)))))
903 (unless (zerop (length string))
904 (write-string string stream)
905 (when (/= decode-end (length buf))
906 (replace buf buf :start2 decode-end :end2 read-end))
907 (decf read-end decode-end))))))))))))
909 (defun get-stream-fd-and-external-format (stream direction)
910 (typecase stream
911 (sb-sys:fd-stream
912 (values (sb-sys:fd-stream-fd stream) nil (stream-external-format stream)))
913 (synonym-stream
914 (get-stream-fd-and-external-format
915 (symbol-value (synonym-stream-symbol stream)) direction))
916 (two-way-stream
917 (ecase direction
918 (:input
919 (get-stream-fd-and-external-format
920 (two-way-stream-input-stream stream) direction))
921 (:output
922 (get-stream-fd-and-external-format
923 (two-way-stream-output-stream stream) direction))))))
926 ;;; Find a file descriptor to use for object given the direction.
927 ;;; Returns the descriptor. If object is :STREAM, returns the created
928 ;;; stream as the second value.
929 (defun get-descriptor-for (object
930 cookie
931 &rest keys
932 &key direction external-format
933 &allow-other-keys)
934 ;; Someday somebody should review our use of the temporary file: are
935 ;; we doing something that's liable to run afoul of disk quotas or
936 ;; to choke on small /tmp file systems?
937 (flet ((make-temp-fd ()
938 (multiple-value-bind (fd name/errno)
939 (sb-unix:unix-mkstemp "/tmp/.run-program-XXXXXX")
940 (unless fd
941 (error "could not open a temporary file: ~A"
942 (strerror name/errno)))
943 #-win32 #|FIXME: should say (logior s_irusr s_iwusr)|#
944 (unless (sb-unix:unix-chmod name/errno #o600)
945 (sb-unix:unix-close fd)
946 (error "failed to chmod the temporary file?!"))
947 (unless (sb-unix:unix-unlink name/errno)
948 (sb-unix:unix-close fd)
949 (error "failed to unlink ~A" name/errno))
950 fd)))
951 (cond ((eq object t)
952 ;; No new descriptor is needed.
953 (values -1 nil))
954 ((eq object nil)
955 ;; Use /dev/null.
956 (multiple-value-bind
957 (fd errno)
958 (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
959 #+win32 #.(coerce "nul" 'base-string)
960 (case direction
961 (:input sb-unix:o_rdonly)
962 (:output sb-unix:o_wronly)
963 (t sb-unix:o_rdwr))
964 #o666)
965 (unless fd
966 (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
967 #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
968 (strerror errno)))
969 (push fd *close-in-parent*)
970 (values fd nil)))
971 ((eq object :stream)
972 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
973 (unless read-fd
974 (error "couldn't create pipe: ~A" (strerror write-fd)))
975 (case direction
976 (:input
977 (push read-fd *close-in-parent*)
978 (push write-fd *close-on-error*)
979 (let ((stream (sb-sys:make-fd-stream write-fd :output t
980 :element-type :default
981 :external-format
982 external-format)))
983 (values read-fd stream)))
984 (:output
985 (push read-fd *close-on-error*)
986 (push write-fd *close-in-parent*)
987 (let ((stream (sb-sys:make-fd-stream read-fd :input t
988 :element-type :default
989 :external-format
990 external-format)))
991 (values write-fd stream)))
993 (sb-unix:unix-close read-fd)
994 (sb-unix:unix-close write-fd)
995 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
996 direction)))))
997 ((or (pathnamep object) (stringp object))
998 (with-open-stream (file (apply #'open object keys))
999 (multiple-value-bind
1000 (fd errno)
1001 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
1002 (cond (fd
1003 (push fd *close-in-parent*)
1004 (values fd nil))
1006 (error "couldn't duplicate file descriptor: ~A"
1007 (strerror errno)))))))
1008 ((streamp object)
1009 ;; XXX: what is the correct way to compare external formats?
1010 (ecase direction
1011 (:input
1013 ;; If we can get an fd for the stream and the
1014 ;; stream's external format is the default, let the
1015 ;; child process use the fd for its descriptor.
1016 ;; Otherwise, we copy data from the stream into a
1017 ;; temp file, and give the temp file's descriptor to
1018 ;; the child.
1019 (multiple-value-bind (fd stream format)
1020 (get-stream-fd-and-external-format object :input)
1021 (when (and fd format
1022 (eq (find-external-format
1023 *default-external-format*)
1024 (find-external-format format)))
1025 (values fd stream)))
1026 (let ((fd (make-temp-fd))
1027 (newline (string #\Newline)))
1028 (loop
1029 (multiple-value-bind
1030 (line no-cr)
1031 (read-line object nil nil)
1032 (unless line
1033 (return))
1034 (let ((vector
1035 (string-to-octets
1036 line :external-format external-format)))
1037 (sb-unix:unix-write
1038 fd vector 0 (length vector)))
1039 (if no-cr
1040 (return)
1041 (sb-unix:unix-write fd newline 0 1))))
1042 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1043 (push fd *close-in-parent*)
1044 (values fd nil))))
1045 (:output
1047 ;; Similar to the :input trick above, except we
1048 ;; arrange to copy data from the stream. This is
1049 ;; only slightly less sleazy than the input case,
1050 ;; since we don't buffer to a file, but I think we
1051 ;; may still lose if there's data in the stream
1052 ;; buffer.
1053 (multiple-value-bind (fd stream format)
1054 (get-stream-fd-and-external-format object :output)
1055 (when (and fd format (eq (find-external-format
1056 *default-external-format*)
1057 (find-external-format format)))
1058 (values fd stream)))
1059 (multiple-value-bind (read-fd write-fd)
1060 (sb-unix:unix-pipe)
1061 (unless read-fd
1062 (error "couldn't create pipe: ~S" (strerror write-fd)))
1063 (copy-descriptor-to-stream
1064 read-fd object cookie external-format)
1065 (push read-fd *close-on-error*)
1066 (push write-fd *close-in-parent*)
1067 (values write-fd nil))))))
1069 (error "invalid option to RUN-PROGRAM: ~S" object)))))