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