1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
4 ;;;; This software is part of the SBCL system. See the README file for
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
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.
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.
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.
60 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
62 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
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)
70 (declare (string string))
71 (let ((=-pos (position #\= string :test #'equal)))
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 ~
83 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
87 ;;; Convert from a CMU CL representation of a Unix environment to a
88 ;;; SBCL representation.
89 (defun unix-environment-sbcl-from-cmucl (cmucl)
92 (destructuring-bind (key . val) cons
93 (declare (type keyword key) (string val))
94 (concatenate 'simple-string (symbol-name key) "=" val)))
97 ;;;; Import wait3(2) from Unix.
100 (define-alien-routine ("waitpid" c-waitpid) sb-alien:int
102 (status sb-alien:int :out)
103 (options sb-alien:int))
106 (defun waitpid (pid &optional do-not-hang check-for-stopped)
108 "Return any available status information on child process with PID."
109 (multiple-value-bind (pid status)
111 (logior (if do-not-hang
114 (if check-for-stopped
117 (cond ((or (minusp pid)
120 ((eql (ldb (byte 8 0) status)
124 (ldb (byte 8 8) status)))
125 ((zerop (ldb (byte 7 0) status))
128 (ldb (byte 8 8) status)))
130 (let ((signal (ldb (byte 7 0) status)))
141 (not (zerop (ldb (byte 1 7) status)))))))))
143 ;;;; process control stuff
144 (defvar *active-processes* nil
146 "List of process structures for all active processes.")
148 (defvar *active-processes-lock*
149 (sb-thread:make-mutex :name "Lock for active processes."))
151 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
152 ;;; mutex is needed. More importantly the sigchld signal handler also
153 ;;; accesses it, that's why we need without-interrupts.
154 (defmacro with-active-processes-lock (() &body body)
155 `(sb-thread::with-system-mutex (*active-processes-lock*)
158 (defstruct (process (:copier nil))
159 pid ; PID of child process
160 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
161 %exit-code ; either exit code or signal
162 core-dumped ; T if a core image was dumped
163 #-win32 pty ; stream to child's pty, or NIL
164 input ; stream to child's input, or NIL
165 output ; stream from child's output, or NIL
166 error ; stream from child's error output, or NIL
167 status-hook ; closure to call when PROC changes status
168 plist ; a place for clients to stash things
169 cookie) ; list of the number of pipes from the subproc
171 (defmethod print-object ((process process) stream)
172 (print-unreadable-object (process stream :type t)
173 (let ((status (process-status process)))
174 (if (eq :exited status)
175 (format stream "~S ~S" status (process-%exit-code process))
176 (format stream "~S ~S" (process-pid process) status)))
180 (setf (documentation 'process-p 'function)
181 "T if OBJECT is a PROCESS, NIL otherwise.")
184 (setf (documentation 'process-pid 'function) "The pid of the child process.")
187 (define-alien-routine ("GetExitCodeProcess" get-exit-code-process)
189 (handle unsigned) (exit-code unsigned :out))
191 (defun process-exit-code (process)
193 "Return the exit code of PROCESS."
194 (or (process-%exit-code process)
195 (progn (get-processes-status-changes)
196 (process-%exit-code process))))
198 (defun process-status (process)
200 "Return the current status of PROCESS. The result is one of :RUNNING,
201 :STOPPED, :EXITED, or :SIGNALED."
202 (get-processes-status-changes)
203 (process-%status process))
206 (setf (documentation 'process-exit-code 'function)
207 "The exit code or the signal of a stopped process.")
210 (setf (documentation 'process-core-dumped 'function)
211 "T if a core image was dumped by the process.")
214 (setf (documentation 'process-pty 'function)
215 "The pty stream of the process or NIL.")
218 (setf (documentation 'process-input 'function)
219 "The input stream of the process or NIL.")
222 (setf (documentation 'process-output 'function)
223 "The output stream of the process or NIL.")
226 (setf (documentation 'process-error 'function)
227 "The error stream of the process or NIL.")
230 (setf (documentation 'process-status-hook 'function)
231 "A function that is called when PROCESS changes its status.
232 The function is called with PROCESS as its only argument.")
235 (setf (documentation 'process-plist 'function)
236 "A place for clients to stash things.")
238 (defun process-wait (process &optional check-for-stopped)
240 "Wait for PROCESS to quit running for some reason. When
241 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
243 (declare (ignorable check-for-stopped))
245 (let ((pid (process-pid process)))
246 (when (and pid (plusp pid))
250 (with-local-interrupts
251 (sb-win32:wait-object-or-signal pid))))))))
254 (case (process-status process)
257 (when check-for-stopped
260 (when (zerop (car (process-cookie process)))
262 (sb-sys:serve-all-events 1))
266 ;;; Find the current foreground process group id.
267 (defun find-current-foreground-process (proc)
268 (with-alien ((result sb-alien:int))
271 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
273 (alien-sap (sb-alien:addr result)))
275 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
280 (defun process-kill (process signal &optional (whom :pid))
282 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
283 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
284 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
285 currently in the foreground."
286 (let ((pid (ecase whom
287 ((:pid :process-group)
288 (process-pid process))
290 (find-current-foreground-process process)))))
295 (sb-unix:unix-killpg pid signal))
297 (sb-unix:unix-kill pid signal)))
300 ((and (eql pid (process-pid process))
301 (= signal sb-unix:sigcont))
302 (setf (process-%status process) :running)
303 (setf (process-%exit-code process) nil)
304 (when (process-status-hook process)
305 (funcall (process-status-hook process) process))
310 (defun process-alive-p (process)
312 "Return T if PROCESS is still alive, NIL otherwise."
313 (let ((status (process-status process)))
314 (if (or (eq status :running)
315 (eq status :stopped))
319 (defun process-close (process)
321 "Close all streams connected to PROCESS and stop maintaining the
323 (macrolet ((frob (stream abort)
324 `(when ,stream (close ,stream :abort ,abort))))
326 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
327 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
328 (frob (process-output process) nil)
329 (frob (process-error process) nil))
330 ;; FIXME: Given that the status-slot is no longer updated,
331 ;; maybe it should be set to :CLOSED, or similar?
332 (with-active-processes-lock ()
333 (setf *active-processes* (delete process *active-processes*)))
335 (let ((handle (shiftf (process-pid process) nil)))
336 (when (and handle (plusp handle))
337 (or (sb-win32:close-handle handle)
338 (sb-win32::win32-error 'process-close))))
341 (defun get-processes-status-changes ()
343 (with-active-processes-lock ()
344 (setf *active-processes*
347 ;; Wait only on pids belonging to processes
348 ;; started by RUN-PROGRAM. There used to be a
349 ;; WAIT3 call here, but that makes direct
350 ;; WAIT, WAITPID usage impossible due to the
351 ;; race with the SIGCHLD signal handler.
352 (multiple-value-bind (pid what code core)
353 (waitpid (process-pid proc) t t)
355 (setf (process-%status proc) what)
356 (setf (process-%exit-code proc) code)
357 (setf (process-core-dumped proc) core)
358 (when (process-status-hook proc)
363 (let ((pid (process-pid proc)))
365 (multiple-value-bind (ok code)
366 (sb-win32::get-exit-code-process pid)
367 (when (and (plusp ok) (/= code 259))
368 (setf (process-%status proc) :exited
369 (process-%exit-code proc) code)
370 (when (process-status-hook proc)
373 *active-processes*)))
374 ;; Can't call the hooks before all the processes have been deal
375 ;; with, as calling a hook may cause re-entry to
376 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using waitpid,
377 ;; but in the Windows implementation it would be deeply bad.
378 (dolist (proc exited)
379 (let ((hook (process-status-hook proc)))
381 (funcall hook proc))))))
383 ;;;; RUN-PROGRAM and close friends
385 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
386 (defvar *close-on-error* nil)
388 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
389 (defvar *close-in-parent* nil)
391 ;;; list of handlers installed by RUN-PROGRAM. FIXME: nothing seems
394 (defvar *handlers-installed* nil)
396 ;;; Find an unused pty. Return three values: the file descriptor for
397 ;;; the master side of the pty, the file descriptor for the slave side
398 ;;; of the pty, and the name of the tty device for the slave side.
401 (define-alien-routine ptsname c-string (fd int))
402 (define-alien-routine grantpt boolean (fd int))
403 (define-alien-routine unlockpt boolean (fd int))
406 ;; First try to use the Unix98 pty api.
407 (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
408 (master-fd (sb-unix:unix-open master-name
409 (logior sb-unix:o_rdwr
415 (let* ((slave-name (ptsname master-fd))
416 (slave-fd (sb-unix:unix-open slave-name
417 (logior sb-unix:o_rdwr
421 (return-from find-a-pty
425 (sb-unix:unix-close master-fd))
426 (error "could not find a pty")))
427 ;; No dice, try using the old-school method.
428 (dolist (char '(#\p #\q))
430 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
432 (master-fd (sb-unix:unix-open master-name
433 (logior sb-unix:o_rdwr
437 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
439 (slave-fd (sb-unix:unix-open slave-name
440 (logior sb-unix:o_rdwr
444 (return-from find-a-pty
448 (sb-unix:unix-close master-fd))))))
449 (error "could not find a pty")))
452 (define-alien-routine openpty int (amaster int :out) (aslave int :out)
453 (name (* char)) (termp (* t)) (winp (* t)))
455 (with-alien ((name-buf (array char 16)))
456 (multiple-value-bind (return-val master-fd slave-fd)
457 (openpty (cast name-buf (* char)) nil nil)
458 (if (zerop return-val)
461 (sb-alien::c-string-to-string (alien-sap name-buf)
462 (sb-impl::default-external-format)
464 (error "could not find a pty"))))))
467 (defun open-pty (pty cookie &key (external-format :default))
472 (push master *close-on-error*)
473 (push slave *close-in-parent*)
475 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
477 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
478 (push new-fd *close-on-error*)
479 (copy-descriptor-to-stream new-fd pty cookie external-format)))
481 (sb-sys:make-fd-stream master :input t :output t
482 :external-format external-format
483 :element-type :default
484 :dual-channel-p t)))))
486 ;; Null terminate strings only C-side: otherwise we can run into
487 ;; A-T-S-L even for simple encodings like ASCII. Multibyte encodings
488 ;; may need more than a single byte of zeros; assume 4 byte is enough
490 (defmacro round-null-terminated-bytes-to-words (n)
491 (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
492 `(logandc2 (the sb-vm:signed-word (+ (the fixnum ,n)
493 4 (1- ,bytes-per-word)))
494 (1- ,bytes-per-word))))
496 (defun string-list-to-c-strvec (string-list)
497 (let* ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))
498 ;; We need an extra for the null, and an extra 'cause exect
499 ;; clobbers argv[-1].
500 (vec-bytes (* bytes-per-word (+ (length string-list) 2)))
501 (octet-vector-list (mapcar (lambda (s)
502 (string-to-octets s))
504 (string-bytes (reduce #'+ octet-vector-list
506 (round-null-terminated-bytes-to-words
508 (total-bytes (+ string-bytes vec-bytes))
509 ;; Memory to hold the vector of pointers and all the strings.
510 (vec-sap (sb-sys:allocate-system-memory total-bytes))
511 (string-sap (sap+ vec-sap vec-bytes))
512 ;; Index starts from [1]!
513 (vec-index-offset bytes-per-word))
514 (declare (sb-vm:signed-word vec-bytes)
515 (sb-vm:word string-bytes total-bytes)
516 (sb-sys:system-area-pointer vec-sap string-sap))
517 (dolist (octets octet-vector-list)
518 (declare (type (simple-array (unsigned-byte 8) (*)) octets))
519 (let ((size (length octets)))
521 (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
523 (sb-kernel:system-area-ub8-fill 0 string-sap size 4)
524 ;; Put the pointer in the vector.
525 (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
526 ;; Advance string-sap for the next string.
527 (setf string-sap (sap+ string-sap
528 (round-null-terminated-bytes-to-words size)))
529 (incf vec-index-offset bytes-per-word)))
530 ;; Final null pointer.
531 (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
532 (values vec-sap (sap+ vec-sap bytes-per-word) total-bytes)))
534 (defmacro with-c-strvec ((var str-list &key null) &body body)
535 (once-only ((null null))
536 (with-unique-names (sap size)
537 `(multiple-value-bind (,sap ,var ,size)
539 (values nil (sb-sys:int-sap 0))
540 (string-list-to-c-strvec ,str-list))
545 (sb-sys:deallocate-system-memory ,sap ,size)))))))
547 (sb-alien:define-alien-routine spawn
549 #+win32 sb-win32::handle
550 (program sb-alien:c-string)
551 (argv (* sb-alien:c-string))
553 (stdout sb-alien:int)
554 (stderr sb-alien:int)
555 (search sb-alien:int)
556 (envp (* sb-alien:c-string))
557 (pty-name sb-alien:c-string)
560 ;;; FIXME: There shouldn't be two semiredundant versions of the
561 ;;; documentation. Since this is a public extension function, the
562 ;;; documentation should be in the doc string. So all information from
563 ;;; this comment should be merged into the doc string, and then this
564 ;;; comment can go away.
566 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
567 ;;; Strange stuff happens to keep the Unix state of the world
570 ;;; The child process needs to get its input from somewhere, and send
571 ;;; its output (both standard and error) to somewhere. We have to do
572 ;;; different things depending on where these somewheres really are.
574 ;;; For input, there are five options:
575 ;;; -- T: Just leave fd 0 alone. Pretty simple.
576 ;;; -- "file": Read from the file. We need to open the file and
577 ;;; pull the descriptor out of the stream. The parent should close
578 ;;; this stream after the child is up and running to free any
579 ;;; storage used in the parent.
580 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
581 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
582 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
583 ;;; writeable descriptor, and pass the readable descriptor to
584 ;;; the child. The parent must close the readable descriptor for
585 ;;; EOF to be passed up correctly.
586 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
587 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
588 ;;; everything across.
590 ;;; For output, there are five options:
591 ;;; -- T: Leave descriptor 1 alone.
592 ;;; -- "file": dump output to the file.
593 ;;; -- NIL: dump output to /dev/null.
594 ;;; -- :STREAM: return a stream that can be read from.
595 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
596 ;;; Otherwise, copy stuff from output to stream.
598 ;;; For error, there are all the same options as output plus:
599 ;;; -- :OUTPUT: redirect to the same place as output.
601 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
602 ;;; the fork worked, and NIL if it did not.
603 (defun run-program (program args
605 #-win32 (env nil env-p)
608 (unix-environment-sbcl-from-cmucl env))
614 if-input-does-not-exist
616 (if-output-exists :error)
618 (if-error-exists :error)
620 (external-format :default))
624 ;; The Texinfoizer is sensitive to whitespace, so mind the
625 ;; placement of the #-win32 pseudosplicings.
626 "RUN-PROGRAM creates a new process specified by the PROGRAM
627 argument. ARGS are the standard arguments that can be passed to a
628 program. For no arguments, use NIL (which means that just the
629 name of the program is passed as arg 0).
631 The program arguments and the environment are encoded using the
632 default external format for streams.
634 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
635 Users Manual for details about the PROCESS structure."#-win32"
637 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
639 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
640 programs, but unlike the original CMU CL implementation, copies
641 the Unix environment by default.
643 - Running Unix programs from a setuid process, or in any other
644 situation where the Unix environment is under the control of someone
645 else, is a mother lode of security problems. If you are contemplating
646 doing this, read about it first. (The Perl community has a lot of good
647 documentation about this and other security issues in script-like
650 The &KEY arguments have the following meanings:
653 a list of STRINGs describing the new Unix environment
654 (as in \"man environ\"). The default is to copy the environment of
657 an alternative lossy representation of the new Unix environment,
658 for compatibility with CMU CL""
660 Look for PROGRAM in each of the directories in the child's $PATH
661 environment variable. Otherwise an absolute pathname is required.
663 If non-NIL (default), wait until the created process finishes. If
664 NIL, continue running Lisp until the program finishes."#-win32"
666 Either T, NIL, or a stream. Unless NIL, the subprocess is established
667 under a PTY. If :pty is a stream, all output to this pty is sent to
668 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
669 connected to pty that can read output and write input.""
671 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
672 input for the current process is inherited. If NIL, "
673 #-win32"/dev/null"#+win32"nul""
674 is used. If a pathname, the file so specified is used. If a stream,
675 all the input is read from that stream and sent to the subprocess. If
676 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
677 its output to the process. Defaults to NIL.
678 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
680 :ERROR to generate an error
681 :CREATE to create an empty file
682 NIL (the default) to return NIL from RUN-PROGRAM
684 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
685 output for the current process is inherited. If NIL, "
686 #-win32"/dev/null"#+win32"nul""
687 is used. If a pathname, the file so specified is used. If a stream,
688 all the output from the process is written to this stream. If
689 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
690 be read to get the output. Defaults to NIL.
691 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
693 :ERROR (the default) to generate an error
694 :SUPERSEDE to supersede the file with output from the program
695 :APPEND to append output from the program to the file
696 NIL to return NIL from RUN-PROGRAM, without doing anything
697 :ERROR and :IF-ERROR-EXISTS
698 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
699 specified as :OUTPUT in which case all error output is routed to the
700 same place as normal output.
702 This is a function the system calls whenever the status of the
703 process changes. The function takes the process as an argument.
705 The external-format to use for :INPUT, :OUTPUT, and :ERROR :STREAMs.")
707 (when (and env-p environment-p)
708 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
709 ;; Prepend the program to the argument list.
710 (push (namestring program) args)
711 (labels (;; It's friendly to allow the caller to pass any string
712 ;; designator, but internally we'd like SIMPLE-STRINGs.
714 ;; Huh? We let users pass in symbols and characters for
715 ;; the arguments, but call NAMESTRING on the program
717 (simplify-args (args)
718 (loop for arg in args
719 as escaped-arg = (escape-arg arg)
720 collect (coerce escaped-arg 'simple-string)))
723 ;; Apparently any spaces or double quotes in the arguments
724 ;; need to be escaped on win32.
725 #+win32 (if (position-if
726 (lambda (c) (find c '(#\" #\Space))) arg)
727 (write-to-string arg)
729 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
730 ;; communicate cleanup info.
733 ;; Some other binding used only on non-Win32. FIXME:
734 ;; nothing seems to set this.
735 #-win32 *handlers-installed*
736 ;; Establish PROC at this level so that we can return it.
738 (simple-args (simplify-args args))
739 (progname (native-namestring program))
743 ;; Note: despite the WITH-* names, these macros don't
744 ;; expand into UNWIND-PROTECT forms. They're just
745 ;; syntactic sugar to make the rest of the routine slightly
747 (macrolet ((with-no-with
749 (&whole form with-something parameters &body body))
750 (declare (ignore with-something parameters))
752 (keyword `(progn ,@body))
754 (t `(let ,no (declare (ignorable ,@no)) ,@body))))
755 (with-fd-and-stream-for (((fd stream) which &rest args)
757 `(multiple-value-bind (,fd ,stream)
760 `(get-descriptor-for ,@args))
762 `(if (eq ,(first args) :output)
763 ;; kludge: we expand into
764 ;; hard-coded symbols here.
765 (values stdout output-stream)
766 (get-descriptor-for ,@args))))
768 (return-from run-program))
770 (with-open-pty (((pty-name pty-stream) (pty cookie))
772 `(multiple-value-bind (,pty-name ,pty-stream)
773 (open-pty ,pty ,cookie :external-format external-format)
775 (with-args-vec ((vec args) &body body)
776 `(with-c-strvec (,vec ,args)
778 (with-environment-vec ((vec) &body body)
779 #+win32 `(let (,vec) ,@body)
783 :null (not (or environment environment-p)))
785 (with-fd-and-stream-for ((stdin input-stream) :input
788 :if-does-not-exist if-input-does-not-exist
789 :external-format external-format
791 (with-fd-and-stream-for ((stdout output-stream) :output
794 :if-exists if-output-exists
795 :external-format external-format)
796 (with-fd-and-stream-for ((stderr error-stream) :error
799 :if-exists if-error-exists
800 :external-format external-format)
801 (with-no-with (#+win32 (pty-name pty-stream))
802 (with-open-pty ((pty-name pty-stream) (pty cookie))
803 ;; Make sure we are not notified about the child
804 ;; death before we have installed the PROCESS
805 ;; structure in *ACTIVE-PROCESSES*.
807 (with-active-processes-lock ()
808 (with-no-with (#+win32 (args-vec))
809 (with-args-vec (args-vec simple-args)
810 (with-no-with (#+win32 (environment-vec))
811 (with-environment-vec (environment-vec)
814 (sb-win32::mswin-spawn
816 (with-output-to-string (argv)
817 (dolist (arg simple-args)
818 (write-string arg argv)
819 (write-char #\Space argv)))
824 (spawn progname args-vec
827 environment-vec pty-name
829 (unless (minusp child)
834 :output output-stream
836 :status-hook status-hook
838 #-win32 (list :pty pty-stream
842 (list :%status :exited
844 (list :%status :running
846 (push proc *active-processes*)))))))
847 ;; Report the error outside the lock.
850 (error "Couldn't execute ~S: ~A" progname (strerror)))
852 (error "Couldn't fork child process: ~A" (strerror)))))))))))
853 (dolist (fd *close-in-parent*)
854 (sb-unix:unix-close fd))
856 (dolist (fd *close-on-error*)
857 (sb-unix:unix-close fd))
859 (dolist (handler *handlers-installed*)
860 (sb-sys:remove-fd-handler handler)))
862 (when (and wait proc)
865 (dolist (handler *handlers-installed*)
866 (sb-sys:remove-fd-handler handler)))))
869 ;;; Install a handler for any input that shows up on the file
870 ;;; descriptor. The handler reads the data and writes it to the
872 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
875 (buf (make-array 256 :element-type '(unsigned-byte 8)))
877 (et (stream-element-type stream))
880 ((member et '(character base-char))
882 (let* ((decode-end read-end)
883 (string (handler-case
886 :external-format external-format)
887 (end-of-input-in-character (e)
889 (octet-decoding-error-start e))
892 :external-format external-format)))))
893 (unless (zerop (length string))
894 (write-string string stream)
895 (when (/= decode-end (length buf))
896 (replace buf buf :start2 decode-end :end2 read-end))
897 (decf read-end decode-end)))))
898 ((member et '(:default (unsigned-byte 8)) :test #'equal)
900 (write-sequence buf stream :end read-end)
904 (error "Don't know how to copy to stream of element-type ~S"
907 (sb-sys:add-fd-handler
911 (declare (ignore fd))
916 (result readable/errno)
917 (sb-unix:unix-select (1+ descriptor)
921 (if (eql sb-unix:eintr readable/errno)
923 (error "~@<Couldn't select on sub-process: ~
925 (strerror readable/errno))))
928 (multiple-value-bind (count errno)
929 (with-pinned-objects (buf)
930 (sb-unix:unix-read descriptor
931 (sap+ (vector-sap buf) read-end)
932 (- (length buf) read-end)))
934 ((and #-win32 (or (and (null count)
935 (eql errno sb-unix:eio))
937 #+win32 (<= count 0))
938 (sb-sys:remove-fd-handler handler)
941 (sb-unix:unix-close descriptor)
942 (unless (zerop read-end)
943 ;; Should this be an END-OF-FILE?
944 (error "~@<non-empty buffer when EOF reached ~
945 while reading from child: ~S~:>" buf))
948 (sb-sys:remove-fd-handler handler)
952 "~@<couldn't read input from sub-process: ~
956 (incf read-end count)
957 (funcall copy-fun))))))))
959 (push handler *handlers-installed*)))
961 ;;; FIXME: something very like this is done in SB-POSIX to treat
962 ;;; streams as file descriptor designators; maybe we can combine these
963 ;;; two? Additionally, as we have a couple of user-defined streams
964 ;;; libraries, maybe we should have a generic function for doing this,
965 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
966 ;;; maybe also with SB-POSIX)?
967 (defun get-stream-fd-and-external-format (stream direction)
970 (values (sb-sys:fd-stream-fd stream) nil (stream-external-format stream)))
972 (get-stream-fd-and-external-format
973 (symbol-value (synonym-stream-symbol stream)) direction))
977 (get-stream-fd-and-external-format
978 (two-way-stream-input-stream stream) direction))
980 (get-stream-fd-and-external-format
981 (two-way-stream-output-stream stream) direction))))))
983 (defun get-temporary-directory ()
984 #-win32 (or (sb-ext:posix-getenv "TMPDIR")
986 #+win32 (or (sb-ext:posix-getenv "TEMP")
990 ;;; Find a file descriptor to use for object given the direction.
991 ;;; Returns the descriptor. If object is :STREAM, returns the created
992 ;;; stream as the second value.
993 (defun get-descriptor-for (object
996 &key direction (external-format :default) wait
998 (declare (ignore wait)) ;This is explained below.
999 ;; Our use of a temporary file dates back to very old CMUCLs, and
1000 ;; was probably only ever intended for use with STRING-STREAMs,
1001 ;; which are ordinarily smallish. However, as we've got
1002 ;; user-defined stream classes, we can end up trying to copy
1003 ;; arbitrarily much data into the temp file, and so are liable to
1004 ;; run afoul of disk quotas or to choke on small /tmp file systems.
1005 (flet ((make-temp-fd ()
1006 (multiple-value-bind (fd name/errno)
1007 (sb-unix:sb-mkstemp (format nil "~a/.run-program-XXXXXX"
1008 (get-temporary-directory))
1011 (error "could not open a temporary file: ~A"
1012 (strerror name/errno)))
1013 ;; Can't unlink an opened file on Windows
1015 (unless (sb-unix:unix-unlink name/errno)
1016 (sb-unix:unix-close fd)
1017 (error "failed to unlink ~A" name/errno))
1019 (let ((dev-null #.(coerce #-win32 "/dev/null" #+win32 "nul" 'base-string)))
1020 (cond ((eq object t)
1021 ;; No new descriptor is needed.
1023 ((or (eq object nil)
1024 (and (typep object 'broadcast-stream)
1025 (not (broadcast-stream-streams object))))
1027 (multiple-value-bind
1029 (sb-unix:unix-open dev-null
1031 (:input sb-unix:o_rdonly)
1032 (:output sb-unix:o_wronly)
1036 (error "~@<couldn't open ~S: ~2I~_~A~:>"
1037 dev-null (strerror errno)))
1039 (setf (sb-win32::inheritable-handle-p fd) t)
1040 (push fd *close-in-parent*)
1042 ((eq object :stream)
1043 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
1045 (error "couldn't create pipe: ~A" (strerror write-fd)))
1047 (setf (sb-win32::inheritable-handle-p read-fd)
1048 (eq direction :input)
1049 (sb-win32::inheritable-handle-p write-fd)
1050 (eq direction :output))
1053 (push read-fd *close-in-parent*)
1054 (push write-fd *close-on-error*)
1055 (let ((stream (sb-sys:make-fd-stream write-fd :output t
1056 :element-type :default
1059 (values read-fd stream)))
1061 (push read-fd *close-on-error*)
1062 (push write-fd *close-in-parent*)
1063 (let ((stream (sb-sys:make-fd-stream read-fd :input t
1064 :element-type :default
1067 (values write-fd stream)))
1069 (sb-unix:unix-close read-fd)
1070 (sb-unix:unix-close write-fd)
1071 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
1073 ((or (pathnamep object) (stringp object))
1074 ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
1075 ;; than munge the &rest list for OPEN, just disable keyword
1076 ;; validation there.
1077 (with-open-stream (file (apply #'open object :allow-other-keys t
1080 (multiple-value-bind
1082 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
1084 (push fd *close-in-parent*)
1087 (error "couldn't duplicate file descriptor: ~A"
1088 (strerror errno))))))))
1093 ;; If we can get an fd for the stream, let the child
1094 ;; process use the fd for its descriptor. Otherwise,
1095 ;; we copy data from the stream into a temp file, and
1096 ;; give the temp file's descriptor to the
1098 (multiple-value-bind (fd stream format)
1099 (get-stream-fd-and-external-format object :input)
1100 (declare (ignore format))
1102 (return (values fd stream))))
1103 ;; FIXME: if we can't get the file descriptor, since
1104 ;; the stream might be interactive or otherwise
1105 ;; block-y, we can't know whether we can copy the
1106 ;; stream's data to a temp file, so if RUN-PROGRAM was
1107 ;; called with :WAIT NIL, we should probably error.
1108 ;; However, STRING-STREAMs aren't fd-streams, but
1109 ;; they're not prone to blocking; any user-defined
1110 ;; streams that "read" from some in-memory data will
1111 ;; probably be similar to STRING-STREAMs. So maybe we
1112 ;; should add a STREAM-INTERACTIVE-P generic function
1113 ;; for problems like this? Anyway, the machinery is
1114 ;; here, if you feel like filling in the details.
1116 (when (and (null wait) #<some undetermined criterion>)
1117 (error "~@<don't know how to get an fd for ~A, and so ~
1118 can't ensure that copying its data to the ~
1119 child process won't hang~:>" object))
1121 (let ((fd (make-temp-fd))
1122 (et (stream-element-type object)))
1123 (cond ((member et '(character base-char))
1125 (multiple-value-bind
1127 (read-line object nil nil)
1130 (let ((vector (string-to-octets
1132 :external-format external-format)))
1134 fd vector 0 (length vector)))
1138 fd #.(string #\Newline) 0 1)))))
1139 ((member et '(:default (unsigned-byte 8))
1141 (loop with buf = (make-array 256 :element-type '(unsigned-byte 8))
1142 for p = (read-sequence buf object)
1144 do (sb-unix:unix-write fd buf 0 p)))
1146 (error "Don't know how to copy from stream of element-type ~S"
1148 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1149 (push fd *close-in-parent*)
1150 (return (values fd nil)))))
1153 ;; Similar to the :input trick above, except we
1154 ;; arrange to copy data from the stream. This is
1155 ;; slightly saner than the input case, since we don't
1156 ;; buffer to a file, but I think we may still lose if
1157 ;; there's unflushed data in the stream buffer and we
1158 ;; give the file descriptor to the child.
1159 (multiple-value-bind (fd stream format)
1160 (get-stream-fd-and-external-format object :output)
1161 (declare (ignore format))
1163 (return (values fd stream))))
1164 (multiple-value-bind (read-fd write-fd)
1167 (error "couldn't create pipe: ~S" (strerror write-fd)))
1168 (copy-descriptor-to-stream read-fd object cookie
1170 (push read-fd *close-on-error*)
1171 (push write-fd *close-in-parent*)
1172 (return (values write-fd nil)))))
1174 (error "invalid option to RUN-PROGRAM: ~S" object))))))))