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