(relocate_fd): Avoid `min'/`max' as variable names.
[bpt/emacs.git] / src / callproc.c
index 5b321f1..bc02c63 100644 (file)
@@ -15,7 +15,8 @@ GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with GNU Emacs; see the file COPYING.  If not, write to
-the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
+the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.  */
 
 
 #include <signal.h>
@@ -46,7 +47,7 @@ extern char *strerror ();
 #include <windows.h>
 #include <stdlib.h>    /* for proper declaration of environ */
 #include <fcntl.h>
-#include "nt.h"
+#include "w32.h"
 #define _P_NOWAIT 1    /* from process.h */
 #endif
 
@@ -70,6 +71,8 @@ extern char *strerror ();
 #include "lisp.h"
 #include "commands.h"
 #include "buffer.h"
+#include "charset.h"
+#include "coding.h"
 #include <paths.h>
 #include "process.h"
 #include "syssignal.h"
@@ -94,6 +97,7 @@ Lisp_Object Vbinary_process_output;
 
 Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
 Lisp_Object Vconfigure_info_directory;
+Lisp_Object Vtemp_file_name_pattern;
 
 Lisp_Object Vshell_file_name;
 
@@ -115,6 +119,8 @@ char *synch_process_death;
 int synch_process_retcode;
 
 extern Lisp_Object Vdoc_file_name;
+
+extern Lisp_Object Vfile_name_coding_system, Vdefault_file_name_coding_system;
 \f
 /* Clean up when exiting Fcall_process.
    On MSDOS, delete the temporary file on any kind of termination.
@@ -204,6 +210,7 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
   char *bufptr = buf;
   int bufsize = 16384;
   int count = specpdl_ptr - specpdl;
+
   register unsigned char **new_argv
     = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
   struct buffer *old = current_buffer;
@@ -217,6 +224,9 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
 #if 0
   int mask;
 #endif
+  struct coding_system process_coding; /* coding-system of process output */
+  struct coding_system argument_coding;        /* coding-system of arguments */
+
   CHECK_STRING (args[0], 0);
 
   error_file = Qt;
@@ -227,6 +237,100 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
     error ("Operating system cannot handle asynchronous subprocesses");
 #endif /* subprocesses */
 
