1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001 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
);
52 #include "syssignal.h"
55 /* Control whether spawnve quotes arguments as necessary to ensure
56 correct parsing by child process. Because not all uses of spawnve
57 are careful about constructing argv arrays, we make this behaviour
58 conditional (off by default). */
59 Lisp_Object Vw32_quote_process_args
;
61 /* Control whether create_child causes the process' window to be
62 hidden. The default is nil. */
63 Lisp_Object Vw32_start_process_show_window
;
65 /* Control whether create_child causes the process to inherit Emacs'
66 console window, or be given a new one of its own. The default is
67 nil, to allow multiple DOS programs to run on Win95. Having separate
68 consoles also allows Emacs to cleanly terminate process groups. */
69 Lisp_Object Vw32_start_process_share_console
;
71 /* Control whether create_child cause the process to inherit Emacs'
72 error mode setting. The default is t, to minimize the possibility of
73 subprocesses blocking when accessing unmounted drives. */
74 Lisp_Object Vw32_start_process_inherit_error_mode
;
76 /* Time to sleep before reading from a subprocess output pipe - this
77 avoids the inefficiency of frequently reading small amounts of data.
78 This is primarily necessary for handling DOS processes on Windows 95,
79 but is useful for W32 processes on both Windows 95 and NT as well. */
80 Lisp_Object Vw32_pipe_read_delay
;
82 /* Control conversion of upper case file names to lower case.
83 nil means no, t means yes. */
84 Lisp_Object Vw32_downcase_file_names
;
86 /* Control whether stat() attempts to generate fake but hopefully
87 "accurate" inode values, by hashing the absolute truenames of files.
88 This should detect aliasing between long and short names, but still
89 allows the possibility of hash collisions. */
90 Lisp_Object Vw32_generate_fake_inodes
;
92 /* Control whether stat() attempts to determine file type and link count
93 exactly, at the expense of slower operation. Since true hard links
94 are supported on NTFS volumes, this is only relevant on NT. */
95 Lisp_Object Vw32_get_true_file_attributes
;
97 Lisp_Object Qhigh
, Qlow
;
100 void _DebPrint (const char *fmt
, ...)
105 va_start (args
, fmt
);
106 vsprintf (buf
, fmt
, args
);
108 OutputDebugString (buf
);
112 typedef void (_CALLBACK_
*signal_handler
)(int);
114 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
115 static signal_handler sig_handlers
[NSIG
];
117 /* Fake signal implementation to record the SIGCHLD handler. */
119 sys_signal (int sig
, signal_handler handler
)
128 old
= sig_handlers
[sig
];
129 sig_handlers
[sig
] = handler
;
133 /* Defined in <process.h> which conflicts with the local copy */
136 /* Child process management list. */
137 int child_proc_count
= 0;
138 child_process child_procs
[ MAX_CHILDREN
];
139 child_process
*dead_child
= NULL
;
141 DWORD WINAPI
reader_thread (void *arg
);
143 /* Find an unused process slot. */
150 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
151 if (!CHILD_ACTIVE (cp
))
153 if (child_proc_count
== MAX_CHILDREN
)
155 cp
= &child_procs
[child_proc_count
++];
158 memset (cp
, 0, sizeof(*cp
));
161 cp
->procinfo
.hProcess
= NULL
;
162 cp
->status
= STATUS_READ_ERROR
;
164 /* use manual reset event so that select() will function properly */
165 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
168 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
169 if (cp
->char_consumed
)
171 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
181 delete_child (child_process
*cp
)
185 /* Should not be deleting a child that is still needed. */
186 for (i
= 0; i
< MAXDESC
; i
++)
187 if (fd_info
[i
].cp
== cp
)
190 if (!CHILD_ACTIVE (cp
))
193 /* reap thread if necessary */
198 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
200 /* let the thread exit cleanly if possible */
201 cp
->status
= STATUS_READ_ERROR
;
202 SetEvent (cp
->char_consumed
);
203 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
205 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
206 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
207 TerminateThread (cp
->thrd
, 0);
210 CloseHandle (cp
->thrd
);
215 CloseHandle (cp
->char_avail
);
216 cp
->char_avail
= NULL
;
218 if (cp
->char_consumed
)
220 CloseHandle (cp
->char_consumed
);
221 cp
->char_consumed
= NULL
;
224 /* update child_proc_count (highest numbered slot in use plus one) */
225 if (cp
== child_procs
+ child_proc_count
- 1)
227 for (i
= child_proc_count
-1; i
>= 0; i
--)
228 if (CHILD_ACTIVE (&child_procs
[i
]))
230 child_proc_count
= i
+ 1;
235 child_proc_count
= 0;
238 /* Find a child by pid. */
239 static child_process
*
240 find_child_pid (DWORD pid
)
244 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
245 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
251 /* Thread proc for child process and socket reader threads. Each thread
252 is normally blocked until woken by select() to check for input by
253 reading one char. When the read completes, char_avail is signalled
254 to wake up the select emulator and the thread blocks itself again. */
256 reader_thread (void *arg
)
261 cp
= (child_process
*)arg
;
263 /* We have to wait for the go-ahead before we can start */
265 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
272 rc
= _sys_read_ahead (cp
->fd
);
274 /* The name char_avail is a misnomer - it really just means the
275 read-ahead has completed, whether successfully or not. */
276 if (!SetEvent (cp
->char_avail
))
278 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
279 GetLastError (), cp
->fd
));
283 if (rc
== STATUS_READ_ERROR
)
286 /* If the read died, the child has died so let the thread die */
287 if (rc
== STATUS_READ_FAILED
)
290 /* Wait until our input is acknowledged before reading again */
291 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
293 DebPrint (("reader_thread.WaitForSingleObject failed with "
294 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
301 /* To avoid Emacs changing directory, we just record here the directory
302 the new process should start in. This is set just before calling
303 sys_spawnve, and is not generally valid at any other time. */
304 static char * process_dir
;
307 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
308 int * pPid
, child_process
*cp
)
311 SECURITY_ATTRIBUTES sec_attrs
;
313 SECURITY_DESCRIPTOR sec_desc
;
316 char dir
[ MAXPATHLEN
];
318 if (cp
== NULL
) abort ();
320 memset (&start
, 0, sizeof (start
));
321 start
.cb
= sizeof (start
);
324 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
325 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
327 start
.dwFlags
= STARTF_USESTDHANDLES
;
328 start
.wShowWindow
= SW_HIDE
;
330 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
331 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
332 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
333 #endif /* HAVE_NTGUI */
336 /* Explicitly specify no security */
337 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
339 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
342 sec_attrs
.nLength
= sizeof (sec_attrs
);
343 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
344 sec_attrs
.bInheritHandle
= FALSE
;
346 strcpy (dir
, process_dir
);
347 unixtodos_filename (dir
);
349 flags
= (!NILP (Vw32_start_process_share_console
)
350 ? CREATE_NEW_PROCESS_GROUP
351 : CREATE_NEW_CONSOLE
);
352 if (NILP (Vw32_start_process_inherit_error_mode
))
353 flags
|= CREATE_DEFAULT_ERROR_MODE
;
354 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
355 flags
, env
, dir
, &start
, &cp
->procinfo
))
358 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
360 /* Hack for Windows 95, which assigns large (ie negative) pids */
364 /* pid must fit in a Lisp_Int */
365 cp
->pid
= (cp
->pid
& VALMASK
);
372 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
376 /* create_child doesn't know what emacs' file handle will be for waiting
377 on output from the child, so we need to make this additional call
378 to register the handle with the process
379 This way the select emulator knows how to match file handles with
380 entries in child_procs. */
382 register_child (int pid
, int fd
)
386 cp
= find_child_pid (pid
);
389 DebPrint (("register_child unable to find pid %lu\n", pid
));
394 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
399 /* thread is initially blocked until select is called; set status so
400 that select will release thread */
401 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
403 /* attach child_process to fd_info */
404 if (fd_info
[fd
].cp
!= NULL
)
406 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
413 /* When a process dies its pipe will break so the reader thread will
414 signal failure to the select emulator.
415 The select emulator then calls this routine to clean up.
416 Since the thread signaled failure we can assume it is exiting. */
418 reap_subprocess (child_process
*cp
)
420 if (cp
->procinfo
.hProcess
)
422 /* Reap the process */
424 /* Process should have already died before we are called. */
425 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
426 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
428 CloseHandle (cp
->procinfo
.hProcess
);
429 cp
->procinfo
.hProcess
= NULL
;
430 CloseHandle (cp
->procinfo
.hThread
);
431 cp
->procinfo
.hThread
= NULL
;
434 /* For asynchronous children, the child_proc resources will be freed
435 when the last pipe read descriptor is closed; for synchronous
436 children, we must explicitly free the resources now because
437 register_child has not been called. */
442 /* Wait for any of our existing child processes to die
443 When it does, close its handle
444 Return the pid and fill in the status if non-NULL. */
447 sys_wait (int *status
)
449 DWORD active
, retval
;
452 child_process
*cp
, *cps
[MAX_CHILDREN
];
453 HANDLE wait_hnd
[MAX_CHILDREN
];
456 if (dead_child
!= NULL
)
458 /* We want to wait for a specific child */
459 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
460 cps
[nh
] = dead_child
;
461 if (!wait_hnd
[nh
]) abort ();
468 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
469 /* some child_procs might be sockets; ignore them */
470 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
)
472 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
480 /* Nothing to wait on, so fail */
487 /* Check for quit about once a second. */
489 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
490 } while (active
== WAIT_TIMEOUT
);
492 if (active
== WAIT_FAILED
)
497 else if (active
>= WAIT_OBJECT_0
498 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
500 active
-= WAIT_OBJECT_0
;
502 else if (active
>= WAIT_ABANDONED_0
503 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
505 active
-= WAIT_ABANDONED_0
;
511 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
513 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
517 if (retval
== STILL_ACTIVE
)
519 /* Should never happen */
520 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
525 /* Massage the exit code from the process to match the format expected
526 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
527 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
529 if (retval
== STATUS_CONTROL_C_EXIT
)
537 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
544 else if (synch_process_alive
)
546 synch_process_alive
= 0;
548 /* Report the status of the synchronous process. */
549 if (WIFEXITED (retval
))
550 synch_process_retcode
= WRETCODE (retval
);
551 else if (WIFSIGNALED (retval
))
553 int code
= WTERMSIG (retval
);
556 synchronize_system_messages_locale ();
557 signame
= strsignal (code
);
562 synch_process_death
= signame
;
565 reap_subprocess (cp
);
568 reap_subprocess (cp
);
574 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
, int * is_gui_app
)
576 file_data executable
;
579 /* Default values in case we can't tell for sure. */
581 *is_cygnus_app
= FALSE
;
584 if (!open_input_file (&executable
, filename
))
587 p
= strrchr (filename
, '.');
589 /* We can only identify DOS .com programs from the extension. */
590 if (p
&& stricmp (p
, ".com") == 0)
592 else if (p
&& (stricmp (p
, ".bat") == 0
593 || stricmp (p
, ".cmd") == 0))
595 /* A DOS shell script - it appears that CreateProcess is happy to
596 accept this (somewhat surprisingly); presumably it looks at
597 COMSPEC to determine what executable to actually invoke.
598 Therefore, we have to do the same here as well. */
599 /* Actually, I think it uses the program association for that
600 extension, which is defined in the registry. */
601 p
= egetenv ("COMSPEC");
603 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
607 /* Look for DOS .exe signature - if found, we must also check that
608 it isn't really a 16- or 32-bit Windows exe, since both formats
609 start with a DOS program stub. Note that 16-bit Windows
610 executables use the OS/2 1.x format. */
612 IMAGE_DOS_HEADER
* dos_header
;
613 IMAGE_NT_HEADERS
* nt_header
;
615 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
616 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
619 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
621 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
623 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
626 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
627 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
631 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
633 /* Look for cygwin.dll in DLL import list. */
634 IMAGE_DATA_DIRECTORY import_dir
=
635 nt_header
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
636 IMAGE_IMPORT_DESCRIPTOR
* imports
;
637 IMAGE_SECTION_HEADER
* section
;
639 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
640 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
, executable
);
642 for ( ; imports
->Name
; imports
++)
644 char * dllname
= RVA_TO_PTR (imports
->Name
, section
, executable
);
646 /* The exact name of the cygwin dll has changed with
647 various releases, but hopefully this will be reasonably
649 if (strncmp (dllname
, "cygwin", 6) == 0)
651 *is_cygnus_app
= TRUE
;
656 /* Check whether app is marked as a console or windowed (aka
657 GUI) app. Accept Posix and OS2 subsytem apps as console
659 *is_gui_app
= (nt_header
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
664 close_file_data (&executable
);
668 compare_env (const void *strp1
, const void *strp2
)
670 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
672 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
674 /* Sort order in command.com/cmd.exe is based on uppercasing
675 names, so do the same here. */
676 if (toupper (*str1
) > toupper (*str2
))
678 else if (toupper (*str1
) < toupper (*str2
))
683 if (*str1
== '=' && *str2
== '=')
685 else if (*str1
== '=')
692 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
708 qsort (new_envp
, num
, sizeof (char *), compare_env
);
713 /* When a new child process is created we need to register it in our list,
714 so intercept spawn requests. */
716 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
718 Lisp_Object program
, full
;
719 char *cmdline
, *env
, *parg
, **targ
;
723 int is_dos_app
, is_cygnus_app
, is_gui_app
;
726 /* We pass our process ID to our children by setting up an environment
727 variable in their environment. */
728 char ppid_env_var_buffer
[64];
729 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
730 char *sepchars
= " \t";
732 /* We don't care about the other modes */
733 if (mode
!= _P_NOWAIT
)
739 /* Handle executable names without an executable suffix. */
740 program
= make_string (cmdname
, strlen (cmdname
));
741 if (NILP (Ffile_executable_p (program
)))
747 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, 1);
757 /* make sure argv[0] and cmdname are both in DOS format */
758 cmdname
= XSTRING (program
)->data
;
759 unixtodos_filename (cmdname
);
762 /* Determine whether program is a 16-bit DOS executable, or a w32
763 executable that is implicitly linked to the Cygnus dll (implying it
764 was compiled with the Cygnus GNU toolchain and hence relies on
765 cygwin.dll to parse the command line - we use this to decide how to
766 escape quote chars in command line args that must be quoted).
768 Also determine whether it is a GUI app, so that we don't hide its
769 initial window unless specifically requested. */
770 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
772 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
773 application to start it by specifying the helper app as cmdname,
774 while leaving the real app name as argv[0]. */
777 cmdname
= alloca (MAXPATHLEN
);
778 if (egetenv ("CMDPROXY"))
779 strcpy (cmdname
, egetenv ("CMDPROXY"));
782 strcpy (cmdname
, XSTRING (Vinvocation_directory
)->data
);
783 strcat (cmdname
, "cmdproxy.exe");
785 unixtodos_filename (cmdname
);
788 /* we have to do some conjuring here to put argv and envp into the
789 form CreateProcess wants... argv needs to be a space separated/null
790 terminated list of parameters, and envp is a null
791 separated/double-null terminated list of parameters.
793 Additionally, zero-length args and args containing whitespace or
794 quote chars need to be wrapped in double quotes - for this to work,
795 embedded quotes need to be escaped as well. The aim is to ensure
796 the child process reconstructs the argv array we start with
797 exactly, so we treat quotes at the beginning and end of arguments
800 The w32 GNU-based library from Cygnus doubles quotes to escape
801 them, while MSVC uses backslash for escaping. (Actually the MSVC
802 startup code does attempt to recognise doubled quotes and accept
803 them, but gets it wrong and ends up requiring three quotes to get a
804 single embedded quote!) So by default we decide whether to use
805 quote or backslash as the escape character based on whether the
806 binary is apparently a Cygnus compiled app.
808 Note that using backslash to escape embedded quotes requires
809 additional special handling if an embedded quote is already
810 preceeded by backslash, or if an arg requiring quoting ends with
811 backslash. In such cases, the run of escape characters needs to be
812 doubled. For consistency, we apply this special handling as long
813 as the escape character is not quote.
815 Since we have no idea how large argv and envp are likely to be we
816 figure out list lengths on the fly and allocate them. */
818 if (!NILP (Vw32_quote_process_args
))
821 /* Override escape char by binding w32-quote-process-args to
822 desired character, or use t for auto-selection. */
823 if (INTEGERP (Vw32_quote_process_args
))
824 escape_char
= XINT (Vw32_quote_process_args
);
826 escape_char
= is_cygnus_app
? '"' : '\\';
829 /* Cygwin apps needs quoting a bit more often */
830 if (escape_char
== '"')
831 sepchars
= "\r\n\t\f '";
840 int escape_char_run
= 0;
846 if (escape_char
== '"' && *p
== '\\')
847 /* If it's a Cygwin app, \ needs to be escaped. */
851 /* allow for embedded quotes to be escaped */
854 /* handle the case where the embedded quote is already escaped */
855 if (escape_char_run
> 0)
857 /* To preserve the arg exactly, we need to double the
858 preceding escape characters (plus adding one to
859 escape the quote character itself). */
860 arglen
+= escape_char_run
;
863 else if (strchr (sepchars
, *p
) != NULL
)
868 if (*p
== escape_char
&& escape_char
!= '"')
876 /* handle the case where the arg ends with an escape char - we
877 must not let the enclosing quote be escaped. */
878 if (escape_char_run
> 0)
879 arglen
+= escape_char_run
;
881 arglen
+= strlen (*targ
++) + 1;
883 cmdline
= alloca (arglen
);
897 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
902 int escape_char_run
= 0;
908 last
= p
+ strlen (p
) - 1;
911 /* This version does not escape quotes if they occur at the
912 beginning or end of the arg - this could lead to incorrect
913 behaviour when the arg itself represents a command line
914 containing quoted args. I believe this was originally done
915 as a hack to make some things work, before
916 `w32-quote-process-args' was added. */
919 if (*p
== '"' && p
> first
&& p
< last
)
920 *parg
++ = escape_char
; /* escape embedded quotes */
928 /* double preceding escape chars if any */
929 while (escape_char_run
> 0)
931 *parg
++ = escape_char
;
934 /* escape all quote chars, even at beginning or end */
935 *parg
++ = escape_char
;
937 else if (escape_char
== '"' && *p
== '\\')
941 if (*p
== escape_char
&& escape_char
!= '"')
946 /* double escape chars before enclosing quote */
947 while (escape_char_run
> 0)
949 *parg
++ = escape_char
;
957 strcpy (parg
, *targ
);
958 parg
+= strlen (*targ
);
968 numenv
= 1; /* for end null */
971 arglen
+= strlen (*targ
++) + 1;
974 /* extra env vars... */
975 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
976 GetCurrentProcessId ());
977 arglen
+= strlen (ppid_env_var_buffer
) + 1;
980 /* merge env passed in and extra env into one, and sort it. */
981 targ
= (char **) alloca (numenv
* sizeof (char *));
982 merge_and_sort_env (envp
, extra_env
, targ
);
984 /* concatenate env entries. */
985 env
= alloca (arglen
);
989 strcpy (parg
, *targ
);
990 parg
+= strlen (*targ
++);
1003 /* Now create the process. */
1004 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1014 /* Emulate the select call
1015 Wait for available input on any of the given rfds, or timeout if
1016 a timeout is given and no input is detected
1017 wfds and efds are not supported and must be NULL.
1019 For simplicity, we detect the death of child processes here and
1020 synchronously call the SIGCHLD handler. Since it is possible for
1021 children to be created without a corresponding pipe handle from which
1022 to read output, we wait separately on the process handles as well as
1023 the char_avail events for each process pipe. We only call
1024 wait/reap_process when the process actually terminates.
1026 To reduce the number of places in which Emacs can be hung such that
1027 C-g is not able to interrupt it, we always wait on interrupt_handle
1028 (which is signalled by the input thread when C-g is detected). If we
1029 detect that we were woken up by C-g, we return -1 with errno set to
1030 EINTR as on Unix. */
1033 extern HANDLE keyboard_handle
;
1035 /* From w32xfns.c */
1036 extern HANDLE interrupt_handle
;
1038 /* From process.c */
1039 extern int proc_buffered_char
[];
1042 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1043 EMACS_TIME
*timeout
)
1046 DWORD timeout_ms
, start_time
;
1049 child_process
*cp
, *cps
[MAX_CHILDREN
];
1050 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1051 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1053 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1055 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1056 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1062 /* Otherwise, we only handle rfds, so fail otherwise. */
1063 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1073 /* Always wait on interrupt_handle, to detect C-g (quit). */
1074 wait_hnd
[0] = interrupt_handle
;
1077 /* Build a list of pipe handles to wait on. */
1079 for (i
= 0; i
< nfds
; i
++)
1080 if (FD_ISSET (i
, &orfds
))
1084 if (keyboard_handle
)
1086 /* Handle stdin specially */
1087 wait_hnd
[nh
] = keyboard_handle
;
1092 /* Check for any emacs-generated input in the queue since
1093 it won't be detected in the wait */
1094 if (detect_input_pending ())
1102 /* Child process and socket input */
1106 int current_status
= cp
->status
;
1108 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1110 /* Tell reader thread which file handle to use. */
1112 /* Wake up the reader thread for this process */
1113 cp
->status
= STATUS_READ_READY
;
1114 if (!SetEvent (cp
->char_consumed
))
1115 DebPrint (("nt_select.SetEvent failed with "
1116 "%lu for fd %ld\n", GetLastError (), i
));
1119 #ifdef CHECK_INTERLOCK
1120 /* slightly crude cross-checking of interlock between threads */
1122 current_status
= cp
->status
;
1123 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1125 /* char_avail has been signalled, so status (which may
1126 have changed) should indicate read has completed
1127 but has not been acknowledged. */
1128 current_status
= cp
->status
;
1129 if (current_status
!= STATUS_READ_SUCCEEDED
1130 && current_status
!= STATUS_READ_FAILED
)
1131 DebPrint (("char_avail set, but read not completed: status %d\n",
1136 /* char_avail has not been signalled, so status should
1137 indicate that read is in progress; small possibility
1138 that read has completed but event wasn't yet signalled
1139 when we tested it (because a context switch occurred
1140 or if running on separate CPUs). */
1141 if (current_status
!= STATUS_READ_READY
1142 && current_status
!= STATUS_READ_IN_PROGRESS
1143 && current_status
!= STATUS_READ_SUCCEEDED
1144 && current_status
!= STATUS_READ_FAILED
)
1145 DebPrint (("char_avail reset, but read status is bad: %d\n",
1149 wait_hnd
[nh
] = cp
->char_avail
;
1151 if (!wait_hnd
[nh
]) abort ();
1154 DebPrint (("select waiting on child %d fd %d\n",
1155 cp
-child_procs
, i
));
1160 /* Unable to find something to wait on for this fd, skip */
1162 /* Note that this is not a fatal error, and can in fact
1163 happen in unusual circumstances. Specifically, if
1164 sys_spawnve fails, eg. because the program doesn't
1165 exist, and debug-on-error is t so Fsignal invokes a
1166 nested input loop, then the process output pipe is
1167 still included in input_wait_mask with no child_proc
1168 associated with it. (It is removed when the debugger
1169 exits the nested input loop and the error is thrown.) */
1171 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1177 /* Add handles of child processes. */
1179 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1180 /* Some child_procs might be sockets; ignore them. Also some
1181 children may have died already, but we haven't finished reading
1182 the process output; ignore them too. */
1183 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1185 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1186 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1189 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1194 /* Nothing to look for, so we didn't find anything */
1202 start_time
= GetTickCount ();
1204 /* Wait for input or child death to be signalled. If user input is
1205 allowed, then also accept window messages. */
1206 if (FD_ISSET (0, &orfds
))
1207 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1210 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1212 if (active
== WAIT_FAILED
)
1214 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1215 nh
+ nc
, timeout_ms
, GetLastError ()));
1216 /* don't return EBADF - this causes wait_reading_process_input to
1217 abort; WAIT_FAILED is returned when single-stepping under
1218 Windows 95 after switching thread focus in debugger, and
1219 possibly at other times. */
1223 else if (active
== WAIT_TIMEOUT
)
1227 else if (active
>= WAIT_OBJECT_0
1228 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1230 active
-= WAIT_OBJECT_0
;
1232 else if (active
>= WAIT_ABANDONED_0
1233 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1235 active
-= WAIT_ABANDONED_0
;
1240 /* Loop over all handles after active (now officially documented as
1241 being the first signalled handle in the array). We do this to
1242 ensure fairness, so that all channels with data available will be
1243 processed - otherwise higher numbered channels could be starved. */
1246 if (active
== nh
+ nc
)
1248 /* There are messages in the lisp thread's queue; we must
1249 drain the queue now to ensure they are processed promptly,
1250 because if we don't do so, we will not be woken again until
1251 further messages arrive.
1253 NB. If ever we allow window message procedures to callback
1254 into lisp, we will need to ensure messages are dispatched
1255 at a safe time for lisp code to be run (*), and we may also
1256 want to provide some hooks in the dispatch loop to cater
1257 for modeless dialogs created by lisp (ie. to register
1258 window handles to pass to IsDialogMessage).
1260 (*) Note that MsgWaitForMultipleObjects above is an
1261 internal dispatch point for messages that are sent to
1262 windows created by this thread. */
1263 drain_message_queue ();
1265 else if (active
>= nh
)
1267 cp
= cps
[active
- nh
];
1269 /* We cannot always signal SIGCHLD immediately; if we have not
1270 finished reading the process output, we must delay sending
1271 SIGCHLD until we do. */
1273 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1274 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1275 /* SIG_DFL for SIGCHLD is ignore */
1276 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1277 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1280 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1284 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1288 else if (fdindex
[active
] == -1)
1290 /* Quit (C-g) was detected. */
1294 else if (fdindex
[active
] == 0)
1296 /* Keyboard input available */
1302 /* must be a socket or pipe - read ahead should have
1303 completed, either succeeding or failing. */
1304 FD_SET (fdindex
[active
], rfds
);
1308 /* Even though wait_reading_process_output only reads from at most
1309 one channel, we must process all channels here so that we reap
1310 all children that have died. */
1311 while (++active
< nh
+ nc
)
1312 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1314 } while (active
< nh
+ nc
);
1316 /* If no input has arrived and timeout hasn't expired, wait again. */
1319 DWORD elapsed
= GetTickCount () - start_time
;
1321 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1323 if (timeout_ms
!= INFINITE
)
1324 timeout_ms
-= elapsed
;
1325 goto count_children
;
1332 /* Substitute for certain kill () operations */
1334 static BOOL CALLBACK
1335 find_child_console (HWND hwnd
, LPARAM arg
)
1337 child_process
* cp
= (child_process
*) arg
;
1341 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1342 if (process_id
== cp
->procinfo
.dwProcessId
)
1344 char window_class
[32];
1346 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1347 if (strcmp (window_class
,
1348 (os_subtype
== OS_WIN95
)
1350 : "ConsoleWindowClass") == 0)
1361 sys_kill (int pid
, int sig
)
1365 int need_to_free
= 0;
1368 /* Only handle signals that will result in the process dying */
1369 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1375 cp
= find_child_pid (pid
);
1378 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1379 if (proc_hand
== NULL
)
1388 proc_hand
= cp
->procinfo
.hProcess
;
1389 pid
= cp
->procinfo
.dwProcessId
;
1391 /* Try to locate console window for process. */
1392 EnumWindows (find_child_console
, (LPARAM
) cp
);
1395 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1397 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1399 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1400 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1401 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1402 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1403 HWND foreground_window
;
1405 if (break_scan_code
== 0)
1407 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1408 vk_break_code
= 'C';
1409 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1412 foreground_window
= GetForegroundWindow ();
1413 if (foreground_window
)
1415 /* NT 5.0, and apparently also Windows 98, will not allow
1416 a Window to be set to foreground directly without the
1417 user's involvement. The workaround is to attach
1418 ourselves to the thread that owns the foreground
1419 window, since that is the only thread that can set the
1420 foreground window. */
1421 DWORD foreground_thread
, child_thread
;
1423 GetWindowThreadProcessId (foreground_window
, NULL
);
1424 if (foreground_thread
== GetCurrentThreadId ()
1425 || !AttachThreadInput (GetCurrentThreadId (),
1426 foreground_thread
, TRUE
))
1427 foreground_thread
= 0;
1429 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1430 if (child_thread
== GetCurrentThreadId ()
1431 || !AttachThreadInput (GetCurrentThreadId (),
1432 child_thread
, TRUE
))
1435 /* Set the foreground window to the child. */
1436 if (SetForegroundWindow (cp
->hwnd
))
1438 /* Generate keystrokes as if user had typed Ctrl-Break or
1440 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1441 keybd_event (vk_break_code
, break_scan_code
,
1442 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1443 keybd_event (vk_break_code
, break_scan_code
,
1444 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1445 | KEYEVENTF_KEYUP
, 0);
1446 keybd_event (VK_CONTROL
, control_scan_code
,
1447 KEYEVENTF_KEYUP
, 0);
1449 /* Sleep for a bit to give time for Emacs frame to respond
1450 to focus change events (if Emacs was active app). */
1453 SetForegroundWindow (foreground_window
);
1455 /* Detach from the foreground and child threads now that
1456 the foreground switching is over. */
1457 if (foreground_thread
)
1458 AttachThreadInput (GetCurrentThreadId (),
1459 foreground_thread
, FALSE
);
1461 AttachThreadInput (GetCurrentThreadId (),
1462 child_thread
, FALSE
);
1465 /* Ctrl-Break is NT equivalent of SIGINT. */
1466 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1468 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1469 "for pid %lu\n", GetLastError (), pid
));
1476 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1479 if (os_subtype
== OS_WIN95
)
1482 Another possibility is to try terminating the VDM out-right by
1483 calling the Shell VxD (id 0x17) V86 interface, function #4
1484 "SHELL_Destroy_VM", ie.
1490 First need to determine the current VM handle, and then arrange for
1491 the shellapi call to be made from the system vm (by using
1492 Switch_VM_and_callback).
1494 Could try to invoke DestroyVM through CallVxD.
1498 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1499 to hang when cmdproxy is used in conjunction with
1500 command.com for an interactive shell. Posting
1501 WM_CLOSE pops up a dialog that, when Yes is selected,
1502 does the same thing. TerminateProcess is also less
1503 than ideal in that subprocesses tend to stick around
1504 until the machine is shutdown, but at least it
1505 doesn't freeze the 16-bit subsystem. */
1506 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1508 if (!TerminateProcess (proc_hand
, 0xff))
1510 DebPrint (("sys_kill.TerminateProcess returned %d "
1511 "for pid %lu\n", GetLastError (), pid
));
1518 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1520 /* Kill the process. On W32 this doesn't kill child processes
1521 so it doesn't work very well for shells which is why it's not
1522 used in every case. */
1523 else if (!TerminateProcess (proc_hand
, 0xff))
1525 DebPrint (("sys_kill.TerminateProcess returned %d "
1526 "for pid %lu\n", GetLastError (), pid
));
1533 CloseHandle (proc_hand
);
1538 /* extern int report_file_error (char *, Lisp_Object); */
1540 /* The following two routines are used to manipulate stdin, stdout, and
1541 stderr of our child processes.
1543 Assuming that in, out, and err are *not* inheritable, we make them
1544 stdin, stdout, and stderr of the child as follows:
1546 - Save the parent's current standard handles.
1547 - Set the std handles to inheritable duplicates of the ones being passed in.
1548 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1549 NT file handle for a crt file descriptor.)
1550 - Spawn the child, which inherits in, out, and err as stdin,
1551 stdout, and stderr. (see Spawnve)
1552 - Close the std handles passed to the child.
1553 - Reset the parent's standard handles to the saved handles.
1554 (see reset_standard_handles)
1555 We assume that the caller closes in, out, and err after calling us. */
1558 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1561 HANDLE newstdin
, newstdout
, newstderr
;
1563 parent
= GetCurrentProcess ();
1565 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1566 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1567 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1569 /* make inheritable copies of the new handles */
1570 if (!DuplicateHandle (parent
,
1571 (HANDLE
) _get_osfhandle (in
),
1576 DUPLICATE_SAME_ACCESS
))
1577 report_file_error ("Duplicating input handle for child", Qnil
);
1579 if (!DuplicateHandle (parent
,
1580 (HANDLE
) _get_osfhandle (out
),
1585 DUPLICATE_SAME_ACCESS
))
1586 report_file_error ("Duplicating output handle for child", Qnil
);
1588 if (!DuplicateHandle (parent
,
1589 (HANDLE
) _get_osfhandle (err
),
1594 DUPLICATE_SAME_ACCESS
))
1595 report_file_error ("Duplicating error handle for child", Qnil
);
1597 /* and store them as our std handles */
1598 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1599 report_file_error ("Changing stdin handle", Qnil
);
1601 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1602 report_file_error ("Changing stdout handle", Qnil
);
1604 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1605 report_file_error ("Changing stderr handle", Qnil
);
1609 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1611 /* close the duplicated handles passed to the child */
1612 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1613 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1614 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1616 /* now restore parent's saved std handles */
1617 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1618 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1619 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1623 set_process_dir (char * dir
)
1630 /* To avoid problems with winsock implementations that work over dial-up
1631 connections causing or requiring a connection to exist while Emacs is
1632 running, Emacs no longer automatically loads winsock on startup if it
1633 is present. Instead, it will be loaded when open-network-stream is
1636 To allow full control over when winsock is loaded, we provide these
1637 two functions to dynamically load and unload winsock. This allows
1638 dial-up users to only be connected when they actually need to use
1642 extern HANDLE winsock_lib
;
1643 extern BOOL
term_winsock (void);
1644 extern BOOL
init_winsock (int load_now
);
1646 extern Lisp_Object Vsystem_name
;
1648 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1649 doc
: /* Test for presence of the Windows socket library `winsock'.
1650 Returns non-nil if winsock support is present, nil otherwise.
1652 If the optional argument LOAD-NOW is non-nil, the winsock library is
1653 also loaded immediately if not already loaded. If winsock is loaded,
1654 the winsock local hostname is returned (since this may be different from
1655 the value of `system-name' and should supplant it), otherwise t is
1656 returned to indicate winsock support is present. */)
1658 Lisp_Object load_now
;
1662 have_winsock
= init_winsock (!NILP (load_now
));
1665 if (winsock_lib
!= NULL
)
1667 /* Return new value for system-name. The best way to do this
1668 is to call init_system_name, saving and restoring the
1669 original value to avoid side-effects. */
1670 Lisp_Object orig_hostname
= Vsystem_name
;
1671 Lisp_Object hostname
;
1673 init_system_name ();
1674 hostname
= Vsystem_name
;
1675 Vsystem_name
= orig_hostname
;
1683 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1685 doc
: /* Unload the Windows socket library `winsock' if loaded.
1686 This is provided to allow dial-up socket connections to be disconnected
1687 when no longer needed. Returns nil without unloading winsock if any
1688 socket connections still exist. */)
1691 return term_winsock () ? Qt
: Qnil
;
1694 #endif /* HAVE_SOCKETS */
1697 /* Some miscellaneous functions that are Windows specific, but not GUI
1698 specific (ie. are applicable in terminal or batch mode as well). */
1700 /* lifted from fileio.c */
1701 #define CORRECT_DIR_SEPS(s) \
1702 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1703 else unixtodos_filename (s); \
1706 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1707 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1708 If FILENAME does not exist, return nil.
1709 All path elements in FILENAME are converted to their short names. */)
1711 Lisp_Object filename
;
1713 char shortname
[MAX_PATH
];
1715 CHECK_STRING (filename
);
1717 /* first expand it. */
1718 filename
= Fexpand_file_name (filename
, Qnil
);
1720 /* luckily, this returns the short version of each element in the path. */
1721 if (GetShortPathName (XSTRING (filename
)->data
, shortname
, MAX_PATH
) == 0)
1724 CORRECT_DIR_SEPS (shortname
);
1726 return build_string (shortname
);
1730 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1732 doc
: /* Return the long file name version of the full path of FILENAME.
1733 If FILENAME does not exist, return nil.
1734 All path elements in FILENAME are converted to their long names. */)
1736 Lisp_Object filename
;
1738 char longname
[ MAX_PATH
];
1740 CHECK_STRING (filename
);
1742 /* first expand it. */
1743 filename
= Fexpand_file_name (filename
, Qnil
);
1745 if (!w32_get_long_filename (XSTRING (filename
)->data
, longname
, MAX_PATH
))
1748 CORRECT_DIR_SEPS (longname
);
1750 return build_string (longname
);
1753 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1754 Sw32_set_process_priority
, 2, 2, 0,
1755 doc
: /* Set the priority of PROCESS to PRIORITY.
1756 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1757 priority of the process whose pid is PROCESS is changed.
1758 PRIORITY should be one of the symbols high, normal, or low;
1759 any other symbol will be interpreted as normal.
1761 If successful, the return value is t, otherwise nil. */)
1763 Lisp_Object process
, priority
;
1765 HANDLE proc_handle
= GetCurrentProcess ();
1766 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1767 Lisp_Object result
= Qnil
;
1769 CHECK_SYMBOL (priority
);
1771 if (!NILP (process
))
1776 CHECK_NUMBER (process
);
1778 /* Allow pid to be an internally generated one, or one obtained
1779 externally. This is necessary because real pids on Win95 are
1782 pid
= XINT (process
);
1783 cp
= find_child_pid (pid
);
1785 pid
= cp
->procinfo
.dwProcessId
;
1787 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1790 if (EQ (priority
, Qhigh
))
1791 priority_class
= HIGH_PRIORITY_CLASS
;
1792 else if (EQ (priority
, Qlow
))
1793 priority_class
= IDLE_PRIORITY_CLASS
;
1795 if (proc_handle
!= NULL
)
1797 if (SetPriorityClass (proc_handle
, priority_class
))
1799 if (!NILP (process
))
1800 CloseHandle (proc_handle
);
1807 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1808 Sw32_get_locale_info
, 1, 2, 0,
1809 doc
: /* Return information about the Windows locale LCID.
1810 By default, return a three letter locale code which encodes the default
1811 language as the first two characters, and the country or regionial variant
1812 as the third letter. For example, ENU refers to `English (United States)',
1813 while ENC means `English (Canadian)'.
1815 If the optional argument LONGFORM is t, the long form of the locale
1816 name is returned, e.g. `English (United States)' instead; if LONGFORM
1817 is a number, it is interpreted as an LCTYPE constant and the corresponding
1818 locale information is returned.
1820 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1822 Lisp_Object lcid
, longform
;
1826 char abbrev_name
[32] = { 0 };
1827 char full_name
[256] = { 0 };
1829 CHECK_NUMBER (lcid
);
1831 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1834 if (NILP (longform
))
1836 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1837 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1838 abbrev_name
, sizeof (abbrev_name
));
1840 return build_string (abbrev_name
);
1842 else if (EQ (longform
, Qt
))
1844 got_full
= GetLocaleInfo (XINT (lcid
),
1845 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1846 full_name
, sizeof (full_name
));
1848 return build_string (full_name
);
1850 else if (NUMBERP (longform
))
1852 got_full
= GetLocaleInfo (XINT (lcid
),
1854 full_name
, sizeof (full_name
));
1856 return make_unibyte_string (full_name
, got_full
);
1863 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
1864 Sw32_get_current_locale_id
, 0, 0, 0,
1865 doc
: /* Return Windows locale id for current locale setting.
1866 This is a numerical value; use `w32-get-locale-info' to convert to a
1867 human-readable form. */)
1870 return make_number (GetThreadLocale ());
1873 DWORD
int_from_hex (char * s
)
1876 static char hex
[] = "0123456789abcdefABCDEF";
1879 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
1881 unsigned digit
= p
- hex
;
1884 val
= val
* 16 + digit
;
1890 /* We need to build a global list, since the EnumSystemLocale callback
1891 function isn't given a context pointer. */
1892 Lisp_Object Vw32_valid_locale_ids
;
1894 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
1896 DWORD id
= int_from_hex (localeNum
);
1897 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
1901 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
1902 Sw32_get_valid_locale_ids
, 0, 0, 0,
1903 doc
: /* Return list of all valid Windows locale ids.
1904 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1905 human-readable form. */)
1908 Vw32_valid_locale_ids
= Qnil
;
1910 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
1912 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
1913 return Vw32_valid_locale_ids
;
1917 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
1918 doc
: /* Return Windows locale id for default locale setting.
1919 By default, the system default locale setting is returned; if the optional
1920 parameter USERP is non-nil, the user default locale setting is returned.
1921 This is a numerical value; use `w32-get-locale-info' to convert to a
1922 human-readable form. */)
1927 return make_number (GetSystemDefaultLCID ());
1928 return make_number (GetUserDefaultLCID ());
1932 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
1933 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
1934 If successful, the new locale id is returned, otherwise nil. */)
1938 CHECK_NUMBER (lcid
);
1940 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1943 if (!SetThreadLocale (XINT (lcid
)))
1946 /* Need to set input thread locale if present. */
1947 if (dwWindowsThreadId
)
1948 /* Reply is not needed. */
1949 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
1951 return make_number (GetThreadLocale ());
1955 /* We need to build a global list, since the EnumCodePages callback
1956 function isn't given a context pointer. */
1957 Lisp_Object Vw32_valid_codepages
;
1959 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
1961 DWORD id
= atoi (codepageNum
);
1962 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
1966 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
1967 Sw32_get_valid_codepages
, 0, 0, 0,
1968 doc
: /* Return list of all valid Windows codepages. */)
1971 Vw32_valid_codepages
= Qnil
;
1973 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
1975 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
1976 return Vw32_valid_codepages
;
1980 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
1981 Sw32_get_console_codepage
, 0, 0, 0,
1982 doc
: /* Return current Windows codepage for console input. */)
1985 return make_number (GetConsoleCP ());
1989 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
1990 Sw32_set_console_codepage
, 1, 1, 0,
1991 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
1992 The codepage setting affects keyboard input and display in tty mode.
1993 If successful, the new CP is returned, otherwise nil. */)
1999 if (!IsValidCodePage (XINT (cp
)))
2002 if (!SetConsoleCP (XINT (cp
)))
2005 return make_number (GetConsoleCP ());
2009 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2010 Sw32_get_console_output_codepage
, 0, 0, 0,
2011 doc
: /* Return current Windows codepage for console output. */)
2014 return make_number (GetConsoleOutputCP ());
2018 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2019 Sw32_set_console_output_codepage
, 1, 1, 0,
2020 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2021 The codepage setting affects keyboard input and display in tty mode.
2022 If successful, the new CP is returned, otherwise nil. */)
2028 if (!IsValidCodePage (XINT (cp
)))
2031 if (!SetConsoleOutputCP (XINT (cp
)))
2034 return make_number (GetConsoleOutputCP ());
2038 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2039 Sw32_get_codepage_charset
, 1, 1, 0,
2040 doc
: /* Return charset of codepage CP.
2041 Returns nil if the codepage is not valid. */)
2049 if (!IsValidCodePage (XINT (cp
)))
2052 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2053 return make_number (info
.ciCharset
);
2059 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2060 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2061 doc
: /* Return list of Windows keyboard languages and layouts.
2062 The return value is a list of pairs of language id and layout id. */)
2065 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2066 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2067 Lisp_Object obj
= Qnil
;
2069 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2071 while (--num_layouts
>= 0)
2073 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2075 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2076 make_number ((kl
>> 16) & 0xffff)),
2085 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2086 Sw32_get_keyboard_layout
, 0, 0, 0,
2087 doc
: /* Return current Windows keyboard language and layout.
2088 The return value is the cons of the language id and the layout id. */)
2091 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2093 return Fcons (make_number (kl
& 0xffff),
2094 make_number ((kl
>> 16) & 0xffff));
2098 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2099 Sw32_set_keyboard_layout
, 1, 1, 0,
2100 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2101 The keyboard layout setting affects interpretation of keyboard input.
2102 If successful, the new layout id is returned, otherwise nil. */)
2108 CHECK_CONS (layout
);
2109 CHECK_NUMBER_CAR (layout
);
2110 CHECK_NUMBER_CDR (layout
);
2112 kl
= (XINT (XCAR (layout
)) & 0xffff)
2113 | (XINT (XCDR (layout
)) << 16);
2115 /* Synchronize layout with input thread. */
2116 if (dwWindowsThreadId
)
2118 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2122 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2124 if (msg
.wParam
== 0)
2128 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2131 return Fw32_get_keyboard_layout ();
2137 Qhigh
= intern ("high");
2138 Qlow
= intern ("low");
2141 defsubr (&Sw32_has_winsock
);
2142 defsubr (&Sw32_unload_winsock
);
2144 defsubr (&Sw32_short_file_name
);
2145 defsubr (&Sw32_long_file_name
);
2146 defsubr (&Sw32_set_process_priority
);
2147 defsubr (&Sw32_get_locale_info
);
2148 defsubr (&Sw32_get_current_locale_id
);
2149 defsubr (&Sw32_get_default_locale_id
);
2150 defsubr (&Sw32_get_valid_locale_ids
);
2151 defsubr (&Sw32_set_current_locale
);
2153 defsubr (&Sw32_get_console_codepage
);
2154 defsubr (&Sw32_set_console_codepage
);
2155 defsubr (&Sw32_get_console_output_codepage
);
2156 defsubr (&Sw32_set_console_output_codepage
);
2157 defsubr (&Sw32_get_valid_codepages
);
2158 defsubr (&Sw32_get_codepage_charset
);
2160 defsubr (&Sw32_get_valid_keyboard_layouts
);
2161 defsubr (&Sw32_get_keyboard_layout
);
2162 defsubr (&Sw32_set_keyboard_layout
);
2164 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2165 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2166 Because Windows does not directly pass argv arrays to child processes,
2167 programs have to reconstruct the argv array by parsing the command
2168 line string. For an argument to contain a space, it must be enclosed
2169 in double quotes or it will be parsed as multiple arguments.
2171 If the value is a character, that character will be used to escape any
2172 quote characters that appear, otherwise a suitable escape character
2173 will be chosen based on the type of the program. */);
2174 Vw32_quote_process_args
= Qt
;
2176 DEFVAR_LISP ("w32-start-process-show-window",
2177 &Vw32_start_process_show_window
,
2178 doc
: /* When nil, new child processes hide their windows.
2179 When non-nil, they show their window in the method of their choice.
2180 This variable doesn't affect GUI applications, which will never be hidden. */);
2181 Vw32_start_process_show_window
= Qnil
;
2183 DEFVAR_LISP ("w32-start-process-share-console",
2184 &Vw32_start_process_share_console
,
2185 doc
: /* When nil, new child processes are given a new console.
2186 When non-nil, they share the Emacs console; this has the limitation of
2187 allowing only only DOS subprocess to run at a time (whether started directly
2188 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2189 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2190 otherwise respond to interrupts from Emacs. */);
2191 Vw32_start_process_share_console
= Qnil
;
2193 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2194 &Vw32_start_process_inherit_error_mode
,
2195 doc
: /* When nil, new child processes revert to the default error mode.
2196 When non-nil, they inherit their error mode setting from Emacs, which stops
2197 them blocking when trying to access unmounted drives etc. */);
2198 Vw32_start_process_inherit_error_mode
= Qt
;
2200 DEFVAR_INT ("w32-pipe-read-delay", &Vw32_pipe_read_delay
,
2201 doc
: /* Forced delay before reading subprocess output.
2202 This is done to improve the buffering of subprocess output, by
2203 avoiding the inefficiency of frequently reading small amounts of data.
2205 If positive, the value is the number of milliseconds to sleep before
2206 reading the subprocess output. If negative, the magnitude is the number
2207 of time slices to wait (effectively boosting the priority of the child
2208 process temporarily). A value of zero disables waiting entirely. */);
2209 Vw32_pipe_read_delay
= 50;
2211 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2212 doc
: /* Non-nil means convert all-upper case file names to lower case.
2213 This applies when performing completions and file name expansion.
2214 Note that the value of this setting also affects remote file names,
2215 so you probably don't want to set to non-nil if you use case-sensitive
2216 filesystems via ange-ftp. */);
2217 Vw32_downcase_file_names
= Qnil
;
2220 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2221 doc
: /* Non-nil means attempt to fake realistic inode values.
2222 This works by hashing the truename of files, and should detect
2223 aliasing between long and short (8.3 DOS) names, but can have
2224 false positives because of hash collisions. Note that determing
2225 the truename of a file can be slow. */);
2226 Vw32_generate_fake_inodes
= Qnil
;
2229 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2230 doc
: /* Non-nil means determine accurate link count in file-attributes.
2231 This option slows down file-attributes noticeably, so is disabled by
2232 default. Note that it is only useful for files on NTFS volumes,
2233 where hard links are supported. */);
2234 Vw32_get_true_file_attributes
= Qnil
;
2236 /* end of ntproc.c */