Rework environment variable support. (Reported by Kalle Olavi Niemitalo and Noah...
[emacs.git] / src / callproc.c
blobb2352e9bd5573fb45ea9f1ca790a6ab0916a71bf
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, 2006 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 Vprocess_environment;
118 #ifdef DOS_NT
119 Lisp_Object Qbuffer_file_type;
120 #endif /* DOS_NT */
122 /* True iff we are about to fork off a synchronous process or if we
123 are waiting for it. */
124 int synch_process_alive;
126 /* Nonzero => this is a string explaining death of synchronous subprocess. */
127 char *synch_process_death;
129 /* Nonzero => this is the signal number that terminated the subprocess. */
130 int synch_process_termsig;
132 /* If synch_process_death is zero,
133 this is exit code of synchronous subprocess. */
134 int synch_process_retcode;
137 /* Clean up when exiting Fcall_process.
138 On MSDOS, delete the temporary file on any kind of termination.
139 On Unix, kill the process and any children on termination by signal. */
141 /* Nonzero if this is termination due to exit. */
142 static int call_process_exited;
144 #ifndef VMS /* VMS version is in vmsproc.c. */
146 static Lisp_Object
147 call_process_kill (fdpid)
148 Lisp_Object fdpid;
150 emacs_close (XFASTINT (Fcar (fdpid)));
151 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
152 synch_process_alive = 0;
153 return Qnil;
156 Lisp_Object
157 call_process_cleanup (fdpid)
158 Lisp_Object fdpid;
160 #if defined (MSDOS) || defined (MAC_OS8)
161 /* for MSDOS fdpid is really (fd . tempfile) */
162 register Lisp_Object file;
163 file = Fcdr (fdpid);
164 emacs_close (XFASTINT (Fcar (fdpid)));
165 if (strcmp (SDATA (file), NULL_DEVICE) != 0)
166 unlink (SDATA (file));
167 #else /* not MSDOS and not MAC_OS8 */
168 register int pid = XFASTINT (Fcdr (fdpid));
170 if (call_process_exited)
172 emacs_close (XFASTINT (Fcar (fdpid)));
173 return Qnil;
176 if (EMACS_KILLPG (pid, SIGINT) == 0)
178 int count = SPECPDL_INDEX ();
179 record_unwind_protect (call_process_kill, fdpid);
180 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
181 immediate_quit = 1;
182 QUIT;
183 wait_for_termination (pid);
184 immediate_quit = 0;
185 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
186 message1 ("Waiting for process to die...done");
188 synch_process_alive = 0;
189 emacs_close (XFASTINT (Fcar (fdpid)));
190 #endif /* not MSDOS */
191 return Qnil;
194 DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
195 doc: /* Call PROGRAM synchronously in separate process.
196 The remaining arguments are optional.
197 The program's input comes from file INFILE (nil means `/dev/null').
198 Insert output in BUFFER before point; t means current buffer;
199 nil for BUFFER means discard it; 0 means discard and don't wait.
200 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
201 REAL-BUFFER says what to do with standard output, as above,
202 while STDERR-FILE says what to do with standard error in the child.
203 STDERR-FILE may be nil (discard standard error output),
204 t (mix it with ordinary output), or a file name string.
206 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
207 Remaining arguments are strings passed as command arguments to PROGRAM.
209 If BUFFER is 0, `call-process' returns immediately with value nil.
210 Otherwise it waits for PROGRAM to terminate
211 and returns a numeric exit status or a signal description string.
212 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
214 usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
215 (nargs, args)
216 int nargs;
217 register Lisp_Object *args;
219 Lisp_Object infile, buffer, current_dir, path;
220 int display_p;
221 int fd[2];
222 int filefd;
223 register int pid;
224 #define CALLPROC_BUFFER_SIZE_MIN (16 * 1024)
225 #define CALLPROC_BUFFER_SIZE_MAX (4 * CALLPROC_BUFFER_SIZE_MIN)
226 char buf[CALLPROC_BUFFER_SIZE_MAX];
227 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
228 int count = SPECPDL_INDEX ();
230 register const unsigned char **new_argv
231 = (const unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
232 struct buffer *old = current_buffer;
233 /* File to use for stderr in the child.
234 t means use same as standard output. */
235 Lisp_Object error_file;
236 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
237 char *outf, *tempfile;
238 int outfilefd;
239 #endif
240 #ifdef MAC_OS8
241 char *tempfile;
242 int outfilefd;
243 #endif
244 #if 0
245 int mask;
246 #endif
247 struct coding_system process_coding; /* coding-system of process output */
248 struct coding_system argument_coding; /* coding-system of arguments */
249 /* Set to the return value of Ffind_operation_coding_system. */
250 Lisp_Object coding_systems;
252 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
253 coding_systems = Qt;
255 CHECK_STRING (args[0]);
257 error_file = Qt;
259 #ifndef subprocesses
260 /* Without asynchronous processes we cannot have BUFFER == 0. */
261 if (nargs >= 3
262 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
263 error ("Operating system cannot handle asynchronous subprocesses");
264 #endif /* subprocesses */
266 /* Decide the coding-system for giving arguments. */
268 Lisp_Object val, *args2;
269 int i;
271 /* If arguments are supplied, we may have to encode them. */
272 if (nargs >= 5)
274 int must_encode = 0;
276 for (i = 4; i < nargs; i++)
277 CHECK_STRING (args[i]);
279 for (i = 4; i < nargs; i++)
280 if (STRING_MULTIBYTE (args[i]))
281 must_encode = 1;
283 if (!NILP (Vcoding_system_for_write))
284 val = Vcoding_system_for_write;
285 else if (! must_encode)
286 val = Qnil;
287 else
289 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
290 args2[0] = Qcall_process;
291 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
292 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
293 if (CONSP (coding_systems))
294 val = XCDR (coding_systems);
295 else if (CONSP (Vdefault_process_coding_system))
296 val = XCDR (Vdefault_process_coding_system);
297 else
298 val = Qnil;
300 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
301 if (argument_coding.common_flags & CODING_ASCII_INCOMPATIBLE_MASK)
302 setup_coding_system (Qraw_text, &argument_coding);
303 if (argument_coding.eol_type == CODING_EOL_UNDECIDED)
304 argument_coding.eol_type = system_eol_type;
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, gcpro4;
367 current_dir = current_buffer->directory;
369 GCPRO4 (infile, buffer, current_dir, error_file);
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 if (STRING_MULTIBYTE (infile))
379 infile = ENCODE_FILE (infile);
380 if (STRING_MULTIBYTE (current_dir))
381 current_dir = ENCODE_FILE (current_dir);
382 if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
383 error_file = ENCODE_FILE (error_file);
384 UNGCPRO;
387 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
389 filefd = emacs_open (SDATA (infile), O_RDONLY, 0);
390 if (filefd < 0)
392 infile = DECODE_FILE (infile);
393 report_file_error ("Opening process input file", Fcons (infile, Qnil));
395 /* Search for program; barf if not found. */
397 struct gcpro gcpro1;
399 GCPRO1 (current_dir);
400 openp (Vexec_path, args[0], Vexec_suffixes, &path, make_number (X_OK));
401 UNGCPRO;
403 if (NILP (path))
405 emacs_close (filefd);
406 report_file_error ("Searching for program", Fcons (args[0], Qnil));
409 /* If program file name starts with /: for quoting a magic name,
410 discard that. */
411 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
412 && SREF (path, 1) == ':')
413 path = Fsubstring (path, make_number (2), Qnil);
415 new_argv[0] = SDATA (path);
416 if (nargs > 4)
418 register int i;
419 struct gcpro gcpro1, gcpro2, gcpro3;
421 GCPRO3 (infile, buffer, current_dir);
422 argument_coding.dst_multibyte = 0;
423 for (i = 4; i < nargs; i++)
425 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
426 if (CODING_REQUIRE_ENCODING (&argument_coding))
428 /* We must encode this argument. */
429 args[i] = encode_coding_string (args[i], &argument_coding, 1);
430 if (argument_coding.type == coding_type_ccl)
431 setup_ccl_program (&(argument_coding.spec.ccl.encoder), Qnil);
433 new_argv[i - 3] = SDATA (args[i]);
435 UNGCPRO;
436 new_argv[nargs - 3] = 0;
438 else
439 new_argv[1] = 0;
441 #ifdef MSDOS /* MW, July 1993 */
442 if ((outf = egetenv ("TMPDIR")))
443 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
444 else
446 tempfile = alloca (20);
447 *tempfile = '\0';
449 dostounix_filename (tempfile);
450 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
451 strcat (tempfile, "/");
452 strcat (tempfile, "detmp.XXX");
453 mktemp (tempfile);
455 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
456 if (outfilefd < 0)
458 emacs_close (filefd);
459 report_file_error ("Opening process output file",
460 Fcons (build_string (tempfile), Qnil));
462 fd[0] = filefd;
463 fd[1] = outfilefd;
464 #endif /* MSDOS */
466 #ifdef MAC_OS8
467 /* Since we don't have pipes on the Mac, create a temporary file to
468 hold the output of the subprocess. */
469 tempfile = (char *) alloca (SBYTES (Vtemp_file_name_pattern) + 1);
470 bcopy (SDATA (Vtemp_file_name_pattern), tempfile,
471 SBYTES (Vtemp_file_name_pattern) + 1);
473 mktemp (tempfile);
475 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
476 if (outfilefd < 0)
478 close (filefd);
479 report_file_error ("Opening process output file",
480 Fcons (build_string (tempfile), Qnil));
482 fd[0] = filefd;
483 fd[1] = outfilefd;
484 #endif /* MAC_OS8 */
486 if (INTEGERP (buffer))
487 fd[1] = emacs_open (NULL_DEVICE, O_WRONLY, 0), fd[0] = -1;
488 else
490 #ifndef MSDOS
491 #ifndef MAC_OS8
492 errno = 0;
493 if (pipe (fd) == -1)
495 emacs_close (filefd);
496 report_file_error ("Creating process pipe", Qnil);
498 #endif
499 #endif
500 #if 0
501 /* Replaced by close_process_descs */
502 set_exclusive_use (fd[0]);
503 #endif
507 /* child_setup must clobber environ in systems with true vfork.
508 Protect it from permanent change. */
509 register char **save_environ = environ;
510 register int fd1 = fd[1];
511 int fd_error = fd1;
513 #if 0 /* Some systems don't have sigblock. */
514 mask = sigblock (sigmask (SIGCHLD));
515 #endif
517 /* Record that we're about to create a synchronous process. */
518 synch_process_alive = 1;
520 /* These vars record information from process termination.
521 Clear them now before process can possibly terminate,
522 to avoid timing error if process terminates soon. */
523 synch_process_death = 0;
524 synch_process_retcode = 0;
525 synch_process_termsig = 0;
527 if (NILP (error_file))
528 fd_error = emacs_open (NULL_DEVICE, O_WRONLY, 0);
529 else if (STRINGP (error_file))
531 #ifdef DOS_NT
532 fd_error = emacs_open (SDATA (error_file),
533 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
534 S_IREAD | S_IWRITE);
535 #else /* not DOS_NT */
536 fd_error = creat (SDATA (error_file), 0666);
537 #endif /* not DOS_NT */
540 if (fd_error < 0)
542 emacs_close (filefd);
543 if (fd[0] != filefd)
544 emacs_close (fd[0]);
545 if (fd1 >= 0)
546 emacs_close (fd1);
547 #ifdef MSDOS
548 unlink (tempfile);
549 #endif
550 if (NILP (error_file))
551 error_file = build_string (NULL_DEVICE);
552 else if (STRINGP (error_file))
553 error_file = DECODE_FILE (error_file);
554 report_file_error ("Cannot redirect stderr", Fcons (error_file, Qnil));
557 #ifdef MAC_OS8
559 /* Call run_mac_command in sysdep.c here directly instead of doing
560 a child_setup as for MSDOS and other platforms. Note that this
561 code does not handle passing the environment to the synchronous
562 Mac subprocess. */
563 char *infn, *outfn, *errfn, *currdn;
565 /* close these files so subprocess can write to them */
566 close (outfilefd);
567 if (fd_error != outfilefd)
568 close (fd_error);
569 fd1 = -1; /* No harm in closing that one! */
571 infn = SDATA (infile);
572 outfn = tempfile;
573 if (NILP (error_file))
574 errfn = NULL_DEVICE;
575 else if (EQ (Qt, error_file))
576 errfn = outfn;
577 else
578 errfn = SDATA (error_file);
579 currdn = SDATA (current_dir);
580 pid = run_mac_command (new_argv, currdn, infn, outfn, errfn);
582 /* Record that the synchronous process exited and note its
583 termination status. */
584 synch_process_alive = 0;
585 synch_process_retcode = pid;
586 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
588 synchronize_system_messages_locale ();
589 synch_process_death = strerror (errno);
592 /* Since CRLF is converted to LF within `decode_coding', we can
593 always open a file with binary mode. */
594 fd[0] = open (tempfile, O_BINARY);
595 if (fd[0] < 0)
597 unlink (tempfile);
598 close (filefd);
599 report_file_error ("Cannot re-open temporary file", Qnil);
602 #else /* not MAC_OS8 */
603 #ifdef MSDOS /* MW, July 1993 */
604 /* Note that on MSDOS `child_setup' actually returns the child process
605 exit status, not its PID, so we assign it to `synch_process_retcode'
606 below. */
607 pid = child_setup (filefd, outfilefd, fd_error, (char **) new_argv,
608 0, current_dir);
610 /* Record that the synchronous process exited and note its
611 termination status. */
612 synch_process_alive = 0;
613 synch_process_retcode = pid;
614 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
616 synchronize_system_messages_locale ();
617 synch_process_death = strerror (errno);
620 emacs_close (outfilefd);
621 if (fd_error != outfilefd)
622 emacs_close (fd_error);
623 fd1 = -1; /* No harm in closing that one! */
624 /* Since CRLF is converted to LF within `decode_coding', we can
625 always open a file with binary mode. */
626 fd[0] = emacs_open (tempfile, O_RDONLY | O_BINARY, 0);
627 if (fd[0] < 0)
629 unlink (tempfile);
630 emacs_close (filefd);
631 report_file_error ("Cannot re-open temporary file", Qnil);
633 #else /* not MSDOS */
634 #ifdef WINDOWSNT
635 pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
636 0, current_dir);
637 #else /* not WINDOWSNT */
638 BLOCK_INPUT;
640 pid = vfork ();
642 if (pid == 0)
644 if (fd[0] >= 0)
645 emacs_close (fd[0]);
646 #ifdef HAVE_SETSID
647 setsid ();
648 #endif
649 #if defined (USG) && !defined (BSD_PGRPS)
650 setpgrp ();
651 #else
652 setpgrp (pid, pid);
653 #endif /* USG */
654 child_setup (filefd, fd1, fd_error, (char **) new_argv,
655 0, current_dir);
658 UNBLOCK_INPUT;
659 #endif /* not WINDOWSNT */
661 /* The MSDOS case did this already. */
662 if (fd_error >= 0)
663 emacs_close (fd_error);
664 #endif /* not MSDOS */
665 #endif /* not MAC_OS8 */
667 environ = save_environ;
669 /* Close most of our fd's, but not fd[0]
670 since we will use that to read input from. */
671 emacs_close (filefd);
672 if (fd1 >= 0 && fd1 != fd_error)
673 emacs_close (fd1);
676 if (pid < 0)
678 if (fd[0] >= 0)
679 emacs_close (fd[0]);
680 report_file_error ("Doing vfork", Qnil);
683 if (INTEGERP (buffer))
685 if (fd[0] >= 0)
686 emacs_close (fd[0]);
687 #ifndef subprocesses
688 /* If Emacs has been built with asynchronous subprocess support,
689 we don't need to do this, I think because it will then have
690 the facilities for handling SIGCHLD. */
691 wait_without_blocking ();
692 #endif /* subprocesses */
693 return Qnil;
696 /* Enable sending signal if user quits below. */
697 call_process_exited = 0;
699 #if defined(MSDOS) || defined(MAC_OS8)
700 /* MSDOS needs different cleanup information. */
701 record_unwind_protect (call_process_cleanup,
702 Fcons (make_number (fd[0]), build_string (tempfile)));
703 #else
704 record_unwind_protect (call_process_cleanup,
705 Fcons (make_number (fd[0]), make_number (pid)));
706 #endif /* not MSDOS and not MAC_OS8 */
709 if (BUFFERP (buffer))
710 Fset_buffer (buffer);
712 if (NILP (buffer))
714 /* If BUFFER is nil, we must read process output once and then
715 discard it, so setup coding system but with nil. */
716 setup_coding_system (Qnil, &process_coding);
718 else
720 Lisp_Object val, *args2;
722 val = Qnil;
723 if (!NILP (Vcoding_system_for_read))
724 val = Vcoding_system_for_read;
725 else
727 if (EQ (coding_systems, Qt))
729 int i;
731 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
732 args2[0] = Qcall_process;
733 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
734 coding_systems
735 = Ffind_operation_coding_system (nargs + 1, args2);
737 if (CONSP (coding_systems))
738 val = XCAR (coding_systems);
739 else if (CONSP (Vdefault_process_coding_system))
740 val = XCAR (Vdefault_process_coding_system);
741 else
742 val = Qnil;
744 setup_coding_system (Fcheck_coding_system (val), &process_coding);
745 /* In unibyte mode, character code conversion should not take
746 place but EOL conversion should. So, setup raw-text or one
747 of the subsidiary according to the information just setup. */
748 if (NILP (current_buffer->enable_multibyte_characters)
749 && !NILP (val))
750 setup_raw_text_coding_system (&process_coding);
752 process_coding.src_multibyte = 0;
753 process_coding.dst_multibyte
754 = (BUFFERP (buffer)
755 ? ! NILP (XBUFFER (buffer)->enable_multibyte_characters)
756 : ! NILP (current_buffer->enable_multibyte_characters));
758 immediate_quit = 1;
759 QUIT;
762 register int nread;
763 int first = 1;
764 int total_read = 0;
765 int carryover = 0;
766 int display_on_the_fly = display_p;
767 struct coding_system saved_coding;
768 int pt_orig = PT, pt_byte_orig = PT_BYTE;
769 int inserted;
771 saved_coding = process_coding;
772 if (process_coding.composing != COMPOSITION_DISABLED)
773 coding_allocate_composition_data (&process_coding, PT);
774 while (1)
776 /* Repeatedly read until we've filled as much as possible
777 of the buffer size we have. But don't read
778 less than 1024--save that for the next bufferful. */
779 nread = carryover;
780 while (nread < bufsize - 1024)
782 int this_read = emacs_read (fd[0], buf + nread,
783 bufsize - nread);
785 if (this_read < 0)
786 goto give_up;
788 if (this_read == 0)
790 process_coding.mode |= CODING_MODE_LAST_BLOCK;
791 break;
794 nread += this_read;
795 total_read += this_read;
797 if (display_on_the_fly)
798 break;
801 /* Now NREAD is the total amount of data in the buffer. */
802 immediate_quit = 0;
804 if (!NILP (buffer))
806 if (! CODING_MAY_REQUIRE_DECODING (&process_coding))
807 insert_1_both (buf, nread, nread, 0, 1, 0);
808 else
809 { /* We have to decode the input. */
810 int size;
811 char *decoding_buf;
813 repeat_decoding:
814 size = decoding_buffer_size (&process_coding, nread);
815 decoding_buf = (char *) xmalloc (size);
817 /* We can't use the macro CODING_REQUIRE_DETECTION
818 because it always returns nonzero if the coding
819 system requires EOL detection. Here, we have to
820 check only whether or not the coding system
821 requires text-encoding detection. */
822 if (process_coding.type == coding_type_undecided)
824 detect_coding (&process_coding, buf, nread);
825 if (process_coding.composing != COMPOSITION_DISABLED)
826 /* We have not yet allocated the composition
827 data because the coding type was undecided. */
828 coding_allocate_composition_data (&process_coding, PT);
830 if (process_coding.cmp_data)
831 process_coding.cmp_data->char_offset = PT;
833 decode_coding (&process_coding, buf, decoding_buf,
834 nread, size);
836 if (display_on_the_fly
837 && saved_coding.type == coding_type_undecided
838 && process_coding.type != coding_type_undecided)
840 /* We have detected some coding system. But,
841 there's a possibility that the detection was
842 done by insufficient data. So, we try the code
843 detection again with more data. */
844 xfree (decoding_buf);
845 display_on_the_fly = 0;
846 process_coding = saved_coding;
847 carryover = nread;
848 /* This is to make the above condition always
849 fails in the future. */
850 saved_coding.type = coding_type_no_conversion;
851 continue;
854 if (process_coding.produced > 0)
855 insert_1_both (decoding_buf, process_coding.produced_char,
856 process_coding.produced, 0, 1, 0);
857 xfree (decoding_buf);
859 if (process_coding.result == CODING_FINISH_INCONSISTENT_EOL)
861 Lisp_Object eol_type, coding;
863 if (process_coding.eol_type == CODING_EOL_CR)
865 /* CRs have been replaced with LFs. Undo
866 that in the text inserted above. */
867 unsigned char *p;
869 move_gap_both (PT, PT_BYTE);
871 p = BYTE_POS_ADDR (pt_byte_orig);
872 for (; p < GPT_ADDR; ++p)
873 if (*p == '\n')
874 *p = '\r';
876 else if (process_coding.eol_type == CODING_EOL_CRLF)
878 /* CR LFs have been replaced with LFs. Undo
879 that by inserting CRs in front of LFs in
880 the text inserted above. */
881 EMACS_INT bytepos, old_pt, old_pt_byte, nCR;
883 old_pt = PT;
884 old_pt_byte = PT_BYTE;
885 nCR = 0;
887 for (bytepos = PT_BYTE - 1;
888 bytepos >= pt_byte_orig;
889 --bytepos)
890 if (FETCH_BYTE (bytepos) == '\n')
892 EMACS_INT charpos = BYTE_TO_CHAR (bytepos);
893 TEMP_SET_PT_BOTH (charpos, bytepos);
894 insert_1_both ("\r", 1, 1, 0, 1, 0);
895 ++nCR;
898 TEMP_SET_PT_BOTH (old_pt + nCR, old_pt_byte + nCR);
901 /* Set the coding system symbol to that for
902 Unix-like EOL. */
903 eol_type = Fget (saved_coding.symbol, Qeol_type);
904 if (VECTORP (eol_type)
905 && ASIZE (eol_type) == 3
906 && SYMBOLP (AREF (eol_type, CODING_EOL_LF)))
907 coding = AREF (eol_type, CODING_EOL_LF);
908 else
909 coding = saved_coding.symbol;
911 process_coding.symbol = coding;
912 process_coding.eol_type = CODING_EOL_LF;
913 process_coding.mode
914 &= ~CODING_MODE_INHIBIT_INCONSISTENT_EOL;
917 nread -= process_coding.consumed;
918 carryover = nread;
919 if (carryover > 0)
920 /* As CARRYOVER should not be that large, we had
921 better avoid overhead of bcopy. */
922 BCOPY_SHORT (buf + process_coding.consumed, buf,
923 carryover);
924 if (process_coding.result == CODING_FINISH_INSUFFICIENT_CMP)
926 /* The decoding ended because of insufficient data
927 area to record information about composition.
928 We must try decoding with additional data area
929 before reading more output for the process. */
930 coding_allocate_composition_data (&process_coding, PT);
931 goto repeat_decoding;
936 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
937 break;
939 #if (CALLPROC_BUFFER_SIZE_MIN != CALLPROC_BUFFER_SIZE_MAX)
940 /* Make the buffer bigger as we continue to read more data,
941 but not past CALLPROC_BUFFER_SIZE_MAX. */
942 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
943 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
944 bufsize = CALLPROC_BUFFER_SIZE_MAX;
945 #endif
947 if (display_p)
949 if (first)
950 prepare_menu_bars ();
951 first = 0;
952 redisplay_preserve_echo_area (1);
953 /* This variable might have been set to 0 for code
954 detection. In that case, we set it back to 1 because
955 we should have already detected a coding system. */
956 display_on_the_fly = 1;
958 immediate_quit = 1;
959 QUIT;
961 give_up: ;
963 if (!NILP (buffer)
964 && process_coding.cmp_data)
966 coding_restore_composition (&process_coding, Fcurrent_buffer ());
967 coding_free_composition_data (&process_coding);
971 int post_read_count = SPECPDL_INDEX ();
973 record_unwind_protect (save_excursion_restore, save_excursion_save ());
974 inserted = PT - pt_orig;
975 TEMP_SET_PT_BOTH (pt_orig, pt_byte_orig);
976 if (SYMBOLP (process_coding.post_read_conversion)
977 && !NILP (Ffboundp (process_coding.post_read_conversion)))
978 call1 (process_coding.post_read_conversion, make_number (inserted));
980 Vlast_coding_system_used = process_coding.symbol;
982 /* If the caller required, let the buffer inherit the
983 coding-system used to decode the process output. */
984 if (inherit_process_coding_system)
985 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
986 make_number (total_read));
988 unbind_to (post_read_count, Qnil);
992 /* Wait for it to terminate, unless it already has. */
993 wait_for_termination (pid);
995 immediate_quit = 0;
997 set_buffer_internal (old);
999 /* Don't kill any children that the subprocess may have left behind
1000 when exiting. */
1001 call_process_exited = 1;
1003 unbind_to (count, Qnil);
1005 if (synch_process_termsig)
1007 char *signame;
1009 synchronize_system_messages_locale ();
1010 signame = strsignal (synch_process_termsig);
1012 if (signame == 0)
1013 signame = "unknown";
1015 synch_process_death = signame;
1018 if (synch_process_death)
1019 return code_convert_string_norecord (build_string (synch_process_death),
1020 Vlocale_coding_system, 0);
1021 return make_number (synch_process_retcode);
1023 #endif
1025 static Lisp_Object
1026 delete_temp_file (name)
1027 Lisp_Object name;
1029 /* Suppress jka-compr handling, etc. */
1030 int count = SPECPDL_INDEX ();
1031 specbind (intern ("file-name-handler-alist"), Qnil);
1032 internal_delete_file (name);
1033 unbind_to (count, Qnil);
1034 return Qnil;
1037 DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
1038 3, MANY, 0,
1039 doc: /* Send text from START to END to a synchronous process running PROGRAM.
1040 The remaining arguments are optional.
1041 Delete the text if fourth arg DELETE is non-nil.
1043 Insert output in BUFFER before point; t means current buffer;
1044 nil for BUFFER means discard it; 0 means discard and don't wait.
1045 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1046 REAL-BUFFER says what to do with standard output, as above,
1047 while STDERR-FILE says what to do with standard error in the child.
1048 STDERR-FILE may be nil (discard standard error output),
1049 t (mix it with ordinary output), or a file name string.
1051 Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1052 Remaining args are passed to PROGRAM at startup as command args.
1054 If BUFFER is 0, `call-process-region' returns immediately with value nil.
1055 Otherwise it waits for PROGRAM to terminate
1056 and returns a numeric exit status or a signal description string.
1057 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
1059 usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
1060 (nargs, args)
1061 int nargs;
1062 register Lisp_Object *args;
1064 struct gcpro gcpro1;
1065 Lisp_Object filename_string;
1066 register Lisp_Object start, end;
1067 int count = SPECPDL_INDEX ();
1068 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1069 Lisp_Object coding_systems;
1070 Lisp_Object val, *args2;
1071 int i;
1072 #ifdef DOS_NT
1073 char *tempfile;
1074 char *outf = '\0';
1076 if ((outf = egetenv ("TMPDIR"))
1077 || (outf = egetenv ("TMP"))
1078 || (outf = egetenv ("TEMP")))
1079 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
1080 else
1082 tempfile = alloca (20);
1083 *tempfile = '\0';
1085 if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
1086 strcat (tempfile, "/");
1087 if ('/' == DIRECTORY_SEP)
1088 dostounix_filename (tempfile);
1089 else
1090 unixtodos_filename (tempfile);
1091 #ifdef WINDOWSNT
1092 strcat (tempfile, "emXXXXXX");
1093 #else
1094 strcat (tempfile, "detmp.XXX");
1095 #endif
1096 #else /* not DOS_NT */
1097 char *tempfile = (char *) alloca (SBYTES (Vtemp_file_name_pattern) + 1);
1098 bcopy (SDATA (Vtemp_file_name_pattern), tempfile,
1099 SBYTES (Vtemp_file_name_pattern) + 1);
1100 #endif /* not DOS_NT */
1102 coding_systems = Qt;
1104 #ifdef HAVE_MKSTEMP
1106 int fd = mkstemp (tempfile);
1107 if (fd == -1)
1108 report_file_error ("Failed to open temporary file",
1109 Fcons (Vtemp_file_name_pattern, Qnil));
1110 else
1111 close (fd);
1113 #else
1114 mktemp (tempfile);
1115 #endif
1117 filename_string = build_string (tempfile);
1118 GCPRO1 (filename_string);
1119 start = args[0];
1120 end = args[1];
1121 /* Decide coding-system of the contents of the temporary file. */
1122 if (!NILP (Vcoding_system_for_write))
1123 val = Vcoding_system_for_write;
1124 else if (NILP (current_buffer->enable_multibyte_characters))
1125 val = Qnil;
1126 else
1128 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1129 args2[0] = Qcall_process_region;
1130 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1131 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1132 if (CONSP (coding_systems))
1133 val = XCDR (coding_systems);
1134 else if (CONSP (Vdefault_process_coding_system))
1135 val = XCDR (Vdefault_process_coding_system);
1136 else
1137 val = Qnil;
1141 int count1 = SPECPDL_INDEX ();
1143 specbind (intern ("coding-system-for-write"), val);
1144 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
1145 happen to get a ".Z" suffix. */
1146 specbind (intern ("file-name-handler-alist"), Qnil);
1147 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
1149 unbind_to (count1, Qnil);
1152 /* Note that Fcall_process takes care of binding
1153 coding-system-for-read. */
1155 record_unwind_protect (delete_temp_file, filename_string);
1157 if (nargs > 3 && !NILP (args[3]))
1158 Fdelete_region (start, end);
1160 if (nargs > 3)
1162 args += 2;
1163 nargs -= 2;
1165 else
1167 args[0] = args[2];
1168 nargs = 2;
1170 args[1] = filename_string;
1172 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
1175 #ifndef VMS /* VMS version is in vmsproc.c. */
1177 static int relocate_fd ();
1179 static char **
1180 add_env (char **env, char **new_env, char *string)
1182 char **ep;
1183 int ok = 1;
1184 if (string == NULL)
1185 return new_env;
1187 /* See if this string duplicates any string already in the env.
1188 If so, don't put it in.
1189 When an env var has multiple definitions,
1190 we keep the definition that comes first in process-environment. */
1191 for (ep = env; ok && ep != new_env; ep++)
1193 char *p = *ep, *q = string;
1194 while (ok)
1196 if (*q != *p)
1197 break;
1198 if (*q == 0)
1199 /* The string is a lone variable name; keep it for now, we
1200 will remove it later. It is a placeholder for a
1201 variable that is not to be included in the environment. */
1202 break;
1203 if (*q == '=')
1204 ok = 0;
1205 p++, q++;
1208 if (ok)
1209 *new_env++ = string;
1210 return new_env;
1213 /* This is the last thing run in a newly forked inferior
1214 either synchronous or asynchronous.
1215 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
1216 Initialize inferior's priority, pgrp, connected dir and environment.
1217 then exec another program based on new_argv.
1219 This function may change environ for the superior process.
1220 Therefore, the superior process must save and restore the value
1221 of environ around the vfork and the call to this function.
1223 SET_PGRP is nonzero if we should put the subprocess into a separate
1224 process group.
1226 CURRENT_DIR is an elisp string giving the path of the current
1227 directory the subprocess should have. Since we can't really signal
1228 a decent error from within the child, this should be verified as an
1229 executable directory by the parent. */
1232 child_setup (in, out, err, new_argv, set_pgrp, current_dir)
1233 int in, out, err;
1234 register char **new_argv;
1235 int set_pgrp;
1236 Lisp_Object current_dir;
1238 char **env;
1239 char *pwd_var;
1240 #ifdef WINDOWSNT
1241 int cpid;
1242 HANDLE handles[3];
1243 #endif /* WINDOWSNT */
1245 int pid = getpid ();
1247 #ifdef SET_EMACS_PRIORITY
1249 extern EMACS_INT emacs_priority;
1251 if (emacs_priority < 0)
1252 nice (- emacs_priority);
1254 #endif
1256 #ifdef subprocesses
1257 /* Close Emacs's descriptors that this process should not have. */
1258 close_process_descs ();
1259 #endif
1260 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1261 we will lose if we call close_load_descs here. */
1262 #ifndef DOS_NT
1263 close_load_descs ();
1264 #endif
1266 /* Note that use of alloca is always safe here. It's obvious for systems
1267 that do not have true vfork or that have true (stack) alloca.
1268 If using vfork and C_ALLOCA it is safe because that changes
1269 the superior's static variables as if the superior had done alloca
1270 and will be cleaned up in the usual way. */
1272 register char *temp;
1273 register int i;
1275 i = SBYTES (current_dir);
1276 #ifdef MSDOS
1277 /* MSDOS must have all environment variables malloc'ed, because
1278 low-level libc functions that launch subsidiary processes rely
1279 on that. */
1280 pwd_var = (char *) xmalloc (i + 6);
1281 #else
1282 pwd_var = (char *) alloca (i + 6);
1283 #endif
1284 temp = pwd_var + 4;
1285 bcopy ("PWD=", pwd_var, 4);
1286 bcopy (SDATA (current_dir), temp, i);
1287 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
1288 temp[i] = 0;
1290 #ifndef DOS_NT
1291 /* We can't signal an Elisp error here; we're in a vfork. Since
1292 the callers check the current directory before forking, this
1293 should only return an error if the directory's permissions
1294 are changed between the check and this chdir, but we should
1295 at least check. */
1296 if (chdir (temp) < 0)
1297 _exit (errno);
1298 #endif
1300 #ifdef DOS_NT
1301 /* Get past the drive letter, so that d:/ is left alone. */
1302 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1304 temp += 2;
1305 i -= 2;
1307 #endif
1309 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
1310 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
1311 temp[--i] = 0;
1314 /* Set `env' to a vector of the strings in the environment. */
1316 register Lisp_Object tem;
1317 register char **new_env;
1318 char **p, **q;
1319 register int new_length;
1320 Lisp_Object local = get_frame_param (XFRAME (Fframe_with_environment (selected_frame)),
1321 Qenvironment);
1323 new_length = 0;
1325 for (tem = Vprocess_environment;
1326 CONSP (tem) && STRINGP (XCAR (tem));
1327 tem = XCDR (tem))
1328 new_length++;
1330 for (tem = local;
1331 CONSP (tem) && STRINGP (XCAR (tem));
1332 tem = XCDR (tem))
1333 new_length++;
1335 /* new_length + 2 to include PWD and terminating 0. */
1336 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
1338 /* If we have a PWD envvar, pass one down,
1339 but with corrected value. */
1340 if (egetenv ("PWD"))
1341 *new_env++ = pwd_var;
1343 /* Overrides. */
1344 for (tem = Vprocess_environment;
1345 CONSP (tem) && STRINGP (XCAR (tem));
1346 tem = XCDR (tem))
1347 new_env = add_env (env, new_env, SDATA (XCAR (tem)));
1349 /* Local part of environment. */
1350 for (tem = local;
1351 CONSP (tem) && STRINGP (XCAR (tem));
1352 tem = XCDR (tem))
1353 new_env = add_env (env, new_env, SDATA (XCAR (tem)));
1355 *new_env = 0;
1357 /* Remove variable names without values. */
1358 p = q = env;
1359 while (*p != 0)
1361 while (*q != 0 && strchr (*q, '=') == NULL)
1362 *q++;
1363 *p = *q++;
1364 if (*p != 0)
1365 p++;
1368 #ifdef WINDOWSNT
1369 prepare_standard_handles (in, out, err, handles);
1370 set_process_dir (SDATA (current_dir));
1371 #else /* not WINDOWSNT */
1372 /* Make sure that in, out, and err are not actually already in
1373 descriptors zero, one, or two; this could happen if Emacs is
1374 started with its standard in, out, or error closed, as might
1375 happen under X. */
1377 int oin = in, oout = out;
1379 /* We have to avoid relocating the same descriptor twice! */
1381 in = relocate_fd (in, 3);
1383 if (out == oin)
1384 out = in;
1385 else
1386 out = relocate_fd (out, 3);
1388 if (err == oin)
1389 err = in;
1390 else if (err == oout)
1391 err = out;
1392 else
1393 err = relocate_fd (err, 3);
1396 #ifndef MSDOS
1397 emacs_close (0);
1398 emacs_close (1);
1399 emacs_close (2);
1401 dup2 (in, 0);
1402 dup2 (out, 1);
1403 dup2 (err, 2);
1404 emacs_close (in);
1405 emacs_close (out);
1406 emacs_close (err);
1407 #endif /* not MSDOS */
1408 #endif /* not WINDOWSNT */
1410 #if defined(USG) && !defined(BSD_PGRPS)
1411 #ifndef SETPGRP_RELEASES_CTTY
1412 setpgrp (); /* No arguments but equivalent in this case */
1413 #endif
1414 #else
1415 setpgrp (pid, pid);
1416 #endif /* USG */
1417 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
1418 EMACS_SET_TTY_PGRP (0, &pid);
1420 #ifdef MSDOS
1421 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1422 xfree (pwd_var);
1423 if (pid == -1)
1424 /* An error occurred while trying to run the subprocess. */
1425 report_file_error ("Spawning child process", Qnil);
1426 return pid;
1427 #else /* not MSDOS */
1428 #ifdef WINDOWSNT
1429 /* Spawn the child. (See ntproc.c:Spawnve). */
1430 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1431 reset_standard_handles (in, out, err, handles);
1432 if (cpid == -1)
1433 /* An error occurred while trying to spawn the process. */
1434 report_file_error ("Spawning child process", Qnil);
1435 return cpid;
1436 #else /* not WINDOWSNT */
1437 /* execvp does not accept an environment arg so the only way
1438 to pass this environment is to set environ. Our caller
1439 is responsible for restoring the ambient value of environ. */
1440 environ = env;
1441 execvp (new_argv[0], new_argv);
1443 emacs_write (1, "Can't exec program: ", 20);
1444 emacs_write (1, new_argv[0], strlen (new_argv[0]));
1445 emacs_write (1, "\n", 1);
1446 _exit (1);
1447 #endif /* not WINDOWSNT */
1448 #endif /* not MSDOS */
1451 /* Move the file descriptor FD so that its number is not less than MINFD.
1452 If the file descriptor is moved at all, the original is freed. */
1453 static int
1454 relocate_fd (fd, minfd)
1455 int fd, minfd;
1457 if (fd >= minfd)
1458 return fd;
1459 else
1461 int new = dup (fd);
1462 if (new == -1)
1464 char *message1 = "Error while setting up child: ";
1465 char *errmessage = strerror (errno);
1466 char *message2 = "\n";
1467 emacs_write (2, message1, strlen (message1));
1468 emacs_write (2, errmessage, strlen (errmessage));
1469 emacs_write (2, message2, strlen (message2));
1470 _exit (1);
1472 /* Note that we hold the original FD open while we recurse,
1473 to guarantee we'll get a new FD if we need it. */
1474 new = relocate_fd (new, minfd);
1475 emacs_close (fd);
1476 return new;
1480 static int
1481 getenv_internal (var, varlen, value, valuelen, frame)
1482 char *var;
1483 int varlen;
1484 char **value;
1485 int *valuelen;
1486 Lisp_Object frame;
1488 Lisp_Object scan;
1490 if (NILP (frame))
1492 /* Try to find VAR in Vprocess_environment first. */
1493 for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
1495 Lisp_Object entry = XCAR (scan);
1496 if (STRINGP (entry)
1497 && SBYTES (entry) >= varlen
1498 #ifdef WINDOWSNT
1499 /* NT environment variables are case insensitive. */
1500 && ! strnicmp (SDATA (entry), var, varlen)
1501 #else /* not WINDOWSNT */
1502 && ! bcmp (SDATA (entry), var, varlen)
1503 #endif /* not WINDOWSNT */
1506 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1508 *value = (char *) SDATA (entry) + (varlen + 1);
1509 *valuelen = SBYTES (entry) - (varlen + 1);
1510 return 1;
1512 else if (SBYTES (entry) == varlen)
1514 /* Lone variable names in Vprocess_environment mean that
1515 variable should be removed from the environment. */
1516 return 0;
1520 frame = selected_frame;
1523 /* Find the environment in which to search the variable. */
1524 CHECK_FRAME (frame);
1525 frame = Fframe_with_environment (frame);
1527 for (scan = get_frame_param (XFRAME (frame), Qenvironment);
1528 CONSP (scan);
1529 scan = XCDR (scan))
1531 Lisp_Object entry;
1533 entry = XCAR (scan);
1534 if (STRINGP (entry)
1535 && SBYTES (entry) > varlen
1536 && SREF (entry, varlen) == '='
1537 #ifdef WINDOWSNT
1538 /* NT environment variables are case insensitive. */
1539 && ! strnicmp (SDATA (entry), var, varlen)
1540 #else /* not WINDOWSNT */
1541 && ! bcmp (SDATA (entry), var, varlen)
1542 #endif /* not WINDOWSNT */
1545 *value = (char *) SDATA (entry) + (varlen + 1);
1546 *valuelen = SBYTES (entry) - (varlen + 1);
1547 return 1;
1551 return 0;
1554 DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
1555 doc: /* Get the value of environment variable VARIABLE.
1556 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1557 the environment. Otherwise, value is a string.
1559 This function searches `process-environment' for VARIABLE. If it is
1560 not found there, then it continues the search in the environment list
1561 of the selected frame.
1563 If optional parameter FRAME is non-nil, then this function will ignore
1564 `process-environment' and will simply look up the variable in that
1565 frame's environment. */)
1566 (variable, frame)
1567 Lisp_Object variable, frame;
1569 char *value;
1570 int valuelen;
1572 CHECK_STRING (variable);
1573 if (getenv_internal (SDATA (variable), SBYTES (variable),
1574 &value, &valuelen, frame))
1575 return make_string (value, valuelen);
1576 else
1577 return Qnil;
1580 /* A version of getenv that consults the Lisp environment lists,
1581 easily callable from C. */
1582 char *
1583 egetenv (var)
1584 char *var;
1586 char *value;
1587 int valuelen;
1589 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
1590 return value;
1591 else
1592 return 0;
1595 #endif /* not VMS */
1597 /* This is run before init_cmdargs. */
1599 void
1600 init_callproc_1 ()
1602 char *data_dir = egetenv ("EMACSDATA");
1603 char *doc_dir = egetenv ("EMACSDOC");
1605 Vdata_directory
1606 = Ffile_name_as_directory (build_string (data_dir ? data_dir
1607 : PATH_DATA));
1608 Vdoc_directory
1609 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1610 : PATH_DOC));
1612 /* Check the EMACSPATH environment variable, defaulting to the
1613 PATH_EXEC path from epaths.h. */
1614 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1615 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1616 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1619 /* This is run after init_cmdargs, when Vinstallation_directory is valid. */
1621 void
1622 init_callproc ()
1624 char *data_dir = egetenv ("EMACSDATA");
1626 register char * sh;
1627 Lisp_Object tempdir;
1629 if (!NILP (Vinstallation_directory))
1631 /* Add to the path the lib-src subdir of the installation dir. */
1632 Lisp_Object tem;
1633 tem = Fexpand_file_name (build_string ("lib-src"),
1634 Vinstallation_directory);
1635 #ifndef DOS_NT
1636 /* MSDOS uses wrapped binaries, so don't do this. */
1637 if (NILP (Fmember (tem, Vexec_path)))
1639 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1640 Vexec_path = Fcons (tem, Vexec_path);
1641 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1644 Vexec_directory = Ffile_name_as_directory (tem);
1645 #endif /* not DOS_NT */
1647 /* Maybe use ../etc as well as ../lib-src. */
1648 if (data_dir == 0)
1650 tem = Fexpand_file_name (build_string ("etc"),
1651 Vinstallation_directory);
1652 Vdoc_directory = Ffile_name_as_directory (tem);
1656 /* Look for the files that should be in etc. We don't use
1657 Vinstallation_directory, because these files are never installed
1658 near the executable, and they are never in the build
1659 directory when that's different from the source directory.
1661 Instead, if these files are not in the nominal place, we try the
1662 source directory. */
1663 if (data_dir == 0)
1665 Lisp_Object tem, tem1, srcdir;
1667 srcdir = Fexpand_file_name (build_string ("../src/"),
1668 build_string (PATH_DUMPLOADSEARCH));
1669 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1670 tem1 = Ffile_exists_p (tem);
1671 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
1673 Lisp_Object newdir;
1674 newdir = Fexpand_file_name (build_string ("../etc/"),
1675 build_string (PATH_DUMPLOADSEARCH));
1676 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1677 tem1 = Ffile_exists_p (tem);
1678 if (!NILP (tem1))
1679 Vdata_directory = newdir;
1683 #ifndef CANNOT_DUMP
1684 if (initialized)
1685 #endif
1687 tempdir = Fdirectory_file_name (Vexec_directory);
1688 if (access (SDATA (tempdir), 0) < 0)
1689 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1690 Vexec_directory);
1693 tempdir = Fdirectory_file_name (Vdata_directory);
1694 if (access (SDATA (tempdir), 0) < 0)
1695 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1696 Vdata_directory);
1698 #ifdef VMS
1699 Vshell_file_name = build_string ("*dcl*");
1700 #else
1701 sh = (char *) getenv ("SHELL");
1702 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
1703 #endif
1705 #ifdef VMS
1706 Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
1707 #else
1708 if (getenv ("TMPDIR"))
1710 char *dir = getenv ("TMPDIR");
1711 Vtemp_file_name_pattern
1712 = Fexpand_file_name (build_string ("emacsXXXXXX"),
1713 build_string (dir));
1715 else
1716 Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
1717 #endif
1719 #ifdef DOS_NT
1720 Vshared_game_score_directory = Qnil;
1721 #else
1722 Vshared_game_score_directory = build_string (PATH_GAME);
1723 if (NILP (Ffile_directory_p (Vshared_game_score_directory)))
1724 Vshared_game_score_directory = Qnil;
1725 #endif
1728 void
1729 set_initial_environment ()
1731 register char **envp;
1732 Lisp_Object env = Qnil;
1733 #ifndef CANNOT_DUMP
1734 if (initialized)
1735 #endif
1737 for (envp = environ; *envp; envp++)
1738 env = Fcons (build_string (*envp), env);
1739 store_frame_param (SELECTED_FRAME(), Qenvironment, env);
1743 void
1744 syms_of_callproc ()
1746 #ifdef DOS_NT
1747 Qbuffer_file_type = intern ("buffer-file-type");
1748 staticpro (&Qbuffer_file_type);
1749 #endif /* DOS_NT */
1751 DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
1752 doc: /* *File name to load inferior shells from.
1753 Initialized from the SHELL environment variable. */);
1755 DEFVAR_LISP ("exec-path", &Vexec_path,
1756 doc: /* *List of directories to search programs to run in subprocesses.
1757 Each element is a string (directory name) or nil (try default directory). */);
1759 DEFVAR_LISP ("exec-suffixes", &Vexec_suffixes,
1760 doc: /* *List of suffixes to try to find executable file names.
1761 Each element is a string. */);
1762 Vexec_suffixes = Qnil;
1764 DEFVAR_LISP ("exec-directory", &Vexec_directory,
1765 doc: /* Directory for executables for Emacs to invoke.
1766 More generally, this includes any architecture-dependent files
1767 that are built and installed from the Emacs distribution. */);
1769 DEFVAR_LISP ("data-directory", &Vdata_directory,
1770 doc: /* Directory of machine-independent files that come with GNU Emacs.
1771 These are files intended for Emacs to use while it runs. */);
1773 DEFVAR_LISP ("doc-directory", &Vdoc_directory,
1774 doc: /* Directory containing the DOC file that comes with GNU Emacs.
1775 This is usually the same as data-directory. */);
1777 DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
1778 doc: /* For internal use by the build procedure only.
1779 This is the name of the directory in which the build procedure installed
1780 Emacs's info files; the default value for Info-default-directory-list
1781 includes this. */);
1782 Vconfigure_info_directory = build_string (PATH_INFO);
1784 DEFVAR_LISP ("shared-game-score-directory", &Vshared_game_score_directory,
1785 doc: /* Directory of score files for games which come with GNU Emacs.
1786 If this variable is nil, then Emacs is unable to use a shared directory. */);
1787 #ifdef DOS_NT
1788 Vshared_game_score_directory = Qnil;
1789 #else
1790 Vshared_game_score_directory = build_string (PATH_GAME);
1791 #endif
1793 DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
1794 doc: /* Pattern for making names for temporary files.
1795 This is used by `call-process-region'. */);
1796 /* This variable is initialized in init_callproc. */
1798 DEFVAR_LISP ("process-environment", &Vprocess_environment,
1799 doc: /* List of overridden environment variables for subprocesses to inherit.
1800 Each element should be a string of the form ENVVARNAME=VALUE.
1802 Entries in this list take precedence to those in the frame-local
1803 environments. Therefore, let-binding `process-environment' is an easy
1804 way to temporarily change the value of an environment variable,
1805 irrespective of where it comes from. To use `process-environment' to
1806 remove an environment variable, include only its name in the list,
1807 without "=VALUE".
1809 This variable is set to nil when Emacs starts.
1811 If multiple entries define the same variable, the first one always
1812 takes precedence.
1814 Non-ASCII characters are encoded according to the initial value of
1815 `locale-coding-system', i.e. the elements must normally be decoded for
1816 use.
1818 See `setenv' and `getenv'. */);
1819 Vprocess_environment = Qnil;
1821 #ifndef VMS
1822 defsubr (&Scall_process);
1823 defsubr (&Sgetenv_internal);
1824 #endif
1825 defsubr (&Scall_process_region);
1828 /* arch-tag: 769b8045-1df7-4d2b-8968-e3fb49017f95
1829 (do not change this comment) */