+  /* Decide the coding-system for giving arguments and reading process
+     output.  */
+  {
+    Lisp_Object val, *args2;
+    /* Qt denotes we have not yet called Ffind_operation_coding_system.  */
+    Lisp_Object coding_systems = Qt;
+    int i;
+
+    /* If arguments are supplied, we may have to encode them.  */
+    if (nargs >= 5)
+      {
+       int must_encode = 0;
+
+       for (i = 4; i < nargs; i++)
+         if (STRING_MULTIBYTE (args[i]))
+           must_encode = 1;
+
+       if (!NILP (Vcoding_system_for_write))
+         val = Vcoding_system_for_write;
+       else if (! must_encode)
+         val = Qnil;
+       else
+         {
+           args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
+           args2[0] = Qcall_process;
+           for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
+           coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
+           if (CONSP (coding_systems))
+             val = XCONS (coding_systems)->cdr;
+           else if (CONSP (Vdefault_process_coding_system))
+             val = XCONS (Vdefault_process_coding_system)->cdr;
+           else
+             val = Qnil;
+         }
+       setup_coding_system (Fcheck_coding_system (val), &argument_coding);
+      }
+
+    /* If BUFFER is nil, we must read process output once and then
+       discard it, so setup coding system but with nil.  If BUFFER is
+       an integer, we can discard it without reading.  */
+    if (nargs < 3 || NILP (args[2]))
+      setup_coding_system (Qnil, &process_coding);
+    else if (!INTEGERP (args[2]))
+      {
+       val = Qnil;
+       if (!NILP (Vcoding_system_for_read))
+         val = Vcoding_system_for_read;
+       else if (NILP (current_buffer->enable_multibyte_characters))
+         val = Qraw_text;
+       else
+         {
+           if (!EQ (coding_systems, Qt))
+             {
+               args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
+               args2[0] = Qcall_process;
+               for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
+               coding_systems
+                 = Ffind_operation_coding_system (nargs + 1, args2);
+             }
+           if (CONSP (coding_systems))
+             val = XCONS (coding_systems)->car;
+           else if (CONSP (Vdefault_process_coding_system))
+             val = XCONS (Vdefault_process_coding_system)->car;
+           else
+             val = Qnil;
+         }
+       setup_coding_system (Fcheck_coding_system (val), &process_coding);
+#ifdef MSDOS
+       /* On MSDOS, if the user did not ask for binary, treat it as
+          "text" which means doing CRLF conversion.  Otherwise, leave
+          the EOLs alone.
+
+          Note that ``binary'' here only means whether EOLs should or
+          should not be converted, since that's what Vbinary_process_XXXput
+          meant in the days before the coding systems were introduced.
+
+          For other conversions, the caller should set coding-system
+          variables explicitly, or rely on auto-detection.  */
+
+       /* FIXME: this probably should be moved into the guts of
+          `Ffind_operation_coding_system' for the case of `call-process'.  */
+       if (NILP (Vbinary_process_output))
+         {
+           process_coding.eol_type = CODING_EOL_CRLF;
+           if (process_coding.type == coding_type_no_conversion)
+             /* FIXME: should we set type to undecided?  */
+             process_coding.type = coding_type_emacs_mule;
+         }
+       else
+         process_coding.eol_type = CODING_EOL_LF;
+#endif
+      }
+  }
+
   if (nargs >= 2 && ! NILP (args[1]))
     {
       infile = Fexpand_file_name (args[1], current_buffer->directory);
@@ -244,8 +348,16 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
       if (CONSP (buffer))
        {
          if (CONSP (XCONS (buffer)->cdr))
-           error_file = Fexpand_file_name (XCONS (XCONS (buffer)->cdr)->car,
-                                           Qnil);
+           {
+             Lisp_Object stderr_file;
+             stderr_file = XCONS (XCONS (buffer)->cdr)->car;
+
+             if (NILP (stderr_file) || EQ (Qt, stderr_file))
+               error_file = stderr_file;
+             else
+               error_file = Fexpand_file_name (stderr_file, Qnil);
+           }
+
          buffer = XCONS (buffer)->car;
        }
 
@@ -255,7 +367,7 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
        {
          Lisp_Object spec_buffer;
          spec_buffer = buffer;
-         buffer = Fget_buffer (buffer);
+         buffer = Fget_buffer_create (buffer);
          /* Mention the buffer name for a better error message.  */
          if (NILP (buffer))
            CHECK_BUFFER (spec_buffer, 2);
@@ -313,23 +425,47 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
       report_file_error ("Searching for program", Fcons (args[0], Qnil));
     }
   new_argv[0] = XSTRING (path)->data;
-  {
-    register int i;
-    for (i = 4; i < nargs; i++)
-      {
-       CHECK_STRING (args[i], i);
-       new_argv[i - 3] = XSTRING (args[i])->data;
-      }
-    new_argv[i - 3] = 0;
-  }
+  if (nargs > 4)
+    {
+      register int i;
 
-#ifdef MSDOS /* MW, July 1993 */
-  /* These vars record information from process termination.
-     Clear them now before process can possibly terminate,
-     to avoid timing error if process terminates soon.  */
-  synch_process_death = 0;
-  synch_process_retcode = 0;
+      for (i = 4; i < nargs; i++) CHECK_STRING (args[i], i);
+
+      if (! CODING_REQUIRE_ENCODING (&argument_coding))
+       {
+         for (i = 4; i < nargs; i++)
+           new_argv[i - 3] = XSTRING (args[i])->data;
+       }
+      else
+       {
+         /* We must encode the arguments.  */
+         struct gcpro gcpro1, gcpro2, gcpro3;
 
+         GCPRO3 (infile, buffer, current_dir);
+         for (i = 4; i < nargs; i++)
+           {
+             int size = encoding_buffer_size (&argument_coding,
+                                              STRING_BYTES (XSTRING (args[i])));
+             unsigned char *dummy1 = (unsigned char *) alloca (size);
+             int dummy;
+
+             /* The Irix 4.0 compiler barfs if we eliminate dummy.  */
+             new_argv[i - 3] = dummy1;
+             encode_coding (&argument_coding,
+                            XSTRING (args[i])->data,
+                            new_argv[i - 3],
+                            STRING_BYTES (XSTRING (args[i])),
+                            size);
+             new_argv[i - 3][argument_coding.produced] = 0;
+           }
+         UNGCPRO;
+       }
+      new_argv[nargs - 3] = 0;
+    }
+  else
+    new_argv[1] = 0;
+
+#ifdef MSDOS /* MW, July 1993 */
   if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
     strcpy (tempfile = alloca (strlen (outf) + 20), outf);
   else
@@ -347,20 +483,19 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
   if (outfilefd < 0)
     {
       close (filefd);
-      report_file_error ("Opening process output file", Fcons (tempfile, Qnil));
+      report_file_error ("Opening process output file",
+                        Fcons (build_string (tempfile), Qnil));
     }
-#endif
+  fd[0] = filefd;
+  fd[1] = outfilefd;
+#endif /* MSDOS */
 
   if (INTEGERP (buffer))
     fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
   else
     {
 #ifndef MSDOS
-#ifdef WINDOWSNT
-      pipe_with_inherited_out (fd);
-#else  /* not WINDOWSNT */
       pipe (fd);
-#endif /* not WINDOWSNT */
 #endif
 #if 0
       /* Replaced by close_process_descs */
@@ -388,21 +523,6 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
     synch_process_death = 0;
     synch_process_retcode = 0;
 
-#ifdef MSDOS /* MW, July 1993 */
-    /* ??? Someone who knows MSDOG needs to check whether this properly
-       closes all descriptors that it opens.  */
-    pid = run_msdos_command (new_argv, current_dir, filefd, outfilefd);
-    close (outfilefd);
-    fd1 = -1; /* No harm in closing that one!  */
-    fd[0] = open (tempfile, NILP (Vbinary_process_output) ? O_TEXT : O_BINARY);
-    if (fd[0] < 0)
-      {
-       unlink (tempfile);
-       close (filefd);
-       report_file_error ("Cannot re-open temporary file", Qnil);
-      }
-#else /* not MSDOS */
-
     if (NILP (error_file))
       fd_error = open (NULL_DEVICE, O_WRONLY);
     else if (STRINGP (error_file))
@@ -419,14 +539,55 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
     if (fd_error < 0)
       {
        close (filefd);
-       close (fd[0]);
+       if (fd[0] != filefd)
+         close (fd[0]);
        if (fd1 >= 0)
          close (fd1);
-       report_file_error ("Cannot open", error_file);
+#ifdef MSDOS
+       unlink (tempfile);
+#endif
+       report_file_error ("Cannot redirect stderr",
+                          Fcons ((NILP (error_file)
+                                  ? build_string (NULL_DEVICE) : error_file),
+                                 Qnil));
       }
 
+    current_dir = ENCODE_FILE (current_dir);
+
+#ifdef MSDOS /* MW, July 1993 */
+    /* ??? Someone who knows MSDOG needs to check whether this properly
+       closes all descriptors that it opens.
+
+       Note that run_msdos_command() actually returns the child process
+       exit status, not its PID, so we assign it to `synch_process_retcode'
+       below.  */
+    pid = run_msdos_command (new_argv, current_dir,
+                            filefd, outfilefd, fd_error);
+
+    /* Record that the synchronous process exited and note its
+       termination status.  */
+    synch_process_alive = 0;
+    synch_process_retcode = pid;
+    if (synch_process_retcode < 0)  /* means it couldn't be exec'ed */
+      synch_process_death = strerror (errno);
+
+    close (outfilefd);
+    if (fd_error != outfilefd)
+      close (fd_error);
+    fd1 = -1; /* No harm in closing that one!  */
+    /* Since CRLF is converted to LF within `decode_coding', we can
+       always open a file with binary mode.  */
+    fd[0] = open (tempfile, O_BINARY);
+    if (fd[0] < 0)
+      {
+       unlink (tempfile);
+       close (filefd);
+       report_file_error ("Cannot re-open temporary file", Qnil);
+      }
+#else /* not MSDOS */
 #ifdef WINDOWSNT
-    pid = child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
+    pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
+                      0, current_dir);
 #else  /* not WINDOWSNT */
     pid = vfork ();
 
@@ -434,22 +595,30 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
       {
        if (fd[0] >= 0)
          close (fd[0]);
-#ifdef USG
+#ifdef HAVE_SETSID
+        setsid ();
+#endif
+#if defined (USG) && !defined (BSD_PGRPS)
         setpgrp ();
 #else
         setpgrp (pid, pid);
 #endif /* USG */
-       child_setup (filefd, fd1, fd_error, new_argv, 0, current_dir);
+       child_setup (filefd, fd1, fd_error, (char **) new_argv,
+                    0, current_dir);
       }
-#endif /* not MSDOS */
 #endif /* not WINDOWSNT */
 
+    /* The MSDOS case did this already.  */
+    if (fd_error >= 0)
+      close (fd_error);
+#endif /* not MSDOS */
+
     environ = save_environ;
 
     /* Close most of our fd's, but not fd[0]
        since we will use that to read input from.  */
     close (filefd);
-    if (fd1 >= 0)
+    if (fd1 >= 0 && fd1 != fd_error)
       close (fd1);
   }
 
