Implement cygw32
[emacs.git] / src / w32proc.c
blob0cc62aebca089f411ad80d7cc5a0cea484a6dca6
1 /* Process support for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1992, 1995, 1999-2012 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 Drew Bliss Oct 14, 1993
21 Adapted from alarm.c by Tim Fleehart
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <io.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <sys/file.h>
31 #include <setjmp.h>
33 /* must include CRT headers *before* config.h */
34 #include <config.h>
36 #undef signal
37 #undef wait
38 #undef spawnve
39 #undef select
40 #undef kill
42 #include <windows.h>
43 #ifdef __GNUC__
44 /* This definition is missing from mingw32 headers. */
45 extern BOOL WINAPI IsValidLocale (LCID, DWORD);
46 #endif
48 #ifdef HAVE_LANGINFO_CODESET
49 #include <nl_types.h>
50 #include <langinfo.h>
51 #endif
53 #include "lisp.h"
54 #include "w32.h"
55 #include "w32heap.h"
56 #include "systime.h"
57 #include "syswait.h"
58 #include "process.h"
59 #include "syssignal.h"
60 #include "w32term.h"
61 #include "dispextern.h" /* for xstrcasecmp */
62 #include "coding.h"
64 #define RVA_TO_PTR(var,section,filedata) \
65 ((void *)((section)->PointerToRawData \
66 + ((DWORD)(var) - (section)->VirtualAddress) \
67 + (filedata).file_base))
69 Lisp_Object Qhigh, Qlow;
71 typedef void (_CALLBACK_ *signal_handler) (int);
73 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
74 static signal_handler sig_handlers[NSIG];
76 /* Fake signal implementation to record the SIGCHLD handler. */
77 signal_handler
78 sys_signal (int sig, signal_handler handler)
80 signal_handler old;
82 if (sig != SIGCHLD)
84 errno = EINVAL;
85 return SIG_ERR;
87 old = sig_handlers[sig];
88 sig_handlers[sig] = handler;
89 return old;
92 /* Defined in <process.h> which conflicts with the local copy */
93 #define _P_NOWAIT 1
95 /* Child process management list. */
96 int child_proc_count = 0;
97 child_process child_procs[ MAX_CHILDREN ];
98 child_process *dead_child = NULL;
100 static DWORD WINAPI reader_thread (void *arg);
102 /* Find an unused process slot. */
103 child_process *
104 new_child (void)
106 child_process *cp;
107 DWORD id;
109 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
110 if (!CHILD_ACTIVE (cp))
111 goto Initialize;
112 if (child_proc_count == MAX_CHILDREN)
113 return NULL;
114 cp = &child_procs[child_proc_count++];
116 Initialize:
117 memset (cp, 0, sizeof (*cp));
118 cp->fd = -1;
119 cp->pid = -1;
120 cp->procinfo.hProcess = NULL;
121 cp->status = STATUS_READ_ERROR;
123 /* use manual reset event so that select() will function properly */
124 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
125 if (cp->char_avail)
127 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
128 if (cp->char_consumed)
130 /* The 0x00010000 flag is STACK_SIZE_PARAM_IS_A_RESERVATION.
131 It means that the 64K stack we are requesting in the 2nd
132 argument is how much memory should be reserved for the
133 stack. If we don't use this flag, the memory requested
134 by the 2nd argument is the amount actually _committed_,
135 but Windows reserves 8MB of memory for each thread's
136 stack. (The 8MB figure comes from the -stack
137 command-line argument we pass to the linker when building
138 Emacs, but that's because we need a large stack for
139 Emacs's main thread.) Since we request 2GB of reserved
140 memory at startup (see w32heap.c), which is close to the
141 maximum memory available for a 32-bit process on Windows,
142 the 8MB reservation for each thread causes failures in
143 starting subprocesses, because we create a thread running
144 reader_thread for each subprocess. As 8MB of stack is
145 way too much for reader_thread, forcing Windows to
146 reserve less wins the day. */
147 cp->thrd = CreateThread (NULL, 64 * 1024, reader_thread, cp,
148 0x00010000, &id);
149 if (cp->thrd)
150 return cp;
153 delete_child (cp);
154 return NULL;
157 void
158 delete_child (child_process *cp)
160 int i;
162 /* Should not be deleting a child that is still needed. */
163 for (i = 0; i < MAXDESC; i++)
164 if (fd_info[i].cp == cp)
165 abort ();
167 if (!CHILD_ACTIVE (cp))
168 return;
170 /* reap thread if necessary */
171 if (cp->thrd)
173 DWORD rc;
175 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
177 /* let the thread exit cleanly if possible */
178 cp->status = STATUS_READ_ERROR;
179 SetEvent (cp->char_consumed);
180 #if 0
181 /* We used to forcibly terminate the thread here, but it
182 is normally unnecessary, and in abnormal cases, the worst that
183 will happen is we have an extra idle thread hanging around
184 waiting for the zombie process. */
185 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
187 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
188 "with %lu for fd %ld\n", GetLastError (), cp->fd));
189 TerminateThread (cp->thrd, 0);
191 #endif
193 CloseHandle (cp->thrd);
194 cp->thrd = NULL;
196 if (cp->char_avail)
198 CloseHandle (cp->char_avail);
199 cp->char_avail = NULL;
201 if (cp->char_consumed)
203 CloseHandle (cp->char_consumed);
204 cp->char_consumed = NULL;
207 /* update child_proc_count (highest numbered slot in use plus one) */
208 if (cp == child_procs + child_proc_count - 1)
210 for (i = child_proc_count-1; i >= 0; i--)
211 if (CHILD_ACTIVE (&child_procs[i]))
213 child_proc_count = i + 1;
214 break;
217 if (i < 0)
218 child_proc_count = 0;
221 /* Find a child by pid. */
222 static child_process *
223 find_child_pid (DWORD pid)
225 child_process *cp;
227 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
228 if (CHILD_ACTIVE (cp) && pid == cp->pid)
229 return cp;
230 return NULL;
234 /* Thread proc for child process and socket reader threads. Each thread
235 is normally blocked until woken by select() to check for input by
236 reading one char. When the read completes, char_avail is signaled
237 to wake up the select emulator and the thread blocks itself again. */
238 static DWORD WINAPI
239 reader_thread (void *arg)
241 child_process *cp;
243 /* Our identity */
244 cp = (child_process *)arg;
246 /* We have to wait for the go-ahead before we can start */
247 if (cp == NULL
248 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
249 || cp->fd < 0)
250 return 1;
252 for (;;)
254 int rc;
256 if (fd_info[cp->fd].flags & FILE_LISTEN)
257 rc = _sys_wait_accept (cp->fd);
258 else
259 rc = _sys_read_ahead (cp->fd);
261 /* The name char_avail is a misnomer - it really just means the
262 read-ahead has completed, whether successfully or not. */
263 if (!SetEvent (cp->char_avail))
265 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
266 GetLastError (), cp->fd));
267 return 1;
270 if (rc == STATUS_READ_ERROR)
271 return 1;
273 /* If the read died, the child has died so let the thread die */
274 if (rc == STATUS_READ_FAILED)
275 break;
277 /* Wait until our input is acknowledged before reading again */
278 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
280 DebPrint (("reader_thread.WaitForSingleObject failed with "
281 "%lu for fd %ld\n", GetLastError (), cp->fd));
282 break;
285 return 0;
288 /* To avoid Emacs changing directory, we just record here the directory
289 the new process should start in. This is set just before calling
290 sys_spawnve, and is not generally valid at any other time. */
291 static char * process_dir;
293 static BOOL
294 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
295 int * pPid, child_process *cp)
297 STARTUPINFO start;
298 SECURITY_ATTRIBUTES sec_attrs;
299 #if 0
300 SECURITY_DESCRIPTOR sec_desc;
301 #endif
302 DWORD flags;
303 char dir[ MAXPATHLEN ];
305 if (cp == NULL) abort ();
307 memset (&start, 0, sizeof (start));
308 start.cb = sizeof (start);
310 #ifdef HAVE_NTGUI
311 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
312 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
313 else
314 start.dwFlags = STARTF_USESTDHANDLES;
315 start.wShowWindow = SW_HIDE;
317 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
318 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
319 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
320 #endif /* HAVE_NTGUI */
322 #if 0
323 /* Explicitly specify no security */
324 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
325 goto EH_Fail;
326 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
327 goto EH_Fail;
328 #endif
329 sec_attrs.nLength = sizeof (sec_attrs);
330 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
331 sec_attrs.bInheritHandle = FALSE;
333 strcpy (dir, process_dir);
334 unixtodos_filename (dir);
336 flags = (!NILP (Vw32_start_process_share_console)
337 ? CREATE_NEW_PROCESS_GROUP
338 : CREATE_NEW_CONSOLE);
339 if (NILP (Vw32_start_process_inherit_error_mode))
340 flags |= CREATE_DEFAULT_ERROR_MODE;
341 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
342 flags, env, dir, &start, &cp->procinfo))
343 goto EH_Fail;
345 cp->pid = (int) cp->procinfo.dwProcessId;
347 /* Hack for Windows 95, which assigns large (ie negative) pids */
348 if (cp->pid < 0)
349 cp->pid = -cp->pid;
351 /* pid must fit in a Lisp_Int */
352 cp->pid = cp->pid & INTMASK;
354 *pPid = cp->pid;
356 return TRUE;
358 EH_Fail:
359 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
360 return FALSE;
363 /* create_child doesn't know what emacs' file handle will be for waiting
364 on output from the child, so we need to make this additional call
365 to register the handle with the process
366 This way the select emulator knows how to match file handles with
367 entries in child_procs. */
368 void
369 register_child (int pid, int fd)
371 child_process *cp;
373 cp = find_child_pid (pid);
374 if (cp == NULL)
376 DebPrint (("register_child unable to find pid %lu\n", pid));
377 return;
380 #ifdef FULL_DEBUG
381 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
382 #endif
384 cp->fd = fd;
386 /* thread is initially blocked until select is called; set status so
387 that select will release thread */
388 cp->status = STATUS_READ_ACKNOWLEDGED;
390 /* attach child_process to fd_info */
391 if (fd_info[fd].cp != NULL)
393 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
394 abort ();
397 fd_info[fd].cp = cp;
400 /* When a process dies its pipe will break so the reader thread will
401 signal failure to the select emulator.
402 The select emulator then calls this routine to clean up.
403 Since the thread signaled failure we can assume it is exiting. */
404 static void
405 reap_subprocess (child_process *cp)
407 if (cp->procinfo.hProcess)
409 /* Reap the process */
410 #ifdef FULL_DEBUG
411 /* Process should have already died before we are called. */
412 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
413 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
414 #endif
415 CloseHandle (cp->procinfo.hProcess);
416 cp->procinfo.hProcess = NULL;
417 CloseHandle (cp->procinfo.hThread);
418 cp->procinfo.hThread = NULL;
421 /* For asynchronous children, the child_proc resources will be freed
422 when the last pipe read descriptor is closed; for synchronous
423 children, we must explicitly free the resources now because
424 register_child has not been called. */
425 if (cp->fd == -1)
426 delete_child (cp);
429 /* Wait for any of our existing child processes to die
430 When it does, close its handle
431 Return the pid and fill in the status if non-NULL. */
434 sys_wait (int *status)
436 DWORD active, retval;
437 int nh;
438 int pid;
439 child_process *cp, *cps[MAX_CHILDREN];
440 HANDLE wait_hnd[MAX_CHILDREN];
442 nh = 0;
443 if (dead_child != NULL)
445 /* We want to wait for a specific child */
446 wait_hnd[nh] = dead_child->procinfo.hProcess;
447 cps[nh] = dead_child;
448 if (!wait_hnd[nh]) abort ();
449 nh++;
450 active = 0;
451 goto get_result;
453 else
455 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
456 /* some child_procs might be sockets; ignore them */
457 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
458 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
460 wait_hnd[nh] = cp->procinfo.hProcess;
461 cps[nh] = cp;
462 nh++;
466 if (nh == 0)
468 /* Nothing to wait on, so fail */
469 errno = ECHILD;
470 return -1;
475 /* Check for quit about once a second. */
476 QUIT;
477 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
478 } while (active == WAIT_TIMEOUT);
480 if (active == WAIT_FAILED)
482 errno = EBADF;
483 return -1;
485 else if (active >= WAIT_OBJECT_0
486 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
488 active -= WAIT_OBJECT_0;
490 else if (active >= WAIT_ABANDONED_0
491 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
493 active -= WAIT_ABANDONED_0;
495 else
496 abort ();
498 get_result:
499 if (!GetExitCodeProcess (wait_hnd[active], &retval))
501 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
502 GetLastError ()));
503 retval = 1;
505 if (retval == STILL_ACTIVE)
507 /* Should never happen */
508 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
509 errno = EINVAL;
510 return -1;
513 /* Massage the exit code from the process to match the format expected
514 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
515 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
517 if (retval == STATUS_CONTROL_C_EXIT)
518 retval = SIGINT;
519 else
520 retval <<= 8;
522 cp = cps[active];
523 pid = cp->pid;
524 #ifdef FULL_DEBUG
525 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
526 #endif
528 if (status)
530 *status = retval;
532 else if (synch_process_alive)
534 synch_process_alive = 0;
536 /* Report the status of the synchronous process. */
537 if (WIFEXITED (retval))
538 synch_process_retcode = WEXITSTATUS (retval);
539 else if (WIFSIGNALED (retval))
541 int code = WTERMSIG (retval);
542 char *signame;
544 synchronize_system_messages_locale ();
545 signame = strsignal (code);
547 if (signame == 0)
548 signame = "unknown";
550 synch_process_death = signame;
553 reap_subprocess (cp);
556 reap_subprocess (cp);
558 return pid;
561 /* Old versions of w32api headers don't have separate 32-bit and
562 64-bit defines, but the one they have matches the 32-bit variety. */
563 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
564 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
565 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
566 #endif
568 static void
569 w32_executable_type (char * filename,
570 int * is_dos_app,
571 int * is_cygnus_app,
572 int * is_gui_app)
574 file_data executable;
575 char * p;
577 /* Default values in case we can't tell for sure. */
578 *is_dos_app = FALSE;
579 *is_cygnus_app = FALSE;
580 *is_gui_app = FALSE;
582 if (!open_input_file (&executable, filename))
583 return;
585 p = strrchr (filename, '.');
587 /* We can only identify DOS .com programs from the extension. */
588 if (p && xstrcasecmp (p, ".com") == 0)
589 *is_dos_app = TRUE;
590 else if (p && (xstrcasecmp (p, ".bat") == 0
591 || xstrcasecmp (p, ".cmd") == 0))
593 /* A DOS shell script - it appears that CreateProcess is happy to
594 accept this (somewhat surprisingly); presumably it looks at
595 COMSPEC to determine what executable to actually invoke.
596 Therefore, we have to do the same here as well. */
597 /* Actually, I think it uses the program association for that
598 extension, which is defined in the registry. */
599 p = egetenv ("COMSPEC");
600 if (p)
601 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
603 else
605 /* Look for DOS .exe signature - if found, we must also check that
606 it isn't really a 16- or 32-bit Windows exe, since both formats
607 start with a DOS program stub. Note that 16-bit Windows
608 executables use the OS/2 1.x format. */
610 IMAGE_DOS_HEADER * dos_header;
611 IMAGE_NT_HEADERS * nt_header;
613 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
614 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
615 goto unwind;
617 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
619 if ((char *) nt_header > (char *) dos_header + executable.size)
621 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
622 *is_dos_app = TRUE;
624 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
625 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
627 *is_dos_app = TRUE;
629 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
631 IMAGE_DATA_DIRECTORY *data_dir = NULL;
632 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
634 /* Ensure we are using the 32 bit structure. */
635 IMAGE_OPTIONAL_HEADER32 *opt
636 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
637 data_dir = opt->DataDirectory;
638 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
640 /* MingW 3.12 has the required 64 bit structs, but in case older
641 versions don't, only check 64 bit exes if we know how. */
642 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
643 else if (nt_header->OptionalHeader.Magic
644 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
646 IMAGE_OPTIONAL_HEADER64 *opt
647 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
648 data_dir = opt->DataDirectory;
649 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
651 #endif
652 if (data_dir)
654 /* Look for cygwin.dll in DLL import list. */
655 IMAGE_DATA_DIRECTORY import_dir =
656 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
657 IMAGE_IMPORT_DESCRIPTOR * imports;
658 IMAGE_SECTION_HEADER * section;
660 section = rva_to_section (import_dir.VirtualAddress, nt_header);
661 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
662 executable);
664 for ( ; imports->Name; imports++)
666 char * dllname = RVA_TO_PTR (imports->Name, section,
667 executable);
669 /* The exact name of the cygwin dll has changed with
670 various releases, but hopefully this will be reasonably
671 future proof. */
672 if (strncmp (dllname, "cygwin", 6) == 0)
674 *is_cygnus_app = TRUE;
675 break;
682 unwind:
683 close_file_data (&executable);
686 static int
687 compare_env (const void *strp1, const void *strp2)
689 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
691 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
693 /* Sort order in command.com/cmd.exe is based on uppercasing
694 names, so do the same here. */
695 if (toupper (*str1) > toupper (*str2))
696 return 1;
697 else if (toupper (*str1) < toupper (*str2))
698 return -1;
699 str1++, str2++;
702 if (*str1 == '=' && *str2 == '=')
703 return 0;
704 else if (*str1 == '=')
705 return -1;
706 else
707 return 1;
710 static void
711 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
713 char **optr, **nptr;
714 int num;
716 nptr = new_envp;
717 optr = envp1;
718 while (*optr)
719 *nptr++ = *optr++;
720 num = optr - envp1;
722 optr = envp2;
723 while (*optr)
724 *nptr++ = *optr++;
725 num += optr - envp2;
727 qsort (new_envp, num, sizeof (char *), compare_env);
729 *nptr = NULL;
732 /* When a new child process is created we need to register it in our list,
733 so intercept spawn requests. */
735 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
737 Lisp_Object program, full;
738 char *cmdline, *env, *parg, **targ;
739 int arglen, numenv;
740 int pid;
741 child_process *cp;
742 int is_dos_app, is_cygnus_app, is_gui_app;
743 int do_quoting = 0;
744 char escape_char;
745 /* We pass our process ID to our children by setting up an environment
746 variable in their environment. */
747 char ppid_env_var_buffer[64];
748 char *extra_env[] = {ppid_env_var_buffer, NULL};
749 /* These are the characters that cause an argument to need quoting.
750 Arguments with whitespace characters need quoting to prevent the
751 argument being split into two or more. Arguments with wildcards
752 are also quoted, for consistency with posix platforms, where wildcards
753 are not expanded if we run the program directly without a shell.
754 Some extra whitespace characters need quoting in Cygwin programs,
755 so this list is conditionally modified below. */
756 char *sepchars = " \t*?";
758 /* We don't care about the other modes */
759 if (mode != _P_NOWAIT)
761 errno = EINVAL;
762 return -1;
765 /* Handle executable names without an executable suffix. */
766 program = build_string (cmdname);
767 if (NILP (Ffile_executable_p (program)))
769 struct gcpro gcpro1;
771 full = Qnil;
772 GCPRO1 (program);
773 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
774 UNGCPRO;
775 if (NILP (full))
777 errno = EINVAL;
778 return -1;
780 program = full;
783 /* make sure argv[0] and cmdname are both in DOS format */
784 cmdname = SDATA (program);
785 unixtodos_filename (cmdname);
786 argv[0] = cmdname;
788 /* Determine whether program is a 16-bit DOS executable, or a 32-bit Windows
789 executable that is implicitly linked to the Cygnus dll (implying it
790 was compiled with the Cygnus GNU toolchain and hence relies on
791 cygwin.dll to parse the command line - we use this to decide how to
792 escape quote chars in command line args that must be quoted).
794 Also determine whether it is a GUI app, so that we don't hide its
795 initial window unless specifically requested. */
796 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
798 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
799 application to start it by specifying the helper app as cmdname,
800 while leaving the real app name as argv[0]. */
801 if (is_dos_app)
803 cmdname = alloca (MAXPATHLEN);
804 if (egetenv ("CMDPROXY"))
805 strcpy (cmdname, egetenv ("CMDPROXY"));
806 else
808 strcpy (cmdname, SDATA (Vinvocation_directory));
809 strcat (cmdname, "cmdproxy.exe");
811 unixtodos_filename (cmdname);
814 /* we have to do some conjuring here to put argv and envp into the
815 form CreateProcess wants... argv needs to be a space separated/null
816 terminated list of parameters, and envp is a null
817 separated/double-null terminated list of parameters.
819 Additionally, zero-length args and args containing whitespace or
820 quote chars need to be wrapped in double quotes - for this to work,
821 embedded quotes need to be escaped as well. The aim is to ensure
822 the child process reconstructs the argv array we start with
823 exactly, so we treat quotes at the beginning and end of arguments
824 as embedded quotes.
826 The w32 GNU-based library from Cygnus doubles quotes to escape
827 them, while MSVC uses backslash for escaping. (Actually the MSVC
828 startup code does attempt to recognize doubled quotes and accept
829 them, but gets it wrong and ends up requiring three quotes to get a
830 single embedded quote!) So by default we decide whether to use
831 quote or backslash as the escape character based on whether the
832 binary is apparently a Cygnus compiled app.
834 Note that using backslash to escape embedded quotes requires
835 additional special handling if an embedded quote is already
836 preceded by backslash, or if an arg requiring quoting ends with
837 backslash. In such cases, the run of escape characters needs to be
838 doubled. For consistency, we apply this special handling as long
839 as the escape character is not quote.
841 Since we have no idea how large argv and envp are likely to be we
842 figure out list lengths on the fly and allocate them. */
844 if (!NILP (Vw32_quote_process_args))
846 do_quoting = 1;
847 /* Override escape char by binding w32-quote-process-args to
848 desired character, or use t for auto-selection. */
849 if (INTEGERP (Vw32_quote_process_args))
850 escape_char = XINT (Vw32_quote_process_args);
851 else
852 escape_char = is_cygnus_app ? '"' : '\\';
855 /* Cygwin apps needs quoting a bit more often. */
856 if (escape_char == '"')
857 sepchars = "\r\n\t\f '";
859 /* do argv... */
860 arglen = 0;
861 targ = argv;
862 while (*targ)
864 char * p = *targ;
865 int need_quotes = 0;
866 int escape_char_run = 0;
868 if (*p == 0)
869 need_quotes = 1;
870 for ( ; *p; p++)
872 if (escape_char == '"' && *p == '\\')
873 /* If it's a Cygwin app, \ needs to be escaped. */
874 arglen++;
875 else if (*p == '"')
877 /* allow for embedded quotes to be escaped */
878 arglen++;
879 need_quotes = 1;
880 /* handle the case where the embedded quote is already escaped */
881 if (escape_char_run > 0)
883 /* To preserve the arg exactly, we need to double the
884 preceding escape characters (plus adding one to
885 escape the quote character itself). */
886 arglen += escape_char_run;
889 else if (strchr (sepchars, *p) != NULL)
891 need_quotes = 1;
894 if (*p == escape_char && escape_char != '"')
895 escape_char_run++;
896 else
897 escape_char_run = 0;
899 if (need_quotes)
901 arglen += 2;
902 /* handle the case where the arg ends with an escape char - we
903 must not let the enclosing quote be escaped. */
904 if (escape_char_run > 0)
905 arglen += escape_char_run;
907 arglen += strlen (*targ++) + 1;
909 cmdline = alloca (arglen);
910 targ = argv;
911 parg = cmdline;
912 while (*targ)
914 char * p = *targ;
915 int need_quotes = 0;
917 if (*p == 0)
918 need_quotes = 1;
920 if (do_quoting)
922 for ( ; *p; p++)
923 if ((strchr (sepchars, *p) != NULL) || *p == '"')
924 need_quotes = 1;
926 if (need_quotes)
928 int escape_char_run = 0;
929 char * first;
930 char * last;
932 p = *targ;
933 first = p;
934 last = p + strlen (p) - 1;
935 *parg++ = '"';
936 #if 0
937 /* This version does not escape quotes if they occur at the
938 beginning or end of the arg - this could lead to incorrect
939 behavior when the arg itself represents a command line
940 containing quoted args. I believe this was originally done
941 as a hack to make some things work, before
942 `w32-quote-process-args' was added. */
943 while (*p)
945 if (*p == '"' && p > first && p < last)
946 *parg++ = escape_char; /* escape embedded quotes */
947 *parg++ = *p++;
949 #else
950 for ( ; *p; p++)
952 if (*p == '"')
954 /* double preceding escape chars if any */
955 while (escape_char_run > 0)
957 *parg++ = escape_char;
958 escape_char_run--;
960 /* escape all quote chars, even at beginning or end */
961 *parg++ = escape_char;
963 else if (escape_char == '"' && *p == '\\')
964 *parg++ = '\\';
965 *parg++ = *p;
967 if (*p == escape_char && escape_char != '"')
968 escape_char_run++;
969 else
970 escape_char_run = 0;
972 /* double escape chars before enclosing quote */
973 while (escape_char_run > 0)
975 *parg++ = escape_char;
976 escape_char_run--;
978 #endif
979 *parg++ = '"';
981 else
983 strcpy (parg, *targ);
984 parg += strlen (*targ);
986 *parg++ = ' ';
987 targ++;
989 *--parg = '\0';
991 /* and envp... */
992 arglen = 1;
993 targ = envp;
994 numenv = 1; /* for end null */
995 while (*targ)
997 arglen += strlen (*targ++) + 1;
998 numenv++;
1000 /* extra env vars... */
1001 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1002 GetCurrentProcessId ());
1003 arglen += strlen (ppid_env_var_buffer) + 1;
1004 numenv++;
1006 /* merge env passed in and extra env into one, and sort it. */
1007 targ = (char **) alloca (numenv * sizeof (char *));
1008 merge_and_sort_env (envp, extra_env, targ);
1010 /* concatenate env entries. */
1011 env = alloca (arglen);
1012 parg = env;
1013 while (*targ)
1015 strcpy (parg, *targ);
1016 parg += strlen (*targ++);
1017 *parg++ = '\0';
1019 *parg++ = '\0';
1020 *parg = '\0';
1022 cp = new_child ();
1023 if (cp == NULL)
1025 errno = EAGAIN;
1026 return -1;
1029 /* Now create the process. */
1030 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1032 delete_child (cp);
1033 errno = ENOEXEC;
1034 return -1;
1037 return pid;
1040 /* Emulate the select call
1041 Wait for available input on any of the given rfds, or timeout if
1042 a timeout is given and no input is detected
1043 wfds and efds are not supported and must be NULL.
1045 For simplicity, we detect the death of child processes here and
1046 synchronously call the SIGCHLD handler. Since it is possible for
1047 children to be created without a corresponding pipe handle from which
1048 to read output, we wait separately on the process handles as well as
1049 the char_avail events for each process pipe. We only call
1050 wait/reap_process when the process actually terminates.
1052 To reduce the number of places in which Emacs can be hung such that
1053 C-g is not able to interrupt it, we always wait on interrupt_handle
1054 (which is signaled by the input thread when C-g is detected). If we
1055 detect that we were woken up by C-g, we return -1 with errno set to
1056 EINTR as on Unix. */
1058 /* From w32console.c */
1059 extern HANDLE keyboard_handle;
1061 /* From w32xfns.c */
1062 extern HANDLE interrupt_handle;
1064 /* From process.c */
1065 extern int proc_buffered_char[];
1068 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1069 EMACS_TIME *timeout, void *ignored)
1071 SELECT_TYPE orfds;
1072 DWORD timeout_ms, start_time;
1073 int i, nh, nc, nr;
1074 DWORD active;
1075 child_process *cp, *cps[MAX_CHILDREN];
1076 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1077 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1079 timeout_ms =
1080 timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 1000000) : INFINITE;
1082 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1083 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1085 Sleep (timeout_ms);
1086 return 0;
1089 /* Otherwise, we only handle rfds, so fail otherwise. */
1090 if (rfds == NULL || wfds != NULL || efds != NULL)
1092 errno = EINVAL;
1093 return -1;
1096 orfds = *rfds;
1097 FD_ZERO (rfds);
1098 nr = 0;
1100 /* Always wait on interrupt_handle, to detect C-g (quit). */
1101 wait_hnd[0] = interrupt_handle;
1102 fdindex[0] = -1;
1104 /* Build a list of pipe handles to wait on. */
1105 nh = 1;
1106 for (i = 0; i < nfds; i++)
1107 if (FD_ISSET (i, &orfds))
1109 if (i == 0)
1111 if (keyboard_handle)
1113 /* Handle stdin specially */
1114 wait_hnd[nh] = keyboard_handle;
1115 fdindex[nh] = i;
1116 nh++;
1119 /* Check for any emacs-generated input in the queue since
1120 it won't be detected in the wait */
1121 if (detect_input_pending ())
1123 FD_SET (i, rfds);
1124 return 1;
1127 else
1129 /* Child process and socket input */
1130 cp = fd_info[i].cp;
1131 if (cp)
1133 int current_status = cp->status;
1135 if (current_status == STATUS_READ_ACKNOWLEDGED)
1137 /* Tell reader thread which file handle to use. */
1138 cp->fd = i;
1139 /* Wake up the reader thread for this process */
1140 cp->status = STATUS_READ_READY;
1141 if (!SetEvent (cp->char_consumed))
1142 DebPrint (("nt_select.SetEvent failed with "
1143 "%lu for fd %ld\n", GetLastError (), i));
1146 #ifdef CHECK_INTERLOCK
1147 /* slightly crude cross-checking of interlock between threads */
1149 current_status = cp->status;
1150 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1152 /* char_avail has been signaled, so status (which may
1153 have changed) should indicate read has completed
1154 but has not been acknowledged. */
1155 current_status = cp->status;
1156 if (current_status != STATUS_READ_SUCCEEDED
1157 && current_status != STATUS_READ_FAILED)
1158 DebPrint (("char_avail set, but read not completed: status %d\n",
1159 current_status));
1161 else
1163 /* char_avail has not been signaled, so status should
1164 indicate that read is in progress; small possibility
1165 that read has completed but event wasn't yet signaled
1166 when we tested it (because a context switch occurred
1167 or if running on separate CPUs). */
1168 if (current_status != STATUS_READ_READY
1169 && current_status != STATUS_READ_IN_PROGRESS
1170 && current_status != STATUS_READ_SUCCEEDED
1171 && current_status != STATUS_READ_FAILED)
1172 DebPrint (("char_avail reset, but read status is bad: %d\n",
1173 current_status));
1175 #endif
1176 wait_hnd[nh] = cp->char_avail;
1177 fdindex[nh] = i;
1178 if (!wait_hnd[nh]) abort ();
1179 nh++;
1180 #ifdef FULL_DEBUG
1181 DebPrint (("select waiting on child %d fd %d\n",
1182 cp-child_procs, i));
1183 #endif
1185 else
1187 /* Unable to find something to wait on for this fd, skip */
1189 /* Note that this is not a fatal error, and can in fact
1190 happen in unusual circumstances. Specifically, if
1191 sys_spawnve fails, eg. because the program doesn't
1192 exist, and debug-on-error is t so Fsignal invokes a
1193 nested input loop, then the process output pipe is
1194 still included in input_wait_mask with no child_proc
1195 associated with it. (It is removed when the debugger
1196 exits the nested input loop and the error is thrown.) */
1198 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1203 count_children:
1204 /* Add handles of child processes. */
1205 nc = 0;
1206 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1207 /* Some child_procs might be sockets; ignore them. Also some
1208 children may have died already, but we haven't finished reading
1209 the process output; ignore them too. */
1210 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1211 && (cp->fd < 0
1212 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1213 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1216 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1217 cps[nc] = cp;
1218 nc++;
1221 /* Nothing to look for, so we didn't find anything */
1222 if (nh + nc == 0)
1224 if (timeout)
1225 Sleep (timeout_ms);
1226 return 0;
1229 start_time = GetTickCount ();
1231 /* Wait for input or child death to be signaled. If user input is
1232 allowed, then also accept window messages. */
1233 if (FD_ISSET (0, &orfds))
1234 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1235 QS_ALLINPUT);
1236 else
1237 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1239 if (active == WAIT_FAILED)
1241 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1242 nh + nc, timeout_ms, GetLastError ()));
1243 /* don't return EBADF - this causes wait_reading_process_output to
1244 abort; WAIT_FAILED is returned when single-stepping under
1245 Windows 95 after switching thread focus in debugger, and
1246 possibly at other times. */
1247 errno = EINTR;
1248 return -1;
1250 else if (active == WAIT_TIMEOUT)
1252 return 0;
1254 else if (active >= WAIT_OBJECT_0
1255 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1257 active -= WAIT_OBJECT_0;
1259 else if (active >= WAIT_ABANDONED_0
1260 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1262 active -= WAIT_ABANDONED_0;
1264 else
1265 abort ();
1267 /* Loop over all handles after active (now officially documented as
1268 being the first signaled handle in the array). We do this to
1269 ensure fairness, so that all channels with data available will be
1270 processed - otherwise higher numbered channels could be starved. */
1273 if (active == nh + nc)
1275 /* There are messages in the lisp thread's queue; we must
1276 drain the queue now to ensure they are processed promptly,
1277 because if we don't do so, we will not be woken again until
1278 further messages arrive.
1280 NB. If ever we allow window message procedures to callback
1281 into lisp, we will need to ensure messages are dispatched
1282 at a safe time for lisp code to be run (*), and we may also
1283 want to provide some hooks in the dispatch loop to cater
1284 for modeless dialogs created by lisp (ie. to register
1285 window handles to pass to IsDialogMessage).
1287 (*) Note that MsgWaitForMultipleObjects above is an
1288 internal dispatch point for messages that are sent to
1289 windows created by this thread. */
1290 drain_message_queue ();
1292 else if (active >= nh)
1294 cp = cps[active - nh];
1296 /* We cannot always signal SIGCHLD immediately; if we have not
1297 finished reading the process output, we must delay sending
1298 SIGCHLD until we do. */
1300 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1301 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1302 /* SIG_DFL for SIGCHLD is ignore */
1303 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1304 sig_handlers[SIGCHLD] != SIG_IGN)
1306 #ifdef FULL_DEBUG
1307 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1308 cp->pid));
1309 #endif
1310 dead_child = cp;
1311 sig_handlers[SIGCHLD] (SIGCHLD);
1312 dead_child = NULL;
1315 else if (fdindex[active] == -1)
1317 /* Quit (C-g) was detected. */
1318 errno = EINTR;
1319 return -1;
1321 else if (fdindex[active] == 0)
1323 /* Keyboard input available */
1324 FD_SET (0, rfds);
1325 nr++;
1327 else
1329 /* must be a socket or pipe - read ahead should have
1330 completed, either succeeding or failing. */
1331 FD_SET (fdindex[active], rfds);
1332 nr++;
1335 /* Even though wait_reading_process_output only reads from at most
1336 one channel, we must process all channels here so that we reap
1337 all children that have died. */
1338 while (++active < nh + nc)
1339 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1340 break;
1341 } while (active < nh + nc);
1343 /* If no input has arrived and timeout hasn't expired, wait again. */
1344 if (nr == 0)
1346 DWORD elapsed = GetTickCount () - start_time;
1348 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1350 if (timeout_ms != INFINITE)
1351 timeout_ms -= elapsed;
1352 goto count_children;
1356 return nr;
1359 /* Substitute for certain kill () operations */
1361 static BOOL CALLBACK
1362 find_child_console (HWND hwnd, LPARAM arg)
1364 child_process * cp = (child_process *) arg;
1365 DWORD thread_id;
1366 DWORD process_id;
1368 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1369 if (process_id == cp->procinfo.dwProcessId)
1371 char window_class[32];
1373 GetClassName (hwnd, window_class, sizeof (window_class));
1374 if (strcmp (window_class,
1375 (os_subtype == OS_9X)
1376 ? "tty"
1377 : "ConsoleWindowClass") == 0)
1379 cp->hwnd = hwnd;
1380 return FALSE;
1383 /* keep looking */
1384 return TRUE;
1388 sys_kill (int pid, int sig)
1390 child_process *cp;
1391 HANDLE proc_hand;
1392 int need_to_free = 0;
1393 int rc = 0;
1395 /* Only handle signals that will result in the process dying */
1396 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1398 errno = EINVAL;
1399 return -1;
1402 cp = find_child_pid (pid);
1403 if (cp == NULL)
1405 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1406 if (proc_hand == NULL)
1408 errno = EPERM;
1409 return -1;
1411 need_to_free = 1;
1413 else
1415 proc_hand = cp->procinfo.hProcess;
1416 pid = cp->procinfo.dwProcessId;
1418 /* Try to locate console window for process. */
1419 EnumWindows (find_child_console, (LPARAM) cp);
1422 if (sig == SIGINT || sig == SIGQUIT)
1424 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1426 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1427 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1428 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1429 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1430 HWND foreground_window;
1432 if (break_scan_code == 0)
1434 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1435 vk_break_code = 'C';
1436 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1439 foreground_window = GetForegroundWindow ();
1440 if (foreground_window)
1442 /* NT 5.0, and apparently also Windows 98, will not allow
1443 a Window to be set to foreground directly without the
1444 user's involvement. The workaround is to attach
1445 ourselves to the thread that owns the foreground
1446 window, since that is the only thread that can set the
1447 foreground window. */
1448 DWORD foreground_thread, child_thread;
1449 foreground_thread =
1450 GetWindowThreadProcessId (foreground_window, NULL);
1451 if (foreground_thread == GetCurrentThreadId ()
1452 || !AttachThreadInput (GetCurrentThreadId (),
1453 foreground_thread, TRUE))
1454 foreground_thread = 0;
1456 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1457 if (child_thread == GetCurrentThreadId ()
1458 || !AttachThreadInput (GetCurrentThreadId (),
1459 child_thread, TRUE))
1460 child_thread = 0;
1462 /* Set the foreground window to the child. */
1463 if (SetForegroundWindow (cp->hwnd))
1465 /* Generate keystrokes as if user had typed Ctrl-Break or
1466 Ctrl-C. */
1467 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1468 keybd_event (vk_break_code, break_scan_code,
1469 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1470 keybd_event (vk_break_code, break_scan_code,
1471 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1472 | KEYEVENTF_KEYUP, 0);
1473 keybd_event (VK_CONTROL, control_scan_code,
1474 KEYEVENTF_KEYUP, 0);
1476 /* Sleep for a bit to give time for Emacs frame to respond
1477 to focus change events (if Emacs was active app). */
1478 Sleep (100);
1480 SetForegroundWindow (foreground_window);
1482 /* Detach from the foreground and child threads now that
1483 the foreground switching is over. */
1484 if (foreground_thread)
1485 AttachThreadInput (GetCurrentThreadId (),
1486 foreground_thread, FALSE);
1487 if (child_thread)
1488 AttachThreadInput (GetCurrentThreadId (),
1489 child_thread, FALSE);
1492 /* Ctrl-Break is NT equivalent of SIGINT. */
1493 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1495 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1496 "for pid %lu\n", GetLastError (), pid));
1497 errno = EINVAL;
1498 rc = -1;
1501 else
1503 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1505 #if 1
1506 if (os_subtype == OS_9X)
1509 Another possibility is to try terminating the VDM out-right by
1510 calling the Shell VxD (id 0x17) V86 interface, function #4
1511 "SHELL_Destroy_VM", ie.
1513 mov edx,4
1514 mov ebx,vm_handle
1515 call shellapi
1517 First need to determine the current VM handle, and then arrange for
1518 the shellapi call to be made from the system vm (by using
1519 Switch_VM_and_callback).
1521 Could try to invoke DestroyVM through CallVxD.
1524 #if 0
1525 /* On Windows 95, posting WM_QUIT causes the 16-bit subsystem
1526 to hang when cmdproxy is used in conjunction with
1527 command.com for an interactive shell. Posting
1528 WM_CLOSE pops up a dialog that, when Yes is selected,
1529 does the same thing. TerminateProcess is also less
1530 than ideal in that subprocesses tend to stick around
1531 until the machine is shutdown, but at least it
1532 doesn't freeze the 16-bit subsystem. */
1533 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1534 #endif
1535 if (!TerminateProcess (proc_hand, 0xff))
1537 DebPrint (("sys_kill.TerminateProcess returned %d "
1538 "for pid %lu\n", GetLastError (), pid));
1539 errno = EINVAL;
1540 rc = -1;
1543 else
1544 #endif
1545 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1547 /* Kill the process. On W32 this doesn't kill child processes
1548 so it doesn't work very well for shells which is why it's not
1549 used in every case. */
1550 else if (!TerminateProcess (proc_hand, 0xff))
1552 DebPrint (("sys_kill.TerminateProcess returned %d "
1553 "for pid %lu\n", GetLastError (), pid));
1554 errno = EINVAL;
1555 rc = -1;
1559 if (need_to_free)
1560 CloseHandle (proc_hand);
1562 return rc;
1565 /* The following two routines are used to manipulate stdin, stdout, and
1566 stderr of our child processes.
1568 Assuming that in, out, and err are *not* inheritable, we make them
1569 stdin, stdout, and stderr of the child as follows:
1571 - Save the parent's current standard handles.
1572 - Set the std handles to inheritable duplicates of the ones being passed in.
1573 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1574 NT file handle for a crt file descriptor.)
1575 - Spawn the child, which inherits in, out, and err as stdin,
1576 stdout, and stderr. (see Spawnve)
1577 - Close the std handles passed to the child.
1578 - Reset the parent's standard handles to the saved handles.
1579 (see reset_standard_handles)
1580 We assume that the caller closes in, out, and err after calling us. */
1582 void
1583 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1585 HANDLE parent;
1586 HANDLE newstdin, newstdout, newstderr;
1588 parent = GetCurrentProcess ();
1590 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1591 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1592 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1594 /* make inheritable copies of the new handles */
1595 if (!DuplicateHandle (parent,
1596 (HANDLE) _get_osfhandle (in),
1597 parent,
1598 &newstdin,
1600 TRUE,
1601 DUPLICATE_SAME_ACCESS))
1602 report_file_error ("Duplicating input handle for child", Qnil);
1604 if (!DuplicateHandle (parent,
1605 (HANDLE) _get_osfhandle (out),
1606 parent,
1607 &newstdout,
1609 TRUE,
1610 DUPLICATE_SAME_ACCESS))
1611 report_file_error ("Duplicating output handle for child", Qnil);
1613 if (!DuplicateHandle (parent,
1614 (HANDLE) _get_osfhandle (err),
1615 parent,
1616 &newstderr,
1618 TRUE,
1619 DUPLICATE_SAME_ACCESS))
1620 report_file_error ("Duplicating error handle for child", Qnil);
1622 /* and store them as our std handles */
1623 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1624 report_file_error ("Changing stdin handle", Qnil);
1626 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1627 report_file_error ("Changing stdout handle", Qnil);
1629 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1630 report_file_error ("Changing stderr handle", Qnil);
1633 void
1634 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1636 /* close the duplicated handles passed to the child */
1637 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1638 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1639 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1641 /* now restore parent's saved std handles */
1642 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1643 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1644 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1647 void
1648 set_process_dir (char * dir)
1650 process_dir = dir;
1653 /* To avoid problems with winsock implementations that work over dial-up
1654 connections causing or requiring a connection to exist while Emacs is
1655 running, Emacs no longer automatically loads winsock on startup if it
1656 is present. Instead, it will be loaded when open-network-stream is
1657 first called.
1659 To allow full control over when winsock is loaded, we provide these
1660 two functions to dynamically load and unload winsock. This allows
1661 dial-up users to only be connected when they actually need to use
1662 socket services. */
1664 /* From w32.c */
1665 extern HANDLE winsock_lib;
1666 extern BOOL term_winsock (void);
1667 extern BOOL init_winsock (int load_now);
1669 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1670 doc: /* Test for presence of the Windows socket library `winsock'.
1671 Returns non-nil if winsock support is present, nil otherwise.
1673 If the optional argument LOAD-NOW is non-nil, the winsock library is
1674 also loaded immediately if not already loaded. If winsock is loaded,
1675 the winsock local hostname is returned (since this may be different from
1676 the value of `system-name' and should supplant it), otherwise t is
1677 returned to indicate winsock support is present. */)
1678 (Lisp_Object load_now)
1680 int have_winsock;
1682 have_winsock = init_winsock (!NILP (load_now));
1683 if (have_winsock)
1685 if (winsock_lib != NULL)
1687 /* Return new value for system-name. The best way to do this
1688 is to call init_system_name, saving and restoring the
1689 original value to avoid side-effects. */
1690 Lisp_Object orig_hostname = Vsystem_name;
1691 Lisp_Object hostname;
1693 init_system_name ();
1694 hostname = Vsystem_name;
1695 Vsystem_name = orig_hostname;
1696 return hostname;
1698 return Qt;
1700 return Qnil;
1703 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1704 0, 0, 0,
1705 doc: /* Unload the Windows socket library `winsock' if loaded.
1706 This is provided to allow dial-up socket connections to be disconnected
1707 when no longer needed. Returns nil without unloading winsock if any
1708 socket connections still exist. */)
1709 (void)
1711 return term_winsock () ? Qt : Qnil;
1715 /* Some miscellaneous functions that are Windows specific, but not GUI
1716 specific (ie. are applicable in terminal or batch mode as well). */
1718 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1719 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1720 If FILENAME does not exist, return nil.
1721 All path elements in FILENAME are converted to their short names. */)
1722 (Lisp_Object filename)
1724 char shortname[MAX_PATH];
1726 CHECK_STRING (filename);
1728 /* first expand it. */
1729 filename = Fexpand_file_name (filename, Qnil);
1731 /* luckily, this returns the short version of each element in the path. */
1732 if (GetShortPathName (SDATA (ENCODE_FILE (filename)), shortname, MAX_PATH) == 0)
1733 return Qnil;
1735 dostounix_filename (shortname);
1737 return build_string (shortname);
1741 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1742 1, 1, 0,
1743 doc: /* Return the long file name version of the full path of FILENAME.
1744 If FILENAME does not exist, return nil.
1745 All path elements in FILENAME are converted to their long names. */)
1746 (Lisp_Object filename)
1748 char longname[ MAX_PATH ];
1749 int drive_only = 0;
1751 CHECK_STRING (filename);
1753 if (SBYTES (filename) == 2
1754 && *(SDATA (filename) + 1) == ':')
1755 drive_only = 1;
1757 /* first expand it. */
1758 filename = Fexpand_file_name (filename, Qnil);
1760 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename)), longname, MAX_PATH))
1761 return Qnil;
1763 dostounix_filename (longname);
1765 /* If we were passed only a drive, make sure that a slash is not appended
1766 for consistency with directories. Allow for drive mapping via SUBST
1767 in case expand-file-name is ever changed to expand those. */
1768 if (drive_only && longname[1] == ':' && longname[2] == '/' && !longname[3])
1769 longname[2] = '\0';
1771 return DECODE_FILE (build_string (longname));
1774 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1775 Sw32_set_process_priority, 2, 2, 0,
1776 doc: /* Set the priority of PROCESS to PRIORITY.
1777 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1778 priority of the process whose pid is PROCESS is changed.
1779 PRIORITY should be one of the symbols high, normal, or low;
1780 any other symbol will be interpreted as normal.
1782 If successful, the return value is t, otherwise nil. */)
1783 (Lisp_Object process, Lisp_Object priority)
1785 HANDLE proc_handle = GetCurrentProcess ();
1786 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1787 Lisp_Object result = Qnil;
1789 CHECK_SYMBOL (priority);
1791 if (!NILP (process))
1793 DWORD pid;
1794 child_process *cp;
1796 CHECK_NUMBER (process);
1798 /* Allow pid to be an internally generated one, or one obtained
1799 externally. This is necessary because real pids on Windows 95 are
1800 negative. */
1802 pid = XINT (process);
1803 cp = find_child_pid (pid);
1804 if (cp != NULL)
1805 pid = cp->procinfo.dwProcessId;
1807 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1810 if (EQ (priority, Qhigh))
1811 priority_class = HIGH_PRIORITY_CLASS;
1812 else if (EQ (priority, Qlow))
1813 priority_class = IDLE_PRIORITY_CLASS;
1815 if (proc_handle != NULL)
1817 if (SetPriorityClass (proc_handle, priority_class))
1818 result = Qt;
1819 if (!NILP (process))
1820 CloseHandle (proc_handle);
1823 return result;
1826 #ifdef HAVE_LANGINFO_CODESET
1827 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1828 char *
1829 nl_langinfo (nl_item item)
1831 /* Conversion of Posix item numbers to their Windows equivalents. */
1832 static const LCTYPE w32item[] = {
1833 LOCALE_IDEFAULTANSICODEPAGE,
1834 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1835 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1836 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1837 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1838 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1839 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1842 static char *nl_langinfo_buf = NULL;
1843 static int nl_langinfo_len = 0;
1845 if (nl_langinfo_len <= 0)
1846 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1848 if (item < 0 || item >= _NL_NUM)
1849 nl_langinfo_buf[0] = 0;
1850 else
1852 LCID cloc = GetThreadLocale ();
1853 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1854 NULL, 0);
1856 if (need_len <= 0)
1857 nl_langinfo_buf[0] = 0;
1858 else
1860 if (item == CODESET)
1862 need_len += 2; /* for the "cp" prefix */
1863 if (need_len < 8) /* for the case we call GetACP */
1864 need_len = 8;
1866 if (nl_langinfo_len <= need_len)
1867 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1868 nl_langinfo_len = need_len);
1869 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1870 nl_langinfo_buf, nl_langinfo_len))
1871 nl_langinfo_buf[0] = 0;
1872 else if (item == CODESET)
1874 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1875 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1876 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1877 else
1879 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1880 strlen (nl_langinfo_buf) + 1);
1881 nl_langinfo_buf[0] = 'c';
1882 nl_langinfo_buf[1] = 'p';
1887 return nl_langinfo_buf;
1889 #endif /* HAVE_LANGINFO_CODESET */
1891 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1892 Sw32_get_locale_info, 1, 2, 0,
1893 doc: /* Return information about the Windows locale LCID.
1894 By default, return a three letter locale code which encodes the default
1895 language as the first two characters, and the country or regional variant
1896 as the third letter. For example, ENU refers to `English (United States)',
1897 while ENC means `English (Canadian)'.
1899 If the optional argument LONGFORM is t, the long form of the locale
1900 name is returned, e.g. `English (United States)' instead; if LONGFORM
1901 is a number, it is interpreted as an LCTYPE constant and the corresponding
1902 locale information is returned.
1904 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1905 (Lisp_Object lcid, Lisp_Object longform)
1907 int got_abbrev;
1908 int got_full;
1909 char abbrev_name[32] = { 0 };
1910 char full_name[256] = { 0 };
1912 CHECK_NUMBER (lcid);
1914 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1915 return Qnil;
1917 if (NILP (longform))
1919 got_abbrev = GetLocaleInfo (XINT (lcid),
1920 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1921 abbrev_name, sizeof (abbrev_name));
1922 if (got_abbrev)
1923 return build_string (abbrev_name);
1925 else if (EQ (longform, Qt))
1927 got_full = GetLocaleInfo (XINT (lcid),
1928 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1929 full_name, sizeof (full_name));
1930 if (got_full)
1931 return DECODE_SYSTEM (build_string (full_name));
1933 else if (NUMBERP (longform))
1935 got_full = GetLocaleInfo (XINT (lcid),
1936 XINT (longform),
1937 full_name, sizeof (full_name));
1938 /* GetLocaleInfo's return value includes the terminating null
1939 character, when the returned information is a string, whereas
1940 make_unibyte_string needs the string length without the
1941 terminating null. */
1942 if (got_full)
1943 return make_unibyte_string (full_name, got_full - 1);
1946 return Qnil;
1950 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1951 Sw32_get_current_locale_id, 0, 0, 0,
1952 doc: /* Return Windows locale id for current locale setting.
1953 This is a numerical value; use `w32-get-locale-info' to convert to a
1954 human-readable form. */)
1955 (void)
1957 return make_number (GetThreadLocale ());
1960 static DWORD
1961 int_from_hex (char * s)
1963 DWORD val = 0;
1964 static char hex[] = "0123456789abcdefABCDEF";
1965 char * p;
1967 while (*s && (p = strchr (hex, *s)) != NULL)
1969 unsigned digit = p - hex;
1970 if (digit > 15)
1971 digit -= 6;
1972 val = val * 16 + digit;
1973 s++;
1975 return val;
1978 /* We need to build a global list, since the EnumSystemLocale callback
1979 function isn't given a context pointer. */
1980 Lisp_Object Vw32_valid_locale_ids;
1982 static BOOL CALLBACK
1983 enum_locale_fn (LPTSTR localeNum)
1985 DWORD id = int_from_hex (localeNum);
1986 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
1987 return TRUE;
1990 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
1991 Sw32_get_valid_locale_ids, 0, 0, 0,
1992 doc: /* Return list of all valid Windows locale ids.
1993 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1994 human-readable form. */)
1995 (void)
1997 Vw32_valid_locale_ids = Qnil;
1999 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2001 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2002 return Vw32_valid_locale_ids;
2006 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2007 doc: /* Return Windows locale id for default locale setting.
2008 By default, the system default locale setting is returned; if the optional
2009 parameter USERP is non-nil, the user default locale setting is returned.
2010 This is a numerical value; use `w32-get-locale-info' to convert to a
2011 human-readable form. */)
2012 (Lisp_Object userp)
2014 if (NILP (userp))
2015 return make_number (GetSystemDefaultLCID ());
2016 return make_number (GetUserDefaultLCID ());
2020 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2021 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2022 If successful, the new locale id is returned, otherwise nil. */)
2023 (Lisp_Object lcid)
2025 CHECK_NUMBER (lcid);
2027 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2028 return Qnil;
2030 if (!SetThreadLocale (XINT (lcid)))
2031 return Qnil;
2033 /* Need to set input thread locale if present. */
2034 if (dwWindowsThreadId)
2035 /* Reply is not needed. */
2036 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2038 return make_number (GetThreadLocale ());
2042 /* We need to build a global list, since the EnumCodePages callback
2043 function isn't given a context pointer. */
2044 Lisp_Object Vw32_valid_codepages;
2046 static BOOL CALLBACK
2047 enum_codepage_fn (LPTSTR codepageNum)
2049 DWORD id = atoi (codepageNum);
2050 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2051 return TRUE;
2054 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2055 Sw32_get_valid_codepages, 0, 0, 0,
2056 doc: /* Return list of all valid Windows codepages. */)
2057 (void)
2059 Vw32_valid_codepages = Qnil;
2061 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2063 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2064 return Vw32_valid_codepages;
2068 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2069 Sw32_get_console_codepage, 0, 0, 0,
2070 doc: /* Return current Windows codepage for console input. */)
2071 (void)
2073 return make_number (GetConsoleCP ());
2077 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2078 Sw32_set_console_codepage, 1, 1, 0,
2079 doc: /* Make Windows codepage CP be the codepage for Emacs tty keyboard input.
2080 This codepage setting affects keyboard input in tty mode.
2081 If successful, the new CP is returned, otherwise nil. */)
2082 (Lisp_Object cp)
2084 CHECK_NUMBER (cp);
2086 if (!IsValidCodePage (XINT (cp)))
2087 return Qnil;
2089 if (!SetConsoleCP (XINT (cp)))
2090 return Qnil;
2092 return make_number (GetConsoleCP ());
2096 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2097 Sw32_get_console_output_codepage, 0, 0, 0,
2098 doc: /* Return current Windows codepage for console output. */)
2099 (void)
2101 return make_number (GetConsoleOutputCP ());
2105 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2106 Sw32_set_console_output_codepage, 1, 1, 0,
2107 doc: /* Make Windows codepage CP be the codepage for Emacs console output.
2108 This codepage setting affects display in tty mode.
2109 If successful, the new CP is returned, otherwise nil. */)
2110 (Lisp_Object cp)
2112 CHECK_NUMBER (cp);
2114 if (!IsValidCodePage (XINT (cp)))
2115 return Qnil;
2117 if (!SetConsoleOutputCP (XINT (cp)))
2118 return Qnil;
2120 return make_number (GetConsoleOutputCP ());
2124 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2125 Sw32_get_codepage_charset, 1, 1, 0,
2126 doc: /* Return charset ID corresponding to codepage CP.
2127 Returns nil if the codepage is not valid. */)
2128 (Lisp_Object cp)
2130 CHARSETINFO info;
2132 CHECK_NUMBER (cp);
2134 if (!IsValidCodePage (XINT (cp)))
2135 return Qnil;
2137 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2138 return make_number (info.ciCharset);
2140 return Qnil;
2144 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2145 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2146 doc: /* Return list of Windows keyboard languages and layouts.
2147 The return value is a list of pairs of language id and layout id. */)
2148 (void)
2150 int num_layouts = GetKeyboardLayoutList (0, NULL);
2151 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2152 Lisp_Object obj = Qnil;
2154 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2156 while (--num_layouts >= 0)
2158 DWORD kl = (DWORD) layouts[num_layouts];
2160 obj = Fcons (Fcons (make_number (kl & 0xffff),
2161 make_number ((kl >> 16) & 0xffff)),
2162 obj);
2166 return obj;
2170 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2171 Sw32_get_keyboard_layout, 0, 0, 0,
2172 doc: /* Return current Windows keyboard language and layout.
2173 The return value is the cons of the language id and the layout id. */)
2174 (void)
2176 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2178 return Fcons (make_number (kl & 0xffff),
2179 make_number ((kl >> 16) & 0xffff));
2183 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2184 Sw32_set_keyboard_layout, 1, 1, 0,
2185 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2186 The keyboard layout setting affects interpretation of keyboard input.
2187 If successful, the new layout id is returned, otherwise nil. */)
2188 (Lisp_Object layout)
2190 DWORD kl;
2192 CHECK_CONS (layout);
2193 CHECK_NUMBER_CAR (layout);
2194 CHECK_NUMBER_CDR (layout);
2196 kl = (XINT (XCAR (layout)) & 0xffff)
2197 | (XINT (XCDR (layout)) << 16);
2199 /* Synchronize layout with input thread. */
2200 if (dwWindowsThreadId)
2202 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2203 (WPARAM) kl, 0))
2205 MSG msg;
2206 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2208 if (msg.wParam == 0)
2209 return Qnil;
2212 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2213 return Qnil;
2215 return Fw32_get_keyboard_layout ();
2219 void
2220 syms_of_ntproc (void)
2222 DEFSYM (Qhigh, "high");
2223 DEFSYM (Qlow, "low");
2225 defsubr (&Sw32_has_winsock);
2226 defsubr (&Sw32_unload_winsock);
2228 defsubr (&Sw32_short_file_name);
2229 defsubr (&Sw32_long_file_name);
2230 defsubr (&Sw32_set_process_priority);
2231 defsubr (&Sw32_get_locale_info);
2232 defsubr (&Sw32_get_current_locale_id);
2233 defsubr (&Sw32_get_default_locale_id);
2234 defsubr (&Sw32_get_valid_locale_ids);
2235 defsubr (&Sw32_set_current_locale);
2237 defsubr (&Sw32_get_console_codepage);
2238 defsubr (&Sw32_set_console_codepage);
2239 defsubr (&Sw32_get_console_output_codepage);
2240 defsubr (&Sw32_set_console_output_codepage);
2241 defsubr (&Sw32_get_valid_codepages);
2242 defsubr (&Sw32_get_codepage_charset);
2244 defsubr (&Sw32_get_valid_keyboard_layouts);
2245 defsubr (&Sw32_get_keyboard_layout);
2246 defsubr (&Sw32_set_keyboard_layout);
2248 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args,
2249 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2250 Because Windows does not directly pass argv arrays to child processes,
2251 programs have to reconstruct the argv array by parsing the command
2252 line string. For an argument to contain a space, it must be enclosed
2253 in double quotes or it will be parsed as multiple arguments.
2255 If the value is a character, that character will be used to escape any
2256 quote characters that appear, otherwise a suitable escape character
2257 will be chosen based on the type of the program. */);
2258 Vw32_quote_process_args = Qt;
2260 DEFVAR_LISP ("w32-start-process-show-window",
2261 Vw32_start_process_show_window,
2262 doc: /* When nil, new child processes hide their windows.
2263 When non-nil, they show their window in the method of their choice.
2264 This variable doesn't affect GUI applications, which will never be hidden. */);
2265 Vw32_start_process_show_window = Qnil;
2267 DEFVAR_LISP ("w32-start-process-share-console",
2268 Vw32_start_process_share_console,
2269 doc: /* When nil, new child processes are given a new console.
2270 When non-nil, they share the Emacs console; this has the limitation of
2271 allowing only one DOS subprocess to run at a time (whether started directly
2272 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2273 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2274 otherwise respond to interrupts from Emacs. */);
2275 Vw32_start_process_share_console = Qnil;
2277 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2278 Vw32_start_process_inherit_error_mode,
2279 doc: /* When nil, new child processes revert to the default error mode.
2280 When non-nil, they inherit their error mode setting from Emacs, which stops
2281 them blocking when trying to access unmounted drives etc. */);
2282 Vw32_start_process_inherit_error_mode = Qt;
2284 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay,
2285 doc: /* Forced delay before reading subprocess output.
2286 This is done to improve the buffering of subprocess output, by
2287 avoiding the inefficiency of frequently reading small amounts of data.
2289 If positive, the value is the number of milliseconds to sleep before
2290 reading the subprocess output. If negative, the magnitude is the number
2291 of time slices to wait (effectively boosting the priority of the child
2292 process temporarily). A value of zero disables waiting entirely. */);
2293 w32_pipe_read_delay = 50;
2295 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names,
2296 doc: /* Non-nil means convert all-upper case file names to lower case.
2297 This applies when performing completions and file name expansion.
2298 Note that the value of this setting also affects remote file names,
2299 so you probably don't want to set to non-nil if you use case-sensitive
2300 filesystems via ange-ftp. */);
2301 Vw32_downcase_file_names = Qnil;
2303 #if 0
2304 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes,
2305 doc: /* Non-nil means attempt to fake realistic inode values.
2306 This works by hashing the truename of files, and should detect
2307 aliasing between long and short (8.3 DOS) names, but can have
2308 false positives because of hash collisions. Note that determining
2309 the truename of a file can be slow. */);
2310 Vw32_generate_fake_inodes = Qnil;
2311 #endif
2313 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes,
2314 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2315 This option controls whether to issue additional system calls to determine
2316 accurate link counts, file type, and ownership information. It is more
2317 useful for files on NTFS volumes, where hard links and file security are
2318 supported, than on volumes of the FAT family.
2320 Without these system calls, link count will always be reported as 1 and file
2321 ownership will be attributed to the current user.
2322 The default value `local' means only issue these system calls for files
2323 on local fixed drives. A value of nil means never issue them.
2324 Any other non-nil value means do this even on remote and removable drives
2325 where the performance impact may be noticeable even on modern hardware. */);
2326 Vw32_get_true_file_attributes = Qlocal;
2328 staticpro (&Vw32_valid_locale_ids);
2329 staticpro (&Vw32_valid_codepages);
2331 /* end of w32proc.c */