Auto-commit of loaddefs files.
[emacs.git] / src / callproc.c
blob21741ad874096297dfb08b4fdf9877ff806f8e8c
1 /* Synchronous subprocess invocation for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1995, 1999-2014 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <unistd.h>
28 #include <sys/file.h>
29 #include <fcntl.h>
31 #include "lisp.h"
33 #ifdef WINDOWSNT
34 #define NOMINMAX
35 #include <sys/socket.h> /* for fcntl */
36 #include <windows.h>
37 #include "w32.h"
38 #define _P_NOWAIT 1 /* from process.h */
39 #endif
41 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
42 #include <sys/stat.h>
43 #include <sys/param.h>
44 #endif /* MSDOS */
46 #include "commands.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "ccl.h"
50 #include "coding.h"
51 #include "composite.h"
52 #include <epaths.h>
53 #include "process.h"
54 #include "syssignal.h"
55 #include "systty.h"
56 #include "syswait.h"
57 #include "blockinput.h"
58 #include "frame.h"
59 #include "termhooks.h"
61 #ifdef MSDOS
62 #include "msdos.h"
63 #endif
65 #ifdef HAVE_NS
66 #include "nsterm.h"
67 #endif
69 /* Pattern used by call-process-region to make temp files. */
70 static Lisp_Object Vtemp_file_name_pattern;
72 /* The next two variables are used while record-unwind-protect is in place
73 during call-process for a subprocess for which record_deleted_pid has
74 not yet been called. At other times, synch_process_pid is zero and
75 synch_process_tempfile's contents are irrelevant. Doing this via static
76 C variables is more convenient than putting them into the arguments
77 of record-unwind-protect, as they need to be updated at randomish
78 times in the code, and Lisp cannot always store these values as
79 Emacs integers. It's safe to use static variables here, as the
80 code is never invoked reentrantly. */
82 /* If nonzero, a process-ID that has not been reaped. */
83 static pid_t synch_process_pid;
85 /* If a string, the name of a temp file that has not been removed. */
86 #ifdef MSDOS
87 static Lisp_Object synch_process_tempfile;
88 #else
89 # define synch_process_tempfile make_number (0)
90 #endif
92 /* Indexes of file descriptors that need closing on call_process_kill. */
93 enum
95 /* The subsidiary process's stdout and stderr. stdin is handled
96 separately, in either Fcall_process_region or create_temp_file. */
97 CALLPROC_STDOUT, CALLPROC_STDERR,
99 /* How to read from a pipe (or substitute) from the subsidiary process. */
100 CALLPROC_PIPEREAD,
102 /* A bound on the number of file descriptors. */
103 CALLPROC_FDS
106 static Lisp_Object call_process (ptrdiff_t, Lisp_Object *, int, ptrdiff_t);
109 #ifndef MSDOS
110 /* Block SIGCHLD. */
112 void
113 block_child_signal (void)
115 sigset_t blocked;
116 sigemptyset (&blocked);
117 sigaddset (&blocked, SIGCHLD);
118 pthread_sigmask (SIG_BLOCK, &blocked, 0);
121 /* Unblock SIGCHLD. */
123 void
124 unblock_child_signal (void)
126 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
129 #endif /* !MSDOS */
131 /* Return the current buffer's working directory, or the home
132 directory if it's unreachable, as a string suitable for a system call.
133 Signal an error if the result would not be an accessible directory. */
135 Lisp_Object
136 encode_current_directory (void)
138 Lisp_Object dir;
139 struct gcpro gcpro1;
141 dir = BVAR (current_buffer, directory);
142 GCPRO1 (dir);
144 dir = Funhandled_file_name_directory (dir);
146 /* If the file name handler says that dir is unreachable, use
147 a sensible default. */
148 if (NILP (dir))
149 dir = build_string ("~");
151 dir = expand_and_dir_to_file (dir, Qnil);
153 if (NILP (Ffile_accessible_directory_p (dir)))
154 report_file_error ("Setting current directory",
155 BVAR (current_buffer, directory));
157 /* Remove "/:" from dir. */
158 if (! NILP (Fstring_match (build_string ("^/:"), dir, Qnil)))
159 dir = Fsubstring (dir, make_number (2), Qnil);
161 if (STRING_MULTIBYTE (dir))
162 dir = ENCODE_FILE (dir);
164 RETURN_UNGCPRO (dir);
167 /* If P is reapable, record it as a deleted process and kill it.
168 Do this in a critical section. Unless PID is wedged it will be
169 reaped on receipt of the first SIGCHLD after the critical section. */
171 void
172 record_kill_process (struct Lisp_Process *p, Lisp_Object tempfile)
174 #ifndef MSDOS
175 block_child_signal ();
177 if (p->alive)
179 record_deleted_pid (p->pid, tempfile);
180 p->alive = 0;
181 kill (- p->pid, SIGKILL);
184 unblock_child_signal ();
185 #endif /* !MSDOS */
188 /* Clean up files, file descriptors and processes created by Fcall_process. */
190 static void
191 delete_temp_file (Lisp_Object name)
193 unlink (SSDATA (name));
196 static void
197 call_process_kill (void *ptr)
199 int *callproc_fd = ptr;
200 int i;
201 for (i = 0; i < CALLPROC_FDS; i++)
202 if (0 <= callproc_fd[i])
203 emacs_close (callproc_fd[i]);
205 if (synch_process_pid)
207 struct Lisp_Process proc;
208 proc.alive = 1;
209 proc.pid = synch_process_pid;
210 record_kill_process (&proc, synch_process_tempfile);
211 synch_process_pid = 0;
213 else if (STRINGP (synch_process_tempfile))
214 delete_temp_file (synch_process_tempfile);
217 /* Clean up when exiting Fcall_process: restore the buffer, and
218 kill the subsidiary process group if the process still exists. */
220 static void
221 call_process_cleanup (Lisp_Object buffer)
223 Fset_buffer (buffer);
225 #ifndef MSDOS
226 if (synch_process_pid)
228 kill (-synch_process_pid, SIGINT);
229 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
230 immediate_quit = 1;
231 QUIT;
232 wait_for_termination (synch_process_pid, 0, 1);
233 synch_process_pid = 0;
234 immediate_quit = 0;
235 message1 ("Waiting for process to die...done");
237 #endif /* !MSDOS */
240 #ifdef DOS_NT
241 static mode_t const default_output_mode = S_IREAD | S_IWRITE;
242 #else
243 static mode_t const default_output_mode = 0666;
244 #endif
246 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
247 doc: /* Call PROGRAM synchronously in separate process.
248 The remaining arguments are optional.
249 The program's input comes from file INFILE (nil means `/dev/null').
250 Insert output in DESTINATION before point; t means current buffer; nil for DESTINATION
251 means discard it; 0 means discard and don't wait; and `(:file FILE)', where
252 FILE is a file name string, means that it should be written to that file
253 \(if the file already exists it is overwritten).
254 DESTINATION can also have the form (REAL-BUFFER STDERR-FILE); in that case,
255 REAL-BUFFER says what to do with standard output, as above,
256 while STDERR-FILE says what to do with standard error in the child.
257 STDERR-FILE may be nil (discard standard error output),
258 t (mix it with ordinary output), or a file name string.
260 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
261 Remaining arguments are strings passed as command arguments to PROGRAM.
263 If executable PROGRAM can't be found as an executable, `call-process'
264 signals a Lisp error. `call-process' reports errors in execution of
265 the program only through its return and output.
267 If DESTINATION is 0, `call-process' returns immediately with value nil.
268 Otherwise it waits for PROGRAM to terminate
269 and returns a numeric exit status or a signal description string.
270 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
272 usage: (call-process PROGRAM &optional INFILE DESTINATION DISPLAY &rest ARGS) */)
273 (ptrdiff_t nargs, Lisp_Object *args)
275 Lisp_Object infile, encoded_infile;
276 int filefd;
277 struct gcpro gcpro1;
278 ptrdiff_t count = SPECPDL_INDEX ();
280 if (nargs >= 2 && ! NILP (args[1]))
282 infile = Fexpand_file_name (args[1], BVAR (current_buffer, directory));
283 CHECK_STRING (infile);
285 else
286 infile = build_string (NULL_DEVICE);
288 GCPRO1 (infile);
289 encoded_infile = STRING_MULTIBYTE (infile) ? ENCODE_FILE (infile) : infile;
291 filefd = emacs_open (SSDATA (encoded_infile), O_RDONLY, 0);
292 if (filefd < 0)
293 report_file_error ("Opening process input file", infile);
294 record_unwind_protect_int (close_file_unwind, filefd);
295 UNGCPRO;
296 return unbind_to (count, call_process (nargs, args, filefd, -1));
299 /* Like Fcall_process (NARGS, ARGS), except use FILEFD as the input file.
301 If TEMPFILE_INDEX is nonnegative, it is the specpdl index of an
302 unwinder that is intended to remove the input temporary file; in
303 this case NARGS must be at least 2 and ARGS[1] is the file's name.
305 At entry, the specpdl stack top entry must be close_file_unwind (FILEFD). */
307 static Lisp_Object
308 call_process (ptrdiff_t nargs, Lisp_Object *args, int filefd,
309 ptrdiff_t tempfile_index)
311 Lisp_Object buffer, current_dir, path;
312 bool display_p;
313 int fd0;
314 int callproc_fd[CALLPROC_FDS];
315 int status;
316 ptrdiff_t i;
317 ptrdiff_t count = SPECPDL_INDEX ();
318 USE_SAFE_ALLOCA;
320 char **new_argv;
321 /* File to use for stderr in the child.
322 t means use same as standard output. */
323 Lisp_Object error_file;
324 Lisp_Object output_file = Qnil;
325 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
326 char *tempfile = NULL;
327 int pid;
328 #else
329 pid_t pid;
330 #endif
331 int child_errno;
332 int fd_output, fd_error;
333 struct coding_system process_coding; /* coding-system of process output */
334 struct coding_system argument_coding; /* coding-system of arguments */
335 /* Set to the return value of Ffind_operation_coding_system. */
336 Lisp_Object coding_systems;
337 bool discard_output;
339 if (synch_process_pid)
340 error ("call-process invoked recursively");
342 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
343 coding_systems = Qt;
345 CHECK_STRING (args[0]);
347 error_file = Qt;
349 #ifndef subprocesses
350 /* Without asynchronous processes we cannot have BUFFER == 0. */
351 if (nargs >= 3
352 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
353 error ("Operating system cannot handle asynchronous subprocesses");
354 #endif /* subprocesses */
356 /* Decide the coding-system for giving arguments. */
358 Lisp_Object val, *args2;
360 /* If arguments are supplied, we may have to encode them. */
361 if (nargs >= 5)
363 bool must_encode = 0;
364 Lisp_Object coding_attrs;
366 for (i = 4; i < nargs; i++)
367 CHECK_STRING (args[i]);
369 for (i = 4; i < nargs; i++)
370 if (STRING_MULTIBYTE (args[i]))
371 must_encode = 1;
373 if (!NILP (Vcoding_system_for_write))
374 val = Vcoding_system_for_write;
375 else if (! must_encode)
376 val = Qraw_text;
377 else
379 SAFE_NALLOCA (args2, 1, nargs + 1);
380 args2[0] = Qcall_process;
381 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
382 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
383 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
385 val = complement_process_encoding_system (val);
386 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
387 coding_attrs = CODING_ID_ATTRS (argument_coding.id);
388 if (NILP (CODING_ATTR_ASCII_COMPAT (coding_attrs)))
390 /* We should not use an ASCII incompatible coding system. */
391 val = raw_text_coding_system (val);
392 setup_coding_system (val, &argument_coding);
397 if (nargs < 3)
398 buffer = Qnil;
399 else
401 buffer = args[2];
403 /* If BUFFER is a list, its meaning is (BUFFER-FOR-STDOUT
404 FILE-FOR-STDERR), unless the first element is :file, in which case see
405 the next paragraph. */
406 if (CONSP (buffer) && !EQ (XCAR (buffer), QCfile))
408 if (CONSP (XCDR (buffer)))
410 Lisp_Object stderr_file;
411 stderr_file = XCAR (XCDR (buffer));
413 if (NILP (stderr_file) || EQ (Qt, stderr_file))
414 error_file = stderr_file;
415 else
416 error_file = Fexpand_file_name (stderr_file, Qnil);
419 buffer = XCAR (buffer);
422 /* If the buffer is (still) a list, it might be a (:file "file") spec. */
423 if (CONSP (buffer) && EQ (XCAR (buffer), QCfile))
425 output_file = Fexpand_file_name (XCAR (XCDR (buffer)),
426 BVAR (current_buffer, directory));
427 CHECK_STRING (output_file);
428 buffer = Qnil;
431 if (! (NILP (buffer) || EQ (buffer, Qt) || INTEGERP (buffer)))
433 Lisp_Object spec_buffer;
434 spec_buffer = buffer;
435 buffer = Fget_buffer_create (buffer);
436 /* Mention the buffer name for a better error message. */
437 if (NILP (buffer))
438 CHECK_BUFFER (spec_buffer);
439 CHECK_BUFFER (buffer);
443 /* Make sure that the child will be able to chdir to the current
444 buffer's current directory, or its unhandled equivalent. We
445 can't just have the child check for an error when it does the
446 chdir, since it's in a vfork.
448 We have to GCPRO around this because Fexpand_file_name,
449 Funhandled_file_name_directory, and Ffile_accessible_directory_p
450 might call a file name handling function. The argument list is
451 protected by the caller, so all we really have to worry about is
452 buffer. */
454 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
456 current_dir = encode_current_directory ();
458 GCPRO4 (buffer, current_dir, error_file, output_file);
460 if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
461 error_file = ENCODE_FILE (error_file);
462 if (STRINGP (output_file) && STRING_MULTIBYTE (output_file))
463 output_file = ENCODE_FILE (output_file);
464 UNGCPRO;
467 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
469 for (i = 0; i < CALLPROC_FDS; i++)
470 callproc_fd[i] = -1;
471 #ifdef MSDOS
472 synch_process_tempfile = make_number (0);
473 #endif
474 record_unwind_protect_ptr (call_process_kill, callproc_fd);
476 /* Search for program; barf if not found. */
478 struct gcpro gcpro1, gcpro2, gcpro3;
479 int ok;
481 GCPRO3 (buffer, current_dir, error_file);
482 ok = openp (Vexec_path, args[0], Vexec_suffixes, &path,
483 make_number (X_OK), false);
484 UNGCPRO;
485 if (ok < 0)
486 report_file_error ("Searching for program", args[0]);
489 /* If program file name starts with /: for quoting a magic name,
490 discard that. */
491 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
492 && SREF (path, 1) == ':')
493 path = Fsubstring (path, make_number (2), Qnil);
495 new_argv = SAFE_ALLOCA ((nargs > 4 ? nargs - 2 : 2) * sizeof *new_argv);
498 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
500 GCPRO4 (buffer, current_dir, path, error_file);
501 if (nargs > 4)
503 ptrdiff_t i;
505 argument_coding.dst_multibyte = 0;
506 for (i = 4; i < nargs; i++)
508 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
509 if (CODING_REQUIRE_ENCODING (&argument_coding))
510 /* We must encode this argument. */
511 args[i] = encode_coding_string (&argument_coding, args[i], 1);
513 for (i = 4; i < nargs; i++)
514 new_argv[i - 3] = SSDATA (args[i]);
515 new_argv[i - 3] = 0;
517 else
518 new_argv[1] = 0;
519 if (STRING_MULTIBYTE (path))
520 path = ENCODE_FILE (path);
521 new_argv[0] = SSDATA (path);
522 UNGCPRO;
525 discard_output = INTEGERP (buffer) || (NILP (buffer) && NILP (output_file));
527 #ifdef MSDOS
528 if (! discard_output && ! STRINGP (output_file))
530 char const *tmpdir = egetenv ("TMPDIR");
531 char const *outf = tmpdir ? tmpdir : "";
532 tempfile = alloca (strlen (outf) + 20);
533 strcpy (tempfile, outf);
534 dostounix_filename (tempfile);
535 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
536 strcat (tempfile, "/");
537 strcat (tempfile, "emXXXXXX");
538 mktemp (tempfile);
539 if (!*tempfile)
540 report_file_error ("Opening process output file", Qnil);
541 output_file = build_string (tempfile);
542 synch_process_tempfile = output_file;
544 #endif
546 if (discard_output)
548 fd_output = emacs_open (NULL_DEVICE, O_WRONLY, 0);
549 if (fd_output < 0)
550 report_file_error ("Opening null device", Qnil);
552 else if (STRINGP (output_file))
554 fd_output = emacs_open (SSDATA (output_file),
555 O_WRONLY | O_CREAT | O_TRUNC | O_TEXT,
556 default_output_mode);
557 if (fd_output < 0)
559 int open_errno = errno;
560 output_file = DECODE_FILE (output_file);
561 report_file_errno ("Opening process output file",
562 output_file, open_errno);
565 else
567 int fd[2];
568 if (emacs_pipe (fd) != 0)
569 report_file_error ("Creating process pipe", Qnil);
570 callproc_fd[CALLPROC_PIPEREAD] = fd[0];
571 fd_output = fd[1];
573 callproc_fd[CALLPROC_STDOUT] = fd_output;
575 fd_error = fd_output;
577 if (STRINGP (error_file) || (NILP (error_file) && !discard_output))
579 fd_error = emacs_open ((STRINGP (error_file)
580 ? SSDATA (error_file)
581 : NULL_DEVICE),
582 O_WRONLY | O_CREAT | O_TRUNC | O_TEXT,
583 default_output_mode);
584 if (fd_error < 0)
586 int open_errno = errno;
587 report_file_errno ("Cannot redirect stderr",
588 (STRINGP (error_file)
589 ? DECODE_FILE (error_file)
590 : build_string (NULL_DEVICE)),
591 open_errno);
593 callproc_fd[CALLPROC_STDERR] = fd_error;
596 #ifdef MSDOS /* MW, July 1993 */
597 /* Note that on MSDOS `child_setup' actually returns the child process
598 exit status, not its PID, so assign it to status below. */
599 pid = child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
601 if (pid < 0)
603 child_errno = errno;
604 unbind_to (count, Qnil);
605 synchronize_system_messages_locale ();
606 return
607 code_convert_string_norecord (build_string (strerror (child_errno)),
608 Vlocale_coding_system, 0);
610 status = pid;
612 for (i = 0; i < CALLPROC_FDS; i++)
613 if (0 <= callproc_fd[i])
615 emacs_close (callproc_fd[i]);
616 callproc_fd[i] = -1;
618 emacs_close (filefd);
619 clear_unwind_protect (count - 1);
621 if (tempfile)
623 /* Since CRLF is converted to LF within `decode_coding', we
624 can always open a file with binary mode. */
625 callproc_fd[CALLPROC_PIPEREAD] = emacs_open (tempfile,
626 O_RDONLY | O_BINARY, 0);
627 if (callproc_fd[CALLPROC_PIPEREAD] < 0)
629 int open_errno = errno;
630 report_file_errno ("Cannot re-open temporary file",
631 build_string (tempfile), open_errno);
635 #endif /* MSDOS */
637 /* Do the unwind-protect now, even though the pid is not known, so
638 that no storage allocation is done in the critical section.
639 The actual PID will be filled in during the critical section. */
640 record_unwind_protect (call_process_cleanup, Fcurrent_buffer ());
642 #ifndef MSDOS
644 block_input ();
645 block_child_signal ();
647 #ifdef WINDOWSNT
648 pid = child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
649 #else /* not WINDOWSNT */
651 /* vfork, and prevent local vars from being clobbered by the vfork. */
653 Lisp_Object volatile buffer_volatile = buffer;
654 Lisp_Object volatile coding_systems_volatile = coding_systems;
655 Lisp_Object volatile current_dir_volatile = current_dir;
656 bool volatile display_p_volatile = display_p;
657 bool volatile sa_must_free_volatile = sa_must_free;
658 int volatile fd_error_volatile = fd_error;
659 int volatile filefd_volatile = filefd;
660 ptrdiff_t volatile count_volatile = count;
661 ptrdiff_t volatile sa_count_volatile = sa_count;
662 char **volatile new_argv_volatile = new_argv;
663 int volatile callproc_fd_volatile[CALLPROC_FDS];
664 for (i = 0; i < CALLPROC_FDS; i++)
665 callproc_fd_volatile[i] = callproc_fd[i];
667 pid = vfork ();
669 buffer = buffer_volatile;
670 coding_systems = coding_systems_volatile;
671 current_dir = current_dir_volatile;
672 display_p = display_p_volatile;
673 sa_must_free = sa_must_free_volatile;
674 fd_error = fd_error_volatile;
675 filefd = filefd_volatile;
676 count = count_volatile;
677 sa_count = sa_count_volatile;
678 new_argv = new_argv_volatile;
680 for (i = 0; i < CALLPROC_FDS; i++)
681 callproc_fd[i] = callproc_fd_volatile[i];
682 fd_output = callproc_fd[CALLPROC_STDOUT];
685 if (pid == 0)
687 unblock_child_signal ();
689 setsid ();
691 /* Emacs ignores SIGPIPE, but the child should not. */
692 signal (SIGPIPE, SIG_DFL);
693 /* Likewise for SIGPROF. */
694 #ifdef SIGPROF
695 signal (SIGPROF, SIG_DFL);
696 #endif
698 child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
701 #endif /* not WINDOWSNT */
703 child_errno = errno;
705 if (pid > 0)
707 synch_process_pid = pid;
709 if (INTEGERP (buffer))
711 if (tempfile_index < 0)
712 record_deleted_pid (pid, Qnil);
713 else
715 eassert (1 < nargs);
716 record_deleted_pid (pid, args[1]);
717 clear_unwind_protect (tempfile_index);
719 synch_process_pid = 0;
723 unblock_child_signal ();
724 unblock_input ();
726 if (pid < 0)
727 report_file_errno ("Doing vfork", Qnil, child_errno);
729 /* Close our file descriptors, except for callproc_fd[CALLPROC_PIPEREAD]
730 since we will use that to read input from. */
731 for (i = 0; i < CALLPROC_FDS; i++)
732 if (i != CALLPROC_PIPEREAD && 0 <= callproc_fd[i])
734 emacs_close (callproc_fd[i]);
735 callproc_fd[i] = -1;
737 emacs_close (filefd);
738 clear_unwind_protect (count - 1);
740 #endif /* not MSDOS */
742 if (INTEGERP (buffer))
743 return unbind_to (count, Qnil);
745 if (BUFFERP (buffer))
746 Fset_buffer (buffer);
748 fd0 = callproc_fd[CALLPROC_PIPEREAD];
750 if (0 <= fd0)
752 Lisp_Object val, *args2;
754 val = Qnil;
755 if (!NILP (Vcoding_system_for_read))
756 val = Vcoding_system_for_read;
757 else
759 if (EQ (coding_systems, Qt))
761 ptrdiff_t i;
763 SAFE_NALLOCA (args2, 1, nargs + 1);
764 args2[0] = Qcall_process;
765 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
766 coding_systems
767 = Ffind_operation_coding_system (nargs + 1, args2);
769 if (CONSP (coding_systems))
770 val = XCAR (coding_systems);
771 else if (CONSP (Vdefault_process_coding_system))
772 val = XCAR (Vdefault_process_coding_system);
773 else
774 val = Qnil;
776 Fcheck_coding_system (val);
777 /* In unibyte mode, character code conversion should not take
778 place but EOL conversion should. So, setup raw-text or one
779 of the subsidiary according to the information just setup. */
780 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
781 && !NILP (val))
782 val = raw_text_coding_system (val);
783 setup_coding_system (val, &process_coding);
784 process_coding.dst_multibyte
785 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
786 process_coding.src_multibyte = 0;
789 immediate_quit = 1;
790 QUIT;
792 if (0 <= fd0)
794 enum { CALLPROC_BUFFER_SIZE_MIN = 16 * 1024 };
795 enum { CALLPROC_BUFFER_SIZE_MAX = 4 * CALLPROC_BUFFER_SIZE_MIN };
796 char buf[CALLPROC_BUFFER_SIZE_MAX];
797 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
798 int nread;
799 EMACS_INT total_read = 0;
800 int carryover = 0;
801 bool display_on_the_fly = display_p;
802 struct coding_system saved_coding = process_coding;
804 while (1)
806 /* Repeatedly read until we've filled as much as possible
807 of the buffer size we have. But don't read
808 less than 1024--save that for the next bufferful. */
809 nread = carryover;
810 while (nread < bufsize - 1024)
812 int this_read = emacs_read (fd0, buf + nread,
813 bufsize - nread);
815 if (this_read < 0)
816 goto give_up;
818 if (this_read == 0)
820 process_coding.mode |= CODING_MODE_LAST_BLOCK;
821 break;
824 nread += this_read;
825 total_read += this_read;
827 if (display_on_the_fly)
828 break;
831 /* Now NREAD is the total amount of data in the buffer. */
832 immediate_quit = 0;
834 if (!nread)
836 else if (NILP (BVAR (current_buffer, enable_multibyte_characters))
837 && ! CODING_MAY_REQUIRE_DECODING (&process_coding))
838 insert_1_both (buf, nread, nread, 0, 1, 0);
839 else
840 { /* We have to decode the input. */
841 Lisp_Object curbuf;
842 ptrdiff_t count1 = SPECPDL_INDEX ();
844 XSETBUFFER (curbuf, current_buffer);
845 /* FIXME: Call signal_after_change! */
846 prepare_to_modify_buffer (PT, PT, NULL);
847 /* We cannot allow after-change-functions be run
848 during decoding, because that might modify the
849 buffer, while we rely on process_coding.produced to
850 faithfully reflect inserted text until we
851 TEMP_SET_PT_BOTH below. */
852 specbind (Qinhibit_modification_hooks, Qt);
853 decode_coding_c_string (&process_coding,
854 (unsigned char *) buf, nread, curbuf);
855 unbind_to (count1, Qnil);
856 if (display_on_the_fly
857 && CODING_REQUIRE_DETECTION (&saved_coding)
858 && ! CODING_REQUIRE_DETECTION (&process_coding))
860 /* We have detected some coding system, but the
861 detection may have been via insufficient data.
862 So give up displaying on the fly. */
863 if (process_coding.produced > 0)
864 del_range_2 (process_coding.dst_pos,
865 process_coding.dst_pos_byte,
866 (process_coding.dst_pos
867 + process_coding.produced_char),
868 (process_coding.dst_pos_byte
869 + process_coding.produced),
871 display_on_the_fly = 0;
872 process_coding = saved_coding;
873 carryover = nread;
874 /* Make the above condition always fail in the future. */
875 saved_coding.common_flags
876 &= ~CODING_REQUIRE_DETECTION_MASK;
877 continue;
880 TEMP_SET_PT_BOTH (PT + process_coding.produced_char,
881 PT_BYTE + process_coding.produced);
882 carryover = process_coding.carryover_bytes;
883 if (carryover > 0)
884 memcpy (buf, process_coding.carryover,
885 process_coding.carryover_bytes);
888 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
889 break;
891 /* Make the buffer bigger as we continue to read more data,
892 but not past CALLPROC_BUFFER_SIZE_MAX. */
893 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
894 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
895 bufsize = CALLPROC_BUFFER_SIZE_MAX;
897 if (display_p)
899 redisplay_preserve_echo_area (1);
900 /* This variable might have been set to 0 for code
901 detection. In that case, set it back to 1 because
902 we should have already detected a coding system. */
903 display_on_the_fly = 1;
905 immediate_quit = 1;
906 QUIT;
908 give_up: ;
910 Vlast_coding_system_used = CODING_ID_NAME (process_coding.id);
911 /* If the caller required, let the buffer inherit the
912 coding-system used to decode the process output. */
913 if (inherit_process_coding_system)
914 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
915 make_number (total_read));
918 #ifndef MSDOS
919 /* Wait for it to terminate, unless it already has. */
920 wait_for_termination (pid, &status, fd0 < 0);
921 #endif
923 immediate_quit = 0;
925 /* Don't kill any children that the subprocess may have left behind
926 when exiting. */
927 synch_process_pid = 0;
929 SAFE_FREE ();
930 unbind_to (count, Qnil);
932 if (WIFSIGNALED (status))
934 const char *signame;
936 synchronize_system_messages_locale ();
937 signame = strsignal (WTERMSIG (status));
939 if (signame == 0)
940 signame = "unknown";
942 return code_convert_string_norecord (build_string (signame),
943 Vlocale_coding_system, 0);
946 eassert (WIFEXITED (status));
947 return make_number (WEXITSTATUS (status));
950 /* Create a temporary file suitable for storing the input data of
951 call-process-region. NARGS and ARGS are the same as for
952 call-process-region. Store into *FILENAME_STRING_PTR a Lisp string
953 naming the file, and return a file descriptor for reading.
954 Unwind-protect the file, so that the file descriptor will be closed
955 and the file removed when the caller unwinds the specpdl stack. */
957 static int
958 create_temp_file (ptrdiff_t nargs, Lisp_Object *args,
959 Lisp_Object *filename_string_ptr)
961 int fd;
962 struct gcpro gcpro1;
963 Lisp_Object filename_string;
964 Lisp_Object val, start, end;
965 Lisp_Object tmpdir;
967 if (STRINGP (Vtemporary_file_directory))
968 tmpdir = Vtemporary_file_directory;
969 else
971 char *outf;
972 #ifndef DOS_NT
973 outf = getenv ("TMPDIR");
974 tmpdir = build_string (outf ? outf : "/tmp/");
975 #else /* DOS_NT */
976 if ((outf = egetenv ("TMPDIR"))
977 || (outf = egetenv ("TMP"))
978 || (outf = egetenv ("TEMP")))
979 tmpdir = build_string (outf);
980 else
981 tmpdir = Ffile_name_as_directory (build_string ("c:/temp"));
982 #endif
986 Lisp_Object pattern = Fexpand_file_name (Vtemp_file_name_pattern, tmpdir);
987 char *tempfile;
988 ptrdiff_t count;
990 #ifdef WINDOWSNT
991 /* Cannot use the result of Fexpand_file_name, because it
992 downcases the XXXXXX part of the pattern, and mktemp then
993 doesn't recognize it. */
994 if (!NILP (Vw32_downcase_file_names))
996 Lisp_Object dirname = Ffile_name_directory (pattern);
998 if (NILP (dirname))
999 pattern = Vtemp_file_name_pattern;
1000 else
1001 pattern = concat2 (dirname, Vtemp_file_name_pattern);
1003 #endif
1005 filename_string = Fcopy_sequence (ENCODE_FILE (pattern));
1006 GCPRO1 (filename_string);
1007 tempfile = SSDATA (filename_string);
1009 count = SPECPDL_INDEX ();
1010 record_unwind_protect_nothing ();
1011 fd = mkostemp (tempfile, O_CLOEXEC);
1012 if (fd < 0)
1013 report_file_error ("Failed to open temporary file using pattern",
1014 pattern);
1015 set_unwind_protect (count, delete_temp_file, filename_string);
1016 record_unwind_protect_int (close_file_unwind, fd);
1019 start = args[0];
1020 end = args[1];
1021 /* Decide coding-system of the contents of the temporary file. */
1022 if (!NILP (Vcoding_system_for_write))
1023 val = Vcoding_system_for_write;
1024 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
1025 val = Qraw_text;
1026 else
1028 Lisp_Object coding_systems;
1029 Lisp_Object *args2;
1030 USE_SAFE_ALLOCA;
1031 SAFE_NALLOCA (args2, 1, nargs + 1);
1032 args2[0] = Qcall_process_region;
1033 memcpy (args2 + 1, args, nargs * sizeof *args);
1034 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1035 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
1036 SAFE_FREE ();
1038 val = complement_process_encoding_system (val);
1041 ptrdiff_t count1 = SPECPDL_INDEX ();
1043 specbind (intern ("coding-system-for-write"), val);
1044 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
1045 happen to get a ".Z" suffix. */
1046 specbind (intern ("file-name-handler-alist"), Qnil);
1047 write_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil, fd);
1049 unbind_to (count1, Qnil);
1052 if (lseek (fd, 0, SEEK_SET) < 0)
1053 report_file_error ("Setting file position", filename_string);
1055 /* Note that Fcall_process takes care of binding
1056 coding-system-for-read. */
1058 *filename_string_ptr = filename_string;
1059 UNGCPRO;
1060 return fd;
1063 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
1064 3, MANY, 0,
1065 doc: /* Send text from START to END to a synchronous process running PROGRAM.
1066 The remaining arguments are optional.
1067 Delete the text if fourth arg DELETE is non-nil.
1069 Insert output in BUFFER before point; t means current buffer; nil for
1070 BUFFER means discard it; 0 means discard and don't wait; and `(:file
1071 FILE)', where FILE is a file name string, means that it should be
1072 written to that file (if the file already exists it is overwritten).
1073 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1074 REAL-BUFFER says what to do with standard output, as above,
1075 while STDERR-FILE says what to do with standard error in the child.
1076 STDERR-FILE may be nil (discard standard error output),
1077 t (mix it with ordinary output), or a file name string.
1079 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1080 Remaining args are passed to PROGRAM at startup as command args.
1082 If BUFFER is 0, `call-process-region' returns immediately with value nil.
1083 Otherwise it waits for PROGRAM to terminate
1084 and returns a numeric exit status or a signal description string.
1085 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
1087 usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
1088 (ptrdiff_t nargs, Lisp_Object *args)
1090 struct gcpro gcpro1;
1091 Lisp_Object infile, val;
1092 ptrdiff_t count = SPECPDL_INDEX ();
1093 Lisp_Object start = args[0];
1094 Lisp_Object end = args[1];
1095 bool empty_input;
1096 int fd;
1098 if (STRINGP (start))
1099 empty_input = SCHARS (start) == 0;
1100 else if (NILP (start))
1101 empty_input = BEG == Z;
1102 else
1104 validate_region (&args[0], &args[1]);
1105 start = args[0];
1106 end = args[1];
1107 empty_input = XINT (start) == XINT (end);
1110 if (!empty_input)
1111 fd = create_temp_file (nargs, args, &infile);
1112 else
1114 infile = Qnil;
1115 fd = emacs_open (NULL_DEVICE, O_RDONLY, 0);
1116 if (fd < 0)
1117 report_file_error ("Opening null device", Qnil);
1118 record_unwind_protect_int (close_file_unwind, fd);
1121 GCPRO1 (infile);
1123 if (nargs > 3 && !NILP (args[3]))
1124 Fdelete_region (start, end);
1126 if (nargs > 3)
1128 args += 2;
1129 nargs -= 2;
1131 else
1133 args[0] = args[2];
1134 nargs = 2;
1136 args[1] = infile;
1138 val = call_process (nargs, args, fd, empty_input ? -1 : count);
1139 RETURN_UNGCPRO (unbind_to (count, val));
1142 #ifndef WINDOWSNT
1143 static int relocate_fd (int fd, int minfd);
1144 #endif
1146 static char **
1147 add_env (char **env, char **new_env, char *string)
1149 char **ep;
1150 bool ok = 1;
1151 if (string == NULL)
1152 return new_env;
1154 /* See if this string duplicates any string already in the env.
1155 If so, don't put it in.
1156 When an env var has multiple definitions,
1157 we keep the definition that comes first in process-environment. */
1158 for (ep = env; ok && ep != new_env; ep++)
1160 char *p = *ep, *q = string;
1161 while (ok)
1163 if (*q != *p)
1164 break;
1165 if (*q == 0)
1166 /* The string is a lone variable name; keep it for now, we
1167 will remove it later. It is a placeholder for a
1168 variable that is not to be included in the environment. */
1169 break;
1170 if (*q == '=')
1171 ok = 0;
1172 p++, q++;
1175 if (ok)
1176 *new_env++ = string;
1177 return new_env;
1180 /* This is the last thing run in a newly forked inferior
1181 either synchronous or asynchronous.
1182 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1183 Initialize inferior's priority, pgrp, connected dir and environment.
1184 then exec another program based on new_argv.
1186 If SET_PGRP, put the subprocess into a separate process group.
1188 CURRENT_DIR is an elisp string giving the path of the current
1189 directory the subprocess should have. Since we can't really signal
1190 a decent error from within the child, this should be verified as an
1191 executable directory by the parent. */
1194 child_setup (int in, int out, int err, char **new_argv, bool set_pgrp,
1195 Lisp_Object current_dir)
1197 char **env;
1198 char *pwd_var;
1199 #ifdef WINDOWSNT
1200 int cpid;
1201 HANDLE handles[3];
1202 #else
1203 int exec_errno;
1205 pid_t pid = getpid ();
1206 #endif /* WINDOWSNT */
1208 /* Note that use of alloca is always safe here. It's obvious for systems
1209 that do not have true vfork or that have true (stack) alloca.
1210 If using vfork and C_ALLOCA (when Emacs used to include
1211 src/alloca.c) it is safe because that changes the superior's
1212 static variables as if the superior had done alloca and will be
1213 cleaned up in the usual way. */
1215 char *temp;
1216 ptrdiff_t i;
1218 i = SBYTES (current_dir);
1219 #ifdef MSDOS
1220 /* MSDOS must have all environment variables malloc'ed, because
1221 low-level libc functions that launch subsidiary processes rely
1222 on that. */
1223 pwd_var = xmalloc (i + 5);
1224 #else
1225 pwd_var = alloca (i + 5);
1226 #endif
1227 temp = pwd_var + 4;
1228 memcpy (pwd_var, "PWD=", 4);
1229 strcpy (temp, SSDATA (current_dir));
1231 #ifndef DOS_NT
1232 /* We can't signal an Elisp error here; we're in a vfork. Since
1233 the callers check the current directory before forking, this
1234 should only return an error if the directory's permissions
1235 are changed between the check and this chdir, but we should
1236 at least check. */
1237 if (chdir (temp) < 0)
1238 _exit (EXIT_CANCELED);
1239 #else /* DOS_NT */
1240 /* Get past the drive letter, so that d:/ is left alone. */
1241 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1243 temp += 2;
1244 i -= 2;
1246 #endif /* DOS_NT */
1248 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1249 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1250 temp[--i] = 0;
1253 /* Set `env' to a vector of the strings in the environment. */
1255 register Lisp_Object tem;
1256 register char **new_env;
1257 char **p, **q;
1258 register int new_length;
1259 Lisp_Object display = Qnil;
1261 new_length = 0;
1263 for (tem = Vprocess_environment;
1264 CONSP (tem) && STRINGP (XCAR (tem));
1265 tem = XCDR (tem))
1267 if (strncmp (SSDATA (XCAR (tem)), "DISPLAY", 7) == 0
1268 && (SDATA (XCAR (tem)) [7] == '\0'
1269 || SDATA (XCAR (tem)) [7] == '='))
1270 /* DISPLAY is specified in process-environment. */
1271 display = Qt;
1272 new_length++;
1275 /* If not provided yet, use the frame's DISPLAY. */
1276 if (NILP (display))
1278 Lisp_Object tmp = Fframe_parameter (selected_frame, Qdisplay);
1279 if (!STRINGP (tmp) && CONSP (Vinitial_environment))
1280 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1281 tmp = Fgetenv_internal (build_string ("DISPLAY"),
1282 Vinitial_environment);
1283 if (STRINGP (tmp))
1285 display = tmp;
1286 new_length++;
1290 /* new_length + 2 to include PWD and terminating 0. */
1291 env = new_env = alloca ((new_length + 2) * sizeof *env);
1292 /* If we have a PWD envvar, pass one down,
1293 but with corrected value. */
1294 if (egetenv ("PWD"))
1295 *new_env++ = pwd_var;
1297 if (STRINGP (display))
1299 char *vdata = alloca (sizeof "DISPLAY=" + SBYTES (display));
1300 strcpy (vdata, "DISPLAY=");
1301 strcat (vdata, SSDATA (display));
1302 new_env = add_env (env, new_env, vdata);
1305 /* Overrides. */
1306 for (tem = Vprocess_environment;
1307 CONSP (tem) && STRINGP (XCAR (tem));
1308 tem = XCDR (tem))
1309 new_env = add_env (env, new_env, SSDATA (XCAR (tem)));
1311 *new_env = 0;
1313 /* Remove variable names without values. */
1314 p = q = env;
1315 while (*p != 0)
1317 while (*q != 0 && strchr (*q, '=') == NULL)
1318 q++;
1319 *p = *q++;
1320 if (*p != 0)
1321 p++;
1326 #ifdef WINDOWSNT
1327 prepare_standard_handles (in, out, err, handles);
1328 set_process_dir (SDATA (current_dir));
1329 /* Spawn the child. (See w32proc.c:sys_spawnve). */
1330 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1331 reset_standard_handles (in, out, err, handles);
1332 if (cpid == -1)
1333 /* An error occurred while trying to spawn the process. */
1334 report_file_error ("Spawning child process", Qnil);
1335 return cpid;
1337 #else /* not WINDOWSNT */
1338 /* Make sure that in, out, and err are not actually already in
1339 descriptors zero, one, or two; this could happen if Emacs is
1340 started with its standard in, out, or error closed, as might
1341 happen under X. */
1343 int oin = in, oout = out;
1345 /* We have to avoid relocating the same descriptor twice! */
1347 in = relocate_fd (in, 3);
1349 if (out == oin)
1350 out = in;
1351 else
1352 out = relocate_fd (out, 3);
1354 if (err == oin)
1355 err = in;
1356 else if (err == oout)
1357 err = out;
1358 else
1359 err = relocate_fd (err, 3);
1362 #ifndef MSDOS
1363 /* Redirect file descriptors and clear the close-on-exec flag on the
1364 redirected ones. IN, OUT, and ERR are close-on-exec so they
1365 need not be closed explicitly. */
1366 dup2 (in, 0);
1367 dup2 (out, 1);
1368 dup2 (err, 2);
1370 setpgid (0, 0);
1371 tcsetpgrp (0, pid);
1373 execve (new_argv[0], new_argv, env);
1374 exec_errno = errno;
1376 /* Avoid deadlock if the child's perror writes to a full pipe; the
1377 pipe's reader is the parent, but with vfork the parent can't
1378 run until the child exits. Truncate the diagnostic instead. */
1379 fcntl (STDERR_FILENO, F_SETFL, O_NONBLOCK);
1381 errno = exec_errno;
1382 emacs_perror (new_argv[0]);
1383 _exit (exec_errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1385 #else /* MSDOS */
1386 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1387 xfree (pwd_var);
1388 if (pid == -1)
1389 /* An error occurred while trying to run the subprocess. */
1390 report_file_error ("Spawning child process", Qnil);
1391 return pid;
1392 #endif /* MSDOS */
1393 #endif /* not WINDOWSNT */
1396 #ifndef WINDOWSNT
1397 /* Move the file descriptor FD so that its number is not less than MINFD.
1398 If the file descriptor is moved at all, the original is closed on MSDOS,
1399 but not elsewhere as the caller will close it anyway. */
1400 static int
1401 relocate_fd (int fd, int minfd)
1403 if (fd >= minfd)
1404 return fd;
1405 else
1407 int new = fcntl (fd, F_DUPFD_CLOEXEC, minfd);
1408 if (new == -1)
1410 emacs_perror ("while setting up child");
1411 _exit (EXIT_CANCELED);
1413 #ifdef MSDOS
1414 emacs_close (fd);
1415 #endif
1416 return new;
1419 #endif /* not WINDOWSNT */
1421 static bool
1422 getenv_internal_1 (const char *var, ptrdiff_t varlen, char **value,
1423 ptrdiff_t *valuelen, Lisp_Object env)
1425 for (; CONSP (env); env = XCDR (env))
1427 Lisp_Object entry = XCAR (env);
1428 if (STRINGP (entry)
1429 && SBYTES (entry) >= varlen
1430 #ifdef WINDOWSNT
1431 /* NT environment variables are case insensitive. */
1432 && ! strnicmp (SDATA (entry), var, varlen)
1433 #else /* not WINDOWSNT */
1434 && ! memcmp (SDATA (entry), var, varlen)
1435 #endif /* not WINDOWSNT */
1438 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1440 *value = SSDATA (entry) + (varlen + 1);
1441 *valuelen = SBYTES (entry) - (varlen + 1);
1442 return 1;
1444 else if (SBYTES (entry) == varlen)
1446 /* Lone variable names in Vprocess_environment mean that
1447 variable should be removed from the environment. */
1448 *value = NULL;
1449 return 1;
1453 return 0;
1456 static bool
1457 getenv_internal (const char *var, ptrdiff_t varlen, char **value,
1458 ptrdiff_t *valuelen, Lisp_Object frame)
1460 /* Try to find VAR in Vprocess_environment first. */
1461 if (getenv_internal_1 (var, varlen, value, valuelen,
1462 Vprocess_environment))
1463 return *value ? 1 : 0;
1465 /* For DISPLAY try to get the values from the frame or the initial env. */
1466 if (strcmp (var, "DISPLAY") == 0)
1468 Lisp_Object display
1469 = Fframe_parameter (NILP (frame) ? selected_frame : frame, Qdisplay);
1470 if (STRINGP (display))
1472 *value = SSDATA (display);
1473 *valuelen = SBYTES (display);
1474 return 1;
1476 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1477 if (getenv_internal_1 (var, varlen, value, valuelen,
1478 Vinitial_environment))
1479 return *value ? 1 : 0;
1482 return 0;
1485 DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
1486 doc: /* Get the value of environment variable VARIABLE.
1487 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1488 the environment. Otherwise, value is a string.
1490 This function searches `process-environment' for VARIABLE.
1492 If optional parameter ENV is a list, then search this list instead of
1493 `process-environment', and return t when encountering a negative entry
1494 \(an entry for a variable with no value). */)
1495 (Lisp_Object variable, Lisp_Object env)
1497 char *value;
1498 ptrdiff_t valuelen;
1500 CHECK_STRING (variable);
1501 if (CONSP (env))
1503 if (getenv_internal_1 (SSDATA (variable), SBYTES (variable),
1504 &value, &valuelen, env))
1505 return value ? make_string (value, valuelen) : Qt;
1506 else
1507 return Qnil;
1509 else if (getenv_internal (SSDATA (variable), SBYTES (variable),
1510 &value, &valuelen, env))
1511 return make_string (value, valuelen);
1512 else
1513 return Qnil;
1516 /* A version of getenv that consults the Lisp environment lists,
1517 easily callable from C. */
1518 char *
1519 egetenv (const char *var)
1521 char *value;
1522 ptrdiff_t valuelen;
1524 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
1525 return value;
1526 else
1527 return 0;
1531 /* This is run before init_cmdargs. */
1533 void
1534 init_callproc_1 (void)
1536 #ifdef HAVE_NS
1537 const char *etc_dir = ns_etc_directory ();
1538 const char *path_exec = ns_exec_path ();
1539 #endif
1541 Vdata_directory = decode_env_path ("EMACSDATA",
1542 #ifdef HAVE_NS
1543 etc_dir ? etc_dir :
1544 #endif
1545 PATH_DATA, 0);
1546 Vdata_directory = Ffile_name_as_directory (Fcar (Vdata_directory));
1548 Vdoc_directory = decode_env_path ("EMACSDOC",
1549 #ifdef HAVE_NS
1550 etc_dir ? etc_dir :
1551 #endif
1552 PATH_DOC, 0);
1553 Vdoc_directory = Ffile_name_as_directory (Fcar (Vdoc_directory));
1555 /* Check the EMACSPATH environment variable, defaulting to the
1556 PATH_EXEC path from epaths.h. */
1557 Vexec_path = decode_env_path ("EMACSPATH",
1558 #ifdef HAVE_NS
1559 path_exec ? path_exec :
1560 #endif
1561 PATH_EXEC, 0);
1562 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1563 /* FIXME? For ns, path_exec should go at the front? */
1564 Vexec_path = nconc2 (decode_env_path ("PATH", "", 0), Vexec_path);
1567 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1569 void
1570 init_callproc (void)
1572 char *data_dir = egetenv ("EMACSDATA");
1574 register char * sh;
1575 Lisp_Object tempdir;
1576 #ifdef HAVE_NS
1577 if (data_dir == 0)
1579 const char *etc_dir = ns_etc_directory ();
1580 if (etc_dir)
1582 data_dir = alloca (strlen (etc_dir) + 1);
1583 strcpy (data_dir, etc_dir);
1586 #endif
1588 if (!NILP (Vinstallation_directory))
1590 /* Add to the path the lib-src subdir of the installation dir. */
1591 Lisp_Object tem;
1592 tem = Fexpand_file_name (build_string ("lib-src"),
1593 Vinstallation_directory);
1594 #ifndef MSDOS
1595 /* MSDOS uses wrapped binaries, so don't do this. */
1596 if (NILP (Fmember (tem, Vexec_path)))
1598 #ifdef HAVE_NS
1599 const char *path_exec = ns_exec_path ();
1600 #endif
1601 Vexec_path = decode_env_path ("EMACSPATH",
1602 #ifdef HAVE_NS
1603 path_exec ? path_exec :
1604 #endif
1605 PATH_EXEC, 0);
1606 Vexec_path = Fcons (tem, Vexec_path);
1607 Vexec_path = nconc2 (decode_env_path ("PATH", "", 0), Vexec_path);
1610 Vexec_directory = Ffile_name_as_directory (tem);
1611 #endif /* not MSDOS */
1613 /* Maybe use ../etc as well as ../lib-src. */
1614 if (data_dir == 0)
1616 tem = Fexpand_file_name (build_string ("etc"),
1617 Vinstallation_directory);
1618 Vdoc_directory = Ffile_name_as_directory (tem);
1622 /* Look for the files that should be in etc. We don't use
1623 Vinstallation_directory, because these files are never installed
1624 near the executable, and they are never in the build
1625 directory when that's different from the source directory.
1627 Instead, if these files are not in the nominal place, we try the
1628 source directory. */
1629 if (data_dir == 0)
1631 Lisp_Object tem, tem1, srcdir;
1632 Lisp_Object lispdir = Fcar (decode_env_path (0, PATH_DUMPLOADSEARCH, 0));
1634 srcdir = Fexpand_file_name (build_string ("../src/"), lispdir);
1636 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1637 tem1 = Ffile_exists_p (tem);
1638 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
1640 Lisp_Object newdir;
1641 newdir = Fexpand_file_name (build_string ("../etc/"), lispdir);
1642 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1643 tem1 = Ffile_exists_p (tem);
1644 if (!NILP (tem1))
1645 Vdata_directory = newdir;
1649 #ifndef CANNOT_DUMP
1650 if (initialized)
1651 #endif
1653 tempdir = Fdirectory_file_name (Vexec_directory);
1654 if (! file_accessible_directory_p (SSDATA (tempdir)))
1655 dir_warning ("arch-dependent data dir", Vexec_directory);
1658 tempdir = Fdirectory_file_name (Vdata_directory);
1659 if (! file_accessible_directory_p (SSDATA (tempdir)))
1660 dir_warning ("arch-independent data dir", Vdata_directory);
1662 sh = getenv ("SHELL");
1663 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1665 #ifdef DOS_NT
1666 Vshared_game_score_directory = Qnil;
1667 #else
1668 Vshared_game_score_directory = build_unibyte_string (PATH_GAME);
1669 if (NILP (Ffile_accessible_directory_p (Vshared_game_score_directory)))
1670 Vshared_game_score_directory = Qnil;
1671 #endif
1674 void
1675 set_initial_environment (void)
1677 char **envp;
1678 for (envp = environ; *envp; envp++)
1679 Vprocess_environment = Fcons (build_string (*envp),
1680 Vprocess_environment);
1681 /* Ideally, the `copy' shouldn't be necessary, but it seems it's frequent
1682 to use `delete' and friends on process-environment. */
1683 Vinitial_environment = Fcopy_sequence (Vprocess_environment);
1686 void
1687 syms_of_callproc (void)
1689 #ifndef DOS_NT
1690 Vtemp_file_name_pattern = build_string ("emacsXXXXXX");
1691 #else /* DOS_NT */
1692 Vtemp_file_name_pattern = build_string ("emXXXXXX");
1693 #endif
1694 staticpro (&Vtemp_file_name_pattern);
1696 #ifdef MSDOS
1697 synch_process_tempfile = make_number (0);
1698 staticpro (&synch_process_tempfile);
1699 #endif
1701 DEFVAR_LISP ("shell-file-name", Vshell_file_name,
1702 doc: /* File name to load inferior shells from.
1703 Initialized from the SHELL environment variable, or to a system-dependent
1704 default if SHELL is not set. */);
1706 DEFVAR_LISP ("exec-path", Vexec_path,
1707 doc: /* List of directories to search programs to run in subprocesses.
1708 Each element is a string (directory name) or nil (try default directory).
1710 By default the last element of this list is `exec-directory'. The
1711 last element is not always used, for example in shell completion
1712 (`shell-dynamic-complete-command'). */);
1714 DEFVAR_LISP ("exec-suffixes", Vexec_suffixes,
1715 doc: /* List of suffixes to try to find executable file names.
1716 Each element is a string. */);
1717 Vexec_suffixes = Qnil;
1719 DEFVAR_LISP ("exec-directory", Vexec_directory,
1720 doc: /* Directory for executables for Emacs to invoke.
1721 More generally, this includes any architecture-dependent files
1722 that are built and installed from the Emacs distribution. */);
1724 DEFVAR_LISP ("data-directory", Vdata_directory,
1725 doc: /* Directory of machine-independent files that come with GNU Emacs.
1726 These are files intended for Emacs to use while it runs. */);
1728 DEFVAR_LISP ("doc-directory", Vdoc_directory,
1729 doc: /* Directory containing the DOC file that comes with GNU Emacs.
1730 This is usually the same as `data-directory'. */);
1732 DEFVAR_LISP ("configure-info-directory", Vconfigure_info_directory,
1733 doc: /* For internal use by the build procedure only.
1734 This is the name of the directory in which the build procedure installed
1735 Emacs's info files; the default value for `Info-default-directory-list'
1736 includes this. */);
1737 Vconfigure_info_directory = build_string (PATH_INFO);
1739 DEFVAR_LISP ("shared-game-score-directory", Vshared_game_score_directory,
1740 doc: /* Directory of score files for games which come with GNU Emacs.
1741 If this variable is nil, then Emacs is unable to use a shared directory. */);
1742 #ifdef DOS_NT
1743 Vshared_game_score_directory = Qnil;
1744 #else
1745 Vshared_game_score_directory = build_string (PATH_GAME);
1746 #endif
1748 DEFVAR_LISP ("initial-environment", Vinitial_environment,
1749 doc: /* List of environment variables inherited from the parent process.
1750 Each element should be a string of the form ENVVARNAME=VALUE.
1751 The elements must normally be decoded (using `locale-coding-system') for use. */);
1752 Vinitial_environment = Qnil;
1754 DEFVAR_LISP ("process-environment", Vprocess_environment,
1755 doc: /* List of overridden environment variables for subprocesses to inherit.
1756 Each element should be a string of the form ENVVARNAME=VALUE.
1758 Entries in this list take precedence to those in the frame-local
1759 environments. Therefore, let-binding `process-environment' is an easy
1760 way to temporarily change the value of an environment variable,
1761 irrespective of where it comes from. To use `process-environment' to
1762 remove an environment variable, include only its name in the list,
1763 without "=VALUE".
1765 This variable is set to nil when Emacs starts.
1767 If multiple entries define the same variable, the first one always
1768 takes precedence.
1770 Non-ASCII characters are encoded according to the initial value of
1771 `locale-coding-system', i.e. the elements must normally be decoded for
1772 use.
1774 See `setenv' and `getenv'. */);
1775 Vprocess_environment = Qnil;
1777 defsubr (&Scall_process);
1778 defsubr (&Sgetenv_internal);
1779 defsubr (&Scall_process_region);