* configure.in: Fix last change.
[emacs.git] / src / w32proc.c
blob5bdeba259587ff35847a7a84dd62394a25fbc5c5
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999-2012 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 3 of the License, or
9 (at your option) 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. If not, see <http://www.gnu.org/licenses/>. */
20 Drew Bliss Oct 14, 1993
21 Adapted from alarm.c by Tim Fleehart
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <io.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <sys/file.h>
31 #include <setjmp.h>
33 /* must include CRT headers *before* config.h */
34 #include <config.h>
36 #undef signal
37 #undef wait
38 #undef spawnve
39 #undef select
40 #undef kill
42 #include <windows.h>
43 #ifdef __GNUC__
44 /* This definition is missing from mingw32 headers. */
45 extern BOOL WINAPI IsValidLocale (LCID, DWORD);
46 #endif
48 #ifdef HAVE_LANGINFO_CODESET
49 #include <nl_types.h>
50 #include <langinfo.h>
51 #endif
53 #include "lisp.h"
54 #include "w32.h"
55 #include "w32heap.h"
56 #include "systime.h"
57 #include "syswait.h"
58 #include "process.h"
59 #include "syssignal.h"
60 #include "w32term.h"
61 #include "dispextern.h" /* for xstrcasecmp */
62 #include "coding.h"
64 #define RVA_TO_PTR(var,section,filedata) \
65 ((void *)((section)->PointerToRawData \
66 + ((DWORD)(var) - (section)->VirtualAddress) \
67 + (filedata).file_base))
69 Lisp_Object Qhigh, Qlow;
71 #ifdef EMACSDEBUG
72 void
73 _DebPrint (const char *fmt, ...)
75 char buf[1024];
76 va_list args;
78 va_start (args, fmt);
79 vsprintf (buf, fmt, args);
80 va_end (args);
81 OutputDebugString (buf);
83 #endif
85 typedef void (_CALLBACK_ *signal_handler) (int);
87 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
88 static signal_handler sig_handlers[NSIG];
90 /* Fake signal implementation to record the SIGCHLD handler. */
91 signal_handler
92 sys_signal (int sig, signal_handler handler)
94 signal_handler old;
96 if (sig != SIGCHLD)
98 errno = EINVAL;
99 return SIG_ERR;
101 old = sig_handlers[sig];
102 sig_handlers[sig] = handler;
103 return old;
106 /* Defined in <process.h> which conflicts with the local copy */
107 #define _P_NOWAIT 1
109 /* Child process management list. */
110 int child_proc_count = 0;
111 child_process child_procs[ MAX_CHILDREN ];
112 child_process *dead_child = NULL;
114 static DWORD WINAPI reader_thread (void *arg);
116 /* Find an unused process slot. */
117 child_process *
118 new_child (void)
120 child_process *cp;
121 DWORD id;
123 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
124 if (!CHILD_ACTIVE (cp))
125 goto Initialize;
126 if (child_proc_count == MAX_CHILDREN)
127 return NULL;
128 cp = &child_procs[child_proc_count++];
130 Initialize:
131 memset (cp, 0, sizeof (*cp));
132 cp->fd = -1;
133 cp->pid = -1;
134 cp->procinfo.hProcess = NULL;
135 cp->status = STATUS_READ_ERROR;
137 /* use manual reset event so that select() will function properly */
138 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
139 if (cp->char_avail)
141 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
142 if (cp->char_consumed)
144 /* The 0x00010000 flag is STACK_SIZE_PARAM_IS_A_RESERVATION.
145 It means that the 64K stack we are requesting in the 2nd
146 argument is how much memory should be reserved for the
147 stack. If we don't use this flag, the memory requested
148 by the 2nd argument is the amount actually _committed_,
149 but Windows reserves 8MB of memory for each thread's
150 stack. (The 8MB figure comes from the -stack
151 command-line argument we pass to the linker when building
152 Emacs, but that's because we need a large stack for
153 Emacs's main thread.) Since we request 2GB of reserved
154 memory at startup (see w32heap.c), which is close to the
155 maximum memory available for a 32-bit process on Windows,
156 the 8MB reservation for each thread causes failures in
157 starting subprocesses, because we create a thread running
158 reader_thread for each subprocess. As 8MB of stack is
159 way too much for reader_thread, forcing Windows to
160 reserve less wins the day. */
161 cp->thrd = CreateThread (NULL, 64 * 1024, reader_thread, cp,
162 0x00010000, &id);
163 if (cp->thrd)
164 return cp;
167 delete_child (cp);
168 return NULL;
171 void
172 delete_child (child_process *cp)
174 int i;
176 /* Should not be deleting a child that is still needed. */
177 for (i = 0; i < MAXDESC; i++)
178 if (fd_info[i].cp == cp)
179 abort ();
181 if (!CHILD_ACTIVE (cp))
182 return;
184 /* reap thread if necessary */
185 if (cp->thrd)
187 DWORD rc;
189 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
191 /* let the thread exit cleanly if possible */
192 cp->status = STATUS_READ_ERROR;
193 SetEvent (cp->char_consumed);
194 #if 0
195 /* We used to forcibly terminate the thread here, but it
196 is normally unnecessary, and in abnormal cases, the worst that
197 will happen is we have an extra idle thread hanging around
198 waiting for the zombie process. */
199 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
201 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
202 "with %lu for fd %ld\n", GetLastError (), cp->fd));
203 TerminateThread (cp->thrd, 0);
205 #endif
207 CloseHandle (cp->thrd);
208 cp->thrd = NULL;
210 if (cp->char_avail)
212 CloseHandle (cp->char_avail);
213 cp->char_avail = NULL;
215 if (cp->char_consumed)
217 CloseHandle (cp->char_consumed);
218 cp->char_consumed = NULL;
221 /* update child_proc_count (highest numbered slot in use plus one) */
222 if (cp == child_procs + child_proc_count - 1)
224 for (i = child_proc_count-1; i >= 0; i--)
225 if (CHILD_ACTIVE (&child_procs[i]))
227 child_proc_count = i + 1;
228 break;
231 if (i < 0)
232 child_proc_count = 0;
235 /* Find a child by pid. */
236 static child_process *
237 find_child_pid (DWORD pid)
239 child_process *cp;
241 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
242 if (CHILD_ACTIVE (cp) && pid == cp->pid)
243 return cp;
244 return NULL;
248 /* Thread proc for child process and socket reader threads. Each thread
249 is normally blocked until woken by select() to check for input by
250 reading one char. When the read completes, char_avail is signaled
251 to wake up the select emulator and the thread blocks itself again. */
252 static DWORD WINAPI
253 reader_thread (void *arg)
255 child_process *cp;
257 /* Our identity */
258 cp = (child_process *)arg;
260 /* We have to wait for the go-ahead before we can start */
261 if (cp == NULL
262 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
263 || cp->fd < 0)
264 return 1;
266 for (;;)
268 int rc;
270 if (fd_info[cp->fd].flags & FILE_LISTEN)
271 rc = _sys_wait_accept (cp->fd);
272 else
273 rc = _sys_read_ahead (cp->fd);
275 /* The name char_avail is a misnomer - it really just means the
276 read-ahead has completed, whether successfully or not. */
277 if (!SetEvent (cp->char_avail))
279 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
280 GetLastError (), cp->fd));
281 return 1;
284 if (rc == STATUS_READ_ERROR)
285 return 1;
287 /* If the read died, the child has died so let the thread die */
288 if (rc == STATUS_READ_FAILED)
289 break;
291 /* Wait until our input is acknowledged before reading again */
292 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
294 DebPrint (("reader_thread.WaitForSingleObject failed with "
295 "%lu for fd %ld\n", GetLastError (), cp->fd));
296 break;
299 return 0;
302 /* To avoid Emacs changing directory, we just record here the directory
303 the new process should start in. This is set just before calling
304 sys_spawnve, and is not generally valid at any other time. */
305 static char * process_dir;
307 static BOOL
308 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
309 int * pPid, child_process *cp)
311 STARTUPINFO start;
312 SECURITY_ATTRIBUTES sec_attrs;
313 #if 0
314 SECURITY_DESCRIPTOR sec_desc;
315 #endif
316 DWORD flags;
317 char dir[ MAXPATHLEN ];
319 if (cp == NULL) abort ();
321 memset (&start, 0, sizeof (start));
322 start.cb = sizeof (start);
324 #ifdef HAVE_NTGUI
325 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
326 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
327 else
328 start.dwFlags = STARTF_USESTDHANDLES;
329 start.wShowWindow = SW_HIDE;
331 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
332 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
333 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
334 #endif /* HAVE_NTGUI */
336 #if 0
337 /* Explicitly specify no security */
338 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
339 goto EH_Fail;
340 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
341 goto EH_Fail;
342 #endif
343 sec_attrs.nLength = sizeof (sec_attrs);
344 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
345 sec_attrs.bInheritHandle = FALSE;
347 strcpy (dir, process_dir);
348 unixtodos_filename (dir);
350 flags = (!NILP (Vw32_start_process_share_console)
351 ? CREATE_NEW_PROCESS_GROUP
352 : CREATE_NEW_CONSOLE);
353 if (NILP (Vw32_start_process_inherit_error_mode))
354 flags |= CREATE_DEFAULT_ERROR_MODE;
355 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
356 flags, env, dir, &start, &cp->procinfo))
357 goto EH_Fail;
359 cp->pid = (int) cp->procinfo.dwProcessId;
361 /* Hack for Windows 95, which assigns large (ie negative) pids */
362 if (cp->pid < 0)
363 cp->pid = -cp->pid;
365 /* pid must fit in a Lisp_Int */
366 cp->pid = cp->pid & INTMASK;
368 *pPid = cp->pid;
370 return TRUE;
372 EH_Fail:
373 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
374 return FALSE;
377 /* create_child doesn't know what emacs' file handle will be for waiting
378 on output from the child, so we need to make this additional call
379 to register the handle with the process
380 This way the select emulator knows how to match file handles with
381 entries in child_procs. */
382 void
383 register_child (int pid, int fd)
385 child_process *cp;
387 cp = find_child_pid (pid);
388 if (cp == NULL)
390 DebPrint (("register_child unable to find pid %lu\n", pid));
391 return;
394 #ifdef FULL_DEBUG
395 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
396 #endif
398 cp->fd = fd;
400 /* thread is initially blocked until select is called; set status so
401 that select will release thread */
402 cp->status = STATUS_READ_ACKNOWLEDGED;
404 /* attach child_process to fd_info */
405 if (fd_info[fd].cp != NULL)
407 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
408 abort ();
411 fd_info[fd].cp = cp;
414 /* When a process dies its pipe will break so the reader thread will
415 signal failure to the select emulator.
416 The select emulator then calls this routine to clean up.
417 Since the thread signaled failure we can assume it is exiting. */
418 static void
419 reap_subprocess (child_process *cp)
421 if (cp->procinfo.hProcess)
423 /* Reap the process */
424 #ifdef FULL_DEBUG
425 /* Process should have already died before we are called. */
426 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
427 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
428 #endif
429 CloseHandle (cp->procinfo.hProcess);
430 cp->procinfo.hProcess = NULL;
431 CloseHandle (cp->procinfo.hThread);
432 cp->procinfo.hThread = NULL;
435 /* For asynchronous children, the child_proc resources will be freed
436 when the last pipe read descriptor is closed; for synchronous
437 children, we must explicitly free the resources now because
438 register_child has not been called. */
439 if (cp->fd == -1)
440 delete_child (cp);
443 /* Wait for any of our existing child processes to die
444 When it does, close its handle
445 Return the pid and fill in the status if non-NULL. */
448 sys_wait (int *status)
450 DWORD active, retval;
451 int nh;
452 int pid;
453 child_process *cp, *cps[MAX_CHILDREN];
454 HANDLE wait_hnd[MAX_CHILDREN];
456 nh = 0;
457 if (dead_child != NULL)
459 /* We want to wait for a specific child */
460 wait_hnd[nh] = dead_child->procinfo.hProcess;
461 cps[nh] = dead_child;
462 if (!wait_hnd[nh]) abort ();
463 nh++;
464 active = 0;
465 goto get_result;
467 else
469 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
470 /* some child_procs might be sockets; ignore them */
471 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
472 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
474 wait_hnd[nh] = cp->procinfo.hProcess;
475 cps[nh] = cp;
476 nh++;
480 if (nh == 0)
482 /* Nothing to wait on, so fail */
483 errno = ECHILD;
484 return -1;
489 /* Check for quit about once a second. */
490 QUIT;
491 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
492 } while (active == WAIT_TIMEOUT);
494 if (active == WAIT_FAILED)
496 errno = EBADF;
497 return -1;
499 else if (active >= WAIT_OBJECT_0
500 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
502 active -= WAIT_OBJECT_0;
504 else if (active >= WAIT_ABANDONED_0
505 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
507 active -= WAIT_ABANDONED_0;
509 else
510 abort ();
512 get_result:
513 if (!GetExitCodeProcess (wait_hnd[active], &retval))
515 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
516 GetLastError ()));
517 retval = 1;
519 if (retval == STILL_ACTIVE)
521 /* Should never happen */
522 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
523 errno = EINVAL;
524 return -1;
527 /* Massage the exit code from the process to match the format expected
528 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
529 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
531 if (retval == STATUS_CONTROL_C_EXIT)
532 retval = SIGINT;
533 else
534 retval <<= 8;
536 cp = cps[active];
537 pid = cp->pid;
538 #ifdef FULL_DEBUG
539 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
540 #endif
542 if (status)
544 *status = retval;
546 else if (synch_process_alive)
548 synch_process_alive = 0;
550 /* Report the status of the synchronous process. */
551 if (WIFEXITED (retval))
552 synch_process_retcode = WRETCODE (retval);
553 else if (WIFSIGNALED (retval))
555 int code = WTERMSIG (retval);
556 char *signame;
558 synchronize_system_messages_locale ();
559 signame = strsignal (code);
561 if (signame == 0)
562 signame = "unknown";
564 synch_process_death = signame;
567 reap_subprocess (cp);
570 reap_subprocess (cp);
572 return pid;
575 /* Old versions of w32api headers don't have separate 32-bit and
576 64-bit defines, but the one they have matches the 32-bit variety. */
577 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
578 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
579 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
580 #endif
582 static void
583 w32_executable_type (char * filename,
584 int * is_dos_app,
585 int * is_cygnus_app,
586 int * is_gui_app)
588 file_data executable;
589 char * p;
591 /* Default values in case we can't tell for sure. */
592 *is_dos_app = FALSE;
593 *is_cygnus_app = FALSE;
594 *is_gui_app = FALSE;
596 if (!open_input_file (&executable, filename))
597 return;
599 p = strrchr (filename, '.');
601 /* We can only identify DOS .com programs from the extension. */
602 if (p && xstrcasecmp (p, ".com") == 0)
603 *is_dos_app = TRUE;
604 else if (p && (xstrcasecmp (p, ".bat") == 0
605 || xstrcasecmp (p, ".cmd") == 0))
607 /* A DOS shell script - it appears that CreateProcess is happy to
608 accept this (somewhat surprisingly); presumably it looks at
609 COMSPEC to determine what executable to actually invoke.
610 Therefore, we have to do the same here as well. */
611 /* Actually, I think it uses the program association for that
612 extension, which is defined in the registry. */
613 p = egetenv ("COMSPEC");
614 if (p)
615 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
617 else
619 /* Look for DOS .exe signature - if found, we must also check that
620 it isn't really a 16- or 32-bit Windows exe, since both formats
621 start with a DOS program stub. Note that 16-bit Windows
622 executables use the OS/2 1.x format. */
624 IMAGE_DOS_HEADER * dos_header;
625 IMAGE_NT_HEADERS * nt_header;
627 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
628 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
629 goto unwind;
631 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
633 if ((char *) nt_header > (char *) dos_header + executable.size)
635 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
636 *is_dos_app = TRUE;
638 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
639 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
641 *is_dos_app = TRUE;
643 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
645 IMAGE_DATA_DIRECTORY *data_dir = NULL;
646 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
648 /* Ensure we are using the 32 bit structure. */
649 IMAGE_OPTIONAL_HEADER32 *opt
650 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
651 data_dir = opt->DataDirectory;
652 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
654 /* MingW 3.12 has the required 64 bit structs, but in case older
655 versions don't, only check 64 bit exes if we know how. */
656 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
657 else if (nt_header->OptionalHeader.Magic
658 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
660 IMAGE_OPTIONAL_HEADER64 *opt
661 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
662 data_dir = opt->DataDirectory;
663 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
665 #endif
666 if (data_dir)
668 /* Look for cygwin.dll in DLL import list. */
669 IMAGE_DATA_DIRECTORY import_dir =
670 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
671 IMAGE_IMPORT_DESCRIPTOR * imports;
672 IMAGE_SECTION_HEADER * section;
674 section = rva_to_section (import_dir.VirtualAddress, nt_header);
675 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
676 executable);
678 for ( ; imports->Name; imports++)
680 char * dllname = RVA_TO_PTR (imports->Name, section,
681 executable);
683 /* The exact name of the cygwin dll has changed with
684 various releases, but hopefully this will be reasonably
685 future proof. */
686 if (strncmp (dllname, "cygwin", 6) == 0)
688 *is_cygnus_app = TRUE;
689 break;
696 unwind:
697 close_file_data (&executable);
700 static int
701 compare_env (const void *strp1, const void *strp2)
703 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
705 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
707 /* Sort order in command.com/cmd.exe is based on uppercasing
708 names, so do the same here. */
709 if (toupper (*str1) > toupper (*str2))
710 return 1;
711 else if (toupper (*str1) < toupper (*str2))
712 return -1;
713 str1++, str2++;
716 if (*str1 == '=' && *str2 == '=')
717 return 0;
718 else if (*str1 == '=')
719 return -1;
720 else
721 return 1;
724 static void
725 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
727 char **optr, **nptr;
728 int num;
730 nptr = new_envp;
731 optr = envp1;
732 while (*optr)
733 *nptr++ = *optr++;
734 num = optr - envp1;
736 optr = envp2;
737 while (*optr)
738 *nptr++ = *optr++;
739 num += optr - envp2;
741 qsort (new_envp, num, sizeof (char *), compare_env);
743 *nptr = NULL;
746 /* When a new child process is created we need to register it in our list,
747 so intercept spawn requests. */
749 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
751 Lisp_Object program, full;
752 char *cmdline, *env, *parg, **targ;
753 int arglen, numenv;
754 int pid;
755 child_process *cp;
756 int is_dos_app, is_cygnus_app, is_gui_app;
757 int do_quoting = 0;
758 char escape_char;
759 /* We pass our process ID to our children by setting up an environment
760 variable in their environment. */
761 char ppid_env_var_buffer[64];
762 char *extra_env[] = {ppid_env_var_buffer, NULL};
763 /* These are the characters that cause an argument to need quoting.
764 Arguments with whitespace characters need quoting to prevent the
765 argument being split into two or more. Arguments with wildcards
766 are also quoted, for consistency with posix platforms, where wildcards
767 are not expanded if we run the program directly without a shell.
768 Some extra whitespace characters need quoting in Cygwin programs,
769 so this list is conditionally modified below. */
770 char *sepchars = " \t*?";
772 /* We don't care about the other modes */
773 if (mode != _P_NOWAIT)
775 errno = EINVAL;
776 return -1;
779 /* Handle executable names without an executable suffix. */
780 program = make_string (cmdname, strlen (cmdname));
781 if (NILP (Ffile_executable_p (program)))
783 struct gcpro gcpro1;
785 full = Qnil;
786 GCPRO1 (program);
787 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
788 UNGCPRO;
789 if (NILP (full))
791 errno = EINVAL;
792 return -1;
794 program = full;
797 /* make sure argv[0] and cmdname are both in DOS format */
798 cmdname = SDATA (program);
799 unixtodos_filename (cmdname);
800 argv[0] = cmdname;
802 /* Determine whether program is a 16-bit DOS executable, or a w32
803 executable that is implicitly linked to the Cygnus dll (implying it
804 was compiled with the Cygnus GNU toolchain and hence relies on
805 cygwin.dll to parse the command line - we use this to decide how to
806 escape quote chars in command line args that must be quoted).
808 Also determine whether it is a GUI app, so that we don't hide its
809 initial window unless specifically requested. */
810 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
812 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
813 application to start it by specifying the helper app as cmdname,
814 while leaving the real app name as argv[0]. */
815 if (is_dos_app)
817 cmdname = alloca (MAXPATHLEN);
818 if (egetenv ("CMDPROXY"))
819 strcpy (cmdname, egetenv ("CMDPROXY"));
820 else
822 strcpy (cmdname, SDATA (Vinvocation_directory));
823 strcat (cmdname, "cmdproxy.exe");
825 unixtodos_filename (cmdname);
828 /* we have to do some conjuring here to put argv and envp into the
829 form CreateProcess wants... argv needs to be a space separated/null
830 terminated list of parameters, and envp is a null
831 separated/double-null terminated list of parameters.
833 Additionally, zero-length args and args containing whitespace or
834 quote chars need to be wrapped in double quotes - for this to work,
835 embedded quotes need to be escaped as well. The aim is to ensure
836 the child process reconstructs the argv array we start with
837 exactly, so we treat quotes at the beginning and end of arguments
838 as embedded quotes.
840 The w32 GNU-based library from Cygnus doubles quotes to escape
841 them, while MSVC uses backslash for escaping. (Actually the MSVC
842 startup code does attempt to recognize doubled quotes and accept
843 them, but gets it wrong and ends up requiring three quotes to get a
844 single embedded quote!) So by default we decide whether to use
845 quote or backslash as the escape character based on whether the
846 binary is apparently a Cygnus compiled app.
848 Note that using backslash to escape embedded quotes requires
849 additional special handling if an embedded quote is already
850 preceded by backslash, or if an arg requiring quoting ends with
851 backslash. In such cases, the run of escape characters needs to be
852 doubled. For consistency, we apply this special handling as long
853 as the escape character is not quote.
855 Since we have no idea how large argv and envp are likely to be we
856 figure out list lengths on the fly and allocate them. */
858 if (!NILP (Vw32_quote_process_args))
860 do_quoting = 1;
861 /* Override escape char by binding w32-quote-process-args to
862 desired character, or use t for auto-selection. */
863 if (INTEGERP (Vw32_quote_process_args))
864 escape_char = XINT (Vw32_quote_process_args);
865 else
866 escape_char = is_cygnus_app ? '"' : '\\';
869 /* Cygwin apps needs quoting a bit more often. */
870 if (escape_char == '"')
871 sepchars = "\r\n\t\f '";
873 /* do argv... */
874 arglen = 0;
875 targ = argv;
876 while (*targ)
878 char * p = *targ;
879 int need_quotes = 0;
880 int escape_char_run = 0;
882 if (*p == 0)
883 need_quotes = 1;
884 for ( ; *p; p++)
886 if (escape_char == '"' && *p == '\\')
887 /* If it's a Cygwin app, \ needs to be escaped. */
888 arglen++;
889 else if (*p == '"')
891 /* allow for embedded quotes to be escaped */
892 arglen++;
893 need_quotes = 1;
894 /* handle the case where the embedded quote is already escaped */
895 if (escape_char_run > 0)
897 /* To preserve the arg exactly, we need to double the
898 preceding escape characters (plus adding one to
899 escape the quote character itself). */
900 arglen += escape_char_run;
903 else if (strchr (sepchars, *p) != NULL)
905 need_quotes = 1;
908 if (*p == escape_char && escape_char != '"')
909 escape_char_run++;
910 else
911 escape_char_run = 0;
913 if (need_quotes)
915 arglen += 2;
916 /* handle the case where the arg ends with an escape char - we
917 must not let the enclosing quote be escaped. */
918 if (escape_char_run > 0)
919 arglen += escape_char_run;
921 arglen += strlen (*targ++) + 1;
923 cmdline = alloca (arglen);
924 targ = argv;
925 parg = cmdline;
926 while (*targ)
928 char * p = *targ;
929 int need_quotes = 0;
931 if (*p == 0)
932 need_quotes = 1;
934 if (do_quoting)
936 for ( ; *p; p++)
937 if ((strchr (sepchars, *p) != NULL) || *p == '"')
938 need_quotes = 1;
940 if (need_quotes)
942 int escape_char_run = 0;
943 char * first;
944 char * last;
946 p = *targ;
947 first = p;
948 last = p + strlen (p) - 1;
949 *parg++ = '"';
950 #if 0
951 /* This version does not escape quotes if they occur at the
952 beginning or end of the arg - this could lead to incorrect
953 behavior when the arg itself represents a command line
954 containing quoted args. I believe this was originally done
955 as a hack to make some things work, before
956 `w32-quote-process-args' was added. */
957 while (*p)
959 if (*p == '"' && p > first && p < last)
960 *parg++ = escape_char; /* escape embedded quotes */
961 *parg++ = *p++;
963 #else
964 for ( ; *p; p++)
966 if (*p == '"')
968 /* double preceding escape chars if any */
969 while (escape_char_run > 0)
971 *parg++ = escape_char;
972 escape_char_run--;
974 /* escape all quote chars, even at beginning or end */
975 *parg++ = escape_char;
977 else if (escape_char == '"' && *p == '\\')
978 *parg++ = '\\';
979 *parg++ = *p;
981 if (*p == escape_char && escape_char != '"')
982 escape_char_run++;
983 else
984 escape_char_run = 0;
986 /* double escape chars before enclosing quote */
987 while (escape_char_run > 0)
989 *parg++ = escape_char;
990 escape_char_run--;
992 #endif
993 *parg++ = '"';
995 else
997 strcpy (parg, *targ);
998 parg += strlen (*targ);
1000 *parg++ = ' ';
1001 targ++;
1003 *--parg = '\0';
1005 /* and envp... */
1006 arglen = 1;
1007 targ = envp;
1008 numenv = 1; /* for end null */
1009 while (*targ)
1011 arglen += strlen (*targ++) + 1;
1012 numenv++;
1014 /* extra env vars... */
1015 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1016 GetCurrentProcessId ());
1017 arglen += strlen (ppid_env_var_buffer) + 1;
1018 numenv++;
1020 /* merge env passed in and extra env into one, and sort it. */
1021 targ = (char **) alloca (numenv * sizeof (char *));
1022 merge_and_sort_env (envp, extra_env, targ);
1024 /* concatenate env entries. */
1025 env = alloca (arglen);
1026 parg = env;
1027 while (*targ)
1029 strcpy (parg, *targ);
1030 parg += strlen (*targ++);
1031 *parg++ = '\0';
1033 *parg++ = '\0';
1034 *parg = '\0';
1036 cp = new_child ();
1037 if (cp == NULL)
1039 errno = EAGAIN;
1040 return -1;
1043 /* Now create the process. */
1044 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1046 delete_child (cp);
1047 errno = ENOEXEC;
1048 return -1;
1051 return pid;
1054 /* Emulate the select call
1055 Wait for available input on any of the given rfds, or timeout if
1056 a timeout is given and no input is detected
1057 wfds and efds are not supported and must be NULL.
1059 For simplicity, we detect the death of child processes here and
1060 synchronously call the SIGCHLD handler. Since it is possible for
1061 children to be created without a corresponding pipe handle from which
1062 to read output, we wait separately on the process handles as well as
1063 the char_avail events for each process pipe. We only call
1064 wait/reap_process when the process actually terminates.
1066 To reduce the number of places in which Emacs can be hung such that
1067 C-g is not able to interrupt it, we always wait on interrupt_handle
1068 (which is signaled by the input thread when C-g is detected). If we
1069 detect that we were woken up by C-g, we return -1 with errno set to
1070 EINTR as on Unix. */
1072 /* From w32console.c */
1073 extern HANDLE keyboard_handle;
1075 /* From w32xfns.c */
1076 extern HANDLE interrupt_handle;
1078 /* From process.c */
1079 extern int proc_buffered_char[];
1082 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1083 EMACS_TIME *timeout)
1085 SELECT_TYPE orfds;
1086 DWORD timeout_ms, start_time;
1087 int i, nh, nc, nr;
1088 DWORD active;
1089 child_process *cp, *cps[MAX_CHILDREN];
1090 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1091 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1093 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1095 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1096 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1098 Sleep (timeout_ms);
1099 return 0;
1102 /* Otherwise, we only handle rfds, so fail otherwise. */
1103 if (rfds == NULL || wfds != NULL || efds != NULL)
1105 errno = EINVAL;
1106 return -1;
1109 orfds = *rfds;
1110 FD_ZERO (rfds);
1111 nr = 0;
1113 /* Always wait on interrupt_handle, to detect C-g (quit). */
1114 wait_hnd[0] = interrupt_handle;
1115 fdindex[0] = -1;
1117 /* Build a list of pipe handles to wait on. */
1118 nh = 1;
1119 for (i = 0; i < nfds; i++)
1120 if (FD_ISSET (i, &orfds))
1122 if (i == 0)
1124 if (keyboard_handle)
1126 /* Handle stdin specially */
1127 wait_hnd[nh] = keyboard_handle;
1128 fdindex[nh] = i;
1129 nh++;
1132 /* Check for any emacs-generated input in the queue since
1133 it won't be detected in the wait */
1134 if (detect_input_pending ())
1136 FD_SET (i, rfds);
1137 return 1;
1140 else
1142 /* Child process and socket input */
1143 cp = fd_info[i].cp;
1144 if (cp)
1146 int current_status = cp->status;
1148 if (current_status == STATUS_READ_ACKNOWLEDGED)
1150 /* Tell reader thread which file handle to use. */
1151 cp->fd = i;
1152 /* Wake up the reader thread for this process */
1153 cp->status = STATUS_READ_READY;
1154 if (!SetEvent (cp->char_consumed))
1155 DebPrint (("nt_select.SetEvent failed with "
1156 "%lu for fd %ld\n", GetLastError (), i));
1159 #ifdef CHECK_INTERLOCK
1160 /* slightly crude cross-checking of interlock between threads */
1162 current_status = cp->status;
1163 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1165 /* char_avail has been signaled, so status (which may
1166 have changed) should indicate read has completed
1167 but has not been acknowledged. */
1168 current_status = cp->status;
1169 if (current_status != STATUS_READ_SUCCEEDED
1170 && current_status != STATUS_READ_FAILED)
1171 DebPrint (("char_avail set, but read not completed: status %d\n",
1172 current_status));
1174 else
1176 /* char_avail has not been signaled, so status should
1177 indicate that read is in progress; small possibility
1178 that read has completed but event wasn't yet signaled
1179 when we tested it (because a context switch occurred
1180 or if running on separate CPUs). */
1181 if (current_status != STATUS_READ_READY
1182 && current_status != STATUS_READ_IN_PROGRESS
1183 && current_status != STATUS_READ_SUCCEEDED
1184 && current_status != STATUS_READ_FAILED)
1185 DebPrint (("char_avail reset, but read status is bad: %d\n",
1186 current_status));
1188 #endif
1189 wait_hnd[nh] = cp->char_avail;
1190 fdindex[nh] = i;
1191 if (!wait_hnd[nh]) abort ();
1192 nh++;
1193 #ifdef FULL_DEBUG
1194 DebPrint (("select waiting on child %d fd %d\n",
1195 cp-child_procs, i));
1196 #endif
1198 else
1200 /* Unable to find something to wait on for this fd, skip */
1202 /* Note that this is not a fatal error, and can in fact
1203 happen in unusual circumstances. Specifically, if
1204 sys_spawnve fails, eg. because the program doesn't
1205 exist, and debug-on-error is t so Fsignal invokes a
1206 nested input loop, then the process output pipe is
1207 still included in input_wait_mask with no child_proc
1208 associated with it. (It is removed when the debugger
1209 exits the nested input loop and the error is thrown.) */
1211 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1216 count_children:
1217 /* Add handles of child processes. */
1218 nc = 0;
1219 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1220 /* Some child_procs might be sockets; ignore them. Also some
1221 children may have died already, but we haven't finished reading
1222 the process output; ignore them too. */
1223 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1224 && (cp->fd < 0
1225 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1226 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1229 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1230 cps[nc] = cp;
1231 nc++;
1234 /* Nothing to look for, so we didn't find anything */
1235 if (nh + nc == 0)
1237 if (timeout)
1238 Sleep (timeout_ms);
1239 return 0;
1242 start_time = GetTickCount ();
1244 /* Wait for input or child death to be signaled. If user input is
1245 allowed, then also accept window messages. */
1246 if (FD_ISSET (0, &orfds))
1247 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1248 QS_ALLINPUT);
1249 else
1250 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1252 if (active == WAIT_FAILED)
1254 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1255 nh + nc, timeout_ms, GetLastError ()));
1256 /* don't return EBADF - this causes wait_reading_process_output to
1257 abort; WAIT_FAILED is returned when single-stepping under
1258 Windows 95 after switching thread focus in debugger, and
1259 possibly at other times. */
1260 errno = EINTR;
1261 return -1;
1263 else if (active == WAIT_TIMEOUT)
1265 return 0;
1267 else if (active >= WAIT_OBJECT_0
1268 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1270 active -= WAIT_OBJECT_0;
1272 else if (active >= WAIT_ABANDONED_0
1273 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1275 active -= WAIT_ABANDONED_0;
1277 else
1278 abort ();
1280 /* Loop over all handles after active (now officially documented as
1281 being the first signaled handle in the array). We do this to
1282 ensure fairness, so that all channels with data available will be
1283 processed - otherwise higher numbered channels could be starved. */
1286 if (active == nh + nc)
1288 /* There are messages in the lisp thread's queue; we must
1289 drain the queue now to ensure they are processed promptly,
1290 because if we don't do so, we will not be woken again until
1291 further messages arrive.
1293 NB. If ever we allow window message procedures to callback
1294 into lisp, we will need to ensure messages are dispatched
1295 at a safe time for lisp code to be run (*), and we may also
1296 want to provide some hooks in the dispatch loop to cater
1297 for modeless dialogs created by lisp (ie. to register
1298 window handles to pass to IsDialogMessage).
1300 (*) Note that MsgWaitForMultipleObjects above is an
1301 internal dispatch point for messages that are sent to
1302 windows created by this thread. */
1303 drain_message_queue ();
1305 else if (active >= nh)
1307 cp = cps[active - nh];
1309 /* We cannot always signal SIGCHLD immediately; if we have not
1310 finished reading the process output, we must delay sending
1311 SIGCHLD until we do. */
1313 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1314 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1315 /* SIG_DFL for SIGCHLD is ignore */
1316 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1317 sig_handlers[SIGCHLD] != SIG_IGN)
1319 #ifdef FULL_DEBUG
1320 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1321 cp->pid));
1322 #endif
1323 dead_child = cp;
1324 sig_handlers[SIGCHLD] (SIGCHLD);
1325 dead_child = NULL;
1328 else if (fdindex[active] == -1)
1330 /* Quit (C-g) was detected. */
1331 errno = EINTR;
1332 return -1;
1334 else if (fdindex[active] == 0)
1336 /* Keyboard input available */
1337 FD_SET (0, rfds);
1338 nr++;
1340 else
1342 /* must be a socket or pipe - read ahead should have
1343 completed, either succeeding or failing. */
1344 FD_SET (fdindex[active], rfds);
1345 nr++;
1348 /* Even though wait_reading_process_output only reads from at most
1349 one channel, we must process all channels here so that we reap
1350 all children that have died. */
1351 while (++active < nh + nc)
1352 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1353 break;
1354 } while (active < nh + nc);
1356 /* If no input has arrived and timeout hasn't expired, wait again. */
1357 if (nr == 0)
1359 DWORD elapsed = GetTickCount () - start_time;
1361 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1363 if (timeout_ms != INFINITE)
1364 timeout_ms -= elapsed;
1365 goto count_children;
1369 return nr;
1372 /* Substitute for certain kill () operations */
1374 static BOOL CALLBACK
1375 find_child_console (HWND hwnd, LPARAM arg)
1377 child_process * cp = (child_process *) arg;
1378 DWORD thread_id;
1379 DWORD process_id;
1381 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1382 if (process_id == cp->procinfo.dwProcessId)
1384 char window_class[32];
1386 GetClassName (hwnd, window_class, sizeof (window_class));
1387 if (strcmp (window_class,
1388 (os_subtype == OS_WIN95)
1389 ? "tty"
1390 : "ConsoleWindowClass") == 0)
1392 cp->hwnd = hwnd;
1393 return FALSE;
1396 /* keep looking */
1397 return TRUE;
1401 sys_kill (int pid, int sig)
1403 child_process *cp;
1404 HANDLE proc_hand;
1405 int need_to_free = 0;
1406 int rc = 0;
1408 /* Only handle signals that will result in the process dying */
1409 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1411 errno = EINVAL;
1412 return -1;
1415 cp = find_child_pid (pid);
1416 if (cp == NULL)
1418 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1419 if (proc_hand == NULL)
1421 errno = EPERM;
1422 return -1;
1424 need_to_free = 1;
1426 else
1428 proc_hand = cp->procinfo.hProcess;
1429 pid = cp->procinfo.dwProcessId;
1431 /* Try to locate console window for process. */
1432 EnumWindows (find_child_console, (LPARAM) cp);
1435 if (sig == SIGINT || sig == SIGQUIT)
1437 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1439 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1440 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1441 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1442 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1443 HWND foreground_window;
1445 if (break_scan_code == 0)
1447 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1448 vk_break_code = 'C';
1449 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1452 foreground_window = GetForegroundWindow ();
1453 if (foreground_window)
1455 /* NT 5.0, and apparently also Windows 98, will not allow
1456 a Window to be set to foreground directly without the
1457 user's involvement. The workaround is to attach
1458 ourselves to the thread that owns the foreground
1459 window, since that is the only thread that can set the
1460 foreground window. */
1461 DWORD foreground_thread, child_thread;
1462 foreground_thread =
1463 GetWindowThreadProcessId (foreground_window, NULL);
1464 if (foreground_thread == GetCurrentThreadId ()
1465 || !AttachThreadInput (GetCurrentThreadId (),
1466 foreground_thread, TRUE))
1467 foreground_thread = 0;
1469 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1470 if (child_thread == GetCurrentThreadId ()
1471 || !AttachThreadInput (GetCurrentThreadId (),
1472 child_thread, TRUE))
1473 child_thread = 0;
1475 /* Set the foreground window to the child. */
1476 if (SetForegroundWindow (cp->hwnd))
1478 /* Generate keystrokes as if user had typed Ctrl-Break or
1479 Ctrl-C. */
1480 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1481 keybd_event (vk_break_code, break_scan_code,
1482 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1483 keybd_event (vk_break_code, break_scan_code,
1484 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1485 | KEYEVENTF_KEYUP, 0);
1486 keybd_event (VK_CONTROL, control_scan_code,
1487 KEYEVENTF_KEYUP, 0);
1489 /* Sleep for a bit to give time for Emacs frame to respond
1490 to focus change events (if Emacs was active app). */
1491 Sleep (100);
1493 SetForegroundWindow (foreground_window);
1495 /* Detach from the foreground and child threads now that
1496 the foreground switching is over. */
1497 if (foreground_thread)
1498 AttachThreadInput (GetCurrentThreadId (),
1499 foreground_thread, FALSE);
1500 if (child_thread)
1501 AttachThreadInput (GetCurrentThreadId (),
1502 child_thread, FALSE);
1505 /* Ctrl-Break is NT equivalent of SIGINT. */
1506 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1508 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1509 "for pid %lu\n", GetLastError (), pid));
1510 errno = EINVAL;
1511 rc = -1;
1514 else
1516 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1518 #if 1
1519 if (os_subtype == OS_WIN95)
1522 Another possibility is to try terminating the VDM out-right by
1523 calling the Shell VxD (id 0x17) V86 interface, function #4
1524 "SHELL_Destroy_VM", ie.
1526 mov edx,4
1527 mov ebx,vm_handle
1528 call shellapi
1530 First need to determine the current VM handle, and then arrange for
1531 the shellapi call to be made from the system vm (by using
1532 Switch_VM_and_callback).
1534 Could try to invoke DestroyVM through CallVxD.
1537 #if 0
1538 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1539 to hang when cmdproxy is used in conjunction with
1540 command.com for an interactive shell. Posting
1541 WM_CLOSE pops up a dialog that, when Yes is selected,
1542 does the same thing. TerminateProcess is also less
1543 than ideal in that subprocesses tend to stick around
1544 until the machine is shutdown, but at least it
1545 doesn't freeze the 16-bit subsystem. */
1546 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1547 #endif
1548 if (!TerminateProcess (proc_hand, 0xff))
1550 DebPrint (("sys_kill.TerminateProcess returned %d "
1551 "for pid %lu\n", GetLastError (), pid));
1552 errno = EINVAL;
1553 rc = -1;
1556 else
1557 #endif
1558 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1560 /* Kill the process. On W32 this doesn't kill child processes
1561 so it doesn't work very well for shells which is why it's not
1562 used in every case. */
1563 else if (!TerminateProcess (proc_hand, 0xff))
1565 DebPrint (("sys_kill.TerminateProcess returned %d "
1566 "for pid %lu\n", GetLastError (), pid));
1567 errno = EINVAL;
1568 rc = -1;
1572 if (need_to_free)
1573 CloseHandle (proc_hand);
1575 return rc;
1578 /* The following two routines are used to manipulate stdin, stdout, and
1579 stderr of our child processes.
1581 Assuming that in, out, and err are *not* inheritable, we make them
1582 stdin, stdout, and stderr of the child as follows:
1584 - Save the parent's current standard handles.
1585 - Set the std handles to inheritable duplicates of the ones being passed in.
1586 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1587 NT file handle for a crt file descriptor.)
1588 - Spawn the child, which inherits in, out, and err as stdin,
1589 stdout, and stderr. (see Spawnve)
1590 - Close the std handles passed to the child.
1591 - Reset the parent's standard handles to the saved handles.
1592 (see reset_standard_handles)
1593 We assume that the caller closes in, out, and err after calling us. */
1595 void
1596 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1598 HANDLE parent;
1599 HANDLE newstdin, newstdout, newstderr;
1601 parent = GetCurrentProcess ();
1603 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1604 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1605 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1607 /* make inheritable copies of the new handles */
1608 if (!DuplicateHandle (parent,
1609 (HANDLE) _get_osfhandle (in),
1610 parent,
1611 &newstdin,
1613 TRUE,
1614 DUPLICATE_SAME_ACCESS))
1615 report_file_error ("Duplicating input handle for child", Qnil);
1617 if (!DuplicateHandle (parent,
1618 (HANDLE) _get_osfhandle (out),
1619 parent,
1620 &newstdout,
1622 TRUE,
1623 DUPLICATE_SAME_ACCESS))
1624 report_file_error ("Duplicating output handle for child", Qnil);
1626 if (!DuplicateHandle (parent,
1627 (HANDLE) _get_osfhandle (err),
1628 parent,
1629 &newstderr,
1631 TRUE,
1632 DUPLICATE_SAME_ACCESS))
1633 report_file_error ("Duplicating error handle for child", Qnil);
1635 /* and store them as our std handles */
1636 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1637 report_file_error ("Changing stdin handle", Qnil);
1639 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1640 report_file_error ("Changing stdout handle", Qnil);
1642 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1643 report_file_error ("Changing stderr handle", Qnil);
1646 void
1647 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1649 /* close the duplicated handles passed to the child */
1650 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1651 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1652 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1654 /* now restore parent's saved std handles */
1655 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1656 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1657 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1660 void
1661 set_process_dir (char * dir)
1663 process_dir = dir;
1666 /* To avoid problems with winsock implementations that work over dial-up
1667 connections causing or requiring a connection to exist while Emacs is
1668 running, Emacs no longer automatically loads winsock on startup if it
1669 is present. Instead, it will be loaded when open-network-stream is
1670 first called.
1672 To allow full control over when winsock is loaded, we provide these
1673 two functions to dynamically load and unload winsock. This allows
1674 dial-up users to only be connected when they actually need to use
1675 socket services. */
1677 /* From w32.c */
1678 extern HANDLE winsock_lib;
1679 extern BOOL term_winsock (void);
1680 extern BOOL init_winsock (int load_now);
1682 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1683 doc: /* Test for presence of the Windows socket library `winsock'.
1684 Returns non-nil if winsock support is present, nil otherwise.
1686 If the optional argument LOAD-NOW is non-nil, the winsock library is
1687 also loaded immediately if not already loaded. If winsock is loaded,
1688 the winsock local hostname is returned (since this may be different from
1689 the value of `system-name' and should supplant it), otherwise t is
1690 returned to indicate winsock support is present. */)
1691 (Lisp_Object load_now)
1693 int have_winsock;
1695 have_winsock = init_winsock (!NILP (load_now));
1696 if (have_winsock)
1698 if (winsock_lib != NULL)
1700 /* Return new value for system-name. The best way to do this
1701 is to call init_system_name, saving and restoring the
1702 original value to avoid side-effects. */
1703 Lisp_Object orig_hostname = Vsystem_name;
1704 Lisp_Object hostname;
1706 init_system_name ();
1707 hostname = Vsystem_name;
1708 Vsystem_name = orig_hostname;
1709 return hostname;
1711 return Qt;
1713 return Qnil;
1716 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1717 0, 0, 0,
1718 doc: /* Unload the Windows socket library `winsock' if loaded.
1719 This is provided to allow dial-up socket connections to be disconnected
1720 when no longer needed. Returns nil without unloading winsock if any
1721 socket connections still exist. */)
1722 (void)
1724 return term_winsock () ? Qt : Qnil;
1728 /* Some miscellaneous functions that are Windows specific, but not GUI
1729 specific (ie. are applicable in terminal or batch mode as well). */
1731 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1732 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1733 If FILENAME does not exist, return nil.
1734 All path elements in FILENAME are converted to their short names. */)
1735 (Lisp_Object filename)
1737 char shortname[MAX_PATH];
1739 CHECK_STRING (filename);
1741 /* first expand it. */
1742 filename = Fexpand_file_name (filename, Qnil);
1744 /* luckily, this returns the short version of each element in the path. */
1745 if (GetShortPathName (SDATA (ENCODE_FILE (filename)), shortname, MAX_PATH) == 0)
1746 return Qnil;
1748 dostounix_filename (shortname);
1750 return build_string (shortname);
1754 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1755 1, 1, 0,
1756 doc: /* Return the long file name version of the full path of FILENAME.
1757 If FILENAME does not exist, return nil.
1758 All path elements in FILENAME are converted to their long names. */)
1759 (Lisp_Object filename)
1761 char longname[ MAX_PATH ];
1762 int drive_only = 0;
1764 CHECK_STRING (filename);
1766 if (SBYTES (filename) == 2
1767 && *(SDATA (filename) + 1) == ':')
1768 drive_only = 1;
1770 /* first expand it. */
1771 filename = Fexpand_file_name (filename, Qnil);
1773 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename)), longname, MAX_PATH))
1774 return Qnil;
1776 dostounix_filename (longname);
1778 /* If we were passed only a drive, make sure that a slash is not appended
1779 for consistency with directories. Allow for drive mapping via SUBST
1780 in case expand-file-name is ever changed to expand those. */
1781 if (drive_only && longname[1] == ':' && longname[2] == '/' && !longname[3])
1782 longname[2] = '\0';
1784 return DECODE_FILE (build_string (longname));
1787 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1788 Sw32_set_process_priority, 2, 2, 0,
1789 doc: /* Set the priority of PROCESS to PRIORITY.
1790 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1791 priority of the process whose pid is PROCESS is changed.
1792 PRIORITY should be one of the symbols high, normal, or low;
1793 any other symbol will be interpreted as normal.
1795 If successful, the return value is t, otherwise nil. */)
1796 (Lisp_Object process, Lisp_Object priority)
1798 HANDLE proc_handle = GetCurrentProcess ();
1799 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1800 Lisp_Object result = Qnil;
1802 CHECK_SYMBOL (priority);
1804 if (!NILP (process))
1806 DWORD pid;
1807 child_process *cp;
1809 CHECK_NUMBER (process);
1811 /* Allow pid to be an internally generated one, or one obtained
1812 externally. This is necessary because real pids on Win95 are
1813 negative. */
1815 pid = XINT (process);
1816 cp = find_child_pid (pid);
1817 if (cp != NULL)
1818 pid = cp->procinfo.dwProcessId;
1820 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1823 if (EQ (priority, Qhigh))
1824 priority_class = HIGH_PRIORITY_CLASS;
1825 else if (EQ (priority, Qlow))
1826 priority_class = IDLE_PRIORITY_CLASS;
1828 if (proc_handle != NULL)
1830 if (SetPriorityClass (proc_handle, priority_class))
1831 result = Qt;
1832 if (!NILP (process))
1833 CloseHandle (proc_handle);
1836 return result;
1839 #ifdef HAVE_LANGINFO_CODESET
1840 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1841 char *
1842 nl_langinfo (nl_item item)
1844 /* Conversion of Posix item numbers to their Windows equivalents. */
1845 static const LCTYPE w32item[] = {
1846 LOCALE_IDEFAULTANSICODEPAGE,
1847 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1848 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1849 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1850 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1851 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1852 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1855 static char *nl_langinfo_buf = NULL;
1856 static int nl_langinfo_len = 0;
1858 if (nl_langinfo_len <= 0)
1859 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1861 if (item < 0 || item >= _NL_NUM)
1862 nl_langinfo_buf[0] = 0;
1863 else
1865 LCID cloc = GetThreadLocale ();
1866 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1867 NULL, 0);
1869 if (need_len <= 0)
1870 nl_langinfo_buf[0] = 0;
1871 else
1873 if (item == CODESET)
1875 need_len += 2; /* for the "cp" prefix */
1876 if (need_len < 8) /* for the case we call GetACP */
1877 need_len = 8;
1879 if (nl_langinfo_len <= need_len)
1880 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1881 nl_langinfo_len = need_len);
1882 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1883 nl_langinfo_buf, nl_langinfo_len))
1884 nl_langinfo_buf[0] = 0;
1885 else if (item == CODESET)
1887 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1888 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1889 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1890 else
1892 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1893 strlen (nl_langinfo_buf) + 1);
1894 nl_langinfo_buf[0] = 'c';
1895 nl_langinfo_buf[1] = 'p';
1900 return nl_langinfo_buf;
1902 #endif /* HAVE_LANGINFO_CODESET */
1904 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1905 Sw32_get_locale_info, 1, 2, 0,
1906 doc: /* Return information about the Windows locale LCID.
1907 By default, return a three letter locale code which encodes the default
1908 language as the first two characters, and the country or regional variant
1909 as the third letter. For example, ENU refers to `English (United States)',
1910 while ENC means `English (Canadian)'.
1912 If the optional argument LONGFORM is t, the long form of the locale
1913 name is returned, e.g. `English (United States)' instead; if LONGFORM
1914 is a number, it is interpreted as an LCTYPE constant and the corresponding
1915 locale information is returned.
1917 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1918 (Lisp_Object lcid, Lisp_Object longform)
1920 int got_abbrev;
1921 int got_full;
1922 char abbrev_name[32] = { 0 };
1923 char full_name[256] = { 0 };
1925 CHECK_NUMBER (lcid);
1927 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1928 return Qnil;
1930 if (NILP (longform))
1932 got_abbrev = GetLocaleInfo (XINT (lcid),
1933 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1934 abbrev_name, sizeof (abbrev_name));
1935 if (got_abbrev)
1936 return build_string (abbrev_name);
1938 else if (EQ (longform, Qt))
1940 got_full = GetLocaleInfo (XINT (lcid),
1941 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1942 full_name, sizeof (full_name));
1943 if (got_full)
1944 return DECODE_SYSTEM (build_string (full_name));
1946 else if (NUMBERP (longform))
1948 got_full = GetLocaleInfo (XINT (lcid),
1949 XINT (longform),
1950 full_name, sizeof (full_name));
1951 if (got_full)
1952 return make_unibyte_string (full_name, got_full);
1955 return Qnil;
1959 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1960 Sw32_get_current_locale_id, 0, 0, 0,
1961 doc: /* Return Windows locale id for current locale setting.
1962 This is a numerical value; use `w32-get-locale-info' to convert to a
1963 human-readable form. */)
1964 (void)
1966 return make_number (GetThreadLocale ());
1969 static DWORD
1970 int_from_hex (char * s)
1972 DWORD val = 0;
1973 static char hex[] = "0123456789abcdefABCDEF";
1974 char * p;
1976 while (*s && (p = strchr (hex, *s)) != NULL)
1978 unsigned digit = p - hex;
1979 if (digit > 15)
1980 digit -= 6;
1981 val = val * 16 + digit;
1982 s++;
1984 return val;
1987 /* We need to build a global list, since the EnumSystemLocale callback
1988 function isn't given a context pointer. */
1989 Lisp_Object Vw32_valid_locale_ids;
1991 static BOOL CALLBACK
1992 enum_locale_fn (LPTSTR localeNum)
1994 DWORD id = int_from_hex (localeNum);
1995 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
1996 return TRUE;
1999 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2000 Sw32_get_valid_locale_ids, 0, 0, 0,
2001 doc: /* Return list of all valid Windows locale ids.
2002 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2003 human-readable form. */)
2004 (void)
2006 Vw32_valid_locale_ids = Qnil;
2008 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2010 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2011 return Vw32_valid_locale_ids;
2015 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2016 doc: /* Return Windows locale id for default locale setting.
2017 By default, the system default locale setting is returned; if the optional
2018 parameter USERP is non-nil, the user default locale setting is returned.
2019 This is a numerical value; use `w32-get-locale-info' to convert to a
2020 human-readable form. */)
2021 (Lisp_Object userp)
2023 if (NILP (userp))
2024 return make_number (GetSystemDefaultLCID ());
2025 return make_number (GetUserDefaultLCID ());
2029 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2030 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2031 If successful, the new locale id is returned, otherwise nil. */)
2032 (Lisp_Object lcid)
2034 CHECK_NUMBER (lcid);
2036 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2037 return Qnil;
2039 if (!SetThreadLocale (XINT (lcid)))
2040 return Qnil;
2042 /* Need to set input thread locale if present. */
2043 if (dwWindowsThreadId)
2044 /* Reply is not needed. */
2045 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2047 return make_number (GetThreadLocale ());
2051 /* We need to build a global list, since the EnumCodePages callback
2052 function isn't given a context pointer. */
2053 Lisp_Object Vw32_valid_codepages;
2055 static BOOL CALLBACK
2056 enum_codepage_fn (LPTSTR codepageNum)
2058 DWORD id = atoi (codepageNum);
2059 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2060 return TRUE;
2063 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2064 Sw32_get_valid_codepages, 0, 0, 0,
2065 doc: /* Return list of all valid Windows codepages. */)
2066 (void)
2068 Vw32_valid_codepages = Qnil;
2070 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2072 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2073 return Vw32_valid_codepages;
2077 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2078 Sw32_get_console_codepage, 0, 0, 0,
2079 doc: /* Return current Windows codepage for console input. */)
2080 (void)
2082 return make_number (GetConsoleCP ());
2086 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2087 Sw32_set_console_codepage, 1, 1, 0,
2088 doc: /* Make Windows codepage CP be the codepage for Emacs tty keyboard input.
2089 This codepage setting affects keyboard input in tty mode.
2090 If successful, the new CP is returned, otherwise nil. */)
2091 (Lisp_Object cp)
2093 CHECK_NUMBER (cp);
2095 if (!IsValidCodePage (XINT (cp)))
2096 return Qnil;
2098 if (!SetConsoleCP (XINT (cp)))
2099 return Qnil;
2101 return make_number (GetConsoleCP ());
2105 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2106 Sw32_get_console_output_codepage, 0, 0, 0,
2107 doc: /* Return current Windows codepage for console output. */)
2108 (void)
2110 return make_number (GetConsoleOutputCP ());
2114 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2115 Sw32_set_console_output_codepage, 1, 1, 0,
2116 doc: /* Make Windows codepage CP be the codepage for Emacs console output.
2117 This codepage setting affects display in tty mode.
2118 If successful, the new CP is returned, otherwise nil. */)
2119 (Lisp_Object cp)
2121 CHECK_NUMBER (cp);
2123 if (!IsValidCodePage (XINT (cp)))
2124 return Qnil;
2126 if (!SetConsoleOutputCP (XINT (cp)))
2127 return Qnil;
2129 return make_number (GetConsoleOutputCP ());
2133 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2134 Sw32_get_codepage_charset, 1, 1, 0,
2135 doc: /* Return charset ID corresponding to codepage CP.
2136 Returns nil if the codepage is not valid. */)
2137 (Lisp_Object cp)
2139 CHARSETINFO info;
2141 CHECK_NUMBER (cp);
2143 if (!IsValidCodePage (XINT (cp)))
2144 return Qnil;
2146 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2147 return make_number (info.ciCharset);
2149 return Qnil;
2153 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2154 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2155 doc: /* Return list of Windows keyboard languages and layouts.
2156 The return value is a list of pairs of language id and layout id. */)
2157 (void)
2159 int num_layouts = GetKeyboardLayoutList (0, NULL);
2160 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2161 Lisp_Object obj = Qnil;
2163 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2165 while (--num_layouts >= 0)
2167 DWORD kl = (DWORD) layouts[num_layouts];
2169 obj = Fcons (Fcons (make_number (kl & 0xffff),
2170 make_number ((kl >> 16) & 0xffff)),
2171 obj);
2175 return obj;
2179 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2180 Sw32_get_keyboard_layout, 0, 0, 0,
2181 doc: /* Return current Windows keyboard language and layout.
2182 The return value is the cons of the language id and the layout id. */)
2183 (void)
2185 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2187 return Fcons (make_number (kl & 0xffff),
2188 make_number ((kl >> 16) & 0xffff));
2192 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2193 Sw32_set_keyboard_layout, 1, 1, 0,
2194 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2195 The keyboard layout setting affects interpretation of keyboard input.
2196 If successful, the new layout id is returned, otherwise nil. */)
2197 (Lisp_Object layout)
2199 DWORD kl;
2201 CHECK_CONS (layout);
2202 CHECK_NUMBER_CAR (layout);
2203 CHECK_NUMBER_CDR (layout);
2205 kl = (XINT (XCAR (layout)) & 0xffff)
2206 | (XINT (XCDR (layout)) << 16);
2208 /* Synchronize layout with input thread. */
2209 if (dwWindowsThreadId)
2211 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2212 (WPARAM) kl, 0))
2214 MSG msg;
2215 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2217 if (msg.wParam == 0)
2218 return Qnil;
2221 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2222 return Qnil;
2224 return Fw32_get_keyboard_layout ();
2228 void
2229 syms_of_ntproc (void)
2231 DEFSYM (Qhigh, "high");
2232 DEFSYM (Qlow, "low");
2234 defsubr (&Sw32_has_winsock);
2235 defsubr (&Sw32_unload_winsock);
2237 defsubr (&Sw32_short_file_name);
2238 defsubr (&Sw32_long_file_name);
2239 defsubr (&Sw32_set_process_priority);
2240 defsubr (&Sw32_get_locale_info);
2241 defsubr (&Sw32_get_current_locale_id);
2242 defsubr (&Sw32_get_default_locale_id);
2243 defsubr (&Sw32_get_valid_locale_ids);
2244 defsubr (&Sw32_set_current_locale);
2246 defsubr (&Sw32_get_console_codepage);
2247 defsubr (&Sw32_set_console_codepage);
2248 defsubr (&Sw32_get_console_output_codepage);
2249 defsubr (&Sw32_set_console_output_codepage);
2250 defsubr (&Sw32_get_valid_codepages);
2251 defsubr (&Sw32_get_codepage_charset);
2253 defsubr (&Sw32_get_valid_keyboard_layouts);
2254 defsubr (&Sw32_get_keyboard_layout);
2255 defsubr (&Sw32_set_keyboard_layout);
2257 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args,
2258 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2259 Because Windows does not directly pass argv arrays to child processes,
2260 programs have to reconstruct the argv array by parsing the command
2261 line string. For an argument to contain a space, it must be enclosed
2262 in double quotes or it will be parsed as multiple arguments.
2264 If the value is a character, that character will be used to escape any
2265 quote characters that appear, otherwise a suitable escape character
2266 will be chosen based on the type of the program. */);
2267 Vw32_quote_process_args = Qt;
2269 DEFVAR_LISP ("w32-start-process-show-window",
2270 Vw32_start_process_show_window,
2271 doc: /* When nil, new child processes hide their windows.
2272 When non-nil, they show their window in the method of their choice.
2273 This variable doesn't affect GUI applications, which will never be hidden. */);
2274 Vw32_start_process_show_window = Qnil;
2276 DEFVAR_LISP ("w32-start-process-share-console",
2277 Vw32_start_process_share_console,
2278 doc: /* When nil, new child processes are given a new console.
2279 When non-nil, they share the Emacs console; this has the limitation of
2280 allowing only one DOS subprocess to run at a time (whether started directly
2281 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2282 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2283 otherwise respond to interrupts from Emacs. */);
2284 Vw32_start_process_share_console = Qnil;
2286 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2287 Vw32_start_process_inherit_error_mode,
2288 doc: /* When nil, new child processes revert to the default error mode.
2289 When non-nil, they inherit their error mode setting from Emacs, which stops
2290 them blocking when trying to access unmounted drives etc. */);
2291 Vw32_start_process_inherit_error_mode = Qt;
2293 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay,
2294 doc: /* Forced delay before reading subprocess output.
2295 This is done to improve the buffering of subprocess output, by
2296 avoiding the inefficiency of frequently reading small amounts of data.
2298 If positive, the value is the number of milliseconds to sleep before
2299 reading the subprocess output. If negative, the magnitude is the number
2300 of time slices to wait (effectively boosting the priority of the child
2301 process temporarily). A value of zero disables waiting entirely. */);
2302 w32_pipe_read_delay = 50;
2304 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names,
2305 doc: /* Non-nil means convert all-upper case file names to lower case.
2306 This applies when performing completions and file name expansion.
2307 Note that the value of this setting also affects remote file names,
2308 so you probably don't want to set to non-nil if you use case-sensitive
2309 filesystems via ange-ftp. */);
2310 Vw32_downcase_file_names = Qnil;
2312 #if 0
2313 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes,
2314 doc: /* Non-nil means attempt to fake realistic inode values.
2315 This works by hashing the truename of files, and should detect
2316 aliasing between long and short (8.3 DOS) names, but can have
2317 false positives because of hash collisions. Note that determining
2318 the truename of a file can be slow. */);
2319 Vw32_generate_fake_inodes = Qnil;
2320 #endif
2322 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes,
2323 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2324 This option controls whether to issue additional system calls to determine
2325 accurate link counts, file type, and ownership information. It is more
2326 useful for files on NTFS volumes, where hard links and file security are
2327 supported, than on volumes of the FAT family.
2329 Without these system calls, link count will always be reported as 1 and file
2330 ownership will be attributed to the current user.
2331 The default value `local' means only issue these system calls for files
2332 on local fixed drives. A value of nil means never issue them.
2333 Any other non-nil value means do this even on remote and removable drives
2334 where the performance impact may be noticeable even on modern hardware. */);
2335 Vw32_get_true_file_attributes = Qlocal;
2337 staticpro (&Vw32_valid_locale_ids);
2338 staticpro (&Vw32_valid_codepages);
2340 /* end of w32proc.c */