(Fclrhash): Return TABLE.
[emacs.git] / src / w32proc.c
blobf050cacf82d34a4387c80878262db1b2474b3f73
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 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, or (at your option)
10 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; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.
22 Drew Bliss Oct 14, 1993
23 Adapted from alarm.c by Tim Fleehart
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <io.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <sys/file.h>
34 /* must include CRT headers *before* config.h */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
40 #undef signal
41 #undef wait
42 #undef spawnve
43 #undef select
44 #undef kill
46 #include <windows.h>
47 #ifdef __GNUC__
48 /* This definition is missing from mingw32 headers. */
49 extern BOOL WINAPI IsValidLocale(LCID, DWORD);
50 #endif
52 #ifdef HAVE_LANGINFO_CODESET
53 #include <nl_types.h>
54 #include <langinfo.h>
55 #endif
57 #include "lisp.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"
66 #define RVA_TO_PTR(var,section,filedata) \
67 ((void *)((section)->PointerToRawData \
68 + ((DWORD)(var) - (section)->VirtualAddress) \
69 + (filedata).file_base))
71 /* Control whether spawnve quotes arguments as necessary to ensure
72 correct parsing by child process. Because not all uses of spawnve
73 are careful about constructing argv arrays, we make this behaviour
74 conditional (off by default). */
75 Lisp_Object Vw32_quote_process_args;
77 /* Control whether create_child causes the process' window to be
78 hidden. The default is nil. */
79 Lisp_Object Vw32_start_process_show_window;
81 /* Control whether create_child causes the process to inherit Emacs'
82 console window, or be given a new one of its own. The default is
83 nil, to allow multiple DOS programs to run on Win95. Having separate
84 consoles also allows Emacs to cleanly terminate process groups. */
85 Lisp_Object Vw32_start_process_share_console;
87 /* Control whether create_child cause the process to inherit Emacs'
88 error mode setting. The default is t, to minimize the possibility of
89 subprocesses blocking when accessing unmounted drives. */
90 Lisp_Object Vw32_start_process_inherit_error_mode;
92 /* Time to sleep before reading from a subprocess output pipe - this
93 avoids the inefficiency of frequently reading small amounts of data.
94 This is primarily necessary for handling DOS processes on Windows 95,
95 but is useful for W32 processes on both Windows 95 and NT as well. */
96 int w32_pipe_read_delay;
98 /* Control conversion of upper case file names to lower case.
99 nil means no, t means yes. */
100 Lisp_Object Vw32_downcase_file_names;
102 /* Control whether stat() attempts to generate fake but hopefully
103 "accurate" inode values, by hashing the absolute truenames of files.
104 This should detect aliasing between long and short names, but still
105 allows the possibility of hash collisions. */
106 Lisp_Object Vw32_generate_fake_inodes;
108 /* Control whether stat() attempts to determine file type and link count
109 exactly, at the expense of slower operation. Since true hard links
110 are supported on NTFS volumes, this is only relevant on NT. */
111 Lisp_Object Vw32_get_true_file_attributes;
113 Lisp_Object Qhigh, Qlow;
115 #ifdef EMACSDEBUG
116 void _DebPrint (const char *fmt, ...)
118 char buf[1024];
119 va_list args;
121 va_start (args, fmt);
122 vsprintf (buf, fmt, args);
123 va_end (args);
124 OutputDebugString (buf);
126 #endif
128 typedef void (_CALLBACK_ *signal_handler)(int);
130 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
131 static signal_handler sig_handlers[NSIG];
133 /* Fake signal implementation to record the SIGCHLD handler. */
134 signal_handler
135 sys_signal (int sig, signal_handler handler)
137 signal_handler old;
139 if (sig != SIGCHLD)
141 errno = EINVAL;
142 return SIG_ERR;
144 old = sig_handlers[sig];
145 sig_handlers[sig] = handler;
146 return old;
149 /* Defined in <process.h> which conflicts with the local copy */
150 #define _P_NOWAIT 1
152 /* Child process management list. */
153 int child_proc_count = 0;
154 child_process child_procs[ MAX_CHILDREN ];
155 child_process *dead_child = NULL;
157 DWORD WINAPI reader_thread (void *arg);
159 /* Find an unused process slot. */
160 child_process *
161 new_child (void)
163 child_process *cp;
164 DWORD id;
166 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
167 if (!CHILD_ACTIVE (cp))
168 goto Initialise;
169 if (child_proc_count == MAX_CHILDREN)
170 return NULL;
171 cp = &child_procs[child_proc_count++];
173 Initialise:
174 memset (cp, 0, sizeof(*cp));
175 cp->fd = -1;
176 cp->pid = -1;
177 cp->procinfo.hProcess = NULL;
178 cp->status = STATUS_READ_ERROR;
180 /* use manual reset event so that select() will function properly */
181 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
182 if (cp->char_avail)
184 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
185 if (cp->char_consumed)
187 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
188 if (cp->thrd)
189 return cp;
192 delete_child (cp);
193 return NULL;
196 void
197 delete_child (child_process *cp)
199 int i;
201 /* Should not be deleting a child that is still needed. */
202 for (i = 0; i < MAXDESC; i++)
203 if (fd_info[i].cp == cp)
204 abort ();
206 if (!CHILD_ACTIVE (cp))
207 return;
209 /* reap thread if necessary */
210 if (cp->thrd)
212 DWORD rc;
214 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
216 /* let the thread exit cleanly if possible */
217 cp->status = STATUS_READ_ERROR;
218 SetEvent (cp->char_consumed);
219 #if 0
220 /* We used to forceably terminate the thread here, but it
221 is normally unnecessary, and in abnormal cases, the worst that
222 will happen is we have an extra idle thread hanging around
223 waiting for the zombie process. */
224 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
226 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
227 "with %lu for fd %ld\n", GetLastError (), cp->fd));
228 TerminateThread (cp->thrd, 0);
230 #endif
232 CloseHandle (cp->thrd);
233 cp->thrd = NULL;
235 if (cp->char_avail)
237 CloseHandle (cp->char_avail);
238 cp->char_avail = NULL;
240 if (cp->char_consumed)
242 CloseHandle (cp->char_consumed);
243 cp->char_consumed = NULL;
246 /* update child_proc_count (highest numbered slot in use plus one) */
247 if (cp == child_procs + child_proc_count - 1)
249 for (i = child_proc_count-1; i >= 0; i--)
250 if (CHILD_ACTIVE (&child_procs[i]))
252 child_proc_count = i + 1;
253 break;
256 if (i < 0)
257 child_proc_count = 0;
260 /* Find a child by pid. */
261 static child_process *
262 find_child_pid (DWORD pid)
264 child_process *cp;
266 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
267 if (CHILD_ACTIVE (cp) && pid == cp->pid)
268 return cp;
269 return NULL;
273 /* Thread proc for child process and socket reader threads. Each thread
274 is normally blocked until woken by select() to check for input by
275 reading one char. When the read completes, char_avail is signalled
276 to wake up the select emulator and the thread blocks itself again. */
277 DWORD WINAPI
278 reader_thread (void *arg)
280 child_process *cp;
282 /* Our identity */
283 cp = (child_process *)arg;
285 /* We have to wait for the go-ahead before we can start */
286 if (cp == NULL
287 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
288 return 1;
290 for (;;)
292 int rc;
294 if (fd_info[cp->fd].flags & FILE_LISTEN)
295 rc = _sys_wait_accept (cp->fd);
296 else
297 rc = _sys_read_ahead (cp->fd);
299 /* The name char_avail is a misnomer - it really just means the
300 read-ahead has completed, whether successfully or not. */
301 if (!SetEvent (cp->char_avail))
303 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
304 GetLastError (), cp->fd));
305 return 1;
308 if (rc == STATUS_READ_ERROR)
309 return 1;
311 /* If the read died, the child has died so let the thread die */
312 if (rc == STATUS_READ_FAILED)
313 break;
315 /* Wait until our input is acknowledged before reading again */
316 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
318 DebPrint (("reader_thread.WaitForSingleObject failed with "
319 "%lu for fd %ld\n", GetLastError (), cp->fd));
320 break;
323 return 0;
326 /* To avoid Emacs changing directory, we just record here the directory
327 the new process should start in. This is set just before calling
328 sys_spawnve, and is not generally valid at any other time. */
329 static char * process_dir;
331 static BOOL
332 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
333 int * pPid, child_process *cp)
335 STARTUPINFO start;
336 SECURITY_ATTRIBUTES sec_attrs;
337 #if 0
338 SECURITY_DESCRIPTOR sec_desc;
339 #endif
340 DWORD flags;
341 char dir[ MAXPATHLEN ];
343 if (cp == NULL) abort ();
345 memset (&start, 0, sizeof (start));
346 start.cb = sizeof (start);
348 #ifdef HAVE_NTGUI
349 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
350 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
351 else
352 start.dwFlags = STARTF_USESTDHANDLES;
353 start.wShowWindow = SW_HIDE;
355 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
356 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
357 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
358 #endif /* HAVE_NTGUI */
360 #if 0
361 /* Explicitly specify no security */
362 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
363 goto EH_Fail;
364 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
365 goto EH_Fail;
366 #endif
367 sec_attrs.nLength = sizeof (sec_attrs);
368 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
369 sec_attrs.bInheritHandle = FALSE;
371 strcpy (dir, process_dir);
372 unixtodos_filename (dir);
374 flags = (!NILP (Vw32_start_process_share_console)
375 ? CREATE_NEW_PROCESS_GROUP
376 : CREATE_NEW_CONSOLE);
377 if (NILP (Vw32_start_process_inherit_error_mode))
378 flags |= CREATE_DEFAULT_ERROR_MODE;
379 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
380 flags, env, dir, &start, &cp->procinfo))
381 goto EH_Fail;
383 cp->pid = (int) cp->procinfo.dwProcessId;
385 /* Hack for Windows 95, which assigns large (ie negative) pids */
386 if (cp->pid < 0)
387 cp->pid = -cp->pid;
389 /* pid must fit in a Lisp_Int */
390 cp->pid = cp->pid & INTMASK;
392 *pPid = cp->pid;
394 return TRUE;
396 EH_Fail:
397 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
398 return FALSE;
401 /* create_child doesn't know what emacs' file handle will be for waiting
402 on output from the child, so we need to make this additional call
403 to register the handle with the process
404 This way the select emulator knows how to match file handles with
405 entries in child_procs. */
406 void
407 register_child (int pid, int fd)
409 child_process *cp;
411 cp = find_child_pid (pid);
412 if (cp == NULL)
414 DebPrint (("register_child unable to find pid %lu\n", pid));
415 return;
418 #ifdef FULL_DEBUG
419 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
420 #endif
422 cp->fd = fd;
424 /* thread is initially blocked until select is called; set status so
425 that select will release thread */
426 cp->status = STATUS_READ_ACKNOWLEDGED;
428 /* attach child_process to fd_info */
429 if (fd_info[fd].cp != NULL)
431 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
432 abort ();
435 fd_info[fd].cp = cp;
438 /* When a process dies its pipe will break so the reader thread will
439 signal failure to the select emulator.
440 The select emulator then calls this routine to clean up.
441 Since the thread signaled failure we can assume it is exiting. */
442 static void
443 reap_subprocess (child_process *cp)
445 if (cp->procinfo.hProcess)
447 /* Reap the process */
448 #ifdef FULL_DEBUG
449 /* Process should have already died before we are called. */
450 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
451 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
452 #endif
453 CloseHandle (cp->procinfo.hProcess);
454 cp->procinfo.hProcess = NULL;
455 CloseHandle (cp->procinfo.hThread);
456 cp->procinfo.hThread = NULL;
459 /* For asynchronous children, the child_proc resources will be freed
460 when the last pipe read descriptor is closed; for synchronous
461 children, we must explicitly free the resources now because
462 register_child has not been called. */
463 if (cp->fd == -1)
464 delete_child (cp);
467 /* Wait for any of our existing child processes to die
468 When it does, close its handle
469 Return the pid and fill in the status if non-NULL. */
472 sys_wait (int *status)
474 DWORD active, retval;
475 int nh;
476 int pid;
477 child_process *cp, *cps[MAX_CHILDREN];
478 HANDLE wait_hnd[MAX_CHILDREN];
480 nh = 0;
481 if (dead_child != NULL)
483 /* We want to wait for a specific child */
484 wait_hnd[nh] = dead_child->procinfo.hProcess;
485 cps[nh] = dead_child;
486 if (!wait_hnd[nh]) abort ();
487 nh++;
488 active = 0;
489 goto get_result;
491 else
493 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
494 /* some child_procs might be sockets; ignore them */
495 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
496 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
498 wait_hnd[nh] = cp->procinfo.hProcess;
499 cps[nh] = cp;
500 nh++;
504 if (nh == 0)
506 /* Nothing to wait on, so fail */
507 errno = ECHILD;
508 return -1;
513 /* Check for quit about once a second. */
514 QUIT;
515 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
516 } while (active == WAIT_TIMEOUT);
518 if (active == WAIT_FAILED)
520 errno = EBADF;
521 return -1;
523 else if (active >= WAIT_OBJECT_0
524 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
526 active -= WAIT_OBJECT_0;
528 else if (active >= WAIT_ABANDONED_0
529 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
531 active -= WAIT_ABANDONED_0;
533 else
534 abort ();
536 get_result:
537 if (!GetExitCodeProcess (wait_hnd[active], &retval))
539 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
540 GetLastError ()));
541 retval = 1;
543 if (retval == STILL_ACTIVE)
545 /* Should never happen */
546 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
547 errno = EINVAL;
548 return -1;
551 /* Massage the exit code from the process to match the format expected
552 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
553 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
555 if (retval == STATUS_CONTROL_C_EXIT)
556 retval = SIGINT;
557 else
558 retval <<= 8;
560 cp = cps[active];
561 pid = cp->pid;
562 #ifdef FULL_DEBUG
563 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
564 #endif
566 if (status)
568 *status = retval;
570 else if (synch_process_alive)
572 synch_process_alive = 0;
574 /* Report the status of the synchronous process. */
575 if (WIFEXITED (retval))
576 synch_process_retcode = WRETCODE (retval);
577 else if (WIFSIGNALED (retval))
579 int code = WTERMSIG (retval);
580 char *signame;
582 synchronize_system_messages_locale ();
583 signame = strsignal (code);
585 if (signame == 0)
586 signame = "unknown";
588 synch_process_death = signame;
591 reap_subprocess (cp);
594 reap_subprocess (cp);
596 return pid;
599 /* Old versions of w32api headers don't have separate 32-bit and
600 64-bit defines, but the one they have matches the 32-bit variety. */
601 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
602 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
603 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
604 #endif
606 void
607 w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app, int * is_gui_app)
609 file_data executable;
610 char * p;
612 /* Default values in case we can't tell for sure. */
613 *is_dos_app = FALSE;
614 *is_cygnus_app = FALSE;
615 *is_gui_app = FALSE;
617 if (!open_input_file (&executable, filename))
618 return;
620 p = strrchr (filename, '.');
622 /* We can only identify DOS .com programs from the extension. */
623 if (p && stricmp (p, ".com") == 0)
624 *is_dos_app = TRUE;
625 else if (p && (stricmp (p, ".bat") == 0
626 || stricmp (p, ".cmd") == 0))
628 /* A DOS shell script - it appears that CreateProcess is happy to
629 accept this (somewhat surprisingly); presumably it looks at
630 COMSPEC to determine what executable to actually invoke.
631 Therefore, we have to do the same here as well. */
632 /* Actually, I think it uses the program association for that
633 extension, which is defined in the registry. */
634 p = egetenv ("COMSPEC");
635 if (p)
636 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
638 else
640 /* Look for DOS .exe signature - if found, we must also check that
641 it isn't really a 16- or 32-bit Windows exe, since both formats
642 start with a DOS program stub. Note that 16-bit Windows
643 executables use the OS/2 1.x format. */
645 IMAGE_DOS_HEADER * dos_header;
646 IMAGE_NT_HEADERS * nt_header;
648 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
649 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
650 goto unwind;
652 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
654 if ((char *) nt_header > (char *) dos_header + executable.size)
656 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
657 *is_dos_app = TRUE;
659 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
660 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
662 *is_dos_app = TRUE;
664 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
666 IMAGE_DATA_DIRECTORY *data_dir = NULL;
667 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
669 /* Ensure we are using the 32 bit structure. */
670 IMAGE_OPTIONAL_HEADER32 *opt
671 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
672 data_dir = opt->DataDirectory;
673 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
675 /* MingW 3.12 has the required 64 bit structs, but in case older
676 versions don't, only check 64 bit exes if we know how. */
677 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
678 else if (nt_header->OptionalHeader.Magic
679 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
681 IMAGE_OPTIONAL_HEADER64 *opt
682 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
683 data_dir = opt->DataDirectory;
684 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
686 #endif
687 if (data_dir)
689 /* Look for cygwin.dll in DLL import list. */
690 IMAGE_DATA_DIRECTORY import_dir =
691 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
692 IMAGE_IMPORT_DESCRIPTOR * imports;
693 IMAGE_SECTION_HEADER * section;
695 section = rva_to_section (import_dir.VirtualAddress, nt_header);
696 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
697 executable);
699 for ( ; imports->Name; imports++)
701 char * dllname = RVA_TO_PTR (imports->Name, section,
702 executable);
704 /* The exact name of the cygwin dll has changed with
705 various releases, but hopefully this will be reasonably
706 future proof. */
707 if (strncmp (dllname, "cygwin", 6) == 0)
709 *is_cygnus_app = TRUE;
710 break;
717 unwind:
718 close_file_data (&executable);
722 compare_env (const void *strp1, const void *strp2)
724 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
726 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
728 /* Sort order in command.com/cmd.exe is based on uppercasing
729 names, so do the same here. */
730 if (toupper (*str1) > toupper (*str2))
731 return 1;
732 else if (toupper (*str1) < toupper (*str2))
733 return -1;
734 str1++, str2++;
737 if (*str1 == '=' && *str2 == '=')
738 return 0;
739 else if (*str1 == '=')
740 return -1;
741 else
742 return 1;
745 void
746 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
748 char **optr, **nptr;
749 int num;
751 nptr = new_envp;
752 optr = envp1;
753 while (*optr)
754 *nptr++ = *optr++;
755 num = optr - envp1;
757 optr = envp2;
758 while (*optr)
759 *nptr++ = *optr++;
760 num += optr - envp2;
762 qsort (new_envp, num, sizeof (char *), compare_env);
764 *nptr = NULL;
767 /* When a new child process is created we need to register it in our list,
768 so intercept spawn requests. */
770 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
772 Lisp_Object program, full;
773 char *cmdline, *env, *parg, **targ;
774 int arglen, numenv;
775 int pid;
776 child_process *cp;
777 int is_dos_app, is_cygnus_app, is_gui_app;
778 int do_quoting = 0;
779 char escape_char;
780 /* We pass our process ID to our children by setting up an environment
781 variable in their environment. */
782 char ppid_env_var_buffer[64];
783 char *extra_env[] = {ppid_env_var_buffer, NULL};
784 /* These are the characters that cause an argument to need quoting.
785 Arguments with whitespace characters need quoting to prevent the
786 argument being split into two or more. Arguments with wildcards
787 are also quoted, for consistency with posix platforms, where wildcards
788 are not expanded if we run the program directly without a shell.
789 Some extra whitespace characters need quoting in Cygwin programs,
790 so this list is conditionally modified below. */
791 char *sepchars = " \t*?";
793 /* We don't care about the other modes */
794 if (mode != _P_NOWAIT)
796 errno = EINVAL;
797 return -1;
800 /* Handle executable names without an executable suffix. */
801 program = make_string (cmdname, strlen (cmdname));
802 if (NILP (Ffile_executable_p (program)))
804 struct gcpro gcpro1;
806 full = Qnil;
807 GCPRO1 (program);
808 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
809 UNGCPRO;
810 if (NILP (full))
812 errno = EINVAL;
813 return -1;
815 program = full;
818 /* make sure argv[0] and cmdname are both in DOS format */
819 cmdname = SDATA (program);
820 unixtodos_filename (cmdname);
821 argv[0] = cmdname;
823 /* Determine whether program is a 16-bit DOS executable, or a w32
824 executable that is implicitly linked to the Cygnus dll (implying it
825 was compiled with the Cygnus GNU toolchain and hence relies on
826 cygwin.dll to parse the command line - we use this to decide how to
827 escape quote chars in command line args that must be quoted).
829 Also determine whether it is a GUI app, so that we don't hide its
830 initial window unless specifically requested. */
831 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
833 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
834 application to start it by specifying the helper app as cmdname,
835 while leaving the real app name as argv[0]. */
836 if (is_dos_app)
838 cmdname = alloca (MAXPATHLEN);
839 if (egetenv ("CMDPROXY"))
840 strcpy (cmdname, egetenv ("CMDPROXY"));
841 else
843 strcpy (cmdname, SDATA (Vinvocation_directory));
844 strcat (cmdname, "cmdproxy.exe");
846 unixtodos_filename (cmdname);
849 /* we have to do some conjuring here to put argv and envp into the
850 form CreateProcess wants... argv needs to be a space separated/null
851 terminated list of parameters, and envp is a null
852 separated/double-null terminated list of parameters.
854 Additionally, zero-length args and args containing whitespace or
855 quote chars need to be wrapped in double quotes - for this to work,
856 embedded quotes need to be escaped as well. The aim is to ensure
857 the child process reconstructs the argv array we start with
858 exactly, so we treat quotes at the beginning and end of arguments
859 as embedded quotes.
861 The w32 GNU-based library from Cygnus doubles quotes to escape
862 them, while MSVC uses backslash for escaping. (Actually the MSVC
863 startup code does attempt to recognise doubled quotes and accept
864 them, but gets it wrong and ends up requiring three quotes to get a
865 single embedded quote!) So by default we decide whether to use
866 quote or backslash as the escape character based on whether the
867 binary is apparently a Cygnus compiled app.
869 Note that using backslash to escape embedded quotes requires
870 additional special handling if an embedded quote is already
871 preceeded by backslash, or if an arg requiring quoting ends with
872 backslash. In such cases, the run of escape characters needs to be
873 doubled. For consistency, we apply this special handling as long
874 as the escape character is not quote.
876 Since we have no idea how large argv and envp are likely to be we
877 figure out list lengths on the fly and allocate them. */
879 if (!NILP (Vw32_quote_process_args))
881 do_quoting = 1;
882 /* Override escape char by binding w32-quote-process-args to
883 desired character, or use t for auto-selection. */
884 if (INTEGERP (Vw32_quote_process_args))
885 escape_char = XINT (Vw32_quote_process_args);
886 else
887 escape_char = is_cygnus_app ? '"' : '\\';
890 /* Cygwin apps needs quoting a bit more often */
891 if (escape_char == '"')
892 sepchars = "\r\n\t\f '";
894 /* do argv... */
895 arglen = 0;
896 targ = argv;
897 while (*targ)
899 char * p = *targ;
900 int need_quotes = 0;
901 int escape_char_run = 0;
903 if (*p == 0)
904 need_quotes = 1;
905 for ( ; *p; p++)
907 if (escape_char == '"' && *p == '\\')
908 /* If it's a Cygwin app, \ needs to be escaped. */
909 arglen++;
910 else if (*p == '"')
912 /* allow for embedded quotes to be escaped */
913 arglen++;
914 need_quotes = 1;
915 /* handle the case where the embedded quote is already escaped */
916 if (escape_char_run > 0)
918 /* To preserve the arg exactly, we need to double the
919 preceding escape characters (plus adding one to
920 escape the quote character itself). */
921 arglen += escape_char_run;
924 else if (strchr (sepchars, *p) != NULL)
926 need_quotes = 1;
929 if (*p == escape_char && escape_char != '"')
930 escape_char_run++;
931 else
932 escape_char_run = 0;
934 if (need_quotes)
936 arglen += 2;
937 /* handle the case where the arg ends with an escape char - we
938 must not let the enclosing quote be escaped. */
939 if (escape_char_run > 0)
940 arglen += escape_char_run;
942 arglen += strlen (*targ++) + 1;
944 cmdline = alloca (arglen);
945 targ = argv;
946 parg = cmdline;
947 while (*targ)
949 char * p = *targ;
950 int need_quotes = 0;
952 if (*p == 0)
953 need_quotes = 1;
955 if (do_quoting)
957 for ( ; *p; p++)
958 if ((strchr (sepchars, *p) != NULL) || *p == '"')
959 need_quotes = 1;
961 if (need_quotes)
963 int escape_char_run = 0;
964 char * first;
965 char * last;
967 p = *targ;
968 first = p;
969 last = p + strlen (p) - 1;
970 *parg++ = '"';
971 #if 0
972 /* This version does not escape quotes if they occur at the
973 beginning or end of the arg - this could lead to incorrect
974 behaviour when the arg itself represents a command line
975 containing quoted args. I believe this was originally done
976 as a hack to make some things work, before
977 `w32-quote-process-args' was added. */
978 while (*p)
980 if (*p == '"' && p > first && p < last)
981 *parg++ = escape_char; /* escape embedded quotes */
982 *parg++ = *p++;
984 #else
985 for ( ; *p; p++)
987 if (*p == '"')
989 /* double preceding escape chars if any */
990 while (escape_char_run > 0)
992 *parg++ = escape_char;
993 escape_char_run--;
995 /* escape all quote chars, even at beginning or end */
996 *parg++ = escape_char;
998 else if (escape_char == '"' && *p == '\\')
999 *parg++ = '\\';
1000 *parg++ = *p;
1002 if (*p == escape_char && escape_char != '"')
1003 escape_char_run++;
1004 else
1005 escape_char_run = 0;
1007 /* double escape chars before enclosing quote */
1008 while (escape_char_run > 0)
1010 *parg++ = escape_char;
1011 escape_char_run--;
1013 #endif
1014 *parg++ = '"';
1016 else
1018 strcpy (parg, *targ);
1019 parg += strlen (*targ);
1021 *parg++ = ' ';
1022 targ++;
1024 *--parg = '\0';
1026 /* and envp... */
1027 arglen = 1;
1028 targ = envp;
1029 numenv = 1; /* for end null */
1030 while (*targ)
1032 arglen += strlen (*targ++) + 1;
1033 numenv++;
1035 /* extra env vars... */
1036 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1037 GetCurrentProcessId ());
1038 arglen += strlen (ppid_env_var_buffer) + 1;
1039 numenv++;
1041 /* merge env passed in and extra env into one, and sort it. */
1042 targ = (char **) alloca (numenv * sizeof (char *));
1043 merge_and_sort_env (envp, extra_env, targ);
1045 /* concatenate env entries. */
1046 env = alloca (arglen);
1047 parg = env;
1048 while (*targ)
1050 strcpy (parg, *targ);
1051 parg += strlen (*targ++);
1052 *parg++ = '\0';
1054 *parg++ = '\0';
1055 *parg = '\0';
1057 cp = new_child ();
1058 if (cp == NULL)
1060 errno = EAGAIN;
1061 return -1;
1064 /* Now create the process. */
1065 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1067 delete_child (cp);
1068 errno = ENOEXEC;
1069 return -1;
1072 return pid;
1075 /* Emulate the select call
1076 Wait for available input on any of the given rfds, or timeout if
1077 a timeout is given and no input is detected
1078 wfds and efds are not supported and must be NULL.
1080 For simplicity, we detect the death of child processes here and
1081 synchronously call the SIGCHLD handler. Since it is possible for
1082 children to be created without a corresponding pipe handle from which
1083 to read output, we wait separately on the process handles as well as
1084 the char_avail events for each process pipe. We only call
1085 wait/reap_process when the process actually terminates.
1087 To reduce the number of places in which Emacs can be hung such that
1088 C-g is not able to interrupt it, we always wait on interrupt_handle
1089 (which is signalled by the input thread when C-g is detected). If we
1090 detect that we were woken up by C-g, we return -1 with errno set to
1091 EINTR as on Unix. */
1093 /* From ntterm.c */
1094 extern HANDLE keyboard_handle;
1096 /* From w32xfns.c */
1097 extern HANDLE interrupt_handle;
1099 /* From process.c */
1100 extern int proc_buffered_char[];
1103 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1104 EMACS_TIME *timeout)
1106 SELECT_TYPE orfds;
1107 DWORD timeout_ms, start_time;
1108 int i, nh, nc, nr;
1109 DWORD active;
1110 child_process *cp, *cps[MAX_CHILDREN];
1111 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1112 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1114 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1116 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1117 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1119 Sleep (timeout_ms);
1120 return 0;
1123 /* Otherwise, we only handle rfds, so fail otherwise. */
1124 if (rfds == NULL || wfds != NULL || efds != NULL)
1126 errno = EINVAL;
1127 return -1;
1130 orfds = *rfds;
1131 FD_ZERO (rfds);
1132 nr = 0;
1134 /* Always wait on interrupt_handle, to detect C-g (quit). */
1135 wait_hnd[0] = interrupt_handle;
1136 fdindex[0] = -1;
1138 /* Build a list of pipe handles to wait on. */
1139 nh = 1;
1140 for (i = 0; i < nfds; i++)
1141 if (FD_ISSET (i, &orfds))
1143 if (i == 0)
1145 if (keyboard_handle)
1147 /* Handle stdin specially */
1148 wait_hnd[nh] = keyboard_handle;
1149 fdindex[nh] = i;
1150 nh++;
1153 /* Check for any emacs-generated input in the queue since
1154 it won't be detected in the wait */
1155 if (detect_input_pending ())
1157 FD_SET (i, rfds);
1158 return 1;
1161 else
1163 /* Child process and socket input */
1164 cp = fd_info[i].cp;
1165 if (cp)
1167 int current_status = cp->status;
1169 if (current_status == STATUS_READ_ACKNOWLEDGED)
1171 /* Tell reader thread which file handle to use. */
1172 cp->fd = i;
1173 /* Wake up the reader thread for this process */
1174 cp->status = STATUS_READ_READY;
1175 if (!SetEvent (cp->char_consumed))
1176 DebPrint (("nt_select.SetEvent failed with "
1177 "%lu for fd %ld\n", GetLastError (), i));
1180 #ifdef CHECK_INTERLOCK
1181 /* slightly crude cross-checking of interlock between threads */
1183 current_status = cp->status;
1184 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1186 /* char_avail has been signalled, so status (which may
1187 have changed) should indicate read has completed
1188 but has not been acknowledged. */
1189 current_status = cp->status;
1190 if (current_status != STATUS_READ_SUCCEEDED
1191 && current_status != STATUS_READ_FAILED)
1192 DebPrint (("char_avail set, but read not completed: status %d\n",
1193 current_status));
1195 else
1197 /* char_avail has not been signalled, so status should
1198 indicate that read is in progress; small possibility
1199 that read has completed but event wasn't yet signalled
1200 when we tested it (because a context switch occurred
1201 or if running on separate CPUs). */
1202 if (current_status != STATUS_READ_READY
1203 && current_status != STATUS_READ_IN_PROGRESS
1204 && current_status != STATUS_READ_SUCCEEDED
1205 && current_status != STATUS_READ_FAILED)
1206 DebPrint (("char_avail reset, but read status is bad: %d\n",
1207 current_status));
1209 #endif
1210 wait_hnd[nh] = cp->char_avail;
1211 fdindex[nh] = i;
1212 if (!wait_hnd[nh]) abort ();
1213 nh++;
1214 #ifdef FULL_DEBUG
1215 DebPrint (("select waiting on child %d fd %d\n",
1216 cp-child_procs, i));
1217 #endif
1219 else
1221 /* Unable to find something to wait on for this fd, skip */
1223 /* Note that this is not a fatal error, and can in fact
1224 happen in unusual circumstances. Specifically, if
1225 sys_spawnve fails, eg. because the program doesn't
1226 exist, and debug-on-error is t so Fsignal invokes a
1227 nested input loop, then the process output pipe is
1228 still included in input_wait_mask with no child_proc
1229 associated with it. (It is removed when the debugger
1230 exits the nested input loop and the error is thrown.) */
1232 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1237 count_children:
1238 /* Add handles of child processes. */
1239 nc = 0;
1240 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
1241 /* Some child_procs might be sockets; ignore them. Also some
1242 children may have died already, but we haven't finished reading
1243 the process output; ignore them too. */
1244 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1245 && (cp->fd < 0
1246 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1247 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1250 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1251 cps[nc] = cp;
1252 nc++;
1255 /* Nothing to look for, so we didn't find anything */
1256 if (nh + nc == 0)
1258 if (timeout)
1259 Sleep (timeout_ms);
1260 return 0;
1263 start_time = GetTickCount ();
1265 /* Wait for input or child death to be signalled. If user input is
1266 allowed, then also accept window messages. */
1267 if (FD_ISSET (0, &orfds))
1268 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1269 QS_ALLINPUT);
1270 else
1271 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1273 if (active == WAIT_FAILED)
1275 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1276 nh + nc, timeout_ms, GetLastError ()));
1277 /* don't return EBADF - this causes wait_reading_process_output to
1278 abort; WAIT_FAILED is returned when single-stepping under
1279 Windows 95 after switching thread focus in debugger, and
1280 possibly at other times. */
1281 errno = EINTR;
1282 return -1;
1284 else if (active == WAIT_TIMEOUT)
1286 return 0;
1288 else if (active >= WAIT_OBJECT_0
1289 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1291 active -= WAIT_OBJECT_0;
1293 else if (active >= WAIT_ABANDONED_0
1294 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1296 active -= WAIT_ABANDONED_0;
1298 else
1299 abort ();
1301 /* Loop over all handles after active (now officially documented as
1302 being the first signalled handle in the array). We do this to
1303 ensure fairness, so that all channels with data available will be
1304 processed - otherwise higher numbered channels could be starved. */
1307 if (active == nh + nc)
1309 /* There are messages in the lisp thread's queue; we must
1310 drain the queue now to ensure they are processed promptly,
1311 because if we don't do so, we will not be woken again until
1312 further messages arrive.
1314 NB. If ever we allow window message procedures to callback
1315 into lisp, we will need to ensure messages are dispatched
1316 at a safe time for lisp code to be run (*), and we may also
1317 want to provide some hooks in the dispatch loop to cater
1318 for modeless dialogs created by lisp (ie. to register
1319 window handles to pass to IsDialogMessage).
1321 (*) Note that MsgWaitForMultipleObjects above is an
1322 internal dispatch point for messages that are sent to
1323 windows created by this thread. */
1324 drain_message_queue ();
1326 else if (active >= nh)
1328 cp = cps[active - nh];
1330 /* We cannot always signal SIGCHLD immediately; if we have not
1331 finished reading the process output, we must delay sending
1332 SIGCHLD until we do. */
1334 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1335 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1336 /* SIG_DFL for SIGCHLD is ignore */
1337 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1338 sig_handlers[SIGCHLD] != SIG_IGN)
1340 #ifdef FULL_DEBUG
1341 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1342 cp->pid));
1343 #endif
1344 dead_child = cp;
1345 sig_handlers[SIGCHLD] (SIGCHLD);
1346 dead_child = NULL;
1349 else if (fdindex[active] == -1)
1351 /* Quit (C-g) was detected. */
1352 errno = EINTR;
1353 return -1;
1355 else if (fdindex[active] == 0)
1357 /* Keyboard input available */
1358 FD_SET (0, rfds);
1359 nr++;
1361 else
1363 /* must be a socket or pipe - read ahead should have
1364 completed, either succeeding or failing. */
1365 FD_SET (fdindex[active], rfds);
1366 nr++;
1369 /* Even though wait_reading_process_output only reads from at most
1370 one channel, we must process all channels here so that we reap
1371 all children that have died. */
1372 while (++active < nh + nc)
1373 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1374 break;
1375 } while (active < nh + nc);
1377 /* If no input has arrived and timeout hasn't expired, wait again. */
1378 if (nr == 0)
1380 DWORD elapsed = GetTickCount () - start_time;
1382 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1384 if (timeout_ms != INFINITE)
1385 timeout_ms -= elapsed;
1386 goto count_children;
1390 return nr;
1393 /* Substitute for certain kill () operations */
1395 static BOOL CALLBACK
1396 find_child_console (HWND hwnd, LPARAM arg)
1398 child_process * cp = (child_process *) arg;
1399 DWORD thread_id;
1400 DWORD process_id;
1402 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1403 if (process_id == cp->procinfo.dwProcessId)
1405 char window_class[32];
1407 GetClassName (hwnd, window_class, sizeof (window_class));
1408 if (strcmp (window_class,
1409 (os_subtype == OS_WIN95)
1410 ? "tty"
1411 : "ConsoleWindowClass") == 0)
1413 cp->hwnd = hwnd;
1414 return FALSE;
1417 /* keep looking */
1418 return TRUE;
1422 sys_kill (int pid, int sig)
1424 child_process *cp;
1425 HANDLE proc_hand;
1426 int need_to_free = 0;
1427 int rc = 0;
1429 /* Only handle signals that will result in the process dying */
1430 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1432 errno = EINVAL;
1433 return -1;
1436 cp = find_child_pid (pid);
1437 if (cp == NULL)
1439 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1440 if (proc_hand == NULL)
1442 errno = EPERM;
1443 return -1;
1445 need_to_free = 1;
1447 else
1449 proc_hand = cp->procinfo.hProcess;
1450 pid = cp->procinfo.dwProcessId;
1452 /* Try to locate console window for process. */
1453 EnumWindows (find_child_console, (LPARAM) cp);
1456 if (sig == SIGINT || sig == SIGQUIT)
1458 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1460 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1461 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1462 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1463 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1464 HWND foreground_window;
1466 if (break_scan_code == 0)
1468 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1469 vk_break_code = 'C';
1470 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1473 foreground_window = GetForegroundWindow ();
1474 if (foreground_window)
1476 /* NT 5.0, and apparently also Windows 98, will not allow
1477 a Window to be set to foreground directly without the
1478 user's involvement. The workaround is to attach
1479 ourselves to the thread that owns the foreground
1480 window, since that is the only thread that can set the
1481 foreground window. */
1482 DWORD foreground_thread, child_thread;
1483 foreground_thread =
1484 GetWindowThreadProcessId (foreground_window, NULL);
1485 if (foreground_thread == GetCurrentThreadId ()
1486 || !AttachThreadInput (GetCurrentThreadId (),
1487 foreground_thread, TRUE))
1488 foreground_thread = 0;
1490 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1491 if (child_thread == GetCurrentThreadId ()
1492 || !AttachThreadInput (GetCurrentThreadId (),
1493 child_thread, TRUE))
1494 child_thread = 0;
1496 /* Set the foreground window to the child. */
1497 if (SetForegroundWindow (cp->hwnd))
1499 /* Generate keystrokes as if user had typed Ctrl-Break or
1500 Ctrl-C. */
1501 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1502 keybd_event (vk_break_code, break_scan_code,
1503 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1504 keybd_event (vk_break_code, break_scan_code,
1505 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1506 | KEYEVENTF_KEYUP, 0);
1507 keybd_event (VK_CONTROL, control_scan_code,
1508 KEYEVENTF_KEYUP, 0);
1510 /* Sleep for a bit to give time for Emacs frame to respond
1511 to focus change events (if Emacs was active app). */
1512 Sleep (100);
1514 SetForegroundWindow (foreground_window);
1516 /* Detach from the foreground and child threads now that
1517 the foreground switching is over. */
1518 if (foreground_thread)
1519 AttachThreadInput (GetCurrentThreadId (),
1520 foreground_thread, FALSE);
1521 if (child_thread)
1522 AttachThreadInput (GetCurrentThreadId (),
1523 child_thread, FALSE);
1526 /* Ctrl-Break is NT equivalent of SIGINT. */
1527 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1529 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1530 "for pid %lu\n", GetLastError (), pid));
1531 errno = EINVAL;
1532 rc = -1;
1535 else
1537 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1539 #if 1
1540 if (os_subtype == OS_WIN95)
1543 Another possibility is to try terminating the VDM out-right by
1544 calling the Shell VxD (id 0x17) V86 interface, function #4
1545 "SHELL_Destroy_VM", ie.
1547 mov edx,4
1548 mov ebx,vm_handle
1549 call shellapi
1551 First need to determine the current VM handle, and then arrange for
1552 the shellapi call to be made from the system vm (by using
1553 Switch_VM_and_callback).
1555 Could try to invoke DestroyVM through CallVxD.
1558 #if 0
1559 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1560 to hang when cmdproxy is used in conjunction with
1561 command.com for an interactive shell. Posting
1562 WM_CLOSE pops up a dialog that, when Yes is selected,
1563 does the same thing. TerminateProcess is also less
1564 than ideal in that subprocesses tend to stick around
1565 until the machine is shutdown, but at least it
1566 doesn't freeze the 16-bit subsystem. */
1567 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1568 #endif
1569 if (!TerminateProcess (proc_hand, 0xff))
1571 DebPrint (("sys_kill.TerminateProcess returned %d "
1572 "for pid %lu\n", GetLastError (), pid));
1573 errno = EINVAL;
1574 rc = -1;
1577 else
1578 #endif
1579 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1581 /* Kill the process. On W32 this doesn't kill child processes
1582 so it doesn't work very well for shells which is why it's not
1583 used in every case. */
1584 else if (!TerminateProcess (proc_hand, 0xff))
1586 DebPrint (("sys_kill.TerminateProcess returned %d "
1587 "for pid %lu\n", GetLastError (), pid));
1588 errno = EINVAL;
1589 rc = -1;
1593 if (need_to_free)
1594 CloseHandle (proc_hand);
1596 return rc;
1599 /* extern int report_file_error (char *, Lisp_Object); */
1601 /* The following two routines are used to manipulate stdin, stdout, and
1602 stderr of our child processes.
1604 Assuming that in, out, and err are *not* inheritable, we make them
1605 stdin, stdout, and stderr of the child as follows:
1607 - Save the parent's current standard handles.
1608 - Set the std handles to inheritable duplicates of the ones being passed in.
1609 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1610 NT file handle for a crt file descriptor.)
1611 - Spawn the child, which inherits in, out, and err as stdin,
1612 stdout, and stderr. (see Spawnve)
1613 - Close the std handles passed to the child.
1614 - Reset the parent's standard handles to the saved handles.
1615 (see reset_standard_handles)
1616 We assume that the caller closes in, out, and err after calling us. */
1618 void
1619 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1621 HANDLE parent;
1622 HANDLE newstdin, newstdout, newstderr;
1624 parent = GetCurrentProcess ();
1626 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1627 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1628 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1630 /* make inheritable copies of the new handles */
1631 if (!DuplicateHandle (parent,
1632 (HANDLE) _get_osfhandle (in),
1633 parent,
1634 &newstdin,
1636 TRUE,
1637 DUPLICATE_SAME_ACCESS))
1638 report_file_error ("Duplicating input handle for child", Qnil);
1640 if (!DuplicateHandle (parent,
1641 (HANDLE) _get_osfhandle (out),
1642 parent,
1643 &newstdout,
1645 TRUE,
1646 DUPLICATE_SAME_ACCESS))
1647 report_file_error ("Duplicating output handle for child", Qnil);
1649 if (!DuplicateHandle (parent,
1650 (HANDLE) _get_osfhandle (err),
1651 parent,
1652 &newstderr,
1654 TRUE,
1655 DUPLICATE_SAME_ACCESS))
1656 report_file_error ("Duplicating error handle for child", Qnil);
1658 /* and store them as our std handles */
1659 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1660 report_file_error ("Changing stdin handle", Qnil);
1662 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1663 report_file_error ("Changing stdout handle", Qnil);
1665 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1666 report_file_error ("Changing stderr handle", Qnil);
1669 void
1670 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1672 /* close the duplicated handles passed to the child */
1673 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1674 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1675 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1677 /* now restore parent's saved std handles */
1678 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1679 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1680 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1683 void
1684 set_process_dir (char * dir)
1686 process_dir = dir;
1689 #ifdef HAVE_SOCKETS
1691 /* To avoid problems with winsock implementations that work over dial-up
1692 connections causing or requiring a connection to exist while Emacs is
1693 running, Emacs no longer automatically loads winsock on startup if it
1694 is present. Instead, it will be loaded when open-network-stream is
1695 first called.
1697 To allow full control over when winsock is loaded, we provide these
1698 two functions to dynamically load and unload winsock. This allows
1699 dial-up users to only be connected when they actually need to use
1700 socket services. */
1702 /* From nt.c */
1703 extern HANDLE winsock_lib;
1704 extern BOOL term_winsock (void);
1705 extern BOOL init_winsock (int load_now);
1707 extern Lisp_Object Vsystem_name;
1709 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1710 doc: /* Test for presence of the Windows socket library `winsock'.
1711 Returns non-nil if winsock support is present, nil otherwise.
1713 If the optional argument LOAD-NOW is non-nil, the winsock library is
1714 also loaded immediately if not already loaded. If winsock is loaded,
1715 the winsock local hostname is returned (since this may be different from
1716 the value of `system-name' and should supplant it), otherwise t is
1717 returned to indicate winsock support is present. */)
1718 (load_now)
1719 Lisp_Object load_now;
1721 int have_winsock;
1723 have_winsock = init_winsock (!NILP (load_now));
1724 if (have_winsock)
1726 if (winsock_lib != NULL)
1728 /* Return new value for system-name. The best way to do this
1729 is to call init_system_name, saving and restoring the
1730 original value to avoid side-effects. */
1731 Lisp_Object orig_hostname = Vsystem_name;
1732 Lisp_Object hostname;
1734 init_system_name ();
1735 hostname = Vsystem_name;
1736 Vsystem_name = orig_hostname;
1737 return hostname;
1739 return Qt;
1741 return Qnil;
1744 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1745 0, 0, 0,
1746 doc: /* Unload the Windows socket library `winsock' if loaded.
1747 This is provided to allow dial-up socket connections to be disconnected
1748 when no longer needed. Returns nil without unloading winsock if any
1749 socket connections still exist. */)
1752 return term_winsock () ? Qt : Qnil;
1755 #endif /* HAVE_SOCKETS */
1758 /* Some miscellaneous functions that are Windows specific, but not GUI
1759 specific (ie. are applicable in terminal or batch mode as well). */
1761 /* lifted from fileio.c */
1762 #define CORRECT_DIR_SEPS(s) \
1763 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1764 else unixtodos_filename (s); \
1765 } while (0)
1767 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1768 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1769 If FILENAME does not exist, return nil.
1770 All path elements in FILENAME are converted to their short names. */)
1771 (filename)
1772 Lisp_Object filename;
1774 char shortname[MAX_PATH];
1776 CHECK_STRING (filename);
1778 /* first expand it. */
1779 filename = Fexpand_file_name (filename, Qnil);
1781 /* luckily, this returns the short version of each element in the path. */
1782 if (GetShortPathName (SDATA (filename), shortname, MAX_PATH) == 0)
1783 return Qnil;
1785 CORRECT_DIR_SEPS (shortname);
1787 return build_string (shortname);
1791 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1792 1, 1, 0,
1793 doc: /* Return the long file name version of the full path of FILENAME.
1794 If FILENAME does not exist, return nil.
1795 All path elements in FILENAME are converted to their long names. */)
1796 (filename)
1797 Lisp_Object filename;
1799 char longname[ MAX_PATH ];
1801 CHECK_STRING (filename);
1803 /* first expand it. */
1804 filename = Fexpand_file_name (filename, Qnil);
1806 if (!w32_get_long_filename (SDATA (filename), longname, MAX_PATH))
1807 return Qnil;
1809 CORRECT_DIR_SEPS (longname);
1811 return build_string (longname);
1814 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1815 Sw32_set_process_priority, 2, 2, 0,
1816 doc: /* Set the priority of PROCESS to PRIORITY.
1817 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1818 priority of the process whose pid is PROCESS is changed.
1819 PRIORITY should be one of the symbols high, normal, or low;
1820 any other symbol will be interpreted as normal.
1822 If successful, the return value is t, otherwise nil. */)
1823 (process, priority)
1824 Lisp_Object process, priority;
1826 HANDLE proc_handle = GetCurrentProcess ();
1827 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1828 Lisp_Object result = Qnil;
1830 CHECK_SYMBOL (priority);
1832 if (!NILP (process))
1834 DWORD pid;
1835 child_process *cp;
1837 CHECK_NUMBER (process);
1839 /* Allow pid to be an internally generated one, or one obtained
1840 externally. This is necessary because real pids on Win95 are
1841 negative. */
1843 pid = XINT (process);
1844 cp = find_child_pid (pid);
1845 if (cp != NULL)
1846 pid = cp->procinfo.dwProcessId;
1848 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1851 if (EQ (priority, Qhigh))
1852 priority_class = HIGH_PRIORITY_CLASS;
1853 else if (EQ (priority, Qlow))
1854 priority_class = IDLE_PRIORITY_CLASS;
1856 if (proc_handle != NULL)
1858 if (SetPriorityClass (proc_handle, priority_class))
1859 result = Qt;
1860 if (!NILP (process))
1861 CloseHandle (proc_handle);
1864 return result;
1867 #ifdef HAVE_LANGINFO_CODESET
1868 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1869 char *nl_langinfo (nl_item item)
1871 /* Conversion of Posix item numbers to their Windows equivalents. */
1872 static const LCTYPE w32item[] = {
1873 LOCALE_IDEFAULTANSICODEPAGE,
1874 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1875 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1876 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1877 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1878 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1879 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1882 static char *nl_langinfo_buf = NULL;
1883 static int nl_langinfo_len = 0;
1885 if (nl_langinfo_len <= 0)
1886 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1888 if (item < 0 || item >= _NL_NUM)
1889 nl_langinfo_buf[0] = 0;
1890 else
1892 LCID cloc = GetThreadLocale ();
1893 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1894 NULL, 0);
1896 if (need_len <= 0)
1897 nl_langinfo_buf[0] = 0;
1898 else
1900 if (item == CODESET)
1902 need_len += 2; /* for the "cp" prefix */
1903 if (need_len < 8) /* for the case we call GetACP */
1904 need_len = 8;
1906 if (nl_langinfo_len <= need_len)
1907 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1908 nl_langinfo_len = need_len);
1909 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1910 nl_langinfo_buf, nl_langinfo_len))
1911 nl_langinfo_buf[0] = 0;
1912 else if (item == CODESET)
1914 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1915 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1916 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1917 else
1919 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1920 strlen (nl_langinfo_buf) + 1);
1921 nl_langinfo_buf[0] = 'c';
1922 nl_langinfo_buf[1] = 'p';
1927 return nl_langinfo_buf;
1929 #endif /* HAVE_LANGINFO_CODESET */
1931 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1932 Sw32_get_locale_info, 1, 2, 0,
1933 doc: /* Return information about the Windows locale LCID.
1934 By default, return a three letter locale code which encodes the default
1935 language as the first two characters, and the country or regionial variant
1936 as the third letter. For example, ENU refers to `English (United States)',
1937 while ENC means `English (Canadian)'.
1939 If the optional argument LONGFORM is t, the long form of the locale
1940 name is returned, e.g. `English (United States)' instead; if LONGFORM
1941 is a number, it is interpreted as an LCTYPE constant and the corresponding
1942 locale information is returned.
1944 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1945 (lcid, longform)
1946 Lisp_Object lcid, longform;
1948 int got_abbrev;
1949 int got_full;
1950 char abbrev_name[32] = { 0 };
1951 char full_name[256] = { 0 };
1953 CHECK_NUMBER (lcid);
1955 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1956 return Qnil;
1958 if (NILP (longform))
1960 got_abbrev = GetLocaleInfo (XINT (lcid),
1961 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1962 abbrev_name, sizeof (abbrev_name));
1963 if (got_abbrev)
1964 return build_string (abbrev_name);
1966 else if (EQ (longform, Qt))
1968 got_full = GetLocaleInfo (XINT (lcid),
1969 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1970 full_name, sizeof (full_name));
1971 if (got_full)
1972 return build_string (full_name);
1974 else if (NUMBERP (longform))
1976 got_full = GetLocaleInfo (XINT (lcid),
1977 XINT (longform),
1978 full_name, sizeof (full_name));
1979 if (got_full)
1980 return make_unibyte_string (full_name, got_full);
1983 return Qnil;
1987 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1988 Sw32_get_current_locale_id, 0, 0, 0,
1989 doc: /* Return Windows locale id for current locale setting.
1990 This is a numerical value; use `w32-get-locale-info' to convert to a
1991 human-readable form. */)
1994 return make_number (GetThreadLocale ());
1997 DWORD int_from_hex (char * s)
1999 DWORD val = 0;
2000 static char hex[] = "0123456789abcdefABCDEF";
2001 char * p;
2003 while (*s && (p = strchr(hex, *s)) != NULL)
2005 unsigned digit = p - hex;
2006 if (digit > 15)
2007 digit -= 6;
2008 val = val * 16 + digit;
2009 s++;
2011 return val;
2014 /* We need to build a global list, since the EnumSystemLocale callback
2015 function isn't given a context pointer. */
2016 Lisp_Object Vw32_valid_locale_ids;
2018 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
2020 DWORD id = int_from_hex (localeNum);
2021 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
2022 return TRUE;
2025 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2026 Sw32_get_valid_locale_ids, 0, 0, 0,
2027 doc: /* Return list of all valid Windows locale ids.
2028 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2029 human-readable form. */)
2032 Vw32_valid_locale_ids = Qnil;
2034 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2036 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2037 return Vw32_valid_locale_ids;
2041 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2042 doc: /* Return Windows locale id for default locale setting.
2043 By default, the system default locale setting is returned; if the optional
2044 parameter USERP is non-nil, the user default locale setting is returned.
2045 This is a numerical value; use `w32-get-locale-info' to convert to a
2046 human-readable form. */)
2047 (userp)
2048 Lisp_Object userp;
2050 if (NILP (userp))
2051 return make_number (GetSystemDefaultLCID ());
2052 return make_number (GetUserDefaultLCID ());
2056 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2057 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2058 If successful, the new locale id is returned, otherwise nil. */)
2059 (lcid)
2060 Lisp_Object lcid;
2062 CHECK_NUMBER (lcid);
2064 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2065 return Qnil;
2067 if (!SetThreadLocale (XINT (lcid)))
2068 return Qnil;
2070 /* Need to set input thread locale if present. */
2071 if (dwWindowsThreadId)
2072 /* Reply is not needed. */
2073 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2075 return make_number (GetThreadLocale ());
2079 /* We need to build a global list, since the EnumCodePages callback
2080 function isn't given a context pointer. */
2081 Lisp_Object Vw32_valid_codepages;
2083 BOOL CALLBACK enum_codepage_fn (LPTSTR codepageNum)
2085 DWORD id = atoi (codepageNum);
2086 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2087 return TRUE;
2090 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2091 Sw32_get_valid_codepages, 0, 0, 0,
2092 doc: /* Return list of all valid Windows codepages. */)
2095 Vw32_valid_codepages = Qnil;
2097 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2099 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2100 return Vw32_valid_codepages;
2104 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2105 Sw32_get_console_codepage, 0, 0, 0,
2106 doc: /* Return current Windows codepage for console input. */)
2109 return make_number (GetConsoleCP ());
2113 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2114 Sw32_set_console_codepage, 1, 1, 0,
2115 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2116 The codepage setting affects keyboard input and display in tty mode.
2117 If successful, the new CP is returned, otherwise nil. */)
2118 (cp)
2119 Lisp_Object cp;
2121 CHECK_NUMBER (cp);
2123 if (!IsValidCodePage (XINT (cp)))
2124 return Qnil;
2126 if (!SetConsoleCP (XINT (cp)))
2127 return Qnil;
2129 return make_number (GetConsoleCP ());
2133 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2134 Sw32_get_console_output_codepage, 0, 0, 0,
2135 doc: /* Return current Windows codepage for console output. */)
2138 return make_number (GetConsoleOutputCP ());
2142 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2143 Sw32_set_console_output_codepage, 1, 1, 0,
2144 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2145 The codepage setting affects keyboard input and display in tty mode.
2146 If successful, the new CP is returned, otherwise nil. */)
2147 (cp)
2148 Lisp_Object cp;
2150 CHECK_NUMBER (cp);
2152 if (!IsValidCodePage (XINT (cp)))
2153 return Qnil;
2155 if (!SetConsoleOutputCP (XINT (cp)))
2156 return Qnil;
2158 return make_number (GetConsoleOutputCP ());
2162 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2163 Sw32_get_codepage_charset, 1, 1, 0,
2164 doc: /* Return charset of codepage CP.
2165 Returns nil if the codepage is not valid. */)
2166 (cp)
2167 Lisp_Object cp;
2169 CHARSETINFO info;
2171 CHECK_NUMBER (cp);
2173 if (!IsValidCodePage (XINT (cp)))
2174 return Qnil;
2176 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2177 return make_number (info.ciCharset);
2179 return Qnil;
2183 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2184 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2185 doc: /* Return list of Windows keyboard languages and layouts.
2186 The return value is a list of pairs of language id and layout id. */)
2189 int num_layouts = GetKeyboardLayoutList (0, NULL);
2190 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2191 Lisp_Object obj = Qnil;
2193 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2195 while (--num_layouts >= 0)
2197 DWORD kl = (DWORD) layouts[num_layouts];
2199 obj = Fcons (Fcons (make_number (kl & 0xffff),
2200 make_number ((kl >> 16) & 0xffff)),
2201 obj);
2205 return obj;
2209 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2210 Sw32_get_keyboard_layout, 0, 0, 0,
2211 doc: /* Return current Windows keyboard language and layout.
2212 The return value is the cons of the language id and the layout id. */)
2215 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2217 return Fcons (make_number (kl & 0xffff),
2218 make_number ((kl >> 16) & 0xffff));
2222 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2223 Sw32_set_keyboard_layout, 1, 1, 0,
2224 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2225 The keyboard layout setting affects interpretation of keyboard input.
2226 If successful, the new layout id is returned, otherwise nil. */)
2227 (layout)
2228 Lisp_Object layout;
2230 DWORD kl;
2232 CHECK_CONS (layout);
2233 CHECK_NUMBER_CAR (layout);
2234 CHECK_NUMBER_CDR (layout);
2236 kl = (XINT (XCAR (layout)) & 0xffff)
2237 | (XINT (XCDR (layout)) << 16);
2239 /* Synchronize layout with input thread. */
2240 if (dwWindowsThreadId)
2242 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2243 (WPARAM) kl, 0))
2245 MSG msg;
2246 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2248 if (msg.wParam == 0)
2249 return Qnil;
2252 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2253 return Qnil;
2255 return Fw32_get_keyboard_layout ();
2259 syms_of_ntproc ()
2261 Qhigh = intern ("high");
2262 Qlow = intern ("low");
2263 staticpro (&Qhigh);
2264 staticpro (&Qlow);
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 link count in `file-attributes'.
2357 Note that this option is only useful for files on NTFS volumes, where hard links
2358 are supported. Moreover, it slows down `file-attributes' noticeably. */);
2359 Vw32_get_true_file_attributes = Qt;
2361 staticpro (&Vw32_valid_locale_ids);
2362 staticpro (&Vw32_valid_codepages);
2364 /* end of ntproc.c */
2366 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2367 (do not change this comment) */