auto upstream
[emacs.git] / src / callproc.c
blob5eba32713580968f86d304a90de5b898257cc638
1 /* Synchronous subprocess invocation for GNU Emacs.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2012
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <unistd.h>
27 #include <sys/file.h>
28 #include <fcntl.h>
30 #include "lisp.h"
32 #ifdef WINDOWSNT
33 #define NOMINMAX
34 #include <windows.h>
35 #include "w32.h"
36 #define _P_NOWAIT 1 /* from process.h */
37 #endif
39 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
40 #include <sys/stat.h>
41 #include <sys/param.h>
42 #endif /* MSDOS */
44 #include "commands.h"
45 #include "character.h"
46 #include "buffer.h"
47 #include "ccl.h"
48 #include "coding.h"
49 #include "composite.h"
50 #include <epaths.h>
51 #include "process.h"
52 #include "syssignal.h"
53 #include "systty.h"
54 #include "syswait.h"
55 #include "blockinput.h"
56 #include "frame.h"
57 #include "termhooks.h"
59 #ifdef MSDOS
60 #include "msdos.h"
61 #endif
63 #ifdef HAVE_NS
64 #include "nsterm.h"
65 #endif
67 /* Pattern used by call-process-region to make temp files. */
68 static Lisp_Object Vtemp_file_name_pattern;
70 /* The next two variables are valid only while record-unwind-protect
71 is in place during call-process for a synchronous subprocess. At
72 other times, their contents are irrelevant. Doing this via static
73 C variables is more convenient than putting them into the arguments
74 of record-unwind-protect, as they need to be updated at randomish
75 times in the code, and Lisp cannot always store these values as
76 Emacs integers. It's safe to use static variables here, as the
77 code is never invoked reentrantly. */
79 /* If nonzero, a process-ID that has not been reaped. */
80 static pid_t synch_process_pid;
82 /* If nonnegative, a file descriptor that has not been closed. */
83 static int synch_process_fd;
85 /* Block SIGCHLD. */
87 static void
88 block_child_signal (void)
90 sigset_t blocked;
91 sigemptyset (&blocked);
92 sigaddset (&blocked, SIGCHLD);
93 pthread_sigmask (SIG_BLOCK, &blocked, 0);
96 /* Unblock SIGCHLD. */
98 static void
99 unblock_child_signal (void)
101 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
104 /* If P is reapable, record it as a deleted process and kill it.
105 Do this in a critical section. Unless PID is wedged it will be
106 reaped on receipt of the first SIGCHLD after the critical section. */
108 void
109 record_kill_process (struct Lisp_Process *p)
111 block_child_signal ();
113 if (p->alive)
115 p->alive = 0;
116 record_deleted_pid (p->pid);
117 kill (- p->pid, SIGKILL);
120 unblock_child_signal ();
123 /* Clean up when exiting call_process_cleanup. */
125 static Lisp_Object
126 call_process_kill (Lisp_Object ignored)
128 if (0 <= synch_process_fd)
129 emacs_close (synch_process_fd);
131 if (synch_process_pid)
133 struct Lisp_Process proc;
134 proc.alive = 1;
135 proc.pid = synch_process_pid;
136 record_kill_process (&proc);
139 return Qnil;
142 /* Clean up when exiting Fcall_process.
143 On MSDOS, delete the temporary file on any kind of termination.
144 On Unix, kill the process and any children on termination by signal. */
146 static Lisp_Object
147 call_process_cleanup (Lisp_Object arg)
149 #ifdef MSDOS
150 Lisp_Object buffer = Fcar (arg);
151 Lisp_Object file = Fcdr (arg);
152 #else
153 Lisp_Object buffer = arg;
154 #endif
156 Fset_buffer (buffer);
158 #ifndef MSDOS
159 /* If the process still exists, kill its process group. */
160 if (synch_process_pid)
162 ptrdiff_t count = SPECPDL_INDEX ();
163 kill (-synch_process_pid, SIGINT);
164 record_unwind_protect (call_process_kill, make_number (0));
165 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
166 immediate_quit = 1;
167 QUIT;
168 wait_for_termination (synch_process_pid, 0, 1);
169 synch_process_pid = 0;
170 immediate_quit = 0;
171 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
172 message1 ("Waiting for process to die...done");
174 #endif
176 if (0 <= synch_process_fd)
177 emacs_close (synch_process_fd);
179 #ifdef MSDOS
180 /* FILE is "" when we didn't actually create a temporary file in
181 call-process. */
182 if (!(strcmp (SDATA (file), NULL_DEVICE) == 0 || SREF (file, 0) == '\0'))
183 unlink (SDATA (file));
184 #endif
186 return Qnil;
189 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
190 doc: /* Call PROGRAM synchronously in separate process.
191 The remaining arguments are optional.
192 The program's input comes from file INFILE (nil means `/dev/null').
193 Insert output in BUFFER before point; t means current buffer; nil for BUFFER
194 means discard it; 0 means discard and don't wait; and `(:file FILE)', where
195 FILE is a file name string, means that it should be written to that file
196 \(if the file already exists it is overwritten).
197 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
198 REAL-BUFFER says what to do with standard output, as above,
199 while STDERR-FILE says what to do with standard error in the child.
200 STDERR-FILE may be nil (discard standard error output),
201 t (mix it with ordinary output), or a file name string.
203 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
204 Remaining arguments are strings passed as command arguments to PROGRAM.
206 If executable PROGRAM can't be found as an executable, `call-process'
207 signals a Lisp error. `call-process' reports errors in execution of
208 the program only through its return and output.
210 If BUFFER is 0, `call-process' returns immediately with value nil.
211 Otherwise it waits for PROGRAM to terminate
212 and returns a numeric exit status or a signal description string.
213 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
215 usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
216 (ptrdiff_t nargs, Lisp_Object *args)
218 Lisp_Object infile, buffer, current_dir, path;
219 bool display_p;
220 int fd0, fd1, filefd;
221 int status;
222 ptrdiff_t count = SPECPDL_INDEX ();
223 USE_SAFE_ALLOCA;
225 char **new_argv;
226 /* File to use for stderr in the child.
227 t means use same as standard output. */
228 Lisp_Object error_file;
229 Lisp_Object output_file = Qnil;
230 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
231 char *outf, *tempfile = NULL;
232 int outfilefd;
233 int pid;
234 #else
235 pid_t pid;
236 #endif
237 int child_errno;
238 int fd_output = -1;
239 struct coding_system process_coding; /* coding-system of process output */
240 struct coding_system argument_coding; /* coding-system of arguments */
241 /* Set to the return value of Ffind_operation_coding_system. */
242 Lisp_Object coding_systems;
243 bool output_to_buffer = 1;
245 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
246 coding_systems = Qt;
248 CHECK_STRING (args[0]);
250 error_file = Qt;
252 #ifndef subprocesses
253 /* Without asynchronous processes we cannot have BUFFER == 0. */
254 if (nargs >= 3
255 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
256 error ("Operating system cannot handle asynchronous subprocesses");
257 #endif /* subprocesses */
259 /* Decide the coding-system for giving arguments. */
261 Lisp_Object val, *args2;
262 ptrdiff_t i;
264 /* If arguments are supplied, we may have to encode them. */
265 if (nargs >= 5)
267 bool must_encode = 0;
268 Lisp_Object coding_attrs;
270 for (i = 4; i < nargs; i++)
271 CHECK_STRING (args[i]);
273 for (i = 4; i < nargs; i++)
274 if (STRING_MULTIBYTE (args[i]))
275 must_encode = 1;
277 if (!NILP (Vcoding_system_for_write))
278 val = Vcoding_system_for_write;
279 else if (! must_encode)
280 val = Qraw_text;
281 else
283 SAFE_NALLOCA (args2, 1, nargs + 1);
284 args2[0] = Qcall_process;
285 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
286 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
287 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
289 val = complement_process_encoding_system (val);
290 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
291 coding_attrs = CODING_ID_ATTRS (argument_coding.id);
292 if (NILP (CODING_ATTR_ASCII_COMPAT (coding_attrs)))
294 /* We should not use an ASCII incompatible coding system. */
295 val = raw_text_coding_system (val);
296 setup_coding_system (val, &argument_coding);
301 if (nargs >= 2 && ! NILP (args[1]))
303 infile = Fexpand_file_name (args[1], BVAR (current_buffer, directory));
304 CHECK_STRING (infile);
306 else
307 infile = build_string (NULL_DEVICE);
309 if (nargs >= 3)
311 buffer = args[2];
313 /* If BUFFER is a list, its meaning is (BUFFER-FOR-STDOUT
314 FILE-FOR-STDERR), unless the first element is :file, in which case see
315 the next paragraph. */
316 if (CONSP (buffer)
317 && (! SYMBOLP (XCAR (buffer))
318 || strcmp (SSDATA (SYMBOL_NAME (XCAR (buffer))), ":file")))
320 if (CONSP (XCDR (buffer)))
322 Lisp_Object stderr_file;
323 stderr_file = XCAR (XCDR (buffer));
325 if (NILP (stderr_file) || EQ (Qt, stderr_file))
326 error_file = stderr_file;
327 else
328 error_file = Fexpand_file_name (stderr_file, Qnil);
331 buffer = XCAR (buffer);
334 /* If the buffer is (still) a list, it might be a (:file "file") spec. */
335 if (CONSP (buffer)
336 && SYMBOLP (XCAR (buffer))
337 && ! strcmp (SSDATA (SYMBOL_NAME (XCAR (buffer))), ":file"))
339 output_file = Fexpand_file_name (XCAR (XCDR (buffer)),
340 BVAR (current_buffer, directory));
341 CHECK_STRING (output_file);
342 buffer = Qnil;
345 if (!(EQ (buffer, Qnil)
346 || EQ (buffer, Qt)
347 || INTEGERP (buffer)))
349 Lisp_Object spec_buffer;
350 spec_buffer = buffer;
351 buffer = Fget_buffer_create (buffer);
352 /* Mention the buffer name for a better error message. */
353 if (NILP (buffer))
354 CHECK_BUFFER (spec_buffer);
355 CHECK_BUFFER (buffer);
358 else
359 buffer = Qnil;
361 /* Make sure that the child will be able to chdir to the current
362 buffer's current directory, or its unhandled equivalent. We
363 can't just have the child check for an error when it does the
364 chdir, since it's in a vfork.
366 We have to GCPRO around this because Fexpand_file_name,
367 Funhandled_file_name_directory, and Ffile_accessible_directory_p
368 might call a file name handling function. The argument list is
369 protected by the caller, so all we really have to worry about is
370 buffer. */
372 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
374 current_dir = BVAR (current_buffer, directory);
376 GCPRO5 (infile, buffer, current_dir, error_file, output_file);
378 current_dir = Funhandled_file_name_directory (current_dir);
379 if (NILP (current_dir))
380 /* If the file name handler says that current_dir is unreachable, use
381 a sensible default. */
382 current_dir = build_string ("~/");
383 current_dir = expand_and_dir_to_file (current_dir, Qnil);
384 current_dir = Ffile_name_as_directory (current_dir);
386 if (NILP (Ffile_accessible_directory_p (current_dir)))
387 report_file_error ("Setting current directory",
388 Fcons (BVAR (current_buffer, directory), Qnil));
390 if (STRING_MULTIBYTE (infile))
391 infile = ENCODE_FILE (infile);
392 if (STRING_MULTIBYTE (current_dir))
393 current_dir = ENCODE_FILE (current_dir);
394 if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
395 error_file = ENCODE_FILE (error_file);
396 if (STRINGP (output_file) && STRING_MULTIBYTE (output_file))
397 output_file = ENCODE_FILE (output_file);
398 UNGCPRO;
401 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
403 filefd = emacs_open (SSDATA (infile), O_RDONLY, 0);
404 if (filefd < 0)
405 report_file_error ("Opening process input file",
406 Fcons (DECODE_FILE (infile), Qnil));
408 if (STRINGP (output_file))
410 #ifdef DOS_NT
411 fd_output = emacs_open (SSDATA (output_file),
412 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
413 S_IREAD | S_IWRITE);
414 #else /* not DOS_NT */
415 fd_output = creat (SSDATA (output_file), 0666);
416 #endif /* not DOS_NT */
417 if (fd_output < 0)
419 output_file = DECODE_FILE (output_file);
420 report_file_error ("Opening process output file",
421 Fcons (output_file, Qnil));
423 if (STRINGP (error_file) || NILP (error_file))
424 output_to_buffer = 0;
427 /* Search for program; barf if not found. */
429 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
431 GCPRO4 (infile, buffer, current_dir, error_file);
432 openp (Vexec_path, args[0], Vexec_suffixes, &path, make_number (X_OK));
433 UNGCPRO;
435 if (NILP (path))
437 emacs_close (filefd);
438 report_file_error ("Searching for program", Fcons (args[0], Qnil));
441 /* If program file name starts with /: for quoting a magic name,
442 discard that. */
443 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
444 && SREF (path, 1) == ':')
445 path = Fsubstring (path, make_number (2), Qnil);
447 new_argv = SAFE_ALLOCA ((nargs > 4 ? nargs - 2 : 2) * sizeof *new_argv);
448 if (nargs > 4)
450 ptrdiff_t i;
451 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
453 GCPRO5 (infile, buffer, current_dir, path, error_file);
454 argument_coding.dst_multibyte = 0;
455 for (i = 4; i < nargs; i++)
457 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
458 if (CODING_REQUIRE_ENCODING (&argument_coding))
459 /* We must encode this argument. */
460 args[i] = encode_coding_string (&argument_coding, args[i], 1);
462 UNGCPRO;
463 for (i = 4; i < nargs; i++)
464 new_argv[i - 3] = SSDATA (args[i]);
465 new_argv[i - 3] = 0;
467 else
468 new_argv[1] = 0;
469 new_argv[0] = SSDATA (path);
471 #ifdef MSDOS /* MW, July 1993 */
473 /* If we're redirecting STDOUT to a file, that file is already open
474 on fd_output. */
475 if (fd_output < 0)
477 if ((outf = egetenv ("TMPDIR")))
478 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
479 else
481 tempfile = alloca (20);
482 *tempfile = '\0';
484 dostounix_filename (tempfile);
485 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
486 strcat (tempfile, "/");
487 strcat (tempfile, "detmp.XXX");
488 mktemp (tempfile);
489 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
490 if (outfilefd < 0) {
491 emacs_close (filefd);
492 report_file_error ("Opening process output file",
493 Fcons (build_string (tempfile), Qnil));
496 else
497 outfilefd = fd_output;
498 fd0 = filefd;
499 fd1 = outfilefd;
500 #endif /* MSDOS */
502 if (INTEGERP (buffer))
504 fd0 = -1;
505 fd1 = emacs_open (NULL_DEVICE, O_WRONLY, 0);
507 else
509 #ifndef MSDOS
510 int fd[2];
511 if (pipe (fd) == -1)
513 int pipe_errno = errno;
514 emacs_close (filefd);
515 errno = pipe_errno;
516 report_file_error ("Creating process pipe", Qnil);
518 fd0 = fd[0];
519 fd1 = fd[1];
520 #endif
524 int fd_error = fd1;
526 if (fd_output >= 0)
527 fd1 = fd_output;
529 if (NILP (error_file))
530 fd_error = emacs_open (NULL_DEVICE, O_WRONLY, 0);
531 else if (STRINGP (error_file))
533 #ifdef DOS_NT
534 fd_error = emacs_open (SSDATA (error_file),
535 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
536 S_IREAD | S_IWRITE);
537 #else /* not DOS_NT */
538 fd_error = creat (SSDATA (error_file), 0666);
539 #endif /* not DOS_NT */
542 if (fd_error < 0)
544 emacs_close (filefd);
545 if (fd0 != filefd)
546 emacs_close (fd0);
547 if (fd1 >= 0)
548 emacs_close (fd1);
549 #ifdef MSDOS
550 unlink (tempfile);
551 #endif
552 if (NILP (error_file))
553 error_file = build_string (NULL_DEVICE);
554 else if (STRINGP (error_file))
555 error_file = DECODE_FILE (error_file);
556 report_file_error ("Cannot redirect stderr", Fcons (error_file, Qnil));
559 #ifdef MSDOS /* MW, July 1993 */
560 /* Note that on MSDOS `child_setup' actually returns the child process
561 exit status, not its PID, so assign it to status below. */
562 pid = child_setup (filefd, outfilefd, fd_error, new_argv, 0, current_dir);
563 child_errno = errno;
565 emacs_close (outfilefd);
566 if (fd_error != outfilefd)
567 emacs_close (fd_error);
568 if (pid < 0)
570 synchronize_system_messages_locale ();
571 return
572 code_convert_string_norecord (build_string (strerror (child_errno)),
573 Vlocale_coding_system, 0);
575 status = pid;
576 fd1 = -1; /* No harm in closing that one! */
577 if (tempfile)
579 /* Since CRLF is converted to LF within `decode_coding', we
580 can always open a file with binary mode. */
581 fd0 = emacs_open (tempfile, O_RDONLY | O_BINARY, 0);
582 if (fd0 < 0)
584 unlink (tempfile);
585 emacs_close (filefd);
586 report_file_error ("Cannot re-open temporary file",
587 Fcons (build_string (tempfile), Qnil));
590 else
591 fd0 = -1; /* We are not going to read from tempfile. */
592 #endif /* MSDOS */
594 /* Do the unwind-protect now, even though the pid is not known, so
595 that no storage allocation is done in the critical section.
596 The actual PID will be filled in during the critical section. */
597 synch_process_pid = 0;
598 synch_process_fd = fd0;
600 #ifdef MSDOS
601 /* MSDOS needs different cleanup information. */
602 record_unwind_protect (call_process_cleanup,
603 Fcons (Fcurrent_buffer (),
604 build_string (tempfile ? tempfile : "")));
605 #else
606 record_unwind_protect (call_process_cleanup, Fcurrent_buffer ());
608 block_input ();
609 block_child_signal ();
611 #ifdef WINDOWSNT
612 pid = child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
613 /* We need to record the input file of this child, for when we are
614 called from call-process-region to create an async subprocess.
615 That's because call-process-region's unwind procedure will
616 attempt to delete the temporary input file, which will fail
617 because that file is still in use. Recording it with the child
618 will allow us to delete the file when the subprocess exits.
619 The second part of this is in delete_temp_file, q.v. */
620 if (pid > 0 && INTEGERP (buffer) && nargs >= 2 && !NILP (args[1]))
621 record_infile (pid, xstrdup (SSDATA (infile)));
622 #else /* not WINDOWSNT */
624 /* vfork, and prevent local vars from being clobbered by the vfork. */
626 Lisp_Object volatile buffer_volatile = buffer;
627 Lisp_Object volatile coding_systems_volatile = coding_systems;
628 Lisp_Object volatile current_dir_volatile = current_dir;
629 bool volatile display_p_volatile = display_p;
630 bool volatile output_to_buffer_volatile = output_to_buffer;
631 bool volatile sa_must_free_volatile = sa_must_free;
632 int volatile fd1_volatile = fd1;
633 int volatile fd_error_volatile = fd_error;
634 int volatile fd_output_volatile = fd_output;
635 int volatile filefd_volatile = filefd;
636 ptrdiff_t volatile count_volatile = count;
637 ptrdiff_t volatile sa_count_volatile = sa_count;
638 char **volatile new_argv_volatile = new_argv;
640 pid = vfork ();
641 child_errno = errno;
643 buffer = buffer_volatile;
644 coding_systems = coding_systems_volatile;
645 current_dir = current_dir_volatile;
646 display_p = display_p_volatile;
647 output_to_buffer = output_to_buffer_volatile;
648 sa_must_free = sa_must_free_volatile;
649 fd1 = fd1_volatile;
650 fd_error = fd_error_volatile;
651 fd_output = fd_output_volatile;
652 filefd = filefd_volatile;
653 count = count_volatile;
654 sa_count = sa_count_volatile;
655 new_argv = new_argv_volatile;
657 fd0 = synch_process_fd;
660 if (pid == 0)
662 unblock_child_signal ();
664 if (fd0 >= 0)
665 emacs_close (fd0);
667 setsid ();
669 /* Emacs ignores SIGPIPE, but the child should not. */
670 signal (SIGPIPE, SIG_DFL);
672 child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
675 #endif /* not WINDOWSNT */
677 child_errno = errno;
679 if (0 < pid)
681 if (INTEGERP (buffer))
682 record_deleted_pid (pid);
683 else
684 synch_process_pid = pid;
687 unblock_child_signal ();
688 unblock_input ();
690 /* The MSDOS case did this already. */
691 if (fd_error >= 0)
692 emacs_close (fd_error);
693 #endif /* not MSDOS */
695 /* Close most of our file descriptors, but not fd0
696 since we will use that to read input from. */
697 emacs_close (filefd);
698 if (fd_output >= 0)
699 emacs_close (fd_output);
700 if (fd1 >= 0 && fd1 != fd_error)
701 emacs_close (fd1);
704 if (pid < 0)
706 errno = child_errno;
707 report_file_error ("Doing vfork", Qnil);
710 if (INTEGERP (buffer))
711 return unbind_to (count, Qnil);
713 if (BUFFERP (buffer))
714 Fset_buffer (buffer);
716 if (NILP (buffer))
718 /* If BUFFER is nil, we must read process output once and then
719 discard it, so setup coding system but with nil. */
720 setup_coding_system (Qnil, &process_coding);
721 process_coding.dst_multibyte = 0;
723 else
725 Lisp_Object val, *args2;
727 val = Qnil;
728 if (!NILP (Vcoding_system_for_read))
729 val = Vcoding_system_for_read;
730 else
732 if (EQ (coding_systems, Qt))
734 ptrdiff_t i;
736 SAFE_NALLOCA (args2, 1, nargs + 1);
737 args2[0] = Qcall_process;
738 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
739 coding_systems
740 = Ffind_operation_coding_system (nargs + 1, args2);
742 if (CONSP (coding_systems))
743 val = XCAR (coding_systems);
744 else if (CONSP (Vdefault_process_coding_system))
745 val = XCAR (Vdefault_process_coding_system);
746 else
747 val = Qnil;
749 Fcheck_coding_system (val);
750 /* In unibyte mode, character code conversion should not take
751 place but EOL conversion should. So, setup raw-text or one
752 of the subsidiary according to the information just setup. */
753 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
754 && !NILP (val))
755 val = raw_text_coding_system (val);
756 setup_coding_system (val, &process_coding);
757 process_coding.dst_multibyte
758 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
760 process_coding.src_multibyte = 0;
762 immediate_quit = 1;
763 QUIT;
765 if (output_to_buffer)
767 enum { CALLPROC_BUFFER_SIZE_MIN = 16 * 1024 };
768 enum { CALLPROC_BUFFER_SIZE_MAX = 4 * CALLPROC_BUFFER_SIZE_MIN };
769 char buf[CALLPROC_BUFFER_SIZE_MAX];
770 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
771 int nread;
772 bool first = 1;
773 EMACS_INT total_read = 0;
774 int carryover = 0;
775 bool display_on_the_fly = display_p;
776 struct coding_system saved_coding;
778 saved_coding = process_coding;
779 while (1)
781 /* Repeatedly read until we've filled as much as possible
782 of the buffer size we have. But don't read
783 less than 1024--save that for the next bufferful. */
784 nread = carryover;
785 while (nread < bufsize - 1024)
787 int this_read = emacs_read (fd0, buf + nread,
788 bufsize - nread);
790 if (this_read < 0)
791 goto give_up;
793 if (this_read == 0)
795 process_coding.mode |= CODING_MODE_LAST_BLOCK;
796 break;
799 nread += this_read;
800 total_read += this_read;
802 if (display_on_the_fly)
803 break;
806 /* Now NREAD is the total amount of data in the buffer. */
807 immediate_quit = 0;
809 if (!NILP (buffer))
811 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
812 && ! CODING_MAY_REQUIRE_DECODING (&process_coding))
813 insert_1_both (buf, nread, nread, 0, 1, 0);
814 else
815 { /* We have to decode the input. */
816 Lisp_Object curbuf;
817 ptrdiff_t count1 = SPECPDL_INDEX ();
819 XSETBUFFER (curbuf, current_buffer);
820 /* We cannot allow after-change-functions be run
821 during decoding, because that might modify the
822 buffer, while we rely on process_coding.produced to
823 faithfully reflect inserted text until we
824 TEMP_SET_PT_BOTH below. */
825 specbind (Qinhibit_modification_hooks, Qt);
826 decode_coding_c_string (&process_coding,
827 (unsigned char *) buf, nread, curbuf);
828 unbind_to (count1, Qnil);
829 if (display_on_the_fly
830 && CODING_REQUIRE_DETECTION (&saved_coding)
831 && ! CODING_REQUIRE_DETECTION (&process_coding))
833 /* We have detected some coding system. But,
834 there's a possibility that the detection was
835 done by insufficient data. So, we give up
836 displaying on the fly. */
837 if (process_coding.produced > 0)
838 del_range_2 (process_coding.dst_pos,
839 process_coding.dst_pos_byte,
840 process_coding.dst_pos
841 + process_coding.produced_char,
842 process_coding.dst_pos_byte
843 + process_coding.produced, 0);
844 display_on_the_fly = 0;
845 process_coding = saved_coding;
846 carryover = nread;
847 /* This is to make the above condition always
848 fails in the future. */
849 saved_coding.common_flags
850 &= ~CODING_REQUIRE_DETECTION_MASK;
851 continue;
854 TEMP_SET_PT_BOTH (PT + process_coding.produced_char,
855 PT_BYTE + process_coding.produced);
856 carryover = process_coding.carryover_bytes;
857 if (carryover > 0)
858 memcpy (buf, process_coding.carryover,
859 process_coding.carryover_bytes);
863 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
864 break;
866 /* Make the buffer bigger as we continue to read more data,
867 but not past CALLPROC_BUFFER_SIZE_MAX. */
868 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
869 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
870 bufsize = CALLPROC_BUFFER_SIZE_MAX;
872 if (display_p)
874 if (first)
875 prepare_menu_bars ();
876 first = 0;
877 redisplay_preserve_echo_area (1);
878 /* This variable might have been set to 0 for code
879 detection. In that case, we set it back to 1 because
880 we should have already detected a coding system. */
881 display_on_the_fly = 1;
883 immediate_quit = 1;
884 QUIT;
886 give_up: ;
888 Vlast_coding_system_used = CODING_ID_NAME (process_coding.id);
889 /* If the caller required, let the buffer inherit the
890 coding-system used to decode the process output. */
891 if (inherit_process_coding_system)
892 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
893 make_number (total_read));
896 #ifndef MSDOS
897 /* Wait for it to terminate, unless it already has. */
898 wait_for_termination (pid, &status, !output_to_buffer);
899 #endif
901 immediate_quit = 0;
903 /* Don't kill any children that the subprocess may have left behind
904 when exiting. */
905 synch_process_pid = 0;
907 SAFE_FREE ();
908 unbind_to (count, Qnil);
910 if (WIFSIGNALED (status))
912 const char *signame;
914 synchronize_system_messages_locale ();
915 signame = strsignal (WTERMSIG (status));
917 if (signame == 0)
918 signame = "unknown";
920 return code_convert_string_norecord (build_string (signame),
921 Vlocale_coding_system, 0);
924 eassert (WIFEXITED (status));
925 return make_number (WEXITSTATUS (status));
928 static Lisp_Object
929 delete_temp_file (Lisp_Object name)
931 /* Suppress jka-compr handling, etc. */
932 ptrdiff_t count = SPECPDL_INDEX ();
933 specbind (intern ("file-name-handler-alist"), Qnil);
934 #ifdef WINDOWSNT
935 /* If this is called when the subprocess didn't exit yet, the
936 attempt to delete its input file will fail. In that case, we
937 schedule the file for deletion when the subprocess exits. This
938 is the 2nd part of handling this situation; see the call to
939 record_infile in call-process above, for the first part. */
940 if (!internal_delete_file (name))
942 Lisp_Object encoded_file = ENCODE_FILE (name);
944 record_pending_deletion (SSDATA (encoded_file));
946 #else
947 internal_delete_file (name);
948 #endif
949 unbind_to (count, Qnil);
950 return Qnil;
953 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
954 3, MANY, 0,
955 doc: /* Send text from START to END to a synchronous process running PROGRAM.
956 The remaining arguments are optional.
957 Delete the text if fourth arg DELETE is non-nil.
959 Insert output in BUFFER before point; t means current buffer; nil for
960 BUFFER means discard it; 0 means discard and don't wait; and `(:file
961 FILE)', where FILE is a file name string, means that it should be
962 written to that file (if the file already exists it is overwritten).
963 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
964 REAL-BUFFER says what to do with standard output, as above,
965 while STDERR-FILE says what to do with standard error in the child.
966 STDERR-FILE may be nil (discard standard error output),
967 t (mix it with ordinary output), or a file name string.
969 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
970 Remaining args are passed to PROGRAM at startup as command args.
972 If BUFFER is 0, `call-process-region' returns immediately with value nil.
973 Otherwise it waits for PROGRAM to terminate
974 and returns a numeric exit status or a signal description string.
975 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
977 usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
978 (ptrdiff_t nargs, Lisp_Object *args)
980 struct gcpro gcpro1;
981 Lisp_Object filename_string;
982 register Lisp_Object start, end;
983 ptrdiff_t count = SPECPDL_INDEX ();
984 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
985 Lisp_Object coding_systems;
986 Lisp_Object val, *args2;
987 ptrdiff_t i;
988 Lisp_Object tmpdir;
990 if (STRINGP (Vtemporary_file_directory))
991 tmpdir = Vtemporary_file_directory;
992 else
994 #ifndef DOS_NT
995 if (getenv ("TMPDIR"))
996 tmpdir = build_string (getenv ("TMPDIR"));
997 else
998 tmpdir = build_string ("/tmp/");
999 #else /* DOS_NT */
1000 char *outf;
1001 if ((outf = egetenv ("TMPDIR"))
1002 || (outf = egetenv ("TMP"))
1003 || (outf = egetenv ("TEMP")))
1004 tmpdir = build_string (outf);
1005 else
1006 tmpdir = Ffile_name_as_directory (build_string ("c:/temp"));
1007 #endif
1011 USE_SAFE_ALLOCA;
1012 Lisp_Object pattern = Fexpand_file_name (Vtemp_file_name_pattern, tmpdir);
1013 Lisp_Object encoded_tem = ENCODE_FILE (pattern);
1014 char *tempfile = SAFE_ALLOCA (SBYTES (encoded_tem) + 1);
1015 memcpy (tempfile, SDATA (encoded_tem), SBYTES (encoded_tem) + 1);
1016 coding_systems = Qt;
1018 #ifdef HAVE_MKSTEMP
1020 int fd;
1022 block_input ();
1023 fd = mkstemp (tempfile);
1024 unblock_input ();
1025 if (fd == -1)
1026 report_file_error ("Failed to open temporary file",
1027 Fcons (build_string (tempfile), Qnil));
1028 else
1029 close (fd);
1031 #else
1032 errno = 0;
1033 mktemp (tempfile);
1034 if (!*tempfile)
1036 if (!errno)
1037 errno = EEXIST;
1038 report_file_error ("Failed to open temporary file using pattern",
1039 Fcons (pattern, Qnil));
1041 #endif
1043 filename_string = build_string (tempfile);
1044 GCPRO1 (filename_string);
1045 SAFE_FREE ();
1048 start = args[0];
1049 end = args[1];
1050 /* Decide coding-system of the contents of the temporary file. */
1051 if (!NILP (Vcoding_system_for_write))
1052 val = Vcoding_system_for_write;
1053 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
1054 val = Qraw_text;
1055 else
1057 USE_SAFE_ALLOCA;
1058 SAFE_NALLOCA (args2, 1, nargs + 1);
1059 args2[0] = Qcall_process_region;
1060 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1061 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1062 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
1063 SAFE_FREE ();
1065 val = complement_process_encoding_system (val);
1068 ptrdiff_t count1 = SPECPDL_INDEX ();
1070 specbind (intern ("coding-system-for-write"), val);
1071 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
1072 happen to get a ".Z" suffix. */
1073 specbind (intern ("file-name-handler-alist"), Qnil);
1074 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
1076 unbind_to (count1, Qnil);
1079 /* Note that Fcall_process takes care of binding
1080 coding-system-for-read. */
1082 record_unwind_protect (delete_temp_file, filename_string);
1084 if (nargs > 3 && !NILP (args[3]))
1085 Fdelete_region (start, end);
1087 if (nargs > 3)
1089 args += 2;
1090 nargs -= 2;
1092 else
1094 args[0] = args[2];
1095 nargs = 2;
1097 args[1] = filename_string;
1099 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
1102 #ifndef WINDOWSNT
1103 static int relocate_fd (int fd, int minfd);
1104 #endif
1106 static char **
1107 add_env (char **env, char **new_env, char *string)
1109 char **ep;
1110 bool ok = 1;
1111 if (string == NULL)
1112 return new_env;
1114 /* See if this string duplicates any string already in the env.
1115 If so, don't put it in.
1116 When an env var has multiple definitions,
1117 we keep the definition that comes first in process-environment. */
1118 for (ep = env; ok && ep != new_env; ep++)
1120 char *p = *ep, *q = string;
1121 while (ok)
1123 if (*q != *p)
1124 break;
1125 if (*q == 0)
1126 /* The string is a lone variable name; keep it for now, we
1127 will remove it later. It is a placeholder for a
1128 variable that is not to be included in the environment. */
1129 break;
1130 if (*q == '=')
1131 ok = 0;
1132 p++, q++;
1135 if (ok)
1136 *new_env++ = string;
1137 return new_env;
1140 /* This is the last thing run in a newly forked inferior
1141 either synchronous or asynchronous.
1142 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1143 Initialize inferior's priority, pgrp, connected dir and environment.
1144 then exec another program based on new_argv.
1146 If SET_PGRP, put the subprocess into a separate process group.
1148 CURRENT_DIR is an elisp string giving the path of the current
1149 directory the subprocess should have. Since we can't really signal
1150 a decent error from within the child, this should be verified as an
1151 executable directory by the parent. */
1154 child_setup (int in, int out, int err, char **new_argv, bool set_pgrp,
1155 Lisp_Object current_dir)
1157 char **env;
1158 char *pwd_var;
1159 #ifdef WINDOWSNT
1160 int cpid;
1161 HANDLE handles[3];
1162 #endif /* WINDOWSNT */
1164 pid_t pid = getpid ();
1166 /* Close Emacs's descriptors that this process should not have. */
1167 close_process_descs ();
1169 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1170 we will lose if we call close_load_descs here. */
1171 #ifndef DOS_NT
1172 close_load_descs ();
1173 #endif
1175 /* Note that use of alloca is always safe here. It's obvious for systems
1176 that do not have true vfork or that have true (stack) alloca.
1177 If using vfork and C_ALLOCA (when Emacs used to include
1178 src/alloca.c) it is safe because that changes the superior's
1179 static variables as if the superior had done alloca and will be
1180 cleaned up in the usual way. */
1182 register char *temp;
1183 size_t i; /* size_t, because ptrdiff_t might overflow here! */
1185 i = SBYTES (current_dir);
1186 #ifdef MSDOS
1187 /* MSDOS must have all environment variables malloc'ed, because
1188 low-level libc functions that launch subsidiary processes rely
1189 on that. */
1190 pwd_var = xmalloc (i + 6);
1191 #else
1192 pwd_var = alloca (i + 6);
1193 #endif
1194 temp = pwd_var + 4;
1195 memcpy (pwd_var, "PWD=", 4);
1196 memcpy (temp, SDATA (current_dir), i);
1197 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
1198 temp[i] = 0;
1200 #ifndef DOS_NT
1201 /* We can't signal an Elisp error here; we're in a vfork. Since
1202 the callers check the current directory before forking, this
1203 should only return an error if the directory's permissions
1204 are changed between the check and this chdir, but we should
1205 at least check. */
1206 if (chdir (temp) < 0)
1207 _exit (errno);
1208 #else /* DOS_NT */
1209 /* Get past the drive letter, so that d:/ is left alone. */
1210 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1212 temp += 2;
1213 i -= 2;
1215 #endif /* DOS_NT */
1217 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1218 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1219 temp[--i] = 0;
1222 /* Set `env' to a vector of the strings in the environment. */
1224 register Lisp_Object tem;
1225 register char **new_env;
1226 char **p, **q;
1227 register int new_length;
1228 Lisp_Object display = Qnil;
1230 new_length = 0;
1232 for (tem = Vprocess_environment;
1233 CONSP (tem) && STRINGP (XCAR (tem));
1234 tem = XCDR (tem))
1236 if (strncmp (SSDATA (XCAR (tem)), "DISPLAY", 7) == 0
1237 && (SDATA (XCAR (tem)) [7] == '\0'
1238 || SDATA (XCAR (tem)) [7] == '='))
1239 /* DISPLAY is specified in process-environment. */
1240 display = Qt;
1241 new_length++;
1244 /* If not provided yet, use the frame's DISPLAY. */
1245 if (NILP (display))
1247 Lisp_Object tmp = Fframe_parameter (selected_frame, Qdisplay);
1248 if (!STRINGP (tmp) && CONSP (Vinitial_environment))
1249 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1250 tmp = Fgetenv_internal (build_string ("DISPLAY"),
1251 Vinitial_environment);
1252 if (STRINGP (tmp))
1254 display = tmp;
1255 new_length++;
1259 /* new_length + 2 to include PWD and terminating 0. */
1260 env = new_env = alloca ((new_length + 2) * sizeof *env);
1261 /* If we have a PWD envvar, pass one down,
1262 but with corrected value. */
1263 if (egetenv ("PWD"))
1264 *new_env++ = pwd_var;
1266 if (STRINGP (display))
1268 char *vdata = alloca (sizeof "DISPLAY=" + SBYTES (display));
1269 strcpy (vdata, "DISPLAY=");
1270 strcat (vdata, SSDATA (display));
1271 new_env = add_env (env, new_env, vdata);
1274 /* Overrides. */
1275 for (tem = Vprocess_environment;
1276 CONSP (tem) && STRINGP (XCAR (tem));
1277 tem = XCDR (tem))
1278 new_env = add_env (env, new_env, SSDATA (XCAR (tem)));
1280 *new_env = 0;
1282 /* Remove variable names without values. */
1283 p = q = env;
1284 while (*p != 0)
1286 while (*q != 0 && strchr (*q, '=') == NULL)
1287 q++;
1288 *p = *q++;
1289 if (*p != 0)
1290 p++;
1295 #ifdef WINDOWSNT
1296 prepare_standard_handles (in, out, err, handles);
1297 set_process_dir (SDATA (current_dir));
1298 /* Spawn the child. (See w32proc.c:sys_spawnve). */
1299 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1300 reset_standard_handles (in, out, err, handles);
1301 if (cpid == -1)
1302 /* An error occurred while trying to spawn the process. */
1303 report_file_error ("Spawning child process", Qnil);
1304 return cpid;
1306 #else /* not WINDOWSNT */
1307 /* Make sure that in, out, and err are not actually already in
1308 descriptors zero, one, or two; this could happen if Emacs is
1309 started with its standard in, out, or error closed, as might
1310 happen under X. */
1312 int oin = in, oout = out;
1314 /* We have to avoid relocating the same descriptor twice! */
1316 in = relocate_fd (in, 3);
1318 if (out == oin)
1319 out = in;
1320 else
1321 out = relocate_fd (out, 3);
1323 if (err == oin)
1324 err = in;
1325 else if (err == oout)
1326 err = out;
1327 else
1328 err = relocate_fd (err, 3);
1331 #ifndef MSDOS
1332 emacs_close (0);
1333 emacs_close (1);
1334 emacs_close (2);
1336 dup2 (in, 0);
1337 dup2 (out, 1);
1338 dup2 (err, 2);
1339 emacs_close (in);
1340 if (out != in)
1341 emacs_close (out);
1342 if (err != in && err != out)
1343 emacs_close (err);
1345 setpgid (0, 0);
1346 tcsetpgrp (0, pid);
1348 execve (new_argv[0], new_argv, env);
1350 emacs_write (1, "Can't exec program: ", 20);
1351 emacs_write (1, new_argv[0], strlen (new_argv[0]));
1352 emacs_write (1, "\n", 1);
1353 _exit (1);
1355 #else /* MSDOS */
1356 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1357 xfree (pwd_var);
1358 if (pid == -1)
1359 /* An error occurred while trying to run the subprocess. */
1360 report_file_error ("Spawning child process", Qnil);
1361 return pid;
1362 #endif /* MSDOS */
1363 #endif /* not WINDOWSNT */
1366 #ifndef WINDOWSNT
1367 /* Move the file descriptor FD so that its number is not less than MINFD.
1368 If the file descriptor is moved at all, the original is freed. */
1369 static int
1370 relocate_fd (int fd, int minfd)
1372 if (fd >= minfd)
1373 return fd;
1374 else
1376 int new = fcntl (fd, F_DUPFD, minfd);
1377 if (new == -1)
1379 const char *message_1 = "Error while setting up child: ";
1380 const char *errmessage = strerror (errno);
1381 const char *message_2 = "\n";
1382 emacs_write (2, message_1, strlen (message_1));
1383 emacs_write (2, errmessage, strlen (errmessage));
1384 emacs_write (2, message_2, strlen (message_2));
1385 _exit (1);
1387 emacs_close (fd);
1388 return new;
1391 #endif /* not WINDOWSNT */
1393 static bool
1394 getenv_internal_1 (const char *var, ptrdiff_t varlen, char **value,
1395 ptrdiff_t *valuelen, Lisp_Object env)
1397 for (; CONSP (env); env = XCDR (env))
1399 Lisp_Object entry = XCAR (env);
1400 if (STRINGP (entry)
1401 && SBYTES (entry) >= varlen
1402 #ifdef WINDOWSNT
1403 /* NT environment variables are case insensitive. */
1404 && ! strnicmp (SDATA (entry), var, varlen)
1405 #else /* not WINDOWSNT */
1406 && ! memcmp (SDATA (entry), var, varlen)
1407 #endif /* not WINDOWSNT */
1410 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1412 *value = SSDATA (entry) + (varlen + 1);
1413 *valuelen = SBYTES (entry) - (varlen + 1);
1414 return 1;
1416 else if (SBYTES (entry) == varlen)
1418 /* Lone variable names in Vprocess_environment mean that
1419 variable should be removed from the environment. */
1420 *value = NULL;
1421 return 1;
1425 return 0;
1428 static bool
1429 getenv_internal (const char *var, ptrdiff_t varlen, char **value,
1430 ptrdiff_t *valuelen, Lisp_Object frame)
1432 /* Try to find VAR in Vprocess_environment first. */
1433 if (getenv_internal_1 (var, varlen, value, valuelen,
1434 Vprocess_environment))
1435 return *value ? 1 : 0;
1437 /* For DISPLAY try to get the values from the frame or the initial env. */
1438 if (strcmp (var, "DISPLAY") == 0)
1440 Lisp_Object display
1441 = Fframe_parameter (NILP (frame) ? selected_frame : frame, Qdisplay);
1442 if (STRINGP (display))
1444 *value = SSDATA (display);
1445 *valuelen = SBYTES (display);
1446 return 1;
1448 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1449 if (getenv_internal_1 (var, varlen, value, valuelen,
1450 Vinitial_environment))
1451 return *value ? 1 : 0;
1454 return 0;
1457 DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
1458 doc: /* Get the value of environment variable VARIABLE.
1459 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1460 the environment. Otherwise, value is a string.
1462 This function searches `process-environment' for VARIABLE.
1464 If optional parameter ENV is a list, then search this list instead of
1465 `process-environment', and return t when encountering a negative entry
1466 \(an entry for a variable with no value). */)
1467 (Lisp_Object variable, Lisp_Object env)
1469 char *value;
1470 ptrdiff_t valuelen;
1472 CHECK_STRING (variable);
1473 if (CONSP (env))
1475 if (getenv_internal_1 (SSDATA (variable), SBYTES (variable),
1476 &value, &valuelen, env))
1477 return value ? make_string (value, valuelen) : Qt;
1478 else
1479 return Qnil;
1481 else if (getenv_internal (SSDATA (variable), SBYTES (variable),
1482 &value, &valuelen, env))
1483 return make_string (value, valuelen);
1484 else
1485 return Qnil;
1488 /* A version of getenv that consults the Lisp environment lists,
1489 easily callable from C. */
1490 char *
1491 egetenv (const char *var)
1493 char *value;
1494 ptrdiff_t valuelen;
1496 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
1497 return value;
1498 else
1499 return 0;
1503 /* This is run before init_cmdargs. */
1505 void
1506 init_callproc_1 (void)
1508 #ifdef HAVE_NS
1509 const char *etc_dir = ns_etc_directory ();
1510 const char *path_exec = ns_exec_path ();
1511 #endif
1513 Vdata_directory = decode_env_path ("EMACSDATA",
1514 #ifdef HAVE_NS
1515 etc_dir ? etc_dir :
1516 #endif
1517 PATH_DATA);
1518 Vdata_directory = Ffile_name_as_directory (Fcar (Vdata_directory));
1520 Vdoc_directory = decode_env_path ("EMACSDOC",
1521 #ifdef HAVE_NS
1522 etc_dir ? etc_dir :
1523 #endif
1524 PATH_DOC);
1525 Vdoc_directory = Ffile_name_as_directory (Fcar (Vdoc_directory));
1527 /* Check the EMACSPATH environment variable, defaulting to the
1528 PATH_EXEC path from epaths.h. */
1529 Vexec_path = decode_env_path ("EMACSPATH",
1530 #ifdef HAVE_NS
1531 path_exec ? path_exec :
1532 #endif
1533 PATH_EXEC);
1534 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1535 /* FIXME? For ns, path_exec should go at the front? */
1536 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1539 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1541 void
1542 init_callproc (void)
1544 char *data_dir = egetenv ("EMACSDATA");
1546 register char * sh;
1547 Lisp_Object tempdir;
1548 #ifdef HAVE_NS
1549 if (data_dir == 0)
1551 const char *etc_dir = ns_etc_directory ();
1552 if (etc_dir)
1554 data_dir = alloca (strlen (etc_dir) + 1);
1555 strcpy (data_dir, etc_dir);
1558 #endif
1560 if (!NILP (Vinstallation_directory))
1562 /* Add to the path the lib-src subdir of the installation dir. */
1563 Lisp_Object tem;
1564 tem = Fexpand_file_name (build_string ("lib-src"),
1565 Vinstallation_directory);
1566 #ifndef MSDOS
1567 /* MSDOS uses wrapped binaries, so don't do this. */
1568 if (NILP (Fmember (tem, Vexec_path)))
1570 #ifdef HAVE_NS
1571 const char *path_exec = ns_exec_path ();
1572 #endif
1573 Vexec_path = decode_env_path ("EMACSPATH",
1574 #ifdef HAVE_NS
1575 path_exec ? path_exec :
1576 #endif
1577 PATH_EXEC);
1578 Vexec_path = Fcons (tem, Vexec_path);
1579 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1582 Vexec_directory = Ffile_name_as_directory (tem);
1583 #endif /* not MSDOS */
1585 /* Maybe use ../etc as well as ../lib-src. */
1586 if (data_dir == 0)
1588 tem = Fexpand_file_name (build_string ("etc"),
1589 Vinstallation_directory);
1590 Vdoc_directory = Ffile_name_as_directory (tem);
1594 /* Look for the files that should be in etc. We don't use
1595 Vinstallation_directory, because these files are never installed
1596 near the executable, and they are never in the build
1597 directory when that's different from the source directory.
1599 Instead, if these files are not in the nominal place, we try the
1600 source directory. */
1601 if (data_dir == 0)
1603 Lisp_Object tem, tem1, srcdir;
1605 srcdir = Fexpand_file_name (build_string ("../src/"),
1606 build_string (PATH_DUMPLOADSEARCH));
1607 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1608 tem1 = Ffile_exists_p (tem);
1609 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
1611 Lisp_Object newdir;
1612 newdir = Fexpand_file_name (build_string ("../etc/"),
1613 build_string (PATH_DUMPLOADSEARCH));
1614 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1615 tem1 = Ffile_exists_p (tem);
1616 if (!NILP (tem1))
1617 Vdata_directory = newdir;
1621 #ifndef CANNOT_DUMP
1622 if (initialized)
1623 #endif
1625 tempdir = Fdirectory_file_name (Vexec_directory);
1626 if (! file_accessible_directory_p (SSDATA (tempdir)))
1627 dir_warning ("arch-dependent data dir", Vexec_directory);
1630 tempdir = Fdirectory_file_name (Vdata_directory);
1631 if (! file_accessible_directory_p (SSDATA (tempdir)))
1632 dir_warning ("arch-independent data dir", Vdata_directory);
1634 sh = (char *) getenv ("SHELL");
1635 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1637 #ifdef DOS_NT
1638 Vshared_game_score_directory = Qnil;
1639 #else
1640 Vshared_game_score_directory = build_string (PATH_GAME);
1641 if (NILP (Ffile_accessible_directory_p (Vshared_game_score_directory)))
1642 Vshared_game_score_directory = Qnil;
1643 #endif
1646 void
1647 set_initial_environment (void)
1649 char **envp;
1650 for (envp = environ; *envp; envp++)
1651 Vprocess_environment = Fcons (build_string (*envp),
1652 Vprocess_environment);
1653 /* Ideally, the `copy' shouldn't be necessary, but it seems it's frequent
1654 to use `delete' and friends on process-environment. */
1655 Vinitial_environment = Fcopy_sequence (Vprocess_environment);
1658 void
1659 syms_of_callproc (void)
1661 #ifndef DOS_NT
1662 Vtemp_file_name_pattern = build_string ("emacsXXXXXX");
1663 #elif defined (WINDOWSNT)
1664 Vtemp_file_name_pattern = build_string ("emXXXXXX");
1665 #else
1666 Vtemp_file_name_pattern = build_string ("detmp.XXX");
1667 #endif
1668 staticpro (&Vtemp_file_name_pattern);
1670 DEFVAR_LISP ("shell-file-name", Vshell_file_name,
1671 doc: /* File name to load inferior shells from.
1672 Initialized from the SHELL environment variable, or to a system-dependent
1673 default if SHELL is not set. */);
1675 DEFVAR_LISP ("exec-path", Vexec_path,
1676 doc: /* List of directories to search programs to run in subprocesses.
1677 Each element is a string (directory name) or nil (try default directory). */);
1679 DEFVAR_LISP ("exec-suffixes", Vexec_suffixes,
1680 doc: /* List of suffixes to try to find executable file names.
1681 Each element is a string. */);
1682 Vexec_suffixes = Qnil;
1684 DEFVAR_LISP ("exec-directory", Vexec_directory,
1685 doc: /* Directory for executables for Emacs to invoke.
1686 More generally, this includes any architecture-dependent files
1687 that are built and installed from the Emacs distribution. */);
1689 DEFVAR_LISP ("data-directory", Vdata_directory,
1690 doc: /* Directory of machine-independent files that come with GNU Emacs.
1691 These are files intended for Emacs to use while it runs. */);
1693 DEFVAR_LISP ("doc-directory", Vdoc_directory,
1694 doc: /* Directory containing the DOC file that comes with GNU Emacs.
1695 This is usually the same as `data-directory'. */);
1697 DEFVAR_LISP ("configure-info-directory", Vconfigure_info_directory,
1698 doc: /* For internal use by the build procedure only.
1699 This is the name of the directory in which the build procedure installed
1700 Emacs's info files; the default value for `Info-default-directory-list'
1701 includes this. */);
1702 Vconfigure_info_directory = build_string (PATH_INFO);
1704 DEFVAR_LISP ("shared-game-score-directory", Vshared_game_score_directory,
1705 doc: /* Directory of score files for games which come with GNU Emacs.
1706 If this variable is nil, then Emacs is unable to use a shared directory. */);
1707 #ifdef DOS_NT
1708 Vshared_game_score_directory = Qnil;
1709 #else
1710 Vshared_game_score_directory = build_string (PATH_GAME);
1711 #endif
1713 DEFVAR_LISP ("initial-environment", Vinitial_environment,
1714 doc: /* List of environment variables inherited from the parent process.
1715 Each element should be a string of the form ENVVARNAME=VALUE.
1716 The elements must normally be decoded (using `locale-coding-system') for use. */);
1717 Vinitial_environment = Qnil;
1719 DEFVAR_LISP ("process-environment", Vprocess_environment,
1720 doc: /* List of overridden environment variables for subprocesses to inherit.
1721 Each element should be a string of the form ENVVARNAME=VALUE.
1723 Entries in this list take precedence to those in the frame-local
1724 environments. Therefore, let-binding `process-environment' is an easy
1725 way to temporarily change the value of an environment variable,
1726 irrespective of where it comes from. To use `process-environment' to
1727 remove an environment variable, include only its name in the list,
1728 without "=VALUE".
1730 This variable is set to nil when Emacs starts.
1732 If multiple entries define the same variable, the first one always
1733 takes precedence.
1735 Non-ASCII characters are encoded according to the initial value of
1736 `locale-coding-system', i.e. the elements must normally be decoded for
1737 use.
1739 See `setenv' and `getenv'. */);
1740 Vprocess_environment = Qnil;
1742 defsubr (&Scall_process);
1743 defsubr (&Sgetenv_internal);
1744 defsubr (&Scall_process_region);