callproc.c 52 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Synchronous subprocess invocation for GNU Emacs.
2

3 4
Copyright (C) 1985-1988, 1993-1995, 1999-2014 Free Software Foundation,
Inc.
Jim Blandy's avatar
Jim Blandy committed
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
19
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
20 21


22
#include <config.h>
23
#include <errno.h>
24
#include <stdio.h>
Jim Blandy's avatar
Jim Blandy committed
25
#include <sys/types.h>
26 27
#include <unistd.h>

Jim Blandy's avatar
Jim Blandy committed
28 29 30
#include <sys/file.h>
#include <fcntl.h>

31 32
#include "lisp.h"

33 34
#ifdef WINDOWSNT
#define NOMINMAX
35
#include <sys/socket.h>	/* for fcntl */
36
#include <windows.h>
Geoff Voelker's avatar
Geoff Voelker committed
37
#include "w32.h"
38 39 40
#define _P_NOWAIT 1	/* from process.h */
#endif

41 42 43 44 45
#ifdef MSDOS	/* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
#include <sys/stat.h>
#include <sys/param.h>
#endif /* MSDOS */

Jim Blandy's avatar
Jim Blandy committed
46
#include "commands.h"
47
#include "character.h"
48
#include "buffer.h"
Kenichi Handa's avatar
Kenichi Handa committed
49
#include "ccl.h"
Karl Heuer's avatar
Karl Heuer committed
50
#include "coding.h"
Kenichi Handa's avatar
Kenichi Handa committed
51
#include "composite.h"
52
#include <epaths.h>
Jim Blandy's avatar
Jim Blandy committed
53
#include "process.h"
54
#include "syssignal.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
55
#include "systty.h"
56
#include "syswait.h"
Kim F. Storm's avatar
Kim F. Storm committed
57
#include "blockinput.h"
58 59
#include "frame.h"
#include "termhooks.h"
Jim Blandy's avatar
Jim Blandy committed
60

Eli Zaretskii's avatar
Eli Zaretskii committed
61 62 63 64
#ifdef MSDOS
#include "msdos.h"
#endif

65 66 67 68
#ifdef HAVE_NS
#include "nsterm.h"
#endif

69 70 71
/* Pattern used by call-process-region to make temp files.  */
static Lisp_Object Vtemp_file_name_pattern;

72 73 74 75
/* The next two variables are used while record-unwind-protect is in place
   during call-process for a subprocess for which record_deleted_pid has
   not yet been called.  At other times, synch_process_pid is zero and
   synch_process_tempfile's contents are irrelevant.  Doing this via static
76 77 78 79 80 81 82 83 84
   C variables is more convenient than putting them into the arguments
   of record-unwind-protect, as they need to be updated at randomish
   times in the code, and Lisp cannot always store these values as
   Emacs integers.  It's safe to use static variables here, as the
   code is never invoked reentrantly.  */

/* If nonzero, a process-ID that has not been reaped.  */
static pid_t synch_process_pid;

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
/* If a string, the name of a temp file that has not been removed.  */
#ifdef MSDOS
static Lisp_Object synch_process_tempfile;
#else
# define synch_process_tempfile make_number (0)
#endif

/* Indexes of file descriptors that need closing on call_process_kill.  */
enum
  {
    /* The subsidiary process's stdout and stderr.  stdin is handled
       separately, in either Fcall_process_region or create_temp_file.  */
    CALLPROC_STDOUT, CALLPROC_STDERR,

    /* How to read from a pipe (or substitute) from the subsidiary process.  */
    CALLPROC_PIPEREAD,

    /* A bound on the number of file descriptors.  */
    CALLPROC_FDS
  };

106
static Lisp_Object call_process (ptrdiff_t, Lisp_Object *, int, ptrdiff_t);
107

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
/* Return the current buffer's working directory, or the home
   directory if it's unreachable, as a string suitable for a system call.
   Signal an error if the result would not be an accessible directory.  */

