1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.
22 Drew Bliss Oct 14, 1993
23 Adapted from alarm.c by Tim Fleehart
34 /* must include CRT headers *before* config.h */
48 /* This definition is missing from mingw32 headers. */
49 extern BOOL WINAPI
IsValidLocale(LCID
, DWORD
);
58 #include "syssignal.h"
61 #define RVA_TO_PTR(var,section,filedata) \
62 ((void *)((section)->PointerToRawData \
63 + ((DWORD)(var) - (section)->VirtualAddress) \
64 + (filedata).file_base))
66 /* Control whether spawnve quotes arguments as necessary to ensure
67 correct parsing by child process. Because not all uses of spawnve
68 are careful about constructing argv arrays, we make this behaviour
69 conditional (off by default). */
70 Lisp_Object Vw32_quote_process_args
;
72 /* Control whether create_child causes the process' window to be
73 hidden. The default is nil. */
74 Lisp_Object Vw32_start_process_show_window
;
76 /* Control whether create_child causes the process to inherit Emacs'
77 console window, or be given a new one of its own. The default is
78 nil, to allow multiple DOS programs to run on Win95. Having separate
79 consoles also allows Emacs to cleanly terminate process groups. */
80 Lisp_Object Vw32_start_process_share_console
;
82 /* Control whether create_child cause the process to inherit Emacs'
83 error mode setting. The default is t, to minimize the possibility of
84 subprocesses blocking when accessing unmounted drives. */
85 Lisp_Object Vw32_start_process_inherit_error_mode
;
87 /* Time to sleep before reading from a subprocess output pipe - this
88 avoids the inefficiency of frequently reading small amounts of data.
89 This is primarily necessary for handling DOS processes on Windows 95,
90 but is useful for W32 processes on both Windows 95 and NT as well. */
91 int w32_pipe_read_delay
;
93 /* Control conversion of upper case file names to lower case.
94 nil means no, t means yes. */
95 Lisp_Object Vw32_downcase_file_names
;
97 /* Control whether stat() attempts to generate fake but hopefully
98 "accurate" inode values, by hashing the absolute truenames of files.
99 This should detect aliasing between long and short names, but still
100 allows the possibility of hash collisions. */
101 Lisp_Object Vw32_generate_fake_inodes
;
103 /* Control whether stat() attempts to determine file type and link count
104 exactly, at the expense of slower operation. Since true hard links
105 are supported on NTFS volumes, this is only relevant on NT. */
106 Lisp_Object Vw32_get_true_file_attributes
;
108 Lisp_Object Qhigh
, Qlow
;
111 void _DebPrint (const char *fmt
, ...)
116 va_start (args
, fmt
);
117 vsprintf (buf
, fmt
, args
);
119 OutputDebugString (buf
);
123 typedef void (_CALLBACK_
*signal_handler
)(int);
125 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
126 static signal_handler sig_handlers
[NSIG
];
128 /* Fake signal implementation to record the SIGCHLD handler. */
130 sys_signal (int sig
, signal_handler handler
)
139 old
= sig_handlers
[sig
];
140 sig_handlers
[sig
] = handler
;
144 /* Defined in <process.h> which conflicts with the local copy */
147 /* Child process management list. */
148 int child_proc_count
= 0;
149 child_process child_procs
[ MAX_CHILDREN
];
150 child_process
*dead_child
= NULL
;
152 DWORD WINAPI
reader_thread (void *arg
);
154 /* Find an unused process slot. */
161 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
162 if (!CHILD_ACTIVE (cp
))
164 if (child_proc_count
== MAX_CHILDREN
)
166 cp
= &child_procs
[child_proc_count
++];
169 memset (cp
, 0, sizeof(*cp
));
172 cp
->procinfo
.hProcess
= NULL
;
173 cp
->status
= STATUS_READ_ERROR
;
175 /* use manual reset event so that select() will function properly */
176 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
179 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
180 if (cp
->char_consumed
)
182 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
192 delete_child (child_process
*cp
)
196 /* Should not be deleting a child that is still needed. */
197 for (i
= 0; i
< MAXDESC
; i
++)
198 if (fd_info
[i
].cp
== cp
)
201 if (!CHILD_ACTIVE (cp
))
204 /* reap thread if necessary */
209 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
211 /* let the thread exit cleanly if possible */
212 cp
->status
= STATUS_READ_ERROR
;
213 SetEvent (cp
->char_consumed
);
214 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
216 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
217 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
218 TerminateThread (cp
->thrd
, 0);
221 CloseHandle (cp
->thrd
);
226 CloseHandle (cp
->char_avail
);
227 cp
->char_avail
= NULL
;
229 if (cp
->char_consumed
)
231 CloseHandle (cp
->char_consumed
);
232 cp
->char_consumed
= NULL
;
235 /* update child_proc_count (highest numbered slot in use plus one) */
236 if (cp
== child_procs
+ child_proc_count
- 1)
238 for (i
= child_proc_count
-1; i
>= 0; i
--)
239 if (CHILD_ACTIVE (&child_procs
[i
]))
241 child_proc_count
= i
+ 1;
246 child_proc_count
= 0;
249 /* Find a child by pid. */
250 static child_process
*
251 find_child_pid (DWORD pid
)
255 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
256 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
262 /* Thread proc for child process and socket reader threads. Each thread
263 is normally blocked until woken by select() to check for input by
264 reading one char. When the read completes, char_avail is signalled
265 to wake up the select emulator and the thread blocks itself again. */
267 reader_thread (void *arg
)
272 cp
= (child_process
*)arg
;
274 /* We have to wait for the go-ahead before we can start */
276 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
283 if (fd_info
[cp
->fd
].flags
& FILE_LISTEN
)
284 rc
= _sys_wait_accept (cp
->fd
);
286 rc
= _sys_read_ahead (cp
->fd
);
288 /* The name char_avail is a misnomer - it really just means the
289 read-ahead has completed, whether successfully or not. */
290 if (!SetEvent (cp
->char_avail
))
292 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
293 GetLastError (), cp
->fd
));
297 if (rc
== STATUS_READ_ERROR
)
300 /* If the read died, the child has died so let the thread die */
301 if (rc
== STATUS_READ_FAILED
)
304 /* Wait until our input is acknowledged before reading again */
305 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
307 DebPrint (("reader_thread.WaitForSingleObject failed with "
308 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
315 /* To avoid Emacs changing directory, we just record here the directory
316 the new process should start in. This is set just before calling
317 sys_spawnve, and is not generally valid at any other time. */
318 static char * process_dir
;
321 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
322 int * pPid
, child_process
*cp
)
325 SECURITY_ATTRIBUTES sec_attrs
;
327 SECURITY_DESCRIPTOR sec_desc
;
330 char dir
[ MAXPATHLEN
];
332 if (cp
== NULL
) abort ();
334 memset (&start
, 0, sizeof (start
));
335 start
.cb
= sizeof (start
);
338 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
339 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
341 start
.dwFlags
= STARTF_USESTDHANDLES
;
342 start
.wShowWindow
= SW_HIDE
;
344 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
345 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
346 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
347 #endif /* HAVE_NTGUI */
350 /* Explicitly specify no security */
351 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
353 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
356 sec_attrs
.nLength
= sizeof (sec_attrs
);
357 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
358 sec_attrs
.bInheritHandle
= FALSE
;
360 strcpy (dir
, process_dir
);
361 unixtodos_filename (dir
);
363 flags
= (!NILP (Vw32_start_process_share_console
)
364 ? CREATE_NEW_PROCESS_GROUP
365 : CREATE_NEW_CONSOLE
);
366 if (NILP (Vw32_start_process_inherit_error_mode
))
367 flags
|= CREATE_DEFAULT_ERROR_MODE
;
368 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
369 flags
, env
, dir
, &start
, &cp
->procinfo
))
372 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
374 /* Hack for Windows 95, which assigns large (ie negative) pids */
378 /* pid must fit in a Lisp_Int */
379 cp
->pid
= cp
->pid
& INTMASK
;
386 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
390 /* create_child doesn't know what emacs' file handle will be for waiting
391 on output from the child, so we need to make this additional call
392 to register the handle with the process
393 This way the select emulator knows how to match file handles with
394 entries in child_procs. */
396 register_child (int pid
, int fd
)
400 cp
= find_child_pid (pid
);
403 DebPrint (("register_child unable to find pid %lu\n", pid
));
408 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
413 /* thread is initially blocked until select is called; set status so
414 that select will release thread */
415 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
417 /* attach child_process to fd_info */
418 if (fd_info
[fd
].cp
!= NULL
)
420 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
427 /* When a process dies its pipe will break so the reader thread will
428 signal failure to the select emulator.
429 The select emulator then calls this routine to clean up.
430 Since the thread signaled failure we can assume it is exiting. */
432 reap_subprocess (child_process
*cp
)
434 if (cp
->procinfo
.hProcess
)
436 /* Reap the process */
438 /* Process should have already died before we are called. */
439 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
440 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
442 CloseHandle (cp
->procinfo
.hProcess
);
443 cp
->procinfo
.hProcess
= NULL
;
444 CloseHandle (cp
->procinfo
.hThread
);
445 cp
->procinfo
.hThread
= NULL
;
448 /* For asynchronous children, the child_proc resources will be freed
449 when the last pipe read descriptor is closed; for synchronous
450 children, we must explicitly free the resources now because
451 register_child has not been called. */
456 /* Wait for any of our existing child processes to die
457 When it does, close its handle
458 Return the pid and fill in the status if non-NULL. */
461 sys_wait (int *status
)
463 DWORD active
, retval
;
466 child_process
*cp
, *cps
[MAX_CHILDREN
];
467 HANDLE wait_hnd
[MAX_CHILDREN
];
470 if (dead_child
!= NULL
)
472 /* We want to wait for a specific child */
473 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
474 cps
[nh
] = dead_child
;
475 if (!wait_hnd
[nh
]) abort ();
482 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
483 /* some child_procs might be sockets; ignore them */
484 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
)
486 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
494 /* Nothing to wait on, so fail */
501 /* Check for quit about once a second. */
503 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
504 } while (active
== WAIT_TIMEOUT
);
506 if (active
== WAIT_FAILED
)
511 else if (active
>= WAIT_OBJECT_0
512 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
514 active
-= WAIT_OBJECT_0
;
516 else if (active
>= WAIT_ABANDONED_0
517 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
519 active
-= WAIT_ABANDONED_0
;
525 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
527 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
531 if (retval
== STILL_ACTIVE
)
533 /* Should never happen */
534 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
539 /* Massage the exit code from the process to match the format expected
540 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
541 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
543 if (retval
== STATUS_CONTROL_C_EXIT
)
551 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
558 else if (synch_process_alive
)
560 synch_process_alive
= 0;
562 /* Report the status of the synchronous process. */
563 if (WIFEXITED (retval
))
564 synch_process_retcode
= WRETCODE (retval
);
565 else if (WIFSIGNALED (retval
))
567 int code
= WTERMSIG (retval
);
570 synchronize_system_messages_locale ();
571 signame
= strsignal (code
);
576 synch_process_death
= signame
;
579 reap_subprocess (cp
);
582 reap_subprocess (cp
);
588 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
, int * is_gui_app
)
590 file_data executable
;
593 /* Default values in case we can't tell for sure. */
595 *is_cygnus_app
= FALSE
;
598 if (!open_input_file (&executable
, filename
))
601 p
= strrchr (filename
, '.');
603 /* We can only identify DOS .com programs from the extension. */
604 if (p
&& stricmp (p
, ".com") == 0)
606 else if (p
&& (stricmp (p
, ".bat") == 0
607 || stricmp (p
, ".cmd") == 0))
609 /* A DOS shell script - it appears that CreateProcess is happy to
610 accept this (somewhat surprisingly); presumably it looks at
611 COMSPEC to determine what executable to actually invoke.
612 Therefore, we have to do the same here as well. */
613 /* Actually, I think it uses the program association for that
614 extension, which is defined in the registry. */
615 p
= egetenv ("COMSPEC");
617 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
621 /* Look for DOS .exe signature - if found, we must also check that
622 it isn't really a 16- or 32-bit Windows exe, since both formats
623 start with a DOS program stub. Note that 16-bit Windows
624 executables use the OS/2 1.x format. */
626 IMAGE_DOS_HEADER
* dos_header
;
627 IMAGE_NT_HEADERS
* nt_header
;
629 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
630 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
633 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
635 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
637 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
640 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
641 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
645 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
647 /* Look for cygwin.dll in DLL import list. */
648 IMAGE_DATA_DIRECTORY import_dir
=
649 nt_header
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
650 IMAGE_IMPORT_DESCRIPTOR
* imports
;
651 IMAGE_SECTION_HEADER
* section
;
653 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
654 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
, executable
);
656 for ( ; imports
->Name
; imports
++)
658 char * dllname
= RVA_TO_PTR (imports
->Name
, section
, executable
);
660 /* The exact name of the cygwin dll has changed with
661 various releases, but hopefully this will be reasonably
663 if (strncmp (dllname
, "cygwin", 6) == 0)
665 *is_cygnus_app
= TRUE
;
670 /* Check whether app is marked as a console or windowed (aka
671 GUI) app. Accept Posix and OS2 subsytem apps as console
673 *is_gui_app
= (nt_header
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
678 close_file_data (&executable
);
682 compare_env (const void *strp1
, const void *strp2
)
684 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
686 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
688 /* Sort order in command.com/cmd.exe is based on uppercasing
689 names, so do the same here. */
690 if (toupper (*str1
) > toupper (*str2
))
692 else if (toupper (*str1
) < toupper (*str2
))
697 if (*str1
== '=' && *str2
== '=')
699 else if (*str1
== '=')
706 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
722 qsort (new_envp
, num
, sizeof (char *), compare_env
);
727 /* When a new child process is created we need to register it in our list,
728 so intercept spawn requests. */
730 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
732 Lisp_Object program
, full
;
733 char *cmdline
, *env
, *parg
, **targ
;
737 int is_dos_app
, is_cygnus_app
, is_gui_app
;
740 /* We pass our process ID to our children by setting up an environment
741 variable in their environment. */
742 char ppid_env_var_buffer
[64];
743 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
744 char *sepchars
= " \t";
746 /* We don't care about the other modes */
747 if (mode
!= _P_NOWAIT
)
753 /* Handle executable names without an executable suffix. */
754 program
= make_string (cmdname
, strlen (cmdname
));
755 if (NILP (Ffile_executable_p (program
)))
761 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, make_number (X_OK
));
771 /* make sure argv[0] and cmdname are both in DOS format */
772 cmdname
= SDATA (program
);
773 unixtodos_filename (cmdname
);
776 /* Determine whether program is a 16-bit DOS executable, or a w32
777 executable that is implicitly linked to the Cygnus dll (implying it
778 was compiled with the Cygnus GNU toolchain and hence relies on
779 cygwin.dll to parse the command line - we use this to decide how to
780 escape quote chars in command line args that must be quoted).
782 Also determine whether it is a GUI app, so that we don't hide its
783 initial window unless specifically requested. */
784 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
786 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
787 application to start it by specifying the helper app as cmdname,
788 while leaving the real app name as argv[0]. */
791 cmdname
= alloca (MAXPATHLEN
);
792 if (egetenv ("CMDPROXY"))
793 strcpy (cmdname
, egetenv ("CMDPROXY"));
796 strcpy (cmdname
, SDATA (Vinvocation_directory
));
797 strcat (cmdname
, "cmdproxy.exe");
799 unixtodos_filename (cmdname
);
802 /* we have to do some conjuring here to put argv and envp into the
803 form CreateProcess wants... argv needs to be a space separated/null
804 terminated list of parameters, and envp is a null
805 separated/double-null terminated list of parameters.
807 Additionally, zero-length args and args containing whitespace or
808 quote chars need to be wrapped in double quotes - for this to work,
809 embedded quotes need to be escaped as well. The aim is to ensure
810 the child process reconstructs the argv array we start with
811 exactly, so we treat quotes at the beginning and end of arguments
814 The w32 GNU-based library from Cygnus doubles quotes to escape
815 them, while MSVC uses backslash for escaping. (Actually the MSVC
816 startup code does attempt to recognise doubled quotes and accept
817 them, but gets it wrong and ends up requiring three quotes to get a
818 single embedded quote!) So by default we decide whether to use
819 quote or backslash as the escape character based on whether the
820 binary is apparently a Cygnus compiled app.
822 Note that using backslash to escape embedded quotes requires
823 additional special handling if an embedded quote is already
824 preceeded by backslash, or if an arg requiring quoting ends with
825 backslash. In such cases, the run of escape characters needs to be
826 doubled. For consistency, we apply this special handling as long
827 as the escape character is not quote.
829 Since we have no idea how large argv and envp are likely to be we
830 figure out list lengths on the fly and allocate them. */
832 if (!NILP (Vw32_quote_process_args
))
835 /* Override escape char by binding w32-quote-process-args to
836 desired character, or use t for auto-selection. */
837 if (INTEGERP (Vw32_quote_process_args
))
838 escape_char
= XINT (Vw32_quote_process_args
);
840 escape_char
= is_cygnus_app
? '"' : '\\';
843 /* Cygwin apps needs quoting a bit more often */
844 if (escape_char
== '"')
845 sepchars
= "\r\n\t\f '";
854 int escape_char_run
= 0;
860 if (escape_char
== '"' && *p
== '\\')
861 /* If it's a Cygwin app, \ needs to be escaped. */
865 /* allow for embedded quotes to be escaped */
868 /* handle the case where the embedded quote is already escaped */
869 if (escape_char_run
> 0)
871 /* To preserve the arg exactly, we need to double the
872 preceding escape characters (plus adding one to
873 escape the quote character itself). */
874 arglen
+= escape_char_run
;
877 else if (strchr (sepchars
, *p
) != NULL
)
882 if (*p
== escape_char
&& escape_char
!= '"')
890 /* handle the case where the arg ends with an escape char - we
891 must not let the enclosing quote be escaped. */
892 if (escape_char_run
> 0)
893 arglen
+= escape_char_run
;
895 arglen
+= strlen (*targ
++) + 1;
897 cmdline
= alloca (arglen
);
911 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
916 int escape_char_run
= 0;
922 last
= p
+ strlen (p
) - 1;
925 /* This version does not escape quotes if they occur at the
926 beginning or end of the arg - this could lead to incorrect
927 behaviour when the arg itself represents a command line
928 containing quoted args. I believe this was originally done
929 as a hack to make some things work, before
930 `w32-quote-process-args' was added. */
933 if (*p
== '"' && p
> first
&& p
< last
)
934 *parg
++ = escape_char
; /* escape embedded quotes */
942 /* double preceding escape chars if any */
943 while (escape_char_run
> 0)
945 *parg
++ = escape_char
;
948 /* escape all quote chars, even at beginning or end */
949 *parg
++ = escape_char
;
951 else if (escape_char
== '"' && *p
== '\\')
955 if (*p
== escape_char
&& escape_char
!= '"')
960 /* double escape chars before enclosing quote */
961 while (escape_char_run
> 0)
963 *parg
++ = escape_char
;
971 strcpy (parg
, *targ
);
972 parg
+= strlen (*targ
);
982 numenv
= 1; /* for end null */
985 arglen
+= strlen (*targ
++) + 1;
988 /* extra env vars... */
989 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
990 GetCurrentProcessId ());
991 arglen
+= strlen (ppid_env_var_buffer
) + 1;
994 /* merge env passed in and extra env into one, and sort it. */
995 targ
= (char **) alloca (numenv
* sizeof (char *));
996 merge_and_sort_env (envp
, extra_env
, targ
);
998 /* concatenate env entries. */
999 env
= alloca (arglen
);
1003 strcpy (parg
, *targ
);
1004 parg
+= strlen (*targ
++);
1017 /* Now create the process. */
1018 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1028 /* Emulate the select call
1029 Wait for available input on any of the given rfds, or timeout if
1030 a timeout is given and no input is detected
1031 wfds and efds are not supported and must be NULL.
1033 For simplicity, we detect the death of child processes here and
1034 synchronously call the SIGCHLD handler. Since it is possible for
1035 children to be created without a corresponding pipe handle from which
1036 to read output, we wait separately on the process handles as well as
1037 the char_avail events for each process pipe. We only call
1038 wait/reap_process when the process actually terminates.
1040 To reduce the number of places in which Emacs can be hung such that
1041 C-g is not able to interrupt it, we always wait on interrupt_handle
1042 (which is signalled by the input thread when C-g is detected). If we
1043 detect that we were woken up by C-g, we return -1 with errno set to
1044 EINTR as on Unix. */
1047 extern HANDLE keyboard_handle
;
1049 /* From w32xfns.c */
1050 extern HANDLE interrupt_handle
;
1052 /* From process.c */
1053 extern int proc_buffered_char
[];
1056 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1057 EMACS_TIME
*timeout
)
1060 DWORD timeout_ms
, start_time
;
1063 child_process
*cp
, *cps
[MAX_CHILDREN
];
1064 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1065 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1067 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1069 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1070 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1076 /* Otherwise, we only handle rfds, so fail otherwise. */
1077 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1087 /* Always wait on interrupt_handle, to detect C-g (quit). */
1088 wait_hnd
[0] = interrupt_handle
;
1091 /* Build a list of pipe handles to wait on. */
1093 for (i
= 0; i
< nfds
; i
++)
1094 if (FD_ISSET (i
, &orfds
))
1098 if (keyboard_handle
)
1100 /* Handle stdin specially */
1101 wait_hnd
[nh
] = keyboard_handle
;
1106 /* Check for any emacs-generated input in the queue since
1107 it won't be detected in the wait */
1108 if (detect_input_pending ())
1116 /* Child process and socket input */
1120 int current_status
= cp
->status
;
1122 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1124 /* Tell reader thread which file handle to use. */
1126 /* Wake up the reader thread for this process */
1127 cp
->status
= STATUS_READ_READY
;
1128 if (!SetEvent (cp
->char_consumed
))
1129 DebPrint (("nt_select.SetEvent failed with "
1130 "%lu for fd %ld\n", GetLastError (), i
));
1133 #ifdef CHECK_INTERLOCK
1134 /* slightly crude cross-checking of interlock between threads */
1136 current_status
= cp
->status
;
1137 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1139 /* char_avail has been signalled, so status (which may
1140 have changed) should indicate read has completed
1141 but has not been acknowledged. */
1142 current_status
= cp
->status
;
1143 if (current_status
!= STATUS_READ_SUCCEEDED
1144 && current_status
!= STATUS_READ_FAILED
)
1145 DebPrint (("char_avail set, but read not completed: status %d\n",
1150 /* char_avail has not been signalled, so status should
1151 indicate that read is in progress; small possibility
1152 that read has completed but event wasn't yet signalled
1153 when we tested it (because a context switch occurred
1154 or if running on separate CPUs). */
1155 if (current_status
!= STATUS_READ_READY
1156 && current_status
!= STATUS_READ_IN_PROGRESS
1157 && current_status
!= STATUS_READ_SUCCEEDED
1158 && current_status
!= STATUS_READ_FAILED
)
1159 DebPrint (("char_avail reset, but read status is bad: %d\n",
1163 wait_hnd
[nh
] = cp
->char_avail
;
1165 if (!wait_hnd
[nh
]) abort ();
1168 DebPrint (("select waiting on child %d fd %d\n",
1169 cp
-child_procs
, i
));
1174 /* Unable to find something to wait on for this fd, skip */
1176 /* Note that this is not a fatal error, and can in fact
1177 happen in unusual circumstances. Specifically, if
1178 sys_spawnve fails, eg. because the program doesn't
1179 exist, and debug-on-error is t so Fsignal invokes a
1180 nested input loop, then the process output pipe is
1181 still included in input_wait_mask with no child_proc
1182 associated with it. (It is removed when the debugger
1183 exits the nested input loop and the error is thrown.) */
1185 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1191 /* Add handles of child processes. */
1193 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1194 /* Some child_procs might be sockets; ignore them. Also some
1195 children may have died already, but we haven't finished reading
1196 the process output; ignore them too. */
1197 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1199 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1200 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1203 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1208 /* Nothing to look for, so we didn't find anything */
1216 start_time
= GetTickCount ();
1218 /* Wait for input or child death to be signalled. If user input is
1219 allowed, then also accept window messages. */
1220 if (FD_ISSET (0, &orfds
))
1221 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1224 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1226 if (active
== WAIT_FAILED
)
1228 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1229 nh
+ nc
, timeout_ms
, GetLastError ()));
1230 /* don't return EBADF - this causes wait_reading_process_output to
1231 abort; WAIT_FAILED is returned when single-stepping under
1232 Windows 95 after switching thread focus in debugger, and
1233 possibly at other times. */
1237 else if (active
== WAIT_TIMEOUT
)
1241 else if (active
>= WAIT_OBJECT_0
1242 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1244 active
-= WAIT_OBJECT_0
;
1246 else if (active
>= WAIT_ABANDONED_0
1247 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1249 active
-= WAIT_ABANDONED_0
;
1254 /* Loop over all handles after active (now officially documented as
1255 being the first signalled handle in the array). We do this to
1256 ensure fairness, so that all channels with data available will be
1257 processed - otherwise higher numbered channels could be starved. */
1260 if (active
== nh
+ nc
)
1262 /* There are messages in the lisp thread's queue; we must
1263 drain the queue now to ensure they are processed promptly,
1264 because if we don't do so, we will not be woken again until
1265 further messages arrive.
1267 NB. If ever we allow window message procedures to callback
1268 into lisp, we will need to ensure messages are dispatched
1269 at a safe time for lisp code to be run (*), and we may also
1270 want to provide some hooks in the dispatch loop to cater
1271 for modeless dialogs created by lisp (ie. to register
1272 window handles to pass to IsDialogMessage).
1274 (*) Note that MsgWaitForMultipleObjects above is an
1275 internal dispatch point for messages that are sent to
1276 windows created by this thread. */
1277 drain_message_queue ();
1279 else if (active
>= nh
)
1281 cp
= cps
[active
- nh
];
1283 /* We cannot always signal SIGCHLD immediately; if we have not
1284 finished reading the process output, we must delay sending
1285 SIGCHLD until we do. */
1287 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1288 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1289 /* SIG_DFL for SIGCHLD is ignore */
1290 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1291 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1294 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1298 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1302 else if (fdindex
[active
] == -1)
1304 /* Quit (C-g) was detected. */
1308 else if (fdindex
[active
] == 0)
1310 /* Keyboard input available */
1316 /* must be a socket or pipe - read ahead should have
1317 completed, either succeeding or failing. */
1318 FD_SET (fdindex
[active
], rfds
);
1322 /* Even though wait_reading_process_output only reads from at most
1323 one channel, we must process all channels here so that we reap
1324 all children that have died. */
1325 while (++active
< nh
+ nc
)
1326 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1328 } while (active
< nh
+ nc
);
1330 /* If no input has arrived and timeout hasn't expired, wait again. */
1333 DWORD elapsed
= GetTickCount () - start_time
;
1335 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1337 if (timeout_ms
!= INFINITE
)
1338 timeout_ms
-= elapsed
;
1339 goto count_children
;
1346 /* Substitute for certain kill () operations */
1348 static BOOL CALLBACK
1349 find_child_console (HWND hwnd
, LPARAM arg
)
1351 child_process
* cp
= (child_process
*) arg
;
1355 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1356 if (process_id
== cp
->procinfo
.dwProcessId
)
1358 char window_class
[32];
1360 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1361 if (strcmp (window_class
,
1362 (os_subtype
== OS_WIN95
)
1364 : "ConsoleWindowClass") == 0)
1375 sys_kill (int pid
, int sig
)
1379 int need_to_free
= 0;
1382 /* Only handle signals that will result in the process dying */
1383 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1389 cp
= find_child_pid (pid
);
1392 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1393 if (proc_hand
== NULL
)
1402 proc_hand
= cp
->procinfo
.hProcess
;
1403 pid
= cp
->procinfo
.dwProcessId
;
1405 /* Try to locate console window for process. */
1406 EnumWindows (find_child_console
, (LPARAM
) cp
);
1409 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1411 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1413 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1414 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1415 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1416 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1417 HWND foreground_window
;
1419 if (break_scan_code
== 0)
1421 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1422 vk_break_code
= 'C';
1423 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1426 foreground_window
= GetForegroundWindow ();
1427 if (foreground_window
)
1429 /* NT 5.0, and apparently also Windows 98, will not allow
1430 a Window to be set to foreground directly without the
1431 user's involvement. The workaround is to attach
1432 ourselves to the thread that owns the foreground
1433 window, since that is the only thread that can set the
1434 foreground window. */
1435 DWORD foreground_thread
, child_thread
;
1437 GetWindowThreadProcessId (foreground_window
, NULL
);
1438 if (foreground_thread
== GetCurrentThreadId ()
1439 || !AttachThreadInput (GetCurrentThreadId (),
1440 foreground_thread
, TRUE
))
1441 foreground_thread
= 0;
1443 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1444 if (child_thread
== GetCurrentThreadId ()
1445 || !AttachThreadInput (GetCurrentThreadId (),
1446 child_thread
, TRUE
))
1449 /* Set the foreground window to the child. */
1450 if (SetForegroundWindow (cp
->hwnd
))
1452 /* Generate keystrokes as if user had typed Ctrl-Break or
1454 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1455 keybd_event (vk_break_code
, break_scan_code
,
1456 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1457 keybd_event (vk_break_code
, break_scan_code
,
1458 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1459 | KEYEVENTF_KEYUP
, 0);
1460 keybd_event (VK_CONTROL
, control_scan_code
,
1461 KEYEVENTF_KEYUP
, 0);
1463 /* Sleep for a bit to give time for Emacs frame to respond
1464 to focus change events (if Emacs was active app). */
1467 SetForegroundWindow (foreground_window
);
1469 /* Detach from the foreground and child threads now that
1470 the foreground switching is over. */
1471 if (foreground_thread
)
1472 AttachThreadInput (GetCurrentThreadId (),
1473 foreground_thread
, FALSE
);
1475 AttachThreadInput (GetCurrentThreadId (),
1476 child_thread
, FALSE
);
1479 /* Ctrl-Break is NT equivalent of SIGINT. */
1480 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1482 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1483 "for pid %lu\n", GetLastError (), pid
));
1490 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1493 if (os_subtype
== OS_WIN95
)
1496 Another possibility is to try terminating the VDM out-right by
1497 calling the Shell VxD (id 0x17) V86 interface, function #4
1498 "SHELL_Destroy_VM", ie.
1504 First need to determine the current VM handle, and then arrange for
1505 the shellapi call to be made from the system vm (by using
1506 Switch_VM_and_callback).
1508 Could try to invoke DestroyVM through CallVxD.
1512 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1513 to hang when cmdproxy is used in conjunction with
1514 command.com for an interactive shell. Posting
1515 WM_CLOSE pops up a dialog that, when Yes is selected,
1516 does the same thing. TerminateProcess is also less
1517 than ideal in that subprocesses tend to stick around
1518 until the machine is shutdown, but at least it
1519 doesn't freeze the 16-bit subsystem. */
1520 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1522 if (!TerminateProcess (proc_hand
, 0xff))
1524 DebPrint (("sys_kill.TerminateProcess returned %d "
1525 "for pid %lu\n", GetLastError (), pid
));
1532 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1534 /* Kill the process. On W32 this doesn't kill child processes
1535 so it doesn't work very well for shells which is why it's not
1536 used in every case. */
1537 else if (!TerminateProcess (proc_hand
, 0xff))
1539 DebPrint (("sys_kill.TerminateProcess returned %d "
1540 "for pid %lu\n", GetLastError (), pid
));
1547 CloseHandle (proc_hand
);
1552 /* extern int report_file_error (char *, Lisp_Object); */
1554 /* The following two routines are used to manipulate stdin, stdout, and
1555 stderr of our child processes.
1557 Assuming that in, out, and err are *not* inheritable, we make them
1558 stdin, stdout, and stderr of the child as follows:
1560 - Save the parent's current standard handles.
1561 - Set the std handles to inheritable duplicates of the ones being passed in.
1562 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1563 NT file handle for a crt file descriptor.)
1564 - Spawn the child, which inherits in, out, and err as stdin,
1565 stdout, and stderr. (see Spawnve)
1566 - Close the std handles passed to the child.
1567 - Reset the parent's standard handles to the saved handles.
1568 (see reset_standard_handles)
1569 We assume that the caller closes in, out, and err after calling us. */
1572 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1575 HANDLE newstdin
, newstdout
, newstderr
;
1577 parent
= GetCurrentProcess ();
1579 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1580 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1581 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1583 /* make inheritable copies of the new handles */
1584 if (!DuplicateHandle (parent
,
1585 (HANDLE
) _get_osfhandle (in
),
1590 DUPLICATE_SAME_ACCESS
))
1591 report_file_error ("Duplicating input handle for child", Qnil
);
1593 if (!DuplicateHandle (parent
,
1594 (HANDLE
) _get_osfhandle (out
),
1599 DUPLICATE_SAME_ACCESS
))
1600 report_file_error ("Duplicating output handle for child", Qnil
);
1602 if (!DuplicateHandle (parent
,
1603 (HANDLE
) _get_osfhandle (err
),
1608 DUPLICATE_SAME_ACCESS
))
1609 report_file_error ("Duplicating error handle for child", Qnil
);
1611 /* and store them as our std handles */
1612 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1613 report_file_error ("Changing stdin handle", Qnil
);
1615 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1616 report_file_error ("Changing stdout handle", Qnil
);
1618 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1619 report_file_error ("Changing stderr handle", Qnil
);
1623 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1625 /* close the duplicated handles passed to the child */
1626 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1627 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1628 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1630 /* now restore parent's saved std handles */
1631 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1632 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1633 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1637 set_process_dir (char * dir
)
1644 /* To avoid problems with winsock implementations that work over dial-up
1645 connections causing or requiring a connection to exist while Emacs is
1646 running, Emacs no longer automatically loads winsock on startup if it
1647 is present. Instead, it will be loaded when open-network-stream is
1650 To allow full control over when winsock is loaded, we provide these
1651 two functions to dynamically load and unload winsock. This allows
1652 dial-up users to only be connected when they actually need to use
1656 extern HANDLE winsock_lib
;
1657 extern BOOL
term_winsock (void);
1658 extern BOOL
init_winsock (int load_now
);
1660 extern Lisp_Object Vsystem_name
;
1662 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1663 doc
: /* Test for presence of the Windows socket library `winsock'.
1664 Returns non-nil if winsock support is present, nil otherwise.
1666 If the optional argument LOAD-NOW is non-nil, the winsock library is
1667 also loaded immediately if not already loaded. If winsock is loaded,
1668 the winsock local hostname is returned (since this may be different from
1669 the value of `system-name' and should supplant it), otherwise t is
1670 returned to indicate winsock support is present. */)
1672 Lisp_Object load_now
;
1676 have_winsock
= init_winsock (!NILP (load_now
));
1679 if (winsock_lib
!= NULL
)
1681 /* Return new value for system-name. The best way to do this
1682 is to call init_system_name, saving and restoring the
1683 original value to avoid side-effects. */
1684 Lisp_Object orig_hostname
= Vsystem_name
;
1685 Lisp_Object hostname
;
1687 init_system_name ();
1688 hostname
= Vsystem_name
;
1689 Vsystem_name
= orig_hostname
;
1697 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1699 doc
: /* Unload the Windows socket library `winsock' if loaded.
1700 This is provided to allow dial-up socket connections to be disconnected
1701 when no longer needed. Returns nil without unloading winsock if any
1702 socket connections still exist. */)
1705 return term_winsock () ? Qt
: Qnil
;
1708 #endif /* HAVE_SOCKETS */
1711 /* Some miscellaneous functions that are Windows specific, but not GUI
1712 specific (ie. are applicable in terminal or batch mode as well). */
1714 /* lifted from fileio.c */
1715 #define CORRECT_DIR_SEPS(s) \
1716 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1717 else unixtodos_filename (s); \
1720 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1721 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1722 If FILENAME does not exist, return nil.
1723 All path elements in FILENAME are converted to their short names. */)
1725 Lisp_Object filename
;
1727 char shortname
[MAX_PATH
];
1729 CHECK_STRING (filename
);
1731 /* first expand it. */
1732 filename
= Fexpand_file_name (filename
, Qnil
);
1734 /* luckily, this returns the short version of each element in the path. */
1735 if (GetShortPathName (SDATA (filename
), shortname
, MAX_PATH
) == 0)
1738 CORRECT_DIR_SEPS (shortname
);
1740 return build_string (shortname
);
1744 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1746 doc
: /* Return the long file name version of the full path of FILENAME.
1747 If FILENAME does not exist, return nil.
1748 All path elements in FILENAME are converted to their long names. */)
1750 Lisp_Object filename
;
1752 char longname
[ MAX_PATH
];
1754 CHECK_STRING (filename
);
1756 /* first expand it. */
1757 filename
= Fexpand_file_name (filename
, Qnil
);
1759 if (!w32_get_long_filename (SDATA (filename
), longname
, MAX_PATH
))
1762 CORRECT_DIR_SEPS (longname
);
1764 return build_string (longname
);
1767 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1768 Sw32_set_process_priority
, 2, 2, 0,
1769 doc
: /* Set the priority of PROCESS to PRIORITY.
1770 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1771 priority of the process whose pid is PROCESS is changed.
1772 PRIORITY should be one of the symbols high, normal, or low;
1773 any other symbol will be interpreted as normal.
1775 If successful, the return value is t, otherwise nil. */)
1777 Lisp_Object process
, priority
;
1779 HANDLE proc_handle
= GetCurrentProcess ();
1780 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1781 Lisp_Object result
= Qnil
;
1783 CHECK_SYMBOL (priority
);
1785 if (!NILP (process
))
1790 CHECK_NUMBER (process
);
1792 /* Allow pid to be an internally generated one, or one obtained
1793 externally. This is necessary because real pids on Win95 are
1796 pid
= XINT (process
);
1797 cp
= find_child_pid (pid
);
1799 pid
= cp
->procinfo
.dwProcessId
;
1801 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1804 if (EQ (priority
, Qhigh
))
1805 priority_class
= HIGH_PRIORITY_CLASS
;
1806 else if (EQ (priority
, Qlow
))
1807 priority_class
= IDLE_PRIORITY_CLASS
;
1809 if (proc_handle
!= NULL
)
1811 if (SetPriorityClass (proc_handle
, priority_class
))
1813 if (!NILP (process
))
1814 CloseHandle (proc_handle
);
1821 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1822 Sw32_get_locale_info
, 1, 2, 0,
1823 doc
: /* Return information about the Windows locale LCID.
1824 By default, return a three letter locale code which encodes the default
1825 language as the first two characters, and the country or regionial variant
1826 as the third letter. For example, ENU refers to `English (United States)',
1827 while ENC means `English (Canadian)'.
1829 If the optional argument LONGFORM is t, the long form of the locale
1830 name is returned, e.g. `English (United States)' instead; if LONGFORM
1831 is a number, it is interpreted as an LCTYPE constant and the corresponding
1832 locale information is returned.
1834 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1836 Lisp_Object lcid
, longform
;
1840 char abbrev_name
[32] = { 0 };
1841 char full_name
[256] = { 0 };
1843 CHECK_NUMBER (lcid
);
1845 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1848 if (NILP (longform
))
1850 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1851 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1852 abbrev_name
, sizeof (abbrev_name
));
1854 return build_string (abbrev_name
);
1856 else if (EQ (longform
, Qt
))
1858 got_full
= GetLocaleInfo (XINT (lcid
),
1859 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1860 full_name
, sizeof (full_name
));
1862 return build_string (full_name
);
1864 else if (NUMBERP (longform
))
1866 got_full
= GetLocaleInfo (XINT (lcid
),
1868 full_name
, sizeof (full_name
));
1870 return make_unibyte_string (full_name
, got_full
);
1877 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
1878 Sw32_get_current_locale_id
, 0, 0, 0,
1879 doc
: /* Return Windows locale id for current locale setting.
1880 This is a numerical value; use `w32-get-locale-info' to convert to a
1881 human-readable form. */)
1884 return make_number (GetThreadLocale ());
1887 DWORD
int_from_hex (char * s
)
1890 static char hex
[] = "0123456789abcdefABCDEF";
1893 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
1895 unsigned digit
= p
- hex
;
1898 val
= val
* 16 + digit
;
1904 /* We need to build a global list, since the EnumSystemLocale callback
1905 function isn't given a context pointer. */
1906 Lisp_Object Vw32_valid_locale_ids
;
1908 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
1910 DWORD id
= int_from_hex (localeNum
);
1911 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
1915 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
1916 Sw32_get_valid_locale_ids
, 0, 0, 0,
1917 doc
: /* Return list of all valid Windows locale ids.
1918 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1919 human-readable form. */)
1922 Vw32_valid_locale_ids
= Qnil
;
1924 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
1926 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
1927 return Vw32_valid_locale_ids
;
1931 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
1932 doc
: /* Return Windows locale id for default locale setting.
1933 By default, the system default locale setting is returned; if the optional
1934 parameter USERP is non-nil, the user default locale setting is returned.
1935 This is a numerical value; use `w32-get-locale-info' to convert to a
1936 human-readable form. */)
1941 return make_number (GetSystemDefaultLCID ());
1942 return make_number (GetUserDefaultLCID ());
1946 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
1947 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
1948 If successful, the new locale id is returned, otherwise nil. */)
1952 CHECK_NUMBER (lcid
);
1954 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1957 if (!SetThreadLocale (XINT (lcid
)))
1960 /* Need to set input thread locale if present. */
1961 if (dwWindowsThreadId
)
1962 /* Reply is not needed. */
1963 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
1965 return make_number (GetThreadLocale ());
1969 /* We need to build a global list, since the EnumCodePages callback
1970 function isn't given a context pointer. */
1971 Lisp_Object Vw32_valid_codepages
;
1973 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
1975 DWORD id
= atoi (codepageNum
);
1976 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
1980 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
1981 Sw32_get_valid_codepages
, 0, 0, 0,
1982 doc
: /* Return list of all valid Windows codepages. */)
1985 Vw32_valid_codepages
= Qnil
;
1987 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
1989 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
1990 return Vw32_valid_codepages
;
1994 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
1995 Sw32_get_console_codepage
, 0, 0, 0,
1996 doc
: /* Return current Windows codepage for console input. */)
1999 return make_number (GetConsoleCP ());
2003 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
2004 Sw32_set_console_codepage
, 1, 1, 0,
2005 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2006 The codepage setting affects keyboard input and display in tty mode.
2007 If successful, the new CP is returned, otherwise nil. */)
2013 if (!IsValidCodePage (XINT (cp
)))
2016 if (!SetConsoleCP (XINT (cp
)))
2019 return make_number (GetConsoleCP ());
2023 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2024 Sw32_get_console_output_codepage
, 0, 0, 0,
2025 doc
: /* Return current Windows codepage for console output. */)
2028 return make_number (GetConsoleOutputCP ());
2032 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2033 Sw32_set_console_output_codepage
, 1, 1, 0,
2034 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2035 The codepage setting affects keyboard input and display in tty mode.
2036 If successful, the new CP is returned, otherwise nil. */)
2042 if (!IsValidCodePage (XINT (cp
)))
2045 if (!SetConsoleOutputCP (XINT (cp
)))
2048 return make_number (GetConsoleOutputCP ());
2052 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2053 Sw32_get_codepage_charset
, 1, 1, 0,
2054 doc
: /* Return charset of codepage CP.
2055 Returns nil if the codepage is not valid. */)
2063 if (!IsValidCodePage (XINT (cp
)))
2066 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2067 return make_number (info
.ciCharset
);
2073 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2074 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2075 doc
: /* Return list of Windows keyboard languages and layouts.
2076 The return value is a list of pairs of language id and layout id. */)
2079 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2080 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2081 Lisp_Object obj
= Qnil
;
2083 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2085 while (--num_layouts
>= 0)
2087 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2089 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2090 make_number ((kl
>> 16) & 0xffff)),
2099 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2100 Sw32_get_keyboard_layout
, 0, 0, 0,
2101 doc
: /* Return current Windows keyboard language and layout.
2102 The return value is the cons of the language id and the layout id. */)
2105 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2107 return Fcons (make_number (kl
& 0xffff),
2108 make_number ((kl
>> 16) & 0xffff));
2112 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2113 Sw32_set_keyboard_layout
, 1, 1, 0,
2114 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2115 The keyboard layout setting affects interpretation of keyboard input.
2116 If successful, the new layout id is returned, otherwise nil. */)
2122 CHECK_CONS (layout
);
2123 CHECK_NUMBER_CAR (layout
);
2124 CHECK_NUMBER_CDR (layout
);
2126 kl
= (XINT (XCAR (layout
)) & 0xffff)
2127 | (XINT (XCDR (layout
)) << 16);
2129 /* Synchronize layout with input thread. */
2130 if (dwWindowsThreadId
)
2132 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2136 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2138 if (msg
.wParam
== 0)
2142 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2145 return Fw32_get_keyboard_layout ();
2151 Qhigh
= intern ("high");
2152 Qlow
= intern ("low");
2157 defsubr (&Sw32_has_winsock
);
2158 defsubr (&Sw32_unload_winsock
);
2160 defsubr (&Sw32_short_file_name
);
2161 defsubr (&Sw32_long_file_name
);
2162 defsubr (&Sw32_set_process_priority
);
2163 defsubr (&Sw32_get_locale_info
);
2164 defsubr (&Sw32_get_current_locale_id
);
2165 defsubr (&Sw32_get_default_locale_id
);
2166 defsubr (&Sw32_get_valid_locale_ids
);
2167 defsubr (&Sw32_set_current_locale
);
2169 defsubr (&Sw32_get_console_codepage
);
2170 defsubr (&Sw32_set_console_codepage
);
2171 defsubr (&Sw32_get_console_output_codepage
);
2172 defsubr (&Sw32_set_console_output_codepage
);
2173 defsubr (&Sw32_get_valid_codepages
);
2174 defsubr (&Sw32_get_codepage_charset
);
2176 defsubr (&Sw32_get_valid_keyboard_layouts
);
2177 defsubr (&Sw32_get_keyboard_layout
);
2178 defsubr (&Sw32_set_keyboard_layout
);
2180 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2181 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2182 Because Windows does not directly pass argv arrays to child processes,
2183 programs have to reconstruct the argv array by parsing the command
2184 line string. For an argument to contain a space, it must be enclosed
2185 in double quotes or it will be parsed as multiple arguments.
2187 If the value is a character, that character will be used to escape any
2188 quote characters that appear, otherwise a suitable escape character
2189 will be chosen based on the type of the program. */);
2190 Vw32_quote_process_args
= Qt
;
2192 DEFVAR_LISP ("w32-start-process-show-window",
2193 &Vw32_start_process_show_window
,
2194 doc
: /* When nil, new child processes hide their windows.
2195 When non-nil, they show their window in the method of their choice.
2196 This variable doesn't affect GUI applications, which will never be hidden. */);
2197 Vw32_start_process_show_window
= Qnil
;
2199 DEFVAR_LISP ("w32-start-process-share-console",
2200 &Vw32_start_process_share_console
,
2201 doc
: /* When nil, new child processes are given a new console.
2202 When non-nil, they share the Emacs console; this has the limitation of
2203 allowing only one DOS subprocess to run at a time (whether started directly
2204 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2205 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2206 otherwise respond to interrupts from Emacs. */);
2207 Vw32_start_process_share_console
= Qnil
;
2209 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2210 &Vw32_start_process_inherit_error_mode
,
2211 doc
: /* When nil, new child processes revert to the default error mode.
2212 When non-nil, they inherit their error mode setting from Emacs, which stops
2213 them blocking when trying to access unmounted drives etc. */);
2214 Vw32_start_process_inherit_error_mode
= Qt
;
2216 DEFVAR_INT ("w32-pipe-read-delay", &w32_pipe_read_delay
,
2217 doc
: /* Forced delay before reading subprocess output.
2218 This is done to improve the buffering of subprocess output, by
2219 avoiding the inefficiency of frequently reading small amounts of data.
2221 If positive, the value is the number of milliseconds to sleep before
2222 reading the subprocess output. If negative, the magnitude is the number
2223 of time slices to wait (effectively boosting the priority of the child
2224 process temporarily). A value of zero disables waiting entirely. */);
2225 w32_pipe_read_delay
= 50;
2227 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2228 doc
: /* Non-nil means convert all-upper case file names to lower case.
2229 This applies when performing completions and file name expansion.
2230 Note that the value of this setting also affects remote file names,
2231 so you probably don't want to set to non-nil if you use case-sensitive
2232 filesystems via ange-ftp. */);
2233 Vw32_downcase_file_names
= Qnil
;
2236 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2237 doc
: /* Non-nil means attempt to fake realistic inode values.
2238 This works by hashing the truename of files, and should detect
2239 aliasing between long and short (8.3 DOS) names, but can have
2240 false positives because of hash collisions. Note that determing
2241 the truename of a file can be slow. */);
2242 Vw32_generate_fake_inodes
= Qnil
;
2245 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2246 doc
: /* Non-nil means determine accurate link count in `file-attributes'.
2247 Note that this option is only useful for files on NTFS volumes, where hard links
2248 are supported. Moreover, it slows down `file-attributes' noticeably. */);
2249 Vw32_get_true_file_attributes
= Qt
;
2251 staticpro (&Vw32_valid_locale_ids
);
2252 staticpro (&Vw32_valid_codepages
);
2254 /* end of ntproc.c */
2256 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2257 (do not change this comment) */