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