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