XEmacs 21.4.18 (Social Property).
[chise/xemacs-chise.git.1] / src / callproc.c
1 /* Old synchronous subprocess invocation for XEmacs.
2    Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
3
4 This file is part of XEmacs.
5
6 XEmacs is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 XEmacs is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with XEmacs; see the file COPYING.  If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.  */
20
21 /* Synched up with: Mule 2.0, FSF 19.30. */
22 /* Partly sync'ed with 19.36.4 */
23
24
25 /* #### This ENTIRE file is only used in batch mode.
26
27    We only need two things to get rid of both this and ntproc.c:
28
29    -- my `stderr-proc' ws, which adds support for a separate stderr
30       in asynch. subprocesses. (it's a feature in `old-call-process-internal'.)
31    -- a noninteractive event loop that supports processes.
32 */
33
34 #include <config.h>
35 #include "lisp.h"
36
37 #include "buffer.h"
38 #include "commands.h"
39 #include "insdel.h"
40 #include "lstream.h"
41 #include "process.h"
42 #include "sysdep.h"
43 #include "window.h"
44 #ifdef FILE_CODING
45 #include "file-coding.h"
46 #endif
47
48 #include "systime.h"
49 #include "sysproc.h"
50 #include "sysfile.h" /* Always include after sysproc.h */
51 #include "sysdir.h"
52 #include "syssignal.h" /* Always include before systty.h */
53 #include "systty.h"
54
55 #ifdef WIN32_NATIVE
56 #define _P_NOWAIT 1     /* from process.h */
57 #include "nt.h"
58 #endif
59
60 #ifdef WIN32_NATIVE
61 /* When we are starting external processes we need to know whether they
62    take binary input (no conversion) or text input (\n is converted to
63    \r\n).  Similarly for output: if newlines are written as \r\n then it's
64    text process output, otherwise it's binary.  */
65 Lisp_Object Vbinary_process_input;
66 Lisp_Object Vbinary_process_output;
67 #endif /* WIN32_NATIVE */
68
69 Lisp_Object Vshell_file_name;
70
71 /* The environment to pass to all subprocesses when they are started.
72    This is in the semi-bogus format of ("VAR=VAL" "VAR2=VAL2" ... )
73  */
74 Lisp_Object Vprocess_environment;
75
76 /* True iff we are about to fork off a synchronous process or if we
77    are waiting for it.  */
78 volatile int synch_process_alive;
79
80 /* Nonzero => this is a string explaining death of synchronous subprocess.  */
81 const char *synch_process_death;
82
83 /* If synch_process_death is zero,
84    this is exit code of synchronous subprocess.  */
85 int synch_process_retcode;
86 \f
87 /* Clean up when exiting Fcall_process_internal.
88    On Windows, delete the temporary file on any kind of termination.
89    On Unix, kill the process and any children on termination by signal.  */
90
91 /* Nonzero if this is termination due to exit.  */
92 static int call_process_exited;
93
94 Lisp_Object Vlisp_EXEC_SUFFIXES;
95
96 static Lisp_Object
97 call_process_kill (Lisp_Object fdpid)
98 {
99   Lisp_Object fd = Fcar (fdpid);
100   Lisp_Object pid = Fcdr (fdpid);
101
102   if (!NILP (fd))
103     close (XINT (fd));
104
105   if (!NILP (pid))
106     EMACS_KILLPG (XINT (pid), SIGKILL);
107
108   synch_process_alive = 0;
109   return Qnil;
110 }
111
112 static Lisp_Object
113 call_process_cleanup (Lisp_Object fdpid)
114 {
115   int fd  = XINT (Fcar (fdpid));
116   int pid = XINT (Fcdr (fdpid));
117
118   if (!call_process_exited &&
119       EMACS_KILLPG (pid, SIGINT) == 0)
120   {
121     int speccount = specpdl_depth ();
122
123     record_unwind_protect (call_process_kill, fdpid);
124     /* #### "c-G" -- need non-consing Single-key-description */
125     message ("Waiting for process to die...(type C-g again to kill it instantly)");
126
127 #ifdef WIN32_NATIVE
128     {
129       HANDLE pHandle = OpenProcess (PROCESS_ALL_ACCESS, 0, pid);
130       if (pHandle == NULL)
131         warn_when_safe (Qprocess, Qwarning,
132                         "cannot open process (PID %d) for cleanup", pid);
133       else
134         wait_for_termination (pHandle);
135     }
136 #else
137     wait_for_termination (pid);
138 #endif
139
140     /* "Discard" the unwind protect.  */
141     XCAR (fdpid) = Qnil;
142     XCDR (fdpid) = Qnil;
143     unbind_to (speccount, Qnil);
144
145     message ("Waiting for process to die... done");
146   }
147   synch_process_alive = 0;
148   close (fd);
149   return Qnil;
150 }
151
152 static Lisp_Object fork_error;
153 #if 0 /* UNUSED */
154 static void
155 report_fork_error (char *string, Lisp_Object data)
156 {
157   Lisp_Object errstring = lisp_strerror (errno);
158
159   fork_error = Fcons (build_string (string), Fcons (errstring, data));
160
161   /* terminate this branch of the fork, without closing stdin/out/etc. */
162   _exit (1);
163 }
164 #endif /* unused */
165
166 DEFUN ("old-call-process-internal", Fold_call_process_internal, 1, MANY, 0, /*
167 Call PROGRAM synchronously in separate process, with coding-system specified.
168 Arguments are
169  (PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS).
170 The program's input comes from file INFILE (nil means `/dev/null').
171 Insert output in BUFFER before point; t means current buffer;
172  nil for BUFFER means discard it; 0 means discard and don't wait.
173 If BUFFER is a string, then find or create a buffer with that name,
174 then insert the output in that buffer, before point.
175 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
176 REAL-BUFFER says what to do with standard output, as above,
177 while STDERR-FILE says what to do with standard error in the child.
178 STDERR-FILE may be nil (discard standard error output),
179 t (mix it with ordinary output), or a file name string.
180
181 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
182 Remaining arguments are strings passed as command arguments to PROGRAM.
183
184 If BUFFER is 0, `call-process' returns immediately with value nil.
185 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
186  or a signal description string.
187 If you quit, the process is killed with SIGINT, or SIGKILL if you
188  quit again.
189 */
190        (int nargs, Lisp_Object *args))
191 {
192   /* This function can GC */
193   Lisp_Object infile, buffer, current_dir, display, path;
194   int fd[2];
195   int filefd;
196 #ifdef WIN32_NATIVE
197   HANDLE pHandle;
198 #endif
199   int pid;
200   char buf[16384];
201   char *bufptr = buf;
202   int bufsize = 16384;
203   int speccount = specpdl_depth ();
204   struct gcpro gcpro1, gcpro2, gcpro3;
205   char **new_argv = alloca_array (char *, max (2, nargs - 2));
206
207   /* File to use for stderr in the child.
208      t means use same as standard output.  */
209   Lisp_Object error_file;
210
211   CHECK_STRING (args[0]);
212
213   error_file = Qt;
214
215 #if defined (NO_SUBPROCESSES)
216   /* Without asynchronous processes we cannot have BUFFER == 0.  */
217   if (nargs >= 3 && !INTP (args[2]))
218     error ("Operating system cannot handle asynchronous subprocesses");
219 #endif /* NO_SUBPROCESSES */
220
221   /* Do this before building new_argv because GC in Lisp code
222    *  called by various filename-hacking routines might relocate strings */
223   locate_file (Vexec_path, args[0], Vlisp_EXEC_SUFFIXES, &path, X_OK);
224
225   /* Make sure that the child will be able to chdir to the current
226      buffer's current directory, or its unhandled equivalent.  We
227      can't just have the child check for an error when it does the
228      chdir, since it's in a vfork. */
229   {
230     struct gcpro ngcpro1, ngcpro2;
231     /* Do this test before building new_argv because GC in Lisp code
232      *  called by various filename-hacking routines might relocate strings */
233     /* Make sure that the child will be able to chdir to the current
234        buffer's current directory.  We can't just have the child check
235        for an error when it does the chdir, since it's in a vfork.  */
236
237     current_dir = current_buffer->directory;
238     NGCPRO2 (current_dir, path);   /* Caller gcprotects args[] */
239     current_dir = Funhandled_file_name_directory (current_dir);
240     current_dir = expand_and_dir_to_file (current_dir, Qnil);
241 #if 0
242     /* This is in FSF, but it breaks everything in the presence of
243        ange-ftp-visited files, so away with it.  */
244     if (NILP (Ffile_accessible_directory_p (current_dir)))
245       report_file_error ("Setting current directory",
246                          Fcons (current_buffer->directory, Qnil));
247 #endif /* 0 */
248     NUNGCPRO;
249   }
250
251   GCPRO2 (current_dir, path);
252
253   if (nargs >= 2 && ! NILP (args[1]))
254     {
255       struct gcpro ngcpro1;
256       NGCPRO1 (current_buffer->directory);
257       infile = Fexpand_file_name (args[1], current_buffer->directory);
258       NUNGCPRO;
259       CHECK_STRING (infile);
260     }
261   else
262     infile = build_string (NULL_DEVICE);
263
264   UNGCPRO;
265
266   GCPRO3 (infile, current_dir, path);   /* Fexpand_file_name might trash it */
267
268   if (nargs >= 3)
269     {
270       buffer = args[2];
271
272       /* If BUFFER is a list, its meaning is
273          (BUFFER-FOR-STDOUT FILE-FOR-STDERR).  */
274       if (CONSP (buffer))
275         {
276           if (CONSP (XCDR (buffer)))
277             {
278               Lisp_Object file_for_stderr = XCAR (XCDR (buffer));
279
280               if (NILP (file_for_stderr) || EQ (Qt, file_for_stderr))
281                 error_file = file_for_stderr;
282               else
283                 error_file = Fexpand_file_name (file_for_stderr, Qnil);
284             }
285
286           buffer = XCAR (buffer);
287         }
288
289       if (!(EQ (buffer, Qnil)
290             || EQ (buffer, Qt)
291             || ZEROP (buffer)))
292         {
293           Lisp_Object spec_buffer = buffer;
294           buffer = Fget_buffer_create (buffer);
295           /* Mention the buffer name for a better error message.  */
296           if (NILP (buffer))
297             CHECK_BUFFER (spec_buffer);
298           CHECK_BUFFER (buffer);
299         }
300     }
301   else
302     buffer = Qnil;
303
304   UNGCPRO;
305
306   display = ((nargs >= 4) ? args[3] : Qnil);
307
308   /* From here we assume we won't GC (unless an error is signaled). */
309   {
310     REGISTER int i;
311     for (i = 4; i < nargs; i++)
312       {
313         CHECK_STRING (args[i]);
314         new_argv[i - 3] = (char *) XSTRING_DATA (args[i]);
315       }
316   }
317   new_argv[max(nargs - 3,1)] = 0;
318
319   if (NILP (path))
320     report_file_error ("Searching for program", Fcons (args[0], Qnil));
321   new_argv[0] = (char *) XSTRING_DATA (path);
322
323   filefd = open ((char *) XSTRING_DATA (infile), O_RDONLY | OPEN_BINARY, 0);
324   if (filefd < 0)
325     report_file_error ("Opening process input file", Fcons (infile, Qnil));
326
327   if (INTP (buffer))
328     {
329       fd[1] = open (NULL_DEVICE, O_WRONLY | OPEN_BINARY, 0);
330       fd[0] = -1;
331     }
332   else
333     {
334       pipe (fd);
335 #if 0
336       /* Replaced by close_process_descs */
337       set_exclusive_use (fd[0]);
338 #endif
339     }
340
341   {
342     /* child_setup must clobber environ in systems with true vfork.
343        Protect it from permanent change.  */
344     REGISTER char **save_environ = environ;
345     REGISTER int fd1 = fd[1];
346     int fd_error = fd1;
347
348     /* Record that we're about to create a synchronous process.  */
349     synch_process_alive = 1;
350
351     /* These vars record information from process termination.
352        Clear them now before process can possibly terminate,
353        to avoid timing error if process terminates soon.  */
354     synch_process_death = 0;
355     synch_process_retcode = 0;
356
357     if (NILP (error_file))
358       fd_error = open (NULL_DEVICE, O_WRONLY | OPEN_BINARY);
359     else if (STRINGP (error_file))
360       {
361         fd_error = open ((const char *) XSTRING_DATA (error_file),
362 #ifdef WIN32_NATIVE
363                          O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
364                          S_IREAD | S_IWRITE
365 #else  /* not WIN32_NATIVE */
366                          O_WRONLY | O_TRUNC | O_CREAT | OPEN_BINARY,
367                          CREAT_MODE
368 #endif /* not WIN32_NATIVE */
369                          );
370       }
371
372     if (fd_error < 0)
373       {
374         int save_errno = errno;
375         close (filefd);
376         close (fd[0]);
377         if (fd1 >= 0)
378           close (fd1);
379         errno = save_errno;
380         report_file_error ("Cannot open", Fcons(error_file, Qnil));
381       }
382
383     fork_error = Qnil;
384 #ifdef WIN32_NATIVE
385     pid = child_setup (filefd, fd1, fd_error, new_argv,
386                        (char *) XSTRING_DATA (current_dir));
387     if (!INTP (buffer))
388       {
389         /* OpenProcess() as soon after child_setup as possible.  It's too
390            late once the process terminated. */
391         pHandle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
392 #if 0
393         if (pHandle == NULL)
394           {
395             /* #### seems to cause crash in unbind_to(...) below. APA */
396             warn_when_safe (Qprocess, Qwarning,
397                             "cannot open process to wait for");
398           }
399 #endif
400       }
401     /* Close STDERR into the parent process.  We no longer need it. */
402     if (fd_error >= 0)
403       close (fd_error);
404 #else  /* not WIN32_NATIVE */
405     pid = fork ();
406
407     if (pid == 0)
408       {
409         if (fd[0] >= 0)
410           close (fd[0]);
411         /* This is necessary because some shells may attempt to
412            access the current controlling terminal and will hang
413            if they are run in the background, as will be the case
414            when XEmacs is started in the background.  Martin
415            Buchholz observed this problem running a subprocess
416            that used zsh to call gzip to uncompress an info
417            file. */
418         disconnect_controlling_terminal ();
419         child_setup (filefd, fd1, fd_error, new_argv,
420                      (char *) XSTRING_DATA (current_dir));
421       }
422     if (fd_error >= 0)
423       close (fd_error);
424
425 #endif /* not WIN32_NATIVE */
426
427     environ = save_environ;
428
429     /* Close most of our fd's, but not fd[0]
430        since we will use that to read input from.  */
431     close (filefd);
432     if (fd1 >= 0)
433       close (fd1);
434   }
435
436   if (!NILP (fork_error))
437     signal_error (Qfile_error, fork_error);
438
439 #ifndef WIN32_NATIVE
440   if (pid < 0)
441     {
442       int save_errno = errno;
443       if (fd[0] >= 0)
444         close (fd[0]);
445       errno = save_errno;
446       report_file_error ("Doing fork", Qnil);
447     }
448 #endif
449
450   if (INTP (buffer))
451     {
452       if (fd[0] >= 0)
453         close (fd[0]);
454 #if defined (NO_SUBPROCESSES)
455       /* If Emacs has been built with asynchronous subprocess support,
456          we don't need to do this, I think because it will then have
457          the facilities for handling SIGCHLD.  */
458       wait_without_blocking ();
459 #endif /* NO_SUBPROCESSES */
460       return Qnil;
461     }
462
463   {
464     int nread;
465     int total_read = 0;
466     Lisp_Object instream;
467     struct gcpro ngcpro1;
468
469     /* Enable sending signal if user quits below.  */
470     call_process_exited = 0;
471
472     record_unwind_protect (call_process_cleanup,
473                            Fcons (make_int (fd[0]), make_int (pid)));
474
475     /* FSFmacs calls Fset_buffer() here.  We don't have to because
476        we can insert into buffers other than the current one. */
477     if (EQ (buffer, Qt))
478       XSETBUFFER (buffer, current_buffer);
479     instream = make_filedesc_input_stream (fd[0], 0, -1, LSTR_ALLOW_QUIT);
480 #ifdef FILE_CODING
481     instream =
482       make_decoding_input_stream
483         (XLSTREAM (instream),
484          Fget_coding_system (Vcoding_system_for_read));
485     Lstream_set_character_mode (XLSTREAM (instream));
486 #endif
487     NGCPRO1 (instream);
488     while (1)
489       {
490         QUIT;
491         /* Repeatedly read until we've filled as much as possible
492            of the buffer size we have.  But don't read
493            less than 1024--save that for the next bufferfull.  */
494
495         nread = 0;
496         while (nread < bufsize - 1024)
497           {
498             Lstream_data_count this_read
499               = Lstream_read (XLSTREAM (instream), bufptr + nread,
500                               bufsize - nread);
501
502             if (this_read < 0)
503               goto give_up;
504
505             if (this_read == 0)
506               goto give_up_1;
507
508             nread += this_read;
509           }
510
511       give_up_1:
512
513         /* Now NREAD is the total amount of data in the buffer.  */
514         if (nread == 0)
515           break;
516
517 #if 0
518 #ifdef WIN32_NATIVE
519        /* Until we pull out of MULE things like
520           make_decoding_input_stream(), we do the following which is
521           less elegant. --marcpa */
522         /* We did. -- kkm */
523        {
524          int lf_count = 0;
525          if (NILP (Vbinary_process_output)) {
526            nread = crlf_to_lf(nread, bufptr, &lf_count);
527          }
528        }
529 #endif
530 #endif
531
532         total_read += nread;
533
534         if (!NILP (buffer))
535           buffer_insert_raw_string (XBUFFER (buffer), (Bufbyte *) bufptr,
536                                     nread);
537
538         /* Make the buffer bigger as we continue to read more data,
539            but not past 64k.  */
540         if (bufsize < 64 * 1024 && total_read > 32 * bufsize)
541           {
542             bufsize *= 2;
543             bufptr = (char *) alloca (bufsize);
544           }
545
546         if (!NILP (display) && INTERACTIVE)
547           {
548             redisplay ();
549           }
550       }
551   give_up:
552     Lstream_close (XLSTREAM (instream));
553     NUNGCPRO;
554
555     QUIT;
556     /* Wait for it to terminate, unless it already has.  */
557 #ifdef WIN32_NATIVE
558     wait_for_termination (pHandle);
559 #else
560     wait_for_termination (pid);
561 #endif
562
563     /* Don't kill any children that the subprocess may have left behind
564        when exiting.  */
565     call_process_exited = 1;
566     unbind_to (speccount, Qnil);
567
568     if (synch_process_death)
569       return build_string (synch_process_death);
570     return make_int (synch_process_retcode);
571   }
572 }
573
574 \f
575
576 /* Move the file descriptor FD so that its number is not less than MIN. *
577    The original file descriptor remains open.  */
578 static int
579 relocate_fd (int fd, int min)
580 {
581   if (fd >= min)
582     return fd;
583   else
584     {
585       int newfd = dup (fd);
586       if (newfd == -1)
587         {
588           stderr_out ("Error while setting up child: %s\n",
589                       strerror (errno));
590           _exit (1);
591         }
592       return relocate_fd (newfd, min);
593     }
594 }
595
596 /* This is the last thing run in a newly forked inferior
597    either synchronous or asynchronous.
598    Copy descriptors IN, OUT and ERR
599    as descriptors STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO.
600    Initialize inferior's priority, pgrp, connected dir and environment.
601    then exec another program based on new_argv.
602
603    This function may change environ for the superior process.
604    Therefore, the superior process must save and restore the value
605    of environ around the fork and the call to this function.
606
607    ENV is the environment for the subprocess.
608
609    XEmacs: We've removed the SET_PGRP argument because it's already
610    done by the callers of child_setup.
611
612    CURRENT_DIR is an elisp string giving the path of the current
613    directory the subprocess should have.  Since we can't really signal
614    a decent error from within the child, this should be verified as an
615    executable directory by the parent.  */
616
617 #ifdef WIN32_NATIVE
618 int
619 #else
620 void
621 #endif
622 child_setup (int in, int out, int err, char **new_argv,
623              const char *current_dir)
624 {
625   char **env;
626   char *pwd;
627 #ifdef WIN32_NATIVE
628   int cpid;
629   HANDLE handles[4];
630 #endif /* WIN32_NATIVE */
631
632 #ifdef SET_EMACS_PRIORITY
633   if (emacs_priority != 0)
634     nice (- emacs_priority);
635 #endif
636
637   /* Under Windows, we are not in a child process at all, so we should
638      not close handles inherited from the parent -- we are the parent
639      and doing so will screw up all manner of things!  Similarly, most
640      of the rest of the cleanup done in this function is not done
641      under Windows.
642
643      #### This entire child_setup() function is an utter and complete
644      piece of shit.  I would rewrite it, at the very least splitting
645      out the Windows and non-Windows stuff into two completely
646      different functions; but instead I'm trying to make it go away
647      entirely, using the Lisp definition in process.el.  What's left
648      is to fix up the routines in event-msw.c (and in event-Xt.c and
649      event-tty.c) to allow for stream devices to be handled correctly.
650      There isn't much to do, in fact, and I'll fix it shortly.  That
651      way, the Lisp definition can be used non-interactively too. */
652 #if !defined (NO_SUBPROCESSES) && !defined (WIN32_NATIVE)
653   /* Close Emacs's descriptors that this process should not have.  */
654   close_process_descs ();
655 #endif /* not NO_SUBPROCESSES */
656 #ifndef WIN32_NATIVE
657   close_load_descs ();
658 #endif
659
660   /* Note that use of alloca is always safe here.  It's obvious for systems
661      that do not have true vfork or that have true (stack) alloca.
662      If using vfork and C_ALLOCA it is safe because that changes
663      the superior's static variables as if the superior had done alloca
664      and will be cleaned up in the usual way.  */
665   {
666     REGISTER int i;
667
668     i = strlen (current_dir);
669     pwd = alloca_array (char, i + 6);
670     memcpy (pwd, "PWD=", 4);
671     memcpy (pwd + 4, current_dir, i);
672     i += 4;
673     if (!IS_DIRECTORY_SEP (pwd[i - 1]))
674       pwd[i++] = DIRECTORY_SEP;
675     pwd[i] = 0;
676
677     /* We can't signal an Elisp error here; we're in a vfork.  Since
678        the callers check the current directory before forking, this
679        should only return an error if the directory's permissions
680        are changed between the check and this chdir, but we should
681        at least check.  */
682     if (chdir (pwd + 4) < 0)
683       {
684         /* Don't report the chdir error, or ange-ftp.el doesn't work. */
685         /* (FSFmacs does _exit (errno) here.) */
686         pwd = 0;
687       }
688     else
689       {
690         /* Strip trailing "/".  Cretinous *[]&@$#^%@#$% Un*x */
691         /* leave "//" (from FSF) */
692         while (i > 6 && IS_DIRECTORY_SEP (pwd[i - 1]))
693           pwd[--i] = 0;
694       }
695   }
696
697   /* Set `env' to a vector of the strings in Vprocess_environment.  */
698   /* + 2 to include PWD and terminating 0.  */
699   env = alloca_array (char *, XINT (Flength (Vprocess_environment)) + 2);
700   {
701     REGISTER Lisp_Object tail;
702     char **new_env = env;
703
704     /* If we have a PWD envvar and we know the real current directory,
705        pass one down, but with corrected value.  */
706     if (pwd && getenv ("PWD"))
707       *new_env++ = pwd;
708
709     /* Copy the Vprocess_environment strings into new_env.  */
710     for (tail = Vprocess_environment;
711          CONSP (tail) && STRINGP (XCAR (tail));
712          tail = XCDR (tail))
713     {
714       char **ep = env;
715       char *envvar_external;
716
717       TO_EXTERNAL_FORMAT (LISP_STRING, XCAR (tail),
718                           C_STRING_ALLOCA, envvar_external,
719                           Qfile_name);
720
721       /* See if envvar_external duplicates any string already in the env.
722          If so, don't put it in.
723          When an env var has multiple definitions,
724          we keep the definition that comes first in process-environment.  */
725       for (; ep != new_env; ep++)
726         {
727           char *p = *ep, *q = envvar_external;
728           while (1)
729             {
730               if (*q == 0)
731                 /* The string is malformed; might as well drop it.  */
732                 goto duplicate;
733               if (*q != *p)
734                 break;
735               if (*q == '=')
736                 goto duplicate;
737               p++, q++;
738             }
739         }
740       if (pwd && !strncmp ("PWD=", envvar_external, 4))
741         {
742           *new_env++ = pwd;
743           pwd = 0;
744         }
745       else
746         *new_env++ = envvar_external;
747
748     duplicate: ;
749     }
750     *new_env = 0;
751   }
752
753 #ifdef WIN32_NATIVE
754   prepare_standard_handles (in, out, err, handles);
755   set_process_dir (current_dir);
756 #else  /* not WIN32_NATIVE */
757   /* Make sure that in, out, and err are not actually already in
758      descriptors zero, one, or two; this could happen if Emacs is
759      started with its standard in, out, or error closed, as might
760      happen under X.  */
761   in  = relocate_fd (in,  3);
762   out = relocate_fd (out, 3);
763   err = relocate_fd (err, 3);
764
765   /* Set the standard input/output channels of the new process.  */
766   close (STDIN_FILENO);
767   close (STDOUT_FILENO);
768   close (STDERR_FILENO);
769
770   dup2 (in,  STDIN_FILENO);
771   dup2 (out, STDOUT_FILENO);
772   dup2 (err, STDERR_FILENO);
773
774   close (in);
775   close (out);
776   close (err);
777
778   /* Close non-process-related file descriptors. It would be cleaner to
779      close just the ones that need to be, but the following brute
780      force approach is certainly effective, and not too slow. */
781
782   {
783     int fd;
784
785     for (fd = 3; fd < MAXDESC; fd++)
786       close (fd);
787   }
788 #endif /* not WIN32_NATIVE */
789
790 #ifdef vipc
791   something missing here;
792 #endif /* vipc */
793
794 #ifdef WIN32_NATIVE
795   /* Spawn the child.  (See ntproc.c:Spawnve).  */
796   cpid = spawnve (_P_NOWAIT, new_argv[0], (const char* const*)new_argv,
797                   (const char* const*)env);
798   if (cpid == -1)
799     /* An error occurred while trying to spawn the process.  */
800     report_file_error ("Spawning child process", Qnil);
801   reset_standard_handles (in, out, err, handles);
802   return cpid;
803 #else /* not WIN32_NATIVE */
804   /* execvp does not accept an environment arg so the only way
805      to pass this environment is to set environ.  Our caller
806      is responsible for restoring the ambient value of environ.  */
807   environ = env;
808   execvp (new_argv[0], new_argv);
809
810   stdout_out ("Can't exec program %s\n", new_argv[0]);
811   _exit (1);
812 #endif /* not WIN32_NATIVE */
813 }
814
815 static int
816 getenv_internal (const Bufbyte *var,
817                  Bytecount varlen,
818                  Bufbyte **value,
819                  Bytecount *valuelen)
820 {
821   Lisp_Object scan;
822
823   for (scan = Vprocess_environment; CONSP (scan); scan = XCDR (scan))
824     {
825       Lisp_Object entry = XCAR (scan);
826
827       if (STRINGP (entry)
828           && XSTRING_LENGTH (entry) > varlen
829           && XSTRING_BYTE (entry, varlen) == '='
830 #ifdef WIN32_NATIVE
831           /* NT environment variables are case insensitive.  */
832           && ! memicmp (XSTRING_DATA (entry), var, varlen)
833 #else  /* not WIN32_NATIVE */
834           && ! memcmp (XSTRING_DATA (entry), var, varlen)
835 #endif /* not WIN32_NATIVE */
836           )
837         {
838           *value    = XSTRING_DATA   (entry) + (varlen + 1);
839           *valuelen = XSTRING_LENGTH (entry) - (varlen + 1);
840           return 1;
841         }
842     }
843
844   return 0;
845 }
846
847 DEFUN ("getenv", Fgetenv, 1, 2, "sEnvironment variable: \np", /*
848 Return the value of environment variable VAR, as a string.
849 VAR is a string, the name of the variable.
850 When invoked interactively, prints the value in the echo area.
851 */
852        (var, interactivep))
853 {
854   Bufbyte *value;
855   Bytecount valuelen;
856   Lisp_Object v = Qnil;
857   struct gcpro gcpro1;
858
859   CHECK_STRING (var);
860   GCPRO1 (v);
861   if (getenv_internal (XSTRING_DATA (var), XSTRING_LENGTH (var),
862                        &value, &valuelen))
863     v = make_string (value, valuelen);
864   if (!NILP (interactivep))
865     {
866       if (NILP (v))
867         message ("%s not defined in environment", XSTRING_DATA (var));
868       else
869         /* #### Should use Fprin1_to_string or Fprin1 to handle string
870            containing quotes correctly.  */
871         message ("\"%s\"", value);
872     }
873   RETURN_UNGCPRO (v);
874 }
875
876 /* A version of getenv that consults process_environment, easily
877    callable from C.  */
878 char *
879 egetenv (const char *var)
880 {
881   /* This cannot GC -- 7-28-00 ben */
882   Bufbyte *value;
883   Bytecount valuelen;
884
885   if (getenv_internal ((const Bufbyte *) var, strlen (var), &value, &valuelen))
886     return (char *) value;
887   else
888     return 0;
889 }
890
891 \f
892 void
893 init_callproc (void)
894 {
895   /* This function can GC */
896
897   {
898     /* jwz: always initialize Vprocess_environment, so that egetenv()
899        works in temacs. */
900     char **envp;
901     Vprocess_environment = Qnil;
902     for (envp = environ; envp && *envp; envp++)
903       Vprocess_environment =
904         Fcons (build_ext_string (*envp, Qfile_name), Vprocess_environment);
905   }
906
907   {
908     /* Initialize shell-file-name from environment variables or best guess. */
909 #ifdef WIN32_NATIVE
910     const char *shell = egetenv ("SHELL");
911     if (!shell) shell = egetenv ("COMSPEC");
912     /* Should never happen! */
913     if (!shell) shell = (GetVersion () & 0x80000000 ? "command" : "cmd");
914 #else /* not WIN32_NATIVE */
915     const char *shell = egetenv ("SHELL");
916     if (!shell) shell = "/bin/sh";
917 #endif
918
919 #if 0 /* defined (WIN32_NATIVE) */
920     /* BAD BAD BAD.  We do not wanting to be passing an XEmacs-created
921        SHELL var down to some inferior Cygwin process, which might get
922        screwed up.
923          
924        There are a few broken apps (eterm/term.el, eterm/tshell.el,
925        os-utils/terminal.el, texinfo/tex-mode.el) where this will
926        cause problems.  Those broken apps don't look at
927        shell-file-name, instead just at explicit-shell-file-name,
928        ESHELL and SHELL.  They are apparently attempting to borrow
929        what `M-x shell' uses, but that latter also looks at
930        shell-file-name.  What we want is for all of these apps to look
931        at shell-file-name, so that the user can change the value of
932        shell-file-name and everything will work out hunky-dorey.
933        */
934     
935     if (!egetenv ("SHELL"))
936       {
937         CBufbyte *faux_var = alloca_array (CBufbyte, 7 + strlen (shell));
938         sprintf (faux_var, "SHELL=%s", shell);
939         Vprocess_environment = Fcons (build_string (faux_var),
940                                       Vprocess_environment);
941       }
942 #endif /* 0 */
943
944     Vshell_file_name = build_string (shell);
945   }
946 }
947
948 #if 0
949 void
950 set_process_environment (void)
951 {
952   REGISTER char **envp;
953
954   Vprocess_environment = Qnil;
955 #ifndef CANNOT_DUMP
956   if (initialized)
957 #endif
958     for (envp = environ; *envp; envp++)
959       Vprocess_environment = Fcons (build_string (*envp),
960                                     Vprocess_environment);
961 }
962 #endif /* unused */
963
964 void
965 syms_of_callproc (void)
966 {
967   DEFSUBR (Fold_call_process_internal);
968   DEFSUBR (Fgetenv);
969 }
970
971 void
972 vars_of_callproc (void)
973 {
974   /* This function can GC */
975 #ifdef WIN32_NATIVE
976   DEFVAR_LISP ("binary-process-input", &Vbinary_process_input /*
977 *If non-nil then new subprocesses are assumed to take binary input.
978 */ );
979   Vbinary_process_input = Qnil;
980
981   DEFVAR_LISP ("binary-process-output", &Vbinary_process_output /*
982 *If non-nil then new subprocesses are assumed to produce binary output.
983 */ );
984   Vbinary_process_output = Qnil;
985 #endif /* WIN32_NATIVE */
986
987   DEFVAR_LISP ("shell-file-name", &Vshell_file_name /*
988 *File name to load inferior shells from.
989 Initialized from the SHELL environment variable.
990 */ );
991
992   DEFVAR_LISP ("process-environment", &Vprocess_environment /*
993 List of environment variables for subprocesses to inherit.
994 Each element should be a string of the form ENVVARNAME=VALUE.
995 The environment which Emacs inherits is placed in this variable
996 when Emacs starts.
997 */ );
998
999   Vlisp_EXEC_SUFFIXES = build_string (EXEC_SUFFIXES);
1000   staticpro (&Vlisp_EXEC_SUFFIXES);
1001 }