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