* doc/misc/url.texi (Disk Caching): Tweak previous change.
[emacs.git] / src / w32proc.c
blobae4e725b6ef51b6d2f6469f85b726d8bb9ffb1fa
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, 2009, 2010 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>
32 #include <setjmp.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 "character.h"
59 #include "w32.h"
60 #include "w32heap.h"
61 #include "systime.h"
62 #include "syswait.h"
63 #include "process.h"
64 #include "syssignal.h"
65 #include "w32term.h"
66 #include "dispextern.h" /* for xstrcasecmp */
67 #include "coding.h"
69 #define RVA_TO_PTR(var,section,filedata) \
70 ((void *)((section)->PointerToRawData \
71 + ((DWORD)(var) - (section)->VirtualAddress) \
72 + (filedata).file_base))
74 /* Control whether spawnve quotes arguments as necessary to ensure
75 correct parsing by child process. Because not all uses of spawnve
76 are careful about constructing argv arrays, we make this behavior
77 conditional (off by default). */
78 Lisp_Object Vw32_quote_process_args;
80 /* Control whether create_child causes the process' window to be
81 hidden. The default is nil. */
82 Lisp_Object Vw32_start_process_show_window;
84 /* Control whether create_child causes the process to inherit Emacs'
85 console window, or be given a new one of its own. The default is
86 nil, to allow multiple DOS programs to run on Win95. Having separate
87 consoles also allows Emacs to cleanly terminate process groups. */
88 Lisp_Object Vw32_start_process_share_console;
90 /* Control whether create_child cause the process to inherit Emacs'
91 error mode setting. The default is t, to minimize the possibility of
92 subprocesses blocking when accessing unmounted drives. */
93 Lisp_Object Vw32_start_process_inherit_error_mode;
95 /* Time to sleep before reading from a subprocess output pipe - this
96 avoids the inefficiency of frequently reading small amounts of data.
97 This is primarily necessary for handling DOS processes on Windows 95,
98 but is useful for W32 processes on both Windows 95 and NT as well. */
99 int w32_pipe_read_delay;
101 /* Control conversion of upper case file names to lower case.
102 nil means no, t means yes. */
103 Lisp_Object Vw32_downcase_file_names;
105 /* Control whether stat() attempts to generate fake but hopefully
106 "accurate" inode values, by hashing the absolute truenames of files.
107 This should detect aliasing between long and short names, but still
108 allows the possibility of hash collisions. */
109 Lisp_Object Vw32_generate_fake_inodes;
111 /* Control whether stat() attempts to determine file type and link count
112 exactly, at the expense of slower operation. Since true hard links
113 are supported on NTFS volumes, this is only relevant on NT. */
114 Lisp_Object Vw32_get_true_file_attributes;
115 extern Lisp_Object Qlocal;
117 Lisp_Object Qhigh, Qlow;
119 #ifdef EMACSDEBUG
120 void
121 _DebPrint (const char *fmt, ...)
123 char buf[1024];
124 va_list args;
126 va_start (args, fmt);
127 vsprintf (buf, fmt, args);
128 va_end (args);
129 OutputDebugString (buf);
131 #endif
133 typedef void (_CALLBACK_ *signal_handler) (int);
135 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
136 static signal_handler sig_handlers[NSIG];
138 /* Fake signal implementation to record the SIGCHLD handler. */
139 signal_handler
140 sys_signal (int sig, signal_handler handler)
142 signal_handler old;
144 if (sig != SIGCHLD)
146 errno = EINVAL;
147 return SIG_ERR;
149 old = sig_handlers[sig];
150 sig_handlers[sig] = handler;
151 return old;
154 /* Defined in <process.h> which conflicts with the local copy */
155 #define _P_NOWAIT 1
157 /* Child process management list. */
158 int child_proc_count = 0;
159 child_process child_procs[ MAX_CHILDREN ];
160 child_process *dead_child = NULL;
162 DWORD WINAPI reader_thread (void *arg);
164 /* Find an unused process slot. */
165 child_process *
166 new_child (void)
168 child_process *cp;
169 DWORD id;
171 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
172 if (!CHILD_ACTIVE (cp))
173 goto Initialise;
174 if (child_proc_count == MAX_CHILDREN)
175 return NULL;
176 cp = &child_procs[child_proc_count++];
178 Initialise:
179 memset (cp, 0, sizeof (*cp));
180 cp->fd = -1;
181 cp->pid = -1;
182 cp->procinfo.hProcess = NULL;
183 cp->status = STATUS_READ_ERROR;
185 /* use manual reset event so that select() will function properly */
186 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
187 if (cp->char_avail)
189 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
190 if (cp->char_consumed)
192 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
193 if (cp->thrd)
194 return cp;
197 delete_child (cp);
198 return NULL;
201 void
202 delete_child (child_process *cp)
204 int i;
206 /* Should not be deleting a child that is still needed. */
207 for (i = 0; i < MAXDESC; i++)
208 if (fd_info[i].cp == cp)
209 abort ();
211 if (!CHILD_ACTIVE (cp))
212 return;
214 /* reap thread if necessary */
215 if (cp->thrd)
217 DWORD rc;
219 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
221 /* let the thread exit cleanly if possible */
222 cp->status = STATUS_READ_ERROR;
223 SetEvent (cp->char_consumed);
224 #if 0
225 /* We used to forceably terminate the thread here, but it
226 is normally unnecessary, and in abnormal cases, the worst that
227 will happen is we have an extra idle thread hanging around
228 waiting for the zombie process. */
229 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
231 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
232 "with %lu for fd %ld\n", GetLastError (), cp->fd));
233 TerminateThread (cp->thrd, 0);
235 #endif
237 CloseHandle (cp->thrd);
238 cp->thrd = NULL;
240 if (cp->char_avail)
242 CloseHandle (cp->char_avail);
243 cp->char_avail = NULL;
245 if (cp->char_consumed)
247 CloseHandle (cp->char_consumed);
248 cp->char_consumed = NULL;
251 /* update child_proc_count (highest numbered slot in use plus one) */
252 if (cp == child_procs + child_proc_count - 1)
254 for (i = child_proc_count-1; i >= 0; i--)
255 if (CHILD_ACTIVE (&child_procs[i]))
257 child_proc_count = i + 1;
258 break;
261 if (i < 0)
262 child_proc_count = 0;
265 /* Find a child by pid. */
266 static child_process *
267 find_child_pid (DWORD pid)
269 child_process *cp;
271 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
272 if (CHILD_ACTIVE (cp) && pid == cp->pid)
273 return cp;
274 return NULL;
278 /* Thread proc for child process and socket reader threads. Each thread
279 is normally blocked until woken by select() to check for input by
280 reading one char. When the read completes, char_avail is signaled
281 to wake up the select emulator and the thread blocks itself again. */
282 DWORD WINAPI
283 reader_thread (void *arg)
285 child_process *cp;
287 /* Our identity */
288 cp = (child_process *)arg;
290 /* We have to wait for the go-ahead before we can start */
291 if (cp == NULL
292 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
293 return 1;
295 for (;;)
297 int rc;
299 if (fd_info[cp->fd].flags & FILE_LISTEN)
300 rc = _sys_wait_accept (cp->fd);
301 else
302 rc = _sys_read_ahead (cp->fd);
304 /* The name char_avail is a misnomer - it really just means the
305 read-ahead has completed, whether successfully or not. */
306 if (!SetEvent (cp->char_avail))
308 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
309 GetLastError (), cp->fd));
310 return 1;
313 if (rc == STATUS_READ_ERROR)
314 return 1;
316 /* If the read died, the child has died so let the thread die */
317 if (rc == STATUS_READ_FAILED)
318 break;
320 /* Wait until our input is acknowledged before reading again */
321 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
323 DebPrint (("reader_thread.WaitForSingleObject failed with "
324 "%lu for fd %ld\n", GetLastError (), cp->fd));
325 break;
328 return 0;
331 /* To avoid Emacs changing directory, we just record here the directory
332 the new process should start in. This is set just before calling
333 sys_spawnve, and is not generally valid at any other time. */
334 static char * process_dir;
336 static BOOL
337 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
338 int * pPid, child_process *cp)
340 STARTUPINFO start;
341 SECURITY_ATTRIBUTES sec_attrs;
342 #if 0
343 SECURITY_DESCRIPTOR sec_desc;
344 #endif
345 DWORD flags;
346 char dir[ MAXPATHLEN ];
348 if (cp == NULL) abort ();
350 memset (&start, 0, sizeof (start));
351 start.cb = sizeof (start);
353 #ifdef HAVE_NTGUI
354 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
355 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
356 else
357 start.dwFlags = STARTF_USESTDHANDLES;
358 start.wShowWindow = SW_HIDE;
360 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
361 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
362 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
363 #endif /* HAVE_NTGUI */
365 #if 0
366 /* Explicitly specify no security */
367 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
368 goto EH_Fail;
369 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
370 goto EH_Fail;
371 #endif
372 sec_attrs.nLength = sizeof (sec_attrs);
373 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
374 sec_attrs.bInheritHandle = FALSE;
376 strcpy (dir, process_dir);
377 unixtodos_filename (dir);
379 flags = (!NILP (Vw32_start_process_share_console)
380 ? CREATE_NEW_PROCESS_GROUP
381 : CREATE_NEW_CONSOLE);
382 if (NILP (Vw32_start_process_inherit_error_mode))
383 flags |= CREATE_DEFAULT_ERROR_MODE;
384 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
385 flags, env, dir, &start, &cp->procinfo))
386 goto EH_Fail;
388 cp->pid = (int) cp->procinfo.dwProcessId;
390 /* Hack for Windows 95, which assigns large (ie negative) pids */
391 if (cp->pid < 0)
392 cp->pid = -cp->pid;
394 /* pid must fit in a Lisp_Int */
395 cp->pid = cp->pid & INTMASK;
397 *pPid = cp->pid;
399 return TRUE;
401 EH_Fail:
402 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
403 return FALSE;
406 /* create_child doesn't know what emacs' file handle will be for waiting
407 on output from the child, so we need to make this additional call
408 to register the handle with the process
409 This way the select emulator knows how to match file handles with
410 entries in child_procs. */
411 void
412 register_child (int pid, int fd)
414 child_process *cp;
416 cp = find_child_pid (pid);
417 if (cp == NULL)
419 DebPrint (("register_child unable to find pid %lu\n", pid));
420 return;
423 #ifdef FULL_DEBUG
424 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
425 #endif
427 cp->fd = fd;
429 /* thread is initially blocked until select is called; set status so
430 that select will release thread */
431 cp->status = STATUS_READ_ACKNOWLEDGED;
433 /* attach child_process to fd_info */
434 if (fd_info[fd].cp != NULL)
436 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
437 abort ();
440 fd_info[fd].cp = cp;
443 /* When a process dies its pipe will break so the reader thread will
444 signal failure to the select emulator.
445 The select emulator then calls this routine to clean up.
446 Since the thread signaled failure we can assume it is exiting. */
447 static void
448 reap_subprocess (child_process *cp)
450 if (cp->procinfo.hProcess)
452 /* Reap the process */
453 #ifdef FULL_DEBUG
454 /* Process should have already died before we are called. */
455 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
456 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
457 #endif
458 CloseHandle (cp->procinfo.hProcess);
459 cp->procinfo.hProcess = NULL;
460 CloseHandle (cp->procinfo.hThread);
461 cp->procinfo.hThread = NULL;
464 /* For asynchronous children, the child_proc resources will be freed
465 when the last pipe read descriptor is closed; for synchronous
466 children, we must explicitly free the resources now because
467 register_child has not been called. */
468 if (cp->fd == -1)
469 delete_child (cp);
472 /* Wait for any of our existing child processes to die
473 When it does, close its handle
474 Return the pid and fill in the status if non-NULL. */
477 sys_wait (int *status)
479 DWORD active, retval;
480 int nh;
481 int pid;
482 child_process *cp, *cps[MAX_CHILDREN];
483 HANDLE wait_hnd[MAX_CHILDREN];
485 nh = 0;
486 if (dead_child != NULL)
488 /* We want to wait for a specific child */
489 wait_hnd[nh] = dead_child->procinfo.hProcess;
490 cps[nh] = dead_child;
491 if (!wait_hnd[nh]) abort ();
492 nh++;
493 active = 0;
494 goto get_result;
496 else
498 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
499 /* some child_procs might be sockets; ignore them */
500 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
501 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
503 wait_hnd[nh] = cp->procinfo.hProcess;
504 cps[nh] = cp;
505 nh++;
509 if (nh == 0)
511 /* Nothing to wait on, so fail */
512 errno = ECHILD;
513 return -1;
518 /* Check for quit about once a second. */
519 QUIT;
520 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
521 } while (active == WAIT_TIMEOUT);
523 if (active == WAIT_FAILED)
525 errno = EBADF;
526 return -1;
528 else if (active >= WAIT_OBJECT_0
529 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
531 active -= WAIT_OBJECT_0;
533 else if (active >= WAIT_ABANDONED_0
534 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
536 active -= WAIT_ABANDONED_0;
538 else
539 abort ();
541 get_result:
542 if (!GetExitCodeProcess (wait_hnd[active], &retval))
544 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
545 GetLastError ()));
546 retval = 1;
548 if (retval == STILL_ACTIVE)
550 /* Should never happen */
551 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
552 errno = EINVAL;
553 return -1;
556 /* Massage the exit code from the process to match the format expected
557 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
558 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
560 if (retval == STATUS_CONTROL_C_EXIT)
561 retval = SIGINT;
562 else
563 retval <<= 8;
565 cp = cps[active];
566 pid = cp->pid;
567 #ifdef FULL_DEBUG
568 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
569 #endif
571 if (status)
573 *status = retval;
575 else if (synch_process_alive)
577 synch_process_alive = 0;
579 /* Report the status of the synchronous process. */
580 if (WIFEXITED (retval))
581 synch_process_retcode = WRETCODE (retval);
582 else if (WIFSIGNALED (retval))
584 int code = WTERMSIG (retval);
585 char *signame;
587 synchronize_system_messages_locale ();
588 signame = strsignal (code);
590 if (signame == 0)
591 signame = "unknown";
593 synch_process_death = signame;
596 reap_subprocess (cp);
599 reap_subprocess (cp);
601 return pid;
604 /* Old versions of w32api headers don't have separate 32-bit and
605 64-bit defines, but the one they have matches the 32-bit variety. */
606 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
607 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
608 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
609 #endif
611 void
612 w32_executable_type (char * filename,
613 int * is_dos_app,
614 int * is_cygnus_app,
615 int * is_gui_app)
617 file_data executable;
618 char * p;
620 /* Default values in case we can't tell for sure. */
621 *is_dos_app = FALSE;
622 *is_cygnus_app = FALSE;
623 *is_gui_app = FALSE;
625 if (!open_input_file (&executable, filename))
626 return;
628 p = strrchr (filename, '.');
630 /* We can only identify DOS .com programs from the extension. */
631 if (p && xstrcasecmp (p, ".com") == 0)
632 *is_dos_app = TRUE;
633 else if (p && (xstrcasecmp (p, ".bat") == 0
634 || xstrcasecmp (p, ".cmd") == 0))
636 /* A DOS shell script - it appears that CreateProcess is happy to
637 accept this (somewhat surprisingly); presumably it looks at
638 COMSPEC to determine what executable to actually invoke.
639 Therefore, we have to do the same here as well. */
640 /* Actually, I think it uses the program association for that
641 extension, which is defined in the registry. */
642 p = egetenv ("COMSPEC");
643 if (p)
644 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
646 else
648 /* Look for DOS .exe signature - if found, we must also check that
649 it isn't really a 16- or 32-bit Windows exe, since both formats
650 start with a DOS program stub. Note that 16-bit Windows
651 executables use the OS/2 1.x format. */
653 IMAGE_DOS_HEADER * dos_header;
654 IMAGE_NT_HEADERS * nt_header;
656 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
657 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
658 goto unwind;
660 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
662 if ((char *) nt_header > (char *) dos_header + executable.size)
664 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
665 *is_dos_app = TRUE;
667 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
668 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
670 *is_dos_app = TRUE;
672 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
674 IMAGE_DATA_DIRECTORY *data_dir = NULL;
675 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
677 /* Ensure we are using the 32 bit structure. */
678 IMAGE_OPTIONAL_HEADER32 *opt
679 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
680 data_dir = opt->DataDirectory;
681 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
683 /* MingW 3.12 has the required 64 bit structs, but in case older
684 versions don't, only check 64 bit exes if we know how. */
685 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
686 else if (nt_header->OptionalHeader.Magic
687 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
689 IMAGE_OPTIONAL_HEADER64 *opt
690 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
691 data_dir = opt->DataDirectory;
692 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
694 #endif
695 if (data_dir)
697 /* Look for cygwin.dll in DLL import list. */
698 IMAGE_DATA_DIRECTORY import_dir =
699 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
700 IMAGE_IMPORT_DESCRIPTOR * imports;
701 IMAGE_SECTION_HEADER * section;
703 section = rva_to_section (import_dir.VirtualAddress, nt_header);
704 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
705 executable);
707 for ( ; imports->Name; imports++)
709 char * dllname = RVA_TO_PTR (imports->Name, section,
710 executable);
712 /* The exact name of the cygwin dll has changed with
713 various releases, but hopefully this will be reasonably
714 future proof. */
715 if (strncmp (dllname, "cygwin", 6) == 0)
717 *is_cygnus_app = TRUE;
718 break;
725 unwind:
726 close_file_data (&executable);
730 compare_env (const void *strp1, const void *strp2)
732 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
734 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
736 /* Sort order in command.com/cmd.exe is based on uppercasing
737 names, so do the same here. */
738 if (toupper (*str1) > toupper (*str2))
739 return 1;
740 else if (toupper (*str1) < toupper (*str2))
741 return -1;
742 str1++, str2++;
745 if (*str1 == '=' && *str2 == '=')
746 return 0;
747 else if (*str1 == '=')
748 return -1;
749 else
750 return 1;
753 void
754 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
756 char **optr, **nptr;
757 int num;
759 nptr = new_envp;
760 optr = envp1;
761 while (*optr)
762 *nptr++ = *optr++;
763 num = optr - envp1;
765 optr = envp2;
766 while (*optr)
767 *nptr++ = *optr++;
768 num += optr - envp2;
770 qsort (new_envp, num, sizeof (char *), compare_env);
772 *nptr = NULL;
775 /* When a new child process is created we need to register it in our list,
776 so intercept spawn requests. */
778 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
780 Lisp_Object program, full;
781 char *cmdline, *env, *parg, **targ;
782 int arglen, numenv;
783 int pid;
784 child_process *cp;
785 int is_dos_app, is_cygnus_app, is_gui_app;
786 int do_quoting = 0;
787 char escape_char;
788 /* We pass our process ID to our children by setting up an environment
789 variable in their environment. */
790 char ppid_env_var_buffer[64];
791 char *extra_env[] = {ppid_env_var_buffer, NULL};
792 /* These are the characters that cause an argument to need quoting.
793 Arguments with whitespace characters need quoting to prevent the
794 argument being split into two or more. Arguments with wildcards
795 are also quoted, for consistency with posix platforms, where wildcards
796 are not expanded if we run the program directly without a shell.
797 Some extra whitespace characters need quoting in Cygwin programs,
798 so this list is conditionally modified below. */
799 char *sepchars = " \t*?";
801 /* We don't care about the other modes */
802 if (mode != _P_NOWAIT)
804 errno = EINVAL;
805 return -1;
808 /* Handle executable names without an executable suffix. */
809 program = make_string (cmdname, strlen (cmdname));
810 if (NILP (Ffile_executable_p (program)))
812 struct gcpro gcpro1;
814 full = Qnil;
815 GCPRO1 (program);
816 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
817 UNGCPRO;
818 if (NILP (full))
820 errno = EINVAL;
821 return -1;
823 program = full;
826 /* make sure argv[0] and cmdname are both in DOS format */
827 cmdname = SDATA (program);
828 unixtodos_filename (cmdname);
829 argv[0] = cmdname;
831 /* Determine whether program is a 16-bit DOS executable, or a w32
832 executable that is implicitly linked to the Cygnus dll (implying it
833 was compiled with the Cygnus GNU toolchain and hence relies on
834 cygwin.dll to parse the command line - we use this to decide how to
835 escape quote chars in command line args that must be quoted).
837 Also determine whether it is a GUI app, so that we don't hide its
838 initial window unless specifically requested. */
839 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
841 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
842 application to start it by specifying the helper app as cmdname,
843 while leaving the real app name as argv[0]. */
844 if (is_dos_app)
846 cmdname = alloca (MAXPATHLEN);
847 if (egetenv ("CMDPROXY"))
848 strcpy (cmdname, egetenv ("CMDPROXY"));
849 else
851 strcpy (cmdname, SDATA (Vinvocation_directory));
852 strcat (cmdname, "cmdproxy.exe");
854 unixtodos_filename (cmdname);
857 /* we have to do some conjuring here to put argv and envp into the
858 form CreateProcess wants... argv needs to be a space separated/null
859 terminated list of parameters, and envp is a null
860 separated/double-null terminated list of parameters.
862 Additionally, zero-length args and args containing whitespace or
863 quote chars need to be wrapped in double quotes - for this to work,
864 embedded quotes need to be escaped as well. The aim is to ensure
865 the child process reconstructs the argv array we start with
866 exactly, so we treat quotes at the beginning and end of arguments
867 as embedded quotes.
869 The w32 GNU-based library from Cygnus doubles quotes to escape
870 them, while MSVC uses backslash for escaping. (Actually the MSVC
871 startup code does attempt to recognise doubled quotes and accept
872 them, but gets it wrong and ends up requiring three quotes to get a
873 single embedded quote!) So by default we decide whether to use
874 quote or backslash as the escape character based on whether the
875 binary is apparently a Cygnus compiled app.
877 Note that using backslash to escape embedded quotes requires
878 additional special handling if an embedded quote is already
879 preceeded by backslash, or if an arg requiring quoting ends with
880 backslash. In such cases, the run of escape characters needs to be
881 doubled. For consistency, we apply this special handling as long
882 as the escape character is not quote.
884 Since we have no idea how large argv and envp are likely to be we
885 figure out list lengths on the fly and allocate them. */
887 if (!NILP (Vw32_quote_process_args))
889 do_quoting = 1;
890 /* Override escape char by binding w32-quote-process-args to
891 desired character, or use t for auto-selection. */
892 if (INTEGERP (Vw32_quote_process_args))
893 escape_char = XINT (Vw32_quote_process_args);
894 else
895 escape_char = is_cygnus_app ? '"' : '\\';
898 /* Cygwin apps needs quoting a bit more often */
899 if (escape_char == '"')
900 sepchars = "\r\n\t\f '";
902 /* do argv... */
903 arglen = 0;
904 targ = argv;
905 while (*targ)
907 char * p = *targ;
908 int need_quotes = 0;
909 int escape_char_run = 0;
911 if (*p == 0)
912 need_quotes = 1;
913 for ( ; *p; p++)
915 if (escape_char == '"' && *p == '\\')
916 /* If it's a Cygwin app, \ needs to be escaped. */
917 arglen++;
918 else if (*p == '"')
920 /* allow for embedded quotes to be escaped */
921 arglen++;
922 need_quotes = 1;
923 /* handle the case where the embedded quote is already escaped */
924 if (escape_char_run > 0)
926 /* To preserve the arg exactly, we need to double the
927 preceding escape characters (plus adding one to
928 escape the quote character itself). */
929 arglen += escape_char_run;
932 else if (strchr (sepchars, *p) != NULL)
934 need_quotes = 1;
937 if (*p == escape_char && escape_char != '"')
938 escape_char_run++;
939 else
940 escape_char_run = 0;
942 if (need_quotes)
944 arglen += 2;
945 /* handle the case where the arg ends with an escape char - we
946 must not let the enclosing quote be escaped. */
947 if (escape_char_run > 0)
948 arglen += escape_char_run;
950 arglen += strlen (*targ++) + 1;
952 cmdline = alloca (arglen);
953 targ = argv;
954 parg = cmdline;
955 while (*targ)
957 char * p = *targ;
958 int need_quotes = 0;
960 if (*p == 0)
961 need_quotes = 1;
963 if (do_quoting)
965 for ( ; *p; p++)
966 if ((strchr (sepchars, *p) != NULL) || *p == '"')
967 need_quotes = 1;
969 if (need_quotes)
971 int escape_char_run = 0;
972 char * first;
973 char * last;
975 p = *targ;
976 first = p;
977 last = p + strlen (p) - 1;
978 *parg++ = '"';
979 #if 0
980 /* This version does not escape quotes if they occur at the
981 beginning or end of the arg - this could lead to incorrect
982 behavior when the arg itself represents a command line
983 containing quoted args. I believe this was originally done
984 as a hack to make some things work, before
985 `w32-quote-process-args' was added. */
986 while (*p)
988 if (*p == '"' && p > first && p < last)
989 *parg++ = escape_char; /* escape embedded quotes */
990 *parg++ = *p++;
992 #else
993 for ( ; *p; p++)
995 if (*p == '"')
997 /* double preceding escape chars if any */
998 while (escape_char_run > 0)
1000 *parg++ = escape_char;
1001 escape_char_run--;
1003 /* escape all quote chars, even at beginning or end */
1004 *parg++ = escape_char;
1006 else if (escape_char == '"' && *p == '\\')
1007 *parg++ = '\\';
1008 *parg++ = *p;
1010 if (*p == escape_char && escape_char != '"')
1011 escape_char_run++;
1012 else
1013 escape_char_run = 0;
1015 /* double escape chars before enclosing quote */
1016 while (escape_char_run > 0)
1018 *parg++ = escape_char;
1019 escape_char_run--;
1021 #endif
1022 *parg++ = '"';
1024 else
1026 strcpy (parg, *targ);
1027 parg += strlen (*targ);
1029 *parg++ = ' ';
1030 targ++;
1032 *--parg = '\0';
1034 /* and envp... */
1035 arglen = 1;
1036 targ = envp;
1037 numenv = 1; /* for end null */
1038 while (*targ)
1040 arglen += strlen (*targ++) + 1;
1041 numenv++;
1043 /* extra env vars... */
1044 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1045 GetCurrentProcessId ());
1046 arglen += strlen (ppid_env_var_buffer) + 1;
1047 numenv++;
1049 /* merge env passed in and extra env into one, and sort it. */
1050 targ = (char **) alloca (numenv * sizeof (char *));
1051 merge_and_sort_env (envp, extra_env, targ);
1053 /* concatenate env entries. */
1054 env = alloca (arglen);
1055 parg = env;
1056 while (*targ)
1058 strcpy (parg, *targ);
1059 parg += strlen (*targ++);
1060 *parg++ = '\0';
1062 *parg++ = '\0';
1063 *parg = '\0';
1065 cp = new_child ();
1066 if (cp == NULL)
1068 errno = EAGAIN;
1069 return -1;
1072 /* Now create the process. */
1073 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1075 delete_child (cp);
1076 errno = ENOEXEC;
1077 return -1;
1080 return pid;
1083 /* Emulate the select call
1084 Wait for available input on any of the given rfds, or timeout if
1085 a timeout is given and no input is detected
1086 wfds and efds are not supported and must be NULL.
1088 For simplicity, we detect the death of child processes here and
1089 synchronously call the SIGCHLD handler. Since it is possible for
1090 children to be created without a corresponding pipe handle from which
1091 to read output, we wait separately on the process handles as well as
1092 the char_avail events for each process pipe. We only call
1093 wait/reap_process when the process actually terminates.
1095 To reduce the number of places in which Emacs can be hung such that
1096 C-g is not able to interrupt it, we always wait on interrupt_handle
1097 (which is signaled by the input thread when C-g is detected). If we
1098 detect that we were woken up by C-g, we return -1 with errno set to
1099 EINTR as on Unix. */
1101 /* From ntterm.c */
1102 extern HANDLE keyboard_handle;
1104 /* From w32xfns.c */
1105 extern HANDLE interrupt_handle;
1107 /* From process.c */
1108 extern int proc_buffered_char[];
1111 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1112 EMACS_TIME *timeout)
1114 SELECT_TYPE orfds;
1115 DWORD timeout_ms, start_time;
1116 int i, nh, nc, nr;
1117 DWORD active;
1118 child_process *cp, *cps[MAX_CHILDREN];
1119 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1120 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1122 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1124 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1125 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1127 Sleep (timeout_ms);
1128 return 0;
1131 /* Otherwise, we only handle rfds, so fail otherwise. */
1132 if (rfds == NULL || wfds != NULL || efds != NULL)
1134 errno = EINVAL;
1135 return -1;
1138 orfds = *rfds;
1139 FD_ZERO (rfds);
1140 nr = 0;
1142 /* Always wait on interrupt_handle, to detect C-g (quit). */
1143 wait_hnd[0] = interrupt_handle;
1144 fdindex[0] = -1;
1146 /* Build a list of pipe handles to wait on. */
1147 nh = 1;
1148 for (i = 0; i < nfds; i++)
1149 if (FD_ISSET (i, &orfds))
1151 if (i == 0)
1153 if (keyboard_handle)
1155 /* Handle stdin specially */
1156 wait_hnd[nh] = keyboard_handle;
1157 fdindex[nh] = i;
1158 nh++;
1161 /* Check for any emacs-generated input in the queue since
1162 it won't be detected in the wait */
1163 if (detect_input_pending ())
1165 FD_SET (i, rfds);
1166 return 1;
1169 else
1171 /* Child process and socket input */
1172 cp = fd_info[i].cp;
1173 if (cp)
1175 int current_status = cp->status;
1177 if (current_status == STATUS_READ_ACKNOWLEDGED)
1179 /* Tell reader thread which file handle to use. */
1180 cp->fd = i;
1181 /* Wake up the reader thread for this process */
1182 cp->status = STATUS_READ_READY;
1183 if (!SetEvent (cp->char_consumed))
1184 DebPrint (("nt_select.SetEvent failed with "
1185 "%lu for fd %ld\n", GetLastError (), i));
1188 #ifdef CHECK_INTERLOCK
1189 /* slightly crude cross-checking of interlock between threads */
1191 current_status = cp->status;
1192 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1194 /* char_avail has been signaled, so status (which may
1195 have changed) should indicate read has completed
1196 but has not been acknowledged. */
1197 current_status = cp->status;
1198 if (current_status != STATUS_READ_SUCCEEDED
1199 && current_status != STATUS_READ_FAILED)
1200 DebPrint (("char_avail set, but read not completed: status %d\n",
1201 current_status));
1203 else
1205 /* char_avail has not been signaled, so status should
1206 indicate that read is in progress; small possibility
1207 that read has completed but event wasn't yet signaled
1208 when we tested it (because a context switch occurred
1209 or if running on separate CPUs). */
1210 if (current_status != STATUS_READ_READY
1211 && current_status != STATUS_READ_IN_PROGRESS
1212 && current_status != STATUS_READ_SUCCEEDED
1213 && current_status != STATUS_READ_FAILED)
1214 DebPrint (("char_avail reset, but read status is bad: %d\n",
1215 current_status));
1217 #endif
1218 wait_hnd[nh] = cp->char_avail;
1219 fdindex[nh] = i;
1220 if (!wait_hnd[nh]) abort ();
1221 nh++;
1222 #ifdef FULL_DEBUG
1223 DebPrint (("select waiting on child %d fd %d\n",
1224 cp-child_procs, i));
1225 #endif
1227 else
1229 /* Unable to find something to wait on for this fd, skip */
1231 /* Note that this is not a fatal error, and can in fact
1232 happen in unusual circumstances. Specifically, if
1233 sys_spawnve fails, eg. because the program doesn't
1234 exist, and debug-on-error is t so Fsignal invokes a
1235 nested input loop, then the process output pipe is
1236 still included in input_wait_mask with no child_proc
1237 associated with it. (It is removed when the debugger
1238 exits the nested input loop and the error is thrown.) */
1240 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1245 count_children:
1246 /* Add handles of child processes. */
1247 nc = 0;
1248 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
1249 /* Some child_procs might be sockets; ignore them. Also some
1250 children may have died already, but we haven't finished reading
1251 the process output; ignore them too. */
1252 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1253 && (cp->fd < 0
1254 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1255 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1258 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1259 cps[nc] = cp;
1260 nc++;
1263 /* Nothing to look for, so we didn't find anything */
1264 if (nh + nc == 0)
1266 if (timeout)
1267 Sleep (timeout_ms);
1268 return 0;
1271 start_time = GetTickCount ();
1273 /* Wait for input or child death to be signaled. If user input is
1274 allowed, then also accept window messages. */
1275 if (FD_ISSET (0, &orfds))
1276 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1277 QS_ALLINPUT);
1278 else
1279 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1281 if (active == WAIT_FAILED)
1283 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1284 nh + nc, timeout_ms, GetLastError ()));
1285 /* don't return EBADF - this causes wait_reading_process_output to
1286 abort; WAIT_FAILED is returned when single-stepping under
1287 Windows 95 after switching thread focus in debugger, and
1288 possibly at other times. */
1289 errno = EINTR;
1290 return -1;
1292 else if (active == WAIT_TIMEOUT)
1294 return 0;
1296 else if (active >= WAIT_OBJECT_0
1297 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1299 active -= WAIT_OBJECT_0;
1301 else if (active >= WAIT_ABANDONED_0
1302 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1304 active -= WAIT_ABANDONED_0;
1306 else
1307 abort ();
1309 /* Loop over all handles after active (now officially documented as
1310 being the first signaled handle in the array). We do this to
1311 ensure fairness, so that all channels with data available will be
1312 processed - otherwise higher numbered channels could be starved. */
1315 if (active == nh + nc)
1317 /* There are messages in the lisp thread's queue; we must
1318 drain the queue now to ensure they are processed promptly,
1319 because if we don't do so, we will not be woken again until
1320 further messages arrive.
1322 NB. If ever we allow window message procedures to callback
1323 into lisp, we will need to ensure messages are dispatched
1324 at a safe time for lisp code to be run (*), and we may also
1325 want to provide some hooks in the dispatch loop to cater
1326 for modeless dialogs created by lisp (ie. to register
1327 window handles to pass to IsDialogMessage).
1329 (*) Note that MsgWaitForMultipleObjects above is an
1330 internal dispatch point for messages that are sent to
1331 windows created by this thread. */
1332 drain_message_queue ();
1334 else if (active >= nh)
1336 cp = cps[active - nh];
1338 /* We cannot always signal SIGCHLD immediately; if we have not
1339 finished reading the process output, we must delay sending
1340 SIGCHLD until we do. */
1342 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1343 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1344 /* SIG_DFL for SIGCHLD is ignore */
1345 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1346 sig_handlers[SIGCHLD] != SIG_IGN)
1348 #ifdef FULL_DEBUG
1349 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1350 cp->pid));
1351 #endif
1352 dead_child = cp;
1353 sig_handlers[SIGCHLD] (SIGCHLD);
1354 dead_child = NULL;
1357 else if (fdindex[active] == -1)
1359 /* Quit (C-g) was detected. */
1360 errno = EINTR;
1361 return -1;
1363 else if (fdindex[active] == 0)
1365 /* Keyboard input available */
1366 FD_SET (0, rfds);
1367 nr++;
1369 else
1371 /* must be a socket or pipe - read ahead should have
1372 completed, either succeeding or failing. */
1373 FD_SET (fdindex[active], rfds);
1374 nr++;
1377 /* Even though wait_reading_process_output only reads from at most
1378 one channel, we must process all channels here so that we reap
1379 all children that have died. */
1380 while (++active < nh + nc)
1381 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1382 break;
1383 } while (active < nh + nc);
1385 /* If no input has arrived and timeout hasn't expired, wait again. */
1386 if (nr == 0)
1388 DWORD elapsed = GetTickCount () - start_time;
1390 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1392 if (timeout_ms != INFINITE)
1393 timeout_ms -= elapsed;
1394 goto count_children;
1398 return nr;
1401 /* Substitute for certain kill () operations */
1403 static BOOL CALLBACK
1404 find_child_console (HWND hwnd, LPARAM arg)
1406 child_process * cp = (child_process *) arg;
1407 DWORD thread_id;
1408 DWORD process_id;
1410 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1411 if (process_id == cp->procinfo.dwProcessId)
1413 char window_class[32];
1415 GetClassName (hwnd, window_class, sizeof (window_class));
1416 if (strcmp (window_class,
1417 (os_subtype == OS_WIN95)
1418 ? "tty"
1419 : "ConsoleWindowClass") == 0)
1421 cp->hwnd = hwnd;
1422 return FALSE;
1425 /* keep looking */
1426 return TRUE;
1430 sys_kill (int pid, int sig)
1432 child_process *cp;
1433 HANDLE proc_hand;
1434 int need_to_free = 0;
1435 int rc = 0;
1437 /* Only handle signals that will result in the process dying */
1438 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1440 errno = EINVAL;
1441 return -1;
1444 cp = find_child_pid (pid);
1445 if (cp == NULL)
1447 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1448 if (proc_hand == NULL)
1450 errno = EPERM;
1451 return -1;
1453 need_to_free = 1;
1455 else
1457 proc_hand = cp->procinfo.hProcess;
1458 pid = cp->procinfo.dwProcessId;
1460 /* Try to locate console window for process. */
1461 EnumWindows (find_child_console, (LPARAM) cp);
1464 if (sig == SIGINT || sig == SIGQUIT)
1466 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1468 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1469 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1470 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1471 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1472 HWND foreground_window;
1474 if (break_scan_code == 0)
1476 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1477 vk_break_code = 'C';
1478 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1481 foreground_window = GetForegroundWindow ();
1482 if (foreground_window)
1484 /* NT 5.0, and apparently also Windows 98, will not allow
1485 a Window to be set to foreground directly without the
1486 user's involvement. The workaround is to attach
1487 ourselves to the thread that owns the foreground
1488 window, since that is the only thread that can set the
1489 foreground window. */
1490 DWORD foreground_thread, child_thread;
1491 foreground_thread =
1492 GetWindowThreadProcessId (foreground_window, NULL);
1493 if (foreground_thread == GetCurrentThreadId ()
1494 || !AttachThreadInput (GetCurrentThreadId (),
1495 foreground_thread, TRUE))
1496 foreground_thread = 0;
1498 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1499 if (child_thread == GetCurrentThreadId ()
1500 || !AttachThreadInput (GetCurrentThreadId (),
1501 child_thread, TRUE))
1502 child_thread = 0;
1504 /* Set the foreground window to the child. */
1505 if (SetForegroundWindow (cp->hwnd))
1507 /* Generate keystrokes as if user had typed Ctrl-Break or
1508 Ctrl-C. */
1509 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1510 keybd_event (vk_break_code, break_scan_code,
1511 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1512 keybd_event (vk_break_code, break_scan_code,
1513 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1514 | KEYEVENTF_KEYUP, 0);
1515 keybd_event (VK_CONTROL, control_scan_code,
1516 KEYEVENTF_KEYUP, 0);
1518 /* Sleep for a bit to give time for Emacs frame to respond
1519 to focus change events (if Emacs was active app). */
1520 Sleep (100);
1522 SetForegroundWindow (foreground_window);
1524 /* Detach from the foreground and child threads now that
1525 the foreground switching is over. */
1526 if (foreground_thread)
1527 AttachThreadInput (GetCurrentThreadId (),
1528 foreground_thread, FALSE);
1529 if (child_thread)
1530 AttachThreadInput (GetCurrentThreadId (),
1531 child_thread, FALSE);
1534 /* Ctrl-Break is NT equivalent of SIGINT. */
1535 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1537 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1538 "for pid %lu\n", GetLastError (), pid));
1539 errno = EINVAL;
1540 rc = -1;
1543 else
1545 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1547 #if 1
1548 if (os_subtype == OS_WIN95)
1551 Another possibility is to try terminating the VDM out-right by
1552 calling the Shell VxD (id 0x17) V86 interface, function #4
1553 "SHELL_Destroy_VM", ie.
1555 mov edx,4
1556 mov ebx,vm_handle
1557 call shellapi
1559 First need to determine the current VM handle, and then arrange for
1560 the shellapi call to be made from the system vm (by using
1561 Switch_VM_and_callback).
1563 Could try to invoke DestroyVM through CallVxD.
1566 #if 0
1567 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1568 to hang when cmdproxy is used in conjunction with
1569 command.com for an interactive shell. Posting
1570 WM_CLOSE pops up a dialog that, when Yes is selected,
1571 does the same thing. TerminateProcess is also less
1572 than ideal in that subprocesses tend to stick around
1573 until the machine is shutdown, but at least it
1574 doesn't freeze the 16-bit subsystem. */
1575 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1576 #endif
1577 if (!TerminateProcess (proc_hand, 0xff))
1579 DebPrint (("sys_kill.TerminateProcess returned %d "
1580 "for pid %lu\n", GetLastError (), pid));
1581 errno = EINVAL;
1582 rc = -1;
1585 else
1586 #endif
1587 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1589 /* Kill the process. On W32 this doesn't kill child processes
1590 so it doesn't work very well for shells which is why it's not
1591 used in every case. */
1592 else if (!TerminateProcess (proc_hand, 0xff))
1594 DebPrint (("sys_kill.TerminateProcess returned %d "
1595 "for pid %lu\n", GetLastError (), pid));
1596 errno = EINVAL;
1597 rc = -1;
1601 if (need_to_free)
1602 CloseHandle (proc_hand);
1604 return rc;
1607 /* extern int report_file_error (char *, Lisp_Object); */
1609 /* The following two routines are used to manipulate stdin, stdout, and
1610 stderr of our child processes.
1612 Assuming that in, out, and err are *not* inheritable, we make them
1613 stdin, stdout, and stderr of the child as follows:
1615 - Save the parent's current standard handles.
1616 - Set the std handles to inheritable duplicates of the ones being passed in.
1617 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1618 NT file handle for a crt file descriptor.)
1619 - Spawn the child, which inherits in, out, and err as stdin,
1620 stdout, and stderr. (see Spawnve)
1621 - Close the std handles passed to the child.
1622 - Reset the parent's standard handles to the saved handles.
1623 (see reset_standard_handles)
1624 We assume that the caller closes in, out, and err after calling us. */
1626 void
1627 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1629 HANDLE parent;
1630 HANDLE newstdin, newstdout, newstderr;
1632 parent = GetCurrentProcess ();
1634 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1635 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1636 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1638 /* make inheritable copies of the new handles */
1639 if (!DuplicateHandle (parent,
1640 (HANDLE) _get_osfhandle (in),
1641 parent,
1642 &newstdin,
1644 TRUE,
1645 DUPLICATE_SAME_ACCESS))
1646 report_file_error ("Duplicating input handle for child", Qnil);
1648 if (!DuplicateHandle (parent,
1649 (HANDLE) _get_osfhandle (out),
1650 parent,
1651 &newstdout,
1653 TRUE,
1654 DUPLICATE_SAME_ACCESS))
1655 report_file_error ("Duplicating output handle for child", Qnil);
1657 if (!DuplicateHandle (parent,
1658 (HANDLE) _get_osfhandle (err),
1659 parent,
1660 &newstderr,
1662 TRUE,
1663 DUPLICATE_SAME_ACCESS))
1664 report_file_error ("Duplicating error handle for child", Qnil);
1666 /* and store them as our std handles */
1667 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1668 report_file_error ("Changing stdin handle", Qnil);
1670 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1671 report_file_error ("Changing stdout handle", Qnil);
1673 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1674 report_file_error ("Changing stderr handle", Qnil);
1677 void
1678 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1680 /* close the duplicated handles passed to the child */
1681 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1682 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1683 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1685 /* now restore parent's saved std handles */
1686 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1687 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1688 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1691 void
1692 set_process_dir (char * dir)
1694 process_dir = dir;
1697 /* To avoid problems with winsock implementations that work over dial-up
1698 connections causing or requiring a connection to exist while Emacs is
1699 running, Emacs no longer automatically loads winsock on startup if it
1700 is present. Instead, it will be loaded when open-network-stream is
1701 first called.
1703 To allow full control over when winsock is loaded, we provide these
1704 two functions to dynamically load and unload winsock. This allows
1705 dial-up users to only be connected when they actually need to use
1706 socket services. */
1708 /* From nt.c */
1709 extern HANDLE winsock_lib;
1710 extern BOOL term_winsock (void);
1711 extern BOOL init_winsock (int load_now);
1713 extern Lisp_Object Vsystem_name;
1715 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1716 doc: /* Test for presence of the Windows socket library `winsock'.
1717 Returns non-nil if winsock support is present, nil otherwise.
1719 If the optional argument LOAD-NOW is non-nil, the winsock library is
1720 also loaded immediately if not already loaded. If winsock is loaded,
1721 the winsock local hostname is returned (since this may be different from
1722 the value of `system-name' and should supplant it), otherwise t is
1723 returned to indicate winsock support is present. */)
1724 (Lisp_Object load_now)
1726 int have_winsock;
1728 have_winsock = init_winsock (!NILP (load_now));
1729 if (have_winsock)
1731 if (winsock_lib != NULL)
1733 /* Return new value for system-name. The best way to do this
1734 is to call init_system_name, saving and restoring the
1735 original value to avoid side-effects. */
1736 Lisp_Object orig_hostname = Vsystem_name;
1737 Lisp_Object hostname;
1739 init_system_name ();
1740 hostname = Vsystem_name;
1741 Vsystem_name = orig_hostname;
1742 return hostname;
1744 return Qt;
1746 return Qnil;
1749 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1750 0, 0, 0,
1751 doc: /* Unload the Windows socket library `winsock' if loaded.
1752 This is provided to allow dial-up socket connections to be disconnected
1753 when no longer needed. Returns nil without unloading winsock if any
1754 socket connections still exist. */)
1755 (void)
1757 return term_winsock () ? Qt : Qnil;
1761 /* Some miscellaneous functions that are Windows specific, but not GUI
1762 specific (ie. are applicable in terminal or batch mode as well). */
1764 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1765 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1766 If FILENAME does not exist, return nil.
1767 All path elements in FILENAME are converted to their short names. */)
1768 (Lisp_Object filename)
1770 char shortname[MAX_PATH];
1772 CHECK_STRING (filename);
1774 /* first expand it. */
1775 filename = Fexpand_file_name (filename, Qnil);
1777 /* luckily, this returns the short version of each element in the path. */
1778 if (GetShortPathName (SDATA (ENCODE_FILE (filename)), shortname, MAX_PATH) == 0)
1779 return Qnil;
1781 dostounix_filename (shortname);
1783 return build_string (shortname);
1787 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1788 1, 1, 0,
1789 doc: /* Return the long file name version of the full path of FILENAME.
1790 If FILENAME does not exist, return nil.
1791 All path elements in FILENAME are converted to their long names. */)
1792 (Lisp_Object filename)
1794 char longname[ MAX_PATH ];
1795 int drive_only = 0;
1797 CHECK_STRING (filename);
1799 if (SBYTES (filename) == 2
1800 && *(SDATA (filename) + 1) == ':')
1801 drive_only = 1;
1803 /* first expand it. */
1804 filename = Fexpand_file_name (filename, Qnil);
1806 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename)), longname, MAX_PATH))
1807 return Qnil;
1809 dostounix_filename (longname);
1811 /* If we were passed only a drive, make sure that a slash is not appended
1812 for consistency with directories. Allow for drive mapping via SUBST
1813 in case expand-file-name is ever changed to expand those. */
1814 if (drive_only && longname[1] == ':' && longname[2] == '/' && !longname[3])
1815 longname[2] = '\0';
1817 return DECODE_FILE (build_string (longname));
1820 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1821 Sw32_set_process_priority, 2, 2, 0,
1822 doc: /* Set the priority of PROCESS to PRIORITY.
1823 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1824 priority of the process whose pid is PROCESS is changed.
1825 PRIORITY should be one of the symbols high, normal, or low;
1826 any other symbol will be interpreted as normal.
1828 If successful, the return value is t, otherwise nil. */)
1829 (Lisp_Object process, Lisp_Object priority)
1831 HANDLE proc_handle = GetCurrentProcess ();
1832 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1833 Lisp_Object result = Qnil;
1835 CHECK_SYMBOL (priority);
1837 if (!NILP (process))
1839 DWORD pid;
1840 child_process *cp;
1842 CHECK_NUMBER (process);
1844 /* Allow pid to be an internally generated one, or one obtained
1845 externally. This is necessary because real pids on Win95 are
1846 negative. */
1848 pid = XINT (process);
1849 cp = find_child_pid (pid);
1850 if (cp != NULL)
1851 pid = cp->procinfo.dwProcessId;
1853 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1856 if (EQ (priority, Qhigh))
1857 priority_class = HIGH_PRIORITY_CLASS;
1858 else if (EQ (priority, Qlow))
1859 priority_class = IDLE_PRIORITY_CLASS;
1861 if (proc_handle != NULL)
1863 if (SetPriorityClass (proc_handle, priority_class))
1864 result = Qt;
1865 if (!NILP (process))
1866 CloseHandle (proc_handle);
1869 return result;
1872 #ifdef HAVE_LANGINFO_CODESET
1873 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1874 char *
1875 nl_langinfo (nl_item item)
1877 /* Conversion of Posix item numbers to their Windows equivalents. */
1878 static const LCTYPE w32item[] = {
1879 LOCALE_IDEFAULTANSICODEPAGE,
1880 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1881 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1882 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1883 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1884 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1885 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1888 static char *nl_langinfo_buf = NULL;
1889 static int nl_langinfo_len = 0;
1891 if (nl_langinfo_len <= 0)
1892 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1894 if (item < 0 || item >= _NL_NUM)
1895 nl_langinfo_buf[0] = 0;
1896 else
1898 LCID cloc = GetThreadLocale ();
1899 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1900 NULL, 0);
1902 if (need_len <= 0)
1903 nl_langinfo_buf[0] = 0;
1904 else
1906 if (item == CODESET)
1908 need_len += 2; /* for the "cp" prefix */
1909 if (need_len < 8) /* for the case we call GetACP */
1910 need_len = 8;
1912 if (nl_langinfo_len <= need_len)
1913 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1914 nl_langinfo_len = need_len);
1915 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1916 nl_langinfo_buf, nl_langinfo_len))
1917 nl_langinfo_buf[0] = 0;
1918 else if (item == CODESET)
1920 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1921 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1922 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1923 else
1925 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1926 strlen (nl_langinfo_buf) + 1);
1927 nl_langinfo_buf[0] = 'c';
1928 nl_langinfo_buf[1] = 'p';
1933 return nl_langinfo_buf;
1935 #endif /* HAVE_LANGINFO_CODESET */
1937 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1938 Sw32_get_locale_info, 1, 2, 0,
1939 doc: /* Return information about the Windows locale LCID.
1940 By default, return a three letter locale code which encodes the default
1941 language as the first two characters, and the country or regional variant
1942 as the third letter. For example, ENU refers to `English (United States)',
1943 while ENC means `English (Canadian)'.
1945 If the optional argument LONGFORM is t, the long form of the locale
1946 name is returned, e.g. `English (United States)' instead; if LONGFORM
1947 is a number, it is interpreted as an LCTYPE constant and the corresponding
1948 locale information is returned.
1950 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1951 (Lisp_Object lcid, Lisp_Object longform)
1953 int got_abbrev;
1954 int got_full;
1955 char abbrev_name[32] = { 0 };
1956 char full_name[256] = { 0 };
1958 CHECK_NUMBER (lcid);
1960 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1961 return Qnil;
1963 if (NILP (longform))
1965 got_abbrev = GetLocaleInfo (XINT (lcid),
1966 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1967 abbrev_name, sizeof (abbrev_name));
1968 if (got_abbrev)
1969 return build_string (abbrev_name);
1971 else if (EQ (longform, Qt))
1973 got_full = GetLocaleInfo (XINT (lcid),
1974 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1975 full_name, sizeof (full_name));
1976 if (got_full)
1977 return DECODE_SYSTEM (build_string (full_name));
1979 else if (NUMBERP (longform))
1981 got_full = GetLocaleInfo (XINT (lcid),
1982 XINT (longform),
1983 full_name, sizeof (full_name));
1984 if (got_full)
1985 return make_unibyte_string (full_name, got_full);
1988 return Qnil;
1992 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1993 Sw32_get_current_locale_id, 0, 0, 0,
1994 doc: /* Return Windows locale id for current locale setting.
1995 This is a numerical value; use `w32-get-locale-info' to convert to a
1996 human-readable form. */)
1997 (void)
1999 return make_number (GetThreadLocale ());
2002 DWORD
2003 int_from_hex (char * s)
2005 DWORD val = 0;
2006 static char hex[] = "0123456789abcdefABCDEF";
2007 char * p;
2009 while (*s && (p = strchr (hex, *s)) != NULL)
2011 unsigned digit = p - hex;
2012 if (digit > 15)
2013 digit -= 6;
2014 val = val * 16 + digit;
2015 s++;
2017 return val;
2020 /* We need to build a global list, since the EnumSystemLocale callback
2021 function isn't given a context pointer. */
2022 Lisp_Object Vw32_valid_locale_ids;
2024 BOOL CALLBACK
2025 enum_locale_fn (LPTSTR localeNum)
2027 DWORD id = int_from_hex (localeNum);
2028 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
2029 return TRUE;
2032 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2033 Sw32_get_valid_locale_ids, 0, 0, 0,
2034 doc: /* Return list of all valid Windows locale ids.
2035 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2036 human-readable form. */)
2037 (void)
2039 Vw32_valid_locale_ids = Qnil;
2041 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2043 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2044 return Vw32_valid_locale_ids;
2048 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2049 doc: /* Return Windows locale id for default locale setting.
2050 By default, the system default locale setting is returned; if the optional
2051 parameter USERP is non-nil, the user default locale setting is returned.
2052 This is a numerical value; use `w32-get-locale-info' to convert to a
2053 human-readable form. */)
2054 (Lisp_Object userp)
2056 if (NILP (userp))
2057 return make_number (GetSystemDefaultLCID ());
2058 return make_number (GetUserDefaultLCID ());
2062 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2063 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2064 If successful, the new locale id is returned, otherwise nil. */)
2065 (Lisp_Object lcid)
2067 CHECK_NUMBER (lcid);
2069 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2070 return Qnil;
2072 if (!SetThreadLocale (XINT (lcid)))
2073 return Qnil;
2075 /* Need to set input thread locale if present. */
2076 if (dwWindowsThreadId)
2077 /* Reply is not needed. */
2078 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2080 return make_number (GetThreadLocale ());
2084 /* We need to build a global list, since the EnumCodePages callback
2085 function isn't given a context pointer. */
2086 Lisp_Object Vw32_valid_codepages;
2088 BOOL CALLBACK
2089 enum_codepage_fn (LPTSTR codepageNum)
2091 DWORD id = atoi (codepageNum);
2092 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2093 return TRUE;
2096 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2097 Sw32_get_valid_codepages, 0, 0, 0,
2098 doc: /* Return list of all valid Windows codepages. */)
2099 (void)
2101 Vw32_valid_codepages = Qnil;
2103 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2105 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2106 return Vw32_valid_codepages;
2110 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2111 Sw32_get_console_codepage, 0, 0, 0,
2112 doc: /* Return current Windows codepage for console input. */)
2113 (void)
2115 return make_number (GetConsoleCP ());
2119 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2120 Sw32_set_console_codepage, 1, 1, 0,
2121 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2122 The codepage setting affects keyboard input and display in tty mode.
2123 If successful, the new CP is returned, otherwise nil. */)
2124 (Lisp_Object cp)
2126 CHECK_NUMBER (cp);
2128 if (!IsValidCodePage (XINT (cp)))
2129 return Qnil;
2131 if (!SetConsoleCP (XINT (cp)))
2132 return Qnil;
2134 return make_number (GetConsoleCP ());
2138 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2139 Sw32_get_console_output_codepage, 0, 0, 0,
2140 doc: /* Return current Windows codepage for console output. */)
2141 (void)
2143 return make_number (GetConsoleOutputCP ());
2147 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2148 Sw32_set_console_output_codepage, 1, 1, 0,
2149 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2150 The codepage setting affects keyboard input and display in tty mode.
2151 If successful, the new CP is returned, otherwise nil. */)
2152 (Lisp_Object cp)
2154 CHECK_NUMBER (cp);
2156 if (!IsValidCodePage (XINT (cp)))
2157 return Qnil;
2159 if (!SetConsoleOutputCP (XINT (cp)))
2160 return Qnil;
2162 return make_number (GetConsoleOutputCP ());
2166 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2167 Sw32_get_codepage_charset, 1, 1, 0,
2168 doc: /* Return charset of codepage CP.
2169 Returns nil if the codepage is not valid. */)
2170 (Lisp_Object cp)
2172 CHARSETINFO info;
2174 CHECK_NUMBER (cp);
2176 if (!IsValidCodePage (XINT (cp)))
2177 return Qnil;
2179 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2180 return make_number (info.ciCharset);
2182 return Qnil;
2186 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2187 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2188 doc: /* Return list of Windows keyboard languages and layouts.
2189 The return value is a list of pairs of language id and layout id. */)
2190 (void)
2192 int num_layouts = GetKeyboardLayoutList (0, NULL);
2193 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2194 Lisp_Object obj = Qnil;
2196 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2198 while (--num_layouts >= 0)
2200 DWORD kl = (DWORD) layouts[num_layouts];
2202 obj = Fcons (Fcons (make_number (kl & 0xffff),
2203 make_number ((kl >> 16) & 0xffff)),
2204 obj);
2208 return obj;
2212 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2213 Sw32_get_keyboard_layout, 0, 0, 0,
2214 doc: /* Return current Windows keyboard language and layout.
2215 The return value is the cons of the language id and the layout id. */)
2216 (void)
2218 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2220 return Fcons (make_number (kl & 0xffff),
2221 make_number ((kl >> 16) & 0xffff));
2225 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2226 Sw32_set_keyboard_layout, 1, 1, 0,
2227 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2228 The keyboard layout setting affects interpretation of keyboard input.
2229 If successful, the new layout id is returned, otherwise nil. */)
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 void
2262 syms_of_ntproc (void)
2264 DEFSYM (Qhigh, "high");
2265 DEFSYM (Qlow, "low");
2267 defsubr (&Sw32_has_winsock);
2268 defsubr (&Sw32_unload_winsock);
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 more
2359 useful for files on NTFS volumes, where hard links and file security are
2360 supported, than on volumes of the FAT family.
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) */