1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
32 /* must include CRT headers *before* config.h */
46 /* This definition is missing from mingw32 headers. */
47 extern BOOL WINAPI
IsValidLocale(LCID
, DWORD
);
56 #include "syssignal.h"
59 /* Control whether spawnve quotes arguments as necessary to ensure
60 correct parsing by child process. Because not all uses of spawnve
61 are careful about constructing argv arrays, we make this behaviour
62 conditional (off by default). */
63 Lisp_Object Vw32_quote_process_args
;
65 /* Control whether create_child causes the process' window to be
66 hidden. The default is nil. */
67 Lisp_Object Vw32_start_process_show_window
;
69 /* Control whether create_child causes the process to inherit Emacs'
70 console window, or be given a new one of its own. The default is
71 nil, to allow multiple DOS programs to run on Win95. Having separate
72 consoles also allows Emacs to cleanly terminate process groups. */
73 Lisp_Object Vw32_start_process_share_console
;
75 /* Control whether create_child cause the process to inherit Emacs'
76 error mode setting. The default is t, to minimize the possibility of
77 subprocesses blocking when accessing unmounted drives. */
78 Lisp_Object Vw32_start_process_inherit_error_mode
;
80 /* Time to sleep before reading from a subprocess output pipe - this
81 avoids the inefficiency of frequently reading small amounts of data.
82 This is primarily necessary for handling DOS processes on Windows 95,
83 but is useful for W32 processes on both Windows 95 and NT as well. */
84 Lisp_Object Vw32_pipe_read_delay
;
86 /* Control conversion of upper case file names to lower case.
87 nil means no, t means yes. */
88 Lisp_Object Vw32_downcase_file_names
;
90 /* Control whether stat() attempts to generate fake but hopefully
91 "accurate" inode values, by hashing the absolute truenames of files.
92 This should detect aliasing between long and short names, but still
93 allows the possibility of hash collisions. */
94 Lisp_Object Vw32_generate_fake_inodes
;
96 /* Control whether stat() attempts to determine file type and link count
97 exactly, at the expense of slower operation. Since true hard links
98 are supported on NTFS volumes, this is only relevant on NT. */
99 Lisp_Object Vw32_get_true_file_attributes
;
101 Lisp_Object Qhigh
, Qlow
;
104 void _DebPrint (const char *fmt
, ...)
109 va_start (args
, fmt
);
110 vsprintf (buf
, fmt
, args
);
112 OutputDebugString (buf
);
116 typedef void (_CALLBACK_
*signal_handler
)(int);
118 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
119 static signal_handler sig_handlers
[NSIG
];
121 /* Fake signal implementation to record the SIGCHLD handler. */
123 sys_signal (int sig
, signal_handler handler
)
132 old
= sig_handlers
[sig
];
133 sig_handlers
[sig
] = handler
;
137 /* Defined in <process.h> which conflicts with the local copy */
140 /* Child process management list. */
141 int child_proc_count
= 0;
142 child_process child_procs
[ MAX_CHILDREN
];
143 child_process
*dead_child
= NULL
;
145 DWORD WINAPI
reader_thread (void *arg
);
147 /* Find an unused process slot. */
154 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
155 if (!CHILD_ACTIVE (cp
))
157 if (child_proc_count
== MAX_CHILDREN
)
159 cp
= &child_procs
[child_proc_count
++];
162 memset (cp
, 0, sizeof(*cp
));
165 cp
->procinfo
.hProcess
= NULL
;
166 cp
->status
= STATUS_READ_ERROR
;
168 /* use manual reset event so that select() will function properly */
169 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
172 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
173 if (cp
->char_consumed
)
175 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
185 delete_child (child_process
*cp
)
189 /* Should not be deleting a child that is still needed. */
190 for (i
= 0; i
< MAXDESC
; i
++)
191 if (fd_info
[i
].cp
== cp
)
194 if (!CHILD_ACTIVE (cp
))
197 /* reap thread if necessary */
202 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
204 /* let the thread exit cleanly if possible */
205 cp
->status
= STATUS_READ_ERROR
;
206 SetEvent (cp
->char_consumed
);
207 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
209 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
210 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
211 TerminateThread (cp
->thrd
, 0);
214 CloseHandle (cp
->thrd
);
219 CloseHandle (cp
->char_avail
);
220 cp
->char_avail
= NULL
;
222 if (cp
->char_consumed
)
224 CloseHandle (cp
->char_consumed
);
225 cp
->char_consumed
= NULL
;
228 /* update child_proc_count (highest numbered slot in use plus one) */
229 if (cp
== child_procs
+ child_proc_count
- 1)
231 for (i
= child_proc_count
-1; i
>= 0; i
--)
232 if (CHILD_ACTIVE (&child_procs
[i
]))
234 child_proc_count
= i
+ 1;
239 child_proc_count
= 0;
242 /* Find a child by pid. */
243 static child_process
*
244 find_child_pid (DWORD pid
)
248 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
249 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
255 /* Thread proc for child process and socket reader threads. Each thread
256 is normally blocked until woken by select() to check for input by
257 reading one char. When the read completes, char_avail is signalled
258 to wake up the select emulator and the thread blocks itself again. */
260 reader_thread (void *arg
)
265 cp
= (child_process
*)arg
;
267 /* We have to wait for the go-ahead before we can start */
269 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
276 rc
= _sys_read_ahead (cp
->fd
);
278 /* The name char_avail is a misnomer - it really just means the
279 read-ahead has completed, whether successfully or not. */
280 if (!SetEvent (cp
->char_avail
))
282 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
283 GetLastError (), cp
->fd
));
287 if (rc
== STATUS_READ_ERROR
)
290 /* If the read died, the child has died so let the thread die */
291 if (rc
== STATUS_READ_FAILED
)
294 /* Wait until our input is acknowledged before reading again */
295 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
297 DebPrint (("reader_thread.WaitForSingleObject failed with "
298 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
305 /* To avoid Emacs changing directory, we just record here the directory
306 the new process should start in. This is set just before calling
307 sys_spawnve, and is not generally valid at any other time. */
308 static char * process_dir
;
311 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
312 int * pPid
, child_process
*cp
)
315 SECURITY_ATTRIBUTES sec_attrs
;
317 SECURITY_DESCRIPTOR sec_desc
;
320 char dir
[ MAXPATHLEN
];
322 if (cp
== NULL
) abort ();
324 memset (&start
, 0, sizeof (start
));
325 start
.cb
= sizeof (start
);
328 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
329 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
331 start
.dwFlags
= STARTF_USESTDHANDLES
;
332 start
.wShowWindow
= SW_HIDE
;
334 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
335 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
336 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
337 #endif /* HAVE_NTGUI */
340 /* Explicitly specify no security */
341 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
343 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
346 sec_attrs
.nLength
= sizeof (sec_attrs
);
347 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
348 sec_attrs
.bInheritHandle
= FALSE
;
350 strcpy (dir
, process_dir
);
351 unixtodos_filename (dir
);
353 flags
= (!NILP (Vw32_start_process_share_console
)
354 ? CREATE_NEW_PROCESS_GROUP
355 : CREATE_NEW_CONSOLE
);
356 if (NILP (Vw32_start_process_inherit_error_mode
))
357 flags
|= CREATE_DEFAULT_ERROR_MODE
;
358 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
359 flags
, env
, dir
, &start
, &cp
->procinfo
))
362 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
364 /* Hack for Windows 95, which assigns large (ie negative) pids */
368 /* pid must fit in a Lisp_Int */
369 cp
->pid
= (cp
->pid
& VALMASK
);
376 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
380 /* create_child doesn't know what emacs' file handle will be for waiting
381 on output from the child, so we need to make this additional call
382 to register the handle with the process
383 This way the select emulator knows how to match file handles with
384 entries in child_procs. */
386 register_child (int pid
, int fd
)
390 cp
= find_child_pid (pid
);
393 DebPrint (("register_child unable to find pid %lu\n", pid
));
398 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
403 /* thread is initially blocked until select is called; set status so
404 that select will release thread */
405 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
407 /* attach child_process to fd_info */
408 if (fd_info
[fd
].cp
!= NULL
)
410 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
417 /* When a process dies its pipe will break so the reader thread will
418 signal failure to the select emulator.
419 The select emulator then calls this routine to clean up.
420 Since the thread signaled failure we can assume it is exiting. */
422 reap_subprocess (child_process
*cp
)
424 if (cp
->procinfo
.hProcess
)
426 /* Reap the process */
428 /* Process should have already died before we are called. */
429 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
430 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
432 CloseHandle (cp
->procinfo
.hProcess
);
433 cp
->procinfo
.hProcess
= NULL
;
434 CloseHandle (cp
->procinfo
.hThread
);
435 cp
->procinfo
.hThread
= NULL
;
438 /* For asynchronous children, the child_proc resources will be freed
439 when the last pipe read descriptor is closed; for synchronous
440 children, we must explicitly free the resources now because
441 register_child has not been called. */
446 /* Wait for any of our existing child processes to die
447 When it does, close its handle
448 Return the pid and fill in the status if non-NULL. */
451 sys_wait (int *status
)
453 DWORD active
, retval
;
456 child_process
*cp
, *cps
[MAX_CHILDREN
];
457 HANDLE wait_hnd
[MAX_CHILDREN
];
460 if (dead_child
!= NULL
)
462 /* We want to wait for a specific child */
463 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
464 cps
[nh
] = dead_child
;
465 if (!wait_hnd
[nh
]) abort ();
472 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
473 /* some child_procs might be sockets; ignore them */
474 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
)
476 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
484 /* Nothing to wait on, so fail */
491 /* Check for quit about once a second. */
493 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
494 } while (active
== WAIT_TIMEOUT
);
496 if (active
== WAIT_FAILED
)
501 else if (active
>= WAIT_OBJECT_0
502 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
504 active
-= WAIT_OBJECT_0
;
506 else if (active
>= WAIT_ABANDONED_0
507 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
509 active
-= WAIT_ABANDONED_0
;
515 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
517 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
521 if (retval
== STILL_ACTIVE
)
523 /* Should never happen */
524 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
529 /* Massage the exit code from the process to match the format expected
530 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
531 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
533 if (retval
== STATUS_CONTROL_C_EXIT
)
541 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
548 else if (synch_process_alive
)
550 synch_process_alive
= 0;
552 /* Report the status of the synchronous process. */
553 if (WIFEXITED (retval
))
554 synch_process_retcode
= WRETCODE (retval
);
555 else if (WIFSIGNALED (retval
))
557 int code
= WTERMSIG (retval
);
560 synchronize_system_messages_locale ();
561 signame
= strsignal (code
);
566 synch_process_death
= signame
;
569 reap_subprocess (cp
);
572 reap_subprocess (cp
);
578 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
, int * is_gui_app
)
580 file_data executable
;
583 /* Default values in case we can't tell for sure. */
585 *is_cygnus_app
= FALSE
;
588 if (!open_input_file (&executable
, filename
))
591 p
= strrchr (filename
, '.');
593 /* We can only identify DOS .com programs from the extension. */
594 if (p
&& stricmp (p
, ".com") == 0)
596 else if (p
&& (stricmp (p
, ".bat") == 0
597 || stricmp (p
, ".cmd") == 0))
599 /* A DOS shell script - it appears that CreateProcess is happy to
600 accept this (somewhat surprisingly); presumably it looks at
601 COMSPEC to determine what executable to actually invoke.
602 Therefore, we have to do the same here as well. */
603 /* Actually, I think it uses the program association for that
604 extension, which is defined in the registry. */
605 p
= egetenv ("COMSPEC");
607 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
611 /* Look for DOS .exe signature - if found, we must also check that
612 it isn't really a 16- or 32-bit Windows exe, since both formats
613 start with a DOS program stub. Note that 16-bit Windows
614 executables use the OS/2 1.x format. */
616 IMAGE_DOS_HEADER
* dos_header
;
617 IMAGE_NT_HEADERS
* nt_header
;
619 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
620 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
623 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
625 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
627 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
630 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
631 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
635 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
637 /* Look for cygwin.dll in DLL import list. */
638 IMAGE_DATA_DIRECTORY import_dir
=
639 nt_header
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
640 IMAGE_IMPORT_DESCRIPTOR
* imports
;
641 IMAGE_SECTION_HEADER
* section
;
643 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
644 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
, executable
);
646 for ( ; imports
->Name
; imports
++)
648 char * dllname
= RVA_TO_PTR (imports
->Name
, section
, executable
);
650 /* The exact name of the cygwin dll has changed with
651 various releases, but hopefully this will be reasonably
653 if (strncmp (dllname
, "cygwin", 6) == 0)
655 *is_cygnus_app
= TRUE
;
660 /* Check whether app is marked as a console or windowed (aka
661 GUI) app. Accept Posix and OS2 subsytem apps as console
663 *is_gui_app
= (nt_header
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
668 close_file_data (&executable
);
672 compare_env (const void *strp1
, const void *strp2
)
674 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
676 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
678 /* Sort order in command.com/cmd.exe is based on uppercasing
679 names, so do the same here. */
680 if (toupper (*str1
) > toupper (*str2
))
682 else if (toupper (*str1
) < toupper (*str2
))
687 if (*str1
== '=' && *str2
== '=')
689 else if (*str1
== '=')
696 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
712 qsort (new_envp
, num
, sizeof (char *), compare_env
);
717 /* When a new child process is created we need to register it in our list,
718 so intercept spawn requests. */
720 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
722 Lisp_Object program
, full
;
723 char *cmdline
, *env
, *parg
, **targ
;
727 int is_dos_app
, is_cygnus_app
, is_gui_app
;
730 /* We pass our process ID to our children by setting up an environment
731 variable in their environment. */
732 char ppid_env_var_buffer
[64];
733 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
734 char *sepchars
= " \t";
736 /* We don't care about the other modes */
737 if (mode
!= _P_NOWAIT
)
743 /* Handle executable names without an executable suffix. */
744 program
= make_string (cmdname
, strlen (cmdname
));
745 if (NILP (Ffile_executable_p (program
)))
751 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, 1);
761 /* make sure argv[0] and cmdname are both in DOS format */
762 cmdname
= XSTRING (program
)->data
;
763 unixtodos_filename (cmdname
);
766 /* Determine whether program is a 16-bit DOS executable, or a w32
767 executable that is implicitly linked to the Cygnus dll (implying it
768 was compiled with the Cygnus GNU toolchain and hence relies on
769 cygwin.dll to parse the command line - we use this to decide how to
770 escape quote chars in command line args that must be quoted).
772 Also determine whether it is a GUI app, so that we don't hide its
773 initial window unless specifically requested. */
774 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
776 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
777 application to start it by specifying the helper app as cmdname,
778 while leaving the real app name as argv[0]. */
781 cmdname
= alloca (MAXPATHLEN
);
782 if (egetenv ("CMDPROXY"))
783 strcpy (cmdname
, egetenv ("CMDPROXY"));
786 strcpy (cmdname
, XSTRING (Vinvocation_directory
)->data
);
787 strcat (cmdname
, "cmdproxy.exe");
789 unixtodos_filename (cmdname
);
792 /* we have to do some conjuring here to put argv and envp into the
793 form CreateProcess wants... argv needs to be a space separated/null
794 terminated list of parameters, and envp is a null
795 separated/double-null terminated list of parameters.
797 Additionally, zero-length args and args containing whitespace or
798 quote chars need to be wrapped in double quotes - for this to work,
799 embedded quotes need to be escaped as well. The aim is to ensure
800 the child process reconstructs the argv array we start with
801 exactly, so we treat quotes at the beginning and end of arguments
804 The w32 GNU-based library from Cygnus doubles quotes to escape
805 them, while MSVC uses backslash for escaping. (Actually the MSVC
806 startup code does attempt to recognise doubled quotes and accept
807 them, but gets it wrong and ends up requiring three quotes to get a
808 single embedded quote!) So by default we decide whether to use
809 quote or backslash as the escape character based on whether the
810 binary is apparently a Cygnus compiled app.
812 Note that using backslash to escape embedded quotes requires
813 additional special handling if an embedded quote is already
814 preceeded by backslash, or if an arg requiring quoting ends with
815 backslash. In such cases, the run of escape characters needs to be
816 doubled. For consistency, we apply this special handling as long
817 as the escape character is not quote.
819 Since we have no idea how large argv and envp are likely to be we
820 figure out list lengths on the fly and allocate them. */
822 if (!NILP (Vw32_quote_process_args
))
825 /* Override escape char by binding w32-quote-process-args to
826 desired character, or use t for auto-selection. */
827 if (INTEGERP (Vw32_quote_process_args
))
828 escape_char
= XINT (Vw32_quote_process_args
);
830 escape_char
= is_cygnus_app
? '"' : '\\';
833 /* Cygwin apps needs quoting a bit more often */
834 if (escape_char
== '"')
835 sepchars
= "\r\n\t\f '";
844 int escape_char_run
= 0;
850 if (escape_char
== '"' && *p
== '\\')
851 /* If it's a Cygwin app, \ needs to be escaped. */
855 /* allow for embedded quotes to be escaped */
858 /* handle the case where the embedded quote is already escaped */
859 if (escape_char_run
> 0)
861 /* To preserve the arg exactly, we need to double the
862 preceding escape characters (plus adding one to
863 escape the quote character itself). */
864 arglen
+= escape_char_run
;
867 else if (strchr (sepchars
, *p
) != NULL
)
872 if (*p
== escape_char
&& escape_char
!= '"')
880 /* handle the case where the arg ends with an escape char - we
881 must not let the enclosing quote be escaped. */
882 if (escape_char_run
> 0)
883 arglen
+= escape_char_run
;
885 arglen
+= strlen (*targ
++) + 1;
887 cmdline
= alloca (arglen
);
901 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
906 int escape_char_run
= 0;
912 last
= p
+ strlen (p
) - 1;
915 /* This version does not escape quotes if they occur at the
916 beginning or end of the arg - this could lead to incorrect
917 behaviour when the arg itself represents a command line
918 containing quoted args. I believe this was originally done
919 as a hack to make some things work, before
920 `w32-quote-process-args' was added. */
923 if (*p
== '"' && p
> first
&& p
< last
)
924 *parg
++ = escape_char
; /* escape embedded quotes */
932 /* double preceding escape chars if any */
933 while (escape_char_run
> 0)
935 *parg
++ = escape_char
;
938 /* escape all quote chars, even at beginning or end */
939 *parg
++ = escape_char
;
941 else if (escape_char
== '"' && *p
== '\\')
945 if (*p
== escape_char
&& escape_char
!= '"')
950 /* double escape chars before enclosing quote */
951 while (escape_char_run
> 0)
953 *parg
++ = escape_char
;
961 strcpy (parg
, *targ
);
962 parg
+= strlen (*targ
);
972 numenv
= 1; /* for end null */
975 arglen
+= strlen (*targ
++) + 1;
978 /* extra env vars... */
979 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
980 GetCurrentProcessId ());
981 arglen
+= strlen (ppid_env_var_buffer
) + 1;
984 /* merge env passed in and extra env into one, and sort it. */
985 targ
= (char **) alloca (numenv
* sizeof (char *));
986 merge_and_sort_env (envp
, extra_env
, targ
);
988 /* concatenate env entries. */
989 env
= alloca (arglen
);
993 strcpy (parg
, *targ
);
994 parg
+= strlen (*targ
++);
1007 /* Now create the process. */
1008 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1018 /* Emulate the select call
1019 Wait for available input on any of the given rfds, or timeout if
1020 a timeout is given and no input is detected
1021 wfds and efds are not supported and must be NULL.
1023 For simplicity, we detect the death of child processes here and
1024 synchronously call the SIGCHLD handler. Since it is possible for
1025 children to be created without a corresponding pipe handle from which
1026 to read output, we wait separately on the process handles as well as
1027 the char_avail events for each process pipe. We only call
1028 wait/reap_process when the process actually terminates.
1030 To reduce the number of places in which Emacs can be hung such that
1031 C-g is not able to interrupt it, we always wait on interrupt_handle
1032 (which is signalled by the input thread when C-g is detected). If we
1033 detect that we were woken up by C-g, we return -1 with errno set to
1034 EINTR as on Unix. */
1037 extern HANDLE keyboard_handle
;
1039 /* From w32xfns.c */
1040 extern HANDLE interrupt_handle
;
1042 /* From process.c */
1043 extern int proc_buffered_char
[];
1046 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1047 EMACS_TIME
*timeout
)
1050 DWORD timeout_ms
, start_time
;
1053 child_process
*cp
, *cps
[MAX_CHILDREN
];
1054 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1055 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1057 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1059 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1060 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1066 /* Otherwise, we only handle rfds, so fail otherwise. */
1067 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1077 /* Always wait on interrupt_handle, to detect C-g (quit). */
1078 wait_hnd
[0] = interrupt_handle
;
1081 /* Build a list of pipe handles to wait on. */
1083 for (i
= 0; i
< nfds
; i
++)
1084 if (FD_ISSET (i
, &orfds
))
1088 if (keyboard_handle
)
1090 /* Handle stdin specially */
1091 wait_hnd
[nh
] = keyboard_handle
;
1096 /* Check for any emacs-generated input in the queue since
1097 it won't be detected in the wait */
1098 if (detect_input_pending ())
1106 /* Child process and socket input */
1110 int current_status
= cp
->status
;
1112 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1114 /* Tell reader thread which file handle to use. */
1116 /* Wake up the reader thread for this process */
1117 cp
->status
= STATUS_READ_READY
;
1118 if (!SetEvent (cp
->char_consumed
))
1119 DebPrint (("nt_select.SetEvent failed with "
1120 "%lu for fd %ld\n", GetLastError (), i
));
1123 #ifdef CHECK_INTERLOCK
1124 /* slightly crude cross-checking of interlock between threads */
1126 current_status
= cp
->status
;
1127 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1129 /* char_avail has been signalled, so status (which may
1130 have changed) should indicate read has completed
1131 but has not been acknowledged. */
1132 current_status
= cp
->status
;
1133 if (current_status
!= STATUS_READ_SUCCEEDED
1134 && current_status
!= STATUS_READ_FAILED
)
1135 DebPrint (("char_avail set, but read not completed: status %d\n",
1140 /* char_avail has not been signalled, so status should
1141 indicate that read is in progress; small possibility
1142 that read has completed but event wasn't yet signalled
1143 when we tested it (because a context switch occurred
1144 or if running on separate CPUs). */
1145 if (current_status
!= STATUS_READ_READY
1146 && current_status
!= STATUS_READ_IN_PROGRESS
1147 && current_status
!= STATUS_READ_SUCCEEDED
1148 && current_status
!= STATUS_READ_FAILED
)
1149 DebPrint (("char_avail reset, but read status is bad: %d\n",
1153 wait_hnd
[nh
] = cp
->char_avail
;
1155 if (!wait_hnd
[nh
]) abort ();
1158 DebPrint (("select waiting on child %d fd %d\n",
1159 cp
-child_procs
, i
));
1164 /* Unable to find something to wait on for this fd, skip */
1166 /* Note that this is not a fatal error, and can in fact
1167 happen in unusual circumstances. Specifically, if
1168 sys_spawnve fails, eg. because the program doesn't
1169 exist, and debug-on-error is t so Fsignal invokes a
1170 nested input loop, then the process output pipe is
1171 still included in input_wait_mask with no child_proc
1172 associated with it. (It is removed when the debugger
1173 exits the nested input loop and the error is thrown.) */
1175 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1181 /* Add handles of child processes. */
1183 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1184 /* Some child_procs might be sockets; ignore them. Also some
1185 children may have died already, but we haven't finished reading
1186 the process output; ignore them too. */
1187 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1189 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1190 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1193 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1198 /* Nothing to look for, so we didn't find anything */
1206 start_time
= GetTickCount ();
1208 /* Wait for input or child death to be signalled. If user input is
1209 allowed, then also accept window messages. */
1210 if (FD_ISSET (0, &orfds
))
1211 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1214 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1216 if (active
== WAIT_FAILED
)
1218 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1219 nh
+ nc
, timeout_ms
, GetLastError ()));
1220 /* don't return EBADF - this causes wait_reading_process_input to
1221 abort; WAIT_FAILED is returned when single-stepping under
1222 Windows 95 after switching thread focus in debugger, and
1223 possibly at other times. */
1227 else if (active
== WAIT_TIMEOUT
)
1231 else if (active
>= WAIT_OBJECT_0
1232 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1234 active
-= WAIT_OBJECT_0
;
1236 else if (active
>= WAIT_ABANDONED_0
1237 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1239 active
-= WAIT_ABANDONED_0
;
1244 /* Loop over all handles after active (now officially documented as
1245 being the first signalled handle in the array). We do this to
1246 ensure fairness, so that all channels with data available will be
1247 processed - otherwise higher numbered channels could be starved. */
1250 if (active
== nh
+ nc
)
1252 /* There are messages in the lisp thread's queue; we must
1253 drain the queue now to ensure they are processed promptly,
1254 because if we don't do so, we will not be woken again until
1255 further messages arrive.
1257 NB. If ever we allow window message procedures to callback
1258 into lisp, we will need to ensure messages are dispatched
1259 at a safe time for lisp code to be run (*), and we may also
1260 want to provide some hooks in the dispatch loop to cater
1261 for modeless dialogs created by lisp (ie. to register
1262 window handles to pass to IsDialogMessage).
1264 (*) Note that MsgWaitForMultipleObjects above is an
1265 internal dispatch point for messages that are sent to
1266 windows created by this thread. */
1267 drain_message_queue ();
1269 else if (active
>= nh
)
1271 cp
= cps
[active
- nh
];
1273 /* We cannot always signal SIGCHLD immediately; if we have not
1274 finished reading the process output, we must delay sending
1275 SIGCHLD until we do. */
1277 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1278 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1279 /* SIG_DFL for SIGCHLD is ignore */
1280 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1281 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1284 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1288 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1292 else if (fdindex
[active
] == -1)
1294 /* Quit (C-g) was detected. */
1298 else if (fdindex
[active
] == 0)
1300 /* Keyboard input available */
1306 /* must be a socket or pipe - read ahead should have
1307 completed, either succeeding or failing. */
1308 FD_SET (fdindex
[active
], rfds
);
1312 /* Even though wait_reading_process_output only reads from at most
1313 one channel, we must process all channels here so that we reap
1314 all children that have died. */
1315 while (++active
< nh
+ nc
)
1316 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1318 } while (active
< nh
+ nc
);
1320 /* If no input has arrived and timeout hasn't expired, wait again. */
1323 DWORD elapsed
= GetTickCount () - start_time
;
1325 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1327 if (timeout_ms
!= INFINITE
)
1328 timeout_ms
-= elapsed
;
1329 goto count_children
;
1336 /* Substitute for certain kill () operations */
1338 static BOOL CALLBACK
1339 find_child_console (HWND hwnd
, LPARAM arg
)
1341 child_process
* cp
= (child_process
*) arg
;
1345 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1346 if (process_id
== cp
->procinfo
.dwProcessId
)
1348 char window_class
[32];
1350 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1351 if (strcmp (window_class
,
1352 (os_subtype
== OS_WIN95
)
1354 : "ConsoleWindowClass") == 0)
1365 sys_kill (int pid
, int sig
)
1369 int need_to_free
= 0;
1372 /* Only handle signals that will result in the process dying */
1373 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1379 cp
= find_child_pid (pid
);
1382 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1383 if (proc_hand
== NULL
)
1392 proc_hand
= cp
->procinfo
.hProcess
;
1393 pid
= cp
->procinfo
.dwProcessId
;
1395 /* Try to locate console window for process. */
1396 EnumWindows (find_child_console
, (LPARAM
) cp
);
1399 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1401 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1403 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1404 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1405 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1406 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1407 HWND foreground_window
;
1409 if (break_scan_code
== 0)
1411 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1412 vk_break_code
= 'C';
1413 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1416 foreground_window
= GetForegroundWindow ();
1417 if (foreground_window
)
1419 /* NT 5.0, and apparently also Windows 98, will not allow
1420 a Window to be set to foreground directly without the
1421 user's involvement. The workaround is to attach
1422 ourselves to the thread that owns the foreground
1423 window, since that is the only thread that can set the
1424 foreground window. */
1425 DWORD foreground_thread
, child_thread
;
1427 GetWindowThreadProcessId (foreground_window
, NULL
);
1428 if (foreground_thread
== GetCurrentThreadId ()
1429 || !AttachThreadInput (GetCurrentThreadId (),
1430 foreground_thread
, TRUE
))
1431 foreground_thread
= 0;
1433 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1434 if (child_thread
== GetCurrentThreadId ()
1435 || !AttachThreadInput (GetCurrentThreadId (),
1436 child_thread
, TRUE
))
1439 /* Set the foreground window to the child. */
1440 if (SetForegroundWindow (cp
->hwnd
))
1442 /* Generate keystrokes as if user had typed Ctrl-Break or
1444 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1445 keybd_event (vk_break_code
, break_scan_code
,
1446 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1447 keybd_event (vk_break_code
, break_scan_code
,
1448 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1449 | KEYEVENTF_KEYUP
, 0);
1450 keybd_event (VK_CONTROL
, control_scan_code
,
1451 KEYEVENTF_KEYUP
, 0);
1453 /* Sleep for a bit to give time for Emacs frame to respond
1454 to focus change events (if Emacs was active app). */
1457 SetForegroundWindow (foreground_window
);
1459 /* Detach from the foreground and child threads now that
1460 the foreground switching is over. */
1461 if (foreground_thread
)
1462 AttachThreadInput (GetCurrentThreadId (),
1463 foreground_thread
, FALSE
);
1465 AttachThreadInput (GetCurrentThreadId (),
1466 child_thread
, FALSE
);
1469 /* Ctrl-Break is NT equivalent of SIGINT. */
1470 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1472 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1473 "for pid %lu\n", GetLastError (), pid
));
1480 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1483 if (os_subtype
== OS_WIN95
)
1486 Another possibility is to try terminating the VDM out-right by
1487 calling the Shell VxD (id 0x17) V86 interface, function #4
1488 "SHELL_Destroy_VM", ie.
1494 First need to determine the current VM handle, and then arrange for
1495 the shellapi call to be made from the system vm (by using
1496 Switch_VM_and_callback).
1498 Could try to invoke DestroyVM through CallVxD.
1502 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1503 to hang when cmdproxy is used in conjunction with
1504 command.com for an interactive shell. Posting
1505 WM_CLOSE pops up a dialog that, when Yes is selected,
1506 does the same thing. TerminateProcess is also less
1507 than ideal in that subprocesses tend to stick around
1508 until the machine is shutdown, but at least it
1509 doesn't freeze the 16-bit subsystem. */
1510 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1512 if (!TerminateProcess (proc_hand
, 0xff))
1514 DebPrint (("sys_kill.TerminateProcess returned %d "
1515 "for pid %lu\n", GetLastError (), pid
));
1522 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1524 /* Kill the process. On W32 this doesn't kill child processes
1525 so it doesn't work very well for shells which is why it's not
1526 used in every case. */
1527 else if (!TerminateProcess (proc_hand
, 0xff))
1529 DebPrint (("sys_kill.TerminateProcess returned %d "
1530 "for pid %lu\n", GetLastError (), pid
));
1537 CloseHandle (proc_hand
);
1542 /* extern int report_file_error (char *, Lisp_Object); */
1544 /* The following two routines are used to manipulate stdin, stdout, and
1545 stderr of our child processes.
1547 Assuming that in, out, and err are *not* inheritable, we make them
1548 stdin, stdout, and stderr of the child as follows:
1550 - Save the parent's current standard handles.
1551 - Set the std handles to inheritable duplicates of the ones being passed in.
1552 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1553 NT file handle for a crt file descriptor.)
1554 - Spawn the child, which inherits in, out, and err as stdin,
1555 stdout, and stderr. (see Spawnve)
1556 - Close the std handles passed to the child.
1557 - Reset the parent's standard handles to the saved handles.
1558 (see reset_standard_handles)
1559 We assume that the caller closes in, out, and err after calling us. */
1562 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1565 HANDLE newstdin
, newstdout
, newstderr
;
1567 parent
= GetCurrentProcess ();
1569 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1570 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1571 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1573 /* make inheritable copies of the new handles */
1574 if (!DuplicateHandle (parent
,
1575 (HANDLE
) _get_osfhandle (in
),
1580 DUPLICATE_SAME_ACCESS
))
1581 report_file_error ("Duplicating input handle for child", Qnil
);
1583 if (!DuplicateHandle (parent
,
1584 (HANDLE
) _get_osfhandle (out
),
1589 DUPLICATE_SAME_ACCESS
))
1590 report_file_error ("Duplicating output handle for child", Qnil
);
1592 if (!DuplicateHandle (parent
,
1593 (HANDLE
) _get_osfhandle (err
),
1598 DUPLICATE_SAME_ACCESS
))
1599 report_file_error ("Duplicating error handle for child", Qnil
);
1601 /* and store them as our std handles */
1602 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1603 report_file_error ("Changing stdin handle", Qnil
);
1605 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1606 report_file_error ("Changing stdout handle", Qnil
);
1608 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1609 report_file_error ("Changing stderr handle", Qnil
);
1613 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1615 /* close the duplicated handles passed to the child */
1616 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1617 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1618 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1620 /* now restore parent's saved std handles */
1621 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1622 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1623 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1627 set_process_dir (char * dir
)
1634 /* To avoid problems with winsock implementations that work over dial-up
1635 connections causing or requiring a connection to exist while Emacs is
1636 running, Emacs no longer automatically loads winsock on startup if it
1637 is present. Instead, it will be loaded when open-network-stream is
1640 To allow full control over when winsock is loaded, we provide these
1641 two functions to dynamically load and unload winsock. This allows
1642 dial-up users to only be connected when they actually need to use
1646 extern HANDLE winsock_lib
;
1647 extern BOOL
term_winsock (void);
1648 extern BOOL
init_winsock (int load_now
);
1650 extern Lisp_Object Vsystem_name
;
1652 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1653 doc
: /* Test for presence of the Windows socket library `winsock'.
1654 Returns non-nil if winsock support is present, nil otherwise.
1656 If the optional argument LOAD-NOW is non-nil, the winsock library is
1657 also loaded immediately if not already loaded. If winsock is loaded,
1658 the winsock local hostname is returned (since this may be different from
1659 the value of `system-name' and should supplant it), otherwise t is
1660 returned to indicate winsock support is present. */)
1662 Lisp_Object load_now
;
1666 have_winsock
= init_winsock (!NILP (load_now
));
1669 if (winsock_lib
!= NULL
)
1671 /* Return new value for system-name. The best way to do this
1672 is to call init_system_name, saving and restoring the
1673 original value to avoid side-effects. */
1674 Lisp_Object orig_hostname
= Vsystem_name
;
1675 Lisp_Object hostname
;
1677 init_system_name ();
1678 hostname
= Vsystem_name
;
1679 Vsystem_name
= orig_hostname
;
1687 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1689 doc
: /* Unload the Windows socket library `winsock' if loaded.
1690 This is provided to allow dial-up socket connections to be disconnected
1691 when no longer needed. Returns nil without unloading winsock if any
1692 socket connections still exist. */)
1695 return term_winsock () ? Qt
: Qnil
;
1698 #endif /* HAVE_SOCKETS */
1701 /* Some miscellaneous functions that are Windows specific, but not GUI
1702 specific (ie. are applicable in terminal or batch mode as well). */
1704 /* lifted from fileio.c */
1705 #define CORRECT_DIR_SEPS(s) \
1706 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1707 else unixtodos_filename (s); \
1710 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1711 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1712 If FILENAME does not exist, return nil.
1713 All path elements in FILENAME are converted to their short names. */)
1715 Lisp_Object filename
;
1717 char shortname
[MAX_PATH
];
1719 CHECK_STRING (filename
);
1721 /* first expand it. */
1722 filename
= Fexpand_file_name (filename
, Qnil
);
1724 /* luckily, this returns the short version of each element in the path. */
1725 if (GetShortPathName (XSTRING (filename
)->data
, shortname
, MAX_PATH
) == 0)
1728 CORRECT_DIR_SEPS (shortname
);
1730 return build_string (shortname
);
1734 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1736 doc
: /* Return the long file name version of the full path of FILENAME.
1737 If FILENAME does not exist, return nil.
1738 All path elements in FILENAME are converted to their long names. */)
1740 Lisp_Object filename
;
1742 char longname
[ MAX_PATH
];
1744 CHECK_STRING (filename
);
1746 /* first expand it. */
1747 filename
= Fexpand_file_name (filename
, Qnil
);
1749 if (!w32_get_long_filename (XSTRING (filename
)->data
, longname
, MAX_PATH
))
1752 CORRECT_DIR_SEPS (longname
);
1754 return build_string (longname
);
1757 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1758 Sw32_set_process_priority
, 2, 2, 0,
1759 doc
: /* Set the priority of PROCESS to PRIORITY.
1760 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1761 priority of the process whose pid is PROCESS is changed.
1762 PRIORITY should be one of the symbols high, normal, or low;
1763 any other symbol will be interpreted as normal.
1765 If successful, the return value is t, otherwise nil. */)
1767 Lisp_Object process
, priority
;
1769 HANDLE proc_handle
= GetCurrentProcess ();
1770 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1771 Lisp_Object result
= Qnil
;
1773 CHECK_SYMBOL (priority
);
1775 if (!NILP (process
))
1780 CHECK_NUMBER (process
);
1782 /* Allow pid to be an internally generated one, or one obtained
1783 externally. This is necessary because real pids on Win95 are
1786 pid
= XINT (process
);
1787 cp
= find_child_pid (pid
);
1789 pid
= cp
->procinfo
.dwProcessId
;
1791 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1794 if (EQ (priority
, Qhigh
))
1795 priority_class
= HIGH_PRIORITY_CLASS
;
1796 else if (EQ (priority
, Qlow
))
1797 priority_class
= IDLE_PRIORITY_CLASS
;
1799 if (proc_handle
!= NULL
)
1801 if (SetPriorityClass (proc_handle
, priority_class
))
1803 if (!NILP (process
))
1804 CloseHandle (proc_handle
);
1811 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1812 Sw32_get_locale_info
, 1, 2, 0,
1813 doc
: /* Return information about the Windows locale LCID.
1814 By default, return a three letter locale code which encodes the default
1815 language as the first two characters, and the country or regionial variant
1816 as the third letter. For example, ENU refers to `English (United States)',
1817 while ENC means `English (Canadian)'.
1819 If the optional argument LONGFORM is t, the long form of the locale
1820 name is returned, e.g. `English (United States)' instead; if LONGFORM
1821 is a number, it is interpreted as an LCTYPE constant and the corresponding
1822 locale information is returned.
1824 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1826 Lisp_Object lcid
, longform
;
1830 char abbrev_name
[32] = { 0 };
1831 char full_name
[256] = { 0 };
1833 CHECK_NUMBER (lcid
);
1835 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1838 if (NILP (longform
))
1840 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1841 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1842 abbrev_name
, sizeof (abbrev_name
));
1844 return build_string (abbrev_name
);
1846 else if (EQ (longform
, Qt
))
1848 got_full
= GetLocaleInfo (XINT (lcid
),
1849 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1850 full_name
, sizeof (full_name
));
1852 return build_string (full_name
);
1854 else if (NUMBERP (longform
))
1856 got_full
= GetLocaleInfo (XINT (lcid
),
1858 full_name
, sizeof (full_name
));
1860 return make_unibyte_string (full_name
, got_full
);
1867 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
1868 Sw32_get_current_locale_id
, 0, 0, 0,
1869 doc
: /* Return Windows locale id for current locale setting.
1870 This is a numerical value; use `w32-get-locale-info' to convert to a
1871 human-readable form. */)
1874 return make_number (GetThreadLocale ());
1877 DWORD
int_from_hex (char * s
)
1880 static char hex
[] = "0123456789abcdefABCDEF";
1883 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
1885 unsigned digit
= p
- hex
;
1888 val
= val
* 16 + digit
;
1894 /* We need to build a global list, since the EnumSystemLocale callback
1895 function isn't given a context pointer. */
1896 Lisp_Object Vw32_valid_locale_ids
;
1898 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
1900 DWORD id
= int_from_hex (localeNum
);
1901 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
1905 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
1906 Sw32_get_valid_locale_ids
, 0, 0, 0,
1907 doc
: /* Return list of all valid Windows locale ids.
1908 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1909 human-readable form. */)
1912 Vw32_valid_locale_ids
= Qnil
;
1914 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
1916 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
1917 return Vw32_valid_locale_ids
;
1921 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
1922 doc
: /* Return Windows locale id for default locale setting.
1923 By default, the system default locale setting is returned; if the optional
1924 parameter USERP is non-nil, the user default locale setting is returned.
1925 This is a numerical value; use `w32-get-locale-info' to convert to a
1926 human-readable form. */)
1931 return make_number (GetSystemDefaultLCID ());
1932 return make_number (GetUserDefaultLCID ());
1936 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
1937 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
1938 If successful, the new locale id is returned, otherwise nil. */)
1942 CHECK_NUMBER (lcid
);
1944 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1947 if (!SetThreadLocale (XINT (lcid
)))
1950 /* Need to set input thread locale if present. */
1951 if (dwWindowsThreadId
)
1952 /* Reply is not needed. */
1953 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
1955 return make_number (GetThreadLocale ());
1959 /* We need to build a global list, since the EnumCodePages callback
1960 function isn't given a context pointer. */
1961 Lisp_Object Vw32_valid_codepages
;
1963 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
1965 DWORD id
= atoi (codepageNum
);
1966 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
1970 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
1971 Sw32_get_valid_codepages
, 0, 0, 0,
1972 doc
: /* Return list of all valid Windows codepages. */)
1975 Vw32_valid_codepages
= Qnil
;
1977 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
1979 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
1980 return Vw32_valid_codepages
;
1984 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
1985 Sw32_get_console_codepage
, 0, 0, 0,
1986 doc
: /* Return current Windows codepage for console input. */)
1989 return make_number (GetConsoleCP ());
1993 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
1994 Sw32_set_console_codepage
, 1, 1, 0,
1995 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
1996 The codepage setting affects keyboard input and display in tty mode.
1997 If successful, the new CP is returned, otherwise nil. */)
2003 if (!IsValidCodePage (XINT (cp
)))
2006 if (!SetConsoleCP (XINT (cp
)))
2009 return make_number (GetConsoleCP ());
2013 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2014 Sw32_get_console_output_codepage
, 0, 0, 0,
2015 doc
: /* Return current Windows codepage for console output. */)
2018 return make_number (GetConsoleOutputCP ());
2022 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2023 Sw32_set_console_output_codepage
, 1, 1, 0,
2024 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2025 The codepage setting affects keyboard input and display in tty mode.
2026 If successful, the new CP is returned, otherwise nil. */)
2032 if (!IsValidCodePage (XINT (cp
)))
2035 if (!SetConsoleOutputCP (XINT (cp
)))
2038 return make_number (GetConsoleOutputCP ());
2042 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2043 Sw32_get_codepage_charset
, 1, 1, 0,
2044 doc
: /* Return charset of codepage CP.
2045 Returns nil if the codepage is not valid. */)
2053 if (!IsValidCodePage (XINT (cp
)))
2056 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2057 return make_number (info
.ciCharset
);
2063 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2064 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2065 doc
: /* Return list of Windows keyboard languages and layouts.
2066 The return value is a list of pairs of language id and layout id. */)
2069 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2070 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2071 Lisp_Object obj
= Qnil
;
2073 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2075 while (--num_layouts
>= 0)
2077 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2079 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2080 make_number ((kl
>> 16) & 0xffff)),
2089 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2090 Sw32_get_keyboard_layout
, 0, 0, 0,
2091 doc
: /* Return current Windows keyboard language and layout.
2092 The return value is the cons of the language id and the layout id. */)
2095 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2097 return Fcons (make_number (kl
& 0xffff),
2098 make_number ((kl
>> 16) & 0xffff));
2102 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2103 Sw32_set_keyboard_layout
, 1, 1, 0,
2104 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2105 The keyboard layout setting affects interpretation of keyboard input.
2106 If successful, the new layout id is returned, otherwise nil. */)
2112 CHECK_CONS (layout
);
2113 CHECK_NUMBER_CAR (layout
);
2114 CHECK_NUMBER_CDR (layout
);
2116 kl
= (XINT (XCAR (layout
)) & 0xffff)
2117 | (XINT (XCDR (layout
)) << 16);
2119 /* Synchronize layout with input thread. */
2120 if (dwWindowsThreadId
)
2122 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2126 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2128 if (msg
.wParam
== 0)
2132 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2135 return Fw32_get_keyboard_layout ();
2141 Qhigh
= intern ("high");
2142 Qlow
= intern ("low");
2145 defsubr (&Sw32_has_winsock
);
2146 defsubr (&Sw32_unload_winsock
);
2148 defsubr (&Sw32_short_file_name
);
2149 defsubr (&Sw32_long_file_name
);
2150 defsubr (&Sw32_set_process_priority
);
2151 defsubr (&Sw32_get_locale_info
);
2152 defsubr (&Sw32_get_current_locale_id
);
2153 defsubr (&Sw32_get_default_locale_id
);
2154 defsubr (&Sw32_get_valid_locale_ids
);
2155 defsubr (&Sw32_set_current_locale
);
2157 defsubr (&Sw32_get_console_codepage
);
2158 defsubr (&Sw32_set_console_codepage
);
2159 defsubr (&Sw32_get_console_output_codepage
);
2160 defsubr (&Sw32_set_console_output_codepage
);
2161 defsubr (&Sw32_get_valid_codepages
);
2162 defsubr (&Sw32_get_codepage_charset
);
2164 defsubr (&Sw32_get_valid_keyboard_layouts
);
2165 defsubr (&Sw32_get_keyboard_layout
);
2166 defsubr (&Sw32_set_keyboard_layout
);
2168 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2169 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2170 Because Windows does not directly pass argv arrays to child processes,
2171 programs have to reconstruct the argv array by parsing the command
2172 line string. For an argument to contain a space, it must be enclosed
2173 in double quotes or it will be parsed as multiple arguments.
2175 If the value is a character, that character will be used to escape any
2176 quote characters that appear, otherwise a suitable escape character
2177 will be chosen based on the type of the program. */);
2178 Vw32_quote_process_args
= Qt
;
2180 DEFVAR_LISP ("w32-start-process-show-window",
2181 &Vw32_start_process_show_window
,
2182 doc
: /* When nil, new child processes hide their windows.
2183 When non-nil, they show their window in the method of their choice.
2184 This variable doesn't affect GUI applications, which will never be hidden. */);
2185 Vw32_start_process_show_window
= Qnil
;
2187 DEFVAR_LISP ("w32-start-process-share-console",
2188 &Vw32_start_process_share_console
,
2189 doc
: /* When nil, new child processes are given a new console.
2190 When non-nil, they share the Emacs console; this has the limitation of
2191 allowing only one DOS subprocess to run at a time (whether started directly
2192 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2193 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2194 otherwise respond to interrupts from Emacs. */);
2195 Vw32_start_process_share_console
= Qnil
;
2197 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2198 &Vw32_start_process_inherit_error_mode
,
2199 doc
: /* When nil, new child processes revert to the default error mode.
2200 When non-nil, they inherit their error mode setting from Emacs, which stops
2201 them blocking when trying to access unmounted drives etc. */);
2202 Vw32_start_process_inherit_error_mode
= Qt
;
2204 DEFVAR_INT ("w32-pipe-read-delay", &Vw32_pipe_read_delay
,
2205 doc
: /* Forced delay before reading subprocess output.
2206 This is done to improve the buffering of subprocess output, by
2207 avoiding the inefficiency of frequently reading small amounts of data.
2209 If positive, the value is the number of milliseconds to sleep before
2210 reading the subprocess output. If negative, the magnitude is the number
2211 of time slices to wait (effectively boosting the priority of the child
2212 process temporarily). A value of zero disables waiting entirely. */);
2213 Vw32_pipe_read_delay
= 50;
2215 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2216 doc
: /* Non-nil means convert all-upper case file names to lower case.
2217 This applies when performing completions and file name expansion.
2218 Note that the value of this setting also affects remote file names,
2219 so you probably don't want to set to non-nil if you use case-sensitive
2220 filesystems via ange-ftp. */);
2221 Vw32_downcase_file_names
= Qnil
;
2224 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2225 doc
: /* Non-nil means attempt to fake realistic inode values.
2226 This works by hashing the truename of files, and should detect
2227 aliasing between long and short (8.3 DOS) names, but can have
2228 false positives because of hash collisions. Note that determing
2229 the truename of a file can be slow. */);
2230 Vw32_generate_fake_inodes
= Qnil
;
2233 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2234 doc
: /* Non-nil means determine accurate link count in file-attributes.
2235 This option slows down file-attributes noticeably, so is disabled by
2236 default. Note that it is only useful for files on NTFS volumes,
2237 where hard links are supported. */);
2238 Vw32_get_true_file_attributes
= Qt
;
2240 /* end of ntproc.c */