Add arch tagline
[emacs.git] / src / w32proc.c
blob33981445c7ca3cceef46c737155525500d959fcd
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 2006, 2007, 2008 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <io.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <sys/file.h>
33 /* must include CRT headers *before* config.h */
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
39 #undef signal
40 #undef wait
41 #undef spawnve
42 #undef select
43 #undef kill
45 #include <windows.h>
46 #ifdef __GNUC__
47 /* This definition is missing from mingw32 headers. */
48 extern BOOL WINAPI IsValidLocale(LCID, DWORD);
49 #endif
51 #ifdef HAVE_LANGINFO_CODESET
52 #include <nl_types.h>
53 #include <langinfo.h>
54 #endif
56 #include "lisp.h"
57 #include "character.h"
58 #include "w32.h"
59 #include "w32heap.h"
60 #include "systime.h"
61 #include "syswait.h"
62 #include "process.h"
63 #include "syssignal.h"
64 #include "w32term.h"
65 #include "dispextern.h" /* for xstrcasecmp */
67 #define RVA_TO_PTR(var,section,filedata) \
68 ((void *)((section)->PointerToRawData \
69 + ((DWORD)(var) - (section)->VirtualAddress) \
70 + (filedata).file_base))
72 /* Control whether spawnve quotes arguments as necessary to ensure
73 correct parsing by child process. Because not all uses of spawnve
74 are careful about constructing argv arrays, we make this behavior
75 conditional (off by default). */
76 Lisp_Object Vw32_quote_process_args;
78 /* Control whether create_child causes the process' window to be
79 hidden. The default is nil. */
80 Lisp_Object Vw32_start_process_show_window;
82 /* Control whether create_child causes the process to inherit Emacs'
83 console window, or be given a new one of its own. The default is
84 nil, to allow multiple DOS programs to run on Win95. Having separate
85 consoles also allows Emacs to cleanly terminate process groups. */
86 Lisp_Object Vw32_start_process_share_console;
88 /* Control whether create_child cause the process to inherit Emacs'
89 error mode setting. The default is t, to minimize the possibility of
90 subprocesses blocking when accessing unmounted drives. */
91 Lisp_Object Vw32_start_process_inherit_error_mode;
93 /* Time to sleep before reading from a subprocess output pipe - this
94 avoids the inefficiency of frequently reading small amounts of data.
95 This is primarily necessary for handling DOS processes on Windows 95,
96 but is useful for W32 processes on both Windows 95 and NT as well. */
97 int w32_pipe_read_delay;
99 /* Control conversion of upper case file names to lower case.
100 nil means no, t means yes. */
101 Lisp_Object Vw32_downcase_file_names;
103 /* Control whether stat() attempts to generate fake but hopefully
104 "accurate" inode values, by hashing the absolute truenames of files.
105 This should detect aliasing between long and short names, but still
106 allows the possibility of hash collisions. */
107 Lisp_Object Vw32_generate_fake_inodes;
109 /* Control whether stat() attempts to determine file type and link count
110 exactly, at the expense of slower operation. Since true hard links
111 are supported on NTFS volumes, this is only relevant on NT. */
112 Lisp_Object Vw32_get_true_file_attributes;
113 extern Lisp_Object Qlocal;
115 Lisp_Object Qhigh, Qlow;
117 #ifdef EMACSDEBUG
118 void _DebPrint (const char *fmt, ...)
120 char buf[1024];
121 va_list args;
123 va_start (args, fmt);
124 vsprintf (buf, fmt, args);
125 va_end (args);
126 OutputDebugString (buf);
128 #endif
130 typedef void (_CALLBACK_ *signal_handler)(int);
132 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
133 static signal_handler sig_handlers[NSIG];
135 /* Fake signal implementation to record the SIGCHLD handler. */
136 signal_handler
137 sys_signal (int sig, signal_handler handler)
139 signal_handler old;
141 if (sig != SIGCHLD)
143 errno = EINVAL;
144 return SIG_ERR;
146 old = sig_handlers[sig];
147 sig_handlers[sig] = handler;
148 return old;
151 /* Defined in <process.h> which conflicts with the local copy */
152 #define _P_NOWAIT 1
154 /* Child process management list. */
155 int child_proc_count = 0;
156 child_process child_procs[ MAX_CHILDREN ];
157 child_process *dead_child = NULL;
159 DWORD WINAPI reader_thread (void *arg);
161 /* Find an unused process slot. */
162 child_process *
163 new_child (void)
165 child_process *cp;
166 DWORD id;
168 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
169 if (!CHILD_ACTIVE (cp))
170 goto Initialise;
171 if (child_proc_count == MAX_CHILDREN)
172 return NULL;
173 cp = &child_procs[child_proc_count++];
175 Initialise:
176 memset (cp, 0, sizeof(*cp));
177 cp->fd = -1;
178 cp->pid = -1;
179 cp->procinfo.hProcess = NULL;
180 cp->status = STATUS_READ_ERROR;
182 /* use manual reset event so that select() will function properly */
183 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
184 if (cp->char_avail)
186 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
187 if (cp->char_consumed)
189 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
190 if (cp->thrd)
191 return cp;
194 delete_child (cp);
195 return NULL;
198 void
199 delete_child (child_process *cp)
201 int i;
203 /* Should not be deleting a child that is still needed. */
204 for (i = 0; i < MAXDESC; i++)
205 if (fd_info[i].cp == cp)
206 abort ();
208 if (!CHILD_ACTIVE (cp))
209 return;
211 /* reap thread if necessary */
212 if (cp->thrd)
214 DWORD rc;
216 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
218 /* let the thread exit cleanly if possible */
219 cp->status = STATUS_READ_ERROR;
220 SetEvent (cp->char_consumed);
221 #if 0
222 /* We used to forceably terminate the thread here, but it
223 is normally unnecessary, and in abnormal cases, the worst that
224 will happen is we have an extra idle thread hanging around
225 waiting for the zombie process. */
226 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
228 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
229 "with %lu for fd %ld\n", GetLastError (), cp->fd));
230 TerminateThread (cp->thrd, 0);
232 #endif
234 CloseHandle (cp->thrd);
235 cp->thrd = NULL;
237 if (cp->char_avail)
239 CloseHandle (cp->char_avail);
240 cp->char_avail = NULL;
242 if (cp->char_consumed)
244 CloseHandle (cp->char_consumed);
245 cp->char_consumed = NULL;
248 /* update child_proc_count (highest numbered slot in use plus one) */
249 if (cp == child_procs + child_proc_count - 1)
251 for (i = child_proc_count-1; i >= 0; i--)
252 if (CHILD_ACTIVE (&child_procs[i]))
254 child_proc_count = i + 1;
255 break;
258 if (i < 0)
259 child_proc_count = 0;
262 /* Find a child by pid. */
263 static child_process *
264 find_child_pid (DWORD pid)
266 child_process *cp;
268 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
269 if (CHILD_ACTIVE (cp) && pid == cp->pid)
270 return cp;
271 return NULL;
275 /* Thread proc for child process and socket reader threads. Each thread
276 is normally blocked until woken by select() to check for input by
277 reading one char. When the read completes, char_avail is signaled
278 to wake up the select emulator and the thread blocks itself again. */
279 DWORD WINAPI
280 reader_thread (void *arg)
282 child_process *cp;
284 /* Our identity */
285 cp = (child_process *)arg;
287 /* We have to wait for the go-ahead before we can start */
288 if (cp == NULL
289 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
290 return 1;
292 for (;;)
294 int rc;
296 if (fd_info[cp->fd].flags & FILE_LISTEN)
297 rc = _sys_wait_accept (cp->fd);
298 else
299 rc = _sys_read_ahead (cp->fd);
301 /* The name char_avail is a misnomer - it really just means the
302 read-ahead has completed, whether successfully or not. */
303 if (!SetEvent (cp->char_avail))
305 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
306 GetLastError (), cp->fd));
307 return 1;
310 if (rc == STATUS_READ_ERROR)
311 return 1;
313 /* If the read died, the child has died so let the thread die */
314 if (rc == STATUS_READ_FAILED)
315 break;
317 /* Wait until our input is acknowledged before reading again */
318 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
320 DebPrint (("reader_thread.WaitForSingleObject failed with "
321 "%lu for fd %ld\n", GetLastError (), cp->fd));
322 break;
325 return 0;
328 /* To avoid Emacs changing directory, we just record here the directory
329 the new process should start in. This is set just before calling
330 sys_spawnve, and is not generally valid at any other time. */
331 static char * process_dir;
333 static BOOL
334 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
335 int * pPid, child_process *cp)
337 STARTUPINFO start;
338 SECURITY_ATTRIBUTES sec_attrs;
339 #if 0
340 SECURITY_DESCRIPTOR sec_desc;
341 #endif
342 DWORD flags;
343 char dir[ MAXPATHLEN ];
345 if (cp == NULL) abort ();
347 memset (&start, 0, sizeof (start));
348 start.cb = sizeof (start);
350 #ifdef HAVE_NTGUI
351 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
352 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
353 else
354 start.dwFlags = STARTF_USESTDHANDLES;
355 start.wShowWindow = SW_HIDE;
357 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
358 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
359 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
360 #endif /* HAVE_NTGUI */
362 #if 0
363 /* Explicitly specify no security */
364 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
365 goto EH_Fail;
366 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
367 goto EH_Fail;
368 #endif
369 sec_attrs.nLength = sizeof (sec_attrs);
370 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
371 sec_attrs.bInheritHandle = FALSE;
373 strcpy (dir, process_dir);
374 unixtodos_filename (dir);
376 flags = (!NILP (Vw32_start_process_share_console)
377 ? CREATE_NEW_PROCESS_GROUP
378 : CREATE_NEW_CONSOLE);
379 if (NILP (Vw32_start_process_inherit_error_mode))
380 flags |= CREATE_DEFAULT_ERROR_MODE;
381 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
382 flags, env, dir, &start, &cp->procinfo))
383 goto EH_Fail;
385 cp->pid = (int) cp->procinfo.dwProcessId;
387 /* Hack for Windows 95, which assigns large (ie negative) pids */
388 if (cp->pid < 0)
389 cp->pid = -cp->pid;
391 /* pid must fit in a Lisp_Int */
392 cp->pid = cp->pid & INTMASK;
394 *pPid = cp->pid;
396 return TRUE;
398 EH_Fail:
399 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
400 return FALSE;
403 /* create_child doesn't know what emacs' file handle will be for waiting
404 on output from the child, so we need to make this additional call
405 to register the handle with the process
406 This way the select emulator knows how to match file handles with
407 entries in child_procs. */
408 void
409 register_child (int pid, int fd)
411 child_process *cp;
413 cp = find_child_pid (pid);
414 if (cp == NULL)
416 DebPrint (("register_child unable to find pid %lu\n", pid));
417 return;
420 #ifdef FULL_DEBUG
421 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
422 #endif
424 cp->fd = fd;
426 /* thread is initially blocked until select is called; set status so
427 that select will release thread */
428 cp->status = STATUS_READ_ACKNOWLEDGED;
430 /* attach child_process to fd_info */
431 if (fd_info[fd].cp != NULL)
433 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
434 abort ();
437 fd_info[fd].cp = cp;
440 /* When a process dies its pipe will break so the reader thread will
441 signal failure to the select emulator.
442 The select emulator then calls this routine to clean up.
443 Since the thread signaled failure we can assume it is exiting. */
444 static void
445 reap_subprocess (child_process *cp)
447 if (cp->procinfo.hProcess)
449 /* Reap the process */
450 #ifdef FULL_DEBUG
451 /* Process should have already died before we are called. */
452 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
453 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
454 #endif
455 CloseHandle (cp->procinfo.hProcess);
456 cp->procinfo.hProcess = NULL;
457 CloseHandle (cp->procinfo.hThread);
458 cp->procinfo.hThread = NULL;
461 /* For asynchronous children, the child_proc resources will be freed
462 when the last pipe read descriptor is closed; for synchronous
463 children, we must explicitly free the resources now because
464 register_child has not been called. */
465 if (cp->fd == -1)
466 delete_child (cp);
469 /* Wait for any of our existing child processes to die
470 When it does, close its handle
471 Return the pid and fill in the status if non-NULL. */
474 sys_wait (int *status)
476 DWORD active, retval;
477 int nh;
478 int pid;
479 child_process *cp, *cps[MAX_CHILDREN];
480 HANDLE wait_hnd[MAX_CHILDREN];
482 nh = 0;
483 if (dead_child != NULL)
485 /* We want to wait for a specific child */
486 wait_hnd[nh] = dead_child->procinfo.hProcess;
487 cps[nh] = dead_child;
488 if (!wait_hnd[nh]) abort ();
489 nh++;
490 active = 0;
491 goto get_result;
493 else
495 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
496 /* some child_procs might be sockets; ignore them */
497 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
498 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
500 wait_hnd[nh] = cp->procinfo.hProcess;
501 cps[nh] = cp;
502 nh++;
506 if (nh == 0)
508 /* Nothing to wait on, so fail */
509 errno = ECHILD;
510 return -1;
515 /* Check for quit about once a second. */
516 QUIT;
517 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
518 } while (active == WAIT_TIMEOUT);
520 if (active == WAIT_FAILED)
522 errno = EBADF;
523 return -1;
525 else if (active >= WAIT_OBJECT_0
526 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
528 active -= WAIT_OBJECT_0;
530 else if (active >= WAIT_ABANDONED_0
531 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
533 active -= WAIT_ABANDONED_0;
535 else
536 abort ();
538 get_result:
539 if (!GetExitCodeProcess (wait_hnd[active], &retval))
541 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
542 GetLastError ()));
543 retval = 1;
545 if (retval == STILL_ACTIVE)
547 /* Should never happen */
548 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
549 errno = EINVAL;
550 return -1;
553 /* Massage the exit code from the process to match the format expected
554 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
555 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
557 if (retval == STATUS_CONTROL_C_EXIT)
558 retval = SIGINT;
559 else
560 retval <<= 8;
562 cp = cps[active];
563 pid = cp->pid;
564 #ifdef FULL_DEBUG
565 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
566 #endif
568 if (status)
570 *status = retval;
572 else if (synch_process_alive)
574 synch_process_alive = 0;
576 /* Report the status of the synchronous process. */
577 if (WIFEXITED (retval))
578 synch_process_retcode = WRETCODE (retval);
579 else if (WIFSIGNALED (retval))
581 int code = WTERMSIG (retval);
582 char *signame;
584 synchronize_system_messages_locale ();
585 signame = strsignal (code);
587 if (signame == 0)
588 signame = "unknown";
590 synch_process_death = signame;
593 reap_subprocess (cp);
596 reap_subprocess (cp);
598 return pid;
601 /* Old versions of w32api headers don't have separate 32-bit and
602 64-bit defines, but the one they have matches the 32-bit variety. */
603 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
604 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
605 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
606 #endif
608 void
609 w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app, int * is_gui_app)
611 file_data executable;
612 char * p;
614 /* Default values in case we can't tell for sure. */
615 *is_dos_app = FALSE;
616 *is_cygnus_app = FALSE;
617 *is_gui_app = FALSE;
619 if (!open_input_file (&executable, filename))
620 return;
622 p = strrchr (filename, '.');
624 /* We can only identify DOS .com programs from the extension. */
625 if (p && xstrcasecmp (p, ".com") == 0)
626 *is_dos_app = TRUE;
627 else if (p && (xstrcasecmp (p, ".bat") == 0
628 || xstrcasecmp (p, ".cmd") == 0))
630 /* A DOS shell script - it appears that CreateProcess is happy to
631 accept this (somewhat surprisingly); presumably it looks at
632 COMSPEC to determine what executable to actually invoke.
633 Therefore, we have to do the same here as well. */
634 /* Actually, I think it uses the program association for that
635 extension, which is defined in the registry. */
636 p = egetenv ("COMSPEC");
637 if (p)
638 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
640 else
642 /* Look for DOS .exe signature - if found, we must also check that
643 it isn't really a 16- or 32-bit Windows exe, since both formats
644 start with a DOS program stub. Note that 16-bit Windows
645 executables use the OS/2 1.x format. */
647 IMAGE_DOS_HEADER * dos_header;
648 IMAGE_NT_HEADERS * nt_header;
650 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
651 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
652 goto unwind;
654 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
656 if ((char *) nt_header > (char *) dos_header + executable.size)
658 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
659 *is_dos_app = TRUE;
661 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
662 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
664 *is_dos_app = TRUE;
666 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
668 IMAGE_DATA_DIRECTORY *data_dir = NULL;
669 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
671 /* Ensure we are using the 32 bit structure. */
672 IMAGE_OPTIONAL_HEADER32 *opt
673 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
674 data_dir = opt->DataDirectory;
675 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
677 /* MingW 3.12 has the required 64 bit structs, but in case older
678 versions don't, only check 64 bit exes if we know how. */
679 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
680 else if (nt_header->OptionalHeader.Magic
681 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
683 IMAGE_OPTIONAL_HEADER64 *opt
684 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
685 data_dir = opt->DataDirectory;
686 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
688 #endif
689 if (data_dir)
691 /* Look for cygwin.dll in DLL import list. */
692 IMAGE_DATA_DIRECTORY import_dir =
693 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
694 IMAGE_IMPORT_DESCRIPTOR * imports;
695 IMAGE_SECTION_HEADER * section;
697 section = rva_to_section (import_dir.VirtualAddress, nt_header);
698 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
699 executable);
701 for ( ; imports->Name; imports++)
703 char * dllname = RVA_TO_PTR (imports->Name, section,
704 executable);
706 /* The exact name of the cygwin dll has changed with
707 various releases, but hopefully this will be reasonably
708 future proof. */
709 if (strncmp (dllname, "cygwin", 6) == 0)
711 *is_cygnus_app = TRUE;
712 break;
719 unwind:
720 close_file_data (&executable);
724 compare_env (const void *strp1, const void *strp2)
726 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
728 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
730 /* Sort order in command.com/cmd.exe is based on uppercasing
731 names, so do the same here. */
732 if (toupper (*str1) > toupper (*str2))
733 return 1;
734 else if (toupper (*str1) < toupper (*str2))
735 return -1;
736 str1++, str2++;
739 if (*str1 == '=' && *str2 == '=')
740 return 0;
741 else if (*str1 == '=')
742 return -1;
743 else
744 return 1;
747 void
748 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
750 char **optr, **nptr;
751 int num;
753 nptr = new_envp;
754 optr = envp1;
755 while (*optr)
756 *nptr++ = *optr++;
757 num = optr - envp1;
759 optr = envp2;
760 while (*optr)
761 *nptr++ = *optr++;
762 num += optr - envp2;
764 qsort (new_envp, num, sizeof (char *), compare_env);
766 *nptr = NULL;
769 /* When a new child process is created we need to register it in our list,
770 so intercept spawn requests. */
772 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
774 Lisp_Object program, full;
775 char *cmdline, *env, *parg, **targ;
776 int arglen, numenv;
777 int pid;
778 child_process *cp;
779 int is_dos_app, is_cygnus_app, is_gui_app;
780 int do_quoting = 0;
781 char escape_char;
782 /* We pass our process ID to our children by setting up an environment
783 variable in their environment. */
784 char ppid_env_var_buffer[64];
785 char *extra_env[] = {ppid_env_var_buffer, NULL};
786 /* These are the characters that cause an argument to need quoting.
787 Arguments with whitespace characters need quoting to prevent the
788 argument being split into two or more. Arguments with wildcards
789 are also quoted, for consistency with posix platforms, where wildcards
790 are not expanded if we run the program directly without a shell.
791 Some extra whitespace characters need quoting in Cygwin programs,
792 so this list is conditionally modified below. */
793 char *sepchars = " \t*?";
795 /* We don't care about the other modes */
796 if (mode != _P_NOWAIT)
798 errno = EINVAL;
799 return -1;
802 /* Handle executable names without an executable suffix. */
803 program = make_string (cmdname, strlen (cmdname));
804 if (NILP (Ffile_executable_p (program)))
806 struct gcpro gcpro1;
808 full = Qnil;
809 GCPRO1 (program);
810 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
811 UNGCPRO;
812 if (NILP (full))
814 errno = EINVAL;
815 return -1;
817 program = full;
820 /* make sure argv[0] and cmdname are both in DOS format */
821 cmdname = SDATA (program);
822 unixtodos_filename (cmdname);
823 argv[0] = cmdname;
825 /* Determine whether program is a 16-bit DOS executable, or a w32
826 executable that is implicitly linked to the Cygnus dll (implying it
827 was compiled with the Cygnus GNU toolchain and hence relies on
828 cygwin.dll to parse the command line - we use this to decide how to
829 escape quote chars in command line args that must be quoted).
831 Also determine whether it is a GUI app, so that we don't hide its
832 initial window unless specifically requested. */
833 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
835 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
836 application to start it by specifying the helper app as cmdname,
837 while leaving the real app name as argv[0]. */
838 if (is_dos_app)
840 cmdname = alloca (MAXPATHLEN);
841 if (egetenv ("CMDPROXY"))
842 strcpy (cmdname, egetenv ("CMDPROXY"));
843 else
845 strcpy (cmdname, SDATA (Vinvocation_directory));
846 strcat (cmdname, "cmdproxy.exe");
848 unixtodos_filename (cmdname);
851 /* we have to do some conjuring here to put argv and envp into the
852 form CreateProcess wants... argv needs to be a space separated/null
853 terminated list of parameters, and envp is a null
854 separated/double-null terminated list of parameters.
856 Additionally, zero-length args and args containing whitespace or
857 quote chars need to be wrapped in double quotes - for this to work,
858 embedded quotes need to be escaped as well. The aim is to ensure
859 the child process reconstructs the argv array we start with
860 exactly, so we treat quotes at the beginning and end of arguments
861 as embedded quotes.
863 The w32 GNU-based library from Cygnus doubles quotes to escape
864 them, while MSVC uses backslash for escaping. (Actually the MSVC
865 startup code does attempt to recognise doubled quotes and accept
866 them, but gets it wrong and ends up requiring three quotes to get a
867 single embedded quote!) So by default we decide whether to use
868 quote or backslash as the escape character based on whether the
869 binary is apparently a Cygnus compiled app.
871 Note that using backslash to escape embedded quotes requires
872 additional special handling if an embedded quote is already
873 preceeded by backslash, or if an arg requiring quoting ends with
874 backslash. In such cases, the run of escape characters needs to be
875 doubled. For consistency, we apply this special handling as long
876 as the escape character is not quote.
878 Since we have no idea how large argv and envp are likely to be we
879 figure out list lengths on the fly and allocate them. */
881 if (!NILP (Vw32_quote_process_args))
883 do_quoting = 1;
884 /* Override escape char by binding w32-quote-process-args to
885 desired character, or use t for auto-selection. */
886 if (INTEGERP (Vw32_quote_process_args))
887 escape_char = XINT (Vw32_quote_process_args);
888 else
889 escape_char = is_cygnus_app ? '"' : '\\';
892 /* Cygwin apps needs quoting a bit more often */
893 if (escape_char == '"')
894 sepchars = "\r\n\t\f '";
896 /* do argv... */
897 arglen = 0;
898 targ = argv;
899 while (*targ)
901 char * p = *targ;
902 int need_quotes = 0;
903 int escape_char_run = 0;
905 if (*p == 0)
906 need_quotes = 1;
907 for ( ; *p; p++)
909 if (escape_char == '"' && *p == '\\')
910 /* If it's a Cygwin app, \ needs to be escaped. */
911 arglen++;
912 else if (*p == '"')
914 /* allow for embedded quotes to be escaped */
915 arglen++;
916 need_quotes = 1;
917 /* handle the case where the embedded quote is already escaped */
918 if (escape_char_run > 0)
920 /* To preserve the arg exactly, we need to double the
921 preceding escape characters (plus adding one to
922 escape the quote character itself). */
923 arglen += escape_char_run;
926 else if (strchr (sepchars, *p) != NULL)
928 need_quotes = 1;
931 if (*p == escape_char && escape_char != '"')
932 escape_char_run++;
933 else
934 escape_char_run = 0;
936 if (need_quotes)
938 arglen += 2;
939 /* handle the case where the arg ends with an escape char - we
940 must not let the enclosing quote be escaped. */
941 if (escape_char_run > 0)
942 arglen += escape_char_run;
944 arglen += strlen (*targ++) + 1;
946 cmdline = alloca (arglen);
947 targ = argv;
948 parg = cmdline;
949 while (*targ)
951 char * p = *targ;
952 int need_quotes = 0;
954 if (*p == 0)
955 need_quotes = 1;
957 if (do_quoting)
959 for ( ; *p; p++)
960 if ((strchr (sepchars, *p) != NULL) || *p == '"')
961 need_quotes = 1;
963 if (need_quotes)
965 int escape_char_run = 0;
966 char * first;
967 char * last;
969 p = *targ;
970 first = p;
971 last = p + strlen (p) - 1;
972 *parg++ = '"';
973 #if 0
974 /* This version does not escape quotes if they occur at the
975 beginning or end of the arg - this could lead to incorrect
976 behavior when the arg itself represents a command line
977 containing quoted args. I believe this was originally done
978 as a hack to make some things work, before
979 `w32-quote-process-args' was added. */
980 while (*p)
982 if (*p == '"' && p > first && p < last)
983 *parg++ = escape_char; /* escape embedded quotes */
984 *parg++ = *p++;
986 #else
987 for ( ; *p; p++)
989 if (*p == '"')
991 /* double preceding escape chars if any */
992 while (escape_char_run > 0)
994 *parg++ = escape_char;
995 escape_char_run--;
997 /* escape all quote chars, even at beginning or end */
998 *parg++ = escape_char;
1000 else if (escape_char == '"' && *p == '\\')
1001 *parg++ = '\\';
1002 *parg++ = *p;
1004 if (*p == escape_char && escape_char != '"')
1005 escape_char_run++;
1006 else
1007 escape_char_run = 0;
1009 /* double escape chars before enclosing quote */
1010 while (escape_char_run > 0)
1012 *parg++ = escape_char;
1013 escape_char_run--;
1015 #endif
1016 *parg++ = '"';
1018 else
1020 strcpy (parg, *targ);
1021 parg += strlen (*targ);
1023 *parg++ = ' ';
1024 targ++;
1026 *--parg = '\0';
1028 /* and envp... */
1029 arglen = 1;
1030 targ = envp;
1031 numenv = 1; /* for end null */
1032 while (*targ)
1034 arglen += strlen (*targ++) + 1;
1035 numenv++;
1037 /* extra env vars... */
1038 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1039 GetCurrentProcessId ());
1040 arglen += strlen (ppid_env_var_buffer) + 1;
1041 numenv++;
1043 /* merge env passed in and extra env into one, and sort it. */
1044 targ = (char **) alloca (numenv * sizeof (char *));
1045 merge_and_sort_env (envp, extra_env, targ);
1047 /* concatenate env entries. */
1048 env = alloca (arglen);
1049 parg = env;
1050 while (*targ)
1052 strcpy (parg, *targ);
1053 parg += strlen (*targ++);
1054 *parg++ = '\0';
1056 *parg++ = '\0';
1057 *parg = '\0';
1059 cp = new_child ();
1060 if (cp == NULL)
1062 errno = EAGAIN;
1063 return -1;
1066 /* Now create the process. */
1067 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1069 delete_child (cp);
1070 errno = ENOEXEC;
1071 return -1;
1074 return pid;
1077 /* Emulate the select call
1078 Wait for available input on any of the given rfds, or timeout if
1079 a timeout is given and no input is detected
1080 wfds and efds are not supported and must be NULL.
1082 For simplicity, we detect the death of child processes here and
1083 synchronously call the SIGCHLD handler. Since it is possible for
1084 children to be created without a corresponding pipe handle from which
1085 to read output, we wait separately on the process handles as well as
1086 the char_avail events for each process pipe. We only call
1087 wait/reap_process when the process actually terminates.
1089 To reduce the number of places in which Emacs can be hung such that
1090 C-g is not able to interrupt it, we always wait on interrupt_handle
1091 (which is signaled by the input thread when C-g is detected). If we
1092 detect that we were woken up by C-g, we return -1 with errno set to
1093 EINTR as on Unix. */
1095 /* From ntterm.c */
1096 extern HANDLE keyboard_handle;
1098 /* From w32xfns.c */
1099 extern HANDLE interrupt_handle;
1101 /* From process.c */
1102 extern int proc_buffered_char[];
1105 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1106 EMACS_TIME *timeout)
1108 SELECT_TYPE orfds;
1109 DWORD timeout_ms, start_time;
1110 int i, nh, nc, nr;
1111 DWORD active;
1112 child_process *cp, *cps[MAX_CHILDREN];
1113 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1114 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1116 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1118 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1119 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1121 Sleep (timeout_ms);
1122 return 0;
1125 /* Otherwise, we only handle rfds, so fail otherwise. */
1126 if (rfds == NULL || wfds != NULL || efds != NULL)
1128 errno = EINVAL;
1129 return -1;
1132 orfds = *rfds;
1133 FD_ZERO (rfds);
1134 nr = 0;
1136 /* Always wait on interrupt_handle, to detect C-g (quit). */
1137 wait_hnd[0] = interrupt_handle;
1138 fdindex[0] = -1;
1140 /* Build a list of pipe handles to wait on. */
1141 nh = 1;
1142 for (i = 0; i < nfds; i++)
1143 if (FD_ISSET (i, &orfds))
1145 if (i == 0)
1147 if (keyboard_handle)
1149 /* Handle stdin specially */
1150 wait_hnd[nh] = keyboard_handle;
1151 fdindex[nh] = i;
1152 nh++;
1155 /* Check for any emacs-generated input in the queue since
1156 it won't be detected in the wait */
1157 if (detect_input_pending ())
1159 FD_SET (i, rfds);
1160 return 1;
1163 else
1165 /* Child process and socket input */
1166 cp = fd_info[i].cp;
1167 if (cp)
1169 int current_status = cp->status;
1171 if (current_status == STATUS_READ_ACKNOWLEDGED)
1173 /* Tell reader thread which file handle to use. */
1174 cp->fd = i;
1175 /* Wake up the reader thread for this process */
1176 cp->status = STATUS_READ_READY;
1177 if (!SetEvent (cp->char_consumed))
1178 DebPrint (("nt_select.SetEvent failed with "
1179 "%lu for fd %ld\n", GetLastError (), i));
1182 #ifdef CHECK_INTERLOCK
1183 /* slightly crude cross-checking of interlock between threads */
1185 current_status = cp->status;
1186 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1188 /* char_avail has been signaled, so status (which may
1189 have changed) should indicate read has completed
1190 but has not been acknowledged. */
1191 current_status = cp->status;
1192 if (current_status != STATUS_READ_SUCCEEDED
1193 && current_status != STATUS_READ_FAILED)
1194 DebPrint (("char_avail set, but read not completed: status %d\n",
1195 current_status));
1197 else
1199 /* char_avail has not been signaled, so status should
1200 indicate that read is in progress; small possibility
1201 that read has completed but event wasn't yet signaled
1202 when we tested it (because a context switch occurred
1203 or if running on separate CPUs). */
1204 if (current_status != STATUS_READ_READY
1205 && current_status != STATUS_READ_IN_PROGRESS
1206 && current_status != STATUS_READ_SUCCEEDED
1207 && current_status != STATUS_READ_FAILED)
1208 DebPrint (("char_avail reset, but read status is bad: %d\n",
1209 current_status));
1211 #endif
1212 wait_hnd[nh] = cp->char_avail;
1213 fdindex[nh] = i;
1214 if (!wait_hnd[nh]) abort ();
1215 nh++;
1216 #ifdef FULL_DEBUG
1217 DebPrint (("select waiting on child %d fd %d\n",
1218 cp-child_procs, i));
1219 #endif
1221 else
1223 /* Unable to find something to wait on for this fd, skip */
1225 /* Note that this is not a fatal error, and can in fact
1226 happen in unusual circumstances. Specifically, if
1227 sys_spawnve fails, eg. because the program doesn't
1228 exist, and debug-on-error is t so Fsignal invokes a
1229 nested input loop, then the process output pipe is
1230 still included in input_wait_mask with no child_proc
1231 associated with it. (It is removed when the debugger
1232 exits the nested input loop and the error is thrown.) */
1234 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1239 count_children:
1240 /* Add handles of child processes. */
1241 nc = 0;
1242 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
1243 /* Some child_procs might be sockets; ignore them. Also some
1244 children may have died already, but we haven't finished reading
1245 the process output; ignore them too. */
1246 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1247 && (cp->fd < 0
1248 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1249 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1252 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1253 cps[nc] = cp;
1254 nc++;
1257 /* Nothing to look for, so we didn't find anything */
1258 if (nh + nc == 0)
1260 if (timeout)
1261 Sleep (timeout_ms);
1262 return 0;
1265 start_time = GetTickCount ();
1267 /* Wait for input or child death to be signaled. If user input is
1268 allowed, then also accept window messages. */
1269 if (FD_ISSET (0, &orfds))
1270 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1271 QS_ALLINPUT);
1272 else
1273 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1275 if (active == WAIT_FAILED)
1277 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1278 nh + nc, timeout_ms, GetLastError ()));
1279 /* don't return EBADF - this causes wait_reading_process_output to
1280 abort; WAIT_FAILED is returned when single-stepping under
1281 Windows 95 after switching thread focus in debugger, and
1282 possibly at other times. */
1283 errno = EINTR;
1284 return -1;
1286 else if (active == WAIT_TIMEOUT)
1288 return 0;
1290 else if (active >= WAIT_OBJECT_0
1291 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1293 active -= WAIT_OBJECT_0;
1295 else if (active >= WAIT_ABANDONED_0
1296 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1298 active -= WAIT_ABANDONED_0;
1300 else
1301 abort ();
1303 /* Loop over all handles after active (now officially documented as
1304 being the first signaled handle in the array). We do this to
1305 ensure fairness, so that all channels with data available will be
1306 processed - otherwise higher numbered channels could be starved. */
1309 if (active == nh + nc)
1311 /* There are messages in the lisp thread's queue; we must
1312 drain the queue now to ensure they are processed promptly,
1313 because if we don't do so, we will not be woken again until
1314 further messages arrive.
1316 NB. If ever we allow window message procedures to callback
1317 into lisp, we will need to ensure messages are dispatched
1318 at a safe time for lisp code to be run (*), and we may also
1319 want to provide some hooks in the dispatch loop to cater
1320 for modeless dialogs created by lisp (ie. to register
1321 window handles to pass to IsDialogMessage).
1323 (*) Note that MsgWaitForMultipleObjects above is an
1324 internal dispatch point for messages that are sent to
1325 windows created by this thread. */
1326 drain_message_queue ();
1328 else if (active >= nh)
1330 cp = cps[active - nh];
1332 /* We cannot always signal SIGCHLD immediately; if we have not
1333 finished reading the process output, we must delay sending
1334 SIGCHLD until we do. */
1336 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1337 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1338 /* SIG_DFL for SIGCHLD is ignore */
1339 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1340 sig_handlers[SIGCHLD] != SIG_IGN)
1342 #ifdef FULL_DEBUG
1343 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1344 cp->pid));
1345 #endif
1346 dead_child = cp;
1347 sig_handlers[SIGCHLD] (SIGCHLD);
1348 dead_child = NULL;
1351 else if (fdindex[active] == -1)
1353 /* Quit (C-g) was detected. */
1354 errno = EINTR;
1355 return -1;
1357 else if (fdindex[active] == 0)
1359 /* Keyboard input available */
1360 FD_SET (0, rfds);
1361 nr++;
1363 else
1365 /* must be a socket or pipe - read ahead should have
1366 completed, either succeeding or failing. */
1367 FD_SET (fdindex[active], rfds);
1368 nr++;
1371 /* Even though wait_reading_process_output only reads from at most
1372 one channel, we must process all channels here so that we reap
1373 all children that have died. */
1374 while (++active < nh + nc)
1375 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1376 break;
1377 } while (active < nh + nc);
1379 /* If no input has arrived and timeout hasn't expired, wait again. */
1380 if (nr == 0)
1382 DWORD elapsed = GetTickCount () - start_time;
1384 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1386 if (timeout_ms != INFINITE)
1387 timeout_ms -= elapsed;
1388 goto count_children;
1392 return nr;
1395 /* Substitute for certain kill () operations */
1397 static BOOL CALLBACK
1398 find_child_console (HWND hwnd, LPARAM arg)
1400 child_process * cp = (child_process *) arg;
1401 DWORD thread_id;
1402 DWORD process_id;
1404 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1405 if (process_id == cp->procinfo.dwProcessId)
1407 char window_class[32];
1409 GetClassName (hwnd, window_class, sizeof (window_class));
1410 if (strcmp (window_class,
1411 (os_subtype == OS_WIN95)
1412 ? "tty"
1413 : "ConsoleWindowClass") == 0)
1415 cp->hwnd = hwnd;
1416 return FALSE;
1419 /* keep looking */
1420 return TRUE;
1424 sys_kill (int pid, int sig)
1426 child_process *cp;
1427 HANDLE proc_hand;
1428 int need_to_free = 0;
1429 int rc = 0;
1431 /* Only handle signals that will result in the process dying */
1432 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1434 errno = EINVAL;
1435 return -1;
1438 cp = find_child_pid (pid);
1439 if (cp == NULL)
1441 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1442 if (proc_hand == NULL)
1444 errno = EPERM;
1445 return -1;
1447 need_to_free = 1;
1449 else
1451 proc_hand = cp->procinfo.hProcess;
1452 pid = cp->procinfo.dwProcessId;
1454 /* Try to locate console window for process. */
1455 EnumWindows (find_child_console, (LPARAM) cp);
1458 if (sig == SIGINT || sig == SIGQUIT)
1460 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1462 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1463 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1464 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1465 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1466 HWND foreground_window;
1468 if (break_scan_code == 0)
1470 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1471 vk_break_code = 'C';
1472 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1475 foreground_window = GetForegroundWindow ();
1476 if (foreground_window)
1478 /* NT 5.0, and apparently also Windows 98, will not allow
1479 a Window to be set to foreground directly without the
1480 user's involvement. The workaround is to attach
1481 ourselves to the thread that owns the foreground
1482 window, since that is the only thread that can set the
1483 foreground window. */
1484 DWORD foreground_thread, child_thread;
1485 foreground_thread =
1486 GetWindowThreadProcessId (foreground_window, NULL);
1487 if (foreground_thread == GetCurrentThreadId ()
1488 || !AttachThreadInput (GetCurrentThreadId (),
1489 foreground_thread, TRUE))
1490 foreground_thread = 0;
1492 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1493 if (child_thread == GetCurrentThreadId ()
1494 || !AttachThreadInput (GetCurrentThreadId (),
1495 child_thread, TRUE))
1496 child_thread = 0;
1498 /* Set the foreground window to the child. */
1499 if (SetForegroundWindow (cp->hwnd))
1501 /* Generate keystrokes as if user had typed Ctrl-Break or
1502 Ctrl-C. */
1503 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1504 keybd_event (vk_break_code, break_scan_code,
1505 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1506 keybd_event (vk_break_code, break_scan_code,
1507 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1508 | KEYEVENTF_KEYUP, 0);
1509 keybd_event (VK_CONTROL, control_scan_code,
1510 KEYEVENTF_KEYUP, 0);
1512 /* Sleep for a bit to give time for Emacs frame to respond
1513 to focus change events (if Emacs was active app). */
1514 Sleep (100);
1516 SetForegroundWindow (foreground_window);
1518 /* Detach from the foreground and child threads now that
1519 the foreground switching is over. */
1520 if (foreground_thread)
1521 AttachThreadInput (GetCurrentThreadId (),
1522 foreground_thread, FALSE);
1523 if (child_thread)
1524 AttachThreadInput (GetCurrentThreadId (),
1525 child_thread, FALSE);
1528 /* Ctrl-Break is NT equivalent of SIGINT. */
1529 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1531 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1532 "for pid %lu\n", GetLastError (), pid));
1533 errno = EINVAL;
1534 rc = -1;
1537 else
1539 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1541 #if 1
1542 if (os_subtype == OS_WIN95)
1545 Another possibility is to try terminating the VDM out-right by
1546 calling the Shell VxD (id 0x17) V86 interface, function #4
1547 "SHELL_Destroy_VM", ie.
1549 mov edx,4
1550 mov ebx,vm_handle
1551 call shellapi
1553 First need to determine the current VM handle, and then arrange for
1554 the shellapi call to be made from the system vm (by using
1555 Switch_VM_and_callback).
1557 Could try to invoke DestroyVM through CallVxD.
1560 #if 0
1561 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1562 to hang when cmdproxy is used in conjunction with
1563 command.com for an interactive shell. Posting
1564 WM_CLOSE pops up a dialog that, when Yes is selected,
1565 does the same thing. TerminateProcess is also less
1566 than ideal in that subprocesses tend to stick around
1567 until the machine is shutdown, but at least it
1568 doesn't freeze the 16-bit subsystem. */
1569 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1570 #endif
1571 if (!TerminateProcess (proc_hand, 0xff))
1573 DebPrint (("sys_kill.TerminateProcess returned %d "
1574 "for pid %lu\n", GetLastError (), pid));
1575 errno = EINVAL;
1576 rc = -1;
1579 else
1580 #endif
1581 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1583 /* Kill the process. On W32 this doesn't kill child processes
1584 so it doesn't work very well for shells which is why it's not
1585 used in every case. */
1586 else if (!TerminateProcess (proc_hand, 0xff))
1588 DebPrint (("sys_kill.TerminateProcess returned %d "
1589 "for pid %lu\n", GetLastError (), pid));
1590 errno = EINVAL;
1591 rc = -1;
1595 if (need_to_free)
1596 CloseHandle (proc_hand);
1598 return rc;
1601 /* extern int report_file_error (char *, Lisp_Object); */
1603 /* The following two routines are used to manipulate stdin, stdout, and
1604 stderr of our child processes.
1606 Assuming that in, out, and err are *not* inheritable, we make them
1607 stdin, stdout, and stderr of the child as follows:
1609 - Save the parent's current standard handles.
1610 - Set the std handles to inheritable duplicates of the ones being passed in.
1611 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1612 NT file handle for a crt file descriptor.)
1613 - Spawn the child, which inherits in, out, and err as stdin,
1614 stdout, and stderr. (see Spawnve)
1615 - Close the std handles passed to the child.
1616 - Reset the parent's standard handles to the saved handles.
1617 (see reset_standard_handles)
1618 We assume that the caller closes in, out, and err after calling us. */
1620 void
1621 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1623 HANDLE parent;
1624 HANDLE newstdin, newstdout, newstderr;
1626 parent = GetCurrentProcess ();
1628 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1629 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1630 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1632 /* make inheritable copies of the new handles */
1633 if (!DuplicateHandle (parent,
1634 (HANDLE) _get_osfhandle (in),
1635 parent,
1636 &newstdin,
1638 TRUE,
1639 DUPLICATE_SAME_ACCESS))
1640 report_file_error ("Duplicating input handle for child", Qnil);
1642 if (!DuplicateHandle (parent,
1643 (HANDLE) _get_osfhandle (out),
1644 parent,
1645 &newstdout,
1647 TRUE,
1648 DUPLICATE_SAME_ACCESS))
1649 report_file_error ("Duplicating output handle for child", Qnil);
1651 if (!DuplicateHandle (parent,
1652 (HANDLE) _get_osfhandle (err),
1653 parent,
1654 &newstderr,
1656 TRUE,
1657 DUPLICATE_SAME_ACCESS))
1658 report_file_error ("Duplicating error handle for child", Qnil);
1660 /* and store them as our std handles */
1661 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1662 report_file_error ("Changing stdin handle", Qnil);
1664 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1665 report_file_error ("Changing stdout handle", Qnil);
1667 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1668 report_file_error ("Changing stderr handle", Qnil);
1671 void
1672 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1674 /* close the duplicated handles passed to the child */
1675 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1676 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1677 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1679 /* now restore parent's saved std handles */
1680 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1681 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1682 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1685 void
1686 set_process_dir (char * dir)
1688 process_dir = dir;
1691 #ifdef HAVE_SOCKETS
1693 /* To avoid problems with winsock implementations that work over dial-up
1694 connections causing or requiring a connection to exist while Emacs is
1695 running, Emacs no longer automatically loads winsock on startup if it
1696 is present. Instead, it will be loaded when open-network-stream is
1697 first called.
1699 To allow full control over when winsock is loaded, we provide these
1700 two functions to dynamically load and unload winsock. This allows
1701 dial-up users to only be connected when they actually need to use
1702 socket services. */
1704 /* From nt.c */
1705 extern HANDLE winsock_lib;
1706 extern BOOL term_winsock (void);
1707 extern BOOL init_winsock (int load_now);
1709 extern Lisp_Object Vsystem_name;
1711 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1712 doc: /* Test for presence of the Windows socket library `winsock'.
1713 Returns non-nil if winsock support is present, nil otherwise.
1715 If the optional argument LOAD-NOW is non-nil, the winsock library is
1716 also loaded immediately if not already loaded. If winsock is loaded,
1717 the winsock local hostname is returned (since this may be different from
1718 the value of `system-name' and should supplant it), otherwise t is
1719 returned to indicate winsock support is present. */)
1720 (load_now)
1721 Lisp_Object load_now;
1723 int have_winsock;
1725 have_winsock = init_winsock (!NILP (load_now));
1726 if (have_winsock)
1728 if (winsock_lib != NULL)
1730 /* Return new value for system-name. The best way to do this
1731 is to call init_system_name, saving and restoring the
1732 original value to avoid side-effects. */
1733 Lisp_Object orig_hostname = Vsystem_name;
1734 Lisp_Object hostname;
1736 init_system_name ();
1737 hostname = Vsystem_name;
1738 Vsystem_name = orig_hostname;
1739 return hostname;
1741 return Qt;
1743 return Qnil;
1746 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1747 0, 0, 0,
1748 doc: /* Unload the Windows socket library `winsock' if loaded.
1749 This is provided to allow dial-up socket connections to be disconnected
1750 when no longer needed. Returns nil without unloading winsock if any
1751 socket connections still exist. */)
1754 return term_winsock () ? Qt : Qnil;
1757 #endif /* HAVE_SOCKETS */
1760 /* Some miscellaneous functions that are Windows specific, but not GUI
1761 specific (ie. are applicable in terminal or batch mode as well). */
1763 /* lifted from fileio.c */
1764 #define CORRECT_DIR_SEPS(s) \
1765 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1766 else unixtodos_filename (s); \
1767 } while (0)
1769 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1770 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1771 If FILENAME does not exist, return nil.
1772 All path elements in FILENAME are converted to their short names. */)
1773 (filename)
1774 Lisp_Object filename;
1776 char shortname[MAX_PATH];
1778 CHECK_STRING (filename);
1780 /* first expand it. */
1781 filename = Fexpand_file_name (filename, Qnil);
1783 /* luckily, this returns the short version of each element in the path. */
1784 if (GetShortPathName (SDATA (filename), shortname, MAX_PATH) == 0)
1785 return Qnil;
1787 CORRECT_DIR_SEPS (shortname);
1789 return build_string (shortname);
1793 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1794 1, 1, 0,
1795 doc: /* Return the long file name version of the full path of FILENAME.
1796 If FILENAME does not exist, return nil.
1797 All path elements in FILENAME are converted to their long names. */)
1798 (filename)
1799 Lisp_Object filename;
1801 char longname[ MAX_PATH ];
1803 CHECK_STRING (filename);
1805 /* first expand it. */
1806 filename = Fexpand_file_name (filename, Qnil);
1808 if (!w32_get_long_filename (SDATA (filename), longname, MAX_PATH))
1809 return Qnil;
1811 CORRECT_DIR_SEPS (longname);
1813 return build_string (longname);
1816 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1817 Sw32_set_process_priority, 2, 2, 0,
1818 doc: /* Set the priority of PROCESS to PRIORITY.
1819 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1820 priority of the process whose pid is PROCESS is changed.
1821 PRIORITY should be one of the symbols high, normal, or low;
1822 any other symbol will be interpreted as normal.
1824 If successful, the return value is t, otherwise nil. */)
1825 (process, priority)
1826 Lisp_Object process, priority;
1828 HANDLE proc_handle = GetCurrentProcess ();
1829 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1830 Lisp_Object result = Qnil;
1832 CHECK_SYMBOL (priority);
1834 if (!NILP (process))
1836 DWORD pid;
1837 child_process *cp;
1839 CHECK_NUMBER (process);
1841 /* Allow pid to be an internally generated one, or one obtained
1842 externally. This is necessary because real pids on Win95 are
1843 negative. */
1845 pid = XINT (process);
1846 cp = find_child_pid (pid);
1847 if (cp != NULL)
1848 pid = cp->procinfo.dwProcessId;
1850 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1853 if (EQ (priority, Qhigh))
1854 priority_class = HIGH_PRIORITY_CLASS;
1855 else if (EQ (priority, Qlow))
1856 priority_class = IDLE_PRIORITY_CLASS;
1858 if (proc_handle != NULL)
1860 if (SetPriorityClass (proc_handle, priority_class))
1861 result = Qt;
1862 if (!NILP (process))
1863 CloseHandle (proc_handle);
1866 return result;
1869 #ifdef HAVE_LANGINFO_CODESET
1870 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1871 char *nl_langinfo (nl_item item)
1873 /* Conversion of Posix item numbers to their Windows equivalents. */
1874 static const LCTYPE w32item[] = {
1875 LOCALE_IDEFAULTANSICODEPAGE,
1876 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1877 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1878 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1879 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1880 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1881 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1884 static char *nl_langinfo_buf = NULL;
1885 static int nl_langinfo_len = 0;
1887 if (nl_langinfo_len <= 0)
1888 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1890 if (item < 0 || item >= _NL_NUM)
1891 nl_langinfo_buf[0] = 0;
1892 else
1894 LCID cloc = GetThreadLocale ();
1895 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1896 NULL, 0);
1898 if (need_len <= 0)
1899 nl_langinfo_buf[0] = 0;
1900 else
1902 if (item == CODESET)
1904 need_len += 2; /* for the "cp" prefix */
1905 if (need_len < 8) /* for the case we call GetACP */
1906 need_len = 8;
1908 if (nl_langinfo_len <= need_len)
1909 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1910 nl_langinfo_len = need_len);
1911 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1912 nl_langinfo_buf, nl_langinfo_len))
1913 nl_langinfo_buf[0] = 0;
1914 else if (item == CODESET)
1916 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1917 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1918 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1919 else
1921 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1922 strlen (nl_langinfo_buf) + 1);
1923 nl_langinfo_buf[0] = 'c';
1924 nl_langinfo_buf[1] = 'p';
1929 return nl_langinfo_buf;
1931 #endif /* HAVE_LANGINFO_CODESET */
1933 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1934 Sw32_get_locale_info, 1, 2, 0,
1935 doc: /* Return information about the Windows locale LCID.
1936 By default, return a three letter locale code which encodes the default
1937 language as the first two characters, and the country or regionial variant
1938 as the third letter. For example, ENU refers to `English (United States)',
1939 while ENC means `English (Canadian)'.
1941 If the optional argument LONGFORM is t, the long form of the locale
1942 name is returned, e.g. `English (United States)' instead; if LONGFORM
1943 is a number, it is interpreted as an LCTYPE constant and the corresponding
1944 locale information is returned.
1946 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1947 (lcid, longform)
1948 Lisp_Object lcid, longform;
1950 int got_abbrev;
1951 int got_full;
1952 char abbrev_name[32] = { 0 };
1953 char full_name[256] = { 0 };
1955 CHECK_NUMBER (lcid);
1957 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1958 return Qnil;
1960 if (NILP (longform))
1962 got_abbrev = GetLocaleInfo (XINT (lcid),
1963 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1964 abbrev_name, sizeof (abbrev_name));
1965 if (got_abbrev)
1966 return build_string (abbrev_name);
1968 else if (EQ (longform, Qt))
1970 got_full = GetLocaleInfo (XINT (lcid),
1971 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1972 full_name, sizeof (full_name));
1973 if (got_full)
1974 return build_string (full_name);
1976 else if (NUMBERP (longform))
1978 got_full = GetLocaleInfo (XINT (lcid),
1979 XINT (longform),
1980 full_name, sizeof (full_name));
1981 if (got_full)
1982 return make_unibyte_string (full_name, got_full);
1985 return Qnil;
1989 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1990 Sw32_get_current_locale_id, 0, 0, 0,
1991 doc: /* Return Windows locale id for current locale setting.
1992 This is a numerical value; use `w32-get-locale-info' to convert to a
1993 human-readable form. */)
1996 return make_number (GetThreadLocale ());
1999 DWORD int_from_hex (char * s)
2001 DWORD val = 0;
2002 static char hex[] = "0123456789abcdefABCDEF";
2003 char * p;
2005 while (*s && (p = strchr(hex, *s)) != NULL)
2007 unsigned digit = p - hex;
2008 if (digit > 15)
2009 digit -= 6;
2010 val = val * 16 + digit;
2011 s++;
2013 return val;
2016 /* We need to build a global list, since the EnumSystemLocale callback
2017 function isn't given a context pointer. */
2018 Lisp_Object Vw32_valid_locale_ids;
2020 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
2022 DWORD id = int_from_hex (localeNum);
2023 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
2024 return TRUE;
2027 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2028 Sw32_get_valid_locale_ids, 0, 0, 0,
2029 doc: /* Return list of all valid Windows locale ids.
2030 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2031 human-readable form. */)
2034 Vw32_valid_locale_ids = Qnil;
2036 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2038 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2039 return Vw32_valid_locale_ids;
2043 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2044 doc: /* Return Windows locale id for default locale setting.
2045 By default, the system default locale setting is returned; if the optional
2046 parameter USERP is non-nil, the user default locale setting is returned.
2047 This is a numerical value; use `w32-get-locale-info' to convert to a
2048 human-readable form. */)
2049 (userp)
2050 Lisp_Object userp;
2052 if (NILP (userp))
2053 return make_number (GetSystemDefaultLCID ());
2054 return make_number (GetUserDefaultLCID ());
2058 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2059 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2060 If successful, the new locale id is returned, otherwise nil. */)
2061 (lcid)
2062 Lisp_Object lcid;
2064 CHECK_NUMBER (lcid);
2066 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2067 return Qnil;
2069 if (!SetThreadLocale (XINT (lcid)))
2070 return Qnil;
2072 /* Need to set input thread locale if present. */
2073 if (dwWindowsThreadId)
2074 /* Reply is not needed. */
2075 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2077 return make_number (GetThreadLocale ());
2081 /* We need to build a global list, since the EnumCodePages callback
2082 function isn't given a context pointer. */
2083 Lisp_Object Vw32_valid_codepages;
2085 BOOL CALLBACK enum_codepage_fn (LPTSTR codepageNum)
2087 DWORD id = atoi (codepageNum);
2088 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2089 return TRUE;
2092 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2093 Sw32_get_valid_codepages, 0, 0, 0,
2094 doc: /* Return list of all valid Windows codepages. */)
2097 Vw32_valid_codepages = Qnil;
2099 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2101 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2102 return Vw32_valid_codepages;
2106 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2107 Sw32_get_console_codepage, 0, 0, 0,
2108 doc: /* Return current Windows codepage for console input. */)
2111 return make_number (GetConsoleCP ());
2115 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2116 Sw32_set_console_codepage, 1, 1, 0,
2117 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2118 The codepage setting affects keyboard input and display in tty mode.
2119 If successful, the new CP is returned, otherwise nil. */)
2120 (cp)
2121 Lisp_Object cp;
2123 CHECK_NUMBER (cp);
2125 if (!IsValidCodePage (XINT (cp)))
2126 return Qnil;
2128 if (!SetConsoleCP (XINT (cp)))
2129 return Qnil;
2131 return make_number (GetConsoleCP ());
2135 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2136 Sw32_get_console_output_codepage, 0, 0, 0,
2137 doc: /* Return current Windows codepage for console output. */)
2140 return make_number (GetConsoleOutputCP ());
2144 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2145 Sw32_set_console_output_codepage, 1, 1, 0,
2146 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2147 The codepage setting affects keyboard input and display in tty mode.
2148 If successful, the new CP is returned, otherwise nil. */)
2149 (cp)
2150 Lisp_Object cp;
2152 CHECK_NUMBER (cp);
2154 if (!IsValidCodePage (XINT (cp)))
2155 return Qnil;
2157 if (!SetConsoleOutputCP (XINT (cp)))
2158 return Qnil;
2160 return make_number (GetConsoleOutputCP ());
2164 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2165 Sw32_get_codepage_charset, 1, 1, 0,
2166 doc: /* Return charset of codepage CP.
2167 Returns nil if the codepage is not valid. */)
2168 (cp)
2169 Lisp_Object cp;
2171 CHARSETINFO info;
2173 CHECK_NUMBER (cp);
2175 if (!IsValidCodePage (XINT (cp)))
2176 return Qnil;
2178 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2179 return make_number (info.ciCharset);
2181 return Qnil;
2185 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2186 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2187 doc: /* Return list of Windows keyboard languages and layouts.
2188 The return value is a list of pairs of language id and layout id. */)
2191 int num_layouts = GetKeyboardLayoutList (0, NULL);
2192 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2193 Lisp_Object obj = Qnil;
2195 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2197 while (--num_layouts >= 0)
2199 DWORD kl = (DWORD) layouts[num_layouts];
2201 obj = Fcons (Fcons (make_number (kl & 0xffff),
2202 make_number ((kl >> 16) & 0xffff)),
2203 obj);
2207 return obj;
2211 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2212 Sw32_get_keyboard_layout, 0, 0, 0,
2213 doc: /* Return current Windows keyboard language and layout.
2214 The return value is the cons of the language id and the layout id. */)
2217 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2219 return Fcons (make_number (kl & 0xffff),
2220 make_number ((kl >> 16) & 0xffff));
2224 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2225 Sw32_set_keyboard_layout, 1, 1, 0,
2226 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2227 The keyboard layout setting affects interpretation of keyboard input.
2228 If successful, the new layout id is returned, otherwise nil. */)
2229 (layout)
2230 Lisp_Object layout;
2232 DWORD kl;
2234 CHECK_CONS (layout);
2235 CHECK_NUMBER_CAR (layout);
2236 CHECK_NUMBER_CDR (layout);
2238 kl = (XINT (XCAR (layout)) & 0xffff)
2239 | (XINT (XCDR (layout)) << 16);
2241 /* Synchronize layout with input thread. */
2242 if (dwWindowsThreadId)
2244 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2245 (WPARAM) kl, 0))
2247 MSG msg;
2248 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2250 if (msg.wParam == 0)
2251 return Qnil;
2254 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2255 return Qnil;
2257 return Fw32_get_keyboard_layout ();
2261 syms_of_ntproc ()
2263 DEFSYM (Qhigh, "high");
2264 DEFSYM (Qlow, "low");
2266 #ifdef HAVE_SOCKETS
2267 defsubr (&Sw32_has_winsock);
2268 defsubr (&Sw32_unload_winsock);
2269 #endif
2270 defsubr (&Sw32_short_file_name);
2271 defsubr (&Sw32_long_file_name);
2272 defsubr (&Sw32_set_process_priority);
2273 defsubr (&Sw32_get_locale_info);
2274 defsubr (&Sw32_get_current_locale_id);
2275 defsubr (&Sw32_get_default_locale_id);
2276 defsubr (&Sw32_get_valid_locale_ids);
2277 defsubr (&Sw32_set_current_locale);
2279 defsubr (&Sw32_get_console_codepage);
2280 defsubr (&Sw32_set_console_codepage);
2281 defsubr (&Sw32_get_console_output_codepage);
2282 defsubr (&Sw32_set_console_output_codepage);
2283 defsubr (&Sw32_get_valid_codepages);
2284 defsubr (&Sw32_get_codepage_charset);
2286 defsubr (&Sw32_get_valid_keyboard_layouts);
2287 defsubr (&Sw32_get_keyboard_layout);
2288 defsubr (&Sw32_set_keyboard_layout);
2290 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args,
2291 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2292 Because Windows does not directly pass argv arrays to child processes,
2293 programs have to reconstruct the argv array by parsing the command
2294 line string. For an argument to contain a space, it must be enclosed
2295 in double quotes or it will be parsed as multiple arguments.
2297 If the value is a character, that character will be used to escape any
2298 quote characters that appear, otherwise a suitable escape character
2299 will be chosen based on the type of the program. */);
2300 Vw32_quote_process_args = Qt;
2302 DEFVAR_LISP ("w32-start-process-show-window",
2303 &Vw32_start_process_show_window,
2304 doc: /* When nil, new child processes hide their windows.
2305 When non-nil, they show their window in the method of their choice.
2306 This variable doesn't affect GUI applications, which will never be hidden. */);
2307 Vw32_start_process_show_window = Qnil;
2309 DEFVAR_LISP ("w32-start-process-share-console",
2310 &Vw32_start_process_share_console,
2311 doc: /* When nil, new child processes are given a new console.
2312 When non-nil, they share the Emacs console; this has the limitation of
2313 allowing only one DOS subprocess to run at a time (whether started directly
2314 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2315 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2316 otherwise respond to interrupts from Emacs. */);
2317 Vw32_start_process_share_console = Qnil;
2319 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2320 &Vw32_start_process_inherit_error_mode,
2321 doc: /* When nil, new child processes revert to the default error mode.
2322 When non-nil, they inherit their error mode setting from Emacs, which stops
2323 them blocking when trying to access unmounted drives etc. */);
2324 Vw32_start_process_inherit_error_mode = Qt;
2326 DEFVAR_INT ("w32-pipe-read-delay", &w32_pipe_read_delay,
2327 doc: /* Forced delay before reading subprocess output.
2328 This is done to improve the buffering of subprocess output, by
2329 avoiding the inefficiency of frequently reading small amounts of data.
2331 If positive, the value is the number of milliseconds to sleep before
2332 reading the subprocess output. If negative, the magnitude is the number
2333 of time slices to wait (effectively boosting the priority of the child
2334 process temporarily). A value of zero disables waiting entirely. */);
2335 w32_pipe_read_delay = 50;
2337 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names,
2338 doc: /* Non-nil means convert all-upper case file names to lower case.
2339 This applies when performing completions and file name expansion.
2340 Note that the value of this setting also affects remote file names,
2341 so you probably don't want to set to non-nil if you use case-sensitive
2342 filesystems via ange-ftp. */);
2343 Vw32_downcase_file_names = Qnil;
2345 #if 0
2346 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes,
2347 doc: /* Non-nil means attempt to fake realistic inode values.
2348 This works by hashing the truename of files, and should detect
2349 aliasing between long and short (8.3 DOS) names, but can have
2350 false positives because of hash collisions. Note that determing
2351 the truename of a file can be slow. */);
2352 Vw32_generate_fake_inodes = Qnil;
2353 #endif
2355 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes,
2356 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2357 This option controls whether to issue additional system calls to determine
2358 accurate link counts, file type, and ownership information. It is only
2359 useful for files on NTFS volumes, where hard links and file security are
2360 supported.
2362 Without these system calls, link count will always be reported as 1 and file
2363 ownership will be attributed to the current user.
2364 The default value `local' means only issue these system calls for files
2365 on local fixed drives. A value of nil means never issue them.
2366 Any other non-nil value means do this even on remote and removable drives
2367 where the performance impact may be noticeable even on modern hardware. */);
2368 Vw32_get_true_file_attributes = Qlocal;
2370 staticpro (&Vw32_valid_locale_ids);
2371 staticpro (&Vw32_valid_codepages);
2373 /* end of ntproc.c */
2375 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2376 (do not change this comment) */