1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
34 /* must include CRT headers *before* config.h */
48 /* This definition is missing from mingw32 headers. */
49 extern BOOL WINAPI
IsValidLocale(LCID
, DWORD
);
52 #ifdef HAVE_LANGINFO_CODESET
58 #include "character.h"
64 #include "syssignal.h"
66 #include "dispextern.h" /* for xstrcasecmp */
69 #define RVA_TO_PTR(var,section,filedata) \
70 ((void *)((section)->PointerToRawData \
71 + ((DWORD)(var) - (section)->VirtualAddress) \
72 + (filedata).file_base))
74 /* Control whether spawnve quotes arguments as necessary to ensure
75 correct parsing by child process. Because not all uses of spawnve
76 are careful about constructing argv arrays, we make this behavior
77 conditional (off by default). */
78 Lisp_Object Vw32_quote_process_args
;
80 /* Control whether create_child causes the process' window to be
81 hidden. The default is nil. */
82 Lisp_Object Vw32_start_process_show_window
;
84 /* Control whether create_child causes the process to inherit Emacs'
85 console window, or be given a new one of its own. The default is
86 nil, to allow multiple DOS programs to run on Win95. Having separate
87 consoles also allows Emacs to cleanly terminate process groups. */
88 Lisp_Object Vw32_start_process_share_console
;
90 /* Control whether create_child cause the process to inherit Emacs'
91 error mode setting. The default is t, to minimize the possibility of
92 subprocesses blocking when accessing unmounted drives. */
93 Lisp_Object Vw32_start_process_inherit_error_mode
;
95 /* Time to sleep before reading from a subprocess output pipe - this
96 avoids the inefficiency of frequently reading small amounts of data.
97 This is primarily necessary for handling DOS processes on Windows 95,
98 but is useful for W32 processes on both Windows 95 and NT as well. */
99 int w32_pipe_read_delay
;
101 /* Control conversion of upper case file names to lower case.
102 nil means no, t means yes. */
103 Lisp_Object Vw32_downcase_file_names
;
105 /* Control whether stat() attempts to generate fake but hopefully
106 "accurate" inode values, by hashing the absolute truenames of files.
107 This should detect aliasing between long and short names, but still
108 allows the possibility of hash collisions. */
109 Lisp_Object Vw32_generate_fake_inodes
;
111 /* Control whether stat() attempts to determine file type and link count
112 exactly, at the expense of slower operation. Since true hard links
113 are supported on NTFS volumes, this is only relevant on NT. */
114 Lisp_Object Vw32_get_true_file_attributes
;
115 extern Lisp_Object Qlocal
;
117 Lisp_Object Qhigh
, Qlow
;
120 void _DebPrint (const char *fmt
, ...)
125 va_start (args
, fmt
);
126 vsprintf (buf
, fmt
, args
);
128 OutputDebugString (buf
);
132 typedef void (_CALLBACK_
*signal_handler
)(int);
134 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
135 static signal_handler sig_handlers
[NSIG
];
137 /* Fake signal implementation to record the SIGCHLD handler. */
139 sys_signal (int sig
, signal_handler handler
)
148 old
= sig_handlers
[sig
];
149 sig_handlers
[sig
] = handler
;
153 /* Defined in <process.h> which conflicts with the local copy */
156 /* Child process management list. */
157 int child_proc_count
= 0;
158 child_process child_procs
[ MAX_CHILDREN
];
159 child_process
*dead_child
= NULL
;
161 DWORD WINAPI
reader_thread (void *arg
);
163 /* Find an unused process slot. */
170 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
171 if (!CHILD_ACTIVE (cp
))
173 if (child_proc_count
== MAX_CHILDREN
)
175 cp
= &child_procs
[child_proc_count
++];
178 memset (cp
, 0, sizeof(*cp
));
181 cp
->procinfo
.hProcess
= NULL
;
182 cp
->status
= STATUS_READ_ERROR
;
184 /* use manual reset event so that select() will function properly */
185 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
188 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
189 if (cp
->char_consumed
)
191 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
201 delete_child (child_process
*cp
)
205 /* Should not be deleting a child that is still needed. */
206 for (i
= 0; i
< MAXDESC
; i
++)
207 if (fd_info
[i
].cp
== cp
)
210 if (!CHILD_ACTIVE (cp
))
213 /* reap thread if necessary */
218 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
220 /* let the thread exit cleanly if possible */
221 cp
->status
= STATUS_READ_ERROR
;
222 SetEvent (cp
->char_consumed
);
224 /* We used to forceably terminate the thread here, but it
225 is normally unnecessary, and in abnormal cases, the worst that
226 will happen is we have an extra idle thread hanging around
227 waiting for the zombie process. */
228 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
230 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
231 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
232 TerminateThread (cp
->thrd
, 0);
236 CloseHandle (cp
->thrd
);
241 CloseHandle (cp
->char_avail
);
242 cp
->char_avail
= NULL
;
244 if (cp
->char_consumed
)
246 CloseHandle (cp
->char_consumed
);
247 cp
->char_consumed
= NULL
;
250 /* update child_proc_count (highest numbered slot in use plus one) */
251 if (cp
== child_procs
+ child_proc_count
- 1)
253 for (i
= child_proc_count
-1; i
>= 0; i
--)
254 if (CHILD_ACTIVE (&child_procs
[i
]))
256 child_proc_count
= i
+ 1;
261 child_proc_count
= 0;
264 /* Find a child by pid. */
265 static child_process
*
266 find_child_pid (DWORD pid
)
270 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
271 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
277 /* Thread proc for child process and socket reader threads. Each thread
278 is normally blocked until woken by select() to check for input by
279 reading one char. When the read completes, char_avail is signaled
280 to wake up the select emulator and the thread blocks itself again. */
282 reader_thread (void *arg
)
287 cp
= (child_process
*)arg
;
289 /* We have to wait for the go-ahead before we can start */
291 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
298 if (fd_info
[cp
->fd
].flags
& FILE_LISTEN
)
299 rc
= _sys_wait_accept (cp
->fd
);
301 rc
= _sys_read_ahead (cp
->fd
);
303 /* The name char_avail is a misnomer - it really just means the
304 read-ahead has completed, whether successfully or not. */
305 if (!SetEvent (cp
->char_avail
))
307 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
308 GetLastError (), cp
->fd
));
312 if (rc
== STATUS_READ_ERROR
)
315 /* If the read died, the child has died so let the thread die */
316 if (rc
== STATUS_READ_FAILED
)
319 /* Wait until our input is acknowledged before reading again */
320 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
322 DebPrint (("reader_thread.WaitForSingleObject failed with "
323 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
330 /* To avoid Emacs changing directory, we just record here the directory
331 the new process should start in. This is set just before calling
332 sys_spawnve, and is not generally valid at any other time. */
333 static char * process_dir
;
336 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
337 int * pPid
, child_process
*cp
)
340 SECURITY_ATTRIBUTES sec_attrs
;
342 SECURITY_DESCRIPTOR sec_desc
;
345 char dir
[ MAXPATHLEN
];
347 if (cp
== NULL
) abort ();
349 memset (&start
, 0, sizeof (start
));
350 start
.cb
= sizeof (start
);
353 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
354 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
356 start
.dwFlags
= STARTF_USESTDHANDLES
;
357 start
.wShowWindow
= SW_HIDE
;
359 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
360 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
361 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
362 #endif /* HAVE_NTGUI */
365 /* Explicitly specify no security */
366 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
368 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
371 sec_attrs
.nLength
= sizeof (sec_attrs
);
372 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
373 sec_attrs
.bInheritHandle
= FALSE
;
375 strcpy (dir
, process_dir
);
376 unixtodos_filename (dir
);
378 flags
= (!NILP (Vw32_start_process_share_console
)
379 ? CREATE_NEW_PROCESS_GROUP
380 : CREATE_NEW_CONSOLE
);
381 if (NILP (Vw32_start_process_inherit_error_mode
))
382 flags
|= CREATE_DEFAULT_ERROR_MODE
;
383 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
384 flags
, env
, dir
, &start
, &cp
->procinfo
))
387 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
389 /* Hack for Windows 95, which assigns large (ie negative) pids */
393 /* pid must fit in a Lisp_Int */
394 cp
->pid
= cp
->pid
& INTMASK
;
401 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
405 /* create_child doesn't know what emacs' file handle will be for waiting
406 on output from the child, so we need to make this additional call
407 to register the handle with the process
408 This way the select emulator knows how to match file handles with
409 entries in child_procs. */
411 register_child (int pid
, int fd
)
415 cp
= find_child_pid (pid
);
418 DebPrint (("register_child unable to find pid %lu\n", pid
));
423 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
428 /* thread is initially blocked until select is called; set status so
429 that select will release thread */
430 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
432 /* attach child_process to fd_info */
433 if (fd_info
[fd
].cp
!= NULL
)
435 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
442 /* When a process dies its pipe will break so the reader thread will
443 signal failure to the select emulator.
444 The select emulator then calls this routine to clean up.
445 Since the thread signaled failure we can assume it is exiting. */
447 reap_subprocess (child_process
*cp
)
449 if (cp
->procinfo
.hProcess
)
451 /* Reap the process */
453 /* Process should have already died before we are called. */
454 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
455 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
457 CloseHandle (cp
->procinfo
.hProcess
);
458 cp
->procinfo
.hProcess
= NULL
;
459 CloseHandle (cp
->procinfo
.hThread
);
460 cp
->procinfo
.hThread
= NULL
;
463 /* For asynchronous children, the child_proc resources will be freed
464 when the last pipe read descriptor is closed; for synchronous
465 children, we must explicitly free the resources now because
466 register_child has not been called. */
471 /* Wait for any of our existing child processes to die
472 When it does, close its handle
473 Return the pid and fill in the status if non-NULL. */
476 sys_wait (int *status
)
478 DWORD active
, retval
;
481 child_process
*cp
, *cps
[MAX_CHILDREN
];
482 HANDLE wait_hnd
[MAX_CHILDREN
];
485 if (dead_child
!= NULL
)
487 /* We want to wait for a specific child */
488 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
489 cps
[nh
] = dead_child
;
490 if (!wait_hnd
[nh
]) abort ();
497 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
498 /* some child_procs might be sockets; ignore them */
499 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
500 && (cp
->fd
< 0 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0))
502 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
510 /* Nothing to wait on, so fail */
517 /* Check for quit about once a second. */
519 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
520 } while (active
== WAIT_TIMEOUT
);
522 if (active
== WAIT_FAILED
)
527 else if (active
>= WAIT_OBJECT_0
528 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
530 active
-= WAIT_OBJECT_0
;
532 else if (active
>= WAIT_ABANDONED_0
533 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
535 active
-= WAIT_ABANDONED_0
;
541 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
543 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
547 if (retval
== STILL_ACTIVE
)
549 /* Should never happen */
550 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
555 /* Massage the exit code from the process to match the format expected
556 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
557 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
559 if (retval
== STATUS_CONTROL_C_EXIT
)
567 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
574 else if (synch_process_alive
)
576 synch_process_alive
= 0;
578 /* Report the status of the synchronous process. */
579 if (WIFEXITED (retval
))
580 synch_process_retcode
= WRETCODE (retval
);
581 else if (WIFSIGNALED (retval
))
583 int code
= WTERMSIG (retval
);
586 synchronize_system_messages_locale ();
587 signame
= strsignal (code
);
592 synch_process_death
= signame
;
595 reap_subprocess (cp
);
598 reap_subprocess (cp
);
603 /* Old versions of w32api headers don't have separate 32-bit and
604 64-bit defines, but the one they have matches the 32-bit variety. */
605 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
606 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
607 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
611 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
, int * is_gui_app
)
613 file_data executable
;
616 /* Default values in case we can't tell for sure. */
618 *is_cygnus_app
= FALSE
;
621 if (!open_input_file (&executable
, filename
))
624 p
= strrchr (filename
, '.');
626 /* We can only identify DOS .com programs from the extension. */
627 if (p
&& xstrcasecmp (p
, ".com") == 0)
629 else if (p
&& (xstrcasecmp (p
, ".bat") == 0
630 || xstrcasecmp (p
, ".cmd") == 0))
632 /* A DOS shell script - it appears that CreateProcess is happy to
633 accept this (somewhat surprisingly); presumably it looks at
634 COMSPEC to determine what executable to actually invoke.
635 Therefore, we have to do the same here as well. */
636 /* Actually, I think it uses the program association for that
637 extension, which is defined in the registry. */
638 p
= egetenv ("COMSPEC");
640 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
644 /* Look for DOS .exe signature - if found, we must also check that
645 it isn't really a 16- or 32-bit Windows exe, since both formats
646 start with a DOS program stub. Note that 16-bit Windows
647 executables use the OS/2 1.x format. */
649 IMAGE_DOS_HEADER
* dos_header
;
650 IMAGE_NT_HEADERS
* nt_header
;
652 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
653 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
656 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
658 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
660 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
663 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
664 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
668 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
670 IMAGE_DATA_DIRECTORY
*data_dir
= NULL
;
671 if (nt_header
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
673 /* Ensure we are using the 32 bit structure. */
674 IMAGE_OPTIONAL_HEADER32
*opt
675 = (IMAGE_OPTIONAL_HEADER32
*) &(nt_header
->OptionalHeader
);
676 data_dir
= opt
->DataDirectory
;
677 *is_gui_app
= (opt
->Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
679 /* MingW 3.12 has the required 64 bit structs, but in case older
680 versions don't, only check 64 bit exes if we know how. */
681 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
682 else if (nt_header
->OptionalHeader
.Magic
683 == IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
685 IMAGE_OPTIONAL_HEADER64
*opt
686 = (IMAGE_OPTIONAL_HEADER64
*) &(nt_header
->OptionalHeader
);
687 data_dir
= opt
->DataDirectory
;
688 *is_gui_app
= (opt
->Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
693 /* Look for cygwin.dll in DLL import list. */
694 IMAGE_DATA_DIRECTORY import_dir
=
695 data_dir
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
696 IMAGE_IMPORT_DESCRIPTOR
* imports
;
697 IMAGE_SECTION_HEADER
* section
;
699 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
700 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
,
703 for ( ; imports
->Name
; imports
++)
705 char * dllname
= RVA_TO_PTR (imports
->Name
, section
,
708 /* The exact name of the cygwin dll has changed with
709 various releases, but hopefully this will be reasonably
711 if (strncmp (dllname
, "cygwin", 6) == 0)
713 *is_cygnus_app
= TRUE
;
722 close_file_data (&executable
);
726 compare_env (const void *strp1
, const void *strp2
)
728 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
730 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
732 /* Sort order in command.com/cmd.exe is based on uppercasing
733 names, so do the same here. */
734 if (toupper (*str1
) > toupper (*str2
))
736 else if (toupper (*str1
) < toupper (*str2
))
741 if (*str1
== '=' && *str2
== '=')
743 else if (*str1
== '=')
750 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
766 qsort (new_envp
, num
, sizeof (char *), compare_env
);
771 /* When a new child process is created we need to register it in our list,
772 so intercept spawn requests. */
774 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
776 Lisp_Object program
, full
;
777 char *cmdline
, *env
, *parg
, **targ
;
781 int is_dos_app
, is_cygnus_app
, is_gui_app
;
784 /* We pass our process ID to our children by setting up an environment
785 variable in their environment. */
786 char ppid_env_var_buffer
[64];
787 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
788 /* These are the characters that cause an argument to need quoting.
789 Arguments with whitespace characters need quoting to prevent the
790 argument being split into two or more. Arguments with wildcards
791 are also quoted, for consistency with posix platforms, where wildcards
792 are not expanded if we run the program directly without a shell.
793 Some extra whitespace characters need quoting in Cygwin programs,
794 so this list is conditionally modified below. */
795 char *sepchars
= " \t*?";
797 /* We don't care about the other modes */
798 if (mode
!= _P_NOWAIT
)
804 /* Handle executable names without an executable suffix. */
805 program
= make_string (cmdname
, strlen (cmdname
));
806 if (NILP (Ffile_executable_p (program
)))
812 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, make_number (X_OK
));
822 /* make sure argv[0] and cmdname are both in DOS format */
823 cmdname
= SDATA (program
);
824 unixtodos_filename (cmdname
);
827 /* Determine whether program is a 16-bit DOS executable, or a w32
828 executable that is implicitly linked to the Cygnus dll (implying it
829 was compiled with the Cygnus GNU toolchain and hence relies on
830 cygwin.dll to parse the command line - we use this to decide how to
831 escape quote chars in command line args that must be quoted).
833 Also determine whether it is a GUI app, so that we don't hide its
834 initial window unless specifically requested. */
835 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
837 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
838 application to start it by specifying the helper app as cmdname,
839 while leaving the real app name as argv[0]. */
842 cmdname
= alloca (MAXPATHLEN
);
843 if (egetenv ("CMDPROXY"))
844 strcpy (cmdname
, egetenv ("CMDPROXY"));
847 strcpy (cmdname
, SDATA (Vinvocation_directory
));
848 strcat (cmdname
, "cmdproxy.exe");
850 unixtodos_filename (cmdname
);
853 /* we have to do some conjuring here to put argv and envp into the
854 form CreateProcess wants... argv needs to be a space separated/null
855 terminated list of parameters, and envp is a null
856 separated/double-null terminated list of parameters.
858 Additionally, zero-length args and args containing whitespace or
859 quote chars need to be wrapped in double quotes - for this to work,
860 embedded quotes need to be escaped as well. The aim is to ensure
861 the child process reconstructs the argv array we start with
862 exactly, so we treat quotes at the beginning and end of arguments
865 The w32 GNU-based library from Cygnus doubles quotes to escape
866 them, while MSVC uses backslash for escaping. (Actually the MSVC
867 startup code does attempt to recognise doubled quotes and accept
868 them, but gets it wrong and ends up requiring three quotes to get a
869 single embedded quote!) So by default we decide whether to use
870 quote or backslash as the escape character based on whether the
871 binary is apparently a Cygnus compiled app.
873 Note that using backslash to escape embedded quotes requires
874 additional special handling if an embedded quote is already
875 preceeded by backslash, or if an arg requiring quoting ends with
876 backslash. In such cases, the run of escape characters needs to be
877 doubled. For consistency, we apply this special handling as long
878 as the escape character is not quote.
880 Since we have no idea how large argv and envp are likely to be we
881 figure out list lengths on the fly and allocate them. */
883 if (!NILP (Vw32_quote_process_args
))
886 /* Override escape char by binding w32-quote-process-args to
887 desired character, or use t for auto-selection. */
888 if (INTEGERP (Vw32_quote_process_args
))
889 escape_char
= XINT (Vw32_quote_process_args
);
891 escape_char
= is_cygnus_app
? '"' : '\\';
894 /* Cygwin apps needs quoting a bit more often */
895 if (escape_char
== '"')
896 sepchars
= "\r\n\t\f '";
905 int escape_char_run
= 0;
911 if (escape_char
== '"' && *p
== '\\')
912 /* If it's a Cygwin app, \ needs to be escaped. */
916 /* allow for embedded quotes to be escaped */
919 /* handle the case where the embedded quote is already escaped */
920 if (escape_char_run
> 0)
922 /* To preserve the arg exactly, we need to double the
923 preceding escape characters (plus adding one to
924 escape the quote character itself). */
925 arglen
+= escape_char_run
;
928 else if (strchr (sepchars
, *p
) != NULL
)
933 if (*p
== escape_char
&& escape_char
!= '"')
941 /* handle the case where the arg ends with an escape char - we
942 must not let the enclosing quote be escaped. */
943 if (escape_char_run
> 0)
944 arglen
+= escape_char_run
;
946 arglen
+= strlen (*targ
++) + 1;
948 cmdline
= alloca (arglen
);
962 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
967 int escape_char_run
= 0;
973 last
= p
+ strlen (p
) - 1;
976 /* This version does not escape quotes if they occur at the
977 beginning or end of the arg - this could lead to incorrect
978 behavior when the arg itself represents a command line
979 containing quoted args. I believe this was originally done
980 as a hack to make some things work, before
981 `w32-quote-process-args' was added. */
984 if (*p
== '"' && p
> first
&& p
< last
)
985 *parg
++ = escape_char
; /* escape embedded quotes */
993 /* double preceding escape chars if any */
994 while (escape_char_run
> 0)
996 *parg
++ = escape_char
;
999 /* escape all quote chars, even at beginning or end */
1000 *parg
++ = escape_char
;
1002 else if (escape_char
== '"' && *p
== '\\')
1006 if (*p
== escape_char
&& escape_char
!= '"')
1009 escape_char_run
= 0;
1011 /* double escape chars before enclosing quote */
1012 while (escape_char_run
> 0)
1014 *parg
++ = escape_char
;
1022 strcpy (parg
, *targ
);
1023 parg
+= strlen (*targ
);
1033 numenv
= 1; /* for end null */
1036 arglen
+= strlen (*targ
++) + 1;
1039 /* extra env vars... */
1040 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
1041 GetCurrentProcessId ());
1042 arglen
+= strlen (ppid_env_var_buffer
) + 1;
1045 /* merge env passed in and extra env into one, and sort it. */
1046 targ
= (char **) alloca (numenv
* sizeof (char *));
1047 merge_and_sort_env (envp
, extra_env
, targ
);
1049 /* concatenate env entries. */
1050 env
= alloca (arglen
);
1054 strcpy (parg
, *targ
);
1055 parg
+= strlen (*targ
++);
1068 /* Now create the process. */
1069 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1079 /* Emulate the select call
1080 Wait for available input on any of the given rfds, or timeout if
1081 a timeout is given and no input is detected
1082 wfds and efds are not supported and must be NULL.
1084 For simplicity, we detect the death of child processes here and
1085 synchronously call the SIGCHLD handler. Since it is possible for
1086 children to be created without a corresponding pipe handle from which
1087 to read output, we wait separately on the process handles as well as
1088 the char_avail events for each process pipe. We only call
1089 wait/reap_process when the process actually terminates.
1091 To reduce the number of places in which Emacs can be hung such that
1092 C-g is not able to interrupt it, we always wait on interrupt_handle
1093 (which is signaled by the input thread when C-g is detected). If we
1094 detect that we were woken up by C-g, we return -1 with errno set to
1095 EINTR as on Unix. */
1098 extern HANDLE keyboard_handle
;
1100 /* From w32xfns.c */
1101 extern HANDLE interrupt_handle
;
1103 /* From process.c */
1104 extern int proc_buffered_char
[];
1107 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1108 EMACS_TIME
*timeout
)
1111 DWORD timeout_ms
, start_time
;
1114 child_process
*cp
, *cps
[MAX_CHILDREN
];
1115 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1116 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1118 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1120 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1121 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1127 /* Otherwise, we only handle rfds, so fail otherwise. */
1128 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1138 /* Always wait on interrupt_handle, to detect C-g (quit). */
1139 wait_hnd
[0] = interrupt_handle
;
1142 /* Build a list of pipe handles to wait on. */
1144 for (i
= 0; i
< nfds
; i
++)
1145 if (FD_ISSET (i
, &orfds
))
1149 if (keyboard_handle
)
1151 /* Handle stdin specially */
1152 wait_hnd
[nh
] = keyboard_handle
;
1157 /* Check for any emacs-generated input in the queue since
1158 it won't be detected in the wait */
1159 if (detect_input_pending ())
1167 /* Child process and socket input */
1171 int current_status
= cp
->status
;
1173 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1175 /* Tell reader thread which file handle to use. */
1177 /* Wake up the reader thread for this process */
1178 cp
->status
= STATUS_READ_READY
;
1179 if (!SetEvent (cp
->char_consumed
))
1180 DebPrint (("nt_select.SetEvent failed with "
1181 "%lu for fd %ld\n", GetLastError (), i
));
1184 #ifdef CHECK_INTERLOCK
1185 /* slightly crude cross-checking of interlock between threads */
1187 current_status
= cp
->status
;
1188 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1190 /* char_avail has been signaled, so status (which may
1191 have changed) should indicate read has completed
1192 but has not been acknowledged. */
1193 current_status
= cp
->status
;
1194 if (current_status
!= STATUS_READ_SUCCEEDED
1195 && current_status
!= STATUS_READ_FAILED
)
1196 DebPrint (("char_avail set, but read not completed: status %d\n",
1201 /* char_avail has not been signaled, so status should
1202 indicate that read is in progress; small possibility
1203 that read has completed but event wasn't yet signaled
1204 when we tested it (because a context switch occurred
1205 or if running on separate CPUs). */
1206 if (current_status
!= STATUS_READ_READY
1207 && current_status
!= STATUS_READ_IN_PROGRESS
1208 && current_status
!= STATUS_READ_SUCCEEDED
1209 && current_status
!= STATUS_READ_FAILED
)
1210 DebPrint (("char_avail reset, but read status is bad: %d\n",
1214 wait_hnd
[nh
] = cp
->char_avail
;
1216 if (!wait_hnd
[nh
]) abort ();
1219 DebPrint (("select waiting on child %d fd %d\n",
1220 cp
-child_procs
, i
));
1225 /* Unable to find something to wait on for this fd, skip */
1227 /* Note that this is not a fatal error, and can in fact
1228 happen in unusual circumstances. Specifically, if
1229 sys_spawnve fails, eg. because the program doesn't
1230 exist, and debug-on-error is t so Fsignal invokes a
1231 nested input loop, then the process output pipe is
1232 still included in input_wait_mask with no child_proc
1233 associated with it. (It is removed when the debugger
1234 exits the nested input loop and the error is thrown.) */
1236 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1242 /* Add handles of child processes. */
1244 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1245 /* Some child_procs might be sockets; ignore them. Also some
1246 children may have died already, but we haven't finished reading
1247 the process output; ignore them too. */
1248 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1250 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1251 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1254 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1259 /* Nothing to look for, so we didn't find anything */
1267 start_time
= GetTickCount ();
1269 /* Wait for input or child death to be signaled. If user input is
1270 allowed, then also accept window messages. */
1271 if (FD_ISSET (0, &orfds
))
1272 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1275 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1277 if (active
== WAIT_FAILED
)
1279 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1280 nh
+ nc
, timeout_ms
, GetLastError ()));
1281 /* don't return EBADF - this causes wait_reading_process_output to
1282 abort; WAIT_FAILED is returned when single-stepping under
1283 Windows 95 after switching thread focus in debugger, and
1284 possibly at other times. */
1288 else if (active
== WAIT_TIMEOUT
)
1292 else if (active
>= WAIT_OBJECT_0
1293 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1295 active
-= WAIT_OBJECT_0
;
1297 else if (active
>= WAIT_ABANDONED_0
1298 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1300 active
-= WAIT_ABANDONED_0
;
1305 /* Loop over all handles after active (now officially documented as
1306 being the first signaled handle in the array). We do this to
1307 ensure fairness, so that all channels with data available will be
1308 processed - otherwise higher numbered channels could be starved. */
1311 if (active
== nh
+ nc
)
1313 /* There are messages in the lisp thread's queue; we must
1314 drain the queue now to ensure they are processed promptly,
1315 because if we don't do so, we will not be woken again until
1316 further messages arrive.
1318 NB. If ever we allow window message procedures to callback
1319 into lisp, we will need to ensure messages are dispatched
1320 at a safe time for lisp code to be run (*), and we may also
1321 want to provide some hooks in the dispatch loop to cater
1322 for modeless dialogs created by lisp (ie. to register
1323 window handles to pass to IsDialogMessage).
1325 (*) Note that MsgWaitForMultipleObjects above is an
1326 internal dispatch point for messages that are sent to
1327 windows created by this thread. */
1328 drain_message_queue ();
1330 else if (active
>= nh
)
1332 cp
= cps
[active
- nh
];
1334 /* We cannot always signal SIGCHLD immediately; if we have not
1335 finished reading the process output, we must delay sending
1336 SIGCHLD until we do. */
1338 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1339 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1340 /* SIG_DFL for SIGCHLD is ignore */
1341 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1342 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1345 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1349 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1353 else if (fdindex
[active
] == -1)
1355 /* Quit (C-g) was detected. */
1359 else if (fdindex
[active
] == 0)
1361 /* Keyboard input available */
1367 /* must be a socket or pipe - read ahead should have
1368 completed, either succeeding or failing. */
1369 FD_SET (fdindex
[active
], rfds
);
1373 /* Even though wait_reading_process_output only reads from at most
1374 one channel, we must process all channels here so that we reap
1375 all children that have died. */
1376 while (++active
< nh
+ nc
)
1377 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1379 } while (active
< nh
+ nc
);
1381 /* If no input has arrived and timeout hasn't expired, wait again. */
1384 DWORD elapsed
= GetTickCount () - start_time
;
1386 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1388 if (timeout_ms
!= INFINITE
)
1389 timeout_ms
-= elapsed
;
1390 goto count_children
;
1397 /* Substitute for certain kill () operations */
1399 static BOOL CALLBACK
1400 find_child_console (HWND hwnd
, LPARAM arg
)
1402 child_process
* cp
= (child_process
*) arg
;
1406 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1407 if (process_id
== cp
->procinfo
.dwProcessId
)
1409 char window_class
[32];
1411 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1412 if (strcmp (window_class
,
1413 (os_subtype
== OS_WIN95
)
1415 : "ConsoleWindowClass") == 0)
1426 sys_kill (int pid
, int sig
)
1430 int need_to_free
= 0;
1433 /* Only handle signals that will result in the process dying */
1434 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1440 cp
= find_child_pid (pid
);
1443 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1444 if (proc_hand
== NULL
)
1453 proc_hand
= cp
->procinfo
.hProcess
;
1454 pid
= cp
->procinfo
.dwProcessId
;
1456 /* Try to locate console window for process. */
1457 EnumWindows (find_child_console
, (LPARAM
) cp
);
1460 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1462 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1464 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1465 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1466 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1467 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1468 HWND foreground_window
;
1470 if (break_scan_code
== 0)
1472 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1473 vk_break_code
= 'C';
1474 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1477 foreground_window
= GetForegroundWindow ();
1478 if (foreground_window
)
1480 /* NT 5.0, and apparently also Windows 98, will not allow
1481 a Window to be set to foreground directly without the
1482 user's involvement. The workaround is to attach
1483 ourselves to the thread that owns the foreground
1484 window, since that is the only thread that can set the
1485 foreground window. */
1486 DWORD foreground_thread
, child_thread
;
1488 GetWindowThreadProcessId (foreground_window
, NULL
);
1489 if (foreground_thread
== GetCurrentThreadId ()
1490 || !AttachThreadInput (GetCurrentThreadId (),
1491 foreground_thread
, TRUE
))
1492 foreground_thread
= 0;
1494 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1495 if (child_thread
== GetCurrentThreadId ()
1496 || !AttachThreadInput (GetCurrentThreadId (),
1497 child_thread
, TRUE
))
1500 /* Set the foreground window to the child. */
1501 if (SetForegroundWindow (cp
->hwnd
))
1503 /* Generate keystrokes as if user had typed Ctrl-Break or
1505 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1506 keybd_event (vk_break_code
, break_scan_code
,
1507 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1508 keybd_event (vk_break_code
, break_scan_code
,
1509 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1510 | KEYEVENTF_KEYUP
, 0);
1511 keybd_event (VK_CONTROL
, control_scan_code
,
1512 KEYEVENTF_KEYUP
, 0);
1514 /* Sleep for a bit to give time for Emacs frame to respond
1515 to focus change events (if Emacs was active app). */
1518 SetForegroundWindow (foreground_window
);
1520 /* Detach from the foreground and child threads now that
1521 the foreground switching is over. */
1522 if (foreground_thread
)
1523 AttachThreadInput (GetCurrentThreadId (),
1524 foreground_thread
, FALSE
);
1526 AttachThreadInput (GetCurrentThreadId (),
1527 child_thread
, FALSE
);
1530 /* Ctrl-Break is NT equivalent of SIGINT. */
1531 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1533 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1534 "for pid %lu\n", GetLastError (), pid
));
1541 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1544 if (os_subtype
== OS_WIN95
)
1547 Another possibility is to try terminating the VDM out-right by
1548 calling the Shell VxD (id 0x17) V86 interface, function #4
1549 "SHELL_Destroy_VM", ie.
1555 First need to determine the current VM handle, and then arrange for
1556 the shellapi call to be made from the system vm (by using
1557 Switch_VM_and_callback).
1559 Could try to invoke DestroyVM through CallVxD.
1563 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1564 to hang when cmdproxy is used in conjunction with
1565 command.com for an interactive shell. Posting
1566 WM_CLOSE pops up a dialog that, when Yes is selected,
1567 does the same thing. TerminateProcess is also less
1568 than ideal in that subprocesses tend to stick around
1569 until the machine is shutdown, but at least it
1570 doesn't freeze the 16-bit subsystem. */
1571 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1573 if (!TerminateProcess (proc_hand
, 0xff))
1575 DebPrint (("sys_kill.TerminateProcess returned %d "
1576 "for pid %lu\n", GetLastError (), pid
));
1583 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1585 /* Kill the process. On W32 this doesn't kill child processes
1586 so it doesn't work very well for shells which is why it's not
1587 used in every case. */
1588 else if (!TerminateProcess (proc_hand
, 0xff))
1590 DebPrint (("sys_kill.TerminateProcess returned %d "
1591 "for pid %lu\n", GetLastError (), pid
));
1598 CloseHandle (proc_hand
);
1603 /* extern int report_file_error (char *, Lisp_Object); */
1605 /* The following two routines are used to manipulate stdin, stdout, and
1606 stderr of our child processes.
1608 Assuming that in, out, and err are *not* inheritable, we make them
1609 stdin, stdout, and stderr of the child as follows:
1611 - Save the parent's current standard handles.
1612 - Set the std handles to inheritable duplicates of the ones being passed in.
1613 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1614 NT file handle for a crt file descriptor.)
1615 - Spawn the child, which inherits in, out, and err as stdin,
1616 stdout, and stderr. (see Spawnve)
1617 - Close the std handles passed to the child.
1618 - Reset the parent's standard handles to the saved handles.
1619 (see reset_standard_handles)
1620 We assume that the caller closes in, out, and err after calling us. */
1623 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1626 HANDLE newstdin
, newstdout
, newstderr
;
1628 parent
= GetCurrentProcess ();
1630 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1631 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1632 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1634 /* make inheritable copies of the new handles */
1635 if (!DuplicateHandle (parent
,
1636 (HANDLE
) _get_osfhandle (in
),
1641 DUPLICATE_SAME_ACCESS
))
1642 report_file_error ("Duplicating input handle for child", Qnil
);
1644 if (!DuplicateHandle (parent
,
1645 (HANDLE
) _get_osfhandle (out
),
1650 DUPLICATE_SAME_ACCESS
))
1651 report_file_error ("Duplicating output handle for child", Qnil
);
1653 if (!DuplicateHandle (parent
,
1654 (HANDLE
) _get_osfhandle (err
),
1659 DUPLICATE_SAME_ACCESS
))
1660 report_file_error ("Duplicating error handle for child", Qnil
);
1662 /* and store them as our std handles */
1663 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1664 report_file_error ("Changing stdin handle", Qnil
);
1666 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1667 report_file_error ("Changing stdout handle", Qnil
);
1669 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1670 report_file_error ("Changing stderr handle", Qnil
);
1674 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1676 /* close the duplicated handles passed to the child */
1677 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1678 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1679 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1681 /* now restore parent's saved std handles */
1682 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1683 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1684 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1688 set_process_dir (char * dir
)
1695 /* To avoid problems with winsock implementations that work over dial-up
1696 connections causing or requiring a connection to exist while Emacs is
1697 running, Emacs no longer automatically loads winsock on startup if it
1698 is present. Instead, it will be loaded when open-network-stream is
1701 To allow full control over when winsock is loaded, we provide these
1702 two functions to dynamically load and unload winsock. This allows
1703 dial-up users to only be connected when they actually need to use
1707 extern HANDLE winsock_lib
;
1708 extern BOOL
term_winsock (void);
1709 extern BOOL
init_winsock (int load_now
);
1711 extern Lisp_Object Vsystem_name
;
1713 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1714 doc
: /* Test for presence of the Windows socket library `winsock'.
1715 Returns non-nil if winsock support is present, nil otherwise.
1717 If the optional argument LOAD-NOW is non-nil, the winsock library is
1718 also loaded immediately if not already loaded. If winsock is loaded,
1719 the winsock local hostname is returned (since this may be different from
1720 the value of `system-name' and should supplant it), otherwise t is
1721 returned to indicate winsock support is present. */)
1723 Lisp_Object load_now
;
1727 have_winsock
= init_winsock (!NILP (load_now
));
1730 if (winsock_lib
!= NULL
)
1732 /* Return new value for system-name. The best way to do this
1733 is to call init_system_name, saving and restoring the
1734 original value to avoid side-effects. */
1735 Lisp_Object orig_hostname
= Vsystem_name
;
1736 Lisp_Object hostname
;
1738 init_system_name ();
1739 hostname
= Vsystem_name
;
1740 Vsystem_name
= orig_hostname
;
1748 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1750 doc
: /* Unload the Windows socket library `winsock' if loaded.
1751 This is provided to allow dial-up socket connections to be disconnected
1752 when no longer needed. Returns nil without unloading winsock if any
1753 socket connections still exist. */)
1756 return term_winsock () ? Qt
: Qnil
;
1759 #endif /* HAVE_SOCKETS */
1762 /* Some miscellaneous functions that are Windows specific, but not GUI
1763 specific (ie. are applicable in terminal or batch mode as well). */
1765 /* lifted from fileio.c */
1766 #define CORRECT_DIR_SEPS(s) \
1767 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1768 else unixtodos_filename (s); \
1771 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1772 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1773 If FILENAME does not exist, return nil.
1774 All path elements in FILENAME are converted to their short names. */)
1776 Lisp_Object filename
;
1778 char shortname
[MAX_PATH
];
1780 CHECK_STRING (filename
);
1782 /* first expand it. */
1783 filename
= Fexpand_file_name (filename
, Qnil
);
1785 /* luckily, this returns the short version of each element in the path. */
1786 if (GetShortPathName (SDATA (ENCODE_FILE (filename
)), shortname
, MAX_PATH
) == 0)
1789 CORRECT_DIR_SEPS (shortname
);
1791 return build_string (shortname
);
1795 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1797 doc
: /* Return the long file name version of the full path of FILENAME.
1798 If FILENAME does not exist, return nil.
1799 All path elements in FILENAME are converted to their long names. */)
1801 Lisp_Object filename
;
1803 char longname
[ MAX_PATH
];
1806 CHECK_STRING (filename
);
1808 if (SBYTES (filename
) == 2
1809 && *(SDATA (filename
) + 1) == ':')
1812 /* first expand it. */
1813 filename
= Fexpand_file_name (filename
, Qnil
);
1815 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename
)), longname
, MAX_PATH
))
1818 CORRECT_DIR_SEPS (longname
);
1820 /* If we were passed only a drive, make sure that a slash is not appended
1821 for consistency with directories. Allow for drive mapping via SUBST
1822 in case expand-file-name is ever changed to expand those. */
1823 if (drive_only
&& longname
[1] == ':' && longname
[2] == '/' && !longname
[3])
1826 return DECODE_FILE (build_string (longname
));
1829 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1830 Sw32_set_process_priority
, 2, 2, 0,
1831 doc
: /* Set the priority of PROCESS to PRIORITY.
1832 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1833 priority of the process whose pid is PROCESS is changed.
1834 PRIORITY should be one of the symbols high, normal, or low;
1835 any other symbol will be interpreted as normal.
1837 If successful, the return value is t, otherwise nil. */)
1839 Lisp_Object process
, priority
;
1841 HANDLE proc_handle
= GetCurrentProcess ();
1842 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1843 Lisp_Object result
= Qnil
;
1845 CHECK_SYMBOL (priority
);
1847 if (!NILP (process
))
1852 CHECK_NUMBER (process
);
1854 /* Allow pid to be an internally generated one, or one obtained
1855 externally. This is necessary because real pids on Win95 are
1858 pid
= XINT (process
);
1859 cp
= find_child_pid (pid
);
1861 pid
= cp
->procinfo
.dwProcessId
;
1863 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1866 if (EQ (priority
, Qhigh
))
1867 priority_class
= HIGH_PRIORITY_CLASS
;
1868 else if (EQ (priority
, Qlow
))
1869 priority_class
= IDLE_PRIORITY_CLASS
;
1871 if (proc_handle
!= NULL
)
1873 if (SetPriorityClass (proc_handle
, priority_class
))
1875 if (!NILP (process
))
1876 CloseHandle (proc_handle
);
1882 #ifdef HAVE_LANGINFO_CODESET
1883 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1884 char *nl_langinfo (nl_item item
)
1886 /* Conversion of Posix item numbers to their Windows equivalents. */
1887 static const LCTYPE w32item
[] = {
1888 LOCALE_IDEFAULTANSICODEPAGE
,
1889 LOCALE_SDAYNAME1
, LOCALE_SDAYNAME2
, LOCALE_SDAYNAME3
,
1890 LOCALE_SDAYNAME4
, LOCALE_SDAYNAME5
, LOCALE_SDAYNAME6
, LOCALE_SDAYNAME7
,
1891 LOCALE_SMONTHNAME1
, LOCALE_SMONTHNAME2
, LOCALE_SMONTHNAME3
,
1892 LOCALE_SMONTHNAME4
, LOCALE_SMONTHNAME5
, LOCALE_SMONTHNAME6
,
1893 LOCALE_SMONTHNAME7
, LOCALE_SMONTHNAME8
, LOCALE_SMONTHNAME9
,
1894 LOCALE_SMONTHNAME10
, LOCALE_SMONTHNAME11
, LOCALE_SMONTHNAME12
1897 static char *nl_langinfo_buf
= NULL
;
1898 static int nl_langinfo_len
= 0;
1900 if (nl_langinfo_len
<= 0)
1901 nl_langinfo_buf
= xmalloc (nl_langinfo_len
= 1);
1903 if (item
< 0 || item
>= _NL_NUM
)
1904 nl_langinfo_buf
[0] = 0;
1907 LCID cloc
= GetThreadLocale ();
1908 int need_len
= GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1912 nl_langinfo_buf
[0] = 0;
1915 if (item
== CODESET
)
1917 need_len
+= 2; /* for the "cp" prefix */
1918 if (need_len
< 8) /* for the case we call GetACP */
1921 if (nl_langinfo_len
<= need_len
)
1922 nl_langinfo_buf
= xrealloc (nl_langinfo_buf
,
1923 nl_langinfo_len
= need_len
);
1924 if (!GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1925 nl_langinfo_buf
, nl_langinfo_len
))
1926 nl_langinfo_buf
[0] = 0;
1927 else if (item
== CODESET
)
1929 if (strcmp (nl_langinfo_buf
, "0") == 0 /* CP_ACP */
1930 || strcmp (nl_langinfo_buf
, "1") == 0) /* CP_OEMCP */
1931 sprintf (nl_langinfo_buf
, "cp%u", GetACP ());
1934 memmove (nl_langinfo_buf
+ 2, nl_langinfo_buf
,
1935 strlen (nl_langinfo_buf
) + 1);
1936 nl_langinfo_buf
[0] = 'c';
1937 nl_langinfo_buf
[1] = 'p';
1942 return nl_langinfo_buf
;
1944 #endif /* HAVE_LANGINFO_CODESET */
1946 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1947 Sw32_get_locale_info
, 1, 2, 0,
1948 doc
: /* Return information about the Windows locale LCID.
1949 By default, return a three letter locale code which encodes the default
1950 language as the first two characters, and the country or regional variant
1951 as the third letter. For example, ENU refers to `English (United States)',
1952 while ENC means `English (Canadian)'.
1954 If the optional argument LONGFORM is t, the long form of the locale
1955 name is returned, e.g. `English (United States)' instead; if LONGFORM
1956 is a number, it is interpreted as an LCTYPE constant and the corresponding
1957 locale information is returned.
1959 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1961 Lisp_Object lcid
, longform
;
1965 char abbrev_name
[32] = { 0 };
1966 char full_name
[256] = { 0 };
1968 CHECK_NUMBER (lcid
);
1970 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1973 if (NILP (longform
))
1975 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1976 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1977 abbrev_name
, sizeof (abbrev_name
));
1979 return build_string (abbrev_name
);
1981 else if (EQ (longform
, Qt
))
1983 got_full
= GetLocaleInfo (XINT (lcid
),
1984 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1985 full_name
, sizeof (full_name
));
1987 return DECODE_SYSTEM (build_string (full_name
));
1989 else if (NUMBERP (longform
))
1991 got_full
= GetLocaleInfo (XINT (lcid
),
1993 full_name
, sizeof (full_name
));
1995 return make_unibyte_string (full_name
, got_full
);
2002 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
2003 Sw32_get_current_locale_id
, 0, 0, 0,
2004 doc
: /* Return Windows locale id for current locale setting.
2005 This is a numerical value; use `w32-get-locale-info' to convert to a
2006 human-readable form. */)
2009 return make_number (GetThreadLocale ());
2012 DWORD
int_from_hex (char * s
)
2015 static char hex
[] = "0123456789abcdefABCDEF";
2018 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
2020 unsigned digit
= p
- hex
;
2023 val
= val
* 16 + digit
;
2029 /* We need to build a global list, since the EnumSystemLocale callback
2030 function isn't given a context pointer. */
2031 Lisp_Object Vw32_valid_locale_ids
;
2033 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
2035 DWORD id
= int_from_hex (localeNum
);
2036 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
2040 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
2041 Sw32_get_valid_locale_ids
, 0, 0, 0,
2042 doc
: /* Return list of all valid Windows locale ids.
2043 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2044 human-readable form. */)
2047 Vw32_valid_locale_ids
= Qnil
;
2049 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
2051 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
2052 return Vw32_valid_locale_ids
;
2056 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
2057 doc
: /* Return Windows locale id for default locale setting.
2058 By default, the system default locale setting is returned; if the optional
2059 parameter USERP is non-nil, the user default locale setting is returned.
2060 This is a numerical value; use `w32-get-locale-info' to convert to a
2061 human-readable form. */)
2066 return make_number (GetSystemDefaultLCID ());
2067 return make_number (GetUserDefaultLCID ());
2071 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
2072 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
2073 If successful, the new locale id is returned, otherwise nil. */)
2077 CHECK_NUMBER (lcid
);
2079 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
2082 if (!SetThreadLocale (XINT (lcid
)))
2085 /* Need to set input thread locale if present. */
2086 if (dwWindowsThreadId
)
2087 /* Reply is not needed. */
2088 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
2090 return make_number (GetThreadLocale ());
2094 /* We need to build a global list, since the EnumCodePages callback
2095 function isn't given a context pointer. */
2096 Lisp_Object Vw32_valid_codepages
;
2098 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
2100 DWORD id
= atoi (codepageNum
);
2101 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
2105 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
2106 Sw32_get_valid_codepages
, 0, 0, 0,
2107 doc
: /* Return list of all valid Windows codepages. */)
2110 Vw32_valid_codepages
= Qnil
;
2112 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
2114 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
2115 return Vw32_valid_codepages
;
2119 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
2120 Sw32_get_console_codepage
, 0, 0, 0,
2121 doc
: /* Return current Windows codepage for console input. */)
2124 return make_number (GetConsoleCP ());
2128 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
2129 Sw32_set_console_codepage
, 1, 1, 0,
2130 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2131 The codepage setting affects keyboard input and display in tty mode.
2132 If successful, the new CP is returned, otherwise nil. */)
2138 if (!IsValidCodePage (XINT (cp
)))
2141 if (!SetConsoleCP (XINT (cp
)))
2144 return make_number (GetConsoleCP ());
2148 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2149 Sw32_get_console_output_codepage
, 0, 0, 0,
2150 doc
: /* Return current Windows codepage for console output. */)
2153 return make_number (GetConsoleOutputCP ());
2157 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2158 Sw32_set_console_output_codepage
, 1, 1, 0,
2159 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2160 The codepage setting affects keyboard input and display in tty mode.
2161 If successful, the new CP is returned, otherwise nil. */)
2167 if (!IsValidCodePage (XINT (cp
)))
2170 if (!SetConsoleOutputCP (XINT (cp
)))
2173 return make_number (GetConsoleOutputCP ());
2177 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2178 Sw32_get_codepage_charset
, 1, 1, 0,
2179 doc
: /* Return charset of codepage CP.
2180 Returns nil if the codepage is not valid. */)
2188 if (!IsValidCodePage (XINT (cp
)))
2191 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2192 return make_number (info
.ciCharset
);
2198 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2199 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2200 doc
: /* Return list of Windows keyboard languages and layouts.
2201 The return value is a list of pairs of language id and layout id. */)
2204 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2205 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2206 Lisp_Object obj
= Qnil
;
2208 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2210 while (--num_layouts
>= 0)
2212 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2214 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2215 make_number ((kl
>> 16) & 0xffff)),
2224 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2225 Sw32_get_keyboard_layout
, 0, 0, 0,
2226 doc
: /* Return current Windows keyboard language and layout.
2227 The return value is the cons of the language id and the layout id. */)
2230 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2232 return Fcons (make_number (kl
& 0xffff),
2233 make_number ((kl
>> 16) & 0xffff));
2237 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2238 Sw32_set_keyboard_layout
, 1, 1, 0,
2239 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2240 The keyboard layout setting affects interpretation of keyboard input.
2241 If successful, the new layout id is returned, otherwise nil. */)
2247 CHECK_CONS (layout
);
2248 CHECK_NUMBER_CAR (layout
);
2249 CHECK_NUMBER_CDR (layout
);
2251 kl
= (XINT (XCAR (layout
)) & 0xffff)
2252 | (XINT (XCDR (layout
)) << 16);
2254 /* Synchronize layout with input thread. */
2255 if (dwWindowsThreadId
)
2257 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2261 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2263 if (msg
.wParam
== 0)
2267 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2270 return Fw32_get_keyboard_layout ();
2276 DEFSYM (Qhigh
, "high");
2277 DEFSYM (Qlow
, "low");
2280 defsubr (&Sw32_has_winsock
);
2281 defsubr (&Sw32_unload_winsock
);
2283 defsubr (&Sw32_short_file_name
);
2284 defsubr (&Sw32_long_file_name
);
2285 defsubr (&Sw32_set_process_priority
);
2286 defsubr (&Sw32_get_locale_info
);
2287 defsubr (&Sw32_get_current_locale_id
);
2288 defsubr (&Sw32_get_default_locale_id
);
2289 defsubr (&Sw32_get_valid_locale_ids
);
2290 defsubr (&Sw32_set_current_locale
);
2292 defsubr (&Sw32_get_console_codepage
);
2293 defsubr (&Sw32_set_console_codepage
);
2294 defsubr (&Sw32_get_console_output_codepage
);
2295 defsubr (&Sw32_set_console_output_codepage
);
2296 defsubr (&Sw32_get_valid_codepages
);
2297 defsubr (&Sw32_get_codepage_charset
);
2299 defsubr (&Sw32_get_valid_keyboard_layouts
);
2300 defsubr (&Sw32_get_keyboard_layout
);
2301 defsubr (&Sw32_set_keyboard_layout
);
2303 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2304 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2305 Because Windows does not directly pass argv arrays to child processes,
2306 programs have to reconstruct the argv array by parsing the command
2307 line string. For an argument to contain a space, it must be enclosed
2308 in double quotes or it will be parsed as multiple arguments.
2310 If the value is a character, that character will be used to escape any
2311 quote characters that appear, otherwise a suitable escape character
2312 will be chosen based on the type of the program. */);
2313 Vw32_quote_process_args
= Qt
;
2315 DEFVAR_LISP ("w32-start-process-show-window",
2316 &Vw32_start_process_show_window
,
2317 doc
: /* When nil, new child processes hide their windows.
2318 When non-nil, they show their window in the method of their choice.
2319 This variable doesn't affect GUI applications, which will never be hidden. */);
2320 Vw32_start_process_show_window
= Qnil
;
2322 DEFVAR_LISP ("w32-start-process-share-console",
2323 &Vw32_start_process_share_console
,
2324 doc
: /* When nil, new child processes are given a new console.
2325 When non-nil, they share the Emacs console; this has the limitation of
2326 allowing only one DOS subprocess to run at a time (whether started directly
2327 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2328 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2329 otherwise respond to interrupts from Emacs. */);
2330 Vw32_start_process_share_console
= Qnil
;
2332 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2333 &Vw32_start_process_inherit_error_mode
,
2334 doc
: /* When nil, new child processes revert to the default error mode.
2335 When non-nil, they inherit their error mode setting from Emacs, which stops
2336 them blocking when trying to access unmounted drives etc. */);
2337 Vw32_start_process_inherit_error_mode
= Qt
;
2339 DEFVAR_INT ("w32-pipe-read-delay", &w32_pipe_read_delay
,
2340 doc
: /* Forced delay before reading subprocess output.
2341 This is done to improve the buffering of subprocess output, by
2342 avoiding the inefficiency of frequently reading small amounts of data.
2344 If positive, the value is the number of milliseconds to sleep before
2345 reading the subprocess output. If negative, the magnitude is the number
2346 of time slices to wait (effectively boosting the priority of the child
2347 process temporarily). A value of zero disables waiting entirely. */);
2348 w32_pipe_read_delay
= 50;
2350 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2351 doc
: /* Non-nil means convert all-upper case file names to lower case.
2352 This applies when performing completions and file name expansion.
2353 Note that the value of this setting also affects remote file names,
2354 so you probably don't want to set to non-nil if you use case-sensitive
2355 filesystems via ange-ftp. */);
2356 Vw32_downcase_file_names
= Qnil
;
2359 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2360 doc
: /* Non-nil means attempt to fake realistic inode values.
2361 This works by hashing the truename of files, and should detect
2362 aliasing between long and short (8.3 DOS) names, but can have
2363 false positives because of hash collisions. Note that determing
2364 the truename of a file can be slow. */);
2365 Vw32_generate_fake_inodes
= Qnil
;
2368 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2369 doc
: /* Non-nil means determine accurate file attributes in `file-attributes'.
2370 This option controls whether to issue additional system calls to determine
2371 accurate link counts, file type, and ownership information. It is more
2372 useful for files on NTFS volumes, where hard links and file security are
2373 supported, than on volumes of the FAT family.
2375 Without these system calls, link count will always be reported as 1 and file
2376 ownership will be attributed to the current user.
2377 The default value `local' means only issue these system calls for files
2378 on local fixed drives. A value of nil means never issue them.
2379 Any other non-nil value means do this even on remote and removable drives
2380 where the performance impact may be noticeable even on modern hardware. */);
2381 Vw32_get_true_file_attributes
= Qlocal
;
2383 staticpro (&Vw32_valid_locale_ids
);
2384 staticpro (&Vw32_valid_codepages
);
2386 /* end of ntproc.c */
2388 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2389 (do not change this comment) */