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