* lisp/progmodes/ruby-mode.el (ruby-parse-partial): No error when end
[emacs.git] / src / w32proc.c
blobafc1b21fdde3cf09b5ef0bac76079801fc312743
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 = build_string (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, void *ignored)
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 =
1094 timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 1000000) : INFINITE;
1096 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1097 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1099 Sleep (timeout_ms);
1100 return 0;
1103 /* Otherwise, we only handle rfds, so fail otherwise. */
1104 if (rfds == NULL || wfds != NULL || efds != NULL)
1106 errno = EINVAL;
1107 return -1;
1110 orfds = *rfds;
1111 FD_ZERO (rfds);
1112 nr = 0;
1114 /* Always wait on interrupt_handle, to detect C-g (quit). */
1115 wait_hnd[0] = interrupt_handle;
1116 fdindex[0] = -1;
1118 /* Build a list of pipe handles to wait on. */
1119 nh = 1;
1120 for (i = 0; i < nfds; i++)
1121 if (FD_ISSET (i, &orfds))
1123 if (i == 0)
1125 if (keyboard_handle)
1127 /* Handle stdin specially */
1128 wait_hnd[nh] = keyboard_handle;
1129 fdindex[nh] = i;
1130 nh++;
1133 /* Check for any emacs-generated input in the queue since
1134 it won't be detected in the wait */
1135 if (detect_input_pending ())
1137 FD_SET (i, rfds);
1138 return 1;
1141 else
1143 /* Child process and socket input */
1144 cp = fd_info[i].cp;
1145 if (cp)
1147 int current_status = cp->status;
1149 if (current_status == STATUS_READ_ACKNOWLEDGED)
1151 /* Tell reader thread which file handle to use. */
1152 cp->fd = i;
1153 /* Wake up the reader thread for this process */
1154 cp->status = STATUS_READ_READY;
1155 if (!SetEvent (cp->char_consumed))
1156 DebPrint (("nt_select.SetEvent failed with "
1157 "%lu for fd %ld\n", GetLastError (), i));
1160 #ifdef CHECK_INTERLOCK
1161 /* slightly crude cross-checking of interlock between threads */
1163 current_status = cp->status;
1164 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1166 /* char_avail has been signaled, so status (which may
1167 have changed) should indicate read has completed
1168 but has not been acknowledged. */
1169 current_status = cp->status;
1170 if (current_status != STATUS_READ_SUCCEEDED
1171 && current_status != STATUS_READ_FAILED)
1172 DebPrint (("char_avail set, but read not completed: status %d\n",
1173 current_status));
1175 else
1177 /* char_avail has not been signaled, so status should
1178 indicate that read is in progress; small possibility
1179 that read has completed but event wasn't yet signaled
1180 when we tested it (because a context switch occurred
1181 or if running on separate CPUs). */
1182 if (current_status != STATUS_READ_READY
1183 && current_status != STATUS_READ_IN_PROGRESS
1184 && current_status != STATUS_READ_SUCCEEDED
1185 && current_status != STATUS_READ_FAILED)
1186 DebPrint (("char_avail reset, but read status is bad: %d\n",
1187 current_status));
1189 #endif
1190 wait_hnd[nh] = cp->char_avail;
1191 fdindex[nh] = i;
1192 if (!wait_hnd[nh]) abort ();
1193 nh++;
1194 #ifdef FULL_DEBUG
1195 DebPrint (("select waiting on child %d fd %d\n",
1196 cp-child_procs, i));
1197 #endif
1199 else
1201 /* Unable to find something to wait on for this fd, skip */
1203 /* Note that this is not a fatal error, and can in fact
1204 happen in unusual circumstances. Specifically, if
1205 sys_spawnve fails, eg. because the program doesn't
1206 exist, and debug-on-error is t so Fsignal invokes a
1207 nested input loop, then the process output pipe is
1208 still included in input_wait_mask with no child_proc
1209 associated with it. (It is removed when the debugger
1210 exits the nested input loop and the error is thrown.) */
1212 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1217 count_children:
1218 /* Add handles of child processes. */
1219 nc = 0;
1220 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1221 /* Some child_procs might be sockets; ignore them. Also some
1222 children may have died already, but we haven't finished reading
1223 the process output; ignore them too. */
1224 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1225 && (cp->fd < 0
1226 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1227 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1230 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1231 cps[nc] = cp;
1232 nc++;
1235 /* Nothing to look for, so we didn't find anything */
1236 if (nh + nc == 0)
1238 if (timeout)
1239 Sleep (timeout_ms);
1240 return 0;
1243 start_time = GetTickCount ();
1245 /* Wait for input or child death to be signaled. If user input is
1246 allowed, then also accept window messages. */
1247 if (FD_ISSET (0, &orfds))
1248 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1249 QS_ALLINPUT);
1250 else
1251 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1253 if (active == WAIT_FAILED)
1255 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1256 nh + nc, timeout_ms, GetLastError ()));
1257 /* don't return EBADF - this causes wait_reading_process_output to
1258 abort; WAIT_FAILED is returned when single-stepping under
1259 Windows 95 after switching thread focus in debugger, and
1260 possibly at other times. */
1261 errno = EINTR;
1262 return -1;
1264 else if (active == WAIT_TIMEOUT)
1266 return 0;
1268 else if (active >= WAIT_OBJECT_0
1269 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1271 active -= WAIT_OBJECT_0;
1273 else if (active >= WAIT_ABANDONED_0
1274 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1276 active -= WAIT_ABANDONED_0;
1278 else
1279 abort ();
1281 /* Loop over all handles after active (now officially documented as
1282 being the first signaled handle in the array). We do this to
1283 ensure fairness, so that all channels with data available will be
1284 processed - otherwise higher numbered channels could be starved. */
1287 if (active == nh + nc)
1289 /* There are messages in the lisp thread's queue; we must
1290 drain the queue now to ensure they are processed promptly,
1291 because if we don't do so, we will not be woken again until
1292 further messages arrive.
1294 NB. If ever we allow window message procedures to callback
1295 into lisp, we will need to ensure messages are dispatched
1296 at a safe time for lisp code to be run (*), and we may also
1297 want to provide some hooks in the dispatch loop to cater
1298 for modeless dialogs created by lisp (ie. to register
1299 window handles to pass to IsDialogMessage).
1301 (*) Note that MsgWaitForMultipleObjects above is an
1302 internal dispatch point for messages that are sent to
1303 windows created by this thread. */
1304 drain_message_queue ();
1306 else if (active >= nh)
1308 cp = cps[active - nh];
1310 /* We cannot always signal SIGCHLD immediately; if we have not
1311 finished reading the process output, we must delay sending
1312 SIGCHLD until we do. */
1314 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1315 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1316 /* SIG_DFL for SIGCHLD is ignore */
1317 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1318 sig_handlers[SIGCHLD] != SIG_IGN)
1320 #ifdef FULL_DEBUG
1321 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1322 cp->pid));
1323 #endif
1324 dead_child = cp;
1325 sig_handlers[SIGCHLD] (SIGCHLD);
1326 dead_child = NULL;
1329 else if (fdindex[active] == -1)
1331 /* Quit (C-g) was detected. */
1332 errno = EINTR;
1333 return -1;
1335 else if (fdindex[active] == 0)
1337 /* Keyboard input available */
1338 FD_SET (0, rfds);
1339 nr++;
1341 else
1343 /* must be a socket or pipe - read ahead should have
1344 completed, either succeeding or failing. */
1345 FD_SET (fdindex[active], rfds);
1346 nr++;
1349 /* Even though wait_reading_process_output only reads from at most
1350 one channel, we must process all channels here so that we reap
1351 all children that have died. */
1352 while (++active < nh + nc)
1353 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1354 break;
1355 } while (active < nh + nc);
1357 /* If no input has arrived and timeout hasn't expired, wait again. */
1358 if (nr == 0)
1360 DWORD elapsed = GetTickCount () - start_time;
1362 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1364 if (timeout_ms != INFINITE)
1365 timeout_ms -= elapsed;
1366 goto count_children;
1370 return nr;
1373 /* Substitute for certain kill () operations */
1375 static BOOL CALLBACK
1376 find_child_console (HWND hwnd, LPARAM arg)
1378 child_process * cp = (child_process *) arg;
1379 DWORD thread_id;
1380 DWORD process_id;
1382 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1383 if (process_id == cp->procinfo.dwProcessId)
1385 char window_class[32];
1387 GetClassName (hwnd, window_class, sizeof (window_class));
1388 if (strcmp (window_class,
1389 (os_subtype == OS_WIN95)
1390 ? "tty"
1391 : "ConsoleWindowClass") == 0)
1393 cp->hwnd = hwnd;
1394 return FALSE;
1397 /* keep looking */
1398 return TRUE;
1402 sys_kill (int pid, int sig)
1404 child_process *cp;
1405 HANDLE proc_hand;
1406 int need_to_free = 0;
1407 int rc = 0;
1409 /* Only handle signals that will result in the process dying */
1410 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1412 errno = EINVAL;
1413 return -1;
1416 cp = find_child_pid (pid);
1417 if (cp == NULL)
1419 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1420 if (proc_hand == NULL)
1422 errno = EPERM;
1423 return -1;
1425 need_to_free = 1;
1427 else
1429 proc_hand = cp->procinfo.hProcess;
1430 pid = cp->procinfo.dwProcessId;
1432 /* Try to locate console window for process. */
1433 EnumWindows (find_child_console, (LPARAM) cp);
1436 if (sig == SIGINT || sig == SIGQUIT)
1438 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1440 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1441 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1442 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1443 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1444 HWND foreground_window;
1446 if (break_scan_code == 0)
1448 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1449 vk_break_code = 'C';
1450 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1453 foreground_window = GetForegroundWindow ();
1454 if (foreground_window)
1456 /* NT 5.0, and apparently also Windows 98, will not allow
1457 a Window to be set to foreground directly without the
1458 user's involvement. The workaround is to attach
1459 ourselves to the thread that owns the foreground
1460 window, since that is the only thread that can set the
1461 foreground window. */
1462 DWORD foreground_thread, child_thread;
1463 foreground_thread =
1464 GetWindowThreadProcessId (foreground_window, NULL);
1465 if (foreground_thread == GetCurrentThreadId ()
1466 || !AttachThreadInput (GetCurrentThreadId (),
1467 foreground_thread, TRUE))
1468 foreground_thread = 0;
1470 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1471 if (child_thread == GetCurrentThreadId ()
1472 || !AttachThreadInput (GetCurrentThreadId (),
1473 child_thread, TRUE))
1474 child_thread = 0;
1476 /* Set the foreground window to the child. */
1477 if (SetForegroundWindow (cp->hwnd))
1479 /* Generate keystrokes as if user had typed Ctrl-Break or
1480 Ctrl-C. */
1481 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1482 keybd_event (vk_break_code, break_scan_code,
1483 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1484 keybd_event (vk_break_code, break_scan_code,
1485 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1486 | KEYEVENTF_KEYUP, 0);
1487 keybd_event (VK_CONTROL, control_scan_code,
1488 KEYEVENTF_KEYUP, 0);
1490 /* Sleep for a bit to give time for Emacs frame to respond
1491 to focus change events (if Emacs was active app). */
1492 Sleep (100);
1494 SetForegroundWindow (foreground_window);
1496 /* Detach from the foreground and child threads now that
1497 the foreground switching is over. */
1498 if (foreground_thread)
1499 AttachThreadInput (GetCurrentThreadId (),
1500 foreground_thread, FALSE);
1501 if (child_thread)
1502 AttachThreadInput (GetCurrentThreadId (),
1503 child_thread, FALSE);
1506 /* Ctrl-Break is NT equivalent of SIGINT. */
1507 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1509 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1510 "for pid %lu\n", GetLastError (), pid));
1511 errno = EINVAL;
1512 rc = -1;
1515 else
1517 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1519 #if 1
1520 if (os_subtype == OS_WIN95)
1523 Another possibility is to try terminating the VDM out-right by
1524 calling the Shell VxD (id 0x17) V86 interface, function #4
1525 "SHELL_Destroy_VM", ie.
1527 mov edx,4
1528 mov ebx,vm_handle
1529 call shellapi
1531 First need to determine the current VM handle, and then arrange for
1532 the shellapi call to be made from the system vm (by using
1533 Switch_VM_and_callback).
1535 Could try to invoke DestroyVM through CallVxD.
1538 #if 0
1539 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1540 to hang when cmdproxy is used in conjunction with
1541 command.com for an interactive shell. Posting
1542 WM_CLOSE pops up a dialog that, when Yes is selected,
1543 does the same thing. TerminateProcess is also less
1544 than ideal in that subprocesses tend to stick around
1545 until the machine is shutdown, but at least it
1546 doesn't freeze the 16-bit subsystem. */
1547 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1548 #endif
1549 if (!TerminateProcess (proc_hand, 0xff))
1551 DebPrint (("sys_kill.TerminateProcess returned %d "
1552 "for pid %lu\n", GetLastError (), pid));
1553 errno = EINVAL;
1554 rc = -1;
1557 else
1558 #endif
1559 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1561 /* Kill the process. On W32 this doesn't kill child processes
1562 so it doesn't work very well for shells which is why it's not
1563 used in every case. */
1564 else if (!TerminateProcess (proc_hand, 0xff))
1566 DebPrint (("sys_kill.TerminateProcess returned %d "
1567 "for pid %lu\n", GetLastError (), pid));
1568 errno = EINVAL;
1569 rc = -1;
1573 if (need_to_free)
1574 CloseHandle (proc_hand);
1576 return rc;
1579 /* The following two routines are used to manipulate stdin, stdout, and
1580 stderr of our child processes.
1582 Assuming that in, out, and err are *not* inheritable, we make them
1583 stdin, stdout, and stderr of the child as follows:
1585 - Save the parent's current standard handles.
1586 - Set the std handles to inheritable duplicates of the ones being passed in.
1587 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1588 NT file handle for a crt file descriptor.)
1589 - Spawn the child, which inherits in, out, and err as stdin,
1590 stdout, and stderr. (see Spawnve)
1591 - Close the std handles passed to the child.
1592 - Reset the parent's standard handles to the saved handles.
1593 (see reset_standard_handles)
1594 We assume that the caller closes in, out, and err after calling us. */
1596 void
1597 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1599 HANDLE parent;
1600 HANDLE newstdin, newstdout, newstderr;
1602 parent = GetCurrentProcess ();
1604 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1605 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1606 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1608 /* make inheritable copies of the new handles */
1609 if (!DuplicateHandle (parent,
1610 (HANDLE) _get_osfhandle (in),
1611 parent,
1612 &newstdin,
1614 TRUE,
1615 DUPLICATE_SAME_ACCESS))
1616 report_file_error ("Duplicating input handle for child", Qnil);
1618 if (!DuplicateHandle (parent,
1619 (HANDLE) _get_osfhandle (out),
1620 parent,
1621 &newstdout,
1623 TRUE,
1624 DUPLICATE_SAME_ACCESS))
1625 report_file_error ("Duplicating output handle for child", Qnil);
1627 if (!DuplicateHandle (parent,
1628 (HANDLE) _get_osfhandle (err),
1629 parent,
1630 &newstderr,
1632 TRUE,
1633 DUPLICATE_SAME_ACCESS))
1634 report_file_error ("Duplicating error handle for child", Qnil);
1636 /* and store them as our std handles */
1637 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1638 report_file_error ("Changing stdin handle", Qnil);
1640 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1641 report_file_error ("Changing stdout handle", Qnil);
1643 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1644 report_file_error ("Changing stderr handle", Qnil);
1647 void
1648 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1650 /* close the duplicated handles passed to the child */
1651 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1652 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1653 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1655 /* now restore parent's saved std handles */
1656 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1657 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1658 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1661 void
1662 set_process_dir (char * dir)
1664 process_dir = dir;
1667 /* To avoid problems with winsock implementations that work over dial-up
1668 connections causing or requiring a connection to exist while Emacs is
1669 running, Emacs no longer automatically loads winsock on startup if it
1670 is present. Instead, it will be loaded when open-network-stream is
1671 first called.
1673 To allow full control over when winsock is loaded, we provide these
1674 two functions to dynamically load and unload winsock. This allows
1675 dial-up users to only be connected when they actually need to use
1676 socket services. */
1678 /* From w32.c */
1679 extern HANDLE winsock_lib;
1680 extern BOOL term_winsock (void);
1681 extern BOOL init_winsock (int load_now);
1683 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1684 doc: /* Test for presence of the Windows socket library `winsock'.
1685 Returns non-nil if winsock support is present, nil otherwise.
1687 If the optional argument LOAD-NOW is non-nil, the winsock library is
1688 also loaded immediately if not already loaded. If winsock is loaded,
1689 the winsock local hostname is returned (since this may be different from
1690 the value of `system-name' and should supplant it), otherwise t is
1691 returned to indicate winsock support is present. */)
1692 (Lisp_Object load_now)
1694 int have_winsock;
1696 have_winsock = init_winsock (!NILP (load_now));
1697 if (have_winsock)
1699 if (winsock_lib != NULL)
1701 /* Return new value for system-name. The best way to do this
1702 is to call init_system_name, saving and restoring the
1703 original value to avoid side-effects. */
1704 Lisp_Object orig_hostname = Vsystem_name;
1705 Lisp_Object hostname;
1707 init_system_name ();
1708 hostname = Vsystem_name;
1709 Vsystem_name = orig_hostname;
1710 return hostname;
1712 return Qt;
1714 return Qnil;
1717 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1718 0, 0, 0,
1719 doc: /* Unload the Windows socket library `winsock' if loaded.
1720 This is provided to allow dial-up socket connections to be disconnected
1721 when no longer needed. Returns nil without unloading winsock if any
1722 socket connections still exist. */)
1723 (void)
1725 return term_winsock () ? Qt : Qnil;
1729 /* Some miscellaneous functions that are Windows specific, but not GUI
1730 specific (ie. are applicable in terminal or batch mode as well). */
1732 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1733 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1734 If FILENAME does not exist, return nil.
1735 All path elements in FILENAME are converted to their short names. */)
1736 (Lisp_Object filename)
1738 char shortname[MAX_PATH];
1740 CHECK_STRING (filename);
1742 /* first expand it. */
1743 filename = Fexpand_file_name (filename, Qnil);
1745 /* luckily, this returns the short version of each element in the path. */
1746 if (GetShortPathName (SDATA (ENCODE_FILE (filename)), shortname, MAX_PATH) == 0)
1747 return Qnil;
1749 dostounix_filename (shortname);
1751 return build_string (shortname);
1755 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1756 1, 1, 0,
1757 doc: /* Return the long file name version of the full path of FILENAME.
1758 If FILENAME does not exist, return nil.
1759 All path elements in FILENAME are converted to their long names. */)
1760 (Lisp_Object filename)
1762 char longname[ MAX_PATH ];
1763 int drive_only = 0;
1765 CHECK_STRING (filename);
1767 if (SBYTES (filename) == 2
1768 && *(SDATA (filename) + 1) == ':')
1769 drive_only = 1;
1771 /* first expand it. */
1772 filename = Fexpand_file_name (filename, Qnil);
1774 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename)), longname, MAX_PATH))
1775 return Qnil;
1777 dostounix_filename (longname);
1779 /* If we were passed only a drive, make sure that a slash is not appended
1780 for consistency with directories. Allow for drive mapping via SUBST
1781 in case expand-file-name is ever changed to expand those. */
1782 if (drive_only && longname[1] == ':' && longname[2] == '/' && !longname[3])
1783 longname[2] = '\0';
1785 return DECODE_FILE (build_string (longname));
1788 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1789 Sw32_set_process_priority, 2, 2, 0,
1790 doc: /* Set the priority of PROCESS to PRIORITY.
1791 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1792 priority of the process whose pid is PROCESS is changed.
1793 PRIORITY should be one of the symbols high, normal, or low;
1794 any other symbol will be interpreted as normal.
1796 If successful, the return value is t, otherwise nil. */)
1797 (Lisp_Object process, Lisp_Object priority)
1799 HANDLE proc_handle = GetCurrentProcess ();
1800 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1801 Lisp_Object result = Qnil;
1803 CHECK_SYMBOL (priority);
1805 if (!NILP (process))
1807 DWORD pid;
1808 child_process *cp;
1810 CHECK_NUMBER (process);
1812 /* Allow pid to be an internally generated one, or one obtained
1813 externally. This is necessary because real pids on Win95 are
1814 negative. */
1816 pid = XINT (process);
1817 cp = find_child_pid (pid);
1818 if (cp != NULL)
1819 pid = cp->procinfo.dwProcessId;
1821 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1824 if (EQ (priority, Qhigh))
1825 priority_class = HIGH_PRIORITY_CLASS;
1826 else if (EQ (priority, Qlow))
1827 priority_class = IDLE_PRIORITY_CLASS;
1829 if (proc_handle != NULL)
1831 if (SetPriorityClass (proc_handle, priority_class))
1832 result = Qt;
1833 if (!NILP (process))
1834 CloseHandle (proc_handle);
1837 return result;
1840 #ifdef HAVE_LANGINFO_CODESET
1841 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1842 char *
1843 nl_langinfo (nl_item item)
1845 /* Conversion of Posix item numbers to their Windows equivalents. */
1846 static const LCTYPE w32item[] = {
1847 LOCALE_IDEFAULTANSICODEPAGE,
1848 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1849 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1850 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1851 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1852 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1853 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1856 static char *nl_langinfo_buf = NULL;
1857 static int nl_langinfo_len = 0;
1859 if (nl_langinfo_len <= 0)
1860 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1862 if (item < 0 || item >= _NL_NUM)
1863 nl_langinfo_buf[0] = 0;
1864 else
1866 LCID cloc = GetThreadLocale ();
1867 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1868 NULL, 0);
1870 if (need_len <= 0)
1871 nl_langinfo_buf[0] = 0;
1872 else
1874 if (item == CODESET)
1876 need_len += 2; /* for the "cp" prefix */
1877 if (need_len < 8) /* for the case we call GetACP */
1878 need_len = 8;
1880 if (nl_langinfo_len <= need_len)
1881 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1882 nl_langinfo_len = need_len);
1883 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1884 nl_langinfo_buf, nl_langinfo_len))
1885 nl_langinfo_buf[0] = 0;
1886 else if (item == CODESET)
1888 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1889 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1890 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1891 else
1893 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1894 strlen (nl_langinfo_buf) + 1);
1895 nl_langinfo_buf[0] = 'c';
1896 nl_langinfo_buf[1] = 'p';
1901 return nl_langinfo_buf;
1903 #endif /* HAVE_LANGINFO_CODESET */
1905 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1906 Sw32_get_locale_info, 1, 2, 0,
1907 doc: /* Return information about the Windows locale LCID.
1908 By default, return a three letter locale code which encodes the default
1909 language as the first two characters, and the country or regional variant
1910 as the third letter. For example, ENU refers to `English (United States)',
1911 while ENC means `English (Canadian)'.
1913 If the optional argument LONGFORM is t, the long form of the locale
1914 name is returned, e.g. `English (United States)' instead; if LONGFORM
1915 is a number, it is interpreted as an LCTYPE constant and the corresponding
1916 locale information is returned.
1918 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1919 (Lisp_Object lcid, Lisp_Object longform)
1921 int got_abbrev;
1922 int got_full;
1923 char abbrev_name[32] = { 0 };
1924 char full_name[256] = { 0 };
1926 CHECK_NUMBER (lcid);
1928 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1929 return Qnil;
1931 if (NILP (longform))
1933 got_abbrev = GetLocaleInfo (XINT (lcid),
1934 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1935 abbrev_name, sizeof (abbrev_name));
1936 if (got_abbrev)
1937 return build_string (abbrev_name);
1939 else if (EQ (longform, Qt))
1941 got_full = GetLocaleInfo (XINT (lcid),
1942 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1943 full_name, sizeof (full_name));
1944 if (got_full)
1945 return DECODE_SYSTEM (build_string (full_name));
1947 else if (NUMBERP (longform))
1949 got_full = GetLocaleInfo (XINT (lcid),
1950 XINT (longform),
1951 full_name, sizeof (full_name));
1952 /* GetLocaleInfo's return value includes the terminating null
1953 character, when the returned information is a string, whereas
1954 make_unibyte_string needs the string length without the
1955 terminating null. */
1956 if (got_full)
1957 return make_unibyte_string (full_name, got_full - 1);
1960 return Qnil;
1964 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1965 Sw32_get_current_locale_id, 0, 0, 0,
1966 doc: /* Return Windows locale id for current locale setting.
1967 This is a numerical value; use `w32-get-locale-info' to convert to a
1968 human-readable form. */)
1969 (void)
1971 return make_number (GetThreadLocale ());
1974 static DWORD
1975 int_from_hex (char * s)
1977 DWORD val = 0;
1978 static char hex[] = "0123456789abcdefABCDEF";
1979 char * p;
1981 while (*s && (p = strchr (hex, *s)) != NULL)
1983 unsigned digit = p - hex;
1984 if (digit > 15)
1985 digit -= 6;
1986 val = val * 16 + digit;
1987 s++;
1989 return val;
1992 /* We need to build a global list, since the EnumSystemLocale callback
1993 function isn't given a context pointer. */
1994 Lisp_Object Vw32_valid_locale_ids;
1996 static BOOL CALLBACK
1997 enum_locale_fn (LPTSTR localeNum)
1999 DWORD id = int_from_hex (localeNum);
2000 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
2001 return TRUE;
2004 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2005 Sw32_get_valid_locale_ids, 0, 0, 0,
2006 doc: /* Return list of all valid Windows locale ids.
2007 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2008 human-readable form. */)
2009 (void)
2011 Vw32_valid_locale_ids = Qnil;
2013 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2015 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2016 return Vw32_valid_locale_ids;
2020 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2021 doc: /* Return Windows locale id for default locale setting.
2022 By default, the system default locale setting is returned; if the optional
2023 parameter USERP is non-nil, the user default locale setting is returned.
2024 This is a numerical value; use `w32-get-locale-info' to convert to a
2025 human-readable form. */)
2026 (Lisp_Object userp)
2028 if (NILP (userp))
2029 return make_number (GetSystemDefaultLCID ());
2030 return make_number (GetUserDefaultLCID ());
2034 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2035 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2036 If successful, the new locale id is returned, otherwise nil. */)
2037 (Lisp_Object lcid)
2039 CHECK_NUMBER (lcid);
2041 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2042 return Qnil;
2044 if (!SetThreadLocale (XINT (lcid)))
2045 return Qnil;
2047 /* Need to set input thread locale if present. */
2048 if (dwWindowsThreadId)
2049 /* Reply is not needed. */
2050 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2052 return make_number (GetThreadLocale ());
2056 /* We need to build a global list, since the EnumCodePages callback
2057 function isn't given a context pointer. */
2058 Lisp_Object Vw32_valid_codepages;
2060 static BOOL CALLBACK
2061 enum_codepage_fn (LPTSTR codepageNum)
2063 DWORD id = atoi (codepageNum);
2064 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2065 return TRUE;
2068 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2069 Sw32_get_valid_codepages, 0, 0, 0,
2070 doc: /* Return list of all valid Windows codepages. */)
2071 (void)
2073 Vw32_valid_codepages = Qnil;
2075 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2077 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2078 return Vw32_valid_codepages;
2082 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2083 Sw32_get_console_codepage, 0, 0, 0,
2084 doc: /* Return current Windows codepage for console input. */)
2085 (void)
2087 return make_number (GetConsoleCP ());
2091 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2092 Sw32_set_console_codepage, 1, 1, 0,
2093 doc: /* Make Windows codepage CP be the codepage for Emacs tty keyboard input.
2094 This codepage setting affects keyboard input in tty mode.
2095 If successful, the new CP is returned, otherwise nil. */)
2096 (Lisp_Object cp)
2098 CHECK_NUMBER (cp);
2100 if (!IsValidCodePage (XINT (cp)))
2101 return Qnil;
2103 if (!SetConsoleCP (XINT (cp)))
2104 return Qnil;
2106 return make_number (GetConsoleCP ());
2110 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2111 Sw32_get_console_output_codepage, 0, 0, 0,
2112 doc: /* Return current Windows codepage for console output. */)
2113 (void)
2115 return make_number (GetConsoleOutputCP ());
2119 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2120 Sw32_set_console_output_codepage, 1, 1, 0,
2121 doc: /* Make Windows codepage CP be the codepage for Emacs console output.
2122 This codepage setting affects display in tty mode.
2123 If successful, the new CP is returned, otherwise nil. */)
2124 (Lisp_Object cp)
2126 CHECK_NUMBER (cp);
2128 if (!IsValidCodePage (XINT (cp)))
2129 return Qnil;
2131 if (!SetConsoleOutputCP (XINT (cp)))
2132 return Qnil;
2134 return make_number (GetConsoleOutputCP ());
2138 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2139 Sw32_get_codepage_charset, 1, 1, 0,
2140 doc: /* Return charset ID corresponding to codepage CP.
2141 Returns nil if the codepage is not valid. */)
2142 (Lisp_Object cp)
2144 CHARSETINFO info;
2146 CHECK_NUMBER (cp);
2148 if (!IsValidCodePage (XINT (cp)))
2149 return Qnil;
2151 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2152 return make_number (info.ciCharset);
2154 return Qnil;
2158 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2159 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2160 doc: /* Return list of Windows keyboard languages and layouts.
2161 The return value is a list of pairs of language id and layout id. */)
2162 (void)
2164 int num_layouts = GetKeyboardLayoutList (0, NULL);
2165 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2166 Lisp_Object obj = Qnil;
2168 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2170 while (--num_layouts >= 0)
2172 DWORD kl = (DWORD) layouts[num_layouts];
2174 obj = Fcons (Fcons (make_number (kl & 0xffff),
2175 make_number ((kl >> 16) & 0xffff)),
2176 obj);
2180 return obj;
2184 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2185 Sw32_get_keyboard_layout, 0, 0, 0,
2186 doc: /* Return current Windows keyboard language and layout.
2187 The return value is the cons of the language id and the layout id. */)
2188 (void)
2190 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2192 return Fcons (make_number (kl & 0xffff),
2193 make_number ((kl >> 16) & 0xffff));
2197 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2198 Sw32_set_keyboard_layout, 1, 1, 0,
2199 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2200 The keyboard layout setting affects interpretation of keyboard input.
2201 If successful, the new layout id is returned, otherwise nil. */)
2202 (Lisp_Object layout)
2204 DWORD kl;
2206 CHECK_CONS (layout);
2207 CHECK_NUMBER_CAR (layout);
2208 CHECK_NUMBER_CDR (layout);
2210 kl = (XINT (XCAR (layout)) & 0xffff)
2211 | (XINT (XCDR (layout)) << 16);
2213 /* Synchronize layout with input thread. */
2214 if (dwWindowsThreadId)
2216 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2217 (WPARAM) kl, 0))
2219 MSG msg;
2220 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2222 if (msg.wParam == 0)
2223 return Qnil;
2226 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2227 return Qnil;
2229 return Fw32_get_keyboard_layout ();
2233 void
2234 syms_of_ntproc (void)
2236 DEFSYM (Qhigh, "high");
2237 DEFSYM (Qlow, "low");
2239 defsubr (&Sw32_has_winsock);
2240 defsubr (&Sw32_unload_winsock);
2242 defsubr (&Sw32_short_file_name);
2243 defsubr (&Sw32_long_file_name);
2244 defsubr (&Sw32_set_process_priority);
2245 defsubr (&Sw32_get_locale_info);
2246 defsubr (&Sw32_get_current_locale_id);
2247 defsubr (&Sw32_get_default_locale_id);
2248 defsubr (&Sw32_get_valid_locale_ids);
2249 defsubr (&Sw32_set_current_locale);
2251 defsubr (&Sw32_get_console_codepage);
2252 defsubr (&Sw32_set_console_codepage);
2253 defsubr (&Sw32_get_console_output_codepage);
2254 defsubr (&Sw32_set_console_output_codepage);
2255 defsubr (&Sw32_get_valid_codepages);
2256 defsubr (&Sw32_get_codepage_charset);
2258 defsubr (&Sw32_get_valid_keyboard_layouts);
2259 defsubr (&Sw32_get_keyboard_layout);
2260 defsubr (&Sw32_set_keyboard_layout);
2262 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args,
2263 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2264 Because Windows does not directly pass argv arrays to child processes,
2265 programs have to reconstruct the argv array by parsing the command
2266 line string. For an argument to contain a space, it must be enclosed
2267 in double quotes or it will be parsed as multiple arguments.
2269 If the value is a character, that character will be used to escape any
2270 quote characters that appear, otherwise a suitable escape character
2271 will be chosen based on the type of the program. */);
2272 Vw32_quote_process_args = Qt;
2274 DEFVAR_LISP ("w32-start-process-show-window",
2275 Vw32_start_process_show_window,
2276 doc: /* When nil, new child processes hide their windows.
2277 When non-nil, they show their window in the method of their choice.
2278 This variable doesn't affect GUI applications, which will never be hidden. */);
2279 Vw32_start_process_show_window = Qnil;
2281 DEFVAR_LISP ("w32-start-process-share-console",
2282 Vw32_start_process_share_console,
2283 doc: /* When nil, new child processes are given a new console.
2284 When non-nil, they share the Emacs console; this has the limitation of
2285 allowing only one DOS subprocess to run at a time (whether started directly
2286 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2287 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2288 otherwise respond to interrupts from Emacs. */);
2289 Vw32_start_process_share_console = Qnil;
2291 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2292 Vw32_start_process_inherit_error_mode,
2293 doc: /* When nil, new child processes revert to the default error mode.
2294 When non-nil, they inherit their error mode setting from Emacs, which stops
2295 them blocking when trying to access unmounted drives etc. */);
2296 Vw32_start_process_inherit_error_mode = Qt;
2298 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay,
2299 doc: /* Forced delay before reading subprocess output.
2300 This is done to improve the buffering of subprocess output, by
2301 avoiding the inefficiency of frequently reading small amounts of data.
2303 If positive, the value is the number of milliseconds to sleep before
2304 reading the subprocess output. If negative, the magnitude is the number
2305 of time slices to wait (effectively boosting the priority of the child
2306 process temporarily). A value of zero disables waiting entirely. */);
2307 w32_pipe_read_delay = 50;
2309 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names,
2310 doc: /* Non-nil means convert all-upper case file names to lower case.
2311 This applies when performing completions and file name expansion.
2312 Note that the value of this setting also affects remote file names,
2313 so you probably don't want to set to non-nil if you use case-sensitive
2314 filesystems via ange-ftp. */);
2315 Vw32_downcase_file_names = Qnil;
2317 #if 0
2318 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes,
2319 doc: /* Non-nil means attempt to fake realistic inode values.
2320 This works by hashing the truename of files, and should detect
2321 aliasing between long and short (8.3 DOS) names, but can have
2322 false positives because of hash collisions. Note that determining
2323 the truename of a file can be slow. */);
2324 Vw32_generate_fake_inodes = Qnil;
2325 #endif
2327 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes,
2328 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2329 This option controls whether to issue additional system calls to determine
2330 accurate link counts, file type, and ownership information. It is more
2331 useful for files on NTFS volumes, where hard links and file security are
2332 supported, than on volumes of the FAT family.
2334 Without these system calls, link count will always be reported as 1 and file
2335 ownership will be attributed to the current user.
2336 The default value `local' means only issue these system calls for files
2337 on local fixed drives. A value of nil means never issue them.
2338 Any other non-nil value means do this even on remote and removable drives
2339 where the performance impact may be noticeable even on modern hardware. */);
2340 Vw32_get_true_file_attributes = Qlocal;
2342 staticpro (&Vw32_valid_locale_ids);
2343 staticpro (&Vw32_valid_codepages);
2345 /* end of w32proc.c */