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