]> code.delx.au - gnu-emacs/blob - src/w32proc.c
Pacify compilation -Wincompatible-pointer-types warnings
[gnu-emacs] / src / w32proc.c
1 /* Process support for GNU Emacs on the Microsoft Windows API.
2
3 Copyright (C) 1992, 1995, 1999-2015 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 /*
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
23 */
24
25 #include <mingw_time.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <ctype.h>
30 #include <io.h>
31 #include <fcntl.h>
32 #include <signal.h>
33 #include <sys/file.h>
34 #include <mbstring.h>
35 #include <locale.h>
36
37 /* must include CRT headers *before* config.h */
38 #include <config.h>
39
40 #undef signal
41 #undef wait
42 #undef spawnve
43 #undef select
44 #undef kill
45
46 #include <windows.h>
47 #if defined(__GNUC__) && !defined(__MINGW64__)
48 /* This definition is missing from mingw.org headers, but not MinGW64
49 headers. */
50 extern BOOL WINAPI IsValidLocale (LCID, DWORD);
51 #endif
52
53 #ifdef HAVE_LANGINFO_CODESET
54 #include <nl_types.h>
55 #include <langinfo.h>
56 #endif
57
58 #include "lisp.h"
59 #include "w32.h"
60 #include "w32common.h"
61 #include "w32heap.h"
62 #include "systime.h"
63 #include "syswait.h"
64 #include "process.h"
65 #include "syssignal.h"
66 #include "w32term.h"
67 #include "dispextern.h" /* for xstrcasecmp */
68 #include "coding.h"
69
70 #define RVA_TO_PTR(var,section,filedata) \
71 ((void *)((section)->PointerToRawData \
72 + ((DWORD_PTR)(var) - (section)->VirtualAddress) \
73 + (filedata).file_base))
74
75 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
76 static signal_handler sig_handlers[NSIG];
77
78 static sigset_t sig_mask;
79
80 static CRITICAL_SECTION crit_sig;
81
82 /* Improve on the CRT 'signal' implementation so that we could record
83 the SIGCHLD handler and fake interval timers. */
84 signal_handler
85 sys_signal (int sig, signal_handler handler)
86 {
87 signal_handler old;
88
89 /* SIGCHLD is needed for supporting subprocesses, see sys_kill
90 below. SIGALRM and SIGPROF are used by setitimer. All the
91 others are the only ones supported by the MS runtime. */
92 if (!(sig == SIGCHLD || sig == SIGSEGV || sig == SIGILL
93 || sig == SIGFPE || sig == SIGABRT || sig == SIGTERM
94 || sig == SIGALRM || sig == SIGPROF))
95 {
96 errno = EINVAL;
97 return SIG_ERR;
98 }
99 old = sig_handlers[sig];
100 /* SIGABRT is treated specially because w32.c installs term_ntproc
101 as its handler, so we don't want to override that afterwards.
102 Aborting Emacs works specially anyway: either by calling
103 emacs_abort directly or through terminate_due_to_signal, which
104 calls emacs_abort through emacs_raise. */
105 if (!(sig == SIGABRT && old == term_ntproc))
106 {
107 sig_handlers[sig] = handler;
108 if (!(sig == SIGCHLD || sig == SIGALRM || sig == SIGPROF))
109 signal (sig, handler);
110 }
111 return old;
112 }
113
114 /* Emulate sigaction. */
115 int
116 sigaction (int sig, const struct sigaction *act, struct sigaction *oact)
117 {
118 signal_handler old = SIG_DFL;
119 int retval = 0;
120
121 if (act)
122 old = sys_signal (sig, act->sa_handler);
123 else if (oact)
124 old = sig_handlers[sig];
125
126 if (old == SIG_ERR)
127 {
128 errno = EINVAL;
129 retval = -1;
130 }
131 if (oact)
132 {
133 oact->sa_handler = old;
134 oact->sa_flags = 0;
135 oact->sa_mask = empty_mask;
136 }
137 return retval;
138 }
139
140 /* Emulate signal sets and blocking of signals used by timers. */
141
142 int
143 sigemptyset (sigset_t *set)
144 {
145 *set = 0;
146 return 0;
147 }
148
149 int
150 sigaddset (sigset_t *set, int signo)
151 {
152 if (!set)
153 {
154 errno = EINVAL;
155 return -1;
156 }
157 if (signo < 0 || signo >= NSIG)
158 {
159 errno = EINVAL;
160 return -1;
161 }
162
163 *set |= (1U << signo);
164
165 return 0;
166 }
167
168 int
169 sigfillset (sigset_t *set)
170 {
171 if (!set)
172 {
173 errno = EINVAL;
174 return -1;
175 }
176
177 *set = 0xFFFFFFFF;
178 return 0;
179 }
180
181 int
182 sigprocmask (int how, const sigset_t *set, sigset_t *oset)
183 {
184 if (!(how == SIG_BLOCK || how == SIG_UNBLOCK || how == SIG_SETMASK))
185 {
186 errno = EINVAL;
187 return -1;
188 }
189
190 if (oset)
191 *oset = sig_mask;
192
193 if (!set)
194 return 0;
195
196 switch (how)
197 {
198 case SIG_BLOCK:
199 sig_mask |= *set;
200 break;
201 case SIG_SETMASK:
202 sig_mask = *set;
203 break;
204 case SIG_UNBLOCK:
205 /* FIXME: Catch signals that are blocked and reissue them when
206 they are unblocked. Important for SIGALRM and SIGPROF only. */
207 sig_mask &= ~(*set);
208 break;
209 }
210
211 return 0;
212 }
213
214 int
215 pthread_sigmask (int how, const sigset_t *set, sigset_t *oset)
216 {
217 if (sigprocmask (how, set, oset) == -1)
218 return EINVAL;
219 return 0;
220 }
221
222 int
223 sigismember (const sigset_t *set, int signo)
224 {
225 if (signo < 0 || signo >= NSIG)
226 {
227 errno = EINVAL;
228 return -1;
229 }
230 if (signo > sizeof (*set) * BITS_PER_CHAR)
231 emacs_abort ();
232
233 return (*set & (1U << signo)) != 0;
234 }
235
236 pid_t
237 getpgrp (void)
238 {
239 return getpid ();
240 }
241
242 pid_t
243 tcgetpgrp (int fd)
244 {
245 return getpid ();
246 }
247
248 int
249 setpgid (pid_t pid, pid_t pgid)
250 {
251 return 0;
252 }
253
254 pid_t
255 setsid (void)
256 {
257 return getpid ();
258 }
259
260 /* Emulations of interval timers.
261
262 Limitations: only ITIMER_REAL and ITIMER_PROF are supported.
263
264 Implementation: a separate thread is started for each timer type,
265 the thread calls the appropriate signal handler when the timer
266 expires, after stopping the thread which installed the timer. */
267
268 struct itimer_data {
269 volatile ULONGLONG expire;
270 volatile ULONGLONG reload;
271 volatile int terminate;
272 int type;
273 HANDLE caller_thread;
274 HANDLE timer_thread;
275 };
276
277 static ULONGLONG ticks_now;
278 static struct itimer_data real_itimer, prof_itimer;
279 static ULONGLONG clocks_min;
280 /* If non-zero, itimers are disabled. Used during shutdown, when we
281 delete the critical sections used by the timer threads. */
282 static int disable_itimers;
283
284 static CRITICAL_SECTION crit_real, crit_prof;
285
286 /* GetThreadTimes is not available on Windows 9X and possibly also on 2K. */
287 typedef BOOL (WINAPI *GetThreadTimes_Proc) (
288 HANDLE hThread,
289 LPFILETIME lpCreationTime,
290 LPFILETIME lpExitTime,
291 LPFILETIME lpKernelTime,
292 LPFILETIME lpUserTime);
293
294 static GetThreadTimes_Proc s_pfn_Get_Thread_Times;
295
296 #define MAX_SINGLE_SLEEP 30
297 #define TIMER_TICKS_PER_SEC 1000
298
299 /* Return a suitable time value, in 1-ms units, for THREAD, a handle
300 to a thread. If THREAD is NULL or an invalid handle, return the
301 current wall-clock time since January 1, 1601 (UTC). Otherwise,
302 return the sum of kernel and user times used by THREAD since it was
303 created, plus its creation time. */
304 static ULONGLONG
305 w32_get_timer_time (HANDLE thread)
306 {
307 ULONGLONG retval;
308 int use_system_time = 1;
309 /* The functions below return times in 100-ns units. */
310 const int tscale = 10 * TIMER_TICKS_PER_SEC;
311
312 if (thread && thread != INVALID_HANDLE_VALUE
313 && s_pfn_Get_Thread_Times != NULL)
314 {
315 FILETIME creation_ftime, exit_ftime, kernel_ftime, user_ftime;
316 ULARGE_INTEGER temp_creation, temp_kernel, temp_user;
317
318 if (s_pfn_Get_Thread_Times (thread, &creation_ftime, &exit_ftime,
319 &kernel_ftime, &user_ftime))
320 {
321 use_system_time = 0;
322 temp_creation.LowPart = creation_ftime.dwLowDateTime;
323 temp_creation.HighPart = creation_ftime.dwHighDateTime;
324 temp_kernel.LowPart = kernel_ftime.dwLowDateTime;
325 temp_kernel.HighPart = kernel_ftime.dwHighDateTime;
326 temp_user.LowPart = user_ftime.dwLowDateTime;
327 temp_user.HighPart = user_ftime.dwHighDateTime;
328 retval =
329 temp_creation.QuadPart / tscale + temp_kernel.QuadPart / tscale
330 + temp_user.QuadPart / tscale;
331 }
332 else
333 DebPrint (("GetThreadTimes failed with error code %lu\n",
334 GetLastError ()));
335 }
336
337 if (use_system_time)
338 {
339 FILETIME current_ftime;
340 ULARGE_INTEGER temp;
341
342 GetSystemTimeAsFileTime (&current_ftime);
343
344 temp.LowPart = current_ftime.dwLowDateTime;
345 temp.HighPart = current_ftime.dwHighDateTime;
346
347 retval = temp.QuadPart / tscale;
348 }
349
350 return retval;
351 }
352
353 /* Thread function for a timer thread. */
354 static DWORD WINAPI
355 timer_loop (LPVOID arg)
356 {
357 struct itimer_data *itimer = (struct itimer_data *)arg;
358 int which = itimer->type;
359 int sig = (which == ITIMER_REAL) ? SIGALRM : SIGPROF;
360 CRITICAL_SECTION *crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
361 const DWORD max_sleep = MAX_SINGLE_SLEEP * 1000 / TIMER_TICKS_PER_SEC;
362 HANDLE hth = (which == ITIMER_REAL) ? NULL : itimer->caller_thread;
363
364 while (1)
365 {
366 DWORD sleep_time;
367 signal_handler handler;
368 ULONGLONG now, expire, reload;
369
370 /* Load new values if requested by setitimer. */
371 EnterCriticalSection (crit);
372 expire = itimer->expire;
373 reload = itimer->reload;
374 LeaveCriticalSection (crit);
375 if (itimer->terminate)
376 return 0;
377
378 if (expire == 0)
379 {
380 /* We are idle. */
381 Sleep (max_sleep);
382 continue;
383 }
384
385 if (expire > (now = w32_get_timer_time (hth)))
386 sleep_time = expire - now;
387 else
388 sleep_time = 0;
389 /* Don't sleep too long at a time, to be able to see the
390 termination flag without too long a delay. */
391 while (sleep_time > max_sleep)
392 {
393 if (itimer->terminate)
394 return 0;
395 Sleep (max_sleep);
396 EnterCriticalSection (crit);
397 expire = itimer->expire;
398 LeaveCriticalSection (crit);
399 sleep_time =
400 (expire > (now = w32_get_timer_time (hth))) ? expire - now : 0;
401 }
402 if (itimer->terminate)
403 return 0;
404 if (sleep_time > 0)
405 {
406 Sleep (sleep_time * 1000 / TIMER_TICKS_PER_SEC);
407 /* Always sleep past the expiration time, to make sure we
408 never call the handler _before_ the expiration time,
409 always slightly after it. Sleep(5) makes sure we don't
410 hog the CPU by calling 'w32_get_timer_time' with high
411 frequency, and also let other threads work. */
412 while (w32_get_timer_time (hth) < expire)
413 Sleep (5);
414 }
415
416 EnterCriticalSection (crit);
417 expire = itimer->expire;
418 LeaveCriticalSection (crit);
419 if (expire == 0)
420 continue;
421
422 /* Time's up. */
423 handler = sig_handlers[sig];
424 if (!(handler == SIG_DFL || handler == SIG_IGN || handler == SIG_ERR)
425 /* FIXME: Don't ignore masked signals. Instead, record that
426 they happened and reissue them when the signal is
427 unblocked. */
428 && !sigismember (&sig_mask, sig)
429 /* Simulate masking of SIGALRM and SIGPROF when processing
430 fatal signals. */
431 && !fatal_error_in_progress
432 && itimer->caller_thread)
433 {
434 /* Simulate a signal delivered to the thread which installed
435 the timer, by suspending that thread while the handler
436 runs. */
437 HANDLE th = itimer->caller_thread;
438 DWORD result = SuspendThread (th);
439
440 if (result == (DWORD)-1)
441 return 2;
442
443 handler (sig);
444 ResumeThread (th);
445 }
446
447 /* Update expiration time and loop. */
448 EnterCriticalSection (crit);
449 expire = itimer->expire;
450 if (expire == 0)
451 {
452 LeaveCriticalSection (crit);
453 continue;
454 }
455 reload = itimer->reload;
456 if (reload > 0)
457 {
458 now = w32_get_timer_time (hth);
459 if (expire <= now)
460 {
461 ULONGLONG lag = now - expire;
462
463 /* If we missed some opportunities (presumably while
464 sleeping or while the signal handler ran), skip
465 them. */
466 if (lag > reload)
467 expire = now - (lag % reload);
468
469 expire += reload;
470 }
471 }
472 else
473 expire = 0; /* become idle */
474 itimer->expire = expire;
475 LeaveCriticalSection (crit);
476 }
477 return 0;
478 }
479
480 static void
481 stop_timer_thread (int which)
482 {
483 struct itimer_data *itimer =
484 (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;
485 int i;
486 DWORD err, exit_code = 255;
487 BOOL status;
488
489 /* Signal the thread that it should terminate. */
490 itimer->terminate = 1;
491
492 if (itimer->timer_thread == NULL)
493 return;
494
495 /* Wait for the timer thread to terminate voluntarily, then kill it
496 if it doesn't. This loop waits twice more than the maximum
497 amount of time a timer thread sleeps, see above. */
498 for (i = 0; i < MAX_SINGLE_SLEEP / 5; i++)
499 {
500 if (!((status = GetExitCodeThread (itimer->timer_thread, &exit_code))
501 && exit_code == STILL_ACTIVE))
502 break;
503 Sleep (10);
504 }
505 if ((status == FALSE && (err = GetLastError ()) == ERROR_INVALID_HANDLE)
506 || exit_code == STILL_ACTIVE)
507 {
508 if (!(status == FALSE && err == ERROR_INVALID_HANDLE))
509 TerminateThread (itimer->timer_thread, 0);
510 }
511
512 /* Clean up. */
513 CloseHandle (itimer->timer_thread);
514 itimer->timer_thread = NULL;
515 if (itimer->caller_thread)
516 {
517 CloseHandle (itimer->caller_thread);
518 itimer->caller_thread = NULL;
519 }
520 }
521
522 /* This is called at shutdown time from term_ntproc. */
523 void
524 term_timers (void)
525 {
526 if (real_itimer.timer_thread)
527 stop_timer_thread (ITIMER_REAL);
528 if (prof_itimer.timer_thread)
529 stop_timer_thread (ITIMER_PROF);
530
531 /* We are going to delete the critical sections, so timers cannot
532 work after this. */
533 disable_itimers = 1;
534
535 DeleteCriticalSection (&crit_real);
536 DeleteCriticalSection (&crit_prof);
537 DeleteCriticalSection (&crit_sig);
538 }
539
540 /* This is called at initialization time from init_ntproc. */
541 void
542 init_timers (void)
543 {
544 /* GetThreadTimes is not available on all versions of Windows, so
545 need to probe for its availability dynamically, and call it
546 through a pointer. */
547 s_pfn_Get_Thread_Times = NULL; /* in case dumped Emacs comes with a value */
548 if (os_subtype != OS_9X)
549 s_pfn_Get_Thread_Times =
550 (GetThreadTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
551 "GetThreadTimes");
552
553 /* Make sure we start with zeroed out itimer structures, since
554 dumping may have left there traces of threads long dead. */
555 memset (&real_itimer, 0, sizeof real_itimer);
556 memset (&prof_itimer, 0, sizeof prof_itimer);
557
558 InitializeCriticalSection (&crit_real);
559 InitializeCriticalSection (&crit_prof);
560 InitializeCriticalSection (&crit_sig);
561
562 disable_itimers = 0;
563 }
564
565 static int
566 start_timer_thread (int which)
567 {
568 DWORD exit_code, tid;
569 HANDLE th;
570 struct itimer_data *itimer =
571 (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;
572
573 if (itimer->timer_thread
574 && GetExitCodeThread (itimer->timer_thread, &exit_code)
575 && exit_code == STILL_ACTIVE)
576 return 0;
577
578 /* Clean up after possibly exited thread. */
579 if (itimer->timer_thread)
580 {
581 CloseHandle (itimer->timer_thread);
582 itimer->timer_thread = NULL;
583 }
584 if (itimer->caller_thread)
585 {
586 CloseHandle (itimer->caller_thread);
587 itimer->caller_thread = NULL;
588 }
589
590 /* Start a new thread. */
591 if (!DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
592 GetCurrentProcess (), &th, 0, FALSE,
593 DUPLICATE_SAME_ACCESS))
594 {
595 errno = ESRCH;
596 return -1;
597 }
598 itimer->terminate = 0;
599 itimer->type = which;
600 itimer->caller_thread = th;
601 /* Request that no more than 64KB of stack be reserved for this
602 thread, to avoid reserving too much memory, which would get in
603 the way of threads we start to wait for subprocesses. See also
604 new_child below. */
605 itimer->timer_thread = CreateThread (NULL, 64 * 1024, timer_loop,
606 (void *)itimer, 0x00010000, &tid);
607
608 if (!itimer->timer_thread)
609 {
610 CloseHandle (itimer->caller_thread);
611 itimer->caller_thread = NULL;
612 errno = EAGAIN;
613 return -1;
614 }
615
616 /* This is needed to make sure that the timer thread running for
617 profiling gets CPU as soon as the Sleep call terminates. */
618 if (which == ITIMER_PROF)
619 SetThreadPriority (itimer->timer_thread, THREAD_PRIORITY_TIME_CRITICAL);
620
621 return 0;
622 }
623
624 /* Most of the code of getitimer and setitimer (but not of their
625 subroutines) was shamelessly stolen from itimer.c in the DJGPP
626 library, see www.delorie.com/djgpp. */
627 int
628 getitimer (int which, struct itimerval *value)
629 {
630 volatile ULONGLONG *t_expire;
631 volatile ULONGLONG *t_reload;
632 ULONGLONG expire, reload;
633 __int64 usecs;
634 CRITICAL_SECTION *crit;
635 struct itimer_data *itimer;
636
637 if (disable_itimers)
638 return -1;
639
640 if (!value)
641 {
642 errno = EFAULT;
643 return -1;
644 }
645
646 if (which != ITIMER_REAL && which != ITIMER_PROF)
647 {
648 errno = EINVAL;
649 return -1;
650 }
651
652 itimer = (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;
653
654 ticks_now = w32_get_timer_time ((which == ITIMER_REAL)
655 ? NULL
656 : GetCurrentThread ());
657
658 t_expire = &itimer->expire;
659 t_reload = &itimer->reload;
660 crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
661
662 EnterCriticalSection (crit);
663 reload = *t_reload;
664 expire = *t_expire;
665 LeaveCriticalSection (crit);
666
667 if (expire)
668 expire -= ticks_now;
669
670 value->it_value.tv_sec = expire / TIMER_TICKS_PER_SEC;
671 usecs =
672 (expire % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
673 value->it_value.tv_usec = usecs;
674 value->it_interval.tv_sec = reload / TIMER_TICKS_PER_SEC;
675 usecs =
676 (reload % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
677 value->it_interval.tv_usec= usecs;
678
679 return 0;
680 }
681
682 int
683 setitimer(int which, struct itimerval *value, struct itimerval *ovalue)
684 {
685 volatile ULONGLONG *t_expire, *t_reload;
686 ULONGLONG expire, reload, expire_old, reload_old;
687 __int64 usecs;
688 CRITICAL_SECTION *crit;
689 struct itimerval tem, *ptem;
690
691 if (disable_itimers)
692 return -1;
693
694 /* Posix systems expect timer values smaller than the resolution of
695 the system clock be rounded up to the clock resolution. First
696 time we are called, measure the clock tick resolution. */
697 if (!clocks_min)
698 {
699 ULONGLONG t1, t2;
700
701 for (t1 = w32_get_timer_time (NULL);
702 (t2 = w32_get_timer_time (NULL)) == t1; )
703 ;
704 clocks_min = t2 - t1;
705 }
706
707 if (ovalue)
708 ptem = ovalue;
709 else
710 ptem = &tem;
711
712 if (getitimer (which, ptem)) /* also sets ticks_now */
713 return -1; /* errno already set */
714
715 t_expire =
716 (which == ITIMER_REAL) ? &real_itimer.expire : &prof_itimer.expire;
717 t_reload =
718 (which == ITIMER_REAL) ? &real_itimer.reload : &prof_itimer.reload;
719
720 crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
721
722 if (!value
723 || (value->it_value.tv_sec == 0 && value->it_value.tv_usec == 0))
724 {
725 EnterCriticalSection (crit);
726 /* Disable the timer. */
727 *t_expire = 0;
728 *t_reload = 0;
729 LeaveCriticalSection (crit);
730 return 0;
731 }
732
733 reload = value->it_interval.tv_sec * TIMER_TICKS_PER_SEC;
734
735 usecs = value->it_interval.tv_usec;
736 if (value->it_interval.tv_sec == 0
737 && usecs && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
738 reload = clocks_min;
739 else
740 {
741 usecs *= TIMER_TICKS_PER_SEC;
742 reload += usecs / 1000000;
743 }
744
745 expire = value->it_value.tv_sec * TIMER_TICKS_PER_SEC;
746 usecs = value->it_value.tv_usec;
747 if (value->it_value.tv_sec == 0
748 && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
749 expire = clocks_min;
750 else
751 {
752 usecs *= TIMER_TICKS_PER_SEC;
753 expire += usecs / 1000000;
754 }
755
756 expire += ticks_now;
757
758 EnterCriticalSection (crit);
759 expire_old = *t_expire;
760 reload_old = *t_reload;
761 if (!(expire == expire_old && reload == reload_old))
762 {
763 *t_reload = reload;
764 *t_expire = expire;
765 }
766 LeaveCriticalSection (crit);
767
768 return start_timer_thread (which);
769 }
770
771 int
772 alarm (int seconds)
773 {
774 #ifdef HAVE_SETITIMER
775 struct itimerval new_values, old_values;
776
777 new_values.it_value.tv_sec = seconds;
778 new_values.it_value.tv_usec = 0;
779 new_values.it_interval.tv_sec = new_values.it_interval.tv_usec = 0;
780
781 if (setitimer (ITIMER_REAL, &new_values, &old_values) < 0)
782 return 0;
783 return old_values.it_value.tv_sec;
784 #else
785 return seconds;
786 #endif
787 }
788
789 \f
790
791 /* Here's an overview of how support for subprocesses and
792 network/serial streams is implemented on MS-Windows.
793
794 The management of both subprocesses and network/serial streams
795 circles around the child_procs[] array, which can record up to the
796 grand total of MAX_CHILDREN (= 32) of these. (The reasons for the
797 32 limitation will become clear below.) Each member of
798 child_procs[] is a child_process structure, defined on w32.h.
799
800 A related data structure is the fd_info[] array, which holds twice
801 as many members, 64, and records the information about file
802 descriptors used for communicating with subprocesses and
803 network/serial devices. Each member of the array is the filedesc
804 structure, which records the Windows handle for communications,
805 such as the read end of the pipe to a subprocess, a socket handle,
806 etc.
807
808 Both these arrays reference each other: there's a member of
809 child_process structure that records the corresponding file
810 descriptor, and there's a member of filedesc structure that holds a
811 pointer to the corresponding child_process.
812
813 Whenever Emacs starts a subprocess or opens a network/serial
814 stream, the function new_child is called to prepare a new
815 child_process structure. new_child looks for the first vacant slot
816 in the child_procs[] array, initializes it, and starts a "reader
817 thread" that will watch the output of the subprocess/stream and its
818 status. (If no vacant slot can be found, new_child returns a
819 failure indication to its caller, and the higher-level Emacs
820 primitive that called it will then fail with EMFILE or EAGAIN.)
821
822 The reader thread started by new_child communicates with the main
823 (a.k.a. "Lisp") thread via two event objects and a status, all of
824 them recorded by the members of the child_process structure in
825 child_procs[]. The event objects serve as semaphores between the
826 reader thread and the 'pselect' emulation in sys_select, as follows:
827
828 . Initially, the reader thread is waiting for the char_consumed
829 event to become signaled by sys_select, which is an indication
830 for the reader thread to go ahead and try reading more stuff
831 from the subprocess/stream.
832
833 . The reader thread then attempts to read by calling a
834 blocking-read function. When the read call returns, either
835 successfully or with some failure indication, the reader thread
836 updates the status of the read accordingly, and signals the 2nd
837 event object, char_avail, on whose handle sys_select is
838 waiting. This tells sys_select that the file descriptor
839 allocated for the subprocess or the the stream is ready to be
840 read from.
841
842 When the subprocess exits or the network/serial stream is closed,
843 the reader thread sets the status accordingly and exits. It also
844 exits when the main thread sets the status to STATUS_READ_ERROR
845 and/or the char_avail and char_consumed event handles become NULL;
846 this is how delete_child, called by Emacs when a subprocess or a
847 stream is terminated, terminates the reader thread as part of
848 deleting the child_process object.
849
850 The sys_select function emulates the Posix 'pselect' function; it
851 is needed because the Windows 'select' function supports only
852 network sockets, while Emacs expects 'pselect' to work for any file
853 descriptor, including pipes and serial streams.
854
855 When sys_select is called, it uses the information in fd_info[]
856 array to convert the file descriptors which it was asked to watch
857 into Windows handles. In general, the handle to watch is the
858 handle of the char_avail event of the child_process structure that
859 corresponds to the file descriptor. In addition, for subprocesses,
860 sys_select watches one more handle: the handle for the subprocess,
861 so that it could emulate the SIGCHLD signal when the subprocess
862 exits.
863
864 If file descriptor zero (stdin) doesn't have its bit set in the
865 'rfds' argument to sys_select, the function always watches for
866 keyboard interrupts, to be able to interrupt the wait and return
867 when the user presses C-g.
868
869 Having collected the handles to watch, sys_select calls
870 WaitForMultipleObjects to wait for any one of them to become
871 signaled. Since WaitForMultipleObjects can only watch up to 64
872 handles, Emacs on Windows is limited to maximum 32 child_process
873 objects (since a subprocess consumes 2 handles to be watched, see
874 above).
875
876 When any of the handles become signaled, sys_select does whatever
877 is appropriate for the corresponding child_process object:
878
879 . If it's a handle to the char_avail event, sys_select marks the
880 corresponding bit in 'rfds', and Emacs will then read from that
881 file descriptor.
882
883 . If it's a handle to the process, sys_select calls the SIGCHLD
884 handler, to inform Emacs of the fact that the subprocess
885 exited.
886
887 The waitpid emulation works very similar to sys_select, except that
888 it only watches handles of subprocesses, and doesn't synchronize
889 with the reader thread.
890
891 Because socket descriptors on Windows are handles, while Emacs
892 expects them to be file descriptors, all low-level I/O functions,
893 such as 'read' and 'write', and all socket operations, like
894 'connect', 'recvfrom', 'accept', etc., are redirected to the
895 corresponding 'sys_*' functions, which must convert a file
896 descriptor to a handle using the fd_info[] array, and then invoke
897 the corresponding Windows API on the handle. Most of these
898 redirected 'sys_*' functions are implemented on w32.c.
899
900 When the file descriptor was produced by functions such as 'open',
901 the corresponding handle is obtained by calling _get_osfhandle. To
902 produce a file descriptor for a socket handle, which has no file
903 descriptor as far as Windows is concerned, the function
904 socket_to_fd opens the null device; the resulting file descriptor
905 will never be used directly in any I/O API, but serves as an index
906 into the fd_info[] array, where the socket handle is stored. The
907 SOCK_HANDLE macro retrieves the handle when given the file
908 descriptor.
909
910 The function sys_kill emulates the Posix 'kill' functionality to
911 terminate other processes. It does that by attaching to the
912 foreground window of the process and sending a Ctrl-C or Ctrl-BREAK
913 signal to the process; if that doesn't work, then it calls
914 TerminateProcess to forcibly terminate the process. Note that this
915 only terminates the immediate process whose PID was passed to
916 sys_kill; it doesn't terminate the child processes of that process.
917 This means, for example, that an Emacs subprocess run through a
918 shell might not be killed, because sys_kill will only terminate the
919 shell. (In practice, however, such problems are very rare.) */
920
921 /* Defined in <process.h> which conflicts with the local copy */
922 #define _P_NOWAIT 1
923
924 /* Child process management list. */
925 int child_proc_count = 0;
926 child_process child_procs[ MAX_CHILDREN ];
927
928 static DWORD WINAPI reader_thread (void *arg);
929
930 /* Find an unused process slot. */
931 child_process *
932 new_child (void)
933 {
934 child_process *cp;
935 DWORD id;
936
937 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
938 if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
939 goto Initialize;
940 if (child_proc_count == MAX_CHILDREN)
941 {
942 int i = 0;
943 child_process *dead_cp = NULL;
944
945 DebPrint (("new_child: No vacant slots, looking for dead processes\n"));
946 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
947 if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
948 {
949 DWORD status = 0;
950
951 if (!GetExitCodeProcess (cp->procinfo.hProcess, &status))
952 {
953 DebPrint (("new_child.GetExitCodeProcess: error %lu for PID %lu\n",
954 GetLastError (), cp->procinfo.dwProcessId));
955 status = STILL_ACTIVE;
956 }
957 if (status != STILL_ACTIVE
958 || WaitForSingleObject (cp->procinfo.hProcess, 0) == WAIT_OBJECT_0)
959 {
960 DebPrint (("new_child: Freeing slot of dead process %d, fd %d\n",
961 cp->procinfo.dwProcessId, cp->fd));
962 CloseHandle (cp->procinfo.hProcess);
963 cp->procinfo.hProcess = NULL;
964 CloseHandle (cp->procinfo.hThread);
965 cp->procinfo.hThread = NULL;
966 /* Free up to 2 dead slots at a time, so that if we
967 have a lot of them, they will eventually all be
968 freed when the tornado ends. */
969 if (i == 0)
970 dead_cp = cp;
971 else
972 break;
973 i++;
974 }
975 }
976 if (dead_cp)
977 {
978 cp = dead_cp;
979 goto Initialize;
980 }
981 }
982 if (child_proc_count == MAX_CHILDREN)
983 return NULL;
984 cp = &child_procs[child_proc_count++];
985
986 Initialize:
987 /* Last opportunity to avoid leaking handles before we forget them
988 for good. */
989 if (cp->procinfo.hProcess)
990 CloseHandle (cp->procinfo.hProcess);
991 if (cp->procinfo.hThread)
992 CloseHandle (cp->procinfo.hThread);
993 memset (cp, 0, sizeof (*cp));
994 cp->fd = -1;
995 cp->pid = -1;
996 cp->procinfo.hProcess = NULL;
997 cp->status = STATUS_READ_ERROR;
998
999 /* use manual reset event so that select() will function properly */
1000 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
1001 if (cp->char_avail)
1002 {
1003 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
1004 if (cp->char_consumed)
1005 {
1006 /* The 0x00010000 flag is STACK_SIZE_PARAM_IS_A_RESERVATION.
1007 It means that the 64K stack we are requesting in the 2nd
1008 argument is how much memory should be reserved for the
1009 stack. If we don't use this flag, the memory requested
1010 by the 2nd argument is the amount actually _committed_,
1011 but Windows reserves 8MB of memory for each thread's
1012 stack. (The 8MB figure comes from the -stack
1013 command-line argument we pass to the linker when building
1014 Emacs, but that's because we need a large stack for
1015 Emacs's main thread.) Since we request 2GB of reserved
1016 memory at startup (see w32heap.c), which is close to the
1017 maximum memory available for a 32-bit process on Windows,
1018 the 8MB reservation for each thread causes failures in
1019 starting subprocesses, because we create a thread running
1020 reader_thread for each subprocess. As 8MB of stack is
1021 way too much for reader_thread, forcing Windows to
1022 reserve less wins the day. */
1023 cp->thrd = CreateThread (NULL, 64 * 1024, reader_thread, cp,
1024 0x00010000, &id);
1025 if (cp->thrd)
1026 return cp;
1027 }
1028 }
1029 delete_child (cp);
1030 return NULL;
1031 }
1032
1033 void
1034 delete_child (child_process *cp)
1035 {
1036 int i;
1037
1038 /* Should not be deleting a child that is still needed. */
1039 for (i = 0; i < MAXDESC; i++)
1040 if (fd_info[i].cp == cp)
1041 emacs_abort ();
1042
1043 if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
1044 return;
1045
1046 /* reap thread if necessary */
1047 if (cp->thrd)
1048 {
1049 DWORD rc;
1050
1051 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
1052 {
1053 /* let the thread exit cleanly if possible */
1054 cp->status = STATUS_READ_ERROR;
1055 SetEvent (cp->char_consumed);
1056 #if 0
1057 /* We used to forcibly terminate the thread here, but it
1058 is normally unnecessary, and in abnormal cases, the worst that
1059 will happen is we have an extra idle thread hanging around
1060 waiting for the zombie process. */
1061 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
1062 {
1063 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
1064 "with %lu for fd %ld\n", GetLastError (), cp->fd));
1065 TerminateThread (cp->thrd, 0);
1066 }
1067 #endif
1068 }
1069 CloseHandle (cp->thrd);
1070 cp->thrd = NULL;
1071 }
1072 if (cp->char_avail)
1073 {
1074 CloseHandle (cp->char_avail);
1075 cp->char_avail = NULL;
1076 }
1077 if (cp->char_consumed)
1078 {
1079 CloseHandle (cp->char_consumed);
1080 cp->char_consumed = NULL;
1081 }
1082
1083 /* update child_proc_count (highest numbered slot in use plus one) */
1084 if (cp == child_procs + child_proc_count - 1)
1085 {
1086 for (i = child_proc_count-1; i >= 0; i--)
1087 if (CHILD_ACTIVE (&child_procs[i])
1088 || child_procs[i].procinfo.hProcess != NULL)
1089 {
1090 child_proc_count = i + 1;
1091 break;
1092 }
1093 }
1094 if (i < 0)
1095 child_proc_count = 0;
1096 }
1097
1098 /* Find a child by pid. */
1099 static child_process *
1100 find_child_pid (DWORD pid)
1101 {
1102 child_process *cp;
1103
1104 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1105 if ((CHILD_ACTIVE (cp) || cp->procinfo.hProcess != NULL)
1106 && pid == cp->pid)
1107 return cp;
1108 return NULL;
1109 }
1110
1111 void
1112 release_listen_threads (void)
1113 {
1114 int i;
1115
1116 for (i = child_proc_count - 1; i >= 0; i--)
1117 {
1118 if (CHILD_ACTIVE (&child_procs[i])
1119 && (fd_info[child_procs[i].fd].flags & FILE_LISTEN))
1120 child_procs[i].status = STATUS_READ_ERROR;
1121 }
1122 }
1123
1124 /* Thread proc for child process and socket reader threads. Each thread
1125 is normally blocked until woken by select() to check for input by
1126 reading one char. When the read completes, char_avail is signaled
1127 to wake up the select emulator and the thread blocks itself again. */
1128 static DWORD WINAPI
1129 reader_thread (void *arg)
1130 {
1131 child_process *cp;
1132
1133 /* Our identity */
1134 cp = (child_process *)arg;
1135
1136 /* We have to wait for the go-ahead before we can start */
1137 if (cp == NULL
1138 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
1139 || cp->fd < 0)
1140 return 1;
1141
1142 for (;;)
1143 {
1144 int rc;
1145
1146 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_CONNECT) != 0)
1147 rc = _sys_wait_connect (cp->fd);
1148 else if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_LISTEN) != 0)
1149 rc = _sys_wait_accept (cp->fd);
1150 else
1151 rc = _sys_read_ahead (cp->fd);
1152
1153 /* Don't bother waiting for the event if we already have been
1154 told to exit by delete_child. */
1155 if (cp->status == STATUS_READ_ERROR || !cp->char_avail)
1156 break;
1157
1158 /* The name char_avail is a misnomer - it really just means the
1159 read-ahead has completed, whether successfully or not. */
1160 if (!SetEvent (cp->char_avail))
1161 {
1162 DebPrint (("reader_thread.SetEvent(0x%x) failed with %lu for fd %ld (PID %d)\n",
1163 (DWORD_PTR)cp->char_avail, GetLastError (),
1164 cp->fd, cp->pid));
1165 return 1;
1166 }
1167
1168 if (rc == STATUS_READ_ERROR || rc == STATUS_CONNECT_FAILED)
1169 return 2;
1170
1171 /* If the read died, the child has died so let the thread die */
1172 if (rc == STATUS_READ_FAILED)
1173 break;
1174
1175 /* Don't bother waiting for the acknowledge if we already have
1176 been told to exit by delete_child. */
1177 if (cp->status == STATUS_READ_ERROR || !cp->char_consumed)
1178 break;
1179
1180 /* Wait until our input is acknowledged before reading again */
1181 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
1182 {
1183 DebPrint (("reader_thread.WaitForSingleObject failed with "
1184 "%lu for fd %ld\n", GetLastError (), cp->fd));
1185 break;
1186 }
1187 /* delete_child sets status to STATUS_READ_ERROR when it wants
1188 us to exit. */
1189 if (cp->status == STATUS_READ_ERROR)
1190 break;
1191 }
1192 return 0;
1193 }
1194
1195 /* To avoid Emacs changing directory, we just record here the
1196 directory the new process should start in. This is set just before
1197 calling sys_spawnve, and is not generally valid at any other time.
1198 Note that this directory's name is UTF-8 encoded. */
1199 static char * process_dir;
1200
1201 static BOOL
1202 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
1203 pid_t * pPid, child_process *cp)
1204 {
1205 STARTUPINFO start;
1206 SECURITY_ATTRIBUTES sec_attrs;
1207 #if 0
1208 SECURITY_DESCRIPTOR sec_desc;
1209 #endif
1210 DWORD flags;
1211 char dir[ MAX_PATH ];
1212 char *p;
1213 const char *ext;
1214
1215 if (cp == NULL) emacs_abort ();
1216
1217 memset (&start, 0, sizeof (start));
1218 start.cb = sizeof (start);
1219
1220 #ifdef HAVE_NTGUI
1221 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
1222 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1223 else
1224 start.dwFlags = STARTF_USESTDHANDLES;
1225 start.wShowWindow = SW_HIDE;
1226
1227 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
1228 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
1229 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
1230 #endif /* HAVE_NTGUI */
1231
1232 #if 0
1233 /* Explicitly specify no security */
1234 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
1235 goto EH_Fail;
1236 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
1237 goto EH_Fail;
1238 #endif
1239 sec_attrs.nLength = sizeof (sec_attrs);
1240 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
1241 sec_attrs.bInheritHandle = FALSE;
1242
1243 filename_to_ansi (process_dir, dir);
1244 /* Can't use unixtodos_filename here, since that needs its file name
1245 argument encoded in UTF-8. OTOH, process_dir, which _is_ in
1246 UTF-8, points, to the directory computed by our caller, and we
1247 don't want to modify that, either. */
1248 for (p = dir; *p; p = CharNextA (p))
1249 if (*p == '/')
1250 *p = '\\';
1251
1252 /* CreateProcess handles batch files as exe specially. This special
1253 handling fails when both the batch file and arguments are quoted.
1254 We pass NULL as exe to avoid the special handling. */
1255 if (exe && cmdline[0] == '"' &&
1256 (ext = strrchr (exe, '.')) &&
1257 (xstrcasecmp (ext, ".bat") == 0
1258 || xstrcasecmp (ext, ".cmd") == 0))
1259 exe = NULL;
1260
1261 flags = (!NILP (Vw32_start_process_share_console)
1262 ? CREATE_NEW_PROCESS_GROUP
1263 : CREATE_NEW_CONSOLE);
1264 if (NILP (Vw32_start_process_inherit_error_mode))
1265 flags |= CREATE_DEFAULT_ERROR_MODE;
1266 if (!CreateProcessA (exe, cmdline, &sec_attrs, NULL, TRUE,
1267 flags, env, dir, &start, &cp->procinfo))
1268 goto EH_Fail;
1269
1270 cp->pid = (int) cp->procinfo.dwProcessId;
1271
1272 /* Hack for Windows 95, which assigns large (ie negative) pids */
1273 if (cp->pid < 0)
1274 cp->pid = -cp->pid;
1275
1276 *pPid = cp->pid;
1277
1278 return TRUE;
1279
1280 EH_Fail:
1281 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
1282 return FALSE;
1283 }
1284
1285 /* create_child doesn't know what emacs's file handle will be for waiting
1286 on output from the child, so we need to make this additional call
1287 to register the handle with the process
1288 This way the select emulator knows how to match file handles with
1289 entries in child_procs. */
1290 void
1291 register_child (pid_t pid, int fd)
1292 {
1293 child_process *cp;
1294
1295 cp = find_child_pid ((DWORD)pid);
1296 if (cp == NULL)
1297 {
1298 DebPrint (("register_child unable to find pid %lu\n", pid));
1299 return;
1300 }
1301
1302 #ifdef FULL_DEBUG
1303 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
1304 #endif
1305
1306 cp->fd = fd;
1307
1308 /* thread is initially blocked until select is called; set status so
1309 that select will release thread */
1310 cp->status = STATUS_READ_ACKNOWLEDGED;
1311
1312 /* attach child_process to fd_info */
1313 if (fd_info[fd].cp != NULL)
1314 {
1315 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
1316 emacs_abort ();
1317 }
1318
1319 fd_info[fd].cp = cp;
1320 }
1321
1322 /* Called from waitpid when a process exits. */
1323 static void
1324 reap_subprocess (child_process *cp)
1325 {
1326 if (cp->procinfo.hProcess)
1327 {
1328 /* Reap the process */
1329 #ifdef FULL_DEBUG
1330 /* Process should have already died before we are called. */
1331 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
1332 DebPrint (("reap_subprocess: child for fd %d has not died yet!", cp->fd));
1333 #endif
1334 CloseHandle (cp->procinfo.hProcess);
1335 cp->procinfo.hProcess = NULL;
1336 CloseHandle (cp->procinfo.hThread);
1337 cp->procinfo.hThread = NULL;
1338 }
1339
1340 /* If cp->fd was not closed yet, we might be still reading the
1341 process output, so don't free its resources just yet. The call
1342 to delete_child on behalf of this subprocess will be made by
1343 sys_read when the subprocess output is fully read. */
1344 if (cp->fd < 0)
1345 delete_child (cp);
1346 }
1347
1348 /* Wait for a child process specified by PID, or for any of our
1349 existing child processes (if PID is nonpositive) to die. When it
1350 does, close its handle. Return the pid of the process that died
1351 and fill in STATUS if non-NULL. */
1352
1353 pid_t
1354 waitpid (pid_t pid, int *status, int options)
1355 {
1356 DWORD active, retval;
1357 int nh;
1358 child_process *cp, *cps[MAX_CHILDREN];
1359 HANDLE wait_hnd[MAX_CHILDREN];
1360 DWORD timeout_ms;
1361 int dont_wait = (options & WNOHANG) != 0;
1362
1363 nh = 0;
1364 /* According to Posix:
1365
1366 PID = -1 means status is requested for any child process.
1367
1368 PID > 0 means status is requested for a single child process
1369 whose pid is PID.
1370
1371 PID = 0 means status is requested for any child process whose
1372 process group ID is equal to that of the calling process. But
1373 since Windows has only a limited support for process groups (only
1374 for console processes and only for the purposes of passing
1375 Ctrl-BREAK signal to them), and since we have no documented way
1376 of determining whether a given process belongs to our group, we
1377 treat 0 as -1.
1378
1379 PID < -1 means status is requested for any child process whose
1380 process group ID is equal to the absolute value of PID. Again,
1381 since we don't support process groups, we treat that as -1. */
1382 if (pid > 0)
1383 {
1384 int our_child = 0;
1385
1386 /* We are requested to wait for a specific child. */
1387 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1388 {
1389 /* Some child_procs might be sockets; ignore them. Also
1390 ignore subprocesses whose output is not yet completely
1391 read. */
1392 if (CHILD_ACTIVE (cp)
1393 && cp->procinfo.hProcess
1394 && cp->pid == pid)
1395 {
1396 our_child = 1;
1397 break;
1398 }
1399 }
1400 if (our_child)
1401 {
1402 if (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1403 {
1404 wait_hnd[nh] = cp->procinfo.hProcess;
1405 cps[nh] = cp;
1406 nh++;
1407 }
1408 else if (dont_wait)
1409 {
1410 /* PID specifies our subprocess, but its status is not
1411 yet available. */
1412 return 0;
1413 }
1414 }
1415 if (nh == 0)
1416 {
1417 /* No such child process, or nothing to wait for, so fail. */
1418 errno = ECHILD;
1419 return -1;
1420 }
1421 }
1422 else
1423 {
1424 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1425 {
1426 if (CHILD_ACTIVE (cp)
1427 && cp->procinfo.hProcess
1428 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
1429 {
1430 wait_hnd[nh] = cp->procinfo.hProcess;
1431 cps[nh] = cp;
1432 nh++;
1433 }
1434 }
1435 if (nh == 0)
1436 {
1437 /* Nothing to wait on, so fail. */
1438 errno = ECHILD;
1439 return -1;
1440 }
1441 }
1442
1443 if (dont_wait)
1444 timeout_ms = 0;
1445 else
1446 timeout_ms = 1000; /* check for quit about once a second. */
1447
1448 do
1449 {
1450 QUIT;
1451 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, timeout_ms);
1452 } while (active == WAIT_TIMEOUT && !dont_wait);
1453
1454 if (active == WAIT_FAILED)
1455 {
1456 errno = EBADF;
1457 return -1;
1458 }
1459 else if (active == WAIT_TIMEOUT && dont_wait)
1460 {
1461 /* PID specifies our subprocess, but it didn't exit yet, so its
1462 status is not yet available. */
1463 #ifdef FULL_DEBUG
1464 DebPrint (("Wait: PID %d not reap yet\n", cp->pid));
1465 #endif
1466 return 0;
1467 }
1468 else if (active >= WAIT_OBJECT_0
1469 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1470 {
1471 active -= WAIT_OBJECT_0;
1472 }
1473 else if (active >= WAIT_ABANDONED_0
1474 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1475 {
1476 active -= WAIT_ABANDONED_0;
1477 }
1478 else
1479 emacs_abort ();
1480
1481 if (!GetExitCodeProcess (wait_hnd[active], &retval))
1482 {
1483 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
1484 GetLastError ()));
1485 retval = 1;
1486 }
1487 if (retval == STILL_ACTIVE)
1488 {
1489 /* Should never happen. */
1490 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
1491 if (pid > 0 && dont_wait)
1492 return 0;
1493 errno = EINVAL;
1494 return -1;
1495 }
1496
1497 /* Massage the exit code from the process to match the format expected
1498 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
1499 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
1500
1501 if (retval == STATUS_CONTROL_C_EXIT)
1502 retval = SIGINT;
1503 else
1504 retval <<= 8;
1505
1506 if (pid > 0 && active != 0)
1507 emacs_abort ();
1508 cp = cps[active];
1509 pid = cp->pid;
1510 #ifdef FULL_DEBUG
1511 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
1512 #endif
1513
1514 if (status)
1515 *status = retval;
1516 reap_subprocess (cp);
1517
1518 return pid;
1519 }
1520
1521 /* Old versions of w32api headers don't have separate 32-bit and
1522 64-bit defines, but the one they have matches the 32-bit variety. */
1523 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
1524 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
1525 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
1526 #endif
1527
1528 /* Implementation note: This function works with file names encoded in
1529 the current ANSI codepage. */
1530 static int
1531 w32_executable_type (char * filename,
1532 int * is_dos_app,
1533 int * is_cygnus_app,
1534 int * is_msys_app,
1535 int * is_gui_app)
1536 {
1537 file_data executable;
1538 char * p;
1539 int retval = 0;
1540
1541 /* Default values in case we can't tell for sure. */
1542 *is_dos_app = FALSE;
1543 *is_cygnus_app = FALSE;
1544 *is_msys_app = FALSE;
1545 *is_gui_app = FALSE;
1546
1547 if (!open_input_file (&executable, filename))
1548 return -1;
1549
1550 p = strrchr (filename, '.');
1551
1552 /* We can only identify DOS .com programs from the extension. */
1553 if (p && xstrcasecmp (p, ".com") == 0)
1554 *is_dos_app = TRUE;
1555 else if (p && (xstrcasecmp (p, ".bat") == 0
1556 || xstrcasecmp (p, ".cmd") == 0))
1557 {
1558 /* A DOS shell script - it appears that CreateProcess is happy to
1559 accept this (somewhat surprisingly); presumably it looks at
1560 COMSPEC to determine what executable to actually invoke.
1561 Therefore, we have to do the same here as well. */
1562 /* Actually, I think it uses the program association for that
1563 extension, which is defined in the registry. */
1564 p = egetenv ("COMSPEC");
1565 if (p)
1566 retval = w32_executable_type (p, is_dos_app, is_cygnus_app, is_msys_app,
1567 is_gui_app);
1568 }
1569 else
1570 {
1571 /* Look for DOS .exe signature - if found, we must also check that
1572 it isn't really a 16- or 32-bit Windows exe, since both formats
1573 start with a DOS program stub. Note that 16-bit Windows
1574 executables use the OS/2 1.x format. */
1575
1576 IMAGE_DOS_HEADER * dos_header;
1577 IMAGE_NT_HEADERS * nt_header;
1578
1579 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
1580 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
1581 goto unwind;
1582
1583 nt_header = (PIMAGE_NT_HEADERS) ((unsigned char *) dos_header + dos_header->e_lfanew);
1584
1585 if ((char *) nt_header > (char *) dos_header + executable.size)
1586 {
1587 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
1588 *is_dos_app = TRUE;
1589 }
1590 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
1591 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
1592 {
1593 *is_dos_app = TRUE;
1594 }
1595 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
1596 {
1597 IMAGE_DATA_DIRECTORY *data_dir = NULL;
1598 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
1599 {
1600 /* Ensure we are using the 32 bit structure. */
1601 IMAGE_OPTIONAL_HEADER32 *opt
1602 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
1603 data_dir = opt->DataDirectory;
1604 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
1605 }
1606 /* MingW 3.12 has the required 64 bit structs, but in case older
1607 versions don't, only check 64 bit exes if we know how. */
1608 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
1609 else if (nt_header->OptionalHeader.Magic
1610 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1611 {
1612 IMAGE_OPTIONAL_HEADER64 *opt
1613 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
1614 data_dir = opt->DataDirectory;
1615 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
1616 }
1617 #endif
1618 if (data_dir)
1619 {
1620 /* Look for Cygwin DLL in the DLL import list. */
1621 IMAGE_DATA_DIRECTORY import_dir =
1622 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
1623 IMAGE_IMPORT_DESCRIPTOR * imports =
1624 RVA_TO_PTR (import_dir.VirtualAddress,
1625 rva_to_section (import_dir.VirtualAddress,
1626 nt_header),
1627 executable);
1628
1629 for ( ; imports->Name; imports++)
1630 {
1631 IMAGE_SECTION_HEADER * section =
1632 rva_to_section (imports->Name, nt_header);
1633 char * dllname = RVA_TO_PTR (imports->Name, section,
1634 executable);
1635
1636 /* The exact name of the Cygwin DLL has changed with
1637 various releases, but hopefully this will be
1638 reasonably future-proof. */
1639 if (strncmp (dllname, "cygwin", 6) == 0)
1640 {
1641 *is_cygnus_app = TRUE;
1642 break;
1643 }
1644 else if (strncmp (dllname, "msys-", 5) == 0)
1645 {
1646 /* This catches both MSYS 1.x and MSYS2
1647 executables (the DLL name is msys-1.0.dll and
1648 msys-2.0.dll, respectively). There doesn't
1649 seem to be a reason to distinguish between
1650 the two, for now. */
1651 *is_msys_app = TRUE;
1652 break;
1653 }
1654 }
1655 }
1656 }
1657 }
1658
1659 unwind:
1660 close_file_data (&executable);
1661 return retval;
1662 }
1663
1664 static int
1665 compare_env (const void *strp1, const void *strp2)
1666 {
1667 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
1668
1669 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
1670 {
1671 /* Sort order in command.com/cmd.exe is based on uppercasing
1672 names, so do the same here. */
1673 if (toupper (*str1) > toupper (*str2))
1674 return 1;
1675 else if (toupper (*str1) < toupper (*str2))
1676 return -1;
1677 str1++, str2++;
1678 }
1679
1680 if (*str1 == '=' && *str2 == '=')
1681 return 0;
1682 else if (*str1 == '=')
1683 return -1;
1684 else
1685 return 1;
1686 }
1687
1688 static void
1689 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
1690 {
1691 char **optr, **nptr;
1692 int num;
1693
1694 nptr = new_envp;
1695 optr = envp1;
1696 while (*optr)
1697 *nptr++ = *optr++;
1698 num = optr - envp1;
1699
1700 optr = envp2;
1701 while (*optr)
1702 *nptr++ = *optr++;
1703 num += optr - envp2;
1704
1705 qsort (new_envp, num, sizeof (char *), compare_env);
1706
1707 *nptr = NULL;
1708 }
1709
1710 /* When a new child process is created we need to register it in our list,
1711 so intercept spawn requests. */
1712 int
1713 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
1714 {
1715 Lisp_Object program, full;
1716 char *cmdline, *env, *parg, **targ;
1717 int arglen, numenv;
1718 pid_t pid;
1719 child_process *cp;
1720 int is_dos_app, is_cygnus_app, is_msys_app, is_gui_app;
1721 int do_quoting = 0;
1722 /* We pass our process ID to our children by setting up an environment
1723 variable in their environment. */
1724 char ppid_env_var_buffer[64];
1725 char *extra_env[] = {ppid_env_var_buffer, NULL};
1726 /* These are the characters that cause an argument to need quoting.
1727 Arguments with whitespace characters need quoting to prevent the
1728 argument being split into two or more. Arguments with wildcards
1729 are also quoted, for consistency with posix platforms, where wildcards
1730 are not expanded if we run the program directly without a shell.
1731 Some extra whitespace characters need quoting in Cygwin/MSYS programs,
1732 so this list is conditionally modified below. */
1733 char *sepchars = " \t*?";
1734 /* This is for native w32 apps; modified below for Cygwin/MSUS apps. */
1735 char escape_char = '\\';
1736 char cmdname_a[MAX_PATH];
1737
1738 /* We don't care about the other modes */
1739 if (mode != _P_NOWAIT)
1740 {
1741 errno = EINVAL;
1742 return -1;
1743 }
1744
1745 /* Handle executable names without an executable suffix. The caller
1746 already searched exec-path and verified the file is executable,
1747 but start-process doesn't do that for file names that are already
1748 absolute. So we double-check this here, just in case. */
1749 if (faccessat (AT_FDCWD, cmdname, X_OK, AT_EACCESS) != 0)
1750 {
1751 struct gcpro gcpro1;
1752
1753 program = build_string (cmdname);
1754 full = Qnil;
1755 GCPRO1 (program);
1756 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK), 0);
1757 UNGCPRO;
1758 if (NILP (full))
1759 {
1760 errno = EINVAL;
1761 return -1;
1762 }
1763 program = ENCODE_FILE (full);
1764 cmdname = SDATA (program);
1765 }
1766 else
1767 {
1768 char *p = alloca (strlen (cmdname) + 1);
1769
1770 /* Don't change the command name we were passed by our caller
1771 (unixtodos_filename below will destructively mirror forward
1772 slashes). */
1773 cmdname = strcpy (p, cmdname);
1774 }
1775
1776 /* make sure argv[0] and cmdname are both in DOS format */
1777 unixtodos_filename (cmdname);
1778 /* argv[0] was encoded by caller using ENCODE_FILE, so it is in
1779 UTF-8. All the other arguments are encoded by ENCODE_SYSTEM or
1780 some such, and are in some ANSI codepage. We need to have
1781 argv[0] encoded in ANSI codepage. */
1782 filename_to_ansi (cmdname, cmdname_a);
1783 /* We explicitly require that the command's file name be encodable
1784 in the current ANSI codepage, because we will be invoking it via
1785 the ANSI APIs. */
1786 if (_mbspbrk (cmdname_a, "?"))
1787 {
1788 errno = ENOENT;
1789 return -1;
1790 }
1791 /* From here on, CMDNAME is an ANSI-encoded string. */
1792 cmdname = cmdname_a;
1793 argv[0] = cmdname;
1794
1795 /* Determine whether program is a 16-bit DOS executable, or a 32-bit
1796 Windows executable that is implicitly linked to the Cygnus or
1797 MSYS dll (implying it was compiled with the Cygnus/MSYS GNU
1798 toolchain and hence relies on cygwin.dll or MSYS DLL to parse the
1799 command line - we use this to decide how to escape quote chars in
1800 command line args that must be quoted).
1801
1802 Also determine whether it is a GUI app, so that we don't hide its
1803 initial window unless specifically requested. */
1804 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_msys_app,
1805 &is_gui_app);
1806
1807 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
1808 application to start it by specifying the helper app as cmdname,
1809 while leaving the real app name as argv[0]. */
1810 if (is_dos_app)
1811 {
1812 char *p;
1813
1814 cmdname = alloca (MAX_PATH);
1815 if (egetenv ("CMDPROXY"))
1816 strcpy (cmdname, egetenv ("CMDPROXY"));
1817 else
1818 strcpy (lispstpcpy (cmdname, Vinvocation_directory), "cmdproxy.exe");
1819
1820 /* Can't use unixtodos_filename here, since that needs its file
1821 name argument encoded in UTF-8. */
1822 for (p = cmdname; *p; p = CharNextA (p))
1823 if (*p == '/')
1824 *p = '\\';
1825 }
1826
1827 /* we have to do some conjuring here to put argv and envp into the
1828 form CreateProcess wants... argv needs to be a space separated/null
1829 terminated list of parameters, and envp is a null
1830 separated/double-null terminated list of parameters.
1831
1832 Additionally, zero-length args and args containing whitespace or
1833 quote chars need to be wrapped in double quotes - for this to work,
1834 embedded quotes need to be escaped as well. The aim is to ensure
1835 the child process reconstructs the argv array we start with
1836 exactly, so we treat quotes at the beginning and end of arguments
1837 as embedded quotes.
1838
1839 The w32 GNU-based library from Cygnus doubles quotes to escape
1840 them, while MSVC uses backslash for escaping. (Actually the MSVC
1841 startup code does attempt to recognize doubled quotes and accept
1842 them, but gets it wrong and ends up requiring three quotes to get a
1843 single embedded quote!) So by default we decide whether to use
1844 quote or backslash as the escape character based on whether the
1845 binary is apparently a Cygnus compiled app.
1846
1847 Note that using backslash to escape embedded quotes requires
1848 additional special handling if an embedded quote is already
1849 preceded by backslash, or if an arg requiring quoting ends with
1850 backslash. In such cases, the run of escape characters needs to be
1851 doubled. For consistency, we apply this special handling as long
1852 as the escape character is not quote.
1853
1854 Since we have no idea how large argv and envp are likely to be we
1855 figure out list lengths on the fly and allocate them. */
1856
1857 if (!NILP (Vw32_quote_process_args))
1858 {
1859 do_quoting = 1;
1860 /* Override escape char by binding w32-quote-process-args to
1861 desired character, or use t for auto-selection. */
1862 if (INTEGERP (Vw32_quote_process_args))
1863 escape_char = XINT (Vw32_quote_process_args);
1864 else
1865 escape_char = (is_cygnus_app || is_msys_app) ? '"' : '\\';
1866 }
1867
1868 /* Cygwin/MSYS apps need quoting a bit more often. */
1869 if (escape_char == '"')
1870 sepchars = "\r\n\t\f '";
1871
1872 /* do argv... */
1873 arglen = 0;
1874 targ = argv;
1875 while (*targ)
1876 {
1877 char * p = *targ;
1878 int need_quotes = 0;
1879 int escape_char_run = 0;
1880
1881 if (*p == 0)
1882 need_quotes = 1;
1883 for ( ; *p; p++)
1884 {
1885 if (escape_char == '"' && *p == '\\')
1886 /* If it's a Cygwin/MSYS app, \ needs to be escaped. */
1887 arglen++;
1888 else if (*p == '"')
1889 {
1890 /* allow for embedded quotes to be escaped */
1891 arglen++;
1892 need_quotes = 1;
1893 /* handle the case where the embedded quote is already escaped */
1894 if (escape_char_run > 0)
1895 {
1896 /* To preserve the arg exactly, we need to double the
1897 preceding escape characters (plus adding one to
1898 escape the quote character itself). */
1899 arglen += escape_char_run;
1900 }
1901 }
1902 else if (strchr (sepchars, *p) != NULL)
1903 {
1904 need_quotes = 1;
1905 }
1906
1907 if (*p == escape_char && escape_char != '"')
1908 escape_char_run++;
1909 else
1910 escape_char_run = 0;
1911 }
1912 if (need_quotes)
1913 {
1914 arglen += 2;
1915 /* handle the case where the arg ends with an escape char - we
1916 must not let the enclosing quote be escaped. */
1917 if (escape_char_run > 0)
1918 arglen += escape_char_run;
1919 }
1920 arglen += strlen (*targ++) + 1;
1921 }
1922 cmdline = alloca (arglen);
1923 targ = argv;
1924 parg = cmdline;
1925 while (*targ)
1926 {
1927 char * p = *targ;
1928 int need_quotes = 0;
1929
1930 if (*p == 0)
1931 need_quotes = 1;
1932
1933 if (do_quoting)
1934 {
1935 for ( ; *p; p++)
1936 if ((strchr (sepchars, *p) != NULL) || *p == '"')
1937 need_quotes = 1;
1938 }
1939 if (need_quotes)
1940 {
1941 int escape_char_run = 0;
1942 /* char * first; */
1943 /* char * last; */
1944
1945 p = *targ;
1946 /* first = p; */
1947 /* last = p + strlen (p) - 1; */
1948 *parg++ = '"';
1949 #if 0
1950 /* This version does not escape quotes if they occur at the
1951 beginning or end of the arg - this could lead to incorrect
1952 behavior when the arg itself represents a command line
1953 containing quoted args. I believe this was originally done
1954 as a hack to make some things work, before
1955 `w32-quote-process-args' was added. */
1956 while (*p)
1957 {
1958 if (*p == '"' && p > first && p < last)
1959 *parg++ = escape_char; /* escape embedded quotes */
1960 *parg++ = *p++;
1961 }
1962 #else
1963 for ( ; *p; p++)
1964 {
1965 if (*p == '"')
1966 {
1967 /* double preceding escape chars if any */
1968 while (escape_char_run > 0)
1969 {
1970 *parg++ = escape_char;
1971 escape_char_run--;
1972 }
1973 /* escape all quote chars, even at beginning or end */
1974 *parg++ = escape_char;
1975 }
1976 else if (escape_char == '"' && *p == '\\')
1977 *parg++ = '\\';
1978 *parg++ = *p;
1979
1980 if (*p == escape_char && escape_char != '"')
1981 escape_char_run++;
1982 else
1983 escape_char_run = 0;
1984 }
1985 /* double escape chars before enclosing quote */
1986 while (escape_char_run > 0)
1987 {
1988 *parg++ = escape_char;
1989 escape_char_run--;
1990 }
1991 #endif
1992 *parg++ = '"';
1993 }
1994 else
1995 {
1996 strcpy (parg, *targ);
1997 parg += strlen (*targ);
1998 }
1999 *parg++ = ' ';
2000 targ++;
2001 }
2002 *--parg = '\0';
2003
2004 /* and envp... */
2005 arglen = 1;
2006 targ = envp;
2007 numenv = 1; /* for end null */
2008 while (*targ)
2009 {
2010 arglen += strlen (*targ++) + 1;
2011 numenv++;
2012 }
2013 /* extra env vars... */
2014 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%lu",
2015 GetCurrentProcessId ());
2016 arglen += strlen (ppid_env_var_buffer) + 1;
2017 numenv++;
2018
2019 /* merge env passed in and extra env into one, and sort it. */
2020 targ = (char **) alloca (numenv * sizeof (char *));
2021 merge_and_sort_env (envp, extra_env, targ);
2022
2023 /* concatenate env entries. */
2024 env = alloca (arglen);
2025 parg = env;
2026 while (*targ)
2027 {
2028 strcpy (parg, *targ);
2029 parg += strlen (*targ++);
2030 *parg++ = '\0';
2031 }
2032 *parg++ = '\0';
2033 *parg = '\0';
2034
2035 cp = new_child ();
2036 if (cp == NULL)
2037 {
2038 errno = EAGAIN;
2039 return -1;
2040 }
2041
2042 /* Now create the process. */
2043 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
2044 {
2045 delete_child (cp);
2046 errno = ENOEXEC;
2047 return -1;
2048 }
2049
2050 return pid;
2051 }
2052
2053 /* Emulate the select call
2054 Wait for available input on any of the given rfds, or timeout if
2055 a timeout is given and no input is detected
2056 wfds and efds are not supported and must be NULL.
2057
2058 For simplicity, we detect the death of child processes here and
2059 synchronously call the SIGCHLD handler. Since it is possible for
2060 children to be created without a corresponding pipe handle from which
2061 to read output, we wait separately on the process handles as well as
2062 the char_avail events for each process pipe. We only call
2063 wait/reap_process when the process actually terminates.
2064
2065 To reduce the number of places in which Emacs can be hung such that
2066 C-g is not able to interrupt it, we always wait on interrupt_handle
2067 (which is signaled by the input thread when C-g is detected). If we
2068 detect that we were woken up by C-g, we return -1 with errno set to
2069 EINTR as on Unix. */
2070
2071 /* From w32console.c */
2072 extern HANDLE keyboard_handle;
2073
2074 /* From w32xfns.c */
2075 extern HANDLE interrupt_handle;
2076
2077 /* From process.c */
2078 extern int proc_buffered_char[];
2079
2080 int
2081 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
2082 struct timespec *timeout, void *ignored)
2083 {
2084 SELECT_TYPE orfds, owfds;
2085 DWORD timeout_ms, start_time;
2086 int i, nh, nc, nr;
2087 DWORD active;
2088 child_process *cp, *cps[MAX_CHILDREN];
2089 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
2090 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
2091
2092 timeout_ms =
2093 timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 1000000) : INFINITE;
2094
2095 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
2096 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
2097 {
2098 Sleep (timeout_ms);
2099 return 0;
2100 }
2101
2102 /* Otherwise, we only handle rfds and wfds, so fail otherwise. */
2103 if ((rfds == NULL && wfds == NULL) || efds != NULL)
2104 {
2105 errno = EINVAL;
2106 return -1;
2107 }
2108
2109 if (rfds)
2110 {
2111 orfds = *rfds;
2112 FD_ZERO (rfds);
2113 }
2114 else
2115 FD_ZERO (&orfds);
2116 if (wfds)
2117 {
2118 owfds = *wfds;
2119 FD_ZERO (wfds);
2120 }
2121 else
2122 FD_ZERO (&owfds);
2123 nr = 0;
2124
2125 /* If interrupt_handle is available and valid, always wait on it, to
2126 detect C-g (quit). */
2127 nh = 0;
2128 if (interrupt_handle && interrupt_handle != INVALID_HANDLE_VALUE)
2129 {
2130 wait_hnd[0] = interrupt_handle;
2131 fdindex[0] = -1;
2132 nh++;
2133 }
2134
2135 /* Build a list of pipe handles to wait on. */
2136 for (i = 0; i < nfds; i++)
2137 if (FD_ISSET (i, &orfds) || FD_ISSET (i, &owfds))
2138 {
2139 if (i == 0)
2140 {
2141 if (keyboard_handle)
2142 {
2143 /* Handle stdin specially */
2144 wait_hnd[nh] = keyboard_handle;
2145 fdindex[nh] = i;
2146 nh++;
2147 }
2148
2149 /* Check for any emacs-generated input in the queue since
2150 it won't be detected in the wait */
2151 if (rfds && detect_input_pending ())
2152 {
2153 FD_SET (i, rfds);
2154 return 1;
2155 }
2156 else if (noninteractive)
2157 {
2158 if (handle_file_notifications (NULL))
2159 return 1;
2160 }
2161 }
2162 else
2163 {
2164 /* Child process and socket/comm port input. */
2165 cp = fd_info[i].cp;
2166 if (FD_ISSET (i, &owfds)
2167 && cp
2168 && (fd_info[i].flags && FILE_CONNECT) == 0)
2169 {
2170 DebPrint (("sys_select: fd %d is in wfds, but FILE_CONNECT is reset!\n", i));
2171 cp = NULL;
2172 }
2173 if (cp)
2174 {
2175 int current_status = cp->status;
2176
2177 if (current_status == STATUS_READ_ACKNOWLEDGED)
2178 {
2179 /* Tell reader thread which file handle to use. */
2180 cp->fd = i;
2181 /* Zero out the error code. */
2182 cp->errcode = 0;
2183 /* Wake up the reader thread for this process */
2184 cp->status = STATUS_READ_READY;
2185 if (!SetEvent (cp->char_consumed))
2186 DebPrint (("sys_select.SetEvent failed with "
2187 "%lu for fd %ld\n", GetLastError (), i));
2188 }
2189
2190 #ifdef CHECK_INTERLOCK
2191 /* slightly crude cross-checking of interlock between threads */
2192
2193 current_status = cp->status;
2194 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
2195 {
2196 /* char_avail has been signaled, so status (which may
2197 have changed) should indicate read has completed
2198 but has not been acknowledged. */
2199 current_status = cp->status;
2200 if (current_status != STATUS_READ_SUCCEEDED
2201 && current_status != STATUS_READ_FAILED)
2202 DebPrint (("char_avail set, but read not completed: status %d\n",
2203 current_status));
2204 }
2205 else
2206 {
2207 /* char_avail has not been signaled, so status should
2208 indicate that read is in progress; small possibility
2209 that read has completed but event wasn't yet signaled
2210 when we tested it (because a context switch occurred
2211 or if running on separate CPUs). */
2212 if (current_status != STATUS_READ_READY
2213 && current_status != STATUS_READ_IN_PROGRESS
2214 && current_status != STATUS_READ_SUCCEEDED
2215 && current_status != STATUS_READ_FAILED)
2216 DebPrint (("char_avail reset, but read status is bad: %d\n",
2217 current_status));
2218 }
2219 #endif
2220 wait_hnd[nh] = cp->char_avail;
2221 fdindex[nh] = i;
2222 if (!wait_hnd[nh]) emacs_abort ();
2223 nh++;
2224 #ifdef FULL_DEBUG
2225 DebPrint (("select waiting on child %d fd %d\n",
2226 cp-child_procs, i));
2227 #endif
2228 }
2229 else
2230 {
2231 /* Unable to find something to wait on for this fd, skip */
2232
2233 /* Note that this is not a fatal error, and can in fact
2234 happen in unusual circumstances. Specifically, if
2235 sys_spawnve fails, eg. because the program doesn't
2236 exist, and debug-on-error is t so Fsignal invokes a
2237 nested input loop, then the process output pipe is
2238 still included in input_wait_mask with no child_proc
2239 associated with it. (It is removed when the debugger
2240 exits the nested input loop and the error is thrown.) */
2241
2242 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
2243 }
2244 }
2245 }
2246
2247 count_children:
2248 /* Add handles of child processes. */
2249 nc = 0;
2250 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
2251 /* Some child_procs might be sockets; ignore them. Also some
2252 children may have died already, but we haven't finished reading
2253 the process output; ignore them too. */
2254 if ((CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
2255 && (cp->fd < 0
2256 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
2257 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
2258 )
2259 {
2260 wait_hnd[nh + nc] = cp->procinfo.hProcess;
2261 cps[nc] = cp;
2262 nc++;
2263 }
2264
2265 /* Nothing to look for, so we didn't find anything */
2266 if (nh + nc == 0)
2267 {
2268 if (timeout)
2269 Sleep (timeout_ms);
2270 if (noninteractive)
2271 {
2272 if (handle_file_notifications (NULL))
2273 return 1;
2274 }
2275 return 0;
2276 }
2277
2278 start_time = GetTickCount ();
2279
2280 /* Wait for input or child death to be signaled. If user input is
2281 allowed, then also accept window messages. */
2282 if (FD_ISSET (0, &orfds))
2283 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
2284 QS_ALLINPUT);
2285 else
2286 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
2287
2288 if (active == WAIT_FAILED)
2289 {
2290 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
2291 nh + nc, timeout_ms, GetLastError ()));
2292 /* don't return EBADF - this causes wait_reading_process_output to
2293 abort; WAIT_FAILED is returned when single-stepping under
2294 Windows 95 after switching thread focus in debugger, and
2295 possibly at other times. */
2296 errno = EINTR;
2297 return -1;
2298 }
2299 else if (active == WAIT_TIMEOUT)
2300 {
2301 if (noninteractive)
2302 {
2303 if (handle_file_notifications (NULL))
2304 return 1;
2305 }
2306 return 0;
2307 }
2308 else if (active >= WAIT_OBJECT_0
2309 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
2310 {
2311 active -= WAIT_OBJECT_0;
2312 }
2313 else if (active >= WAIT_ABANDONED_0
2314 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
2315 {
2316 active -= WAIT_ABANDONED_0;
2317 }
2318 else
2319 emacs_abort ();
2320
2321 /* Loop over all handles after active (now officially documented as
2322 being the first signaled handle in the array). We do this to
2323 ensure fairness, so that all channels with data available will be
2324 processed - otherwise higher numbered channels could be starved. */
2325 do
2326 {
2327 if (active == nh + nc)
2328 {
2329 /* There are messages in the lisp thread's queue; we must
2330 drain the queue now to ensure they are processed promptly,
2331 because if we don't do so, we will not be woken again until
2332 further messages arrive.
2333
2334 NB. If ever we allow window message procedures to callback
2335 into lisp, we will need to ensure messages are dispatched
2336 at a safe time for lisp code to be run (*), and we may also
2337 want to provide some hooks in the dispatch loop to cater
2338 for modeless dialogs created by lisp (ie. to register
2339 window handles to pass to IsDialogMessage).
2340
2341 (*) Note that MsgWaitForMultipleObjects above is an
2342 internal dispatch point for messages that are sent to
2343 windows created by this thread. */
2344 if (drain_message_queue ()
2345 /* If drain_message_queue returns non-zero, that means
2346 we received a WM_EMACS_FILENOTIFY message. If this
2347 is a TTY frame, we must signal the caller that keyboard
2348 input is available, so that w32_console_read_socket
2349 will be called to pick up the notifications. If we
2350 don't do that, file notifications will only work when
2351 the Emacs TTY frame has focus. */
2352 && FRAME_TERMCAP_P (SELECTED_FRAME ())
2353 /* they asked for stdin reads */
2354 && FD_ISSET (0, &orfds)
2355 /* the stdin handle is valid */
2356 && keyboard_handle)
2357 {
2358 FD_SET (0, rfds);
2359 if (nr == 0)
2360 nr = 1;
2361 }
2362 }
2363 else if (active >= nh)
2364 {
2365 cp = cps[active - nh];
2366
2367 /* We cannot always signal SIGCHLD immediately; if we have not
2368 finished reading the process output, we must delay sending
2369 SIGCHLD until we do. */
2370
2371 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
2372 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
2373 /* SIG_DFL for SIGCHLD is ignored */
2374 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
2375 sig_handlers[SIGCHLD] != SIG_IGN)
2376 {
2377 #ifdef FULL_DEBUG
2378 DebPrint (("select calling SIGCHLD handler for pid %d\n",
2379 cp->pid));
2380 #endif
2381 sig_handlers[SIGCHLD] (SIGCHLD);
2382 }
2383 }
2384 else if (fdindex[active] == -1)
2385 {
2386 /* Quit (C-g) was detected. */
2387 errno = EINTR;
2388 return -1;
2389 }
2390 else if (rfds && fdindex[active] == 0)
2391 {
2392 /* Keyboard input available */
2393 FD_SET (0, rfds);
2394 nr++;
2395 }
2396 else
2397 {
2398 /* Must be a socket or pipe - read ahead should have
2399 completed, either succeeding or failing. If this handle
2400 was waiting for an async 'connect', reset the connect
2401 flag, so it could read from now on. */
2402 if (wfds && (fd_info[fdindex[active]].flags & FILE_CONNECT) != 0)
2403 {
2404 cp = fd_info[fdindex[active]].cp;
2405 if (cp)
2406 {
2407 /* Don't reset the FILE_CONNECT bit and don't
2408 acknowledge the read if the status is
2409 STATUS_CONNECT_FAILED or some other
2410 failure. That's because the thread exits in those
2411 cases, so it doesn't need the ACK, and we want to
2412 keep the FILE_CONNECT bit as evidence that the
2413 connect failed, to be checked in sys_read. */
2414 if (cp->status == STATUS_READ_SUCCEEDED)
2415 {
2416 fd_info[cp->fd].flags &= ~FILE_CONNECT;
2417 cp->status = STATUS_READ_ACKNOWLEDGED;
2418 }
2419 ResetEvent (cp->char_avail);
2420 }
2421 FD_SET (fdindex[active], wfds);
2422 }
2423 else if (rfds)
2424 FD_SET (fdindex[active], rfds);
2425 nr++;
2426 }
2427
2428 /* Even though wait_reading_process_output only reads from at most
2429 one channel, we must process all channels here so that we reap
2430 all children that have died. */
2431 while (++active < nh + nc)
2432 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
2433 break;
2434 } while (active < nh + nc);
2435
2436 if (noninteractive)
2437 {
2438 if (handle_file_notifications (NULL))
2439 nr++;
2440 }
2441
2442 /* If no input has arrived and timeout hasn't expired, wait again. */
2443 if (nr == 0)
2444 {
2445 DWORD elapsed = GetTickCount () - start_time;
2446
2447 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
2448 {
2449 if (timeout_ms != INFINITE)
2450 timeout_ms -= elapsed;
2451 goto count_children;
2452 }
2453 }
2454
2455 return nr;
2456 }
2457
2458 /* Substitute for certain kill () operations */
2459
2460 static BOOL CALLBACK
2461 find_child_console (HWND hwnd, LPARAM arg)
2462 {
2463 child_process * cp = (child_process *) arg;
2464 DWORD process_id;
2465
2466 GetWindowThreadProcessId (hwnd, &process_id);
2467 if (process_id == cp->procinfo.dwProcessId)
2468 {
2469 char window_class[32];
2470
2471 GetClassName (hwnd, window_class, sizeof (window_class));
2472 if (strcmp (window_class,
2473 (os_subtype == OS_9X)
2474 ? "tty"
2475 : "ConsoleWindowClass") == 0)
2476 {
2477 cp->hwnd = hwnd;
2478 return FALSE;
2479 }
2480 }
2481 /* keep looking */
2482 return TRUE;
2483 }
2484
2485 /* Emulate 'kill', but only for other processes. */
2486 int
2487 sys_kill (pid_t pid, int sig)
2488 {
2489 child_process *cp;
2490 HANDLE proc_hand;
2491 int need_to_free = 0;
2492 int rc = 0;
2493
2494 /* Each process is in its own process group. */
2495 if (pid < 0)
2496 pid = -pid;
2497
2498 /* Only handle signals that will result in the process dying */
2499 if (sig != 0
2500 && sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
2501 {
2502 errno = EINVAL;
2503 return -1;
2504 }
2505
2506 if (sig == 0)
2507 {
2508 /* It will take _some_ time before PID 4 or less on Windows will
2509 be Emacs... */
2510 if (pid <= 4)
2511 {
2512 errno = EPERM;
2513 return -1;
2514 }
2515 proc_hand = OpenProcess (PROCESS_QUERY_INFORMATION, 0, pid);
2516 if (proc_hand == NULL)
2517 {
2518 DWORD err = GetLastError ();
2519
2520 switch (err)
2521 {
2522 case ERROR_ACCESS_DENIED: /* existing process, but access denied */
2523 errno = EPERM;
2524 return -1;
2525 case ERROR_INVALID_PARAMETER: /* process PID does not exist */
2526 errno = ESRCH;
2527 return -1;
2528 }
2529 }
2530 else
2531 CloseHandle (proc_hand);
2532 return 0;
2533 }
2534
2535 cp = find_child_pid (pid);
2536 if (cp == NULL)
2537 {
2538 /* We were passed a PID of something other than our subprocess.
2539 If that is our own PID, we will send to ourself a message to
2540 close the selected frame, which does not necessarily
2541 terminates Emacs. But then we are not supposed to call
2542 sys_kill with our own PID. */
2543 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
2544 if (proc_hand == NULL)
2545 {
2546 errno = EPERM;
2547 return -1;
2548 }
2549 need_to_free = 1;
2550 }
2551 else
2552 {
2553 proc_hand = cp->procinfo.hProcess;
2554 pid = cp->procinfo.dwProcessId;
2555
2556 /* Try to locate console window for process. */
2557 EnumWindows (find_child_console, (LPARAM) cp);
2558 }
2559
2560 if (sig == SIGINT || sig == SIGQUIT)
2561 {
2562 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
2563 {
2564 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
2565 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
2566 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
2567 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
2568 HWND foreground_window;
2569
2570 if (break_scan_code == 0)
2571 {
2572 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
2573 vk_break_code = 'C';
2574 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
2575 }
2576
2577 foreground_window = GetForegroundWindow ();
2578 if (foreground_window)
2579 {
2580 /* NT 5.0, and apparently also Windows 98, will not allow
2581 a Window to be set to foreground directly without the
2582 user's involvement. The workaround is to attach
2583 ourselves to the thread that owns the foreground
2584 window, since that is the only thread that can set the
2585 foreground window. */
2586 DWORD foreground_thread, child_thread;
2587 foreground_thread =
2588 GetWindowThreadProcessId (foreground_window, NULL);
2589 if (foreground_thread == GetCurrentThreadId ()
2590 || !AttachThreadInput (GetCurrentThreadId (),
2591 foreground_thread, TRUE))
2592 foreground_thread = 0;
2593
2594 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
2595 if (child_thread == GetCurrentThreadId ()
2596 || !AttachThreadInput (GetCurrentThreadId (),
2597 child_thread, TRUE))
2598 child_thread = 0;
2599
2600 /* Set the foreground window to the child. */
2601 if (SetForegroundWindow (cp->hwnd))
2602 {
2603 /* Generate keystrokes as if user had typed Ctrl-Break or
2604 Ctrl-C. */
2605 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
2606 keybd_event (vk_break_code, break_scan_code,
2607 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
2608 keybd_event (vk_break_code, break_scan_code,
2609 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
2610 | KEYEVENTF_KEYUP, 0);
2611 keybd_event (VK_CONTROL, control_scan_code,
2612 KEYEVENTF_KEYUP, 0);
2613
2614 /* Sleep for a bit to give time for Emacs frame to respond
2615 to focus change events (if Emacs was active app). */
2616 Sleep (100);
2617
2618 SetForegroundWindow (foreground_window);
2619 }
2620 /* Detach from the foreground and child threads now that
2621 the foreground switching is over. */
2622 if (foreground_thread)
2623 AttachThreadInput (GetCurrentThreadId (),
2624 foreground_thread, FALSE);
2625 if (child_thread)
2626 AttachThreadInput (GetCurrentThreadId (),
2627 child_thread, FALSE);
2628 }
2629 }
2630 /* Ctrl-Break is NT equivalent of SIGINT. */
2631 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
2632 {
2633 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
2634 "for pid %lu\n", GetLastError (), pid));
2635 errno = EINVAL;
2636 rc = -1;
2637 }
2638 }
2639 else
2640 {
2641 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
2642 {
2643 #if 1
2644 if (os_subtype == OS_9X)
2645 {
2646 /*
2647 Another possibility is to try terminating the VDM out-right by
2648 calling the Shell VxD (id 0x17) V86 interface, function #4
2649 "SHELL_Destroy_VM", ie.
2650
2651 mov edx,4
2652 mov ebx,vm_handle
2653 call shellapi
2654
2655 First need to determine the current VM handle, and then arrange for
2656 the shellapi call to be made from the system vm (by using
2657 Switch_VM_and_callback).
2658
2659 Could try to invoke DestroyVM through CallVxD.
2660
2661 */
2662 #if 0
2663 /* On Windows 95, posting WM_QUIT causes the 16-bit subsystem
2664 to hang when cmdproxy is used in conjunction with
2665 command.com for an interactive shell. Posting
2666 WM_CLOSE pops up a dialog that, when Yes is selected,
2667 does the same thing. TerminateProcess is also less
2668 than ideal in that subprocesses tend to stick around
2669 until the machine is shutdown, but at least it
2670 doesn't freeze the 16-bit subsystem. */
2671 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
2672 #endif
2673 if (!TerminateProcess (proc_hand, 0xff))
2674 {
2675 DebPrint (("sys_kill.TerminateProcess returned %d "
2676 "for pid %lu\n", GetLastError (), pid));
2677 errno = EINVAL;
2678 rc = -1;
2679 }
2680 }
2681 else
2682 #endif
2683 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
2684 }
2685 /* Kill the process. On W32 this doesn't kill child processes
2686 so it doesn't work very well for shells which is why it's not
2687 used in every case. */
2688 else if (!TerminateProcess (proc_hand, 0xff))
2689 {
2690 DebPrint (("sys_kill.TerminateProcess returned %d "
2691 "for pid %lu\n", GetLastError (), pid));
2692 errno = EINVAL;
2693 rc = -1;
2694 }
2695 }
2696
2697 if (need_to_free)
2698 CloseHandle (proc_hand);
2699
2700 return rc;
2701 }
2702
2703 /* The following two routines are used to manipulate stdin, stdout, and
2704 stderr of our child processes.
2705
2706 Assuming that in, out, and err are *not* inheritable, we make them
2707 stdin, stdout, and stderr of the child as follows:
2708
2709 - Save the parent's current standard handles.
2710 - Set the std handles to inheritable duplicates of the ones being passed in.
2711 (Note that _get_osfhandle() is an io.h procedure that retrieves the
2712 NT file handle for a crt file descriptor.)
2713 - Spawn the child, which inherits in, out, and err as stdin,
2714 stdout, and stderr. (see Spawnve)
2715 - Close the std handles passed to the child.
2716 - Reset the parent's standard handles to the saved handles.
2717 (see reset_standard_handles)
2718 We assume that the caller closes in, out, and err after calling us. */
2719
2720 void
2721 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
2722 {
2723 HANDLE parent;
2724 HANDLE newstdin, newstdout, newstderr;
2725
2726 parent = GetCurrentProcess ();
2727
2728 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
2729 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
2730 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
2731
2732 /* make inheritable copies of the new handles */
2733 if (!DuplicateHandle (parent,
2734 (HANDLE) _get_osfhandle (in),
2735 parent,
2736 &newstdin,
2737 0,
2738 TRUE,
2739 DUPLICATE_SAME_ACCESS))
2740 report_file_error ("Duplicating input handle for child", Qnil);
2741
2742 if (!DuplicateHandle (parent,
2743 (HANDLE) _get_osfhandle (out),
2744 parent,
2745 &newstdout,
2746 0,
2747 TRUE,
2748 DUPLICATE_SAME_ACCESS))
2749 report_file_error ("Duplicating output handle for child", Qnil);
2750
2751 if (!DuplicateHandle (parent,
2752 (HANDLE) _get_osfhandle (err),
2753 parent,
2754 &newstderr,
2755 0,
2756 TRUE,
2757 DUPLICATE_SAME_ACCESS))
2758 report_file_error ("Duplicating error handle for child", Qnil);
2759
2760 /* and store them as our std handles */
2761 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
2762 report_file_error ("Changing stdin handle", Qnil);
2763
2764 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
2765 report_file_error ("Changing stdout handle", Qnil);
2766
2767 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
2768 report_file_error ("Changing stderr handle", Qnil);
2769 }
2770
2771 void
2772 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
2773 {
2774 /* close the duplicated handles passed to the child */
2775 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
2776 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
2777 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
2778
2779 /* now restore parent's saved std handles */
2780 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
2781 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
2782 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
2783 }
2784
2785 void
2786 set_process_dir (char * dir)
2787 {
2788 process_dir = dir;
2789 }
2790
2791 /* To avoid problems with winsock implementations that work over dial-up
2792 connections causing or requiring a connection to exist while Emacs is
2793 running, Emacs no longer automatically loads winsock on startup if it
2794 is present. Instead, it will be loaded when open-network-stream is
2795 first called.
2796
2797 To allow full control over when winsock is loaded, we provide these
2798 two functions to dynamically load and unload winsock. This allows
2799 dial-up users to only be connected when they actually need to use
2800 socket services. */
2801
2802 /* From w32.c */
2803 extern HANDLE winsock_lib;
2804 extern BOOL term_winsock (void);
2805 extern BOOL init_winsock (int load_now);
2806
2807 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
2808 doc: /* Test for presence of the Windows socket library `winsock'.
2809 Returns non-nil if winsock support is present, nil otherwise.
2810
2811 If the optional argument LOAD-NOW is non-nil, the winsock library is
2812 also loaded immediately if not already loaded. If winsock is loaded,
2813 the winsock local hostname is returned (since this may be different from
2814 the value of `system-name' and should supplant it), otherwise t is
2815 returned to indicate winsock support is present. */)
2816 (Lisp_Object load_now)
2817 {
2818 int have_winsock;
2819
2820 have_winsock = init_winsock (!NILP (load_now));
2821 if (have_winsock)
2822 {
2823 if (winsock_lib != NULL)
2824 {
2825 /* Return new value for system-name. The best way to do this
2826 is to call init_system_name, saving and restoring the
2827 original value to avoid side-effects. */
2828 Lisp_Object orig_hostname = Vsystem_name;
2829 Lisp_Object hostname;
2830
2831 init_system_name ();
2832 hostname = Vsystem_name;
2833 Vsystem_name = orig_hostname;
2834 return hostname;
2835 }
2836 return Qt;
2837 }
2838 return Qnil;
2839 }
2840
2841 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
2842 0, 0, 0,
2843 doc: /* Unload the Windows socket library `winsock' if loaded.
2844 This is provided to allow dial-up socket connections to be disconnected
2845 when no longer needed. Returns nil without unloading winsock if any
2846 socket connections still exist. */)
2847 (void)
2848 {
2849 return term_winsock () ? Qt : Qnil;
2850 }
2851
2852 \f
2853 /* Some miscellaneous functions that are Windows specific, but not GUI
2854 specific (ie. are applicable in terminal or batch mode as well). */
2855
2856 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
2857 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
2858 If FILENAME does not exist, return nil.
2859 All path elements in FILENAME are converted to their short names. */)
2860 (Lisp_Object filename)
2861 {
2862 char shortname[MAX_PATH];
2863
2864 CHECK_STRING (filename);
2865
2866 /* first expand it. */
2867 filename = Fexpand_file_name (filename, Qnil);
2868
2869 /* luckily, this returns the short version of each element in the path. */
2870 if (w32_get_short_filename (SDATA (ENCODE_FILE (filename)),
2871 shortname, MAX_PATH) == 0)
2872 return Qnil;
2873
2874 dostounix_filename (shortname);
2875
2876 /* No need to DECODE_FILE, because 8.3 names are pure ASCII. */
2877 return build_string (shortname);
2878 }
2879
2880
2881 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
2882 1, 1, 0,
2883 doc: /* Return the long file name version of the full path of FILENAME.
2884 If FILENAME does not exist, return nil.
2885 All path elements in FILENAME are converted to their long names. */)
2886 (Lisp_Object filename)
2887 {
2888 char longname[ MAX_UTF8_PATH ];
2889 int drive_only = 0;
2890
2891 CHECK_STRING (filename);
2892
2893 if (SBYTES (filename) == 2
2894 && *(SDATA (filename) + 1) == ':')
2895 drive_only = 1;
2896
2897 /* first expand it. */
2898 filename = Fexpand_file_name (filename, Qnil);
2899
2900 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename)), longname,
2901 MAX_UTF8_PATH))
2902 return Qnil;
2903
2904 dostounix_filename (longname);
2905
2906 /* If we were passed only a drive, make sure that a slash is not appended
2907 for consistency with directories. Allow for drive mapping via SUBST
2908 in case expand-file-name is ever changed to expand those. */
2909 if (drive_only && longname[1] == ':' && longname[2] == '/' && !longname[3])
2910 longname[2] = '\0';
2911
2912 return DECODE_FILE (build_unibyte_string (longname));
2913 }
2914
2915 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
2916 Sw32_set_process_priority, 2, 2, 0,
2917 doc: /* Set the priority of PROCESS to PRIORITY.
2918 If PROCESS is nil, the priority of Emacs is changed, otherwise the
2919 priority of the process whose pid is PROCESS is changed.
2920 PRIORITY should be one of the symbols high, normal, or low;
2921 any other symbol will be interpreted as normal.
2922
2923 If successful, the return value is t, otherwise nil. */)
2924 (Lisp_Object process, Lisp_Object priority)
2925 {
2926 HANDLE proc_handle = GetCurrentProcess ();
2927 DWORD priority_class = NORMAL_PRIORITY_CLASS;
2928 Lisp_Object result = Qnil;
2929
2930 CHECK_SYMBOL (priority);
2931
2932 if (!NILP (process))
2933 {
2934 DWORD pid;
2935 child_process *cp;
2936
2937 CHECK_NUMBER (process);
2938
2939 /* Allow pid to be an internally generated one, or one obtained
2940 externally. This is necessary because real pids on Windows 95 are
2941 negative. */
2942
2943 pid = XINT (process);
2944 cp = find_child_pid (pid);
2945 if (cp != NULL)
2946 pid = cp->procinfo.dwProcessId;
2947
2948 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
2949 }
2950
2951 if (EQ (priority, Qhigh))
2952 priority_class = HIGH_PRIORITY_CLASS;
2953 else if (EQ (priority, Qlow))
2954 priority_class = IDLE_PRIORITY_CLASS;
2955
2956 if (proc_handle != NULL)
2957 {
2958 if (SetPriorityClass (proc_handle, priority_class))
2959 result = Qt;
2960 if (!NILP (process))
2961 CloseHandle (proc_handle);
2962 }
2963
2964 return result;
2965 }
2966
2967 DEFUN ("w32-application-type", Fw32_application_type,
2968 Sw32_application_type, 1, 1, 0,
2969 doc: /* Return the type of an MS-Windows PROGRAM.
2970
2971 Knowing the type of an executable could be useful for formatting
2972 file names passed to it or for quoting its command-line arguments.
2973
2974 PROGRAM should specify an executable file, including the extension.
2975
2976 The value is one of the following:
2977
2978 `dos' -- a DOS .com program or some other non-PE executable
2979 `cygwin' -- a Cygwin program that depends on Cygwin DLL
2980 `msys' -- an MSYS 1.x or MSYS2 program
2981 `w32-native' -- a native Windows application
2982 `unknown' -- a file that doesn't exist, or cannot be open, or whose
2983 name is not encodable in the current ANSI codepage.
2984
2985 Note that for .bat and .cmd batch files the function returns the type
2986 of their command interpreter, as specified by the \"COMSPEC\"
2987 environment variable.
2988
2989 This function returns `unknown' for programs whose file names
2990 include characters not supported by the current ANSI codepage, as
2991 such programs cannot be invoked by Emacs anyway. */)
2992 (Lisp_Object program)
2993 {
2994 int is_dos_app, is_cygwin_app, is_msys_app, dummy;
2995 Lisp_Object encoded_progname;
2996 char *progname, progname_a[MAX_PATH];
2997
2998 program = Fexpand_file_name (program, Qnil);
2999 encoded_progname = ENCODE_FILE (program);
3000 progname = SDATA (encoded_progname);
3001 unixtodos_filename (progname);
3002 filename_to_ansi (progname, progname_a);
3003 /* Reject file names that cannot be encoded in the current ANSI
3004 codepage. */
3005 if (_mbspbrk (progname_a, "?"))
3006 return Qunknown;
3007
3008 if (w32_executable_type (progname_a, &is_dos_app, &is_cygwin_app,
3009 &is_msys_app, &dummy) != 0)
3010 return Qunknown;
3011 if (is_dos_app)
3012 return Qdos;
3013 if (is_cygwin_app)
3014 return Qcygwin;
3015 if (is_msys_app)
3016 return Qmsys;
3017 return Qw32_native;
3018 }
3019
3020 #ifdef HAVE_LANGINFO_CODESET
3021 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
3022 char *
3023 nl_langinfo (nl_item item)
3024 {
3025 /* Conversion of Posix item numbers to their Windows equivalents. */
3026 static const LCTYPE w32item[] = {
3027 LOCALE_IDEFAULTANSICODEPAGE,
3028 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
3029 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
3030 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
3031 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
3032 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
3033 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
3034 };
3035
3036 static char *nl_langinfo_buf = NULL;
3037 static int nl_langinfo_len = 0;
3038
3039 if (nl_langinfo_len <= 0)
3040 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
3041
3042 if (item < 0 || item >= _NL_NUM)
3043 nl_langinfo_buf[0] = 0;
3044 else
3045 {
3046 LCID cloc = GetThreadLocale ();
3047 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
3048 NULL, 0);
3049
3050 if (need_len <= 0)
3051 nl_langinfo_buf[0] = 0;
3052 else
3053 {
3054 if (item == CODESET)
3055 {
3056 need_len += 2; /* for the "cp" prefix */
3057 if (need_len < 8) /* for the case we call GetACP */
3058 need_len = 8;
3059 }
3060 if (nl_langinfo_len <= need_len)
3061 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
3062 nl_langinfo_len = need_len);
3063 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
3064 nl_langinfo_buf, nl_langinfo_len))
3065 nl_langinfo_buf[0] = 0;
3066 else if (item == CODESET)
3067 {
3068 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
3069 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
3070 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
3071 else
3072 {
3073 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
3074 strlen (nl_langinfo_buf) + 1);
3075 nl_langinfo_buf[0] = 'c';
3076 nl_langinfo_buf[1] = 'p';
3077 }
3078 }
3079 }
3080 }
3081 return nl_langinfo_buf;
3082 }
3083 #endif /* HAVE_LANGINFO_CODESET */
3084
3085 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
3086 Sw32_get_locale_info, 1, 2, 0,
3087 doc: /* Return information about the Windows locale LCID.
3088 By default, return a three letter locale code which encodes the default
3089 language as the first two characters, and the country or regional variant
3090 as the third letter. For example, ENU refers to `English (United States)',
3091 while ENC means `English (Canadian)'.
3092
3093 If the optional argument LONGFORM is t, the long form of the locale
3094 name is returned, e.g. `English (United States)' instead; if LONGFORM
3095 is a number, it is interpreted as an LCTYPE constant and the corresponding
3096 locale information is returned.
3097
3098 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
3099 (Lisp_Object lcid, Lisp_Object longform)
3100 {
3101 int got_abbrev;
3102 int got_full;
3103 char abbrev_name[32] = { 0 };
3104 char full_name[256] = { 0 };
3105
3106 CHECK_NUMBER (lcid);
3107
3108 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
3109 return Qnil;
3110
3111 if (NILP (longform))
3112 {
3113 got_abbrev = GetLocaleInfo (XINT (lcid),
3114 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
3115 abbrev_name, sizeof (abbrev_name));
3116 if (got_abbrev)
3117 return build_string (abbrev_name);
3118 }
3119 else if (EQ (longform, Qt))
3120 {
3121 got_full = GetLocaleInfo (XINT (lcid),
3122 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
3123 full_name, sizeof (full_name));
3124 if (got_full)
3125 return DECODE_SYSTEM (build_string (full_name));
3126 }
3127 else if (NUMBERP (longform))
3128 {
3129 got_full = GetLocaleInfo (XINT (lcid),
3130 XINT (longform),
3131 full_name, sizeof (full_name));
3132 /* GetLocaleInfo's return value includes the terminating null
3133 character, when the returned information is a string, whereas
3134 make_unibyte_string needs the string length without the
3135 terminating null. */
3136 if (got_full)
3137 return make_unibyte_string (full_name, got_full - 1);
3138 }
3139
3140 return Qnil;
3141 }
3142
3143
3144 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
3145 Sw32_get_current_locale_id, 0, 0, 0,
3146 doc: /* Return Windows locale id for current locale setting.
3147 This is a numerical value; use `w32-get-locale-info' to convert to a
3148 human-readable form. */)
3149 (void)
3150 {
3151 return make_number (GetThreadLocale ());
3152 }
3153
3154 static DWORD
3155 int_from_hex (char * s)
3156 {
3157 DWORD val = 0;
3158 static char hex[] = "0123456789abcdefABCDEF";
3159 char * p;
3160
3161 while (*s && (p = strchr (hex, *s)) != NULL)
3162 {
3163 unsigned digit = p - hex;
3164 if (digit > 15)
3165 digit -= 6;
3166 val = val * 16 + digit;
3167 s++;
3168 }
3169 return val;
3170 }
3171
3172 /* We need to build a global list, since the EnumSystemLocale callback
3173 function isn't given a context pointer. */
3174 Lisp_Object Vw32_valid_locale_ids;
3175
3176 static BOOL CALLBACK ALIGN_STACK
3177 enum_locale_fn (LPTSTR localeNum)
3178 {
3179 DWORD id = int_from_hex (localeNum);
3180 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
3181 return TRUE;
3182 }
3183
3184 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
3185 Sw32_get_valid_locale_ids, 0, 0, 0,
3186 doc: /* Return list of all valid Windows locale ids.
3187 Each id is a numerical value; use `w32-get-locale-info' to convert to a
3188 human-readable form. */)
3189 (void)
3190 {
3191 Vw32_valid_locale_ids = Qnil;
3192
3193 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
3194
3195 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
3196 return Vw32_valid_locale_ids;
3197 }
3198
3199
3200 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
3201 doc: /* Return Windows locale id for default locale setting.
3202 By default, the system default locale setting is returned; if the optional
3203 parameter USERP is non-nil, the user default locale setting is returned.
3204 This is a numerical value; use `w32-get-locale-info' to convert to a
3205 human-readable form. */)
3206 (Lisp_Object userp)
3207 {
3208 if (NILP (userp))
3209 return make_number (GetSystemDefaultLCID ());
3210 return make_number (GetUserDefaultLCID ());
3211 }
3212
3213
3214 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
3215 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
3216 If successful, the new locale id is returned, otherwise nil. */)
3217 (Lisp_Object lcid)
3218 {
3219 CHECK_NUMBER (lcid);
3220
3221 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
3222 return Qnil;
3223
3224 if (!SetThreadLocale (XINT (lcid)))
3225 return Qnil;
3226
3227 /* Need to set input thread locale if present. */
3228 if (dwWindowsThreadId)
3229 /* Reply is not needed. */
3230 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
3231
3232 return make_number (GetThreadLocale ());
3233 }
3234
3235
3236 /* We need to build a global list, since the EnumCodePages callback
3237 function isn't given a context pointer. */
3238 Lisp_Object Vw32_valid_codepages;
3239
3240 static BOOL CALLBACK ALIGN_STACK
3241 enum_codepage_fn (LPTSTR codepageNum)
3242 {
3243 DWORD id = atoi (codepageNum);
3244 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
3245 return TRUE;
3246 }
3247
3248 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
3249 Sw32_get_valid_codepages, 0, 0, 0,
3250 doc: /* Return list of all valid Windows codepages. */)
3251 (void)
3252 {
3253 Vw32_valid_codepages = Qnil;
3254
3255 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
3256
3257 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
3258 return Vw32_valid_codepages;
3259 }
3260
3261
3262 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
3263 Sw32_get_console_codepage, 0, 0, 0,
3264 doc: /* Return current Windows codepage for console input. */)
3265 (void)
3266 {
3267 return make_number (GetConsoleCP ());
3268 }
3269
3270
3271 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
3272 Sw32_set_console_codepage, 1, 1, 0,
3273 doc: /* Make Windows codepage CP be the codepage for Emacs tty keyboard input.
3274 This codepage setting affects keyboard input in tty mode.
3275 If successful, the new CP is returned, otherwise nil. */)
3276 (Lisp_Object cp)
3277 {
3278 CHECK_NUMBER (cp);
3279
3280 if (!IsValidCodePage (XINT (cp)))
3281 return Qnil;
3282
3283 if (!SetConsoleCP (XINT (cp)))
3284 return Qnil;
3285
3286 return make_number (GetConsoleCP ());
3287 }
3288
3289
3290 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
3291 Sw32_get_console_output_codepage, 0, 0, 0,
3292 doc: /* Return current Windows codepage for console output. */)
3293 (void)
3294 {
3295 return make_number (GetConsoleOutputCP ());
3296 }
3297
3298
3299 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
3300 Sw32_set_console_output_codepage, 1, 1, 0,
3301 doc: /* Make Windows codepage CP be the codepage for Emacs console output.
3302 This codepage setting affects display in tty mode.
3303 If successful, the new CP is returned, otherwise nil. */)
3304 (Lisp_Object cp)
3305 {
3306 CHECK_NUMBER (cp);
3307
3308 if (!IsValidCodePage (XINT (cp)))
3309 return Qnil;
3310
3311 if (!SetConsoleOutputCP (XINT (cp)))
3312 return Qnil;
3313
3314 return make_number (GetConsoleOutputCP ());
3315 }
3316
3317
3318 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
3319 Sw32_get_codepage_charset, 1, 1, 0,
3320 doc: /* Return charset ID corresponding to codepage CP.
3321 Returns nil if the codepage is not valid or its charset ID could
3322 not be determined.
3323
3324 Note that this function is only guaranteed to work with ANSI
3325 codepages; most console codepages are not supported and will
3326 yield nil. */)
3327 (Lisp_Object cp)
3328 {
3329 CHARSETINFO info;
3330 DWORD_PTR dwcp;
3331
3332 CHECK_NUMBER (cp);
3333
3334 if (!IsValidCodePage (XINT (cp)))
3335 return Qnil;
3336
3337 /* Going through a temporary DWORD_PTR variable avoids compiler warning
3338 about cast to pointer from integer of different size, when
3339 building --with-wide-int or building for 64bit. */
3340 dwcp = XINT (cp);
3341 if (TranslateCharsetInfo ((DWORD *) dwcp, &info, TCI_SRCCODEPAGE))
3342 return make_number (info.ciCharset);
3343
3344 return Qnil;
3345 }
3346
3347
3348 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
3349 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
3350 doc: /* Return list of Windows keyboard languages and layouts.
3351 The return value is a list of pairs of language id and layout id. */)
3352 (void)
3353 {
3354 int num_layouts = GetKeyboardLayoutList (0, NULL);
3355 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
3356 Lisp_Object obj = Qnil;
3357
3358 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
3359 {
3360 while (--num_layouts >= 0)
3361 {
3362 HKL kl = layouts[num_layouts];
3363
3364 obj = Fcons (Fcons (make_number (LOWORD (kl)),
3365 make_number (HIWORD (kl))),
3366 obj);
3367 }
3368 }
3369
3370 return obj;
3371 }
3372
3373
3374 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
3375 Sw32_get_keyboard_layout, 0, 0, 0,
3376 doc: /* Return current Windows keyboard language and layout.
3377 The return value is the cons of the language id and the layout id. */)
3378 (void)
3379 {
3380 HKL kl = GetKeyboardLayout (dwWindowsThreadId);
3381
3382 return Fcons (make_number (LOWORD (kl)),
3383 make_number (HIWORD (kl)));
3384 }
3385
3386
3387 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
3388 Sw32_set_keyboard_layout, 1, 1, 0,
3389 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
3390 The keyboard layout setting affects interpretation of keyboard input.
3391 If successful, the new layout id is returned, otherwise nil. */)
3392 (Lisp_Object layout)
3393 {
3394 HKL kl;
3395
3396 CHECK_CONS (layout);
3397 CHECK_NUMBER_CAR (layout);
3398 CHECK_NUMBER_CDR (layout);
3399
3400 kl = (HKL) (UINT_PTR) ((XINT (XCAR (layout)) & 0xffff)
3401 | (XINT (XCDR (layout)) << 16));
3402
3403 /* Synchronize layout with input thread. */
3404 if (dwWindowsThreadId)
3405 {
3406 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
3407 (WPARAM) kl, 0))
3408 {
3409 MSG msg;
3410 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
3411
3412 if (msg.wParam == 0)
3413 return Qnil;
3414 }
3415 }
3416 else if (!ActivateKeyboardLayout (kl, 0))
3417 return Qnil;
3418
3419 return Fw32_get_keyboard_layout ();
3420 }
3421
3422 /* Two variables to interface between get_lcid and the EnumLocales
3423 callback function below. */
3424 #ifndef LOCALE_NAME_MAX_LENGTH
3425 # define LOCALE_NAME_MAX_LENGTH 85
3426 #endif
3427 static LCID found_lcid;
3428 static char lname[3 * LOCALE_NAME_MAX_LENGTH + 1 + 1];
3429
3430 /* Callback function for EnumLocales. */
3431 static BOOL CALLBACK
3432 get_lcid_callback (LPTSTR locale_num_str)
3433 {
3434 char *endp;
3435 char locval[2 * LOCALE_NAME_MAX_LENGTH + 1 + 1];
3436 LCID try_lcid = strtoul (locale_num_str, &endp, 16);
3437
3438 if (GetLocaleInfo (try_lcid, LOCALE_SABBREVLANGNAME,
3439 locval, LOCALE_NAME_MAX_LENGTH))
3440 {
3441 size_t locval_len;
3442
3443 /* This is for when they only specify the language, as in "ENU". */
3444 if (stricmp (locval, lname) == 0)
3445 {
3446 found_lcid = try_lcid;
3447 return FALSE;
3448 }
3449 locval_len = strlen (locval);
3450 strcpy (locval + locval_len, "_");
3451 if (GetLocaleInfo (try_lcid, LOCALE_SABBREVCTRYNAME,
3452 locval + locval_len + 1, LOCALE_NAME_MAX_LENGTH))
3453 {
3454 locval_len = strlen (locval);
3455 if (strnicmp (locval, lname, locval_len) == 0
3456 && (lname[locval_len] == '.'
3457 || lname[locval_len] == '\0'))
3458 {
3459 found_lcid = try_lcid;
3460 return FALSE;
3461 }
3462 }
3463 }
3464 return TRUE;
3465 }
3466
3467 /* Return the Locale ID (LCID) number given the locale's name, a
3468 string, in LOCALE_NAME. This works by enumerating all the locales
3469 supported by the system, until we find one whose name matches
3470 LOCALE_NAME. */
3471 static LCID
3472 get_lcid (const char *locale_name)
3473 {
3474 /* A simple cache. */
3475 static LCID last_lcid;
3476 static char last_locale[1000];
3477
3478 /* The code below is not thread-safe, as it uses static variables.
3479 But this function is called only from the Lisp thread. */
3480 if (last_lcid > 0 && strcmp (locale_name, last_locale) == 0)
3481 return last_lcid;
3482
3483 strncpy (lname, locale_name, sizeof (lname) - 1);
3484 lname[sizeof (lname) - 1] = '\0';
3485 found_lcid = 0;
3486 EnumSystemLocales (get_lcid_callback, LCID_SUPPORTED);
3487 if (found_lcid > 0)
3488 {
3489 last_lcid = found_lcid;
3490 strcpy (last_locale, locale_name);
3491 }
3492 return found_lcid;
3493 }
3494
3495 #ifndef _NSLCMPERROR
3496 # define _NSLCMPERROR INT_MAX
3497 #endif
3498 #ifndef LINGUISTIC_IGNORECASE
3499 # define LINGUISTIC_IGNORECASE 0x00000010
3500 #endif
3501
3502 typedef int (WINAPI *CompareStringW_Proc)
3503 (LCID, DWORD, LPCWSTR, int, LPCWSTR, int);
3504
3505 int
3506 w32_compare_strings (const char *s1, const char *s2, char *locname,
3507 int ignore_case)
3508 {
3509 LCID lcid = GetThreadLocale ();
3510 wchar_t *string1_w, *string2_w;
3511 int val, needed;
3512 extern BOOL g_b_init_compare_string_w;
3513 static CompareStringW_Proc pCompareStringW;
3514 DWORD flags = 0;
3515
3516 USE_SAFE_ALLOCA;
3517
3518 /* The LCID machinery doesn't seem to support the "C" locale, so we
3519 need to do that by hand. */
3520 if (locname
3521 && ((locname[0] == 'C' && (locname[1] == '\0' || locname[1] == '.'))
3522 || strcmp (locname, "POSIX") == 0))
3523 return (ignore_case ? stricmp (s1, s2) : strcmp (s1, s2));
3524
3525 if (!g_b_init_compare_string_w)
3526 {
3527 if (os_subtype == OS_9X)
3528 {
3529 pCompareStringW =
3530 (CompareStringW_Proc) GetProcAddress (LoadLibrary ("Unicows.dll"),
3531 "CompareStringW");
3532 if (!pCompareStringW)
3533 {
3534 errno = EINVAL;
3535 /* This return value is compatible with wcscoll and
3536 other MS CRT functions. */
3537 return _NSLCMPERROR;
3538 }
3539 }
3540 else
3541 pCompareStringW = CompareStringW;
3542
3543 g_b_init_compare_string_w = 1;
3544 }
3545
3546 needed = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, s1, -1, NULL, 0);
3547 if (needed > 0)
3548 {
3549 SAFE_NALLOCA (string1_w, 1, needed + 1);
3550 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, s1, -1,
3551 string1_w, needed);
3552 }
3553 else
3554 {
3555 errno = EINVAL;
3556 return _NSLCMPERROR;
3557 }
3558
3559 needed = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, s2, -1, NULL, 0);
3560 if (needed > 0)
3561 {
3562 SAFE_NALLOCA (string2_w, 1, needed + 1);
3563 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, s2, -1,
3564 string2_w, needed);
3565 }
3566 else
3567 {
3568 SAFE_FREE ();
3569 errno = EINVAL;
3570 return _NSLCMPERROR;
3571 }
3572
3573 if (locname)
3574 {
3575 /* Convert locale name string to LCID. We don't want to use
3576 LocaleNameToLCID because (a) it is only available since
3577 Vista, and (b) it doesn't accept locale names returned by
3578 'setlocale' and 'GetLocaleInfo'. */
3579 LCID new_lcid = get_lcid (locname);
3580
3581 if (new_lcid > 0)
3582 lcid = new_lcid;
3583 else
3584 error ("Invalid locale %s: Invalid argument", locname);
3585 }
3586
3587 if (ignore_case)
3588 {
3589 /* NORM_IGNORECASE ignores any tertiary distinction, not just
3590 case variants. LINGUISTIC_IGNORECASE is more selective, and
3591 is sensitive to the locale's language, but it is not
3592 available before Vista. */
3593 if (w32_major_version >= 6)
3594 flags |= LINGUISTIC_IGNORECASE;
3595 else
3596 flags |= NORM_IGNORECASE;
3597 }
3598 /* This approximates what glibc collation functions do when the
3599 locale's codeset is UTF-8. */
3600 if (!NILP (Vw32_collate_ignore_punctuation))
3601 flags |= NORM_IGNORESYMBOLS;
3602 val = pCompareStringW (lcid, flags, string1_w, -1, string2_w, -1);
3603 SAFE_FREE ();
3604 if (!val)
3605 {
3606 errno = EINVAL;
3607 return _NSLCMPERROR;
3608 }
3609 return val - 2;
3610 }
3611
3612 \f
3613 void
3614 syms_of_ntproc (void)
3615 {
3616 DEFSYM (Qhigh, "high");
3617 DEFSYM (Qlow, "low");
3618 DEFSYM (Qcygwin, "cygwin");
3619 DEFSYM (Qmsys, "msys");
3620 DEFSYM (Qw32_native, "w32-native");
3621
3622 defsubr (&Sw32_has_winsock);
3623 defsubr (&Sw32_unload_winsock);
3624
3625 defsubr (&Sw32_short_file_name);
3626 defsubr (&Sw32_long_file_name);
3627 defsubr (&Sw32_set_process_priority);
3628 defsubr (&Sw32_application_type);
3629 defsubr (&Sw32_get_locale_info);
3630 defsubr (&Sw32_get_current_locale_id);
3631 defsubr (&Sw32_get_default_locale_id);
3632 defsubr (&Sw32_get_valid_locale_ids);
3633 defsubr (&Sw32_set_current_locale);
3634
3635 defsubr (&Sw32_get_console_codepage);
3636 defsubr (&Sw32_set_console_codepage);
3637 defsubr (&Sw32_get_console_output_codepage);
3638 defsubr (&Sw32_set_console_output_codepage);
3639 defsubr (&Sw32_get_valid_codepages);
3640 defsubr (&Sw32_get_codepage_charset);
3641
3642 defsubr (&Sw32_get_valid_keyboard_layouts);
3643 defsubr (&Sw32_get_keyboard_layout);
3644 defsubr (&Sw32_set_keyboard_layout);
3645
3646 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args,
3647 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
3648 Because Windows does not directly pass argv arrays to child processes,
3649 programs have to reconstruct the argv array by parsing the command
3650 line string. For an argument to contain a space, it must be enclosed
3651 in double quotes or it will be parsed as multiple arguments.
3652
3653 If the value is a character, that character will be used to escape any
3654 quote characters that appear, otherwise a suitable escape character
3655 will be chosen based on the type of the program. */);
3656 Vw32_quote_process_args = Qt;
3657
3658 DEFVAR_LISP ("w32-start-process-show-window",
3659 Vw32_start_process_show_window,
3660 doc: /* When nil, new child processes hide their windows.
3661 When non-nil, they show their window in the method of their choice.
3662 This variable doesn't affect GUI applications, which will never be hidden. */);
3663 Vw32_start_process_show_window = Qnil;
3664
3665 DEFVAR_LISP ("w32-start-process-share-console",
3666 Vw32_start_process_share_console,
3667 doc: /* When nil, new child processes are given a new console.
3668 When non-nil, they share the Emacs console; this has the limitation of
3669 allowing only one DOS subprocess to run at a time (whether started directly
3670 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
3671 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
3672 otherwise respond to interrupts from Emacs. */);
3673 Vw32_start_process_share_console = Qnil;
3674
3675 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
3676 Vw32_start_process_inherit_error_mode,
3677 doc: /* When nil, new child processes revert to the default error mode.
3678 When non-nil, they inherit their error mode setting from Emacs, which stops
3679 them blocking when trying to access unmounted drives etc. */);
3680 Vw32_start_process_inherit_error_mode = Qt;
3681
3682 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay,
3683 doc: /* Forced delay before reading subprocess output.
3684 This is done to improve the buffering of subprocess output, by
3685 avoiding the inefficiency of frequently reading small amounts of data.
3686
3687 If positive, the value is the number of milliseconds to sleep before
3688 reading the subprocess output. If negative, the magnitude is the number
3689 of time slices to wait (effectively boosting the priority of the child
3690 process temporarily). A value of zero disables waiting entirely. */);
3691 w32_pipe_read_delay = 50;
3692
3693 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names,
3694 doc: /* Non-nil means convert all-upper case file names to lower case.
3695 This applies when performing completions and file name expansion.
3696 Note that the value of this setting also affects remote file names,
3697 so you probably don't want to set to non-nil if you use case-sensitive
3698 filesystems via ange-ftp. */);
3699 Vw32_downcase_file_names = Qnil;
3700
3701 #if 0
3702 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes,
3703 doc: /* Non-nil means attempt to fake realistic inode values.
3704 This works by hashing the truename of files, and should detect
3705 aliasing between long and short (8.3 DOS) names, but can have
3706 false positives because of hash collisions. Note that determining
3707 the truename of a file can be slow. */);
3708 Vw32_generate_fake_inodes = Qnil;
3709 #endif
3710
3711 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes,
3712 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
3713 This option controls whether to issue additional system calls to determine
3714 accurate link counts, file type, and ownership information. It is more
3715 useful for files on NTFS volumes, where hard links and file security are
3716 supported, than on volumes of the FAT family.
3717
3718 Without these system calls, link count will always be reported as 1 and file
3719 ownership will be attributed to the current user.
3720 The default value `local' means only issue these system calls for files
3721 on local fixed drives. A value of nil means never issue them.
3722 Any other non-nil value means do this even on remote and removable drives
3723 where the performance impact may be noticeable even on modern hardware. */);
3724 Vw32_get_true_file_attributes = Qlocal;
3725
3726 DEFVAR_LISP ("w32-collate-ignore-punctuation",
3727 Vw32_collate_ignore_punctuation,
3728 doc: /* Non-nil causes string collation functions ignore punctuation on MS-Windows.
3729 On Posix platforms, `string-collate-lessp' and `string-collate-equalp'
3730 ignore punctuation characters when they compare strings, if the
3731 locale's codeset is UTF-8, as in \"en_US.UTF-8\". Binding this option
3732 to a non-nil value will achieve a similar effect on MS-Windows, where
3733 locales with UTF-8 codeset are not supported.
3734
3735 Note that setting this to non-nil will also ignore blanks and symbols
3736 in the strings. So do NOT use this option when comparing file names
3737 for equality, only when you need to sort them. */);
3738 Vw32_collate_ignore_punctuation = Qnil;
3739
3740 staticpro (&Vw32_valid_locale_ids);
3741 staticpro (&Vw32_valid_codepages);
3742 }
3743 /* end of w32proc.c */