Convert consecutive FSF copyright years to ranges.
[bpt/emacs.git] / src / callproc.c
CommitLineData
80856e74 1/* Synchronous subprocess invocation for GNU Emacs.
73b0cd50 2 Copyright (C) 1985-1988, 1993-1995, 1999-2011
8cabe764 3 Free Software Foundation, Inc.
80856e74
JB
4
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
80856e74 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
80856e74
JB
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
80856e74
JB
19
20
68c45bf0 21#include <config.h>
80856e74 22#include <signal.h>
e576cab4 23#include <errno.h>
565620a5 24#include <stdio.h>
d7306fe6 25#include <setjmp.h>
80856e74 26#include <sys/types.h>
3cbd6585 27#include <unistd.h>
3cbd6585 28
80856e74 29#include <sys/file.h>
80856e74 30#include <fcntl.h>
80856e74 31
bad95d8f
RS
32#ifdef WINDOWSNT
33#define NOMINMAX
34#include <windows.h>
489f9371 35#include "w32.h"
bad95d8f
RS
36#define _P_NOWAIT 1 /* from process.h */
37#endif
38
7e6c2178 39#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
7e6c2178
RS
40#include <sys/stat.h>
41#include <sys/param.h>
7e6c2178
RS
42#endif /* MSDOS */
43
80856e74
JB
44#include "lisp.h"
45#include "commands.h"
46#include "buffer.h"
91183bfd 47#include "character.h"
edf496dd 48#include "ccl.h"
32d08644 49#include "coding.h"
f0b950cf 50#include "composite.h"
57bda87a 51#include <epaths.h>
80856e74 52#include "process.h"
d177f194 53#include "syssignal.h"
a129418f 54#include "systty.h"
aba637ec 55#include "blockinput.h"
f105f403
KL
56#include "frame.h"
57#include "termhooks.h"
80856e74 58
5f027cea
EZ
59#ifdef MSDOS
60#include "msdos.h"
61#endif
62
03695ace 63#ifndef USE_CRT_DLL
80856e74
JB
64extern char **environ;
65#endif
66
f95c3f91 67#ifdef HAVE_SETPGID
58eb6cf0 68#if !defined (USG)
320695d8 69#undef setpgrp
f95c3f91
GM
70#define setpgrp setpgid
71#endif
2b7e8799 72#endif
f95c3f91 73
f92d51d8
CY
74/* Pattern used by call-process-region to make temp files. */
75static Lisp_Object Vtemp_file_name_pattern;
76
bad95d8f 77#ifdef DOS_NT
093650fe 78Lisp_Object Qbuffer_file_type;
bad95d8f 79#endif /* DOS_NT */
093650fe 80
e0f24100 81/* True if we are about to fork off a synchronous process or if we
80856e74
JB
82 are waiting for it. */
83int synch_process_alive;
84
85/* Nonzero => this is a string explaining death of synchronous subprocess. */
42ca4633 86const char *synch_process_death;
80856e74 87
6b61353c
KH
88/* Nonzero => this is the signal number that terminated the subprocess. */
89int synch_process_termsig;
90
80856e74
JB
91/* If synch_process_death is zero,
92 this is exit code of synchronous subprocess. */
93int synch_process_retcode;
f105f403 94
80856e74 95\f
37d54121
RS
96/* Clean up when exiting Fcall_process.
97 On MSDOS, delete the temporary file on any kind of termination.
98 On Unix, kill the process and any children on termination by signal. */
99
100/* Nonzero if this is termination due to exit. */
101static int call_process_exited;
102
d2bb6598
SM
103EXFUN (Fgetenv_internal, 2);
104
d177f194 105static Lisp_Object
971de7fb 106call_process_kill (Lisp_Object fdpid)
d177f194 107{
68c45bf0 108 emacs_close (XFASTINT (Fcar (fdpid)));
d177f194
JB
109 EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
110 synch_process_alive = 0;
111 return Qnil;
112}
113
80856e74 114Lisp_Object
971de7fb 115call_process_cleanup (Lisp_Object arg)
80856e74 116{
ad3aaf33
AS
117 Lisp_Object fdpid = Fcdr (arg);
118#if defined (MSDOS)
119 Lisp_Object file;
120#else
121 int pid;
122#endif
123
124 Fset_buffer (Fcar (arg));
125
e39a993c 126#if defined (MSDOS)
7e6c2178 127 /* for MSDOS fdpid is really (fd . tempfile) */
c1350752 128 file = Fcdr (fdpid);
68c45bf0 129 emacs_close (XFASTINT (Fcar (fdpid)));
d5db4077
KR
130 if (strcmp (SDATA (file), NULL_DEVICE) != 0)
131 unlink (SDATA (file));
e39a993c 132#else /* not MSDOS */
ad3aaf33 133 pid = XFASTINT (Fcdr (fdpid));
d177f194 134
37d54121 135 if (call_process_exited)
6b6e798b 136 {
68c45bf0 137 emacs_close (XFASTINT (Fcar (fdpid)));
6b6e798b
RS
138 return Qnil;
139 }
37d54121 140
d177f194
JB
141 if (EMACS_KILLPG (pid, SIGINT) == 0)
142 {
aed13378 143 int count = SPECPDL_INDEX ();
d177f194
JB
144 record_unwind_protect (call_process_kill, fdpid);
145 message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
146 immediate_quit = 1;
147 QUIT;
148 wait_for_termination (pid);
149 immediate_quit = 0;
150 specpdl_ptr = specpdl + count; /* Discard the unwind protect. */
151 message1 ("Waiting for process to die...done");
152 }
80856e74 153 synch_process_alive = 0;
68c45bf0 154 emacs_close (XFASTINT (Fcar (fdpid)));
7e6c2178 155#endif /* not MSDOS */
80856e74
JB
156 return Qnil;
157}
158
159DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
fdb82f93
PJ
160 doc: /* Call PROGRAM synchronously in separate process.
161The remaining arguments are optional.
162The program's input comes from file INFILE (nil means `/dev/null').
163Insert output in BUFFER before point; t means current buffer;
164 nil for BUFFER means discard it; 0 means discard and don't wait.
165BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
166REAL-BUFFER says what to do with standard output, as above,
167while STDERR-FILE says what to do with standard error in the child.
168STDERR-FILE may be nil (discard standard error output),
169t (mix it with ordinary output), or a file name string.
170
171Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
172Remaining arguments are strings passed as command arguments to PROGRAM.
173
a4feb144
RS
174If executable PROGRAM can't be found as an executable, `call-process'
175signals a Lisp error. `call-process' reports errors in execution of
176the program only through its return and output.
177
fdb82f93
PJ
178If BUFFER is 0, `call-process' returns immediately with value nil.
179Otherwise it waits for PROGRAM to terminate
180and returns a numeric exit status or a signal description string.
d98b59b5
MB
181If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
182
183usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
5842a27b 184 (int nargs, register Lisp_Object *args)
80856e74 185{
0aa2630f
KS
186 Lisp_Object infile, buffer, current_dir, path;
187 int display_p;
80856e74
JB
188 int fd[2];
189 int filefd;
190 register int pid;
4da256b1
KS
191#define CALLPROC_BUFFER_SIZE_MIN (16 * 1024)
192#define CALLPROC_BUFFER_SIZE_MAX (4 * CALLPROC_BUFFER_SIZE_MIN)
193 char buf[CALLPROC_BUFFER_SIZE_MAX];
194 int bufsize = CALLPROC_BUFFER_SIZE_MIN;
aed13378 195 int count = SPECPDL_INDEX ();
2d607244 196
1aa83b22 197 register const unsigned char **new_argv;
39eaa782
RS
198 /* File to use for stderr in the child.
199 t means use same as standard output. */
200 Lisp_Object error_file;
7e6c2178
RS
201#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
202 char *outf, *tempfile;
203 int outfilefd;
80856e74 204#endif
32d08644
KH
205 struct coding_system process_coding; /* coding-system of process output */
206 struct coding_system argument_coding; /* coding-system of arguments */
09494912
RS
207 /* Set to the return value of Ffind_operation_coding_system. */
208 Lisp_Object coding_systems;
209
210 /* Qt denotes that Ffind_operation_coding_system is not yet called. */
211 coding_systems = Qt;
32d08644 212
b7826503 213 CHECK_STRING (args[0]);
80856e74 214
39eaa782
RS
215 error_file = Qt;
216
7e6c2178
RS
217#ifndef subprocesses
218 /* Without asynchronous processes we cannot have BUFFER == 0. */
177c0ea7 219 if (nargs >= 3
09ffb8b5 220 && (INTEGERP (CONSP (args[2]) ? XCAR (args[2]) : args[2])))
7e6c2178
RS
221 error ("Operating system cannot handle asynchronous subprocesses");
222#endif /* subprocesses */
223
09494912 224 /* Decide the coding-system for giving arguments. */
32d08644
KH
225 {
226 Lisp_Object val, *args2;
32d08644
KH
227 int i;
228
229 /* If arguments are supplied, we may have to encode them. */
230 if (nargs >= 5)
231 {
30d57b8e 232 int must_encode = 0;
6e50da0a 233 Lisp_Object coding_attrs;
30d57b8e 234
e7c1c20e 235 for (i = 4; i < nargs; i++)
b7826503 236 CHECK_STRING (args[i]);
e7c1c20e 237
a2286b5c 238 for (i = 4; i < nargs; i++)
30d57b8e
RS
239 if (STRING_MULTIBYTE (args[i]))
240 must_encode = 1;
241
beacaab3
KH
242 if (!NILP (Vcoding_system_for_write))
243 val = Vcoding_system_for_write;
30d57b8e 244 else if (! must_encode)
fcaf8878 245 val = Qraw_text;
beacaab3 246 else
32d08644
KH
247 {
248 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
249 args2[0] = Qcall_process;
250 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
08ee4e87 251 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
fcaf8878 252 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
32d08644 253 }
fcaf8878 254 val = complement_process_encoding_system (val);
32d08644 255 setup_coding_system (Fcheck_coding_system (val), &argument_coding);
6e50da0a
KH
256 coding_attrs = CODING_ID_ATTRS (argument_coding.id);
257 if (NILP (CODING_ATTR_ASCII_COMPAT (coding_attrs)))
258 {
259 /* We should not use an ASCII incompatible coding system. */
260 val = raw_text_coding_system (val);
261 setup_coding_system (val, &argument_coding);
262 }
32d08644 263 }
32d08644
KH
264 }
265
e576cab4
JB
266 if (nargs >= 2 && ! NILP (args[1]))
267 {
268 infile = Fexpand_file_name (args[1], current_buffer->directory);
b7826503 269 CHECK_STRING (infile);
e576cab4 270 }
80856e74 271 else
5437e9f9 272 infile = build_string (NULL_DEVICE);
80856e74 273
e576cab4
JB
274 if (nargs >= 3)
275 {
39eaa782
RS
276 buffer = args[2];
277
278 /* If BUFFER is a list, its meaning is
279 (BUFFER-FOR-STDOUT FILE-FOR-STDERR). */
280 if (CONSP (buffer))
281 {
70949dac 282 if (CONSP (XCDR (buffer)))
45be8a1e 283 {
a9d4f28a 284 Lisp_Object stderr_file;
70949dac 285 stderr_file = XCAR (XCDR (buffer));
45be8a1e
RS
286
287 if (NILP (stderr_file) || EQ (Qt, stderr_file))
288 error_file = stderr_file;
289 else
290 error_file = Fexpand_file_name (stderr_file, Qnil);
291 }
292
70949dac 293 buffer = XCAR (buffer);
39eaa782 294 }
044512ed 295
39eaa782
RS
296 if (!(EQ (buffer, Qnil)
297 || EQ (buffer, Qt)
3ffde7d6 298 || INTEGERP (buffer)))
e576cab4 299 {
39eaa782
RS
300 Lisp_Object spec_buffer;
301 spec_buffer = buffer;
50fe359b 302 buffer = Fget_buffer_create (buffer);
39eaa782
RS
303 /* Mention the buffer name for a better error message. */
304 if (NILP (buffer))
b7826503
PJ
305 CHECK_BUFFER (spec_buffer);
306 CHECK_BUFFER (buffer);
e576cab4
JB
307 }
308 }
177c0ea7 309 else
e576cab4 310 buffer = Qnil;
80856e74 311
58616e67
JB
312 /* Make sure that the child will be able to chdir to the current
313 buffer's current directory, or its unhandled equivalent. We
314 can't just have the child check for an error when it does the
315 chdir, since it's in a vfork.
316
317 We have to GCPRO around this because Fexpand_file_name,
318 Funhandled_file_name_directory, and Ffile_accessible_directory_p
319 might call a file name handling function. The argument list is
320 protected by the caller, so all we really have to worry about is
321 buffer. */
322 {
34b87689 323 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
58616e67
JB
324
325 current_dir = current_buffer->directory;
326
34b87689 327 GCPRO4 (infile, buffer, current_dir, error_file);
58616e67 328
ca319910
SM
329 current_dir = Funhandled_file_name_directory (current_dir);
330 if (NILP (current_dir))
331 /* If the file name handler says that current_dir is unreachable, use
332 a sensible default. */
333 current_dir = build_string ("~/");
334 current_dir = expand_and_dir_to_file (current_dir, Qnil);
db8454b0
CY
335 current_dir = Ffile_name_as_directory (current_dir);
336
58616e67
JB
337 if (NILP (Ffile_accessible_directory_p (current_dir)))
338 report_file_error ("Setting current directory",
339 Fcons (current_buffer->directory, Qnil));
340
34b87689
KH
341 if (STRING_MULTIBYTE (infile))
342 infile = ENCODE_FILE (infile);
343 if (STRING_MULTIBYTE (current_dir))
344 current_dir = ENCODE_FILE (current_dir);
345 if (STRINGP (error_file) && STRING_MULTIBYTE (error_file))
346 error_file = ENCODE_FILE (error_file);
58616e67
JB
347 UNGCPRO;
348 }
349
0aa2630f 350 display_p = INTERACTIVE && nargs >= 4 && !NILP (args[3]);
80856e74 351
d5db4077 352 filefd = emacs_open (SDATA (infile), O_RDONLY, 0);
80856e74
JB
353 if (filefd < 0)
354 {
34b87689 355 infile = DECODE_FILE (infile);
e576cab4 356 report_file_error ("Opening process input file", Fcons (infile, Qnil));
80856e74
JB
357 }
358 /* Search for program; barf if not found. */
c52b0b34 359 {
ad3aaf33 360 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
c52b0b34 361
ad3aaf33 362 GCPRO4 (infile, buffer, current_dir, error_file);
5c150961 363 openp (Vexec_path, args[0], Vexec_suffixes, &path, make_number (X_OK));
c52b0b34
KH
364 UNGCPRO;
365 }
012c6fcb 366 if (NILP (path))
80856e74 367 {
68c45bf0 368 emacs_close (filefd);
80856e74
JB
369 report_file_error ("Searching for program", Fcons (args[0], Qnil));
370 }
8ee8f447
RS
371
372 /* If program file name starts with /: for quoting a magic name,
373 discard that. */
374 if (SBYTES (path) > 2 && SREF (path, 0) == '/'
375 && SREF (path, 1) == ':')
376 path = Fsubstring (path, make_number (2), Qnil);
377
1aa83b22
AS
378 new_argv = (const unsigned char **)
379 alloca (max (2, nargs - 2) * sizeof (char *));
c364e618
KH
380 if (nargs > 4)
381 {
382 register int i;
ad3aaf33 383 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
c364e618 384
ad3aaf33 385 GCPRO5 (infile, buffer, current_dir, path, error_file);
c5bfa12b
KH
386 argument_coding.dst_multibyte = 0;
387 for (i = 4; i < nargs; i++)
c364e618 388 {
c5bfa12b
KH
389 argument_coding.src_multibyte = STRING_MULTIBYTE (args[i]);
390 if (CODING_REQUIRE_ENCODING (&argument_coding))
91183bfd
KH
391 /* We must encode this argument. */
392 args[i] = encode_coding_string (&argument_coding, args[i], 1);
c364e618 393 }
c5bfa12b 394 UNGCPRO;
1aa83b22
AS
395 for (i = 4; i < nargs; i++)
396 new_argv[i - 3] = SDATA (args[i]);
397 new_argv[i - 3] = 0;
c364e618 398 }
db54baaa
KH
399 else
400 new_argv[1] = 0;
1aa83b22 401 new_argv[0] = SDATA (path);
80856e74 402
7e6c2178 403#ifdef MSDOS /* MW, July 1993 */
8a52365c 404 if ((outf = egetenv ("TMPDIR")))
7e6c2178
RS
405 strcpy (tempfile = alloca (strlen (outf) + 20), outf);
406 else
407 {
408 tempfile = alloca (20);
409 *tempfile = '\0';
410 }
411 dostounix_filename (tempfile);
177c0ea7 412 if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/')
7e6c2178
RS
413 strcat (tempfile, "/");
414 strcat (tempfile, "detmp.XXX");
415 mktemp (tempfile);
416
417 outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
418 if (outfilefd < 0)
419 {
68c45bf0 420 emacs_close (filefd);
6f89d28a
MB
421 report_file_error ("Opening process output file",
422 Fcons (build_string (tempfile), Qnil));
7e6c2178 423 }
6f89d28a 424 fd[0] = filefd;
2610078a 425 fd[1] = outfilefd;
6f89d28a 426#endif /* MSDOS */
7e6c2178 427
d50d3dc8 428 if (INTEGERP (buffer))
68c45bf0 429 fd[1] = emacs_open (NULL_DEVICE, O_WRONLY, 0), fd[0] = -1;
80856e74
JB
430 else
431 {
7e6c2178 432#ifndef MSDOS
db92b288
GM
433 errno = 0;
434 if (pipe (fd) == -1)
435 {
436 emacs_close (filefd);
437 report_file_error ("Creating process pipe", Qnil);
438 }
80856e74
JB
439#endif
440 }
441
442 {
443 /* child_setup must clobber environ in systems with true vfork.
444 Protect it from permanent change. */
445 register char **save_environ = environ;
446 register int fd1 = fd[1];
39eaa782 447 int fd_error = fd1;
80856e74
JB
448
449#if 0 /* Some systems don't have sigblock. */
e065a56e 450 mask = sigblock (sigmask (SIGCHLD));
80856e74
JB
451#endif
452
453 /* Record that we're about to create a synchronous process. */
454 synch_process_alive = 1;
455
5c03767e
RS
456 /* These vars record information from process termination.
457 Clear them now before process can possibly terminate,
458 to avoid timing error if process terminates soon. */
459 synch_process_death = 0;
460 synch_process_retcode = 0;
6b61353c 461 synch_process_termsig = 0;
5c03767e 462
39eaa782 463 if (NILP (error_file))
68c45bf0 464 fd_error = emacs_open (NULL_DEVICE, O_WRONLY, 0);
39eaa782
RS
465 else if (STRINGP (error_file))
466 {
467#ifdef DOS_NT
d5db4077 468 fd_error = emacs_open (SDATA (error_file),
68c45bf0
PE
469 O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
470 S_IREAD | S_IWRITE);
39eaa782 471#else /* not DOS_NT */
d5db4077 472 fd_error = creat (SDATA (error_file), 0666);
39eaa782
RS
473#endif /* not DOS_NT */
474 }
475
476 if (fd_error < 0)
477 {
68c45bf0 478 emacs_close (filefd);
6f89d28a 479 if (fd[0] != filefd)
68c45bf0 480 emacs_close (fd[0]);
39eaa782 481 if (fd1 >= 0)
68c45bf0 482 emacs_close (fd1);
6f89d28a
MB
483#ifdef MSDOS
484 unlink (tempfile);
485#endif
34b87689
KH
486 if (NILP (error_file))
487 error_file = build_string (NULL_DEVICE);
488 else if (STRINGP (error_file))
489 error_file = DECODE_FILE (error_file);
490 report_file_error ("Cannot redirect stderr", Fcons (error_file, Qnil));
39eaa782 491 }
89e1ec1d 492
2610078a 493#ifdef MSDOS /* MW, July 1993 */
c17c4250 494 /* Note that on MSDOS `child_setup' actually returns the child process
2610078a
KH
495 exit status, not its PID, so we assign it to `synch_process_retcode'
496 below. */
c17c4250
EZ
497 pid = child_setup (filefd, outfilefd, fd_error, (char **) new_argv,
498 0, current_dir);
39eaa782 499
2610078a
KH
500 /* Record that the synchronous process exited and note its
501 termination status. */
502 synch_process_alive = 0;
503 synch_process_retcode = pid;
504 if (synch_process_retcode < 0) /* means it couldn't be exec'ed */
68c45bf0 505 {
ca9c0567 506 synchronize_system_messages_locale ();
68c45bf0
PE
507 synch_process_death = strerror (errno);
508 }
2610078a 509
68c45bf0 510 emacs_close (outfilefd);
2610078a 511 if (fd_error != outfilefd)
68c45bf0 512 emacs_close (fd_error);
2610078a 513 fd1 = -1; /* No harm in closing that one! */
32d08644
KH
514 /* Since CRLF is converted to LF within `decode_coding', we can
515 always open a file with binary mode. */
68c45bf0 516 fd[0] = emacs_open (tempfile, O_RDONLY | O_BINARY, 0);
2610078a
KH
517 if (fd[0] < 0)
518 {
519 unlink (tempfile);
68c45bf0 520 emacs_close (filefd);
2610078a
KH
521 report_file_error ("Cannot re-open temporary file", Qnil);
522 }
523#else /* not MSDOS */
bad95d8f 524#ifdef WINDOWSNT
2d607244
RS
525 pid = child_setup (filefd, fd1, fd_error, (char **) new_argv,
526 0, current_dir);
bad95d8f 527#else /* not WINDOWSNT */
aba637ec
KS
528 BLOCK_INPUT;
529
80856e74
JB
530 pid = vfork ();
531
532 if (pid == 0)
533 {
534 if (fd[0] >= 0)
68c45bf0 535 emacs_close (fd[0]);
1e7963c7
RS
536#ifdef HAVE_SETSID
537 setsid ();
538#endif
58eb6cf0 539#if defined (USG)
80856e74
JB
540 setpgrp ();
541#else
542 setpgrp (pid, pid);
543#endif /* USG */
2d607244
RS
544 child_setup (filefd, fd1, fd_error, (char **) new_argv,
545 0, current_dir);
80856e74 546 }
aba637ec
KS
547
548 UNBLOCK_INPUT;
bad95d8f 549#endif /* not WINDOWSNT */
cd5f8f60
RS
550
551 /* The MSDOS case did this already. */
552 if (fd_error >= 0)
68c45bf0 553 emacs_close (fd_error);
2610078a 554#endif /* not MSDOS */
80856e74 555
80856e74
JB
556 environ = save_environ;
557
6b6e798b
RS
558 /* Close most of our fd's, but not fd[0]
559 since we will use that to read input from. */
68c45bf0 560 emacs_close (filefd);
799abb26 561 if (fd1 >= 0 && fd1 != fd_error)
68c45bf0 562 emacs_close (fd1);
80856e74
JB
563 }
564
565 if (pid < 0)
566 {
6b6e798b 567 if (fd[0] >= 0)
68c45bf0 568 emacs_close (fd[0]);
80856e74
JB
569 report_file_error ("Doing vfork", Qnil);
570 }
571
d50d3dc8 572 if (INTEGERP (buffer))
80856e74 573 {
6b6e798b 574 if (fd[0] >= 0)
68c45bf0 575 emacs_close (fd[0]);
80856e74
JB
576 return Qnil;
577 }
578
6b6e798b 579 /* Enable sending signal if user quits below. */
37d54121
RS
580 call_process_exited = 0;
581
e39a993c 582#if defined(MSDOS)
7e6c2178
RS
583 /* MSDOS needs different cleanup information. */
584 record_unwind_protect (call_process_cleanup,
ad3aaf33
AS
585 Fcons (Fcurrent_buffer (),
586 Fcons (make_number (fd[0]),
587 build_string (tempfile))));
7e6c2178 588#else
80856e74 589 record_unwind_protect (call_process_cleanup,
ad3aaf33
AS
590 Fcons (Fcurrent_buffer (),
591 Fcons (make_number (fd[0]), make_number (pid))));
e39a993c 592#endif /* not MSDOS */
80856e74
JB
593
594
d50d3dc8 595 if (BUFFERP (buffer))
80856e74
JB
596 Fset_buffer (buffer);
597
09494912
RS
598 if (NILP (buffer))
599 {
600 /* If BUFFER is nil, we must read process output once and then
601 discard it, so setup coding system but with nil. */
602 setup_coding_system (Qnil, &process_coding);
603 }
604 else
605 {
606 Lisp_Object val, *args2;
607
608 val = Qnil;
609 if (!NILP (Vcoding_system_for_read))
610 val = Vcoding_system_for_read;
611 else
612 {
613 if (EQ (coding_systems, Qt))
614 {
615 int i;
616
617 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
618 args2[0] = Qcall_process;
619 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
620 coding_systems
621 = Ffind_operation_coding_system (nargs + 1, args2);
622 }
623 if (CONSP (coding_systems))
70949dac 624 val = XCAR (coding_systems);
09494912 625 else if (CONSP (Vdefault_process_coding_system))
70949dac 626 val = XCAR (Vdefault_process_coding_system);
09494912
RS
627 else
628 val = Qnil;
629 }
91183bfd 630 Fcheck_coding_system (val);
09494912
RS
631 /* In unibyte mode, character code conversion should not take
632 place but EOL conversion should. So, setup raw-text or one
633 of the subsidiary according to the information just setup. */
634 if (NILP (current_buffer->enable_multibyte_characters)
635 && !NILP (val))
91183bfd
KH
636 val = raw_text_coding_system (val);
637 setup_coding_system (val, &process_coding);
09494912
RS
638 }
639
80856e74
JB
640 immediate_quit = 1;
641 QUIT;
642
643 {
69481da7 644 register EMACS_INT nread;
0ad477db 645 int first = 1;
69481da7 646 EMACS_INT total_read = 0;
321fecde 647 int carryover = 0;
0aa2630f 648 int display_on_the_fly = display_p;
05b44e90
KH
649 struct coding_system saved_coding;
650
651 saved_coding = process_coding;
60558b19 652 while (1)
80856e74 653 {
60558b19
RS
654 /* Repeatedly read until we've filled as much as possible
655 of the buffer size we have. But don't read
8e6208c5 656 less than 1024--save that for the next bufferful. */
321fecde 657 nread = carryover;
60558b19 658 while (nread < bufsize - 1024)
00fb3e95 659 {
4da256b1 660 int this_read = emacs_read (fd[0], buf + nread,
68c45bf0 661 bufsize - nread);
60558b19
RS
662
663 if (this_read < 0)
664 goto give_up;
665
666 if (this_read == 0)
7a7ab107
KH
667 {
668 process_coding.mode |= CODING_MODE_LAST_BLOCK;
669 break;
670 }
60558b19
RS
671
672 nread += this_read;
7a7ab107 673 total_read += this_read;
60558b19 674
7a7ab107
KH
675 if (display_on_the_fly)
676 break;
677 }
60558b19
RS
678
679 /* Now NREAD is the total amount of data in the buffer. */
80856e74 680 immediate_quit = 0;
177c0ea7 681
012c6fcb 682 if (!NILP (buffer))
32d08644 683 {
bb4a3884
KH
684 if (NILP (current_buffer->enable_multibyte_characters)
685 && ! CODING_MAY_REQUIRE_DECODING (&process_coding))
4da256b1 686 insert_1_both (buf, nread, nread, 0, 1, 0);
32d08644
KH
687 else
688 { /* We have to decode the input. */
45d60801 689 Lisp_Object curbuf;
71a0c011 690 int count1 = SPECPDL_INDEX ();
177c0ea7 691
45d60801 692 XSETBUFFER (curbuf, current_buffer);
71a0c011
EZ
693 /* We cannot allow after-change-functions be run
694 during decoding, because that might modify the
695 buffer, while we rely on process_coding.produced to
696 faithfully reflect inserted text until we
697 TEMP_SET_PT_BOTH below. */
698 specbind (Qinhibit_modification_hooks, Qt);
45d60801
KH
699 decode_coding_c_string (&process_coding, buf, nread,
700 curbuf);
71a0c011 701 unbind_to (count1, Qnil);
7a7ab107 702 if (display_on_the_fly
91183bfd
KH
703 && CODING_REQUIRE_DETECTION (&saved_coding)
704 && ! CODING_REQUIRE_DETECTION (&process_coding))
7a7ab107
KH
705 {
706 /* We have detected some coding system. But,
707 there's a possibility that the detection was
708 done by insufficient data. So, we give up
709 displaying on the fly. */
91183bfd
KH
710 if (process_coding.produced > 0)
711 del_range_2 (process_coding.dst_pos,
712 process_coding.dst_pos_byte,
713 process_coding.dst_pos
714 + process_coding.produced_char,
715 process_coding.dst_pos_byte
716 + process_coding.produced, 0);
7a7ab107
KH
717 display_on_the_fly = 0;
718 process_coding = saved_coding;
719 carryover = nread;
0aa2630f
KS
720 /* This is to make the above condition always
721 fails in the future. */
21d0467f
KH
722 saved_coding.common_flags
723 &= ~CODING_REQUIRE_DETECTION_MASK;
7a7ab107
KH
724 continue;
725 }
177c0ea7 726
ea99bcc1
KH
727 TEMP_SET_PT_BOTH (PT + process_coding.produced_char,
728 PT_BYTE + process_coding.produced);
54ab3d3b 729 carryover = process_coding.carryover_bytes;
321fecde 730 if (carryover > 0)
72af86bd
AS
731 memcpy (buf, process_coding.carryover,
732 process_coding.carryover_bytes);
32d08644
KH
733 }
734 }
c5bfa12b 735
321fecde 736 if (process_coding.mode & CODING_MODE_LAST_BLOCK)
c5bfa12b 737 break;
6e3bfbb2
RS
738
739 /* Make the buffer bigger as we continue to read more data,
4da256b1
KS
740 but not past CALLPROC_BUFFER_SIZE_MAX. */
741 if (bufsize < CALLPROC_BUFFER_SIZE_MAX && total_read > 32 * bufsize)
742 if ((bufsize *= 2) > CALLPROC_BUFFER_SIZE_MAX)
743 bufsize = CALLPROC_BUFFER_SIZE_MAX;
6e3bfbb2 744
0aa2630f 745 if (display_p)
0ad477db
RS
746 {
747 if (first)
748 prepare_menu_bars ();
749 first = 0;
3007ebfb 750 redisplay_preserve_echo_area (1);
0aa2630f
KS
751 /* This variable might have been set to 0 for code
752 detection. In that case, we set it back to 1 because
753 we should have already detected a coding system. */
754 display_on_the_fly = 1;
0ad477db 755 }
80856e74
JB
756 immediate_quit = 1;
757 QUIT;
758 }
60558b19 759 give_up: ;
80856e74 760
91183bfd
KH
761 Vlast_coding_system_used = CODING_ID_NAME (process_coding.id);
762 /* If the caller required, let the buffer inherit the
763 coding-system used to decode the process output. */
764 if (inherit_process_coding_system)
765 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
ad3aaf33 766 make_number (total_read));
3b440bb5
EZ
767 }
768
77defa9a 769#ifndef MSDOS
80856e74
JB
770 /* Wait for it to terminate, unless it already has. */
771 wait_for_termination (pid);
77defa9a 772#endif
80856e74
JB
773
774 immediate_quit = 0;
775
37d54121
RS
776 /* Don't kill any children that the subprocess may have left behind
777 when exiting. */
778 call_process_exited = 1;
779
80856e74
JB
780 unbind_to (count, Qnil);
781
6b61353c
KH
782 if (synch_process_termsig)
783 {
42ca4633 784 const char *signame;
6b61353c
KH
785
786 synchronize_system_messages_locale ();
787 signame = strsignal (synch_process_termsig);
788
789 if (signame == 0)
790 signame = "unknown";
791
792 synch_process_death = signame;
793 }
794
80856e74 795 if (synch_process_death)
68c45bf0
PE
796 return code_convert_string_norecord (build_string (synch_process_death),
797 Vlocale_coding_system, 0);
80856e74
JB
798 return make_number (synch_process_retcode);
799}
80856e74 800\f
9fefd2ba 801static Lisp_Object
971de7fb 802delete_temp_file (Lisp_Object name)
80856e74 803{
1a271e14
KR
804 /* Suppress jka-compr handling, etc. */
805 int count = SPECPDL_INDEX ();
806 specbind (intern ("file-name-handler-alist"), Qnil);
f1a5d776 807 internal_delete_file (name);
1a271e14 808 unbind_to (count, Qnil);
320695d8 809 return Qnil;
80856e74
JB
810}
811
812DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
fdb82f93
PJ
813 3, MANY, 0,
814 doc: /* Send text from START to END to a synchronous process running PROGRAM.
815The remaining arguments are optional.
816Delete the text if fourth arg DELETE is non-nil.
817
818Insert output in BUFFER before point; t means current buffer;
819 nil for BUFFER means discard it; 0 means discard and don't wait.
820BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
821REAL-BUFFER says what to do with standard output, as above,
822while STDERR-FILE says what to do with standard error in the child.
823STDERR-FILE may be nil (discard standard error output),
824t (mix it with ordinary output), or a file name string.
825
826Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.
827Remaining args are passed to PROGRAM at startup as command args.
828
ba9a5174 829If BUFFER is 0, `call-process-region' returns immediately with value nil.
fdb82f93
PJ
830Otherwise it waits for PROGRAM to terminate
831and returns a numeric exit status or a signal description string.
d98b59b5
MB
832If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
833
834usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS) */)
5842a27b 835 (int nargs, register Lisp_Object *args)
80856e74 836{
39323a7e
KH
837 struct gcpro gcpro1;
838 Lisp_Object filename_string;
839 register Lisp_Object start, end;
aed13378 840 int count = SPECPDL_INDEX ();
08ee4e87 841 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
09494912 842 Lisp_Object coding_systems;
32d08644
KH
843 Lisp_Object val, *args2;
844 int i;
7e6c2178 845 char *tempfile;
f92d51d8 846 Lisp_Object tmpdir, pattern;
7e6c2178 847
f92d51d8
CY
848 if (STRINGP (Vtemporary_file_directory))
849 tmpdir = Vtemporary_file_directory;
7e6c2178
RS
850 else
851 {
f92d51d8
CY
852#ifndef DOS_NT
853 if (getenv ("TMPDIR"))
854 tmpdir = build_string (getenv ("TMPDIR"));
855 else
856 tmpdir = build_string ("/tmp/");
857#else /* DOS_NT */
858 char *outf;
859 if ((outf = egetenv ("TMPDIR"))
860 || (outf = egetenv ("TMP"))
861 || (outf = egetenv ("TEMP")))
862 tmpdir = build_string (outf);
863 else
864 tmpdir = Ffile_name_as_directory (build_string ("c:/temp"));
0774fcf8 865#endif
f92d51d8 866 }
7e6c2178 867
f92d51d8
CY
868 pattern = Fexpand_file_name (Vtemp_file_name_pattern, tmpdir);
869 tempfile = (char *) alloca (SBYTES (pattern) + 1);
72af86bd 870 memcpy (tempfile, SDATA (pattern), SBYTES (pattern) + 1);
09494912
RS
871 coding_systems = Qt;
872
1ddc85a4
DL
873#ifdef HAVE_MKSTEMP
874 {
d277f1f7
YM
875 int fd;
876
877 BLOCK_INPUT;
878 fd = mkstemp (tempfile);
879 UNBLOCK_INPUT;
1ddc85a4
DL
880 if (fd == -1)
881 report_file_error ("Failed to open temporary file",
882 Fcons (Vtemp_file_name_pattern, Qnil));
883 else
884 close (fd);
885 }
886#else
80856e74 887 mktemp (tempfile);
1ddc85a4 888#endif
80856e74
JB
889
890 filename_string = build_string (tempfile);
39323a7e 891 GCPRO1 (filename_string);
80856e74
JB
892 start = args[0];
893 end = args[1];
32d08644 894 /* Decide coding-system of the contents of the temporary file. */
91489411
RS
895 if (!NILP (Vcoding_system_for_write))
896 val = Vcoding_system_for_write;
897 else if (NILP (current_buffer->enable_multibyte_characters))
fcaf8878 898 val = Qraw_text;
32d08644 899 else
beacaab3 900 {
91489411
RS
901 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
902 args2[0] = Qcall_process_region;
903 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
904 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
fcaf8878 905 val = CONSP (coding_systems) ? XCDR (coding_systems) : Qnil;
beacaab3 906 }
fcaf8878 907 val = complement_process_encoding_system (val);
32d08644 908
168afdaa 909 {
aed13378 910 int count1 = SPECPDL_INDEX ();
168afdaa
RS
911
912 specbind (intern ("coding-system-for-write"), val);
bb951f0e
KR
913 /* POSIX lets mk[s]temp use "."; don't invoke jka-compr if we
914 happen to get a ".Z" suffix. */
915 specbind (intern ("file-name-handler-alist"), Qnil);
168afdaa
RS
916 Fwrite_region (start, end, filename_string, Qnil, Qlambda, Qnil, Qnil);
917
918 unbind_to (count1, Qnil);
919 }
91489411 920
177c0ea7 921 /* Note that Fcall_process takes care of binding
91489411 922 coding-system-for-read. */
093650fe 923
80856e74
JB
924 record_unwind_protect (delete_temp_file, filename_string);
925
edf496dd 926 if (nargs > 3 && !NILP (args[3]))
80856e74
JB
927 Fdelete_region (start, end);
928
edf496dd
KH
929 if (nargs > 3)
930 {
931 args += 2;
932 nargs -= 2;
933 }
934 else
935 {
936 args[0] = args[2];
937 nargs = 2;
938 }
939 args[1] = filename_string;
80856e74 940
edf496dd 941 RETURN_UNGCPRO (unbind_to (count, Fcall_process (nargs, args)));
80856e74
JB
942}
943\f
361358ea 944#ifndef WINDOWSNT
971de7fb 945static int relocate_fd (int fd, int minfd);
361358ea 946#endif
dfcf069d 947
5990851d
KL
948static char **
949add_env (char **env, char **new_env, char *string)
950{
951 char **ep;
952 int ok = 1;
953 if (string == NULL)
954 return new_env;
955
956 /* See if this string duplicates any string already in the env.
957 If so, don't put it in.
958 When an env var has multiple definitions,
959 we keep the definition that comes first in process-environment. */
960 for (ep = env; ok && ep != new_env; ep++)
961 {
962 char *p = *ep, *q = string;
963 while (ok)
964 {
965 if (*q != *p)
966 break;
967 if (*q == 0)
968 /* The string is a lone variable name; keep it for now, we
969 will remove it later. It is a placeholder for a
970 variable that is not to be included in the environment. */
971 break;
972 if (*q == '=')
973 ok = 0;
974 p++, q++;
975 }
976 }
977 if (ok)
978 *new_env++ = string;
979 return new_env;
980}
981
80856e74
JB
982/* This is the last thing run in a newly forked inferior
983 either synchronous or asynchronous.
984 Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
985 Initialize inferior's priority, pgrp, connected dir and environment.
986 then exec another program based on new_argv.
987
988 This function may change environ for the superior process.
989 Therefore, the superior process must save and restore the value
990 of environ around the vfork and the call to this function.
991
80856e74 992 SET_PGRP is nonzero if we should put the subprocess into a separate
177c0ea7 993 process group.
e576cab4
JB
994
995 CURRENT_DIR is an elisp string giving the path of the current
996 directory the subprocess should have. Since we can't really signal
997 a decent error from within the child, this should be verified as an
998 executable directory by the parent. */
80856e74 999
dfcf069d 1000int
971de7fb 1001child_setup (int in, int out, int err, register char **new_argv, int set_pgrp, Lisp_Object current_dir)
80856e74 1002{
e576cab4 1003 char **env;
7fcf7f05 1004 char *pwd_var;
bad95d8f
RS
1005#ifdef WINDOWSNT
1006 int cpid;
4252a4bd 1007 HANDLE handles[3];
bad95d8f 1008#endif /* WINDOWSNT */
e576cab4 1009
33abe2d9 1010 int pid = getpid ();
80856e74 1011
80856e74
JB
1012 /* Close Emacs's descriptors that this process should not have. */
1013 close_process_descs ();
ded80a25 1014
c17c4250
EZ
1015 /* DOS_NT isn't in a vfork, so if we are in the middle of load-file,
1016 we will lose if we call close_load_descs here. */
1017#ifndef DOS_NT
4458cebe 1018 close_load_descs ();
c17c4250 1019#endif
80856e74
JB
1020
1021 /* Note that use of alloca is always safe here. It's obvious for systems
1022 that do not have true vfork or that have true (stack) alloca.
caa01fe0
GM
1023 If using vfork and C_ALLOCA (when Emacs used to include
1024 src/alloca.c) it is safe because that changes the superior's
1025 static variables as if the superior had done alloca and will be
1026 cleaned up in the usual way. */
e576cab4 1027 {
7fcf7f05 1028 register char *temp;
e576cab4 1029 register int i;
77d78be1 1030
d5db4077 1031 i = SBYTES (current_dir);
16425c4a
EZ
1032#ifdef MSDOS
1033 /* MSDOS must have all environment variables malloc'ed, because
1034 low-level libc functions that launch subsidiary processes rely
1035 on that. */
1036 pwd_var = (char *) xmalloc (i + 6);
1037#else
7fcf7f05 1038 pwd_var = (char *) alloca (i + 6);
16425c4a 1039#endif
7fcf7f05 1040 temp = pwd_var + 4;
72af86bd
AS
1041 memcpy (pwd_var, "PWD=", 4);
1042 memcpy (temp, SDATA (current_dir), i);
bad95d8f 1043 if (!IS_DIRECTORY_SEP (temp[i - 1])) temp[i++] = DIRECTORY_SEP;
e576cab4
JB
1044 temp[i] = 0;
1045
c17c4250 1046#ifndef DOS_NT
e576cab4
JB
1047 /* We can't signal an Elisp error here; we're in a vfork. Since
1048 the callers check the current directory before forking, this
1049 should only return an error if the directory's permissions
1050 are changed between the check and this chdir, but we should
1051 at least check. */
1052 if (chdir (temp) < 0)
20b25e46 1053 _exit (errno);
f8d23104 1054#else /* DOS_NT */
c17c4250
EZ
1055 /* Get past the drive letter, so that d:/ is left alone. */
1056 if (i > 2 && IS_DEVICE_SEP (temp[1]) && IS_DIRECTORY_SEP (temp[2]))
1057 {
1058 temp += 2;
1059 i -= 2;
1060 }
f8d23104 1061#endif /* DOS_NT */
c17c4250 1062
7fcf7f05 1063 /* Strip trailing slashes for PWD, but leave "/" and "//" alone. */
bad95d8f 1064 while (i > 2 && IS_DIRECTORY_SEP (temp[i - 1]))
7fcf7f05 1065 temp[--i] = 0;
e576cab4 1066 }
80856e74 1067
5990851d 1068 /* Set `env' to a vector of the strings in the environment. */
80856e74
JB
1069 {
1070 register Lisp_Object tem;
1071 register char **new_env;
5990851d 1072 char **p, **q;
80856e74 1073 register int new_length;
d2bb6598 1074 Lisp_Object display = Qnil;
361358ea 1075
80856e74 1076 new_length = 0;
f105f403 1077
80856e74 1078 for (tem = Vprocess_environment;
5990851d
KL
1079 CONSP (tem) && STRINGP (XCAR (tem));
1080 tem = XCDR (tem))
d2bb6598
SM
1081 {
1082 if (strncmp (SDATA (XCAR (tem)), "DISPLAY", 7) == 0
1083 && (SDATA (XCAR (tem)) [7] == '\0'
1084 || SDATA (XCAR (tem)) [7] == '='))
1085 /* DISPLAY is specified in process-environment. */
1086 display = Qt;
1087 new_length++;
1088 }
de87fb59 1089
d2bb6598
SM
1090 /* If not provided yet, use the frame's DISPLAY. */
1091 if (NILP (display))
1092 {
1093 Lisp_Object tmp = Fframe_parameter (selected_frame, Qdisplay);
1094 if (!STRINGP (tmp) && CONSP (Vinitial_environment))
1095 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1096 tmp = Fgetenv_internal (build_string ("DISPLAY"),
1097 Vinitial_environment);
1098 if (STRINGP (tmp))
1099 {
1100 display = tmp;
1101 new_length++;
1102 }
1103 }
80856e74 1104
7fcf7f05
RS
1105 /* new_length + 2 to include PWD and terminating 0. */
1106 env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
7fcf7f05
RS
1107 /* If we have a PWD envvar, pass one down,
1108 but with corrected value. */
a13f8f50 1109 if (egetenv ("PWD"))
7fcf7f05 1110 *new_env++ = pwd_var;
361358ea 1111
6b8e474c 1112 if (STRINGP (display))
de87fb59
DN
1113 {
1114 int vlen = strlen ("DISPLAY=") + strlen (SDATA (display)) + 1;
1115 char *vdata = (char *) alloca (vlen);
1116 strcpy (vdata, "DISPLAY=");
1117 strcat (vdata, SDATA (display));
1118 new_env = add_env (env, new_env, vdata);
1119 }
80856e74 1120
5990851d 1121 /* Overrides. */
80856e74 1122 for (tem = Vprocess_environment;
70949dac
KR
1123 CONSP (tem) && STRINGP (XCAR (tem));
1124 tem = XCDR (tem))
5990851d 1125 new_env = add_env (env, new_env, SDATA (XCAR (tem)));
d2bb6598 1126
5990851d
KL
1127 *new_env = 0;
1128
1129 /* Remove variable names without values. */
1130 p = q = env;
1131 while (*p != 0)
cd9565ba 1132 {
5990851d 1133 while (*q != 0 && strchr (*q, '=') == NULL)
1baf6db9 1134 q++;
5990851d
KL
1135 *p = *q++;
1136 if (*p != 0)
1137 p++;
cd9565ba 1138 }
80856e74 1139 }
de87fb59 1140
361358ea 1141
bad95d8f
RS
1142#ifdef WINDOWSNT
1143 prepare_standard_handles (in, out, err, handles);
d5db4077 1144 set_process_dir (SDATA (current_dir));
67802943
DN
1145 /* Spawn the child. (See ntproc.c:Spawnve). */
1146 cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
1147 reset_standard_handles (in, out, err, handles);
1148 if (cpid == -1)
1149 /* An error occurred while trying to spawn the process. */
1150 report_file_error ("Spawning child process", Qnil);
1151 return cpid;
1152
bad95d8f 1153#else /* not WINDOWSNT */
426b37ae
JB
1154 /* Make sure that in, out, and err are not actually already in
1155 descriptors zero, one, or two; this could happen if Emacs is
7e6c2178 1156 started with its standard in, out, or error closed, as might
426b37ae 1157 happen under X. */
f29f9e4a
RS
1158 {
1159 int oin = in, oout = out;
1160
1161 /* We have to avoid relocating the same descriptor twice! */
1162
1163 in = relocate_fd (in, 3);
1164
1165 if (out == oin)
1166 out = in;
1167 else
3e9367e7 1168 out = relocate_fd (out, 3);
f29f9e4a
RS
1169
1170 if (err == oin)
1171 err = in;
1172 else if (err == oout)
1173 err = out;
1174 else
3e9367e7 1175 err = relocate_fd (err, 3);
f29f9e4a 1176 }
426b37ae 1177
c17c4250 1178#ifndef MSDOS
68c45bf0
PE
1179 emacs_close (0);
1180 emacs_close (1);
1181 emacs_close (2);
80856e74
JB
1182
1183 dup2 (in, 0);
1184 dup2 (out, 1);
1185 dup2 (err, 2);
68c45bf0 1186 emacs_close (in);
ce8f5a9a
AS
1187 if (out != in)
1188 emacs_close (out);
1189 if (err != in && err != out)
1190 emacs_close (err);
80856e74 1191
58eb6cf0 1192#if defined(USG)
fdba8590 1193#ifndef SETPGRP_RELEASES_CTTY
e576cab4 1194 setpgrp (); /* No arguments but equivalent in this case */
fdba8590 1195#endif
67802943 1196#else /* not USG */
e576cab4 1197 setpgrp (pid, pid);
67802943 1198#endif /* not USG */
80856e74 1199
a7ebc409 1200 /* setpgrp_of_tty is incorrect here; it uses input_fd. */
12e610e8 1201 tcsetpgrp (0, pid);
a7ebc409 1202
80856e74
JB
1203 /* execvp does not accept an environment arg so the only way
1204 to pass this environment is to set environ. Our caller
1205 is responsible for restoring the ambient value of environ. */
1206 environ = env;
1207 execvp (new_argv[0], new_argv);
1208
68c45bf0
PE
1209 emacs_write (1, "Can't exec program: ", 20);
1210 emacs_write (1, new_argv[0], strlen (new_argv[0]));
1211 emacs_write (1, "\n", 1);
80856e74 1212 _exit (1);
67802943
DN
1213
1214#else /* MSDOS */
1215 pid = run_msdos_command (new_argv, pwd_var + 4, in, out, err, env);
1216 xfree (pwd_var);
1217 if (pid == -1)
1218 /* An error occurred while trying to run the subprocess. */
1219 report_file_error ("Spawning child process", Qnil);
1220 return pid;
1221#endif /* MSDOS */
ae76d9e1 1222#endif /* not WINDOWSNT */
80856e74
JB
1223}
1224
361358ea 1225#ifndef WINDOWSNT
a3833dfe 1226/* Move the file descriptor FD so that its number is not less than MINFD.
426b37ae 1227 If the file descriptor is moved at all, the original is freed. */
dfcf069d 1228static int
971de7fb 1229relocate_fd (int fd, int minfd)
426b37ae 1230{
a3833dfe 1231 if (fd >= minfd)
426b37ae
JB
1232 return fd;
1233 else
1234 {
cf237e27
AS
1235 int new;
1236#ifdef F_DUPFD
1237 new = fcntl (fd, F_DUPFD, minfd);
1238#else
1239 new = dup (fd);
1240 if (new != -1)
1241 /* Note that we hold the original FD open while we recurse,
1242 to guarantee we'll get a new FD if we need it. */
1243 new = relocate_fd (new, minfd);
1244#endif
426b37ae
JB
1245 if (new == -1)
1246 {
a8fe7202
AS
1247 const char *message1 = "Error while setting up child: ";
1248 const char *errmessage = strerror (errno);
1249 const char *message2 = "\n";
68c45bf0
PE
1250 emacs_write (2, message1, strlen (message1));
1251 emacs_write (2, errmessage, strlen (errmessage));
1252 emacs_write (2, message2, strlen (message2));
426b37ae
JB
1253 _exit (1);
1254 }
68c45bf0 1255 emacs_close (fd);
426b37ae
JB
1256 return new;
1257 }
1258}
361358ea 1259#endif /* not WINDOWSNT */
426b37ae 1260
012c6fcb 1261static int
a8fe7202
AS
1262getenv_internal_1 (const char *var, int varlen, char **value, int *valuelen,
1263 Lisp_Object env)
012c6fcb 1264{
db699fc6 1265 for (; CONSP (env); env = XCDR (env))
012c6fcb 1266 {
db699fc6 1267 Lisp_Object entry = XCAR (env);
d50d3dc8 1268 if (STRINGP (entry)
db699fc6 1269 && SBYTES (entry) >= varlen
bad95d8f
RS
1270#ifdef WINDOWSNT
1271 /* NT environment variables are case insensitive. */
d5db4077 1272 && ! strnicmp (SDATA (entry), var, varlen)
bad95d8f 1273#else /* not WINDOWSNT */
72af86bd 1274 && ! memcmp (SDATA (entry), var, varlen)
bad95d8f 1275#endif /* not WINDOWSNT */
a9971c6d 1276 )
012c6fcb 1277 {
db699fc6
SM
1278 if (SBYTES (entry) > varlen && SREF (entry, varlen) == '=')
1279 {
51b59d79 1280 *value = SSDATA (entry) + (varlen + 1);
db699fc6
SM
1281 *valuelen = SBYTES (entry) - (varlen + 1);
1282 return 1;
1283 }
1284 else if (SBYTES (entry) == varlen)
1285 {
1286 /* Lone variable names in Vprocess_environment mean that
1287 variable should be removed from the environment. */
1288 *value = NULL;
1289 return 1;
1290 }
1291 }
1292 }
1293 return 0;
1294}
1295
012c6fcb 1296static int
a8fe7202
AS
1297getenv_internal (const char *var, int varlen, char **value, int *valuelen,
1298 Lisp_Object frame)
012c6fcb 1299{
d2bb6598
SM
1300 /* Try to find VAR in Vprocess_environment first. */
1301 if (getenv_internal_1 (var, varlen, value, valuelen,
1302 Vprocess_environment))
1303 return *value ? 1 : 0;
f105f403 1304
d2bb6598 1305 /* For DISPLAY try to get the values from the frame or the initial env. */
de87fb59 1306 if (strcmp (var, "DISPLAY") == 0)
d2bb6598
SM
1307 {
1308 Lisp_Object display
1309 = Fframe_parameter (NILP (frame) ? selected_frame : frame, Qdisplay);
1310 if (STRINGP (display))
1311 {
51b59d79 1312 *value = SSDATA (display);
de87fb59 1313 *valuelen = SBYTES (display);
012c6fcb
JA
1314 return 1;
1315 }
d2bb6598
SM
1316 /* If still not found, Look for DISPLAY in Vinitial_environment. */
1317 if (getenv_internal_1 (var, varlen, value, valuelen,
1318 Vinitial_environment))
1319 return *value ? 1 : 0;
012c6fcb
JA
1320 }
1321
1322 return 0;
1323}
1324
f105f403 1325DEFUN ("getenv-internal", Fgetenv_internal, Sgetenv_internal, 1, 2, 0,
5990851d
KL
1326 doc: /* Get the value of environment variable VARIABLE.
1327VARIABLE should be a string. Value is nil if VARIABLE is undefined in
1328the environment. Otherwise, value is a string.
f105f403 1329
acf20901 1330This function searches `process-environment' for VARIABLE.
5990851d 1331
db699fc6 1332If optional parameter ENV is a list, then search this list instead of
acf20901
JB
1333`process-environment', and return t when encountering a negative entry
1334\(an entry for a variable with no value). */)
5842a27b 1335 (Lisp_Object variable, Lisp_Object env)
012c6fcb
JA
1336{
1337 char *value;
1338 int valuelen;
1339
5990851d 1340 CHECK_STRING (variable);
db699fc6
SM
1341 if (CONSP (env))
1342 {
1343 if (getenv_internal_1 (SDATA (variable), SBYTES (variable),
1344 &value, &valuelen, env))
1345 return value ? make_string (value, valuelen) : Qt;
1346 else
1347 return Qnil;
1348 }
1349 else if (getenv_internal (SDATA (variable), SBYTES (variable),
d2bb6598 1350 &value, &valuelen, env))
012c6fcb
JA
1351 return make_string (value, valuelen);
1352 else
1353 return Qnil;
1354}
1355
5990851d
KL
1356/* A version of getenv that consults the Lisp environment lists,
1357 easily callable from C. */
012c6fcb 1358char *
a8fe7202 1359egetenv (const char *var)
012c6fcb
JA
1360{
1361 char *value;
1362 int valuelen;
1363
f105f403 1364 if (getenv_internal (var, strlen (var), &value, &valuelen, Qnil))
012c6fcb
JA
1365 return value;
1366 else
1367 return 0;
1368}
1369
80856e74 1370\f
8de15d69 1371/* This is run before init_cmdargs. */
177c0ea7 1372
dfcf069d 1373void
971de7fb 1374init_callproc_1 (void)
8de15d69
RS
1375{
1376 char *data_dir = egetenv ("EMACSDATA");
35a2f4b8
KH
1377 char *doc_dir = egetenv ("EMACSDOC");
1378
8de15d69 1379 Vdata_directory
177c0ea7 1380 = Ffile_name_as_directory (build_string (data_dir ? data_dir
8de15d69 1381 : PATH_DATA));
35a2f4b8
KH
1382 Vdoc_directory
1383 = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
1384 : PATH_DOC));
9453ea7b 1385
e576cab4 1386 /* Check the EMACSPATH environment variable, defaulting to the
57bda87a 1387 PATH_EXEC path from epaths.h. */
e576cab4 1388 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
80856e74
JB
1389 Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
1390 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
8de15d69
RS
1391}
1392
e17f7533 1393/* This is run after init_cmdargs, when Vinstallation_directory is valid. */
8de15d69 1394
dfcf069d 1395void
971de7fb 1396init_callproc (void)
8de15d69
RS
1397{
1398 char *data_dir = egetenv ("EMACSDATA");
177c0ea7 1399
8de15d69
RS
1400 register char * sh;
1401 Lisp_Object tempdir;
1402
9cc4fad5 1403 if (!NILP (Vinstallation_directory))
8de15d69 1404 {
05630743
RS
1405 /* Add to the path the lib-src subdir of the installation dir. */
1406 Lisp_Object tem;
1407 tem = Fexpand_file_name (build_string ("lib-src"),
1408 Vinstallation_directory);
bad95d8f 1409#ifndef DOS_NT
1a6640ec 1410 /* MSDOS uses wrapped binaries, so don't do this. */
0fa248bc 1411 if (NILP (Fmember (tem, Vexec_path)))
70ec1377
RS
1412 {
1413 Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
1414 Vexec_path = Fcons (tem, Vexec_path);
1415 Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
1416 }
177c0ea7 1417
0fa248bc 1418 Vexec_directory = Ffile_name_as_directory (tem);
bad95d8f 1419#endif /* not DOS_NT */
8de15d69 1420
e17f7533
RS
1421 /* Maybe use ../etc as well as ../lib-src. */
1422 if (data_dir == 0)
1423 {
1424 tem = Fexpand_file_name (build_string ("etc"),
1425 Vinstallation_directory);
1426 Vdoc_directory = Ffile_name_as_directory (tem);
8de15d69
RS
1427 }
1428 }
7e933683
RS
1429
1430 /* Look for the files that should be in etc. We don't use
1431 Vinstallation_directory, because these files are never installed
e17f7533 1432 near the executable, and they are never in the build
7e933683
RS
1433 directory when that's different from the source directory.
1434
1435 Instead, if these files are not in the nominal place, we try the
1436 source directory. */
1437 if (data_dir == 0)
1438 {
70ec1377 1439 Lisp_Object tem, tem1, srcdir;
7e933683 1440
70ec1377
RS
1441 srcdir = Fexpand_file_name (build_string ("../src/"),
1442 build_string (PATH_DUMPLOADSEARCH));
7e933683
RS
1443 tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
1444 tem1 = Ffile_exists_p (tem);
70ec1377 1445 if (!NILP (Fequal (srcdir, Vinvocation_directory)) || NILP (tem1))
7e933683 1446 {
70ec1377 1447 Lisp_Object newdir;
7e933683
RS
1448 newdir = Fexpand_file_name (build_string ("../etc/"),
1449 build_string (PATH_DUMPLOADSEARCH));
1450 tem = Fexpand_file_name (build_string ("GNU"), newdir);
1451 tem1 = Ffile_exists_p (tem);
1452 if (!NILP (tem1))
1453 Vdata_directory = newdir;
1454 }
1455 }
80856e74 1456
d883eb62
RS
1457#ifndef CANNOT_DUMP
1458 if (initialized)
1459#endif
1460 {
1461 tempdir = Fdirectory_file_name (Vexec_directory);
d5db4077 1462 if (access (SDATA (tempdir), 0) < 0)
d883eb62
RS
1463 dir_warning ("Warning: arch-dependent data dir (%s) does not exist.\n",
1464 Vexec_directory);
1465 }
80856e74 1466
e576cab4 1467 tempdir = Fdirectory_file_name (Vdata_directory);
d5db4077 1468 if (access (SDATA (tempdir), 0) < 0)
76d5c6cf
RS
1469 dir_warning ("Warning: arch-independent data dir (%s) does not exist.\n",
1470 Vdata_directory);
e576cab4 1471
e576cab4 1472 sh = (char *) getenv ("SHELL");
80856e74 1473 Vshell_file_name = build_string (sh ? sh : "/bin/sh");
8abd035b 1474
40b49d4b
JB
1475#ifdef DOS_NT
1476 Vshared_game_score_directory = Qnil;
1477#else
63789758
RS
1478 Vshared_game_score_directory = build_string (PATH_GAME);
1479 if (NILP (Ffile_directory_p (Vshared_game_score_directory)))
1480 Vshared_game_score_directory = Qnil;
40b49d4b 1481#endif
9fefd2ba
JB
1482}
1483
dfcf069d 1484void
971de7fb 1485set_initial_environment (void)
9fefd2ba
JB
1486{
1487 register char **envp;
7bfa6d77
AS
1488#ifdef CANNOT_DUMP
1489 Vprocess_environment = Qnil;
edfda783 1490#else
7bfa6d77 1491 if (initialized)
edfda783 1492#endif
7bfa6d77 1493 {
a13f8f50 1494 for (envp = environ; *envp; envp++)
de87fb59
DN
1495 Vprocess_environment = Fcons (build_string (*envp),
1496 Vprocess_environment);
3c33c79a
SM
1497 /* Ideally, the `copy' shouldn't be necessary, but it seems it's frequent
1498 to use `delete' and friends on process-environment. */
1499 Vinitial_environment = Fcopy_sequence (Vprocess_environment);
a13f8f50 1500 }
80856e74
JB
1501}
1502
dfcf069d 1503void
971de7fb 1504syms_of_callproc (void)
80856e74 1505{
bad95d8f 1506#ifdef DOS_NT
dde990a0 1507 Qbuffer_file_type = intern_c_string ("buffer-file-type");
093650fe 1508 staticpro (&Qbuffer_file_type);
bad95d8f 1509#endif /* DOS_NT */
7e6c2178 1510
f92d51d8
CY
1511#ifndef DOS_NT
1512 Vtemp_file_name_pattern = build_string ("emacsXXXXXX");
1513#elif defined (WINDOWSNT)
1514 Vtemp_file_name_pattern = build_string ("emXXXXXX");
1515#else
1516 Vtemp_file_name_pattern = build_string ("detmp.XXX");
1517#endif
1518 staticpro (&Vtemp_file_name_pattern);
1519
29208e82 1520 DEFVAR_LISP ("shell-file-name", Vshell_file_name,
fdb82f93 1521 doc: /* *File name to load inferior shells from.
b20b29be
EZ
1522Initialized from the SHELL environment variable, or to a system-dependent
1523default if SHELL is not set. */);
80856e74 1524
29208e82 1525 DEFVAR_LISP ("exec-path", Vexec_path,
fdb82f93
PJ
1526 doc: /* *List of directories to search programs to run in subprocesses.
1527Each element is a string (directory name) or nil (try default directory). */);
80856e74 1528
29208e82 1529 DEFVAR_LISP ("exec-suffixes", Vexec_suffixes,
fdb82f93
PJ
1530 doc: /* *List of suffixes to try to find executable file names.
1531Each element is a string. */);
33d5af99 1532 Vexec_suffixes = Qnil;
b81a1b72 1533
29208e82 1534 DEFVAR_LISP ("exec-directory", Vexec_directory,
fdb82f93
PJ
1535 doc: /* Directory for executables for Emacs to invoke.
1536More generally, this includes any architecture-dependent files
1537that are built and installed from the Emacs distribution. */);
e576cab4 1538
29208e82 1539 DEFVAR_LISP ("data-directory", Vdata_directory,
fdb82f93
PJ
1540 doc: /* Directory of machine-independent files that come with GNU Emacs.
1541These are files intended for Emacs to use while it runs. */);
80856e74 1542
29208e82 1543 DEFVAR_LISP ("doc-directory", Vdoc_directory,
fdb82f93 1544 doc: /* Directory containing the DOC file that comes with GNU Emacs.
ebf24b59 1545This is usually the same as `data-directory'. */);
35a2f4b8 1546
29208e82 1547 DEFVAR_LISP ("configure-info-directory", Vconfigure_info_directory,
fdb82f93
PJ
1548 doc: /* For internal use by the build procedure only.
1549This is the name of the directory in which the build procedure installed
ebf24b59 1550Emacs's info files; the default value for `Info-default-directory-list'
fdb82f93 1551includes this. */);
ed61592a
JB
1552 Vconfigure_info_directory = build_string (PATH_INFO);
1553
29208e82 1554 DEFVAR_LISP ("shared-game-score-directory", Vshared_game_score_directory,
b065672a
CW
1555 doc: /* Directory of score files for games which come with GNU Emacs.
1556If this variable is nil, then Emacs is unable to use a shared directory. */);
40b49d4b
JB
1557#ifdef DOS_NT
1558 Vshared_game_score_directory = Qnil;
1559#else
63789758 1560 Vshared_game_score_directory = build_string (PATH_GAME);
40b49d4b 1561#endif
b065672a 1562
29208e82 1563 DEFVAR_LISP ("initial-environment", Vinitial_environment,
6b8e474c
SM
1564 doc: /* List of environment variables inherited from the parent process.
1565Each element should be a string of the form ENVVARNAME=VALUE.
1566The elements must normally be decoded (using `locale-coding-system') for use. */);
1567 Vinitial_environment = Qnil;
1568
29208e82 1569 DEFVAR_LISP ("process-environment", Vprocess_environment,
5990851d 1570 doc: /* List of overridden environment variables for subprocesses to inherit.
fdb82f93 1571Each element should be a string of the form ENVVARNAME=VALUE.
5990851d 1572
a13f8f50
KL
1573Entries in this list take precedence to those in the frame-local
1574environments. Therefore, let-binding `process-environment' is an easy
1575way to temporarily change the value of an environment variable,
1576irrespective of where it comes from. To use `process-environment' to
1577remove an environment variable, include only its name in the list,
1578without "=VALUE".
5990851d
KL
1579
1580This variable is set to nil when Emacs starts.
1581
fdb82f93
PJ
1582If multiple entries define the same variable, the first one always
1583takes precedence.
5990851d 1584
776a24a1 1585Non-ASCII characters are encoded according to the initial value of
5990851d
KL
1586`locale-coding-system', i.e. the elements must normally be decoded for
1587use.
1588
776a24a1 1589See `setenv' and `getenv'. */);
86f5ca04 1590 Vprocess_environment = Qnil;
80856e74 1591
80856e74 1592 defsubr (&Scall_process);
83fa009c 1593 defsubr (&Sgetenv_internal);
e576cab4 1594 defsubr (&Scall_process_region);
80856e74 1595}