1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999-2012 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 Drew Bliss Oct 14, 1993
21 Adapted from alarm.c by Tim Fleehart
33 /* must include CRT headers *before* config.h */
44 /* This definition is missing from mingw32 headers. */
45 extern BOOL WINAPI
IsValidLocale (LCID
, DWORD
);
48 #ifdef HAVE_LANGINFO_CODESET
59 #include "syssignal.h"
61 #include "dispextern.h" /* for xstrcasecmp */
64 #define RVA_TO_PTR(var,section,filedata) \
65 ((void *)((section)->PointerToRawData \
66 + ((DWORD)(var) - (section)->VirtualAddress) \
67 + (filedata).file_base))
69 Lisp_Object Qhigh
, Qlow
;
73 _DebPrint (const char *fmt
, ...)
79 vsprintf (buf
, fmt
, args
);
81 OutputDebugString (buf
);
85 typedef void (_CALLBACK_
*signal_handler
) (int);
87 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
88 static signal_handler sig_handlers
[NSIG
];
90 /* Fake signal implementation to record the SIGCHLD handler. */
92 sys_signal (int sig
, signal_handler handler
)
101 old
= sig_handlers
[sig
];
102 sig_handlers
[sig
] = handler
;
106 /* Defined in <process.h> which conflicts with the local copy */
109 /* Child process management list. */
110 int child_proc_count
= 0;
111 child_process child_procs
[ MAX_CHILDREN
];
112 child_process
*dead_child
= NULL
;
114 static DWORD WINAPI
reader_thread (void *arg
);
116 /* Find an unused process slot. */
123 for (cp
= child_procs
+ (child_proc_count
-1); cp
>= child_procs
; cp
--)
124 if (!CHILD_ACTIVE (cp
))
126 if (child_proc_count
== MAX_CHILDREN
)
128 cp
= &child_procs
[child_proc_count
++];
131 memset (cp
, 0, sizeof (*cp
));
134 cp
->procinfo
.hProcess
= NULL
;
135 cp
->status
= STATUS_READ_ERROR
;
137 /* use manual reset event so that select() will function properly */
138 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
141 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
142 if (cp
->char_consumed
)
144 /* The 0x00010000 flag is STACK_SIZE_PARAM_IS_A_RESERVATION.
145 It means that the 64K stack we are requesting in the 2nd
146 argument is how much memory should be reserved for the
147 stack. If we don't use this flag, the memory requested
148 by the 2nd argument is the amount actually _committed_,
149 but Windows reserves 8MB of memory for each thread's
150 stack. (The 8MB figure comes from the -stack
151 command-line argument we pass to the linker when building
152 Emacs, but that's because we need a large stack for
153 Emacs's main thread.) Since we request 2GB of reserved
154 memory at startup (see w32heap.c), which is close to the
155 maximum memory available for a 32-bit process on Windows,
156 the 8MB reservation for each thread causes failures in
157 starting subprocesses, because we create a thread running
158 reader_thread for each subprocess. As 8MB of stack is
159 way too much for reader_thread, forcing Windows to
160 reserve less wins the day. */
161 cp
->thrd
= CreateThread (NULL
, 64 * 1024, reader_thread
, cp
,
172 delete_child (child_process
*cp
)
176 /* Should not be deleting a child that is still needed. */
177 for (i
= 0; i
< MAXDESC
; i
++)
178 if (fd_info
[i
].cp
== cp
)
181 if (!CHILD_ACTIVE (cp
))
184 /* reap thread if necessary */
189 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
191 /* let the thread exit cleanly if possible */
192 cp
->status
= STATUS_READ_ERROR
;
193 SetEvent (cp
->char_consumed
);
195 /* We used to forcibly terminate the thread here, but it
196 is normally unnecessary, and in abnormal cases, the worst that
197 will happen is we have an extra idle thread hanging around
198 waiting for the zombie process. */
199 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
201 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
202 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
203 TerminateThread (cp
->thrd
, 0);
207 CloseHandle (cp
->thrd
);
212 CloseHandle (cp
->char_avail
);
213 cp
->char_avail
= NULL
;
215 if (cp
->char_consumed
)
217 CloseHandle (cp
->char_consumed
);
218 cp
->char_consumed
= NULL
;
221 /* update child_proc_count (highest numbered slot in use plus one) */
222 if (cp
== child_procs
+ child_proc_count
- 1)
224 for (i
= child_proc_count
-1; i
>= 0; i
--)
225 if (CHILD_ACTIVE (&child_procs
[i
]))
227 child_proc_count
= i
+ 1;
232 child_proc_count
= 0;
235 /* Find a child by pid. */
236 static child_process
*
237 find_child_pid (DWORD pid
)
241 for (cp
= child_procs
+ (child_proc_count
-1); cp
>= child_procs
; cp
--)
242 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
248 /* Thread proc for child process and socket reader threads. Each thread
249 is normally blocked until woken by select() to check for input by
250 reading one char. When the read completes, char_avail is signaled
251 to wake up the select emulator and the thread blocks itself again. */
253 reader_thread (void *arg
)
258 cp
= (child_process
*)arg
;
260 /* We have to wait for the go-ahead before we can start */
262 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
270 if (fd_info
[cp
->fd
].flags
& FILE_LISTEN
)
271 rc
= _sys_wait_accept (cp
->fd
);
273 rc
= _sys_read_ahead (cp
->fd
);
275 /* The name char_avail is a misnomer - it really just means the
276 read-ahead has completed, whether successfully or not. */
277 if (!SetEvent (cp
->char_avail
))
279 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
280 GetLastError (), cp
->fd
));
284 if (rc
== STATUS_READ_ERROR
)
287 /* If the read died, the child has died so let the thread die */
288 if (rc
== STATUS_READ_FAILED
)
291 /* Wait until our input is acknowledged before reading again */
292 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
294 DebPrint (("reader_thread.WaitForSingleObject failed with "
295 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
302 /* To avoid Emacs changing directory, we just record here the directory
303 the new process should start in. This is set just before calling
304 sys_spawnve, and is not generally valid at any other time. */
305 static char * process_dir
;
308 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
309 int * pPid
, child_process
*cp
)
312 SECURITY_ATTRIBUTES sec_attrs
;
314 SECURITY_DESCRIPTOR sec_desc
;
317 char dir
[ MAXPATHLEN
];
319 if (cp
== NULL
) abort ();
321 memset (&start
, 0, sizeof (start
));
322 start
.cb
= sizeof (start
);
325 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
326 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
328 start
.dwFlags
= STARTF_USESTDHANDLES
;
329 start
.wShowWindow
= SW_HIDE
;
331 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
332 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
333 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
334 #endif /* HAVE_NTGUI */
337 /* Explicitly specify no security */
338 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
340 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
343 sec_attrs
.nLength
= sizeof (sec_attrs
);
344 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
345 sec_attrs
.bInheritHandle
= FALSE
;
347 strcpy (dir
, process_dir
);
348 unixtodos_filename (dir
);
350 flags
= (!NILP (Vw32_start_process_share_console
)
351 ? CREATE_NEW_PROCESS_GROUP
352 : CREATE_NEW_CONSOLE
);
353 if (NILP (Vw32_start_process_inherit_error_mode
))
354 flags
|= CREATE_DEFAULT_ERROR_MODE
;
355 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
356 flags
, env
, dir
, &start
, &cp
->procinfo
))
359 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
361 /* Hack for Windows 95, which assigns large (ie negative) pids */
365 /* pid must fit in a Lisp_Int */
366 cp
->pid
= cp
->pid
& INTMASK
;
373 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
377 /* create_child doesn't know what emacs' file handle will be for waiting
378 on output from the child, so we need to make this additional call
379 to register the handle with the process
380 This way the select emulator knows how to match file handles with
381 entries in child_procs. */
383 register_child (int pid
, int fd
)
387 cp
= find_child_pid (pid
);
390 DebPrint (("register_child unable to find pid %lu\n", pid
));
395 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
400 /* thread is initially blocked until select is called; set status so
401 that select will release thread */
402 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
404 /* attach child_process to fd_info */
405 if (fd_info
[fd
].cp
!= NULL
)
407 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
414 /* When a process dies its pipe will break so the reader thread will
415 signal failure to the select emulator.
416 The select emulator then calls this routine to clean up.
417 Since the thread signaled failure we can assume it is exiting. */
419 reap_subprocess (child_process
*cp
)
421 if (cp
->procinfo
.hProcess
)
423 /* Reap the process */
425 /* Process should have already died before we are called. */
426 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
427 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
429 CloseHandle (cp
->procinfo
.hProcess
);
430 cp
->procinfo
.hProcess
= NULL
;
431 CloseHandle (cp
->procinfo
.hThread
);
432 cp
->procinfo
.hThread
= NULL
;
435 /* For asynchronous children, the child_proc resources will be freed
436 when the last pipe read descriptor is closed; for synchronous
437 children, we must explicitly free the resources now because
438 register_child has not been called. */
443 /* Wait for any of our existing child processes to die
444 When it does, close its handle
445 Return the pid and fill in the status if non-NULL. */
448 sys_wait (int *status
)
450 DWORD active
, retval
;
453 child_process
*cp
, *cps
[MAX_CHILDREN
];
454 HANDLE wait_hnd
[MAX_CHILDREN
];
457 if (dead_child
!= NULL
)
459 /* We want to wait for a specific child */
460 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
461 cps
[nh
] = dead_child
;
462 if (!wait_hnd
[nh
]) abort ();
469 for (cp
= child_procs
+ (child_proc_count
-1); cp
>= child_procs
; cp
--)
470 /* some child_procs might be sockets; ignore them */
471 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
472 && (cp
->fd
< 0 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0))
474 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
482 /* Nothing to wait on, so fail */
489 /* Check for quit about once a second. */
491 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
492 } while (active
== WAIT_TIMEOUT
);
494 if (active
== WAIT_FAILED
)
499 else if (active
>= WAIT_OBJECT_0
500 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
502 active
-= WAIT_OBJECT_0
;
504 else if (active
>= WAIT_ABANDONED_0
505 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
507 active
-= WAIT_ABANDONED_0
;
513 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
515 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
519 if (retval
== STILL_ACTIVE
)
521 /* Should never happen */
522 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
527 /* Massage the exit code from the process to match the format expected
528 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
529 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
531 if (retval
== STATUS_CONTROL_C_EXIT
)
539 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
546 else if (synch_process_alive
)
548 synch_process_alive
= 0;
550 /* Report the status of the synchronous process. */
551 if (WIFEXITED (retval
))
552 synch_process_retcode
= WRETCODE (retval
);
553 else if (WIFSIGNALED (retval
))
555 int code
= WTERMSIG (retval
);
558 synchronize_system_messages_locale ();
559 signame
= strsignal (code
);
564 synch_process_death
= signame
;
567 reap_subprocess (cp
);
570 reap_subprocess (cp
);
575 /* Old versions of w32api headers don't have separate 32-bit and
576 64-bit defines, but the one they have matches the 32-bit variety. */
577 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
578 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
579 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
583 w32_executable_type (char * filename
,
588 file_data executable
;
591 /* Default values in case we can't tell for sure. */
593 *is_cygnus_app
= FALSE
;
596 if (!open_input_file (&executable
, filename
))
599 p
= strrchr (filename
, '.');
601 /* We can only identify DOS .com programs from the extension. */
602 if (p
&& xstrcasecmp (p
, ".com") == 0)
604 else if (p
&& (xstrcasecmp (p
, ".bat") == 0
605 || xstrcasecmp (p
, ".cmd") == 0))
607 /* A DOS shell script - it appears that CreateProcess is happy to
608 accept this (somewhat surprisingly); presumably it looks at
609 COMSPEC to determine what executable to actually invoke.
610 Therefore, we have to do the same here as well. */
611 /* Actually, I think it uses the program association for that
612 extension, which is defined in the registry. */
613 p
= egetenv ("COMSPEC");
615 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
619 /* Look for DOS .exe signature - if found, we must also check that
620 it isn't really a 16- or 32-bit Windows exe, since both formats
621 start with a DOS program stub. Note that 16-bit Windows
622 executables use the OS/2 1.x format. */
624 IMAGE_DOS_HEADER
* dos_header
;
625 IMAGE_NT_HEADERS
* nt_header
;
627 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
628 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
631 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
633 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
635 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
638 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
639 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
643 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
645 IMAGE_DATA_DIRECTORY
*data_dir
= NULL
;
646 if (nt_header
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
648 /* Ensure we are using the 32 bit structure. */
649 IMAGE_OPTIONAL_HEADER32
*opt
650 = (IMAGE_OPTIONAL_HEADER32
*) &(nt_header
->OptionalHeader
);
651 data_dir
= opt
->DataDirectory
;
652 *is_gui_app
= (opt
->Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
654 /* MingW 3.12 has the required 64 bit structs, but in case older
655 versions don't, only check 64 bit exes if we know how. */
656 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
657 else if (nt_header
->OptionalHeader
.Magic
658 == IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
660 IMAGE_OPTIONAL_HEADER64
*opt
661 = (IMAGE_OPTIONAL_HEADER64
*) &(nt_header
->OptionalHeader
);
662 data_dir
= opt
->DataDirectory
;
663 *is_gui_app
= (opt
->Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
668 /* Look for cygwin.dll in DLL import list. */
669 IMAGE_DATA_DIRECTORY import_dir
=
670 data_dir
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
671 IMAGE_IMPORT_DESCRIPTOR
* imports
;
672 IMAGE_SECTION_HEADER
* section
;
674 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
675 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
,
678 for ( ; imports
->Name
; imports
++)
680 char * dllname
= RVA_TO_PTR (imports
->Name
, section
,
683 /* The exact name of the cygwin dll has changed with
684 various releases, but hopefully this will be reasonably
686 if (strncmp (dllname
, "cygwin", 6) == 0)
688 *is_cygnus_app
= TRUE
;
697 close_file_data (&executable
);
701 compare_env (const void *strp1
, const void *strp2
)
703 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
705 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
707 /* Sort order in command.com/cmd.exe is based on uppercasing
708 names, so do the same here. */
709 if (toupper (*str1
) > toupper (*str2
))
711 else if (toupper (*str1
) < toupper (*str2
))
716 if (*str1
== '=' && *str2
== '=')
718 else if (*str1
== '=')
725 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
741 qsort (new_envp
, num
, sizeof (char *), compare_env
);
746 /* When a new child process is created we need to register it in our list,
747 so intercept spawn requests. */
749 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
751 Lisp_Object program
, full
;
752 char *cmdline
, *env
, *parg
, **targ
;
756 int is_dos_app
, is_cygnus_app
, is_gui_app
;
759 /* We pass our process ID to our children by setting up an environment
760 variable in their environment. */
761 char ppid_env_var_buffer
[64];
762 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
763 /* These are the characters that cause an argument to need quoting.
764 Arguments with whitespace characters need quoting to prevent the
765 argument being split into two or more. Arguments with wildcards
766 are also quoted, for consistency with posix platforms, where wildcards
767 are not expanded if we run the program directly without a shell.
768 Some extra whitespace characters need quoting in Cygwin programs,
769 so this list is conditionally modified below. */
770 char *sepchars
= " \t*?";
772 /* We don't care about the other modes */
773 if (mode
!= _P_NOWAIT
)
779 /* Handle executable names without an executable suffix. */
780 program
= build_string (cmdname
);
781 if (NILP (Ffile_executable_p (program
)))
787 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, make_number (X_OK
));
797 /* make sure argv[0] and cmdname are both in DOS format */
798 cmdname
= SDATA (program
);
799 unixtodos_filename (cmdname
);
802 /* Determine whether program is a 16-bit DOS executable, or a w32
803 executable that is implicitly linked to the Cygnus dll (implying it
804 was compiled with the Cygnus GNU toolchain and hence relies on
805 cygwin.dll to parse the command line - we use this to decide how to
806 escape quote chars in command line args that must be quoted).
808 Also determine whether it is a GUI app, so that we don't hide its
809 initial window unless specifically requested. */
810 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
812 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
813 application to start it by specifying the helper app as cmdname,
814 while leaving the real app name as argv[0]. */
817 cmdname
= alloca (MAXPATHLEN
);
818 if (egetenv ("CMDPROXY"))
819 strcpy (cmdname
, egetenv ("CMDPROXY"));
822 strcpy (cmdname
, SDATA (Vinvocation_directory
));
823 strcat (cmdname
, "cmdproxy.exe");
825 unixtodos_filename (cmdname
);
828 /* we have to do some conjuring here to put argv and envp into the
829 form CreateProcess wants... argv needs to be a space separated/null
830 terminated list of parameters, and envp is a null
831 separated/double-null terminated list of parameters.
833 Additionally, zero-length args and args containing whitespace or
834 quote chars need to be wrapped in double quotes - for this to work,
835 embedded quotes need to be escaped as well. The aim is to ensure
836 the child process reconstructs the argv array we start with
837 exactly, so we treat quotes at the beginning and end of arguments
840 The w32 GNU-based library from Cygnus doubles quotes to escape
841 them, while MSVC uses backslash for escaping. (Actually the MSVC
842 startup code does attempt to recognize doubled quotes and accept
843 them, but gets it wrong and ends up requiring three quotes to get a
844 single embedded quote!) So by default we decide whether to use
845 quote or backslash as the escape character based on whether the
846 binary is apparently a Cygnus compiled app.
848 Note that using backslash to escape embedded quotes requires
849 additional special handling if an embedded quote is already
850 preceded by backslash, or if an arg requiring quoting ends with
851 backslash. In such cases, the run of escape characters needs to be
852 doubled. For consistency, we apply this special handling as long
853 as the escape character is not quote.
855 Since we have no idea how large argv and envp are likely to be we
856 figure out list lengths on the fly and allocate them. */
858 if (!NILP (Vw32_quote_process_args
))
861 /* Override escape char by binding w32-quote-process-args to
862 desired character, or use t for auto-selection. */
863 if (INTEGERP (Vw32_quote_process_args
))
864 escape_char
= XINT (Vw32_quote_process_args
);
866 escape_char
= is_cygnus_app
? '"' : '\\';
869 /* Cygwin apps needs quoting a bit more often. */
870 if (escape_char
== '"')
871 sepchars
= "\r\n\t\f '";
880 int escape_char_run
= 0;
886 if (escape_char
== '"' && *p
== '\\')
887 /* If it's a Cygwin app, \ needs to be escaped. */
891 /* allow for embedded quotes to be escaped */
894 /* handle the case where the embedded quote is already escaped */
895 if (escape_char_run
> 0)
897 /* To preserve the arg exactly, we need to double the
898 preceding escape characters (plus adding one to
899 escape the quote character itself). */
900 arglen
+= escape_char_run
;
903 else if (strchr (sepchars
, *p
) != NULL
)
908 if (*p
== escape_char
&& escape_char
!= '"')
916 /* handle the case where the arg ends with an escape char - we
917 must not let the enclosing quote be escaped. */
918 if (escape_char_run
> 0)
919 arglen
+= escape_char_run
;
921 arglen
+= strlen (*targ
++) + 1;
923 cmdline
= alloca (arglen
);
937 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
942 int escape_char_run
= 0;
948 last
= p
+ strlen (p
) - 1;
951 /* This version does not escape quotes if they occur at the
952 beginning or end of the arg - this could lead to incorrect
953 behavior when the arg itself represents a command line
954 containing quoted args. I believe this was originally done
955 as a hack to make some things work, before
956 `w32-quote-process-args' was added. */
959 if (*p
== '"' && p
> first
&& p
< last
)
960 *parg
++ = escape_char
; /* escape embedded quotes */
968 /* double preceding escape chars if any */
969 while (escape_char_run
> 0)
971 *parg
++ = escape_char
;
974 /* escape all quote chars, even at beginning or end */
975 *parg
++ = escape_char
;
977 else if (escape_char
== '"' && *p
== '\\')
981 if (*p
== escape_char
&& escape_char
!= '"')
986 /* double escape chars before enclosing quote */
987 while (escape_char_run
> 0)
989 *parg
++ = escape_char
;
997 strcpy (parg
, *targ
);
998 parg
+= strlen (*targ
);
1008 numenv
= 1; /* for end null */
1011 arglen
+= strlen (*targ
++) + 1;
1014 /* extra env vars... */
1015 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
1016 GetCurrentProcessId ());
1017 arglen
+= strlen (ppid_env_var_buffer
) + 1;
1020 /* merge env passed in and extra env into one, and sort it. */
1021 targ
= (char **) alloca (numenv
* sizeof (char *));
1022 merge_and_sort_env (envp
, extra_env
, targ
);
1024 /* concatenate env entries. */
1025 env
= alloca (arglen
);
1029 strcpy (parg
, *targ
);
1030 parg
+= strlen (*targ
++);
1043 /* Now create the process. */
1044 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1054 /* Emulate the select call
1055 Wait for available input on any of the given rfds, or timeout if
1056 a timeout is given and no input is detected
1057 wfds and efds are not supported and must be NULL.
1059 For simplicity, we detect the death of child processes here and
1060 synchronously call the SIGCHLD handler. Since it is possible for
1061 children to be created without a corresponding pipe handle from which
1062 to read output, we wait separately on the process handles as well as
1063 the char_avail events for each process pipe. We only call
1064 wait/reap_process when the process actually terminates.
1066 To reduce the number of places in which Emacs can be hung such that
1067 C-g is not able to interrupt it, we always wait on interrupt_handle
1068 (which is signaled by the input thread when C-g is detected). If we
1069 detect that we were woken up by C-g, we return -1 with errno set to
1070 EINTR as on Unix. */
1072 /* From w32console.c */
1073 extern HANDLE keyboard_handle
;
1075 /* From w32xfns.c */
1076 extern HANDLE interrupt_handle
;
1078 /* From process.c */
1079 extern int proc_buffered_char
[];
1082 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1083 EMACS_TIME
*timeout
, void *ignored
)
1086 DWORD timeout_ms
, start_time
;
1089 child_process
*cp
, *cps
[MAX_CHILDREN
];
1090 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1091 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1094 timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_nsec
/ 1000000) : INFINITE
;
1096 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1097 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1103 /* Otherwise, we only handle rfds, so fail otherwise. */
1104 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1114 /* Always wait on interrupt_handle, to detect C-g (quit). */
1115 wait_hnd
[0] = interrupt_handle
;
1118 /* Build a list of pipe handles to wait on. */
1120 for (i
= 0; i
< nfds
; i
++)
1121 if (FD_ISSET (i
, &orfds
))
1125 if (keyboard_handle
)
1127 /* Handle stdin specially */
1128 wait_hnd
[nh
] = keyboard_handle
;
1133 /* Check for any emacs-generated input in the queue since
1134 it won't be detected in the wait */
1135 if (detect_input_pending ())
1143 /* Child process and socket input */
1147 int current_status
= cp
->status
;
1149 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1151 /* Tell reader thread which file handle to use. */
1153 /* Wake up the reader thread for this process */
1154 cp
->status
= STATUS_READ_READY
;
1155 if (!SetEvent (cp
->char_consumed
))
1156 DebPrint (("nt_select.SetEvent failed with "
1157 "%lu for fd %ld\n", GetLastError (), i
));
1160 #ifdef CHECK_INTERLOCK
1161 /* slightly crude cross-checking of interlock between threads */
1163 current_status
= cp
->status
;
1164 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1166 /* char_avail has been signaled, so status (which may
1167 have changed) should indicate read has completed
1168 but has not been acknowledged. */
1169 current_status
= cp
->status
;
1170 if (current_status
!= STATUS_READ_SUCCEEDED
1171 && current_status
!= STATUS_READ_FAILED
)
1172 DebPrint (("char_avail set, but read not completed: status %d\n",
1177 /* char_avail has not been signaled, so status should
1178 indicate that read is in progress; small possibility
1179 that read has completed but event wasn't yet signaled
1180 when we tested it (because a context switch occurred
1181 or if running on separate CPUs). */
1182 if (current_status
!= STATUS_READ_READY
1183 && current_status
!= STATUS_READ_IN_PROGRESS
1184 && current_status
!= STATUS_READ_SUCCEEDED
1185 && current_status
!= STATUS_READ_FAILED
)
1186 DebPrint (("char_avail reset, but read status is bad: %d\n",
1190 wait_hnd
[nh
] = cp
->char_avail
;
1192 if (!wait_hnd
[nh
]) abort ();
1195 DebPrint (("select waiting on child %d fd %d\n",
1196 cp
-child_procs
, i
));
1201 /* Unable to find something to wait on for this fd, skip */
1203 /* Note that this is not a fatal error, and can in fact
1204 happen in unusual circumstances. Specifically, if
1205 sys_spawnve fails, eg. because the program doesn't
1206 exist, and debug-on-error is t so Fsignal invokes a
1207 nested input loop, then the process output pipe is
1208 still included in input_wait_mask with no child_proc
1209 associated with it. (It is removed when the debugger
1210 exits the nested input loop and the error is thrown.) */
1212 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1218 /* Add handles of child processes. */
1220 for (cp
= child_procs
+ (child_proc_count
-1); cp
>= child_procs
; cp
--)
1221 /* Some child_procs might be sockets; ignore them. Also some
1222 children may have died already, but we haven't finished reading
1223 the process output; ignore them too. */
1224 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1226 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1227 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1230 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1235 /* Nothing to look for, so we didn't find anything */
1243 start_time
= GetTickCount ();
1245 /* Wait for input or child death to be signaled. If user input is
1246 allowed, then also accept window messages. */
1247 if (FD_ISSET (0, &orfds
))
1248 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1251 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1253 if (active
== WAIT_FAILED
)
1255 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1256 nh
+ nc
, timeout_ms
, GetLastError ()));
1257 /* don't return EBADF - this causes wait_reading_process_output to
1258 abort; WAIT_FAILED is returned when single-stepping under
1259 Windows 95 after switching thread focus in debugger, and
1260 possibly at other times. */
1264 else if (active
== WAIT_TIMEOUT
)
1268 else if (active
>= WAIT_OBJECT_0
1269 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1271 active
-= WAIT_OBJECT_0
;
1273 else if (active
>= WAIT_ABANDONED_0
1274 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1276 active
-= WAIT_ABANDONED_0
;
1281 /* Loop over all handles after active (now officially documented as
1282 being the first signaled handle in the array). We do this to
1283 ensure fairness, so that all channels with data available will be
1284 processed - otherwise higher numbered channels could be starved. */
1287 if (active
== nh
+ nc
)
1289 /* There are messages in the lisp thread's queue; we must
1290 drain the queue now to ensure they are processed promptly,
1291 because if we don't do so, we will not be woken again until
1292 further messages arrive.
1294 NB. If ever we allow window message procedures to callback
1295 into lisp, we will need to ensure messages are dispatched
1296 at a safe time for lisp code to be run (*), and we may also
1297 want to provide some hooks in the dispatch loop to cater
1298 for modeless dialogs created by lisp (ie. to register
1299 window handles to pass to IsDialogMessage).
1301 (*) Note that MsgWaitForMultipleObjects above is an
1302 internal dispatch point for messages that are sent to
1303 windows created by this thread. */
1304 drain_message_queue ();
1306 else if (active
>= nh
)
1308 cp
= cps
[active
- nh
];
1310 /* We cannot always signal SIGCHLD immediately; if we have not
1311 finished reading the process output, we must delay sending
1312 SIGCHLD until we do. */
1314 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1315 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1316 /* SIG_DFL for SIGCHLD is ignore */
1317 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1318 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1321 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1325 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1329 else if (fdindex
[active
] == -1)
1331 /* Quit (C-g) was detected. */
1335 else if (fdindex
[active
] == 0)
1337 /* Keyboard input available */
1343 /* must be a socket or pipe - read ahead should have
1344 completed, either succeeding or failing. */
1345 FD_SET (fdindex
[active
], rfds
);
1349 /* Even though wait_reading_process_output only reads from at most
1350 one channel, we must process all channels here so that we reap
1351 all children that have died. */
1352 while (++active
< nh
+ nc
)
1353 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1355 } while (active
< nh
+ nc
);
1357 /* If no input has arrived and timeout hasn't expired, wait again. */
1360 DWORD elapsed
= GetTickCount () - start_time
;
1362 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1364 if (timeout_ms
!= INFINITE
)
1365 timeout_ms
-= elapsed
;
1366 goto count_children
;
1373 /* Substitute for certain kill () operations */
1375 static BOOL CALLBACK
1376 find_child_console (HWND hwnd
, LPARAM arg
)
1378 child_process
* cp
= (child_process
*) arg
;
1382 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1383 if (process_id
== cp
->procinfo
.dwProcessId
)
1385 char window_class
[32];
1387 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1388 if (strcmp (window_class
,
1389 (os_subtype
== OS_WIN95
)
1391 : "ConsoleWindowClass") == 0)
1402 sys_kill (int pid
, int sig
)
1406 int need_to_free
= 0;
1409 /* Only handle signals that will result in the process dying */
1410 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1416 cp
= find_child_pid (pid
);
1419 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1420 if (proc_hand
== NULL
)
1429 proc_hand
= cp
->procinfo
.hProcess
;
1430 pid
= cp
->procinfo
.dwProcessId
;
1432 /* Try to locate console window for process. */
1433 EnumWindows (find_child_console
, (LPARAM
) cp
);
1436 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1438 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1440 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1441 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1442 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1443 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1444 HWND foreground_window
;
1446 if (break_scan_code
== 0)
1448 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1449 vk_break_code
= 'C';
1450 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1453 foreground_window
= GetForegroundWindow ();
1454 if (foreground_window
)
1456 /* NT 5.0, and apparently also Windows 98, will not allow
1457 a Window to be set to foreground directly without the
1458 user's involvement. The workaround is to attach
1459 ourselves to the thread that owns the foreground
1460 window, since that is the only thread that can set the
1461 foreground window. */
1462 DWORD foreground_thread
, child_thread
;
1464 GetWindowThreadProcessId (foreground_window
, NULL
);
1465 if (foreground_thread
== GetCurrentThreadId ()
1466 || !AttachThreadInput (GetCurrentThreadId (),
1467 foreground_thread
, TRUE
))
1468 foreground_thread
= 0;
1470 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1471 if (child_thread
== GetCurrentThreadId ()
1472 || !AttachThreadInput (GetCurrentThreadId (),
1473 child_thread
, TRUE
))
1476 /* Set the foreground window to the child. */
1477 if (SetForegroundWindow (cp
->hwnd
))
1479 /* Generate keystrokes as if user had typed Ctrl-Break or
1481 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1482 keybd_event (vk_break_code
, break_scan_code
,
1483 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1484 keybd_event (vk_break_code
, break_scan_code
,
1485 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1486 | KEYEVENTF_KEYUP
, 0);
1487 keybd_event (VK_CONTROL
, control_scan_code
,
1488 KEYEVENTF_KEYUP
, 0);
1490 /* Sleep for a bit to give time for Emacs frame to respond
1491 to focus change events (if Emacs was active app). */
1494 SetForegroundWindow (foreground_window
);
1496 /* Detach from the foreground and child threads now that
1497 the foreground switching is over. */
1498 if (foreground_thread
)
1499 AttachThreadInput (GetCurrentThreadId (),
1500 foreground_thread
, FALSE
);
1502 AttachThreadInput (GetCurrentThreadId (),
1503 child_thread
, FALSE
);
1506 /* Ctrl-Break is NT equivalent of SIGINT. */
1507 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1509 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1510 "for pid %lu\n", GetLastError (), pid
));
1517 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1520 if (os_subtype
== OS_WIN95
)
1523 Another possibility is to try terminating the VDM out-right by
1524 calling the Shell VxD (id 0x17) V86 interface, function #4
1525 "SHELL_Destroy_VM", ie.
1531 First need to determine the current VM handle, and then arrange for
1532 the shellapi call to be made from the system vm (by using
1533 Switch_VM_and_callback).
1535 Could try to invoke DestroyVM through CallVxD.
1539 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1540 to hang when cmdproxy is used in conjunction with
1541 command.com for an interactive shell. Posting
1542 WM_CLOSE pops up a dialog that, when Yes is selected,
1543 does the same thing. TerminateProcess is also less
1544 than ideal in that subprocesses tend to stick around
1545 until the machine is shutdown, but at least it
1546 doesn't freeze the 16-bit subsystem. */
1547 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1549 if (!TerminateProcess (proc_hand
, 0xff))
1551 DebPrint (("sys_kill.TerminateProcess returned %d "
1552 "for pid %lu\n", GetLastError (), pid
));
1559 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1561 /* Kill the process. On W32 this doesn't kill child processes
1562 so it doesn't work very well for shells which is why it's not
1563 used in every case. */
1564 else if (!TerminateProcess (proc_hand
, 0xff))
1566 DebPrint (("sys_kill.TerminateProcess returned %d "
1567 "for pid %lu\n", GetLastError (), pid
));
1574 CloseHandle (proc_hand
);
1579 /* The following two routines are used to manipulate stdin, stdout, and
1580 stderr of our child processes.
1582 Assuming that in, out, and err are *not* inheritable, we make them
1583 stdin, stdout, and stderr of the child as follows:
1585 - Save the parent's current standard handles.
1586 - Set the std handles to inheritable duplicates of the ones being passed in.
1587 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1588 NT file handle for a crt file descriptor.)
1589 - Spawn the child, which inherits in, out, and err as stdin,
1590 stdout, and stderr. (see Spawnve)
1591 - Close the std handles passed to the child.
1592 - Reset the parent's standard handles to the saved handles.
1593 (see reset_standard_handles)
1594 We assume that the caller closes in, out, and err after calling us. */
1597 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1600 HANDLE newstdin
, newstdout
, newstderr
;
1602 parent
= GetCurrentProcess ();
1604 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1605 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1606 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1608 /* make inheritable copies of the new handles */
1609 if (!DuplicateHandle (parent
,
1610 (HANDLE
) _get_osfhandle (in
),
1615 DUPLICATE_SAME_ACCESS
))
1616 report_file_error ("Duplicating input handle for child", Qnil
);
1618 if (!DuplicateHandle (parent
,
1619 (HANDLE
) _get_osfhandle (out
),
1624 DUPLICATE_SAME_ACCESS
))
1625 report_file_error ("Duplicating output handle for child", Qnil
);
1627 if (!DuplicateHandle (parent
,
1628 (HANDLE
) _get_osfhandle (err
),
1633 DUPLICATE_SAME_ACCESS
))
1634 report_file_error ("Duplicating error handle for child", Qnil
);
1636 /* and store them as our std handles */
1637 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1638 report_file_error ("Changing stdin handle", Qnil
);
1640 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1641 report_file_error ("Changing stdout handle", Qnil
);
1643 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1644 report_file_error ("Changing stderr handle", Qnil
);
1648 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1650 /* close the duplicated handles passed to the child */
1651 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1652 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1653 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1655 /* now restore parent's saved std handles */
1656 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1657 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1658 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1662 set_process_dir (char * dir
)
1667 /* To avoid problems with winsock implementations that work over dial-up
1668 connections causing or requiring a connection to exist while Emacs is
1669 running, Emacs no longer automatically loads winsock on startup if it
1670 is present. Instead, it will be loaded when open-network-stream is
1673 To allow full control over when winsock is loaded, we provide these
1674 two functions to dynamically load and unload winsock. This allows
1675 dial-up users to only be connected when they actually need to use
1679 extern HANDLE winsock_lib
;
1680 extern BOOL
term_winsock (void);
1681 extern BOOL
init_winsock (int load_now
);
1683 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1684 doc
: /* Test for presence of the Windows socket library `winsock'.
1685 Returns non-nil if winsock support is present, nil otherwise.
1687 If the optional argument LOAD-NOW is non-nil, the winsock library is
1688 also loaded immediately if not already loaded. If winsock is loaded,
1689 the winsock local hostname is returned (since this may be different from
1690 the value of `system-name' and should supplant it), otherwise t is
1691 returned to indicate winsock support is present. */)
1692 (Lisp_Object load_now
)
1696 have_winsock
= init_winsock (!NILP (load_now
));
1699 if (winsock_lib
!= NULL
)
1701 /* Return new value for system-name. The best way to do this
1702 is to call init_system_name, saving and restoring the
1703 original value to avoid side-effects. */
1704 Lisp_Object orig_hostname
= Vsystem_name
;
1705 Lisp_Object hostname
;
1707 init_system_name ();
1708 hostname
= Vsystem_name
;
1709 Vsystem_name
= orig_hostname
;
1717 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1719 doc
: /* Unload the Windows socket library `winsock' if loaded.
1720 This is provided to allow dial-up socket connections to be disconnected
1721 when no longer needed. Returns nil without unloading winsock if any
1722 socket connections still exist. */)
1725 return term_winsock () ? Qt
: Qnil
;
1729 /* Some miscellaneous functions that are Windows specific, but not GUI
1730 specific (ie. are applicable in terminal or batch mode as well). */
1732 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1733 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1734 If FILENAME does not exist, return nil.
1735 All path elements in FILENAME are converted to their short names. */)
1736 (Lisp_Object filename
)
1738 char shortname
[MAX_PATH
];
1740 CHECK_STRING (filename
);
1742 /* first expand it. */
1743 filename
= Fexpand_file_name (filename
, Qnil
);
1745 /* luckily, this returns the short version of each element in the path. */
1746 if (GetShortPathName (SDATA (ENCODE_FILE (filename
)), shortname
, MAX_PATH
) == 0)
1749 dostounix_filename (shortname
);
1751 return build_string (shortname
);
1755 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1757 doc
: /* Return the long file name version of the full path of FILENAME.
1758 If FILENAME does not exist, return nil.
1759 All path elements in FILENAME are converted to their long names. */)
1760 (Lisp_Object filename
)
1762 char longname
[ MAX_PATH
];
1765 CHECK_STRING (filename
);
1767 if (SBYTES (filename
) == 2
1768 && *(SDATA (filename
) + 1) == ':')
1771 /* first expand it. */
1772 filename
= Fexpand_file_name (filename
, Qnil
);
1774 if (!w32_get_long_filename (SDATA (ENCODE_FILE (filename
)), longname
, MAX_PATH
))
1777 dostounix_filename (longname
);
1779 /* If we were passed only a drive, make sure that a slash is not appended
1780 for consistency with directories. Allow for drive mapping via SUBST
1781 in case expand-file-name is ever changed to expand those. */
1782 if (drive_only
&& longname
[1] == ':' && longname
[2] == '/' && !longname
[3])
1785 return DECODE_FILE (build_string (longname
));
1788 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1789 Sw32_set_process_priority
, 2, 2, 0,
1790 doc
: /* Set the priority of PROCESS to PRIORITY.
1791 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1792 priority of the process whose pid is PROCESS is changed.
1793 PRIORITY should be one of the symbols high, normal, or low;
1794 any other symbol will be interpreted as normal.
1796 If successful, the return value is t, otherwise nil. */)
1797 (Lisp_Object process
, Lisp_Object priority
)
1799 HANDLE proc_handle
= GetCurrentProcess ();
1800 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1801 Lisp_Object result
= Qnil
;
1803 CHECK_SYMBOL (priority
);
1805 if (!NILP (process
))
1810 CHECK_NUMBER (process
);
1812 /* Allow pid to be an internally generated one, or one obtained
1813 externally. This is necessary because real pids on Win95 are
1816 pid
= XINT (process
);
1817 cp
= find_child_pid (pid
);
1819 pid
= cp
->procinfo
.dwProcessId
;
1821 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1824 if (EQ (priority
, Qhigh
))
1825 priority_class
= HIGH_PRIORITY_CLASS
;
1826 else if (EQ (priority
, Qlow
))
1827 priority_class
= IDLE_PRIORITY_CLASS
;
1829 if (proc_handle
!= NULL
)
1831 if (SetPriorityClass (proc_handle
, priority_class
))
1833 if (!NILP (process
))
1834 CloseHandle (proc_handle
);
1840 #ifdef HAVE_LANGINFO_CODESET
1841 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1843 nl_langinfo (nl_item item
)
1845 /* Conversion of Posix item numbers to their Windows equivalents. */
1846 static const LCTYPE w32item
[] = {
1847 LOCALE_IDEFAULTANSICODEPAGE
,
1848 LOCALE_SDAYNAME1
, LOCALE_SDAYNAME2
, LOCALE_SDAYNAME3
,
1849 LOCALE_SDAYNAME4
, LOCALE_SDAYNAME5
, LOCALE_SDAYNAME6
, LOCALE_SDAYNAME7
,
1850 LOCALE_SMONTHNAME1
, LOCALE_SMONTHNAME2
, LOCALE_SMONTHNAME3
,
1851 LOCALE_SMONTHNAME4
, LOCALE_SMONTHNAME5
, LOCALE_SMONTHNAME6
,
1852 LOCALE_SMONTHNAME7
, LOCALE_SMONTHNAME8
, LOCALE_SMONTHNAME9
,
1853 LOCALE_SMONTHNAME10
, LOCALE_SMONTHNAME11
, LOCALE_SMONTHNAME12
1856 static char *nl_langinfo_buf
= NULL
;
1857 static int nl_langinfo_len
= 0;
1859 if (nl_langinfo_len
<= 0)
1860 nl_langinfo_buf
= xmalloc (nl_langinfo_len
= 1);
1862 if (item
< 0 || item
>= _NL_NUM
)
1863 nl_langinfo_buf
[0] = 0;
1866 LCID cloc
= GetThreadLocale ();
1867 int need_len
= GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1871 nl_langinfo_buf
[0] = 0;
1874 if (item
== CODESET
)
1876 need_len
+= 2; /* for the "cp" prefix */
1877 if (need_len
< 8) /* for the case we call GetACP */
1880 if (nl_langinfo_len
<= need_len
)
1881 nl_langinfo_buf
= xrealloc (nl_langinfo_buf
,
1882 nl_langinfo_len
= need_len
);
1883 if (!GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1884 nl_langinfo_buf
, nl_langinfo_len
))
1885 nl_langinfo_buf
[0] = 0;
1886 else if (item
== CODESET
)
1888 if (strcmp (nl_langinfo_buf
, "0") == 0 /* CP_ACP */
1889 || strcmp (nl_langinfo_buf
, "1") == 0) /* CP_OEMCP */
1890 sprintf (nl_langinfo_buf
, "cp%u", GetACP ());
1893 memmove (nl_langinfo_buf
+ 2, nl_langinfo_buf
,
1894 strlen (nl_langinfo_buf
) + 1);
1895 nl_langinfo_buf
[0] = 'c';
1896 nl_langinfo_buf
[1] = 'p';
1901 return nl_langinfo_buf
;
1903 #endif /* HAVE_LANGINFO_CODESET */
1905 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1906 Sw32_get_locale_info
, 1, 2, 0,
1907 doc
: /* Return information about the Windows locale LCID.
1908 By default, return a three letter locale code which encodes the default
1909 language as the first two characters, and the country or regional variant
1910 as the third letter. For example, ENU refers to `English (United States)',
1911 while ENC means `English (Canadian)'.
1913 If the optional argument LONGFORM is t, the long form of the locale
1914 name is returned, e.g. `English (United States)' instead; if LONGFORM
1915 is a number, it is interpreted as an LCTYPE constant and the corresponding
1916 locale information is returned.
1918 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1919 (Lisp_Object lcid
, Lisp_Object longform
)
1923 char abbrev_name
[32] = { 0 };
1924 char full_name
[256] = { 0 };
1926 CHECK_NUMBER (lcid
);
1928 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1931 if (NILP (longform
))
1933 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1934 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1935 abbrev_name
, sizeof (abbrev_name
));
1937 return build_string (abbrev_name
);
1939 else if (EQ (longform
, Qt
))
1941 got_full
= GetLocaleInfo (XINT (lcid
),
1942 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1943 full_name
, sizeof (full_name
));
1945 return DECODE_SYSTEM (build_string (full_name
));
1947 else if (NUMBERP (longform
))
1949 got_full
= GetLocaleInfo (XINT (lcid
),
1951 full_name
, sizeof (full_name
));
1952 /* GetLocaleInfo's return value includes the terminating null
1953 character, when the returned information is a string, whereas
1954 make_unibyte_string needs the string length without the
1955 terminating null. */
1957 return make_unibyte_string (full_name
, got_full
- 1);
1964 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
1965 Sw32_get_current_locale_id
, 0, 0, 0,
1966 doc
: /* Return Windows locale id for current locale setting.
1967 This is a numerical value; use `w32-get-locale-info' to convert to a
1968 human-readable form. */)
1971 return make_number (GetThreadLocale ());
1975 int_from_hex (char * s
)
1978 static char hex
[] = "0123456789abcdefABCDEF";
1981 while (*s
&& (p
= strchr (hex
, *s
)) != NULL
)
1983 unsigned digit
= p
- hex
;
1986 val
= val
* 16 + digit
;
1992 /* We need to build a global list, since the EnumSystemLocale callback
1993 function isn't given a context pointer. */
1994 Lisp_Object Vw32_valid_locale_ids
;
1996 static BOOL CALLBACK
1997 enum_locale_fn (LPTSTR localeNum
)
1999 DWORD id
= int_from_hex (localeNum
);
2000 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
2004 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
2005 Sw32_get_valid_locale_ids
, 0, 0, 0,
2006 doc
: /* Return list of all valid Windows locale ids.
2007 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2008 human-readable form. */)
2011 Vw32_valid_locale_ids
= Qnil
;
2013 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
2015 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
2016 return Vw32_valid_locale_ids
;
2020 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
2021 doc
: /* Return Windows locale id for default locale setting.
2022 By default, the system default locale setting is returned; if the optional
2023 parameter USERP is non-nil, the user default locale setting is returned.
2024 This is a numerical value; use `w32-get-locale-info' to convert to a
2025 human-readable form. */)
2029 return make_number (GetSystemDefaultLCID ());
2030 return make_number (GetUserDefaultLCID ());
2034 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
2035 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
2036 If successful, the new locale id is returned, otherwise nil. */)
2039 CHECK_NUMBER (lcid
);
2041 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
2044 if (!SetThreadLocale (XINT (lcid
)))
2047 /* Need to set input thread locale if present. */
2048 if (dwWindowsThreadId
)
2049 /* Reply is not needed. */
2050 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
2052 return make_number (GetThreadLocale ());
2056 /* We need to build a global list, since the EnumCodePages callback
2057 function isn't given a context pointer. */
2058 Lisp_Object Vw32_valid_codepages
;
2060 static BOOL CALLBACK
2061 enum_codepage_fn (LPTSTR codepageNum
)
2063 DWORD id
= atoi (codepageNum
);
2064 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
2068 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
2069 Sw32_get_valid_codepages
, 0, 0, 0,
2070 doc
: /* Return list of all valid Windows codepages. */)
2073 Vw32_valid_codepages
= Qnil
;
2075 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
2077 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
2078 return Vw32_valid_codepages
;
2082 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
2083 Sw32_get_console_codepage
, 0, 0, 0,
2084 doc
: /* Return current Windows codepage for console input. */)
2087 return make_number (GetConsoleCP ());
2091 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
2092 Sw32_set_console_codepage
, 1, 1, 0,
2093 doc
: /* Make Windows codepage CP be the codepage for Emacs tty keyboard input.
2094 This codepage setting affects keyboard input in tty mode.
2095 If successful, the new CP is returned, otherwise nil. */)
2100 if (!IsValidCodePage (XINT (cp
)))
2103 if (!SetConsoleCP (XINT (cp
)))
2106 return make_number (GetConsoleCP ());
2110 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2111 Sw32_get_console_output_codepage
, 0, 0, 0,
2112 doc
: /* Return current Windows codepage for console output. */)
2115 return make_number (GetConsoleOutputCP ());
2119 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2120 Sw32_set_console_output_codepage
, 1, 1, 0,
2121 doc
: /* Make Windows codepage CP be the codepage for Emacs console output.
2122 This codepage setting affects display in tty mode.
2123 If successful, the new CP is returned, otherwise nil. */)
2128 if (!IsValidCodePage (XINT (cp
)))
2131 if (!SetConsoleOutputCP (XINT (cp
)))
2134 return make_number (GetConsoleOutputCP ());
2138 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2139 Sw32_get_codepage_charset
, 1, 1, 0,
2140 doc
: /* Return charset ID corresponding to codepage CP.
2141 Returns nil if the codepage is not valid. */)
2148 if (!IsValidCodePage (XINT (cp
)))
2151 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2152 return make_number (info
.ciCharset
);
2158 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2159 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2160 doc
: /* Return list of Windows keyboard languages and layouts.
2161 The return value is a list of pairs of language id and layout id. */)
2164 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2165 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2166 Lisp_Object obj
= Qnil
;
2168 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2170 while (--num_layouts
>= 0)
2172 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2174 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2175 make_number ((kl
>> 16) & 0xffff)),
2184 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2185 Sw32_get_keyboard_layout
, 0, 0, 0,
2186 doc
: /* Return current Windows keyboard language and layout.
2187 The return value is the cons of the language id and the layout id. */)
2190 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2192 return Fcons (make_number (kl
& 0xffff),
2193 make_number ((kl
>> 16) & 0xffff));
2197 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2198 Sw32_set_keyboard_layout
, 1, 1, 0,
2199 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2200 The keyboard layout setting affects interpretation of keyboard input.
2201 If successful, the new layout id is returned, otherwise nil. */)
2202 (Lisp_Object layout
)
2206 CHECK_CONS (layout
);
2207 CHECK_NUMBER_CAR (layout
);
2208 CHECK_NUMBER_CDR (layout
);
2210 kl
= (XINT (XCAR (layout
)) & 0xffff)
2211 | (XINT (XCDR (layout
)) << 16);
2213 /* Synchronize layout with input thread. */
2214 if (dwWindowsThreadId
)
2216 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2220 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2222 if (msg
.wParam
== 0)
2226 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2229 return Fw32_get_keyboard_layout ();
2234 syms_of_ntproc (void)
2236 DEFSYM (Qhigh
, "high");
2237 DEFSYM (Qlow
, "low");
2239 defsubr (&Sw32_has_winsock
);
2240 defsubr (&Sw32_unload_winsock
);
2242 defsubr (&Sw32_short_file_name
);
2243 defsubr (&Sw32_long_file_name
);
2244 defsubr (&Sw32_set_process_priority
);
2245 defsubr (&Sw32_get_locale_info
);
2246 defsubr (&Sw32_get_current_locale_id
);
2247 defsubr (&Sw32_get_default_locale_id
);
2248 defsubr (&Sw32_get_valid_locale_ids
);
2249 defsubr (&Sw32_set_current_locale
);
2251 defsubr (&Sw32_get_console_codepage
);
2252 defsubr (&Sw32_set_console_codepage
);
2253 defsubr (&Sw32_get_console_output_codepage
);
2254 defsubr (&Sw32_set_console_output_codepage
);
2255 defsubr (&Sw32_get_valid_codepages
);
2256 defsubr (&Sw32_get_codepage_charset
);
2258 defsubr (&Sw32_get_valid_keyboard_layouts
);
2259 defsubr (&Sw32_get_keyboard_layout
);
2260 defsubr (&Sw32_set_keyboard_layout
);
2262 DEFVAR_LISP ("w32-quote-process-args", Vw32_quote_process_args
,
2263 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2264 Because Windows does not directly pass argv arrays to child processes,
2265 programs have to reconstruct the argv array by parsing the command
2266 line string. For an argument to contain a space, it must be enclosed
2267 in double quotes or it will be parsed as multiple arguments.
2269 If the value is a character, that character will be used to escape any
2270 quote characters that appear, otherwise a suitable escape character
2271 will be chosen based on the type of the program. */);
2272 Vw32_quote_process_args
= Qt
;
2274 DEFVAR_LISP ("w32-start-process-show-window",
2275 Vw32_start_process_show_window
,
2276 doc
: /* When nil, new child processes hide their windows.
2277 When non-nil, they show their window in the method of their choice.
2278 This variable doesn't affect GUI applications, which will never be hidden. */);
2279 Vw32_start_process_show_window
= Qnil
;
2281 DEFVAR_LISP ("w32-start-process-share-console",
2282 Vw32_start_process_share_console
,
2283 doc
: /* When nil, new child processes are given a new console.
2284 When non-nil, they share the Emacs console; this has the limitation of
2285 allowing only one DOS subprocess to run at a time (whether started directly
2286 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2287 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2288 otherwise respond to interrupts from Emacs. */);
2289 Vw32_start_process_share_console
= Qnil
;
2291 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2292 Vw32_start_process_inherit_error_mode
,
2293 doc
: /* When nil, new child processes revert to the default error mode.
2294 When non-nil, they inherit their error mode setting from Emacs, which stops
2295 them blocking when trying to access unmounted drives etc. */);
2296 Vw32_start_process_inherit_error_mode
= Qt
;
2298 DEFVAR_INT ("w32-pipe-read-delay", w32_pipe_read_delay
,
2299 doc
: /* Forced delay before reading subprocess output.
2300 This is done to improve the buffering of subprocess output, by
2301 avoiding the inefficiency of frequently reading small amounts of data.
2303 If positive, the value is the number of milliseconds to sleep before
2304 reading the subprocess output. If negative, the magnitude is the number
2305 of time slices to wait (effectively boosting the priority of the child
2306 process temporarily). A value of zero disables waiting entirely. */);
2307 w32_pipe_read_delay
= 50;
2309 DEFVAR_LISP ("w32-downcase-file-names", Vw32_downcase_file_names
,
2310 doc
: /* Non-nil means convert all-upper case file names to lower case.
2311 This applies when performing completions and file name expansion.
2312 Note that the value of this setting also affects remote file names,
2313 so you probably don't want to set to non-nil if you use case-sensitive
2314 filesystems via ange-ftp. */);
2315 Vw32_downcase_file_names
= Qnil
;
2318 DEFVAR_LISP ("w32-generate-fake-inodes", Vw32_generate_fake_inodes
,
2319 doc
: /* Non-nil means attempt to fake realistic inode values.
2320 This works by hashing the truename of files, and should detect
2321 aliasing between long and short (8.3 DOS) names, but can have
2322 false positives because of hash collisions. Note that determining
2323 the truename of a file can be slow. */);
2324 Vw32_generate_fake_inodes
= Qnil
;
2327 DEFVAR_LISP ("w32-get-true-file-attributes", Vw32_get_true_file_attributes
,
2328 doc
: /* Non-nil means determine accurate file attributes in `file-attributes'.
2329 This option controls whether to issue additional system calls to determine
2330 accurate link counts, file type, and ownership information. It is more
2331 useful for files on NTFS volumes, where hard links and file security are
2332 supported, than on volumes of the FAT family.
2334 Without these system calls, link count will always be reported as 1 and file
2335 ownership will be attributed to the current user.
2336 The default value `local' means only issue these system calls for files
2337 on local fixed drives. A value of nil means never issue them.
2338 Any other non-nil value means do this even on remote and removable drives
2339 where the performance impact may be noticeable even on modern hardware. */);
2340 Vw32_get_true_file_attributes
= Qlocal
;
2342 staticpro (&Vw32_valid_locale_ids
);
2343 staticpro (&Vw32_valid_codepages
);
2345 /* end of w32proc.c */