@@ -496,22 +665,71 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
     register int nread;
     int first = 1;
     int total_read = 0;
+    int carryover = 0;
 
-    while ((nread = read (fd[0], bufptr, bufsize)) != 0)
+    while (1)
       {
-       if (nread < 0)
+       /* Repeatedly read until we've filled as much as possible
+          of the buffer size we have.  But don't read
+          less than 1024--save that for the next bufferful.  */
+
+       nread = carryover;
+       while (nread < bufsize - 1024)
          {
-#if defined (__osf__) && defined (__alpha)
-           continue;           /* Work around bug in DEC OSF/1 V3.0.  */
-#else
-           break;
-#endif
+           int this_read = read (fd[0], bufptr + nread, bufsize - nread);
+
+           if (this_read < 0)
+             goto give_up;
+
+           if (this_read == 0)
+             goto give_up_1;
+
+           nread += this_read;
          }
+
+      give_up_1:
+
+       /* Now NREAD is the total amount of data in the buffer.  */
+       if (nread == carryover)
+         /* Here, just tell decode_coding that we are processing the
+             last block.  We break the loop after decoding.  */
+         process_coding.mode |= CODING_MODE_LAST_BLOCK;
+
        immediate_quit = 0;
-       total_read += nread;
+       total_read += nread - carryover;
        
        if (!NILP (buffer))
-         insert (bufptr, nread);
+         {
+           if (process_coding.type == coding_type_no_conversion)
+             insert (bufptr, nread);
+           else
+             {                 /* We have to decode the input.  */
+               int size = decoding_buffer_size (&process_coding, nread);
+               char *decoding_buf = get_conversion_buffer (size);
+
+               decode_coding (&process_coding, bufptr, decoding_buf,
+                              nread, size);
+               if (process_coding.produced > 0)
+                 insert (decoding_buf, process_coding.produced);
+               carryover = nread - process_coding.consumed;
+               if (carryover > 0)
+                 {
+                   /* As CARRYOVER should not be that large, we had
+                      better avoid overhead of bcopy.  */
+                   char *p = bufptr + process_coding.consumed;
+                   char *pend = p + carryover;
+                   char *dst = bufptr;
+
+                   while (p < pend) *dst++ = *p++;
+                 }
+             }
+         }
+       if (process_coding.mode & CODING_MODE_LAST_BLOCK)
+         {
+           if (carryover > 0)
+             insert (bufptr, carryover);
+           break;
+         }
 
        /* Make the buffer bigger as we continue to read more data,
           but not past 64k.  */
@@ -531,8 +749,11 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
        immediate_quit = 1;
        QUIT;
       }
