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