Fix MS-Windows build.
[emacs.git] / src / callproc.c
blob938c2fbd04b5dfe6cf9123939b0b9d62bd0a2143
1 /* Synchronous subprocess invocation for GNU Emacs.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2013
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>
29 #ifdef WINDOWSNT
30 #define NOMINMAX
31 #include <sys/socket.h> /* for fcntl */
32 #endif
34 #include "lisp.h"
36 #ifdef WINDOWSNT
37 #include <windows.h>
38 #include "w32.h"
39 #define _P_NOWAIT 1 /* from process.h */
40 #endif
42 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
43 #include <sys/stat.h>
44 #include <sys/param.h>
45 #endif /* MSDOS */
47 #include "commands.h"
48 #include "character.h"
49 #include "buffer.h"
50 #include "ccl.h"
51 #include "coding.h"
52 #include "composite.h"
53 #include <epaths.h>
54 #include "process.h"
55 #include "syssignal.h"
56 #include "systty.h"
57 #include "syswait.h"
58 #include "blockinput.h"
59 #include "frame.h"
60 #include "termhooks.h"
62 #ifdef MSDOS
63 #include "msdos.h"
64 #endif
66 #ifdef HAVE_NS
67 #include "nsterm.h"
68 #endif
70 /* Pattern used by call-process-region to make temp files. */
71 static Lisp_Object Vtemp_file_name_pattern;
73 /* The next two variables are used while record-unwind-protect is in place
74 during call-process for a subprocess for which record_deleted_pid has
75 not yet been called. At other times, synch_process_pid is zero and
76 synch_process_tempfile's contents are irrelevant. Doing this via static
77 C variables is more convenient than putting them into the arguments
78 of record-unwind-protect, as they need to be updated at randomish
79 times in the code, and Lisp cannot always store these values as
80 Emacs integers. It's safe to use static variables here, as the
81 code is never invoked reentrantly. */
83 /* If nonzero, a process-ID that has not been reaped. */
84 static pid_t synch_process_pid;
86 /* If a string, the name of a temp file that has not been removed. */
87 #ifdef MSDOS
88 static Lisp_Object synch_process_tempfile;
89 #else
90 # define synch_process_tempfile make_number (0)
91 #endif
93 /* Indexes of file descriptors that need closing on call_process_kill. */
94 enum
96 /* The subsidiary process's stdout and stderr. stdin is handled
97 separately, in either Fcall_process_region or create_temp_file. */
98 CALLPROC_STDOUT, CALLPROC_STDERR,
100 /* How to read from a pipe (or substitute) from the subsidiary process. */
101 CALLPROC_PIPEREAD,
103 /* A bound on the number of file descriptors. */
104 CALLPROC_FDS
107 static Lisp_Object call_process (ptrdiff_t, Lisp_Object *, int, ptrdiff_t);
109 /* Block SIGCHLD. */
111 void
112 block_child_signal (void)
114 sigset_t blocked;
115 sigemptyset (&blocked);
116 sigaddset (&blocked, SIGCHLD);
117 pthread_sigmask (SIG_BLOCK, &blocked, 0);
120 /* Unblock SIGCHLD. */
122 void
123 unblock_child_signal (void)
125 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
128 /* Return the current buffer's working directory, or the home
129 directory if it's unreachable, as a string suitable for a system call.
130 Signal an error if the result would not be an accessible directory. */
132 Lisp_Object
133 encode_current_directory (void)
135 Lisp_Object dir;
136 struct gcpro gcpro1;
138 dir = BVAR (current_buffer, directory);
139 GCPRO1 (dir);
141 dir = Funhandled_file_name_directory (dir);
143 /* If the file name handler says that dir is unreachable, use
144 a sensible default. */
145 if (NILP (dir))
146 dir = build_string ("~");
148 dir = expand_and_dir_to_file (dir, Qnil);
150 if (STRING_MULTIBYTE (dir))
151 dir = ENCODE_FILE (dir);
152 if (! file_accessible_directory_p (SSDATA (dir)))
153 report_file_error ("Setting current directory",
154 BVAR (current_buffer, directory));
156 RETURN_UNGCPRO (dir);
159 /* If P is reapable, record it as a deleted process and kill it.
160 Do this in a critical section. Unless PID is wedged it will be
161 reaped on receipt of the first SIGCHLD after the critical section. */
163 void
164 record_kill_process (struct Lisp_Process *p, Lisp_Object tempfile)
166 block_child_signal ();
168 if (p->alive)
170 record_deleted_pid (p->pid, tempfile);
171 p->alive = 0;
172 kill (- p->pid, SIGKILL);
175 unblock_child_signal ();
178 /* Clean up files, file descriptors and processes created by Fcall_process. */
180 static void
181 delete_temp_file (Lisp_Object name)
183 unlink (SSDATA (name));
186 static void
187 call_process_kill (void *ptr)
189 int *callproc_fd = ptr;
190 int i;
191 for (i = 0; i < CALLPROC_FDS; i++)
192 if (0 <= callproc_fd[i])
193 emacs_close (callproc_fd[i]);
195 if (synch_process_pid)
197 struct Lisp_Process proc;
198 proc.alive = 1;
199 proc.pid = synch_process_pid;
200 record_kill_process (&proc, synch_process_tempfile);
201 synch_process_pid = 0;
203 else if (STRINGP (synch_process_tempfile))
204 delete_temp_file (synch_process_tempfile);
207 /* Clean up when exiting Fcall_process: restore the buffer, and
208 kill the subsidiary process group if the process still exists. */
210 static void
211 call_process_cleanup (Lisp_Object buffer)
213 Fset_buffer (buffer);
215 if (synch_process_pid)
217 kill (-synch_process_pid, SIGINT);
218 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
219 immediate_quit = 1;
220 QUIT;
221 wait_for_termination (synch_process_pid, 0, 1);
222 synch_process_pid = 0;
223 immediate_quit = 0;
224 message1 ("Waiting for process to die...done");
228 #ifdef DOS_NT
229 static mode_t const default_output_mode = S_IREAD | S_IWRITE;
230 #else
231 static mode_t const default_output_mode = 0666;
232 #endif
234 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
235 doc: /* Call PROGRAM synchronously in separate process.
236 The remaining arguments are optional.
237 The program's input comes from file INFILE (nil means `/dev/null').
238 Insert output in DESTINATION before point; t means current buffer; nil for DESTINATION
239 means discard it; 0 means discard and don't wait; and `(:file FILE)', where
240 FILE is a file name string, means that it should be written to that file
241 \(if the file already exists it is overwritten).
242 DESTINATION can also have the form (REAL-BUFFER STDERR-FILE); in that case,
243 REAL-BUFFER says what to do with standard output, as above,
244 while STDERR-FILE says what to do with standard error in the child.
245 STDERR-FILE may be nil (discard standard error output),
246 t (mix it with ordinary output), or a file name string.
248 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
249 Remaining arguments are strings passed as command arguments to PROGRAM.
251 If executable PROGRAM can't be found as an executable, `call-process'
252 signals a Lisp error. `call-process' reports errors in execution of
253 the program only through its return and output.
255 If DESTINATION is 0, `call-process' returns immediately with value nil.
256 Otherwise it waits for PROGRAM to terminate
257 and returns a numeric exit status or a signal description string.
258 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
260 usage: (call-process PROGRAM &optional INFILE DESTINATION DISPLAY &rest ARGS) */)
261 (ptrdiff_t nargs, Lisp_Object *args)
263 Lisp_Object infile, encoded_infile;
264 int filefd;
265 struct gcpro gcpro1;
266 ptrdiff_t count = SPECPDL_INDEX ();
268 if (nargs >= 2 && ! NILP (args[1]))
270 infile = Fexpand_file_name (args[1], BVAR (current_buffer, directory));
271 CHECK_STRING (infile);
273 else
274 infile = build_string (NULL_DEVICE);
276 GCPRO1 (infile);
277 encoded_infile = STRING_MULTIBYTE (infile) ? ENCODE_FILE (infile) : infile;
279 filefd = emacs_open (SSDATA (encoded_infile), O_RDONLY, 0);
280 if (filefd < 0)
281 report_file_error ("Opening process input file", infile);
282 record_unwind_protect_int (close_file_unwind, filefd);
283 UNGCPRO;
284 return unbind_to (count, call_process (nargs, args, filefd, -1));
287 /* Like Fcall_process (NARGS, ARGS), except use FILEFD as the input file.
289 If TEMPFILE_INDEX is nonnegative, it is the specpdl index of an
290 unwinder that is intended to remove the input temporary file; in
291 this case NARGS must be at least 2 and ARGS[1] is the file's name.
293 At entry, the specpdl stack top entry must be close_file_unwind (FILEFD). */
295 static Lisp_Object
296 call_process (ptrdiff_t nargs, Lisp_Object *args, int filefd,
297 ptrdiff_t tempfile_index)
299 Lisp_Object buffer, current_dir, path;
300 bool display_p;
301 int fd0;
302 int callproc_fd[CALLPROC_FDS];
303 int status;
304 ptrdiff_t i;
305 ptrdiff_t count = SPECPDL_INDEX ();
306 USE_SAFE_ALLOCA;
308 char **new_argv;
309 /* File to use for stderr in the child.
310 t means use same as standard output. */
311 Lisp_Object error_file;
312 Lisp_Object output_file = Qnil;
313 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
314 char *tempfile = NULL;
315 int pid;
316 #else
317 pid_t pid;
318 #endif
319 int child_errno;
320 int fd_output, fd_error;
321 struct coding_system process_coding; /* coding-system of process output */
322 struct coding_system argument_coding; /* coding-system of arguments */
323 /* Set to the return value of Ffind_operation_coding_system. */
324 Lisp_Object coding_systems;
325 bool discard_output;
327 if (synch_process_pid)
328 error ("call-process invoked recursively");
330 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
331 coding_systems = Qt;
333 CHECK_STRING (args[0]);
335 error_file = Qt;
337 #ifndef subprocesses
338 /* Without asynchronous processes we cannot have BUFFER == 0. */
339 if (nargs >= 3
340 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
341 error ("Operating system cannot handle asynchronous subprocesses");
342 #endif /* subprocesses */
344 /* Decide the coding-system for giving arguments. */
346 Lisp_Object val, *args2;
348 /* If arguments are supplied, we may have to encode them. */
349 if (nargs >= 5)
351 bool must_encode = 0;
352 Lisp_Object coding_attrs;
354 for (i = 4; i < nargs; i++)
355 CHECK_STRING (args[i]);
357 for (i = 4; i < nargs; i++)
358 if (STRING_MULTIBYTE (args[i]))
359 must_encode = 1;
361 if (!NILP (Vcoding_system_for_write))
362 val = Vcoding_system_for_write;
363 else if (! must_encode)
364 val = Qraw_text;
365 else
367 SAFE_NALLOCA (args2, 1, nargs + 1);
368 args2[0] = Qcall_process;
369 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
370 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
371 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
373 val = complement_process_encoding_system (val);
374 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
375 coding_attrs = CODING_ID_ATTRS (argument_coding.id);
376 if (NILP (CODING_ATTR_ASCII_COMPAT (coding_attrs)))
378 /* We should not use an ASCII incompatible coding system. */
379 val = raw_text_coding_system (val);
380 setup_coding_system (val, &argument_coding);
385 if (nargs < 3)
386 buffer = Qnil;
387 else
389 buffer = args[2];
391 /* If BUFFER is a list, its meaning is (BUFFER-FOR-STDOUT
392 FILE-FOR-STDERR), unless the first element is :file, in which case see
393 the next paragraph. */
394 if (CONSP (buffer) && !EQ (XCAR (buffer), QCfile))
396 if (CONSP (XCDR (buffer)))
398 Lisp_Object stderr_file;
399 stderr_file = XCAR (XCDR (buffer));
401 if (NILP (stderr_file) || EQ (Qt, stderr_file))
402 error_file = stderr_file;
403 else
404 error_file = Fexpand_file_name (stderr_file, Qnil);
407 buffer = XCAR (buffer);
410 /* If the buffer is (still) a list, it might be a (:file "file") spec. */
411 if (CONSP (buffer) && EQ (XCAR (buffer), QCfile))
413 output_file = Fexpand_file_name (XCAR (XCDR (buffer)),
414 BVAR (current_buffer, directory));
415 CHECK_STRING (output_file);
416 buffer = Qnil;
419 if (! (NILP (buffer) || EQ (buffer, Qt) || INTEGERP (buffer)))
421 Lisp_Object spec_buffer;
422 spec_buffer = buffer;
423 buffer = Fget_buffer_create (buffer);
424 /* Mention the buffer name for a better error message. */
425 if (NILP (buffer))
426 CHECK_BUFFER (spec_buffer);
427 CHECK_BUFFER (buffer);
431 /* Make sure that the child will be able to chdir to the current
432 buffer's current directory, or its unhandled equivalent. We
433 can't just have the child check for an error when it does the
434 chdir, since it's in a vfork.
436 We have to GCPRO around this because Fexpand_file_name,
437 Funhandled_file_name_directory, and Ffile_accessible_directory_p
438 might call a file name handling function. The argument list is
439 protected by the caller, so all we really have to worry about is
440 buffer. */
442 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
444 current_dir = encode_current_directory ();
446 GCPRO4 (buffer, current_dir, error_file, output_file);
448 if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
449 error_file = ENCODE_FILE (error_file);
450 if (STRINGP (output_file) && STRING_MULTIBYTE (output_file))
451 output_file = ENCODE_FILE (output_file);
452 UNGCPRO;
455 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
457 for (i = 0; i < CALLPROC_FDS; i++)
458 callproc_fd[i] = -1;
459 #ifdef MSDOS
460 synch_process_tempfile = make_number (0);
461 #endif
462 record_unwind_protect_ptr (call_process_kill, callproc_fd);
464 /* Search for program; barf if not found. */
466 struct gcpro gcpro1, gcpro2, gcpro3;
467 int ok;
469 GCPRO3 (buffer, current_dir, error_file);
470 ok = openp (Vexec_path, args[0], Vexec_suffixes, &path, make_number (X_OK));
471 UNGCPRO;
472 if (ok < 0)
473 report_file_error ("Searching for program", args[0]);
476 /* If program file name starts with /: for quoting a magic name,
477 discard that. */
478 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
479 && SREF (path, 1) == ':')
480 path = Fsubstring (path, make_number (2), Qnil);
482 new_argv = SAFE_ALLOCA ((nargs > 4 ? nargs - 2 : 2) * sizeof *new_argv);
485 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
487 GCPRO4 (buffer, current_dir, path, error_file);
488 if (nargs > 4)
490 ptrdiff_t i;
492 argument_coding.dst_multibyte = 0;
493 for (i = 4; i < nargs; i++)
495 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
496 if (CODING_REQUIRE_ENCODING (&argument_coding))
497 /* We must encode this argument. */
498 args[i] = encode_coding_string (&argument_coding, args[i], 1);
500 for (i = 4; i < nargs; i++)
501 new_argv[i - 3] = SSDATA (args[i]);
502 new_argv[i - 3] = 0;
504 else
505 new_argv[1] = 0;
506 if (STRING_MULTIBYTE (path))
507 path = ENCODE_FILE (path);
508 new_argv[0] = SSDATA (path);
509 UNGCPRO;
512 discard_output = INTEGERP (buffer) || (NILP (buffer) && NILP (output_file));
514 #ifdef MSDOS
515 if (! discard_output && ! STRINGP (output_file))
517 char const *tmpdir = egetenv ("TMPDIR");
518 char const *outf = tmpdir ? tmpdir : "";
519 tempfile = alloca (strlen (outf) + 20);
520 strcpy (tempfile, outf);
521 dostounix_filename (tempfile, 0);
522 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
523 strcat (tempfile, "/");
524 strcat (tempfile, "detmp.XXX");
525 mktemp (tempfile);
526 if (!*tempfile)
527 report_file_error ("Opening process output file", Qnil);
528 output_file = build_string (tempfile);
529 synch_process_tempfile = output_file;
531 #endif
533 if (discard_output)
535 fd_output = emacs_open (NULL_DEVICE, O_WRONLY, 0);
536 if (fd_output < 0)
537 report_file_error ("Opening null device", Qnil);
539 else if (STRINGP (output_file))
541 fd_output = emacs_open (SSDATA (output_file),
542 O_WRONLY | O_CREAT | O_TRUNC | O_TEXT,
543 default_output_mode);
544 if (fd_output < 0)
546 int open_errno = errno;
547 output_file = DECODE_FILE (output_file);
548 report_file_errno ("Opening process output file",
549 output_file, open_errno);
552 else
554 int fd[2];
555 if (emacs_pipe (fd) != 0)
556 report_file_error ("Creating process pipe", Qnil);
557 callproc_fd[CALLPROC_PIPEREAD] = fd[0];
558 fd_output = fd[1];
560 callproc_fd[CALLPROC_STDOUT] = fd_output;
562 fd_error = fd_output;
564 if (STRINGP (error_file) || (NILP (error_file) && !discard_output))
566 fd_error = emacs_open ((STRINGP (error_file)
567 ? SSDATA (error_file)
568 : NULL_DEVICE),
569 O_WRONLY | O_CREAT | O_TRUNC | O_TEXT,
570 default_output_mode);
571 if (fd_error < 0)
573 int open_errno = errno;
574 report_file_errno ("Cannot redirect stderr",
575 (STRINGP (error_file)
576 ? DECODE_FILE (error_file)
577 : build_string (NULL_DEVICE)),
578 open_errno);
580 callproc_fd[CALLPROC_STDERR] = fd_error;
583 #ifdef MSDOS /* MW, July 1993 */
584 /* Note that on MSDOS `child_setup' actually returns the child process
585 exit status, not its PID, so assign it to status below. */
586 pid = child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
588 if (pid < 0)
590 child_errno = errno;
591 unbind_to (count, Qnil);
592 synchronize_system_messages_locale ();
593 return
594 code_convert_string_norecord (build_string (strerror (child_errno)),
595 Vlocale_coding_system, 0);
597 status = pid;
599 for (i = 0; i < CALLPROC_FDS; i++)
600 if (0 <= callproc_fd[i])
602 emacs_close (callproc_fd[i]);
603 callproc_fd[i] = -1;
605 emacs_close (filefd);
606 clear_unwind_protect (count - 1);
608 if (tempfile)
610 /* Since CRLF is converted to LF within `decode_coding', we
611 can always open a file with binary mode. */
612 callproc_fd[CALLPROC_PIPEREAD] = emacs_open (tempfile,
613 O_RDONLY | O_BINARY, 0);
614 if (callproc_fd[CALLPROC_PIPEREAD] < 0)
616 int open_errno = errno;
617 report_file_errno ("Cannot re-open temporary file",
618 build_string (tempfile), open_errno);
622 #endif /* MSDOS */
624 /* Do the unwind-protect now, even though the pid is not known, so
625 that no storage allocation is done in the critical section.
626 The actual PID will be filled in during the critical section. */
627 record_unwind_protect (call_process_cleanup, Fcurrent_buffer ());
629 #ifndef MSDOS
631 block_input ();
632 block_child_signal ();
634 #ifdef WINDOWSNT
635 pid = child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
636 #else /* not WINDOWSNT */
638 /* vfork, and prevent local vars from being clobbered by the vfork. */
640 Lisp_Object volatile buffer_volatile = buffer;
641 Lisp_Object volatile coding_systems_volatile = coding_systems;
642 Lisp_Object volatile current_dir_volatile = current_dir;
643 bool volatile display_p_volatile = display_p;
644 bool volatile sa_must_free_volatile = sa_must_free;
645 int volatile fd_error_volatile = fd_error;
646 int volatile filefd_volatile = filefd;
647 ptrdiff_t volatile count_volatile = count;
648 ptrdiff_t volatile sa_count_volatile = sa_count;
649 char **volatile new_argv_volatile = new_argv;
650 int volatile callproc_fd_volatile[CALLPROC_FDS];
651 for (i = 0; i < CALLPROC_FDS; i++)
652 callproc_fd_volatile[i] = callproc_fd[i];
654 pid = vfork ();
656 buffer = buffer_volatile;
657 coding_systems = coding_systems_volatile;
658 current_dir = current_dir_volatile;
659 display_p = display_p_volatile;
660 sa_must_free = sa_must_free_volatile;
661 fd_error = fd_error_volatile;
662 filefd = filefd_volatile;
663 count = count_volatile;
664 sa_count = sa_count_volatile;
665 new_argv = new_argv_volatile;
667 for (i = 0; i < CALLPROC_FDS; i++)
668 callproc_fd[i] = callproc_fd_volatile[i];
669 fd_output = callproc_fd[CALLPROC_STDOUT];
672 if (pid == 0)
674 unblock_child_signal ();
676 setsid ();
678 /* Emacs ignores SIGPIPE, but the child should not. */
679 signal (SIGPIPE, SIG_DFL);
681 child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
684 #endif /* not WINDOWSNT */
686 child_errno = errno;
688 if (pid > 0)
690 synch_process_pid = pid;
692 if (INTEGERP (buffer))
694 if (tempfile_index < 0)
695 record_deleted_pid (pid, Qnil);
696 else
698 eassert (1 < nargs);
699 record_deleted_pid (pid, args[1]);
700 clear_unwind_protect (tempfile_index);
702 synch_process_pid = 0;
706 unblock_child_signal ();
707 unblock_input ();
709 #endif /* not MSDOS */
711 if (pid < 0)
712 report_file_errno ("Doing vfork", Qnil, child_errno);
714 /* Close our file descriptors, except for callproc_fd[CALLPROC_PIPEREAD]
715 since we will use that to read input from. */
716 for (i = 0; i < CALLPROC_FDS; i++)
717 if (i != CALLPROC_PIPEREAD && 0 <= callproc_fd[i])
719 emacs_close (callproc_fd[i]);
720 callproc_fd[i] = -1;
722 emacs_close (filefd);
723 clear_unwind_protect (count - 1);
725 if (INTEGERP (buffer))
726 return unbind_to (count, Qnil);
728 if (BUFFERP (buffer))
729 Fset_buffer (buffer);
731 fd0 = callproc_fd[CALLPROC_PIPEREAD];
733 if (0 <= fd0)
735 Lisp_Object val, *args2;
737 val = Qnil;
738 if (!NILP (Vcoding_system_for_read))
739 val = Vcoding_system_for_read;
740 else
742 if (EQ (coding_systems, Qt))
744 ptrdiff_t i;
746 SAFE_NALLOCA (args2, 1, nargs + 1);
747 args2[0] = Qcall_process;
748 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
749 coding_systems
750 = Ffind_operation_coding_system (nargs + 1, args2);
752 if (CONSP (coding_systems))
753 val = XCAR (coding_systems);
754 else if (CONSP (Vdefault_process_coding_system))
755 val = XCAR (Vdefault_process_coding_system);
756 else
757 val = Qnil;
759 Fcheck_coding_system (val);
760 /* In unibyte mode, character code conversion should not take
761 place but EOL conversion should. So, setup raw-text or one
762 of the subsidiary according to the information just setup. */
763 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
764 && !NILP (val))
765 val = raw_text_coding_system (val);
766 setup_coding_system (val, &process_coding);
767 process_coding.dst_multibyte
768 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
769 process_coding.src_multibyte = 0;
772 immediate_quit = 1;
773 QUIT;
775 if (0 <= fd0)
777 enum { CALLPROC_BUFFER_SIZE_MIN = 16 * 1024 };
778 enum { CALLPROC_BUFFER_SIZE_MAX = 4 * CALLPROC_BUFFER_SIZE_MIN };
779 char buf[CALLPROC_BUFFER_SIZE_MAX];
780 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
781 int nread;
782 bool first = 1;
783 EMACS_INT total_read = 0;
784 int carryover = 0;
785 bool display_on_the_fly = display_p;
786 struct coding_system saved_coding = process_coding;
788 while (1)
790 /* Repeatedly read until we've filled as much as possible
791 of the buffer size we have. But don't read
792 less than 1024--save that for the next bufferful. */
793 nread = carryover;
794 while (nread < bufsize - 1024)
796 int this_read = emacs_read (fd0, buf + nread,
797 bufsize - nread);
799 if (this_read < 0)
800 goto give_up;
802 if (this_read == 0)
804 process_coding.mode |= CODING_MODE_LAST_BLOCK;
805 break;
808 nread += this_read;
809 total_read += this_read;
811 if (display_on_the_fly)
812 break;
815 /* Now NREAD is the total amount of data in the buffer. */
816 immediate_quit = 0;
818 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
819 && ! CODING_MAY_REQUIRE_DECODING (&process_coding))
820 insert_1_both (buf, nread, nread, 0, 1, 0);
821 else
822 { /* We have to decode the input. */
823 Lisp_Object curbuf;
824 ptrdiff_t count1 = SPECPDL_INDEX ();
826 XSETBUFFER (curbuf, current_buffer);
827 /* We cannot allow after-change-functions be run
828 during decoding, because that might modify the
829 buffer, while we rely on process_coding.produced to
830 faithfully reflect inserted text until we
831 TEMP_SET_PT_BOTH below. */
832 specbind (Qinhibit_modification_hooks, Qt);
833 decode_coding_c_string (&process_coding,
834 (unsigned char *) buf, nread, curbuf);
835 unbind_to (count1, Qnil);
836 if (display_on_the_fly
837 && CODING_REQUIRE_DETECTION (&saved_coding)
838 && ! CODING_REQUIRE_DETECTION (&process_coding))
840 /* We have detected some coding system, but the
841 detection may have been via insufficient data.
842 So give up displaying on the fly. */
843 if (process_coding.produced > 0)
844 del_range_2 (process_coding.dst_pos,
845 process_coding.dst_pos_byte,
846 (process_coding.dst_pos
847 + process_coding.produced_char),
848 (process_coding.dst_pos_byte
849 + process_coding.produced),
851 display_on_the_fly = 0;
852 process_coding = saved_coding;
853 carryover = nread;
854 /* Make the above condition always fail in the future. */
855 saved_coding.common_flags
856 &= ~CODING_REQUIRE_DETECTION_MASK;
857 continue;
860 TEMP_SET_PT_BOTH (PT + process_coding.produced_char,
861 PT_BYTE + process_coding.produced);
862 carryover = process_coding.carryover_bytes;
863 if (carryover > 0)
864 memcpy (buf, process_coding.carryover,
865 process_coding.carryover_bytes);
868 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
869 break;
871 /* Make the buffer bigger as we continue to read more data,
872 but not past CALLPROC_BUFFER_SIZE_MAX. */
873 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
874 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
875 bufsize = CALLPROC_BUFFER_SIZE_MAX;
877 if (display_p)
879 if (first)
880 prepare_menu_bars ();
881 first = 0;
882 redisplay_preserve_echo_area (1);
883 /* This variable might have been set to 0 for code
884 detection. In that case, set it back to 1 because
885 we should have already detected a coding system. */
886 display_on_the_fly = 1;
888 immediate_quit = 1;
889 QUIT;
891 give_up: ;
893 Vlast_coding_system_used = CODING_ID_NAME (process_coding.id);
894 /* If the caller required, let the buffer inherit the
895 coding-system used to decode the process output. */
896 if (inherit_process_coding_system)
897 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
898 make_number (total_read));
901 #ifndef MSDOS
902 /* Wait for it to terminate, unless it already has. */
903 wait_for_termination (pid, &status, fd0 < 0);
904 #endif
906 immediate_quit = 0;
908 /* Don't kill any children that the subprocess may have left behind
909 when exiting. */
910 synch_process_pid = 0;
912 SAFE_FREE ();
913 unbind_to (count, Qnil);
915 if (WIFSIGNALED (status))
917 const char *signame;
919 synchronize_system_messages_locale ();
920 signame = strsignal (WTERMSIG (status));
922 if (signame == 0)
923 signame = "unknown";
925 return code_convert_string_norecord (build_string (signame),
926 Vlocale_coding_system, 0);
929 eassert (WIFEXITED (status));
930 return make_number (WEXITSTATUS (status));
933 /* Create a temporary file suitable for storing the input data of
934 call-process-region. NARGS and ARGS are the same as for
935 call-process-region. Store into *FILENAME_STRING_PTR a Lisp string
936 naming the file, and return a file descriptor for reading.
937 Unwind-protect the file, so that the file descriptor will be closed
938 and the file removed when the caller unwinds the specpdl stack. */
940 static int
941 create_temp_file (ptrdiff_t nargs, Lisp_Object *args,
942 Lisp_Object *filename_string_ptr)
944 int fd;
945 struct gcpro gcpro1;
946 Lisp_Object filename_string;
947 Lisp_Object val, start, end;
948 Lisp_Object tmpdir;
950 if (STRINGP (Vtemporary_file_directory))
951 tmpdir = Vtemporary_file_directory;
952 else
954 char *outf;
955 #ifndef DOS_NT
956 outf = getenv ("TMPDIR");
957 tmpdir = build_string (outf ? outf : "/tmp/");
958 #else /* DOS_NT */
959 if ((outf = egetenv ("TMPDIR"))
960 || (outf = egetenv ("TMP"))
961 || (outf = egetenv ("TEMP")))
962 tmpdir = build_string (outf);
963 else
964 tmpdir = Ffile_name_as_directory (build_string ("c:/temp"));
965 #endif
969 Lisp_Object pattern = Fexpand_file_name (Vtemp_file_name_pattern, tmpdir);
970 char *tempfile;
971 ptrdiff_t count;
973 #ifdef WINDOWSNT
974 /* Cannot use the result of Fexpand_file_name, because it
975 downcases the XXXXXX part of the pattern, and mktemp then
976 doesn't recognize it. */
977 if (!NILP (Vw32_downcase_file_names))
979 Lisp_Object dirname = Ffile_name_directory (pattern);
981 if (NILP (dirname))
982 pattern = Vtemp_file_name_pattern;
983 else
984 pattern = concat2 (dirname, Vtemp_file_name_pattern);
986 #endif
988 filename_string = Fcopy_sequence (ENCODE_FILE (pattern));
989 GCPRO1 (filename_string);
990 tempfile = SSDATA (filename_string);
992 count = SPECPDL_INDEX ();
993 record_unwind_protect_nothing ();
994 fd = mkostemp (tempfile, O_CLOEXEC);
995 if (fd < 0)
996 report_file_error ("Failed to open temporary file using pattern",
997 pattern);
998 set_unwind_protect (count, delete_temp_file, filename_string);
999 record_unwind_protect_int (close_file_unwind, fd);
1002 start = args[0];
1003 end = args[1];
1004 /* Decide coding-system of the contents of the temporary file. */
1005 if (!NILP (Vcoding_system_for_write))
1006 val = Vcoding_system_for_write;
1007 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
1008 val = Qraw_text;
1009 else
1011 Lisp_Object coding_systems;
1012 Lisp_Object *args2;
1013 USE_SAFE_ALLOCA;
1014 SAFE_NALLOCA (args2, 1, nargs + 1);
1015 args2[0] = Qcall_process_region;
1016 memcpy (args2 + 1, args, nargs * sizeof *args);
1017 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1018 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
1019 SAFE_FREE ();
1021 val = complement_process_encoding_system (val);
1024 ptrdiff_t count1 = SPECPDL_INDEX ();
1026 specbind (intern ("coding-system-for-write"), val);
1027 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
1028 happen to get a ".Z" suffix. */
1029 specbind (intern ("file-name-handler-alist"), Qnil);
1030 write_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil, fd);
1032 unbind_to (count1, Qnil);
1035 if (lseek (fd, 0, SEEK_SET) < 0)
1036 report_file_error ("Setting file position", filename_string);
1038 /* Note that Fcall_process takes care of binding
1039 coding-system-for-read. */
1041 *filename_string_ptr = filename_string;
1042 UNGCPRO;
1043 return fd;
1046 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
1047 3, MANY, 0,
1048 doc: /* Send text from START to END to a synchronous process running PROGRAM.
1049 The remaining arguments are optional.
1050 Delete the text if fourth arg DELETE is non-nil.
1052 Insert output in BUFFER before point; t means current buffer; nil for
1053 BUFFER means discard it; 0 means discard and don't wait; and `(:file
1054 FILE)', where FILE is a file name string, means that it should be
1055 written to that file (if the file already exists it is overwritten).
1056 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1057 REAL-BUFFER says what to do with standard output, as above,
1058 while STDERR-FILE says what to do with standard error in the child.
1059 STDERR-FILE may be nil (discard standard error output),
1060 t (mix it with ordinary output), or a file name string.
1062 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1063 Remaining args are passed to PROGRAM at startup as command args.
1065 If BUFFER is 0, `call-process-region' returns immediately with value nil.
1066 Otherwise it waits for PROGRAM to terminate
1067 and returns a numeric exit status or a signal description string.
1068 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
1070 usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
1071 (ptrdiff_t nargs, Lisp_Object *args)
1073 struct gcpro gcpro1;
1074 Lisp_Object infile, val;
1075 ptrdiff_t count = SPECPDL_INDEX ();
1076 Lisp_Object start = args[0];
1077 Lisp_Object end = args[1];
1078 bool empty_input;
1079 int fd;
1081 if (STRINGP (start))
1082 empty_input = SCHARS (start) == 0;
1083 else if (NILP (start))
1084 empty_input = BEG == Z;
1085 else
1087 validate_region (&args[0], &args[1]);
1088 start = args[0];
1089 end = args[1];
1090 empty_input = XINT (start) == XINT (end);
1093 if (!empty_input)
1094 fd = create_temp_file (nargs, args, &infile);
1095 else
1097 infile = Qnil;
1098 fd = emacs_open (NULL_DEVICE, O_RDONLY, 0);
1099 if (fd < 0)
1100 report_file_error ("Opening null device", Qnil);
1101 record_unwind_protect_int (close_file_unwind, fd);
1104 GCPRO1 (infile);
1106 if (nargs > 3 && !NILP (args[3]))
1107 Fdelete_region (start, end);
1109 if (nargs > 3)
1111 args += 2;
1112 nargs -= 2;
1114 else
1116 args[0] = args[2];
1117 nargs = 2;
1119 args[1] = infile;
1121 val = call_process (nargs, args, fd, empty_input ? -1 : count);
1122 RETURN_UNGCPRO (unbind_to (count, val));
1125 #ifndef WINDOWSNT
1126 static int relocate_fd (int fd, int minfd);
1127 #endif
1129 static char **
1130 add_env (char **env, char **new_env, char *string)
1132 char **ep;
1133 bool ok = 1;
1134 if (string == NULL)
1135 return new_env;
1137 /* See if this string duplicates any string already in the env.
1138 If so, don't put it in.
1139 When an env var has multiple definitions,
1140 we keep the definition that comes first in process-environment. */
1141 for (ep = env; ok && ep != new_env; ep++)
1143 char *p = *ep, *q = string;
1144 while (ok)
1146 if (*q != *p)
1147 break;
1148 if (*q == 0)
1149 /* The string is a lone variable name; keep it for now, we
1150 will remove it later. It is a placeholder for a
1151 variable that is not to be included in the environment. */
1152 break;
1153 if (*q == '=')
1154 ok = 0;
1155 p++, q++;
1158 if (ok)
1159 *new_env++ = string;
1160 return new_env;
1163 /* This is the last thing run in a newly forked inferior
1164 either synchronous or asynchronous.
1165 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1166 Initialize inferior's priority, pgrp, connected dir and environment.
1167 then exec another program based on new_argv.
1169 If SET_PGRP, put the subprocess into a separate process group.
1171 CURRENT_DIR is an elisp string giving the path of the current
1172 directory the subprocess should have. Since we can't really signal
1173 a decent error from within the child, this should be verified as an
1174 executable directory by the parent. */
1177 child_setup (int in, int out, int err, char **new_argv, bool set_pgrp,
1178 Lisp_Object current_dir)
1180 char **env;
1181 char *pwd_var;
1182 #ifdef WINDOWSNT
1183 int cpid;
1184 HANDLE handles[3];
1185 #else
1186 int exec_errno;
1188 pid_t pid = getpid ();
1189 #endif /* WINDOWSNT */
1191 /* Note that use of alloca is always safe here. It's obvious for systems
1192 that do not have true vfork or that have true (stack) alloca.
1193 If using vfork and C_ALLOCA (when Emacs used to include
1194 src/alloca.c) it is safe because that changes the superior's
1195 static variables as if the superior had done alloca and will be
1196 cleaned up in the usual way. */
1198 char *temp;
1199 ptrdiff_t i;
1201 i = SBYTES (current_dir);
1202 #ifdef MSDOS
1203 /* MSDOS must have all environment variables malloc'ed, because
1204 low-level libc functions that launch subsidiary processes rely
1205 on that. */
1206 pwd_var = xmalloc (i + 5);
1207 #else
1208 pwd_var = alloca (i + 5);
1209 #endif
1210 temp = pwd_var + 4;
1211 memcpy (pwd_var, "PWD=", 4);
1212 strcpy (temp, SSDATA (current_dir));
1214 #ifndef DOS_NT
1215 /* We can't signal an Elisp error here; we're in a vfork. Since
1216 the callers check the current directory before forking, this
1217 should only return an error if the directory's permissions
1218 are changed between the check and this chdir, but we should
1219 at least check. */
1220 if (chdir (temp) < 0)
1221 _exit (EXIT_CANCELED);
1222 #else /* DOS_NT */
1223 /* Get past the drive letter, so that d:/ is left alone. */
1224 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1226 temp += 2;
1227 i -= 2;
1229 #endif /* DOS_NT */
1231 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1232 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1233 temp[--i] = 0;
1236 /* Set `env' to a vector of the strings in the environment. */
1238 register Lisp_Object tem;
1239 register char **new_env;
1240 char **p, **q;
1241 register int new_length;
1242 Lisp_Object display = Qnil;
1244 new_length = 0;
1246 for (tem = Vprocess_environment;
1247 CONSP (tem) && STRINGP (XCAR (tem));
1248 tem = XCDR (tem))
1250 if (strncmp (SSDATA (XCAR (tem)), "DISPLAY", 7) == 0
1251 && (SDATA (XCAR (tem)) [7] == '\0'
1252 || SDATA (XCAR (tem)) [7] == '='))
1253 /* DISPLAY is specified in process-environment. */
1254 display = Qt;
1255 new_length++;
1258 /* If not provided yet, use the frame's DISPLAY. */
1259 if (NILP (display))
1261 Lisp_Object tmp = Fframe_parameter (selected_frame, Qdisplay);
1262 if (!STRINGP (tmp) && CONSP (Vinitial_environment))
1263 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1264 tmp = Fgetenv_internal (build_string ("DISPLAY"),
1265 Vinitial_environment);
1266 if (STRINGP (tmp))
1268 display = tmp;
1269 new_length++;
1273 /* new_length + 2 to include PWD and terminating 0. */
1274 env = new_env = alloca ((new_length + 2) * sizeof *env);
1275 /* If we have a PWD envvar, pass one down,
1276 but with corrected value. */
1277 if (egetenv ("PWD"))
1278 *new_env++ = pwd_var;
1280 if (STRINGP (display))
1282 char *vdata = alloca (sizeof "DISPLAY=" + SBYTES (display));
1283 strcpy (vdata, "DISPLAY=");
1284 strcat (vdata, SSDATA (display));
1285 new_env = add_env (env, new_env, vdata);
1288 /* Overrides. */
1289 for (tem = Vprocess_environment;
1290 CONSP (tem) && STRINGP (XCAR (tem));
1291 tem = XCDR (tem))
1292 new_env = add_env (env, new_env, SSDATA (XCAR (tem)));
1294 *new_env = 0;
1296 /* Remove variable names without values. */
1297 p = q = env;
1298 while (*p != 0)
1300 while (*q != 0 && strchr (*q, '=') == NULL)
1301 q++;
1302 *p = *q++;
1303 if (*p != 0)
1304 p++;
1309 #ifdef WINDOWSNT
1310 prepare_standard_handles (in, out, err, handles);
1311 set_process_dir (SDATA (current_dir));
1312 /* Spawn the child. (See w32proc.c:sys_spawnve). */
1313 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1314 reset_standard_handles (in, out, err, handles);
1315 if (cpid == -1)
1316 /* An error occurred while trying to spawn the process. */
1317 report_file_error ("Spawning child process", Qnil);
1318 return cpid;
1320 #else /* not WINDOWSNT */
1321 /* Make sure that in, out, and err are not actually already in
1322 descriptors zero, one, or two; this could happen if Emacs is
1323 started with its standard in, out, or error closed, as might
1324 happen under X. */
1326 int oin = in, oout = out;
1328 /* We have to avoid relocating the same descriptor twice! */
1330 in = relocate_fd (in, 3);
1332 if (out == oin)
1333 out = in;
1334 else
1335 out = relocate_fd (out, 3);
1337 if (err == oin)
1338 err = in;
1339 else if (err == oout)
1340 err = out;
1341 else
1342 err = relocate_fd (err, 3);
1345 #ifndef MSDOS
1346 /* Redirect file descriptors and clear the close-on-exec flag on the
1347 redirected ones. IN, OUT, and ERR are close-on-exec so they
1348 need not be closed explicitly. */
1349 dup2 (in, 0);
1350 dup2 (out, 1);
1351 dup2 (err, 2);
1353 setpgid (0, 0);
1354 tcsetpgrp (0, pid);
1356 execve (new_argv[0], new_argv, env);
1357 exec_errno = errno;
1359 /* Avoid deadlock if the child's perror writes to a full pipe; the
1360 pipe's reader is the parent, but with vfork the parent can't
1361 run until the child exits. Truncate the diagnostic instead. */
1362 fcntl (STDERR_FILENO, F_SETFL, O_NONBLOCK);
1364 errno = exec_errno;
1365 emacs_perror (new_argv[0]);
1366 _exit (exec_errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1368 #else /* MSDOS */
1369 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1370 xfree (pwd_var);
1371 if (pid == -1)
1372 /* An error occurred while trying to run the subprocess. */
1373 report_file_error ("Spawning child process", Qnil);
1374 return pid;
1375 #endif /* MSDOS */
1376 #endif /* not WINDOWSNT */
1379 #ifndef WINDOWSNT
1380 /* Move the file descriptor FD so that its number is not less than MINFD.
1381 If the file descriptor is moved at all, the original is closed on MSDOS,
1382 but not elsewhere as the caller will close it anyway. */
1383 static int
1384 relocate_fd (int fd, int minfd)
1386 if (fd >= minfd)
1387 return fd;
1388 else
1390 int new = fcntl (fd, F_DUPFD_CLOEXEC, minfd);
1391 if (new == -1)
1393 emacs_perror ("while setting up child");
1394 _exit (EXIT_CANCELED);
1396 #ifdef MSDOS
1397 emacs_close (fd);
1398 #endif
1399 return new;
1402 #endif /* not WINDOWSNT */
1404 static bool
1405 getenv_internal_1 (const char *var, ptrdiff_t varlen, char **value,
1406 ptrdiff_t *valuelen, Lisp_Object env)
1408 for (; CONSP (env); env = XCDR (env))
1410 Lisp_Object entry = XCAR (env);
1411 if (STRINGP (entry)
1412 && SBYTES (entry) >= varlen
1413 #ifdef WINDOWSNT
1414 /* NT environment variables are case insensitive. */
1415 && ! strnicmp (SDATA (entry), var, varlen)
1416 #else /* not WINDOWSNT */
1417 && ! memcmp (SDATA (entry), var, varlen)
1418 #endif /* not WINDOWSNT */
1421 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1423 *value = SSDATA (entry) + (varlen + 1);
1424 *valuelen = SBYTES (entry) - (varlen + 1);
1425 return 1;
1427 else if (SBYTES (entry) == varlen)
1429 /* Lone variable names in Vprocess_environment mean that
1430 variable should be removed from the environment. */
1431 *value = NULL;
1432 return 1;
1436 return 0;
1439 static bool
1440 getenv_internal (const char *var, ptrdiff_t varlen, char **value,
1441 ptrdiff_t *valuelen, Lisp_Object frame)
1443 /* Try to find VAR in Vprocess_environment first. */
1444 if (getenv_internal_1 (var, varlen, value, valuelen,
1445 Vprocess_environment))
1446 return *value ? 1 : 0;
1448 /* For DISPLAY try to get the values from the frame or the initial env. */
1449 if (strcmp (var, "DISPLAY") == 0)
1451 Lisp_Object display
1452 = Fframe_parameter (NILP (frame) ? selected_frame : frame, Qdisplay);
1453 if (STRINGP (display))
1455 *value = SSDATA (display);
1456 *valuelen = SBYTES (display);
1457 return 1;
1459 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1460 if (getenv_internal_1 (var, varlen, value, valuelen,
1461 Vinitial_environment))
1462 return *value ? 1 : 0;
1465 return 0;
1468 DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
1469 doc: /* Get the value of environment variable VARIABLE.
1470 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1471 the environment. Otherwise, value is a string.
1473 This function searches `process-environment' for VARIABLE.
1475 If optional parameter ENV is a list, then search this list instead of
1476 `process-environment', and return t when encountering a negative entry
1477 \(an entry for a variable with no value). */)
1478 (Lisp_Object variable, Lisp_Object env)
1480 char *value;
1481 ptrdiff_t valuelen;
1483 CHECK_STRING (variable);
1484 if (CONSP (env))
1486 if (getenv_internal_1 (SSDATA (variable), SBYTES (variable),
1487 &value, &valuelen, env))
1488 return value ? make_string (value, valuelen) : Qt;
1489 else
1490 return Qnil;
1492 else if (getenv_internal (SSDATA (variable), SBYTES (variable),
1493 &value, &valuelen, env))
1494 return make_string (value, valuelen);
1495 else
1496 return Qnil;
1499 /* A version of getenv that consults the Lisp environment lists,
1500 easily callable from C. */
1501 char *
1502 egetenv (const char *var)
1504 char *value;
1505 ptrdiff_t valuelen;
1507 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
1508 return value;
1509 else
1510 return 0;
1514 /* This is run before init_cmdargs. */
1516 void
1517 init_callproc_1 (void)
1519 #ifdef HAVE_NS
1520 const char *etc_dir = ns_etc_directory ();
1521 const char *path_exec = ns_exec_path ();
1522 #endif
1524 Vdata_directory = decode_env_path ("EMACSDATA",
1525 #ifdef HAVE_NS
1526 etc_dir ? etc_dir :
1527 #endif
1528 PATH_DATA);
1529 Vdata_directory = Ffile_name_as_directory (Fcar (Vdata_directory));
1531 Vdoc_directory = decode_env_path ("EMACSDOC",
1532 #ifdef HAVE_NS
1533 etc_dir ? etc_dir :
1534 #endif
1535 PATH_DOC);
1536 Vdoc_directory = Ffile_name_as_directory (Fcar (Vdoc_directory));
1538 /* Check the EMACSPATH environment variable, defaulting to the
1539 PATH_EXEC path from epaths.h. */
1540 Vexec_path = decode_env_path ("EMACSPATH",
1541 #ifdef HAVE_NS
1542 path_exec ? path_exec :
1543 #endif
1544 PATH_EXEC);
1545 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1546 /* FIXME? For ns, path_exec should go at the front? */
1547 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1550 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1552 void
1553 init_callproc (void)
1555 char *data_dir = egetenv ("EMACSDATA");
1557 register char * sh;
1558 Lisp_Object tempdir;
1559 #ifdef HAVE_NS
1560 if (data_dir == 0)
1562 const char *etc_dir = ns_etc_directory ();
1563 if (etc_dir)
1565 data_dir = alloca (strlen (etc_dir) + 1);
1566 strcpy (data_dir, etc_dir);
1569 #endif
1571 if (!NILP (Vinstallation_directory))
1573 /* Add to the path the lib-src subdir of the installation dir. */
1574 Lisp_Object tem;
1575 tem = Fexpand_file_name (build_string ("lib-src"),
1576 Vinstallation_directory);
1577 #ifndef MSDOS
1578 /* MSDOS uses wrapped binaries, so don't do this. */
1579 if (NILP (Fmember (tem, Vexec_path)))
1581 #ifdef HAVE_NS
1582 const char *path_exec = ns_exec_path ();
1583 #endif
1584 Vexec_path = decode_env_path ("EMACSPATH",
1585 #ifdef HAVE_NS
1586 path_exec ? path_exec :
1587 #endif
1588 PATH_EXEC);
1589 Vexec_path = Fcons (tem, Vexec_path);
1590 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1593 Vexec_directory = Ffile_name_as_directory (tem);
1594 #endif /* not MSDOS */
1596 /* Maybe use ../etc as well as ../lib-src. */
1597 if (data_dir == 0)
1599 tem = Fexpand_file_name (build_string ("etc"),
1600 Vinstallation_directory);
1601 Vdoc_directory = Ffile_name_as_directory (tem);
1605 /* Look for the files that should be in etc. We don't use
1606 Vinstallation_directory, because these files are never installed
1607 near the executable, and they are never in the build
1608 directory when that's different from the source directory.
1610 Instead, if these files are not in the nominal place, we try the
1611 source directory. */
1612 if (data_dir == 0)
1614 Lisp_Object tem, tem1, srcdir;
1616 srcdir = Fexpand_file_name (build_string ("../src/"),
1617 build_string (PATH_DUMPLOADSEARCH));
1618 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1619 tem1 = Ffile_exists_p (tem);
1620 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
1622 Lisp_Object newdir;
1623 newdir = Fexpand_file_name (build_string ("../etc/"),
1624 build_string (PATH_DUMPLOADSEARCH));
1625 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1626 tem1 = Ffile_exists_p (tem);
1627 if (!NILP (tem1))
1628 Vdata_directory = newdir;
1632 #ifndef CANNOT_DUMP
1633 if (initialized)
1634 #endif
1636 tempdir = Fdirectory_file_name (Vexec_directory);
1637 if (! file_accessible_directory_p (SSDATA (tempdir)))
1638 dir_warning ("arch-dependent data dir", Vexec_directory);
1641 tempdir = Fdirectory_file_name (Vdata_directory);
1642 if (! file_accessible_directory_p (SSDATA (tempdir)))
1643 dir_warning ("arch-independent data dir", Vdata_directory);
1645 sh = getenv ("SHELL");
1646 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1648 #ifdef DOS_NT
1649 Vshared_game_score_directory = Qnil;
1650 #else
1651 Vshared_game_score_directory = build_string (PATH_GAME);
1652 if (NILP (Ffile_accessible_directory_p (Vshared_game_score_directory)))
1653 Vshared_game_score_directory = Qnil;
1654 #endif
1657 void
1658 set_initial_environment (void)
1660 char **envp;
1661 for (envp = environ; *envp; envp++)
1662 Vprocess_environment = Fcons (build_string (*envp),
1663 Vprocess_environment);
1664 /* Ideally, the `copy' shouldn't be necessary, but it seems it's frequent
1665 to use `delete' and friends on process-environment. */
1666 Vinitial_environment = Fcopy_sequence (Vprocess_environment);
1669 void
1670 syms_of_callproc (void)
1672 #ifndef DOS_NT
1673 Vtemp_file_name_pattern = build_string ("emacsXXXXXX");
1674 #elif defined (WINDOWSNT)
1675 Vtemp_file_name_pattern = build_string ("emXXXXXX");
1676 #else
1677 Vtemp_file_name_pattern = build_string ("detmp.XXX");
1678 #endif
1679 staticpro (&Vtemp_file_name_pattern);
1681 #ifdef MSDOS
1682 synch_process_tempfile = make_number (0);
1683 staticpro (&synch_process_tempfile);
1684 #endif
1686 DEFVAR_LISP ("shell-file-name", Vshell_file_name,
1687 doc: /* File name to load inferior shells from.
1688 Initialized from the SHELL environment variable, or to a system-dependent
1689 default if SHELL is not set. */);
1691 DEFVAR_LISP ("exec-path", Vexec_path,
1692 doc: /* List of directories to search programs to run in subprocesses.
1693 Each element is a string (directory name) or nil (try default directory). */);
1695 DEFVAR_LISP ("exec-suffixes", Vexec_suffixes,
1696 doc: /* List of suffixes to try to find executable file names.
1697 Each element is a string. */);
1698 Vexec_suffixes = Qnil;
1700 DEFVAR_LISP ("exec-directory", Vexec_directory,
1701 doc: /* Directory for executables for Emacs to invoke.
1702 More generally, this includes any architecture-dependent files
1703 that are built and installed from the Emacs distribution. */);
1705 DEFVAR_LISP ("data-directory", Vdata_directory,
1706 doc: /* Directory of machine-independent files that come with GNU Emacs.
1707 These are files intended for Emacs to use while it runs. */);
1709 DEFVAR_LISP ("doc-directory", Vdoc_directory,
1710 doc: /* Directory containing the DOC file that comes with GNU Emacs.
1711 This is usually the same as `data-directory'. */);
1713 DEFVAR_LISP ("configure-info-directory", Vconfigure_info_directory,
1714 doc: /* For internal use by the build procedure only.
1715 This is the name of the directory in which the build procedure installed
1716 Emacs's info files; the default value for `Info-default-directory-list'
1717 includes this. */);
1718 Vconfigure_info_directory = build_string (PATH_INFO);
1720 DEFVAR_LISP ("shared-game-score-directory", Vshared_game_score_directory,
1721 doc: /* Directory of score files for games which come with GNU Emacs.
1722 If this variable is nil, then Emacs is unable to use a shared directory. */);
1723 #ifdef DOS_NT
1724 Vshared_game_score_directory = Qnil;
1725 #else
1726 Vshared_game_score_directory = build_string (PATH_GAME);
1727 #endif
1729 DEFVAR_LISP ("initial-environment", Vinitial_environment,
1730 doc: /* List of environment variables inherited from the parent process.
1731 Each element should be a string of the form ENVVARNAME=VALUE.
1732 The elements must normally be decoded (using `locale-coding-system') for use. */);
1733 Vinitial_environment = Qnil;
1735 DEFVAR_LISP ("process-environment", Vprocess_environment,
1736 doc: /* List of overridden environment variables for subprocesses to inherit.
1737 Each element should be a string of the form ENVVARNAME=VALUE.
1739 Entries in this list take precedence to those in the frame-local
1740 environments. Therefore, let-binding `process-environment' is an easy
1741 way to temporarily change the value of an environment variable,
1742 irrespective of where it comes from. To use `process-environment' to
1743 remove an environment variable, include only its name in the list,
1744 without "=VALUE".
1746 This variable is set to nil when Emacs starts.
1748 If multiple entries define the same variable, the first one always
1749 takes precedence.
1751 Non-ASCII characters are encoded according to the initial value of
1752 `locale-coding-system', i.e. the elements must normally be decoded for
1753 use.
1755 See `setenv' and `getenv'. */);
1756 Vprocess_environment = Qnil;
1758 defsubr (&Scall_process);
1759 defsubr (&Sgetenv_internal);
1760 defsubr (&Scall_process_region);