+  give_up: ;
   }
 
+  Vlast_coding_system_used = process_coding.symbol;
+
   /* Wait for it to terminate, unless it already has.  */
   wait_for_termination (pid);
 
@@ -588,13 +809,13 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
   struct gcpro gcpro1;
   Lisp_Object filename_string;
   register Lisp_Object start, end;
-#ifdef DOS_NT
-  char *tempfile;
-#else
-  char tempfile[20];
-#endif
   int count = specpdl_ptr - specpdl;
+  /* Qt denotes we have not yet called Ffind_operation_coding_system.  */
+  Lisp_Object coding_systems = Qt;
+  Lisp_Object val, *args2;
+  int i;
 #ifdef DOS_NT
+  char *tempfile;
   char *outf = '\0';
 
   if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
@@ -604,17 +825,21 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
       tempfile = alloca (20);
       *tempfile = '\0';
     }
-  dostounix_filename (tempfile);
-  if (tempfile[strlen (tempfile) - 1] != '/')
+  if (!IS_DIRECTORY_SEP (tempfile[strlen (tempfile) - 1]))
     strcat (tempfile, "/");
-  strcat (tempfile, "detmp.XXX");
-#else /* not DOS_NT */
-
-#ifdef VMS
-  strcpy (tempfile, "tmp:emacsXXXXXX.");
+  if ('/' == DIRECTORY_SEP)
+    dostounix_filename (tempfile);
+  else
+    unixtodos_filename (tempfile);
+#ifdef WINDOWSNT
+  strcat (tempfile, "emXXXXXX");
 #else
