(xcar, xcdr): Print with /x.
[emacs.git] / src / w32proc.c
blobfec9a9ddeeee1cf58f659b7a5537fc92878a1394
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
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.
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.
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.
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <io.h>
29 #include <fcntl.h>
30 #include <signal.h>
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
40 #include <windows.h>
42 #include "lisp.h"
43 #include "w32.h"
44 #include "systime.h"
45 #include "syswait.h"
46 #include "process.h"
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;
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;
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;
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;
68 /* Keep track of whether we have already started a DOS program. */
69 BOOL dos_process_running;
71 #ifndef SYS_SIGLIST_DECLARED
72 extern char *sys_siglist[];
73 #endif
75 #ifdef EMACSDEBUG
76 void _DebPrint (const char *fmt, ...)
78 char buf[1024];
79 va_list args;
81 va_start (args, fmt);
82 vsprintf (buf, fmt, args);
83 va_end (args);
84 OutputDebugString (buf);
86 #endif
88 typedef void (_CALLBACK_ *signal_handler)(int);
90 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
91 static signal_handler sig_handlers[NSIG];
93 /* Fake signal implementation to record the SIGCHLD handler. */
94 signal_handler
95 sys_signal (int sig, signal_handler handler)
97 signal_handler old;
99 if (sig != SIGCHLD)
101 errno = EINVAL;
102 return SIG_ERR;
104 old = sig_handlers[sig];
105 sig_handlers[sig] = handler;
106 return old;
109 /* Defined in <process.h> which conflicts with the local copy */
110 #define _P_NOWAIT 1
112 /* Child process management list. */
113 int child_proc_count = 0;
114 child_process child_procs[ MAX_CHILDREN ];
115 child_process *dead_child = NULL;
117 DWORD WINAPI reader_thread (void *arg);
119 /* Find an unused process slot. */
120 child_process *
121 new_child (void)
123 child_process *cp;
124 DWORD id;
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++];
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;
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)
144 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
145 if (cp->char_consumed)
147 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
148 if (cp->thrd)
149 return cp;
152 delete_child (cp);
153 return NULL;
156 void
157 delete_child (child_process *cp)
159 int i;
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 ();
166 if (!CHILD_ACTIVE (cp))
167 return;
169 /* reap thread if necessary */
170 if (cp->thrd)
172 DWORD rc;
174 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
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)
181 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
182 "with %lu for fd %ld\n", GetLastError (), cp->fd));
183 TerminateThread (cp->thrd, 0);
186 CloseHandle (cp->thrd);
187 cp->thrd = NULL;
189 if (cp->char_avail)
191 CloseHandle (cp->char_avail);
192 cp->char_avail = NULL;
194 if (cp->char_consumed)
196 CloseHandle (cp->char_consumed);
197 cp->char_consumed = NULL;
200 /* update child_proc_count (highest numbered slot in use plus one) */
201 if (cp == child_procs + child_proc_count - 1)
203 for (i = child_proc_count-1; i >= 0; i--)
204 if (CHILD_ACTIVE (&child_procs[i]))
206 child_proc_count = i + 1;
207 break;
210 if (i < 0)
211 child_proc_count = 0;
214 /* Find a child by pid. */
215 static child_process *
216 find_child_pid (DWORD pid)
218 child_process *cp;
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;
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)
234 child_process *cp;
236 /* Our identity */
237 cp = (child_process *)arg;
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;
244 for (;;)
246 int rc;
248 rc = _sys_read_ahead (cp->fd);
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))
254 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
255 GetLastError (), cp->fd));
256 return 1;
259 if (rc == STATUS_READ_ERROR)
260 return 1;
262 /* If the read died, the child has died so let the thread die */
263 if (rc == STATUS_READ_FAILED)
264 break;
266 /* Wait until our input is acknowledged before reading again */
267 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
269 DebPrint (("reader_thread.WaitForSingleObject failed with "
270 "%lu for fd %ld\n", GetLastError (), cp->fd));
271 break;
274 return 0;
277 static BOOL
278 create_child (char *exe, char *cmdline, char *env,
279 int * pPid, child_process *cp)
281 STARTUPINFO start;
282 SECURITY_ATTRIBUTES sec_attrs;
283 SECURITY_DESCRIPTOR sec_desc;
285 if (cp == NULL) abort ();
287 memset (&start, 0, sizeof (start));
288 start.cb = sizeof (start);
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;
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 */
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;
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;
317 cp->pid = (int) cp->procinfo.dwProcessId;
319 /* Hack for Windows 95, which assigns large (ie negative) pids */
320 if (cp->pid < 0)
321 cp->pid = -cp->pid;
323 /* pid must fit in a Lisp_Int */
324 cp->pid = (cp->pid & VALMASK);
327 *pPid = cp->pid;
329 return TRUE;
331 EH_Fail:
332 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
333 return FALSE;
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)
344 child_process *cp;
346 cp = find_child_pid (pid);
347 if (cp == NULL)
349 DebPrint (("register_child unable to find pid %lu\n", pid));
350 return;
353 #ifdef FULL_DEBUG
354 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
355 #endif
357 cp->fd = fd;
359 /* thread is initially blocked until select is called; set status so
360 that select will release thread */
361 cp->status = STATUS_READ_ACKNOWLEDGED;
363 /* attach child_process to fd_info */
364 if (fd_info[fd].cp != NULL)
366 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
367 abort ();
370 fd_info[fd].cp = cp;
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)
380 if (cp->procinfo.hProcess)
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;
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;
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);
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. */
409 int
410 sys_wait (int *status)
412 DWORD active, retval;
413 int nh;
414 int pid;
415 child_process *cp, *cps[MAX_CHILDREN];
416 HANDLE wait_hnd[MAX_CHILDREN];
418 nh = 0;
419 if (dead_child != NULL)
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++;
427 else
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)
433 wait_hnd[nh] = cp->procinfo.hProcess;
434 cps[nh] = cp;
435 if (!wait_hnd[nh]) abort ();
436 nh++;
440 if (nh == 0)
442 /* Nothing to wait on, so fail */
443 errno = ECHILD;
444 return -1;
447 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, INFINITE);
448 if (active == WAIT_FAILED)
450 errno = EBADF;
451 return -1;
453 else if (active == WAIT_TIMEOUT)
455 /* Should never happen */
456 errno = EINVAL;
457 return -1;
459 else if (active >= WAIT_OBJECT_0 &&
460 active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
462 active -= WAIT_OBJECT_0;
464 else if (active >= WAIT_ABANDONED_0 &&
465 active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
467 active -= WAIT_ABANDONED_0;
470 if (!GetExitCodeProcess (wait_hnd[active], &retval))
472 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
473 GetLastError ()));
474 retval = 1;
476 if (retval == STILL_ACTIVE)
478 /* Should never happen */
479 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
480 errno = EINVAL;
481 return -1;
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. */
488 if (retval == STATUS_CONTROL_C_EXIT)
489 retval = SIGINT;
490 else
491 retval <<= 8;
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
499 if (status)
501 *status = retval;
503 else if (synch_process_alive)
505 synch_process_alive = 0;
507 /* Report the status of the synchronous process. */
508 if (WIFEXITED (retval))
509 synch_process_retcode = WRETCODE (retval);
510 else if (WIFSIGNALED (retval))
512 int code = WTERMSIG (retval);
513 char *signame = 0;
515 if (code < NSIG)
517 /* Suppress warning if the table has const char *. */
518 signame = (char *) sys_siglist[code];
520 if (signame == 0)
521 signame = "unknown";
523 synch_process_death = signame;
526 reap_subprocess (cp);
529 return pid;
533 w32_is_dos_binary (char * filename)
535 IMAGE_DOS_HEADER dos_header;
536 DWORD signature;
537 int fd;
538 int is_dos_binary = FALSE;
540 fd = open (filename, O_RDONLY | O_BINARY, 0);
541 if (fd >= 0)
543 char * p = strrchr (filename, '.');
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)
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);
558 else
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)
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;
574 close (fd);
577 return is_dos_binary;
581 compare_env (const char **strp1, const char **strp2)
583 const char *str1 = *strp1, *str2 = *strp2;
585 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
587 if (tolower (*str1) > tolower (*str2))
588 return 1;
589 else if (tolower (*str1) < tolower (*str2))
590 return -1;
591 str1++, str2++;
594 if (*str1 == '=' && *str2 == '=')
595 return 0;
596 else if (*str1 == '=')
597 return -1;
598 else
599 return 1;
602 void
603 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
605 char **optr, **nptr;
606 int num;
608 nptr = new_envp;
609 optr = envp1;
610 while (*optr)
611 *nptr++ = *optr++;
612 num = optr - envp1;
614 optr = envp2;
615 while (*optr)
616 *nptr++ = *optr++;
617 num += optr - envp2;
619 qsort (new_envp, num, sizeof (char *), compare_env);
621 *nptr = NULL;
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)
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};
640 /* We don't care about the other modes */
641 if (mode != _P_NOWAIT)
643 errno = EINVAL;
644 return -1;
647 /* Handle executable names without an executable suffix. */
648 program = make_string (cmdname, strlen (cmdname));
649 if (NILP (Ffile_executable_p (program)))
651 struct gcpro gcpro1;
653 full = Qnil;
654 GCPRO1 (program);
655 openp (Vexec_path, program, EXEC_SUFFIXES, &full, 1);
656 UNGCPRO;
657 if (NILP (full))
659 errno = EINVAL;
660 return -1;
662 cmdname = XSTRING (full)->data;
663 argv[0] = cmdname;
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;
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)
676 errno = EAGAIN;
677 return -1;
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.
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.
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. */
697 /* do argv... */
698 arglen = 0;
699 targ = argv;
700 while (*targ)
702 char * p = *targ;
703 int add_quotes = 0;
705 if (*p == 0)
706 add_quotes = 1;
707 while (*p)
708 if (*p++ == '"')
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;
715 else if (*p == ' ' || *p == '\t')
716 add_quotes = 1;
717 if (add_quotes)
718 arglen += 2;
719 arglen += strlen (*targ++) + 1;
721 cmdline = alloca (arglen);
722 targ = argv;
723 parg = cmdline;
724 while (*targ)
726 char * p = *targ;
727 int add_quotes = 0;
729 if (*p == 0)
730 add_quotes = 1;
732 if (!NILP (Vw32_quote_process_args))
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;
743 if (add_quotes)
745 char * first;
746 char * last;
748 p = *targ;
749 first = p;
750 last = p + strlen (p) - 1;
751 *parg++ = '"';
752 while (*p)
754 if (*p == '"' && p > first && p < last)
755 *parg++ = '"'; /* double up embedded quotes only */
756 *parg++ = *p++;
758 *parg++ = '"';
760 else
762 strcpy (parg, *targ);
763 parg += strlen (*targ);
765 *parg++ = ' ';
766 targ++;
768 *--parg = '\0';
770 /* and envp... */
771 arglen = 1;
772 targ = envp;
773 numenv = 1; /* for end null */
774 while (*targ)
776 arglen += strlen (*targ++) + 1;
777 numenv++;
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++;
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);
789 /* concatenate env entries. */
790 env = alloca (arglen);
791 parg = env;
792 while (*targ)
794 strcpy (parg, *targ);
795 parg += strlen (*targ++);
796 *parg++ = '\0';
798 *parg++ = '\0';
799 *parg = '\0';
801 cp = new_child ();
802 if (cp == NULL)
804 errno = EAGAIN;
805 return -1;
808 /* Now create the process. */
809 if (!create_child (cmdname, cmdline, env, &pid, cp))
811 delete_child (cp);
812 errno = ENOEXEC;
813 return -1;
816 if (is_dos_binary)
818 cp->is_dos_process = TRUE;
819 dos_process_running = TRUE;
822 return pid;
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. */
830 /* From ntterm.c */
831 extern HANDLE keyboard_handle;
832 /* From process.c */
833 extern int proc_buffered_char[];
835 int
836 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
837 EMACS_TIME *timeout)
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 */
847 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
848 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
850 Sleep (timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
851 return 0;
854 /* Otherwise, we only handle rfds, so fail otherwise. */
855 if (rfds == NULL || wfds != NULL || efds != NULL)
857 errno = EINVAL;
858 return -1;
861 orfds = *rfds;
862 FD_ZERO (rfds);
863 nr = 0;
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))
870 if (i == 0)
872 if (keyboard_handle)
874 /* Handle stdin specially */
875 wait_hnd[nh] = keyboard_handle;
876 fdindex[nh] = i;
877 nh++;
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 ())
884 FD_SET (i, rfds);
885 return 1;
888 else
890 /* Child process and socket input */
891 cp = fd_info[i].cp;
892 if (cp)
894 int current_status = cp->status;
896 if (current_status == STATUS_READ_ACKNOWLEDGED)
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));
907 #ifdef CHECK_INTERLOCK
908 /* slightly crude cross-checking of interlock between threads */
910 current_status = cp->status;
911 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
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));
922 else
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));
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
946 else
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 ();
955 /* Nothing to look for, so we didn't find anything */
956 if (nh == 0)
958 if (timeout)
959 Sleep (timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
960 return 0;
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
969 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
971 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, timeout_ms);
973 if (active == WAIT_FAILED)
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;
984 else if (active == WAIT_TIMEOUT)
986 return 0;
988 else if (active >= WAIT_OBJECT_0 &&
989 active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
991 active -= WAIT_OBJECT_0;
993 else if (active >= WAIT_ABANDONED_0 &&
994 active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
996 active -= WAIT_ABANDONED_0;
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. */
1005 if (fdindex[active] == 0)
1007 /* Keyboard input available */
1008 FD_SET (0, rfds);
1009 nr++;
1011 else
1013 /* must be a socket or pipe */
1014 int current_status;
1016 cp = fd_info[ fdindex[active] ].cp;
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)
1024 if (current_status != STATUS_READ_FAILED)
1025 DebPrint (("internal error: subprocess pipe signalled "
1026 "at the wrong time (status %d)\n!", current_status));
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)
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)
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;
1051 /* Clean up the child process entry in the table */
1052 reap_subprocess (cp);
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);
1063 return nr;
1066 /* Substitute for certain kill () operations */
1067 int
1068 sys_kill (int pid, int sig)
1070 child_process *cp;
1071 HANDLE proc_hand;
1072 int need_to_free = 0;
1073 int rc = 0;
1075 /* Only handle signals that will result in the process dying */
1076 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1078 errno = EINVAL;
1079 return -1;
1082 cp = find_child_pid (pid);
1083 if (cp == NULL)
1085 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1086 if (proc_hand == NULL)
1088 errno = EPERM;
1089 return -1;
1091 need_to_free = 1;
1093 else
1095 proc_hand = cp->procinfo.hProcess;
1096 pid = cp->procinfo.dwProcessId;
1099 if (sig == SIGINT)
1101 /* Ctrl-Break is NT equivalent of SIGINT. */
1102 if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1104 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1105 "for pid %lu\n", GetLastError (), pid));
1106 errno = EINVAL;
1107 rc = -1;
1110 else
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))
1119 DebPrint (("sys_kill.TerminateProcess returned %d "
1120 "for pid %lu\n", GetLastError (), pid));
1121 errno = EINVAL;
1122 rc = -1;
1126 if (need_to_free)
1127 CloseHandle (proc_hand);
1129 return rc;
1132 extern int report_file_error (char *, Lisp_Object);
1134 /* The following two routines are used to manipulate stdin, stdout, and
1135 stderr of our child processes.
1137 Assuming that in, out, and err are *not* inheritable, we make them
1138 stdin, stdout, and stderr of the child as follows:
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. */
1151 void
1152 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1154 HANDLE parent;
1155 HANDLE newstdin, newstdout, newstderr;
1157 parent = GetCurrentProcess ();
1159 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1160 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1161 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1163 /* make inheritable copies of the new handles */
1164 if (!DuplicateHandle (parent,
1165 (HANDLE) _get_osfhandle (in),
1166 parent,
1167 &newstdin,
1169 TRUE,
1170 DUPLICATE_SAME_ACCESS))
1171 report_file_error ("Duplicating input handle for child", Qnil);
1173 if (!DuplicateHandle (parent,
1174 (HANDLE) _get_osfhandle (out),
1175 parent,
1176 &newstdout,
1178 TRUE,
1179 DUPLICATE_SAME_ACCESS))
1180 report_file_error ("Duplicating output handle for child", Qnil);
1182 if (!DuplicateHandle (parent,
1183 (HANDLE) _get_osfhandle (err),
1184 parent,
1185 &newstderr,
1187 TRUE,
1188 DUPLICATE_SAME_ACCESS))
1189 report_file_error ("Duplicating error handle for child", Qnil);
1191 /* and store them as our std handles */
1192 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1193 report_file_error ("Changing stdin handle", Qnil);
1195 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1196 report_file_error ("Changing stdout handle", Qnil);
1198 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1199 report_file_error ("Changing stderr handle", Qnil);
1202 void
1203 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
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));
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]);
1216 #ifdef HAVE_SOCKETS
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.
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. */
1229 /* From nt.c */
1230 extern HANDLE winsock_lib;
1231 extern BOOL term_winsock (void);
1232 extern BOOL init_winsock (int load_now);
1234 extern Lisp_Object Vsystem_name;
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\
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;
1248 int have_winsock;
1250 have_winsock = init_winsock (!NILP (load_now));
1251 if (have_winsock)
1253 if (winsock_lib != NULL)
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;
1261 init_system_name ();
1262 hostname = Vsystem_name;
1263 Vsystem_name = orig_hostname;
1264 return hostname;
1266 return Qt;
1268 return Qnil;
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.")
1279 return term_winsock () ? Qt : Qnil;
1282 #endif /* HAVE_SOCKETS */
1285 syms_of_ntproc ()
1287 #ifdef HAVE_SOCKETS
1288 defsubr (&Sw32_has_winsock);
1289 defsubr (&Sw32_unload_winsock);
1290 #endif
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\
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;
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;
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\
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;
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;
1326 /* end of ntproc.c */