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