-  strcpy (tempfile, "/tmp/emacsXXXXXX");
+  strcat (tempfile, "detmp.XXX");
 #endif
+#else /* not DOS_NT */
+  char *tempfile = (char *) alloca (STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
+  bcopy (XSTRING (Vtemp_file_name_pattern)->data, tempfile,
+        STRING_BYTES (XSTRING (Vtemp_file_name_pattern)) + 1);
 #endif /* not DOS_NT */
 
   mktemp (tempfile);
@@ -623,13 +848,59 @@ If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
   GCPRO1 (filename_string);
   start = args[0];
   end = args[1];
+  /* Decide coding-system of the contents of the temporary file.  */
 #ifdef DOS_NT
+  /* This is to cause find-buffer-file-type-coding-system (see
+     dos-w32.el) to choose correct EOL translation for write-region.  */
   specbind (Qbuffer_file_type, Vbinary_process_input);
-  Fwrite_region (start, end, filename_string, Qnil, Qlambda);
-  unbind_to (count, Qnil);
-#else  /* not DOS_NT */
-  Fwrite_region (start, end, filename_string, Qnil, Qlambda);
-#endif /* not DOS_NT */
+#endif
+  if (!NILP (Vcoding_system_for_write))
+    val = Vcoding_system_for_write;
+  else if (NILP (current_buffer->enable_multibyte_characters))
+    val = Qnil;
+  else
+    {
+      args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
+      args2[0] = Qcall_process_region;
+      for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
+      coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
+      if (CONSP (coding_systems))
+       val = XCONS (coding_systems)->cdr;
+      else if (CONSP (Vdefault_process_coding_system))
+       val = XCONS (Vdefault_process_coding_system)->cdr;
+      else
+       val = Qnil;
+    }
+
+#ifdef DOS_NT
+  /* binary-process-input tells whether the buffer needs to be
+     written with EOL conversions, but it doesn't say anything
+     about the rest of text encoding.  It takes effect whenever
+     the coding system doesn't otherwise specify what to do for
+     eol conversion.  */
+  if (NILP (val))
+    {
+      if (! NILP (Vbinary_process_input))
+       val = intern ("undecided-unix");
+      else
+       val = intern ("undecided-dos");
+    }
+  else if (SYMBOLP (val) && NILP (Vcoding_system_for_write))
+    {
+      Lisp_Object eolval;
+      eolval = Fget (val, Qeol_type);
+      if (VECTORP (eolval) && XVECTOR (eolval)->size > 1)
+       /* Use element 1 (CRLF conversion) for "text",
+          and element 0 (LF conversion) for "binary".  */
+       val = XVECTOR (eolval)->contents[NILP (Vbinary_process_input)];
+    }
+#endif
+
+  specbind (intern ("coding-system-for-write"), val);
+  Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
+
+  /* Note that Fcall_process takes care of binding 
+     coding-system-for-read.  */
 
   record_unwind_protect (delete_temp_file, filename_string);
 
@@ -677,7 +948,7 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
   char *pwd_var;
 #ifdef WINDOWSNT
   int cpid;
-  HANDLE handles[4];
+  HANDLE handles[3];
 #endif /* WINDOWSNT */
 
   int pid = getpid ();
@@ -706,7 +977,7 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
     register char *temp;
     register int i;
 
-    i = XSTRING (current_dir)->size;
+    i = STRING_BYTES (XSTRING (current_dir));
     pwd_var = (char *) alloca (i + 6);
     temp = pwd_var + 4;
     bcopy ("PWD=", pwd_var, 4);
@@ -714,6 +985,7 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
     if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
     temp[i] = 0;
 
+#ifndef WINDOWSNT
     /* We can't signal an Elisp error here; we're in a vfork.  Since
        the callers check the current directory before forking, this
        should only return an error if the directory's permissions
@@ -721,6 +993,7 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
        at least check.  */
     if (chdir (temp) < 0)
       _exit (errno);
+#endif
 
     /* Strip trailing slashes for PWD, but leave "/" and "//" alone.  */
     while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
@@ -780,19 +1053,31 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
   }
 #ifdef WINDOWSNT
   prepare_standard_handles (in, out, err, handles);
