(Fcall_process): Check type of process cmd args earlier on.
[bpt/emacs.git] / src / callproc.c
1 /* Synchronous subprocess invocation for GNU Emacs.
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
20
21
22 #include <signal.h>
23 #include <errno.h>
24
25 #include <config.h>
26 #include <stdio.h>
27
28 extern int errno;
29 extern char *strerror ();
30
31 /* Define SIGCHLD as an alias for SIGCLD. */
32
33 #if !defined (SIGCHLD) && defined (SIGCLD)
34 #define SIGCHLD SIGCLD
35 #endif /* SIGCLD */
36
37 #include <sys/types.h>
38
39 #include <sys/file.h>
40 #ifdef USG5
41 #define INCLUDED_FCNTL
42 #include <fcntl.h>
43 #endif
44
45 #ifdef WINDOWSNT
46 #define NOMINMAX
47 #include <windows.h>
48 #include <stdlib.h> /* for proper declaration of environ */
49 #include <fcntl.h>
50 #include "w32.h"
51 #define _P_NOWAIT 1 /* from process.h */
52 #endif
53
54 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
55 #define INCLUDED_FCNTL
56 #include <fcntl.h>
57 #include <sys/stat.h>
58 #include <sys/param.h>
59 #include <errno.h>
60 #endif /* MSDOS */
61
62 #ifndef O_RDONLY
63 #define O_RDONLY 0
64 #endif
65
66 #ifndef O_WRONLY
67 #define O_WRONLY 1
68 #endif
69
70 #include "lisp.h"
71 #include "commands.h"
72 #include "buffer.h"
73 #include "charset.h"
74 #include "coding.h"
75 #include <paths.h>
76 #include "process.h"
77 #include "syssignal.h"
78 #include "systty.h"
79
80 #ifdef MSDOS
81 #include "msdos.h"
82 #endif
83
84 #ifdef VMS
85 extern noshare char **environ;
86 #else
87 extern char **environ;
88 #endif
89
90 #define max(a, b) ((a) > (b) ? (a) : (b))
91
92 Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
93 Lisp_Object Vconfigure_info_directory;
94 Lisp_Object Vtemp_file_name_pattern;
95
96 Lisp_Object Vshell_file_name;
97
98 Lisp_Object Vprocess_environment;
99
100 #ifdef DOS_NT
101 Lisp_Object Qbuffer_file_type;
102 #endif /* DOS_NT */
103
104 /* True iff we are about to fork off a synchronous process or if we
105 are waiting for it. */
106 int synch_process_alive;
107
108 /* Nonzero => this is a string explaining death of synchronous subprocess. */
109 char *synch_process_death;
110
111 /* If synch_process_death is zero,
112 this is exit code of synchronous subprocess. */
113 int synch_process_retcode;
114
115 extern Lisp_Object Vdoc_file_name;
116
117 extern Lisp_Object Vfile_name_coding_system, Vdefault_file_name_coding_system;
118 \f
119 /* Clean up when exiting Fcall_process.
120 On MSDOS, delete the temporary file on any kind of termination.
121 On Unix, kill the process and any children on termination by signal. */
122
123 /* Nonzero if this is termination due to exit. */
124 static int call_process_exited;
125
126 #ifndef VMS /* VMS version is in vmsproc.c. */
127
128 static Lisp_Object
129 call_process_kill (fdpid)
130 Lisp_Object fdpid;
131 {
132 close (XFASTINT (Fcar (fdpid)));
133 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
134 synch_process_alive = 0;
135 return Qnil;
136 }
137
138 Lisp_Object
139 call_process_cleanup (fdpid)
140 Lisp_Object fdpid;
141 {
142 #ifdef MSDOS
143 /* for MSDOS fdpid is really (fd . tempfile) */
144 register Lisp_Object file;
145 file = Fcdr (fdpid);
146 close (XFASTINT (Fcar (fdpid)));
147 if (strcmp (XSTRING (file)-> data, NULL_DEVICE) != 0)
148 unlink (XSTRING (file)->data);
149 #else /* not MSDOS */
150 register int pid = XFASTINT (Fcdr (fdpid));
151
152
153 if (call_process_exited)
154 {
155 close (XFASTINT (Fcar (fdpid)));
156 return Qnil;
157 }
158
159 if (EMACS_KILLPG (pid, SIGINT) == 0)
160 {
161 int count = specpdl_ptr - specpdl;
162 record_unwind_protect (call_process_kill, fdpid);
163 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
164 immediate_quit = 1;
165 QUIT;
166 wait_for_termination (pid);
167 immediate_quit = 0;
168 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
169 message1 ("Waiting for process to die...done");
170 }
171 synch_process_alive = 0;
172 close (XFASTINT (Fcar (fdpid)));
173 #endif /* not MSDOS */
174 return Qnil;
175 }
176
177 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
178 "Call PROGRAM synchronously in separate process.\n\
179 The program's input comes from file INFILE (nil means `/dev/null').\n\
180 Insert output in BUFFER before point; t means current buffer;\n\
181 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
182 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
183 REAL-BUFFER says what to do with standard output, as above,\n\
184 while STDERR-FILE says what to do with standard error in the child.\n\
185 STDERR-FILE may be nil (discard standard error output),\n\
186 t (mix it with ordinary output), or a file name string.\n\
187 \n\
188 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
189 Remaining arguments are strings passed as command arguments to PROGRAM.\n\
190 \n\
191 If BUFFER is 0, `call-process' returns immediately with value nil.\n\
192 Otherwise it waits for PROGRAM to terminate\n\
193 and returns a numeric exit status or a signal description string.\n\
194 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
195 (nargs, args)
196 int nargs;
197 register Lisp_Object *args;
198 {
199 Lisp_Object infile, buffer, current_dir, display, path;
200 int fd[2];
201 int filefd;
202 register int pid;
203 char buf[16384];
204 char *bufptr = buf;
205 int bufsize = 16384;
206 int count = specpdl_ptr - specpdl;
207
208 register unsigned char **new_argv
209 = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
210 struct buffer *old = current_buffer;
211 /* File to use for stderr in the child.
212 t means use same as standard output. */
213 Lisp_Object error_file;
214 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
215 char *outf, *tempfile;
216 int outfilefd;
217 #endif
218 #if 0
219 int mask;
220 #endif
221 struct coding_system process_coding; /* coding-system of process output */
222 struct coding_system argument_coding; /* coding-system of arguments */
223
224 CHECK_STRING (args[0], 0);
225
226 error_file = Qt;
227
228 #ifndef subprocesses
229 /* Without asynchronous processes we cannot have BUFFER == 0. */
230 if (nargs >= 3
231 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
232 error ("Operating system cannot handle asynchronous subprocesses");
233 #endif /* subprocesses */
234
235 /* Decide the coding-system for giving arguments and reading process
236 output. */
237 {
238 Lisp_Object val, *args2;
239 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
240 Lisp_Object coding_systems = Qt;
241 int i;
242
243 /* If arguments are supplied, we may have to encode them. */
244 if (nargs >= 5)
245 {
246 int must_encode = 0;
247
248 for (i = 4; i < nargs; i++)
249 CHECK_STRING (args[i], i);
250
251 for (i = 4; i < nargs; i++)
252 if (STRING_MULTIBYTE (args[i]))
253 must_encode = 1;
254
255 if (!NILP (Vcoding_system_for_write))
256 val = Vcoding_system_for_write;
257 else if (! must_encode)
258 val = Qnil;
259 else
260 {
261 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
262 args2[0] = Qcall_process;
263 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
264 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
265 if (CONSP (coding_systems))
266 val = XCONS (coding_systems)->cdr;
267 else if (CONSP (Vdefault_process_coding_system))
268 val = XCONS (Vdefault_process_coding_system)->cdr;
269 else
270 val = Qnil;
271 }
272 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
273 }
274
275 /* If BUFFER is nil, we must read process output once and then
276 discard it, so setup coding system but with nil. If BUFFER is
277 an integer, we can discard it without reading. */
278 if (nargs < 3 || NILP (args[2])
279 || (CONSP (args[2]) && NILP (XCAR (args[2]))))
280 setup_coding_system (Qnil, &process_coding);
281 else if (!INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2]))
282 {
283 val = Qnil;
284 if (!NILP (Vcoding_system_for_read))
285 val = Vcoding_system_for_read;
286 else if (NILP (current_buffer->enable_multibyte_characters))
287 val = Qraw_text;
288 else
289 {
290 if (EQ (coding_systems, Qt))
291 {
292 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
293 args2[0] = Qcall_process;
294 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
295 coding_systems
296 = Ffind_operation_coding_system (nargs + 1, args2);
297 }
298 if (CONSP (coding_systems))
299 val = XCONS (coding_systems)->car;
300 else if (CONSP (Vdefault_process_coding_system))
301 val = XCONS (Vdefault_process_coding_system)->car;
302 else
303 val = Qnil;
304 }
305 setup_coding_system (Fcheck_coding_system (val), &process_coding);
306 }
307 }
308
309 if (nargs >= 2 && ! NILP (args[1]))
310 {
311 infile = Fexpand_file_name (args[1], current_buffer->directory);
312 CHECK_STRING (infile, 1);
313 }
314 else
315 infile = build_string (NULL_DEVICE);
316
317 if (nargs >= 3)
318 {
319 buffer = args[2];
320
321 /* If BUFFER is a list, its meaning is
322 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
323 if (CONSP (buffer))
324 {
325 if (CONSP (XCONS (buffer)->cdr))
326 {
327 Lisp_Object stderr_file;
328 stderr_file = XCONS (XCONS (buffer)->cdr)->car;
329
330 if (NILP (stderr_file) || EQ (Qt, stderr_file))
331 error_file = stderr_file;
332 else
333 error_file = Fexpand_file_name (stderr_file, Qnil);
334 }
335
336 buffer = XCONS (buffer)->car;
337 }
338
339 if (!(EQ (buffer, Qnil)
340 || EQ (buffer, Qt)
341 || INTEGERP (buffer)))
342 {
343 Lisp_Object spec_buffer;
344 spec_buffer = buffer;
345 buffer = Fget_buffer_create (buffer);
346 /* Mention the buffer name for a better error message. */
347 if (NILP (buffer))
348 CHECK_BUFFER (spec_buffer, 2);
349 CHECK_BUFFER (buffer, 2);
350 }
351 }
352 else
353 buffer = Qnil;
354
355 /* Make sure that the child will be able to chdir to the current
356 buffer's current directory, or its unhandled equivalent. We
357 can't just have the child check for an error when it does the
358 chdir, since it's in a vfork.
359
360 We have to GCPRO around this because Fexpand_file_name,
361 Funhandled_file_name_directory, and Ffile_accessible_directory_p
362 might call a file name handling function. The argument list is
363 protected by the caller, so all we really have to worry about is
364 buffer. */
365 {
366 struct gcpro gcpro1, gcpro2, gcpro3;
367
368 current_dir = current_buffer->directory;
369
370 GCPRO3 (infile, buffer, current_dir);
371
372 current_dir
373 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
374 Qnil);
375 if (NILP (Ffile_accessible_directory_p (current_dir)))
376 report_file_error ("Setting current directory",
377 Fcons (current_buffer->directory, Qnil));
378
379 UNGCPRO;
380 }
381
382 display = nargs >= 4 ? args[3] : Qnil;
383
384 filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
385 if (filefd < 0)
386 {
387 report_file_error ("Opening process input file", Fcons (infile, Qnil));
388 }
389 /* Search for program; barf if not found. */
390 {
391 struct gcpro gcpro1;
392
393 GCPRO1 (current_dir);
394 openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
395 UNGCPRO;
396 }
397 if (NILP (path))
398 {
399 close (filefd);
400 report_file_error ("Searching for program", Fcons (args[0], Qnil));
401 }
402 new_argv[0] = XSTRING (path)->data;
403 if (nargs > 4)
404 {
405 register int i;
406
407 if (! CODING_REQUIRE_ENCODING (&argument_coding))
408 {
409 for (i = 4; i < nargs; i++)
410 new_argv[i - 3] = XSTRING (args[i])->data;
411 }
412 else
413 {
414 /* We must encode the arguments. */
415 struct gcpro gcpro1, gcpro2, gcpro3;
416
417 GCPRO3 (infile, buffer, current_dir);
418 for (i = 4; i < nargs; i++)
419 {
420 int size = encoding_buffer_size (&argument_coding,
421 STRING_BYTES (XSTRING (args[i])));
422 unsigned char *dummy1 = (unsigned char *) alloca (size);
423 int dummy;
424
425 /* The Irix 4.0 compiler barfs if we eliminate dummy. */
426 new_argv[i - 3] = dummy1;
427 encode_coding (&argument_coding,
428 XSTRING (args[i])->data,
429 new_argv[i - 3],
430 STRING_BYTES (XSTRING (args[i])),
431 size);
432 new_argv[i - 3][argument_coding.produced] = 0;
433 }
434 UNGCPRO;
435 }
436 new_argv[nargs - 3] = 0;
437 }
438 else
439 new_argv[1] = 0;
440
441 #ifdef MSDOS /* MW, July 1993 */
442 if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
443 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
444 else
445 {
446 tempfile = alloca (20);
447 *tempfile = '\0';
448 }
449 dostounix_filename (tempfile);
450 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
451 strcat (tempfile, "/");
452 strcat (tempfile, "detmp.XXX");
453 mktemp (tempfile);
454
455 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
456 if (outfilefd < 0)
457 {
458 close (filefd);
459 report_file_error ("Opening process output file",
460 Fcons (build_string (tempfile), Qnil));
461 }
462 fd[0] = filefd;
463 fd[1] = outfilefd;
464 #endif /* MSDOS */
465
466 if (INTEGERP (buffer))
467 fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
468 else
469 {
470 #ifndef MSDOS
471 pipe (fd);
472 #endif
473 #if 0
474 /* Replaced by close_process_descs */
475 set_exclusive_use (fd[0]);
476 #endif
477 }
478
479 {
480 /* child_setup must clobber environ in systems with true vfork.
481 Protect it from permanent change. */
482 register char **save_environ = environ;
483 register int fd1 = fd[1];
484 int fd_error = fd1;
485
486 #if 0 /* Some systems don't have sigblock. */
487 mask = sigblock (sigmask (SIGCHLD));
488 #endif
489
490 /* Record that we're about to create a synchronous process. */
491 synch_process_alive = 1;
492
493 /* These vars record information from process termination.
494 Clear them now before process can possibly terminate,
495 to avoid timing error if process terminates soon. */
496 synch_process_death = 0;
497 synch_process_retcode = 0;
498
499 if (NILP (error_file))
500 fd_error = open (NULL_DEVICE, O_WRONLY);
501 else if (STRINGP (error_file))
502 {
503 #ifdef DOS_NT
504 fd_error = open (XSTRING (error_file)->data,
505 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
506 S_IREAD | S_IWRITE);
507 #else /* not DOS_NT */
508 fd_error = creat (XSTRING (error_file)->data, 0666);
509 #endif /* not DOS_NT */
510 }
511
512 if (fd_error < 0)
513 {
514 close (filefd);
515 if (fd[0] != filefd)
516 close (fd[0]);
517 if (fd1 >= 0)
518 close (fd1);
519 #ifdef MSDOS
520 unlink (tempfile);
521 #endif
522 report_file_error ("Cannot redirect stderr",
523 Fcons ((NILP (error_file)
524 ? build_string (NULL_DEVICE) : error_file),
525 Qnil));
526 }
527
528 current_dir = ENCODE_FILE (current_dir);
529
530 #ifdef MSDOS /* MW, July 1993 */
531 /* Note that on MSDOS `child_setup' actually returns the child process
532 exit status, not its PID, so we assign it to `synch_process_retcode'
533 below. */
534 pid = child_setup (filefd, outfilefd, fd_error, (char **) new_argv,
535 0, current_dir);
536
537 /* Record that the synchronous process exited and note its
538 termination status. */
539 synch_process_alive = 0;
540 synch_process_retcode = pid;
541 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
542 synch_process_death = strerror (errno);
543
544 close (outfilefd);
545 if (fd_error != outfilefd)
546 close (fd_error);
547 fd1 = -1; /* No harm in closing that one! */
548 /* Since CRLF is converted to LF within `decode_coding', we can
549 always open a file with binary mode. */
550 fd[0] = open (tempfile, O_BINARY);
551 if (fd[0] < 0)
552 {
553 unlink (tempfile);
554 close (filefd);
555 report_file_error ("Cannot re-open temporary file", Qnil);
556 }
557 #else /* not MSDOS */
558 #ifdef WINDOWSNT
559 pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
560 0, current_dir);
561 #else /* not WINDOWSNT */
562 pid = vfork ();
563
564 if (pid == 0)
565 {
566 if (fd[0] >= 0)
567 close (fd[0]);
568 #ifdef HAVE_SETSID
569 setsid ();
570 #endif
571 #if defined (USG) && !defined (BSD_PGRPS)
572 setpgrp ();
573 #else
574 setpgrp (pid, pid);
575 #endif /* USG */
576 child_setup (filefd, fd1, fd_error, (char **) new_argv,
577 0, current_dir);
578 }
579 #endif /* not WINDOWSNT */
580
581 /* The MSDOS case did this already. */
582 if (fd_error >= 0)
583 close (fd_error);
584 #endif /* not MSDOS */
585
586 environ = save_environ;
587
588 /* Close most of our fd's, but not fd[0]
589 since we will use that to read input from. */
590 close (filefd);
591 if (fd1 >= 0 && fd1 != fd_error)
592 close (fd1);
593 }
594
595 if (pid < 0)
596 {
597 if (fd[0] >= 0)
598 close (fd[0]);
599 report_file_error ("Doing vfork", Qnil);
600 }
601
602 if (INTEGERP (buffer))
603 {
604 if (fd[0] >= 0)
605 close (fd[0]);
606 #ifndef subprocesses
607 /* If Emacs has been built with asynchronous subprocess support,
608 we don't need to do this, I think because it will then have
609 the facilities for handling SIGCHLD. */
610 wait_without_blocking ();
611 #endif /* subprocesses */
612 return Qnil;
613 }
614
615 /* Enable sending signal if user quits below. */
616 call_process_exited = 0;
617
618 #ifdef MSDOS
619 /* MSDOS needs different cleanup information. */
620 record_unwind_protect (call_process_cleanup,
621 Fcons (make_number (fd[0]), build_string (tempfile)));
622 #else
623 record_unwind_protect (call_process_cleanup,
624 Fcons (make_number (fd[0]), make_number (pid)));
625 #endif /* not MSDOS */
626
627
628 if (BUFFERP (buffer))
629 Fset_buffer (buffer);
630
631 immediate_quit = 1;
632 QUIT;
633
634 {
635 register int nread;
636 int first = 1;
637 int total_read = 0;
638 int carryover = 0;
639 int display_on_the_fly = !NILP (display) && INTERACTIVE;
640 struct coding_system saved_coding;
641
642 saved_coding = process_coding;
643
644 while (1)
645 {
646 /* Repeatedly read until we've filled as much as possible
647 of the buffer size we have. But don't read
648 less than 1024--save that for the next bufferful. */
649 nread = carryover;
650 while (nread < bufsize - 1024)
651 {
652 int this_read = read (fd[0], bufptr + nread, bufsize - nread);
653
654 if (this_read < 0)
655 goto give_up;
656
657 if (this_read == 0)
658 {
659 process_coding.mode |= CODING_MODE_LAST_BLOCK;
660 break;
661 }
662
663 nread += this_read;
664 total_read += this_read;
665
666 if (display_on_the_fly)
667 break;
668 }
669
670 /* Now NREAD is the total amount of data in the buffer. */
671 immediate_quit = 0;
672
673 if (!NILP (buffer))
674 {
675 if (process_coding.type == coding_type_no_conversion)
676 insert (bufptr, nread);
677 else
678 { /* We have to decode the input. */
679 int size = decoding_buffer_size (&process_coding, nread);
680 char *decoding_buf = (char *) alloca (size);
681
682 decode_coding (&process_coding, bufptr, decoding_buf,
683 nread, size);
684 if (display_on_the_fly
685 && saved_coding.type == coding_type_undecided
686 && process_coding.type != coding_type_undecided)
687 {
688 /* We have detected some coding system. But,
689 there's a possibility that the detection was
690 done by insufficient data. So, we give up
691 displaying on the fly. */
692 display_on_the_fly = 0;
693 process_coding = saved_coding;
694 carryover = nread;
695 continue;
696 }
697 if (process_coding.produced > 0)
698 insert (decoding_buf, process_coding.produced);
699 carryover = nread - process_coding.consumed;
700 if (carryover > 0)
701 {
702 /* As CARRYOVER should not be that large, we had
703 better avoid overhead of bcopy. */
704 char *p = bufptr + process_coding.consumed;
705 char *pend = p + carryover;
706 char *dst = bufptr;
707
708 while (p < pend) *dst++ = *p++;
709 }
710 }
711 }
712 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
713 {
714 if (carryover > 0)
715 insert (bufptr, carryover);
716 break;
717 }
718
719 /* Make the buffer bigger as we continue to read more data,
720 but not past 64k. */
721 if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
722 {
723 bufsize *= 2;
724 bufptr = (char *) alloca (bufsize);
725 }
726
727 if (!NILP (display) && INTERACTIVE)
728 {
729 if (first)
730 prepare_menu_bars ();
731 first = 0;
732 redisplay_preserve_echo_area ();
733 }
734 immediate_quit = 1;
735 QUIT;
736 }
737 give_up: ;
738
739 Vlast_coding_system_used = process_coding.symbol;
740
741 /* If the caller required, let the buffer inherit the
742 coding-system used to decode the process output. */
743 if (inherit_process_coding_system)
744 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
745 make_number (total_read));
746 }
747
748 /* Wait for it to terminate, unless it already has. */
749 wait_for_termination (pid);
750
751 immediate_quit = 0;
752
753 set_buffer_internal (old);
754
755 /* Don't kill any children that the subprocess may have left behind
756 when exiting. */
757 call_process_exited = 1;
758
759 unbind_to (count, Qnil);
760
761 if (synch_process_death)
762 return build_string (synch_process_death);
763 return make_number (synch_process_retcode);
764 }
765 #endif
766 \f
767 static Lisp_Object
768 delete_temp_file (name)
769 Lisp_Object name;
770 {
771 /* Use Fdelete_file (indirectly) because that runs a file name handler.
772 We did that when writing the file, so we should do so when deleting. */
773 internal_delete_file (name);
774 }
775
776 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
777 3, MANY, 0,
778 "Send text from START to END to a synchronous process running PROGRAM.\n\
779 Delete the text if fourth arg DELETE is non-nil.\n\
780 \n\
781 Insert output in BUFFER before point; t means current buffer;\n\
782 nil for BUFFER means discard it; 0 means discard and don't wait.\n\
783 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,\n\
784 REAL-BUFFER says what to do with standard output, as above,\n\
785 while STDERR-FILE says what to do with standard error in the child.\n\
786 STDERR-FILE may be nil (discard standard error output),\n\
787 t (mix it with ordinary output), or a file name string.\n\
788 \n\
789 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
790 Remaining args are passed to PROGRAM at startup as command args.\n\
791 \n\
792 If BUFFER is nil, `call-process-region' returns immediately with value nil.\n\
793 Otherwise it waits for PROGRAM to terminate\n\
794 and returns a numeric exit status or a signal description string.\n\
795 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
796 (nargs, args)
797 int nargs;
798 register Lisp_Object *args;
799 {
800 struct gcpro gcpro1;
801 Lisp_Object filename_string;
802 register Lisp_Object start, end;
803 int count = specpdl_ptr - specpdl;
804 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
805 Lisp_Object coding_systems = Qt;
806 Lisp_Object val, *args2;
807 int i;
808 #ifdef DOS_NT
809 char *tempfile;
810 char *outf = '\0';
811
812 if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
813 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
814 else
815 {
816 tempfile = alloca (20);
817 *tempfile = '\0';
818 }
819 if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
820 strcat (tempfile, "/");
821 if ('/' == DIRECTORY_SEP)
822 dostounix_filename (tempfile);
823 else
824 unixtodos_filename (tempfile);
825 #ifdef WINDOWSNT
826 strcat (tempfile, "emXXXXXX");
827 #else
828 strcat (tempfile, "detmp.XXX");
829 #endif
830 #else /* not DOS_NT */
831 char *tempfile = (char *) alloca (STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
832 bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
833 STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
834 #endif /* not DOS_NT */
835
836 mktemp (tempfile);
837
838 filename_string = build_string (tempfile);
839 GCPRO1 (filename_string);
840 start = args[0];
841 end = args[1];
842 /* Decide coding-system of the contents of the temporary file. */
843 if (!NILP (Vcoding_system_for_write))
844 val = Vcoding_system_for_write;
845 else if (NILP (current_buffer->enable_multibyte_characters))
846 val = Qnil;
847 else
848 {
849 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
850 args2[0] = Qcall_process_region;
851 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
852 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
853 if (CONSP (coding_systems))
854 val = XCONS (coding_systems)->cdr;
855 else if (CONSP (Vdefault_process_coding_system))
856 val = XCONS (Vdefault_process_coding_system)->cdr;
857 else
858 val = Qnil;
859 }
860
861 {
862 int count1 = specpdl_ptr - specpdl;
863
864 specbind (intern ("coding-system-for-write"), val);
865 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
866
867 unbind_to (count1, Qnil);
868 }
869
870 /* Note that Fcall_process takes care of binding
871 coding-system-for-read. */
872
873 record_unwind_protect (delete_temp_file, filename_string);
874
875 if (!NILP (args[3]))
876 Fdelete_region (start, end);
877
878 args[3] = filename_string;
879
880 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs - 2, args + 2)));
881 }
882 \f
883 #ifndef VMS /* VMS version is in vmsproc.c. */
884
885 static int relocate_fd ();
886
887 /* This is the last thing run in a newly forked inferior
888 either synchronous or asynchronous.
889 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
890 Initialize inferior's priority, pgrp, connected dir and environment.
891 then exec another program based on new_argv.
892
893 This function may change environ for the superior process.
894 Therefore, the superior process must save and restore the value
895 of environ around the vfork and the call to this function.
896
897 SET_PGRP is nonzero if we should put the subprocess into a separate
898 process group.
899
900 CURRENT_DIR is an elisp string giving the path of the current
901 directory the subprocess should have. Since we can't really signal
902 a decent error from within the child, this should be verified as an
903 executable directory by the parent. */
904
905 int
906 child_setup (in, out, err, new_argv, set_pgrp, current_dir)
907 int in, out, err;
908 register char **new_argv;
909 int set_pgrp;
910 Lisp_Object current_dir;
911 {
912 char **env;
913 char *pwd_var;
914 #ifdef WINDOWSNT
915 int cpid;
916 HANDLE handles[3];
917 #endif /* WINDOWSNT */
918
919 int pid = getpid ();
920
921 #ifdef SET_EMACS_PRIORITY
922 {
923 extern int emacs_priority;
924
925 if (emacs_priority < 0)
926 nice (- emacs_priority);
927 }
928 #endif
929
930 #ifdef subprocesses
931 /* Close Emacs's descriptors that this process should not have. */
932 close_process_descs ();
933 #endif
934 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
935 we will lose if we call close_load_descs here. */
936 #ifndef DOS_NT
937 close_load_descs ();
938 #endif
939
940 /* Note that use of alloca is always safe here. It's obvious for systems
941 that do not have true vfork or that have true (stack) alloca.
942 If using vfork and C_ALLOCA it is safe because that changes
943 the superior's static variables as if the superior had done alloca
944 and will be cleaned up in the usual way. */
945 {
946 register char *temp;
947 register int i;
948
949 i = STRING_BYTES (XSTRING (current_dir));
950 pwd_var = (char *) alloca (i + 6);
951 temp = pwd_var + 4;
952 bcopy ("PWD=", pwd_var, 4);
953 bcopy (XSTRING (current_dir)->data, temp, i);
954 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
955 temp[i] = 0;
956
957 #ifndef DOS_NT
958 /* We can't signal an Elisp error here; we're in a vfork. Since
959 the callers check the current directory before forking, this
960 should only return an error if the directory's permissions
961 are changed between the check and this chdir, but we should
962 at least check. */
963 if (chdir (temp) < 0)
964 _exit (errno);
965 #endif
966
967 #ifdef DOS_NT
968 /* Get past the drive letter, so that d:/ is left alone. */
969 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
970 {
971 temp += 2;
972 i -= 2;
973 }
974 #endif
975
976 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
977 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
978 temp[--i] = 0;
979 }
980
981 /* Set `env' to a vector of the strings in Vprocess_environment. */
982 {
983 register Lisp_Object tem;
984 register char **new_env;
985 register int new_length;
986
987 new_length = 0;
988 for (tem = Vprocess_environment;
989 CONSP (tem) && STRINGP (XCONS (tem)->car);
990 tem = XCONS (tem)->cdr)
991 new_length++;
992
993 /* new_length + 2 to include PWD and terminating 0. */
994 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
995
996 /* If we have a PWD envvar, pass one down,
997 but with corrected value. */
998 if (getenv ("PWD"))
999 *new_env++ = pwd_var;
1000
1001 /* Copy the Vprocess_environment strings into new_env. */
1002 for (tem = Vprocess_environment;
1003 CONSP (tem) && STRINGP (XCONS (tem)->car);
1004 tem = XCONS (tem)->cdr)
1005 {
1006 char **ep = env;
1007 char *string = (char *) XSTRING (XCONS (tem)->car)->data;
1008 /* See if this string duplicates any string already in the env.
1009 If so, don't put it in.
1010 When an env var has multiple definitions,
1011 we keep the definition that comes first in process-environment. */
1012 for (; ep != new_env; ep++)
1013 {
1014 char *p = *ep, *q = string;
1015 while (1)
1016 {
1017 if (*q == 0)
1018 /* The string is malformed; might as well drop it. */
1019 goto duplicate;
1020 if (*q != *p)
1021 break;
1022 if (*q == '=')
1023 goto duplicate;
1024 p++, q++;
1025 }
1026 }
1027 *new_env++ = string;
1028 duplicate: ;
1029 }
1030 *new_env = 0;
1031 }
1032 #ifdef WINDOWSNT
1033 prepare_standard_handles (in, out, err, handles);
1034 set_process_dir (XSTRING (current_dir)->data);
1035 #else /* not WINDOWSNT */
1036 /* Make sure that in, out, and err are not actually already in
1037 descriptors zero, one, or two; this could happen if Emacs is
1038 started with its standard in, out, or error closed, as might
1039 happen under X. */
1040 {
1041 int oin = in, oout = out;
1042
1043 /* We have to avoid relocating the same descriptor twice! */
1044
1045 in = relocate_fd (in, 3);
1046
1047 if (out == oin)
1048 out = in;
1049 else
1050 out = relocate_fd (out, 3);
1051
1052 if (err == oin)
1053 err = in;
1054 else if (err == oout)
1055 err = out;
1056 else
1057 err = relocate_fd (err, 3);
1058 }
1059
1060 #ifndef MSDOS
1061 close (0);
1062 close (1);
1063 close (2);
1064
1065 dup2 (in, 0);
1066 dup2 (out, 1);
1067 dup2 (err, 2);
1068 close (in);
1069 close (out);
1070 close (err);
1071 #endif /* not MSDOS */
1072 #endif /* not WINDOWSNT */
1073
1074 #if defined(USG) && !defined(BSD_PGRPS)
1075 #ifndef SETPGRP_RELEASES_CTTY
1076 setpgrp (); /* No arguments but equivalent in this case */
1077 #endif
1078 #else
1079 setpgrp (pid, pid);
1080 #endif /* USG */
1081 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
1082 EMACS_SET_TTY_PGRP (0, &pid);
1083
1084 #ifdef vipc
1085 something missing here;
1086 #endif /* vipc */
1087
1088 #ifdef MSDOS
1089 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1090 if (pid == -1)
1091 /* An error occurred while trying to run the subprocess. */
1092 report_file_error ("Spawning child process", Qnil);
1093 return pid;
1094 #else /* not MSDOS */
1095 #ifdef WINDOWSNT
1096 /* Spawn the child. (See ntproc.c:Spawnve). */
1097 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1098 reset_standard_handles (in, out, err, handles);
1099 if (cpid == -1)
1100 /* An error occurred while trying to spawn the process. */
1101 report_file_error ("Spawning child process", Qnil);
1102 return cpid;
1103 #else /* not WINDOWSNT */
1104 /* execvp does not accept an environment arg so the only way
1105 to pass this environment is to set environ. Our caller
1106 is responsible for restoring the ambient value of environ. */
1107 environ = env;
1108 execvp (new_argv[0], new_argv);
1109
1110 write (1, "Can't exec program: ", 20);
1111 write (1, new_argv[0], strlen (new_argv[0]));
1112 write (1, "\n", 1);
1113 _exit (1);
1114 #endif /* not WINDOWSNT */
1115 #endif /* not MSDOS */
1116 }
1117
1118 /* Move the file descriptor FD so that its number is not less than MINFD.
1119 If the file descriptor is moved at all, the original is freed. */
1120 static int
1121 relocate_fd (fd, minfd)
1122 int fd, minfd;
1123 {
1124 if (fd >= minfd)
1125 return fd;
1126 else
1127 {
1128 int new = dup (fd);
1129 if (new == -1)
1130 {
1131 char *message1 = "Error while setting up child: ";
1132 char *errmessage = strerror (errno);
1133 char *message2 = "\n";
1134 write (2, message1, strlen (message1));
1135 write (2, errmessage, strlen (errmessage));
1136 write (2, message2, strlen (message2));
1137 _exit (1);
1138 }
1139 /* Note that we hold the original FD open while we recurse,
1140 to guarantee we'll get a new FD if we need it. */
1141 new = relocate_fd (new, minfd);
1142 close (fd);
1143 return new;
1144 }
1145 }
1146
1147 static int
1148 getenv_internal (var, varlen, value, valuelen)
1149 char *var;
1150 int varlen;
1151 char **value;
1152 int *valuelen;
1153 {
1154 Lisp_Object scan;
1155
1156 for (scan = Vprocess_environment; CONSP (scan); scan = XCONS (scan)->cdr)
1157 {
1158 Lisp_Object entry;
1159
1160 entry = XCONS (scan)->car;
1161 if (STRINGP (entry)
1162 && STRING_BYTES (XSTRING (entry)) > varlen
1163 && XSTRING (entry)->data[varlen] == '='
1164 #ifdef WINDOWSNT
1165 /* NT environment variables are case insensitive. */
1166 && ! strnicmp (XSTRING (entry)->data, var, varlen)
1167 #else /* not WINDOWSNT */
1168 && ! bcmp (XSTRING (entry)->data, var, varlen)
1169 #endif /* not WINDOWSNT */
1170 )
1171 {
1172 *value = (char *) XSTRING (entry)->data + (varlen + 1);
1173 *valuelen = STRING_BYTES (XSTRING (entry)) - (varlen + 1);
1174 return 1;
1175 }
1176 }
1177
1178 return 0;
1179 }
1180
1181 DEFUN ("getenv", Fgetenv, Sgetenv, 1, 1, 0,
1182 "Return the value of environment variable VAR, as a string.\n\
1183 VAR should be a string. Value is nil if VAR is undefined in the environment.\n\
1184 This function consults the variable ``process-environment'' for its value.")
1185 (var)
1186 Lisp_Object var;
1187 {
1188 char *value;
1189 int valuelen;
1190
1191 CHECK_STRING (var, 0);
1192 if (getenv_internal (XSTRING (var)->data, STRING_BYTES (XSTRING (var)),
1193 &value, &valuelen))
1194 return make_string (value, valuelen);
1195 else
1196 return Qnil;
1197 }
1198
1199 /* A version of getenv that consults process_environment, easily
1200 callable from C. */
1201 char *
1202 egetenv (var)
1203 char *var;
1204 {
1205 char *value;
1206 int valuelen;
1207
1208 if (getenv_internal (var, strlen (var), &value, &valuelen))
1209 return value;
1210 else
1211 return 0;
1212 }
1213
1214 #endif /* not VMS */
1215 \f
1216 /* This is run before init_cmdargs. */
1217
1218 void
1219 init_callproc_1 ()
1220 {
1221 char *data_dir = egetenv ("EMACSDATA");
1222 char *doc_dir = egetenv ("EMACSDOC");
1223
1224 Vdata_directory
1225 = Ffile_name_as_directory (build_string (data_dir ? data_dir
1226 : PATH_DATA));
1227 Vdoc_directory
1228 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1229 : PATH_DOC));
1230
1231 /* Check the EMACSPATH environment variable, defaulting to the
1232 PATH_EXEC path from paths.h. */
1233 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1234 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1235 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1236 }
1237
1238 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1239
1240 void
1241 init_callproc ()
1242 {
1243 char *data_dir = egetenv ("EMACSDATA");
1244
1245 register char * sh;
1246 Lisp_Object tempdir;
1247
1248 if (!NILP (Vinstallation_directory))
1249 {
1250 /* Add to the path the lib-src subdir of the installation dir. */
1251 Lisp_Object tem;
1252 tem = Fexpand_file_name (build_string ("lib-src"),
1253 Vinstallation_directory);
1254 if (NILP (Fmember (tem, Vexec_path)))
1255 {
1256 #ifndef DOS_NT
1257 /* MSDOS uses wrapped binaries, so don't do this. */
1258 Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
1259 Vexec_directory = Ffile_name_as_directory (tem);
1260 #endif /* not DOS_NT */
1261 }
1262
1263 /* Maybe use ../etc as well as ../lib-src. */
1264 if (data_dir == 0)
1265 {
1266 tem = Fexpand_file_name (build_string ("etc"),
1267 Vinstallation_directory);
1268 Vdoc_directory = Ffile_name_as_directory (tem);
1269 }
1270 }
1271
1272 /* Look for the files that should be in etc. We don't use
1273 Vinstallation_directory, because these files are never installed
1274 near the executable, and they are never in the build
1275 directory when that's different from the source directory.
1276
1277 Instead, if these files are not in the nominal place, we try the
1278 source directory. */
1279 if (data_dir == 0)
1280 {
1281 Lisp_Object tem, tem1, newdir;
1282
1283 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1284 tem1 = Ffile_exists_p (tem);
1285 if (NILP (tem1))
1286 {
1287 newdir = Fexpand_file_name (build_string ("../etc/"),
1288 build_string (PATH_DUMPLOADSEARCH));
1289 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1290 tem1 = Ffile_exists_p (tem);
1291 if (!NILP (tem1))
1292 Vdata_directory = newdir;
1293 }
1294 }
1295
1296 #ifndef CANNOT_DUMP
1297 if (initialized)
1298 #endif
1299 {
1300 tempdir = Fdirectory_file_name (Vexec_directory);
1301 if (access (XSTRING (tempdir)->data, 0) < 0)
1302 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1303 Vexec_directory);
1304 }
1305
1306 tempdir = Fdirectory_file_name (Vdata_directory);
1307 if (access (XSTRING (tempdir)->data, 0) < 0)
1308 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1309 Vdata_directory);
1310
1311 #ifdef VMS
1312 Vshell_file_name = build_string ("*dcl*");
1313 #else
1314 sh = (char *) getenv ("SHELL");
1315 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1316 #endif
1317
1318 #ifdef VMS
1319 Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
1320 #else
1321 if (getenv ("TMPDIR"))
1322 {
1323 char *dir = getenv ("TMPDIR");
1324 Vtemp_file_name_pattern
1325 = Fexpand_file_name (build_string ("emacsXXXXXX"),
1326 build_string (dir));
1327 }
1328 else
1329 Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
1330 #endif
1331 }
1332
1333 void
1334 set_process_environment ()
1335 {
1336 register char **envp;
1337
1338 Vprocess_environment = Qnil;
1339 #ifndef CANNOT_DUMP
1340 if (initialized)
1341 #endif
1342 for (envp = environ; *envp; envp++)
1343 Vprocess_environment = Fcons (build_string (*envp),
1344 Vprocess_environment);
1345 }
1346
1347 void
1348 syms_of_callproc ()
1349 {
1350 #ifdef DOS_NT
1351 Qbuffer_file_type = intern ("buffer-file-type");
1352 staticpro (&Qbuffer_file_type);
1353 #endif /* DOS_NT */
1354
1355 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1356 "*File name to load inferior shells from.\n\
1357 Initialized from the SHELL environment variable.");
1358
1359 DEFVAR_LISP ("exec-path", &Vexec_path,
1360 "*List of directories to search programs to run in subprocesses.\n\
1361 Each element is a string (directory name) or nil (try default directory).");
1362
1363 DEFVAR_LISP ("exec-directory", &Vexec_directory,
1364 "Directory for executables for Emacs to invoke.\n\
1365 More generally, this includes any architecture-dependent files\n\
1366 that are built and installed from the Emacs distribution.");
1367
1368 DEFVAR_LISP ("data-directory", &Vdata_directory,
1369 "Directory of machine-independent files that come with GNU Emacs.\n\
1370 These are files intended for Emacs to use while it runs.");
1371
1372 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1373 "Directory containing the DOC file that comes with GNU Emacs.\n\
1374 This is usually the same as data-directory.");
1375
1376 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1377 "For internal use by the build procedure only.\n\
1378 This is the name of the directory in which the build procedure installed\n\
1379 Emacs's info files; the default value for Info-default-directory-list\n\
1380 includes this.");
1381 Vconfigure_info_directory = build_string (PATH_INFO);
1382
1383 DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
1384 "Pattern for making names for temporary files.\n\
1385 This is used by `call-process-region'.");
1386 /* This variable is initialized in init_callproc. */
1387
1388 DEFVAR_LISP ("process-environment", &Vprocess_environment,
1389 "List of environment variables for subprocesses to inherit.\n\
1390 Each element should be a string of the form ENVVARNAME=VALUE.\n\
1391 The environment which Emacs inherits is placed in this variable\n\
1392 when Emacs starts.");
1393
1394 #ifndef VMS
1395 defsubr (&Scall_process);
1396 defsubr (&Sgetenv);
1397 #endif
1398 defsubr (&Scall_process_region);
1399 }