Lisp_Object
encode_current_directory (void)
{
  Lisp_Object dir;
  struct gcpro gcpro1;

  dir = BVAR (current_buffer, directory);
  GCPRO1 (dir);

  dir = Funhandled_file_name_directory (dir);

  /* If the file name handler says that dir is unreachable, use
     a sensible default. */
  if (NILP (dir))
    dir = build_string ("~");

  dir = expand_and_dir_to_file (dir, Qnil);

130
  if (NILP (Ffile_accessible_directory_p (dir)))
131 132 133
    report_file_error ("Setting current directory",
		       BVAR (current_buffer, directory));

134
  /* Remove "/:" from dir.  */
135
  if (! NILP (Fstring_match (build_string ("^/:"), dir, Qnil)))
136 137
    dir = Fsubstring (dir, make_number (2), Qnil);

138 139
  if (STRING_MULTIBYTE (dir))
    dir = ENCODE_FILE (dir);
140
  if (! file_accessible_directory_p (dir))
141 142 143 144 145 146
    report_file_error ("Setting current directory",
		       BVAR (current_buffer, directory));

  RETURN_UNGCPRO (dir);
}

147 148 149 150 151
/* If P is reapable, record it as a deleted process and kill it.
   Do this in a critical section.  Unless PID is wedged it will be
   reaped on receipt of the first SIGCHLD after the critical section.  */

void
152
record_kill_process (struct Lisp_Process *p, Lisp_Object tempfile)
153
{
Eli Zaretskii's avatar
Eli Zaretskii committed
154
#ifndef MSDOS
155 156
  sigset_t oldset;
  block_child_signal (&oldset);
157 158 159

  if (p->alive)
    {
160
      record_deleted_pid (p->pid, tempfile);
161
      p->alive = 0;
162
      kill (- p->pid, SIGKILL);
163 164
    }

165
  unblock_child_signal (&oldset);
Eli Zaretskii's avatar
Eli Zaretskii committed
166
#endif	/* !MSDOS */
167 168
}

169 170 171 172 173 174 175
/* Clean up files, file descriptors and processes created by Fcall_process.  */

static void
delete_temp_file (Lisp_Object name)
{
  unlink (SSDATA (name));
}
176

177
static void
178
call_process_kill (void *ptr)
179
{
180 181 182 183 184
  int *callproc_fd = ptr;
  int i;
  for (i = 0; i < CALLPROC_FDS; i++)
    if (0 <= callproc_fd[i])
      emacs_close (callproc_fd[i]);
185 186 187

  if (synch_process_pid)
    {
188 189 190
      struct Lisp_Process proc;
      proc.alive = 1;
      proc.pid = synch_process_pid;
191 192
      record_kill_process (&proc, synch_process_tempfile);
      synch_process_pid = 0;
193
    }
194 195
  else if (STRINGP (synch_process_tempfile))
    delete_temp_file (synch_process_tempfile);
196 197
}

198 199
/* Clean up when exiting Fcall_process: restore the buffer, and
   kill the subsidiary process group if the process still exists.  */
200

201
static void
202
call_process_cleanup (Lisp_Object buffer)
Jim Blandy's avatar
Jim Blandy committed
203
{
204
  Fset_buffer (buffer);
205

Eli Zaretskii's avatar
Eli Zaretskii committed
206
#ifndef MSDOS
207
  if (synch_process_pid)
208
    {
209
      kill (-synch_process_pid, SIGINT);
210 211 212
      message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
      immediate_quit = 1;
      QUIT;
213 214
      wait_for_termination (synch_process_pid, 0, 1);
      synch_process_pid = 0;
215 216 217
      immediate_quit = 0;
      message1 ("Waiting for process to die...done");
    }
Eli Zaretskii's avatar
Eli Zaretskii committed
218
#endif	/* !MSDOS */
Jim Blandy's avatar
Jim Blandy committed
219 220
}

221 222 223 224 225 226
#ifdef DOS_NT
static mode_t const default_output_mode = S_IREAD | S_IWRITE;
#else
static mode_t const default_output_mode = 0666;
#endif

Paul Eggert's avatar
Paul Eggert committed
227
DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
228 229 230
       doc: /* Call PROGRAM synchronously in separate process.
The remaining arguments are optional.
The program's input comes from file INFILE (nil means `/dev/null').
231
Insert output in DESTINATION before point; t means current buffer; nil for DESTINATION
232
 means discard it; 0 means discard and don't wait; and `(:file FILE)', where
233 234
 FILE is a file name string, means that it should be written to that file
 \(if the file already exists it is overwritten).
235
DESTINATION can also have the form (REAL-BUFFER STDERR-FILE); in that case,
236 237 238 239 240 241 242 243
REAL-BUFFER says what to do with standard output, as above,
while STDERR-FILE says what to do with standard error in the child.
STDERR-FILE may be nil (discard standard error output),
t (mix it with ordinary output), or a file name string.

Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
Remaining arguments are strings passed as command arguments to PROGRAM.

244 245 246 247
If executable PROGRAM can't be found as an executable, `call-process'
signals a Lisp error.  `call-process' reports errors in execution of
the program only through its return and output.

248
If DESTINATION is 0, `call-process' returns immediately with value nil.
249 250
Otherwise it waits for PROGRAM to terminate
and returns a numeric exit status or a signal description string.
251 252
If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.

253
usage: (call-process PROGRAM &optional INFILE DESTINATION DISPLAY &rest ARGS)  */)
254
  (ptrdiff_t nargs, Lisp_Object *args)