+  set_process_dir (XSTRING (current_dir)->data);
 #else  /* not WINDOWSNT */
   /* Make sure that in, out, and err are not actually already in
      descriptors zero, one, or two; this could happen if Emacs is
      started with its standard in, out, or error closed, as might
      happen under X.  */
-  in = relocate_fd (in, 3);
-  if (out == err)
-    err = out = relocate_fd (out, 3);
-  else
-    {
+  {
+    int oin = in, oout = out;
+
+    /* We have to avoid relocating the same descriptor twice!  */
+
+    in = relocate_fd (in, 3);
+
+    if (out == oin)
+      out = in;
+    else
       out = relocate_fd (out, 3);
+
+    if (err == oin)
+      err = in;
+    else if (err == oout)
+      err = out;
+    else
       err = relocate_fd (err, 3);
-    }
+  }
 
   close (0);
   close (1);
@@ -806,7 +1091,7 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
   close (err);
 #endif /* not WINDOWSNT */
 
-#ifdef USG
+#if defined(USG) && !defined(BSD_PGRPS)
 #ifndef SETPGRP_RELEASES_CTTY
   setpgrp ();                  /* No arguments but equivalent in this case */
 #endif
@@ -823,10 +1108,10 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
 #ifdef WINDOWSNT
   /* Spawn the child.  (See ntproc.c:Spawnve).  */
   cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
