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