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