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