XEmacs 21.2.32 "Kastor & Polydeukes".
[chise/xemacs-chise.git.1] / src / ntproc.c
1 /* Process support for Windows NT port of XEMACS.
2    Copyright (C) 1992, 1995 Free Software Foundation, Inc.
3
4 This file is part of XEmacs.
5
6 XEmacs is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 XEmacs is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with XEmacs; see the file COPYING.  If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
20
21    Drew Bliss                   Oct 14, 1993
22      Adapted from alarm.c by Tim Fleehart */
23
24 /* Adapted for XEmacs by David Hobley <david@spook-le0.cia.com.au> */
25 /* Synced with FSF Emacs 19.34.6 by Marc Paquette <marcpa@cam.org> */
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <io.h>
31 #include <fcntl.h>
32 #include <signal.h>
33
34 /* must include CRT headers *before* config.h */
35 /* #### I don't believe it - martin */
36 #include <config.h>
37 #undef signal
38 #undef wait
39 #undef spawnve
40 #undef select
41 #undef kill
42
43 #include <windows.h>
44 #include <sys/socket.h>
45 #ifdef HAVE_A_OUT_H
46 #include <a.out.h>
47 #endif
48 #include "lisp.h"
49 #include "sysproc.h"
50 #include "nt.h"
51 #include "ntheap.h" /* From 19.34.6 */
52 #include "systime.h"
53 #include "syssignal.h"
54 #include "sysfile.h"
55 #include "syswait.h"
56 #include "buffer.h"
57 #include "process.h"
58
59 #include "console-msw.h"
60
61 /*#include "w32term.h"*/ /* From 19.34.6: sync in ? --marcpa */
62
63 /* #### I'm not going to play with shit. */
64 #pragma warning (disable:4013 4024 4090)
65
66 /* Control whether spawnve quotes arguments as necessary to ensure
67    correct parsing by child process.  Because not all uses of spawnve
68    are careful about constructing argv arrays, we make this behavior
69    conditional (off by default). */
70 Lisp_Object Vwin32_quote_process_args;
71
72 /* Control whether create_child causes the process' window to be
73    hidden.  The default is nil. */
74 Lisp_Object Vwin32_start_process_show_window;
75
76 /* Control whether create_child causes the process to inherit Emacs'
77    console window, or be given a new one of its own.  The default is
78    nil, to allow multiple DOS programs to run on Win95.  Having separate
79    consoles also allows Emacs to cleanly terminate process groups.  */
80 Lisp_Object Vwin32_start_process_share_console;
81
82 /* Time to sleep before reading from a subprocess output pipe - this
83    avoids the inefficiency of frequently reading small amounts of data.
84    This is primarily necessary for handling DOS processes on Windows 95,
85    but is useful for Win32 processes on both Win95 and NT as well.  */
86 Lisp_Object Vwin32_pipe_read_delay;
87
88 /* Control whether stat() attempts to generate fake but hopefully
89    "accurate" inode values, by hashing the absolute truenames of files.
90    This should detect aliasing between long and short names, but still
91    allows the possibility of hash collisions.  */
92 Lisp_Object Vwin32_generate_fake_inodes;
93
94 Lisp_Object Qhigh, Qlow;
95
96 extern Lisp_Object Vlisp_EXEC_SUFFIXES;
97
98 #ifndef DEBUG_XEMACS
99 __inline
100 #endif
101 void _DebPrint (const char *fmt, ...)
102 {
103 #ifdef DEBUG_XEMACS
104   char buf[1024];
105   va_list args;
106
107   va_start (args, fmt);
108   vsprintf (buf, fmt, args);
109   va_end (args);
110   OutputDebugString (buf);
111 #endif
112 }
113
114 /* sys_signal moved to nt.c. It's now called msw_signal... */
115
116 /* Defined in <process.h> which conflicts with the local copy */
117 #define _P_NOWAIT 1
118
119 /* Child process management list.  */
120 int child_proc_count = 0;
121 child_process child_procs[ MAX_CHILDREN ];
122 child_process *dead_child = NULL;
123
124 DWORD WINAPI reader_thread (void *arg);
125
126 /* Find an unused process slot.  */
127 child_process *
128 new_child (void)
129 {
130   child_process *cp;
131   DWORD id;
132   
133   for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
134     if (!CHILD_ACTIVE (cp))
135       goto Initialize;
136   if (child_proc_count == MAX_CHILDREN)
137     return NULL;
138   cp = &child_procs[child_proc_count++];
139
140  Initialize:
141   xzero (*cp);
142   cp->fd = -1;
143   cp->pid = -1;
144   if (cp->procinfo.hProcess)
145     CloseHandle(cp->procinfo.hProcess);
146   cp->procinfo.hProcess = NULL;
147   cp->status = STATUS_READ_ERROR;
148
149   /* use manual reset event so that select() will function properly */
150   cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
151   if (cp->char_avail)
152     {
153       cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
154       if (cp->char_consumed)
155         {
156           cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
157           if (cp->thrd)
158             return cp;
159         }
160     }
161   delete_child (cp);
162   return NULL;
163 }
164
165 void 
166 delete_child (child_process *cp)
167 {
168   int i;
169
170   /* Should not be deleting a child that is still needed. */
171   for (i = 0; i < MAXDESC; i++)
172     if (fd_info[i].cp == cp)
173       abort ();
174
175   if (!CHILD_ACTIVE (cp))
176     return;
177
178   /* reap thread if necessary */
179   if (cp->thrd)
180     {
181       DWORD rc;
182
183       if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
184         {
185           /* let the thread exit cleanly if possible */
186           cp->status = STATUS_READ_ERROR;
187           SetEvent (cp->char_consumed);
188           if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
189             {
190               DebPrint (("delete_child.WaitForSingleObject (thread) failed "
191                          "with %lu for fd %ld\n", GetLastError (), cp->fd));
192               TerminateThread (cp->thrd, 0);
193             }
194         }
195       CloseHandle (cp->thrd);
196       cp->thrd = NULL;
197     }
198   if (cp->char_avail)
199     {
200       CloseHandle (cp->char_avail);
201       cp->char_avail = NULL;
202     }
203   if (cp->char_consumed)
204     {
205       CloseHandle (cp->char_consumed);
206       cp->char_consumed = NULL;
207     }
208
209   /* update child_proc_count (highest numbered slot in use plus one) */
210   if (cp == child_procs + child_proc_count - 1)
211     {
212       for (i = child_proc_count-1; i >= 0; i--)
213         if (CHILD_ACTIVE (&child_procs[i]))
214           {
215             child_proc_count = i + 1;
216             break;
217           }
218     }
219   if (i < 0)
220     child_proc_count = 0;
221 }
222
223 /* Find a child by pid.  */
224 static child_process *
225 find_child_pid (DWORD pid)
226 {
227   child_process *cp;
228
229   for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
230     if (CHILD_ACTIVE (cp) && pid == cp->pid)
231       return cp;
232   return NULL;
233 }
234
235 /* Function to do blocking read of one byte, needed to implement
236    select.  It is only allowed on sockets and pipes. */
237 static int
238 _sys_read_ahead (int fd)
239 {
240   child_process * cp;
241   int rc = 0;
242
243   if (fd < 0 || fd >= MAXDESC)
244     return STATUS_READ_ERROR;
245
246   cp = fd_info[fd].cp;
247
248   if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
249     return STATUS_READ_ERROR;
250
251   if ((fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET)) == 0
252       || (fd_info[fd].flags & FILE_READ) == 0)
253     {
254       /* fd is not a pipe or socket */
255       abort ();
256     }
257   
258   cp->status = STATUS_READ_IN_PROGRESS;
259   
260   if (fd_info[fd].flags & FILE_PIPE)
261     {
262       rc = _read (fd, &cp->chr, sizeof (char));
263
264       /* Give subprocess time to buffer some more output for us before
265          reporting that input is available; we need this because Win95
266          connects DOS programs to pipes by making the pipe appear to be
267          the normal console stdout - as a result most DOS programs will
268          write to stdout without buffering, ie.  one character at a
269          time.  Even some Win32 programs do this - "dir" in a command
270          shell on NT is very slow if we don't do this. */
271       if (rc > 0)
272         {
273           int wait = XINT (Vwin32_pipe_read_delay);
274
275           if (wait > 0)
276             Sleep (wait);
277           else if (wait < 0)
278             while (++wait <= 0)
279               /* Yield remainder of our time slice, effectively giving a
280                  temporary priority boost to the child process. */
281               Sleep (0);
282         }
283     }
284
285   if (rc == sizeof (char))
286     cp->status = STATUS_READ_SUCCEEDED;
287   else
288     cp->status = STATUS_READ_FAILED;
289
290   return cp->status;
291 }
292
293 /* Thread proc for child process and socket reader threads. Each thread
294    is normally blocked until woken by select() to check for input by
295    reading one char.  When the read completes, char_avail is signalled
296    to wake up the select emulator and the thread blocks itself again. */
297 DWORD WINAPI 
298 reader_thread (void *arg)
299 {
300   child_process *cp;
301   
302   /* Our identity */
303   cp = (child_process *)arg;
304   
305   /* <matts@tibco.com> - I think the test below is wrong - we don't
306      want to wait for someone to signal char_consumed, as we haven't
307      read anything for them to consume yet! */
308
309   /*
310   if (cp == NULL ||
311       WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
312   */
313
314   if (cp == NULL)
315   {
316       return 1;
317   }
318
319   for (;;)
320     {
321       int rc;
322
323       rc = _sys_read_ahead (cp->fd);
324
325       /* The name char_avail is a misnomer - it really just means the
326          read-ahead has completed, whether successfully or not. */
327       if (!SetEvent (cp->char_avail))
328         {
329           DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
330                      GetLastError (), cp->fd));
331           return 1;
332         }
333
334       if (rc == STATUS_READ_ERROR)
335       {
336         /* We are finished, so clean up handles and set to NULL so
337            that CHILD_ACTIVE will see what is going on */
338         if (cp->char_avail) {
339           CloseHandle (cp->char_avail);
340           cp->char_avail = NULL;
341         }
342         if (cp->thrd) {
343           CloseHandle (cp->thrd);
344           cp->thrd = NULL;
345         }
346         if (cp->char_consumed) {
347           CloseHandle(cp->char_consumed);
348           cp->char_consumed = NULL;
349         }
350         if (cp->procinfo.hProcess)
351         {
352           CloseHandle (cp->procinfo.hProcess);
353           cp->procinfo.hProcess=NULL;
354         }
355         return 1;
356       }
357         
358       /* If the read died, the child has died so let the thread die */
359       if (rc == STATUS_READ_FAILED)
360         break;
361         
362       /* Wait until our input is acknowledged before reading again */
363       if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
364         {
365           DebPrint (("reader_thread.WaitForSingleObject failed with "
366                      "%lu for fd %ld\n", GetLastError (), cp->fd));
367           break;
368         }
369     }
370   /* We are finished, so clean up handles and set to NULL so that
371      CHILD_ACTIVE will see what is going on */
372   if (cp->char_avail) {
373     CloseHandle (cp->char_avail);
374     cp->char_avail = NULL;
375   }
376   if (cp->thrd) {
377     CloseHandle (cp->thrd);
378     cp->thrd = NULL;
379   }
380   if (cp->char_consumed) {
381     CloseHandle(cp->char_consumed);
382     cp->char_consumed = NULL;
383   }
384   if (cp->procinfo.hProcess)
385   {
386     CloseHandle (cp->procinfo.hProcess);
387     cp->procinfo.hProcess=NULL;
388   }
389   
390   return 0;
391 }
392
393 /* To avoid Emacs changing directory, we just record here the directory
394    the new process should start in.  This is set just before calling
395    sys_spawnve, and is not generally valid at any other time.  */
396 static const char * process_dir;
397
398 static BOOL 
399 create_child (const char *exe, char *cmdline, char *env,
400               int * pPid, child_process *cp)
401 {
402   STARTUPINFO start;
403   SECURITY_ATTRIBUTES sec_attrs;
404   SECURITY_DESCRIPTOR sec_desc;
405   char dir[ MAXPATHLEN ];
406   
407   if (cp == NULL) abort ();
408   
409   xzero (start);
410   start.cb = sizeof (start);
411   
412 #ifdef HAVE_NTGUI
413   if (NILP (Vwin32_start_process_show_window))
414   start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
415   else
416     start.dwFlags = STARTF_USESTDHANDLES;
417   start.wShowWindow = SW_HIDE;
418
419   start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
420   start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
421   start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
422 #endif /* HAVE_NTGUI */
423
424   /* Explicitly specify no security */
425   if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
426     goto EH_Fail;
427   if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
428     goto EH_Fail;
429   sec_attrs.nLength = sizeof (sec_attrs);
430   sec_attrs.lpSecurityDescriptor = &sec_desc;
431   sec_attrs.bInheritHandle = FALSE;
432   
433   strcpy (dir, process_dir);
434   unixtodos_filename (dir);
435   
436   if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
437                       (!NILP (Vwin32_start_process_share_console)
438                        ? CREATE_NEW_PROCESS_GROUP
439                        : CREATE_NEW_CONSOLE),
440                       env, dir,
441                       &start, &cp->procinfo))
442     goto EH_Fail;
443
444   cp->pid = (int) cp->procinfo.dwProcessId;
445
446   CloseHandle (cp->procinfo.hThread);
447   CloseHandle (cp->procinfo.hProcess);
448   cp->procinfo.hThread=NULL;
449   cp->procinfo.hProcess=NULL;
450
451   /* pid must fit in a Lisp_Int */
452
453
454   *pPid = cp->pid;
455   
456   return TRUE;
457   
458  EH_Fail:
459   DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
460   return FALSE;
461 }
462
463 #ifndef __MINGW32__
464 /* Return pointer to section header for section containing the given
465    relative virtual address. */
466 static IMAGE_SECTION_HEADER *
467 rva_to_section (DWORD rva, IMAGE_NT_HEADERS * nt_header)
468 {
469   PIMAGE_SECTION_HEADER section;
470   int i;
471
472   section = IMAGE_FIRST_SECTION (nt_header);
473
474   for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
475     {
476       if (rva >= section->VirtualAddress
477           && rva < section->VirtualAddress + section->SizeOfRawData)
478         return section;
479       section++;
480     }
481   return NULL;
482 }
483 #endif
484
485 void
486 win32_executable_type (const char * filename, int * is_dos_app, int * is_cygnus_app)
487 {
488   file_data executable;
489   char * p;
490
491   /* Default values in case we can't tell for sure.  */
492   *is_dos_app = FALSE;
493   *is_cygnus_app = FALSE;
494
495   if (!open_input_file (&executable, filename))
496     return;
497
498   p = strrchr (filename, '.');
499
500       /* We can only identify DOS .com programs from the extension. */
501       if (p && stricmp (p, ".com") == 0)
502     *is_dos_app = TRUE;
503   else if (p && (stricmp (p, ".bat") == 0 ||
504                  stricmp (p, ".cmd") == 0))
505     {
506       /* A DOS shell script - it appears that CreateProcess is happy to
507          accept this (somewhat surprisingly); presumably it looks at
508          COMSPEC to determine what executable to actually invoke.
509              Therefore, we have to do the same here as well. */
510       /* Actually, I think it uses the program association for that
511          extension, which is defined in the registry.  */
512       p = egetenv ("COMSPEC");
513       if (p)
514         win32_executable_type (p, is_dos_app, is_cygnus_app);
515     }
516       else
517         {
518       /* Look for DOS .exe signature - if found, we must also check that
519          it isn't really a 16- or 32-bit Windows exe, since both formats
520          start with a DOS program stub.  Note that 16-bit Windows
521          executables use the OS/2 1.x format. */
522
523 #ifdef __MINGW32__
524           /* mingw32 doesn't have enough headers to detect cygwin
525              apps, just do what we can. */
526           FILHDR * exe_header;
527
528           exe_header = (FILHDR*) executable.file_base;
529           if (exe_header->e_magic != DOSMAGIC)
530             goto unwind;
531
532           if ((char*) exe_header->e_lfanew > (char*) executable.size)
533             {
534               /* Some dos headers (pkunzip) have bogus e_lfanew fields.  */
535               *is_dos_app = TRUE;
536             } 
537           else if (exe_header->nt_signature != NT_SIGNATURE)
538             {
539               *is_dos_app = TRUE;
540             }
541 #else
542           IMAGE_DOS_HEADER * dos_header;
543           IMAGE_NT_HEADERS * nt_header;
544
545           dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
546           if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
547             goto unwind;
548           
549           nt_header = (PIMAGE_NT_HEADERS) ((char*) dos_header + dos_header->e_lfanew);
550           
551           if ((char*) nt_header > (char*) dos_header + executable.size) 
552             {
553               /* Some dos headers (pkunzip) have bogus e_lfanew fields.  */
554               *is_dos_app = TRUE;
555             } 
556           else if (nt_header->Signature != IMAGE_NT_SIGNATURE &&
557                    LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
558             {
559               *is_dos_app = TRUE;
560             }
561           else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
562             {
563               /* Look for cygwin.dll in DLL import list. */
564               IMAGE_DATA_DIRECTORY import_dir =
565                 nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
566               IMAGE_IMPORT_DESCRIPTOR * imports;
567               IMAGE_SECTION_HEADER * section;
568
569               section = rva_to_section (import_dir.VirtualAddress, nt_header);
570               imports = (IMAGE_IMPORT_DESCRIPTOR *) RVA_TO_PTR (import_dir.VirtualAddress,
571                                                                 section, executable);
572               
573               for ( ; imports->Name; imports++)
574                 {
575                   char *dllname = (char*) RVA_TO_PTR (imports->Name, section, executable);
576
577                   if (strcmp (dllname, "cygwin.dll") == 0)
578                     {
579                       *is_cygnus_app = TRUE;
580                       break;
581                     }
582                 }
583             }
584 #endif
585         }
586
587  unwind:
588       close_file_data (&executable);
589 }
590
591 int
592 compare_env (const void *strp1, const void *strp2)
593 {
594   const char *str1 = *(const char**)strp1, *str2 = *(const char**)strp2;
595
596   while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
597     {
598       if ((*str1) > (*str2))
599         return 1;
600       else if ((*str1) < (*str2))
601         return -1;
602       str1++, str2++;
603     }
604
605   if (*str1 == '=' && *str2 == '=')
606     return 0;
607   else if (*str1 == '=')
608     return -1;
609   else
610     return 1;
611 }
612
613 void
614 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
615 {
616   char **optr, **nptr;
617   int num;
618
619   nptr = new_envp;
620   optr = envp1;
621   while (*optr)
622     *nptr++ = *optr++;
623   num = optr - envp1;
624
625   optr = envp2;
626   while (*optr)
627     *nptr++ = *optr++;
628   num += optr - envp2;
629
630   qsort (new_envp, num, sizeof (char*), compare_env);
631
632   *nptr = NULL;
633 }
634
635 /* When a new child process is created we need to register it in our list,
636    so intercept spawn requests.  */
637 int 
638 sys_spawnve (int mode, const char *cmdname,
639              const char * const *argv, const char *const *envp)
640 {
641   Lisp_Object program, full;
642   char *cmdline, *env, *parg, **targ;
643   int arglen, numenv;
644   int pid;
645   child_process *cp;
646   int is_dos_app, is_cygnus_app;
647   int do_quoting = 0;
648   char escape_char = 0;
649   /* We pass our process ID to our children by setting up an environment
650      variable in their environment.  */
651   char ppid_env_var_buffer[64];
652   char *extra_env[] = {ppid_env_var_buffer, NULL};
653   struct gcpro gcpro1;
654     
655   /* We don't care about the other modes */
656   if (mode != _P_NOWAIT)
657     {
658       errno = EINVAL;
659       return -1;
660     }
661
662   /* Handle executable names without an executable suffix.  */
663   program = make_string (cmdname, strlen (cmdname));
664   GCPRO1 (program);
665   if (NILP (Ffile_executable_p (program)))
666     {
667       full = Qnil;
668       locate_file (Vexec_path, program, Vlisp_EXEC_SUFFIXES, &full, 1);
669       if (NILP (full))
670         {
671           UNGCPRO;
672           errno = EINVAL;
673           return -1;
674         }
675       TO_EXTERNAL_FORMAT (LISP_STRING, full,
676                           C_STRING_ALLOCA, cmdname,
677                           Qfile_name);
678     }
679   else
680     {
681       cmdname = (char*)alloca (strlen (argv[0]) + 1);
682       strcpy ((char*)cmdname, argv[0]);
683     }
684   UNGCPRO;
685
686   /* make sure argv[0] and cmdname are both in DOS format */
687   unixtodos_filename ((char*)cmdname);
688   /* #### KLUDGE */
689   ((const char**)argv)[0] = cmdname;
690
691   /* Determine whether program is a 16-bit DOS executable, or a Win32
692      executable that is implicitly linked to the Cygnus dll (implying it
693      was compiled with the Cygnus GNU toolchain and hence relies on
694      cygwin.dll to parse the command line - we use this to decide how to
695      escape quote chars in command line args that must be quoted). */
696   win32_executable_type (cmdname, &is_dos_app, &is_cygnus_app);
697
698   /* On Windows 95, if cmdname is a DOS app, we invoke a helper
699      application to start it by specifying the helper app as cmdname,
700      while leaving the real app name as argv[0].  */
701   if (is_dos_app)
702     {
703       cmdname = (char*) alloca (MAXPATHLEN);
704       if (egetenv ("CMDPROXY"))
705         strcpy ((char*)cmdname, egetenv ("CMDPROXY"));
706       else
707     {
708           strcpy ((char*)cmdname, XSTRING_DATA (Vinvocation_directory));
709           strcat ((char*)cmdname, "cmdproxy.exe");
710         }
711       unixtodos_filename ((char*)cmdname);
712     }
713   
714   /* we have to do some conjuring here to put argv and envp into the
715      form CreateProcess wants...  argv needs to be a space separated/null
716      terminated list of parameters, and envp is a null
717      separated/double-null terminated list of parameters.
718
719      Additionally, zero-length args and args containing whitespace or
720      quote chars need to be wrapped in double quotes - for this to work,
721      embedded quotes need to be escaped as well.  The aim is to ensure
722      the child process reconstructs the argv array we start with
723      exactly, so we treat quotes at the beginning and end of arguments
724      as embedded quotes.
725
726      The Win32 GNU-based library from Cygnus doubles quotes to escape
727      them, while MSVC uses backslash for escaping.  (Actually the MSVC
728      startup code does attempt to recognize doubled quotes and accept
729      them, but gets it wrong and ends up requiring three quotes to get a
730      single embedded quote!)  So by default we decide whether to use
731      quote or backslash as the escape character based on whether the
732      binary is apparently a Cygnus compiled app.
733
734      Note that using backslash to escape embedded quotes requires
735      additional special handling if an embedded quote is already
736      preceded by backslash, or if an arg requiring quoting ends with
737      backslash.  In such cases, the run of escape characters needs to be
738      doubled.  For consistency, we apply this special handling as long
739      as the escape character is not quote.
740    
741      Since we have no idea how large argv and envp are likely to be we
742      figure out list lengths on the fly and allocate them.  */
743   
744   if (!NILP (Vwin32_quote_process_args))
745     {
746       do_quoting = 1;
747       /* Override escape char by binding win32-quote-process-args to
748          desired character, or use t for auto-selection.  */
749       if (INTP (Vwin32_quote_process_args))
750         escape_char = (char) XINT (Vwin32_quote_process_args);
751       else
752         escape_char = is_cygnus_app ? '"' : '\\';
753     }
754   
755   /* do argv...  */
756   arglen = 0;
757   targ = (char**)argv;
758   while (*targ)
759     {
760       char * p = *targ;
761       int need_quotes = 0;
762       int escape_char_run = 0;
763
764       if (*p == 0)
765         need_quotes = 1;
766       for ( ; *p; p++)
767         {
768           if (*p == '"')
769           {
770               /* allow for embedded quotes to be escaped */
771             arglen++;
772               need_quotes = 1;
773               /* handle the case where the embedded quote is already escaped */
774               if (escape_char_run > 0)
775                 {
776                   /* To preserve the arg exactly, we need to double the
777                      preceding escape characters (plus adding one to
778                      escape the quote character itself).  */
779                   arglen += escape_char_run;
780           }
781             }
782       else if (*p == ' ' || *p == '\t')
783             {
784               need_quotes = 1;
785             }
786
787           if (*p == escape_char && escape_char != '"')
788             escape_char_run++;
789           else
790             escape_char_run = 0;
791         }
792       if (need_quotes)
793         {
794         arglen += 2;
795           /* handle the case where the arg ends with an escape char - we
796              must not let the enclosing quote be escaped.  */
797           if (escape_char_run > 0)
798             arglen += escape_char_run;
799         }
800       arglen += strlen (*targ++) + 1;
801     }
802   cmdline = (char*) alloca (arglen);
803   targ = (char**)argv;
804   parg = cmdline;
805   while (*targ)
806     {
807       char * p = *targ;
808       int need_quotes = 0;
809
810       if (*p == 0)
811         need_quotes = 1;
812
813       if (do_quoting)
814         {
815           for ( ; *p; p++)
816             if (*p == ' ' || *p == '\t' || *p == '"')
817               need_quotes = 1;
818         }
819       if (need_quotes)
820         {
821           int escape_char_run = 0;
822           char * first;
823           char * last;
824
825           p = *targ;
826           first = p;
827           last = p + strlen (p) - 1;
828           *parg++ = '"';
829 #if 0
830           /* This version does not escape quotes if they occur at the
831              beginning or end of the arg - this could lead to incorrect
832              behavior when the arg itself represents a command line
833              containing quoted args.  I believe this was originally done
834              as a hack to make some things work, before
835              `win32-quote-process-args' was added.  */
836           while (*p)
837             {
838               if (*p == '"' && p > first && p < last)
839                 *parg++ = escape_char;  /* escape embedded quotes */
840               *parg++ = *p++;
841             }
842 #else
843           for ( ; *p; p++)
844             {
845               if (*p == '"')
846                 {
847                   /* double preceding escape chars if any */
848                   while (escape_char_run > 0)
849                     {
850                       *parg++ = escape_char;
851                       escape_char_run--;
852                     }
853                   /* escape all quote chars, even at beginning or end */
854                   *parg++ = escape_char;
855                 }
856               *parg++ = *p;
857
858               if (*p == escape_char && escape_char != '"')
859                 escape_char_run++;
860               else
861                 escape_char_run = 0;
862             }
863           /* double escape chars before enclosing quote */
864           while (escape_char_run > 0)
865             {
866               *parg++ = escape_char;
867               escape_char_run--;
868             }
869 #endif
870           *parg++ = '"';
871         }
872       else
873         {
874           strcpy (parg, *targ);
875           parg += strlen (*targ);
876         }
877       *parg++ = ' ';
878       targ++;
879     }
880   *--parg = '\0';
881   
882   /* and envp...  */
883   arglen = 1;
884   targ = (char**) envp;
885   numenv = 1; /* for end null */
886   while (*targ)
887     {
888       arglen += strlen (*targ++) + 1;
889       numenv++;
890     }
891   /* extra env vars... */
892   sprintf (ppid_env_var_buffer, "__PARENT_PROCESS_ID=%d", 
893            GetCurrentProcessId ());
894   arglen += strlen (ppid_env_var_buffer) + 1;
895   numenv++;
896
897   /* merge env passed in and extra env into one, and sort it.  */
898   targ = (char **) alloca (numenv * sizeof (char*));
899   merge_and_sort_env ((char**) envp, extra_env, targ);
900
901   /* concatenate env entries.  */
902   env = (char*) alloca (arglen);
903   parg = env;
904   while (*targ)
905     {
906       strcpy (parg, *targ);
907       parg += strlen (*targ++);
908       *parg++ = '\0';
909     }
910   *parg++ = '\0';
911   *parg = '\0';
912
913   cp = new_child ();
914   if (cp == NULL)
915     {
916       errno = EAGAIN;
917       return -1;
918     }
919   
920   /* Now create the process.  */
921   if (!create_child (cmdname, cmdline, env, &pid, cp))
922     {
923       delete_child (cp);
924       errno = ENOEXEC;
925       return -1;
926     }
927
928   return pid;
929 }
930
931 /* Substitute for certain kill () operations */
932
933 static BOOL CALLBACK
934 find_child_console (HWND hwnd, child_process * cp)
935 {
936   DWORD thread_id;
937   DWORD process_id;
938
939   thread_id = GetWindowThreadProcessId (hwnd, &process_id);
940   if (process_id == cp->procinfo.dwProcessId)
941     {
942       char window_class[32];
943
944       GetClassName (hwnd, window_class, sizeof (window_class));
945       if (strcmp (window_class,
946                   msw_windows9x_p()
947                   ? "tty"
948                   : "ConsoleWindowClass") == 0)
949         {
950           cp->hwnd = hwnd;
951           return FALSE;
952         }
953     }
954   /* keep looking */
955   return TRUE;
956 }
957
958 int 
959 sys_kill (int pid, int sig)
960 {
961   child_process *cp;
962   HANDLE proc_hand;
963   int need_to_free = 0;
964   int rc = 0;
965   
966   /* Only handle signals that will result in the process dying */
967   if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
968     {
969       errno = EINVAL;
970       return -1;
971     }
972
973   cp = find_child_pid (pid);
974   if (cp == NULL)
975     {
976       proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
977       if (proc_hand == NULL)
978         {
979           errno = EPERM;
980           return -1;
981         }
982       need_to_free = 1;
983     }
984   else
985     {
986       proc_hand = cp->procinfo.hProcess;
987       pid = cp->procinfo.dwProcessId;
988
989       /* Try to locate console window for process. */
990       EnumWindows ((WNDENUMPROC)find_child_console, (LPARAM) cp);
991     }
992   
993   if (sig == SIGINT)
994     {
995       if (NILP (Vwin32_start_process_share_console) && cp && cp->hwnd)
996         {
997           BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
998           BYTE vk_break_code = VK_CANCEL;
999           BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1000           HWND foreground_window;
1001
1002           if (break_scan_code == 0)
1003             {
1004               /* Fake Ctrl-C if we can't manage Ctrl-Break. */
1005               vk_break_code = 'C';
1006               break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1007             }
1008
1009           foreground_window = GetForegroundWindow ();
1010           if (foreground_window && SetForegroundWindow (cp->hwnd))
1011             {
1012               /* Generate keystrokes as if user had typed Ctrl-Break or Ctrl-C.  */
1013               keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1014               keybd_event (vk_break_code, break_scan_code, 0, 0);
1015               keybd_event (vk_break_code, break_scan_code, KEYEVENTF_KEYUP, 0);
1016               keybd_event (VK_CONTROL, control_scan_code, KEYEVENTF_KEYUP, 0);
1017
1018               /* Sleep for a bit to give time for Emacs frame to respond
1019                  to focus change events (if Emacs was active app).  */
1020               Sleep (10);
1021
1022               SetForegroundWindow (foreground_window);
1023             }
1024         }
1025       /* Ctrl-Break is NT equivalent of SIGINT.  */
1026       else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1027         {
1028           DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1029                      "for pid %lu\n", GetLastError (), pid));
1030           errno = EINVAL;
1031           rc = -1;
1032         }
1033     }
1034   else
1035     {
1036       if (NILP (Vwin32_start_process_share_console) && cp && cp->hwnd)
1037         {
1038 #if 1
1039           if (msw_windows9x_p())
1040             {
1041 /*
1042    Another possibility is to try terminating the VDM out-right by
1043    calling the Shell VxD (id 0x17) V86 interface, function #4
1044    "SHELL_Destroy_VM", ie.
1045
1046      mov edx,4
1047      mov ebx,vm_handle
1048      call shellapi
1049
1050    First need to determine the current VM handle, and then arrange for
1051    the shellapi call to be made from the system vm (by using
1052    Switch_VM_and_callback).
1053
1054    Could try to invoke DestroyVM through CallVxD.
1055
1056 */
1057 #if 0
1058               /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1059                  to hang when cmdproxy is used in conjunction with
1060                  command.com for an interactive shell.  Posting
1061                  WM_CLOSE pops up a dialog that, when Yes is selected,
1062                  does the same thing.  TerminateProcess is also less
1063                  than ideal in that subprocesses tend to stick around
1064                  until the machine is shutdown, but at least it
1065                  doesn't freeze the 16-bit subsystem.  */
1066               PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1067 #endif
1068               if (!TerminateProcess (proc_hand, 0xff))
1069                 {
1070                   DebPrint (("sys_kill.TerminateProcess returned %d "
1071                              "for pid %lu\n", GetLastError (), pid));
1072                   errno = EINVAL;
1073                   rc = -1;
1074                 }
1075             }
1076           else
1077 #endif
1078             PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1079         }
1080       /* Kill the process.  On Win32 this doesn't kill child processes
1081          so it doesn't work very well for shells which is why it's not
1082          used in every case.  */
1083       else if (!TerminateProcess (proc_hand, 0xff))
1084         {
1085           DebPrint (("sys_kill.TerminateProcess returned %d "
1086                      "for pid %lu\n", GetLastError (), pid));
1087           errno = EINVAL;
1088           rc = -1;
1089         }
1090     }
1091
1092   if (need_to_free)
1093     CloseHandle (proc_hand);
1094
1095   return rc;
1096 }
1097
1098 #if 0
1099 /* Sync with FSF Emacs 19.34.6 note: ifdef'ed out in XEmacs */
1100 extern int report_file_error (const char *, Lisp_Object);
1101 #endif
1102 /* The following two routines are used to manipulate stdin, stdout, and
1103    stderr of our child processes.
1104
1105    Assuming that in, out, and err are *not* inheritable, we make them
1106    stdin, stdout, and stderr of the child as follows:
1107
1108    - Save the parent's current standard handles.
1109    - Set the std handles to inheritable duplicates of the ones being passed in.
1110      (Note that _get_osfhandle() is an io.h procedure that retrieves the
1111      NT file handle for a crt file descriptor.)
1112    - Spawn the child, which inherits in, out, and err as stdin,
1113      stdout, and stderr. (see Spawnve)
1114    - Close the std handles passed to the child.
1115    - Reset the parent's standard handles to the saved handles.
1116      (see reset_standard_handles)
1117    We assume that the caller closes in, out, and err after calling us.  */
1118
1119 void
1120 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1121 {
1122   HANDLE parent;
1123   HANDLE newstdin, newstdout, newstderr;
1124
1125   parent = GetCurrentProcess ();
1126
1127   handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1128   handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1129   handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1130
1131   /* make inheritable copies of the new handles */
1132   if (!DuplicateHandle (parent, 
1133                        (HANDLE) _get_osfhandle (in),
1134                        parent,
1135                        &newstdin, 
1136                        0, 
1137                        TRUE, 
1138                        DUPLICATE_SAME_ACCESS))
1139     report_file_error ("Duplicating input handle for child", Qnil);
1140   
1141   if (!DuplicateHandle (parent,
1142                        (HANDLE) _get_osfhandle (out),
1143                        parent,
1144                        &newstdout,
1145                        0,
1146                        TRUE,
1147                        DUPLICATE_SAME_ACCESS))
1148     report_file_error ("Duplicating output handle for child", Qnil);
1149   
1150   if (!DuplicateHandle (parent,
1151                        (HANDLE) _get_osfhandle (err),
1152                        parent,
1153                        &newstderr,
1154                        0,
1155                        TRUE,
1156                        DUPLICATE_SAME_ACCESS))
1157     report_file_error ("Duplicating error handle for child", Qnil);
1158
1159   /* and store them as our std handles */
1160   if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1161     report_file_error ("Changing stdin handle", Qnil);
1162   
1163   if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1164     report_file_error ("Changing stdout handle", Qnil);
1165
1166   if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1167     report_file_error ("Changing stderr handle", Qnil);
1168 }
1169
1170 void
1171 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1172 {
1173   /* close the duplicated handles passed to the child */
1174   CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1175   CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1176   CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1177
1178   /* now restore parent's saved std handles */
1179   SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1180   SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1181   SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1182 }
1183
1184 void
1185 set_process_dir (const char * dir)
1186 {
1187   process_dir = dir;
1188 }
1189 \f
1190 /* Some miscellaneous functions that are Windows specific, but not GUI
1191    specific (ie. are applicable in terminal or batch mode as well).  */
1192
1193 /* lifted from fileio.c  */
1194 #define CORRECT_DIR_SEPS(s) \
1195   do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1196        else unixtodos_filename (s); \
1197   } while (0)
1198
1199 DEFUN ("win32-short-file-name", Fwin32_short_file_name, 1, 1, "", /*
1200   Return the short file name version (8.3) of the full path of FILENAME.
1201 If FILENAME does not exist, return nil.
1202 All path elements in FILENAME are converted to their short names.
1203 */
1204        (filename))
1205 {
1206   char shortname[MAX_PATH];
1207
1208   CHECK_STRING (filename);
1209
1210   /* first expand it.  */
1211   filename = Fexpand_file_name (filename, Qnil);
1212
1213   /* luckily, this returns the short version of each element in the path.  */
1214   if (GetShortPathName (XSTRING_DATA (filename), shortname, MAX_PATH) == 0)
1215     return Qnil;
1216
1217   CORRECT_DIR_SEPS (shortname);
1218
1219   return build_string (shortname);
1220 }
1221
1222
1223 DEFUN ("win32-long-file-name", Fwin32_long_file_name, 1, 1, "", /*
1224   Return the long file name version of the full path of FILENAME.
1225 If FILENAME does not exist, return nil.
1226 All path elements in FILENAME are converted to their long names.
1227 */
1228        (filename))
1229 {
1230   char longname[ MAX_PATH ];
1231
1232   CHECK_STRING (filename);
1233
1234   /* first expand it.  */
1235   filename = Fexpand_file_name (filename, Qnil);
1236
1237   if (!win32_get_long_filename (XSTRING_DATA (filename), longname, MAX_PATH))
1238     return Qnil;
1239
1240   CORRECT_DIR_SEPS (longname);
1241
1242   return build_string (longname);
1243 }
1244
1245 DEFUN ("win32-set-process-priority", Fwin32_set_process_priority, 2, 2, "", /*
1246   Set the priority of PROCESS to PRIORITY.
1247 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1248 priority of the process whose pid is PROCESS is changed.
1249 PRIORITY should be one of the symbols high, normal, or low;
1250 any other symbol will be interpreted as normal.
1251
1252 If successful, the return value is t, otherwise nil.
1253 */
1254        (process, priority))
1255 {
1256   HANDLE proc_handle = GetCurrentProcess ();
1257   DWORD  priority_class = NORMAL_PRIORITY_CLASS;
1258   Lisp_Object result = Qnil;
1259
1260   CHECK_SYMBOL (priority);
1261
1262   if (!NILP (process))
1263     {
1264       DWORD pid;
1265       child_process *cp;
1266
1267       CHECK_INT (process);
1268
1269       /* Allow pid to be an internally generated one, or one obtained
1270          externally.  This is necessary because real pids on Win95 are
1271          negative.  */
1272
1273       pid = XINT (process);
1274       cp = find_child_pid (pid);
1275       if (cp != NULL)
1276         pid = cp->procinfo.dwProcessId;
1277
1278       proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1279     }
1280
1281   if (EQ (priority, Qhigh))
1282     priority_class = HIGH_PRIORITY_CLASS;
1283   else if (EQ (priority, Qlow))
1284     priority_class = IDLE_PRIORITY_CLASS;
1285
1286   if (proc_handle != NULL)
1287     {
1288       if (SetPriorityClass (proc_handle, priority_class))
1289         result = Qt;
1290       if (!NILP (process))
1291         CloseHandle (proc_handle);
1292     }
1293
1294   return result;
1295 }
1296
1297
1298 DEFUN ("win32-get-locale-info", Fwin32_get_locale_info, 1, 2, "", /*
1299   "Return information about the Windows locale LCID.
1300 By default, return a three letter locale code which encodes the default
1301 language as the first two characters, and the country or regional variant
1302 as the third letter.  For example, ENU refers to `English (United States)',
1303 while ENC means `English (Canadian)'.
1304
1305 If the optional argument LONGFORM is non-nil, the long form of the locale
1306 name is returned, e.g. `English (United States)' instead.
1307
1308 If LCID (a 16-bit number) is not a valid locale, the result is nil.
1309 */
1310      (lcid, longform))
1311 {
1312   int got_abbrev;
1313   int got_full;
1314   char abbrev_name[32] = { 0 };
1315   char full_name[256] = { 0 };
1316
1317   CHECK_INT (lcid);
1318
1319   if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1320     return Qnil;
1321
1322   if (NILP (longform))
1323     {
1324       got_abbrev = GetLocaleInfo (XINT (lcid),
1325                                   LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1326                                   abbrev_name, sizeof (abbrev_name));
1327       if (got_abbrev)
1328         return build_string (abbrev_name);
1329     }
1330   else
1331     {
1332       got_full = GetLocaleInfo (XINT (lcid),
1333                                 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1334                                 full_name, sizeof (full_name));
1335       if (got_full)
1336         return build_string (full_name);
1337     }
1338
1339   return Qnil;
1340 }
1341
1342
1343 DEFUN ("win32-get-current-locale-id", Fwin32_get_current_locale_id, 0, 0, "", /*
1344   "Return Windows locale id for current locale setting.
1345 This is a numerical value; use `win32-get-locale-info' to convert to a
1346 human-readable form.
1347 */
1348        ())
1349 {
1350   return make_int (GetThreadLocale ());
1351 }
1352
1353
1354 DEFUN ("win32-get-default-locale-id", Fwin32_get_default_locale_id, 0, 1, "", /*
1355   "Return Windows locale id for default locale setting.
1356 By default, the system default locale setting is returned; if the optional
1357 parameter USERP is non-nil, the user default locale setting is returned.
1358 This is a numerical value; use `win32-get-locale-info' to convert to a
1359 human-readable form.
1360 */
1361        (userp))
1362 {
1363   if (NILP (userp))
1364     return make_int (GetSystemDefaultLCID ());
1365   return make_int (GetUserDefaultLCID ());
1366 }
1367
1368 DWORD int_from_hex (char * s)
1369 {
1370   DWORD val = 0;
1371   static char hex[] = "0123456789abcdefABCDEF";
1372   char * p;
1373
1374   while (*s && (p = strchr(hex, *s)) != NULL)
1375     {
1376       unsigned digit = p - hex;
1377       if (digit > 15)
1378         digit -= 6;
1379       val = val * 16 + digit;
1380       s++;
1381     }
1382   return val;
1383 }
1384
1385 /* We need to build a global list, since the EnumSystemLocale callback
1386    function isn't given a context pointer.  */
1387 Lisp_Object Vwin32_valid_locale_ids;
1388
1389 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
1390 {
1391   DWORD id = int_from_hex (localeNum);
1392   Vwin32_valid_locale_ids = Fcons (make_int (id), Vwin32_valid_locale_ids);
1393   return TRUE;
1394 }
1395
1396 DEFUN ("win32-get-valid-locale-ids", Fwin32_get_valid_locale_ids, 0, 0, "", /*
1397   Return list of all valid Windows locale ids.
1398 Each id is a numerical value; use `win32-get-locale-info' to convert to a
1399 human-readable form.
1400 */
1401        ())
1402 {
1403   Vwin32_valid_locale_ids = Qnil;
1404
1405   EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
1406
1407   Vwin32_valid_locale_ids = Fnreverse (Vwin32_valid_locale_ids);
1408   return Vwin32_valid_locale_ids;
1409 }
1410
1411
1412 DEFUN ("win32-set-current-locale", Fwin32_set_current_locale, 1, 1, "", /*
1413   Make Windows locale LCID be the current locale setting for Emacs.
1414 If successful, the new locale id is returned, otherwise nil.
1415 */
1416      (lcid))
1417 {
1418   CHECK_INT (lcid);
1419
1420   if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1421     return Qnil;
1422
1423   if (!SetThreadLocale (XINT (lcid)))
1424     return Qnil;
1425
1426 /* Sync with FSF Emacs 19.34.6 note: dwWinThreadId declared in
1427    w32term.h and defined in w32fns.c, both of which are not in current
1428    XEmacs.  #### Check what we lose by ifdef'ing out these. --marcpa */
1429 #if 0
1430   /* Need to set input thread locale if present.  */
1431   if (dwWinThreadId)
1432     /* Reply is not needed.  */
1433     PostThreadMessage (dwWinThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
1434 #endif
1435
1436   return make_int (GetThreadLocale ());
1437 }
1438
1439 \f
1440 void
1441 syms_of_ntproc (void)
1442 {
1443   DEFSUBR (Fwin32_short_file_name);
1444   DEFSUBR (Fwin32_long_file_name);
1445   DEFSUBR (Fwin32_set_process_priority);
1446   DEFSUBR (Fwin32_get_locale_info);
1447   DEFSUBR (Fwin32_get_current_locale_id);
1448   DEFSUBR (Fwin32_get_default_locale_id);
1449   DEFSUBR (Fwin32_get_valid_locale_ids);
1450   DEFSUBR (Fwin32_set_current_locale);
1451 }
1452
1453
1454 void
1455 vars_of_ntproc (void)
1456 {
1457   defsymbol (&Qhigh, "high");
1458   defsymbol (&Qlow, "low");
1459
1460   DEFVAR_LISP ("win32-quote-process-args", &Vwin32_quote_process_args /*
1461     Non-nil enables quoting of process arguments to ensure correct parsing.
1462 Because Windows does not directly pass argv arrays to child processes,
1463 programs have to reconstruct the argv array by parsing the command
1464 line string.  For an argument to contain a space, it must be enclosed
1465 in double quotes or it will be parsed as multiple arguments.
1466
1467 If the value is a character, that character will be used to escape any
1468 quote characters that appear, otherwise a suitable escape character
1469 will be chosen based on the type of the program.
1470 */ );
1471   Vwin32_quote_process_args = Qt;
1472
1473   DEFVAR_LISP ("win32-start-process-show-window",
1474                &Vwin32_start_process_show_window /*
1475     When nil, processes started via start-process hide their windows.
1476 When non-nil, they show their window in the method of their choice.
1477 */ );
1478   Vwin32_start_process_show_window = Qnil;
1479
1480   DEFVAR_LISP ("win32-start-process-share-console",
1481                &Vwin32_start_process_share_console /*
1482     When nil, processes started via start-process are given a new console.
1483 When non-nil, they share the Emacs console; this has the limitation of
1484 allowing only only DOS subprocess to run at a time (whether started directly
1485 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
1486 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
1487 otherwise respond to interrupts from Emacs.
1488 */ );
1489   Vwin32_start_process_share_console = Qt;
1490
1491   DEFVAR_LISP ("win32-pipe-read-delay", &Vwin32_pipe_read_delay /*
1492     Forced delay before reading subprocess output.
1493 This is done to improve the buffering of subprocess output, by
1494 avoiding the inefficiency of frequently reading small amounts of data.
1495
1496 If positive, the value is the number of milliseconds to sleep before
1497 reading the subprocess output.  If negative, the magnitude is the number
1498 of time slices to wait (effectively boosting the priority of the child
1499 process temporarily).  A value of zero disables waiting entirely.
1500 */ );
1501   Vwin32_pipe_read_delay = make_int (50);
1502
1503 #if 0
1504   DEFVAR_LISP ("win32-generate-fake-inodes", &Vwin32_generate_fake_inodes /*
1505     "Non-nil means attempt to fake realistic inode values.
1506 This works by hashing the truename of files, and should detect 
1507 aliasing between long and short (8.3 DOS) names, but can have
1508 false positives because of hash collisions.  Note that determining
1509 the truename of a file can be slow.
1510 */ );
1511   Vwin32_generate_fake_inodes = Qnil;
1512 #endif
1513 }
1514
1515 /* end of ntproc.c */