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, 2007 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, 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
);
52 #ifdef HAVE_LANGINFO_CODESET
58 #include "character.h"
64 #include "syssignal.h"
67 #define RVA_TO_PTR(var,section,filedata) \
68 ((void *)((section)->PointerToRawData \
69 + ((DWORD)(var) - (section)->VirtualAddress) \
70 + (filedata).file_base))
72 /* Control whether spawnve quotes arguments as necessary to ensure
73 correct parsing by child process. Because not all uses of spawnve
74 are careful about constructing argv arrays, we make this behaviour
75 conditional (off by default). */
76 Lisp_Object Vw32_quote_process_args
;
78 /* Control whether create_child causes the process' window to be
79 hidden. The default is nil. */
80 Lisp_Object Vw32_start_process_show_window
;
82 /* Control whether create_child causes the process to inherit Emacs'
83 console window, or be given a new one of its own. The default is
84 nil, to allow multiple DOS programs to run on Win95. Having separate
85 consoles also allows Emacs to cleanly terminate process groups. */
86 Lisp_Object Vw32_start_process_share_console
;
88 /* Control whether create_child cause the process to inherit Emacs'
89 error mode setting. The default is t, to minimize the possibility of
90 subprocesses blocking when accessing unmounted drives. */
91 Lisp_Object Vw32_start_process_inherit_error_mode
;
93 /* Time to sleep before reading from a subprocess output pipe - this
94 avoids the inefficiency of frequently reading small amounts of data.
95 This is primarily necessary for handling DOS processes on Windows 95,
96 but is useful for W32 processes on both Windows 95 and NT as well. */
97 int w32_pipe_read_delay
;
99 /* Control conversion of upper case file names to lower case.
100 nil means no, t means yes. */
101 Lisp_Object Vw32_downcase_file_names
;
103 /* Control whether stat() attempts to generate fake but hopefully
104 "accurate" inode values, by hashing the absolute truenames of files.
105 This should detect aliasing between long and short names, but still
106 allows the possibility of hash collisions. */
107 Lisp_Object Vw32_generate_fake_inodes
;
109 /* Control whether stat() attempts to determine file type and link count
110 exactly, at the expense of slower operation. Since true hard links
111 are supported on NTFS volumes, this is only relevant on NT. */
112 Lisp_Object Vw32_get_true_file_attributes
;
114 Lisp_Object Qhigh
, Qlow
;
117 void _DebPrint (const char *fmt
, ...)
122 va_start (args
, fmt
);
123 vsprintf (buf
, fmt
, args
);
125 OutputDebugString (buf
);
129 typedef void (_CALLBACK_
*signal_handler
)(int);
131 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
132 static signal_handler sig_handlers
[NSIG
];
134 /* Fake signal implementation to record the SIGCHLD handler. */
136 sys_signal (int sig
, signal_handler handler
)
145 old
= sig_handlers
[sig
];
146 sig_handlers
[sig
] = handler
;
150 /* Defined in <process.h> which conflicts with the local copy */
153 /* Child process management list. */
154 int child_proc_count
= 0;
155 child_process child_procs
[ MAX_CHILDREN
];
156 child_process
*dead_child
= NULL
;
158 DWORD WINAPI
reader_thread (void *arg
);
160 /* Find an unused process slot. */
167 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
168 if (!CHILD_ACTIVE (cp
))
170 if (child_proc_count
== MAX_CHILDREN
)
172 cp
= &child_procs
[child_proc_count
++];
175 memset (cp
, 0, sizeof(*cp
));
178 cp
->procinfo
.hProcess
= NULL
;
179 cp
->status
= STATUS_READ_ERROR
;
181 /* use manual reset event so that select() will function properly */
182 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
185 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
186 if (cp
->char_consumed
)
188 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
198 delete_child (child_process
*cp
)
202 /* Should not be deleting a child that is still needed. */
203 for (i
= 0; i
< MAXDESC
; i
++)
204 if (fd_info
[i
].cp
== cp
)
207 if (!CHILD_ACTIVE (cp
))
210 /* reap thread if necessary */
215 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
217 /* let the thread exit cleanly if possible */
218 cp
->status
= STATUS_READ_ERROR
;
219 SetEvent (cp
->char_consumed
);
221 /* We used to forceably terminate the thread here, but it
222 is normally unnecessary, and in abnormal cases, the worst that
223 will happen is we have an extra idle thread hanging around
224 waiting for the zombie process. */
225 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
227 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
228 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
229 TerminateThread (cp
->thrd
, 0);
233 CloseHandle (cp
->thrd
);
238 CloseHandle (cp
->char_avail
);
239 cp
->char_avail
= NULL
;
241 if (cp
->char_consumed
)
243 CloseHandle (cp
->char_consumed
);
244 cp
->char_consumed
= NULL
;
247 /* update child_proc_count (highest numbered slot in use plus one) */
248 if (cp
== child_procs
+ child_proc_count
- 1)
250 for (i
= child_proc_count
-1; i
>= 0; i
--)
251 if (CHILD_ACTIVE (&child_procs
[i
]))
253 child_proc_count
= i
+ 1;
258 child_proc_count
= 0;
261 /* Find a child by pid. */
262 static child_process
*
263 find_child_pid (DWORD pid
)
267 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
268 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
274 /* Thread proc for child process and socket reader threads. Each thread
275 is normally blocked until woken by select() to check for input by
276 reading one char. When the read completes, char_avail is signalled
277 to wake up the select emulator and the thread blocks itself again. */
279 reader_thread (void *arg
)
284 cp
= (child_process
*)arg
;
286 /* We have to wait for the go-ahead before we can start */
288 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
295 if (fd_info
[cp
->fd
].flags
& FILE_LISTEN
)
296 rc
= _sys_wait_accept (cp
->fd
);
298 rc
= _sys_read_ahead (cp
->fd
);
300 /* The name char_avail is a misnomer - it really just means the
301 read-ahead has completed, whether successfully or not. */
302 if (!SetEvent (cp
->char_avail
))
304 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
305 GetLastError (), cp
->fd
));
309 if (rc
== STATUS_READ_ERROR
)
312 /* If the read died, the child has died so let the thread die */
313 if (rc
== STATUS_READ_FAILED
)
316 /* Wait until our input is acknowledged before reading again */
317 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
319 DebPrint (("reader_thread.WaitForSingleObject failed with "
320 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
327 /* To avoid Emacs changing directory, we just record here the directory
328 the new process should start in. This is set just before calling
329 sys_spawnve, and is not generally valid at any other time. */
330 static char * process_dir
;
333 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
334 int * pPid
, child_process
*cp
)
337 SECURITY_ATTRIBUTES sec_attrs
;
339 SECURITY_DESCRIPTOR sec_desc
;
342 char dir
[ MAXPATHLEN
];
344 if (cp
== NULL
) abort ();
346 memset (&start
, 0, sizeof (start
));
347 start
.cb
= sizeof (start
);
350 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
351 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
353 start
.dwFlags
= STARTF_USESTDHANDLES
;
354 start
.wShowWindow
= SW_HIDE
;
356 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
357 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
358 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
359 #endif /* HAVE_NTGUI */
362 /* Explicitly specify no security */
363 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
365 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
368 sec_attrs
.nLength
= sizeof (sec_attrs
);
369 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
370 sec_attrs
.bInheritHandle
= FALSE
;
372 strcpy (dir
, process_dir
);
373 unixtodos_filename (dir
);
375 flags
= (!NILP (Vw32_start_process_share_console
)
376 ? CREATE_NEW_PROCESS_GROUP
377 : CREATE_NEW_CONSOLE
);
378 if (NILP (Vw32_start_process_inherit_error_mode
))
379 flags
|= CREATE_DEFAULT_ERROR_MODE
;
380 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
381 flags
, env
, dir
, &start
, &cp
->procinfo
))
384 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
386 /* Hack for Windows 95, which assigns large (ie negative) pids */
390 /* pid must fit in a Lisp_Int */
391 cp
->pid
= cp
->pid
& INTMASK
;
398 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
402 /* create_child doesn't know what emacs' file handle will be for waiting
403 on output from the child, so we need to make this additional call
404 to register the handle with the process
405 This way the select emulator knows how to match file handles with
406 entries in child_procs. */
408 register_child (int pid
, int fd
)
412 cp
= find_child_pid (pid
);
415 DebPrint (("register_child unable to find pid %lu\n", pid
));
420 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
425 /* thread is initially blocked until select is called; set status so
426 that select will release thread */
427 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
429 /* attach child_process to fd_info */
430 if (fd_info
[fd
].cp
!= NULL
)
432 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
439 /* When a process dies its pipe will break so the reader thread will
440 signal failure to the select emulator.
441 The select emulator then calls this routine to clean up.
442 Since the thread signaled failure we can assume it is exiting. */
444 reap_subprocess (child_process
*cp
)
446 if (cp
->procinfo
.hProcess
)
448 /* Reap the process */
450 /* Process should have already died before we are called. */
451 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
452 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
454 CloseHandle (cp
->procinfo
.hProcess
);
455 cp
->procinfo
.hProcess
= NULL
;
456 CloseHandle (cp
->procinfo
.hThread
);
457 cp
->procinfo
.hThread
= NULL
;
460 /* For asynchronous children, the child_proc resources will be freed
461 when the last pipe read descriptor is closed; for synchronous
462 children, we must explicitly free the resources now because
463 register_child has not been called. */
468 /* Wait for any of our existing child processes to die
469 When it does, close its handle
470 Return the pid and fill in the status if non-NULL. */
473 sys_wait (int *status
)
475 DWORD active
, retval
;
478 child_process
*cp
, *cps
[MAX_CHILDREN
];
479 HANDLE wait_hnd
[MAX_CHILDREN
];
482 if (dead_child
!= NULL
)
484 /* We want to wait for a specific child */
485 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
486 cps
[nh
] = dead_child
;
487 if (!wait_hnd
[nh
]) abort ();
494 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
495 /* some child_procs might be sockets; ignore them */
496 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
497 && (cp
->fd
< 0 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0))
499 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
507 /* Nothing to wait on, so fail */
514 /* Check for quit about once a second. */
516 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
517 } while (active
== WAIT_TIMEOUT
);
519 if (active
== WAIT_FAILED
)
524 else if (active
>= WAIT_OBJECT_0
525 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
527 active
-= WAIT_OBJECT_0
;
529 else if (active
>= WAIT_ABANDONED_0
530 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
532 active
-= WAIT_ABANDONED_0
;
538 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
540 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
544 if (retval
== STILL_ACTIVE
)
546 /* Should never happen */
547 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
552 /* Massage the exit code from the process to match the format expected
553 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
554 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
556 if (retval
== STATUS_CONTROL_C_EXIT
)
564 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
571 else if (synch_process_alive
)
573 synch_process_alive
= 0;
575 /* Report the status of the synchronous process. */
576 if (WIFEXITED (retval
))
577 synch_process_retcode
= WRETCODE (retval
);
578 else if (WIFSIGNALED (retval
))
580 int code
= WTERMSIG (retval
);
583 synchronize_system_messages_locale ();
584 signame
= strsignal (code
);
589 synch_process_death
= signame
;
592 reap_subprocess (cp
);
595 reap_subprocess (cp
);
600 /* Old versions of w32api headers don't have separate 32-bit and
601 64-bit defines, but the one they have matches the 32-bit variety. */
602 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
603 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
604 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
608 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
, int * is_gui_app
)
610 file_data executable
;
613 /* Default values in case we can't tell for sure. */
615 *is_cygnus_app
= FALSE
;
618 if (!open_input_file (&executable
, filename
))
621 p
= strrchr (filename
, '.');
623 /* We can only identify DOS .com programs from the extension. */
624 if (p
&& stricmp (p
, ".com") == 0)
626 else if (p
&& (stricmp (p
, ".bat") == 0
627 || stricmp (p
, ".cmd") == 0))
629 /* A DOS shell script - it appears that CreateProcess is happy to
630 accept this (somewhat surprisingly); presumably it looks at
631 COMSPEC to determine what executable to actually invoke.
632 Therefore, we have to do the same here as well. */
633 /* Actually, I think it uses the program association for that
634 extension, which is defined in the registry. */
635 p
= egetenv ("COMSPEC");
637 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
641 /* Look for DOS .exe signature - if found, we must also check that
642 it isn't really a 16- or 32-bit Windows exe, since both formats
643 start with a DOS program stub. Note that 16-bit Windows
644 executables use the OS/2 1.x format. */
646 IMAGE_DOS_HEADER
* dos_header
;
647 IMAGE_NT_HEADERS
* nt_header
;
649 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
650 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
653 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
655 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
657 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
660 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
661 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
665 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
667 IMAGE_DATA_DIRECTORY
*data_dir
= NULL
;
668 if (nt_header
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
670 /* Ensure we are using the 32 bit structure. */
671 IMAGE_OPTIONAL_HEADER32
*opt
672 = (IMAGE_OPTIONAL_HEADER32
*) &(nt_header
->OptionalHeader
);
673 data_dir
= opt
->DataDirectory
;
674 *is_gui_app
= (opt
->Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
676 /* MingW 3.12 has the required 64 bit structs, but in case older
677 versions don't, only check 64 bit exes if we know how. */
678 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
679 else if (nt_header
->OptionalHeader
.Magic
680 == IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
682 IMAGE_OPTIONAL_HEADER64
*opt
683 = (IMAGE_OPTIONAL_HEADER64
*) &(nt_header
->OptionalHeader
);
684 data_dir
= opt
->DataDirectory
;
685 *is_gui_app
= (opt
->Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
690 /* Look for cygwin.dll in DLL import list. */
691 IMAGE_DATA_DIRECTORY import_dir
=
692 data_dir
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
693 IMAGE_IMPORT_DESCRIPTOR
* imports
;
694 IMAGE_SECTION_HEADER
* section
;
696 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
697 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
,
700 for ( ; imports
->Name
; imports
++)
702 char * dllname
= RVA_TO_PTR (imports
->Name
, section
,
705 /* The exact name of the cygwin dll has changed with
706 various releases, but hopefully this will be reasonably
708 if (strncmp (dllname
, "cygwin", 6) == 0)
710 *is_cygnus_app
= TRUE
;
719 close_file_data (&executable
);
723 compare_env (const void *strp1
, const void *strp2
)
725 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
727 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
729 /* Sort order in command.com/cmd.exe is based on uppercasing
730 names, so do the same here. */
731 if (toupper (*str1
) > toupper (*str2
))
733 else if (toupper (*str1
) < toupper (*str2
))
738 if (*str1
== '=' && *str2
== '=')
740 else if (*str1
== '=')
747 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
763 qsort (new_envp
, num
, sizeof (char *), compare_env
);
768 /* When a new child process is created we need to register it in our list,
769 so intercept spawn requests. */
771 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
773 Lisp_Object program
, full
;
774 char *cmdline
, *env
, *parg
, **targ
;
778 int is_dos_app
, is_cygnus_app
, is_gui_app
;
781 /* We pass our process ID to our children by setting up an environment
782 variable in their environment. */
783 char ppid_env_var_buffer
[64];
784 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
785 char *sepchars
= " \t";
787 /* We don't care about the other modes */
788 if (mode
!= _P_NOWAIT
)
794 /* Handle executable names without an executable suffix. */
795 program
= make_string (cmdname
, strlen (cmdname
));
796 if (NILP (Ffile_executable_p (program
)))
802 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, make_number (X_OK
));
812 /* make sure argv[0] and cmdname are both in DOS format */
813 cmdname
= SDATA (program
);
814 unixtodos_filename (cmdname
);
817 /* Determine whether program is a 16-bit DOS executable, or a w32
818 executable that is implicitly linked to the Cygnus dll (implying it
819 was compiled with the Cygnus GNU toolchain and hence relies on
820 cygwin.dll to parse the command line - we use this to decide how to
821 escape quote chars in command line args that must be quoted).
823 Also determine whether it is a GUI app, so that we don't hide its
824 initial window unless specifically requested. */
825 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
827 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
828 application to start it by specifying the helper app as cmdname,
829 while leaving the real app name as argv[0]. */
832 cmdname
= alloca (MAXPATHLEN
);
833 if (egetenv ("CMDPROXY"))
834 strcpy (cmdname
, egetenv ("CMDPROXY"));
837 strcpy (cmdname
, SDATA (Vinvocation_directory
));
838 strcat (cmdname
, "cmdproxy.exe");
840 unixtodos_filename (cmdname
);
843 /* we have to do some conjuring here to put argv and envp into the
844 form CreateProcess wants... argv needs to be a space separated/null
845 terminated list of parameters, and envp is a null
846 separated/double-null terminated list of parameters.
848 Additionally, zero-length args and args containing whitespace or
849 quote chars need to be wrapped in double quotes - for this to work,
850 embedded quotes need to be escaped as well. The aim is to ensure
851 the child process reconstructs the argv array we start with
852 exactly, so we treat quotes at the beginning and end of arguments
855 The w32 GNU-based library from Cygnus doubles quotes to escape
856 them, while MSVC uses backslash for escaping. (Actually the MSVC
857 startup code does attempt to recognise doubled quotes and accept
858 them, but gets it wrong and ends up requiring three quotes to get a
859 single embedded quote!) So by default we decide whether to use
860 quote or backslash as the escape character based on whether the
861 binary is apparently a Cygnus compiled app.
863 Note that using backslash to escape embedded quotes requires
864 additional special handling if an embedded quote is already
865 preceeded by backslash, or if an arg requiring quoting ends with
866 backslash. In such cases, the run of escape characters needs to be
867 doubled. For consistency, we apply this special handling as long
868 as the escape character is not quote.
870 Since we have no idea how large argv and envp are likely to be we
871 figure out list lengths on the fly and allocate them. */
873 if (!NILP (Vw32_quote_process_args
))
876 /* Override escape char by binding w32-quote-process-args to
877 desired character, or use t for auto-selection. */
878 if (INTEGERP (Vw32_quote_process_args
))
879 escape_char
= XINT (Vw32_quote_process_args
);
881 escape_char
= is_cygnus_app
? '"' : '\\';
884 /* Cygwin apps needs quoting a bit more often */
885 if (escape_char
== '"')
886 sepchars
= "\r\n\t\f '";
895 int escape_char_run
= 0;
901 if (escape_char
== '"' && *p
== '\\')
902 /* If it's a Cygwin app, \ needs to be escaped. */
906 /* allow for embedded quotes to be escaped */
909 /* handle the case where the embedded quote is already escaped */
910 if (escape_char_run
> 0)
912 /* To preserve the arg exactly, we need to double the
913 preceding escape characters (plus adding one to
914 escape the quote character itself). */
915 arglen
+= escape_char_run
;
918 else if (strchr (sepchars
, *p
) != NULL
)
923 if (*p
== escape_char
&& escape_char
!= '"')
931 /* handle the case where the arg ends with an escape char - we
932 must not let the enclosing quote be escaped. */
933 if (escape_char_run
> 0)
934 arglen
+= escape_char_run
;
936 arglen
+= strlen (*targ
++) + 1;
938 cmdline
= alloca (arglen
);
952 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
957 int escape_char_run
= 0;
963 last
= p
+ strlen (p
) - 1;
966 /* This version does not escape quotes if they occur at the
967 beginning or end of the arg - this could lead to incorrect
968 behaviour when the arg itself represents a command line
969 containing quoted args. I believe this was originally done
970 as a hack to make some things work, before
971 `w32-quote-process-args' was added. */
974 if (*p
== '"' && p
> first
&& p
< last
)
975 *parg
++ = escape_char
; /* escape embedded quotes */
983 /* double preceding escape chars if any */
984 while (escape_char_run
> 0)
986 *parg
++ = escape_char
;
989 /* escape all quote chars, even at beginning or end */
990 *parg
++ = escape_char
;
992 else if (escape_char
== '"' && *p
== '\\')
996 if (*p
== escape_char
&& escape_char
!= '"')
1001 /* double escape chars before enclosing quote */
1002 while (escape_char_run
> 0)
1004 *parg
++ = escape_char
;
1012 strcpy (parg
, *targ
);
1013 parg
+= strlen (*targ
);
1023 numenv
= 1; /* for end null */
1026 arglen
+= strlen (*targ
++) + 1;
1029 /* extra env vars... */
1030 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
1031 GetCurrentProcessId ());
1032 arglen
+= strlen (ppid_env_var_buffer
) + 1;
1035 /* merge env passed in and extra env into one, and sort it. */
1036 targ
= (char **) alloca (numenv
* sizeof (char *));
1037 merge_and_sort_env (envp
, extra_env
, targ
);
1039 /* concatenate env entries. */
1040 env
= alloca (arglen
);
1044 strcpy (parg
, *targ
);
1045 parg
+= strlen (*targ
++);
1058 /* Now create the process. */
1059 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1069 /* Emulate the select call
1070 Wait for available input on any of the given rfds, or timeout if
1071 a timeout is given and no input is detected
1072 wfds and efds are not supported and must be NULL.
1074 For simplicity, we detect the death of child processes here and
1075 synchronously call the SIGCHLD handler. Since it is possible for
1076 children to be created without a corresponding pipe handle from which
1077 to read output, we wait separately on the process handles as well as
1078 the char_avail events for each process pipe. We only call
1079 wait/reap_process when the process actually terminates.
1081 To reduce the number of places in which Emacs can be hung such that
1082 C-g is not able to interrupt it, we always wait on interrupt_handle
1083 (which is signalled by the input thread when C-g is detected). If we
1084 detect that we were woken up by C-g, we return -1 with errno set to
1085 EINTR as on Unix. */
1088 extern HANDLE keyboard_handle
;
1090 /* From w32xfns.c */
1091 extern HANDLE interrupt_handle
;
1093 /* From process.c */
1094 extern int proc_buffered_char
[];
1097 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1098 EMACS_TIME
*timeout
)
1101 DWORD timeout_ms
, start_time
;
1104 child_process
*cp
, *cps
[MAX_CHILDREN
];
1105 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1106 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1108 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1110 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1111 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1117 /* Otherwise, we only handle rfds, so fail otherwise. */
1118 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1128 /* Always wait on interrupt_handle, to detect C-g (quit). */
1129 wait_hnd
[0] = interrupt_handle
;
1132 /* Build a list of pipe handles to wait on. */
1134 for (i
= 0; i
< nfds
; i
++)
1135 if (FD_ISSET (i
, &orfds
))
1139 if (keyboard_handle
)
1141 /* Handle stdin specially */
1142 wait_hnd
[nh
] = keyboard_handle
;
1147 /* Check for any emacs-generated input in the queue since
1148 it won't be detected in the wait */
1149 if (detect_input_pending ())
1157 /* Child process and socket input */
1161 int current_status
= cp
->status
;
1163 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1165 /* Tell reader thread which file handle to use. */
1167 /* Wake up the reader thread for this process */
1168 cp
->status
= STATUS_READ_READY
;
1169 if (!SetEvent (cp
->char_consumed
))
1170 DebPrint (("nt_select.SetEvent failed with "
1171 "%lu for fd %ld\n", GetLastError (), i
));
1174 #ifdef CHECK_INTERLOCK
1175 /* slightly crude cross-checking of interlock between threads */
1177 current_status
= cp
->status
;
1178 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1180 /* char_avail has been signalled, so status (which may
1181 have changed) should indicate read has completed
1182 but has not been acknowledged. */
1183 current_status
= cp
->status
;
1184 if (current_status
!= STATUS_READ_SUCCEEDED
1185 && current_status
!= STATUS_READ_FAILED
)
1186 DebPrint (("char_avail set, but read not completed: status %d\n",
1191 /* char_avail has not been signalled, so status should
1192 indicate that read is in progress; small possibility
1193 that read has completed but event wasn't yet signalled
1194 when we tested it (because a context switch occurred
1195 or if running on separate CPUs). */
1196 if (current_status
!= STATUS_READ_READY
1197 && current_status
!= STATUS_READ_IN_PROGRESS
1198 && current_status
!= STATUS_READ_SUCCEEDED
1199 && current_status
!= STATUS_READ_FAILED
)
1200 DebPrint (("char_avail reset, but read status is bad: %d\n",
1204 wait_hnd
[nh
] = cp
->char_avail
;
1206 if (!wait_hnd
[nh
]) abort ();
1209 DebPrint (("select waiting on child %d fd %d\n",
1210 cp
-child_procs
, i
));
1215 /* Unable to find something to wait on for this fd, skip */
1217 /* Note that this is not a fatal error, and can in fact
1218 happen in unusual circumstances. Specifically, if
1219 sys_spawnve fails, eg. because the program doesn't
1220 exist, and debug-on-error is t so Fsignal invokes a
1221 nested input loop, then the process output pipe is
1222 still included in input_wait_mask with no child_proc
1223 associated with it. (It is removed when the debugger
1224 exits the nested input loop and the error is thrown.) */
1226 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1232 /* Add handles of child processes. */
1234 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1235 /* Some child_procs might be sockets; ignore them. Also some
1236 children may have died already, but we haven't finished reading
1237 the process output; ignore them too. */
1238 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1240 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1241 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1244 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1249 /* Nothing to look for, so we didn't find anything */
1257 start_time
= GetTickCount ();
1259 /* Wait for input or child death to be signalled. If user input is
1260 allowed, then also accept window messages. */
1261 if (FD_ISSET (0, &orfds
))
1262 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1265 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1267 if (active
== WAIT_FAILED
)
1269 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1270 nh
+ nc
, timeout_ms
, GetLastError ()));
1271 /* don't return EBADF - this causes wait_reading_process_output to
1272 abort; WAIT_FAILED is returned when single-stepping under
1273 Windows 95 after switching thread focus in debugger, and
1274 possibly at other times. */
1278 else if (active
== WAIT_TIMEOUT
)
1282 else if (active
>= WAIT_OBJECT_0
1283 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1285 active
-= WAIT_OBJECT_0
;
1287 else if (active
>= WAIT_ABANDONED_0
1288 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1290 active
-= WAIT_ABANDONED_0
;
1295 /* Loop over all handles after active (now officially documented as
1296 being the first signalled handle in the array). We do this to
1297 ensure fairness, so that all channels with data available will be
1298 processed - otherwise higher numbered channels could be starved. */
1301 if (active
== nh
+ nc
)
1303 /* There are messages in the lisp thread's queue; we must
1304 drain the queue now to ensure they are processed promptly,
1305 because if we don't do so, we will not be woken again until
1306 further messages arrive.
1308 NB. If ever we allow window message procedures to callback
1309 into lisp, we will need to ensure messages are dispatched
1310 at a safe time for lisp code to be run (*), and we may also
1311 want to provide some hooks in the dispatch loop to cater
1312 for modeless dialogs created by lisp (ie. to register
1313 window handles to pass to IsDialogMessage).
1315 (*) Note that MsgWaitForMultipleObjects above is an
1316 internal dispatch point for messages that are sent to
1317 windows created by this thread. */
1318 drain_message_queue ();
1320 else if (active
>= nh
)
1322 cp
= cps
[active
- nh
];
1324 /* We cannot always signal SIGCHLD immediately; if we have not
1325 finished reading the process output, we must delay sending
1326 SIGCHLD until we do. */
1328 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1329 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1330 /* SIG_DFL for SIGCHLD is ignore */
1331 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1332 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1335 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1339 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1343 else if (fdindex
[active
] == -1)
1345 /* Quit (C-g) was detected. */
1349 else if (fdindex
[active
] == 0)
1351 /* Keyboard input available */
1357 /* must be a socket or pipe - read ahead should have
1358 completed, either succeeding or failing. */
1359 FD_SET (fdindex
[active
], rfds
);
1363 /* Even though wait_reading_process_output only reads from at most
1364 one channel, we must process all channels here so that we reap
1365 all children that have died. */
1366 while (++active
< nh
+ nc
)
1367 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1369 } while (active
< nh
+ nc
);
1371 /* If no input has arrived and timeout hasn't expired, wait again. */
1374 DWORD elapsed
= GetTickCount () - start_time
;
1376 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1378 if (timeout_ms
!= INFINITE
)
1379 timeout_ms
-= elapsed
;
1380 goto count_children
;
1387 /* Substitute for certain kill () operations */
1389 static BOOL CALLBACK
1390 find_child_console (HWND hwnd
, LPARAM arg
)
1392 child_process
* cp
= (child_process
*) arg
;
1396 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1397 if (process_id
== cp
->procinfo
.dwProcessId
)
1399 char window_class
[32];
1401 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1402 if (strcmp (window_class
,
1403 (os_subtype
== OS_WIN95
)
1405 : "ConsoleWindowClass") == 0)
1416 sys_kill (int pid
, int sig
)
1420 int need_to_free
= 0;
1423 /* Only handle signals that will result in the process dying */
1424 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1430 cp
= find_child_pid (pid
);
1433 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1434 if (proc_hand
== NULL
)
1443 proc_hand
= cp
->procinfo
.hProcess
;
1444 pid
= cp
->procinfo
.dwProcessId
;
1446 /* Try to locate console window for process. */
1447 EnumWindows (find_child_console
, (LPARAM
) cp
);
1450 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1452 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1454 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1455 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1456 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1457 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1458 HWND foreground_window
;
1460 if (break_scan_code
== 0)
1462 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1463 vk_break_code
= 'C';
1464 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1467 foreground_window
= GetForegroundWindow ();
1468 if (foreground_window
)
1470 /* NT 5.0, and apparently also Windows 98, will not allow
1471 a Window to be set to foreground directly without the
1472 user's involvement. The workaround is to attach
1473 ourselves to the thread that owns the foreground
1474 window, since that is the only thread that can set the
1475 foreground window. */
1476 DWORD foreground_thread
, child_thread
;
1478 GetWindowThreadProcessId (foreground_window
, NULL
);
1479 if (foreground_thread
== GetCurrentThreadId ()
1480 || !AttachThreadInput (GetCurrentThreadId (),
1481 foreground_thread
, TRUE
))
1482 foreground_thread
= 0;
1484 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1485 if (child_thread
== GetCurrentThreadId ()
1486 || !AttachThreadInput (GetCurrentThreadId (),
1487 child_thread
, TRUE
))
1490 /* Set the foreground window to the child. */
1491 if (SetForegroundWindow (cp
->hwnd
))
1493 /* Generate keystrokes as if user had typed Ctrl-Break or
1495 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1496 keybd_event (vk_break_code
, break_scan_code
,
1497 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1498 keybd_event (vk_break_code
, break_scan_code
,
1499 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1500 | KEYEVENTF_KEYUP
, 0);
1501 keybd_event (VK_CONTROL
, control_scan_code
,
1502 KEYEVENTF_KEYUP
, 0);
1504 /* Sleep for a bit to give time for Emacs frame to respond
1505 to focus change events (if Emacs was active app). */
1508 SetForegroundWindow (foreground_window
);
1510 /* Detach from the foreground and child threads now that
1511 the foreground switching is over. */
1512 if (foreground_thread
)
1513 AttachThreadInput (GetCurrentThreadId (),
1514 foreground_thread
, FALSE
);
1516 AttachThreadInput (GetCurrentThreadId (),
1517 child_thread
, FALSE
);
1520 /* Ctrl-Break is NT equivalent of SIGINT. */
1521 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1523 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1524 "for pid %lu\n", GetLastError (), pid
));
1531 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1534 if (os_subtype
== OS_WIN95
)
1537 Another possibility is to try terminating the VDM out-right by
1538 calling the Shell VxD (id 0x17) V86 interface, function #4
1539 "SHELL_Destroy_VM", ie.
1545 First need to determine the current VM handle, and then arrange for
1546 the shellapi call to be made from the system vm (by using
1547 Switch_VM_and_callback).
1549 Could try to invoke DestroyVM through CallVxD.
1553 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1554 to hang when cmdproxy is used in conjunction with
1555 command.com for an interactive shell. Posting
1556 WM_CLOSE pops up a dialog that, when Yes is selected,
1557 does the same thing. TerminateProcess is also less
1558 than ideal in that subprocesses tend to stick around
1559 until the machine is shutdown, but at least it
1560 doesn't freeze the 16-bit subsystem. */
1561 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1563 if (!TerminateProcess (proc_hand
, 0xff))
1565 DebPrint (("sys_kill.TerminateProcess returned %d "
1566 "for pid %lu\n", GetLastError (), pid
));
1573 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1575 /* Kill the process. On W32 this doesn't kill child processes
1576 so it doesn't work very well for shells which is why it's not
1577 used in every case. */
1578 else if (!TerminateProcess (proc_hand
, 0xff))
1580 DebPrint (("sys_kill.TerminateProcess returned %d "
1581 "for pid %lu\n", GetLastError (), pid
));
1588 CloseHandle (proc_hand
);
1593 /* extern int report_file_error (char *, Lisp_Object); */
1595 /* The following two routines are used to manipulate stdin, stdout, and
1596 stderr of our child processes.
1598 Assuming that in, out, and err are *not* inheritable, we make them
1599 stdin, stdout, and stderr of the child as follows:
1601 - Save the parent's current standard handles.
1602 - Set the std handles to inheritable duplicates of the ones being passed in.
1603 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1604 NT file handle for a crt file descriptor.)
1605 - Spawn the child, which inherits in, out, and err as stdin,
1606 stdout, and stderr. (see Spawnve)
1607 - Close the std handles passed to the child.
1608 - Reset the parent's standard handles to the saved handles.
1609 (see reset_standard_handles)
1610 We assume that the caller closes in, out, and err after calling us. */
1613 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1616 HANDLE newstdin
, newstdout
, newstderr
;
1618 parent
= GetCurrentProcess ();
1620 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1621 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1622 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1624 /* make inheritable copies of the new handles */
1625 if (!DuplicateHandle (parent
,
1626 (HANDLE
) _get_osfhandle (in
),
1631 DUPLICATE_SAME_ACCESS
))
1632 report_file_error ("Duplicating input handle for child", Qnil
);
1634 if (!DuplicateHandle (parent
,
1635 (HANDLE
) _get_osfhandle (out
),
1640 DUPLICATE_SAME_ACCESS
))
1641 report_file_error ("Duplicating output handle for child", Qnil
);
1643 if (!DuplicateHandle (parent
,
1644 (HANDLE
) _get_osfhandle (err
),
1649 DUPLICATE_SAME_ACCESS
))
1650 report_file_error ("Duplicating error handle for child", Qnil
);
1652 /* and store them as our std handles */
1653 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1654 report_file_error ("Changing stdin handle", Qnil
);
1656 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1657 report_file_error ("Changing stdout handle", Qnil
);
1659 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1660 report_file_error ("Changing stderr handle", Qnil
);
1664 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1666 /* close the duplicated handles passed to the child */
1667 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1668 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1669 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1671 /* now restore parent's saved std handles */
1672 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1673 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1674 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1678 set_process_dir (char * dir
)
1685 /* To avoid problems with winsock implementations that work over dial-up
1686 connections causing or requiring a connection to exist while Emacs is
1687 running, Emacs no longer automatically loads winsock on startup if it
1688 is present. Instead, it will be loaded when open-network-stream is
1691 To allow full control over when winsock is loaded, we provide these
1692 two functions to dynamically load and unload winsock. This allows
1693 dial-up users to only be connected when they actually need to use
1697 extern HANDLE winsock_lib
;
1698 extern BOOL
term_winsock (void);
1699 extern BOOL
init_winsock (int load_now
);
1701 extern Lisp_Object Vsystem_name
;
1703 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1704 doc
: /* Test for presence of the Windows socket library `winsock'.
1705 Returns non-nil if winsock support is present, nil otherwise.
1707 If the optional argument LOAD-NOW is non-nil, the winsock library is
1708 also loaded immediately if not already loaded. If winsock is loaded,
1709 the winsock local hostname is returned (since this may be different from
1710 the value of `system-name' and should supplant it), otherwise t is
1711 returned to indicate winsock support is present. */)
1713 Lisp_Object load_now
;
1717 have_winsock
= init_winsock (!NILP (load_now
));
1720 if (winsock_lib
!= NULL
)
1722 /* Return new value for system-name. The best way to do this
1723 is to call init_system_name, saving and restoring the
1724 original value to avoid side-effects. */
1725 Lisp_Object orig_hostname
= Vsystem_name
;
1726 Lisp_Object hostname
;
1728 init_system_name ();
1729 hostname
= Vsystem_name
;
1730 Vsystem_name
= orig_hostname
;
1738 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1740 doc
: /* Unload the Windows socket library `winsock' if loaded.
1741 This is provided to allow dial-up socket connections to be disconnected
1742 when no longer needed. Returns nil without unloading winsock if any
1743 socket connections still exist. */)
1746 return term_winsock () ? Qt
: Qnil
;
1749 #endif /* HAVE_SOCKETS */
1752 /* Some miscellaneous functions that are Windows specific, but not GUI
1753 specific (ie. are applicable in terminal or batch mode as well). */
1755 /* lifted from fileio.c */
1756 #define CORRECT_DIR_SEPS(s) \
1757 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1758 else unixtodos_filename (s); \
1761 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1762 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1763 If FILENAME does not exist, return nil.
1764 All path elements in FILENAME are converted to their short names. */)
1766 Lisp_Object filename
;
1768 char shortname
[MAX_PATH
];
1770 CHECK_STRING (filename
);
1772 /* first expand it. */
1773 filename
= Fexpand_file_name (filename
, Qnil
);
1775 /* luckily, this returns the short version of each element in the path. */
1776 if (GetShortPathName (SDATA (filename
), shortname
, MAX_PATH
) == 0)
1779 CORRECT_DIR_SEPS (shortname
);
1781 return build_string (shortname
);
1785 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1787 doc
: /* Return the long file name version of the full path of FILENAME.
1788 If FILENAME does not exist, return nil.
1789 All path elements in FILENAME are converted to their long names. */)
1791 Lisp_Object filename
;
1793 char longname
[ MAX_PATH
];
1795 CHECK_STRING (filename
);
1797 /* first expand it. */
1798 filename
= Fexpand_file_name (filename
, Qnil
);
1800 if (!w32_get_long_filename (SDATA (filename
), longname
, MAX_PATH
))
1803 CORRECT_DIR_SEPS (longname
);
1805 return build_string (longname
);
1808 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1809 Sw32_set_process_priority
, 2, 2, 0,
1810 doc
: /* Set the priority of PROCESS to PRIORITY.
1811 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1812 priority of the process whose pid is PROCESS is changed.
1813 PRIORITY should be one of the symbols high, normal, or low;
1814 any other symbol will be interpreted as normal.
1816 If successful, the return value is t, otherwise nil. */)
1818 Lisp_Object process
, priority
;
1820 HANDLE proc_handle
= GetCurrentProcess ();
1821 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1822 Lisp_Object result
= Qnil
;
1824 CHECK_SYMBOL (priority
);
1826 if (!NILP (process
))
1831 CHECK_NUMBER (process
);
1833 /* Allow pid to be an internally generated one, or one obtained
1834 externally. This is necessary because real pids on Win95 are
1837 pid
= XINT (process
);
1838 cp
= find_child_pid (pid
);
1840 pid
= cp
->procinfo
.dwProcessId
;
1842 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1845 if (EQ (priority
, Qhigh
))
1846 priority_class
= HIGH_PRIORITY_CLASS
;
1847 else if (EQ (priority
, Qlow
))
1848 priority_class
= IDLE_PRIORITY_CLASS
;
1850 if (proc_handle
!= NULL
)
1852 if (SetPriorityClass (proc_handle
, priority_class
))
1854 if (!NILP (process
))
1855 CloseHandle (proc_handle
);
1861 #ifdef HAVE_LANGINFO_CODESET
1862 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1863 char *nl_langinfo (nl_item item
)
1865 /* Conversion of Posix item numbers to their Windows equivalents. */
1866 static const LCTYPE w32item
[] = {
1867 LOCALE_IDEFAULTANSICODEPAGE
,
1868 LOCALE_SDAYNAME1
, LOCALE_SDAYNAME2
, LOCALE_SDAYNAME3
,
1869 LOCALE_SDAYNAME4
, LOCALE_SDAYNAME5
, LOCALE_SDAYNAME6
, LOCALE_SDAYNAME7
,
1870 LOCALE_SMONTHNAME1
, LOCALE_SMONTHNAME2
, LOCALE_SMONTHNAME3
,
1871 LOCALE_SMONTHNAME4
, LOCALE_SMONTHNAME5
, LOCALE_SMONTHNAME6
,
1872 LOCALE_SMONTHNAME7
, LOCALE_SMONTHNAME8
, LOCALE_SMONTHNAME9
,
1873 LOCALE_SMONTHNAME10
, LOCALE_SMONTHNAME11
, LOCALE_SMONTHNAME12
1876 static char *nl_langinfo_buf
= NULL
;
1877 static int nl_langinfo_len
= 0;
1879 if (nl_langinfo_len
<= 0)
1880 nl_langinfo_buf
= xmalloc (nl_langinfo_len
= 1);
1882 if (item
< 0 || item
>= _NL_NUM
)
1883 nl_langinfo_buf
[0] = 0;
1886 LCID cloc
= GetThreadLocale ();
1887 int need_len
= GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1891 nl_langinfo_buf
[0] = 0;
1894 if (item
== CODESET
)
1896 need_len
+= 2; /* for the "cp" prefix */
1897 if (need_len
< 8) /* for the case we call GetACP */
1900 if (nl_langinfo_len
<= need_len
)
1901 nl_langinfo_buf
= xrealloc (nl_langinfo_buf
,
1902 nl_langinfo_len
= need_len
);
1903 if (!GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1904 nl_langinfo_buf
, nl_langinfo_len
))
1905 nl_langinfo_buf
[0] = 0;
1906 else if (item
== CODESET
)
1908 if (strcmp (nl_langinfo_buf
, "0") == 0 /* CP_ACP */
1909 || strcmp (nl_langinfo_buf
, "1") == 0) /* CP_OEMCP */
1910 sprintf (nl_langinfo_buf
, "cp%u", GetACP ());
1913 memmove (nl_langinfo_buf
+ 2, nl_langinfo_buf
,
1914 strlen (nl_langinfo_buf
) + 1);
1915 nl_langinfo_buf
[0] = 'c';
1916 nl_langinfo_buf
[1] = 'p';
1921 return nl_langinfo_buf
;
1923 #endif /* HAVE_LANGINFO_CODESET */
1925 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1926 Sw32_get_locale_info
, 1, 2, 0,
1927 doc
: /* Return information about the Windows locale LCID.
1928 By default, return a three letter locale code which encodes the default
1929 language as the first two characters, and the country or regionial variant
1930 as the third letter. For example, ENU refers to `English (United States)',
1931 while ENC means `English (Canadian)'.
1933 If the optional argument LONGFORM is t, the long form of the locale
1934 name is returned, e.g. `English (United States)' instead; if LONGFORM
1935 is a number, it is interpreted as an LCTYPE constant and the corresponding
1936 locale information is returned.
1938 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1940 Lisp_Object lcid
, longform
;
1944 char abbrev_name
[32] = { 0 };
1945 char full_name
[256] = { 0 };
1947 CHECK_NUMBER (lcid
);
1949 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1952 if (NILP (longform
))
1954 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1955 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1956 abbrev_name
, sizeof (abbrev_name
));
1958 return build_string (abbrev_name
);
1960 else if (EQ (longform
, Qt
))
1962 got_full
= GetLocaleInfo (XINT (lcid
),
1963 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1964 full_name
, sizeof (full_name
));
1966 return build_string (full_name
);
1968 else if (NUMBERP (longform
))
1970 got_full
= GetLocaleInfo (XINT (lcid
),
1972 full_name
, sizeof (full_name
));
1974 return make_unibyte_string (full_name
, got_full
);
1981 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
1982 Sw32_get_current_locale_id
, 0, 0, 0,
1983 doc
: /* Return Windows locale id for current locale setting.
1984 This is a numerical value; use `w32-get-locale-info' to convert to a
1985 human-readable form. */)
1988 return make_number (GetThreadLocale ());
1991 DWORD
int_from_hex (char * s
)
1994 static char hex
[] = "0123456789abcdefABCDEF";
1997 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
1999 unsigned digit
= p
- hex
;
2002 val
= val
* 16 + digit
;
2008 /* We need to build a global list, since the EnumSystemLocale callback
2009 function isn't given a context pointer. */
2010 Lisp_Object Vw32_valid_locale_ids
;
2012 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
2014 DWORD id
= int_from_hex (localeNum
);
2015 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
2019 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
2020 Sw32_get_valid_locale_ids
, 0, 0, 0,
2021 doc
: /* Return list of all valid Windows locale ids.
2022 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2023 human-readable form. */)
2026 Vw32_valid_locale_ids
= Qnil
;
2028 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
2030 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
2031 return Vw32_valid_locale_ids
;
2035 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
2036 doc
: /* Return Windows locale id for default locale setting.
2037 By default, the system default locale setting is returned; if the optional
2038 parameter USERP is non-nil, the user default locale setting is returned.
2039 This is a numerical value; use `w32-get-locale-info' to convert to a
2040 human-readable form. */)
2045 return make_number (GetSystemDefaultLCID ());
2046 return make_number (GetUserDefaultLCID ());
2050 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
2051 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
2052 If successful, the new locale id is returned, otherwise nil. */)
2056 CHECK_NUMBER (lcid
);
2058 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
2061 if (!SetThreadLocale (XINT (lcid
)))
2064 /* Need to set input thread locale if present. */
2065 if (dwWindowsThreadId
)
2066 /* Reply is not needed. */
2067 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
2069 return make_number (GetThreadLocale ());
2073 /* We need to build a global list, since the EnumCodePages callback
2074 function isn't given a context pointer. */
2075 Lisp_Object Vw32_valid_codepages
;
2077 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
2079 DWORD id
= atoi (codepageNum
);
2080 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
2084 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
2085 Sw32_get_valid_codepages
, 0, 0, 0,
2086 doc
: /* Return list of all valid Windows codepages. */)
2089 Vw32_valid_codepages
= Qnil
;
2091 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
2093 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
2094 return Vw32_valid_codepages
;
2098 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
2099 Sw32_get_console_codepage
, 0, 0, 0,
2100 doc
: /* Return current Windows codepage for console input. */)
2103 return make_number (GetConsoleCP ());
2107 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
2108 Sw32_set_console_codepage
, 1, 1, 0,
2109 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2110 The codepage setting affects keyboard input and display in tty mode.
2111 If successful, the new CP is returned, otherwise nil. */)
2117 if (!IsValidCodePage (XINT (cp
)))
2120 if (!SetConsoleCP (XINT (cp
)))
2123 return make_number (GetConsoleCP ());
2127 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2128 Sw32_get_console_output_codepage
, 0, 0, 0,
2129 doc
: /* Return current Windows codepage for console output. */)
2132 return make_number (GetConsoleOutputCP ());
2136 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2137 Sw32_set_console_output_codepage
, 1, 1, 0,
2138 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2139 The codepage setting affects keyboard input and display in tty mode.
2140 If successful, the new CP is returned, otherwise nil. */)
2146 if (!IsValidCodePage (XINT (cp
)))
2149 if (!SetConsoleOutputCP (XINT (cp
)))
2152 return make_number (GetConsoleOutputCP ());
2156 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2157 Sw32_get_codepage_charset
, 1, 1, 0,
2158 doc
: /* Return charset of codepage CP.
2159 Returns nil if the codepage is not valid. */)
2167 if (!IsValidCodePage (XINT (cp
)))
2170 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2171 return make_number (info
.ciCharset
);
2177 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2178 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2179 doc
: /* Return list of Windows keyboard languages and layouts.
2180 The return value is a list of pairs of language id and layout id. */)
2183 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2184 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2185 Lisp_Object obj
= Qnil
;
2187 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2189 while (--num_layouts
>= 0)
2191 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2193 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2194 make_number ((kl
>> 16) & 0xffff)),
2203 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2204 Sw32_get_keyboard_layout
, 0, 0, 0,
2205 doc
: /* Return current Windows keyboard language and layout.
2206 The return value is the cons of the language id and the layout id. */)
2209 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2211 return Fcons (make_number (kl
& 0xffff),
2212 make_number ((kl
>> 16) & 0xffff));
2216 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2217 Sw32_set_keyboard_layout
, 1, 1, 0,
2218 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2219 The keyboard layout setting affects interpretation of keyboard input.
2220 If successful, the new layout id is returned, otherwise nil. */)
2226 CHECK_CONS (layout
);
2227 CHECK_NUMBER_CAR (layout
);
2228 CHECK_NUMBER_CDR (layout
);
2230 kl
= (XINT (XCAR (layout
)) & 0xffff)
2231 | (XINT (XCDR (layout
)) << 16);
2233 /* Synchronize layout with input thread. */
2234 if (dwWindowsThreadId
)
2236 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2240 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2242 if (msg
.wParam
== 0)
2246 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2249 return Fw32_get_keyboard_layout ();
2255 DEFSYM (Qhigh
, "high");
2256 DEFSYM (Qlow
, "low");
2259 defsubr (&Sw32_has_winsock
);
2260 defsubr (&Sw32_unload_winsock
);
2262 defsubr (&Sw32_short_file_name
);
2263 defsubr (&Sw32_long_file_name
);
2264 defsubr (&Sw32_set_process_priority
);
2265 defsubr (&Sw32_get_locale_info
);
2266 defsubr (&Sw32_get_current_locale_id
);
2267 defsubr (&Sw32_get_default_locale_id
);
2268 defsubr (&Sw32_get_valid_locale_ids
);
2269 defsubr (&Sw32_set_current_locale
);
2271 defsubr (&Sw32_get_console_codepage
);
2272 defsubr (&Sw32_set_console_codepage
);
2273 defsubr (&Sw32_get_console_output_codepage
);
2274 defsubr (&Sw32_set_console_output_codepage
);
2275 defsubr (&Sw32_get_valid_codepages
);
2276 defsubr (&Sw32_get_codepage_charset
);
2278 defsubr (&Sw32_get_valid_keyboard_layouts
);
2279 defsubr (&Sw32_get_keyboard_layout
);
2280 defsubr (&Sw32_set_keyboard_layout
);
2282 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2283 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2284 Because Windows does not directly pass argv arrays to child processes,
2285 programs have to reconstruct the argv array by parsing the command
2286 line string. For an argument to contain a space, it must be enclosed
2287 in double quotes or it will be parsed as multiple arguments.
2289 If the value is a character, that character will be used to escape any
2290 quote characters that appear, otherwise a suitable escape character
2291 will be chosen based on the type of the program. */);
2292 Vw32_quote_process_args
= Qt
;
2294 DEFVAR_LISP ("w32-start-process-show-window",
2295 &Vw32_start_process_show_window
,
2296 doc
: /* When nil, new child processes hide their windows.
2297 When non-nil, they show their window in the method of their choice.
2298 This variable doesn't affect GUI applications, which will never be hidden. */);
2299 Vw32_start_process_show_window
= Qnil
;
2301 DEFVAR_LISP ("w32-start-process-share-console",
2302 &Vw32_start_process_share_console
,
2303 doc
: /* When nil, new child processes are given a new console.
2304 When non-nil, they share the Emacs console; this has the limitation of
2305 allowing only one DOS subprocess to run at a time (whether started directly
2306 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2307 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2308 otherwise respond to interrupts from Emacs. */);
2309 Vw32_start_process_share_console
= Qnil
;
2311 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2312 &Vw32_start_process_inherit_error_mode
,
2313 doc
: /* When nil, new child processes revert to the default error mode.
2314 When non-nil, they inherit their error mode setting from Emacs, which stops
2315 them blocking when trying to access unmounted drives etc. */);
2316 Vw32_start_process_inherit_error_mode
= Qt
;
2318 DEFVAR_INT ("w32-pipe-read-delay", &w32_pipe_read_delay
,
2319 doc
: /* Forced delay before reading subprocess output.
2320 This is done to improve the buffering of subprocess output, by
2321 avoiding the inefficiency of frequently reading small amounts of data.
2323 If positive, the value is the number of milliseconds to sleep before
2324 reading the subprocess output. If negative, the magnitude is the number
2325 of time slices to wait (effectively boosting the priority of the child
2326 process temporarily). A value of zero disables waiting entirely. */);
2327 w32_pipe_read_delay
= 50;
2329 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2330 doc
: /* Non-nil means convert all-upper case file names to lower case.
2331 This applies when performing completions and file name expansion.
2332 Note that the value of this setting also affects remote file names,
2333 so you probably don't want to set to non-nil if you use case-sensitive
2334 filesystems via ange-ftp. */);
2335 Vw32_downcase_file_names
= Qnil
;
2338 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2339 doc
: /* Non-nil means attempt to fake realistic inode values.
2340 This works by hashing the truename of files, and should detect
2341 aliasing between long and short (8.3 DOS) names, but can have
2342 false positives because of hash collisions. Note that determing
2343 the truename of a file can be slow. */);
2344 Vw32_generate_fake_inodes
= Qnil
;
2347 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2348 doc
: /* Non-nil means determine accurate link count in `file-attributes'.
2349 Note that this option is only useful for files on NTFS volumes, where hard links
2350 are supported. Moreover, it slows down `file-attributes' noticeably. */);
2351 Vw32_get_true_file_attributes
= Qt
;
2353 staticpro (&Vw32_valid_locale_ids
);
2354 staticpro (&Vw32_valid_codepages
);
2356 /* end of ntproc.c */
2358 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2359 (do not change this comment) */