Add pcomplete support for hosts defined in .ssh/config.
[emacs.git] / src / w32proc.c
blobc490dee69090ba7399851c1a258f85e1648492bb
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, 2011 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 */
35 #include <config.h>
37 #undef signal
38 #undef wait
39 #undef spawnve
40 #undef select
41 #undef kill
43 #include <windows.h>
44 #ifdef __GNUC__
45 /* This definition is missing from mingw32 headers. */
46 extern BOOL WINAPI IsValidLocale (LCID, DWORD);
47 #endif
49 #ifdef HAVE_LANGINFO_CODESET
50 #include <nl_types.h>
51 #include <langinfo.h>
52 #endif
54 #include "lisp.h"
55 #include "character.h"
56 #include "w32.h"
57 #include "w32heap.h"
58 #include "systime.h"
59 #include "syswait.h"
60 #include "process.h"
61 #include "syssignal.h"
62 #include "w32term.h"
63 #include "dispextern.h" /* for xstrcasecmp */
64 #include "coding.h"
66 #define RVA_TO_PTR(var,section,filedata) \
67 ((void *)((section)->PointerToRawData \
68 + ((DWORD)(var) - (section)->VirtualAddress) \
69 + (filedata).file_base))
71 extern Lisp_Object Qlocal;
73 Lisp_Object Qhigh, Qlow;
75 #ifdef EMACSDEBUG
76 void
77 _DebPrint (const char *fmt, ...)
79 char buf[1024];
80 va_list args;
82 va_start (args, fmt);
83 vsprintf (buf, fmt, args);
84 va_end (args);
85 OutputDebugString (buf);
87 #endif
89 typedef void (_CALLBACK_ *signal_handler) (int);
91 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
92 static signal_handler sig_handlers[NSIG];
94 /* Fake signal implementation to record the SIGCHLD handler. */
95 signal_handler
96 sys_signal (int sig, signal_handler handler)
98 signal_handler old;
100 if (sig != SIGCHLD)
102 errno = EINVAL;
103 return SIG_ERR;
105 old = sig_handlers[sig];
106 sig_handlers[sig] = handler;
107 return old;
110 /* Defined in <process.h> which conflicts with the local copy */
111 #define _P_NOWAIT 1
113 /* Child process management list. */
114 int child_proc_count = 0;
115 child_process child_procs[ MAX_CHILDREN ];
116 child_process *dead_child = NULL;
118 static DWORD WINAPI reader_thread (void *arg);
120 /* Find an unused process slot. */
121 child_process *
122 new_child (void)
124 child_process *cp;
125 DWORD id;
127 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
128 if (!CHILD_ACTIVE (cp))
129 goto Initialise;
130 if (child_proc_count == MAX_CHILDREN)
131 return NULL;
132 cp = &child_procs[child_proc_count++];
134 Initialise:
135 memset (cp, 0, sizeof (*cp));
136 cp->fd = -1;
137 cp->pid = -1;
138 cp->procinfo.hProcess = NULL;
139 cp->status = STATUS_READ_ERROR;
141 /* use manual reset event so that select() will function properly */
142 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
143 if (cp->char_avail)
145 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
146 if (cp->char_consumed)
148 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &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 forceably 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 return 1;
251 for (;;)
253 int rc;
255 if (fd_info[cp->fd].flags & FILE_LISTEN)
256 rc = _sys_wait_accept (cp->fd);
257 else
258 rc = _sys_read_ahead (cp->fd);
260 /* The name char_avail is a misnomer - it really just means the
261 read-ahead has completed, whether successfully or not. */
262 if (!SetEvent (cp->char_avail))
264 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
265 GetLastError (), cp->fd));
266 return 1;
269 if (rc == STATUS_READ_ERROR)
270 return 1;
272 /* If the read died, the child has died so let the thread die */
273 if (rc == STATUS_READ_FAILED)
274 break;
276 /* Wait until our input is acknowledged before reading again */
277 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
279 DebPrint (("reader_thread.WaitForSingleObject failed with "
280 "%lu for fd %ld\n", GetLastError (), cp->fd));
281 break;
284 return 0;
287 /* To avoid Emacs changing directory, we just record here the directory
288 the new process should start in. This is set just before calling
289 sys_spawnve, and is not generally valid at any other time. */
290 static char * process_dir;
292 static BOOL
293 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
294 int * pPid, child_process *cp)
296 STARTUPINFO start;
297 SECURITY_ATTRIBUTES sec_attrs;
298 #if 0
299 SECURITY_DESCRIPTOR sec_desc;
300 #endif
301 DWORD flags;
302 char dir[ MAXPATHLEN ];
304 if (cp == NULL) abort ();
306 memset (&start, 0, sizeof (start));
307 start.cb = sizeof (start);
309 #ifdef HAVE_NTGUI
310 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
311 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
312 else
313 start.dwFlags = STARTF_USESTDHANDLES;
314 start.wShowWindow = SW_HIDE;
316 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
317 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
318 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
319 #endif /* HAVE_NTGUI */
321 #if 0
322 /* Explicitly specify no security */
323 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
324 goto EH_Fail;
325 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
326 goto EH_Fail;
327 #endif
328 sec_attrs.nLength = sizeof (sec_attrs);
329 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
330 sec_attrs.bInheritHandle = FALSE;
332 strcpy (dir, process_dir);
333 unixtodos_filename (dir);
335 flags = (!NILP (Vw32_start_process_share_console)
336 ? CREATE_NEW_PROCESS_GROUP
337 : CREATE_NEW_CONSOLE);
338 if (NILP (Vw32_start_process_inherit_error_mode))
339 flags |= CREATE_DEFAULT_ERROR_MODE;
340 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
341 flags, env, dir, &start, &cp->procinfo))
342 goto EH_Fail;
344 cp->pid = (int) cp->procinfo.dwProcessId;
346 /* Hack for Windows 95, which assigns large (ie negative) pids */
347 if (cp->pid < 0)
348 cp->pid = -cp->pid;
350 /* pid must fit in a Lisp_Int */
351 cp->pid = cp->pid & INTMASK;
353 *pPid = cp->pid;
355 return TRUE;
357 EH_Fail:
358 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
359 return FALSE;
362 /* create_child doesn't know what emacs' file handle will be for waiting
363 on output from the child, so we need to make this additional call
364 to register the handle with the process
365 This way the select emulator knows how to match file handles with
366 entries in child_procs. */
367 void
368 register_child (int pid, int fd)
370 child_process *cp;
372 cp = find_child_pid (pid);
373 if (cp == NULL)
375 DebPrint (("register_child unable to find pid %lu\n", pid));
376 return;
379 #ifdef FULL_DEBUG
380 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
381 #endif
383 cp->fd = fd;
385 /* thread is initially blocked until select is called; set status so
386 that select will release thread */
387 cp->status = STATUS_READ_ACKNOWLEDGED;
389 /* attach child_process to fd_info */
390 if (fd_info[fd].cp != NULL)
392 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
393 abort ();
396 fd_info[fd].cp = cp;
399 /* When a process dies its pipe will break so the reader thread will
400 signal failure to the select emulator.
401 The select emulator then calls this routine to clean up.
402 Since the thread signaled failure we can assume it is exiting. */
403 static void
404 reap_subprocess (child_process *cp)
406 if (cp->procinfo.hProcess)
408 /* Reap the process */
409 #ifdef FULL_DEBUG
410 /* Process should have already died before we are called. */
411 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
412 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
413 #endif
414 CloseHandle (cp->procinfo.hProcess);
415 cp->procinfo.hProcess = NULL;
416 CloseHandle (cp->procinfo.hThread);
417 cp->procinfo.hThread = NULL;
420 /* For asynchronous children, the child_proc resources will be freed
421 when the last pipe read descriptor is closed; for synchronous
422 children, we must explicitly free the resources now because
423 register_child has not been called. */
424 if (cp->fd == -1)
425 delete_child (cp);
428 /* Wait for any of our existing child processes to die
429 When it does, close its handle
430 Return the pid and fill in the status if non-NULL. */
433 sys_wait (int *status)
435 DWORD active, retval;
436 int nh;
437 int pid;
438 child_process *cp, *cps[MAX_CHILDREN];
439 HANDLE wait_hnd[MAX_CHILDREN];
441 nh = 0;
442 if (dead_child != NULL)
444 /* We want to wait for a specific child */
445 wait_hnd[nh] = dead_child->procinfo.hProcess;
446 cps[nh] = dead_child;
447 if (!wait_hnd[nh]) abort ();
448 nh++;
449 active = 0;
450 goto get_result;
452 else
454 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
455 /* some child_procs might be sockets; ignore them */
456 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
457 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
459 wait_hnd[nh] = cp->procinfo.hProcess;
460 cps[nh] = cp;
461 nh++;
465 if (nh == 0)
467 /* Nothing to wait on, so fail */
468 errno = ECHILD;
469 return -1;
474 /* Check for quit about once a second. */
475 QUIT;
476 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
477 } while (active == WAIT_TIMEOUT);
479 if (active == WAIT_FAILED)
481 errno = EBADF;
482 return -1;
484 else if (active >= WAIT_OBJECT_0
485 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
487 active -= WAIT_OBJECT_0;
489 else if (active >= WAIT_ABANDONED_0
490 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
492 active -= WAIT_ABANDONED_0;
494 else
495 abort ();
497 get_result:
498 if (!GetExitCodeProcess (wait_hnd[active], &retval))
500 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
501 GetLastError ()));
502 retval = 1;
504 if (retval == STILL_ACTIVE)
506 /* Should never happen */
507 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
508 errno = EINVAL;
509 return -1;
512 /* Massage the exit code from the process to match the format expected
513 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
514 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
516 if (retval == STATUS_CONTROL_C_EXIT)
517 retval = SIGINT;
518 else
519 retval <<= 8;
521 cp = cps[active];
522 pid = cp->pid;
523 #ifdef FULL_DEBUG
524 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
525 #endif
527 if (status)
529 *status = retval;
531 else if (synch_process_alive)
533 synch_process_alive = 0;
535 /* Report the status of the synchronous process. */
536 if (WIFEXITED (retval))
537 synch_process_retcode = WRETCODE (retval);
538 else if (WIFSIGNALED (retval))
540 int code = WTERMSIG (retval);
541 char *signame;
543 synchronize_system_messages_locale ();
544 signame = strsignal (code);
546 if (signame == 0)
547 signame = "unknown";
549 synch_process_death = signame;
552 reap_subprocess (cp);
555 reap_subprocess (cp);
557 return pid;
560 /* Old versions of w32api headers don't have separate 32-bit and
561 64-bit defines, but the one they have matches the 32-bit variety. */
562 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
563 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
564 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
565 #endif
567 static void
568 w32_executable_type (char * filename,
569 int * is_dos_app,
570 int * is_cygnus_app,
571 int * is_gui_app)
573 file_data executable;
574 char * p;
576 /* Default values in case we can't tell for sure. */
577 *is_dos_app = FALSE;
578 *is_cygnus_app = FALSE;
579 *is_gui_app = FALSE;
581 if (!open_input_file (&executable, filename))
582 return;
584 p = strrchr (filename, '.');
586 /* We can only identify DOS .com programs from the extension. */
587 if (p && xstrcasecmp (p, ".com") == 0)
588 *is_dos_app = TRUE;
589 else if (p && (xstrcasecmp (p, ".bat") == 0
590 || xstrcasecmp (p, ".cmd") == 0))
592 /* A DOS shell script - it appears that CreateProcess is happy to
593 accept this (somewhat surprisingly); presumably it looks at
594 COMSPEC to determine what executable to actually invoke.
595 Therefore, we have to do the same here as well. */
596 /* Actually, I think it uses the program association for that
597 extension, which is defined in the registry. */
598 p = egetenv ("COMSPEC");
599 if (p)
600 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
602 else
604 /* Look for DOS .exe signature - if found, we must also check that
605 it isn't really a 16- or 32-bit Windows exe, since both formats
606 start with a DOS program stub. Note that 16-bit Windows
607 executables use the OS/2 1.x format. */
609 IMAGE_DOS_HEADER * dos_header;
610 IMAGE_NT_HEADERS * nt_header;
612 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
613 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
614 goto unwind;
616 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
618 if ((char *) nt_header > (char *) dos_header + executable.size)
620 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
621 *is_dos_app = TRUE;
623 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
624 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
626 *is_dos_app = TRUE;
628 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
630 IMAGE_DATA_DIRECTORY *data_dir = NULL;
631 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
633 /* Ensure we are using the 32 bit structure. */
634 IMAGE_OPTIONAL_HEADER32 *opt
635 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
636 data_dir = opt->DataDirectory;
637 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
639 /* MingW 3.12 has the required 64 bit structs, but in case older
640 versions don't, only check 64 bit exes if we know how. */
641 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
642 else if (nt_header->OptionalHeader.Magic
643 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
645 IMAGE_OPTIONAL_HEADER64 *opt
646 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
647 data_dir = opt->DataDirectory;
648 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
650 #endif
651 if (data_dir)
653 /* Look for cygwin.dll in DLL import list. */
654 IMAGE_DATA_DIRECTORY import_dir =
655 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
656 IMAGE_IMPORT_DESCRIPTOR * imports;
657 IMAGE_SECTION_HEADER * section;
659 section = rva_to_section (import_dir.VirtualAddress, nt_header);
660 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
661 executable);
663 for ( ; imports->Name; imports++)
665 char * dllname = RVA_TO_PTR (imports->Name, section,
666 executable);
668 /* The exact name of the cygwin dll has changed with
669 various releases, but hopefully this will be reasonably
670 future proof. */
671 if (strncmp (dllname, "cygwin", 6) == 0)
673 *is_cygnus_app = TRUE;
674 break;
681 unwind:
682 close_file_data (&executable);
685 static int
686 compare_env (const void *strp1, const void *strp2)
688 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
690 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
692 /* Sort order in command.com/cmd.exe is based on uppercasing
693 names, so do the same here. */
694 if (toupper (*str1) > toupper (*str2))
695 return 1;
696 else if (toupper (*str1) < toupper (*str2))
697 return -1;
698 str1++, str2++;
701 if (*str1 == '=' && *str2 == '=')
702 return 0;
703 else if (*str1 == '=')
704 return -1;
705 else
706 return 1;
709 static void
710 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
712 char **optr, **nptr;
713 int num;
715 nptr = new_envp;
716 optr = envp1;
717 while (*optr)
718 *nptr++ = *optr++;
719 num = optr - envp1;
721 optr = envp2;
722 while (*optr)
723 *nptr++ = *optr++;
724 num += optr - envp2;
726 qsort (new_envp, num, sizeof (char *), compare_env);
728 *nptr = NULL;
731 /* When a new child process is created we need to register it in our list,
732 so intercept spawn requests. */
734 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
736 Lisp_Object program, full;
737 char *cmdline, *env, *parg, **targ;
738 int arglen, numenv;
739 int pid;
740 child_process *cp;
741 int is_dos_app, is_cygnus_app, is_gui_app;
742 int do_quoting = 0;
743 char escape_char;
744 /* We pass our process ID to our children by setting up an environment
745 variable in their environment. */
746 char ppid_env_var_buffer[64];
747 char *extra_env[] = {ppid_env_var_buffer, NULL};
748 /* These are the characters that cause an argument to need quoting.
749 Arguments with whitespace characters need quoting to prevent the
750 argument being split into two or more. Arguments with wildcards
751 are also quoted, for consistency with posix platforms, where wildcards
752 are not expanded if we run the program directly without a shell.
753 Some extra whitespace characters need quoting in Cygwin programs,
754 so this list is conditionally modified below. */
755 char *sepchars = " \t*?";
757 /* We don't care about the other modes */
758 if (mode != _P_NOWAIT)
760 errno = EINVAL;
761 return -1;
764 /* Handle executable names without an executable suffix. */
765 program = make_string (cmdname, strlen (cmdname));
766 if (NILP (Ffile_executable_p (program)))
768 struct gcpro gcpro1;
770 full = Qnil;
771 GCPRO1 (program);
772 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
773 UNGCPRO;
774 if (NILP (full))
776 errno = EINVAL;
777 return -1;
779 program = full;
782 /* make sure argv[0] and cmdname are both in DOS format */
783 cmdname = SDATA (program);
784 unixtodos_filename (cmdname);
785 argv[0] = cmdname;
787 /* Determine whether program is a 16-bit DOS executable, or a w32
788 executable that is implicitly linked to the Cygnus dll (implying it
789 was compiled with the Cygnus GNU toolchain and hence relies on
790 cygwin.dll to parse the command line - we use this to decide how to
791 escape quote chars in command line args that must be quoted).
793 Also determine whether it is a GUI app, so that we don't hide its
794 initial window unless specifically requested. */
795 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
797 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
798 application to start it by specifying the helper app as cmdname,
799 while leaving the real app name as argv[0]. */
800 if (is_dos_app)
802 cmdname = alloca (MAXPATHLEN);
803 if (egetenv ("CMDPROXY"))
804 strcpy (cmdname, egetenv ("CMDPROXY"));
805 else
807 strcpy (cmdname, SDATA (Vinvocation_directory));
808 strcat (cmdname, "cmdproxy.exe");
810 unixtodos_filename (cmdname);
813 /* we have to do some conjuring here to put argv and envp into the
814 form CreateProcess wants... argv needs to be a space separated/null
815 terminated list of parameters, and envp is a null
816 separated/double-null terminated list of parameters.
818 Additionally, zero-length args and args containing whitespace or
819 quote chars need to be wrapped in double quotes - for this to work,
820 embedded quotes need to be escaped as well. The aim is to ensure
821 the child process reconstructs the argv array we start with
822 exactly, so we treat quotes at the beginning and end of arguments
823 as embedded quotes.
825 The w32 GNU-based library from Cygnus doubles quotes to escape
826 them, while MSVC uses backslash for escaping. (Actually the MSVC
827 startup code does attempt to recognise doubled quotes and accept
828 them, but gets it wrong and ends up requiring three quotes to get a
829 single embedded quote!) So by default we decide whether to use
830 quote or backslash as the escape character based on whether the
831 binary is apparently a Cygnus compiled app.
833 Note that using backslash to escape embedded quotes requires
834 additional special handling if an embedded quote is already
835 preceeded by backslash, or if an arg requiring quoting ends with
836 backslash. In such cases, the run of escape characters needs to be
837 doubled. For consistency, we apply this special handling as long
838 as the escape character is not quote.
840 Since we have no idea how large argv and envp are likely to be we
841 figure out list lengths on the fly and allocate them. */
843 if (!NILP (Vw32_quote_process_args))
845 do_quoting = 1;
846 /* Override escape char by binding w32-quote-process-args to
847 desired character, or use t for auto-selection. */
848 if (INTEGERP (Vw32_quote_process_args))
849 escape_char = XINT (Vw32_quote_process_args);
850 else
851 escape_char = is_cygnus_app ? '"' : '\\';
854 /* Cygwin apps needs quoting a bit more often. */
855 if (escape_char == '"')
856 sepchars = "\r\n\t\f '";
858 /* do argv... */
859 arglen = 0;
860 targ = argv;
861 while (*targ)
863 char * p = *targ;
864 int need_quotes = 0;
865 int escape_char_run = 0;
867 if (*p == 0)
868 need_quotes = 1;
869 for ( ; *p; p++)
871 if (escape_char == '"' && *p == '\\')
872 /* If it's a Cygwin app, \ needs to be escaped. */
873 arglen++;
874 else if (*p == '"')
876 /* allow for embedded quotes to be escaped */
877 arglen++;
878 need_quotes = 1;
879 /* handle the case where the embedded quote is already escaped */
880 if (escape_char_run > 0)
882 /* To preserve the arg exactly, we need to double the
883 preceding escape characters (plus adding one to
884 escape the quote character itself). */
885 arglen += escape_char_run;
888 else if (strchr (sepchars, *p) != NULL)
890 need_quotes = 1;
893 if (*p == escape_char && escape_char != '"')
894 escape_char_run++;
895 else
896 escape_char_run = 0;
898 if (need_quotes)
900 arglen += 2;
901 /* handle the case where the arg ends with an escape char - we
902 must not let the enclosing quote be escaped. */
903 if (escape_char_run > 0)
904 arglen += escape_char_run;
906 arglen += strlen (*targ++) + 1;
908 cmdline = alloca (arglen);
909 targ = argv;
910 parg = cmdline;
911 while (*targ)
913 char * p = *targ;
914 int need_quotes = 0;
916 if (*p == 0)
917 need_quotes = 1;
919 if (do_quoting)
921 for ( ; *p; p++)
922 if ((strchr (sepchars, *p) != NULL) || *p == '"')
923 need_quotes = 1;
925 if (need_quotes)
927 int escape_char_run = 0;
928 char * first;
929 char * last;
931 p = *targ;
932 first = p;
933 last = p + strlen (p) - 1;
934 *parg++ = '"';
935 #if 0
936 /* This version does not escape quotes if they occur at the
937 beginning or end of the arg - this could lead to incorrect
938 behavior when the arg itself represents a command line
939 containing quoted args. I believe this was originally done
940 as a hack to make some things work, before
941 `w32-quote-process-args' was added. */
942 while (*p)
944 if (*p == '"' && p > first && p < last)
945 *parg++ = escape_char; /* escape embedded quotes */
946 *parg++ = *p++;
948 #else
949 for ( ; *p; p++)
951 if (*p == '"')
953 /* double preceding escape chars if any */
954 while (escape_char_run > 0)
956 *parg++ = escape_char;
957 escape_char_run--;
959 /* escape all quote chars, even at beginning or end */
960 *parg++ = escape_char;
962 else if (escape_char == '"' && *p == '\\')
963 *parg++ = '\\';
964 *parg++ = *p;
966 if (*p == escape_char && escape_char != '"')
967 escape_char_run++;
968 else
969 escape_char_run = 0;
971 /* double escape chars before enclosing quote */
972 while (escape_char_run > 0)
974 *parg++ = escape_char;
975 escape_char_run--;
977 #endif
978 *parg++ = '"';
980 else
982 strcpy (parg, *targ);
983 parg += strlen (*targ);
985 *parg++ = ' ';
986 targ++;
988 *--parg = '\0';
990 /* and envp... */
991 arglen = 1;
992 targ = envp;
993 numenv = 1; /* for end null */
994 while (*targ)
996 arglen += strlen (*targ++) + 1;
997 numenv++;
999 /* extra env vars... */
1000 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1001 GetCurrentProcessId ());
1002 arglen += strlen (ppid_env_var_buffer) + 1;
1003 numenv++;
1005 /* merge env passed in and extra env into one, and sort it. */
1006 targ = (char **) alloca (numenv * sizeof (char *));
1007 merge_and_sort_env (envp, extra_env, targ);
1009 /* concatenate env entries. */
1010 env = alloca (arglen);
1011 parg = env;
1012 while (*targ)
1014 strcpy (parg, *targ);
1015 parg += strlen (*targ++);
1016 *parg++ = '\0';
1018 *parg++ = '\0';
1019 *parg = '\0';
1021 cp = new_child ();
1022 if (cp == NULL)
1024 errno = EAGAIN;
1025 return -1;
1028 /* Now create the process. */
1029 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1031 delete_child (cp);
1032 errno = ENOEXEC;
1033 return -1;
1036 return pid;
1039 /* Emulate the select call
1040 Wait for available input on any of the given rfds, or timeout if
1041 a timeout is given and no input is detected
1042 wfds and efds are not supported and must be NULL.
1044 For simplicity, we detect the death of child processes here and
1045 synchronously call the SIGCHLD handler. Since it is possible for
1046 children to be created without a corresponding pipe handle from which
1047 to read output, we wait separately on the process handles as well as
1048 the char_avail events for each process pipe. We only call
1049 wait/reap_process when the process actually terminates.
1051 To reduce the number of places in which Emacs can be hung such that
1052 C-g is not able to interrupt it, we always wait on interrupt_handle
1053 (which is signaled by the input thread when C-g is detected). If we
1054 detect that we were woken up by C-g, we return -1 with errno set to
1055 EINTR as on Unix. */
1057 /* From ntterm.c */
1058 extern HANDLE keyboard_handle;
1060 /* From w32xfns.c */
1061 extern HANDLE interrupt_handle;
1063 /* From process.c */
1064 extern int proc_buffered_char[];
1067 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1068 EMACS_TIME *timeout)
1070 SELECT_TYPE orfds;
1071 DWORD timeout_ms, start_time;
1072 int i, nh, nc, nr;
1073 DWORD active;
1074 child_process *cp, *cps[MAX_CHILDREN];
1075 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1076 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1078 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1080 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1081 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1083 Sleep (timeout_ms);
1084 return 0;
1087 /* Otherwise, we only handle rfds, so fail otherwise. */
1088 if (rfds == NULL || wfds != NULL || efds != NULL)
1090 errno = EINVAL;
1091 return -1;
1094 orfds = *rfds;
1095 FD_ZERO (rfds);
1096 nr = 0;
1098 /* Always wait on interrupt_handle, to detect C-g (quit). */
1099 wait_hnd[0] = interrupt_handle;
1100 fdindex[0] = -1;
1102 /* Build a list of pipe handles to wait on. */
1103 nh = 1;
1104 for (i = 0; i < nfds; i++)
1105 if (FD_ISSET (i, &orfds))
1107 if (i == 0)
1109 if (keyboard_handle)
1111 /* Handle stdin specially */
1112 wait_hnd[nh] = keyboard_handle;
1113 fdindex[nh] = i;
1114 nh++;
1117 /* Check for any emacs-generated input in the queue since
1118 it won't be detected in the wait */
1119 if (detect_input_pending ())
1121 FD_SET (i, rfds);
1122 return 1;
1125 else
1127 /* Child process and socket input */
1128 cp = fd_info[i].cp;
1129 if (cp)
1131 int current_status = cp->status;
1133 if (current_status == STATUS_READ_ACKNOWLEDGED)
1135 /* Tell reader thread which file handle to use. */
1136 cp->fd = i;
1137 /* Wake up the reader thread for this process */
1138 cp->status = STATUS_READ_READY;
1139 if (!SetEvent (cp->char_consumed))
1140 DebPrint (("nt_select.SetEvent failed with "
1141 "%lu for fd %ld\n", GetLastError (), i));
1144 #ifdef CHECK_INTERLOCK
1145 /* slightly crude cross-checking of interlock between threads */
1147 current_status = cp->status;
1148 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1150 /* char_avail has been signaled, so status (which may
1151 have changed) should indicate read has completed
1152 but has not been acknowledged. */
1153 current_status = cp->status;
1154 if (current_status != STATUS_READ_SUCCEEDED
1155 && current_status != STATUS_READ_FAILED)
1156 DebPrint (("char_avail set, but read not completed: status %d\n",
1157 current_status));
1159 else
1161 /* char_avail has not been signaled, so status should
1162 indicate that read is in progress; small possibility
1163 that read has completed but event wasn't yet signaled
1164 when we tested it (because a context switch occurred
1165 or if running on separate CPUs). */
1166 if (current_status != STATUS_READ_READY
1167 && current_status != STATUS_READ_IN_PROGRESS
1168 && current_status != STATUS_READ_SUCCEEDED
1169 && current_status != STATUS_READ_FAILED)
1170 DebPrint (("char_avail reset, but read status is bad: %d\n",
1171 current_status));
1173 #endif
1174 wait_hnd[nh] = cp->char_avail;
1175 fdindex[nh] = i;
1176 if (!wait_hnd[nh]) abort ();
1177 nh++;
1178 #ifdef FULL_DEBUG
1179 DebPrint (("select waiting on child %d fd %d\n",
1180 cp-child_procs, i));
1181 #endif
1183 else
1185 /* Unable to find something to wait on for this fd, skip */
1187 /* Note that this is not a fatal error, and can in fact
1188 happen in unusual circumstances. Specifically, if
1189 sys_spawnve fails, eg. because the program doesn't
1190 exist, and debug-on-error is t so Fsignal invokes a
1191 nested input loop, then the process output pipe is
1192 still included in input_wait_mask with no child_proc
1193 associated with it. (It is removed when the debugger
1194 exits the nested input loop and the error is thrown.) */
1196 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1201 count_children:
1202 /* Add handles of child processes. */
1203 nc = 0;
1204 for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1205 /* Some child_procs might be sockets; ignore them. Also some
1206 children may have died already, but we haven't finished reading
1207 the process output; ignore them too. */
1208 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1209 && (cp->fd < 0
1210 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1211 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1214 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1215 cps[nc] = cp;
1216 nc++;
1219 /* Nothing to look for, so we didn't find anything */
1220 if (nh + nc == 0)
1222 if (timeout)
1223 Sleep (timeout_ms);
1224 return 0;
1227 start_time = GetTickCount ();
1229 /* Wait for input or child death to be signaled. If user input is
1230 allowed, then also accept window messages. */
1231 if (FD_ISSET (0, &orfds))
1232 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1233 QS_ALLINPUT);
1234 else
1235 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1237 if (active == WAIT_FAILED)
1239 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1240 nh + nc, timeout_ms, GetLastError ()));
1241 /* don't return EBADF - this causes wait_reading_process_output to
1242 abort; WAIT_FAILED is returned when single-stepping under
1243 Windows 95 after switching thread focus in debugger, and
1244 possibly at other times. */
1245 errno = EINTR;
1246 return -1;
1248 else if (active == WAIT_TIMEOUT)
1250 return 0;
1252 else if (active >= WAIT_OBJECT_0
1253 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1255 active -= WAIT_OBJECT_0;
1257 else if (active >= WAIT_ABANDONED_0
1258 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1260 active -= WAIT_ABANDONED_0;
1262 else
1263 abort ();
1265 /* Loop over all handles after active (now officially documented as
1266 being the first signaled handle in the array). We do this to
1267 ensure fairness, so that all channels with data available will be
1268 processed - otherwise higher numbered channels could be starved. */
1271 if (active == nh + nc)
1273 /* There are messages in the lisp thread's queue; we must
1274 drain the queue now to ensure they are processed promptly,
1275 because if we don't do so, we will not be woken again until
1276 further messages arrive.
1278 NB. If ever we allow window message procedures to callback
1279 into lisp, we will need to ensure messages are dispatched
1280 at a safe time for lisp code to be run (*), and we may also
1281 want to provide some hooks in the dispatch loop to cater
1282 for modeless dialogs created by lisp (ie. to register
1283 window handles to pass to IsDialogMessage).
1285 (*) Note that MsgWaitForMultipleObjects above is an
1286 internal dispatch point for messages that are sent to
1287 windows created by this thread. */
1288 drain_message_queue ();
1290 else if (active >= nh)
1292 cp = cps[active - nh];
1294 /* We cannot always signal SIGCHLD immediately; if we have not
1295 finished reading the process output, we must delay sending
1296 SIGCHLD until we do. */
1298 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1299 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1300 /* SIG_DFL for SIGCHLD is ignore */
1301 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1302 sig_handlers[SIGCHLD] != SIG_IGN)
1304 #ifdef FULL_DEBUG
1305 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1306 cp->pid));
1307 #endif
1308 dead_child = cp;
1309 sig_handlers[SIGCHLD] (SIGCHLD);
1310 dead_child = NULL;
1313 else if (fdindex[active] == -1)
1315 /* Quit (C-g) was detected. */
1316 errno = EINTR;
1317 return -1;
1319 else if (fdindex[active] == 0)
1321 /* Keyboard input available */
1322 FD_SET (0, rfds);
1323 nr++;
1325 else
1327 /* must be a socket or pipe - read ahead should have
1328 completed, either succeeding or failing. */
1329 FD_SET (fdindex[active], rfds);
1330 nr++;
1333 /* Even though wait_reading_process_output only reads from at most
1334 one channel, we must process all channels here so that we reap
1335 all children that have died. */
1336 while (++active < nh + nc)
1337 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1338 break;
1339 } while (active < nh + nc);
1341 /* If no input has arrived and timeout hasn't expired, wait again. */
1342 if (nr == 0)
1344 DWORD elapsed = GetTickCount () - start_time;
1346 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1348 if (timeout_ms != INFINITE)
1349 timeout_ms -= elapsed;
1350 goto count_children;
1354 return nr;
1357 /* Substitute for certain kill () operations */
1359 static BOOL CALLBACK
1360 find_child_console (HWND hwnd, LPARAM arg)
1362 child_process * cp = (child_process *) arg;
1363 DWORD thread_id;
1364 DWORD process_id;
1366 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1367 if (process_id == cp->procinfo.dwProcessId)
1369 char window_class[32];
1371 GetClassName (hwnd, window_class, sizeof (window_class));
1372 if (strcmp (window_class,
1373 (os_subtype == OS_WIN95)
1374 ? "tty"
1375 : "ConsoleWindowClass") == 0)
1377 cp->hwnd = hwnd;
1378 return FALSE;
1381 /* keep looking */
1382 return TRUE;
1386 sys_kill (int pid, int sig)
1388 child_process *cp;
1389 HANDLE proc_hand;
1390 int need_to_free = 0;
1391 int rc = 0;
1393 /* Only handle signals that will result in the process dying */
1394 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1396 errno = EINVAL;
1397 return -1;
1400 cp = find_child_pid (pid);
1401 if (cp == NULL)
1403 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1404 if (proc_hand == NULL)
1406 errno = EPERM;
1407 return -1;
1409 need_to_free = 1;
1411 else
1413 proc_hand = cp->procinfo.hProcess;
1414 pid = cp->procinfo.dwProcessId;
1416 /* Try to locate console window for process. */
1417 EnumWindows (find_child_console, (LPARAM) cp);
1420 if (sig == SIGINT || sig == SIGQUIT)
1422 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1424 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1425 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1426 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1427 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1428 HWND foreground_window;
1430 if (break_scan_code == 0)
1432 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1433 vk_break_code = 'C';
1434 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1437 foreground_window = GetForegroundWindow ();
1438 if (foreground_window)
1440 /* NT 5.0, and apparently also Windows 98, will not allow
1441 a Window to be set to foreground directly without the
1442 user's involvement. The workaround is to attach
1443 ourselves to the thread that owns the foreground
1444 window, since that is the only thread that can set the
1445 foreground window. */
1446 DWORD foreground_thread, child_thread;
1447 foreground_thread =
1448 GetWindowThreadProcessId (foreground_window, NULL);
1449 if (foreground_thread == GetCurrentThreadId ()
1450 || !AttachThreadInput (GetCurrentThreadId (),
1451 foreground_thread, TRUE))
1452 foreground_thread = 0;
1454 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1455 if (child_thread == GetCurrentThreadId ()
1456 || !AttachThreadInput (GetCurrentThreadId (),
1457 child_thread, TRUE))
1458 child_thread = 0;
1460 /* Set the foreground window to the child. */
1461 if (SetForegroundWindow (cp->hwnd))
1463 /* Generate keystrokes as if user had typed Ctrl-Break or
1464 Ctrl-C. */
1465 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1466 keybd_event (vk_break_code, break_scan_code,
1467 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1468 keybd_event (vk_break_code, break_scan_code,
1469 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1470 | KEYEVENTF_KEYUP, 0);
1471 keybd_event (VK_CONTROL, control_scan_code,
1472 KEYEVENTF_KEYUP, 0);
1474 /* Sleep for a bit to give time for Emacs frame to respond
1475 to focus change events (if Emacs was active app). */
1476 Sleep (100);
1478 SetForegroundWindow (foreground_window);
1480 /* Detach from the foreground and child threads now that
1481 the foreground switching is over. */
1482 if (foreground_thread)
1483 AttachThreadInput (GetCurrentThreadId (),
1484 foreground_thread, FALSE);
1485 if (child_thread)
1486 AttachThreadInput (GetCurrentThreadId (),
1487 child_thread, FALSE);
1490 /* Ctrl-Break is NT equivalent of SIGINT. */
1491 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1493 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1494 "for pid %lu\n", GetLastError (), pid));
1495 errno = EINVAL;
1496 rc = -1;
1499 else
1501 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1503 #if 1
1504 if (os_subtype == OS_WIN95)
1507 Another possibility is to try terminating the VDM out-right by
1508 calling the Shell VxD (id 0x17) V86 interface, function #4
1509 "SHELL_Destroy_VM", ie.
1511 mov edx,4
1512 mov ebx,vm_handle
1513 call shellapi
1515 First need to determine the current VM handle, and then arrange for
1516 the shellapi call to be made from the system vm (by using
1517 Switch_VM_and_callback).
1519 Could try to invoke DestroyVM through CallVxD.
1522 #if 0
1523 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1524 to hang when cmdproxy is used in conjunction with
1525 command.com for an interactive shell. Posting
1526 WM_CLOSE pops up a dialog that, when Yes is selected,
1527 does the same thing. TerminateProcess is also less
1528 than ideal in that subprocesses tend to stick around
1529 until the machine is shutdown, but at least it
1530 doesn't freeze the 16-bit subsystem. */
1531 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1532 #endif
1533 if (!TerminateProcess (proc_hand, 0xff))
1535 DebPrint (("sys_kill.TerminateProcess returned %d "
1536 "for pid %lu\n", GetLastError (), pid));
1537 errno = EINVAL;
1538 rc = -1;
1541 else
1542 #endif
1543 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1545 /* Kill the process. On W32 this doesn't kill child processes
1546 so it doesn't work very well for shells which is why it's not
1547 used in every case. */
1548 else if (!TerminateProcess (proc_hand, 0xff))
1550 DebPrint (("sys_kill.TerminateProcess returned %d "
1551 "for pid %lu\n", GetLastError (), pid));
1552 errno = EINVAL;
1553 rc = -1;
1557 if (need_to_free)
1558 CloseHandle (proc_hand);
1560 return rc;
1563 /* extern int report_file_error (char *, Lisp_Object); */
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 nt.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 Win95 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 if (got_full)
1939 return make_unibyte_string (full_name, got_full);
1942 return Qnil;
1946 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1947 Sw32_get_current_locale_id, 0, 0, 0,
1948 doc: /* Return Windows locale id for current locale setting.
1949 This is a numerical value; use `w32-get-locale-info' to convert to a
1950 human-readable form. */)
1951 (void)
1953 return make_number (GetThreadLocale ());
1956 static DWORD
1957 int_from_hex (char * s)
1959 DWORD val = 0;
1960 static char hex[] = "0123456789abcdefABCDEF";
1961 char * p;
1963 while (*s && (p = strchr (hex, *s)) != NULL)
1965 unsigned digit = p - hex;
1966 if (digit > 15)
1967 digit -= 6;
1968 val = val * 16 + digit;
1969 s++;
1971 return val;
1974 /* We need to build a global list, since the EnumSystemLocale callback
1975 function isn't given a context pointer. */
1976 Lisp_Object Vw32_valid_locale_ids;
1978 static BOOL CALLBACK
1979 enum_locale_fn (LPTSTR localeNum)
1981 DWORD id = int_from_hex (localeNum);
1982 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
1983 return TRUE;
1986 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
1987 Sw32_get_valid_locale_ids, 0, 0, 0,
1988 doc: /* Return list of all valid Windows locale ids.
1989 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1990 human-readable form. */)
1991 (void)
1993 Vw32_valid_locale_ids = Qnil;
1995 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
1997 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
1998 return Vw32_valid_locale_ids;
2002 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2003 doc: /* Return Windows locale id for default locale setting.
2004 By default, the system default locale setting is returned; if the optional
2005 parameter USERP is non-nil, the user default locale setting is returned.
2006 This is a numerical value; use `w32-get-locale-info' to convert to a
2007 human-readable form. */)
2008 (Lisp_Object userp)
2010 if (NILP (userp))
2011 return make_number (GetSystemDefaultLCID ());
2012 return make_number (GetUserDefaultLCID ());
2016 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2017 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2018 If successful, the new locale id is returned, otherwise nil. */)
2019 (Lisp_Object lcid)
2021 CHECK_NUMBER (lcid);
2023 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2024 return Qnil;
2026 if (!SetThreadLocale (XINT (lcid)))
2027 return Qnil;
2029 /* Need to set input thread locale if present. */
2030 if (dwWindowsThreadId)
2031 /* Reply is not needed. */
2032 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2034 return make_number (GetThreadLocale ());
2038 /* We need to build a global list, since the EnumCodePages callback
2039 function isn't given a context pointer. */
2040 Lisp_Object Vw32_valid_codepages;
2042 static BOOL CALLBACK
2043 enum_codepage_fn (LPTSTR codepageNum)
2045 DWORD id = atoi (codepageNum);
2046 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2047 return TRUE;
2050 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2051 Sw32_get_valid_codepages, 0, 0, 0,
2052 doc: /* Return list of all valid Windows codepages. */)
2053 (void)
2055 Vw32_valid_codepages = Qnil;
2057 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2059 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2060 return Vw32_valid_codepages;
2064 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2065 Sw32_get_console_codepage, 0, 0, 0,
2066 doc: /* Return current Windows codepage for console input. */)
2067 (void)
2069 return make_number (GetConsoleCP ());
2073 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2074 Sw32_set_console_codepage, 1, 1, 0,
2075 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2076 The codepage setting affects keyboard input and display in tty mode.
2077 If successful, the new CP is returned, otherwise nil. */)
2078 (Lisp_Object cp)
2080 CHECK_NUMBER (cp);
2082 if (!IsValidCodePage (XINT (cp)))
2083 return Qnil;
2085 if (!SetConsoleCP (XINT (cp)))
2086 return Qnil;
2088 return make_number (GetConsoleCP ());
2092 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2093 Sw32_get_console_output_codepage, 0, 0, 0,
2094 doc: /* Return current Windows codepage for console output. */)
2095 (void)
2097 return make_number (GetConsoleOutputCP ());
2101 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2102 Sw32_set_console_output_codepage, 1, 1, 0,
2103 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2104 The codepage setting affects keyboard input and display in tty mode.
2105 If successful, the new CP is returned, otherwise nil. */)
2106 (Lisp_Object cp)
2108 CHECK_NUMBER (cp);
2110 if (!IsValidCodePage (XINT (cp)))
2111 return Qnil;
2113 if (!SetConsoleOutputCP (XINT (cp)))
2114 return Qnil;
2116 return make_number (GetConsoleOutputCP ());
2120 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2121 Sw32_get_codepage_charset, 1, 1, 0,
2122 doc: /* Return charset of codepage CP.
2123 Returns nil if the codepage is not valid. */)
2124 (Lisp_Object cp)
2126 CHARSETINFO info;
2128 CHECK_NUMBER (cp);
2130 if (!IsValidCodePage (XINT (cp)))
2131 return Qnil;
2133 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2134 return make_number (info.ciCharset);
2136 return Qnil;
2140 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2141 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2142 doc: /* Return list of Windows keyboard languages and layouts.
2143 The return value is a list of pairs of language id and layout id. */)
2144 (void)
2146 int num_layouts = GetKeyboardLayoutList (0, NULL);
2147 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2148 Lisp_Object obj = Qnil;
2150 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2152 while (--num_layouts >= 0)
2154 DWORD kl = (DWORD) layouts[num_layouts];
2156 obj = Fcons (Fcons (make_number (kl & 0xffff),
2157 make_number ((kl >> 16) & 0xffff)),
2158 obj);
2162 return obj;
2166 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2167 Sw32_get_keyboard_layout, 0, 0, 0,
2168 doc: /* Return current Windows keyboard language and layout.
2169 The return value is the cons of the language id and the layout id. */)
2170 (void)
2172 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2174 return Fcons (make_number (kl & 0xffff),
2175 make_number ((kl >> 16) & 0xffff));
2179 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2180 Sw32_set_keyboard_layout, 1, 1, 0,
2181 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2182 The keyboard layout setting affects interpretation of keyboard input.
2183 If successful, the new layout id is returned, otherwise nil. */)
2184 (Lisp_Object layout)
2186 DWORD kl;
2188 CHECK_CONS (layout);
2189 CHECK_NUMBER_CAR (layout);
2190 CHECK_NUMBER_CDR (layout);
2192 kl = (XINT (XCAR (layout)) & 0xffff)
2193 | (XINT (XCDR (layout)) << 16);
2195 /* Synchronize layout with input thread. */
2196 if (dwWindowsThreadId)
2198 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2199 (WPARAM) kl, 0))
2201 MSG msg;
2202 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2204 if (msg.wParam == 0)
2205 return Qnil;
2208 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2209 return Qnil;
2211 return Fw32_get_keyboard_layout ();
2215 void
2216 syms_of_ntproc (void)
2218 DEFSYM (Qhigh, "high");
2219 DEFSYM (Qlow, "low");
2221 defsubr (&Sw32_has_winsock);
2222 defsubr (&Sw32_unload_winsock);
2224 defsubr (&Sw32_short_file_name);
2225 defsubr (&Sw32_long_file_name);
2226 defsubr (&Sw32_set_process_priority);
2227 defsubr (&Sw32_get_locale_info);
2228 defsubr (&Sw32_get_current_locale_id);
2229 defsubr (&Sw32_get_default_locale_id);
2230 defsubr (&Sw32_get_valid_locale_ids);
2231 defsubr (&Sw32_set_current_locale);
2233 defsubr (&Sw32_get_console_codepage);
2234 defsubr (&Sw32_set_console_codepage);
2235 defsubr (&Sw32_get_console_output_codepage);
2236 defsubr (&Sw32_set_console_output_codepage);
2237 defsubr (&Sw32_get_valid_codepages);
2238 defsubr (&Sw32_get_codepage_charset);
2240 defsubr (&Sw32_get_valid_keyboard_layouts);
2241 defsubr (&Sw32_get_keyboard_layout);
2242 defsubr (&Sw32_set_keyboard_layout);
2244 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args,
2245 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2246 Because Windows does not directly pass argv arrays to child processes,
2247 programs have to reconstruct the argv array by parsing the command
2248 line string. For an argument to contain a space, it must be enclosed
2249 in double quotes or it will be parsed as multiple arguments.
2251 If the value is a character, that character will be used to escape any
2252 quote characters that appear, otherwise a suitable escape character
2253 will be chosen based on the type of the program. */);
2254 Vw32_quote_process_args = Qt;
2256 DEFVAR_LISP ("w32-start-process-show-window",
2257 Vw32_start_process_show_window,
2258 doc: /* When nil, new child processes hide their windows.
2259 When non-nil, they show their window in the method of their choice.
2260 This variable doesn't affect GUI applications, which will never be hidden. */);
2261 Vw32_start_process_show_window = Qnil;
2263 DEFVAR_LISP ("w32-start-process-share-console",
2264 Vw32_start_process_share_console,
2265 doc: /* When nil, new child processes are given a new console.
2266 When non-nil, they share the Emacs console; this has the limitation of
2267 allowing only one DOS subprocess to run at a time (whether started directly
2268 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2269 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2270 otherwise respond to interrupts from Emacs. */);
2271 Vw32_start_process_share_console = Qnil;
2273 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2274 Vw32_start_process_inherit_error_mode,
2275 doc: /* When nil, new child processes revert to the default error mode.
2276 When non-nil, they inherit their error mode setting from Emacs, which stops
2277 them blocking when trying to access unmounted drives etc. */);
2278 Vw32_start_process_inherit_error_mode = Qt;
2280 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay,
2281 doc: /* Forced delay before reading subprocess output.
2282 This is done to improve the buffering of subprocess output, by
2283 avoiding the inefficiency of frequently reading small amounts of data.
2285 If positive, the value is the number of milliseconds to sleep before
2286 reading the subprocess output. If negative, the magnitude is the number
2287 of time slices to wait (effectively boosting the priority of the child
2288 process temporarily). A value of zero disables waiting entirely. */);
2289 w32_pipe_read_delay = 50;
2291 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names,
2292 doc: /* Non-nil means convert all-upper case file names to lower case.
2293 This applies when performing completions and file name expansion.
2294 Note that the value of this setting also affects remote file names,
2295 so you probably don't want to set to non-nil if you use case-sensitive
2296 filesystems via ange-ftp. */);
2297 Vw32_downcase_file_names = Qnil;
2299 #if 0
2300 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes,
2301 doc: /* Non-nil means attempt to fake realistic inode values.
2302 This works by hashing the truename of files, and should detect
2303 aliasing between long and short (8.3 DOS) names, but can have
2304 false positives because of hash collisions. Note that determing
2305 the truename of a file can be slow. */);
2306 Vw32_generate_fake_inodes = Qnil;
2307 #endif
2309 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes,
2310 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2311 This option controls whether to issue additional system calls to determine
2312 accurate link counts, file type, and ownership information. It is more
2313 useful for files on NTFS volumes, where hard links and file security are
2314 supported, than on volumes of the FAT family.
2316 Without these system calls, link count will always be reported as 1 and file
2317 ownership will be attributed to the current user.
2318 The default value `local' means only issue these system calls for files
2319 on local fixed drives. A value of nil means never issue them.
2320 Any other non-nil value means do this even on remote and removable drives
2321 where the performance impact may be noticeable even on modern hardware. */);
2322 Vw32_get_true_file_attributes = Qlocal;
2324 staticpro (&Vw32_valid_locale_ids);
2325 staticpro (&Vw32_valid_codepages);
2327 /* end of w32proc.c */