(display-time): Call display-time-mode.
[emacs.git] / src / w32proc.c
blob01ffd33bebb1aa1df81a34da1e2ad03c92b7690b
1 /* Process support for Windows NT port of GNU EMACS.
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 "nt.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 Vwin32_quote_process_args;
54 /* Time to sleep before reading from a subprocess output pipe - this
55 avoids the inefficiency of frequently reading small amounts of data.
56 This is primarily necessary for handling DOS processes on Windows 95,
57 but is useful for Win32 processes on both Win95 and NT as well. */
58 Lisp_Object Vwin32_pipe_read_delay;
60 /* Control conversion of upper case file names to lower case.
61 nil means no, t means yes. */
62 Lisp_Object Vwin32_downcase_file_names;
64 /* Keep track of whether we have already started a DOS program. */
65 BOOL dos_process_running;
67 #ifndef SYS_SIGLIST_DECLARED
68 extern char *sys_siglist[];
69 #endif
71 #ifdef EMACSDEBUG
72 void _DebPrint (const char *fmt, ...)
74 char buf[1024];
75 va_list args;
77 va_start (args, fmt);
78 vsprintf (buf, fmt, args);
79 va_end (args);
80 OutputDebugString (buf);
82 #endif
84 typedef void (_CALLBACK_ *signal_handler)(int);
86 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
87 static signal_handler sig_handlers[NSIG];
89 /* Fake signal implementation to record the SIGCHLD handler. */
90 signal_handler
91 sys_signal (int sig, signal_handler handler)
93 signal_handler old;
95 if (sig != SIGCHLD)
97 errno = EINVAL;
98 return SIG_ERR;
100 old = sig_handlers[sig];
101 sig_handlers[sig] = handler;
102 return old;
105 /* Defined in <process.h> which conflicts with the local copy */
106 #define _P_NOWAIT 1
108 /* Child process management list. */
109 int child_proc_count = 0;
110 child_process child_procs[ MAX_CHILDREN ];
111 child_process *dead_child = NULL;
113 DWORD WINAPI reader_thread (void *arg);
115 /* Find an unused process slot. */
116 child_process *
117 new_child (void)
119 child_process *cp;
120 DWORD id;
122 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
123 if (!CHILD_ACTIVE (cp))
124 goto Initialise;
125 if (child_proc_count == MAX_CHILDREN)
126 return NULL;
127 cp = &child_procs[child_proc_count++];
129 Initialise:
130 memset (cp, 0, sizeof(*cp));
131 cp->fd = -1;
132 cp->pid = -1;
133 cp->procinfo.hProcess = NULL;
134 cp->status = STATUS_READ_ERROR;
136 /* use manual reset event so that select() will function properly */
137 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
138 if (cp->char_avail)
140 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
141 if (cp->char_consumed)
143 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
144 if (cp->thrd)
145 return cp;
148 delete_child (cp);
149 return NULL;
152 void
153 delete_child (child_process *cp)
155 int i;
157 /* Should not be deleting a child that is still needed. */
158 for (i = 0; i < MAXDESC; i++)
159 if (fd_info[i].cp == cp)
160 abort ();
162 if (!CHILD_ACTIVE (cp))
163 return;
165 /* reap thread if necessary */
166 if (cp->thrd)
168 DWORD rc;
170 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
172 /* let the thread exit cleanly if possible */
173 cp->status = STATUS_READ_ERROR;
174 SetEvent (cp->char_consumed);
175 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
177 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
178 "with %lu for fd %ld\n", GetLastError (), cp->fd));
179 TerminateThread (cp->thrd, 0);
182 CloseHandle (cp->thrd);
183 cp->thrd = NULL;
185 if (cp->char_avail)
187 CloseHandle (cp->char_avail);
188 cp->char_avail = NULL;
190 if (cp->char_consumed)
192 CloseHandle (cp->char_consumed);
193 cp->char_consumed = NULL;
196 /* update child_proc_count (highest numbered slot in use plus one) */
197 if (cp == child_procs + child_proc_count - 1)
199 for (i = child_proc_count-1; i >= 0; i--)
200 if (CHILD_ACTIVE (&child_procs[i]))
202 child_proc_count = i + 1;
203 break;
206 if (i < 0)
207 child_proc_count = 0;
210 /* Find a child by pid. */
211 static child_process *
212 find_child_pid (DWORD pid)
214 child_process *cp;
216 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
217 if (CHILD_ACTIVE (cp) && pid == cp->pid)
218 return cp;
219 return NULL;
223 /* Thread proc for child process and socket reader threads. Each thread
224 is normally blocked until woken by select() to check for input by
225 reading one char. When the read completes, char_avail is signalled
226 to wake up the select emulator and the thread blocks itself again. */
227 DWORD WINAPI
228 reader_thread (void *arg)
230 child_process *cp;
232 /* Our identity */
233 cp = (child_process *)arg;
235 /* We have to wait for the go-ahead before we can start */
236 if (cp == NULL ||
237 WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
238 return 1;
240 for (;;)
242 int rc;
244 rc = _sys_read_ahead (cp->fd);
246 /* The name char_avail is a misnomer - it really just means the
247 read-ahead has completed, whether successfully or not. */
248 if (!SetEvent (cp->char_avail))
250 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
251 GetLastError (), cp->fd));
252 return 1;
255 if (rc == STATUS_READ_ERROR)
256 return 1;
258 /* If the read died, the child has died so let the thread die */
259 if (rc == STATUS_READ_FAILED)
260 break;
262 /* Wait until our input is acknowledged before reading again */
263 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
265 DebPrint (("reader_thread.WaitForSingleObject failed with "
266 "%lu for fd %ld\n", GetLastError (), cp->fd));
267 break;
270 return 0;
273 static BOOL
274 create_child (char *exe, char *cmdline, char *env,
275 int * pPid, child_process *cp)
277 STARTUPINFO start;
278 SECURITY_ATTRIBUTES sec_attrs;
279 SECURITY_DESCRIPTOR sec_desc;
281 if (cp == NULL) abort ();
283 memset (&start, 0, sizeof (start));
284 start.cb = sizeof (start);
286 #ifdef HAVE_NTGUI
287 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
288 start.wShowWindow = SW_HIDE;
290 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
291 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
292 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
293 #endif /* HAVE_NTGUI */
295 /* Explicitly specify no security */
296 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
297 goto EH_Fail;
298 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
299 goto EH_Fail;
300 sec_attrs.nLength = sizeof (sec_attrs);
301 sec_attrs.lpSecurityDescriptor = &sec_desc;
302 sec_attrs.bInheritHandle = FALSE;
304 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
305 CREATE_NEW_PROCESS_GROUP,
306 env, NULL,
307 &start, &cp->procinfo))
308 goto EH_Fail;
310 cp->pid = (int) cp->procinfo.dwProcessId;
312 /* Hack for Windows 95, which assigns large (ie negative) pids */
313 if (cp->pid < 0)
314 cp->pid = -cp->pid;
316 /* pid must fit in a Lisp_Int */
317 cp->pid = (cp->pid & VALMASK);
320 *pPid = cp->pid;
322 return TRUE;
324 EH_Fail:
325 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
326 return FALSE;
329 /* create_child doesn't know what emacs' file handle will be for waiting
330 on output from the child, so we need to make this additional call
331 to register the handle with the process
332 This way the select emulator knows how to match file handles with
333 entries in child_procs. */
334 void
335 register_child (int pid, int fd)
337 child_process *cp;
339 cp = find_child_pid (pid);
340 if (cp == NULL)
342 DebPrint (("register_child unable to find pid %lu\n", pid));
343 return;
346 #ifdef FULL_DEBUG
347 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
348 #endif
350 cp->fd = fd;
352 /* thread is initially blocked until select is called; set status so
353 that select will release thread */
354 cp->status = STATUS_READ_ACKNOWLEDGED;
356 /* attach child_process to fd_info */
357 if (fd_info[fd].cp != NULL)
359 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
360 abort ();
363 fd_info[fd].cp = cp;
366 /* When a process dies its pipe will break so the reader thread will
367 signal failure to the select emulator.
368 The select emulator then calls this routine to clean up.
369 Since the thread signaled failure we can assume it is exiting. */
370 static void
371 reap_subprocess (child_process *cp)
373 if (cp->procinfo.hProcess)
375 /* Reap the process */
376 if (WaitForSingleObject (cp->procinfo.hProcess, INFINITE) != WAIT_OBJECT_0)
377 DebPrint (("reap_subprocess.WaitForSingleObject (process) failed "
378 "with %lu for fd %ld\n", GetLastError (), cp->fd));
379 CloseHandle (cp->procinfo.hProcess);
380 cp->procinfo.hProcess = NULL;
381 CloseHandle (cp->procinfo.hThread);
382 cp->procinfo.hThread = NULL;
384 /* If this was a DOS process, indicate that it is now safe to
385 start a new one. */
386 if (cp->is_dos_process)
387 dos_process_running = FALSE;
390 /* For asynchronous children, the child_proc resources will be freed
391 when the last pipe read descriptor is closed; for synchronous
392 children, we must explicitly free the resources now because
393 register_child has not been called. */
394 if (cp->fd == -1)
395 delete_child (cp);
398 /* Wait for any of our existing child processes to die
399 When it does, close its handle
400 Return the pid and fill in the status if non-NULL. */
402 int
403 sys_wait (int *status)
405 DWORD active, retval;
406 int nh;
407 int pid;
408 child_process *cp, *cps[MAX_CHILDREN];
409 HANDLE wait_hnd[MAX_CHILDREN];
411 nh = 0;
412 if (dead_child != NULL)
414 /* We want to wait for a specific child */
415 wait_hnd[nh] = dead_child->procinfo.hProcess;
416 cps[nh] = dead_child;
417 if (!wait_hnd[nh]) abort ();
418 nh++;
420 else
422 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
423 /* some child_procs might be sockets; ignore them */
424 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
426 wait_hnd[nh] = cp->procinfo.hProcess;
427 cps[nh] = cp;
428 if (!wait_hnd[nh]) abort ();
429 nh++;
433 if (nh == 0)
435 /* Nothing to wait on, so fail */
436 errno = ECHILD;
437 return -1;
440 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, INFINITE);
441 if (active == WAIT_FAILED)
443 errno = EBADF;
444 return -1;
446 else if (active == WAIT_TIMEOUT)
448 /* Should never happen */
449 errno = EINVAL;
450 return -1;
452 else if (active >= WAIT_OBJECT_0 &&
453 active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
455 active -= WAIT_OBJECT_0;
457 else if (active >= WAIT_ABANDONED_0 &&
458 active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
460 active -= WAIT_ABANDONED_0;
463 if (!GetExitCodeProcess (wait_hnd[active], &retval))
465 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
466 GetLastError ()));
467 retval = 1;
469 if (retval == STILL_ACTIVE)
471 /* Should never happen */
472 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
473 errno = EINVAL;
474 return -1;
477 /* Massage the exit code from the process to match the format expected
478 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
479 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
481 if (retval == STATUS_CONTROL_C_EXIT)
482 retval = SIGINT;
483 else
484 retval <<= 8;
486 cp = cps[active];
487 pid = cp->pid;
488 #ifdef FULL_DEBUG
489 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
490 #endif
492 if (status)
494 *status = retval;
496 else if (synch_process_alive)
498 synch_process_alive = 0;
500 /* Report the status of the synchronous process. */
501 if (WIFEXITED (retval))
502 synch_process_retcode = WRETCODE (retval);
503 else if (WIFSIGNALED (retval))
505 int code = WTERMSIG (retval);
506 char *signame = 0;
508 if (code < NSIG)
510 /* Suppress warning if the table has const char *. */
511 signame = (char *) sys_siglist[code];
513 if (signame == 0)
514 signame = "unknown";
516 synch_process_death = signame;
519 reap_subprocess (cp);
522 return pid;
526 win32_is_dos_binary (char * filename)
528 IMAGE_DOS_HEADER dos_header;
529 DWORD signature;
530 int fd;
531 int is_dos_binary = FALSE;
533 fd = open (filename, O_RDONLY | O_BINARY, 0);
534 if (fd >= 0)
536 char * p = strrchr (filename, '.');
538 /* We can only identify DOS .com programs from the extension. */
539 if (p && stricmp (p, ".com") == 0)
540 is_dos_binary = TRUE;
541 else if (p && stricmp (p, ".bat") == 0)
543 /* A DOS shell script - it appears that CreateProcess is happy
544 to accept this (somewhat surprisingly); presumably it looks
545 at COMSPEC to determine what executable to actually invoke.
546 Therefore, we have to do the same here as well. */
547 p = getenv ("COMSPEC");
548 if (p)
549 is_dos_binary = win32_is_dos_binary (p);
551 else
553 /* Look for DOS .exe signature - if found, we must also check
554 that it isn't really a 16- or 32-bit Windows exe, since
555 both formats start with a DOS program stub. Note that
556 16-bit Windows executables use the OS/2 1.x format. */
557 if (read (fd, &dos_header, sizeof (dos_header)) == sizeof (dos_header)
558 && dos_header.e_magic == IMAGE_DOS_SIGNATURE
559 && lseek (fd, dos_header.e_lfanew, SEEK_SET) != -1)
561 if (read (fd, &signature, sizeof (signature)) != sizeof (signature)
562 || (signature != IMAGE_NT_SIGNATURE &&
563 LOWORD (signature) != IMAGE_OS2_SIGNATURE))
564 is_dos_binary = TRUE;
567 close (fd);
570 return is_dos_binary;
573 /* We pass our process ID to our children by setting up an environment
574 variable in their environment. */
575 char ppid_env_var_buffer[64];
577 /* When a new child process is created we need to register it in our list,
578 so intercept spawn requests. */
579 int
580 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
582 Lisp_Object program, full;
583 char *cmdline, *env, *parg, **targ;
584 int arglen;
585 int pid;
586 child_process *cp;
587 int is_dos_binary;
589 /* We don't care about the other modes */
590 if (mode != _P_NOWAIT)
592 errno = EINVAL;
593 return -1;
596 /* Handle executable names without an executable suffix. */
597 program = make_string (cmdname, strlen (cmdname));
598 if (NILP (Ffile_executable_p (program)))
600 struct gcpro gcpro1;
602 full = Qnil;
603 GCPRO1 (program);
604 openp (Vexec_path, program, EXEC_SUFFIXES, &full, 1);
605 UNGCPRO;
606 if (NILP (full))
608 errno = EINVAL;
609 return -1;
611 cmdname = XSTRING (full)->data;
612 argv[0] = cmdname;
615 /* make sure cmdname is in DOS format */
616 strcpy (cmdname = alloca (strlen (cmdname) + 1), argv[0]);
617 unixtodos_filename (cmdname);
618 argv[0] = cmdname;
620 /* Check if program is a DOS executable, and if so whether we are
621 allowed to start it. */
622 is_dos_binary = win32_is_dos_binary (cmdname);
623 if (is_dos_binary && dos_process_running)
625 errno = EAGAIN;
626 return -1;
629 /* we have to do some conjuring here to put argv and envp into the
630 form CreateProcess wants... argv needs to be a space separated/null
631 terminated list of parameters, and envp is a null
632 separated/double-null terminated list of parameters.
634 Additionally, zero-length args and args containing whitespace need
635 to be wrapped in double quotes. Args containing embedded double
636 quotes (as opposed to enclosing quotes, which we leave alone) are
637 usually illegal (most Win32 programs do not implement escaping of
638 double quotes - sad but true, at least for programs compiled with
639 MSVC), but we will escape quotes anyway for those programs that can
640 handle it. The Win32 gcc library from Cygnus doubles quotes to
641 escape them, so we will use that convention.
643 Since I have no idea how large argv and envp are likely to be
644 we figure out list lengths on the fly and allocate them. */
646 /* do argv... */
647 arglen = 0;
648 targ = argv;
649 while (*targ)
651 char * p = *targ;
652 int add_quotes = 0;
654 if (*p == 0)
655 add_quotes = 1;
656 while (*p)
657 if (*p++ == '"')
659 /* allow for embedded quotes to be doubled - we won't
660 actually double quotes that aren't embedded though */
661 arglen++;
662 add_quotes = 1;
664 else if (*p == ' ' || *p == '\t')
665 add_quotes = 1;
666 if (add_quotes)
667 arglen += 2;
668 arglen += strlen (*targ++) + 1;
670 cmdline = alloca (arglen);
671 targ = argv;
672 parg = cmdline;
673 while (*targ)
675 char * p = *targ;
676 int add_quotes = 0;
678 if (*p == 0)
679 add_quotes = 1;
681 if (!NILP (Vwin32_quote_process_args))
683 /* This is conditional because it sometimes causes more
684 problems than it solves, since argv arrays are not always
685 carefully constructed. M-x grep, for instance, passes the
686 whole command line as one argument, so it becomes
687 impossible to pass a regexp which contains spaces. */
688 for ( ; *p; p++)
689 if (*p == ' ' || *p == '\t' || *p == '"')
690 add_quotes = 1;
692 if (add_quotes)
694 char * first;
695 char * last;
697 p = *targ;
698 first = p;
699 last = p + strlen (p) - 1;
700 *parg++ = '"';
701 while (*p)
703 if (*p == '"' && p > first && p < last)
704 *parg++ = '"'; /* double up embedded quotes only */
705 *parg++ = *p++;
707 *parg++ = '"';
709 else
711 strcpy (parg, *targ);
712 parg += strlen (*targ);
714 *parg++ = ' ';
715 targ++;
717 *--parg = '\0';
719 /* and envp... */
720 arglen = 1;
721 targ = envp;
722 while (*targ)
724 arglen += strlen (*targ++) + 1;
726 sprintf (ppid_env_var_buffer, "__PARENT_PROCESS_ID=%d",
727 GetCurrentProcessId ());
728 arglen += strlen (ppid_env_var_buffer) + 1;
730 env = alloca (arglen);
731 targ = envp;
732 parg = env;
733 while (*targ)
735 strcpy (parg, *targ);
736 parg += strlen (*targ++);
737 *parg++ = '\0';
739 strcpy (parg, ppid_env_var_buffer);
740 parg += strlen (ppid_env_var_buffer);
741 *parg++ = '\0';
742 *parg = '\0';
744 cp = new_child ();
745 if (cp == NULL)
747 errno = EAGAIN;
748 return -1;
751 /* Now create the process. */
752 if (!create_child (cmdname, cmdline, env, &pid, cp))
754 delete_child (cp);
755 errno = ENOEXEC;
756 return -1;
759 if (is_dos_binary)
761 cp->is_dos_process = TRUE;
762 dos_process_running = TRUE;
765 return pid;
768 /* Emulate the select call
769 Wait for available input on any of the given rfds, or timeout if
770 a timeout is given and no input is detected
771 wfds and efds are not supported and must be NULL. */
773 /* From ntterm.c */
774 extern HANDLE keyboard_handle;
775 /* From process.c */
776 extern int proc_buffered_char[];
778 int
779 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
780 EMACS_TIME *timeout)
782 SELECT_TYPE orfds;
783 DWORD timeout_ms;
784 int i, nh, nr;
785 DWORD active;
786 child_process *cp;
787 HANDLE wait_hnd[MAXDESC];
788 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
790 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
791 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
793 Sleep (timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
794 return 0;
797 /* Otherwise, we only handle rfds, so fail otherwise. */
798 if (rfds == NULL || wfds != NULL || efds != NULL)
800 errno = EINVAL;
801 return -1;
804 orfds = *rfds;
805 FD_ZERO (rfds);
806 nr = 0;
808 /* Build a list of handles to wait on. */
809 nh = 0;
810 for (i = 0; i < nfds; i++)
811 if (FD_ISSET (i, &orfds))
813 if (i == 0)
815 if (keyboard_handle)
817 /* Handle stdin specially */
818 wait_hnd[nh] = keyboard_handle;
819 fdindex[nh] = i;
820 nh++;
823 /* Check for any emacs-generated input in the queue since
824 it won't be detected in the wait */
825 if (detect_input_pending ())
827 FD_SET (i, rfds);
828 return 1;
831 else
833 /* Child process and socket input */
834 cp = fd_info[i].cp;
835 if (cp)
837 int current_status = cp->status;
839 if (current_status == STATUS_READ_ACKNOWLEDGED)
841 /* Tell reader thread which file handle to use. */
842 cp->fd = i;
843 /* Wake up the reader thread for this process */
844 cp->status = STATUS_READ_READY;
845 if (!SetEvent (cp->char_consumed))
846 DebPrint (("nt_select.SetEvent failed with "
847 "%lu for fd %ld\n", GetLastError (), i));
850 #ifdef CHECK_INTERLOCK
851 /* slightly crude cross-checking of interlock between threads */
853 current_status = cp->status;
854 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
856 /* char_avail has been signalled, so status (which may
857 have changed) should indicate read has completed
858 but has not been acknowledged. */
859 current_status = cp->status;
860 if (current_status != STATUS_READ_SUCCEEDED &&
861 current_status != STATUS_READ_FAILED)
862 DebPrint (("char_avail set, but read not completed: status %d\n",
863 current_status));
865 else
867 /* char_avail has not been signalled, so status should
868 indicate that read is in progress; small possibility
869 that read has completed but event wasn't yet signalled
870 when we tested it (because a context switch occurred
871 or if running on separate CPUs). */
872 if (current_status != STATUS_READ_READY &&
873 current_status != STATUS_READ_IN_PROGRESS &&
874 current_status != STATUS_READ_SUCCEEDED &&
875 current_status != STATUS_READ_FAILED)
876 DebPrint (("char_avail reset, but read status is bad: %d\n",
877 current_status));
879 #endif
880 wait_hnd[nh] = cp->char_avail;
881 fdindex[nh] = i;
882 if (!wait_hnd[nh]) abort ();
883 nh++;
884 #ifdef FULL_DEBUG
885 DebPrint (("select waiting on child %d fd %d\n",
886 cp-child_procs, i));
887 #endif
889 else
891 /* Unable to find something to wait on for this fd, skip */
892 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
893 abort ();
898 /* Nothing to look for, so we didn't find anything */
899 if (nh == 0)
901 if (timeout)
902 Sleep (timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
903 return 0;
907 Wait for input
908 If a child process dies while this is waiting, its pipe will break
909 so the reader thread will signal an error condition, thus, the wait
910 will wake up
912 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
914 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, timeout_ms);
916 if (active == WAIT_FAILED)
918 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
919 nh, timeout_ms, GetLastError ()));
920 /* don't return EBADF - this causes wait_reading_process_input to
921 abort; WAIT_FAILED is returned when single-stepping under
922 Windows 95 after switching thread focus in debugger, and
923 possibly at other times. */
924 errno = EINTR;
925 return -1;
927 else if (active == WAIT_TIMEOUT)
929 return 0;
931 else if (active >= WAIT_OBJECT_0 &&
932 active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
934 active -= WAIT_OBJECT_0;
936 else if (active >= WAIT_ABANDONED_0 &&
937 active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
939 active -= WAIT_ABANDONED_0;
942 /* Loop over all handles after active (now officially documented as
943 being the first signalled handle in the array). We do this to
944 ensure fairness, so that all channels with data available will be
945 processed - otherwise higher numbered channels could be starved. */
948 if (fdindex[active] == 0)
950 /* Keyboard input available */
951 FD_SET (0, rfds);
952 nr++;
954 else
956 /* must be a socket or pipe */
957 int current_status;
959 cp = fd_info[ fdindex[active] ].cp;
961 /* Read ahead should have completed, either succeeding or failing. */
962 FD_SET (fdindex[active], rfds);
963 nr++;
964 current_status = cp->status;
965 if (current_status != STATUS_READ_SUCCEEDED)
967 if (current_status != STATUS_READ_FAILED)
968 DebPrint (("internal error: subprocess pipe signalled "
969 "at the wrong time (status %d)\n!", current_status));
971 /* The child_process entry for a socket or pipe will be
972 freed when the last descriptor using it is closed; for
973 pipes, we call the SIGCHLD handler. */
974 if (fd_info[ fdindex[active] ].flags & FILE_PIPE)
976 /* The SIGCHLD handler will do a Wait so we know it won't
977 return until the process is dead
978 We force Wait to only wait for this process to avoid it
979 picking up other children that happen to be dead but that
980 we haven't noticed yet
981 SIG_DFL for SIGCHLD is ignore? */
982 if (sig_handlers[SIGCHLD] != SIG_DFL &&
983 sig_handlers[SIGCHLD] != SIG_IGN)
985 #ifdef FULL_DEBUG
986 DebPrint (("select calling SIGCHLD handler for pid %d\n",
987 cp->pid));
988 #endif
989 dead_child = cp;
990 sig_handlers[SIGCHLD] (SIGCHLD);
991 dead_child = NULL;
994 /* Clean up the child process entry in the table */
995 reap_subprocess (cp);
1000 /* Test for input on remaining channels. */
1001 while (++active < nh)
1002 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1003 break;
1004 } while (active < nh);
1006 return nr;
1009 /* Substitute for certain kill () operations */
1010 int
1011 sys_kill (int pid, int sig)
1013 child_process *cp;
1014 HANDLE proc_hand;
1015 int need_to_free = 0;
1016 int rc = 0;
1018 /* Only handle signals that will result in the process dying */
1019 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1021 errno = EINVAL;
1022 return -1;
1025 cp = find_child_pid (pid);
1026 if (cp == NULL)
1028 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1029 if (proc_hand == NULL)
1031 errno = EPERM;
1032 return -1;
1034 need_to_free = 1;
1036 else
1038 proc_hand = cp->procinfo.hProcess;
1039 pid = cp->procinfo.dwProcessId;
1042 if (sig == SIGINT)
1044 /* Ctrl-Break is NT equivalent of SIGINT. */
1045 if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1047 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1048 "for pid %lu\n", GetLastError (), pid));
1049 errno = EINVAL;
1050 rc = -1;
1053 else
1055 /* Kill the process. On Win32 this doesn't kill child processes
1056 so it doesn't work very well for shells which is why it's not
1057 used in every case. Also, don't try to terminate DOS processes
1058 (on Win95), because this will hang Emacs. */
1059 if (!(cp && cp->is_dos_process)
1060 && !TerminateProcess (proc_hand, 0xff))
1062 DebPrint (("sys_kill.TerminateProcess returned %d "
1063 "for pid %lu\n", GetLastError (), pid));
1064 errno = EINVAL;
1065 rc = -1;
1069 if (need_to_free)
1070 CloseHandle (proc_hand);
1072 return rc;
1075 extern int report_file_error (char *, Lisp_Object);
1077 /* The following two routines are used to manipulate stdin, stdout, and
1078 stderr of our child processes.
1080 Assuming that in, out, and err are *not* inheritable, we make them
1081 stdin, stdout, and stderr of the child as follows:
1083 - Save the parent's current standard handles.
1084 - Set the std handles to inheritable duplicates of the ones being passed in.
1085 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1086 NT file handle for a crt file descriptor.)
1087 - Spawn the child, which inherits in, out, and err as stdin,
1088 stdout, and stderr. (see Spawnve)
1089 - Close the std handles passed to the child.
1090 - Reset the parent's standard handles to the saved handles.
1091 (see reset_standard_handles)
1092 We assume that the caller closes in, out, and err after calling us. */
1094 void
1095 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1097 HANDLE parent;
1098 HANDLE newstdin, newstdout, newstderr;
1100 parent = GetCurrentProcess ();
1102 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1103 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1104 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1106 /* make inheritable copies of the new handles */
1107 if (!DuplicateHandle (parent,
1108 (HANDLE) _get_osfhandle (in),
1109 parent,
1110 &newstdin,
1112 TRUE,
1113 DUPLICATE_SAME_ACCESS))
1114 report_file_error ("Duplicating input handle for child", Qnil);
1116 if (!DuplicateHandle (parent,
1117 (HANDLE) _get_osfhandle (out),
1118 parent,
1119 &newstdout,
1121 TRUE,
1122 DUPLICATE_SAME_ACCESS))
1123 report_file_error ("Duplicating output handle for child", Qnil);
1125 if (!DuplicateHandle (parent,
1126 (HANDLE) _get_osfhandle (err),
1127 parent,
1128 &newstderr,
1130 TRUE,
1131 DUPLICATE_SAME_ACCESS))
1132 report_file_error ("Duplicating error handle for child", Qnil);
1134 /* and store them as our std handles */
1135 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1136 report_file_error ("Changing stdin handle", Qnil);
1138 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1139 report_file_error ("Changing stdout handle", Qnil);
1141 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1142 report_file_error ("Changing stderr handle", Qnil);
1145 void
1146 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1148 /* close the duplicated handles passed to the child */
1149 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1150 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1151 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1153 /* now restore parent's saved std handles */
1154 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1155 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1156 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1159 #ifdef HAVE_SOCKETS
1161 /* To avoid problems with winsock implementations that work over dial-up
1162 connections causing or requiring a connection to exist while Emacs is
1163 running, Emacs no longer automatically loads winsock on startup if it
1164 is present. Instead, it will be loaded when open-network-stream is
1165 first called.
1167 To allow full control over when winsock is loaded, we provide these
1168 two functions to dynamically load and unload winsock. This allows
1169 dial-up users to only be connected when they actually need to use
1170 socket services. */
1172 /* From nt.c */
1173 extern HANDLE winsock_lib;
1174 extern BOOL term_winsock (void);
1175 extern BOOL init_winsock (int load_now);
1177 extern Lisp_Object Vsystem_name;
1179 DEFUN ("win32-has-winsock", Fwin32_has_winsock, Swin32_has_winsock, 0, 1, 0,
1180 "Test for presence of the Windows socket library `winsock'.\n\
1181 Returns non-nil if winsock support is present, nil otherwise.\n\
1183 If the optional argument LOAD-NOW is non-nil, the winsock library is\n\
1184 also loaded immediately if not already loaded. If winsock is loaded,\n\
1185 the winsock local hostname is returned (since this may be different from\n\
1186 the value of `system-name' and should supplant it), otherwise t is\n\
1187 returned to indicate winsock support is present.")
1188 (load_now)
1189 Lisp_Object load_now;
1191 int have_winsock;
1193 have_winsock = init_winsock (!NILP (load_now));
1194 if (have_winsock)
1196 if (winsock_lib != NULL)
1198 /* Return new value for system-name. The best way to do this
1199 is to call init_system_name, saving and restoring the
1200 original value to avoid side-effects. */
1201 Lisp_Object orig_hostname = Vsystem_name;
1202 Lisp_Object hostname;
1204 init_system_name ();
1205 hostname = Vsystem_name;
1206 Vsystem_name = orig_hostname;
1207 return hostname;
1209 return Qt;
1211 return Qnil;
1214 DEFUN ("win32-unload-winsock", Fwin32_unload_winsock, Swin32_unload_winsock,
1215 0, 0, 0,
1216 "Unload the Windows socket library `winsock' if loaded.\n\
1217 This is provided to allow dial-up socket connections to be disconnected\n\
1218 when no longer needed. Returns nil without unloading winsock if any\n\
1219 socket connections still exist.")
1222 return term_winsock () ? Qt : Qnil;
1225 #endif /* HAVE_SOCKETS */
1228 syms_of_ntproc ()
1230 #ifdef HAVE_SOCKETS
1231 defsubr (&Swin32_has_winsock);
1232 defsubr (&Swin32_unload_winsock);
1233 #endif
1235 DEFVAR_LISP ("win32-quote-process-args", &Vwin32_quote_process_args,
1236 "Non-nil enables quoting of process arguments to ensure correct parsing.\n\
1237 Because Windows does not directly pass argv arrays to child processes,\n\
1238 programs have to reconstruct the argv array by parsing the command\n\
1239 line string. For an argument to contain a space, it must be enclosed\n\
1240 in double quotes or it will be parsed as multiple arguments.\n\
1242 However, the argument list to call-process is not always correctly\n\
1243 constructed (or arguments have already been quoted), so enabling this\n\
1244 option may cause unexpected behavior.");
1245 Vwin32_quote_process_args = Qnil;
1247 DEFVAR_INT ("win32-pipe-read-delay", &Vwin32_pipe_read_delay,
1248 "Forced delay before reading subprocess output.\n\
1249 This is done to improve the buffering of subprocess output, by\n\
1250 avoiding the inefficiency of frequently reading small amounts of data.\n\
1252 If positive, the value is the number of milliseconds to sleep before\n\
1253 reading the subprocess output. If negative, the magnitude is the number\n\
1254 of time slices to wait (effectively boosting the priority of the child\n\
1255 process temporarily). A value of zero disables waiting entirely.");
1256 Vwin32_pipe_read_delay = 50;
1258 DEFVAR_LISP ("win32-downcase-file-names", &Vwin32_downcase_file_names,
1259 "Non-nil means convert all-upper case file names to lower case.\n\
1260 This applies when performing completions and file name expansion.");
1261 Vwin32_downcase_file_names = Qnil;
1263 /* end of ntproc.c */