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