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