Merge from emacs-24; up to 2012-11-24T16:58:43Z!cyd@gnu.org
[emacs.git] / src / callproc.c
blob6153bc1b6c6cb6b87fc9eba3820bdd18b424527e
1 /* Synchronous subprocess invocation for GNU Emacs.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2012
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <unistd.h>
27 #include <sys/file.h>
28 #include <fcntl.h>
30 #include "lisp.h"
32 #ifdef WINDOWSNT
33 #define NOMINMAX
34 #include <windows.h>
35 #include "w32.h"
36 #define _P_NOWAIT 1 /* from process.h */
37 #endif
39 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
40 #include <sys/stat.h>
41 #include <sys/param.h>
42 #endif /* MSDOS */
44 #include "commands.h"
45 #include "character.h"
46 #include "buffer.h"
47 #include "ccl.h"
48 #include "coding.h"
49 #include "composite.h"
50 #include <epaths.h>
51 #include "process.h"
52 #include "syssignal.h"
53 #include "systty.h"
54 #include "syswait.h"
55 #include "blockinput.h"
56 #include "frame.h"
57 #include "termhooks.h"
59 #ifdef MSDOS
60 #include "msdos.h"
61 #endif
63 #ifdef HAVE_NS
64 #include "nsterm.h"
65 #endif
67 /* Pattern used by call-process-region to make temp files. */
68 static Lisp_Object Vtemp_file_name_pattern;
70 /* The next two variables are valid only while record-unwind-protect
71 is in place during call-process for a synchronous subprocess. At
72 other times, their contents are irrelevant. Doing this via static
73 C variables is more convenient than putting them into the arguments
74 of record-unwind-protect, as they need to be updated at randomish
75 times in the code, and Lisp cannot always store these values as
76 Emacs integers. It's safe to use static variables here, as the
77 code is never invoked reentrantly. */
79 /* If nonzero, a process-ID that has not been reaped. */
80 static pid_t synch_process_pid;
82 /* If nonnegative, a file descriptor that has not been closed. */
83 static int synch_process_fd;
85 /* Block SIGCHLD. */
87 static void
88 block_child_signal (void)
90 #ifdef SIGCHLD
91 sigset_t blocked;
92 sigemptyset (&blocked);
93 sigaddset (&blocked, SIGCHLD);
94 pthread_sigmask (SIG_BLOCK, &blocked, 0);
95 #endif
98 /* Unblock SIGCHLD. */
100 static void
101 unblock_child_signal (void)
103 #ifdef SIGCHLD
104 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
105 #endif
108 /* Clean up when exiting call_process_cleanup. */
110 static Lisp_Object
111 call_process_kill (Lisp_Object ignored)
113 if (0 <= synch_process_fd)
114 emacs_close (synch_process_fd);
116 /* If PID is reapable, kill it and record it as a deleted process.
117 Do this in a critical section. Unless PID is wedged it will be
118 reaped on receipt of the first SIGCHLD after the critical section. */
119 if (synch_process_pid)
121 block_child_signal ();
122 record_deleted_pid (synch_process_pid);
123 EMACS_KILLPG (synch_process_pid, SIGKILL);
124 unblock_child_signal ();
127 return Qnil;
130 /* Clean up when exiting Fcall_process.
131 On MSDOS, delete the temporary file on any kind of termination.
132 On Unix, kill the process and any children on termination by signal. */
134 static Lisp_Object
135 call_process_cleanup (Lisp_Object arg)
137 #ifdef MSDOS
138 Lisp_Object buffer = Fcar (arg);
139 Lisp_Object file = Fcdr (arg);
140 #else
141 Lisp_Object buffer = arg;
142 #endif
144 Fset_buffer (buffer);
146 #ifndef MSDOS
147 /* If the process still exists, kill its process group. */
148 if (synch_process_pid)
150 ptrdiff_t count = SPECPDL_INDEX ();
151 EMACS_KILLPG (synch_process_pid, SIGINT);
152 record_unwind_protect (call_process_kill, make_number (0));
153 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
154 immediate_quit = 1;
155 QUIT;
156 wait_for_termination (synch_process_pid, 0, 1);
157 synch_process_pid = 0;
158 immediate_quit = 0;
159 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
160 message1 ("Waiting for process to die...done");
162 #endif
164 if (0 <= synch_process_fd)
165 emacs_close (synch_process_fd);
167 #ifdef MSDOS
168 /* FILE is "" when we didn't actually create a temporary file in
169 call-process. */
170 if (!(strcmp (SDATA (file), NULL_DEVICE) == 0 || SREF (file, 0) == '\0'))
171 unlink (SDATA (file));
172 #endif
174 return Qnil;
177 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
178 doc: /* Call PROGRAM synchronously in separate process.
179 The remaining arguments are optional.
180 The program's input comes from file INFILE (nil means `/dev/null').
181 Insert output in BUFFER before point; t means current buffer; nil for BUFFER
182 means discard it; 0 means discard and don't wait; and `(:file FILE)', where
183 FILE is a file name string, means that it should be written to that file
184 \(if the file already exists it is overwritten).
185 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
186 REAL-BUFFER says what to do with standard output, as above,
187 while STDERR-FILE says what to do with standard error in the child.
188 STDERR-FILE may be nil (discard standard error output),
189 t (mix it with ordinary output), or a file name string.
191 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
192 Remaining arguments are strings passed as command arguments to PROGRAM.
194 If executable PROGRAM can't be found as an executable, `call-process'
195 signals a Lisp error. `call-process' reports errors in execution of
196 the program only through its return and output.
198 If BUFFER is 0, `call-process' returns immediately with value nil.
199 Otherwise it waits for PROGRAM to terminate
200 and returns a numeric exit status or a signal description string.
201 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
203 usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
204 (ptrdiff_t nargs, Lisp_Object *args)
206 Lisp_Object infile, buffer, current_dir, path;
207 bool display_p;
208 int fd0, fd1, filefd;
209 int status;
210 ptrdiff_t count = SPECPDL_INDEX ();
211 USE_SAFE_ALLOCA;
213 char **new_argv;
214 /* File to use for stderr in the child.
215 t means use same as standard output. */
216 Lisp_Object error_file;
217 Lisp_Object output_file = Qnil;
218 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
219 char *outf, *tempfile = NULL;
220 int outfilefd;
221 int pid;
222 #else
223 pid_t pid;
224 #endif
225 int child_errno;
226 int fd_output = -1;
227 struct coding_system process_coding; /* coding-system of process output */
228 struct coding_system argument_coding; /* coding-system of arguments */
229 /* Set to the return value of Ffind_operation_coding_system. */
230 Lisp_Object coding_systems;
231 bool output_to_buffer = 1;
233 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
234 coding_systems = Qt;
236 CHECK_STRING (args[0]);
238 error_file = Qt;
240 #ifndef subprocesses
241 /* Without asynchronous processes we cannot have BUFFER == 0. */
242 if (nargs >= 3
243 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
244 error ("Operating system cannot handle asynchronous subprocesses");
245 #endif /* subprocesses */
247 /* Decide the coding-system for giving arguments. */
249 Lisp_Object val, *args2;
250 ptrdiff_t i;
252 /* If arguments are supplied, we may have to encode them. */
253 if (nargs >= 5)
255 bool must_encode = 0;
256 Lisp_Object coding_attrs;
258 for (i = 4; i < nargs; i++)
259 CHECK_STRING (args[i]);
261 for (i = 4; i < nargs; i++)
262 if (STRING_MULTIBYTE (args[i]))
263 must_encode = 1;
265 if (!NILP (Vcoding_system_for_write))
266 val = Vcoding_system_for_write;
267 else if (! must_encode)
268 val = Qraw_text;
269 else
271 SAFE_NALLOCA (args2, 1, nargs + 1);
272 args2[0] = Qcall_process;
273 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
274 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
275 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
277 val = complement_process_encoding_system (val);
278 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
279 coding_attrs = CODING_ID_ATTRS (argument_coding.id);
280 if (NILP (CODING_ATTR_ASCII_COMPAT (coding_attrs)))
282 /* We should not use an ASCII incompatible coding system. */
283 val = raw_text_coding_system (val);
284 setup_coding_system (val, &argument_coding);
289 if (nargs >= 2 && ! NILP (args[1]))
291 infile = Fexpand_file_name (args[1], BVAR (current_buffer, directory));
292 CHECK_STRING (infile);
294 else
295 infile = build_string (NULL_DEVICE);
297 if (nargs >= 3)
299 buffer = args[2];
301 /* If BUFFER is a list, its meaning is (BUFFER-FOR-STDOUT
302 FILE-FOR-STDERR), unless the first element is :file, in which case see
303 the next paragraph. */
304 if (CONSP (buffer)
305 && (! SYMBOLP (XCAR (buffer))
306 || strcmp (SSDATA (SYMBOL_NAME (XCAR (buffer))), ":file")))
308 if (CONSP (XCDR (buffer)))
310 Lisp_Object stderr_file;
311 stderr_file = XCAR (XCDR (buffer));
313 if (NILP (stderr_file) || EQ (Qt, stderr_file))
314 error_file = stderr_file;
315 else
316 error_file = Fexpand_file_name (stderr_file, Qnil);
319 buffer = XCAR (buffer);
322 /* If the buffer is (still) a list, it might be a (:file "file") spec. */
323 if (CONSP (buffer)
324 && SYMBOLP (XCAR (buffer))
325 && ! strcmp (SSDATA (SYMBOL_NAME (XCAR (buffer))), ":file"))
327 output_file = Fexpand_file_name (XCAR (XCDR (buffer)),
328 BVAR (current_buffer, directory));
329 CHECK_STRING (output_file);
330 buffer = Qnil;
333 if (!(EQ (buffer, Qnil)
334 || EQ (buffer, Qt)
335 || INTEGERP (buffer)))
337 Lisp_Object spec_buffer;
338 spec_buffer = buffer;
339 buffer = Fget_buffer_create (buffer);
340 /* Mention the buffer name for a better error message. */
341 if (NILP (buffer))
342 CHECK_BUFFER (spec_buffer);
343 CHECK_BUFFER (buffer);
346 else
347 buffer = Qnil;
349 /* Make sure that the child will be able to chdir to the current
350 buffer's current directory, or its unhandled equivalent. We
351 can't just have the child check for an error when it does the
352 chdir, since it's in a vfork.
354 We have to GCPRO around this because Fexpand_file_name,
355 Funhandled_file_name_directory, and Ffile_accessible_directory_p
356 might call a file name handling function. The argument list is
357 protected by the caller, so all we really have to worry about is
358 buffer. */
360 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
362 current_dir = BVAR (current_buffer, directory);
364 GCPRO5 (infile, buffer, current_dir, error_file, output_file);
366 current_dir = Funhandled_file_name_directory (current_dir);
367 if (NILP (current_dir))
368 /* If the file name handler says that current_dir is unreachable, use
369 a sensible default. */
370 current_dir = build_string ("~/");
371 current_dir = expand_and_dir_to_file (current_dir, Qnil);
372 current_dir = Ffile_name_as_directory (current_dir);
374 if (NILP (Ffile_accessible_directory_p (current_dir)))
375 report_file_error ("Setting current directory",
376 Fcons (BVAR (current_buffer, directory), Qnil));
378 if (STRING_MULTIBYTE (infile))
379 infile = ENCODE_FILE (infile);
380 if (STRING_MULTIBYTE (current_dir))
381 current_dir = ENCODE_FILE (current_dir);
382 if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
383 error_file = ENCODE_FILE (error_file);
384 if (STRINGP (output_file) && STRING_MULTIBYTE (output_file))
385 output_file = ENCODE_FILE (output_file);
386 UNGCPRO;
389 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
391 filefd = emacs_open (SSDATA (infile), O_RDONLY, 0);
392 if (filefd < 0)
394 infile = DECODE_FILE (infile);
395 report_file_error ("Opening process input file", Fcons (infile, Qnil));
398 if (STRINGP (output_file))
400 #ifdef DOS_NT
401 fd_output = emacs_open (SSDATA (output_file),
402 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
403 S_IREAD | S_IWRITE);
404 #else /* not DOS_NT */
405 fd_output = creat (SSDATA (output_file), 0666);
406 #endif /* not DOS_NT */
407 if (fd_output < 0)
409 output_file = DECODE_FILE (output_file);
410 report_file_error ("Opening process output file",
411 Fcons (output_file, Qnil));
413 if (STRINGP (error_file) || NILP (error_file))
414 output_to_buffer = 0;
417 /* Search for program; barf if not found. */
419 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
421 GCPRO4 (infile, buffer, current_dir, error_file);
422 openp (Vexec_path, args[0], Vexec_suffixes, &path, make_number (X_OK));
423 UNGCPRO;
425 if (NILP (path))
427 emacs_close (filefd);
428 report_file_error ("Searching for program", Fcons (args[0], Qnil));
431 /* If program file name starts with /: for quoting a magic name,
432 discard that. */
433 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
434 && SREF (path, 1) == ':')
435 path = Fsubstring (path, make_number (2), Qnil);
437 new_argv = SAFE_ALLOCA ((nargs > 4 ? nargs - 2 : 2) * sizeof *new_argv);
438 if (nargs > 4)
440 ptrdiff_t i;
441 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
443 GCPRO5 (infile, buffer, current_dir, path, error_file);
444 argument_coding.dst_multibyte = 0;
445 for (i = 4; i < nargs; i++)
447 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
448 if (CODING_REQUIRE_ENCODING (&argument_coding))
449 /* We must encode this argument. */
450 args[i] = encode_coding_string (&argument_coding, args[i], 1);
452 UNGCPRO;
453 for (i = 4; i < nargs; i++)
454 new_argv[i - 3] = SSDATA (args[i]);
455 new_argv[i - 3] = 0;
457 else
458 new_argv[1] = 0;
459 new_argv[0] = SSDATA (path);
461 #ifdef MSDOS /* MW, July 1993 */
463 /* If we're redirecting STDOUT to a file, that file is already open
464 on fd_output. */
465 if (fd_output < 0)
467 if ((outf = egetenv ("TMPDIR")))
468 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
469 else
471 tempfile = alloca (20);
472 *tempfile = '\0';
474 dostounix_filename (tempfile);
475 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
476 strcat (tempfile, "/");
477 strcat (tempfile, "detmp.XXX");
478 mktemp (tempfile);
479 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
480 if (outfilefd < 0) {
481 emacs_close (filefd);
482 report_file_error ("Opening process output file",
483 Fcons (build_string (tempfile), Qnil));
486 else
487 outfilefd = fd_output;
488 fd0 = filefd;
489 fd1 = outfilefd;
490 #endif /* MSDOS */
492 if (INTEGERP (buffer))
494 fd0 = -1;
495 fd1 = emacs_open (NULL_DEVICE, O_WRONLY, 0);
497 else
499 #ifndef MSDOS
500 int fd[2];
501 if (pipe (fd) == -1)
503 int pipe_errno = errno;
504 emacs_close (filefd);
505 errno = pipe_errno;
506 report_file_error ("Creating process pipe", Qnil);
508 fd0 = fd[0];
509 fd1 = fd[1];
510 #endif
514 int fd_error = fd1;
516 if (fd_output >= 0)
517 fd1 = fd_output;
519 if (NILP (error_file))
520 fd_error = emacs_open (NULL_DEVICE, O_WRONLY, 0);
521 else if (STRINGP (error_file))
523 #ifdef DOS_NT
524 fd_error = emacs_open (SSDATA (error_file),
525 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
526 S_IREAD | S_IWRITE);
527 #else /* not DOS_NT */
528 fd_error = creat (SSDATA (error_file), 0666);
529 #endif /* not DOS_NT */
532 if (fd_error < 0)
534 emacs_close (filefd);
535 if (fd0 != filefd)
536 emacs_close (fd0);
537 if (fd1 >= 0)
538 emacs_close (fd1);
539 #ifdef MSDOS
540 unlink (tempfile);
541 #endif
542 if (NILP (error_file))
543 error_file = build_string (NULL_DEVICE);
544 else if (STRINGP (error_file))
545 error_file = DECODE_FILE (error_file);
546 report_file_error ("Cannot redirect stderr", Fcons (error_file, Qnil));
549 #ifdef MSDOS /* MW, July 1993 */
550 /* Note that on MSDOS `child_setup' actually returns the child process
551 exit status, not its PID, so assign it to status below. */
552 pid = child_setup (filefd, outfilefd, fd_error, new_argv, 0, current_dir);
553 child_errno = errno;
555 emacs_close (outfilefd);
556 if (fd_error != outfilefd)
557 emacs_close (fd_error);
558 if (pid < 0)
560 synchronize_system_messages_locale ();
561 return
562 code_convert_string_norecord (build_string (strerror (child_errno)),
563 Vlocale_coding_system, 0);
565 status = pid;
566 fd1 = -1; /* No harm in closing that one! */
567 if (tempfile)
569 /* Since CRLF is converted to LF within `decode_coding', we
570 can always open a file with binary mode. */
571 fd0 = emacs_open (tempfile, O_RDONLY | O_BINARY, 0);
572 if (fd0 < 0)
574 unlink (tempfile);
575 emacs_close (filefd);
576 report_file_error ("Cannot re-open temporary file",
577 Fcons (build_string (tempfile), Qnil));
580 else
581 fd0 = -1; /* We are not going to read from tempfile. */
582 #endif /* MSDOS */
584 /* Do the unwind-protect now, even though the pid is not known, so
585 that no storage allocation is done in the critical section.
586 The actual PID will be filled in during the critical section. */
587 synch_process_pid = 0;
588 synch_process_fd = fd0;
590 #ifdef MSDOS
591 /* MSDOS needs different cleanup information. */
592 record_unwind_protect (call_process_cleanup,
593 Fcons (Fcurrent_buffer (),
594 build_string (tempfile ? tempfile : "")));
595 #else
596 record_unwind_protect (call_process_cleanup, Fcurrent_buffer ());
598 block_input ();
599 block_child_signal ();
601 #ifdef WINDOWSNT
602 pid = child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
603 #else /* not WINDOWSNT */
605 /* vfork, and prevent local vars from being clobbered by the vfork. */
607 Lisp_Object volatile buffer_volatile = buffer;
608 Lisp_Object volatile coding_systems_volatile = coding_systems;
609 Lisp_Object volatile current_dir_volatile = current_dir;
610 bool volatile display_p_volatile = display_p;
611 bool volatile output_to_buffer_volatile = output_to_buffer;
612 bool volatile sa_must_free_volatile = sa_must_free;
613 int volatile fd1_volatile = fd1;
614 int volatile fd_error_volatile = fd_error;
615 int volatile fd_output_volatile = fd_output;
616 int volatile filefd_volatile = filefd;
617 ptrdiff_t volatile count_volatile = count;
618 ptrdiff_t volatile sa_count_volatile = sa_count;
619 char **volatile new_argv_volatile = new_argv;
621 pid = vfork ();
622 child_errno = errno;
624 buffer = buffer_volatile;
625 coding_systems = coding_systems_volatile;
626 current_dir = current_dir_volatile;
627 display_p = display_p_volatile;
628 output_to_buffer = output_to_buffer_volatile;
629 sa_must_free = sa_must_free_volatile;
630 fd1 = fd1_volatile;
631 fd_error = fd_error_volatile;
632 fd_output = fd_output_volatile;
633 filefd = filefd_volatile;
634 count = count_volatile;
635 sa_count = sa_count_volatile;
636 new_argv = new_argv_volatile;
638 fd0 = synch_process_fd;
641 if (pid == 0)
643 unblock_child_signal ();
645 if (fd0 >= 0)
646 emacs_close (fd0);
648 setsid ();
650 /* Emacs ignores SIGPIPE, but the child should not. */
651 signal (SIGPIPE, SIG_DFL);
653 child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
656 #endif /* not WINDOWSNT */
658 child_errno = errno;
660 if (0 < pid)
662 if (INTEGERP (buffer))
663 record_deleted_pid (pid);
664 else
665 synch_process_pid = pid;
668 unblock_child_signal ();
669 unblock_input ();
671 /* The MSDOS case did this already. */
672 if (fd_error >= 0)
673 emacs_close (fd_error);
674 #endif /* not MSDOS */
676 /* Close most of our file descriptors, but not fd0
677 since we will use that to read input from. */
678 emacs_close (filefd);
679 if (fd_output >= 0)
680 emacs_close (fd_output);
681 if (fd1 >= 0 && fd1 != fd_error)
682 emacs_close (fd1);
685 if (pid < 0)
687 errno = child_errno;
688 report_file_error ("Doing vfork", Qnil);
691 if (INTEGERP (buffer))
692 return unbind_to (count, Qnil);
694 if (BUFFERP (buffer))
695 Fset_buffer (buffer);
697 if (NILP (buffer))
699 /* If BUFFER is nil, we must read process output once and then
700 discard it, so setup coding system but with nil. */
701 setup_coding_system (Qnil, &process_coding);
702 process_coding.dst_multibyte = 0;
704 else
706 Lisp_Object val, *args2;
708 val = Qnil;
709 if (!NILP (Vcoding_system_for_read))
710 val = Vcoding_system_for_read;
711 else
713 if (EQ (coding_systems, Qt))
715 ptrdiff_t i;
717 SAFE_NALLOCA (args2, 1, nargs + 1);
718 args2[0] = Qcall_process;
719 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
720 coding_systems
721 = Ffind_operation_coding_system (nargs + 1, args2);
723 if (CONSP (coding_systems))
724 val = XCAR (coding_systems);
725 else if (CONSP (Vdefault_process_coding_system))
726 val = XCAR (Vdefault_process_coding_system);
727 else
728 val = Qnil;
730 Fcheck_coding_system (val);
731 /* In unibyte mode, character code conversion should not take
732 place but EOL conversion should. So, setup raw-text or one
733 of the subsidiary according to the information just setup. */
734 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
735 && !NILP (val))
736 val = raw_text_coding_system (val);
737 setup_coding_system (val, &process_coding);
738 process_coding.dst_multibyte
739 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
741 process_coding.src_multibyte = 0;
743 immediate_quit = 1;
744 QUIT;
746 if (output_to_buffer)
748 enum { CALLPROC_BUFFER_SIZE_MIN = 16 * 1024 };
749 enum { CALLPROC_BUFFER_SIZE_MAX = 4 * CALLPROC_BUFFER_SIZE_MIN };
750 char buf[CALLPROC_BUFFER_SIZE_MAX];
751 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
752 int nread;
753 bool first = 1;
754 EMACS_INT total_read = 0;
755 int carryover = 0;
756 bool display_on_the_fly = display_p;
757 struct coding_system saved_coding;
759 saved_coding = process_coding;
760 while (1)
762 /* Repeatedly read until we've filled as much as possible
763 of the buffer size we have. But don't read
764 less than 1024--save that for the next bufferful. */
765 nread = carryover;
766 while (nread < bufsize - 1024)
768 int this_read = emacs_read (fd0, buf + nread,
769 bufsize - nread);
771 if (this_read < 0)
772 goto give_up;
774 if (this_read == 0)
776 process_coding.mode |= CODING_MODE_LAST_BLOCK;
777 break;
780 nread += this_read;
781 total_read += this_read;
783 if (display_on_the_fly)
784 break;
787 /* Now NREAD is the total amount of data in the buffer. */
788 immediate_quit = 0;
790 if (!NILP (buffer))
792 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
793 && ! CODING_MAY_REQUIRE_DECODING (&process_coding))
794 insert_1_both (buf, nread, nread, 0, 1, 0);
795 else
796 { /* We have to decode the input. */
797 Lisp_Object curbuf;
798 ptrdiff_t count1 = SPECPDL_INDEX ();
800 XSETBUFFER (curbuf, current_buffer);
801 /* We cannot allow after-change-functions be run
802 during decoding, because that might modify the
803 buffer, while we rely on process_coding.produced to
804 faithfully reflect inserted text until we
805 TEMP_SET_PT_BOTH below. */
806 specbind (Qinhibit_modification_hooks, Qt);
807 decode_coding_c_string (&process_coding,
808 (unsigned char *) buf, nread, curbuf);
809 unbind_to (count1, Qnil);
810 if (display_on_the_fly
811 && CODING_REQUIRE_DETECTION (&saved_coding)
812 && ! CODING_REQUIRE_DETECTION (&process_coding))
814 /* We have detected some coding system. But,
815 there's a possibility that the detection was
816 done by insufficient data. So, we give up
817 displaying on the fly. */
818 if (process_coding.produced > 0)
819 del_range_2 (process_coding.dst_pos,
820 process_coding.dst_pos_byte,
821 process_coding.dst_pos
822 + process_coding.produced_char,
823 process_coding.dst_pos_byte
824 + process_coding.produced, 0);
825 display_on_the_fly = 0;
826 process_coding = saved_coding;
827 carryover = nread;
828 /* This is to make the above condition always
829 fails in the future. */
830 saved_coding.common_flags
831 &= ~CODING_REQUIRE_DETECTION_MASK;
832 continue;
835 TEMP_SET_PT_BOTH (PT + process_coding.produced_char,
836 PT_BYTE + process_coding.produced);
837 carryover = process_coding.carryover_bytes;
838 if (carryover > 0)
839 memcpy (buf, process_coding.carryover,
840 process_coding.carryover_bytes);
844 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
845 break;
847 /* Make the buffer bigger as we continue to read more data,
848 but not past CALLPROC_BUFFER_SIZE_MAX. */
849 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
850 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
851 bufsize = CALLPROC_BUFFER_SIZE_MAX;
853 if (display_p)
855 if (first)
856 prepare_menu_bars ();
857 first = 0;
858 redisplay_preserve_echo_area (1);
859 /* This variable might have been set to 0 for code
860 detection. In that case, we set it back to 1 because
861 we should have already detected a coding system. */
862 display_on_the_fly = 1;
864 immediate_quit = 1;
865 QUIT;
867 give_up: ;
869 Vlast_coding_system_used = CODING_ID_NAME (process_coding.id);
870 /* If the caller required, let the buffer inherit the
871 coding-system used to decode the process output. */
872 if (inherit_process_coding_system)
873 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
874 make_number (total_read));
877 #ifndef MSDOS
878 /* Wait for it to terminate, unless it already has. */
879 wait_for_termination (pid, &status, !output_to_buffer);
880 #endif
882 immediate_quit = 0;
884 /* Don't kill any children that the subprocess may have left behind
885 when exiting. */
886 synch_process_pid = 0;
888 SAFE_FREE ();
889 unbind_to (count, Qnil);
891 if (WIFSIGNALED (status))
893 const char *signame;
895 synchronize_system_messages_locale ();
896 signame = strsignal (WTERMSIG (status));
898 if (signame == 0)
899 signame = "unknown";
901 return code_convert_string_norecord (build_string (signame),
902 Vlocale_coding_system, 0);
905 eassert (WIFEXITED (status));
906 return make_number (WEXITSTATUS (status));
909 static Lisp_Object
910 delete_temp_file (Lisp_Object name)
912 /* Suppress jka-compr handling, etc. */
913 ptrdiff_t count = SPECPDL_INDEX ();
914 specbind (intern ("file-name-handler-alist"), Qnil);
915 internal_delete_file (name);
916 unbind_to (count, Qnil);
917 return Qnil;
920 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
921 3, MANY, 0,
922 doc: /* Send text from START to END to a synchronous process running PROGRAM.
923 The remaining arguments are optional.
924 Delete the text if fourth arg DELETE is non-nil.
926 Insert output in BUFFER before point; t means current buffer; nil for
927 BUFFER means discard it; 0 means discard and don't wait; and `(:file
928 FILE)', where FILE is a file name string, means that it should be
929 written to that file (if the file already exists it is overwritten).
930 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
931 REAL-BUFFER says what to do with standard output, as above,
932 while STDERR-FILE says what to do with standard error in the child.
933 STDERR-FILE may be nil (discard standard error output),
934 t (mix it with ordinary output), or a file name string.
936 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
937 Remaining args are passed to PROGRAM at startup as command args.
939 If BUFFER is 0, `call-process-region' returns immediately with value nil.
940 Otherwise it waits for PROGRAM to terminate
941 and returns a numeric exit status or a signal description string.
942 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
944 usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
945 (ptrdiff_t nargs, Lisp_Object *args)
947 struct gcpro gcpro1;
948 Lisp_Object filename_string;
949 register Lisp_Object start, end;
950 ptrdiff_t count = SPECPDL_INDEX ();
951 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
952 Lisp_Object coding_systems;
953 Lisp_Object val, *args2;
954 ptrdiff_t i;
955 Lisp_Object tmpdir;
957 if (STRINGP (Vtemporary_file_directory))
958 tmpdir = Vtemporary_file_directory;
959 else
961 #ifndef DOS_NT
962 if (getenv ("TMPDIR"))
963 tmpdir = build_string (getenv ("TMPDIR"));
964 else
965 tmpdir = build_string ("/tmp/");
966 #else /* DOS_NT */
967 char *outf;
968 if ((outf = egetenv ("TMPDIR"))
969 || (outf = egetenv ("TMP"))
970 || (outf = egetenv ("TEMP")))
971 tmpdir = build_string (outf);
972 else
973 tmpdir = Ffile_name_as_directory (build_string ("c:/temp"));
974 #endif
978 USE_SAFE_ALLOCA;
979 Lisp_Object pattern = Fexpand_file_name (Vtemp_file_name_pattern, tmpdir);
980 Lisp_Object encoded_tem = ENCODE_FILE (pattern);
981 char *tempfile = SAFE_ALLOCA (SBYTES (encoded_tem) + 1);
982 memcpy (tempfile, SDATA (encoded_tem), SBYTES (encoded_tem) + 1);
983 coding_systems = Qt;
985 #ifdef HAVE_MKSTEMP
987 int fd;
989 block_input ();
990 fd = mkstemp (tempfile);
991 unblock_input ();
992 if (fd == -1)
993 report_file_error ("Failed to open temporary file",
994 Fcons (build_string (tempfile), Qnil));
995 else
996 close (fd);
998 #else
999 errno = 0;
1000 mktemp (tempfile);
1001 if (!*tempfile)
1003 if (!errno)
1004 errno = EEXIST;
1005 report_file_error ("Failed to open temporary file using pattern",
1006 Fcons (pattern, Qnil));
1008 #endif
1010 filename_string = build_string (tempfile);
1011 GCPRO1 (filename_string);
1012 SAFE_FREE ();
1015 start = args[0];
1016 end = args[1];
1017 /* Decide coding-system of the contents of the temporary file. */
1018 if (!NILP (Vcoding_system_for_write))
1019 val = Vcoding_system_for_write;
1020 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
1021 val = Qraw_text;
1022 else
1024 USE_SAFE_ALLOCA;
1025 SAFE_NALLOCA (args2, 1, nargs + 1);
1026 args2[0] = Qcall_process_region;
1027 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1028 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1029 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
1030 SAFE_FREE ();
1032 val = complement_process_encoding_system (val);
1035 ptrdiff_t count1 = SPECPDL_INDEX ();
1037 specbind (intern ("coding-system-for-write"), val);
1038 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
1039 happen to get a ".Z" suffix. */
1040 specbind (intern ("file-name-handler-alist"), Qnil);
1041 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
1043 unbind_to (count1, Qnil);
1046 /* Note that Fcall_process takes care of binding
1047 coding-system-for-read. */
1049 record_unwind_protect (delete_temp_file, filename_string);
1051 if (nargs > 3 && !NILP (args[3]))
1052 Fdelete_region (start, end);
1054 if (nargs > 3)
1056 args += 2;
1057 nargs -= 2;
1059 else
1061 args[0] = args[2];
1062 nargs = 2;
1064 args[1] = filename_string;
1066 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
1069 #ifndef WINDOWSNT
1070 static int relocate_fd (int fd, int minfd);
1071 #endif
1073 static char **
1074 add_env (char **env, char **new_env, char *string)
1076 char **ep;
1077 bool ok = 1;
1078 if (string == NULL)
1079 return new_env;
1081 /* See if this string duplicates any string already in the env.
1082 If so, don't put it in.
1083 When an env var has multiple definitions,
1084 we keep the definition that comes first in process-environment. */
1085 for (ep = env; ok && ep != new_env; ep++)
1087 char *p = *ep, *q = string;
1088 while (ok)
1090 if (*q != *p)
1091 break;
1092 if (*q == 0)
1093 /* The string is a lone variable name; keep it for now, we
1094 will remove it later. It is a placeholder for a
1095 variable that is not to be included in the environment. */
1096 break;
1097 if (*q == '=')
1098 ok = 0;
1099 p++, q++;
1102 if (ok)
1103 *new_env++ = string;
1104 return new_env;
1107 /* This is the last thing run in a newly forked inferior
1108 either synchronous or asynchronous.
1109 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1110 Initialize inferior's priority, pgrp, connected dir and environment.
1111 then exec another program based on new_argv.
1113 If SET_PGRP, put the subprocess into a separate process group.
1115 CURRENT_DIR is an elisp string giving the path of the current
1116 directory the subprocess should have. Since we can't really signal
1117 a decent error from within the child, this should be verified as an
1118 executable directory by the parent. */
1121 child_setup (int in, int out, int err, char **new_argv, bool set_pgrp,
1122 Lisp_Object current_dir)
1124 char **env;
1125 char *pwd_var;
1126 #ifdef WINDOWSNT
1127 int cpid;
1128 HANDLE handles[3];
1129 #endif /* WINDOWSNT */
1131 pid_t pid = getpid ();
1133 /* Close Emacs's descriptors that this process should not have. */
1134 close_process_descs ();
1136 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1137 we will lose if we call close_load_descs here. */
1138 #ifndef DOS_NT
1139 close_load_descs ();
1140 #endif
1142 /* Note that use of alloca is always safe here. It's obvious for systems
1143 that do not have true vfork or that have true (stack) alloca.
1144 If using vfork and C_ALLOCA (when Emacs used to include
1145 src/alloca.c) it is safe because that changes the superior's
1146 static variables as if the superior had done alloca and will be
1147 cleaned up in the usual way. */
1149 register char *temp;
1150 size_t i; /* size_t, because ptrdiff_t might overflow here! */
1152 i = SBYTES (current_dir);
1153 #ifdef MSDOS
1154 /* MSDOS must have all environment variables malloc'ed, because
1155 low-level libc functions that launch subsidiary processes rely
1156 on that. */
1157 pwd_var = xmalloc (i + 6);
1158 #else
1159 pwd_var = alloca (i + 6);
1160 #endif
1161 temp = pwd_var + 4;
1162 memcpy (pwd_var, "PWD=", 4);
1163 memcpy (temp, SDATA (current_dir), i);
1164 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
1165 temp[i] = 0;
1167 #ifndef DOS_NT
1168 /* We can't signal an Elisp error here; we're in a vfork. Since
1169 the callers check the current directory before forking, this
1170 should only return an error if the directory's permissions
1171 are changed between the check and this chdir, but we should
1172 at least check. */
1173 if (chdir (temp) < 0)
1174 _exit (errno);
1175 #else /* DOS_NT */
1176 /* Get past the drive letter, so that d:/ is left alone. */
1177 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1179 temp += 2;
1180 i -= 2;
1182 #endif /* DOS_NT */
1184 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1185 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1186 temp[--i] = 0;
1189 /* Set `env' to a vector of the strings in the environment. */
1191 register Lisp_Object tem;
1192 register char **new_env;
1193 char **p, **q;
1194 register int new_length;
1195 Lisp_Object display = Qnil;
1197 new_length = 0;
1199 for (tem = Vprocess_environment;
1200 CONSP (tem) && STRINGP (XCAR (tem));
1201 tem = XCDR (tem))
1203 if (strncmp (SSDATA (XCAR (tem)), "DISPLAY", 7) == 0
1204 && (SDATA (XCAR (tem)) [7] == '\0'
1205 || SDATA (XCAR (tem)) [7] == '='))
1206 /* DISPLAY is specified in process-environment. */
1207 display = Qt;
1208 new_length++;
1211 /* If not provided yet, use the frame's DISPLAY. */
1212 if (NILP (display))
1214 Lisp_Object tmp = Fframe_parameter (selected_frame, Qdisplay);
1215 if (!STRINGP (tmp) && CONSP (Vinitial_environment))
1216 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1217 tmp = Fgetenv_internal (build_string ("DISPLAY"),
1218 Vinitial_environment);
1219 if (STRINGP (tmp))
1221 display = tmp;
1222 new_length++;
1226 /* new_length + 2 to include PWD and terminating 0. */
1227 env = new_env = alloca ((new_length + 2) * sizeof *env);
1228 /* If we have a PWD envvar, pass one down,
1229 but with corrected value. */
1230 if (egetenv ("PWD"))
1231 *new_env++ = pwd_var;
1233 if (STRINGP (display))
1235 char *vdata = alloca (sizeof "DISPLAY=" + SBYTES (display));
1236 strcpy (vdata, "DISPLAY=");
1237 strcat (vdata, SSDATA (display));
1238 new_env = add_env (env, new_env, vdata);
1241 /* Overrides. */
1242 for (tem = Vprocess_environment;
1243 CONSP (tem) && STRINGP (XCAR (tem));
1244 tem = XCDR (tem))
1245 new_env = add_env (env, new_env, SSDATA (XCAR (tem)));
1247 *new_env = 0;
1249 /* Remove variable names without values. */
1250 p = q = env;
1251 while (*p != 0)
1253 while (*q != 0 && strchr (*q, '=') == NULL)
1254 q++;
1255 *p = *q++;
1256 if (*p != 0)
1257 p++;
1262 #ifdef WINDOWSNT
1263 prepare_standard_handles (in, out, err, handles);
1264 set_process_dir (SDATA (current_dir));
1265 /* Spawn the child. (See ntproc.c:Spawnve). */
1266 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1267 reset_standard_handles (in, out, err, handles);
1268 if (cpid == -1)
1269 /* An error occurred while trying to spawn the process. */
1270 report_file_error ("Spawning child process", Qnil);
1271 return cpid;
1273 #else /* not WINDOWSNT */
1274 /* Make sure that in, out, and err are not actually already in
1275 descriptors zero, one, or two; this could happen if Emacs is
1276 started with its standard in, out, or error closed, as might
1277 happen under X. */
1279 int oin = in, oout = out;
1281 /* We have to avoid relocating the same descriptor twice! */
1283 in = relocate_fd (in, 3);
1285 if (out == oin)
1286 out = in;
1287 else
1288 out = relocate_fd (out, 3);
1290 if (err == oin)
1291 err = in;
1292 else if (err == oout)
1293 err = out;
1294 else
1295 err = relocate_fd (err, 3);
1298 #ifndef MSDOS
1299 emacs_close (0);
1300 emacs_close (1);
1301 emacs_close (2);
1303 dup2 (in, 0);
1304 dup2 (out, 1);
1305 dup2 (err, 2);
1306 emacs_close (in);
1307 if (out != in)
1308 emacs_close (out);
1309 if (err != in && err != out)
1310 emacs_close (err);
1312 setpgid (0, 0);
1313 tcsetpgrp (0, pid);
1315 execve (new_argv[0], new_argv, env);
1317 emacs_write (1, "Can't exec program: ", 20);
1318 emacs_write (1, new_argv[0], strlen (new_argv[0]));
1319 emacs_write (1, "\n", 1);
1320 _exit (1);
1322 #else /* MSDOS */
1323 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1324 xfree (pwd_var);
1325 if (pid == -1)
1326 /* An error occurred while trying to run the subprocess. */
1327 report_file_error ("Spawning child process", Qnil);
1328 return pid;
1329 #endif /* MSDOS */
1330 #endif /* not WINDOWSNT */
1333 #ifndef WINDOWSNT
1334 /* Move the file descriptor FD so that its number is not less than MINFD.
1335 If the file descriptor is moved at all, the original is freed. */
1336 static int
1337 relocate_fd (int fd, int minfd)
1339 if (fd >= minfd)
1340 return fd;
1341 else
1343 int new = fcntl (fd, F_DUPFD, minfd);
1344 if (new == -1)
1346 const char *message_1 = "Error while setting up child: ";
1347 const char *errmessage = strerror (errno);
1348 const char *message_2 = "\n";
1349 emacs_write (2, message_1, strlen (message_1));
1350 emacs_write (2, errmessage, strlen (errmessage));
1351 emacs_write (2, message_2, strlen (message_2));
1352 _exit (1);
1354 emacs_close (fd);
1355 return new;
1358 #endif /* not WINDOWSNT */
1360 static bool
1361 getenv_internal_1 (const char *var, ptrdiff_t varlen, char **value,
1362 ptrdiff_t *valuelen, Lisp_Object env)
1364 for (; CONSP (env); env = XCDR (env))
1366 Lisp_Object entry = XCAR (env);
1367 if (STRINGP (entry)
1368 && SBYTES (entry) >= varlen
1369 #ifdef WINDOWSNT
1370 /* NT environment variables are case insensitive. */
1371 && ! strnicmp (SDATA (entry), var, varlen)
1372 #else /* not WINDOWSNT */
1373 && ! memcmp (SDATA (entry), var, varlen)
1374 #endif /* not WINDOWSNT */
1377 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1379 *value = SSDATA (entry) + (varlen + 1);
1380 *valuelen = SBYTES (entry) - (varlen + 1);
1381 return 1;
1383 else if (SBYTES (entry) == varlen)
1385 /* Lone variable names in Vprocess_environment mean that
1386 variable should be removed from the environment. */
1387 *value = NULL;
1388 return 1;
1392 return 0;
1395 static bool
1396 getenv_internal (const char *var, ptrdiff_t varlen, char **value,
1397 ptrdiff_t *valuelen, Lisp_Object frame)
1399 /* Try to find VAR in Vprocess_environment first. */
1400 if (getenv_internal_1 (var, varlen, value, valuelen,
1401 Vprocess_environment))
1402 return *value ? 1 : 0;
1404 /* For DISPLAY try to get the values from the frame or the initial env. */
1405 if (strcmp (var, "DISPLAY") == 0)
1407 Lisp_Object display
1408 = Fframe_parameter (NILP (frame) ? selected_frame : frame, Qdisplay);
1409 if (STRINGP (display))
1411 *value = SSDATA (display);
1412 *valuelen = SBYTES (display);
1413 return 1;
1415 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1416 if (getenv_internal_1 (var, varlen, value, valuelen,
1417 Vinitial_environment))
1418 return *value ? 1 : 0;
1421 return 0;
1424 DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
1425 doc: /* Get the value of environment variable VARIABLE.
1426 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1427 the environment. Otherwise, value is a string.
1429 This function searches `process-environment' for VARIABLE.
1431 If optional parameter ENV is a list, then search this list instead of
1432 `process-environment', and return t when encountering a negative entry
1433 \(an entry for a variable with no value). */)
1434 (Lisp_Object variable, Lisp_Object env)
1436 char *value;
1437 ptrdiff_t valuelen;
1439 CHECK_STRING (variable);
1440 if (CONSP (env))
1442 if (getenv_internal_1 (SSDATA (variable), SBYTES (variable),
1443 &value, &valuelen, env))
1444 return value ? make_string (value, valuelen) : Qt;
1445 else
1446 return Qnil;
1448 else if (getenv_internal (SSDATA (variable), SBYTES (variable),
1449 &value, &valuelen, env))
1450 return make_string (value, valuelen);
1451 else
1452 return Qnil;
1455 /* A version of getenv that consults the Lisp environment lists,
1456 easily callable from C. */
1457 char *
1458 egetenv (const char *var)
1460 char *value;
1461 ptrdiff_t valuelen;
1463 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
1464 return value;
1465 else
1466 return 0;
1470 /* This is run before init_cmdargs. */
1472 void
1473 init_callproc_1 (void)
1475 #ifdef HAVE_NS
1476 const char *etc_dir = ns_etc_directory ();
1477 const char *path_exec = ns_exec_path ();
1478 #endif
1480 Vdata_directory = decode_env_path ("EMACSDATA",
1481 #ifdef HAVE_NS
1482 etc_dir ? etc_dir :
1483 #endif
1484 PATH_DATA);
1485 Vdata_directory = Ffile_name_as_directory (Fcar (Vdata_directory));
1487 Vdoc_directory = decode_env_path ("EMACSDOC",
1488 #ifdef HAVE_NS
1489 etc_dir ? etc_dir :
1490 #endif
1491 PATH_DOC);
1492 Vdoc_directory = Ffile_name_as_directory (Fcar (Vdoc_directory));
1494 /* Check the EMACSPATH environment variable, defaulting to the
1495 PATH_EXEC path from epaths.h. */
1496 Vexec_path = decode_env_path ("EMACSPATH",
1497 #ifdef HAVE_NS
1498 path_exec ? path_exec :
1499 #endif
1500 PATH_EXEC);
1501 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1502 /* FIXME? For ns, path_exec should go at the front? */
1503 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1506 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1508 void
1509 init_callproc (void)
1511 char *data_dir = egetenv ("EMACSDATA");
1513 register char * sh;
1514 Lisp_Object tempdir;
1515 #ifdef HAVE_NS
1516 if (data_dir == 0)
1518 const char *etc_dir = ns_etc_directory ();
1519 if (etc_dir)
1521 data_dir = alloca (strlen (etc_dir) + 1);
1522 strcpy (data_dir, etc_dir);
1525 #endif
1527 if (!NILP (Vinstallation_directory))
1529 /* Add to the path the lib-src subdir of the installation dir. */
1530 Lisp_Object tem;
1531 tem = Fexpand_file_name (build_string ("lib-src"),
1532 Vinstallation_directory);
1533 #ifndef MSDOS
1534 /* MSDOS uses wrapped binaries, so don't do this. */
1535 if (NILP (Fmember (tem, Vexec_path)))
1537 #ifdef HAVE_NS
1538 const char *path_exec = ns_exec_path ();
1539 #endif
1540 Vexec_path = decode_env_path ("EMACSPATH",
1541 #ifdef HAVE_NS
1542 path_exec ? path_exec :
1543 #endif
1544 PATH_EXEC);
1545 Vexec_path = Fcons (tem, Vexec_path);
1546 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1549 Vexec_directory = Ffile_name_as_directory (tem);
1550 #endif /* not MSDOS */
1552 /* Maybe use ../etc as well as ../lib-src. */
1553 if (data_dir == 0)
1555 tem = Fexpand_file_name (build_string ("etc"),
1556 Vinstallation_directory);
1557 Vdoc_directory = Ffile_name_as_directory (tem);
1561 /* Look for the files that should be in etc. We don't use
1562 Vinstallation_directory, because these files are never installed
1563 near the executable, and they are never in the build
1564 directory when that's different from the source directory.
1566 Instead, if these files are not in the nominal place, we try the
1567 source directory. */
1568 if (data_dir == 0)
1570 Lisp_Object tem, tem1, srcdir;
1572 srcdir = Fexpand_file_name (build_string ("../src/"),
1573 build_string (PATH_DUMPLOADSEARCH));
1574 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1575 tem1 = Ffile_exists_p (tem);
1576 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
1578 Lisp_Object newdir;
1579 newdir = Fexpand_file_name (build_string ("../etc/"),
1580 build_string (PATH_DUMPLOADSEARCH));
1581 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1582 tem1 = Ffile_exists_p (tem);
1583 if (!NILP (tem1))
1584 Vdata_directory = newdir;
1588 #ifndef CANNOT_DUMP
1589 if (initialized)
1590 #endif
1592 tempdir = Fdirectory_file_name (Vexec_directory);
1593 if (! file_accessible_directory_p (SSDATA (tempdir)))
1594 dir_warning ("arch-dependent data dir", Vexec_directory);
1597 tempdir = Fdirectory_file_name (Vdata_directory);
1598 if (! file_accessible_directory_p (SSDATA (tempdir)))
1599 dir_warning ("arch-independent data dir", Vdata_directory);
1601 sh = (char *) getenv ("SHELL");
1602 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1604 #ifdef DOS_NT
1605 Vshared_game_score_directory = Qnil;
1606 #else
1607 Vshared_game_score_directory = build_string (PATH_GAME);
1608 if (NILP (Ffile_accessible_directory_p (Vshared_game_score_directory)))
1609 Vshared_game_score_directory = Qnil;
1610 #endif
1613 void
1614 set_initial_environment (void)
1616 char **envp;
1617 for (envp = environ; *envp; envp++)
1618 Vprocess_environment = Fcons (build_string (*envp),
1619 Vprocess_environment);
1620 /* Ideally, the `copy' shouldn't be necessary, but it seems it's frequent
1621 to use `delete' and friends on process-environment. */
1622 Vinitial_environment = Fcopy_sequence (Vprocess_environment);
1625 void
1626 syms_of_callproc (void)
1628 #ifndef DOS_NT
1629 Vtemp_file_name_pattern = build_string ("emacsXXXXXX");
1630 #elif defined (WINDOWSNT)
1631 Vtemp_file_name_pattern = build_string ("emXXXXXX");
1632 #else
1633 Vtemp_file_name_pattern = build_string ("detmp.XXX");
1634 #endif
1635 staticpro (&Vtemp_file_name_pattern);
1637 DEFVAR_LISP ("shell-file-name", Vshell_file_name,
1638 doc: /* File name to load inferior shells from.
1639 Initialized from the SHELL environment variable, or to a system-dependent
1640 default if SHELL is not set. */);
1642 DEFVAR_LISP ("exec-path", Vexec_path,
1643 doc: /* List of directories to search programs to run in subprocesses.
1644 Each element is a string (directory name) or nil (try default directory). */);
1646 DEFVAR_LISP ("exec-suffixes", Vexec_suffixes,
1647 doc: /* List of suffixes to try to find executable file names.
1648 Each element is a string. */);
1649 Vexec_suffixes = Qnil;
1651 DEFVAR_LISP ("exec-directory", Vexec_directory,
1652 doc: /* Directory for executables for Emacs to invoke.
1653 More generally, this includes any architecture-dependent files
1654 that are built and installed from the Emacs distribution. */);
1656 DEFVAR_LISP ("data-directory", Vdata_directory,
1657 doc: /* Directory of machine-independent files that come with GNU Emacs.
1658 These are files intended for Emacs to use while it runs. */);
1660 DEFVAR_LISP ("doc-directory", Vdoc_directory,
1661 doc: /* Directory containing the DOC file that comes with GNU Emacs.
1662 This is usually the same as `data-directory'. */);
1664 DEFVAR_LISP ("configure-info-directory", Vconfigure_info_directory,
1665 doc: /* For internal use by the build procedure only.
1666 This is the name of the directory in which the build procedure installed
1667 Emacs's info files; the default value for `Info-default-directory-list'
1668 includes this. */);
1669 Vconfigure_info_directory = build_string (PATH_INFO);
1671 DEFVAR_LISP ("shared-game-score-directory", Vshared_game_score_directory,
1672 doc: /* Directory of score files for games which come with GNU Emacs.
1673 If this variable is nil, then Emacs is unable to use a shared directory. */);
1674 #ifdef DOS_NT
1675 Vshared_game_score_directory = Qnil;
1676 #else
1677 Vshared_game_score_directory = build_string (PATH_GAME);
1678 #endif
1680 DEFVAR_LISP ("initial-environment", Vinitial_environment,
1681 doc: /* List of environment variables inherited from the parent process.
1682 Each element should be a string of the form ENVVARNAME=VALUE.
1683 The elements must normally be decoded (using `locale-coding-system') for use. */);
1684 Vinitial_environment = Qnil;
1686 DEFVAR_LISP ("process-environment", Vprocess_environment,
1687 doc: /* List of overridden environment variables for subprocesses to inherit.
1688 Each element should be a string of the form ENVVARNAME=VALUE.
1690 Entries in this list take precedence to those in the frame-local
1691 environments. Therefore, let-binding `process-environment' is an easy
1692 way to temporarily change the value of an environment variable,
1693 irrespective of where it comes from. To use `process-environment' to
1694 remove an environment variable, include only its name in the list,
1695 without "=VALUE".
1697 This variable is set to nil when Emacs starts.
1699 If multiple entries define the same variable, the first one always
1700 takes precedence.
1702 Non-ASCII characters are encoded according to the initial value of
1703 `locale-coding-system', i.e. the elements must normally be decoded for
1704 use.
1706 See `setenv' and `getenv'. */);
1707 Vprocess_environment = Qnil;
1709 defsubr (&Scall_process);
1710 defsubr (&Sgetenv_internal);
1711 defsubr (&Scall_process_region);