+  reset_standard_handles (in, out, err, handles);
   if (cpid == -1)
     /* An error occurred while trying to spawn the process.  */
     report_file_error ("Spawning child process", Qnil);
-  reset_standard_handles (in, out, err, handles);
   return cpid;
 #else /* not WINDOWSNT */
   /* execvp does not accept an environment arg so the only way
@@ -835,7 +1120,7 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
   environ = env;
   execvp (new_argv[0], new_argv);
 
-  write (1, "Can't exec program: ", 26);
+  write (1, "Can't exec program: ", 20);
   write (1, new_argv[0], strlen (new_argv[0]));
   write (1, "\n", 1);
   _exit (1);
@@ -843,13 +1128,13 @@ child_setup (in, out, err, new_argv, set_pgrp, current_dir)
 #endif /* not MSDOS */
 }
 
-/* Move the file descriptor FD so that its number is not less than MIN.
+/* Move the file descriptor FD so that its number is not less than MINFD.
    If the file descriptor is moved at all, the original is freed.  */
 int
-relocate_fd (fd, min)
-     int fd, min;
+relocate_fd (fd, minfd)
+     int fd, minfd;
 {
-  if (fd >= min)
+  if (fd >= minfd)
     return fd;
   else
     {
@@ -866,7 +1151,7 @@ relocate_fd (fd, min)
        }
       /* Note that we hold the original FD open while we recurse,
         to guarantee we'll get a new FD if we need it.  */
-      new = relocate_fd (new, min);
+      new = relocate_fd (new, minfd);
       close (fd);
       return new;
     }
@@ -887,7 +1172,7 @@ getenv_internal (var, varlen, value, valuelen)
 
       entry = XCONS (scan)->car;
       if (STRINGP (entry)
-         && XSTRING (entry)->size > varlen
+         && STRING_BYTES (XSTRING (entry)) > varlen
          && XSTRING (entry)->data[varlen] == '='
 #ifdef WINDOWSNT
          /* NT environment variables are case insensitive.  */
@@ -898,7 +1183,7 @@ getenv_internal (var, varlen, value, valuelen)
          )
        {
          *value    = (char *) XSTRING (entry)->data + (varlen + 1);
-         *valuelen = XSTRING (entry)->size - (varlen + 1);
+         *valuelen = STRING_BYTES (XSTRING (entry)) - (varlen + 1);
          return 1;
        }
     }
@@ -917,7 +1202,7 @@ This function consults the variable ``process-environment'' for its value.")
   int valuelen;
 
   CHECK_STRING (var, 0);
