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