(temp_output_buffer_show): Copy default-directory from current buffer.
[bpt/emacs.git] / src / w32proc.c
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
20
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
23 */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <io.h>
29 #include <fcntl.h>
30 #include <signal.h>
31
32 /* must include CRT headers *before* config.h */
33 #include "config.h"
34 #undef signal
35 #undef wait
36 #undef spawnve
37 #undef select
38 #undef kill
39
40 #include <windows.h>
41
42 #include "lisp.h"
43 #include "w32.h"
44 #include "systime.h"
45 #include "syswait.h"
46 #include "process.h"
47
48 /* Control whether spawnve quotes arguments as necessary to ensure
49 correct parsing by child process. Because not all uses of spawnve
50 are careful about constructing argv arrays, we make this behaviour
51 conditional (off by default). */
52 Lisp_Object Vw32_quote_process_args;
53
54 /* Control whether create_child causes the process' window to be
55 hidden. The default is nil. */
56 Lisp_Object Vw32_start_process_show_window;
57
58 /* Time to sleep before reading from a subprocess output pipe - this
59 avoids the inefficiency of frequently reading small amounts of data.
60 This is primarily necessary for handling DOS processes on Windows 95,
61 but is useful for W32 processes on both Windows 95 and NT as well. */
62 Lisp_Object Vw32_pipe_read_delay;
63
64 /* Control conversion of upper case file names to lower case.
65 nil means no, t means yes. */
66 Lisp_Object Vw32_downcase_file_names;
67
68 /* Keep track of whether we have already started a DOS program. */
69 BOOL dos_process_running;
70
71 #ifndef SYS_SIGLIST_DECLARED
72 extern char *sys_siglist[];
73 #endif
74
75 #ifdef EMACSDEBUG
76 void _DebPrint (const char *fmt, ...)
77 {
78 char buf[1024];
79 va_list args;
80
81 va_start (args, fmt);
82 vsprintf (buf, fmt, args);
83 va_end (args);
84 OutputDebugString (buf);
85 }
86 #endif
87
88 typedef void (_CALLBACK_ *signal_handler)(int);
89
90 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
91 static signal_handler sig_handlers[NSIG];
92
93 /* Fake signal implementation to record the SIGCHLD handler. */
94 signal_handler
95 sys_signal (int sig, signal_handler handler)
96 {
97 signal_handler old;
98
99 if (sig != SIGCHLD)
100 {
101 errno = EINVAL;
102 return SIG_ERR;
103 }
104 old = sig_handlers[sig];
105 sig_handlers[sig] = handler;
106 return old;
107 }
108
109 /* Defined in <process.h> which conflicts with the local copy */
110 #define _P_NOWAIT 1
111
112 /* Child process management list. */
113 int child_proc_count = 0;
114 child_process child_procs[ MAX_CHILDREN ];
115 child_process *dead_child = NULL;
116
117 DWORD WINAPI reader_thread (void *arg);
118
119 /* Find an unused process slot. */
120 child_process *
121 new_child (void)
122 {
123 child_process *cp;
124 DWORD id;
125
126 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
127 if (!CHILD_ACTIVE (cp))
128 goto Initialise;
129 if (child_proc_count == MAX_CHILDREN)
130 return NULL;
131 cp = &child_procs[child_proc_count++];
132
133 Initialise:
134 memset (cp, 0, sizeof(*cp));
135 cp->fd = -1;
136 cp->pid = -1;
137 cp->procinfo.hProcess = NULL;
138 cp->status = STATUS_READ_ERROR;
139
140 /* use manual reset event so that select() will function properly */
141 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
142 if (cp->char_avail)
143 {
144 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
145 if (cp->char_consumed)
146 {
147 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
148 if (cp->thrd)
149 return cp;
150 }
151 }
152 delete_child (cp);
153 return NULL;
154 }
155
156 void
157 delete_child (child_process *cp)
158 {
159 int i;
160
161 /* Should not be deleting a child that is still needed. */
162 for (i = 0; i < MAXDESC; i++)
163 if (fd_info[i].cp == cp)
164 abort ();
165
166 if (!CHILD_ACTIVE (cp))
167 return;
168
169 /* reap thread if necessary */
170 if (cp->thrd)
171 {
172 DWORD rc;
173
174 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
175 {
176 /* let the thread exit cleanly if possible */
177 cp->status = STATUS_READ_ERROR;
178 SetEvent (cp->char_consumed);
179 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
180 {
181 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
182 "with %lu for fd %ld\n", GetLastError (), cp->fd));
183 TerminateThread (cp->thrd, 0);
184 }
185 }
186 CloseHandle (cp->thrd);
187 cp->thrd = NULL;
188 }
189 if (cp->char_avail)
190 {
191 CloseHandle (cp->char_avail);
192 cp->char_avail = NULL;
193 }
194 if (cp->char_consumed)
195 {
196 CloseHandle (cp->char_consumed);
197 cp->char_consumed = NULL;
198 }
199
200 /* update child_proc_count (highest numbered slot in use plus one) */
201 if (cp == child_procs + child_proc_count - 1)
202 {
203 for (i = child_proc_count-1; i >= 0; i--)
204 if (CHILD_ACTIVE (&child_procs[i]))
205 {
206 child_proc_count = i + 1;
207 break;
208 }
209 }
210 if (i < 0)
211 child_proc_count = 0;
212 }
213
214 /* Find a child by pid. */
215 static child_process *
216 find_child_pid (DWORD pid)
217 {
218 child_process *cp;
219
220 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
221 if (CHILD_ACTIVE (cp) && pid == cp->pid)
222 return cp;
223 return NULL;
224 }
225
226
227 /* Thread proc for child process and socket reader threads. Each thread
228 is normally blocked until woken by select() to check for input by
229 reading one char. When the read completes, char_avail is signalled
230 to wake up the select emulator and the thread blocks itself again. */
231 DWORD WINAPI
232 reader_thread (void *arg)
233 {
234 child_process *cp;
235
236 /* Our identity */
237 cp = (child_process *)arg;
238
239 /* We have to wait for the go-ahead before we can start */
240 if (cp == NULL ||
241 WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
242 return 1;
243
244 for (;;)
245 {
246 int rc;
247
248 rc = _sys_read_ahead (cp->fd);
249
250 /* The name char_avail is a misnomer - it really just means the
251 read-ahead has completed, whether successfully or not. */
252 if (!SetEvent (cp->char_avail))
253 {
254 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
255 GetLastError (), cp->fd));
256 return 1;
257 }
258
259 if (rc == STATUS_READ_ERROR)
260 return 1;
261
262 /* If the read died, the child has died so let the thread die */
263 if (rc == STATUS_READ_FAILED)
264 break;
265
266 /* Wait until our input is acknowledged before reading again */
267 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
268 {
269 DebPrint (("reader_thread.WaitForSingleObject failed with "
270 "%lu for fd %ld\n", GetLastError (), cp->fd));
271 break;
272 }
273 }
274 return 0;
275 }
276
277 static BOOL
278 create_child (char *exe, char *cmdline, char *env,
279 int * pPid, child_process *cp)
280 {
281 STARTUPINFO start;
282 SECURITY_ATTRIBUTES sec_attrs;
283 SECURITY_DESCRIPTOR sec_desc;
284
285 if (cp == NULL) abort ();
286
287 memset (&start, 0, sizeof (start));
288 start.cb = sizeof (start);
289
290 #ifdef HAVE_NTGUI
291 if (NILP (Vw32_start_process_show_window))
292 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
293 else
294 start.dwFlags = STARTF_USESTDHANDLES;
295 start.wShowWindow = SW_HIDE;
296
297 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
298 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
299 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
300 #endif /* HAVE_NTGUI */
301
302 /* Explicitly specify no security */
303 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
304 goto EH_Fail;
305 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
306 goto EH_Fail;
307 sec_attrs.nLength = sizeof (sec_attrs);
308 sec_attrs.lpSecurityDescriptor = &sec_desc;
309 sec_attrs.bInheritHandle = FALSE;
310
311 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
312 CREATE_NEW_PROCESS_GROUP,
313 env, NULL,
314 &start, &cp->procinfo))
315 goto EH_Fail;
316
317 cp->pid = (int) cp->procinfo.dwProcessId;
318
319 /* Hack for Windows 95, which assigns large (ie negative) pids */
320 if (cp->pid < 0)
321 cp->pid = -cp->pid;
322
323 /* pid must fit in a Lisp_Int */
324 cp->pid = (cp->pid & VALMASK);
325
326
327 *pPid = cp->pid;
328
329 return TRUE;
330
331 EH_Fail:
332 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
333 return FALSE;
334 }
335
336 /* create_child doesn't know what emacs' file handle will be for waiting
337 on output from the child, so we need to make this additional call
338 to register the handle with the process
339 This way the select emulator knows how to match file handles with
340 entries in child_procs. */
341 void
342 register_child (int pid, int fd)
343 {
344 child_process *cp;
345
346 cp = find_child_pid (pid);
347 if (cp == NULL)
348 {
349 DebPrint (("register_child unable to find pid %lu\n", pid));
350 return;
351 }
352
353 #ifdef FULL_DEBUG
354 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
355 #endif
356
357 cp->fd = fd;
358
359 /* thread is initially blocked until select is called; set status so
360 that select will release thread */
361 cp->status = STATUS_READ_ACKNOWLEDGED;
362
363 /* attach child_process to fd_info */
364 if (fd_info[fd].cp != NULL)
365 {
366 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
367 abort ();
368 }
369
370 fd_info[fd].cp = cp;
371 }
372
373 /* When a process dies its pipe will break so the reader thread will
374 signal failure to the select emulator.
375 The select emulator then calls this routine to clean up.
376 Since the thread signaled failure we can assume it is exiting. */
377 static void
378 reap_subprocess (child_process *cp)
379 {
380 if (cp->procinfo.hProcess)
381 {
382 /* Reap the process */
383 if (WaitForSingleObject (cp->procinfo.hProcess, INFINITE) != WAIT_OBJECT_0)
384 DebPrint (("reap_subprocess.WaitForSingleObject (process) failed "
385 "with %lu for fd %ld\n", GetLastError (), cp->fd));
386 CloseHandle (cp->procinfo.hProcess);
387 cp->procinfo.hProcess = NULL;
388 CloseHandle (cp->procinfo.hThread);
389 cp->procinfo.hThread = NULL;
390
391 /* If this was a DOS process, indicate that it is now safe to
392 start a new one. */
393 if (cp->is_dos_process)
394 dos_process_running = FALSE;
395 }
396
397 /* For asynchronous children, the child_proc resources will be freed
398 when the last pipe read descriptor is closed; for synchronous
399 children, we must explicitly free the resources now because
400 register_child has not been called. */
401 if (cp->fd == -1)
402 delete_child (cp);
403 }
404
405 /* Wait for any of our existing child processes to die
406 When it does, close its handle
407 Return the pid and fill in the status if non-NULL. */
408
409 int
410 sys_wait (int *status)
411 {
412 DWORD active, retval;
413 int nh;
414 int pid;
415 child_process *cp, *cps[MAX_CHILDREN];
416 HANDLE wait_hnd[MAX_CHILDREN];
417
418 nh = 0;
419 if (dead_child != NULL)
420 {
421 /* We want to wait for a specific child */
422 wait_hnd[nh] = dead_child->procinfo.hProcess;
423 cps[nh] = dead_child;
424 if (!wait_hnd[nh]) abort ();
425 nh++;
426 }
427 else
428 {
429 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
430 /* some child_procs might be sockets; ignore them */
431 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
432 {
433 wait_hnd[nh] = cp->procinfo.hProcess;
434 cps[nh] = cp;
435 if (!wait_hnd[nh]) abort ();
436 nh++;
437 }
438 }
439
440 if (nh == 0)
441 {
442 /* Nothing to wait on, so fail */
443 errno = ECHILD;
444 return -1;
445 }
446
447 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, INFINITE);
448 if (active == WAIT_FAILED)
449 {
450 errno = EBADF;
451 return -1;
452 }
453 else if (active == WAIT_TIMEOUT)
454 {
455 /* Should never happen */
456 errno = EINVAL;
457 return -1;
458 }
459 else if (active >= WAIT_OBJECT_0 &&
460 active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
461 {
462 active -= WAIT_OBJECT_0;
463 }
464 else if (active >= WAIT_ABANDONED_0 &&
465 active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
466 {
467 active -= WAIT_ABANDONED_0;
468 }
469
470 if (!GetExitCodeProcess (wait_hnd[active], &retval))
471 {
472 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
473 GetLastError ()));
474 retval = 1;
475 }
476 if (retval == STILL_ACTIVE)
477 {
478 /* Should never happen */
479 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
480 errno = EINVAL;
481 return -1;
482 }
483
484 /* Massage the exit code from the process to match the format expected
485 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
486 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
487
488 if (retval == STATUS_CONTROL_C_EXIT)
489 retval = SIGINT;
490 else
491 retval <<= 8;
492
493 cp = cps[active];
494 pid = cp->pid;
495 #ifdef FULL_DEBUG
496 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
497 #endif
498
499 if (status)
500 {
501 *status = retval;
502 }
503 else if (synch_process_alive)
504 {
505 synch_process_alive = 0;
506
507 /* Report the status of the synchronous process. */
508 if (WIFEXITED (retval))
509 synch_process_retcode = WRETCODE (retval);
510 else if (WIFSIGNALED (retval))
511 {
512 int code = WTERMSIG (retval);
513 char *signame = 0;
514
515 if (code < NSIG)
516 {
517 /* Suppress warning if the table has const char *. */
518 signame = (char *) sys_siglist[code];
519 }
520 if (signame == 0)
521 signame = "unknown";
522
523 synch_process_death = signame;
524 }
525
526 reap_subprocess (cp);
527 }
528
529 return pid;
530 }
531
532 int
533 w32_is_dos_binary (char * filename)
534 {
535 IMAGE_DOS_HEADER dos_header;
536 DWORD signature;
537 int fd;
538 int is_dos_binary = FALSE;
539
540 fd = open (filename, O_RDONLY | O_BINARY, 0);
541 if (fd >= 0)
542 {
543 char * p = strrchr (filename, '.');
544
545 /* We can only identify DOS .com programs from the extension. */
546 if (p && stricmp (p, ".com") == 0)
547 is_dos_binary = TRUE;
548 else if (p && stricmp (p, ".bat") == 0)
549 {
550 /* A DOS shell script - it appears that CreateProcess is happy
551 to accept this (somewhat surprisingly); presumably it looks
552 at COMSPEC to determine what executable to actually invoke.
553 Therefore, we have to do the same here as well. */
554 p = getenv ("COMSPEC");
555 if (p)
556 is_dos_binary = w32_is_dos_binary (p);
557 }
558 else
559 {
560 /* Look for DOS .exe signature - if found, we must also check
561 that it isn't really a 16- or 32-bit Windows exe, since
562 both formats start with a DOS program stub. Note that
563 16-bit Windows executables use the OS/2 1.x format. */
564 if (read (fd, &dos_header, sizeof (dos_header)) == sizeof (dos_header)
565 && dos_header.e_magic == IMAGE_DOS_SIGNATURE
566 && lseek (fd, dos_header.e_lfanew, SEEK_SET) != -1)
567 {
568 if (read (fd, &signature, sizeof (signature)) != sizeof (signature)
569 || (signature != IMAGE_NT_SIGNATURE &&
570 LOWORD (signature) != IMAGE_OS2_SIGNATURE))
571 is_dos_binary = TRUE;
572 }
573 }
574 close (fd);
575 }
576
577 return is_dos_binary;
578 }
579
580 int
581 compare_env (const char **strp1, const char **strp2)
582 {
583 const char *str1 = *strp1, *str2 = *strp2;
584
585 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
586 {
587 if (tolower (*str1) > tolower (*str2))
588 return 1;
589 else if (tolower (*str1) < tolower (*str2))
590 return -1;
591 str1++, str2++;
592 }
593
594 if (*str1 == '=' && *str2 == '=')
595 return 0;
596 else if (*str1 == '=')
597 return -1;
598 else
599 return 1;
600 }
601
602 void
603 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
604 {
605 char **optr, **nptr;
606 int num;
607
608 nptr = new_envp;
609 optr = envp1;
610 while (*optr)
611 *nptr++ = *optr++;
612 num = optr - envp1;
613
614 optr = envp2;
615 while (*optr)
616 *nptr++ = *optr++;
617 num += optr - envp2;
618
619 qsort (new_envp, num, sizeof (char *), compare_env);
620
621 *nptr = NULL;
622 }
623
624 /* When a new child process is created we need to register it in our list,
625 so intercept spawn requests. */
626 int
627 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
628 {
629 Lisp_Object program, full;
630 char *cmdline, *env, *parg, **targ;
631 int arglen, numenv;
632 int pid;
633 child_process *cp;
634 int is_dos_binary;
635 /* We pass our process ID to our children by setting up an environment
636 variable in their environment. */
637 char ppid_env_var_buffer[64];
638 char *extra_env[] = {ppid_env_var_buffer, NULL};
639
640 /* We don't care about the other modes */
641 if (mode != _P_NOWAIT)
642 {
643 errno = EINVAL;
644 return -1;
645 }
646
647 /* Handle executable names without an executable suffix. */
648 program = make_string (cmdname, strlen (cmdname));
649 if (NILP (Ffile_executable_p (program)))
650 {
651 struct gcpro gcpro1;
652
653 full = Qnil;
654 GCPRO1 (program);
655 openp (Vexec_path, program, EXEC_SUFFIXES, &full, 1);
656 UNGCPRO;
657 if (NILP (full))
658 {
659 errno = EINVAL;
660 return -1;
661 }
662 cmdname = XSTRING (full)->data;
663 argv[0] = cmdname;
664 }
665
666 /* make sure cmdname is in DOS format */
667 strcpy (cmdname = alloca (strlen (cmdname) + 1), argv[0]);
668 unixtodos_filename (cmdname);
669 argv[0] = cmdname;
670
671 /* Check if program is a DOS executable, and if so whether we are
672 allowed to start it. */
673 is_dos_binary = w32_is_dos_binary (cmdname);
674 if (is_dos_binary && dos_process_running)
675 {
676 errno = EAGAIN;
677 return -1;
678 }
679
680 /* we have to do some conjuring here to put argv and envp into the
681 form CreateProcess wants... argv needs to be a space separated/null
682 terminated list of parameters, and envp is a null
683 separated/double-null terminated list of parameters.
684
685 Additionally, zero-length args and args containing whitespace need
686 to be wrapped in double quotes. Args containing embedded double
687 quotes (as opposed to enclosing quotes, which we leave alone) are
688 usually illegal (most W32 programs do not implement escaping of
689 double quotes - sad but true, at least for programs compiled with
690 MSVC), but we will escape quotes anyway for those programs that can
691 handle it. The W32 gcc library from Cygnus doubles quotes to
692 escape them, so we will use that convention.
693
694 Since I have no idea how large argv and envp are likely to be
695 we figure out list lengths on the fly and allocate them. */
696
697 /* do argv... */
698 arglen = 0;
699 targ = argv;
700 while (*targ)
701 {
702 char * p = *targ;
703 int add_quotes = 0;
704
705 if (*p == 0)
706 add_quotes = 1;
707 while (*p)
708 if (*p++ == '"')
709 {
710 /* allow for embedded quotes to be doubled - we won't
711 actually double quotes that aren't embedded though */
712 arglen++;
713 add_quotes = 1;
714 }
715 else if (*p == ' ' || *p == '\t')
716 add_quotes = 1;
717 if (add_quotes)
718 arglen += 2;
719 arglen += strlen (*targ++) + 1;
720 }
721 cmdline = alloca (arglen);
722 targ = argv;
723 parg = cmdline;
724 while (*targ)
725 {
726 char * p = *targ;
727 int add_quotes = 0;
728
729 if (*p == 0)
730 add_quotes = 1;
731
732 if (!NILP (Vw32_quote_process_args))
733 {
734 /* This is conditional because it sometimes causes more
735 problems than it solves, since argv arrays are not always
736 carefully constructed. M-x grep, for instance, passes the
737 whole command line as one argument, so it becomes
738 impossible to pass a regexp which contains spaces. */
739 for ( ; *p; p++)
740 if (*p == ' ' || *p == '\t' || *p == '"')
741 add_quotes = 1;
742 }
743 if (add_quotes)
744 {
745 char * first;
746 char * last;
747
748 p = *targ;
749 first = p;
750 last = p + strlen (p) - 1;
751 *parg++ = '"';
752 while (*p)
753 {
754 if (*p == '"' && p > first && p < last)
755 *parg++ = '"'; /* double up embedded quotes only */
756 *parg++ = *p++;
757 }
758 *parg++ = '"';
759 }
760 else
761 {
762 strcpy (parg, *targ);
763 parg += strlen (*targ);
764 }
765 *parg++ = ' ';
766 targ++;
767 }
768 *--parg = '\0';
769
770 /* and envp... */
771 arglen = 1;
772 targ = envp;
773 numenv = 1; /* for end null */
774 while (*targ)
775 {
776 arglen += strlen (*targ++) + 1;
777 numenv++;
778 }
779 /* extra env vars... */
780 sprintf (ppid_env_var_buffer, "__PARENT_PROCESS_ID=%d",
781 GetCurrentProcessId ());
782 arglen += strlen (ppid_env_var_buffer) + 1;
783 numenv++;
784
785 /* merge env passed in and extra env into one, and sort it. */
786 targ = (char **) alloca (numenv * sizeof (char *));
787 merge_and_sort_env (envp, extra_env, targ);
788
789 /* concatenate env entries. */
790 env = alloca (arglen);
791 parg = env;
792 while (*targ)
793 {
794 strcpy (parg, *targ);
795 parg += strlen (*targ++);
796 *parg++ = '\0';
797 }
798 *parg++ = '\0';
799 *parg = '\0';
800
801 cp = new_child ();
802 if (cp == NULL)
803 {
804 errno = EAGAIN;
805 return -1;
806 }
807
808 /* Now create the process. */
809 if (!create_child (cmdname, cmdline, env, &pid, cp))
810 {
811 delete_child (cp);
812 errno = ENOEXEC;
813 return -1;
814 }
815
816 if (is_dos_binary)
817 {
818 cp->is_dos_process = TRUE;
819 dos_process_running = TRUE;
820 }
821
822 return pid;
823 }
824
825 /* Emulate the select call
826 Wait for available input on any of the given rfds, or timeout if
827 a timeout is given and no input is detected
828 wfds and efds are not supported and must be NULL. */
829
830 /* From ntterm.c */
831 extern HANDLE keyboard_handle;
832 /* From process.c */
833 extern int proc_buffered_char[];
834
835 int
836 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
837 EMACS_TIME *timeout)
838 {
839 SELECT_TYPE orfds;
840 DWORD timeout_ms;
841 int i, nh, nr;
842 DWORD active;
843 child_process *cp;
844 HANDLE wait_hnd[MAXDESC];
845 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
846
847 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
848 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
849 {
850 Sleep (timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
851 return 0;
852 }
853
854 /* Otherwise, we only handle rfds, so fail otherwise. */
855 if (rfds == NULL || wfds != NULL || efds != NULL)
856 {
857 errno = EINVAL;
858 return -1;
859 }
860
861 orfds = *rfds;
862 FD_ZERO (rfds);
863 nr = 0;
864
865 /* Build a list of handles to wait on. */
866 nh = 0;
867 for (i = 0; i < nfds; i++)
868 if (FD_ISSET (i, &orfds))
869 {
870 if (i == 0)
871 {
872 if (keyboard_handle)
873 {
874 /* Handle stdin specially */
875 wait_hnd[nh] = keyboard_handle;
876 fdindex[nh] = i;
877 nh++;
878 }
879
880 /* Check for any emacs-generated input in the queue since
881 it won't be detected in the wait */
882 if (detect_input_pending ())
883 {
884 FD_SET (i, rfds);
885 return 1;
886 }
887 }
888 else
889 {
890 /* Child process and socket input */
891 cp = fd_info[i].cp;
892 if (cp)
893 {
894 int current_status = cp->status;
895
896 if (current_status == STATUS_READ_ACKNOWLEDGED)
897 {
898 /* Tell reader thread which file handle to use. */
899 cp->fd = i;
900 /* Wake up the reader thread for this process */
901 cp->status = STATUS_READ_READY;
902 if (!SetEvent (cp->char_consumed))
903 DebPrint (("nt_select.SetEvent failed with "
904 "%lu for fd %ld\n", GetLastError (), i));
905 }
906
907 #ifdef CHECK_INTERLOCK
908 /* slightly crude cross-checking of interlock between threads */
909
910 current_status = cp->status;
911 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
912 {
913 /* char_avail has been signalled, so status (which may
914 have changed) should indicate read has completed
915 but has not been acknowledged. */
916 current_status = cp->status;
917 if (current_status != STATUS_READ_SUCCEEDED &&
918 current_status != STATUS_READ_FAILED)
919 DebPrint (("char_avail set, but read not completed: status %d\n",
920 current_status));
921 }
922 else
923 {
924 /* char_avail has not been signalled, so status should
925 indicate that read is in progress; small possibility
926 that read has completed but event wasn't yet signalled
927 when we tested it (because a context switch occurred
928 or if running on separate CPUs). */
929 if (current_status != STATUS_READ_READY &&
930 current_status != STATUS_READ_IN_PROGRESS &&
931 current_status != STATUS_READ_SUCCEEDED &&
932 current_status != STATUS_READ_FAILED)
933 DebPrint (("char_avail reset, but read status is bad: %d\n",
934 current_status));
935 }
936 #endif
937 wait_hnd[nh] = cp->char_avail;
938 fdindex[nh] = i;
939 if (!wait_hnd[nh]) abort ();
940 nh++;
941 #ifdef FULL_DEBUG
942 DebPrint (("select waiting on child %d fd %d\n",
943 cp-child_procs, i));
944 #endif
945 }
946 else
947 {
948 /* Unable to find something to wait on for this fd, skip */
949 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
950 abort ();
951 }
952 }
953 }
954
955 /* Nothing to look for, so we didn't find anything */
956 if (nh == 0)
957 {
958 if (timeout)
959 Sleep (timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
960 return 0;
961 }
962
963 /*
964 Wait for input
965 If a child process dies while this is waiting, its pipe will break
966 so the reader thread will signal an error condition, thus, the wait
967 will wake up
968 */
969 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
970
971 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, timeout_ms);
972
973 if (active == WAIT_FAILED)
974 {
975 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
976 nh, timeout_ms, GetLastError ()));
977 /* don't return EBADF - this causes wait_reading_process_input to
978 abort; WAIT_FAILED is returned when single-stepping under
979 Windows 95 after switching thread focus in debugger, and
980 possibly at other times. */
981 errno = EINTR;
982 return -1;
983 }
984 else if (active == WAIT_TIMEOUT)
985 {
986 return 0;
987 }
988 else if (active >= WAIT_OBJECT_0 &&
989 active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
990 {
991 active -= WAIT_OBJECT_0;
992 }
993 else if (active >= WAIT_ABANDONED_0 &&
994 active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
995 {
996 active -= WAIT_ABANDONED_0;
997 }
998
999 /* Loop over all handles after active (now officially documented as
1000 being the first signalled handle in the array). We do this to
1001 ensure fairness, so that all channels with data available will be
1002 processed - otherwise higher numbered channels could be starved. */
1003 do
1004 {
1005 if (fdindex[active] == 0)
1006 {
1007 /* Keyboard input available */
1008 FD_SET (0, rfds);
1009 nr++;
1010 }
1011 else
1012 {
1013 /* must be a socket or pipe */
1014 int current_status;
1015
1016 cp = fd_info[ fdindex[active] ].cp;
1017
1018 /* Read ahead should have completed, either succeeding or failing. */
1019 FD_SET (fdindex[active], rfds);
1020 nr++;
1021 current_status = cp->status;
1022 if (current_status != STATUS_READ_SUCCEEDED)
1023 {
1024 if (current_status != STATUS_READ_FAILED)
1025 DebPrint (("internal error: subprocess pipe signalled "
1026 "at the wrong time (status %d)\n!", current_status));
1027
1028 /* The child_process entry for a socket or pipe will be
1029 freed when the last descriptor using it is closed; for
1030 pipes, we call the SIGCHLD handler. */
1031 if (fd_info[ fdindex[active] ].flags & FILE_PIPE)
1032 {
1033 /* The SIGCHLD handler will do a Wait so we know it won't
1034 return until the process is dead
1035 We force Wait to only wait for this process to avoid it
1036 picking up other children that happen to be dead but that
1037 we haven't noticed yet
1038 SIG_DFL for SIGCHLD is ignore? */
1039 if (sig_handlers[SIGCHLD] != SIG_DFL &&
1040 sig_handlers[SIGCHLD] != SIG_IGN)
1041 {
1042 #ifdef FULL_DEBUG
1043 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1044 cp->pid));
1045 #endif
1046 dead_child = cp;
1047 sig_handlers[SIGCHLD] (SIGCHLD);
1048 dead_child = NULL;
1049 }
1050
1051 /* Clean up the child process entry in the table */
1052 reap_subprocess (cp);
1053 }
1054 }
1055 }
1056
1057 /* Test for input on remaining channels. */
1058 while (++active < nh)
1059 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1060 break;
1061 } while (active < nh);
1062
1063 return nr;
1064 }
1065
1066 /* Substitute for certain kill () operations */
1067 int
1068 sys_kill (int pid, int sig)
1069 {
1070 child_process *cp;
1071 HANDLE proc_hand;
1072 int need_to_free = 0;
1073 int rc = 0;
1074
1075 /* Only handle signals that will result in the process dying */
1076 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1077 {
1078 errno = EINVAL;
1079 return -1;
1080 }
1081
1082 cp = find_child_pid (pid);
1083 if (cp == NULL)
1084 {
1085 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1086 if (proc_hand == NULL)
1087 {
1088 errno = EPERM;
1089 return -1;
1090 }
1091 need_to_free = 1;
1092 }
1093 else
1094 {
1095 proc_hand = cp->procinfo.hProcess;
1096 pid = cp->procinfo.dwProcessId;
1097 }
1098
1099 if (sig == SIGINT)
1100 {
1101 /* Ctrl-Break is NT equivalent of SIGINT. */
1102 if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1103 {
1104 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1105 "for pid %lu\n", GetLastError (), pid));
1106 errno = EINVAL;
1107 rc = -1;
1108 }
1109 }
1110 else
1111 {
1112 /* Kill the process. On W32 this doesn't kill child processes
1113 so it doesn't work very well for shells which is why it's not
1114 used in every case. Also, don't try to terminate DOS processes
1115 (on Windows 95), because this will hang Emacs. */
1116 if (!(cp && cp->is_dos_process)
1117 && !TerminateProcess (proc_hand, 0xff))
1118 {
1119 DebPrint (("sys_kill.TerminateProcess returned %d "
1120 "for pid %lu\n", GetLastError (), pid));
1121 errno = EINVAL;
1122 rc = -1;
1123 }
1124 }
1125
1126 if (need_to_free)
1127 CloseHandle (proc_hand);
1128
1129 return rc;
1130 }
1131
1132 extern int report_file_error (char *, Lisp_Object);
1133
1134 /* The following two routines are used to manipulate stdin, stdout, and
1135 stderr of our child processes.
1136
1137 Assuming that in, out, and err are *not* inheritable, we make them
1138 stdin, stdout, and stderr of the child as follows:
1139
1140 - Save the parent's current standard handles.
1141 - Set the std handles to inheritable duplicates of the ones being passed in.
1142 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1143 NT file handle for a crt file descriptor.)
1144 - Spawn the child, which inherits in, out, and err as stdin,
1145 stdout, and stderr. (see Spawnve)
1146 - Close the std handles passed to the child.
1147 - Reset the parent's standard handles to the saved handles.
1148 (see reset_standard_handles)
1149 We assume that the caller closes in, out, and err after calling us. */
1150
1151 void
1152 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1153 {
1154 HANDLE parent;
1155 HANDLE newstdin, newstdout, newstderr;
1156
1157 parent = GetCurrentProcess ();
1158
1159 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1160 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1161 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1162
1163 /* make inheritable copies of the new handles */
1164 if (!DuplicateHandle (parent,
1165 (HANDLE) _get_osfhandle (in),
1166 parent,
1167 &newstdin,
1168 0,
1169 TRUE,
1170 DUPLICATE_SAME_ACCESS))
1171 report_file_error ("Duplicating input handle for child", Qnil);
1172
1173 if (!DuplicateHandle (parent,
1174 (HANDLE) _get_osfhandle (out),
1175 parent,
1176 &newstdout,
1177 0,
1178 TRUE,
1179 DUPLICATE_SAME_ACCESS))
1180 report_file_error ("Duplicating output handle for child", Qnil);
1181
1182 if (!DuplicateHandle (parent,
1183 (HANDLE) _get_osfhandle (err),
1184 parent,
1185 &newstderr,
1186 0,
1187 TRUE,
1188 DUPLICATE_SAME_ACCESS))
1189 report_file_error ("Duplicating error handle for child", Qnil);
1190
1191 /* and store them as our std handles */
1192 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1193 report_file_error ("Changing stdin handle", Qnil);
1194
1195 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1196 report_file_error ("Changing stdout handle", Qnil);
1197
1198 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1199 report_file_error ("Changing stderr handle", Qnil);
1200 }
1201
1202 void
1203 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1204 {
1205 /* close the duplicated handles passed to the child */
1206 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1207 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1208 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1209
1210 /* now restore parent's saved std handles */
1211 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1212 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1213 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1214 }
1215
1216 #ifdef HAVE_SOCKETS
1217
1218 /* To avoid problems with winsock implementations that work over dial-up
1219 connections causing or requiring a connection to exist while Emacs is
1220 running, Emacs no longer automatically loads winsock on startup if it
1221 is present. Instead, it will be loaded when open-network-stream is
1222 first called.
1223
1224 To allow full control over when winsock is loaded, we provide these
1225 two functions to dynamically load and unload winsock. This allows
1226 dial-up users to only be connected when they actually need to use
1227 socket services. */
1228
1229 /* From nt.c */
1230 extern HANDLE winsock_lib;
1231 extern BOOL term_winsock (void);
1232 extern BOOL init_winsock (int load_now);
1233
1234 extern Lisp_Object Vsystem_name;
1235
1236 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1237 "Test for presence of the Windows socket library `winsock'.\n\
1238 Returns non-nil if winsock support is present, nil otherwise.\n\
1239 \n\
1240 If the optional argument LOAD-NOW is non-nil, the winsock library is\n\
1241 also loaded immediately if not already loaded. If winsock is loaded,\n\
1242 the winsock local hostname is returned (since this may be different from\n\
1243 the value of `system-name' and should supplant it), otherwise t is\n\
1244 returned to indicate winsock support is present.")
1245 (load_now)
1246 Lisp_Object load_now;
1247 {
1248 int have_winsock;
1249
1250 have_winsock = init_winsock (!NILP (load_now));
1251 if (have_winsock)
1252 {
1253 if (winsock_lib != NULL)
1254 {
1255 /* Return new value for system-name. The best way to do this
1256 is to call init_system_name, saving and restoring the
1257 original value to avoid side-effects. */
1258 Lisp_Object orig_hostname = Vsystem_name;
1259 Lisp_Object hostname;
1260
1261 init_system_name ();
1262 hostname = Vsystem_name;
1263 Vsystem_name = orig_hostname;
1264 return hostname;
1265 }
1266 return Qt;
1267 }
1268 return Qnil;
1269 }
1270
1271 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1272 0, 0, 0,
1273 "Unload the Windows socket library `winsock' if loaded.\n\
1274 This is provided to allow dial-up socket connections to be disconnected\n\
1275 when no longer needed. Returns nil without unloading winsock if any\n\
1276 socket connections still exist.")
1277 ()
1278 {
1279 return term_winsock () ? Qt : Qnil;
1280 }
1281
1282 #endif /* HAVE_SOCKETS */
1283
1284 \f
1285 syms_of_ntproc ()
1286 {
1287 #ifdef HAVE_SOCKETS
1288 defsubr (&Sw32_has_winsock);
1289 defsubr (&Sw32_unload_winsock);
1290 #endif
1291
1292 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args,
1293 "Non-nil enables quoting of process arguments to ensure correct parsing.\n\
1294 Because Windows does not directly pass argv arrays to child processes,\n\
1295 programs have to reconstruct the argv array by parsing the command\n\
1296 line string. For an argument to contain a space, it must be enclosed\n\
1297 in double quotes or it will be parsed as multiple arguments.\n\
1298 \n\
1299 However, the argument list to call-process is not always correctly\n\
1300 constructed (or arguments have already been quoted), so enabling this\n\
1301 option may cause unexpected behavior.");
1302 Vw32_quote_process_args = Qnil;
1303
1304 DEFVAR_LISP ("w32-start-process-show-window",
1305 &Vw32_start_process_show_window,
1306 "When nil, processes started via start-process hide their windows.\n\
1307 When non-nil, they show their window in the method of their choice.");
1308 Vw32_start_process_show_window = Qnil;
1309
1310 DEFVAR_INT ("w32-pipe-read-delay", &Vw32_pipe_read_delay,
1311 "Forced delay before reading subprocess output.\n\
1312 This is done to improve the buffering of subprocess output, by\n\
1313 avoiding the inefficiency of frequently reading small amounts of data.\n\
1314 \n\
1315 If positive, the value is the number of milliseconds to sleep before\n\
1316 reading the subprocess output. If negative, the magnitude is the number\n\
1317 of time slices to wait (effectively boosting the priority of the child\n\
1318 process temporarily). A value of zero disables waiting entirely.");
1319 Vw32_pipe_read_delay = 50;
1320
1321 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names,
1322 "Non-nil means convert all-upper case file names to lower case.\n\
1323 This applies when performing completions and file name expansion.");
1324 Vw32_downcase_file_names = Qnil;
1325 }
1326 /* end of ntproc.c */