-  if (getenv_internal (XSTRING (var)->data, XSTRING (var)->size,
+  if (getenv_internal (XSTRING (var)->data, STRING_BYTES (XSTRING (var)),
                       &value, &valuelen))
     return make_string (value, valuelen);
   else
@@ -962,7 +1247,7 @@ init_callproc_1 ()
   Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
 }
 
-/* This is run after init_cmdargs, so that Vinvocation_directory is valid.  */
+/* This is run after init_cmdargs, when Vinstallation_directory is valid.  */
 
 init_callproc ()
 {
@@ -984,21 +1269,20 @@ init_callproc ()
          Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
          Vexec_directory = Ffile_name_as_directory (tem);
 #endif /* not DOS_NT */
+       }
 
-         /* If we use ../lib-src, maybe use ../etc as well.
-            Do so if ../etc exists and has our DOC-... file in it.  */
-         if (data_dir == 0)
-           {
-             tem = Fexpand_file_name (build_string ("etc"),
-                                      Vinstallation_directory);
-             Vdoc_directory = Ffile_name_as_directory (tem);
-           }
+      /* Maybe use ../etc as well as ../lib-src.  */
+      if (data_dir == 0)
+       {
+         tem = Fexpand_file_name (build_string ("etc"),
+                                  Vinstallation_directory);
+         Vdoc_directory = Ffile_name_as_directory (tem);
        }
     }
 
   /* Look for the files that should be in etc.  We don't use
      Vinstallation_directory, because these files are never installed
-     in /bin near the executable, and they are never in the build
+     near the executable, and they are never in the build
      directory when that's different from the source directory.
 
      Instead, if these files are not in the nominal place, we try the
@@ -1020,23 +1304,20 @@ init_callproc ()
        }
     }
 
-  tempdir = Fdirectory_file_name (Vexec_directory);
-  if (access (XSTRING (tempdir)->data, 0) < 0)
+#ifndef CANNOT_DUMP
+  if (initialized)
+#endif
     {
-      fprintf (stderr,
-              "Warning: arch-dependent data dir (%s) does not exist.\n",
-              XSTRING (Vexec_directory)->data);
-      sleep (2);
+      tempdir = Fdirectory_file_name (Vexec_directory);
+      if (access (XSTRING (tempdir)->data, 0) < 0)
+       dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
+                    Vexec_directory);
     }
 
   tempdir = Fdirectory_file_name (Vdata_directory);
   if (access (XSTRING (tempdir)->data, 0) < 0)
-    {
-      fprintf (stderr,
-              "Warning: arch-independent data dir (%s) does not exist.\n",
-              XSTRING (Vdata_directory)->data);
-      sleep (2);
-    }
+    dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
+                Vdata_directory);
 
 #ifdef VMS
   Vshell_file_name = build_string ("*dcl*");
@@ -1044,6 +1325,20 @@ init_callproc ()
   sh = (char *) getenv ("SHELL");
   Vshell_file_name = build_string (sh ? sh : "/bin/sh");
 #endif
+
+#ifdef VMS
+  Vtemp_file_name_pattern = build_string ("tmp:emacsXXXXXX.");
+#else
+  if (getenv ("TMPDIR"))
+    {
+      char *dir = getenv ("TMPDIR");
+      Vtemp_file_name_pattern
+       = Fexpand_file_name (build_string ("emacsXXXXXX"),
+                            build_string (dir));
+    }
+  else
+    Vtemp_file_name_pattern = build_string ("/tmp/emacsXXXXXX");
+#endif
 }
 
 set_process_environment ()
@@ -1083,12 +1378,13 @@ Initialized from the SHELL environment variable.");
 Each element is a string (directory name) or nil (try default directory).");
 
   DEFVAR_LISP ("exec-directory", &Vexec_directory,
-    "Directory of architecture-dependent files that come with GNU Emacs,\n\
-especially executable programs intended for Emacs to invoke.");
+    "Directory for executables for Emacs to invoke.\n\
+More generally, this includes any architecture-dependent files\n\
+that are built and installed from the Emacs distribution.");
 
   DEFVAR_LISP ("data-directory", &Vdata_directory,
-    "Directory of architecture-independent files that come with GNU Emacs,\n\
-intended for Emacs to use.");
+    "Directory of machine-independent files that come with GNU Emacs.\n\
+These are files intended for Emacs to use while it runs.");
 
   DEFVAR_LISP ("doc-directory", &Vdoc_directory,
     "Directory containing the DOC file that comes with GNU Emacs.\n\
@@ -1101,6 +1397,11 @@ Emacs's info files; the default value for Info-default-directory-list\n\
 includes this.");
   Vconfigure_info_directory = build_string (PATH_INFO);
 
+  DEFVAR_LISP ("temp-file-name-pattern", &Vtemp_file_name_pattern,
+    "Pattern for making names for temporary files.\n\
+This is used by `call-process-region'.");
+  /* This variable is initialized in init_callproc.  */
+
   DEFVAR_LISP ("process-environment", &Vprocess_environment,
     "List of environment variables for subprocesses to inherit.\n\
 Each element should be a string of the form ENVVARNAME=VALUE.\n\