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