1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
32 /* must include CRT headers *before* config.h */
42 /* This definition is missing from mingw32 headers. */
43 extern BOOL WINAPI
IsValidLocale(LCID
, DWORD
);
54 /* Control whether spawnve quotes arguments as necessary to ensure
55 correct parsing by child process. Because not all uses of spawnve
56 are careful about constructing argv arrays, we make this behaviour
57 conditional (off by default). */
58 Lisp_Object Vw32_quote_process_args
;
60 /* Control whether create_child causes the process' window to be
61 hidden. The default is nil. */
62 Lisp_Object Vw32_start_process_show_window
;
64 /* Control whether create_child causes the process to inherit Emacs'
65 console window, or be given a new one of its own. The default is
66 nil, to allow multiple DOS programs to run on Win95. Having separate
67 consoles also allows Emacs to cleanly terminate process groups. */
68 Lisp_Object Vw32_start_process_share_console
;
70 /* Control whether create_child cause the process to inherit Emacs'
71 error mode setting. The default is t, to minimize the possibility of
72 subprocesses blocking when accessing unmounted drives. */
73 Lisp_Object Vw32_start_process_inherit_error_mode
;
75 /* Time to sleep before reading from a subprocess output pipe - this
76 avoids the inefficiency of frequently reading small amounts of data.
77 This is primarily necessary for handling DOS processes on Windows 95,
78 but is useful for W32 processes on both Windows 95 and NT as well. */
79 Lisp_Object Vw32_pipe_read_delay
;
81 /* Control conversion of upper case file names to lower case.
82 nil means no, t means yes. */
83 Lisp_Object Vw32_downcase_file_names
;
85 /* Control whether stat() attempts to generate fake but hopefully
86 "accurate" inode values, by hashing the absolute truenames of files.
87 This should detect aliasing between long and short names, but still
88 allows the possibility of hash collisions. */
89 Lisp_Object Vw32_generate_fake_inodes
;
91 /* Control whether stat() attempts to determine file type and link count
92 exactly, at the expense of slower operation. Since true hard links
93 are supported on NTFS volumes, this is only relevant on NT. */
94 Lisp_Object Vw32_get_true_file_attributes
;
96 Lisp_Object Qhigh
, Qlow
;
99 void _DebPrint (const char *fmt
, ...)
104 va_start (args
, fmt
);
105 vsprintf (buf
, fmt
, args
);
107 OutputDebugString (buf
);
111 typedef void (_CALLBACK_
*signal_handler
)(int);
113 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
114 static signal_handler sig_handlers
[NSIG
];
116 /* Fake signal implementation to record the SIGCHLD handler. */
118 sys_signal (int sig
, signal_handler handler
)
127 old
= sig_handlers
[sig
];
128 sig_handlers
[sig
] = handler
;
132 /* Defined in <process.h> which conflicts with the local copy */
135 /* Child process management list. */
136 int child_proc_count
= 0;
137 child_process child_procs
[ MAX_CHILDREN
];
138 child_process
*dead_child
= NULL
;
140 DWORD WINAPI
reader_thread (void *arg
);
142 /* Find an unused process slot. */
149 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
150 if (!CHILD_ACTIVE (cp
))
152 if (child_proc_count
== MAX_CHILDREN
)
154 cp
= &child_procs
[child_proc_count
++];
157 memset (cp
, 0, sizeof(*cp
));
160 cp
->procinfo
.hProcess
= NULL
;
161 cp
->status
= STATUS_READ_ERROR
;
163 /* use manual reset event so that select() will function properly */
164 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
167 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
168 if (cp
->char_consumed
)
170 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
180 delete_child (child_process
*cp
)
184 /* Should not be deleting a child that is still needed. */
185 for (i
= 0; i
< MAXDESC
; i
++)
186 if (fd_info
[i
].cp
== cp
)
189 if (!CHILD_ACTIVE (cp
))
192 /* reap thread if necessary */
197 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
199 /* let the thread exit cleanly if possible */
200 cp
->status
= STATUS_READ_ERROR
;
201 SetEvent (cp
->char_consumed
);
202 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
204 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
205 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
206 TerminateThread (cp
->thrd
, 0);
209 CloseHandle (cp
->thrd
);
214 CloseHandle (cp
->char_avail
);
215 cp
->char_avail
= NULL
;
217 if (cp
->char_consumed
)
219 CloseHandle (cp
->char_consumed
);
220 cp
->char_consumed
= NULL
;
223 /* update child_proc_count (highest numbered slot in use plus one) */
224 if (cp
== child_procs
+ child_proc_count
- 1)
226 for (i
= child_proc_count
-1; i
>= 0; i
--)
227 if (CHILD_ACTIVE (&child_procs
[i
]))
229 child_proc_count
= i
+ 1;
234 child_proc_count
= 0;
237 /* Find a child by pid. */
238 static child_process
*
239 find_child_pid (DWORD pid
)
243 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
244 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
250 /* Thread proc for child process and socket reader threads. Each thread
251 is normally blocked until woken by select() to check for input by
252 reading one char. When the read completes, char_avail is signalled
253 to wake up the select emulator and the thread blocks itself again. */
255 reader_thread (void *arg
)
260 cp
= (child_process
*)arg
;
262 /* We have to wait for the go-ahead before we can start */
264 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
271 rc
= _sys_read_ahead (cp
->fd
);
273 /* The name char_avail is a misnomer - it really just means the
274 read-ahead has completed, whether successfully or not. */
275 if (!SetEvent (cp
->char_avail
))
277 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
278 GetLastError (), cp
->fd
));
282 if (rc
== STATUS_READ_ERROR
)
285 /* If the read died, the child has died so let the thread die */
286 if (rc
== STATUS_READ_FAILED
)
289 /* Wait until our input is acknowledged before reading again */
290 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
292 DebPrint (("reader_thread.WaitForSingleObject failed with "
293 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
300 /* To avoid Emacs changing directory, we just record here the directory
301 the new process should start in. This is set just before calling
302 sys_spawnve, and is not generally valid at any other time. */
303 static char * process_dir
;
306 create_child (char *exe
, char *cmdline
, char *env
,
307 int * pPid
, child_process
*cp
)
310 SECURITY_ATTRIBUTES sec_attrs
;
312 SECURITY_DESCRIPTOR sec_desc
;
315 char dir
[ MAXPATHLEN
];
317 if (cp
== NULL
) abort ();
319 memset (&start
, 0, sizeof (start
));
320 start
.cb
= sizeof (start
);
323 if (NILP (Vw32_start_process_show_window
))
324 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
326 start
.dwFlags
= STARTF_USESTDHANDLES
;
327 start
.wShowWindow
= SW_HIDE
;
329 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
330 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
331 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
332 #endif /* HAVE_NTGUI */
335 /* Explicitly specify no security */
336 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
338 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
341 sec_attrs
.nLength
= sizeof (sec_attrs
);
342 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
343 sec_attrs
.bInheritHandle
= FALSE
;
345 strcpy (dir
, process_dir
);
346 unixtodos_filename (dir
);
348 flags
= (!NILP (Vw32_start_process_share_console
)
349 ? CREATE_NEW_PROCESS_GROUP
350 : CREATE_NEW_CONSOLE
);
351 if (NILP (Vw32_start_process_inherit_error_mode
))
352 flags
|= CREATE_DEFAULT_ERROR_MODE
;
353 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
354 flags
, env
, dir
, &start
, &cp
->procinfo
))
357 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
359 /* Hack for Windows 95, which assigns large (ie negative) pids */
363 /* pid must fit in a Lisp_Int */
364 cp
->pid
= (cp
->pid
& VALMASK
);
371 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
375 /* create_child doesn't know what emacs' file handle will be for waiting
376 on output from the child, so we need to make this additional call
377 to register the handle with the process
378 This way the select emulator knows how to match file handles with
379 entries in child_procs. */
381 register_child (int pid
, int fd
)
385 cp
= find_child_pid (pid
);
388 DebPrint (("register_child unable to find pid %lu\n", pid
));
393 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
398 /* thread is initially blocked until select is called; set status so
399 that select will release thread */
400 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
402 /* attach child_process to fd_info */
403 if (fd_info
[fd
].cp
!= NULL
)
405 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
412 /* When a process dies its pipe will break so the reader thread will
413 signal failure to the select emulator.
414 The select emulator then calls this routine to clean up.
415 Since the thread signaled failure we can assume it is exiting. */
417 reap_subprocess (child_process
*cp
)
419 if (cp
->procinfo
.hProcess
)
421 /* Reap the process */
423 /* Process should have already died before we are called. */
424 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
425 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
427 CloseHandle (cp
->procinfo
.hProcess
);
428 cp
->procinfo
.hProcess
= NULL
;
429 CloseHandle (cp
->procinfo
.hThread
);
430 cp
->procinfo
.hThread
= NULL
;
433 /* For asynchronous children, the child_proc resources will be freed
434 when the last pipe read descriptor is closed; for synchronous
435 children, we must explicitly free the resources now because
436 register_child has not been called. */
441 /* Wait for any of our existing child processes to die
442 When it does, close its handle
443 Return the pid and fill in the status if non-NULL. */
446 sys_wait (int *status
)
448 DWORD active
, retval
;
451 child_process
*cp
, *cps
[MAX_CHILDREN
];
452 HANDLE wait_hnd
[MAX_CHILDREN
];
455 if (dead_child
!= NULL
)
457 /* We want to wait for a specific child */
458 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
459 cps
[nh
] = dead_child
;
460 if (!wait_hnd
[nh
]) abort ();
467 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
468 /* some child_procs might be sockets; ignore them */
469 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
)
471 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
479 /* Nothing to wait on, so fail */
486 /* Check for quit about once a second. */
488 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
489 } while (active
== WAIT_TIMEOUT
);
491 if (active
== WAIT_FAILED
)
496 else if (active
>= WAIT_OBJECT_0
497 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
499 active
-= WAIT_OBJECT_0
;
501 else if (active
>= WAIT_ABANDONED_0
502 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
504 active
-= WAIT_ABANDONED_0
;
510 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
512 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
516 if (retval
== STILL_ACTIVE
)
518 /* Should never happen */
519 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
524 /* Massage the exit code from the process to match the format expected
525 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
526 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
528 if (retval
== STATUS_CONTROL_C_EXIT
)
536 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
543 else if (synch_process_alive
)
545 synch_process_alive
= 0;
547 /* Report the status of the synchronous process. */
548 if (WIFEXITED (retval
))
549 synch_process_retcode
= WRETCODE (retval
);
550 else if (WIFSIGNALED (retval
))
552 int code
= WTERMSIG (retval
);
555 synchronize_system_messages_locale ();
556 signame
= strsignal (code
);
561 synch_process_death
= signame
;
564 reap_subprocess (cp
);
567 reap_subprocess (cp
);
573 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
)
575 file_data executable
;
578 /* Default values in case we can't tell for sure. */
580 *is_cygnus_app
= FALSE
;
582 if (!open_input_file (&executable
, filename
))
585 p
= strrchr (filename
, '.');
587 /* We can only identify DOS .com programs from the extension. */
588 if (p
&& stricmp (p
, ".com") == 0)
590 else if (p
&& (stricmp (p
, ".bat") == 0
591 || stricmp (p
, ".cmd") == 0))
593 /* A DOS shell script - it appears that CreateProcess is happy to
594 accept this (somewhat surprisingly); presumably it looks at
595 COMSPEC to determine what executable to actually invoke.
596 Therefore, we have to do the same here as well. */
597 /* Actually, I think it uses the program association for that
598 extension, which is defined in the registry. */
599 p
= egetenv ("COMSPEC");
601 w32_executable_type (p
, is_dos_app
, is_cygnus_app
);
605 /* Look for DOS .exe signature - if found, we must also check that
606 it isn't really a 16- or 32-bit Windows exe, since both formats
607 start with a DOS program stub. Note that 16-bit Windows
608 executables use the OS/2 1.x format. */
610 IMAGE_DOS_HEADER
* dos_header
;
611 IMAGE_NT_HEADERS
* nt_header
;
613 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
614 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
617 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
619 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
621 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
624 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
625 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
629 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
631 /* Look for cygwin.dll in DLL import list. */
632 IMAGE_DATA_DIRECTORY import_dir
=
633 nt_header
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
634 IMAGE_IMPORT_DESCRIPTOR
* imports
;
635 IMAGE_SECTION_HEADER
* section
;
637 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
638 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
, executable
);
640 for ( ; imports
->Name
; imports
++)
642 char * dllname
= RVA_TO_PTR (imports
->Name
, section
, executable
);
644 /* The exact name of the cygwin dll has changed with
645 various releases, but hopefully this will be reasonably
647 if (strncmp (dllname
, "cygwin", 6) == 0)
649 *is_cygnus_app
= TRUE
;
657 close_file_data (&executable
);
661 compare_env (const void *strp1
, const void *strp2
)
663 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
665 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
667 if (tolower (*str1
) > tolower (*str2
))
669 else if (tolower (*str1
) < tolower (*str2
))
674 if (*str1
== '=' && *str2
== '=')
676 else if (*str1
== '=')
683 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
699 qsort (new_envp
, num
, sizeof (char *), compare_env
);
704 /* When a new child process is created we need to register it in our list,
705 so intercept spawn requests. */
707 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
709 Lisp_Object program
, full
;
710 char *cmdline
, *env
, *parg
, **targ
;
714 int is_dos_app
, is_cygnus_app
;
717 /* We pass our process ID to our children by setting up an environment
718 variable in their environment. */
719 char ppid_env_var_buffer
[64];
720 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
722 /* We don't care about the other modes */
723 if (mode
!= _P_NOWAIT
)
729 /* Handle executable names without an executable suffix. */
730 program
= make_string (cmdname
, strlen (cmdname
));
731 if (NILP (Ffile_executable_p (program
)))
737 openp (Vexec_path
, program
, EXEC_SUFFIXES
, &full
, 1);
747 /* make sure argv[0] and cmdname are both in DOS format */
748 cmdname
= XSTRING (program
)->data
;
749 unixtodos_filename (cmdname
);
752 /* Determine whether program is a 16-bit DOS executable, or a w32
753 executable that is implicitly linked to the Cygnus dll (implying it
754 was compiled with the Cygnus GNU toolchain and hence relies on
755 cygwin.dll to parse the command line - we use this to decide how to
756 escape quote chars in command line args that must be quoted). */
757 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
);
759 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
760 application to start it by specifying the helper app as cmdname,
761 while leaving the real app name as argv[0]. */
764 cmdname
= alloca (MAXPATHLEN
);
765 if (egetenv ("CMDPROXY"))
766 strcpy (cmdname
, egetenv ("CMDPROXY"));
769 strcpy (cmdname
, XSTRING (Vinvocation_directory
)->data
);
770 strcat (cmdname
, "cmdproxy.exe");
772 unixtodos_filename (cmdname
);
775 /* we have to do some conjuring here to put argv and envp into the
776 form CreateProcess wants... argv needs to be a space separated/null
777 terminated list of parameters, and envp is a null
778 separated/double-null terminated list of parameters.
780 Additionally, zero-length args and args containing whitespace or
781 quote chars need to be wrapped in double quotes - for this to work,
782 embedded quotes need to be escaped as well. The aim is to ensure
783 the child process reconstructs the argv array we start with
784 exactly, so we treat quotes at the beginning and end of arguments
787 The w32 GNU-based library from Cygnus doubles quotes to escape
788 them, while MSVC uses backslash for escaping. (Actually the MSVC
789 startup code does attempt to recognise doubled quotes and accept
790 them, but gets it wrong and ends up requiring three quotes to get a
791 single embedded quote!) So by default we decide whether to use
792 quote or backslash as the escape character based on whether the
793 binary is apparently a Cygnus compiled app.
795 Note that using backslash to escape embedded quotes requires
796 additional special handling if an embedded quote is already
797 preceeded by backslash, or if an arg requiring quoting ends with
798 backslash. In such cases, the run of escape characters needs to be
799 doubled. For consistency, we apply this special handling as long
800 as the escape character is not quote.
802 Since we have no idea how large argv and envp are likely to be we
803 figure out list lengths on the fly and allocate them. */
805 if (!NILP (Vw32_quote_process_args
))
808 /* Override escape char by binding w32-quote-process-args to
809 desired character, or use t for auto-selection. */
810 if (INTEGERP (Vw32_quote_process_args
))
811 escape_char
= XINT (Vw32_quote_process_args
);
813 escape_char
= is_cygnus_app
? '"' : '\\';
823 int escape_char_run
= 0;
831 /* allow for embedded quotes to be escaped */
834 /* handle the case where the embedded quote is already escaped */
835 if (escape_char_run
> 0)
837 /* To preserve the arg exactly, we need to double the
838 preceding escape characters (plus adding one to
839 escape the quote character itself). */
840 arglen
+= escape_char_run
;
843 else if (*p
== ' ' || *p
== '\t')
848 if (*p
== escape_char
&& escape_char
!= '"')
856 /* handle the case where the arg ends with an escape char - we
857 must not let the enclosing quote be escaped. */
858 if (escape_char_run
> 0)
859 arglen
+= escape_char_run
;
861 arglen
+= strlen (*targ
++) + 1;
863 cmdline
= alloca (arglen
);
877 if (*p
== ' ' || *p
== '\t' || *p
== '"')
882 int escape_char_run
= 0;
888 last
= p
+ strlen (p
) - 1;
891 /* This version does not escape quotes if they occur at the
892 beginning or end of the arg - this could lead to incorrect
893 behaviour when the arg itself represents a command line
894 containing quoted args. I believe this was originally done
895 as a hack to make some things work, before
896 `w32-quote-process-args' was added. */
899 if (*p
== '"' && p
> first
&& p
< last
)
900 *parg
++ = escape_char
; /* escape embedded quotes */
908 /* double preceding escape chars if any */
909 while (escape_char_run
> 0)
911 *parg
++ = escape_char
;
914 /* escape all quote chars, even at beginning or end */
915 *parg
++ = escape_char
;
919 if (*p
== escape_char
&& escape_char
!= '"')
924 /* double escape chars before enclosing quote */
925 while (escape_char_run
> 0)
927 *parg
++ = escape_char
;
935 strcpy (parg
, *targ
);
936 parg
+= strlen (*targ
);
946 numenv
= 1; /* for end null */
949 arglen
+= strlen (*targ
++) + 1;
952 /* extra env vars... */
953 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
954 GetCurrentProcessId ());
955 arglen
+= strlen (ppid_env_var_buffer
) + 1;
958 /* merge env passed in and extra env into one, and sort it. */
959 targ
= (char **) alloca (numenv
* sizeof (char *));
960 merge_and_sort_env (envp
, extra_env
, targ
);
962 /* concatenate env entries. */
963 env
= alloca (arglen
);
967 strcpy (parg
, *targ
);
968 parg
+= strlen (*targ
++);
981 /* Now create the process. */
982 if (!create_child (cmdname
, cmdline
, env
, &pid
, cp
))
992 /* Emulate the select call
993 Wait for available input on any of the given rfds, or timeout if
994 a timeout is given and no input is detected
995 wfds and efds are not supported and must be NULL.
997 For simplicity, we detect the death of child processes here and
998 synchronously call the SIGCHLD handler. Since it is possible for
999 children to be created without a corresponding pipe handle from which
1000 to read output, we wait separately on the process handles as well as
1001 the char_avail events for each process pipe. We only call
1002 wait/reap_process when the process actually terminates.
1004 To reduce the number of places in which Emacs can be hung such that
1005 C-g is not able to interrupt it, we always wait on interrupt_handle
1006 (which is signalled by the input thread when C-g is detected). If we
1007 detect that we were woken up by C-g, we return -1 with errno set to
1008 EINTR as on Unix. */
1011 extern HANDLE keyboard_handle
;
1013 /* From w32xfns.c */
1014 extern HANDLE interrupt_handle
;
1016 /* From process.c */
1017 extern int proc_buffered_char
[];
1020 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1021 EMACS_TIME
*timeout
)
1024 DWORD timeout_ms
, start_time
;
1027 child_process
*cp
, *cps
[MAX_CHILDREN
];
1028 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1029 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1031 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1033 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1034 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1040 /* Otherwise, we only handle rfds, so fail otherwise. */
1041 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1051 /* Always wait on interrupt_handle, to detect C-g (quit). */
1052 wait_hnd
[0] = interrupt_handle
;
1055 /* Build a list of pipe handles to wait on. */
1057 for (i
= 0; i
< nfds
; i
++)
1058 if (FD_ISSET (i
, &orfds
))
1062 if (keyboard_handle
)
1064 /* Handle stdin specially */
1065 wait_hnd
[nh
] = keyboard_handle
;
1070 /* Check for any emacs-generated input in the queue since
1071 it won't be detected in the wait */
1072 if (detect_input_pending ())
1080 /* Child process and socket input */
1084 int current_status
= cp
->status
;
1086 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1088 /* Tell reader thread which file handle to use. */
1090 /* Wake up the reader thread for this process */
1091 cp
->status
= STATUS_READ_READY
;
1092 if (!SetEvent (cp
->char_consumed
))
1093 DebPrint (("nt_select.SetEvent failed with "
1094 "%lu for fd %ld\n", GetLastError (), i
));
1097 #ifdef CHECK_INTERLOCK
1098 /* slightly crude cross-checking of interlock between threads */
1100 current_status
= cp
->status
;
1101 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1103 /* char_avail has been signalled, so status (which may
1104 have changed) should indicate read has completed
1105 but has not been acknowledged. */
1106 current_status
= cp
->status
;
1107 if (current_status
!= STATUS_READ_SUCCEEDED
1108 && current_status
!= STATUS_READ_FAILED
)
1109 DebPrint (("char_avail set, but read not completed: status %d\n",
1114 /* char_avail has not been signalled, so status should
1115 indicate that read is in progress; small possibility
1116 that read has completed but event wasn't yet signalled
1117 when we tested it (because a context switch occurred
1118 or if running on separate CPUs). */
1119 if (current_status
!= STATUS_READ_READY
1120 && current_status
!= STATUS_READ_IN_PROGRESS
1121 && current_status
!= STATUS_READ_SUCCEEDED
1122 && current_status
!= STATUS_READ_FAILED
)
1123 DebPrint (("char_avail reset, but read status is bad: %d\n",
1127 wait_hnd
[nh
] = cp
->char_avail
;
1129 if (!wait_hnd
[nh
]) abort ();
1132 DebPrint (("select waiting on child %d fd %d\n",
1133 cp
-child_procs
, i
));
1138 /* Unable to find something to wait on for this fd, skip */
1140 /* Note that this is not a fatal error, and can in fact
1141 happen in unusual circumstances. Specifically, if
1142 sys_spawnve fails, eg. because the program doesn't
1143 exist, and debug-on-error is t so Fsignal invokes a
1144 nested input loop, then the process output pipe is
1145 still included in input_wait_mask with no child_proc
1146 associated with it. (It is removed when the debugger
1147 exits the nested input loop and the error is thrown.) */
1149 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1155 /* Add handles of child processes. */
1157 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1158 /* Some child_procs might be sockets; ignore them. Also some
1159 children may have died already, but we haven't finished reading
1160 the process output; ignore them too. */
1161 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1163 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1164 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1167 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1172 /* Nothing to look for, so we didn't find anything */
1180 start_time
= GetTickCount ();
1182 /* Wait for input or child death to be signalled. If user input is
1183 allowed, then also accept window messages. */
1184 if (FD_ISSET (0, &orfds
))
1185 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1188 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1190 if (active
== WAIT_FAILED
)
1192 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1193 nh
+ nc
, timeout_ms
, GetLastError ()));
1194 /* don't return EBADF - this causes wait_reading_process_input to
1195 abort; WAIT_FAILED is returned when single-stepping under
1196 Windows 95 after switching thread focus in debugger, and
1197 possibly at other times. */
1201 else if (active
== WAIT_TIMEOUT
)
1205 else if (active
>= WAIT_OBJECT_0
1206 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1208 active
-= WAIT_OBJECT_0
;
1210 else if (active
>= WAIT_ABANDONED_0
1211 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1213 active
-= WAIT_ABANDONED_0
;
1218 /* Loop over all handles after active (now officially documented as
1219 being the first signalled handle in the array). We do this to
1220 ensure fairness, so that all channels with data available will be
1221 processed - otherwise higher numbered channels could be starved. */
1224 if (active
== nh
+ nc
)
1226 /* There are messages in the lisp thread's queue; we must
1227 drain the queue now to ensure they are processed promptly,
1228 because if we don't do so, we will not be woken again until
1229 further messages arrive.
1231 NB. If ever we allow window message procedures to callback
1232 into lisp, we will need to ensure messages are dispatched
1233 at a safe time for lisp code to be run (*), and we may also
1234 want to provide some hooks in the dispatch loop to cater
1235 for modeless dialogs created by lisp (ie. to register
1236 window handles to pass to IsDialogMessage).
1238 (*) Note that MsgWaitForMultipleObjects above is an
1239 internal dispatch point for messages that are sent to
1240 windows created by this thread. */
1241 drain_message_queue ();
1243 else if (active
>= nh
)
1245 cp
= cps
[active
- nh
];
1247 /* We cannot always signal SIGCHLD immediately; if we have not
1248 finished reading the process output, we must delay sending
1249 SIGCHLD until we do. */
1251 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1252 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1253 /* SIG_DFL for SIGCHLD is ignore */
1254 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1255 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1258 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1262 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1266 else if (fdindex
[active
] == -1)
1268 /* Quit (C-g) was detected. */
1272 else if (fdindex
[active
] == 0)
1274 /* Keyboard input available */
1280 /* must be a socket or pipe - read ahead should have
1281 completed, either succeeding or failing. */
1282 FD_SET (fdindex
[active
], rfds
);
1286 /* Even though wait_reading_process_output only reads from at most
1287 one channel, we must process all channels here so that we reap
1288 all children that have died. */
1289 while (++active
< nh
+ nc
)
1290 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1292 } while (active
< nh
+ nc
);
1294 /* If no input has arrived and timeout hasn't expired, wait again. */
1297 DWORD elapsed
= GetTickCount () - start_time
;
1299 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1301 if (timeout_ms
!= INFINITE
)
1302 timeout_ms
-= elapsed
;
1303 goto count_children
;
1310 /* Substitute for certain kill () operations */
1312 static BOOL CALLBACK
1313 find_child_console (HWND hwnd
, LPARAM arg
)
1315 child_process
* cp
= (child_process
*) arg
;
1319 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1320 if (process_id
== cp
->procinfo
.dwProcessId
)
1322 char window_class
[32];
1324 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1325 if (strcmp (window_class
,
1326 (os_subtype
== OS_WIN95
)
1328 : "ConsoleWindowClass") == 0)
1339 sys_kill (int pid
, int sig
)
1343 int need_to_free
= 0;
1346 /* Only handle signals that will result in the process dying */
1347 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1353 cp
= find_child_pid (pid
);
1356 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1357 if (proc_hand
== NULL
)
1366 proc_hand
= cp
->procinfo
.hProcess
;
1367 pid
= cp
->procinfo
.dwProcessId
;
1369 /* Try to locate console window for process. */
1370 EnumWindows (find_child_console
, (LPARAM
) cp
);
1375 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1377 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1378 BYTE vk_break_code
= VK_CANCEL
;
1379 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1380 HWND foreground_window
;
1382 if (break_scan_code
== 0)
1384 /* Fake Ctrl-C if we can't manage Ctrl-Break. */
1385 vk_break_code
= 'C';
1386 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1389 foreground_window
= GetForegroundWindow ();
1390 if (foreground_window
)
1392 /* NT 5.0, and apparently also Windows 98, will not allow
1393 a Window to be set to foreground directly without the
1394 user's involvement. The workaround is to attach
1395 ourselves to the thread that owns the foreground
1396 window, since that is the only thread that can set the
1397 foreground window. */
1398 DWORD foreground_thread
, child_thread
;
1400 GetWindowThreadProcessId (foreground_window
, NULL
);
1401 if (foreground_thread
== GetCurrentThreadId ()
1402 || !AttachThreadInput (GetCurrentThreadId (),
1403 foreground_thread
, TRUE
))
1404 foreground_thread
= 0;
1406 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1407 if (child_thread
== GetCurrentThreadId ()
1408 || !AttachThreadInput (GetCurrentThreadId (),
1409 child_thread
, TRUE
))
1412 /* Set the foreground window to the child. */
1413 if (SetForegroundWindow (cp
->hwnd
))
1415 /* Generate keystrokes as if user had typed Ctrl-Break or
1417 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1418 keybd_event (vk_break_code
, break_scan_code
,
1419 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1420 keybd_event (vk_break_code
, break_scan_code
,
1421 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1422 | KEYEVENTF_KEYUP
, 0);
1423 keybd_event (VK_CONTROL
, control_scan_code
,
1424 KEYEVENTF_KEYUP
, 0);
1426 /* Sleep for a bit to give time for Emacs frame to respond
1427 to focus change events (if Emacs was active app). */
1430 SetForegroundWindow (foreground_window
);
1432 /* Detach from the foreground and child threads now that
1433 the foreground switching is over. */
1434 if (foreground_thread
)
1435 AttachThreadInput (GetCurrentThreadId (),
1436 foreground_thread
, FALSE
);
1438 AttachThreadInput (GetCurrentThreadId (),
1439 child_thread
, FALSE
);
1442 /* Ctrl-Break is NT equivalent of SIGINT. */
1443 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1445 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1446 "for pid %lu\n", GetLastError (), pid
));
1453 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1456 if (os_subtype
== OS_WIN95
)
1459 Another possibility is to try terminating the VDM out-right by
1460 calling the Shell VxD (id 0x17) V86 interface, function #4
1461 "SHELL_Destroy_VM", ie.
1467 First need to determine the current VM handle, and then arrange for
1468 the shellapi call to be made from the system vm (by using
1469 Switch_VM_and_callback).
1471 Could try to invoke DestroyVM through CallVxD.
1475 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1476 to hang when cmdproxy is used in conjunction with
1477 command.com for an interactive shell. Posting
1478 WM_CLOSE pops up a dialog that, when Yes is selected,
1479 does the same thing. TerminateProcess is also less
1480 than ideal in that subprocesses tend to stick around
1481 until the machine is shutdown, but at least it
1482 doesn't freeze the 16-bit subsystem. */
1483 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1485 if (!TerminateProcess (proc_hand
, 0xff))
1487 DebPrint (("sys_kill.TerminateProcess returned %d "
1488 "for pid %lu\n", GetLastError (), pid
));
1495 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1497 /* Kill the process. On W32 this doesn't kill child processes
1498 so it doesn't work very well for shells which is why it's not
1499 used in every case. */
1500 else if (!TerminateProcess (proc_hand
, 0xff))
1502 DebPrint (("sys_kill.TerminateProcess returned %d "
1503 "for pid %lu\n", GetLastError (), pid
));
1510 CloseHandle (proc_hand
);
1515 /* extern int report_file_error (char *, Lisp_Object); */
1517 /* The following two routines are used to manipulate stdin, stdout, and
1518 stderr of our child processes.
1520 Assuming that in, out, and err are *not* inheritable, we make them
1521 stdin, stdout, and stderr of the child as follows:
1523 - Save the parent's current standard handles.
1524 - Set the std handles to inheritable duplicates of the ones being passed in.
1525 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1526 NT file handle for a crt file descriptor.)
1527 - Spawn the child, which inherits in, out, and err as stdin,
1528 stdout, and stderr. (see Spawnve)
1529 - Close the std handles passed to the child.
1530 - Reset the parent's standard handles to the saved handles.
1531 (see reset_standard_handles)
1532 We assume that the caller closes in, out, and err after calling us. */
1535 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1538 HANDLE newstdin
, newstdout
, newstderr
;
1540 parent
= GetCurrentProcess ();
1542 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1543 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1544 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1546 /* make inheritable copies of the new handles */
1547 if (!DuplicateHandle (parent
,
1548 (HANDLE
) _get_osfhandle (in
),
1553 DUPLICATE_SAME_ACCESS
))
1554 report_file_error ("Duplicating input handle for child", Qnil
);
1556 if (!DuplicateHandle (parent
,
1557 (HANDLE
) _get_osfhandle (out
),
1562 DUPLICATE_SAME_ACCESS
))
1563 report_file_error ("Duplicating output handle for child", Qnil
);
1565 if (!DuplicateHandle (parent
,
1566 (HANDLE
) _get_osfhandle (err
),
1571 DUPLICATE_SAME_ACCESS
))
1572 report_file_error ("Duplicating error handle for child", Qnil
);
1574 /* and store them as our std handles */
1575 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1576 report_file_error ("Changing stdin handle", Qnil
);
1578 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1579 report_file_error ("Changing stdout handle", Qnil
);
1581 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1582 report_file_error ("Changing stderr handle", Qnil
);
1586 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1588 /* close the duplicated handles passed to the child */
1589 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1590 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1591 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1593 /* now restore parent's saved std handles */
1594 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1595 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1596 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1600 set_process_dir (char * dir
)
1607 /* To avoid problems with winsock implementations that work over dial-up
1608 connections causing or requiring a connection to exist while Emacs is
1609 running, Emacs no longer automatically loads winsock on startup if it
1610 is present. Instead, it will be loaded when open-network-stream is
1613 To allow full control over when winsock is loaded, we provide these
1614 two functions to dynamically load and unload winsock. This allows
1615 dial-up users to only be connected when they actually need to use
1619 extern HANDLE winsock_lib
;
1620 extern BOOL
term_winsock (void);
1621 extern BOOL
init_winsock (int load_now
);
1623 extern Lisp_Object Vsystem_name
;
1625 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1626 "Test for presence of the Windows socket library `winsock'.\n\
1627 Returns non-nil if winsock support is present, nil otherwise.\n\
1629 If the optional argument LOAD-NOW is non-nil, the winsock library is\n\
1630 also loaded immediately if not already loaded. If winsock is loaded,\n\
1631 the winsock local hostname is returned (since this may be different from\n\
1632 the value of `system-name' and should supplant it), otherwise t is\n\
1633 returned to indicate winsock support is present.")
1635 Lisp_Object load_now
;
1639 have_winsock
= init_winsock (!NILP (load_now
));
1642 if (winsock_lib
!= NULL
)
1644 /* Return new value for system-name. The best way to do this
1645 is to call init_system_name, saving and restoring the
1646 original value to avoid side-effects. */
1647 Lisp_Object orig_hostname
= Vsystem_name
;
1648 Lisp_Object hostname
;
1650 init_system_name ();
1651 hostname
= Vsystem_name
;
1652 Vsystem_name
= orig_hostname
;
1660 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1662 "Unload the Windows socket library `winsock' if loaded.\n\
1663 This is provided to allow dial-up socket connections to be disconnected\n\
1664 when no longer needed. Returns nil without unloading winsock if any\n\
1665 socket connections still exist.")
1668 return term_winsock () ? Qt
: Qnil
;
1671 #endif /* HAVE_SOCKETS */
1674 /* Some miscellaneous functions that are Windows specific, but not GUI
1675 specific (ie. are applicable in terminal or batch mode as well). */
1677 /* lifted from fileio.c */
1678 #define CORRECT_DIR_SEPS(s) \
1679 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1680 else unixtodos_filename (s); \
1683 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1684 "Return the short file name version (8.3) of the full path of FILENAME.\n\
1685 If FILENAME does not exist, return nil.\n\
1686 All path elements in FILENAME are converted to their short names.")
1688 Lisp_Object filename
;
1690 char shortname
[MAX_PATH
];
1692 CHECK_STRING (filename
, 0);
1694 /* first expand it. */
1695 filename
= Fexpand_file_name (filename
, Qnil
);
1697 /* luckily, this returns the short version of each element in the path. */
1698 if (GetShortPathName (XSTRING (filename
)->data
, shortname
, MAX_PATH
) == 0)
1701 CORRECT_DIR_SEPS (shortname
);
1703 return build_string (shortname
);
1707 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1709 "Return the long file name version of the full path of FILENAME.\n\
1710 If FILENAME does not exist, return nil.\n\
1711 All path elements in FILENAME are converted to their long names.")
1713 Lisp_Object filename
;
1715 char longname
[ MAX_PATH
];
1717 CHECK_STRING (filename
, 0);
1719 /* first expand it. */
1720 filename
= Fexpand_file_name (filename
, Qnil
);
1722 if (!w32_get_long_filename (XSTRING (filename
)->data
, longname
, MAX_PATH
))
1725 CORRECT_DIR_SEPS (longname
);
1727 return build_string (longname
);
1730 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
, Sw32_set_process_priority
,
1732 "Set the priority of PROCESS to PRIORITY.\n\
1733 If PROCESS is nil, the priority of Emacs is changed, otherwise the\n\
1734 priority of the process whose pid is PROCESS is changed.\n\
1735 PRIORITY should be one of the symbols high, normal, or low;\n\
1736 any other symbol will be interpreted as normal.\n\
1738 If successful, the return value is t, otherwise nil.")
1740 Lisp_Object process
, priority
;
1742 HANDLE proc_handle
= GetCurrentProcess ();
1743 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1744 Lisp_Object result
= Qnil
;
1746 CHECK_SYMBOL (priority
, 0);
1748 if (!NILP (process
))
1753 CHECK_NUMBER (process
, 0);
1755 /* Allow pid to be an internally generated one, or one obtained
1756 externally. This is necessary because real pids on Win95 are
1759 pid
= XINT (process
);
1760 cp
= find_child_pid (pid
);
1762 pid
= cp
->procinfo
.dwProcessId
;
1764 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1767 if (EQ (priority
, Qhigh
))
1768 priority_class
= HIGH_PRIORITY_CLASS
;
1769 else if (EQ (priority
, Qlow
))
1770 priority_class
= IDLE_PRIORITY_CLASS
;
1772 if (proc_handle
!= NULL
)
1774 if (SetPriorityClass (proc_handle
, priority_class
))
1776 if (!NILP (process
))
1777 CloseHandle (proc_handle
);
1784 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
, Sw32_get_locale_info
, 1, 2, 0,
1785 "Return information about the Windows locale LCID.\n\
1786 By default, return a three letter locale code which encodes the default\n\
1787 language as the first two characters, and the country or regionial variant\n\
1788 as the third letter. For example, ENU refers to `English (United States)',\n\
1789 while ENC means `English (Canadian)'.\n\
1791 If the optional argument LONGFORM is t, the long form of the locale\n\
1792 name is returned, e.g. `English (United States)' instead; if LONGFORM\n\
1793 is a number, it is interpreted as an LCTYPE constant and the corresponding\n\
1794 locale information is returned.\n\
1796 If LCID (a 16-bit number) is not a valid locale, the result is nil.")
1798 Lisp_Object lcid
, longform
;
1802 char abbrev_name
[32] = { 0 };
1803 char full_name
[256] = { 0 };
1805 CHECK_NUMBER (lcid
, 0);
1807 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1810 if (NILP (longform
))
1812 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1813 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1814 abbrev_name
, sizeof (abbrev_name
));
1816 return build_string (abbrev_name
);
1818 else if (EQ (longform
, Qt
))
1820 got_full
= GetLocaleInfo (XINT (lcid
),
1821 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1822 full_name
, sizeof (full_name
));
1824 return build_string (full_name
);
1826 else if (NUMBERP (longform
))
1828 got_full
= GetLocaleInfo (XINT (lcid
),
1830 full_name
, sizeof (full_name
));
1832 return make_unibyte_string (full_name
, got_full
);
1839 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
, Sw32_get_current_locale_id
, 0, 0, 0,
1840 "Return Windows locale id for current locale setting.\n\
1841 This is a numerical value; use `w32-get-locale-info' to convert to a\n\
1842 human-readable form.")
1845 return make_number (GetThreadLocale ());
1848 DWORD
int_from_hex (char * s
)
1851 static char hex
[] = "0123456789abcdefABCDEF";
1854 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
1856 unsigned digit
= p
- hex
;
1859 val
= val
* 16 + digit
;
1865 /* We need to build a global list, since the EnumSystemLocale callback
1866 function isn't given a context pointer. */
1867 Lisp_Object Vw32_valid_locale_ids
;
1869 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
1871 DWORD id
= int_from_hex (localeNum
);
1872 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
1876 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
, Sw32_get_valid_locale_ids
, 0, 0, 0,
1877 "Return list of all valid Windows locale ids.\n\
1878 Each id is a numerical value; use `w32-get-locale-info' to convert to a\n\
1879 human-readable form.")
1882 Vw32_valid_locale_ids
= Qnil
;
1884 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
1886 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
1887 return Vw32_valid_locale_ids
;
1891 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
1892 "Return Windows locale id for default locale setting.\n\
1893 By default, the system default locale setting is returned; if the optional\n\
1894 parameter USERP is non-nil, the user default locale setting is returned.\n\
1895 This is a numerical value; use `w32-get-locale-info' to convert to a\n\
1896 human-readable form.")
1901 return make_number (GetSystemDefaultLCID ());
1902 return make_number (GetUserDefaultLCID ());
1906 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
1907 "Make Windows locale LCID be the current locale setting for Emacs.\n\
1908 If successful, the new locale id is returned, otherwise nil.")
1912 CHECK_NUMBER (lcid
, 0);
1914 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1917 if (!SetThreadLocale (XINT (lcid
)))
1920 /* Need to set input thread locale if present. */
1921 if (dwWindowsThreadId
)
1922 /* Reply is not needed. */
1923 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
1925 return make_number (GetThreadLocale ());
1929 /* We need to build a global list, since the EnumCodePages callback
1930 function isn't given a context pointer. */
1931 Lisp_Object Vw32_valid_codepages
;
1933 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
1935 DWORD id
= atoi (codepageNum
);
1936 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
1940 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
, Sw32_get_valid_codepages
, 0, 0, 0,
1941 "Return list of all valid Windows codepages.")
1944 Vw32_valid_codepages
= Qnil
;
1946 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
1948 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
1949 return Vw32_valid_codepages
;
1953 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
, Sw32_get_console_codepage
, 0, 0, 0,
1954 "Return current Windows codepage for console input.")
1957 return make_number (GetConsoleCP ());
1961 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
, Sw32_set_console_codepage
, 1, 1, 0,
1962 "Make Windows codepage CP be the current codepage setting for Emacs.\n\
1963 The codepage setting affects keyboard input and display in tty mode.\n\
1964 If successful, the new CP is returned, otherwise nil.")
1968 CHECK_NUMBER (cp
, 0);
1970 if (!IsValidCodePage (XINT (cp
)))
1973 if (!SetConsoleCP (XINT (cp
)))
1976 return make_number (GetConsoleCP ());
1980 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
, Sw32_get_console_output_codepage
, 0, 0, 0,
1981 "Return current Windows codepage for console output.")
1984 return make_number (GetConsoleOutputCP ());
1988 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
, Sw32_set_console_output_codepage
, 1, 1, 0,
1989 "Make Windows codepage CP be the current codepage setting for Emacs.\n\
1990 The codepage setting affects keyboard input and display in tty mode.\n\
1991 If successful, the new CP is returned, otherwise nil.")
1995 CHECK_NUMBER (cp
, 0);
1997 if (!IsValidCodePage (XINT (cp
)))
2000 if (!SetConsoleOutputCP (XINT (cp
)))
2003 return make_number (GetConsoleOutputCP ());
2007 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
, Sw32_get_codepage_charset
, 1, 1, 0,
2008 "Return charset of codepage CP.\n\
2009 Returns nil if the codepage is not valid.")
2015 CHECK_NUMBER (cp
, 0);
2017 if (!IsValidCodePage (XINT (cp
)))
2020 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2021 return make_number (info
.ciCharset
);
2027 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
, Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2028 "Return list of Windows keyboard languages and layouts.\n\
2029 The return value is a list of pairs of language id and layout id.")
2032 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2033 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2034 Lisp_Object obj
= Qnil
;
2036 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2038 while (--num_layouts
>= 0)
2040 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2042 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2043 make_number ((kl
>> 16) & 0xffff)),
2052 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
, Sw32_get_keyboard_layout
, 0, 0, 0,
2053 "Return current Windows keyboard language and layout.\n\
2054 The return value is the cons of the language id and the layout id.")
2057 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2059 return Fcons (make_number (kl
& 0xffff),
2060 make_number ((kl
>> 16) & 0xffff));
2064 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
, Sw32_set_keyboard_layout
, 1, 1, 0,
2065 "Make LAYOUT be the current keyboard layout for Emacs.\n\
2066 The keyboard layout setting affects interpretation of keyboard input.\n\
2067 If successful, the new layout id is returned, otherwise nil.")
2073 CHECK_CONS (layout
, 0);
2074 CHECK_NUMBER (XCAR (layout
), 0);
2075 CHECK_NUMBER (XCDR (layout
), 0);
2077 kl
= (XINT (XCAR (layout
)) & 0xffff)
2078 | (XINT (XCDR (layout
)) << 16);
2080 /* Synchronize layout with input thread. */
2081 if (dwWindowsThreadId
)
2083 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2087 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2089 if (msg
.wParam
== 0)
2093 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2096 return Fw32_get_keyboard_layout ();
2102 Qhigh
= intern ("high");
2103 Qlow
= intern ("low");
2106 defsubr (&Sw32_has_winsock
);
2107 defsubr (&Sw32_unload_winsock
);
2109 defsubr (&Sw32_short_file_name
);
2110 defsubr (&Sw32_long_file_name
);
2111 defsubr (&Sw32_set_process_priority
);
2112 defsubr (&Sw32_get_locale_info
);
2113 defsubr (&Sw32_get_current_locale_id
);
2114 defsubr (&Sw32_get_default_locale_id
);
2115 defsubr (&Sw32_get_valid_locale_ids
);
2116 defsubr (&Sw32_set_current_locale
);
2118 defsubr (&Sw32_get_console_codepage
);
2119 defsubr (&Sw32_set_console_codepage
);
2120 defsubr (&Sw32_get_console_output_codepage
);
2121 defsubr (&Sw32_set_console_output_codepage
);
2122 defsubr (&Sw32_get_valid_codepages
);
2123 defsubr (&Sw32_get_codepage_charset
);
2125 defsubr (&Sw32_get_valid_keyboard_layouts
);
2126 defsubr (&Sw32_get_keyboard_layout
);
2127 defsubr (&Sw32_set_keyboard_layout
);
2129 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2130 "Non-nil enables quoting of process arguments to ensure correct parsing.\n\
2131 Because Windows does not directly pass argv arrays to child processes,\n\
2132 programs have to reconstruct the argv array by parsing the command\n\
2133 line string. For an argument to contain a space, it must be enclosed\n\
2134 in double quotes or it will be parsed as multiple arguments.\n\
2136 If the value is a character, that character will be used to escape any\n\
2137 quote characters that appear, otherwise a suitable escape character\n\
2138 will be chosen based on the type of the program.");
2139 Vw32_quote_process_args
= Qt
;
2141 DEFVAR_LISP ("w32-start-process-show-window",
2142 &Vw32_start_process_show_window
,
2143 "When nil, new child processes hide their windows.\n\
2144 When non-nil, they show their window in the method of their choice.");
2145 Vw32_start_process_show_window
= Qnil
;
2147 DEFVAR_LISP ("w32-start-process-share-console",
2148 &Vw32_start_process_share_console
,
2149 "When nil, new child processes are given a new console.\n\
2150 When non-nil, they share the Emacs console; this has the limitation of\n\
2151 allowing only only DOS subprocess to run at a time (whether started directly\n\
2152 or indirectly by Emacs), and preventing Emacs from cleanly terminating the\n\
2153 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't\n\
2154 otherwise respond to interrupts from Emacs.");
2155 Vw32_start_process_share_console
= Qnil
;
2157 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2158 &Vw32_start_process_inherit_error_mode
,
2159 "When nil, new child processes revert to the default error mode.\n\
2160 When non-nil, they inherit their error mode setting from Emacs, which stops\n\
2161 them blocking when trying to access unmounted drives etc.");
2162 Vw32_start_process_inherit_error_mode
= Qt
;
2164 DEFVAR_INT ("w32-pipe-read-delay", &Vw32_pipe_read_delay
,
2165 "Forced delay before reading subprocess output.\n\
2166 This is done to improve the buffering of subprocess output, by\n\
2167 avoiding the inefficiency of frequently reading small amounts of data.\n\
2169 If positive, the value is the number of milliseconds to sleep before\n\
2170 reading the subprocess output. If negative, the magnitude is the number\n\
2171 of time slices to wait (effectively boosting the priority of the child\n\
2172 process temporarily). A value of zero disables waiting entirely.");
2173 Vw32_pipe_read_delay
= 50;
2175 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2176 "Non-nil means convert all-upper case file names to lower case.\n\
2177 This applies when performing completions and file name expansion.");
2178 Vw32_downcase_file_names
= Qnil
;
2181 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2182 "Non-nil means attempt to fake realistic inode values.\n\
2183 This works by hashing the truename of files, and should detect \n\
2184 aliasing between long and short (8.3 DOS) names, but can have\n\
2185 false positives because of hash collisions. Note that determing\n\
2186 the truename of a file can be slow.");
2187 Vw32_generate_fake_inodes
= Qnil
;
2190 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2191 "Non-nil means determine accurate link count in file-attributes.\n\
2192 This option slows down file-attributes noticeably, so is disabled by\n\
2193 default. Note that it is only useful for files on NTFS volumes,\n\
2194 where hard links are supported.");
2195 Vw32_get_true_file_attributes
= Qnil
;
2197 /* end of ntproc.c */