Support atimers and CPU profiler via profile.c on MS-Windows.
[bpt/emacs.git] / src / w32proc.c
CommitLineData
b46a6a83 1/* Process support for GNU Emacs on the Microsoft Windows API.
acaf905b 2 Copyright (C) 1992, 1995, 1999-2012 Free Software Foundation, Inc.
6cdfb6e6 3
3b7ad313
EN
4This file is part of GNU Emacs.
5
9ec0b715 6GNU Emacs is free software: you can redistribute it and/or modify
3b7ad313 7it under the terms of the GNU General Public License as published by
9ec0b715
GM
8the Free Software Foundation, either version 3 of the License, or
9(at your option) any later version.
3b7ad313
EN
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
9ec0b715 17along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
6cdfb6e6 18
9ec0b715 19/*
6cdfb6e6
RS
20 Drew Bliss Oct 14, 1993
21 Adapted from alarm.c by Tim Fleehart
22*/
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <errno.h>
27#include <io.h>
c519b5e1 28#include <fcntl.h>
6cdfb6e6 29#include <signal.h>
51f635c4 30#include <sys/file.h>
6cdfb6e6 31
c519b5e1 32/* must include CRT headers *before* config.h */
4838e624 33#include <config.h>
4838e624 34
c519b5e1
GV
35#undef signal
36#undef wait
37#undef spawnve
38#undef select
39#undef kill
40
6cdfb6e6 41#include <windows.h>
42c95ffb
AI
42#ifdef __GNUC__
43/* This definition is missing from mingw32 headers. */
ed3751c8 44extern BOOL WINAPI IsValidLocale (LCID, DWORD);
42c95ffb 45#endif
6cdfb6e6 46
d613418b
EZ
47#ifdef HAVE_LANGINFO_CODESET
48#include <nl_types.h>
49#include <langinfo.h>
50#endif
51
6cdfb6e6 52#include "lisp.h"
489f9371 53#include "w32.h"
b2fc9f3d 54#include "w32heap.h"
6cdfb6e6 55#include "systime.h"
3d7eead0
GV
56#include "syswait.h"
57#include "process.h"
e7c15bba 58#include "syssignal.h"
ef79fbba 59#include "w32term.h"
f481eb31 60#include "dispextern.h" /* for xstrcasecmp */
b23077df 61#include "coding.h"
3d7eead0 62
8747ac3f
EZ
63#define RVA_TO_PTR(var,section,filedata) \
64 ((void *)((section)->PointerToRawData \
65 + ((DWORD)(var) - (section)->VirtualAddress) \
66 + (filedata).file_base))
67
b2fc9f3d 68Lisp_Object Qhigh, Qlow;
817abdf6 69
6cdfb6e6 70#ifdef EMACSDEBUG
b56ceb92
JB
71void
72_DebPrint (const char *fmt, ...)
6cdfb6e6 73{
c519b5e1 74 char buf[1024];
6cdfb6e6
RS
75 va_list args;
76
77 va_start (args, fmt);
78 vsprintf (buf, fmt, args);
79 va_end (args);
80 OutputDebugString (buf);
81}
82#endif
83
ed3751c8 84typedef void (_CALLBACK_ *signal_handler) (int);
6cdfb6e6
RS
85
86/* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
87static signal_handler sig_handlers[NSIG];
88
c06c382a
EZ
89static sigset_t sig_mask;
90
91static CRITICAL_SECTION crit_sig;
92
16b22fef 93/* Improve on the CRT 'signal' implementation so that we could record
c06c382a 94 the SIGCHLD handler and fake interval timers. */
177c0ea7 95signal_handler
c519b5e1 96sys_signal (int sig, signal_handler handler)
6cdfb6e6
RS
97{
98 signal_handler old;
177c0ea7 99
16b22fef 100 /* SIGCHLD is needed for supporting subprocesses, see sys_kill
c06c382a
EZ
101 below. SIGALRM and SIGPROF are used by setitimer. All the
102 others are the only ones supported by the MS runtime. */
16b22fef 103 if (!(sig == SIGCHLD || sig == SIGSEGV || sig == SIGILL
c06c382a
EZ
104 || sig == SIGFPE || sig == SIGABRT || sig == SIGTERM
105 || sig == SIGALRM || sig == SIGPROF))
6cdfb6e6
RS
106 {
107 errno = EINVAL;
108 return SIG_ERR;
109 }
110 old = sig_handlers[sig];
16b22fef
EZ
111 /* SIGABRT is treated specially because w32.c installs term_ntproc
112 as its handler, so we don't want to override that afterwards.
113 Aborting Emacs works specially anyway: either by calling
114 emacs_abort directly or through terminate_due_to_signal, which
115 calls emacs_abort through emacs_raise. */
116 if (!(sig == SIGABRT && old == term_ntproc))
117 {
118 sig_handlers[sig] = handler;
c06c382a 119 if (!(sig == SIGCHLD || sig == SIGALRM || sig == SIGPROF))
16b22fef
EZ
120 signal (sig, handler);
121 }
6cdfb6e6
RS
122 return old;
123}
124
3e6d6928
EZ
125/* Emulate sigaction. */
126int
127sigaction (int sig, const struct sigaction *act, struct sigaction *oact)
128{
16b22fef
EZ
129 signal_handler old = SIG_DFL;
130 int retval = 0;
131
132 if (act)
133 old = sys_signal (sig, act->sa_handler);
134 else if (oact)
135 old = sig_handlers[sig];
3e6d6928 136
16b22fef 137 if (old == SIG_ERR)
3e6d6928
EZ
138 {
139 errno = EINVAL;
16b22fef 140 retval = -1;
3e6d6928 141 }
3e6d6928
EZ
142 if (oact)
143 {
144 oact->sa_handler = old;
145 oact->sa_flags = 0;
146 oact->sa_mask = empty_mask;
147 }
16b22fef 148 return retval;
3e6d6928
EZ
149}
150
c06c382a
EZ
151/* Emulate signal sets and blocking of signals used by timers. */
152
153int
154sigemptyset (sigset_t *set)
155{
156 *set = 0;
157 return 0;
158}
159
160int
161sigaddset (sigset_t *set, int signo)
162{
163 if (!set)
164 {
165 errno = EINVAL;
166 return -1;
167 }
168 if (signo < 0 || signo >= NSIG)
169 {
170 errno = EINVAL;
171 return -1;
172 }
173
174 *set |= (1U << signo);
175
176 return 0;
177}
178
179int
180sigfillset (sigset_t *set)
181{
182 if (!set)
183 {
184 errno = EINVAL;
185 return -1;
186 }
187
188 *set = 0xFFFFFFFF;
189 return 0;
190}
191
192int
193sigprocmask (int how, const sigset_t *set, sigset_t *oset)
194{
195 if (!(how == SIG_BLOCK || how == SIG_UNBLOCK || how == SIG_SETMASK))
196 {
197 errno = EINVAL;
198 return -1;
199 }
200
201 if (oset)
202 *oset = sig_mask;
203
204 if (!set)
205 return 0;
206
207 switch (how)
208 {
209 case SIG_BLOCK:
210 sig_mask |= *set;
211 break;
212 case SIG_SETMASK:
213 sig_mask = *set;
214 break;
215 case SIG_UNBLOCK:
216 /* FIXME: Catch signals that are blocked and reissue them when
217 they are unblocked. Important for SIGALRM and SIGPROF only. */
218 sig_mask &= ~(*set);
219 break;
220 }
221
222 return 0;
223}
224
225int
226pthread_sigmask (int how, const sigset_t *set, sigset_t *oset)
227{
228 if (sigprocmask (how, set, oset) == -1)
229 return EINVAL;
230 return 0;
231}
232
233int
234sigismember (const sigset_t *set, int signo)
235{
236 if (signo < 0 || signo >= NSIG)
237 {
238 errno = EINVAL;
239 return -1;
240 }
241 if (signo > sizeof (*set) * BITS_PER_CHAR)
242 emacs_abort ();
243
244 return (*set & (1U << signo)) != 0;
245}
246
247int
248setpgrp (int pid, int gid)
249{
250 return 0;
251}
252
253/* Emulations of interval timers.
254
255 Limitations: only ITIMER_REAL and ITIMER_PROF are supported.
256
257 Implementation: a separate thread is started for each timer type,
258 the thread calls the appropriate signal handler when the timer
259 expires, after stopping the thread which installed the timer. */
260
261/* FIXME: clock_t counts overflow after 49 days, need to handle the
262 wrap-around. */
263struct itimer_data {
264 clock_t expire;
265 clock_t reload;
266 int terminate;
267 int type;
268 HANDLE caller_thread;
269 HANDLE timer_thread;
270};
271
272static clock_t ticks_now;
273static struct itimer_data real_itimer, prof_itimer;
274static clock_t clocks_min;
275
276static CRITICAL_SECTION crit_real, crit_prof;
277
278#define MAX_SINGLE_SLEEP 30
279
280static DWORD WINAPI
281timer_loop (LPVOID arg)
282{
283 struct itimer_data *itimer = (struct itimer_data *)arg;
284 int which = itimer->type;
285 int sig = (which == ITIMER_REAL) ? SIGALRM : SIGPROF;
286 CRITICAL_SECTION *crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
287 const DWORD max_sleep = MAX_SINGLE_SLEEP * 1000 / CLOCKS_PER_SEC;
288 int new_count = 0;
289
290 while (1)
291 {
292 DWORD sleep_time;
293 signal_handler handler;
294 clock_t now, expire, reload;
295
296 /* Load new values if requested by setitimer. */
297 EnterCriticalSection (crit);
298 expire = itimer->expire;
299 reload = itimer->reload;
300 LeaveCriticalSection (crit);
301 if (itimer->terminate)
302 return 0;
303
304 if (itimer->expire == 0)
305 {
306 /* We are idle. */
307 Sleep (max_sleep);
308 continue;
309 }
310
311 expire = itimer->expire;
312 if (expire > (now = clock ()))
313 sleep_time = expire - now;
314 else
315 sleep_time = 0;
316 /* Don't sleep too long at a time, to be able to see the
317 termination flag without too long a delay. */
318 while (sleep_time > max_sleep)
319 {
320 if (itimer->terminate)
321 return 0;
322 Sleep (max_sleep);
323 expire = itimer->expire;
324 sleep_time = (expire > (now = clock ())) ? expire - now : 0;
325 }
326 if (itimer->terminate)
327 return 0;
328 if (sleep_time > 0)
329 {
330 Sleep (sleep_time * 1000 / CLOCKS_PER_SEC);
331 /* Always sleep past the expiration time, to make sure we
332 never call the handler _before_ the expiration time,
333 always slightly after it. Sleep(0) relinquishes the rest
334 of the scheduled slot, so that we let other threads
335 work. */
336 while (clock () < expire)
337 Sleep (0);
338 }
339
340 if (itimer->expire == 0)
341 continue;
342
343 /* Time's up. */
344 handler = sig_handlers[sig];
345 if (!(handler == SIG_DFL || handler == SIG_IGN || handler == SIG_ERR)
346 /* FIXME: Don't ignore masked signals. Instead, record that
347 they happened and reissue them when the signal is
348 unblocked. */
349 && !sigismember (&sig_mask, sig)
350 /* Simulate masking of SIGALRM and SIGPROF when processing
351 fatal signals. */
352 && !fatal_error_in_progress
353 && itimer->caller_thread)
354 {
355 /* Simulate a signal delivered to the thread which installed
356 the timer, by suspending that thread while the handler
357 runs. */
358 DWORD result = SuspendThread (itimer->caller_thread);
359
360 if (result == (DWORD)-1)
361 {
362 DebPrint (("Thread %d exiting with status 2\n", which));
363 return 2;
364 }
365 handler (sig);
366 ResumeThread (itimer->caller_thread);
367 }
368
369 if (itimer->expire == 0)
370 continue;
371
372 /* Update expiration time and loop. */
373 EnterCriticalSection (crit);
374 expire = itimer->expire;
375 reload = itimer->reload;
376 if (reload > 0)
377 {
378 now = clock ();
379 if (expire <= now)
380 {
381 clock_t lag = now - expire;
382
383 /* If we missed some opportunities (presumably while
384 sleeping or while the signal handler ran), skip
385 them. */
386 if (lag > reload)
387 expire = now - (lag % reload);
388
389 expire += reload;
390 }
391 }
392 else
393 expire = 0; /* become idle */
394 itimer->expire = expire;
395 LeaveCriticalSection (crit);
396 }
397 return 0;
398}
399
400static void
401stop_timer_thread (int which)
402{
403 struct itimer_data *itimer =
404 (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;
405 int i;
406 DWORD exit_code = 255;
407 BOOL status, err;
408
409 /* Signal the thread that it should terminate. */
410 itimer->terminate = 1;
411
412 if (itimer->timer_thread == NULL)
413 return;
414
415 /* Wait for the timer thread to terminate voluntarily, then kill it
416 if it doesn't. This loop waits twice more than the maximum
417 amount of time a timer thread sleeps, see above. */
418 for (i = 0; i < MAX_SINGLE_SLEEP / 5; i++)
419 {
420 if (!((status = GetExitCodeThread (itimer->timer_thread, &exit_code))
421 && exit_code == STILL_ACTIVE))
422 break;
423 Sleep (10);
424 }
425 if ((status == FALSE && (err = GetLastError ()) == ERROR_INVALID_HANDLE)
426 || exit_code == STILL_ACTIVE)
427 {
428 if (!(status == FALSE && err == ERROR_INVALID_HANDLE))
429 TerminateThread (itimer->timer_thread, 0);
430 }
431
432 /* Clean up. */
433 CloseHandle (itimer->timer_thread);
434 itimer->timer_thread = NULL;
435 if (itimer->caller_thread)
436 {
437 CloseHandle (itimer->caller_thread);
438 itimer->caller_thread = NULL;
439 }
440}
441
442/* This is called at shutdown time from term_ntproc. */
443void
444term_timers (void)
445{
446 if (real_itimer.timer_thread)
447 stop_timer_thread (ITIMER_REAL);
448 if (prof_itimer.timer_thread)
449 stop_timer_thread (ITIMER_PROF);
450
451 DeleteCriticalSection (&crit_real);
452 DeleteCriticalSection (&crit_prof);
453 DeleteCriticalSection (&crit_sig);
454}
455
456/* This is called at initialization time from init_ntproc. */
457void
458init_timers (void)
459{
460 /* Make sure we start with zeroed out itimer structures, since
461 dumping may have left there traces of threads long dead. */
462 memset (&real_itimer, 0, sizeof real_itimer);
463 memset (&prof_itimer, 0, sizeof prof_itimer);
464
465 InitializeCriticalSection (&crit_real);
466 InitializeCriticalSection (&crit_prof);
467 InitializeCriticalSection (&crit_sig);
468}
469
470static int
471start_timer_thread (int which)
472{
473 DWORD exit_code;
474 struct itimer_data *itimer =
475 (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;
476
477 if (itimer->timer_thread
478 && GetExitCodeThread (itimer->timer_thread, &exit_code)
479 && exit_code == STILL_ACTIVE)
480 return 0;
481
482 /* Start a new thread. */
483 if (!DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
484 GetCurrentProcess (), &itimer->caller_thread, 0,
485 FALSE, DUPLICATE_SAME_ACCESS))
486 {
487 errno = ESRCH;
488 return -1;
489 }
490
491 itimer->terminate = 0;
492 itimer->type = which;
493 /* Request that no more than 64KB of stack be reserved for this
494 thread, to avoid reserving too much memory, which would get in
495 the way of threads we start to wait for subprocesses. See also
496 new_child below. */
497 itimer->timer_thread = CreateThread (NULL, 64 * 1024, timer_loop,
498 (void *)itimer, 0x00010000, NULL);
499
500 if (!itimer->timer_thread)
501 {
502 CloseHandle (itimer->caller_thread);
503 itimer->caller_thread = NULL;
504 errno = EAGAIN;
505 return -1;
506 }
507
508 /* This is needed to make sure that the timer thread running for
509 profiling gets CPU as soon as the Sleep call terminates. */
510 if (which == ITIMER_PROF)
511 SetThreadPriority (itimer->caller_thread, THREAD_PRIORITY_TIME_CRITICAL);
512
513 return 0;
514}
515
516/* Most of the code of getitimer and setitimer (but not of their
517 subroutines) was shamelessly stolen from itimer.c in the DJGPP
518 library, see www.delorie.com/djgpp. */
519int
520getitimer (int which, struct itimerval *value)
521{
522 volatile clock_t *t_expire;
523 volatile clock_t *t_reload;
524 clock_t expire, reload;
525 __int64 usecs;
526 CRITICAL_SECTION *crit;
527
528 ticks_now = clock ();
529
530 if (!value)
531 {
532 errno = EFAULT;
533 return -1;
534 }
535
536 if (which != ITIMER_REAL && which != ITIMER_PROF)
537 {
538 errno = EINVAL;
539 return -1;
540 }
541
542 t_expire = (which == ITIMER_REAL) ? &real_itimer.expire: &prof_itimer.expire;
543 t_reload = (which == ITIMER_REAL) ? &real_itimer.reload: &prof_itimer.reload;
544 crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
545
546 EnterCriticalSection (crit);
547 reload = *t_reload;
548 expire = *t_expire;
549 LeaveCriticalSection (crit);
550
551 if (expire)
552 expire -= ticks_now;
553
554 value->it_value.tv_sec = expire / CLOCKS_PER_SEC;
555 usecs = (expire % CLOCKS_PER_SEC) * (__int64)1000000 / CLOCKS_PER_SEC;
556 value->it_value.tv_usec = usecs;
557 value->it_interval.tv_sec = reload / CLOCKS_PER_SEC;
558 usecs = (reload % CLOCKS_PER_SEC) * (__int64)1000000 / CLOCKS_PER_SEC;
559 value->it_interval.tv_usec= usecs;
560
561 return 0;
562}
563
564int
565setitimer(int which, struct itimerval *value, struct itimerval *ovalue)
566{
567 volatile clock_t *t_expire, *t_reload;
568 clock_t expire, reload, expire_old, reload_old;
569 __int64 usecs;
570 CRITICAL_SECTION *crit;
571
572 /* Posix systems expect timer values smaller than the resolution of
573 the system clock be rounded up to the clock resolution. First
574 time we are called, measure the clock tick resolution. */
575 if (!clocks_min)
576 {
577 clock_t t1, t2;
578
579 for (t1 = clock (); (t2 = clock ()) == t1; )
580 ;
581 clocks_min = t2 - t1;
582 }
583
584 if (ovalue)
585 {
586 if (getitimer (which, ovalue)) /* also sets ticks_now */
587 return -1; /* errno already set */
588 }
589 else
590 ticks_now = clock ();
591
592 if (which != ITIMER_REAL && which != ITIMER_PROF)
593 {
594 errno = EINVAL;
595 return -1;
596 }
597
598 t_expire =
599 (which == ITIMER_REAL) ? &real_itimer.expire : &prof_itimer.expire;
600 t_reload =
601 (which == ITIMER_REAL) ? &real_itimer.reload : &prof_itimer.reload;
602
603 crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
604
605 if (!value
606 || (value->it_value.tv_sec == 0 && value->it_value.tv_usec == 0))
607 {
608 EnterCriticalSection (crit);
609 /* Disable the timer. */
610 *t_expire = 0;
611 *t_reload = 0;
612 LeaveCriticalSection (crit);
613 return 0;
614 }
615
616 reload = value->it_interval.tv_sec * CLOCKS_PER_SEC;
617
618 usecs = value->it_interval.tv_usec;
619 if (value->it_interval.tv_sec == 0
620 && usecs && usecs * CLOCKS_PER_SEC < clocks_min * 1000000)
621 reload = clocks_min;
622 else
623 {
624 usecs *= CLOCKS_PER_SEC;
625 reload += usecs / 1000000;
626 }
627
628 expire = value->it_value.tv_sec * CLOCKS_PER_SEC;
629 usecs = value->it_value.tv_usec;
630 if (value->it_value.tv_sec == 0
631 && usecs * CLOCKS_PER_SEC < clocks_min * 1000000)
632 expire = clocks_min;
633 else
634 {
635 usecs *= CLOCKS_PER_SEC;
636 expire += usecs / 1000000;
637 }
638
639 expire += ticks_now;
640
641 EnterCriticalSection (crit);
642 expire_old = *t_expire;
643 reload_old = *t_reload;
644 if (!(expire == expire_old && reload == reload_old))
645 {
646 *t_reload = reload;
647 *t_expire = expire;
648 }
649 LeaveCriticalSection (crit);
650
651 return start_timer_thread (which);
652}
653
654int
655alarm (int seconds)
656{
657 struct itimerval new_values;
658
659 new_values.it_value.tv_sec = seconds;
660 new_values.it_value.tv_usec = 0;
661 new_values.it_interval.tv_sec = new_values.it_interval.tv_usec = 0;
662
663 setitimer (ITIMER_REAL, &new_values, NULL);
664
665 return seconds;
666}
667
c519b5e1
GV
668/* Defined in <process.h> which conflicts with the local copy */
669#define _P_NOWAIT 1
670
671/* Child process management list. */
672int child_proc_count = 0;
673child_process child_procs[ MAX_CHILDREN ];
674child_process *dead_child = NULL;
675
24f981c9 676static DWORD WINAPI reader_thread (void *arg);
c519b5e1 677
6cdfb6e6 678/* Find an unused process slot. */
c519b5e1 679child_process *
6cdfb6e6
RS
680new_child (void)
681{
682 child_process *cp;
c519b5e1 683 DWORD id;
177c0ea7 684
9d4f32e8 685 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
6cdfb6e6 686 if (!CHILD_ACTIVE (cp))
e1dbe924 687 goto Initialize;
c519b5e1
GV
688 if (child_proc_count == MAX_CHILDREN)
689 return NULL;
690 cp = &child_procs[child_proc_count++];
691
e1dbe924 692 Initialize:
ed3751c8 693 memset (cp, 0, sizeof (*cp));
c519b5e1
GV
694 cp->fd = -1;
695 cp->pid = -1;
696 cp->procinfo.hProcess = NULL;
697 cp->status = STATUS_READ_ERROR;
698
699 /* use manual reset event so that select() will function properly */
700 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
701 if (cp->char_avail)
702 {
703 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
704 if (cp->char_consumed)
705 {
0d887c7d
EZ
706 /* The 0x00010000 flag is STACK_SIZE_PARAM_IS_A_RESERVATION.
707 It means that the 64K stack we are requesting in the 2nd
708 argument is how much memory should be reserved for the
709 stack. If we don't use this flag, the memory requested
710 by the 2nd argument is the amount actually _committed_,
711 but Windows reserves 8MB of memory for each thread's
712 stack. (The 8MB figure comes from the -stack
713 command-line argument we pass to the linker when building
714 Emacs, but that's because we need a large stack for
715 Emacs's main thread.) Since we request 2GB of reserved
716 memory at startup (see w32heap.c), which is close to the
717 maximum memory available for a 32-bit process on Windows,
718 the 8MB reservation for each thread causes failures in
719 starting subprocesses, because we create a thread running
720 reader_thread for each subprocess. As 8MB of stack is
721 way too much for reader_thread, forcing Windows to
722 reserve less wins the day. */
723 cp->thrd = CreateThread (NULL, 64 * 1024, reader_thread, cp,
724 0x00010000, &id);
c519b5e1
GV
725 if (cp->thrd)
726 return cp;
727 }
728 }
729 delete_child (cp);
730 return NULL;
731}
732
177c0ea7 733void
c519b5e1
GV
734delete_child (child_process *cp)
735{
736 int i;
737
738 /* Should not be deleting a child that is still needed. */
739 for (i = 0; i < MAXDESC; i++)
740 if (fd_info[i].cp == cp)
1088b922 741 emacs_abort ();
c519b5e1
GV
742
743 if (!CHILD_ACTIVE (cp))
744 return;
745
746 /* reap thread if necessary */
747 if (cp->thrd)
748 {
749 DWORD rc;
750
751 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
752 {
753 /* let the thread exit cleanly if possible */
754 cp->status = STATUS_READ_ERROR;
755 SetEvent (cp->char_consumed);
a017b515 756#if 0
c5e87d10 757 /* We used to forcibly terminate the thread here, but it
a017b515
JR
758 is normally unnecessary, and in abnormal cases, the worst that
759 will happen is we have an extra idle thread hanging around
760 waiting for the zombie process. */
c519b5e1
GV
761 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
762 {
763 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
764 "with %lu for fd %ld\n", GetLastError (), cp->fd));
765 TerminateThread (cp->thrd, 0);
766 }
a017b515 767#endif
c519b5e1
GV
768 }
769 CloseHandle (cp->thrd);
770 cp->thrd = NULL;
771 }
772 if (cp->char_avail)
773 {
774 CloseHandle (cp->char_avail);
775 cp->char_avail = NULL;
776 }
777 if (cp->char_consumed)
778 {
779 CloseHandle (cp->char_consumed);
780 cp->char_consumed = NULL;
781 }
782
783 /* update child_proc_count (highest numbered slot in use plus one) */
784 if (cp == child_procs + child_proc_count - 1)
785 {
786 for (i = child_proc_count-1; i >= 0; i--)
787 if (CHILD_ACTIVE (&child_procs[i]))
788 {
789 child_proc_count = i + 1;
790 break;
791 }
792 }
793 if (i < 0)
794 child_proc_count = 0;
6cdfb6e6
RS
795}
796
797/* Find a child by pid. */
798static child_process *
799find_child_pid (DWORD pid)
800{
801 child_process *cp;
c519b5e1 802
9d4f32e8 803 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
6cdfb6e6
RS
804 if (CHILD_ACTIVE (cp) && pid == cp->pid)
805 return cp;
806 return NULL;
807}
808
6cdfb6e6 809
c519b5e1
GV
810/* Thread proc for child process and socket reader threads. Each thread
811 is normally blocked until woken by select() to check for input by
04bf5b65 812 reading one char. When the read completes, char_avail is signaled
c519b5e1 813 to wake up the select emulator and the thread blocks itself again. */
24f981c9 814static DWORD WINAPI
6cdfb6e6
RS
815reader_thread (void *arg)
816{
817 child_process *cp;
177c0ea7 818
6cdfb6e6
RS
819 /* Our identity */
820 cp = (child_process *)arg;
177c0ea7 821
6cdfb6e6 822 /* We have to wait for the go-ahead before we can start */
b2fc9f3d 823 if (cp == NULL
f067b8ec
JB
824 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
825 || cp->fd < 0)
c519b5e1
GV
826 return 1;
827
6cdfb6e6
RS
828 for (;;)
829 {
c519b5e1
GV
830 int rc;
831
f9125cde
KS
832 if (fd_info[cp->fd].flags & FILE_LISTEN)
833 rc = _sys_wait_accept (cp->fd);
834 else
835 rc = _sys_read_ahead (cp->fd);
c519b5e1
GV
836
837 /* The name char_avail is a misnomer - it really just means the
838 read-ahead has completed, whether successfully or not. */
6cdfb6e6
RS
839 if (!SetEvent (cp->char_avail))
840 {
841 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
842 GetLastError (), cp->fd));
c519b5e1
GV
843 return 1;
844 }
845
846 if (rc == STATUS_READ_ERROR)
847 return 1;
177c0ea7 848
6cdfb6e6 849 /* If the read died, the child has died so let the thread die */
c519b5e1 850 if (rc == STATUS_READ_FAILED)
6cdfb6e6 851 break;
177c0ea7 852
6cdfb6e6
RS
853 /* Wait until our input is acknowledged before reading again */
854 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
855 {
856 DebPrint (("reader_thread.WaitForSingleObject failed with "
857 "%lu for fd %ld\n", GetLastError (), cp->fd));
858 break;
859 }
860 }
861 return 0;
862}
863
b2fc9f3d
GV
864/* To avoid Emacs changing directory, we just record here the directory
865 the new process should start in. This is set just before calling
866 sys_spawnve, and is not generally valid at any other time. */
867static char * process_dir;
868
177c0ea7 869static BOOL
a55a5f3c 870create_child (char *exe, char *cmdline, char *env, int is_gui_app,
c519b5e1 871 int * pPid, child_process *cp)
6cdfb6e6 872{
6cdfb6e6
RS
873 STARTUPINFO start;
874 SECURITY_ATTRIBUTES sec_attrs;
42c95ffb 875#if 0
6cdfb6e6 876 SECURITY_DESCRIPTOR sec_desc;
42c95ffb 877#endif
82e7c0a9 878 DWORD flags;
b2fc9f3d 879 char dir[ MAXPATHLEN ];
177c0ea7 880
1088b922 881 if (cp == NULL) emacs_abort ();
177c0ea7 882
6cdfb6e6
RS
883 memset (&start, 0, sizeof (start));
884 start.cb = sizeof (start);
177c0ea7 885
58d4e829 886#ifdef HAVE_NTGUI
a55a5f3c 887 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
0ecf7d36
RS
888 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
889 else
890 start.dwFlags = STARTF_USESTDHANDLES;
58d4e829
GV
891 start.wShowWindow = SW_HIDE;
892
893 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
894 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
895 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
896#endif /* HAVE_NTGUI */
897
42c95ffb 898#if 0
6cdfb6e6
RS
899 /* Explicitly specify no security */
900 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
c519b5e1 901 goto EH_Fail;
6cdfb6e6 902 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
c519b5e1 903 goto EH_Fail;
42c95ffb 904#endif
6cdfb6e6 905 sec_attrs.nLength = sizeof (sec_attrs);
42c95ffb 906 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
6cdfb6e6 907 sec_attrs.bInheritHandle = FALSE;
177c0ea7 908
b2fc9f3d
GV
909 strcpy (dir, process_dir);
910 unixtodos_filename (dir);
82e7c0a9
AI
911
912 flags = (!NILP (Vw32_start_process_share_console)
913 ? CREATE_NEW_PROCESS_GROUP
914 : CREATE_NEW_CONSOLE);
915 if (NILP (Vw32_start_process_inherit_error_mode))
916 flags |= CREATE_DEFAULT_ERROR_MODE;
6cdfb6e6 917 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
82e7c0a9 918 flags, env, dir, &start, &cp->procinfo))
c519b5e1
GV
919 goto EH_Fail;
920
921 cp->pid = (int) cp->procinfo.dwProcessId;
922
923 /* Hack for Windows 95, which assigns large (ie negative) pids */
924 if (cp->pid < 0)
925 cp->pid = -cp->pid;
926
927 /* pid must fit in a Lisp_Int */
acba5cae 928 cp->pid = cp->pid & INTMASK;
c519b5e1 929
c519b5e1 930 *pPid = cp->pid;
b2fc9f3d 931
6cdfb6e6 932 return TRUE;
b2fc9f3d 933
6cdfb6e6 934 EH_Fail:
ed3751c8 935 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
6cdfb6e6
RS
936 return FALSE;
937}
938
939/* create_child doesn't know what emacs' file handle will be for waiting
940 on output from the child, so we need to make this additional call
941 to register the handle with the process
942 This way the select emulator knows how to match file handles with
943 entries in child_procs. */
177c0ea7 944void
6cdfb6e6
RS
945register_child (int pid, int fd)
946{
947 child_process *cp;
177c0ea7 948
6cdfb6e6
RS
949 cp = find_child_pid (pid);
950 if (cp == NULL)
951 {
952 DebPrint (("register_child unable to find pid %lu\n", pid));
953 return;
954 }
177c0ea7 955
6cdfb6e6
RS
956#ifdef FULL_DEBUG
957 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
958#endif
177c0ea7 959
6cdfb6e6 960 cp->fd = fd;
6cdfb6e6 961
c519b5e1
GV
962 /* thread is initially blocked until select is called; set status so
963 that select will release thread */
964 cp->status = STATUS_READ_ACKNOWLEDGED;
965
966 /* attach child_process to fd_info */
967 if (fd_info[fd].cp != NULL)
6cdfb6e6 968 {
c519b5e1 969 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
1088b922 970 emacs_abort ();
6cdfb6e6 971 }
c519b5e1
GV
972
973 fd_info[fd].cp = cp;
6cdfb6e6
RS
974}
975
976/* When a process dies its pipe will break so the reader thread will
977 signal failure to the select emulator.
978 The select emulator then calls this routine to clean up.
979 Since the thread signaled failure we can assume it is exiting. */
177c0ea7 980static void
c519b5e1 981reap_subprocess (child_process *cp)
6cdfb6e6 982{
c519b5e1 983 if (cp->procinfo.hProcess)
6cdfb6e6 984 {
c519b5e1 985 /* Reap the process */
b2fc9f3d
GV
986#ifdef FULL_DEBUG
987 /* Process should have already died before we are called. */
988 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
989 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
990#endif
c519b5e1
GV
991 CloseHandle (cp->procinfo.hProcess);
992 cp->procinfo.hProcess = NULL;
993 CloseHandle (cp->procinfo.hThread);
994 cp->procinfo.hThread = NULL;
6cdfb6e6 995 }
c519b5e1
GV
996
997 /* For asynchronous children, the child_proc resources will be freed
998 when the last pipe read descriptor is closed; for synchronous
999 children, we must explicitly free the resources now because
1000 register_child has not been called. */
1001 if (cp->fd == -1)
1002 delete_child (cp);
6cdfb6e6
RS
1003}
1004
1005/* Wait for any of our existing child processes to die
1006 When it does, close its handle
1007 Return the pid and fill in the status if non-NULL. */
22759c72 1008
177c0ea7 1009int
c519b5e1 1010sys_wait (int *status)
6cdfb6e6
RS
1011{
1012 DWORD active, retval;
1013 int nh;
c519b5e1 1014 int pid;
6cdfb6e6
RS
1015 child_process *cp, *cps[MAX_CHILDREN];
1016 HANDLE wait_hnd[MAX_CHILDREN];
177c0ea7 1017
6cdfb6e6
RS
1018 nh = 0;
1019 if (dead_child != NULL)
1020 {
1021 /* We want to wait for a specific child */
c519b5e1 1022 wait_hnd[nh] = dead_child->procinfo.hProcess;
6cdfb6e6 1023 cps[nh] = dead_child;
1088b922 1024 if (!wait_hnd[nh]) emacs_abort ();
6cdfb6e6 1025 nh++;
b2fc9f3d
GV
1026 active = 0;
1027 goto get_result;
6cdfb6e6
RS
1028 }
1029 else
1030 {
9d4f32e8 1031 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
c519b5e1 1032 /* some child_procs might be sockets; ignore them */
3ac04ed0
CY
1033 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1034 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
6cdfb6e6 1035 {
c519b5e1 1036 wait_hnd[nh] = cp->procinfo.hProcess;
6cdfb6e6
RS
1037 cps[nh] = cp;
1038 nh++;
1039 }
1040 }
177c0ea7 1041
6cdfb6e6
RS
1042 if (nh == 0)
1043 {
1044 /* Nothing to wait on, so fail */
1045 errno = ECHILD;
1046 return -1;
1047 }
b2fc9f3d
GV
1048
1049 do
1050 {
1051 /* Check for quit about once a second. */
1052 QUIT;
1053 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
1054 } while (active == WAIT_TIMEOUT);
1055
6cdfb6e6
RS
1056 if (active == WAIT_FAILED)
1057 {
1058 errno = EBADF;
1059 return -1;
1060 }
b2fc9f3d
GV
1061 else if (active >= WAIT_OBJECT_0
1062 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
6cdfb6e6
RS
1063 {
1064 active -= WAIT_OBJECT_0;
1065 }
b2fc9f3d
GV
1066 else if (active >= WAIT_ABANDONED_0
1067 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
6cdfb6e6
RS
1068 {
1069 active -= WAIT_ABANDONED_0;
1070 }
b2fc9f3d 1071 else
1088b922 1072 emacs_abort ();
b2fc9f3d
GV
1073
1074get_result:
6cdfb6e6
RS
1075 if (!GetExitCodeProcess (wait_hnd[active], &retval))
1076 {
1077 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
1078 GetLastError ()));
1079 retval = 1;
1080 }
1081 if (retval == STILL_ACTIVE)
1082 {
1083 /* Should never happen */
1084 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
1085 errno = EINVAL;
1086 return -1;
1087 }
bc69349b
RS
1088
1089 /* Massage the exit code from the process to match the format expected
8e6208c5 1090 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
bc69349b
RS
1091 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
1092
1093 if (retval == STATUS_CONTROL_C_EXIT)
1094 retval = SIGINT;
1095 else
1096 retval <<= 8;
177c0ea7 1097
6cdfb6e6 1098 cp = cps[active];
c519b5e1
GV
1099 pid = cp->pid;
1100#ifdef FULL_DEBUG
1101 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
1102#endif
22759c72 1103
6cdfb6e6
RS
1104 if (status)
1105 {
22759c72
KH
1106 *status = retval;
1107 }
1108 else if (synch_process_alive)
1109 {
1110 synch_process_alive = 0;
22759c72 1111
3d7eead0
GV
1112 /* Report the status of the synchronous process. */
1113 if (WIFEXITED (retval))
13294f95 1114 synch_process_retcode = WEXITSTATUS (retval);
3d7eead0
GV
1115 else if (WIFSIGNALED (retval))
1116 {
1117 int code = WTERMSIG (retval);
68c45bf0
PE
1118 char *signame;
1119
ca9c0567 1120 synchronize_system_messages_locale ();
68c45bf0
PE
1121 signame = strsignal (code);
1122
3d7eead0
GV
1123 if (signame == 0)
1124 signame = "unknown";
1125
1126 synch_process_death = signame;
1127 }
c519b5e1
GV
1128
1129 reap_subprocess (cp);
6cdfb6e6 1130 }
b2fc9f3d
GV
1131
1132 reap_subprocess (cp);
177c0ea7 1133
c519b5e1 1134 return pid;
6cdfb6e6
RS
1135}
1136
75be5258
EZ
1137/* Old versions of w32api headers don't have separate 32-bit and
1138 64-bit defines, but the one they have matches the 32-bit variety. */
1139#ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
1140# define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
1141# define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
1142#endif
1143
24f981c9 1144static void
b56ceb92
JB
1145w32_executable_type (char * filename,
1146 int * is_dos_app,
1147 int * is_cygnus_app,
1148 int * is_gui_app)
817abdf6 1149{
b2fc9f3d
GV
1150 file_data executable;
1151 char * p;
177c0ea7 1152
b2fc9f3d
GV
1153 /* Default values in case we can't tell for sure. */
1154 *is_dos_app = FALSE;
1155 *is_cygnus_app = FALSE;
a55a5f3c 1156 *is_gui_app = FALSE;
b2fc9f3d
GV
1157
1158 if (!open_input_file (&executable, filename))
1159 return;
817abdf6 1160
b2fc9f3d 1161 p = strrchr (filename, '.');
177c0ea7 1162
b2fc9f3d 1163 /* We can only identify DOS .com programs from the extension. */
05131107 1164 if (p && xstrcasecmp (p, ".com") == 0)
b2fc9f3d 1165 *is_dos_app = TRUE;
05131107
JR
1166 else if (p && (xstrcasecmp (p, ".bat") == 0
1167 || xstrcasecmp (p, ".cmd") == 0))
b2fc9f3d
GV
1168 {
1169 /* A DOS shell script - it appears that CreateProcess is happy to
1170 accept this (somewhat surprisingly); presumably it looks at
1171 COMSPEC to determine what executable to actually invoke.
1172 Therefore, we have to do the same here as well. */
1173 /* Actually, I think it uses the program association for that
1174 extension, which is defined in the registry. */
1175 p = egetenv ("COMSPEC");
1176 if (p)
a55a5f3c 1177 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
b2fc9f3d
GV
1178 }
1179 else
817abdf6 1180 {
b2fc9f3d
GV
1181 /* Look for DOS .exe signature - if found, we must also check that
1182 it isn't really a 16- or 32-bit Windows exe, since both formats
1183 start with a DOS program stub. Note that 16-bit Windows
1184 executables use the OS/2 1.x format. */
817abdf6 1185
b2fc9f3d
GV
1186 IMAGE_DOS_HEADER * dos_header;
1187 IMAGE_NT_HEADERS * nt_header;
1188
1189 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
1190 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
1191 goto unwind;
1192
1193 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
1194
177c0ea7 1195 if ((char *) nt_header > (char *) dos_header + executable.size)
817abdf6 1196 {
b2fc9f3d
GV
1197 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
1198 *is_dos_app = TRUE;
177c0ea7 1199 }
b2fc9f3d
GV
1200 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
1201 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
1202 {
1203 *is_dos_app = TRUE;
1204 }
1205 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
1206 {
2b6e2f4d
JR
1207 IMAGE_DATA_DIRECTORY *data_dir = NULL;
1208 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
1209 {
1210 /* Ensure we are using the 32 bit structure. */
1211 IMAGE_OPTIONAL_HEADER32 *opt
1212 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
1213 data_dir = opt->DataDirectory;
1214 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
1215 }
1216 /* MingW 3.12 has the required 64 bit structs, but in case older
1217 versions don't, only check 64 bit exes if we know how. */
1218#ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
1219 else if (nt_header->OptionalHeader.Magic
1220 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1221 {
1222 IMAGE_OPTIONAL_HEADER64 *opt
1223 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
1224 data_dir = opt->DataDirectory;
1225 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
1226 }
1227#endif
1228 if (data_dir)
1229 {
1230 /* Look for cygwin.dll in DLL import list. */
1231 IMAGE_DATA_DIRECTORY import_dir =
1232 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
1233 IMAGE_IMPORT_DESCRIPTOR * imports;
1234 IMAGE_SECTION_HEADER * section;
1235
1236 section = rva_to_section (import_dir.VirtualAddress, nt_header);
1237 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
1238 executable);
1239
1240 for ( ; imports->Name; imports++)
1241 {
1242 char * dllname = RVA_TO_PTR (imports->Name, section,
1243 executable);
35f36d65 1244
2b6e2f4d
JR
1245 /* The exact name of the cygwin dll has changed with
1246 various releases, but hopefully this will be reasonably
1247 future proof. */
1248 if (strncmp (dllname, "cygwin", 6) == 0)
1249 {
1250 *is_cygnus_app = TRUE;
1251 break;
1252 }
1253 }
1254 }
b2fc9f3d 1255 }
817abdf6 1256 }
177c0ea7 1257
b2fc9f3d
GV
1258unwind:
1259 close_file_data (&executable);
817abdf6
KH
1260}
1261
24f981c9 1262static int
42c95ffb 1263compare_env (const void *strp1, const void *strp2)
d9709fde 1264{
42c95ffb 1265 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
d9709fde
GV
1266
1267 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
1268 {
11c22fff
AI
1269 /* Sort order in command.com/cmd.exe is based on uppercasing
1270 names, so do the same here. */
1271 if (toupper (*str1) > toupper (*str2))
d9709fde 1272 return 1;
11c22fff 1273 else if (toupper (*str1) < toupper (*str2))
d9709fde
GV
1274 return -1;
1275 str1++, str2++;
1276 }
1277
1278 if (*str1 == '=' && *str2 == '=')
1279 return 0;
1280 else if (*str1 == '=')
1281 return -1;
1282 else
1283 return 1;
1284}
1285
24f981c9 1286static void
d9709fde
GV
1287merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
1288{
1289 char **optr, **nptr;
1290 int num;
1291
1292 nptr = new_envp;
1293 optr = envp1;
1294 while (*optr)
1295 *nptr++ = *optr++;
1296 num = optr - envp1;
1297
1298 optr = envp2;
1299 while (*optr)
1300 *nptr++ = *optr++;
1301 num += optr - envp2;
1302
1303 qsort (new_envp, num, sizeof (char *), compare_env);
1304
1305 *nptr = NULL;
1306}
6cdfb6e6
RS
1307
1308/* When a new child process is created we need to register it in our list,
1309 so intercept spawn requests. */
177c0ea7 1310int
c519b5e1 1311sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
6cdfb6e6 1312{
0a4de642 1313 Lisp_Object program, full;
6cdfb6e6 1314 char *cmdline, *env, *parg, **targ;
d9709fde 1315 int arglen, numenv;
c519b5e1
GV
1316 int pid;
1317 child_process *cp;
a55a5f3c 1318 int is_dos_app, is_cygnus_app, is_gui_app;
b2fc9f3d
GV
1319 int do_quoting = 0;
1320 char escape_char;
d9709fde
GV
1321 /* We pass our process ID to our children by setting up an environment
1322 variable in their environment. */
1323 char ppid_env_var_buffer[64];
1324 char *extra_env[] = {ppid_env_var_buffer, NULL};
0a7a6051
JR
1325 /* These are the characters that cause an argument to need quoting.
1326 Arguments with whitespace characters need quoting to prevent the
1327 argument being split into two or more. Arguments with wildcards
1328 are also quoted, for consistency with posix platforms, where wildcards
1329 are not expanded if we run the program directly without a shell.
1330 Some extra whitespace characters need quoting in Cygwin programs,
1331 so this list is conditionally modified below. */
1332 char *sepchars = " \t*?";
d9709fde 1333
c519b5e1
GV
1334 /* We don't care about the other modes */
1335 if (mode != _P_NOWAIT)
1336 {
1337 errno = EINVAL;
1338 return -1;
1339 }
0a4de642
RS
1340
1341 /* Handle executable names without an executable suffix. */
1130ecfc 1342 program = build_string (cmdname);
0a4de642
RS
1343 if (NILP (Ffile_executable_p (program)))
1344 {
1345 struct gcpro gcpro1;
177c0ea7 1346
0a4de642
RS
1347 full = Qnil;
1348 GCPRO1 (program);
44c7a526 1349 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
0a4de642
RS
1350 UNGCPRO;
1351 if (NILP (full))
1352 {
1353 errno = EINVAL;
1354 return -1;
1355 }
b2fc9f3d 1356 program = full;
0a4de642
RS
1357 }
1358
b2fc9f3d 1359 /* make sure argv[0] and cmdname are both in DOS format */
d5db4077 1360 cmdname = SDATA (program);
c519b5e1
GV
1361 unixtodos_filename (cmdname);
1362 argv[0] = cmdname;
817abdf6 1363
b46a6a83 1364 /* Determine whether program is a 16-bit DOS executable, or a 32-bit Windows
b2fc9f3d
GV
1365 executable that is implicitly linked to the Cygnus dll (implying it
1366 was compiled with the Cygnus GNU toolchain and hence relies on
1367 cygwin.dll to parse the command line - we use this to decide how to
a55a5f3c
AI
1368 escape quote chars in command line args that must be quoted).
1369
1370 Also determine whether it is a GUI app, so that we don't hide its
1371 initial window unless specifically requested. */
1372 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
b2fc9f3d
GV
1373
1374 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
1375 application to start it by specifying the helper app as cmdname,
1376 while leaving the real app name as argv[0]. */
1377 if (is_dos_app)
817abdf6 1378 {
b2fc9f3d
GV
1379 cmdname = alloca (MAXPATHLEN);
1380 if (egetenv ("CMDPROXY"))
1381 strcpy (cmdname, egetenv ("CMDPROXY"));
1382 else
1383 {
d5db4077 1384 strcpy (cmdname, SDATA (Vinvocation_directory));
b2fc9f3d
GV
1385 strcat (cmdname, "cmdproxy.exe");
1386 }
1387 unixtodos_filename (cmdname);
817abdf6 1388 }
177c0ea7 1389
6cdfb6e6
RS
1390 /* we have to do some conjuring here to put argv and envp into the
1391 form CreateProcess wants... argv needs to be a space separated/null
1392 terminated list of parameters, and envp is a null
1393 separated/double-null terminated list of parameters.
c519b5e1 1394
b2fc9f3d
GV
1395 Additionally, zero-length args and args containing whitespace or
1396 quote chars need to be wrapped in double quotes - for this to work,
1397 embedded quotes need to be escaped as well. The aim is to ensure
1398 the child process reconstructs the argv array we start with
1399 exactly, so we treat quotes at the beginning and end of arguments
1400 as embedded quotes.
1401
ef79fbba 1402 The w32 GNU-based library from Cygnus doubles quotes to escape
b2fc9f3d 1403 them, while MSVC uses backslash for escaping. (Actually the MSVC
e1dbe924 1404 startup code does attempt to recognize doubled quotes and accept
b2fc9f3d
GV
1405 them, but gets it wrong and ends up requiring three quotes to get a
1406 single embedded quote!) So by default we decide whether to use
1407 quote or backslash as the escape character based on whether the
1408 binary is apparently a Cygnus compiled app.
1409
1410 Note that using backslash to escape embedded quotes requires
1411 additional special handling if an embedded quote is already
97610156 1412 preceded by backslash, or if an arg requiring quoting ends with
b2fc9f3d
GV
1413 backslash. In such cases, the run of escape characters needs to be
1414 doubled. For consistency, we apply this special handling as long
1415 as the escape character is not quote.
1416
1417 Since we have no idea how large argv and envp are likely to be we
1418 figure out list lengths on the fly and allocate them. */
1419
1420 if (!NILP (Vw32_quote_process_args))
1421 {
1422 do_quoting = 1;
1423 /* Override escape char by binding w32-quote-process-args to
1424 desired character, or use t for auto-selection. */
1425 if (INTEGERP (Vw32_quote_process_args))
1426 escape_char = XINT (Vw32_quote_process_args);
1427 else
1428 escape_char = is_cygnus_app ? '"' : '\\';
1429 }
177c0ea7 1430
9d4f32e8 1431 /* Cygwin apps needs quoting a bit more often. */
dbb70029
GM
1432 if (escape_char == '"')
1433 sepchars = "\r\n\t\f '";
1434
6cdfb6e6
RS
1435 /* do argv... */
1436 arglen = 0;
1437 targ = argv;
1438 while (*targ)
1439 {
c519b5e1 1440 char * p = *targ;
b2fc9f3d
GV
1441 int need_quotes = 0;
1442 int escape_char_run = 0;
c519b5e1
GV
1443
1444 if (*p == 0)
b2fc9f3d
GV
1445 need_quotes = 1;
1446 for ( ; *p; p++)
1447 {
dbb70029
GM
1448 if (escape_char == '"' && *p == '\\')
1449 /* If it's a Cygwin app, \ needs to be escaped. */
1450 arglen++;
1451 else if (*p == '"')
b2fc9f3d
GV
1452 {
1453 /* allow for embedded quotes to be escaped */
1454 arglen++;
1455 need_quotes = 1;
1456 /* handle the case where the embedded quote is already escaped */
1457 if (escape_char_run > 0)
1458 {
1459 /* To preserve the arg exactly, we need to double the
1460 preceding escape characters (plus adding one to
1461 escape the quote character itself). */
1462 arglen += escape_char_run;
1463 }
1464 }
dbb70029 1465 else if (strchr (sepchars, *p) != NULL)
b2fc9f3d
GV
1466 {
1467 need_quotes = 1;
1468 }
1469
1470 if (*p == escape_char && escape_char != '"')
1471 escape_char_run++;
1472 else
1473 escape_char_run = 0;
1474 }
1475 if (need_quotes)
1476 {
1477 arglen += 2;
1478 /* handle the case where the arg ends with an escape char - we
1479 must not let the enclosing quote be escaped. */
1480 if (escape_char_run > 0)
1481 arglen += escape_char_run;
1482 }
6cdfb6e6
RS
1483 arglen += strlen (*targ++) + 1;
1484 }
c519b5e1 1485 cmdline = alloca (arglen);
6cdfb6e6
RS
1486 targ = argv;
1487 parg = cmdline;
1488 while (*targ)
1489 {
c519b5e1 1490 char * p = *targ;
b2fc9f3d 1491 int need_quotes = 0;
c519b5e1
GV
1492
1493 if (*p == 0)
b2fc9f3d 1494 need_quotes = 1;
93fdf2f8 1495
b2fc9f3d 1496 if (do_quoting)
93fdf2f8 1497 {
93fdf2f8 1498 for ( ; *p; p++)
dbb70029 1499 if ((strchr (sepchars, *p) != NULL) || *p == '"')
b2fc9f3d 1500 need_quotes = 1;
93fdf2f8 1501 }
b2fc9f3d 1502 if (need_quotes)
c519b5e1 1503 {
b2fc9f3d 1504 int escape_char_run = 0;
c519b5e1
GV
1505 char * first;
1506 char * last;
1507
1508 p = *targ;
1509 first = p;
1510 last = p + strlen (p) - 1;
1511 *parg++ = '"';
b2fc9f3d
GV
1512#if 0
1513 /* This version does not escape quotes if they occur at the
1514 beginning or end of the arg - this could lead to incorrect
fffa137c 1515 behavior when the arg itself represents a command line
b2fc9f3d
GV
1516 containing quoted args. I believe this was originally done
1517 as a hack to make some things work, before
1518 `w32-quote-process-args' was added. */
c519b5e1
GV
1519 while (*p)
1520 {
1521 if (*p == '"' && p > first && p < last)
b2fc9f3d 1522 *parg++ = escape_char; /* escape embedded quotes */
c519b5e1
GV
1523 *parg++ = *p++;
1524 }
b2fc9f3d
GV
1525#else
1526 for ( ; *p; p++)
1527 {
1528 if (*p == '"')
1529 {
1530 /* double preceding escape chars if any */
1531 while (escape_char_run > 0)
1532 {
1533 *parg++ = escape_char;
1534 escape_char_run--;
1535 }
1536 /* escape all quote chars, even at beginning or end */
1537 *parg++ = escape_char;
1538 }
dbb70029
GM
1539 else if (escape_char == '"' && *p == '\\')
1540 *parg++ = '\\';
b2fc9f3d
GV
1541 *parg++ = *p;
1542
1543 if (*p == escape_char && escape_char != '"')
1544 escape_char_run++;
1545 else
1546 escape_char_run = 0;
1547 }
1548 /* double escape chars before enclosing quote */
1549 while (escape_char_run > 0)
1550 {
1551 *parg++ = escape_char;
1552 escape_char_run--;
1553 }
1554#endif
c519b5e1
GV
1555 *parg++ = '"';
1556 }
1557 else
1558 {
1559 strcpy (parg, *targ);
1560 parg += strlen (*targ);
1561 }
6cdfb6e6 1562 *parg++ = ' ';
c519b5e1 1563 targ++;
6cdfb6e6
RS
1564 }
1565 *--parg = '\0';
177c0ea7 1566
6cdfb6e6
RS
1567 /* and envp... */
1568 arglen = 1;
1569 targ = envp;
d9709fde 1570 numenv = 1; /* for end null */
6cdfb6e6
RS
1571 while (*targ)
1572 {
1573 arglen += strlen (*targ++) + 1;
d9709fde 1574 numenv++;
6cdfb6e6 1575 }
d9709fde 1576 /* extra env vars... */
177c0ea7 1577 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
6cdfb6e6
RS
1578 GetCurrentProcessId ());
1579 arglen += strlen (ppid_env_var_buffer) + 1;
d9709fde 1580 numenv++;
6cdfb6e6 1581
d9709fde
GV
1582 /* merge env passed in and extra env into one, and sort it. */
1583 targ = (char **) alloca (numenv * sizeof (char *));
1584 merge_and_sort_env (envp, extra_env, targ);
1585
1586 /* concatenate env entries. */
c519b5e1 1587 env = alloca (arglen);
6cdfb6e6
RS
1588 parg = env;
1589 while (*targ)
1590 {
1591 strcpy (parg, *targ);
1592 parg += strlen (*targ++);
1593 *parg++ = '\0';
1594 }
6cdfb6e6
RS
1595 *parg++ = '\0';
1596 *parg = '\0';
c519b5e1
GV
1597
1598 cp = new_child ();
1599 if (cp == NULL)
1600 {
1601 errno = EAGAIN;
1602 return -1;
1603 }
177c0ea7 1604
6cdfb6e6 1605 /* Now create the process. */
a55a5f3c 1606 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
6cdfb6e6 1607 {
c519b5e1 1608 delete_child (cp);
6cdfb6e6 1609 errno = ENOEXEC;
c519b5e1 1610 return -1;
6cdfb6e6 1611 }
177c0ea7 1612
c519b5e1 1613 return pid;
6cdfb6e6
RS
1614}
1615
1616/* Emulate the select call
1617 Wait for available input on any of the given rfds, or timeout if
1618 a timeout is given and no input is detected
b2fc9f3d
GV
1619 wfds and efds are not supported and must be NULL.
1620
1621 For simplicity, we detect the death of child processes here and
1622 synchronously call the SIGCHLD handler. Since it is possible for
1623 children to be created without a corresponding pipe handle from which
1624 to read output, we wait separately on the process handles as well as
1625 the char_avail events for each process pipe. We only call
86143765
RS
1626 wait/reap_process when the process actually terminates.
1627
1628 To reduce the number of places in which Emacs can be hung such that
1629 C-g is not able to interrupt it, we always wait on interrupt_handle
04bf5b65 1630 (which is signaled by the input thread when C-g is detected). If we
86143765
RS
1631 detect that we were woken up by C-g, we return -1 with errno set to
1632 EINTR as on Unix. */
6cdfb6e6 1633
7684e57b 1634/* From w32console.c */
6cdfb6e6 1635extern HANDLE keyboard_handle;
86143765
RS
1636
1637/* From w32xfns.c */
1638extern HANDLE interrupt_handle;
1639
6cdfb6e6
RS
1640/* From process.c */
1641extern int proc_buffered_char[];
1642
177c0ea7 1643int
22759c72 1644sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
c9240d7a 1645 EMACS_TIME *timeout, void *ignored)
6cdfb6e6
RS
1646{
1647 SELECT_TYPE orfds;
b2fc9f3d
GV
1648 DWORD timeout_ms, start_time;
1649 int i, nh, nc, nr;
6cdfb6e6 1650 DWORD active;
b2fc9f3d
GV
1651 child_process *cp, *cps[MAX_CHILDREN];
1652 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
c519b5e1 1653 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
177c0ea7 1654
388cdec0
EZ
1655 timeout_ms =
1656 timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 1000000) : INFINITE;
b2fc9f3d 1657
6cdfb6e6 1658 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
177c0ea7 1659 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
6cdfb6e6 1660 {
b2fc9f3d 1661 Sleep (timeout_ms);
6cdfb6e6
RS
1662 return 0;
1663 }
1664
1665 /* Otherwise, we only handle rfds, so fail otherwise. */
1666 if (rfds == NULL || wfds != NULL || efds != NULL)
1667 {
1668 errno = EINVAL;
1669 return -1;
1670 }
177c0ea7 1671
6cdfb6e6
RS
1672 orfds = *rfds;
1673 FD_ZERO (rfds);
1674 nr = 0;
86143765
RS
1675
1676 /* Always wait on interrupt_handle, to detect C-g (quit). */
1677 wait_hnd[0] = interrupt_handle;
1678 fdindex[0] = -1;
177c0ea7 1679
b2fc9f3d 1680 /* Build a list of pipe handles to wait on. */
86143765 1681 nh = 1;
6cdfb6e6
RS
1682 for (i = 0; i < nfds; i++)
1683 if (FD_ISSET (i, &orfds))
1684 {
1685 if (i == 0)
1686 {
c519b5e1
GV
1687 if (keyboard_handle)
1688 {
1689 /* Handle stdin specially */
1690 wait_hnd[nh] = keyboard_handle;
1691 fdindex[nh] = i;
1692 nh++;
1693 }
6cdfb6e6
RS
1694
1695 /* Check for any emacs-generated input in the queue since
1696 it won't be detected in the wait */
1697 if (detect_input_pending ())
1698 {
1699 FD_SET (i, rfds);
c519b5e1 1700 return 1;
6cdfb6e6
RS
1701 }
1702 }
1703 else
1704 {
c519b5e1
GV
1705 /* Child process and socket input */
1706 cp = fd_info[i].cp;
6cdfb6e6
RS
1707 if (cp)
1708 {
c519b5e1
GV
1709 int current_status = cp->status;
1710
1711 if (current_status == STATUS_READ_ACKNOWLEDGED)
1712 {
1713 /* Tell reader thread which file handle to use. */
1714 cp->fd = i;
1715 /* Wake up the reader thread for this process */
1716 cp->status = STATUS_READ_READY;
1717 if (!SetEvent (cp->char_consumed))
1718 DebPrint (("nt_select.SetEvent failed with "
1719 "%lu for fd %ld\n", GetLastError (), i));
1720 }
1721
1722#ifdef CHECK_INTERLOCK
1723 /* slightly crude cross-checking of interlock between threads */
1724
1725 current_status = cp->status;
1726 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1727 {
04bf5b65 1728 /* char_avail has been signaled, so status (which may
c519b5e1
GV
1729 have changed) should indicate read has completed
1730 but has not been acknowledged. */
1731 current_status = cp->status;
b2fc9f3d
GV
1732 if (current_status != STATUS_READ_SUCCEEDED
1733 && current_status != STATUS_READ_FAILED)
c519b5e1
GV
1734 DebPrint (("char_avail set, but read not completed: status %d\n",
1735 current_status));
1736 }
1737 else
1738 {
04bf5b65 1739 /* char_avail has not been signaled, so status should
c519b5e1 1740 indicate that read is in progress; small possibility
04bf5b65 1741 that read has completed but event wasn't yet signaled
c519b5e1
GV
1742 when we tested it (because a context switch occurred
1743 or if running on separate CPUs). */
b2fc9f3d
GV
1744 if (current_status != STATUS_READ_READY
1745 && current_status != STATUS_READ_IN_PROGRESS
1746 && current_status != STATUS_READ_SUCCEEDED
1747 && current_status != STATUS_READ_FAILED)
c519b5e1
GV
1748 DebPrint (("char_avail reset, but read status is bad: %d\n",
1749 current_status));
1750 }
1751#endif
1752 wait_hnd[nh] = cp->char_avail;
1753 fdindex[nh] = i;
1088b922 1754 if (!wait_hnd[nh]) emacs_abort ();
c519b5e1 1755 nh++;
6cdfb6e6
RS
1756#ifdef FULL_DEBUG
1757 DebPrint (("select waiting on child %d fd %d\n",
1758 cp-child_procs, i));
1759#endif
6cdfb6e6
RS
1760 }
1761 else
1762 {
c519b5e1 1763 /* Unable to find something to wait on for this fd, skip */
ef79fbba
GV
1764
1765 /* Note that this is not a fatal error, and can in fact
1766 happen in unusual circumstances. Specifically, if
1767 sys_spawnve fails, eg. because the program doesn't
1768 exist, and debug-on-error is t so Fsignal invokes a
1769 nested input loop, then the process output pipe is
1770 still included in input_wait_mask with no child_proc
1771 associated with it. (It is removed when the debugger
1772 exits the nested input loop and the error is thrown.) */
1773
c519b5e1 1774 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
6cdfb6e6
RS
1775 }
1776 }
1777 }
b2fc9f3d
GV
1778
1779count_children:
1780 /* Add handles of child processes. */
1781 nc = 0;
9d4f32e8 1782 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
ef79fbba
GV
1783 /* Some child_procs might be sockets; ignore them. Also some
1784 children may have died already, but we haven't finished reading
1785 the process output; ignore them too. */
1786 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1787 && (cp->fd < 0
1788 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1789 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1790 )
b2fc9f3d
GV
1791 {
1792 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1793 cps[nc] = cp;
1794 nc++;
1795 }
177c0ea7 1796
6cdfb6e6 1797 /* Nothing to look for, so we didn't find anything */
177c0ea7 1798 if (nh + nc == 0)
6cdfb6e6 1799 {
22759c72 1800 if (timeout)
b2fc9f3d 1801 Sleep (timeout_ms);
6cdfb6e6
RS
1802 return 0;
1803 }
177c0ea7 1804
b2fc9f3d 1805 start_time = GetTickCount ();
8b031dcc 1806
04bf5b65 1807 /* Wait for input or child death to be signaled. If user input is
8b031dcc
AI
1808 allowed, then also accept window messages. */
1809 if (FD_ISSET (0, &orfds))
1810 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1811 QS_ALLINPUT);
1812 else
1813 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
c519b5e1 1814
6cdfb6e6
RS
1815 if (active == WAIT_FAILED)
1816 {
1817 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
b2fc9f3d 1818 nh + nc, timeout_ms, GetLastError ()));
d64b707c 1819 /* don't return EBADF - this causes wait_reading_process_output to
c519b5e1
GV
1820 abort; WAIT_FAILED is returned when single-stepping under
1821 Windows 95 after switching thread focus in debugger, and
1822 possibly at other times. */
1823 errno = EINTR;
6cdfb6e6
RS
1824 return -1;
1825 }
1826 else if (active == WAIT_TIMEOUT)
1827 {
1828 return 0;
1829 }
b2fc9f3d
GV
1830 else if (active >= WAIT_OBJECT_0
1831 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
6cdfb6e6
RS
1832 {
1833 active -= WAIT_OBJECT_0;
1834 }
b2fc9f3d
GV
1835 else if (active >= WAIT_ABANDONED_0
1836 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
6cdfb6e6
RS
1837 {
1838 active -= WAIT_ABANDONED_0;
1839 }
b2fc9f3d 1840 else
1088b922 1841 emacs_abort ();
6cdfb6e6 1842
c519b5e1 1843 /* Loop over all handles after active (now officially documented as
04bf5b65 1844 being the first signaled handle in the array). We do this to
c519b5e1
GV
1845 ensure fairness, so that all channels with data available will be
1846 processed - otherwise higher numbered channels could be starved. */
1847 do
6cdfb6e6 1848 {
8b031dcc
AI
1849 if (active == nh + nc)
1850 {
1851 /* There are messages in the lisp thread's queue; we must
1852 drain the queue now to ensure they are processed promptly,
1853 because if we don't do so, we will not be woken again until
1854 further messages arrive.
1855
1856 NB. If ever we allow window message procedures to callback
1857 into lisp, we will need to ensure messages are dispatched
1858 at a safe time for lisp code to be run (*), and we may also
1859 want to provide some hooks in the dispatch loop to cater
1860 for modeless dialogs created by lisp (ie. to register
1861 window handles to pass to IsDialogMessage).
1862
1863 (*) Note that MsgWaitForMultipleObjects above is an
1864 internal dispatch point for messages that are sent to
1865 windows created by this thread. */
1866 drain_message_queue ();
1867 }
1868 else if (active >= nh)
b2fc9f3d
GV
1869 {
1870 cp = cps[active - nh];
ef79fbba
GV
1871
1872 /* We cannot always signal SIGCHLD immediately; if we have not
1873 finished reading the process output, we must delay sending
1874 SIGCHLD until we do. */
1875
1876 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1877 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
b2fc9f3d 1878 /* SIG_DFL for SIGCHLD is ignore */
ef79fbba
GV
1879 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1880 sig_handlers[SIGCHLD] != SIG_IGN)
b2fc9f3d
GV
1881 {
1882#ifdef FULL_DEBUG
1883 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1884 cp->pid));
1885#endif
1886 dead_child = cp;
1887 sig_handlers[SIGCHLD] (SIGCHLD);
1888 dead_child = NULL;
1889 }
1890 }
86143765
RS
1891 else if (fdindex[active] == -1)
1892 {
1893 /* Quit (C-g) was detected. */
1894 errno = EINTR;
1895 return -1;
1896 }
b2fc9f3d 1897 else if (fdindex[active] == 0)
c519b5e1
GV
1898 {
1899 /* Keyboard input available */
1900 FD_SET (0, rfds);
6cdfb6e6 1901 nr++;
c519b5e1 1902 }
6cdfb6e6 1903 else
c519b5e1 1904 {
b2fc9f3d
GV
1905 /* must be a socket or pipe - read ahead should have
1906 completed, either succeeding or failing. */
c519b5e1
GV
1907 FD_SET (fdindex[active], rfds);
1908 nr++;
c519b5e1
GV
1909 }
1910
b2fc9f3d
GV
1911 /* Even though wait_reading_process_output only reads from at most
1912 one channel, we must process all channels here so that we reap
1913 all children that have died. */
1914 while (++active < nh + nc)
c519b5e1
GV
1915 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1916 break;
b2fc9f3d
GV
1917 } while (active < nh + nc);
1918
1919 /* If no input has arrived and timeout hasn't expired, wait again. */
1920 if (nr == 0)
1921 {
1922 DWORD elapsed = GetTickCount () - start_time;
1923
1924 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1925 {
1926 if (timeout_ms != INFINITE)
1927 timeout_ms -= elapsed;
1928 goto count_children;
1929 }
1930 }
c519b5e1 1931
6cdfb6e6
RS
1932 return nr;
1933}
1934
c519b5e1 1935/* Substitute for certain kill () operations */
b2fc9f3d
GV
1936
1937static BOOL CALLBACK
42c95ffb 1938find_child_console (HWND hwnd, LPARAM arg)
b2fc9f3d 1939{
42c95ffb 1940 child_process * cp = (child_process *) arg;
b2fc9f3d
GV
1941 DWORD thread_id;
1942 DWORD process_id;
1943
1944 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1945 if (process_id == cp->procinfo.dwProcessId)
1946 {
1947 char window_class[32];
1948
1949 GetClassName (hwnd, window_class, sizeof (window_class));
1950 if (strcmp (window_class,
417a7a0e 1951 (os_subtype == OS_9X)
b2fc9f3d
GV
1952 ? "tty"
1953 : "ConsoleWindowClass") == 0)
1954 {
1955 cp->hwnd = hwnd;
1956 return FALSE;
1957 }
1958 }
1959 /* keep looking */
1960 return TRUE;
1961}
1962
16b22fef 1963/* Emulate 'kill', but only for other processes. */
177c0ea7 1964int
c519b5e1 1965sys_kill (int pid, int sig)
6cdfb6e6
RS
1966{
1967 child_process *cp;
c519b5e1
GV
1968 HANDLE proc_hand;
1969 int need_to_free = 0;
1970 int rc = 0;
177c0ea7 1971
6cdfb6e6
RS
1972 /* Only handle signals that will result in the process dying */
1973 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1974 {
1975 errno = EINVAL;
1976 return -1;
1977 }
c519b5e1 1978
6cdfb6e6
RS
1979 cp = find_child_pid (pid);
1980 if (cp == NULL)
1981 {
16b22fef
EZ
1982 /* We were passed a PID of something other than our subprocess.
1983 If that is our own PID, we will send to ourself a message to
1984 close the selected frame, which does not necessarily
1985 terminates Emacs. But then we are not supposed to call
1986 sys_kill with our own PID. */
c519b5e1
GV
1987 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1988 if (proc_hand == NULL)
1989 {
1990 errno = EPERM;
1991 return -1;
1992 }
1993 need_to_free = 1;
1994 }
1995 else
1996 {
1997 proc_hand = cp->procinfo.hProcess;
1998 pid = cp->procinfo.dwProcessId;
b2fc9f3d
GV
1999
2000 /* Try to locate console window for process. */
2001 EnumWindows (find_child_console, (LPARAM) cp);
6cdfb6e6 2002 }
177c0ea7 2003
a55a5f3c 2004 if (sig == SIGINT || sig == SIGQUIT)
6cdfb6e6 2005 {
b2fc9f3d
GV
2006 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
2007 {
2008 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
a55a5f3c
AI
2009 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
2010 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
b2fc9f3d
GV
2011 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
2012 HWND foreground_window;
2013
2014 if (break_scan_code == 0)
2015 {
a55a5f3c 2016 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
b2fc9f3d
GV
2017 vk_break_code = 'C';
2018 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
2019 }
2020
2021 foreground_window = GetForegroundWindow ();
f446016f 2022 if (foreground_window)
b2fc9f3d 2023 {
f446016f
AI
2024 /* NT 5.0, and apparently also Windows 98, will not allow
2025 a Window to be set to foreground directly without the
2026 user's involvement. The workaround is to attach
2027 ourselves to the thread that owns the foreground
2028 window, since that is the only thread that can set the
2029 foreground window. */
2030 DWORD foreground_thread, child_thread;
2031 foreground_thread =
2032 GetWindowThreadProcessId (foreground_window, NULL);
2033 if (foreground_thread == GetCurrentThreadId ()
2034 || !AttachThreadInput (GetCurrentThreadId (),
2035 foreground_thread, TRUE))
2036 foreground_thread = 0;
2037
2038 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
2039 if (child_thread == GetCurrentThreadId ()
2040 || !AttachThreadInput (GetCurrentThreadId (),
2041 child_thread, TRUE))
2042 child_thread = 0;
2043
2044 /* Set the foreground window to the child. */
2045 if (SetForegroundWindow (cp->hwnd))
2046 {
2047 /* Generate keystrokes as if user had typed Ctrl-Break or
2048 Ctrl-C. */
2049 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
2050 keybd_event (vk_break_code, break_scan_code,
2051 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
2052 keybd_event (vk_break_code, break_scan_code,
2053 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
2054 | KEYEVENTF_KEYUP, 0);
2055 keybd_event (VK_CONTROL, control_scan_code,
2056 KEYEVENTF_KEYUP, 0);
2057
2058 /* Sleep for a bit to give time for Emacs frame to respond
2059 to focus change events (if Emacs was active app). */
2060 Sleep (100);
2061
2062 SetForegroundWindow (foreground_window);
2063 }
2064 /* Detach from the foreground and child threads now that
2065 the foreground switching is over. */
2066 if (foreground_thread)
2067 AttachThreadInput (GetCurrentThreadId (),
2068 foreground_thread, FALSE);
2069 if (child_thread)
2070 AttachThreadInput (GetCurrentThreadId (),
2071 child_thread, FALSE);
2072 }
2073 }
c519b5e1 2074 /* Ctrl-Break is NT equivalent of SIGINT. */
b2fc9f3d 2075 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
6cdfb6e6 2076 {
c519b5e1 2077 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
6cdfb6e6
RS
2078 "for pid %lu\n", GetLastError (), pid));
2079 errno = EINVAL;
c519b5e1 2080 rc = -1;
80874ef7 2081 }
6cdfb6e6
RS
2082 }
2083 else
2084 {
b2fc9f3d
GV
2085 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
2086 {
2087#if 1
417a7a0e 2088 if (os_subtype == OS_9X)
b2fc9f3d
GV
2089 {
2090/*
2091 Another possibility is to try terminating the VDM out-right by
2092 calling the Shell VxD (id 0x17) V86 interface, function #4
2093 "SHELL_Destroy_VM", ie.
2094
2095 mov edx,4
2096 mov ebx,vm_handle
2097 call shellapi
2098
2099 First need to determine the current VM handle, and then arrange for
2100 the shellapi call to be made from the system vm (by using
2101 Switch_VM_and_callback).
2102
2103 Could try to invoke DestroyVM through CallVxD.
2104
2105*/
ef79fbba 2106#if 0
b46a6a83 2107 /* On Windows 95, posting WM_QUIT causes the 16-bit subsystem
ef79fbba
GV
2108 to hang when cmdproxy is used in conjunction with
2109 command.com for an interactive shell. Posting
2110 WM_CLOSE pops up a dialog that, when Yes is selected,
2111 does the same thing. TerminateProcess is also less
2112 than ideal in that subprocesses tend to stick around
2113 until the machine is shutdown, but at least it
2114 doesn't freeze the 16-bit subsystem. */
b2fc9f3d 2115 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
ef79fbba
GV
2116#endif
2117 if (!TerminateProcess (proc_hand, 0xff))
2118 {
2119 DebPrint (("sys_kill.TerminateProcess returned %d "
2120 "for pid %lu\n", GetLastError (), pid));
2121 errno = EINVAL;
2122 rc = -1;
2123 }
b2fc9f3d
GV
2124 }
2125 else
2126#endif
2127 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
2128 }
fbd6baed 2129 /* Kill the process. On W32 this doesn't kill child processes
8eae7766 2130 so it doesn't work very well for shells which is why it's not
b2fc9f3d
GV
2131 used in every case. */
2132 else if (!TerminateProcess (proc_hand, 0xff))
6cdfb6e6 2133 {
c519b5e1 2134 DebPrint (("sys_kill.TerminateProcess returned %d "
6cdfb6e6
RS
2135 "for pid %lu\n", GetLastError (), pid));
2136 errno = EINVAL;
c519b5e1 2137 rc = -1;
6cdfb6e6
RS
2138 }
2139 }
c519b5e1
GV
2140
2141 if (need_to_free)
2142 CloseHandle (proc_hand);
2143
2144 return rc;
6cdfb6e6
RS
2145}
2146
c519b5e1
GV
2147/* The following two routines are used to manipulate stdin, stdout, and
2148 stderr of our child processes.
2149
2150 Assuming that in, out, and err are *not* inheritable, we make them
2151 stdin, stdout, and stderr of the child as follows:
2152
2153 - Save the parent's current standard handles.
2154 - Set the std handles to inheritable duplicates of the ones being passed in.
2155 (Note that _get_osfhandle() is an io.h procedure that retrieves the
2156 NT file handle for a crt file descriptor.)
2157 - Spawn the child, which inherits in, out, and err as stdin,
2158 stdout, and stderr. (see Spawnve)
2159 - Close the std handles passed to the child.
2160 - Reset the parent's standard handles to the saved handles.
2161 (see reset_standard_handles)
2162 We assume that the caller closes in, out, and err after calling us. */
2163
2164void
2165prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
6cdfb6e6 2166{
c519b5e1
GV
2167 HANDLE parent;
2168 HANDLE newstdin, newstdout, newstderr;
2169
2170 parent = GetCurrentProcess ();
2171
2172 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
2173 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
2174 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
2175
2176 /* make inheritable copies of the new handles */
177c0ea7 2177 if (!DuplicateHandle (parent,
c519b5e1
GV
2178 (HANDLE) _get_osfhandle (in),
2179 parent,
177c0ea7
JB
2180 &newstdin,
2181 0,
2182 TRUE,
c519b5e1
GV
2183 DUPLICATE_SAME_ACCESS))
2184 report_file_error ("Duplicating input handle for child", Qnil);
177c0ea7 2185
c519b5e1
GV
2186 if (!DuplicateHandle (parent,
2187 (HANDLE) _get_osfhandle (out),
2188 parent,
2189 &newstdout,
2190 0,
2191 TRUE,
2192 DUPLICATE_SAME_ACCESS))
2193 report_file_error ("Duplicating output handle for child", Qnil);
177c0ea7 2194
c519b5e1
GV
2195 if (!DuplicateHandle (parent,
2196 (HANDLE) _get_osfhandle (err),
2197 parent,
2198 &newstderr,
2199 0,
2200 TRUE,
2201 DUPLICATE_SAME_ACCESS))
2202 report_file_error ("Duplicating error handle for child", Qnil);
2203
2204 /* and store them as our std handles */
2205 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
2206 report_file_error ("Changing stdin handle", Qnil);
177c0ea7 2207
c519b5e1
GV
2208 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
2209 report_file_error ("Changing stdout handle", Qnil);
2210
2211 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
2212 report_file_error ("Changing stderr handle", Qnil);
2213}
2214
2215void
2216reset_standard_handles (int in, int out, int err, HANDLE handles[3])
2217{
2218 /* close the duplicated handles passed to the child */
2219 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
2220 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
2221 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
2222
2223 /* now restore parent's saved std handles */
2224 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
2225 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
2226 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
6cdfb6e6 2227}
c519b5e1 2228
b2fc9f3d
GV
2229void
2230set_process_dir (char * dir)
2231{
2232 process_dir = dir;
2233}
2234
a11e68d0
RS
2235/* To avoid problems with winsock implementations that work over dial-up
2236 connections causing or requiring a connection to exist while Emacs is
2237 running, Emacs no longer automatically loads winsock on startup if it
2238 is present. Instead, it will be loaded when open-network-stream is
2239 first called.
2240
2241 To allow full control over when winsock is loaded, we provide these
2242 two functions to dynamically load and unload winsock. This allows
2243 dial-up users to only be connected when they actually need to use
2244 socket services. */
2245
7684e57b 2246/* From w32.c */
a11e68d0
RS
2247extern HANDLE winsock_lib;
2248extern BOOL term_winsock (void);
2249extern BOOL init_winsock (int load_now);
2250
fbd6baed 2251DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
33f09670
JR
2252 doc: /* Test for presence of the Windows socket library `winsock'.
2253Returns non-nil if winsock support is present, nil otherwise.
2254
2255If the optional argument LOAD-NOW is non-nil, the winsock library is
2256also loaded immediately if not already loaded. If winsock is loaded,
2257the winsock local hostname is returned (since this may be different from
2258the value of `system-name' and should supplant it), otherwise t is
2259returned to indicate winsock support is present. */)
5842a27b 2260 (Lisp_Object load_now)
a11e68d0
RS
2261{
2262 int have_winsock;
2263
2264 have_winsock = init_winsock (!NILP (load_now));
2265 if (have_winsock)
2266 {
2267 if (winsock_lib != NULL)
2268 {
2269 /* Return new value for system-name. The best way to do this
2270 is to call init_system_name, saving and restoring the
2271 original value to avoid side-effects. */
2272 Lisp_Object orig_hostname = Vsystem_name;
2273 Lisp_Object hostname;
2274
2275 init_system_name ();
2276 hostname = Vsystem_name;
2277 Vsystem_name = orig_hostname;
2278 return hostname;
2279 }
2280 return Qt;
2281 }
2282 return Qnil;
2283}
2284
fbd6baed 2285DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
a11e68d0 2286 0, 0, 0,
33f09670
JR
2287 doc: /* Unload the Windows socket library `winsock' if loaded.
2288This is provided to allow dial-up socket connections to be disconnected
2289when no longer needed. Returns nil without unloading winsock if any
2290socket connections still exist. */)
5842a27b 2291 (void)
a11e68d0
RS
2292{
2293 return term_winsock () ? Qt : Qnil;
2294}
2295
93fdf2f8 2296\f
b2fc9f3d
GV
2297/* Some miscellaneous functions that are Windows specific, but not GUI
2298 specific (ie. are applicable in terminal or batch mode as well). */
2299
b2fc9f3d 2300DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
33f09670
JR
2301 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
2302If FILENAME does not exist, return nil.
2303All path elements in FILENAME are converted to their short names. */)
5842a27b 2304 (Lisp_Object filename)
b2fc9f3d
GV
2305{
2306 char shortname[MAX_PATH];
2307
b7826503 2308 CHECK_STRING (filename);
b2fc9f3d
GV
2309
2310 /* first expand it. */
2311 filename = Fexpand_file_name (filename, Qnil);
2312
2313 /* luckily, this returns the short version of each element in the path. */
b23077df 2314 if (GetShortPathName (SDATA (ENCODE_FILE (filename)), shortname, MAX_PATH) == 0)
b2fc9f3d
GV
2315 return Qnil;
2316
087fc47a 2317 dostounix_filename (shortname);
b2fc9f3d
GV
2318
2319 return build_string (shortname);
2320}
2321
2322
2323DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
2324 1, 1, 0,
33f09670
JR
2325 doc: /* Return the long file name version of the full path of FILENAME.
2326If FILENAME does not exist, return nil.
2327All path elements in FILENAME are converted to their long names. */)
5842a27b 2328 (Lisp_Object filename)
b2fc9f3d
GV
2329{
2330 char longname[ MAX_PATH ];
8dcaeba2 2331 int drive_only = 0;
b2fc9f3d 2332
b7826503 2333 CHECK_STRING (filename);
b2fc9f3d 2334
8dcaeba2
JR
2335 if (SBYTES (filename) == 2
2336 && *(SDATA (filename) + 1) == ':')
2337 drive_only = 1;
2338
b2fc9f3d
GV
2339 /* first expand it. */
2340 filename = Fexpand_file_name (filename, Qnil);
2341
b23077df 2342 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename)), longname, MAX_PATH))
b2fc9f3d
GV
2343 return Qnil;
2344
087fc47a 2345 dostounix_filename (longname);
b2fc9f3d 2346
8dcaeba2
JR
2347 /* If we were passed only a drive, make sure that a slash is not appended
2348 for consistency with directories. Allow for drive mapping via SUBST
2349 in case expand-file-name is ever changed to expand those. */
2350 if (drive_only && longname[1] == ':' && longname[2] == '/' && !longname[3])
2351 longname[2] = '\0';
2352
b23077df 2353 return DECODE_FILE (build_string (longname));
b2fc9f3d
GV
2354}
2355
33f09670
JR
2356DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
2357 Sw32_set_process_priority, 2, 2, 0,
2358 doc: /* Set the priority of PROCESS to PRIORITY.
2359If PROCESS is nil, the priority of Emacs is changed, otherwise the
2360priority of the process whose pid is PROCESS is changed.
2361PRIORITY should be one of the symbols high, normal, or low;
2362any other symbol will be interpreted as normal.
2363
2364If successful, the return value is t, otherwise nil. */)
5842a27b 2365 (Lisp_Object process, Lisp_Object priority)
b2fc9f3d
GV
2366{
2367 HANDLE proc_handle = GetCurrentProcess ();
2368 DWORD priority_class = NORMAL_PRIORITY_CLASS;
2369 Lisp_Object result = Qnil;
2370
b7826503 2371 CHECK_SYMBOL (priority);
b2fc9f3d
GV
2372
2373 if (!NILP (process))
2374 {
2375 DWORD pid;
2376 child_process *cp;
2377
b7826503 2378 CHECK_NUMBER (process);
b2fc9f3d
GV
2379
2380 /* Allow pid to be an internally generated one, or one obtained
b46a6a83 2381 externally. This is necessary because real pids on Windows 95 are
b2fc9f3d
GV
2382 negative. */
2383
2384 pid = XINT (process);
2385 cp = find_child_pid (pid);
2386 if (cp != NULL)
2387 pid = cp->procinfo.dwProcessId;
2388
2389 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
2390 }
2391
2392 if (EQ (priority, Qhigh))
2393 priority_class = HIGH_PRIORITY_CLASS;
2394 else if (EQ (priority, Qlow))
2395 priority_class = IDLE_PRIORITY_CLASS;
2396
2397 if (proc_handle != NULL)
2398 {
2399 if (SetPriorityClass (proc_handle, priority_class))
2400 result = Qt;
2401 if (!NILP (process))
2402 CloseHandle (proc_handle);
2403 }
2404
2405 return result;
2406}
2407
d613418b
EZ
2408#ifdef HAVE_LANGINFO_CODESET
2409/* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
b56ceb92
JB
2410char *
2411nl_langinfo (nl_item item)
d613418b
EZ
2412{
2413 /* Conversion of Posix item numbers to their Windows equivalents. */
2414 static const LCTYPE w32item[] = {
2415 LOCALE_IDEFAULTANSICODEPAGE,
2416 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
2417 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
2418 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
2419 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
2420 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
2421 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
2422 };
2423
2424 static char *nl_langinfo_buf = NULL;
2425 static int nl_langinfo_len = 0;
2426
2427 if (nl_langinfo_len <= 0)
2428 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
2429
2430 if (item < 0 || item >= _NL_NUM)
2431 nl_langinfo_buf[0] = 0;
2432 else
2433 {
2434 LCID cloc = GetThreadLocale ();
2435 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
2436 NULL, 0);
2437
2438 if (need_len <= 0)
2439 nl_langinfo_buf[0] = 0;
2440 else
2441 {
2442 if (item == CODESET)
2443 {
2444 need_len += 2; /* for the "cp" prefix */
2445 if (need_len < 8) /* for the case we call GetACP */
2446 need_len = 8;
2447 }
2448 if (nl_langinfo_len <= need_len)
2449 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
2450 nl_langinfo_len = need_len);
2451 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
2452 nl_langinfo_buf, nl_langinfo_len))
2453 nl_langinfo_buf[0] = 0;
2454 else if (item == CODESET)
2455 {
2456 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
2457 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
2458 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
2459 else
2460 {
2461 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
2462 strlen (nl_langinfo_buf) + 1);
2463 nl_langinfo_buf[0] = 'c';
2464 nl_langinfo_buf[1] = 'p';
2465 }
2466 }
2467 }
2468 }
2469 return nl_langinfo_buf;
2470}
2471#endif /* HAVE_LANGINFO_CODESET */
b2fc9f3d 2472
33f09670
JR
2473DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
2474 Sw32_get_locale_info, 1, 2, 0,
2475 doc: /* Return information about the Windows locale LCID.
2476By default, return a three letter locale code which encodes the default
35f36d65 2477language as the first two characters, and the country or regional variant
33f09670
JR
2478as the third letter. For example, ENU refers to `English (United States)',
2479while ENC means `English (Canadian)'.
2480
2481If the optional argument LONGFORM is t, the long form of the locale
2482name is returned, e.g. `English (United States)' instead; if LONGFORM
2483is a number, it is interpreted as an LCTYPE constant and the corresponding
2484locale information is returned.
2485
2486If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
5842a27b 2487 (Lisp_Object lcid, Lisp_Object longform)
b2fc9f3d
GV
2488{
2489 int got_abbrev;
2490 int got_full;
2491 char abbrev_name[32] = { 0 };
2492 char full_name[256] = { 0 };
2493
b7826503 2494 CHECK_NUMBER (lcid);
b2fc9f3d
GV
2495
2496 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2497 return Qnil;
2498
2499 if (NILP (longform))
2500 {
2501 got_abbrev = GetLocaleInfo (XINT (lcid),
2502 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2503 abbrev_name, sizeof (abbrev_name));
2504 if (got_abbrev)
2505 return build_string (abbrev_name);
2506 }
0eaf5926 2507 else if (EQ (longform, Qt))
b2fc9f3d
GV
2508 {
2509 got_full = GetLocaleInfo (XINT (lcid),
2510 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
2511 full_name, sizeof (full_name));
2512 if (got_full)
011a0143 2513 return DECODE_SYSTEM (build_string (full_name));
b2fc9f3d 2514 }
0eaf5926
GV
2515 else if (NUMBERP (longform))
2516 {
2517 got_full = GetLocaleInfo (XINT (lcid),
2518 XINT (longform),
2519 full_name, sizeof (full_name));
96512555
EZ
2520 /* GetLocaleInfo's return value includes the terminating null
2521 character, when the returned information is a string, whereas
2522 make_unibyte_string needs the string length without the
2523 terminating null. */
0eaf5926 2524 if (got_full)
96512555 2525 return make_unibyte_string (full_name, got_full - 1);
0eaf5926 2526 }
b2fc9f3d
GV
2527
2528 return Qnil;
2529}
2530
2531
33f09670
JR
2532DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
2533 Sw32_get_current_locale_id, 0, 0, 0,
2534 doc: /* Return Windows locale id for current locale setting.
2535This is a numerical value; use `w32-get-locale-info' to convert to a
2536human-readable form. */)
5842a27b 2537 (void)
b2fc9f3d
GV
2538{
2539 return make_number (GetThreadLocale ());
2540}
2541
24f981c9 2542static DWORD
b56ceb92 2543int_from_hex (char * s)
ef79fbba
GV
2544{
2545 DWORD val = 0;
2546 static char hex[] = "0123456789abcdefABCDEF";
2547 char * p;
2548
ed3751c8 2549 while (*s && (p = strchr (hex, *s)) != NULL)
ef79fbba
GV
2550 {
2551 unsigned digit = p - hex;
2552 if (digit > 15)
2553 digit -= 6;
2554 val = val * 16 + digit;
2555 s++;
2556 }
2557 return val;
2558}
2559
2560/* We need to build a global list, since the EnumSystemLocale callback
2561 function isn't given a context pointer. */
2562Lisp_Object Vw32_valid_locale_ids;
2563
24f981c9 2564static BOOL CALLBACK
b56ceb92 2565enum_locale_fn (LPTSTR localeNum)
ef79fbba
GV
2566{
2567 DWORD id = int_from_hex (localeNum);
2568 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
2569 return TRUE;
2570}
2571
33f09670
JR
2572DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2573 Sw32_get_valid_locale_ids, 0, 0, 0,
2574 doc: /* Return list of all valid Windows locale ids.
2575Each id is a numerical value; use `w32-get-locale-info' to convert to a
2576human-readable form. */)
5842a27b 2577 (void)
ef79fbba
GV
2578{
2579 Vw32_valid_locale_ids = Qnil;
2580
2581 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2582
2583 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2584 return Vw32_valid_locale_ids;
2585}
2586
b2fc9f3d
GV
2587
2588DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
33f09670
JR
2589 doc: /* Return Windows locale id for default locale setting.
2590By default, the system default locale setting is returned; if the optional
2591parameter USERP is non-nil, the user default locale setting is returned.
2592This is a numerical value; use `w32-get-locale-info' to convert to a
2593human-readable form. */)
5842a27b 2594 (Lisp_Object userp)
b2fc9f3d
GV
2595{
2596 if (NILP (userp))
2597 return make_number (GetSystemDefaultLCID ());
2598 return make_number (GetUserDefaultLCID ());
2599}
2600
177c0ea7 2601
b2fc9f3d 2602DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
33f09670
JR
2603 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2604If successful, the new locale id is returned, otherwise nil. */)
5842a27b 2605 (Lisp_Object lcid)
b2fc9f3d 2606{
b7826503 2607 CHECK_NUMBER (lcid);
b2fc9f3d
GV
2608
2609 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2610 return Qnil;
2611
2612 if (!SetThreadLocale (XINT (lcid)))
2613 return Qnil;
2614
ef79fbba
GV
2615 /* Need to set input thread locale if present. */
2616 if (dwWindowsThreadId)
2617 /* Reply is not needed. */
2618 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2619
b2fc9f3d
GV
2620 return make_number (GetThreadLocale ());
2621}
2622
0eaf5926
GV
2623
2624/* We need to build a global list, since the EnumCodePages callback
2625 function isn't given a context pointer. */
2626Lisp_Object Vw32_valid_codepages;
2627
24f981c9 2628static BOOL CALLBACK
b56ceb92 2629enum_codepage_fn (LPTSTR codepageNum)
0eaf5926
GV
2630{
2631 DWORD id = atoi (codepageNum);
2632 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2633 return TRUE;
2634}
2635
33f09670
JR
2636DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2637 Sw32_get_valid_codepages, 0, 0, 0,
2638 doc: /* Return list of all valid Windows codepages. */)
5842a27b 2639 (void)
0eaf5926
GV
2640{
2641 Vw32_valid_codepages = Qnil;
2642
2643 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2644
2645 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2646 return Vw32_valid_codepages;
2647}
2648
2649
33f09670
JR
2650DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2651 Sw32_get_console_codepage, 0, 0, 0,
2652 doc: /* Return current Windows codepage for console input. */)
5842a27b 2653 (void)
0eaf5926
GV
2654{
2655 return make_number (GetConsoleCP ());
2656}
2657
177c0ea7 2658
33f09670
JR
2659DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2660 Sw32_set_console_codepage, 1, 1, 0,
62356a1b
EZ
2661 doc: /* Make Windows codepage CP be the codepage for Emacs tty keyboard input.
2662This codepage setting affects keyboard input in tty mode.
33f09670 2663If successful, the new CP is returned, otherwise nil. */)
5842a27b 2664 (Lisp_Object cp)
0eaf5926 2665{
b7826503 2666 CHECK_NUMBER (cp);
0eaf5926
GV
2667
2668 if (!IsValidCodePage (XINT (cp)))
2669 return Qnil;
2670
2671 if (!SetConsoleCP (XINT (cp)))
2672 return Qnil;
2673
2674 return make_number (GetConsoleCP ());
2675}
2676
2677
33f09670
JR
2678DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2679 Sw32_get_console_output_codepage, 0, 0, 0,
2680 doc: /* Return current Windows codepage for console output. */)
5842a27b 2681 (void)
0eaf5926
GV
2682{
2683 return make_number (GetConsoleOutputCP ());
2684}
2685
177c0ea7 2686
33f09670
JR
2687DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2688 Sw32_set_console_output_codepage, 1, 1, 0,
62356a1b
EZ
2689 doc: /* Make Windows codepage CP be the codepage for Emacs console output.
2690This codepage setting affects display in tty mode.
33f09670 2691If successful, the new CP is returned, otherwise nil. */)
5842a27b 2692 (Lisp_Object cp)
0eaf5926 2693{
b7826503 2694 CHECK_NUMBER (cp);
0eaf5926
GV
2695
2696 if (!IsValidCodePage (XINT (cp)))
2697 return Qnil;
2698
2699 if (!SetConsoleOutputCP (XINT (cp)))
2700 return Qnil;
2701
2702 return make_number (GetConsoleOutputCP ());
2703}
2704
2705
33f09670
JR
2706DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2707 Sw32_get_codepage_charset, 1, 1, 0,
62356a1b 2708 doc: /* Return charset ID corresponding to codepage CP.
33f09670 2709Returns nil if the codepage is not valid. */)
5842a27b 2710 (Lisp_Object cp)
0eaf5926
GV
2711{
2712 CHARSETINFO info;
2713
b7826503 2714 CHECK_NUMBER (cp);
0eaf5926
GV
2715
2716 if (!IsValidCodePage (XINT (cp)))
2717 return Qnil;
2718
2719 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2720 return make_number (info.ciCharset);
2721
2722 return Qnil;
2723}
2724
2725
33f09670
JR
2726DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2727 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2728 doc: /* Return list of Windows keyboard languages and layouts.
2729The return value is a list of pairs of language id and layout id. */)
5842a27b 2730 (void)
0eaf5926
GV
2731{
2732 int num_layouts = GetKeyboardLayoutList (0, NULL);
2733 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2734 Lisp_Object obj = Qnil;
2735
2736 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2737 {
2738 while (--num_layouts >= 0)
2739 {
2740 DWORD kl = (DWORD) layouts[num_layouts];
2741
2742 obj = Fcons (Fcons (make_number (kl & 0xffff),
2743 make_number ((kl >> 16) & 0xffff)),
2744 obj);
2745 }
2746 }
2747
2748 return obj;
2749}
2750
2751
33f09670
JR
2752DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2753 Sw32_get_keyboard_layout, 0, 0, 0,
2754 doc: /* Return current Windows keyboard language and layout.
2755The return value is the cons of the language id and the layout id. */)
5842a27b 2756 (void)
0eaf5926
GV
2757{
2758 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2759
2760 return Fcons (make_number (kl & 0xffff),
2761 make_number ((kl >> 16) & 0xffff));
2762}
2763
177c0ea7 2764
33f09670
JR
2765DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2766 Sw32_set_keyboard_layout, 1, 1, 0,
2767 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2768The keyboard layout setting affects interpretation of keyboard input.
2769If successful, the new layout id is returned, otherwise nil. */)
5842a27b 2770 (Lisp_Object layout)
0eaf5926
GV
2771{
2772 DWORD kl;
2773
b7826503 2774 CHECK_CONS (layout);
f4532092
AI
2775 CHECK_NUMBER_CAR (layout);
2776 CHECK_NUMBER_CDR (layout);
0eaf5926 2777
8e713be6
KR
2778 kl = (XINT (XCAR (layout)) & 0xffff)
2779 | (XINT (XCDR (layout)) << 16);
0eaf5926
GV
2780
2781 /* Synchronize layout with input thread. */
2782 if (dwWindowsThreadId)
2783 {
2784 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2785 (WPARAM) kl, 0))
2786 {
2787 MSG msg;
2788 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2789
2790 if (msg.wParam == 0)
2791 return Qnil;
2792 }
2793 }
2794 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2795 return Qnil;
2796
2797 return Fw32_get_keyboard_layout ();
2798}
2799
b2fc9f3d 2800\f
b56ceb92
JB
2801void
2802syms_of_ntproc (void)
93fdf2f8 2803{
51128692
JR
2804 DEFSYM (Qhigh, "high");
2805 DEFSYM (Qlow, "low");
b2fc9f3d 2806
fbd6baed
GV
2807 defsubr (&Sw32_has_winsock);
2808 defsubr (&Sw32_unload_winsock);
7d701334 2809
b2fc9f3d
GV
2810 defsubr (&Sw32_short_file_name);
2811 defsubr (&Sw32_long_file_name);
2812 defsubr (&Sw32_set_process_priority);
2813 defsubr (&Sw32_get_locale_info);
2814 defsubr (&Sw32_get_current_locale_id);
2815 defsubr (&Sw32_get_default_locale_id);
ef79fbba 2816 defsubr (&Sw32_get_valid_locale_ids);
b2fc9f3d 2817 defsubr (&Sw32_set_current_locale);
a11e68d0 2818
0eaf5926
GV
2819 defsubr (&Sw32_get_console_codepage);
2820 defsubr (&Sw32_set_console_codepage);
2821 defsubr (&Sw32_get_console_output_codepage);
2822 defsubr (&Sw32_set_console_output_codepage);
2823 defsubr (&Sw32_get_valid_codepages);
2824 defsubr (&Sw32_get_codepage_charset);
2825
2826 defsubr (&Sw32_get_valid_keyboard_layouts);
2827 defsubr (&Sw32_get_keyboard_layout);
2828 defsubr (&Sw32_set_keyboard_layout);
2829
29208e82 2830 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args,
33f09670
JR
2831 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2832Because Windows does not directly pass argv arrays to child processes,
2833programs have to reconstruct the argv array by parsing the command
2834line string. For an argument to contain a space, it must be enclosed
2835in double quotes or it will be parsed as multiple arguments.
2836
2837If the value is a character, that character will be used to escape any
2838quote characters that appear, otherwise a suitable escape character
2839will be chosen based on the type of the program. */);
b2fc9f3d 2840 Vw32_quote_process_args = Qt;
817abdf6 2841
fbd6baed 2842 DEFVAR_LISP ("w32-start-process-show-window",
29208e82 2843 Vw32_start_process_show_window,
33f09670
JR
2844 doc: /* When nil, new child processes hide their windows.
2845When non-nil, they show their window in the method of their choice.
2846This variable doesn't affect GUI applications, which will never be hidden. */);
fbd6baed 2847 Vw32_start_process_show_window = Qnil;
0ecf7d36 2848
b2fc9f3d 2849 DEFVAR_LISP ("w32-start-process-share-console",
29208e82 2850 Vw32_start_process_share_console,
33f09670
JR
2851 doc: /* When nil, new child processes are given a new console.
2852When non-nil, they share the Emacs console; this has the limitation of
804d894a 2853allowing only one DOS subprocess to run at a time (whether started directly
33f09670
JR
2854or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2855subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2856otherwise respond to interrupts from Emacs. */);
b2fc9f3d
GV
2857 Vw32_start_process_share_console = Qnil;
2858
82e7c0a9 2859 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
29208e82 2860 Vw32_start_process_inherit_error_mode,
33f09670
JR
2861 doc: /* When nil, new child processes revert to the default error mode.
2862When non-nil, they inherit their error mode setting from Emacs, which stops
2863them blocking when trying to access unmounted drives etc. */);
82e7c0a9
AI
2864 Vw32_start_process_inherit_error_mode = Qt;
2865
29208e82 2866 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay,
33f09670
JR
2867 doc: /* Forced delay before reading subprocess output.
2868This is done to improve the buffering of subprocess output, by
2869avoiding the inefficiency of frequently reading small amounts of data.
2870
2871If positive, the value is the number of milliseconds to sleep before
2872reading the subprocess output. If negative, the magnitude is the number
2873of time slices to wait (effectively boosting the priority of the child
2874process temporarily). A value of zero disables waiting entirely. */);
5322f50b 2875 w32_pipe_read_delay = 50;
0c04091e 2876
29208e82 2877 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names,
33f09670
JR
2878 doc: /* Non-nil means convert all-upper case file names to lower case.
2879This applies when performing completions and file name expansion.
2880Note that the value of this setting also affects remote file names,
2881so you probably don't want to set to non-nil if you use case-sensitive
177c0ea7 2882filesystems via ange-ftp. */);
fbd6baed 2883 Vw32_downcase_file_names = Qnil;
b2fc9f3d
GV
2884
2885#if 0
29208e82 2886 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes,
33f09670
JR
2887 doc: /* Non-nil means attempt to fake realistic inode values.
2888This works by hashing the truename of files, and should detect
2889aliasing between long and short (8.3 DOS) names, but can have
4c36be58 2890false positives because of hash collisions. Note that determining
33f09670 2891the truename of a file can be slow. */);
b2fc9f3d
GV
2892 Vw32_generate_fake_inodes = Qnil;
2893#endif
2894
29208e82 2895 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes,
ed4c17bb
EZ
2896 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2897This option controls whether to issue additional system calls to determine
017dab84 2898accurate link counts, file type, and ownership information. It is more
ed4c17bb 2899useful for files on NTFS volumes, where hard links and file security are
017dab84 2900supported, than on volumes of the FAT family.
ed4c17bb
EZ
2901
2902Without these system calls, link count will always be reported as 1 and file
2903ownership will be attributed to the current user.
2904The default value `local' means only issue these system calls for files
2905on local fixed drives. A value of nil means never issue them.
2906Any other non-nil value means do this even on remote and removable drives
2907where the performance impact may be noticeable even on modern hardware. */);
2fa4f090 2908 Vw32_get_true_file_attributes = Qlocal;
af621bc3
EZ
2909
2910 staticpro (&Vw32_valid_locale_ids);
2911 staticpro (&Vw32_valid_codepages);
93fdf2f8 2912}
42a7e7f1 2913/* end of w32proc.c */