*** empty log message ***
[emacs.git] / src / w32proc.c
bloba2b5000b88d4739f9f2cd5204e8091a77b6ad0a2
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; 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.
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <io.h>
29 #include <fcntl.h>
30 #include <signal.h>
32 /* must include CRT headers *before* config.h */
33 #include "config.h"
34 #undef signal
35 #undef wait
36 #undef spawnve
37 #undef select
38 #undef kill
40 #include <windows.h>
41 #ifdef __GNUC__
42 /* This definition is missing from mingw32 headers. */
43 extern BOOL WINAPI IsValidLocale(LCID, DWORD);
44 #endif
46 #include "lisp.h"
47 #include "w32.h"
48 #include "w32heap.h"
49 #include "systime.h"
50 #include "syswait.h"
51 #include "process.h"
52 #include "syssignal.h"
53 #include "w32term.h"
55 /* Control whether spawnve quotes arguments as necessary to ensure
56 correct parsing by child process. Because not all uses of spawnve
57 are careful about constructing argv arrays, we make this behaviour
58 conditional (off by default). */
59 Lisp_Object Vw32_quote_process_args;
61 /* Control whether create_child causes the process' window to be
62 hidden. The default is nil. */
63 Lisp_Object Vw32_start_process_show_window;
65 /* Control whether create_child causes the process to inherit Emacs'
66 console window, or be given a new one of its own. The default is
67 nil, to allow multiple DOS programs to run on Win95. Having separate
68 consoles also allows Emacs to cleanly terminate process groups. */
69 Lisp_Object Vw32_start_process_share_console;
71 /* Control whether create_child cause the process to inherit Emacs'
72 error mode setting. The default is t, to minimize the possibility of
73 subprocesses blocking when accessing unmounted drives. */
74 Lisp_Object Vw32_start_process_inherit_error_mode;
76 /* Time to sleep before reading from a subprocess output pipe - this
77 avoids the inefficiency of frequently reading small amounts of data.
78 This is primarily necessary for handling DOS processes on Windows 95,
79 but is useful for W32 processes on both Windows 95 and NT as well. */
80 Lisp_Object Vw32_pipe_read_delay;
82 /* Control conversion of upper case file names to lower case.
83 nil means no, t means yes. */
84 Lisp_Object Vw32_downcase_file_names;
86 /* Control whether stat() attempts to generate fake but hopefully
87 "accurate" inode values, by hashing the absolute truenames of files.
88 This should detect aliasing between long and short names, but still
89 allows the possibility of hash collisions. */
90 Lisp_Object Vw32_generate_fake_inodes;
92 /* Control whether stat() attempts to determine file type and link count
93 exactly, at the expense of slower operation. Since true hard links
94 are supported on NTFS volumes, this is only relevant on NT. */
95 Lisp_Object Vw32_get_true_file_attributes;
97 Lisp_Object Qhigh, Qlow;
99 #ifdef EMACSDEBUG
100 void _DebPrint (const char *fmt, ...)
102 char buf[1024];
103 va_list args;
105 va_start (args, fmt);
106 vsprintf (buf, fmt, args);
107 va_end (args);
108 OutputDebugString (buf);
110 #endif
112 typedef void (_CALLBACK_ *signal_handler)(int);
114 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
115 static signal_handler sig_handlers[NSIG];
117 /* Fake signal implementation to record the SIGCHLD handler. */
118 signal_handler
119 sys_signal (int sig, signal_handler handler)
121 signal_handler old;
123 if (sig != SIGCHLD)
125 errno = EINVAL;
126 return SIG_ERR;
128 old = sig_handlers[sig];
129 sig_handlers[sig] = handler;
130 return old;
133 /* Defined in <process.h> which conflicts with the local copy */
134 #define _P_NOWAIT 1
136 /* Child process management list. */
137 int child_proc_count = 0;
138 child_process child_procs[ MAX_CHILDREN ];
139 child_process *dead_child = NULL;
141 DWORD WINAPI reader_thread (void *arg);
143 /* Find an unused process slot. */
144 child_process *
145 new_child (void)
147 child_process *cp;
148 DWORD id;
150 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
151 if (!CHILD_ACTIVE (cp))
152 goto Initialise;
153 if (child_proc_count == MAX_CHILDREN)
154 return NULL;
155 cp = &child_procs[child_proc_count++];
157 Initialise:
158 memset (cp, 0, sizeof(*cp));
159 cp->fd = -1;
160 cp->pid = -1;
161 cp->procinfo.hProcess = NULL;
162 cp->status = STATUS_READ_ERROR;
164 /* use manual reset event so that select() will function properly */
165 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
166 if (cp->char_avail)
168 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
169 if (cp->char_consumed)
171 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
172 if (cp->thrd)
173 return cp;
176 delete_child (cp);
177 return NULL;
180 void
181 delete_child (child_process *cp)
183 int i;
185 /* Should not be deleting a child that is still needed. */
186 for (i = 0; i < MAXDESC; i++)
187 if (fd_info[i].cp == cp)
188 abort ();
190 if (!CHILD_ACTIVE (cp))
191 return;
193 /* reap thread if necessary */
194 if (cp->thrd)
196 DWORD rc;
198 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
200 /* let the thread exit cleanly if possible */
201 cp->status = STATUS_READ_ERROR;
202 SetEvent (cp->char_consumed);
203 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
205 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
206 "with %lu for fd %ld\n", GetLastError (), cp->fd));
207 TerminateThread (cp->thrd, 0);
210 CloseHandle (cp->thrd);
211 cp->thrd = NULL;
213 if (cp->char_avail)
215 CloseHandle (cp->char_avail);
216 cp->char_avail = NULL;
218 if (cp->char_consumed)
220 CloseHandle (cp->char_consumed);
221 cp->char_consumed = NULL;
224 /* update child_proc_count (highest numbered slot in use plus one) */
225 if (cp == child_procs + child_proc_count - 1)
227 for (i = child_proc_count-1; i >= 0; i--)
228 if (CHILD_ACTIVE (&child_procs[i]))
230 child_proc_count = i + 1;
231 break;
234 if (i < 0)
235 child_proc_count = 0;
238 /* Find a child by pid. */
239 static child_process *
240 find_child_pid (DWORD pid)
242 child_process *cp;
244 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
245 if (CHILD_ACTIVE (cp) && pid == cp->pid)
246 return cp;
247 return NULL;
251 /* Thread proc for child process and socket reader threads. Each thread
252 is normally blocked until woken by select() to check for input by
253 reading one char. When the read completes, char_avail is signalled
254 to wake up the select emulator and the thread blocks itself again. */
255 DWORD WINAPI
256 reader_thread (void *arg)
258 child_process *cp;
260 /* Our identity */
261 cp = (child_process *)arg;
263 /* We have to wait for the go-ahead before we can start */
264 if (cp == NULL
265 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
266 return 1;
268 for (;;)
270 int rc;
272 rc = _sys_read_ahead (cp->fd);
274 /* The name char_avail is a misnomer - it really just means the
275 read-ahead has completed, whether successfully or not. */
276 if (!SetEvent (cp->char_avail))
278 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
279 GetLastError (), cp->fd));
280 return 1;
283 if (rc == STATUS_READ_ERROR)
284 return 1;
286 /* If the read died, the child has died so let the thread die */
287 if (rc == STATUS_READ_FAILED)
288 break;
290 /* Wait until our input is acknowledged before reading again */
291 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
293 DebPrint (("reader_thread.WaitForSingleObject failed with "
294 "%lu for fd %ld\n", GetLastError (), cp->fd));
295 break;
298 return 0;
301 /* To avoid Emacs changing directory, we just record here the directory
302 the new process should start in. This is set just before calling
303 sys_spawnve, and is not generally valid at any other time. */
304 static char * process_dir;
306 static BOOL
307 create_child (char *exe, char *cmdline, char *env,
308 int * pPid, child_process *cp)
310 STARTUPINFO start;
311 SECURITY_ATTRIBUTES sec_attrs;
312 #if 0
313 SECURITY_DESCRIPTOR sec_desc;
314 #endif
315 DWORD flags;
316 char dir[ MAXPATHLEN ];
318 if (cp == NULL) abort ();
320 memset (&start, 0, sizeof (start));
321 start.cb = sizeof (start);
323 #ifdef HAVE_NTGUI
324 if (NILP (Vw32_start_process_show_window))
325 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
326 else
327 start.dwFlags = STARTF_USESTDHANDLES;
328 start.wShowWindow = SW_HIDE;
330 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
331 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
332 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
333 #endif /* HAVE_NTGUI */
335 #if 0
336 /* Explicitly specify no security */
337 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
338 goto EH_Fail;
339 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
340 goto EH_Fail;
341 #endif
342 sec_attrs.nLength = sizeof (sec_attrs);
343 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
344 sec_attrs.bInheritHandle = FALSE;
346 strcpy (dir, process_dir);
347 unixtodos_filename (dir);
349 flags = (!NILP (Vw32_start_process_share_console)
350 ? CREATE_NEW_PROCESS_GROUP
351 : CREATE_NEW_CONSOLE);
352 if (NILP (Vw32_start_process_inherit_error_mode))
353 flags |= CREATE_DEFAULT_ERROR_MODE;
354 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
355 flags, env, dir, &start, &cp->procinfo))
356 goto EH_Fail;
358 cp->pid = (int) cp->procinfo.dwProcessId;
360 /* Hack for Windows 95, which assigns large (ie negative) pids */
361 if (cp->pid < 0)
362 cp->pid = -cp->pid;
364 /* pid must fit in a Lisp_Int */
365 cp->pid = (cp->pid & VALMASK);
367 *pPid = cp->pid;
369 return TRUE;
371 EH_Fail:
372 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
373 return FALSE;
376 /* create_child doesn't know what emacs' file handle will be for waiting
377 on output from the child, so we need to make this additional call
378 to register the handle with the process
379 This way the select emulator knows how to match file handles with
380 entries in child_procs. */
381 void
382 register_child (int pid, int fd)
384 child_process *cp;
386 cp = find_child_pid (pid);
387 if (cp == NULL)
389 DebPrint (("register_child unable to find pid %lu\n", pid));
390 return;
393 #ifdef FULL_DEBUG
394 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
395 #endif
397 cp->fd = fd;
399 /* thread is initially blocked until select is called; set status so
400 that select will release thread */
401 cp->status = STATUS_READ_ACKNOWLEDGED;
403 /* attach child_process to fd_info */
404 if (fd_info[fd].cp != NULL)
406 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
407 abort ();
410 fd_info[fd].cp = cp;
413 /* When a process dies its pipe will break so the reader thread will
414 signal failure to the select emulator.
415 The select emulator then calls this routine to clean up.
416 Since the thread signaled failure we can assume it is exiting. */
417 static void
418 reap_subprocess (child_process *cp)
420 if (cp->procinfo.hProcess)
422 /* Reap the process */
423 #ifdef FULL_DEBUG
424 /* Process should have already died before we are called. */
425 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
426 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
427 #endif
428 CloseHandle (cp->procinfo.hProcess);
429 cp->procinfo.hProcess = NULL;
430 CloseHandle (cp->procinfo.hThread);
431 cp->procinfo.hThread = NULL;
434 /* For asynchronous children, the child_proc resources will be freed
435 when the last pipe read descriptor is closed; for synchronous
436 children, we must explicitly free the resources now because
437 register_child has not been called. */
438 if (cp->fd == -1)
439 delete_child (cp);
442 /* Wait for any of our existing child processes to die
443 When it does, close its handle
444 Return the pid and fill in the status if non-NULL. */
446 int
447 sys_wait (int *status)
449 DWORD active, retval;
450 int nh;
451 int pid;
452 child_process *cp, *cps[MAX_CHILDREN];
453 HANDLE wait_hnd[MAX_CHILDREN];
455 nh = 0;
456 if (dead_child != NULL)
458 /* We want to wait for a specific child */
459 wait_hnd[nh] = dead_child->procinfo.hProcess;
460 cps[nh] = dead_child;
461 if (!wait_hnd[nh]) abort ();
462 nh++;
463 active = 0;
464 goto get_result;
466 else
468 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
469 /* some child_procs might be sockets; ignore them */
470 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
472 wait_hnd[nh] = cp->procinfo.hProcess;
473 cps[nh] = cp;
474 nh++;
478 if (nh == 0)
480 /* Nothing to wait on, so fail */
481 errno = ECHILD;
482 return -1;
487 /* Check for quit about once a second. */
488 QUIT;
489 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
490 } while (active == WAIT_TIMEOUT);
492 if (active == WAIT_FAILED)
494 errno = EBADF;
495 return -1;
497 else if (active >= WAIT_OBJECT_0
498 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
500 active -= WAIT_OBJECT_0;
502 else if (active >= WAIT_ABANDONED_0
503 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
505 active -= WAIT_ABANDONED_0;
507 else
508 abort ();
510 get_result:
511 if (!GetExitCodeProcess (wait_hnd[active], &retval))
513 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
514 GetLastError ()));
515 retval = 1;
517 if (retval == STILL_ACTIVE)
519 /* Should never happen */
520 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
521 errno = EINVAL;
522 return -1;
525 /* Massage the exit code from the process to match the format expected
526 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
527 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
529 if (retval == STATUS_CONTROL_C_EXIT)
530 retval = SIGINT;
531 else
532 retval <<= 8;
534 cp = cps[active];
535 pid = cp->pid;
536 #ifdef FULL_DEBUG
537 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
538 #endif
540 if (status)
542 *status = retval;
544 else if (synch_process_alive)
546 synch_process_alive = 0;
548 /* Report the status of the synchronous process. */
549 if (WIFEXITED (retval))
550 synch_process_retcode = WRETCODE (retval);
551 else if (WIFSIGNALED (retval))
553 int code = WTERMSIG (retval);
554 char *signame;
556 synchronize_system_messages_locale ();
557 signame = strsignal (code);
559 if (signame == 0)
560 signame = "unknown";
562 synch_process_death = signame;
565 reap_subprocess (cp);
568 reap_subprocess (cp);
570 return pid;
573 void
574 w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app)
576 file_data executable;
577 char * p;
579 /* Default values in case we can't tell for sure. */
580 *is_dos_app = FALSE;
581 *is_cygnus_app = FALSE;
583 if (!open_input_file (&executable, filename))
584 return;
586 p = strrchr (filename, '.');
588 /* We can only identify DOS .com programs from the extension. */
589 if (p && stricmp (p, ".com") == 0)
590 *is_dos_app = TRUE;
591 else if (p && (stricmp (p, ".bat") == 0
592 || stricmp (p, ".cmd") == 0))
594 /* A DOS shell script - it appears that CreateProcess is happy to
595 accept this (somewhat surprisingly); presumably it looks at
596 COMSPEC to determine what executable to actually invoke.
597 Therefore, we have to do the same here as well. */
598 /* Actually, I think it uses the program association for that
599 extension, which is defined in the registry. */
600 p = egetenv ("COMSPEC");
601 if (p)
602 w32_executable_type (p, is_dos_app, is_cygnus_app);
604 else
606 /* Look for DOS .exe signature - if found, we must also check that
607 it isn't really a 16- or 32-bit Windows exe, since both formats
608 start with a DOS program stub. Note that 16-bit Windows
609 executables use the OS/2 1.x format. */
611 IMAGE_DOS_HEADER * dos_header;
612 IMAGE_NT_HEADERS * nt_header;
614 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
615 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
616 goto unwind;
618 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
620 if ((char *) nt_header > (char *) dos_header + executable.size)
622 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
623 *is_dos_app = TRUE;
625 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
626 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
628 *is_dos_app = TRUE;
630 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
632 /* Look for cygwin.dll in DLL import list. */
633 IMAGE_DATA_DIRECTORY import_dir =
634 nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
635 IMAGE_IMPORT_DESCRIPTOR * imports;
636 IMAGE_SECTION_HEADER * section;
638 section = rva_to_section (import_dir.VirtualAddress, nt_header);
639 imports = RVA_TO_PTR (import_dir.VirtualAddress, section, executable);
641 for ( ; imports->Name; imports++)
643 char * dllname = RVA_TO_PTR (imports->Name, section, executable);
645 /* The exact name of the cygwin dll has changed with
646 various releases, but hopefully this will be reasonably
647 future proof. */
648 if (strncmp (dllname, "cygwin", 6) == 0)
650 *is_cygnus_app = TRUE;
651 break;
657 unwind:
658 close_file_data (&executable);
662 compare_env (const void *strp1, const void *strp2)
664 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
666 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
668 /* Sort order in command.com/cmd.exe is based on uppercasing
669 names, so do the same here. */
670 if (toupper (*str1) > toupper (*str2))
671 return 1;
672 else if (toupper (*str1) < toupper (*str2))
673 return -1;
674 str1++, str2++;
677 if (*str1 == '=' && *str2 == '=')
678 return 0;
679 else if (*str1 == '=')
680 return -1;
681 else
682 return 1;
685 void
686 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
688 char **optr, **nptr;
689 int num;
691 nptr = new_envp;
692 optr = envp1;
693 while (*optr)
694 *nptr++ = *optr++;
695 num = optr - envp1;
697 optr = envp2;
698 while (*optr)
699 *nptr++ = *optr++;
700 num += optr - envp2;
702 qsort (new_envp, num, sizeof (char *), compare_env);
704 *nptr = NULL;
707 /* When a new child process is created we need to register it in our list,
708 so intercept spawn requests. */
709 int
710 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
712 Lisp_Object program, full;
713 char *cmdline, *env, *parg, **targ;
714 int arglen, numenv;
715 int pid;
716 child_process *cp;
717 int is_dos_app, is_cygnus_app;
718 int do_quoting = 0;
719 char escape_char;
720 /* We pass our process ID to our children by setting up an environment
721 variable in their environment. */
722 char ppid_env_var_buffer[64];
723 char *extra_env[] = {ppid_env_var_buffer, NULL};
724 char *sepchars = " \t";
726 /* We don't care about the other modes */
727 if (mode != _P_NOWAIT)
729 errno = EINVAL;
730 return -1;
733 /* Handle executable names without an executable suffix. */
734 program = make_string (cmdname, strlen (cmdname));
735 if (NILP (Ffile_executable_p (program)))
737 struct gcpro gcpro1;
739 full = Qnil;
740 GCPRO1 (program);
741 openp (Vexec_path, program, EXEC_SUFFIXES, &full, 1);
742 UNGCPRO;
743 if (NILP (full))
745 errno = EINVAL;
746 return -1;
748 program = full;
751 /* make sure argv[0] and cmdname are both in DOS format */
752 cmdname = XSTRING (program)->data;
753 unixtodos_filename (cmdname);
754 argv[0] = cmdname;
756 /* Determine whether program is a 16-bit DOS executable, or a w32
757 executable that is implicitly linked to the Cygnus dll (implying it
758 was compiled with the Cygnus GNU toolchain and hence relies on
759 cygwin.dll to parse the command line - we use this to decide how to
760 escape quote chars in command line args that must be quoted). */
761 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app);
763 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
764 application to start it by specifying the helper app as cmdname,
765 while leaving the real app name as argv[0]. */
766 if (is_dos_app)
768 cmdname = alloca (MAXPATHLEN);
769 if (egetenv ("CMDPROXY"))
770 strcpy (cmdname, egetenv ("CMDPROXY"));
771 else
773 strcpy (cmdname, XSTRING (Vinvocation_directory)->data);
774 strcat (cmdname, "cmdproxy.exe");
776 unixtodos_filename (cmdname);
779 /* we have to do some conjuring here to put argv and envp into the
780 form CreateProcess wants... argv needs to be a space separated/null
781 terminated list of parameters, and envp is a null
782 separated/double-null terminated list of parameters.
784 Additionally, zero-length args and args containing whitespace or
785 quote chars need to be wrapped in double quotes - for this to work,
786 embedded quotes need to be escaped as well. The aim is to ensure
787 the child process reconstructs the argv array we start with
788 exactly, so we treat quotes at the beginning and end of arguments
789 as embedded quotes.
791 The w32 GNU-based library from Cygnus doubles quotes to escape
792 them, while MSVC uses backslash for escaping. (Actually the MSVC
793 startup code does attempt to recognise doubled quotes and accept
794 them, but gets it wrong and ends up requiring three quotes to get a
795 single embedded quote!) So by default we decide whether to use
796 quote or backslash as the escape character based on whether the
797 binary is apparently a Cygnus compiled app.
799 Note that using backslash to escape embedded quotes requires
800 additional special handling if an embedded quote is already
801 preceeded by backslash, or if an arg requiring quoting ends with
802 backslash. In such cases, the run of escape characters needs to be
803 doubled. For consistency, we apply this special handling as long
804 as the escape character is not quote.
806 Since we have no idea how large argv and envp are likely to be we
807 figure out list lengths on the fly and allocate them. */
809 if (!NILP (Vw32_quote_process_args))
811 do_quoting = 1;
812 /* Override escape char by binding w32-quote-process-args to
813 desired character, or use t for auto-selection. */
814 if (INTEGERP (Vw32_quote_process_args))
815 escape_char = XINT (Vw32_quote_process_args);
816 else
817 escape_char = is_cygnus_app ? '"' : '\\';
820 /* Cygwin apps needs quoting a bit more often */
821 if (escape_char == '"')
822 sepchars = "\r\n\t\f '";
824 /* do argv... */
825 arglen = 0;
826 targ = argv;
827 while (*targ)
829 char * p = *targ;
830 int need_quotes = 0;
831 int escape_char_run = 0;
833 if (*p == 0)
834 need_quotes = 1;
835 for ( ; *p; p++)
837 if (escape_char == '"' && *p == '\\')
838 /* If it's a Cygwin app, \ needs to be escaped. */
839 arglen++;
840 else if (*p == '"')
842 /* allow for embedded quotes to be escaped */
843 arglen++;
844 need_quotes = 1;
845 /* handle the case where the embedded quote is already escaped */
846 if (escape_char_run > 0)
848 /* To preserve the arg exactly, we need to double the
849 preceding escape characters (plus adding one to
850 escape the quote character itself). */
851 arglen += escape_char_run;
854 else if (strchr (sepchars, *p) != NULL)
856 need_quotes = 1;
859 if (*p == escape_char && escape_char != '"')
860 escape_char_run++;
861 else
862 escape_char_run = 0;
864 if (need_quotes)
866 arglen += 2;
867 /* handle the case where the arg ends with an escape char - we
868 must not let the enclosing quote be escaped. */
869 if (escape_char_run > 0)
870 arglen += escape_char_run;
872 arglen += strlen (*targ++) + 1;
874 cmdline = alloca (arglen);
875 targ = argv;
876 parg = cmdline;
877 while (*targ)
879 char * p = *targ;
880 int need_quotes = 0;
882 if (*p == 0)
883 need_quotes = 1;
885 if (do_quoting)
887 for ( ; *p; p++)
888 if ((strchr (sepchars, *p) != NULL) || *p == '"')
889 need_quotes = 1;
891 if (need_quotes)
893 int escape_char_run = 0;
894 char * first;
895 char * last;
897 p = *targ;
898 first = p;
899 last = p + strlen (p) - 1;
900 *parg++ = '"';
901 #if 0
902 /* This version does not escape quotes if they occur at the
903 beginning or end of the arg - this could lead to incorrect
904 behaviour when the arg itself represents a command line
905 containing quoted args. I believe this was originally done
906 as a hack to make some things work, before
907 `w32-quote-process-args' was added. */
908 while (*p)
910 if (*p == '"' && p > first && p < last)
911 *parg++ = escape_char; /* escape embedded quotes */
912 *parg++ = *p++;
914 #else
915 for ( ; *p; p++)
917 if (*p == '"')
919 /* double preceding escape chars if any */
920 while (escape_char_run > 0)
922 *parg++ = escape_char;
923 escape_char_run--;
925 /* escape all quote chars, even at beginning or end */
926 *parg++ = escape_char;
928 else if (escape_char == '"' && *p == '\\')
929 *parg++ = '\\';
930 *parg++ = *p;
932 if (*p == escape_char && escape_char != '"')
933 escape_char_run++;
934 else
935 escape_char_run = 0;
937 /* double escape chars before enclosing quote */
938 while (escape_char_run > 0)
940 *parg++ = escape_char;
941 escape_char_run--;
943 #endif
944 *parg++ = '"';
946 else
948 strcpy (parg, *targ);
949 parg += strlen (*targ);
951 *parg++ = ' ';
952 targ++;
954 *--parg = '\0';
956 /* and envp... */
957 arglen = 1;
958 targ = envp;
959 numenv = 1; /* for end null */
960 while (*targ)
962 arglen += strlen (*targ++) + 1;
963 numenv++;
965 /* extra env vars... */
966 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
967 GetCurrentProcessId ());
968 arglen += strlen (ppid_env_var_buffer) + 1;
969 numenv++;
971 /* merge env passed in and extra env into one, and sort it. */
972 targ = (char **) alloca (numenv * sizeof (char *));
973 merge_and_sort_env (envp, extra_env, targ);
975 /* concatenate env entries. */
976 env = alloca (arglen);
977 parg = env;
978 while (*targ)
980 strcpy (parg, *targ);
981 parg += strlen (*targ++);
982 *parg++ = '\0';
984 *parg++ = '\0';
985 *parg = '\0';
987 cp = new_child ();
988 if (cp == NULL)
990 errno = EAGAIN;
991 return -1;
994 /* Now create the process. */
995 if (!create_child (cmdname, cmdline, env, &pid, cp))
997 delete_child (cp);
998 errno = ENOEXEC;
999 return -1;
1002 return pid;
1005 /* Emulate the select call
1006 Wait for available input on any of the given rfds, or timeout if
1007 a timeout is given and no input is detected
1008 wfds and efds are not supported and must be NULL.
1010 For simplicity, we detect the death of child processes here and
1011 synchronously call the SIGCHLD handler. Since it is possible for
1012 children to be created without a corresponding pipe handle from which
1013 to read output, we wait separately on the process handles as well as
1014 the char_avail events for each process pipe. We only call
1015 wait/reap_process when the process actually terminates.
1017 To reduce the number of places in which Emacs can be hung such that
1018 C-g is not able to interrupt it, we always wait on interrupt_handle
1019 (which is signalled by the input thread when C-g is detected). If we
1020 detect that we were woken up by C-g, we return -1 with errno set to
1021 EINTR as on Unix. */
1023 /* From ntterm.c */
1024 extern HANDLE keyboard_handle;
1026 /* From w32xfns.c */
1027 extern HANDLE interrupt_handle;
1029 /* From process.c */
1030 extern int proc_buffered_char[];
1032 int
1033 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1034 EMACS_TIME *timeout)
1036 SELECT_TYPE orfds;
1037 DWORD timeout_ms, start_time;
1038 int i, nh, nc, nr;
1039 DWORD active;
1040 child_process *cp, *cps[MAX_CHILDREN];
1041 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1042 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1044 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1046 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1047 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1049 Sleep (timeout_ms);
1050 return 0;
1053 /* Otherwise, we only handle rfds, so fail otherwise. */
1054 if (rfds == NULL || wfds != NULL || efds != NULL)
1056 errno = EINVAL;
1057 return -1;
1060 orfds = *rfds;
1061 FD_ZERO (rfds);
1062 nr = 0;
1064 /* Always wait on interrupt_handle, to detect C-g (quit). */
1065 wait_hnd[0] = interrupt_handle;
1066 fdindex[0] = -1;
1068 /* Build a list of pipe handles to wait on. */
1069 nh = 1;
1070 for (i = 0; i < nfds; i++)
1071 if (FD_ISSET (i, &orfds))
1073 if (i == 0)
1075 if (keyboard_handle)
1077 /* Handle stdin specially */
1078 wait_hnd[nh] = keyboard_handle;
1079 fdindex[nh] = i;
1080 nh++;
1083 /* Check for any emacs-generated input in the queue since
1084 it won't be detected in the wait */
1085 if (detect_input_pending ())
1087 FD_SET (i, rfds);
1088 return 1;
1091 else
1093 /* Child process and socket input */
1094 cp = fd_info[i].cp;
1095 if (cp)
1097 int current_status = cp->status;
1099 if (current_status == STATUS_READ_ACKNOWLEDGED)
1101 /* Tell reader thread which file handle to use. */
1102 cp->fd = i;
1103 /* Wake up the reader thread for this process */
1104 cp->status = STATUS_READ_READY;
1105 if (!SetEvent (cp->char_consumed))
1106 DebPrint (("nt_select.SetEvent failed with "
1107 "%lu for fd %ld\n", GetLastError (), i));
1110 #ifdef CHECK_INTERLOCK
1111 /* slightly crude cross-checking of interlock between threads */
1113 current_status = cp->status;
1114 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1116 /* char_avail has been signalled, so status (which may
1117 have changed) should indicate read has completed
1118 but has not been acknowledged. */
1119 current_status = cp->status;
1120 if (current_status != STATUS_READ_SUCCEEDED
1121 && current_status != STATUS_READ_FAILED)
1122 DebPrint (("char_avail set, but read not completed: status %d\n",
1123 current_status));
1125 else
1127 /* char_avail has not been signalled, so status should
1128 indicate that read is in progress; small possibility
1129 that read has completed but event wasn't yet signalled
1130 when we tested it (because a context switch occurred
1131 or if running on separate CPUs). */
1132 if (current_status != STATUS_READ_READY
1133 && current_status != STATUS_READ_IN_PROGRESS
1134 && current_status != STATUS_READ_SUCCEEDED
1135 && current_status != STATUS_READ_FAILED)
1136 DebPrint (("char_avail reset, but read status is bad: %d\n",
1137 current_status));
1139 #endif
1140 wait_hnd[nh] = cp->char_avail;
1141 fdindex[nh] = i;
1142 if (!wait_hnd[nh]) abort ();
1143 nh++;
1144 #ifdef FULL_DEBUG
1145 DebPrint (("select waiting on child %d fd %d\n",
1146 cp-child_procs, i));
1147 #endif
1149 else
1151 /* Unable to find something to wait on for this fd, skip */
1153 /* Note that this is not a fatal error, and can in fact
1154 happen in unusual circumstances. Specifically, if
1155 sys_spawnve fails, eg. because the program doesn't
1156 exist, and debug-on-error is t so Fsignal invokes a
1157 nested input loop, then the process output pipe is
1158 still included in input_wait_mask with no child_proc
1159 associated with it. (It is removed when the debugger
1160 exits the nested input loop and the error is thrown.) */
1162 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1167 count_children:
1168 /* Add handles of child processes. */
1169 nc = 0;
1170 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
1171 /* Some child_procs might be sockets; ignore them. Also some
1172 children may have died already, but we haven't finished reading
1173 the process output; ignore them too. */
1174 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1175 && (cp->fd < 0
1176 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1177 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1180 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1181 cps[nc] = cp;
1182 nc++;
1185 /* Nothing to look for, so we didn't find anything */
1186 if (nh + nc == 0)
1188 if (timeout)
1189 Sleep (timeout_ms);
1190 return 0;
1193 start_time = GetTickCount ();
1195 /* Wait for input or child death to be signalled. If user input is
1196 allowed, then also accept window messages. */
1197 if (FD_ISSET (0, &orfds))
1198 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1199 QS_ALLINPUT);
1200 else
1201 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1203 if (active == WAIT_FAILED)
1205 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1206 nh + nc, timeout_ms, GetLastError ()));
1207 /* don't return EBADF - this causes wait_reading_process_input to
1208 abort; WAIT_FAILED is returned when single-stepping under
1209 Windows 95 after switching thread focus in debugger, and
1210 possibly at other times. */
1211 errno = EINTR;
1212 return -1;
1214 else if (active == WAIT_TIMEOUT)
1216 return 0;
1218 else if (active >= WAIT_OBJECT_0
1219 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1221 active -= WAIT_OBJECT_0;
1223 else if (active >= WAIT_ABANDONED_0
1224 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1226 active -= WAIT_ABANDONED_0;
1228 else
1229 abort ();
1231 /* Loop over all handles after active (now officially documented as
1232 being the first signalled handle in the array). We do this to
1233 ensure fairness, so that all channels with data available will be
1234 processed - otherwise higher numbered channels could be starved. */
1237 if (active == nh + nc)
1239 /* There are messages in the lisp thread's queue; we must
1240 drain the queue now to ensure they are processed promptly,
1241 because if we don't do so, we will not be woken again until
1242 further messages arrive.
1244 NB. If ever we allow window message procedures to callback
1245 into lisp, we will need to ensure messages are dispatched
1246 at a safe time for lisp code to be run (*), and we may also
1247 want to provide some hooks in the dispatch loop to cater
1248 for modeless dialogs created by lisp (ie. to register
1249 window handles to pass to IsDialogMessage).
1251 (*) Note that MsgWaitForMultipleObjects above is an
1252 internal dispatch point for messages that are sent to
1253 windows created by this thread. */
1254 drain_message_queue ();
1256 else if (active >= nh)
1258 cp = cps[active - nh];
1260 /* We cannot always signal SIGCHLD immediately; if we have not
1261 finished reading the process output, we must delay sending
1262 SIGCHLD until we do. */
1264 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1265 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1266 /* SIG_DFL for SIGCHLD is ignore */
1267 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1268 sig_handlers[SIGCHLD] != SIG_IGN)
1270 #ifdef FULL_DEBUG
1271 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1272 cp->pid));
1273 #endif
1274 dead_child = cp;
1275 sig_handlers[SIGCHLD] (SIGCHLD);
1276 dead_child = NULL;
1279 else if (fdindex[active] == -1)
1281 /* Quit (C-g) was detected. */
1282 errno = EINTR;
1283 return -1;
1285 else if (fdindex[active] == 0)
1287 /* Keyboard input available */
1288 FD_SET (0, rfds);
1289 nr++;
1291 else
1293 /* must be a socket or pipe - read ahead should have
1294 completed, either succeeding or failing. */
1295 FD_SET (fdindex[active], rfds);
1296 nr++;
1299 /* Even though wait_reading_process_output only reads from at most
1300 one channel, we must process all channels here so that we reap
1301 all children that have died. */
1302 while (++active < nh + nc)
1303 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1304 break;
1305 } while (active < nh + nc);
1307 /* If no input has arrived and timeout hasn't expired, wait again. */
1308 if (nr == 0)
1310 DWORD elapsed = GetTickCount () - start_time;
1312 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1314 if (timeout_ms != INFINITE)
1315 timeout_ms -= elapsed;
1316 goto count_children;
1320 return nr;
1323 /* Substitute for certain kill () operations */
1325 static BOOL CALLBACK
1326 find_child_console (HWND hwnd, LPARAM arg)
1328 child_process * cp = (child_process *) arg;
1329 DWORD thread_id;
1330 DWORD process_id;
1332 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1333 if (process_id == cp->procinfo.dwProcessId)
1335 char window_class[32];
1337 GetClassName (hwnd, window_class, sizeof (window_class));
1338 if (strcmp (window_class,
1339 (os_subtype == OS_WIN95)
1340 ? "tty"
1341 : "ConsoleWindowClass") == 0)
1343 cp->hwnd = hwnd;
1344 return FALSE;
1347 /* keep looking */
1348 return TRUE;
1351 int
1352 sys_kill (int pid, int sig)
1354 child_process *cp;
1355 HANDLE proc_hand;
1356 int need_to_free = 0;
1357 int rc = 0;
1359 /* Only handle signals that will result in the process dying */
1360 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1362 errno = EINVAL;
1363 return -1;
1366 cp = find_child_pid (pid);
1367 if (cp == NULL)
1369 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1370 if (proc_hand == NULL)
1372 errno = EPERM;
1373 return -1;
1375 need_to_free = 1;
1377 else
1379 proc_hand = cp->procinfo.hProcess;
1380 pid = cp->procinfo.dwProcessId;
1382 /* Try to locate console window for process. */
1383 EnumWindows (find_child_console, (LPARAM) cp);
1386 if (sig == SIGINT)
1388 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1390 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1391 BYTE vk_break_code = VK_CANCEL;
1392 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1393 HWND foreground_window;
1395 if (break_scan_code == 0)
1397 /* Fake Ctrl-C if we can't manage Ctrl-Break. */
1398 vk_break_code = 'C';
1399 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1402 foreground_window = GetForegroundWindow ();
1403 if (foreground_window)
1405 /* NT 5.0, and apparently also Windows 98, will not allow
1406 a Window to be set to foreground directly without the
1407 user's involvement. The workaround is to attach
1408 ourselves to the thread that owns the foreground
1409 window, since that is the only thread that can set the
1410 foreground window. */
1411 DWORD foreground_thread, child_thread;
1412 foreground_thread =
1413 GetWindowThreadProcessId (foreground_window, NULL);
1414 if (foreground_thread == GetCurrentThreadId ()
1415 || !AttachThreadInput (GetCurrentThreadId (),
1416 foreground_thread, TRUE))
1417 foreground_thread = 0;
1419 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1420 if (child_thread == GetCurrentThreadId ()
1421 || !AttachThreadInput (GetCurrentThreadId (),
1422 child_thread, TRUE))
1423 child_thread = 0;
1425 /* Set the foreground window to the child. */
1426 if (SetForegroundWindow (cp->hwnd))
1428 /* Generate keystrokes as if user had typed Ctrl-Break or
1429 Ctrl-C. */
1430 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1431 keybd_event (vk_break_code, break_scan_code,
1432 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1433 keybd_event (vk_break_code, break_scan_code,
1434 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1435 | KEYEVENTF_KEYUP, 0);
1436 keybd_event (VK_CONTROL, control_scan_code,
1437 KEYEVENTF_KEYUP, 0);
1439 /* Sleep for a bit to give time for Emacs frame to respond
1440 to focus change events (if Emacs was active app). */
1441 Sleep (100);
1443 SetForegroundWindow (foreground_window);
1445 /* Detach from the foreground and child threads now that
1446 the foreground switching is over. */
1447 if (foreground_thread)
1448 AttachThreadInput (GetCurrentThreadId (),
1449 foreground_thread, FALSE);
1450 if (child_thread)
1451 AttachThreadInput (GetCurrentThreadId (),
1452 child_thread, FALSE);
1455 /* Ctrl-Break is NT equivalent of SIGINT. */
1456 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1458 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1459 "for pid %lu\n", GetLastError (), pid));
1460 errno = EINVAL;
1461 rc = -1;
1464 else
1466 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1468 #if 1
1469 if (os_subtype == OS_WIN95)
1472 Another possibility is to try terminating the VDM out-right by
1473 calling the Shell VxD (id 0x17) V86 interface, function #4
1474 "SHELL_Destroy_VM", ie.
1476 mov edx,4
1477 mov ebx,vm_handle
1478 call shellapi
1480 First need to determine the current VM handle, and then arrange for
1481 the shellapi call to be made from the system vm (by using
1482 Switch_VM_and_callback).
1484 Could try to invoke DestroyVM through CallVxD.
1487 #if 0
1488 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1489 to hang when cmdproxy is used in conjunction with
1490 command.com for an interactive shell. Posting
1491 WM_CLOSE pops up a dialog that, when Yes is selected,
1492 does the same thing. TerminateProcess is also less
1493 than ideal in that subprocesses tend to stick around
1494 until the machine is shutdown, but at least it
1495 doesn't freeze the 16-bit subsystem. */
1496 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1497 #endif
1498 if (!TerminateProcess (proc_hand, 0xff))
1500 DebPrint (("sys_kill.TerminateProcess returned %d "
1501 "for pid %lu\n", GetLastError (), pid));
1502 errno = EINVAL;
1503 rc = -1;
1506 else
1507 #endif
1508 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1510 /* Kill the process. On W32 this doesn't kill child processes
1511 so it doesn't work very well for shells which is why it's not
1512 used in every case. */
1513 else if (!TerminateProcess (proc_hand, 0xff))
1515 DebPrint (("sys_kill.TerminateProcess returned %d "
1516 "for pid %lu\n", GetLastError (), pid));
1517 errno = EINVAL;
1518 rc = -1;
1522 if (need_to_free)
1523 CloseHandle (proc_hand);
1525 return rc;
1528 /* extern int report_file_error (char *, Lisp_Object); */
1530 /* The following two routines are used to manipulate stdin, stdout, and
1531 stderr of our child processes.
1533 Assuming that in, out, and err are *not* inheritable, we make them
1534 stdin, stdout, and stderr of the child as follows:
1536 - Save the parent's current standard handles.
1537 - Set the std handles to inheritable duplicates of the ones being passed in.
1538 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1539 NT file handle for a crt file descriptor.)
1540 - Spawn the child, which inherits in, out, and err as stdin,
1541 stdout, and stderr. (see Spawnve)
1542 - Close the std handles passed to the child.
1543 - Reset the parent's standard handles to the saved handles.
1544 (see reset_standard_handles)
1545 We assume that the caller closes in, out, and err after calling us. */
1547 void
1548 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1550 HANDLE parent;
1551 HANDLE newstdin, newstdout, newstderr;
1553 parent = GetCurrentProcess ();
1555 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1556 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1557 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1559 /* make inheritable copies of the new handles */
1560 if (!DuplicateHandle (parent,
1561 (HANDLE) _get_osfhandle (in),
1562 parent,
1563 &newstdin,
1565 TRUE,
1566 DUPLICATE_SAME_ACCESS))
1567 report_file_error ("Duplicating input handle for child", Qnil);
1569 if (!DuplicateHandle (parent,
1570 (HANDLE) _get_osfhandle (out),
1571 parent,
1572 &newstdout,
1574 TRUE,
1575 DUPLICATE_SAME_ACCESS))
1576 report_file_error ("Duplicating output handle for child", Qnil);
1578 if (!DuplicateHandle (parent,
1579 (HANDLE) _get_osfhandle (err),
1580 parent,
1581 &newstderr,
1583 TRUE,
1584 DUPLICATE_SAME_ACCESS))
1585 report_file_error ("Duplicating error handle for child", Qnil);
1587 /* and store them as our std handles */
1588 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1589 report_file_error ("Changing stdin handle", Qnil);
1591 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1592 report_file_error ("Changing stdout handle", Qnil);
1594 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1595 report_file_error ("Changing stderr handle", Qnil);
1598 void
1599 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1601 /* close the duplicated handles passed to the child */
1602 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1603 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1604 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1606 /* now restore parent's saved std handles */
1607 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1608 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1609 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1612 void
1613 set_process_dir (char * dir)
1615 process_dir = dir;
1618 #ifdef HAVE_SOCKETS
1620 /* To avoid problems with winsock implementations that work over dial-up
1621 connections causing or requiring a connection to exist while Emacs is
1622 running, Emacs no longer automatically loads winsock on startup if it
1623 is present. Instead, it will be loaded when open-network-stream is
1624 first called.
1626 To allow full control over when winsock is loaded, we provide these
1627 two functions to dynamically load and unload winsock. This allows
1628 dial-up users to only be connected when they actually need to use
1629 socket services. */
1631 /* From nt.c */
1632 extern HANDLE winsock_lib;
1633 extern BOOL term_winsock (void);
1634 extern BOOL init_winsock (int load_now);
1636 extern Lisp_Object Vsystem_name;
1638 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1639 "Test for presence of the Windows socket library `winsock'.\n\
1640 Returns non-nil if winsock support is present, nil otherwise.\n\
1642 If the optional argument LOAD-NOW is non-nil, the winsock library is\n\
1643 also loaded immediately if not already loaded. If winsock is loaded,\n\
1644 the winsock local hostname is returned (since this may be different from\n\
1645 the value of `system-name' and should supplant it), otherwise t is\n\
1646 returned to indicate winsock support is present.")
1647 (load_now)
1648 Lisp_Object load_now;
1650 int have_winsock;
1652 have_winsock = init_winsock (!NILP (load_now));
1653 if (have_winsock)
1655 if (winsock_lib != NULL)
1657 /* Return new value for system-name. The best way to do this
1658 is to call init_system_name, saving and restoring the
1659 original value to avoid side-effects. */
1660 Lisp_Object orig_hostname = Vsystem_name;
1661 Lisp_Object hostname;
1663 init_system_name ();
1664 hostname = Vsystem_name;
1665 Vsystem_name = orig_hostname;
1666 return hostname;
1668 return Qt;
1670 return Qnil;
1673 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1674 0, 0, 0,
1675 "Unload the Windows socket library `winsock' if loaded.\n\
1676 This is provided to allow dial-up socket connections to be disconnected\n\
1677 when no longer needed. Returns nil without unloading winsock if any\n\
1678 socket connections still exist.")
1681 return term_winsock () ? Qt : Qnil;
1684 #endif /* HAVE_SOCKETS */
1687 /* Some miscellaneous functions that are Windows specific, but not GUI
1688 specific (ie. are applicable in terminal or batch mode as well). */
1690 /* lifted from fileio.c */
1691 #define CORRECT_DIR_SEPS(s) \
1692 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1693 else unixtodos_filename (s); \
1694 } while (0)
1696 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1697 "Return the short file name version (8.3) of the full path of FILENAME.\n\
1698 If FILENAME does not exist, return nil.\n\
1699 All path elements in FILENAME are converted to their short names.")
1700 (filename)
1701 Lisp_Object filename;
1703 char shortname[MAX_PATH];
1705 CHECK_STRING (filename, 0);
1707 /* first expand it. */
1708 filename = Fexpand_file_name (filename, Qnil);
1710 /* luckily, this returns the short version of each element in the path. */
1711 if (GetShortPathName (XSTRING (filename)->data, shortname, MAX_PATH) == 0)
1712 return Qnil;
1714 CORRECT_DIR_SEPS (shortname);
1716 return build_string (shortname);
1720 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1721 1, 1, 0,
1722 "Return the long file name version of the full path of FILENAME.\n\
1723 If FILENAME does not exist, return nil.\n\
1724 All path elements in FILENAME are converted to their long names.")
1725 (filename)
1726 Lisp_Object filename;
1728 char longname[ MAX_PATH ];
1730 CHECK_STRING (filename, 0);
1732 /* first expand it. */
1733 filename = Fexpand_file_name (filename, Qnil);
1735 if (!w32_get_long_filename (XSTRING (filename)->data, longname, MAX_PATH))
1736 return Qnil;
1738 CORRECT_DIR_SEPS (longname);
1740 return build_string (longname);
1743 DEFUN ("w32-set-process-priority", Fw32_set_process_priority, Sw32_set_process_priority,
1744 2, 2, 0,
1745 "Set the priority of PROCESS to PRIORITY.\n\
1746 If PROCESS is nil, the priority of Emacs is changed, otherwise the\n\
1747 priority of the process whose pid is PROCESS is changed.\n\
1748 PRIORITY should be one of the symbols high, normal, or low;\n\
1749 any other symbol will be interpreted as normal.\n\
1751 If successful, the return value is t, otherwise nil.")
1752 (process, priority)
1753 Lisp_Object process, priority;
1755 HANDLE proc_handle = GetCurrentProcess ();
1756 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1757 Lisp_Object result = Qnil;
1759 CHECK_SYMBOL (priority, 0);
1761 if (!NILP (process))
1763 DWORD pid;
1764 child_process *cp;
1766 CHECK_NUMBER (process, 0);
1768 /* Allow pid to be an internally generated one, or one obtained
1769 externally. This is necessary because real pids on Win95 are
1770 negative. */
1772 pid = XINT (process);
1773 cp = find_child_pid (pid);
1774 if (cp != NULL)
1775 pid = cp->procinfo.dwProcessId;
1777 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1780 if (EQ (priority, Qhigh))
1781 priority_class = HIGH_PRIORITY_CLASS;
1782 else if (EQ (priority, Qlow))
1783 priority_class = IDLE_PRIORITY_CLASS;
1785 if (proc_handle != NULL)
1787 if (SetPriorityClass (proc_handle, priority_class))
1788 result = Qt;
1789 if (!NILP (process))
1790 CloseHandle (proc_handle);
1793 return result;
1797 DEFUN ("w32-get-locale-info", Fw32_get_locale_info, Sw32_get_locale_info, 1, 2, 0,
1798 "Return information about the Windows locale LCID.\n\
1799 By default, return a three letter locale code which encodes the default\n\
1800 language as the first two characters, and the country or regionial variant\n\
1801 as the third letter. For example, ENU refers to `English (United States)',\n\
1802 while ENC means `English (Canadian)'.\n\
1804 If the optional argument LONGFORM is t, the long form of the locale\n\
1805 name is returned, e.g. `English (United States)' instead; if LONGFORM\n\
1806 is a number, it is interpreted as an LCTYPE constant and the corresponding\n\
1807 locale information is returned.\n\
1809 If LCID (a 16-bit number) is not a valid locale, the result is nil.")
1810 (lcid, longform)
1811 Lisp_Object lcid, longform;
1813 int got_abbrev;
1814 int got_full;
1815 char abbrev_name[32] = { 0 };
1816 char full_name[256] = { 0 };
1818 CHECK_NUMBER (lcid, 0);
1820 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1821 return Qnil;
1823 if (NILP (longform))
1825 got_abbrev = GetLocaleInfo (XINT (lcid),
1826 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1827 abbrev_name, sizeof (abbrev_name));
1828 if (got_abbrev)
1829 return build_string (abbrev_name);
1831 else if (EQ (longform, Qt))
1833 got_full = GetLocaleInfo (XINT (lcid),
1834 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1835 full_name, sizeof (full_name));
1836 if (got_full)
1837 return build_string (full_name);
1839 else if (NUMBERP (longform))
1841 got_full = GetLocaleInfo (XINT (lcid),
1842 XINT (longform),
1843 full_name, sizeof (full_name));
1844 if (got_full)
1845 return make_unibyte_string (full_name, got_full);
1848 return Qnil;
1852 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id, Sw32_get_current_locale_id, 0, 0, 0,
1853 "Return Windows locale id for current locale setting.\n\
1854 This is a numerical value; use `w32-get-locale-info' to convert to a\n\
1855 human-readable form.")
1858 return make_number (GetThreadLocale ());
1861 DWORD int_from_hex (char * s)
1863 DWORD val = 0;
1864 static char hex[] = "0123456789abcdefABCDEF";
1865 char * p;
1867 while (*s && (p = strchr(hex, *s)) != NULL)
1869 unsigned digit = p - hex;
1870 if (digit > 15)
1871 digit -= 6;
1872 val = val * 16 + digit;
1873 s++;
1875 return val;
1878 /* We need to build a global list, since the EnumSystemLocale callback
1879 function isn't given a context pointer. */
1880 Lisp_Object Vw32_valid_locale_ids;
1882 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
1884 DWORD id = int_from_hex (localeNum);
1885 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
1886 return TRUE;
1889 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids, Sw32_get_valid_locale_ids, 0, 0, 0,
1890 "Return list of all valid Windows locale ids.\n\
1891 Each id is a numerical value; use `w32-get-locale-info' to convert to a\n\
1892 human-readable form.")
1895 Vw32_valid_locale_ids = Qnil;
1897 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
1899 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
1900 return Vw32_valid_locale_ids;
1904 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
1905 "Return Windows locale id for default locale setting.\n\
1906 By default, the system default locale setting is returned; if the optional\n\
1907 parameter USERP is non-nil, the user default locale setting is returned.\n\
1908 This is a numerical value; use `w32-get-locale-info' to convert to a\n\
1909 human-readable form.")
1910 (userp)
1911 Lisp_Object userp;
1913 if (NILP (userp))
1914 return make_number (GetSystemDefaultLCID ());
1915 return make_number (GetUserDefaultLCID ());
1919 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
1920 "Make Windows locale LCID be the current locale setting for Emacs.\n\
1921 If successful, the new locale id is returned, otherwise nil.")
1922 (lcid)
1923 Lisp_Object lcid;
1925 CHECK_NUMBER (lcid, 0);
1927 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1928 return Qnil;
1930 if (!SetThreadLocale (XINT (lcid)))
1931 return Qnil;
1933 /* Need to set input thread locale if present. */
1934 if (dwWindowsThreadId)
1935 /* Reply is not needed. */
1936 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
1938 return make_number (GetThreadLocale ());
1942 /* We need to build a global list, since the EnumCodePages callback
1943 function isn't given a context pointer. */
1944 Lisp_Object Vw32_valid_codepages;
1946 BOOL CALLBACK enum_codepage_fn (LPTSTR codepageNum)
1948 DWORD id = atoi (codepageNum);
1949 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
1950 return TRUE;
1953 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages, Sw32_get_valid_codepages, 0, 0, 0,
1954 "Return list of all valid Windows codepages.")
1957 Vw32_valid_codepages = Qnil;
1959 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
1961 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
1962 return Vw32_valid_codepages;
1966 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage, Sw32_get_console_codepage, 0, 0, 0,
1967 "Return current Windows codepage for console input.")
1970 return make_number (GetConsoleCP ());
1974 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage, Sw32_set_console_codepage, 1, 1, 0,
1975 "Make Windows codepage CP be the current codepage setting for Emacs.\n\
1976 The codepage setting affects keyboard input and display in tty mode.\n\
1977 If successful, the new CP is returned, otherwise nil.")
1978 (cp)
1979 Lisp_Object cp;
1981 CHECK_NUMBER (cp, 0);
1983 if (!IsValidCodePage (XINT (cp)))
1984 return Qnil;
1986 if (!SetConsoleCP (XINT (cp)))
1987 return Qnil;
1989 return make_number (GetConsoleCP ());
1993 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage, Sw32_get_console_output_codepage, 0, 0, 0,
1994 "Return current Windows codepage for console output.")
1997 return make_number (GetConsoleOutputCP ());
2001 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage, Sw32_set_console_output_codepage, 1, 1, 0,
2002 "Make Windows codepage CP be the current codepage setting for Emacs.\n\
2003 The codepage setting affects keyboard input and display in tty mode.\n\
2004 If successful, the new CP is returned, otherwise nil.")
2005 (cp)
2006 Lisp_Object cp;
2008 CHECK_NUMBER (cp, 0);
2010 if (!IsValidCodePage (XINT (cp)))
2011 return Qnil;
2013 if (!SetConsoleOutputCP (XINT (cp)))
2014 return Qnil;
2016 return make_number (GetConsoleOutputCP ());
2020 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset, Sw32_get_codepage_charset, 1, 1, 0,
2021 "Return charset of codepage CP.\n\
2022 Returns nil if the codepage is not valid.")
2023 (cp)
2024 Lisp_Object cp;
2026 CHARSETINFO info;
2028 CHECK_NUMBER (cp, 0);
2030 if (!IsValidCodePage (XINT (cp)))
2031 return Qnil;
2033 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2034 return make_number (info.ciCharset);
2036 return Qnil;
2040 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts, Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2041 "Return list of Windows keyboard languages and layouts.\n\
2042 The return value is a list of pairs of language id and layout id.")
2045 int num_layouts = GetKeyboardLayoutList (0, NULL);
2046 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2047 Lisp_Object obj = Qnil;
2049 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2051 while (--num_layouts >= 0)
2053 DWORD kl = (DWORD) layouts[num_layouts];
2055 obj = Fcons (Fcons (make_number (kl & 0xffff),
2056 make_number ((kl >> 16) & 0xffff)),
2057 obj);
2061 return obj;
2065 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout, Sw32_get_keyboard_layout, 0, 0, 0,
2066 "Return current Windows keyboard language and layout.\n\
2067 The return value is the cons of the language id and the layout id.")
2070 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2072 return Fcons (make_number (kl & 0xffff),
2073 make_number ((kl >> 16) & 0xffff));
2077 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout, Sw32_set_keyboard_layout, 1, 1, 0,
2078 "Make LAYOUT be the current keyboard layout for Emacs.\n\
2079 The keyboard layout setting affects interpretation of keyboard input.\n\
2080 If successful, the new layout id is returned, otherwise nil.")
2081 (layout)
2082 Lisp_Object layout;
2084 DWORD kl;
2086 CHECK_CONS (layout, 0);
2087 CHECK_NUMBER (XCAR (layout), 0);
2088 CHECK_NUMBER (XCDR (layout), 0);
2090 kl = (XINT (XCAR (layout)) & 0xffff)
2091 | (XINT (XCDR (layout)) << 16);
2093 /* Synchronize layout with input thread. */
2094 if (dwWindowsThreadId)
2096 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2097 (WPARAM) kl, 0))
2099 MSG msg;
2100 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2102 if (msg.wParam == 0)
2103 return Qnil;
2106 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2107 return Qnil;
2109 return Fw32_get_keyboard_layout ();
2113 syms_of_ntproc ()
2115 Qhigh = intern ("high");
2116 Qlow = intern ("low");
2118 #ifdef HAVE_SOCKETS
2119 defsubr (&Sw32_has_winsock);
2120 defsubr (&Sw32_unload_winsock);
2121 #endif
2122 defsubr (&Sw32_short_file_name);
2123 defsubr (&Sw32_long_file_name);
2124 defsubr (&Sw32_set_process_priority);
2125 defsubr (&Sw32_get_locale_info);
2126 defsubr (&Sw32_get_current_locale_id);
2127 defsubr (&Sw32_get_default_locale_id);
2128 defsubr (&Sw32_get_valid_locale_ids);
2129 defsubr (&Sw32_set_current_locale);
2131 defsubr (&Sw32_get_console_codepage);
2132 defsubr (&Sw32_set_console_codepage);
2133 defsubr (&Sw32_get_console_output_codepage);
2134 defsubr (&Sw32_set_console_output_codepage);
2135 defsubr (&Sw32_get_valid_codepages);
2136 defsubr (&Sw32_get_codepage_charset);
2138 defsubr (&Sw32_get_valid_keyboard_layouts);
2139 defsubr (&Sw32_get_keyboard_layout);
2140 defsubr (&Sw32_set_keyboard_layout);
2142 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args,
2143 "Non-nil enables quoting of process arguments to ensure correct parsing.\n\
2144 Because Windows does not directly pass argv arrays to child processes,\n\
2145 programs have to reconstruct the argv array by parsing the command\n\
2146 line string. For an argument to contain a space, it must be enclosed\n\
2147 in double quotes or it will be parsed as multiple arguments.\n\
2149 If the value is a character, that character will be used to escape any\n\
2150 quote characters that appear, otherwise a suitable escape character\n\
2151 will be chosen based on the type of the program.");
2152 Vw32_quote_process_args = Qt;
2154 DEFVAR_LISP ("w32-start-process-show-window",
2155 &Vw32_start_process_show_window,
2156 "When nil, new child processes hide their windows.\n\
2157 When non-nil, they show their window in the method of their choice.");
2158 Vw32_start_process_show_window = Qnil;
2160 DEFVAR_LISP ("w32-start-process-share-console",
2161 &Vw32_start_process_share_console,
2162 "When nil, new child processes are given a new console.\n\
2163 When non-nil, they share the Emacs console; this has the limitation of\n\
2164 allowing only only DOS subprocess to run at a time (whether started directly\n\
2165 or indirectly by Emacs), and preventing Emacs from cleanly terminating the\n\
2166 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't\n\
2167 otherwise respond to interrupts from Emacs.");
2168 Vw32_start_process_share_console = Qnil;
2170 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2171 &Vw32_start_process_inherit_error_mode,
2172 "When nil, new child processes revert to the default error mode.\n\
2173 When non-nil, they inherit their error mode setting from Emacs, which stops\n\
2174 them blocking when trying to access unmounted drives etc.");
2175 Vw32_start_process_inherit_error_mode = Qt;
2177 DEFVAR_INT ("w32-pipe-read-delay", &Vw32_pipe_read_delay,
2178 "Forced delay before reading subprocess output.\n\
2179 This is done to improve the buffering of subprocess output, by\n\
2180 avoiding the inefficiency of frequently reading small amounts of data.\n\
2182 If positive, the value is the number of milliseconds to sleep before\n\
2183 reading the subprocess output. If negative, the magnitude is the number\n\
2184 of time slices to wait (effectively boosting the priority of the child\n\
2185 process temporarily). A value of zero disables waiting entirely.");
2186 Vw32_pipe_read_delay = 50;
2188 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names,
2189 "Non-nil means convert all-upper case file names to lower case.\n\
2190 This applies when performing completions and file name expansion.\n\
2191 Note that the value of this setting also affects remote file names,\n\
2192 so you probably don't want to set to non-nil if you use case-sensitive\n\
2193 filesystems via ange-ftp.");
2194 Vw32_downcase_file_names = Qnil;
2196 #if 0
2197 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes,
2198 "Non-nil means attempt to fake realistic inode values.\n\
2199 This works by hashing the truename of files, and should detect \n\
2200 aliasing between long and short (8.3 DOS) names, but can have\n\
2201 false positives because of hash collisions. Note that determing\n\
2202 the truename of a file can be slow.");
2203 Vw32_generate_fake_inodes = Qnil;
2204 #endif
2206 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes,
2207 "Non-nil means determine accurate link count in file-attributes.\n\
2208 This option slows down file-attributes noticeably, so is disabled by\n\
2209 default. Note that it is only useful for files on NTFS volumes,\n\
2210 where hard links are supported.");
2211 Vw32_get_true_file_attributes = Qnil;
2213 /* end of ntproc.c */