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