Merged from miles@gnu.org--gnu-2005 (patch 683-684)
[emacs.git] / src / callproc.c
blobeebbabb2739248147b44a9a1753191db92fde3e4
1 /* Synchronous subprocess invocation for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1999, 2000, 2001,
3 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
23 #include <config.h>
24 #include <signal.h>
25 #include <errno.h>
26 #include <stdio.h>
28 #ifndef USE_CRT_DLL
29 extern int errno;
30 #endif
32 /* Define SIGCHLD as an alias for SIGCLD. */
34 #if !defined (SIGCHLD) && defined (SIGCLD)
35 #define SIGCHLD SIGCLD
36 #endif /* SIGCLD */
38 #include <sys/types.h>
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
44 #include <sys/file.h>
45 #ifdef HAVE_FCNTL_H
46 #define INCLUDED_FCNTL
47 #include <fcntl.h>
48 #endif
50 #ifdef WINDOWSNT
51 #define NOMINMAX
52 #include <windows.h>
53 #include <stdlib.h> /* for proper declaration of environ */
54 #include <fcntl.h>
55 #include "w32.h"
56 #define _P_NOWAIT 1 /* from process.h */
57 #endif
59 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
60 #define INCLUDED_FCNTL
61 #include <fcntl.h>
62 #include <sys/stat.h>
63 #include <sys/param.h>
64 #include <errno.h>
65 #endif /* MSDOS */
67 #ifndef O_RDONLY
68 #define O_RDONLY 0
69 #endif
71 #ifndef O_WRONLY
72 #define O_WRONLY 1
73 #endif
75 #include "lisp.h"
76 #include "commands.h"
77 #include "buffer.h"
78 #include "charset.h"
79 #include "ccl.h"
80 #include "coding.h"
81 #include "composite.h"
82 #include <epaths.h>
83 #include "process.h"
84 #include "syssignal.h"
85 #include "systty.h"
86 #include "blockinput.h"
87 #include "frame.h"
88 #include "termhooks.h"
90 #ifdef MSDOS
91 #include "msdos.h"
92 #endif
94 #ifdef VMS
95 extern noshare char **environ;
96 #else
97 #ifndef USE_CRT_DLL
98 extern char **environ;
99 #endif
100 #endif
102 #ifdef HAVE_SETPGID
103 #if !defined (USG) || defined (BSD_PGRPS)
104 #undef setpgrp
105 #define setpgrp setpgid
106 #endif
107 #endif
109 Lisp_Object Vexec_path, Vexec_directory, Vexec_suffixes;
110 Lisp_Object Vdata_directory, Vdoc_directory;
111 Lisp_Object Vconfigure_info_directory, Vshared_game_score_directory;
112 Lisp_Object Vtemp_file_name_pattern;
114 Lisp_Object Vshell_file_name;
116 Lisp_Object Vglobal_environment;
117 Lisp_Object Vprocess_environment;
119 #ifdef DOS_NT
120 Lisp_Object Qbuffer_file_type;
121 #endif /* DOS_NT */
123 /* True iff we are about to fork off a synchronous process or if we
124 are waiting for it. */
125 int synch_process_alive;
127 /* Nonzero => this is a string explaining death of synchronous subprocess. */
128 char *synch_process_death;
130 /* Nonzero => this is the signal number that terminated the subprocess. */
131 int synch_process_termsig;
133 /* If synch_process_death is zero,
134 this is exit code of synchronous subprocess. */
135 int synch_process_retcode;
137 /* List of environment variables to look up in emacsclient. */
138 Lisp_Object Vlocal_environment_variables;
141 /* Clean up when exiting Fcall_process.
142 On MSDOS, delete the temporary file on any kind of termination.
143 On Unix, kill the process and any children on termination by signal. */
145 /* Nonzero if this is termination due to exit. */
146 static int call_process_exited;
148 #ifndef VMS /* VMS version is in vmsproc.c. */
150 static Lisp_Object
151 call_process_kill (fdpid)
152 Lisp_Object fdpid;
154 emacs_close (XFASTINT (Fcar (fdpid)));
155 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
156 synch_process_alive = 0;
157 return Qnil;
160 Lisp_Object
161 call_process_cleanup (fdpid)
162 Lisp_Object fdpid;
164 #if defined (MSDOS) || defined (MAC_OS8)
165 /* for MSDOS fdpid is really (fd . tempfile) */
166 register Lisp_Object file;
167 file = Fcdr (fdpid);
168 emacs_close (XFASTINT (Fcar (fdpid)));
169 if (strcmp (SDATA (file), NULL_DEVICE) != 0)
170 unlink (SDATA (file));
171 #else /* not MSDOS and not MAC_OS8 */
172 register int pid = XFASTINT (Fcdr (fdpid));
174 if (call_process_exited)
176 emacs_close (XFASTINT (Fcar (fdpid)));
177 return Qnil;
180 if (EMACS_KILLPG (pid, SIGINT) == 0)
182 int count = SPECPDL_INDEX ();
183 record_unwind_protect (call_process_kill, fdpid);
184 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
185 immediate_quit = 1;
186 QUIT;
187 wait_for_termination (pid);
188 immediate_quit = 0;
189 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
190 message1 ("Waiting for process to die...done");
192 synch_process_alive = 0;
193 emacs_close (XFASTINT (Fcar (fdpid)));
194 #endif /* not MSDOS */
195 return Qnil;
198 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
199 doc: /* Call PROGRAM synchronously in separate process.
200 The remaining arguments are optional.
201 The program's input comes from file INFILE (nil means `/dev/null').
202 Insert output in BUFFER before point; t means current buffer;
203 nil for BUFFER means discard it; 0 means discard and don't wait.
204 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
205 REAL-BUFFER says what to do with standard output, as above,
206 while STDERR-FILE says what to do with standard error in the child.
207 STDERR-FILE may be nil (discard standard error output),
208 t (mix it with ordinary output), or a file name string.
210 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
211 Remaining arguments are strings passed as command arguments to PROGRAM.
213 If BUFFER is 0, `call-process' returns immediately with value nil.
214 Otherwise it waits for PROGRAM to terminate
215 and returns a numeric exit status or a signal description string.
216 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
218 usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
219 (nargs, args)
220 int nargs;
221 register Lisp_Object *args;
223 Lisp_Object infile, buffer, current_dir, path;
224 int display_p;
225 int fd[2];
226 int filefd;
227 register int pid;
228 #define CALLPROC_BUFFER_SIZE_MIN (16 * 1024)
229 #define CALLPROC_BUFFER_SIZE_MAX (4 * CALLPROC_BUFFER_SIZE_MIN)
230 char buf[CALLPROC_BUFFER_SIZE_MAX];
231 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
232 int count = SPECPDL_INDEX ();
234 register const unsigned char **new_argv
235 = (const unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
236 struct buffer *old = current_buffer;
237 /* File to use for stderr in the child.
238 t means use same as standard output. */
239 Lisp_Object error_file;
240 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
241 char *outf, *tempfile;
242 int outfilefd;
243 #endif
244 #ifdef MAC_OS8
245 char *tempfile;
246 int outfilefd;
247 #endif
248 #if 0
249 int mask;
250 #endif
251 struct coding_system process_coding; /* coding-system of process output */
252 struct coding_system argument_coding; /* coding-system of arguments */
253 /* Set to the return value of Ffind_operation_coding_system. */
254 Lisp_Object coding_systems;
256 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
257 coding_systems = Qt;
259 CHECK_STRING (args[0]);
261 error_file = Qt;
263 #ifndef subprocesses
264 /* Without asynchronous processes we cannot have BUFFER == 0. */
265 if (nargs >= 3
266 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
267 error ("Operating system cannot handle asynchronous subprocesses");
268 #endif /* subprocesses */
270 /* Decide the coding-system for giving arguments. */
272 Lisp_Object val, *args2;
273 int i;
275 /* If arguments are supplied, we may have to encode them. */
276 if (nargs >= 5)
278 int must_encode = 0;
280 for (i = 4; i < nargs; i++)
281 CHECK_STRING (args[i]);
283 for (i = 4; i < nargs; i++)
284 if (STRING_MULTIBYTE (args[i]))
285 must_encode = 1;
287 if (!NILP (Vcoding_system_for_write))
288 val = Vcoding_system_for_write;
289 else if (! must_encode)
290 val = Qnil;
291 else
293 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
294 args2[0] = Qcall_process;
295 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
296 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
297 if (CONSP (coding_systems))
298 val = XCDR (coding_systems);
299 else if (CONSP (Vdefault_process_coding_system))
300 val = XCDR (Vdefault_process_coding_system);
301 else
302 val = Qnil;
304 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
308 if (nargs >= 2 && ! NILP (args[1]))
310 infile = Fexpand_file_name (args[1], current_buffer->directory);
311 CHECK_STRING (infile);
313 else
314 infile = build_string (NULL_DEVICE);
316 if (nargs >= 3)
318 buffer = args[2];
320 /* If BUFFER is a list, its meaning is
321 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
322 if (CONSP (buffer))
324 if (CONSP (XCDR (buffer)))
326 Lisp_Object stderr_file;
327 stderr_file = XCAR (XCDR (buffer));
329 if (NILP (stderr_file) || EQ (Qt, stderr_file))
330 error_file = stderr_file;
331 else
332 error_file = Fexpand_file_name (stderr_file, Qnil);
335 buffer = XCAR (buffer);
338 if (!(EQ (buffer, Qnil)
339 || EQ (buffer, Qt)
340 || INTEGERP (buffer)))
342 Lisp_Object spec_buffer;
343 spec_buffer = buffer;
344 buffer = Fget_buffer_create (buffer);
345 /* Mention the buffer name for a better error message. */
346 if (NILP (buffer))
347 CHECK_BUFFER (spec_buffer);
348 CHECK_BUFFER (buffer);
351 else
352 buffer = Qnil;
354 /* Make sure that the child will be able to chdir to the current
355 buffer's current directory, or its unhandled equivalent. We
356 can't just have the child check for an error when it does the
357 chdir, since it's in a vfork.
359 We have to GCPRO around this because Fexpand_file_name,
360 Funhandled_file_name_directory, and Ffile_accessible_directory_p
361 might call a file name handling function. The argument list is
362 protected by the caller, so all we really have to worry about is
363 buffer. */
365 struct gcpro gcpro1, gcpro2, gcpro3;
367 current_dir = current_buffer->directory;
369 GCPRO3 (infile, buffer, current_dir);
371 current_dir
372 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
373 Qnil);
374 if (NILP (Ffile_accessible_directory_p (current_dir)))
375 report_file_error ("Setting current directory",
376 Fcons (current_buffer->directory, Qnil));
378 UNGCPRO;
381 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
383 filefd = emacs_open (SDATA (infile), O_RDONLY, 0);
384 if (filefd < 0)
386 report_file_error ("Opening process input file", Fcons (infile, Qnil));
388 /* Search for program; barf if not found. */
390 struct gcpro gcpro1;
392 GCPRO1 (current_dir);
393 openp (Vexec_path, args[0], Vexec_suffixes, &path, make_number (X_OK));
394 UNGCPRO;
396 if (NILP (path))
398 emacs_close (filefd);
399 report_file_error ("Searching for program", Fcons (args[0], Qnil));
402 /* If program file name starts with /: for quoting a magic name,
403 discard that. */
404 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
405 && SREF (path, 1) == ':')
406 path = Fsubstring (path, make_number (2), Qnil);
408 new_argv[0] = SDATA (path);
409 if (nargs > 4)
411 register int i;
412 struct gcpro gcpro1, gcpro2, gcpro3;
414 GCPRO3 (infile, buffer, current_dir);
415 argument_coding.dst_multibyte = 0;
416 for (i = 4; i < nargs; i++)
418 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
419 if (CODING_REQUIRE_ENCODING (&argument_coding))
421 /* We must encode this argument. */
422 args[i] = encode_coding_string (args[i], &argument_coding, 1);
423 if (argument_coding.type == coding_type_ccl)
424 setup_ccl_program (&(argument_coding.spec.ccl.encoder), Qnil);
426 new_argv[i - 3] = SDATA (args[i]);
428 UNGCPRO;
429 new_argv[nargs - 3] = 0;
431 else
432 new_argv[1] = 0;
434 #ifdef MSDOS /* MW, July 1993 */
435 if ((outf = egetenv ("TMPDIR")))
436 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
437 else
439 tempfile = alloca (20);
440 *tempfile = '\0';
442 dostounix_filename (tempfile);
443 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
444 strcat (tempfile, "/");
445 strcat (tempfile, "detmp.XXX");
446 mktemp (tempfile);
448 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
449 if (outfilefd < 0)
451 emacs_close (filefd);
452 report_file_error ("Opening process output file",
453 Fcons (build_string (tempfile), Qnil));
455 fd[0] = filefd;
456 fd[1] = outfilefd;
457 #endif /* MSDOS */
459 #ifdef MAC_OS8
460 /* Since we don't have pipes on the Mac, create a temporary file to
461 hold the output of the subprocess. */
462 tempfile = (char *) alloca (SBYTES (Vtemp_file_name_pattern) + 1);
463 bcopy (SDATA (Vtemp_file_name_pattern), tempfile,
464 SBYTES (Vtemp_file_name_pattern) + 1);
466 mktemp (tempfile);
468 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
469 if (outfilefd < 0)
471 close (filefd);
472 report_file_error ("Opening process output file",
473 Fcons (build_string (tempfile), Qnil));
475 fd[0] = filefd;
476 fd[1] = outfilefd;
477 #endif /* MAC_OS8 */
479 if (INTEGERP (buffer))
480 fd[1] = emacs_open (NULL_DEVICE, O_WRONLY, 0), fd[0] = -1;
481 else
483 #ifndef MSDOS
484 #ifndef MAC_OS8
485 errno = 0;
486 if (pipe (fd) == -1)
488 emacs_close (filefd);
489 report_file_error ("Creating process pipe", Qnil);
491 #endif
492 #endif
493 #if 0
494 /* Replaced by close_process_descs */
495 set_exclusive_use (fd[0]);
496 #endif
500 /* child_setup must clobber environ in systems with true vfork.
501 Protect it from permanent change. */
502 register char **save_environ = environ;
503 register int fd1 = fd[1];
504 int fd_error = fd1;
506 #if 0 /* Some systems don't have sigblock. */
507 mask = sigblock (sigmask (SIGCHLD));
508 #endif
510 /* Record that we're about to create a synchronous process. */
511 synch_process_alive = 1;
513 /* These vars record information from process termination.
514 Clear them now before process can possibly terminate,
515 to avoid timing error if process terminates soon. */
516 synch_process_death = 0;
517 synch_process_retcode = 0;
518 synch_process_termsig = 0;
520 if (NILP (error_file))
521 fd_error = emacs_open (NULL_DEVICE, O_WRONLY, 0);
522 else if (STRINGP (error_file))
524 #ifdef DOS_NT
525 fd_error = emacs_open (SDATA (error_file),
526 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
527 S_IREAD | S_IWRITE);
528 #else /* not DOS_NT */
529 fd_error = creat (SDATA (error_file), 0666);
530 #endif /* not DOS_NT */
533 if (fd_error < 0)
535 emacs_close (filefd);
536 if (fd[0] != filefd)
537 emacs_close (fd[0]);
538 if (fd1 >= 0)
539 emacs_close (fd1);
540 #ifdef MSDOS
541 unlink (tempfile);
542 #endif
543 report_file_error ("Cannot redirect stderr",
544 Fcons ((NILP (error_file)
545 ? build_string (NULL_DEVICE) : error_file),
546 Qnil));
549 current_dir = ENCODE_FILE (current_dir);
551 #ifdef MAC_OS8
553 /* Call run_mac_command in sysdep.c here directly instead of doing
554 a child_setup as for MSDOS and other platforms. Note that this
555 code does not handle passing the environment to the synchronous
556 Mac subprocess. */
557 char *infn, *outfn, *errfn, *currdn;
559 /* close these files so subprocess can write to them */
560 close (outfilefd);
561 if (fd_error != outfilefd)
562 close (fd_error);
563 fd1 = -1; /* No harm in closing that one! */
565 infn = SDATA (infile);
566 outfn = tempfile;
567 if (NILP (error_file))
568 errfn = NULL_DEVICE;
569 else if (EQ (Qt, error_file))
570 errfn = outfn;
571 else
572 errfn = SDATA (error_file);
573 currdn = SDATA (current_dir);
574 pid = run_mac_command (new_argv, currdn, infn, outfn, errfn);
576 /* Record that the synchronous process exited and note its
577 termination status. */
578 synch_process_alive = 0;
579 synch_process_retcode = pid;
580 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
582 synchronize_system_messages_locale ();
583 synch_process_death = strerror (errno);
586 /* Since CRLF is converted to LF within `decode_coding', we can
587 always open a file with binary mode. */
588 fd[0] = open (tempfile, O_BINARY);
589 if (fd[0] < 0)
591 unlink (tempfile);
592 close (filefd);
593 report_file_error ("Cannot re-open temporary file", Qnil);
596 #else /* not MAC_OS8 */
597 #ifdef MSDOS /* MW, July 1993 */
598 /* Note that on MSDOS `child_setup' actually returns the child process
599 exit status, not its PID, so we assign it to `synch_process_retcode'
600 below. */
601 pid = child_setup (filefd, outfilefd, fd_error, (char **) new_argv,
602 0, current_dir);
604 /* Record that the synchronous process exited and note its
605 termination status. */
606 synch_process_alive = 0;
607 synch_process_retcode = pid;
608 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
610 synchronize_system_messages_locale ();
611 synch_process_death = strerror (errno);
614 emacs_close (outfilefd);
615 if (fd_error != outfilefd)
616 emacs_close (fd_error);
617 fd1 = -1; /* No harm in closing that one! */
618 /* Since CRLF is converted to LF within `decode_coding', we can
619 always open a file with binary mode. */
620 fd[0] = emacs_open (tempfile, O_RDONLY | O_BINARY, 0);
621 if (fd[0] < 0)
623 unlink (tempfile);
624 emacs_close (filefd);
625 report_file_error ("Cannot re-open temporary file", Qnil);
627 #else /* not MSDOS */
628 #ifdef WINDOWSNT
629 pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
630 0, current_dir);
631 #else /* not WINDOWSNT */
632 BLOCK_INPUT;
634 pid = vfork ();
636 if (pid == 0)
638 if (fd[0] >= 0)
639 emacs_close (fd[0]);
640 #ifdef HAVE_SETSID
641 setsid ();
642 #endif
643 #if defined (USG) && !defined (BSD_PGRPS)
644 setpgrp ();
645 #else
646 setpgrp (pid, pid);
647 #endif /* USG */
648 child_setup (filefd, fd1, fd_error, (char **) new_argv,
649 0, current_dir);
652 UNBLOCK_INPUT;
653 #endif /* not WINDOWSNT */
655 /* The MSDOS case did this already. */
656 if (fd_error >= 0)
657 emacs_close (fd_error);
658 #endif /* not MSDOS */
659 #endif /* not MAC_OS8 */
661 environ = save_environ;
663 /* Close most of our fd's, but not fd[0]
664 since we will use that to read input from. */
665 emacs_close (filefd);
666 if (fd1 >= 0 && fd1 != fd_error)
667 emacs_close (fd1);
670 if (pid < 0)
672 if (fd[0] >= 0)
673 emacs_close (fd[0]);
674 report_file_error ("Doing vfork", Qnil);
677 if (INTEGERP (buffer))
679 if (fd[0] >= 0)
680 emacs_close (fd[0]);
681 #ifndef subprocesses
682 /* If Emacs has been built with asynchronous subprocess support,
683 we don't need to do this, I think because it will then have
684 the facilities for handling SIGCHLD. */
685 wait_without_blocking ();
686 #endif /* subprocesses */
687 return Qnil;
690 /* Enable sending signal if user quits below. */
691 call_process_exited = 0;
693 #if defined(MSDOS) || defined(MAC_OS8)
694 /* MSDOS needs different cleanup information. */
695 record_unwind_protect (call_process_cleanup,
696 Fcons (make_number (fd[0]), build_string (tempfile)));
697 #else
698 record_unwind_protect (call_process_cleanup,
699 Fcons (make_number (fd[0]), make_number (pid)));
700 #endif /* not MSDOS and not MAC_OS8 */
703 if (BUFFERP (buffer))
704 Fset_buffer (buffer);
706 if (NILP (buffer))
708 /* If BUFFER is nil, we must read process output once and then
709 discard it, so setup coding system but with nil. */
710 setup_coding_system (Qnil, &process_coding);
712 else
714 Lisp_Object val, *args2;
716 val = Qnil;
717 if (!NILP (Vcoding_system_for_read))
718 val = Vcoding_system_for_read;
719 else
721 if (EQ (coding_systems, Qt))
723 int i;
725 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
726 args2[0] = Qcall_process;
727 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
728 coding_systems
729 = Ffind_operation_coding_system (nargs + 1, args2);
731 if (CONSP (coding_systems))
732 val = XCAR (coding_systems);
733 else if (CONSP (Vdefault_process_coding_system))
734 val = XCAR (Vdefault_process_coding_system);
735 else
736 val = Qnil;
738 setup_coding_system (Fcheck_coding_system (val), &process_coding);
739 /* In unibyte mode, character code conversion should not take
740 place but EOL conversion should. So, setup raw-text or one
741 of the subsidiary according to the information just setup. */
742 if (NILP (current_buffer->enable_multibyte_characters)
743 && !NILP (val))
744 setup_raw_text_coding_system (&process_coding);
746 process_coding.src_multibyte = 0;
747 process_coding.dst_multibyte
748 = (BUFFERP (buffer)
749 ? ! NILP (XBUFFER (buffer)->enable_multibyte_characters)
750 : ! NILP (current_buffer->enable_multibyte_characters));
752 immediate_quit = 1;
753 QUIT;
756 register int nread;
757 int first = 1;
758 int total_read = 0;
759 int carryover = 0;
760 int display_on_the_fly = display_p;
761 struct coding_system saved_coding;
762 int pt_orig = PT, pt_byte_orig = PT_BYTE;
763 int inserted;
765 saved_coding = process_coding;
766 if (process_coding.composing != COMPOSITION_DISABLED)
767 coding_allocate_composition_data (&process_coding, PT);
768 while (1)
770 /* Repeatedly read until we've filled as much as possible
771 of the buffer size we have. But don't read
772 less than 1024--save that for the next bufferful. */
773 nread = carryover;
774 while (nread < bufsize - 1024)
776 int this_read = emacs_read (fd[0], buf + nread,
777 bufsize - nread);
779 if (this_read < 0)
780 goto give_up;
782 if (this_read == 0)
784 process_coding.mode |= CODING_MODE_LAST_BLOCK;
785 break;
788 nread += this_read;
789 total_read += this_read;
791 if (display_on_the_fly)
792 break;
795 /* Now NREAD is the total amount of data in the buffer. */
796 immediate_quit = 0;
798 if (!NILP (buffer))
800 if (! CODING_MAY_REQUIRE_DECODING (&process_coding))
801 insert_1_both (buf, nread, nread, 0, 1, 0);
802 else
803 { /* We have to decode the input. */
804 int size;
805 char *decoding_buf;
807 repeat_decoding:
808 size = decoding_buffer_size (&process_coding, nread);
809 decoding_buf = (char *) xmalloc (size);
811 /* We can't use the macro CODING_REQUIRE_DETECTION
812 because it always returns nonzero if the coding
813 system requires EOL detection. Here, we have to
814 check only whether or not the coding system
815 requires text-encoding detection. */
816 if (process_coding.type == coding_type_undecided)
818 detect_coding (&process_coding, buf, nread);
819 if (process_coding.composing != COMPOSITION_DISABLED)
820 /* We have not yet allocated the composition
821 data because the coding type was undecided. */
822 coding_allocate_composition_data (&process_coding, PT);
824 if (process_coding.cmp_data)
825 process_coding.cmp_data->char_offset = PT;
827 decode_coding (&process_coding, buf, decoding_buf,
828 nread, size);
830 if (display_on_the_fly
831 && saved_coding.type == coding_type_undecided
832 && process_coding.type != coding_type_undecided)
834 /* We have detected some coding system. But,
835 there's a possibility that the detection was
836 done by insufficient data. So, we try the code
837 detection again with more data. */
838 xfree (decoding_buf);
839 display_on_the_fly = 0;
840 process_coding = saved_coding;
841 carryover = nread;
842 /* This is to make the above condition always
843 fails in the future. */
844 saved_coding.type = coding_type_no_conversion;
845 continue;
848 if (process_coding.produced > 0)
849 insert_1_both (decoding_buf, process_coding.produced_char,
850 process_coding.produced, 0, 1, 0);
851 xfree (decoding_buf);
853 if (process_coding.result == CODING_FINISH_INCONSISTENT_EOL)
855 Lisp_Object eol_type, coding;
857 if (process_coding.eol_type == CODING_EOL_CR)
859 /* CRs have been replaced with LFs. Undo
860 that in the text inserted above. */
861 unsigned char *p;
863 move_gap_both (PT, PT_BYTE);
865 p = BYTE_POS_ADDR (pt_byte_orig);
866 for (; p < GPT_ADDR; ++p)
867 if (*p == '\n')
868 *p = '\r';
870 else if (process_coding.eol_type == CODING_EOL_CRLF)
872 /* CR LFs have been replaced with LFs. Undo
873 that by inserting CRs in front of LFs in
874 the text inserted above. */
875 EMACS_INT bytepos, old_pt, old_pt_byte, nCR;
877 old_pt = PT;
878 old_pt_byte = PT_BYTE;
879 nCR = 0;
881 for (bytepos = PT_BYTE - 1;
882 bytepos >= pt_byte_orig;
883 --bytepos)
884 if (FETCH_BYTE (bytepos) == '\n')
886 EMACS_INT charpos = BYTE_TO_CHAR (bytepos);
887 TEMP_SET_PT_BOTH (charpos, bytepos);
888 insert_1_both ("\r", 1, 1, 0, 1, 0);
889 ++nCR;
892 TEMP_SET_PT_BOTH (old_pt + nCR, old_pt_byte + nCR);
895 /* Set the coding system symbol to that for
896 Unix-like EOL. */
897 eol_type = Fget (saved_coding.symbol, Qeol_type);
898 if (VECTORP (eol_type)
899 && ASIZE (eol_type) == 3
900 && SYMBOLP (AREF (eol_type, CODING_EOL_LF)))
901 coding = AREF (eol_type, CODING_EOL_LF);
902 else
903 coding = saved_coding.symbol;
905 process_coding.symbol = coding;
906 process_coding.eol_type = CODING_EOL_LF;
907 process_coding.mode
908 &= ~CODING_MODE_INHIBIT_INCONSISTENT_EOL;
911 nread -= process_coding.consumed;
912 carryover = nread;
913 if (carryover > 0)
914 /* As CARRYOVER should not be that large, we had
915 better avoid overhead of bcopy. */
916 BCOPY_SHORT (buf + process_coding.consumed, buf,
917 carryover);
918 if (process_coding.result == CODING_FINISH_INSUFFICIENT_CMP)
920 /* The decoding ended because of insufficient data
921 area to record information about composition.
922 We must try decoding with additional data area
923 before reading more output for the process. */
924 coding_allocate_composition_data (&process_coding, PT);
925 goto repeat_decoding;
930 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
931 break;
933 #if (CALLPROC_BUFFER_SIZE_MIN != CALLPROC_BUFFER_SIZE_MAX)
934 /* Make the buffer bigger as we continue to read more data,
935 but not past CALLPROC_BUFFER_SIZE_MAX. */
936 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
937 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
938 bufsize = CALLPROC_BUFFER_SIZE_MAX;
939 #endif
941 if (display_p)
943 if (first)
944 prepare_menu_bars ();
945 first = 0;
946 redisplay_preserve_echo_area (1);
947 /* This variable might have been set to 0 for code
948 detection. In that case, we set it back to 1 because
949 we should have already detected a coding system. */
950 display_on_the_fly = 1;
952 immediate_quit = 1;
953 QUIT;
955 give_up: ;
957 if (!NILP (buffer)
958 && process_coding.cmp_data)
960 coding_restore_composition (&process_coding, Fcurrent_buffer ());
961 coding_free_composition_data (&process_coding);
965 int post_read_count = SPECPDL_INDEX ();
967 record_unwind_protect (save_excursion_restore, save_excursion_save ());
968 inserted = PT - pt_orig;
969 TEMP_SET_PT_BOTH (pt_orig, pt_byte_orig);
970 if (SYMBOLP (process_coding.post_read_conversion)
971 && !NILP (Ffboundp (process_coding.post_read_conversion)))
972 call1 (process_coding.post_read_conversion, make_number (inserted));
974 Vlast_coding_system_used = process_coding.symbol;
976 /* If the caller required, let the buffer inherit the
977 coding-system used to decode the process output. */
978 if (inherit_process_coding_system)
979 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
980 make_number (total_read));
982 unbind_to (post_read_count, Qnil);
986 /* Wait for it to terminate, unless it already has. */
987 wait_for_termination (pid);
989 immediate_quit = 0;
991 set_buffer_internal (old);
993 /* Don't kill any children that the subprocess may have left behind
994 when exiting. */
995 call_process_exited = 1;
997 unbind_to (count, Qnil);
999 if (synch_process_termsig)
1001 char *signame;
1003 synchronize_system_messages_locale ();
1004 signame = strsignal (synch_process_termsig);
1006 if (signame == 0)
1007 signame = "unknown";
1009 synch_process_death = signame;
1012 if (synch_process_death)
1013 return code_convert_string_norecord (build_string (synch_process_death),
1014 Vlocale_coding_system, 0);
1015 return make_number (synch_process_retcode);
1017 #endif
1019 static Lisp_Object
1020 delete_temp_file (name)
1021 Lisp_Object name;
1023 /* Suppress jka-compr handling, etc. */
1024 int count = SPECPDL_INDEX ();
1025 specbind (intern ("file-name-handler-alist"), Qnil);
1026 internal_delete_file (name);
1027 unbind_to (count, Qnil);
1028 return Qnil;
1031 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
1032 3, MANY, 0,
1033 doc: /* Send text from START to END to a synchronous process running PROGRAM.
1034 The remaining arguments are optional.
1035 Delete the text if fourth arg DELETE is non-nil.
1037 Insert output in BUFFER before point; t means current buffer;
1038 nil for BUFFER means discard it; 0 means discard and don't wait.
1039 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1040 REAL-BUFFER says what to do with standard output, as above,
1041 while STDERR-FILE says what to do with standard error in the child.
1042 STDERR-FILE may be nil (discard standard error output),
1043 t (mix it with ordinary output), or a file name string.
1045 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1046 Remaining args are passed to PROGRAM at startup as command args.
1048 If BUFFER is 0, `call-process-region' returns immediately with value nil.
1049 Otherwise it waits for PROGRAM to terminate
1050 and returns a numeric exit status or a signal description string.
1051 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
1053 usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
1054 (nargs, args)
1055 int nargs;
1056 register Lisp_Object *args;
1058 struct gcpro gcpro1;
1059 Lisp_Object filename_string;
1060 register Lisp_Object start, end;
1061 int count = SPECPDL_INDEX ();
1062 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1063 Lisp_Object coding_systems;
1064 Lisp_Object val, *args2;
1065 int i;
1066 #ifdef DOS_NT
1067 char *tempfile;
1068 char *outf = '\0';
1070 if ((outf = egetenv ("TMPDIR"))
1071 || (outf = egetenv ("TMP"))
1072 || (outf = egetenv ("TEMP")))
1073 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
1074 else
1076 tempfile = alloca (20);
1077 *tempfile = '\0';
1079 if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
1080 strcat (tempfile, "/");
1081 if ('/' == DIRECTORY_SEP)
1082 dostounix_filename (tempfile);
1083 else
1084 unixtodos_filename (tempfile);
1085 #ifdef WINDOWSNT
1086 strcat (tempfile, "emXXXXXX");
1087 #else
1088 strcat (tempfile, "detmp.XXX");
1089 #endif
1090 #else /* not DOS_NT */
1091 char *tempfile = (char *) alloca (SBYTES (Vtemp_file_name_pattern) + 1);
1092 bcopy (SDATA (Vtemp_file_name_pattern), tempfile,
1093 SBYTES (Vtemp_file_name_pattern) + 1);
1094 #endif /* not DOS_NT */
1096 coding_systems = Qt;
1098 #ifdef HAVE_MKSTEMP
1100 int fd = mkstemp (tempfile);
1101 if (fd == -1)
1102 report_file_error ("Failed to open temporary file",
1103 Fcons (Vtemp_file_name_pattern, Qnil));
1104 else
1105 close (fd);
1107 #else
1108 mktemp (tempfile);
1109 #endif
1111 filename_string = build_string (tempfile);
1112 GCPRO1 (filename_string);
1113 start = args[0];
1114 end = args[1];
1115 /* Decide coding-system of the contents of the temporary file. */
1116 if (!NILP (Vcoding_system_for_write))
1117 val = Vcoding_system_for_write;
1118 else if (NILP (current_buffer->enable_multibyte_characters))
1119 val = Qnil;
1120 else
1122 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1123 args2[0] = Qcall_process_region;
1124 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1125 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1126 if (CONSP (coding_systems))
1127 val = XCDR (coding_systems);
1128 else if (CONSP (Vdefault_process_coding_system))
1129 val = XCDR (Vdefault_process_coding_system);
1130 else
1131 val = Qnil;
1135 int count1 = SPECPDL_INDEX ();
1137 specbind (intern ("coding-system-for-write"), val);
1138 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
1139 happen to get a ".Z" suffix. */
1140 specbind (intern ("file-name-handler-alist"), Qnil);
1141 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
1143 unbind_to (count1, Qnil);
1146 /* Note that Fcall_process takes care of binding
1147 coding-system-for-read. */
1149 record_unwind_protect (delete_temp_file, filename_string);
1151 if (nargs > 3 && !NILP (args[3]))
1152 Fdelete_region (start, end);
1154 if (nargs > 3)
1156 args += 2;
1157 nargs -= 2;
1159 else
1161 args[0] = args[2];
1162 nargs = 2;
1164 args[1] = filename_string;
1166 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
1169 #ifndef VMS /* VMS version is in vmsproc.c. */
1171 static int relocate_fd ();
1173 static char **
1174 add_env (char **env, char **new_env, char *string)
1176 char **ep;
1177 int ok = 1;
1178 if (string == NULL)
1179 return new_env;
1181 /* See if this string duplicates any string already in the env.
1182 If so, don't put it in.
1183 When an env var has multiple definitions,
1184 we keep the definition that comes first in process-environment. */
1185 for (ep = env; ok && ep != new_env; ep++)
1187 char *p = *ep, *q = string;
1188 while (ok)
1190 if (*q != *p)
1191 break;
1192 if (*q == 0)
1193 /* The string is a lone variable name; keep it for now, we
1194 will remove it later. It is a placeholder for a
1195 variable that is not to be included in the environment. */
1196 break;
1197 if (*q == '=')
1198 ok = 0;
1199 p++, q++;
1202 if (ok)
1203 *new_env++ = string;
1204 return new_env;
1207 /* This is the last thing run in a newly forked inferior
1208 either synchronous or asynchronous.
1209 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1210 Initialize inferior's priority, pgrp, connected dir and environment.
1211 then exec another program based on new_argv.
1213 This function may change environ for the superior process.
1214 Therefore, the superior process must save and restore the value
1215 of environ around the vfork and the call to this function.
1217 SET_PGRP is nonzero if we should put the subprocess into a separate
1218 process group.
1220 CURRENT_DIR is an elisp string giving the path of the current
1221 directory the subprocess should have. Since we can't really signal
1222 a decent error from within the child, this should be verified as an
1223 executable directory by the parent. */
1226 child_setup (in, out, err, new_argv, set_pgrp, current_dir)
1227 int in, out, err;
1228 register char **new_argv;
1229 int set_pgrp;
1230 Lisp_Object current_dir;
1232 char **env;
1233 char *pwd_var;
1234 #ifdef WINDOWSNT
1235 int cpid;
1236 HANDLE handles[3];
1237 #endif /* WINDOWSNT */
1239 int pid = getpid ();
1241 #ifdef SET_EMACS_PRIORITY
1243 extern EMACS_INT emacs_priority;
1245 if (emacs_priority < 0)
1246 nice (- emacs_priority);
1248 #endif
1250 #ifdef subprocesses
1251 /* Close Emacs's descriptors that this process should not have. */
1252 close_process_descs ();
1253 #endif
1254 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1255 we will lose if we call close_load_descs here. */
1256 #ifndef DOS_NT
1257 close_load_descs ();
1258 #endif
1260 /* Note that use of alloca is always safe here. It's obvious for systems
1261 that do not have true vfork or that have true (stack) alloca.
1262 If using vfork and C_ALLOCA it is safe because that changes
1263 the superior's static variables as if the superior had done alloca
1264 and will be cleaned up in the usual way. */
1266 register char *temp;
1267 register int i;
1269 i = SBYTES (current_dir);
1270 #ifdef MSDOS
1271 /* MSDOS must have all environment variables malloc'ed, because
1272 low-level libc functions that launch subsidiary processes rely
1273 on that. */
1274 pwd_var = (char *) xmalloc (i + 6);
1275 #else
1276 pwd_var = (char *) alloca (i + 6);
1277 #endif
1278 temp = pwd_var + 4;
1279 bcopy ("PWD=", pwd_var, 4);
1280 bcopy (SDATA (current_dir), temp, i);
1281 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
1282 temp[i] = 0;
1284 #ifndef DOS_NT
1285 /* We can't signal an Elisp error here; we're in a vfork. Since
1286 the callers check the current directory before forking, this
1287 should only return an error if the directory's permissions
1288 are changed between the check and this chdir, but we should
1289 at least check. */
1290 if (chdir (temp) < 0)
1291 _exit (errno);
1292 #endif
1294 #ifdef DOS_NT
1295 /* Get past the drive letter, so that d:/ is left alone. */
1296 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1298 temp += 2;
1299 i -= 2;
1301 #endif
1303 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1304 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1305 temp[--i] = 0;
1308 /* Set `env' to a vector of the strings in the environment. */
1310 register Lisp_Object tem;
1311 register char **new_env;
1312 char **p, **q;
1313 register int new_length;
1314 Lisp_Object environment = Vglobal_environment;
1315 Lisp_Object local;
1317 new_length = 0;
1319 for (tem = Vprocess_environment;
1320 CONSP (tem) && STRINGP (XCAR (tem));
1321 tem = XCDR (tem))
1322 new_length++;
1324 if (!NILP (Vlocal_environment_variables))
1326 local = get_frame_param (XFRAME (Fframe_with_environment (selected_frame)),
1327 Qenvironment);
1328 if (EQ (Vlocal_environment_variables, Qt)
1329 && !NILP (local))
1330 environment = local;
1331 else if (CONSP (local))
1333 new_length += Fsafe_length (Vlocal_environment_variables);
1337 for (tem = environment;
1338 CONSP (tem) && STRINGP (XCAR (tem));
1339 tem = XCDR (tem))
1340 new_length++;
1342 /* new_length + 2 to include PWD and terminating 0. */
1343 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
1345 /* If we have a PWD envvar, pass one down,
1346 but with corrected value. */
1347 if (getenv ("PWD"))
1348 *new_env++ = pwd_var;
1350 /* Overrides. */
1351 for (tem = Vprocess_environment;
1352 CONSP (tem) && STRINGP (XCAR (tem));
1353 tem = XCDR (tem))
1354 new_env = add_env (env, new_env, SDATA (XCAR (tem)));
1356 /* Local part of environment, if Vlocal_environment_variables is a list. */
1357 for (tem = Vlocal_environment_variables;
1358 CONSP (tem) && STRINGP (XCAR (tem));
1359 tem = XCDR (tem))
1360 new_env = add_env (env, new_env, egetenv (SDATA (XCAR (tem))));
1362 /* The rest of the environment (either Vglobal_environment or the
1363 'environment frame parameter). */
1364 for (tem = environment;
1365 CONSP (tem) && STRINGP (XCAR (tem));
1366 tem = XCDR (tem))
1367 new_env = add_env (env, new_env, SDATA (XCAR (tem)));
1369 *new_env = 0;
1371 /* Remove variable names without values. */
1372 p = q = env;
1373 while (*p != 0)
1375 while (*q != 0 && strchr (*q, '=') == NULL)
1376 *q++;
1377 *p = *q++;
1378 if (*p != 0)
1379 p++;
1382 #ifdef WINDOWSNT
1383 prepare_standard_handles (in, out, err, handles);
1384 set_process_dir (SDATA (current_dir));
1385 #else /* not WINDOWSNT */
1386 /* Make sure that in, out, and err are not actually already in
1387 descriptors zero, one, or two; this could happen if Emacs is
1388 started with its standard in, out, or error closed, as might
1389 happen under X. */
1391 int oin = in, oout = out;
1393 /* We have to avoid relocating the same descriptor twice! */
1395 in = relocate_fd (in, 3);
1397 if (out == oin)
1398 out = in;
1399 else
1400 out = relocate_fd (out, 3);
1402 if (err == oin)
1403 err = in;
1404 else if (err == oout)
1405 err = out;
1406 else
1407 err = relocate_fd (err, 3);
1410 #ifndef MSDOS
1411 emacs_close (0);
1412 emacs_close (1);
1413 emacs_close (2);
1415 dup2 (in, 0);
1416 dup2 (out, 1);
1417 dup2 (err, 2);
1418 emacs_close (in);
1419 emacs_close (out);
1420 emacs_close (err);
1421 #endif /* not MSDOS */
1422 #endif /* not WINDOWSNT */
1424 #if defined(USG) && !defined(BSD_PGRPS)
1425 #ifndef SETPGRP_RELEASES_CTTY
1426 setpgrp (); /* No arguments but equivalent in this case */
1427 #endif
1428 #else
1429 setpgrp (pid, pid);
1430 #endif /* USG */
1431 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
1432 EMACS_SET_TTY_PGRP (0, &pid);
1434 #ifdef MSDOS
1435 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1436 xfree (pwd_var);
1437 if (pid == -1)
1438 /* An error occurred while trying to run the subprocess. */
1439 report_file_error ("Spawning child process", Qnil);
1440 return pid;
1441 #else /* not MSDOS */
1442 #ifdef WINDOWSNT
1443 /* Spawn the child. (See ntproc.c:Spawnve). */
1444 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1445 reset_standard_handles (in, out, err, handles);
1446 if (cpid == -1)
1447 /* An error occurred while trying to spawn the process. */
1448 report_file_error ("Spawning child process", Qnil);
1449 return cpid;
1450 #else /* not WINDOWSNT */
1451 /* execvp does not accept an environment arg so the only way
1452 to pass this environment is to set environ. Our caller
1453 is responsible for restoring the ambient value of environ. */
1454 environ = env;
1455 execvp (new_argv[0], new_argv);
1457 emacs_write (1, "Can't exec program: ", 20);
1458 emacs_write (1, new_argv[0], strlen (new_argv[0]));
1459 emacs_write (1, "\n", 1);
1460 _exit (1);
1461 #endif /* not WINDOWSNT */
1462 #endif /* not MSDOS */
1465 /* Move the file descriptor FD so that its number is not less than MINFD.
1466 If the file descriptor is moved at all, the original is freed. */
1467 static int
1468 relocate_fd (fd, minfd)
1469 int fd, minfd;
1471 if (fd >= minfd)
1472 return fd;
1473 else
1475 int new = dup (fd);
1476 if (new == -1)
1478 char *message1 = "Error while setting up child: ";
1479 char *errmessage = strerror (errno);
1480 char *message2 = "\n";
1481 emacs_write (2, message1, strlen (message1));
1482 emacs_write (2, errmessage, strlen (errmessage));
1483 emacs_write (2, message2, strlen (message2));
1484 _exit (1);
1486 /* Note that we hold the original FD open while we recurse,
1487 to guarantee we'll get a new FD if we need it. */
1488 new = relocate_fd (new, minfd);
1489 emacs_close (fd);
1490 return new;
1494 static int
1495 getenv_internal (var, varlen, value, valuelen, frame)
1496 char *var;
1497 int varlen;
1498 char **value;
1499 int *valuelen;
1500 Lisp_Object frame;
1502 Lisp_Object scan;
1503 Lisp_Object environment = Vglobal_environment;
1505 /* Try to find VAR in Vprocess_environment first. */
1506 for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
1508 Lisp_Object entry = XCAR (scan);
1509 if (STRINGP (entry)
1510 && SBYTES (entry) >= varlen
1511 #ifdef WINDOWSNT
1512 /* NT environment variables are case insensitive. */
1513 && ! strnicmp (SDATA (entry), var, varlen)
1514 #else /* not WINDOWSNT */
1515 && ! bcmp (SDATA (entry), var, varlen)
1516 #endif /* not WINDOWSNT */
1519 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1521 *value = (char *) SDATA (entry) + (varlen + 1);
1522 *valuelen = SBYTES (entry) - (varlen + 1);
1523 return 1;
1525 else if (SBYTES (entry) == varlen)
1527 /* Lone variable names in Vprocess_environment mean that
1528 variable should be removed from the environment. */
1529 return 0;
1534 /* Find the environment in which to search the variable. */
1535 if (!NILP (frame))
1537 CHECK_FRAME (frame);
1538 frame = Fframe_with_environment (frame);
1539 Lisp_Object local = get_frame_param (XFRAME (frame), Qenvironment);
1540 /* Use Vglobal_environment if there is no local environment. */
1541 if (!NILP (local))
1542 environment = local;
1544 else if (!NILP (Vlocal_environment_variables))
1546 Lisp_Object local = get_frame_param (XFRAME (Fframe_with_environment (selected_frame)),
1547 Qenvironment);
1548 if (EQ (Vlocal_environment_variables, Qt)
1549 && !NILP (local))
1550 environment = local;
1551 else if (CONSP (local))
1553 for (scan = Vlocal_environment_variables; CONSP (scan); scan = XCDR (scan))
1555 Lisp_Object entry = XCAR (scan);
1556 if (STRINGP (entry)
1557 && SBYTES (entry) == varlen
1558 #ifdef WINDOWSNT
1559 /* NT environment variables are case insensitive. */
1560 && ! strnicmp (SDATA (entry), var, varlen)
1561 #else /* not WINDOWSNT */
1562 && ! bcmp (SDATA (entry), var, varlen)
1563 #endif /* not WINDOWSNT */
1566 environment = local;
1567 break;
1573 for (scan = environment; CONSP (scan); scan = XCDR (scan))
1575 Lisp_Object entry;
1577 entry = XCAR (scan);
1578 if (STRINGP (entry)
1579 && SBYTES (entry) > varlen
1580 && SREF (entry, varlen) == '='
1581 #ifdef WINDOWSNT
1582 /* NT environment variables are case insensitive. */
1583 && ! strnicmp (SDATA (entry), var, varlen)
1584 #else /* not WINDOWSNT */
1585 && ! bcmp (SDATA (entry), var, varlen)
1586 #endif /* not WINDOWSNT */
1589 *value = (char *) SDATA (entry) + (varlen + 1);
1590 *valuelen = SBYTES (entry) - (varlen + 1);
1591 return 1;
1595 return 0;
1598 DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
1599 doc: /* Get the value of environment variable VARIABLE.
1600 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1601 the environment. Otherwise, value is a string.
1603 If optional parameter FRAME is non-nil, then it should be a frame. If
1604 that frame has its own set of environment variables, this function
1605 will look up VARIABLE in there.
1607 Otherwise, this function searches `process-environment' for VARIABLE.
1608 If it is not found there, then it continues the search in either
1609 `global-environment' or the environment list of the selected frame,
1610 depending on the value of `local-environment-variables'. */)
1611 (variable, frame)
1612 Lisp_Object variable, frame;
1614 char *value;
1615 int valuelen;
1617 CHECK_STRING (variable);
1618 if (getenv_internal (SDATA (variable), SBYTES (variable),
1619 &value, &valuelen, frame))
1620 return make_string (value, valuelen);
1621 else
1622 return Qnil;
1625 /* A version of getenv that consults the Lisp environment lists,
1626 easily callable from C. */
1627 char *
1628 egetenv (var)
1629 char *var;
1631 char *value;
1632 int valuelen;
1634 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
1635 return value;
1636 else
1637 return 0;
1640 #endif /* not VMS */
1642 /* This is run before init_cmdargs. */
1644 void
1645 init_callproc_1 ()
1647 char *data_dir = egetenv ("EMACSDATA");
1648 char *doc_dir = egetenv ("EMACSDOC");
1650 Vdata_directory
1651 = Ffile_name_as_directory (build_string (data_dir ? data_dir
1652 : PATH_DATA));
1653 Vdoc_directory
1654 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1655 : PATH_DOC));
1657 /* Check the EMACSPATH environment variable, defaulting to the
1658 PATH_EXEC path from epaths.h. */
1659 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1660 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1661 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1664 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1666 void
1667 init_callproc ()
1669 char *data_dir = egetenv ("EMACSDATA");
1671 register char * sh;
1672 Lisp_Object tempdir;
1674 if (!NILP (Vinstallation_directory))
1676 /* Add to the path the lib-src subdir of the installation dir. */
1677 Lisp_Object tem;
1678 tem = Fexpand_file_name (build_string ("lib-src"),
1679 Vinstallation_directory);
1680 #ifndef DOS_NT
1681 /* MSDOS uses wrapped binaries, so don't do this. */
1682 if (NILP (Fmember (tem, Vexec_path)))
1684 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1685 Vexec_path = Fcons (tem, Vexec_path);
1686 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1689 Vexec_directory = Ffile_name_as_directory (tem);
1690 #endif /* not DOS_NT */
1692 /* Maybe use ../etc as well as ../lib-src. */
1693 if (data_dir == 0)
1695 tem = Fexpand_file_name (build_string ("etc"),
1696 Vinstallation_directory);
1697 Vdoc_directory = Ffile_name_as_directory (tem);
1701 /* Look for the files that should be in etc. We don't use
1702 Vinstallation_directory, because these files are never installed
1703 near the executable, and they are never in the build
1704 directory when that's different from the source directory.
1706 Instead, if these files are not in the nominal place, we try the
1707 source directory. */
1708 if (data_dir == 0)
1710 Lisp_Object tem, tem1, srcdir;
1712 srcdir = Fexpand_file_name (build_string ("../src/"),
1713 build_string (PATH_DUMPLOADSEARCH));
1714 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1715 tem1 = Ffile_exists_p (tem);
1716 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
1718 Lisp_Object newdir;
1719 newdir = Fexpand_file_name (build_string ("../etc/"),
1720 build_string (PATH_DUMPLOADSEARCH));
1721 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1722 tem1 = Ffile_exists_p (tem);
1723 if (!NILP (tem1))
1724 Vdata_directory = newdir;
1728 #ifndef CANNOT_DUMP
1729 if (initialized)
1730 #endif
1732 tempdir = Fdirectory_file_name (Vexec_directory);
1733 if (access (SDATA (tempdir), 0) < 0)
1734 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1735 Vexec_directory);
1738 tempdir = Fdirectory_file_name (Vdata_directory);
1739 if (access (SDATA (tempdir), 0) < 0)
1740 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1741 Vdata_directory);
1743 #ifdef VMS
1744 Vshell_file_name = build_string ("*dcl*");
1745 #else
1746 sh = (char *) getenv ("SHELL");
1747 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1748 #endif
1750 #ifdef VMS
1751 Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
1752 #else
1753 if (getenv ("TMPDIR"))
1755 char *dir = getenv ("TMPDIR");
1756 Vtemp_file_name_pattern
1757 = Fexpand_file_name (build_string ("emacsXXXXXX"),
1758 build_string (dir));
1760 else
1761 Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
1762 #endif
1764 #ifdef DOS_NT
1765 Vshared_game_score_directory = Qnil;
1766 #else
1767 Vshared_game_score_directory = build_string (PATH_GAME);
1768 if (NILP (Ffile_directory_p (Vshared_game_score_directory)))
1769 Vshared_game_score_directory = Qnil;
1770 #endif
1773 void
1774 set_global_environment ()
1776 register char **envp;
1778 Vglobal_environment = Qnil;
1779 #ifndef CANNOT_DUMP
1780 if (initialized)
1781 #endif
1782 for (envp = environ; *envp; envp++)
1783 Vglobal_environment = Fcons (build_string (*envp),
1784 Vglobal_environment);
1787 void
1788 syms_of_callproc ()
1790 #ifdef DOS_NT
1791 Qbuffer_file_type = intern ("buffer-file-type");
1792 staticpro (&Qbuffer_file_type);
1793 #endif /* DOS_NT */
1795 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1796 doc: /* *File name to load inferior shells from.
1797 Initialized from the SHELL environment variable. */);
1799 DEFVAR_LISP ("exec-path", &Vexec_path,
1800 doc: /* *List of directories to search programs to run in subprocesses.
1801 Each element is a string (directory name) or nil (try default directory). */);
1803 DEFVAR_LISP ("exec-suffixes", &Vexec_suffixes,
1804 doc: /* *List of suffixes to try to find executable file names.
1805 Each element is a string. */);
1806 Vexec_suffixes = Qnil;
1808 DEFVAR_LISP ("exec-directory", &Vexec_directory,
1809 doc: /* Directory for executables for Emacs to invoke.
1810 More generally, this includes any architecture-dependent files
1811 that are built and installed from the Emacs distribution. */);
1813 DEFVAR_LISP ("data-directory", &Vdata_directory,
1814 doc: /* Directory of machine-independent files that come with GNU Emacs.
1815 These are files intended for Emacs to use while it runs. */);
1817 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1818 doc: /* Directory containing the DOC file that comes with GNU Emacs.
1819 This is usually the same as data-directory. */);
1821 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1822 doc: /* For internal use by the build procedure only.
1823 This is the name of the directory in which the build procedure installed
1824 Emacs's info files; the default value for Info-default-directory-list
1825 includes this. */);
1826 Vconfigure_info_directory = build_string (PATH_INFO);
1828 DEFVAR_LISP ("shared-game-score-directory", &Vshared_game_score_directory,
1829 doc: /* Directory of score files for games which come with GNU Emacs.
1830 If this variable is nil, then Emacs is unable to use a shared directory. */);
1831 #ifdef DOS_NT
1832 Vshared_game_score_directory = Qnil;
1833 #else
1834 Vshared_game_score_directory = build_string (PATH_GAME);
1835 #endif
1837 DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
1838 doc: /* Pattern for making names for temporary files.
1839 This is used by `call-process-region'. */);
1840 /* This variable is initialized in init_callproc. */
1842 DEFVAR_LISP ("global-environment", &Vglobal_environment,
1843 doc: /* Global list of environment variables for subprocesses to inherit.
1844 Each element should be a string of the form ENVVARNAME=VALUE.
1846 The environment which Emacs inherits is placed in this variable when
1847 Emacs starts.
1849 Some frames may have their own local list of environment variables in
1850 their 'environment parameter, which may override this global list; see
1851 `local-environment-variables' and `frame-with-environment'. See
1852 `process-environment' for a way to modify an environment variable on
1853 all frames.
1855 If multiple entries define the same variable, the first one always
1856 takes precedence.
1858 Non-ASCII characters are encoded according to the initial value of
1859 `locale-coding-system', i.e. the elements must normally be decoded for use.
1860 See `setenv' and `getenv'. */);
1862 DEFVAR_LISP ("process-environment", &Vprocess_environment,
1863 doc: /* List of overridden environment variables for subprocesses to inherit.
1864 Each element should be a string of the form ENVVARNAME=VALUE.
1866 Entries in this list take precedence to those in `global-environment'
1867 or the frame-local environments. (See `local-environment-variables'
1868 and `frame-with-environment'.) Therefore, let-binding
1869 `process-environment' is an easy way to temporarily change the value
1870 of an environment variable, irrespective of where it comes from. To
1871 use `process-environment' to remove an environment variable, include
1872 only its name in the list, without "=VALUE".
1874 This variable is set to nil when Emacs starts.
1876 If multiple entries define the same variable, the first one always
1877 takes precedence.
1879 Non-ASCII characters are encoded according to the initial value of
1880 `locale-coding-system', i.e. the elements must normally be decoded for
1881 use.
1883 See `setenv' and `getenv'. */);
1884 Vprocess_environment = Qnil;
1886 #ifndef VMS
1887 defsubr (&Scall_process);
1888 defsubr (&Sgetenv_internal);
1889 #endif
1890 defsubr (&Scall_process_region);
1892 DEFVAR_LISP ("local-environment-variables", &Vlocal_environment_variables,
1893 doc: /* Enable or disable frame-local environment variables.
1894 If set to t, `getenv', `setenv' and subprocess creation functions use
1895 the local environment of the selected frame, ignoring
1896 `global-environment'.
1898 If set to nil, Emacs uses `global-environment' and ignores the
1899 frame-local environment.
1901 Otherwise, `local-environment-variables' should be a list of variable
1902 names (represented by Lisp strings) to look up in the frame's
1903 environment. The rest will come from `global-environment'.
1905 The frame-local environment is stored in the 'environment frame
1906 parameter. See `frame-with-environment'. */);
1907 Vlocal_environment_variables = Qt;
1910 /* arch-tag: 769b8045-1df7-4d2b-8968-e3fb49017f95
1911 (do not change this comment) */