(url-open-stream): Really use asynchronous connections (accidentally
[emacs.git] / src / w32proc.c
blob2949193101563d6ad62244471439a609fd7e9c52
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 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 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.
22 Drew Bliss Oct 14, 1993
23 Adapted from alarm.c by Tim Fleehart
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <io.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <sys/file.h>
34 /* must include CRT headers *before* config.h */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
40 #undef signal
41 #undef wait
42 #undef spawnve
43 #undef select
44 #undef kill
46 #include <windows.h>
47 #ifdef __GNUC__
48 /* This definition is missing from mingw32 headers. */
49 extern BOOL WINAPI IsValidLocale(LCID, DWORD);
50 #endif
52 #ifdef HAVE_LANGINFO_CODESET
53 #include <nl_types.h>
54 #include <langinfo.h>
55 #endif
57 #include "lisp.h"
58 #include "w32.h"
59 #include "w32heap.h"
60 #include "systime.h"
61 #include "syswait.h"
62 #include "process.h"
63 #include "syssignal.h"
64 #include "w32term.h"
66 #define RVA_TO_PTR(var,section,filedata) \
67 ((void *)((section)->PointerToRawData \
68 + ((DWORD)(var) - (section)->VirtualAddress) \
69 + (filedata).file_base))
71 /* Control whether spawnve quotes arguments as necessary to ensure
72 correct parsing by child process. Because not all uses of spawnve
73 are careful about constructing argv arrays, we make this behaviour
74 conditional (off by default). */
75 Lisp_Object Vw32_quote_process_args;
77 /* Control whether create_child causes the process' window to be
78 hidden. The default is nil. */
79 Lisp_Object Vw32_start_process_show_window;
81 /* Control whether create_child causes the process to inherit Emacs'
82 console window, or be given a new one of its own. The default is
83 nil, to allow multiple DOS programs to run on Win95. Having separate
84 consoles also allows Emacs to cleanly terminate process groups. */
85 Lisp_Object Vw32_start_process_share_console;
87 /* Control whether create_child cause the process to inherit Emacs'
88 error mode setting. The default is t, to minimize the possibility of
89 subprocesses blocking when accessing unmounted drives. */
90 Lisp_Object Vw32_start_process_inherit_error_mode;
92 /* Time to sleep before reading from a subprocess output pipe - this
93 avoids the inefficiency of frequently reading small amounts of data.
94 This is primarily necessary for handling DOS processes on Windows 95,
95 but is useful for W32 processes on both Windows 95 and NT as well. */
96 int w32_pipe_read_delay;
98 /* Control conversion of upper case file names to lower case.
99 nil means no, t means yes. */
100 Lisp_Object Vw32_downcase_file_names;
102 /* Control whether stat() attempts to generate fake but hopefully
103 "accurate" inode values, by hashing the absolute truenames of files.
104 This should detect aliasing between long and short names, but still
105 allows the possibility of hash collisions. */
106 Lisp_Object Vw32_generate_fake_inodes;
108 /* Control whether stat() attempts to determine file type and link count
109 exactly, at the expense of slower operation. Since true hard links
110 are supported on NTFS volumes, this is only relevant on NT. */
111 Lisp_Object Vw32_get_true_file_attributes;
113 Lisp_Object Qhigh, Qlow;
115 #ifdef EMACSDEBUG
116 void _DebPrint (const char *fmt, ...)
118 char buf[1024];
119 va_list args;
121 va_start (args, fmt);
122 vsprintf (buf, fmt, args);
123 va_end (args);
124 OutputDebugString (buf);
126 #endif
128 typedef void (_CALLBACK_ *signal_handler)(int);
130 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
131 static signal_handler sig_handlers[NSIG];
133 /* Fake signal implementation to record the SIGCHLD handler. */
134 signal_handler
135 sys_signal (int sig, signal_handler handler)
137 signal_handler old;
139 if (sig != SIGCHLD)
141 errno = EINVAL;
142 return SIG_ERR;
144 old = sig_handlers[sig];
145 sig_handlers[sig] = handler;
146 return old;
149 /* Defined in <process.h> which conflicts with the local copy */
150 #define _P_NOWAIT 1
152 /* Child process management list. */
153 int child_proc_count = 0;
154 child_process child_procs[ MAX_CHILDREN ];
155 child_process *dead_child = NULL;
157 DWORD WINAPI reader_thread (void *arg);
159 /* Find an unused process slot. */
160 child_process *
161 new_child (void)
163 child_process *cp;
164 DWORD id;
166 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
167 if (!CHILD_ACTIVE (cp))
168 goto Initialise;
169 if (child_proc_count == MAX_CHILDREN)
170 return NULL;
171 cp = &child_procs[child_proc_count++];
173 Initialise:
174 memset (cp, 0, sizeof(*cp));
175 cp->fd = -1;
176 cp->pid = -1;
177 cp->procinfo.hProcess = NULL;
178 cp->status = STATUS_READ_ERROR;
180 /* use manual reset event so that select() will function properly */
181 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
182 if (cp->char_avail)
184 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
185 if (cp->char_consumed)
187 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
188 if (cp->thrd)
189 return cp;
192 delete_child (cp);
193 return NULL;
196 void
197 delete_child (child_process *cp)
199 int i;
201 /* Should not be deleting a child that is still needed. */
202 for (i = 0; i < MAXDESC; i++)
203 if (fd_info[i].cp == cp)
204 abort ();
206 if (!CHILD_ACTIVE (cp))
207 return;
209 /* reap thread if necessary */
210 if (cp->thrd)
212 DWORD rc;
214 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
216 /* let the thread exit cleanly if possible */
217 cp->status = STATUS_READ_ERROR;
218 SetEvent (cp->char_consumed);
219 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
221 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
222 "with %lu for fd %ld\n", GetLastError (), cp->fd));
223 TerminateThread (cp->thrd, 0);
226 CloseHandle (cp->thrd);
227 cp->thrd = NULL;
229 if (cp->char_avail)
231 CloseHandle (cp->char_avail);
232 cp->char_avail = NULL;
234 if (cp->char_consumed)
236 CloseHandle (cp->char_consumed);
237 cp->char_consumed = NULL;
240 /* update child_proc_count (highest numbered slot in use plus one) */
241 if (cp == child_procs + child_proc_count - 1)
243 for (i = child_proc_count-1; i >= 0; i--)
244 if (CHILD_ACTIVE (&child_procs[i]))
246 child_proc_count = i + 1;
247 break;
250 if (i < 0)
251 child_proc_count = 0;
254 /* Find a child by pid. */
255 static child_process *
256 find_child_pid (DWORD pid)
258 child_process *cp;
260 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
261 if (CHILD_ACTIVE (cp) && pid == cp->pid)
262 return cp;
263 return NULL;
267 /* Thread proc for child process and socket reader threads. Each thread
268 is normally blocked until woken by select() to check for input by
269 reading one char. When the read completes, char_avail is signalled
270 to wake up the select emulator and the thread blocks itself again. */
271 DWORD WINAPI
272 reader_thread (void *arg)
274 child_process *cp;
276 /* Our identity */
277 cp = (child_process *)arg;
279 /* We have to wait for the go-ahead before we can start */
280 if (cp == NULL
281 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
282 return 1;
284 for (;;)
286 int rc;
288 if (fd_info[cp->fd].flags & FILE_LISTEN)
289 rc = _sys_wait_accept (cp->fd);
290 else
291 rc = _sys_read_ahead (cp->fd);
293 /* The name char_avail is a misnomer - it really just means the
294 read-ahead has completed, whether successfully or not. */
295 if (!SetEvent (cp->char_avail))
297 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
298 GetLastError (), cp->fd));
299 return 1;
302 if (rc == STATUS_READ_ERROR)
303 return 1;
305 /* If the read died, the child has died so let the thread die */
306 if (rc == STATUS_READ_FAILED)
307 break;
309 /* Wait until our input is acknowledged before reading again */
310 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
312 DebPrint (("reader_thread.WaitForSingleObject failed with "
313 "%lu for fd %ld\n", GetLastError (), cp->fd));
314 break;
317 return 0;
320 /* To avoid Emacs changing directory, we just record here the directory
321 the new process should start in. This is set just before calling
322 sys_spawnve, and is not generally valid at any other time. */
323 static char * process_dir;
325 static BOOL
326 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
327 int * pPid, child_process *cp)
329 STARTUPINFO start;
330 SECURITY_ATTRIBUTES sec_attrs;
331 #if 0
332 SECURITY_DESCRIPTOR sec_desc;
333 #endif
334 DWORD flags;
335 char dir[ MAXPATHLEN ];
337 if (cp == NULL) abort ();
339 memset (&start, 0, sizeof (start));
340 start.cb = sizeof (start);
342 #ifdef HAVE_NTGUI
343 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
344 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
345 else
346 start.dwFlags = STARTF_USESTDHANDLES;
347 start.wShowWindow = SW_HIDE;
349 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
350 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
351 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
352 #endif /* HAVE_NTGUI */
354 #if 0
355 /* Explicitly specify no security */
356 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
357 goto EH_Fail;
358 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
359 goto EH_Fail;
360 #endif
361 sec_attrs.nLength = sizeof (sec_attrs);
362 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
363 sec_attrs.bInheritHandle = FALSE;
365 strcpy (dir, process_dir);
366 unixtodos_filename (dir);
368 flags = (!NILP (Vw32_start_process_share_console)
369 ? CREATE_NEW_PROCESS_GROUP
370 : CREATE_NEW_CONSOLE);
371 if (NILP (Vw32_start_process_inherit_error_mode))
372 flags |= CREATE_DEFAULT_ERROR_MODE;
373 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
374 flags, env, dir, &start, &cp->procinfo))
375 goto EH_Fail;
377 cp->pid = (int) cp->procinfo.dwProcessId;
379 /* Hack for Windows 95, which assigns large (ie negative) pids */
380 if (cp->pid < 0)
381 cp->pid = -cp->pid;
383 /* pid must fit in a Lisp_Int */
384 cp->pid = cp->pid & INTMASK;
386 *pPid = cp->pid;
388 return TRUE;
390 EH_Fail:
391 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
392 return FALSE;
395 /* create_child doesn't know what emacs' file handle will be for waiting
396 on output from the child, so we need to make this additional call
397 to register the handle with the process
398 This way the select emulator knows how to match file handles with
399 entries in child_procs. */
400 void
401 register_child (int pid, int fd)
403 child_process *cp;
405 cp = find_child_pid (pid);
406 if (cp == NULL)
408 DebPrint (("register_child unable to find pid %lu\n", pid));
409 return;
412 #ifdef FULL_DEBUG
413 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
414 #endif
416 cp->fd = fd;
418 /* thread is initially blocked until select is called; set status so
419 that select will release thread */
420 cp->status = STATUS_READ_ACKNOWLEDGED;
422 /* attach child_process to fd_info */
423 if (fd_info[fd].cp != NULL)
425 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
426 abort ();
429 fd_info[fd].cp = cp;
432 /* When a process dies its pipe will break so the reader thread will
433 signal failure to the select emulator.
434 The select emulator then calls this routine to clean up.
435 Since the thread signaled failure we can assume it is exiting. */
436 static void
437 reap_subprocess (child_process *cp)
439 if (cp->procinfo.hProcess)
441 /* Reap the process */
442 #ifdef FULL_DEBUG
443 /* Process should have already died before we are called. */
444 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
445 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
446 #endif
447 CloseHandle (cp->procinfo.hProcess);
448 cp->procinfo.hProcess = NULL;
449 CloseHandle (cp->procinfo.hThread);
450 cp->procinfo.hThread = NULL;
453 /* For asynchronous children, the child_proc resources will be freed
454 when the last pipe read descriptor is closed; for synchronous
455 children, we must explicitly free the resources now because
456 register_child has not been called. */
457 if (cp->fd == -1)
458 delete_child (cp);
461 /* Wait for any of our existing child processes to die
462 When it does, close its handle
463 Return the pid and fill in the status if non-NULL. */
466 sys_wait (int *status)
468 DWORD active, retval;
469 int nh;
470 int pid;
471 child_process *cp, *cps[MAX_CHILDREN];
472 HANDLE wait_hnd[MAX_CHILDREN];
474 nh = 0;
475 if (dead_child != NULL)
477 /* We want to wait for a specific child */
478 wait_hnd[nh] = dead_child->procinfo.hProcess;
479 cps[nh] = dead_child;
480 if (!wait_hnd[nh]) abort ();
481 nh++;
482 active = 0;
483 goto get_result;
485 else
487 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
488 /* some child_procs might be sockets; ignore them */
489 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
491 wait_hnd[nh] = cp->procinfo.hProcess;
492 cps[nh] = cp;
493 nh++;
497 if (nh == 0)
499 /* Nothing to wait on, so fail */
500 errno = ECHILD;
501 return -1;
506 /* Check for quit about once a second. */
507 QUIT;
508 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
509 } while (active == WAIT_TIMEOUT);
511 if (active == WAIT_FAILED)
513 errno = EBADF;
514 return -1;
516 else if (active >= WAIT_OBJECT_0
517 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
519 active -= WAIT_OBJECT_0;
521 else if (active >= WAIT_ABANDONED_0
522 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
524 active -= WAIT_ABANDONED_0;
526 else
527 abort ();
529 get_result:
530 if (!GetExitCodeProcess (wait_hnd[active], &retval))
532 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
533 GetLastError ()));
534 retval = 1;
536 if (retval == STILL_ACTIVE)
538 /* Should never happen */
539 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
540 errno = EINVAL;
541 return -1;
544 /* Massage the exit code from the process to match the format expected
545 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
546 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
548 if (retval == STATUS_CONTROL_C_EXIT)
549 retval = SIGINT;
550 else
551 retval <<= 8;
553 cp = cps[active];
554 pid = cp->pid;
555 #ifdef FULL_DEBUG
556 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
557 #endif
559 if (status)
561 *status = retval;
563 else if (synch_process_alive)
565 synch_process_alive = 0;
567 /* Report the status of the synchronous process. */
568 if (WIFEXITED (retval))
569 synch_process_retcode = WRETCODE (retval);
570 else if (WIFSIGNALED (retval))
572 int code = WTERMSIG (retval);
573 char *signame;
575 synchronize_system_messages_locale ();
576 signame = strsignal (code);
578 if (signame == 0)
579 signame = "unknown";
581 synch_process_death = signame;
584 reap_subprocess (cp);
587 reap_subprocess (cp);
589 return pid;
592 void
593 w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app, int * is_gui_app)
595 file_data executable;
596 char * p;
598 /* Default values in case we can't tell for sure. */
599 *is_dos_app = FALSE;
600 *is_cygnus_app = FALSE;
601 *is_gui_app = FALSE;
603 if (!open_input_file (&executable, filename))
604 return;
606 p = strrchr (filename, '.');
608 /* We can only identify DOS .com programs from the extension. */
609 if (p && stricmp (p, ".com") == 0)
610 *is_dos_app = TRUE;
611 else if (p && (stricmp (p, ".bat") == 0
612 || stricmp (p, ".cmd") == 0))
614 /* A DOS shell script - it appears that CreateProcess is happy to
615 accept this (somewhat surprisingly); presumably it looks at
616 COMSPEC to determine what executable to actually invoke.
617 Therefore, we have to do the same here as well. */
618 /* Actually, I think it uses the program association for that
619 extension, which is defined in the registry. */
620 p = egetenv ("COMSPEC");
621 if (p)
622 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
624 else
626 /* Look for DOS .exe signature - if found, we must also check that
627 it isn't really a 16- or 32-bit Windows exe, since both formats
628 start with a DOS program stub. Note that 16-bit Windows
629 executables use the OS/2 1.x format. */
631 IMAGE_DOS_HEADER * dos_header;
632 IMAGE_NT_HEADERS * nt_header;
634 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
635 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
636 goto unwind;
638 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
640 if ((char *) nt_header > (char *) dos_header + executable.size)
642 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
643 *is_dos_app = TRUE;
645 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
646 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
648 *is_dos_app = TRUE;
650 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
652 /* Look for cygwin.dll in DLL import list. */
653 IMAGE_DATA_DIRECTORY import_dir =
654 nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
655 IMAGE_IMPORT_DESCRIPTOR * imports;
656 IMAGE_SECTION_HEADER * section;
658 section = rva_to_section (import_dir.VirtualAddress, nt_header);
659 imports = RVA_TO_PTR (import_dir.VirtualAddress, section, executable);
661 for ( ; imports->Name; imports++)
663 char * dllname = RVA_TO_PTR (imports->Name, section, executable);
665 /* The exact name of the cygwin dll has changed with
666 various releases, but hopefully this will be reasonably
667 future proof. */
668 if (strncmp (dllname, "cygwin", 6) == 0)
670 *is_cygnus_app = TRUE;
671 break;
675 /* Check whether app is marked as a console or windowed (aka
676 GUI) app. Accept Posix and OS2 subsytem apps as console
677 apps. */
678 *is_gui_app = (nt_header->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
682 unwind:
683 close_file_data (&executable);
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 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 char *sepchars = " \t";
751 /* We don't care about the other modes */
752 if (mode != _P_NOWAIT)
754 errno = EINVAL;
755 return -1;
758 /* Handle executable names without an executable suffix. */
759 program = make_string (cmdname, strlen (cmdname));
760 if (NILP (Ffile_executable_p (program)))
762 struct gcpro gcpro1;
764 full = Qnil;
765 GCPRO1 (program);
766 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
767 UNGCPRO;
768 if (NILP (full))
770 errno = EINVAL;
771 return -1;
773 program = full;
776 /* make sure argv[0] and cmdname are both in DOS format */
777 cmdname = SDATA (program);
778 unixtodos_filename (cmdname);
779 argv[0] = cmdname;
781 /* Determine whether program is a 16-bit DOS executable, or a w32
782 executable that is implicitly linked to the Cygnus dll (implying it
783 was compiled with the Cygnus GNU toolchain and hence relies on
784 cygwin.dll to parse the command line - we use this to decide how to
785 escape quote chars in command line args that must be quoted).
787 Also determine whether it is a GUI app, so that we don't hide its
788 initial window unless specifically requested. */
789 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
791 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
792 application to start it by specifying the helper app as cmdname,
793 while leaving the real app name as argv[0]. */
794 if (is_dos_app)
796 cmdname = alloca (MAXPATHLEN);
797 if (egetenv ("CMDPROXY"))
798 strcpy (cmdname, egetenv ("CMDPROXY"));
799 else
801 strcpy (cmdname, SDATA (Vinvocation_directory));
802 strcat (cmdname, "cmdproxy.exe");
804 unixtodos_filename (cmdname);
807 /* we have to do some conjuring here to put argv and envp into the
808 form CreateProcess wants... argv needs to be a space separated/null
809 terminated list of parameters, and envp is a null
810 separated/double-null terminated list of parameters.
812 Additionally, zero-length args and args containing whitespace or
813 quote chars need to be wrapped in double quotes - for this to work,
814 embedded quotes need to be escaped as well. The aim is to ensure
815 the child process reconstructs the argv array we start with
816 exactly, so we treat quotes at the beginning and end of arguments
817 as embedded quotes.
819 The w32 GNU-based library from Cygnus doubles quotes to escape
820 them, while MSVC uses backslash for escaping. (Actually the MSVC
821 startup code does attempt to recognise doubled quotes and accept
822 them, but gets it wrong and ends up requiring three quotes to get a
823 single embedded quote!) So by default we decide whether to use
824 quote or backslash as the escape character based on whether the
825 binary is apparently a Cygnus compiled app.
827 Note that using backslash to escape embedded quotes requires
828 additional special handling if an embedded quote is already
829 preceeded by backslash, or if an arg requiring quoting ends with
830 backslash. In such cases, the run of escape characters needs to be
831 doubled. For consistency, we apply this special handling as long
832 as the escape character is not quote.
834 Since we have no idea how large argv and envp are likely to be we
835 figure out list lengths on the fly and allocate them. */
837 if (!NILP (Vw32_quote_process_args))
839 do_quoting = 1;
840 /* Override escape char by binding w32-quote-process-args to
841 desired character, or use t for auto-selection. */
842 if (INTEGERP (Vw32_quote_process_args))
843 escape_char = XINT (Vw32_quote_process_args);
844 else
845 escape_char = is_cygnus_app ? '"' : '\\';
848 /* Cygwin apps needs quoting a bit more often */
849 if (escape_char == '"')
850 sepchars = "\r\n\t\f '";
852 /* do argv... */
853 arglen = 0;
854 targ = argv;
855 while (*targ)
857 char * p = *targ;
858 int need_quotes = 0;
859 int escape_char_run = 0;
861 if (*p == 0)
862 need_quotes = 1;
863 for ( ; *p; p++)
865 if (escape_char == '"' && *p == '\\')
866 /* If it's a Cygwin app, \ needs to be escaped. */
867 arglen++;
868 else if (*p == '"')
870 /* allow for embedded quotes to be escaped */
871 arglen++;
872 need_quotes = 1;
873 /* handle the case where the embedded quote is already escaped */
874 if (escape_char_run > 0)
876 /* To preserve the arg exactly, we need to double the
877 preceding escape characters (plus adding one to
878 escape the quote character itself). */
879 arglen += escape_char_run;
882 else if (strchr (sepchars, *p) != NULL)
884 need_quotes = 1;
887 if (*p == escape_char && escape_char != '"')
888 escape_char_run++;
889 else
890 escape_char_run = 0;
892 if (need_quotes)
894 arglen += 2;
895 /* handle the case where the arg ends with an escape char - we
896 must not let the enclosing quote be escaped. */
897 if (escape_char_run > 0)
898 arglen += escape_char_run;
900 arglen += strlen (*targ++) + 1;
902 cmdline = alloca (arglen);
903 targ = argv;
904 parg = cmdline;
905 while (*targ)
907 char * p = *targ;
908 int need_quotes = 0;
910 if (*p == 0)
911 need_quotes = 1;
913 if (do_quoting)
915 for ( ; *p; p++)
916 if ((strchr (sepchars, *p) != NULL) || *p == '"')
917 need_quotes = 1;
919 if (need_quotes)
921 int escape_char_run = 0;
922 char * first;
923 char * last;
925 p = *targ;
926 first = p;
927 last = p + strlen (p) - 1;
928 *parg++ = '"';
929 #if 0
930 /* This version does not escape quotes if they occur at the
931 beginning or end of the arg - this could lead to incorrect
932 behaviour when the arg itself represents a command line
933 containing quoted args. I believe this was originally done
934 as a hack to make some things work, before
935 `w32-quote-process-args' was added. */
936 while (*p)
938 if (*p == '"' && p > first && p < last)
939 *parg++ = escape_char; /* escape embedded quotes */
940 *parg++ = *p++;
942 #else
943 for ( ; *p; p++)
945 if (*p == '"')
947 /* double preceding escape chars if any */
948 while (escape_char_run > 0)
950 *parg++ = escape_char;
951 escape_char_run--;
953 /* escape all quote chars, even at beginning or end */
954 *parg++ = escape_char;
956 else if (escape_char == '"' && *p == '\\')
957 *parg++ = '\\';
958 *parg++ = *p;
960 if (*p == escape_char && escape_char != '"')
961 escape_char_run++;
962 else
963 escape_char_run = 0;
965 /* double escape chars before enclosing quote */
966 while (escape_char_run > 0)
968 *parg++ = escape_char;
969 escape_char_run--;
971 #endif
972 *parg++ = '"';
974 else
976 strcpy (parg, *targ);
977 parg += strlen (*targ);
979 *parg++ = ' ';
980 targ++;
982 *--parg = '\0';
984 /* and envp... */
985 arglen = 1;
986 targ = envp;
987 numenv = 1; /* for end null */
988 while (*targ)
990 arglen += strlen (*targ++) + 1;
991 numenv++;
993 /* extra env vars... */
994 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
995 GetCurrentProcessId ());
996 arglen += strlen (ppid_env_var_buffer) + 1;
997 numenv++;
999 /* merge env passed in and extra env into one, and sort it. */
1000 targ = (char **) alloca (numenv * sizeof (char *));
1001 merge_and_sort_env (envp, extra_env, targ);
1003 /* concatenate env entries. */
1004 env = alloca (arglen);
1005 parg = env;
1006 while (*targ)
1008 strcpy (parg, *targ);
1009 parg += strlen (*targ++);
1010 *parg++ = '\0';
1012 *parg++ = '\0';
1013 *parg = '\0';
1015 cp = new_child ();
1016 if (cp == NULL)
1018 errno = EAGAIN;
1019 return -1;
1022 /* Now create the process. */
1023 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1025 delete_child (cp);
1026 errno = ENOEXEC;
1027 return -1;
1030 return pid;
1033 /* Emulate the select call
1034 Wait for available input on any of the given rfds, or timeout if
1035 a timeout is given and no input is detected
1036 wfds and efds are not supported and must be NULL.
1038 For simplicity, we detect the death of child processes here and
1039 synchronously call the SIGCHLD handler. Since it is possible for
1040 children to be created without a corresponding pipe handle from which
1041 to read output, we wait separately on the process handles as well as
1042 the char_avail events for each process pipe. We only call
1043 wait/reap_process when the process actually terminates.
1045 To reduce the number of places in which Emacs can be hung such that
1046 C-g is not able to interrupt it, we always wait on interrupt_handle
1047 (which is signalled by the input thread when C-g is detected). If we
1048 detect that we were woken up by C-g, we return -1 with errno set to
1049 EINTR as on Unix. */
1051 /* From ntterm.c */
1052 extern HANDLE keyboard_handle;
1054 /* From w32xfns.c */
1055 extern HANDLE interrupt_handle;
1057 /* From process.c */
1058 extern int proc_buffered_char[];
1061 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1062 EMACS_TIME *timeout)
1064 SELECT_TYPE orfds;
1065 DWORD timeout_ms, start_time;
1066 int i, nh, nc, nr;
1067 DWORD active;
1068 child_process *cp, *cps[MAX_CHILDREN];
1069 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1070 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1072 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1074 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1075 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1077 Sleep (timeout_ms);
1078 return 0;
1081 /* Otherwise, we only handle rfds, so fail otherwise. */
1082 if (rfds == NULL || wfds != NULL || efds != NULL)
1084 errno = EINVAL;
1085 return -1;
1088 orfds = *rfds;
1089 FD_ZERO (rfds);
1090 nr = 0;
1092 /* Always wait on interrupt_handle, to detect C-g (quit). */
1093 wait_hnd[0] = interrupt_handle;
1094 fdindex[0] = -1;
1096 /* Build a list of pipe handles to wait on. */
1097 nh = 1;
1098 for (i = 0; i < nfds; i++)
1099 if (FD_ISSET (i, &orfds))
1101 if (i == 0)
1103 if (keyboard_handle)
1105 /* Handle stdin specially */
1106 wait_hnd[nh] = keyboard_handle;
1107 fdindex[nh] = i;
1108 nh++;
1111 /* Check for any emacs-generated input in the queue since
1112 it won't be detected in the wait */
1113 if (detect_input_pending ())
1115 FD_SET (i, rfds);
1116 return 1;
1119 else
1121 /* Child process and socket input */
1122 cp = fd_info[i].cp;
1123 if (cp)
1125 int current_status = cp->status;
1127 if (current_status == STATUS_READ_ACKNOWLEDGED)
1129 /* Tell reader thread which file handle to use. */
1130 cp->fd = i;
1131 /* Wake up the reader thread for this process */
1132 cp->status = STATUS_READ_READY;
1133 if (!SetEvent (cp->char_consumed))
1134 DebPrint (("nt_select.SetEvent failed with "
1135 "%lu for fd %ld\n", GetLastError (), i));
1138 #ifdef CHECK_INTERLOCK
1139 /* slightly crude cross-checking of interlock between threads */
1141 current_status = cp->status;
1142 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1144 /* char_avail has been signalled, so status (which may
1145 have changed) should indicate read has completed
1146 but has not been acknowledged. */
1147 current_status = cp->status;
1148 if (current_status != STATUS_READ_SUCCEEDED
1149 && current_status != STATUS_READ_FAILED)
1150 DebPrint (("char_avail set, but read not completed: status %d\n",
1151 current_status));
1153 else
1155 /* char_avail has not been signalled, so status should
1156 indicate that read is in progress; small possibility
1157 that read has completed but event wasn't yet signalled
1158 when we tested it (because a context switch occurred
1159 or if running on separate CPUs). */
1160 if (current_status != STATUS_READ_READY
1161 && current_status != STATUS_READ_IN_PROGRESS
1162 && current_status != STATUS_READ_SUCCEEDED
1163 && current_status != STATUS_READ_FAILED)
1164 DebPrint (("char_avail reset, but read status is bad: %d\n",
1165 current_status));
1167 #endif
1168 wait_hnd[nh] = cp->char_avail;
1169 fdindex[nh] = i;
1170 if (!wait_hnd[nh]) abort ();
1171 nh++;
1172 #ifdef FULL_DEBUG
1173 DebPrint (("select waiting on child %d fd %d\n",
1174 cp-child_procs, i));
1175 #endif
1177 else
1179 /* Unable to find something to wait on for this fd, skip */
1181 /* Note that this is not a fatal error, and can in fact
1182 happen in unusual circumstances. Specifically, if
1183 sys_spawnve fails, eg. because the program doesn't
1184 exist, and debug-on-error is t so Fsignal invokes a
1185 nested input loop, then the process output pipe is
1186 still included in input_wait_mask with no child_proc
1187 associated with it. (It is removed when the debugger
1188 exits the nested input loop and the error is thrown.) */
1190 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1195 count_children:
1196 /* Add handles of child processes. */
1197 nc = 0;
1198 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
1199 /* Some child_procs might be sockets; ignore them. Also some
1200 children may have died already, but we haven't finished reading
1201 the process output; ignore them too. */
1202 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1203 && (cp->fd < 0
1204 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1205 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1208 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1209 cps[nc] = cp;
1210 nc++;
1213 /* Nothing to look for, so we didn't find anything */
1214 if (nh + nc == 0)
1216 if (timeout)
1217 Sleep (timeout_ms);
1218 return 0;
1221 start_time = GetTickCount ();
1223 /* Wait for input or child death to be signalled. If user input is
1224 allowed, then also accept window messages. */
1225 if (FD_ISSET (0, &orfds))
1226 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1227 QS_ALLINPUT);
1228 else
1229 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1231 if (active == WAIT_FAILED)
1233 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1234 nh + nc, timeout_ms, GetLastError ()));
1235 /* don't return EBADF - this causes wait_reading_process_output to
1236 abort; WAIT_FAILED is returned when single-stepping under
1237 Windows 95 after switching thread focus in debugger, and
1238 possibly at other times. */
1239 errno = EINTR;
1240 return -1;
1242 else if (active == WAIT_TIMEOUT)
1244 return 0;
1246 else if (active >= WAIT_OBJECT_0
1247 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1249 active -= WAIT_OBJECT_0;
1251 else if (active >= WAIT_ABANDONED_0
1252 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1254 active -= WAIT_ABANDONED_0;
1256 else
1257 abort ();
1259 /* Loop over all handles after active (now officially documented as
1260 being the first signalled handle in the array). We do this to
1261 ensure fairness, so that all channels with data available will be
1262 processed - otherwise higher numbered channels could be starved. */
1265 if (active == nh + nc)
1267 /* There are messages in the lisp thread's queue; we must
1268 drain the queue now to ensure they are processed promptly,
1269 because if we don't do so, we will not be woken again until
1270 further messages arrive.
1272 NB. If ever we allow window message procedures to callback
1273 into lisp, we will need to ensure messages are dispatched
1274 at a safe time for lisp code to be run (*), and we may also
1275 want to provide some hooks in the dispatch loop to cater
1276 for modeless dialogs created by lisp (ie. to register
1277 window handles to pass to IsDialogMessage).
1279 (*) Note that MsgWaitForMultipleObjects above is an
1280 internal dispatch point for messages that are sent to
1281 windows created by this thread. */
1282 drain_message_queue ();
1284 else if (active >= nh)
1286 cp = cps[active - nh];
1288 /* We cannot always signal SIGCHLD immediately; if we have not
1289 finished reading the process output, we must delay sending
1290 SIGCHLD until we do. */
1292 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1293 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1294 /* SIG_DFL for SIGCHLD is ignore */
1295 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1296 sig_handlers[SIGCHLD] != SIG_IGN)
1298 #ifdef FULL_DEBUG
1299 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1300 cp->pid));
1301 #endif
1302 dead_child = cp;
1303 sig_handlers[SIGCHLD] (SIGCHLD);
1304 dead_child = NULL;
1307 else if (fdindex[active] == -1)
1309 /* Quit (C-g) was detected. */
1310 errno = EINTR;
1311 return -1;
1313 else if (fdindex[active] == 0)
1315 /* Keyboard input available */
1316 FD_SET (0, rfds);
1317 nr++;
1319 else
1321 /* must be a socket or pipe - read ahead should have
1322 completed, either succeeding or failing. */
1323 FD_SET (fdindex[active], rfds);
1324 nr++;
1327 /* Even though wait_reading_process_output only reads from at most
1328 one channel, we must process all channels here so that we reap
1329 all children that have died. */
1330 while (++active < nh + nc)
1331 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1332 break;
1333 } while (active < nh + nc);
1335 /* If no input has arrived and timeout hasn't expired, wait again. */
1336 if (nr == 0)
1338 DWORD elapsed = GetTickCount () - start_time;
1340 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1342 if (timeout_ms != INFINITE)
1343 timeout_ms -= elapsed;
1344 goto count_children;
1348 return nr;
1351 /* Substitute for certain kill () operations */
1353 static BOOL CALLBACK
1354 find_child_console (HWND hwnd, LPARAM arg)
1356 child_process * cp = (child_process *) arg;
1357 DWORD thread_id;
1358 DWORD process_id;
1360 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1361 if (process_id == cp->procinfo.dwProcessId)
1363 char window_class[32];
1365 GetClassName (hwnd, window_class, sizeof (window_class));
1366 if (strcmp (window_class,
1367 (os_subtype == OS_WIN95)
1368 ? "tty"
1369 : "ConsoleWindowClass") == 0)
1371 cp->hwnd = hwnd;
1372 return FALSE;
1375 /* keep looking */
1376 return TRUE;
1380 sys_kill (int pid, int sig)
1382 child_process *cp;
1383 HANDLE proc_hand;
1384 int need_to_free = 0;
1385 int rc = 0;
1387 /* Only handle signals that will result in the process dying */
1388 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1390 errno = EINVAL;
1391 return -1;
1394 cp = find_child_pid (pid);
1395 if (cp == NULL)
1397 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1398 if (proc_hand == NULL)
1400 errno = EPERM;
1401 return -1;
1403 need_to_free = 1;
1405 else
1407 proc_hand = cp->procinfo.hProcess;
1408 pid = cp->procinfo.dwProcessId;
1410 /* Try to locate console window for process. */
1411 EnumWindows (find_child_console, (LPARAM) cp);
1414 if (sig == SIGINT || sig == SIGQUIT)
1416 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1418 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1419 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1420 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1421 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1422 HWND foreground_window;
1424 if (break_scan_code == 0)
1426 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1427 vk_break_code = 'C';
1428 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1431 foreground_window = GetForegroundWindow ();
1432 if (foreground_window)
1434 /* NT 5.0, and apparently also Windows 98, will not allow
1435 a Window to be set to foreground directly without the
1436 user's involvement. The workaround is to attach
1437 ourselves to the thread that owns the foreground
1438 window, since that is the only thread that can set the
1439 foreground window. */
1440 DWORD foreground_thread, child_thread;
1441 foreground_thread =
1442 GetWindowThreadProcessId (foreground_window, NULL);
1443 if (foreground_thread == GetCurrentThreadId ()
1444 || !AttachThreadInput (GetCurrentThreadId (),
1445 foreground_thread, TRUE))
1446 foreground_thread = 0;
1448 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1449 if (child_thread == GetCurrentThreadId ()
1450 || !AttachThreadInput (GetCurrentThreadId (),
1451 child_thread, TRUE))
1452 child_thread = 0;
1454 /* Set the foreground window to the child. */
1455 if (SetForegroundWindow (cp->hwnd))
1457 /* Generate keystrokes as if user had typed Ctrl-Break or
1458 Ctrl-C. */
1459 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1460 keybd_event (vk_break_code, break_scan_code,
1461 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1462 keybd_event (vk_break_code, break_scan_code,
1463 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1464 | KEYEVENTF_KEYUP, 0);
1465 keybd_event (VK_CONTROL, control_scan_code,
1466 KEYEVENTF_KEYUP, 0);
1468 /* Sleep for a bit to give time for Emacs frame to respond
1469 to focus change events (if Emacs was active app). */
1470 Sleep (100);
1472 SetForegroundWindow (foreground_window);
1474 /* Detach from the foreground and child threads now that
1475 the foreground switching is over. */
1476 if (foreground_thread)
1477 AttachThreadInput (GetCurrentThreadId (),
1478 foreground_thread, FALSE);
1479 if (child_thread)
1480 AttachThreadInput (GetCurrentThreadId (),
1481 child_thread, FALSE);
1484 /* Ctrl-Break is NT equivalent of SIGINT. */
1485 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1487 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1488 "for pid %lu\n", GetLastError (), pid));
1489 errno = EINVAL;
1490 rc = -1;
1493 else
1495 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1497 #if 1
1498 if (os_subtype == OS_WIN95)
1501 Another possibility is to try terminating the VDM out-right by
1502 calling the Shell VxD (id 0x17) V86 interface, function #4
1503 "SHELL_Destroy_VM", ie.
1505 mov edx,4
1506 mov ebx,vm_handle
1507 call shellapi
1509 First need to determine the current VM handle, and then arrange for
1510 the shellapi call to be made from the system vm (by using
1511 Switch_VM_and_callback).
1513 Could try to invoke DestroyVM through CallVxD.
1516 #if 0
1517 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1518 to hang when cmdproxy is used in conjunction with
1519 command.com for an interactive shell. Posting
1520 WM_CLOSE pops up a dialog that, when Yes is selected,
1521 does the same thing. TerminateProcess is also less
1522 than ideal in that subprocesses tend to stick around
1523 until the machine is shutdown, but at least it
1524 doesn't freeze the 16-bit subsystem. */
1525 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1526 #endif
1527 if (!TerminateProcess (proc_hand, 0xff))
1529 DebPrint (("sys_kill.TerminateProcess returned %d "
1530 "for pid %lu\n", GetLastError (), pid));
1531 errno = EINVAL;
1532 rc = -1;
1535 else
1536 #endif
1537 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1539 /* Kill the process. On W32 this doesn't kill child processes
1540 so it doesn't work very well for shells which is why it's not
1541 used in every case. */
1542 else if (!TerminateProcess (proc_hand, 0xff))
1544 DebPrint (("sys_kill.TerminateProcess returned %d "
1545 "for pid %lu\n", GetLastError (), pid));
1546 errno = EINVAL;
1547 rc = -1;
1551 if (need_to_free)
1552 CloseHandle (proc_hand);
1554 return rc;
1557 /* extern int report_file_error (char *, Lisp_Object); */
1559 /* The following two routines are used to manipulate stdin, stdout, and
1560 stderr of our child processes.
1562 Assuming that in, out, and err are *not* inheritable, we make them
1563 stdin, stdout, and stderr of the child as follows:
1565 - Save the parent's current standard handles.
1566 - Set the std handles to inheritable duplicates of the ones being passed in.
1567 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1568 NT file handle for a crt file descriptor.)
1569 - Spawn the child, which inherits in, out, and err as stdin,
1570 stdout, and stderr. (see Spawnve)
1571 - Close the std handles passed to the child.
1572 - Reset the parent's standard handles to the saved handles.
1573 (see reset_standard_handles)
1574 We assume that the caller closes in, out, and err after calling us. */
1576 void
1577 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1579 HANDLE parent;
1580 HANDLE newstdin, newstdout, newstderr;
1582 parent = GetCurrentProcess ();
1584 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1585 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1586 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1588 /* make inheritable copies of the new handles */
1589 if (!DuplicateHandle (parent,
1590 (HANDLE) _get_osfhandle (in),
1591 parent,
1592 &newstdin,
1594 TRUE,
1595 DUPLICATE_SAME_ACCESS))
1596 report_file_error ("Duplicating input handle for child", Qnil);
1598 if (!DuplicateHandle (parent,
1599 (HANDLE) _get_osfhandle (out),
1600 parent,
1601 &newstdout,
1603 TRUE,
1604 DUPLICATE_SAME_ACCESS))
1605 report_file_error ("Duplicating output handle for child", Qnil);
1607 if (!DuplicateHandle (parent,
1608 (HANDLE) _get_osfhandle (err),
1609 parent,
1610 &newstderr,
1612 TRUE,
1613 DUPLICATE_SAME_ACCESS))
1614 report_file_error ("Duplicating error handle for child", Qnil);
1616 /* and store them as our std handles */
1617 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1618 report_file_error ("Changing stdin handle", Qnil);
1620 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1621 report_file_error ("Changing stdout handle", Qnil);
1623 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1624 report_file_error ("Changing stderr handle", Qnil);
1627 void
1628 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1630 /* close the duplicated handles passed to the child */
1631 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1632 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1633 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1635 /* now restore parent's saved std handles */
1636 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1637 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1638 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1641 void
1642 set_process_dir (char * dir)
1644 process_dir = dir;
1647 #ifdef HAVE_SOCKETS
1649 /* To avoid problems with winsock implementations that work over dial-up
1650 connections causing or requiring a connection to exist while Emacs is
1651 running, Emacs no longer automatically loads winsock on startup if it
1652 is present. Instead, it will be loaded when open-network-stream is
1653 first called.
1655 To allow full control over when winsock is loaded, we provide these
1656 two functions to dynamically load and unload winsock. This allows
1657 dial-up users to only be connected when they actually need to use
1658 socket services. */
1660 /* From nt.c */
1661 extern HANDLE winsock_lib;
1662 extern BOOL term_winsock (void);
1663 extern BOOL init_winsock (int load_now);
1665 extern Lisp_Object Vsystem_name;
1667 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1668 doc: /* Test for presence of the Windows socket library `winsock'.
1669 Returns non-nil if winsock support is present, nil otherwise.
1671 If the optional argument LOAD-NOW is non-nil, the winsock library is
1672 also loaded immediately if not already loaded. If winsock is loaded,
1673 the winsock local hostname is returned (since this may be different from
1674 the value of `system-name' and should supplant it), otherwise t is
1675 returned to indicate winsock support is present. */)
1676 (load_now)
1677 Lisp_Object load_now;
1679 int have_winsock;
1681 have_winsock = init_winsock (!NILP (load_now));
1682 if (have_winsock)
1684 if (winsock_lib != NULL)
1686 /* Return new value for system-name. The best way to do this
1687 is to call init_system_name, saving and restoring the
1688 original value to avoid side-effects. */
1689 Lisp_Object orig_hostname = Vsystem_name;
1690 Lisp_Object hostname;
1692 init_system_name ();
1693 hostname = Vsystem_name;
1694 Vsystem_name = orig_hostname;
1695 return hostname;
1697 return Qt;
1699 return Qnil;
1702 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1703 0, 0, 0,
1704 doc: /* Unload the Windows socket library `winsock' if loaded.
1705 This is provided to allow dial-up socket connections to be disconnected
1706 when no longer needed. Returns nil without unloading winsock if any
1707 socket connections still exist. */)
1710 return term_winsock () ? Qt : Qnil;
1713 #endif /* HAVE_SOCKETS */
1716 /* Some miscellaneous functions that are Windows specific, but not GUI
1717 specific (ie. are applicable in terminal or batch mode as well). */
1719 /* lifted from fileio.c */
1720 #define CORRECT_DIR_SEPS(s) \
1721 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1722 else unixtodos_filename (s); \
1723 } while (0)
1725 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1726 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1727 If FILENAME does not exist, return nil.
1728 All path elements in FILENAME are converted to their short names. */)
1729 (filename)
1730 Lisp_Object filename;
1732 char shortname[MAX_PATH];
1734 CHECK_STRING (filename);
1736 /* first expand it. */
1737 filename = Fexpand_file_name (filename, Qnil);
1739 /* luckily, this returns the short version of each element in the path. */
1740 if (GetShortPathName (SDATA (filename), shortname, MAX_PATH) == 0)
1741 return Qnil;
1743 CORRECT_DIR_SEPS (shortname);
1745 return build_string (shortname);
1749 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1750 1, 1, 0,
1751 doc: /* Return the long file name version of the full path of FILENAME.
1752 If FILENAME does not exist, return nil.
1753 All path elements in FILENAME are converted to their long names. */)
1754 (filename)
1755 Lisp_Object filename;
1757 char longname[ MAX_PATH ];
1759 CHECK_STRING (filename);
1761 /* first expand it. */
1762 filename = Fexpand_file_name (filename, Qnil);
1764 if (!w32_get_long_filename (SDATA (filename), longname, MAX_PATH))
1765 return Qnil;
1767 CORRECT_DIR_SEPS (longname);
1769 return build_string (longname);
1772 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1773 Sw32_set_process_priority, 2, 2, 0,
1774 doc: /* Set the priority of PROCESS to PRIORITY.
1775 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1776 priority of the process whose pid is PROCESS is changed.
1777 PRIORITY should be one of the symbols high, normal, or low;
1778 any other symbol will be interpreted as normal.
1780 If successful, the return value is t, otherwise nil. */)
1781 (process, priority)
1782 Lisp_Object process, priority;
1784 HANDLE proc_handle = GetCurrentProcess ();
1785 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1786 Lisp_Object result = Qnil;
1788 CHECK_SYMBOL (priority);
1790 if (!NILP (process))
1792 DWORD pid;
1793 child_process *cp;
1795 CHECK_NUMBER (process);
1797 /* Allow pid to be an internally generated one, or one obtained
1798 externally. This is necessary because real pids on Win95 are
1799 negative. */
1801 pid = XINT (process);
1802 cp = find_child_pid (pid);
1803 if (cp != NULL)
1804 pid = cp->procinfo.dwProcessId;
1806 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1809 if (EQ (priority, Qhigh))
1810 priority_class = HIGH_PRIORITY_CLASS;
1811 else if (EQ (priority, Qlow))
1812 priority_class = IDLE_PRIORITY_CLASS;
1814 if (proc_handle != NULL)
1816 if (SetPriorityClass (proc_handle, priority_class))
1817 result = Qt;
1818 if (!NILP (process))
1819 CloseHandle (proc_handle);
1822 return result;
1825 #ifdef HAVE_LANGINFO_CODESET
1826 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1827 char *nl_langinfo (nl_item item)
1829 /* Conversion of Posix item numbers to their Windows equivalents. */
1830 static const LCTYPE w32item[] = {
1831 LOCALE_IDEFAULTANSICODEPAGE,
1832 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1833 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1834 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1835 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1836 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1837 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1840 static char *nl_langinfo_buf = NULL;
1841 static int nl_langinfo_len = 0;
1843 if (nl_langinfo_len <= 0)
1844 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1846 if (item < 0 || item >= _NL_NUM)
1847 nl_langinfo_buf[0] = 0;
1848 else
1850 LCID cloc = GetThreadLocale ();
1851 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1852 NULL, 0);
1854 if (need_len <= 0)
1855 nl_langinfo_buf[0] = 0;
1856 else
1858 if (item == CODESET)
1860 need_len += 2; /* for the "cp" prefix */
1861 if (need_len < 8) /* for the case we call GetACP */
1862 need_len = 8;
1864 if (nl_langinfo_len <= need_len)
1865 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1866 nl_langinfo_len = need_len);
1867 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1868 nl_langinfo_buf, nl_langinfo_len))
1869 nl_langinfo_buf[0] = 0;
1870 else if (item == CODESET)
1872 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1873 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1874 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1875 else
1877 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1878 strlen (nl_langinfo_buf) + 1);
1879 nl_langinfo_buf[0] = 'c';
1880 nl_langinfo_buf[1] = 'p';
1885 return nl_langinfo_buf;
1887 #endif /* HAVE_LANGINFO_CODESET */
1889 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1890 Sw32_get_locale_info, 1, 2, 0,
1891 doc: /* Return information about the Windows locale LCID.
1892 By default, return a three letter locale code which encodes the default
1893 language as the first two characters, and the country or regionial variant
1894 as the third letter. For example, ENU refers to `English (United States)',
1895 while ENC means `English (Canadian)'.
1897 If the optional argument LONGFORM is t, the long form of the locale
1898 name is returned, e.g. `English (United States)' instead; if LONGFORM
1899 is a number, it is interpreted as an LCTYPE constant and the corresponding
1900 locale information is returned.
1902 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1903 (lcid, longform)
1904 Lisp_Object lcid, longform;
1906 int got_abbrev;
1907 int got_full;
1908 char abbrev_name[32] = { 0 };
1909 char full_name[256] = { 0 };
1911 CHECK_NUMBER (lcid);
1913 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1914 return Qnil;
1916 if (NILP (longform))
1918 got_abbrev = GetLocaleInfo (XINT (lcid),
1919 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1920 abbrev_name, sizeof (abbrev_name));
1921 if (got_abbrev)
1922 return build_string (abbrev_name);
1924 else if (EQ (longform, Qt))
1926 got_full = GetLocaleInfo (XINT (lcid),
1927 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1928 full_name, sizeof (full_name));
1929 if (got_full)
1930 return build_string (full_name);
1932 else if (NUMBERP (longform))
1934 got_full = GetLocaleInfo (XINT (lcid),
1935 XINT (longform),
1936 full_name, sizeof (full_name));
1937 if (got_full)
1938 return make_unibyte_string (full_name, got_full);
1941 return Qnil;
1945 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1946 Sw32_get_current_locale_id, 0, 0, 0,
1947 doc: /* Return Windows locale id for current locale setting.
1948 This is a numerical value; use `w32-get-locale-info' to convert to a
1949 human-readable form. */)
1952 return make_number (GetThreadLocale ());
1955 DWORD int_from_hex (char * s)
1957 DWORD val = 0;
1958 static char hex[] = "0123456789abcdefABCDEF";
1959 char * p;
1961 while (*s && (p = strchr(hex, *s)) != NULL)
1963 unsigned digit = p - hex;
1964 if (digit > 15)
1965 digit -= 6;
1966 val = val * 16 + digit;
1967 s++;
1969 return val;
1972 /* We need to build a global list, since the EnumSystemLocale callback
1973 function isn't given a context pointer. */
1974 Lisp_Object Vw32_valid_locale_ids;
1976 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
1978 DWORD id = int_from_hex (localeNum);
1979 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
1980 return TRUE;
1983 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
1984 Sw32_get_valid_locale_ids, 0, 0, 0,
1985 doc: /* Return list of all valid Windows locale ids.
1986 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1987 human-readable form. */)
1990 Vw32_valid_locale_ids = Qnil;
1992 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
1994 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
1995 return Vw32_valid_locale_ids;
1999 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2000 doc: /* Return Windows locale id for default locale setting.
2001 By default, the system default locale setting is returned; if the optional
2002 parameter USERP is non-nil, the user default locale setting is returned.
2003 This is a numerical value; use `w32-get-locale-info' to convert to a
2004 human-readable form. */)
2005 (userp)
2006 Lisp_Object userp;
2008 if (NILP (userp))
2009 return make_number (GetSystemDefaultLCID ());
2010 return make_number (GetUserDefaultLCID ());
2014 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2015 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2016 If successful, the new locale id is returned, otherwise nil. */)
2017 (lcid)
2018 Lisp_Object lcid;
2020 CHECK_NUMBER (lcid);
2022 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2023 return Qnil;
2025 if (!SetThreadLocale (XINT (lcid)))
2026 return Qnil;
2028 /* Need to set input thread locale if present. */
2029 if (dwWindowsThreadId)
2030 /* Reply is not needed. */
2031 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2033 return make_number (GetThreadLocale ());
2037 /* We need to build a global list, since the EnumCodePages callback
2038 function isn't given a context pointer. */
2039 Lisp_Object Vw32_valid_codepages;
2041 BOOL CALLBACK enum_codepage_fn (LPTSTR codepageNum)
2043 DWORD id = atoi (codepageNum);
2044 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2045 return TRUE;
2048 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2049 Sw32_get_valid_codepages, 0, 0, 0,
2050 doc: /* Return list of all valid Windows codepages. */)
2053 Vw32_valid_codepages = Qnil;
2055 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2057 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2058 return Vw32_valid_codepages;
2062 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2063 Sw32_get_console_codepage, 0, 0, 0,
2064 doc: /* Return current Windows codepage for console input. */)
2067 return make_number (GetConsoleCP ());
2071 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2072 Sw32_set_console_codepage, 1, 1, 0,
2073 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2074 The codepage setting affects keyboard input and display in tty mode.
2075 If successful, the new CP is returned, otherwise nil. */)
2076 (cp)
2077 Lisp_Object cp;
2079 CHECK_NUMBER (cp);
2081 if (!IsValidCodePage (XINT (cp)))
2082 return Qnil;
2084 if (!SetConsoleCP (XINT (cp)))
2085 return Qnil;
2087 return make_number (GetConsoleCP ());
2091 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2092 Sw32_get_console_output_codepage, 0, 0, 0,
2093 doc: /* Return current Windows codepage for console output. */)
2096 return make_number (GetConsoleOutputCP ());
2100 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2101 Sw32_set_console_output_codepage, 1, 1, 0,
2102 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2103 The codepage setting affects keyboard input and display in tty mode.
2104 If successful, the new CP is returned, otherwise nil. */)
2105 (cp)
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 (cp)
2125 Lisp_Object cp;
2127 CHARSETINFO info;
2129 CHECK_NUMBER (cp);
2131 if (!IsValidCodePage (XINT (cp)))
2132 return Qnil;
2134 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2135 return make_number (info.ciCharset);
2137 return Qnil;
2141 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2142 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2143 doc: /* Return list of Windows keyboard languages and layouts.
2144 The return value is a list of pairs of language id and layout id. */)
2147 int num_layouts = GetKeyboardLayoutList (0, NULL);
2148 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2149 Lisp_Object obj = Qnil;
2151 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2153 while (--num_layouts >= 0)
2155 DWORD kl = (DWORD) layouts[num_layouts];
2157 obj = Fcons (Fcons (make_number (kl & 0xffff),
2158 make_number ((kl >> 16) & 0xffff)),
2159 obj);
2163 return obj;
2167 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2168 Sw32_get_keyboard_layout, 0, 0, 0,
2169 doc: /* Return current Windows keyboard language and layout.
2170 The return value is the cons of the language id and the layout id. */)
2173 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2175 return Fcons (make_number (kl & 0xffff),
2176 make_number ((kl >> 16) & 0xffff));
2180 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2181 Sw32_set_keyboard_layout, 1, 1, 0,
2182 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2183 The keyboard layout setting affects interpretation of keyboard input.
2184 If successful, the new layout id is returned, otherwise nil. */)
2185 (layout)
2186 Lisp_Object layout;
2188 DWORD kl;
2190 CHECK_CONS (layout);
2191 CHECK_NUMBER_CAR (layout);
2192 CHECK_NUMBER_CDR (layout);
2194 kl = (XINT (XCAR (layout)) & 0xffff)
2195 | (XINT (XCDR (layout)) << 16);
2197 /* Synchronize layout with input thread. */
2198 if (dwWindowsThreadId)
2200 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2201 (WPARAM) kl, 0))
2203 MSG msg;
2204 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2206 if (msg.wParam == 0)
2207 return Qnil;
2210 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2211 return Qnil;
2213 return Fw32_get_keyboard_layout ();
2217 syms_of_ntproc ()
2219 Qhigh = intern ("high");
2220 Qlow = intern ("low");
2221 staticpro (&Qhigh);
2222 staticpro (&Qlow);
2224 #ifdef HAVE_SOCKETS
2225 defsubr (&Sw32_has_winsock);
2226 defsubr (&Sw32_unload_winsock);
2227 #endif
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 determing
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 link count in `file-attributes'.
2315 Note that this option is only useful for files on NTFS volumes, where hard links
2316 are supported. Moreover, it slows down `file-attributes' noticeably. */);
2317 Vw32_get_true_file_attributes = Qt;
2319 staticpro (&Vw32_valid_locale_ids);
2320 staticpro (&Vw32_valid_codepages);
2322 /* end of ntproc.c */
2324 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2325 (do not change this comment) */