Jim Blandy's avatar
Jim Blandy committed
255
{
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  Lisp_Object infile, encoded_infile;
  int filefd;
  struct gcpro gcpro1;
  ptrdiff_t count = SPECPDL_INDEX ();

  if (nargs >= 2 && ! NILP (args[1]))
    {
      infile = Fexpand_file_name (args[1], BVAR (current_buffer, directory));
      CHECK_STRING (infile);
    }
  else
    infile = build_string (NULL_DEVICE);

  GCPRO1 (infile);
  encoded_infile = STRING_MULTIBYTE (infile) ? ENCODE_FILE (infile) : infile;

  filefd = emacs_open (SSDATA (encoded_infile), O_RDONLY, 0);
  if (filefd < 0)
    report_file_error ("Opening process input file", infile);
  record_unwind_protect_int (close_file_unwind, filefd);
  UNGCPRO;
277
  return unbind_to (count, call_process (nargs, args, filefd, -1));
278 279 280
}

/* Like Fcall_process (NARGS, ARGS), except use FILEFD as the input file.
281 282 283 284 285

   If TEMPFILE_INDEX is nonnegative, it is the specpdl index of an
   unwinder that is intended to remove the input temporary file; in
   this case NARGS must be at least 2 and ARGS[1] is the file's name.

286 287 288
   At entry, the specpdl stack top entry must be close_file_unwind (FILEFD).  */

static Lisp_Object
289 290
call_process (ptrdiff_t nargs, Lisp_Object *args, int filefd,
	      ptrdiff_t tempfile_index)
