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