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