291 292
{
  Lisp_Object buffer, current_dir, path;
293
  bool display_p;
294 295
  int fd0;
  int callproc_fd[CALLPROC_FDS];
296
  int status;
297
  ptrdiff_t i;
298 299
  ptrdiff_t count = SPECPDL_INDEX ();
  USE_SAFE_ALLOCA;
300

301
  char **new_argv;
302 303 304
  /* File to use for stderr in the child.
     t means use same as standard output.  */
  Lisp_Object error_file;
305
  Lisp_Object output_file = Qnil;
306
#ifdef MSDOS	/* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
307
  char *tempfile = NULL;
308 309
  int pid;
#else
310
  sigset_t oldset;
311
  pid_t pid;
Jim Blandy's avatar
Jim Blandy committed
312
#endif
313
  int child_errno;
314
  int fd_output, fd_error;
Karl Heuer's avatar
Karl Heuer committed
315 316
  struct coding_system process_coding; /* coding-system of process output */
  struct coding_system argument_coding;	/* coding-system of arguments */
317 318
  /* Set to the return value of Ffind_operation_coding_system.  */
  Lisp_Object coding_systems;
319 320 321 322
  bool discard_output;

  if (synch_process_pid)
    error ("call-process invoked recursively");
323 324 325

  /* Qt denotes that Ffind_operation_coding_system is not yet called.  */
  coding_systems = Qt;
Karl Heuer's avatar
Karl Heuer committed
326

327
  CHECK_STRING (args[0]);
Jim Blandy's avatar
Jim Blandy committed
328

329 330
  error_file = Qt;

331 332
#ifndef subprocesses
  /* Without asynchronous processes we cannot have BUFFER == 0.  */
333
  if (nargs >= 3
334
      && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
335 336 337
    error ("Operating system cannot handle asynchronous subprocesses");
#endif /* subprocesses */

338
  /* Decide the coding-system for giving arguments.  */
Karl Heuer's avatar
Karl Heuer committed
339 340 341 342 343 344
  {
    Lisp_Object val, *args2;

    /* If arguments are supplied, we may have to encode them.  */
    if (nargs >= 5)
      {
345
	bool must_encode = 0;
346
	Lisp_Object coding_attrs;
347

348
	for (i = 4; i < nargs; i++)
349
	  CHECK_STRING (args[i]);
350

351
	for (i = 4; i < nargs; i++)
352 353 354
	  if (STRING_MULTIBYTE (args[i]))
	    must_encode = 1;

355 356
	if (!NILP (Vcoding_system_for_write))
	  val = Vcoding_system_for_write;
357
	else if (! must_encode)
358
	  val = Qraw_text;
359
	else
Karl Heuer's avatar
Karl Heuer committed
360
	  {
361
	    SAFE_NALLOCA (args2, 1, nargs + 1);
Karl Heuer's avatar
Karl Heuer committed
362 363
	    args2[0] = Qcall_process;
	    for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
364
	    coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
365
	    val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
Karl Heuer's avatar
Karl Heuer committed
366
	  }
367
	val = complement_process_encoding_system (val);
Karl Heuer's avatar
Karl Heuer committed
368
	setup_coding_system (Fcheck_coding_system (val), &argument_coding);
369 370 371 372 373 374 375
	coding_attrs = CODING_ID_ATTRS (argument_coding.id);
	if (NILP (CODING_ATTR_ASCII_COMPAT (coding_attrs)))
	  {
	    /* We should not use an ASCII incompatible coding system.  */
	    val = raw_text_coding_system (val);
	    setup_coding_system (val, &argument_coding);
	  }
Karl Heuer's avatar
Karl Heuer committed
376 377 378
      }
  }

379 380
  if (nargs < 3)
    buffer = Qnil;
Jim Blandy's avatar
Jim Blandy committed
381
  else
382
    {
383 384
      buffer = args[2];

385 386 387
      /* If BUFFER is a list, its meaning is (BUFFER-FOR-STDOUT
	 FILE-FOR-STDERR), unless the first element is :file, in which case see
	 the next paragraph. */
388
      if (CONSP (buffer) && !EQ (XCAR (buffer), QCfile))
389
	{
390
	  if (CONSP (XCDR (buffer)))
391
	    {
392
	      Lisp_Object stderr_file;
393
	      stderr_file = XCAR (XCDR (buffer));
394 395 396 397 398 399 400

	      if (NILP (stderr_file) || EQ (Qt, stderr_file))
		error_file = stderr_file;
	      else
		error_file = Fexpand_file_name (stderr_file, Qnil);
	    }

401
	  buffer = XCAR (buffer);
402
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
403

404
      /* If the buffer is (still) a list, it might be a (:file "file") spec. */
405
      if (CONSP (buffer) && EQ (XCAR (buffer), QCfile))
406 407 408 409 410 411 412
	{
	  output_file = Fexpand_file_name (XCAR (XCDR (buffer)),
					   BVAR (current_buffer, directory));
	  CHECK_STRING (output_file);
	  buffer = Qnil;
	}

413
      if (! (NILP (buffer) || EQ (buffer, Qt) || INTEGERP (buffer)))
414
	{
415 416
	  Lisp_Object spec_buffer;
	  spec_buffer = buffer;
417
	  buffer = Fget_buffer_create (buffer);
418 419
	  /* Mention the buffer name for a better error message.  */
	  if (NILP (buffer))
420 421
	    CHECK_BUFFER (spec_buffer);
	  CHECK_BUFFER (buffer);
422 423
	}
    }
Jim Blandy's avatar
Jim Blandy committed
424

425 426 427 428 429 430 431 432 433 434 435
  /* Make sure that the child will be able to chdir to the current
     buffer's current directory, or its unhandled equivalent.  We
     can't just have the child check for an error when it does the
     chdir, since it's in a vfork.

     We have to GCPRO around this because Fexpand_file_name,
     Funhandled_file_name_directory, and Ffile_accessible_directory_p
     might call a file name handling function.  The argument list is
     protected by the caller, so all we really have to worry about is
     buffer.  */
  {
436
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
437

438
    current_dir = encode_current_directory ();
439

440
    GCPRO4 (buffer, current_dir, error_file, output_file);
441

442 443
    if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
      error_file = ENCODE_FILE (error_file);
444 445
    if (STRINGP (output_file) && STRING_MULTIBYTE (output_file))
      output_file = ENCODE_FILE (output_file);
446 447 448
    UNGCPRO;
  }

449
  display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
Jim Blandy's avatar
Jim Blandy committed
450

451 452 453 454 455 456
  for (i = 0; i < CALLPROC_FDS; i++)
    callproc_fd[i] = -1;
#ifdef MSDOS
  synch_process_tempfile = make_number (0);
#endif
  record_unwind_protect_ptr (call_process_kill, callproc_fd);
457

Jim Blandy's avatar
Jim Blandy committed
458
  /* Search for program; barf if not found.  */
459
  {
460
    struct gcpro gcpro1, gcpro2, gcpro3;
461
    int ok;
462

463
    GCPRO3 (buffer, current_dir, error_file);
464 465
    ok = openp (Vexec_path, args[0], Vexec_suffixes, &path,
		make_number (X_OK), false);
466
    UNGCPRO;
467
    if (ok < 0)
468
      report_file_error ("Searching for program", args[0]);
469
  }
470 471 472 473 474 475 476

  /* If program file name starts with /: for quoting a magic name,
     discard that.  */
  if (SBYTES (path) > 2 && SREF (path, 0) == '/'
      && SREF (path, 1) == ':')
    path = Fsubstring (path, make_number (2), Qnil);

477
  SAFE_NALLOCA (new_argv, 1, nargs < 4 ? 2 : nargs - 2);
478

479
  {
480
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
481

482
    GCPRO4 (buffer, current_dir, path, error_file);
483 484 485 486 487 488 489 490 491 492 493 494 495
    if (nargs > 4)
      {
	ptrdiff_t i;

	argument_coding.dst_multibyte = 0;
	for (i = 4; i < nargs; i++)
	  {
	    argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
	    if (CODING_REQUIRE_ENCODING (&argument_coding))
	      /* We must encode this argument.  */
	      args[i] = encode_coding_string (&argument_coding, args[i], 1);
	  }
	for (i = 4; i < nargs; i++)
496
	  new_argv[i - 3] = SSDATA (args[i]);
497 498 499 500 501 502
	new_argv[i - 3] = 0;
      }
    else
      new_argv[1] = 0;
    if (STRING_MULTIBYTE (path))
      path = ENCODE_FILE (path);
503
    new_argv[0] = SSDATA (path);
504 505
    UNGCPRO;
  }
Jim Blandy's avatar
Jim Blandy committed
506

507
  discard_output = INTEGERP (buffer) || (NILP (buffer) && NILP (output_file));
508

509 510
#ifdef MSDOS
  if (! discard_output && ! STRINGP (output_file))
511
    {
512 513 514 515
      char const *tmpdir = egetenv ("TMPDIR");
      char const *outf = tmpdir ? tmpdir : "";
      tempfile = alloca (strlen (outf) + 20);
      strcpy (tempfile, outf);
Eli Zaretskii's avatar
Eli Zaretskii committed
516
      dostounix_filename (tempfile);
517 518
      if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
	strcat (tempfile, "/");
Eli Zaretskii's avatar
Eli Zaretskii committed
519
      strcat (tempfile, "emXXXXXX");
520
      mktemp (tempfile);
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
      if (!*tempfile)
	report_file_error ("Opening process output file", Qnil);
      output_file = build_string (tempfile);
      synch_process_tempfile = output_file;
    }
#endif

  if (discard_output)
    {
      fd_output = emacs_open (NULL_DEVICE, O_WRONLY, 0);
      if (fd_output < 0)
	report_file_error ("Opening null device", Qnil);
    }
  else if (STRINGP (output_file))
    {
      fd_output = emacs_open (SSDATA (output_file),
			      O_WRONLY | O_CREAT | O_TRUNC | O_TEXT,
			      default_output_mode);
      if (fd_output < 0)
540 541
	{
	  int open_errno = errno;
542
	  output_file = DECODE_FILE (output_file);
543
	  report_file_errno ("Opening process output file",
544
			     output_file, open_errno);
545
	}
546
    }
Jim Blandy's avatar
Jim Blandy committed
547 548
  else
    {
549
      int fd[2];
550
      if (emacs_pipe (fd) != 0)
551 552 553
	report_file_error ("Creating process pipe", Qnil);
      callproc_fd[CALLPROC_PIPEREAD] = fd[0];
      fd_output = fd[1];
Jim Blandy's avatar
Jim Blandy committed
554
    }
555
  callproc_fd[CALLPROC_STDOUT] = fd_output;
Jim Blandy's avatar
Jim Blandy committed
556

557
  fd_error = fd_output;
Jim Blandy's avatar
Jim Blandy committed
558

559 560 561 562 563
  if (STRINGP (error_file) || (NILP (error_file) && !discard_output))
    {
      fd_error = emacs_open ((STRINGP (error_file)
			      ? SSDATA (error_file)
			      : NULL_DEVICE),
564 565
			     O_WRONLY | O_CREAT | O_TRUNC | O_TEXT,
			     default_output_mode);
566 567 568 569 570 571 572 573 574 575 576
      if (fd_error < 0)
	{
	  int open_errno = errno;
	  report_file_errno ("Cannot redirect stderr",
			     (STRINGP (error_file)
			      ? DECODE_FILE (error_file)
			      : build_string (NULL_DEVICE)),
			     open_errno);
	}
      callproc_fd[CALLPROC_STDERR] = fd_error;
    }
577

578
#ifdef MSDOS /* MW, July 1993 */
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
  /* Note that on MSDOS `child_setup' actually returns the child process
     exit status, not its PID, so assign it to status below.  */
  pid = child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);

  if (pid < 0)
    {
      child_errno = errno;
      unbind_to (count, Qnil);
      synchronize_system_messages_locale ();
      return
	code_convert_string_norecord (build_string (strerror (child_errno)),
				      Vlocale_coding_system, 0);
    }
  status = pid;

  for (i = 0; i < CALLPROC_FDS; i++)
    if (0 <= callproc_fd[i])
596
      {
597 598
	emacs_close (callproc_fd[i]);
	callproc_fd[i] = -1;
599
      }
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
  emacs_close (filefd);
  clear_unwind_protect (count - 1);

  if (tempfile)
    {
      /* Since CRLF is converted to LF within `decode_coding', we
	 can always open a file with binary mode.  */
      callproc_fd[CALLPROC_PIPEREAD] = emacs_open (tempfile,
						   O_RDONLY | O_BINARY, 0);
      if (callproc_fd[CALLPROC_PIPEREAD] < 0)
	{
	  int open_errno = errno;
	  report_file_errno ("Cannot re-open temporary file",
			     build_string (tempfile), open_errno);
	}
    }

Paul Eggert's avatar
Paul Eggert committed
617
#endif /* MSDOS */
618

619 620 621 622
  /* Do the unwind-protect now, even though the pid is not known, so
     that no storage allocation is done in the critical section.
     The actual PID will be filled in during the critical section.  */
  record_unwind_protect (call_process_cleanup, Fcurrent_buffer ());
Paul Eggert's avatar
Paul Eggert committed
623

624
#ifndef MSDOS
625

626
  block_input ();
627
  block_child_signal (&oldset);
628

629
#ifdef WINDOWSNT
630
  pid = child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
631
#else  /* not WINDOWSNT */
632

633 634 635 636 637 638 639 640 641 642
  /* vfork, and prevent local vars from being clobbered by the vfork.  */
  {
    Lisp_Object volatile buffer_volatile = buffer;
    Lisp_Object volatile coding_systems_volatile = coding_systems;
    Lisp_Object volatile current_dir_volatile = current_dir;
    bool volatile display_p_volatile = display_p;
    bool volatile sa_must_free_volatile = sa_must_free;
    int volatile fd_error_volatile = fd_error;
    int volatile filefd_volatile = filefd;
    ptrdiff_t volatile count_volatile = count;
643
    ptrdiff_t volatile sa_avail_volatile = sa_avail;
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    ptrdiff_t volatile sa_count_volatile = sa_count;
    char **volatile new_argv_volatile = new_argv;
    int volatile callproc_fd_volatile[CALLPROC_FDS];
    for (i = 0; i < CALLPROC_FDS; i++)
      callproc_fd_volatile[i] = callproc_fd[i];

    pid = vfork ();

    buffer = buffer_volatile;
    coding_systems = coding_systems_volatile;
    current_dir = current_dir_volatile;
    display_p = display_p_volatile;
    sa_must_free = sa_must_free_volatile;
    fd_error = fd_error_volatile;
    filefd = filefd_volatile;
    count = count_volatile;
660
    sa_avail = sa_avail_volatile;
661 662 663 664 665 666 667
    sa_count = sa_count_volatile;
    new_argv = new_argv_volatile;

    for (i = 0; i < CALLPROC_FDS; i++)
      callproc_fd[i] = callproc_fd_volatile[i];
    fd_output = callproc_fd[CALLPROC_STDOUT];
  }
668

669 670
  if (pid == 0)
    {
671
      unblock_child_signal (&oldset);
672

673
      setsid ();
674

675 676
      /* Emacs ignores SIGPIPE, but the child should not.  */
      signal (SIGPIPE, SIG_DFL);
677 678 679 680
      /* Likewise for SIGPROF.  */
#ifdef SIGPROF
      signal (SIGPROF, SIG_DFL);
#endif
681

682 683
      child_setup (filefd, fd_output, fd_error, new_argv, 0, current_dir);
    }
Kim F. Storm's avatar
Kim F. Storm committed
684

685
#endif /* not WINDOWSNT */
686

687
  child_errno = errno;
688

689
  if (pid > 0)
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    {
      synch_process_pid = pid;

      if (INTEGERP (buffer))
	{
	  if (tempfile_index < 0)
	    record_deleted_pid (pid, Qnil);
	  else
	    {
	      eassert (1 < nargs);
	      record_deleted_pid (pid, args[1]);
	      clear_unwind_protect (tempfile_index);
	    }
	  synch_process_pid = 0;
	}
    }
706

707
  unblock_child_signal (&oldset);
708
  unblock_input ();
709

Jim Blandy's avatar
Jim Blandy committed
710
  if (pid < 0)
711
    report_file_errno ("Doing vfork", Qnil, child_errno);
Jim Blandy's avatar
Jim Blandy committed
712

713 714 715 716 717 718 719 720 721 722 723
  /* Close our file descriptors, except for callproc_fd[CALLPROC_PIPEREAD]
     since we will use that to read input from.  */
  for (i = 0; i < CALLPROC_FDS; i++)
    if (i != CALLPROC_PIPEREAD && 0 <= callproc_fd[i])
      {
	emacs_close (callproc_fd[i]);
	callproc_fd[i] = -1;
      }
  emacs_close (filefd);
  clear_unwind_protect (count - 1);

Eli Zaretskii's avatar
Eli Zaretskii committed
724 725
#endif /* not MSDOS */

726
  if (INTEGERP (buffer))
Paul Eggert's avatar
Paul Eggert committed
727
    return unbind_to (count, Qnil);
Jim Blandy's avatar
Jim Blandy committed
728

729
  if (BUFFERP (buffer))
Jim Blandy's avatar
Jim Blandy committed
730 731
    Fset_buffer (buffer);

732 733 734
  fd0 = callproc_fd[CALLPROC_PIPEREAD];

  if (0 <= fd0)
735 736 737 738 739 740 741 742 743 744
    {
      Lisp_Object val, *args2;

      val = Qnil;
      if (!NILP (Vcoding_system_for_read))
	val = Vcoding_system_for_read;
      else
	{
	  if (EQ (coding_systems, Qt))
	    {
745
	      ptrdiff_t i;
746

747
	      SAFE_NALLOCA (args2, 1, nargs + 1);
748 749 750 751 752 753
	      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))
754
	    val = XCAR (coding_systems);
755
	  else if (CONSP (Vdefault_process_coding_system))
756
	    val = XCAR (Vdefault_process_coding_system);
757 758 759
	  else
	    val = Qnil;
	}
760
      Fcheck_coding_system (val);
761 762 763
      /* In unibyte mode, character code conversion should not take
	 place but EOL conversion should.  So, setup raw-text or one
	 of the subsidiary according to the information just setup.  */
Tom Tromey's avatar
Tom Tromey committed
764
      if (NILP (BVAR (current_buffer, enable_multibyte_characters))
765
	  && !NILP (val))
766 767
	val = raw_text_coding_system (val);
      setup_coding_system (val, &process_coding);
768 769
      process_coding.dst_multibyte
	= ! NILP (BVAR (current_buffer, enable_multibyte_characters));
770
      process_coding.src_multibyte = 0;
771 772
    }

Jim Blandy's avatar
Jim Blandy committed
773 774 775
  immediate_quit = 1;
  QUIT;

776
  if (0 <= fd0)
777
    {
778 779 780 781
      enum { CALLPROC_BUFFER_SIZE_MIN = 16 * 1024 };
      enum { CALLPROC_BUFFER_SIZE_MAX = 4 * CALLPROC_BUFFER_SIZE_MIN };
      char buf[CALLPROC_BUFFER_SIZE_MAX];
      int bufsize = CALLPROC_BUFFER_SIZE_MIN;
782
      int nread;
783 784
      EMACS_INT total_read = 0;
      int carryover = 0;
785
      bool display_on_the_fly = display_p;
786
      struct coding_system saved_coding = process_coding;
787 788 789 790 791 792 793 794 795

      while (1)
	{
	  /* 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)
	    {
796
	      int this_read = emacs_read (fd0, buf + nread,
797
					  bufsize - nread);
798

799 800
	      if (this_read < 0)
		goto give_up;
801

802 803 804 805 806
	      if (this_read == 0)
		{
		  process_coding.mode |= CODING_MODE_LAST_BLOCK;
		  break;
		}
807

808 809
	      nread += this_read;
	      total_read += this_read;
810

811 812 813
	      if (display_on_the_fly)
		break;
	    }
814

815 816
	  /* Now NREAD is the total amount of data in the buffer.  */
	  immediate_quit = 0;
817

818 819 820 821
	  if (!nread)
	    ;
	  else if (NILP (BVAR (current_buffer, enable_multibyte_characters))
		   && ! CODING_MAY_REQUIRE_DECODING (&process_coding))
822 823 824 825 826 827 828
	    insert_1_both (buf, nread, nread, 0, 1, 0);
	  else
	    {			/* We have to decode the input.  */
	      Lisp_Object curbuf;
	      ptrdiff_t count1 = SPECPDL_INDEX ();

	      XSETBUFFER (curbuf, current_buffer);
829
	      /* FIXME: Call signal_after_change!  */
830
	      prepare_to_modify_buffer (PT, PT, NULL);
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
	      /* We cannot allow after-change-functions be run
		 during decoding, because that might modify the
		 buffer, while we rely on process_coding.produced to
		 faithfully reflect inserted text until we
		 TEMP_SET_PT_BOTH below.  */
	      specbind (Qinhibit_modification_hooks, Qt);
	      decode_coding_c_string (&process_coding,
				      (unsigned char *) buf, nread, curbuf);
	      unbind_to (count1, Qnil);
	      if (display_on_the_fly
		  && CODING_REQUIRE_DETECTION (&saved_coding)
		  && ! CODING_REQUIRE_DETECTION (&process_coding))
		{
		  /* We have detected some coding system, but the
		     detection may have been via insufficient data.
		     So give up displaying on the fly.  */
		  if (process_coding.produced > 0)
		    del_range_2 (process_coding.dst_pos,
				 process_coding.dst_pos_byte,
				 (process_coding.dst_pos
				  + process_coding.produced_char),
				 (process_coding.dst_pos_byte
				  + process_coding.produced),
				 0);
855
		  display_on_the_fly = false;
856 857 858 859 860 861
		  process_coding = saved_coding;
		  carryover = nread;
		  /* Make the above condition always fail in the future.  */
		  saved_coding.common_flags
		    &= ~CODING_REQUIRE_DETECTION_MASK;
		  continue;
862
		}
863 864 865 866 867 868 869

	      TEMP_SET_PT_BOTH (PT + process_coding.produced_char,
				PT_BYTE + process_coding.produced);
	      carryover = process_coding.carryover_bytes;
	      if (carryover > 0)
		memcpy (buf, process_coding.carryover,
			process_coding.carryover_bytes);
870
	    }
871

872 873
	  if (process_coding.mode & CODING_MODE_LAST_BLOCK)
	    break;
874

875 876 877 878 879
	  /* Make the buffer bigger as we continue to read more data,
	     but not past CALLPROC_BUFFER_SIZE_MAX.  */
	  if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
	    if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
	      bufsize = CALLPROC_BUFFER_SIZE_MAX;
880

881 882 883 884
	  if (display_p)
	    {
	      redisplay_preserve_echo_area (1);
	      /* This variable might have been set to 0 for code
885
		 detection.  In that case, set it back to 1 because
886
		 we should have already detected a coding system.  */
887
	      display_on_the_fly = true;
888
	    }
889
	  immediate_quit = true;
890 891 892 893 894 895 896 897 898 899 900
	  QUIT;
	}
    give_up: ;

      Vlast_coding_system_used = CODING_ID_NAME (process_coding.id);
      /* If the caller required, let the buffer inherit the
	 coding-system used to decode the process output.  */
      if (inherit_process_coding_system)
	call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
	       make_number (total_read));
    }
Eli Zaretskii's avatar
Eli Zaretskii committed
901

902
#ifndef MSDOS
Jim Blandy's avatar
Jim Blandy committed
903
  /* Wait for it to terminate, unless it already has.  */
904
  wait_for_termination (pid, &status, fd0 < 0);
905
#endif
Jim Blandy's avatar
Jim Blandy committed
906 907 908

  immediate_quit = 0;

909 910
  /* Don't kill any children that the subprocess may have left behind
     when exiting.  */
911
  synch_process_pid = 0;
912

913
  SAFE_FREE ();
Jim Blandy's avatar