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