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