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