1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.
22 Drew Bliss Oct 14, 1993
23 Adapted from alarm.c by Tim Fleehart
34 /* must include CRT headers *before* config.h */
48 /* This definition is missing from mingw32 headers. */
49 extern BOOL WINAPI
IsValidLocale(LCID
, DWORD
);
52 #ifdef HAVE_LANGINFO_CODESET
63 #include "syssignal.h"
66 #define RVA_TO_PTR(var,section,filedata) \
67 ((void *)((section)->PointerToRawData \
68 + ((DWORD)(var) - (section)->VirtualAddress) \
69 + (filedata).file_base))
71 /* Control whether spawnve quotes arguments as necessary to ensure
72 correct parsing by child process. Because not all uses of spawnve
73 are careful about constructing argv arrays, we make this behaviour
74 conditional (off by default). */
75 Lisp_Object Vw32_quote_process_args
;
77 /* Control whether create_child causes the process' window to be
78 hidden. The default is nil. */
79 Lisp_Object Vw32_start_process_show_window
;
81 /* Control whether create_child causes the process to inherit Emacs'
82 console window, or be given a new one of its own. The default is
83 nil, to allow multiple DOS programs to run on Win95. Having separate
84 consoles also allows Emacs to cleanly terminate process groups. */
85 Lisp_Object Vw32_start_process_share_console
;
87 /* Control whether create_child cause the process to inherit Emacs'
88 error mode setting. The default is t, to minimize the possibility of
89 subprocesses blocking when accessing unmounted drives. */
90 Lisp_Object Vw32_start_process_inherit_error_mode
;
92 /* Time to sleep before reading from a subprocess output pipe - this
93 avoids the inefficiency of frequently reading small amounts of data.
94 This is primarily necessary for handling DOS processes on Windows 95,
95 but is useful for W32 processes on both Windows 95 and NT as well. */
96 int w32_pipe_read_delay
;
98 /* Control conversion of upper case file names to lower case.
99 nil means no, t means yes. */
100 Lisp_Object Vw32_downcase_file_names
;
102 /* Control whether stat() attempts to generate fake but hopefully
103 "accurate" inode values, by hashing the absolute truenames of files.
104 This should detect aliasing between long and short names, but still
105 allows the possibility of hash collisions. */
106 Lisp_Object Vw32_generate_fake_inodes
;
108 /* Control whether stat() attempts to determine file type and link count
109 exactly, at the expense of slower operation. Since true hard links
110 are supported on NTFS volumes, this is only relevant on NT. */
111 Lisp_Object Vw32_get_true_file_attributes
;
113 Lisp_Object Qhigh
, Qlow
;
116 void _DebPrint (const char *fmt
, ...)
121 va_start (args
, fmt
);
122 vsprintf (buf
, fmt
, args
);
124 OutputDebugString (buf
);
128 typedef void (_CALLBACK_
*signal_handler
)(int);
130 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
131 static signal_handler sig_handlers
[NSIG
];
133 /* Fake signal implementation to record the SIGCHLD handler. */
135 sys_signal (int sig
, signal_handler handler
)
144 old
= sig_handlers
[sig
];
145 sig_handlers
[sig
] = handler
;
149 /* Defined in <process.h> which conflicts with the local copy */
152 /* Child process management list. */
153 int child_proc_count
= 0;
154 child_process child_procs
[ MAX_CHILDREN
];
155 child_process
*dead_child
= NULL
;
157 DWORD WINAPI
reader_thread (void *arg
);
159 /* Find an unused process slot. */
166 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
167 if (!CHILD_ACTIVE (cp
))
169 if (child_proc_count
== MAX_CHILDREN
)
171 cp
= &child_procs
[child_proc_count
++];
174 memset (cp
, 0, sizeof(*cp
));
177 cp
->procinfo
.hProcess
= NULL
;
178 cp
->status
= STATUS_READ_ERROR
;
180 /* use manual reset event so that select() will function properly */
181 cp
->char_avail
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
184 cp
->char_consumed
= CreateEvent (NULL
, FALSE
, FALSE
, NULL
);
185 if (cp
->char_consumed
)
187 cp
->thrd
= CreateThread (NULL
, 1024, reader_thread
, cp
, 0, &id
);
197 delete_child (child_process
*cp
)
201 /* Should not be deleting a child that is still needed. */
202 for (i
= 0; i
< MAXDESC
; i
++)
203 if (fd_info
[i
].cp
== cp
)
206 if (!CHILD_ACTIVE (cp
))
209 /* reap thread if necessary */
214 if (GetExitCodeThread (cp
->thrd
, &rc
) && rc
== STILL_ACTIVE
)
216 /* let the thread exit cleanly if possible */
217 cp
->status
= STATUS_READ_ERROR
;
218 SetEvent (cp
->char_consumed
);
219 if (WaitForSingleObject (cp
->thrd
, 1000) != WAIT_OBJECT_0
)
221 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
222 "with %lu for fd %ld\n", GetLastError (), cp
->fd
));
223 TerminateThread (cp
->thrd
, 0);
226 CloseHandle (cp
->thrd
);
231 CloseHandle (cp
->char_avail
);
232 cp
->char_avail
= NULL
;
234 if (cp
->char_consumed
)
236 CloseHandle (cp
->char_consumed
);
237 cp
->char_consumed
= NULL
;
240 /* update child_proc_count (highest numbered slot in use plus one) */
241 if (cp
== child_procs
+ child_proc_count
- 1)
243 for (i
= child_proc_count
-1; i
>= 0; i
--)
244 if (CHILD_ACTIVE (&child_procs
[i
]))
246 child_proc_count
= i
+ 1;
251 child_proc_count
= 0;
254 /* Find a child by pid. */
255 static child_process
*
256 find_child_pid (DWORD pid
)
260 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
261 if (CHILD_ACTIVE (cp
) && pid
== cp
->pid
)
267 /* Thread proc for child process and socket reader threads. Each thread
268 is normally blocked until woken by select() to check for input by
269 reading one char. When the read completes, char_avail is signalled
270 to wake up the select emulator and the thread blocks itself again. */
272 reader_thread (void *arg
)
277 cp
= (child_process
*)arg
;
279 /* We have to wait for the go-ahead before we can start */
281 || WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
288 if (fd_info
[cp
->fd
].flags
& FILE_LISTEN
)
289 rc
= _sys_wait_accept (cp
->fd
);
291 rc
= _sys_read_ahead (cp
->fd
);
293 /* The name char_avail is a misnomer - it really just means the
294 read-ahead has completed, whether successfully or not. */
295 if (!SetEvent (cp
->char_avail
))
297 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
298 GetLastError (), cp
->fd
));
302 if (rc
== STATUS_READ_ERROR
)
305 /* If the read died, the child has died so let the thread die */
306 if (rc
== STATUS_READ_FAILED
)
309 /* Wait until our input is acknowledged before reading again */
310 if (WaitForSingleObject (cp
->char_consumed
, INFINITE
) != WAIT_OBJECT_0
)
312 DebPrint (("reader_thread.WaitForSingleObject failed with "
313 "%lu for fd %ld\n", GetLastError (), cp
->fd
));
320 /* To avoid Emacs changing directory, we just record here the directory
321 the new process should start in. This is set just before calling
322 sys_spawnve, and is not generally valid at any other time. */
323 static char * process_dir
;
326 create_child (char *exe
, char *cmdline
, char *env
, int is_gui_app
,
327 int * pPid
, child_process
*cp
)
330 SECURITY_ATTRIBUTES sec_attrs
;
332 SECURITY_DESCRIPTOR sec_desc
;
335 char dir
[ MAXPATHLEN
];
337 if (cp
== NULL
) abort ();
339 memset (&start
, 0, sizeof (start
));
340 start
.cb
= sizeof (start
);
343 if (NILP (Vw32_start_process_show_window
) && !is_gui_app
)
344 start
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
346 start
.dwFlags
= STARTF_USESTDHANDLES
;
347 start
.wShowWindow
= SW_HIDE
;
349 start
.hStdInput
= GetStdHandle (STD_INPUT_HANDLE
);
350 start
.hStdOutput
= GetStdHandle (STD_OUTPUT_HANDLE
);
351 start
.hStdError
= GetStdHandle (STD_ERROR_HANDLE
);
352 #endif /* HAVE_NTGUI */
355 /* Explicitly specify no security */
356 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
358 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
361 sec_attrs
.nLength
= sizeof (sec_attrs
);
362 sec_attrs
.lpSecurityDescriptor
= NULL
/* &sec_desc */;
363 sec_attrs
.bInheritHandle
= FALSE
;
365 strcpy (dir
, process_dir
);
366 unixtodos_filename (dir
);
368 flags
= (!NILP (Vw32_start_process_share_console
)
369 ? CREATE_NEW_PROCESS_GROUP
370 : CREATE_NEW_CONSOLE
);
371 if (NILP (Vw32_start_process_inherit_error_mode
))
372 flags
|= CREATE_DEFAULT_ERROR_MODE
;
373 if (!CreateProcess (exe
, cmdline
, &sec_attrs
, NULL
, TRUE
,
374 flags
, env
, dir
, &start
, &cp
->procinfo
))
377 cp
->pid
= (int) cp
->procinfo
.dwProcessId
;
379 /* Hack for Windows 95, which assigns large (ie negative) pids */
383 /* pid must fit in a Lisp_Int */
384 cp
->pid
= cp
->pid
& INTMASK
;
391 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
395 /* create_child doesn't know what emacs' file handle will be for waiting
396 on output from the child, so we need to make this additional call
397 to register the handle with the process
398 This way the select emulator knows how to match file handles with
399 entries in child_procs. */
401 register_child (int pid
, int fd
)
405 cp
= find_child_pid (pid
);
408 DebPrint (("register_child unable to find pid %lu\n", pid
));
413 DebPrint (("register_child registered fd %d with pid %lu\n", fd
, pid
));
418 /* thread is initially blocked until select is called; set status so
419 that select will release thread */
420 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
422 /* attach child_process to fd_info */
423 if (fd_info
[fd
].cp
!= NULL
)
425 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd
));
432 /* When a process dies its pipe will break so the reader thread will
433 signal failure to the select emulator.
434 The select emulator then calls this routine to clean up.
435 Since the thread signaled failure we can assume it is exiting. */
437 reap_subprocess (child_process
*cp
)
439 if (cp
->procinfo
.hProcess
)
441 /* Reap the process */
443 /* Process should have already died before we are called. */
444 if (WaitForSingleObject (cp
->procinfo
.hProcess
, 0) != WAIT_OBJECT_0
)
445 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp
->fd
));
447 CloseHandle (cp
->procinfo
.hProcess
);
448 cp
->procinfo
.hProcess
= NULL
;
449 CloseHandle (cp
->procinfo
.hThread
);
450 cp
->procinfo
.hThread
= NULL
;
453 /* For asynchronous children, the child_proc resources will be freed
454 when the last pipe read descriptor is closed; for synchronous
455 children, we must explicitly free the resources now because
456 register_child has not been called. */
461 /* Wait for any of our existing child processes to die
462 When it does, close its handle
463 Return the pid and fill in the status if non-NULL. */
466 sys_wait (int *status
)
468 DWORD active
, retval
;
471 child_process
*cp
, *cps
[MAX_CHILDREN
];
472 HANDLE wait_hnd
[MAX_CHILDREN
];
475 if (dead_child
!= NULL
)
477 /* We want to wait for a specific child */
478 wait_hnd
[nh
] = dead_child
->procinfo
.hProcess
;
479 cps
[nh
] = dead_child
;
480 if (!wait_hnd
[nh
]) abort ();
487 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
488 /* some child_procs might be sockets; ignore them */
489 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
490 && (cp
->fd
< 0 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0))
492 wait_hnd
[nh
] = cp
->procinfo
.hProcess
;
500 /* Nothing to wait on, so fail */
507 /* Check for quit about once a second. */
509 active
= WaitForMultipleObjects (nh
, wait_hnd
, FALSE
, 1000);
510 } while (active
== WAIT_TIMEOUT
);
512 if (active
== WAIT_FAILED
)
517 else if (active
>= WAIT_OBJECT_0
518 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
520 active
-= WAIT_OBJECT_0
;
522 else if (active
>= WAIT_ABANDONED_0
523 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
525 active
-= WAIT_ABANDONED_0
;
531 if (!GetExitCodeProcess (wait_hnd
[active
], &retval
))
533 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
537 if (retval
== STILL_ACTIVE
)
539 /* Should never happen */
540 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
545 /* Massage the exit code from the process to match the format expected
546 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
547 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
549 if (retval
== STATUS_CONTROL_C_EXIT
)
557 DebPrint (("Wait signaled with process pid %d\n", cp
->pid
));
564 else if (synch_process_alive
)
566 synch_process_alive
= 0;
568 /* Report the status of the synchronous process. */
569 if (WIFEXITED (retval
))
570 synch_process_retcode
= WRETCODE (retval
);
571 else if (WIFSIGNALED (retval
))
573 int code
= WTERMSIG (retval
);
576 synchronize_system_messages_locale ();
577 signame
= strsignal (code
);
582 synch_process_death
= signame
;
585 reap_subprocess (cp
);
588 reap_subprocess (cp
);
594 w32_executable_type (char * filename
, int * is_dos_app
, int * is_cygnus_app
, int * is_gui_app
)
596 file_data executable
;
599 /* Default values in case we can't tell for sure. */
601 *is_cygnus_app
= FALSE
;
604 if (!open_input_file (&executable
, filename
))
607 p
= strrchr (filename
, '.');
609 /* We can only identify DOS .com programs from the extension. */
610 if (p
&& stricmp (p
, ".com") == 0)
612 else if (p
&& (stricmp (p
, ".bat") == 0
613 || stricmp (p
, ".cmd") == 0))
615 /* A DOS shell script - it appears that CreateProcess is happy to
616 accept this (somewhat surprisingly); presumably it looks at
617 COMSPEC to determine what executable to actually invoke.
618 Therefore, we have to do the same here as well. */
619 /* Actually, I think it uses the program association for that
620 extension, which is defined in the registry. */
621 p
= egetenv ("COMSPEC");
623 w32_executable_type (p
, is_dos_app
, is_cygnus_app
, is_gui_app
);
627 /* Look for DOS .exe signature - if found, we must also check that
628 it isn't really a 16- or 32-bit Windows exe, since both formats
629 start with a DOS program stub. Note that 16-bit Windows
630 executables use the OS/2 1.x format. */
632 IMAGE_DOS_HEADER
* dos_header
;
633 IMAGE_NT_HEADERS
* nt_header
;
635 dos_header
= (PIMAGE_DOS_HEADER
) executable
.file_base
;
636 if (dos_header
->e_magic
!= IMAGE_DOS_SIGNATURE
)
639 nt_header
= (PIMAGE_NT_HEADERS
) ((char *) dos_header
+ dos_header
->e_lfanew
);
641 if ((char *) nt_header
> (char *) dos_header
+ executable
.size
)
643 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
646 else if (nt_header
->Signature
!= IMAGE_NT_SIGNATURE
647 && LOWORD (nt_header
->Signature
) != IMAGE_OS2_SIGNATURE
)
651 else if (nt_header
->Signature
== IMAGE_NT_SIGNATURE
)
653 /* Look for cygwin.dll in DLL import list. */
654 IMAGE_DATA_DIRECTORY import_dir
=
655 nt_header
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
];
656 IMAGE_IMPORT_DESCRIPTOR
* imports
;
657 IMAGE_SECTION_HEADER
* section
;
659 section
= rva_to_section (import_dir
.VirtualAddress
, nt_header
);
660 imports
= RVA_TO_PTR (import_dir
.VirtualAddress
, section
, executable
);
662 for ( ; imports
->Name
; imports
++)
664 char * dllname
= RVA_TO_PTR (imports
->Name
, section
, executable
);
666 /* The exact name of the cygwin dll has changed with
667 various releases, but hopefully this will be reasonably
669 if (strncmp (dllname
, "cygwin", 6) == 0)
671 *is_cygnus_app
= TRUE
;
676 /* Check whether app is marked as a console or windowed (aka
677 GUI) app. Accept Posix and OS2 subsytem apps as console
679 *is_gui_app
= (nt_header
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
);
684 close_file_data (&executable
);
688 compare_env (const void *strp1
, const void *strp2
)
690 const char *str1
= *(const char **)strp1
, *str2
= *(const char **)strp2
;
692 while (*str1
&& *str2
&& *str1
!= '=' && *str2
!= '=')
694 /* Sort order in command.com/cmd.exe is based on uppercasing
695 names, so do the same here. */
696 if (toupper (*str1
) > toupper (*str2
))
698 else if (toupper (*str1
) < toupper (*str2
))
703 if (*str1
== '=' && *str2
== '=')
705 else if (*str1
== '=')
712 merge_and_sort_env (char **envp1
, char **envp2
, char **new_envp
)
728 qsort (new_envp
, num
, sizeof (char *), compare_env
);
733 /* When a new child process is created we need to register it in our list,
734 so intercept spawn requests. */
736 sys_spawnve (int mode
, char *cmdname
, char **argv
, char **envp
)
738 Lisp_Object program
, full
;
739 char *cmdline
, *env
, *parg
, **targ
;
743 int is_dos_app
, is_cygnus_app
, is_gui_app
;
746 /* We pass our process ID to our children by setting up an environment
747 variable in their environment. */
748 char ppid_env_var_buffer
[64];
749 char *extra_env
[] = {ppid_env_var_buffer
, NULL
};
750 char *sepchars
= " \t";
752 /* We don't care about the other modes */
753 if (mode
!= _P_NOWAIT
)
759 /* Handle executable names without an executable suffix. */
760 program
= make_string (cmdname
, strlen (cmdname
));
761 if (NILP (Ffile_executable_p (program
)))
767 openp (Vexec_path
, program
, Vexec_suffixes
, &full
, make_number (X_OK
));
777 /* make sure argv[0] and cmdname are both in DOS format */
778 cmdname
= SDATA (program
);
779 unixtodos_filename (cmdname
);
782 /* Determine whether program is a 16-bit DOS executable, or a w32
783 executable that is implicitly linked to the Cygnus dll (implying it
784 was compiled with the Cygnus GNU toolchain and hence relies on
785 cygwin.dll to parse the command line - we use this to decide how to
786 escape quote chars in command line args that must be quoted).
788 Also determine whether it is a GUI app, so that we don't hide its
789 initial window unless specifically requested. */
790 w32_executable_type (cmdname
, &is_dos_app
, &is_cygnus_app
, &is_gui_app
);
792 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
793 application to start it by specifying the helper app as cmdname,
794 while leaving the real app name as argv[0]. */
797 cmdname
= alloca (MAXPATHLEN
);
798 if (egetenv ("CMDPROXY"))
799 strcpy (cmdname
, egetenv ("CMDPROXY"));
802 strcpy (cmdname
, SDATA (Vinvocation_directory
));
803 strcat (cmdname
, "cmdproxy.exe");
805 unixtodos_filename (cmdname
);
808 /* we have to do some conjuring here to put argv and envp into the
809 form CreateProcess wants... argv needs to be a space separated/null
810 terminated list of parameters, and envp is a null
811 separated/double-null terminated list of parameters.
813 Additionally, zero-length args and args containing whitespace or
814 quote chars need to be wrapped in double quotes - for this to work,
815 embedded quotes need to be escaped as well. The aim is to ensure
816 the child process reconstructs the argv array we start with
817 exactly, so we treat quotes at the beginning and end of arguments
820 The w32 GNU-based library from Cygnus doubles quotes to escape
821 them, while MSVC uses backslash for escaping. (Actually the MSVC
822 startup code does attempt to recognise doubled quotes and accept
823 them, but gets it wrong and ends up requiring three quotes to get a
824 single embedded quote!) So by default we decide whether to use
825 quote or backslash as the escape character based on whether the
826 binary is apparently a Cygnus compiled app.
828 Note that using backslash to escape embedded quotes requires
829 additional special handling if an embedded quote is already
830 preceeded by backslash, or if an arg requiring quoting ends with
831 backslash. In such cases, the run of escape characters needs to be
832 doubled. For consistency, we apply this special handling as long
833 as the escape character is not quote.
835 Since we have no idea how large argv and envp are likely to be we
836 figure out list lengths on the fly and allocate them. */
838 if (!NILP (Vw32_quote_process_args
))
841 /* Override escape char by binding w32-quote-process-args to
842 desired character, or use t for auto-selection. */
843 if (INTEGERP (Vw32_quote_process_args
))
844 escape_char
= XINT (Vw32_quote_process_args
);
846 escape_char
= is_cygnus_app
? '"' : '\\';
849 /* Cygwin apps needs quoting a bit more often */
850 if (escape_char
== '"')
851 sepchars
= "\r\n\t\f '";
860 int escape_char_run
= 0;
866 if (escape_char
== '"' && *p
== '\\')
867 /* If it's a Cygwin app, \ needs to be escaped. */
871 /* allow for embedded quotes to be escaped */
874 /* handle the case where the embedded quote is already escaped */
875 if (escape_char_run
> 0)
877 /* To preserve the arg exactly, we need to double the
878 preceding escape characters (plus adding one to
879 escape the quote character itself). */
880 arglen
+= escape_char_run
;
883 else if (strchr (sepchars
, *p
) != NULL
)
888 if (*p
== escape_char
&& escape_char
!= '"')
896 /* handle the case where the arg ends with an escape char - we
897 must not let the enclosing quote be escaped. */
898 if (escape_char_run
> 0)
899 arglen
+= escape_char_run
;
901 arglen
+= strlen (*targ
++) + 1;
903 cmdline
= alloca (arglen
);
917 if ((strchr (sepchars
, *p
) != NULL
) || *p
== '"')
922 int escape_char_run
= 0;
928 last
= p
+ strlen (p
) - 1;
931 /* This version does not escape quotes if they occur at the
932 beginning or end of the arg - this could lead to incorrect
933 behaviour when the arg itself represents a command line
934 containing quoted args. I believe this was originally done
935 as a hack to make some things work, before
936 `w32-quote-process-args' was added. */
939 if (*p
== '"' && p
> first
&& p
< last
)
940 *parg
++ = escape_char
; /* escape embedded quotes */
948 /* double preceding escape chars if any */
949 while (escape_char_run
> 0)
951 *parg
++ = escape_char
;
954 /* escape all quote chars, even at beginning or end */
955 *parg
++ = escape_char
;
957 else if (escape_char
== '"' && *p
== '\\')
961 if (*p
== escape_char
&& escape_char
!= '"')
966 /* double escape chars before enclosing quote */
967 while (escape_char_run
> 0)
969 *parg
++ = escape_char
;
977 strcpy (parg
, *targ
);
978 parg
+= strlen (*targ
);
988 numenv
= 1; /* for end null */
991 arglen
+= strlen (*targ
++) + 1;
994 /* extra env vars... */
995 sprintf (ppid_env_var_buffer
, "EM_PARENT_PROCESS_ID=%d",
996 GetCurrentProcessId ());
997 arglen
+= strlen (ppid_env_var_buffer
) + 1;
1000 /* merge env passed in and extra env into one, and sort it. */
1001 targ
= (char **) alloca (numenv
* sizeof (char *));
1002 merge_and_sort_env (envp
, extra_env
, targ
);
1004 /* concatenate env entries. */
1005 env
= alloca (arglen
);
1009 strcpy (parg
, *targ
);
1010 parg
+= strlen (*targ
++);
1023 /* Now create the process. */
1024 if (!create_child (cmdname
, cmdline
, env
, is_gui_app
, &pid
, cp
))
1034 /* Emulate the select call
1035 Wait for available input on any of the given rfds, or timeout if
1036 a timeout is given and no input is detected
1037 wfds and efds are not supported and must be NULL.
1039 For simplicity, we detect the death of child processes here and
1040 synchronously call the SIGCHLD handler. Since it is possible for
1041 children to be created without a corresponding pipe handle from which
1042 to read output, we wait separately on the process handles as well as
1043 the char_avail events for each process pipe. We only call
1044 wait/reap_process when the process actually terminates.
1046 To reduce the number of places in which Emacs can be hung such that
1047 C-g is not able to interrupt it, we always wait on interrupt_handle
1048 (which is signalled by the input thread when C-g is detected). If we
1049 detect that we were woken up by C-g, we return -1 with errno set to
1050 EINTR as on Unix. */
1053 extern HANDLE keyboard_handle
;
1055 /* From w32xfns.c */
1056 extern HANDLE interrupt_handle
;
1058 /* From process.c */
1059 extern int proc_buffered_char
[];
1062 sys_select (int nfds
, SELECT_TYPE
*rfds
, SELECT_TYPE
*wfds
, SELECT_TYPE
*efds
,
1063 EMACS_TIME
*timeout
)
1066 DWORD timeout_ms
, start_time
;
1069 child_process
*cp
, *cps
[MAX_CHILDREN
];
1070 HANDLE wait_hnd
[MAXDESC
+ MAX_CHILDREN
];
1071 int fdindex
[MAXDESC
]; /* mapping from wait handles back to descriptors */
1073 timeout_ms
= timeout
? (timeout
->tv_sec
* 1000 + timeout
->tv_usec
/ 1000) : INFINITE
;
1075 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1076 if (rfds
== NULL
&& wfds
== NULL
&& efds
== NULL
&& timeout
!= NULL
)
1082 /* Otherwise, we only handle rfds, so fail otherwise. */
1083 if (rfds
== NULL
|| wfds
!= NULL
|| efds
!= NULL
)
1093 /* Always wait on interrupt_handle, to detect C-g (quit). */
1094 wait_hnd
[0] = interrupt_handle
;
1097 /* Build a list of pipe handles to wait on. */
1099 for (i
= 0; i
< nfds
; i
++)
1100 if (FD_ISSET (i
, &orfds
))
1104 if (keyboard_handle
)
1106 /* Handle stdin specially */
1107 wait_hnd
[nh
] = keyboard_handle
;
1112 /* Check for any emacs-generated input in the queue since
1113 it won't be detected in the wait */
1114 if (detect_input_pending ())
1122 /* Child process and socket input */
1126 int current_status
= cp
->status
;
1128 if (current_status
== STATUS_READ_ACKNOWLEDGED
)
1130 /* Tell reader thread which file handle to use. */
1132 /* Wake up the reader thread for this process */
1133 cp
->status
= STATUS_READ_READY
;
1134 if (!SetEvent (cp
->char_consumed
))
1135 DebPrint (("nt_select.SetEvent failed with "
1136 "%lu for fd %ld\n", GetLastError (), i
));
1139 #ifdef CHECK_INTERLOCK
1140 /* slightly crude cross-checking of interlock between threads */
1142 current_status
= cp
->status
;
1143 if (WaitForSingleObject (cp
->char_avail
, 0) == WAIT_OBJECT_0
)
1145 /* char_avail has been signalled, so status (which may
1146 have changed) should indicate read has completed
1147 but has not been acknowledged. */
1148 current_status
= cp
->status
;
1149 if (current_status
!= STATUS_READ_SUCCEEDED
1150 && current_status
!= STATUS_READ_FAILED
)
1151 DebPrint (("char_avail set, but read not completed: status %d\n",
1156 /* char_avail has not been signalled, so status should
1157 indicate that read is in progress; small possibility
1158 that read has completed but event wasn't yet signalled
1159 when we tested it (because a context switch occurred
1160 or if running on separate CPUs). */
1161 if (current_status
!= STATUS_READ_READY
1162 && current_status
!= STATUS_READ_IN_PROGRESS
1163 && current_status
!= STATUS_READ_SUCCEEDED
1164 && current_status
!= STATUS_READ_FAILED
)
1165 DebPrint (("char_avail reset, but read status is bad: %d\n",
1169 wait_hnd
[nh
] = cp
->char_avail
;
1171 if (!wait_hnd
[nh
]) abort ();
1174 DebPrint (("select waiting on child %d fd %d\n",
1175 cp
-child_procs
, i
));
1180 /* Unable to find something to wait on for this fd, skip */
1182 /* Note that this is not a fatal error, and can in fact
1183 happen in unusual circumstances. Specifically, if
1184 sys_spawnve fails, eg. because the program doesn't
1185 exist, and debug-on-error is t so Fsignal invokes a
1186 nested input loop, then the process output pipe is
1187 still included in input_wait_mask with no child_proc
1188 associated with it. (It is removed when the debugger
1189 exits the nested input loop and the error is thrown.) */
1191 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i
));
1197 /* Add handles of child processes. */
1199 for (cp
= child_procs
+(child_proc_count
-1); cp
>= child_procs
; cp
--)
1200 /* Some child_procs might be sockets; ignore them. Also some
1201 children may have died already, but we haven't finished reading
1202 the process output; ignore them too. */
1203 if (CHILD_ACTIVE (cp
) && cp
->procinfo
.hProcess
1205 || (fd_info
[cp
->fd
].flags
& FILE_SEND_SIGCHLD
) == 0
1206 || (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) != 0)
1209 wait_hnd
[nh
+ nc
] = cp
->procinfo
.hProcess
;
1214 /* Nothing to look for, so we didn't find anything */
1222 start_time
= GetTickCount ();
1224 /* Wait for input or child death to be signalled. If user input is
1225 allowed, then also accept window messages. */
1226 if (FD_ISSET (0, &orfds
))
1227 active
= MsgWaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
,
1230 active
= WaitForMultipleObjects (nh
+ nc
, wait_hnd
, FALSE
, timeout_ms
);
1232 if (active
== WAIT_FAILED
)
1234 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1235 nh
+ nc
, timeout_ms
, GetLastError ()));
1236 /* don't return EBADF - this causes wait_reading_process_output to
1237 abort; WAIT_FAILED is returned when single-stepping under
1238 Windows 95 after switching thread focus in debugger, and
1239 possibly at other times. */
1243 else if (active
== WAIT_TIMEOUT
)
1247 else if (active
>= WAIT_OBJECT_0
1248 && active
< WAIT_OBJECT_0
+MAXIMUM_WAIT_OBJECTS
)
1250 active
-= WAIT_OBJECT_0
;
1252 else if (active
>= WAIT_ABANDONED_0
1253 && active
< WAIT_ABANDONED_0
+MAXIMUM_WAIT_OBJECTS
)
1255 active
-= WAIT_ABANDONED_0
;
1260 /* Loop over all handles after active (now officially documented as
1261 being the first signalled handle in the array). We do this to
1262 ensure fairness, so that all channels with data available will be
1263 processed - otherwise higher numbered channels could be starved. */
1266 if (active
== nh
+ nc
)
1268 /* There are messages in the lisp thread's queue; we must
1269 drain the queue now to ensure they are processed promptly,
1270 because if we don't do so, we will not be woken again until
1271 further messages arrive.
1273 NB. If ever we allow window message procedures to callback
1274 into lisp, we will need to ensure messages are dispatched
1275 at a safe time for lisp code to be run (*), and we may also
1276 want to provide some hooks in the dispatch loop to cater
1277 for modeless dialogs created by lisp (ie. to register
1278 window handles to pass to IsDialogMessage).
1280 (*) Note that MsgWaitForMultipleObjects above is an
1281 internal dispatch point for messages that are sent to
1282 windows created by this thread. */
1283 drain_message_queue ();
1285 else if (active
>= nh
)
1287 cp
= cps
[active
- nh
];
1289 /* We cannot always signal SIGCHLD immediately; if we have not
1290 finished reading the process output, we must delay sending
1291 SIGCHLD until we do. */
1293 if (cp
->fd
>= 0 && (fd_info
[cp
->fd
].flags
& FILE_AT_EOF
) == 0)
1294 fd_info
[cp
->fd
].flags
|= FILE_SEND_SIGCHLD
;
1295 /* SIG_DFL for SIGCHLD is ignore */
1296 else if (sig_handlers
[SIGCHLD
] != SIG_DFL
&&
1297 sig_handlers
[SIGCHLD
] != SIG_IGN
)
1300 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1304 sig_handlers
[SIGCHLD
] (SIGCHLD
);
1308 else if (fdindex
[active
] == -1)
1310 /* Quit (C-g) was detected. */
1314 else if (fdindex
[active
] == 0)
1316 /* Keyboard input available */
1322 /* must be a socket or pipe - read ahead should have
1323 completed, either succeeding or failing. */
1324 FD_SET (fdindex
[active
], rfds
);
1328 /* Even though wait_reading_process_output only reads from at most
1329 one channel, we must process all channels here so that we reap
1330 all children that have died. */
1331 while (++active
< nh
+ nc
)
1332 if (WaitForSingleObject (wait_hnd
[active
], 0) == WAIT_OBJECT_0
)
1334 } while (active
< nh
+ nc
);
1336 /* If no input has arrived and timeout hasn't expired, wait again. */
1339 DWORD elapsed
= GetTickCount () - start_time
;
1341 if (timeout_ms
> elapsed
) /* INFINITE is MAX_UINT */
1343 if (timeout_ms
!= INFINITE
)
1344 timeout_ms
-= elapsed
;
1345 goto count_children
;
1352 /* Substitute for certain kill () operations */
1354 static BOOL CALLBACK
1355 find_child_console (HWND hwnd
, LPARAM arg
)
1357 child_process
* cp
= (child_process
*) arg
;
1361 thread_id
= GetWindowThreadProcessId (hwnd
, &process_id
);
1362 if (process_id
== cp
->procinfo
.dwProcessId
)
1364 char window_class
[32];
1366 GetClassName (hwnd
, window_class
, sizeof (window_class
));
1367 if (strcmp (window_class
,
1368 (os_subtype
== OS_WIN95
)
1370 : "ConsoleWindowClass") == 0)
1381 sys_kill (int pid
, int sig
)
1385 int need_to_free
= 0;
1388 /* Only handle signals that will result in the process dying */
1389 if (sig
!= SIGINT
&& sig
!= SIGKILL
&& sig
!= SIGQUIT
&& sig
!= SIGHUP
)
1395 cp
= find_child_pid (pid
);
1398 proc_hand
= OpenProcess (PROCESS_TERMINATE
, 0, pid
);
1399 if (proc_hand
== NULL
)
1408 proc_hand
= cp
->procinfo
.hProcess
;
1409 pid
= cp
->procinfo
.dwProcessId
;
1411 /* Try to locate console window for process. */
1412 EnumWindows (find_child_console
, (LPARAM
) cp
);
1415 if (sig
== SIGINT
|| sig
== SIGQUIT
)
1417 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1419 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
1420 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1421 BYTE vk_break_code
= (sig
== SIGINT
) ? 'C' : VK_CANCEL
;
1422 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1423 HWND foreground_window
;
1425 if (break_scan_code
== 0)
1427 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1428 vk_break_code
= 'C';
1429 break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
1432 foreground_window
= GetForegroundWindow ();
1433 if (foreground_window
)
1435 /* NT 5.0, and apparently also Windows 98, will not allow
1436 a Window to be set to foreground directly without the
1437 user's involvement. The workaround is to attach
1438 ourselves to the thread that owns the foreground
1439 window, since that is the only thread that can set the
1440 foreground window. */
1441 DWORD foreground_thread
, child_thread
;
1443 GetWindowThreadProcessId (foreground_window
, NULL
);
1444 if (foreground_thread
== GetCurrentThreadId ()
1445 || !AttachThreadInput (GetCurrentThreadId (),
1446 foreground_thread
, TRUE
))
1447 foreground_thread
= 0;
1449 child_thread
= GetWindowThreadProcessId (cp
->hwnd
, NULL
);
1450 if (child_thread
== GetCurrentThreadId ()
1451 || !AttachThreadInput (GetCurrentThreadId (),
1452 child_thread
, TRUE
))
1455 /* Set the foreground window to the child. */
1456 if (SetForegroundWindow (cp
->hwnd
))
1458 /* Generate keystrokes as if user had typed Ctrl-Break or
1460 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
1461 keybd_event (vk_break_code
, break_scan_code
,
1462 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
1463 keybd_event (vk_break_code
, break_scan_code
,
1464 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
1465 | KEYEVENTF_KEYUP
, 0);
1466 keybd_event (VK_CONTROL
, control_scan_code
,
1467 KEYEVENTF_KEYUP
, 0);
1469 /* Sleep for a bit to give time for Emacs frame to respond
1470 to focus change events (if Emacs was active app). */
1473 SetForegroundWindow (foreground_window
);
1475 /* Detach from the foreground and child threads now that
1476 the foreground switching is over. */
1477 if (foreground_thread
)
1478 AttachThreadInput (GetCurrentThreadId (),
1479 foreground_thread
, FALSE
);
1481 AttachThreadInput (GetCurrentThreadId (),
1482 child_thread
, FALSE
);
1485 /* Ctrl-Break is NT equivalent of SIGINT. */
1486 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT
, pid
))
1488 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1489 "for pid %lu\n", GetLastError (), pid
));
1496 if (NILP (Vw32_start_process_share_console
) && cp
&& cp
->hwnd
)
1499 if (os_subtype
== OS_WIN95
)
1502 Another possibility is to try terminating the VDM out-right by
1503 calling the Shell VxD (id 0x17) V86 interface, function #4
1504 "SHELL_Destroy_VM", ie.
1510 First need to determine the current VM handle, and then arrange for
1511 the shellapi call to be made from the system vm (by using
1512 Switch_VM_and_callback).
1514 Could try to invoke DestroyVM through CallVxD.
1518 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1519 to hang when cmdproxy is used in conjunction with
1520 command.com for an interactive shell. Posting
1521 WM_CLOSE pops up a dialog that, when Yes is selected,
1522 does the same thing. TerminateProcess is also less
1523 than ideal in that subprocesses tend to stick around
1524 until the machine is shutdown, but at least it
1525 doesn't freeze the 16-bit subsystem. */
1526 PostMessage (cp
->hwnd
, WM_QUIT
, 0xff, 0);
1528 if (!TerminateProcess (proc_hand
, 0xff))
1530 DebPrint (("sys_kill.TerminateProcess returned %d "
1531 "for pid %lu\n", GetLastError (), pid
));
1538 PostMessage (cp
->hwnd
, WM_CLOSE
, 0, 0);
1540 /* Kill the process. On W32 this doesn't kill child processes
1541 so it doesn't work very well for shells which is why it's not
1542 used in every case. */
1543 else if (!TerminateProcess (proc_hand
, 0xff))
1545 DebPrint (("sys_kill.TerminateProcess returned %d "
1546 "for pid %lu\n", GetLastError (), pid
));
1553 CloseHandle (proc_hand
);
1558 /* extern int report_file_error (char *, Lisp_Object); */
1560 /* The following two routines are used to manipulate stdin, stdout, and
1561 stderr of our child processes.
1563 Assuming that in, out, and err are *not* inheritable, we make them
1564 stdin, stdout, and stderr of the child as follows:
1566 - Save the parent's current standard handles.
1567 - Set the std handles to inheritable duplicates of the ones being passed in.
1568 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1569 NT file handle for a crt file descriptor.)
1570 - Spawn the child, which inherits in, out, and err as stdin,
1571 stdout, and stderr. (see Spawnve)
1572 - Close the std handles passed to the child.
1573 - Reset the parent's standard handles to the saved handles.
1574 (see reset_standard_handles)
1575 We assume that the caller closes in, out, and err after calling us. */
1578 prepare_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1581 HANDLE newstdin
, newstdout
, newstderr
;
1583 parent
= GetCurrentProcess ();
1585 handles
[0] = GetStdHandle (STD_INPUT_HANDLE
);
1586 handles
[1] = GetStdHandle (STD_OUTPUT_HANDLE
);
1587 handles
[2] = GetStdHandle (STD_ERROR_HANDLE
);
1589 /* make inheritable copies of the new handles */
1590 if (!DuplicateHandle (parent
,
1591 (HANDLE
) _get_osfhandle (in
),
1596 DUPLICATE_SAME_ACCESS
))
1597 report_file_error ("Duplicating input handle for child", Qnil
);
1599 if (!DuplicateHandle (parent
,
1600 (HANDLE
) _get_osfhandle (out
),
1605 DUPLICATE_SAME_ACCESS
))
1606 report_file_error ("Duplicating output handle for child", Qnil
);
1608 if (!DuplicateHandle (parent
,
1609 (HANDLE
) _get_osfhandle (err
),
1614 DUPLICATE_SAME_ACCESS
))
1615 report_file_error ("Duplicating error handle for child", Qnil
);
1617 /* and store them as our std handles */
1618 if (!SetStdHandle (STD_INPUT_HANDLE
, newstdin
))
1619 report_file_error ("Changing stdin handle", Qnil
);
1621 if (!SetStdHandle (STD_OUTPUT_HANDLE
, newstdout
))
1622 report_file_error ("Changing stdout handle", Qnil
);
1624 if (!SetStdHandle (STD_ERROR_HANDLE
, newstderr
))
1625 report_file_error ("Changing stderr handle", Qnil
);
1629 reset_standard_handles (int in
, int out
, int err
, HANDLE handles
[3])
1631 /* close the duplicated handles passed to the child */
1632 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
1633 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
1634 CloseHandle (GetStdHandle (STD_ERROR_HANDLE
));
1636 /* now restore parent's saved std handles */
1637 SetStdHandle (STD_INPUT_HANDLE
, handles
[0]);
1638 SetStdHandle (STD_OUTPUT_HANDLE
, handles
[1]);
1639 SetStdHandle (STD_ERROR_HANDLE
, handles
[2]);
1643 set_process_dir (char * dir
)
1650 /* To avoid problems with winsock implementations that work over dial-up
1651 connections causing or requiring a connection to exist while Emacs is
1652 running, Emacs no longer automatically loads winsock on startup if it
1653 is present. Instead, it will be loaded when open-network-stream is
1656 To allow full control over when winsock is loaded, we provide these
1657 two functions to dynamically load and unload winsock. This allows
1658 dial-up users to only be connected when they actually need to use
1662 extern HANDLE winsock_lib
;
1663 extern BOOL
term_winsock (void);
1664 extern BOOL
init_winsock (int load_now
);
1666 extern Lisp_Object Vsystem_name
;
1668 DEFUN ("w32-has-winsock", Fw32_has_winsock
, Sw32_has_winsock
, 0, 1, 0,
1669 doc
: /* Test for presence of the Windows socket library `winsock'.
1670 Returns non-nil if winsock support is present, nil otherwise.
1672 If the optional argument LOAD-NOW is non-nil, the winsock library is
1673 also loaded immediately if not already loaded. If winsock is loaded,
1674 the winsock local hostname is returned (since this may be different from
1675 the value of `system-name' and should supplant it), otherwise t is
1676 returned to indicate winsock support is present. */)
1678 Lisp_Object load_now
;
1682 have_winsock
= init_winsock (!NILP (load_now
));
1685 if (winsock_lib
!= NULL
)
1687 /* Return new value for system-name. The best way to do this
1688 is to call init_system_name, saving and restoring the
1689 original value to avoid side-effects. */
1690 Lisp_Object orig_hostname
= Vsystem_name
;
1691 Lisp_Object hostname
;
1693 init_system_name ();
1694 hostname
= Vsystem_name
;
1695 Vsystem_name
= orig_hostname
;
1703 DEFUN ("w32-unload-winsock", Fw32_unload_winsock
, Sw32_unload_winsock
,
1705 doc
: /* Unload the Windows socket library `winsock' if loaded.
1706 This is provided to allow dial-up socket connections to be disconnected
1707 when no longer needed. Returns nil without unloading winsock if any
1708 socket connections still exist. */)
1711 return term_winsock () ? Qt
: Qnil
;
1714 #endif /* HAVE_SOCKETS */
1717 /* Some miscellaneous functions that are Windows specific, but not GUI
1718 specific (ie. are applicable in terminal or batch mode as well). */
1720 /* lifted from fileio.c */
1721 #define CORRECT_DIR_SEPS(s) \
1722 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1723 else unixtodos_filename (s); \
1726 DEFUN ("w32-short-file-name", Fw32_short_file_name
, Sw32_short_file_name
, 1, 1, 0,
1727 doc
: /* Return the short file name version (8.3) of the full path of FILENAME.
1728 If FILENAME does not exist, return nil.
1729 All path elements in FILENAME are converted to their short names. */)
1731 Lisp_Object filename
;
1733 char shortname
[MAX_PATH
];
1735 CHECK_STRING (filename
);
1737 /* first expand it. */
1738 filename
= Fexpand_file_name (filename
, Qnil
);
1740 /* luckily, this returns the short version of each element in the path. */
1741 if (GetShortPathName (SDATA (filename
), shortname
, MAX_PATH
) == 0)
1744 CORRECT_DIR_SEPS (shortname
);
1746 return build_string (shortname
);
1750 DEFUN ("w32-long-file-name", Fw32_long_file_name
, Sw32_long_file_name
,
1752 doc
: /* Return the long file name version of the full path of FILENAME.
1753 If FILENAME does not exist, return nil.
1754 All path elements in FILENAME are converted to their long names. */)
1756 Lisp_Object filename
;
1758 char longname
[ MAX_PATH
];
1760 CHECK_STRING (filename
);
1762 /* first expand it. */
1763 filename
= Fexpand_file_name (filename
, Qnil
);
1765 if (!w32_get_long_filename (SDATA (filename
), longname
, MAX_PATH
))
1768 CORRECT_DIR_SEPS (longname
);
1770 return build_string (longname
);
1773 DEFUN ("w32-set-process-priority", Fw32_set_process_priority
,
1774 Sw32_set_process_priority
, 2, 2, 0,
1775 doc
: /* Set the priority of PROCESS to PRIORITY.
1776 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1777 priority of the process whose pid is PROCESS is changed.
1778 PRIORITY should be one of the symbols high, normal, or low;
1779 any other symbol will be interpreted as normal.
1781 If successful, the return value is t, otherwise nil. */)
1783 Lisp_Object process
, priority
;
1785 HANDLE proc_handle
= GetCurrentProcess ();
1786 DWORD priority_class
= NORMAL_PRIORITY_CLASS
;
1787 Lisp_Object result
= Qnil
;
1789 CHECK_SYMBOL (priority
);
1791 if (!NILP (process
))
1796 CHECK_NUMBER (process
);
1798 /* Allow pid to be an internally generated one, or one obtained
1799 externally. This is necessary because real pids on Win95 are
1802 pid
= XINT (process
);
1803 cp
= find_child_pid (pid
);
1805 pid
= cp
->procinfo
.dwProcessId
;
1807 proc_handle
= OpenProcess (PROCESS_SET_INFORMATION
, FALSE
, pid
);
1810 if (EQ (priority
, Qhigh
))
1811 priority_class
= HIGH_PRIORITY_CLASS
;
1812 else if (EQ (priority
, Qlow
))
1813 priority_class
= IDLE_PRIORITY_CLASS
;
1815 if (proc_handle
!= NULL
)
1817 if (SetPriorityClass (proc_handle
, priority_class
))
1819 if (!NILP (process
))
1820 CloseHandle (proc_handle
);
1826 #ifdef HAVE_LANGINFO_CODESET
1827 /* Emulation of nl_langinfo. Used in fns.c:Flocale_info. */
1828 char *nl_langinfo (nl_item item
)
1830 /* Conversion of Posix item numbers to their Windows equivalents. */
1831 static const LCTYPE w32item
[] = {
1832 LOCALE_IDEFAULTANSICODEPAGE
,
1833 LOCALE_SDAYNAME1
, LOCALE_SDAYNAME2
, LOCALE_SDAYNAME3
,
1834 LOCALE_SDAYNAME4
, LOCALE_SDAYNAME5
, LOCALE_SDAYNAME6
, LOCALE_SDAYNAME7
,
1835 LOCALE_SMONTHNAME1
, LOCALE_SMONTHNAME2
, LOCALE_SMONTHNAME3
,
1836 LOCALE_SMONTHNAME4
, LOCALE_SMONTHNAME5
, LOCALE_SMONTHNAME6
,
1837 LOCALE_SMONTHNAME7
, LOCALE_SMONTHNAME8
, LOCALE_SMONTHNAME9
,
1838 LOCALE_SMONTHNAME10
, LOCALE_SMONTHNAME11
, LOCALE_SMONTHNAME12
1841 static char *nl_langinfo_buf
= NULL
;
1842 static int nl_langinfo_len
= 0;
1844 if (nl_langinfo_len
<= 0)
1845 nl_langinfo_buf
= xmalloc (nl_langinfo_len
= 1);
1847 if (item
< 0 || item
>= _NL_NUM
)
1848 nl_langinfo_buf
[0] = 0;
1851 LCID cloc
= GetThreadLocale ();
1852 int need_len
= GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1856 nl_langinfo_buf
[0] = 0;
1859 if (item
== CODESET
)
1861 need_len
+= 2; /* for the "cp" prefix */
1862 if (need_len
< 8) /* for the case we call GetACP */
1865 if (nl_langinfo_len
<= need_len
)
1866 nl_langinfo_buf
= xrealloc (nl_langinfo_buf
,
1867 nl_langinfo_len
= need_len
);
1868 if (!GetLocaleInfo (cloc
, w32item
[item
] | LOCALE_USE_CP_ACP
,
1869 nl_langinfo_buf
, nl_langinfo_len
))
1870 nl_langinfo_buf
[0] = 0;
1871 else if (item
== CODESET
)
1873 if (strcmp (nl_langinfo_buf
, "0") == 0 /* CP_ACP */
1874 || strcmp (nl_langinfo_buf
, "1") == 0) /* CP_OEMCP */
1875 sprintf (nl_langinfo_buf
, "cp%u", GetACP ());
1878 memmove (nl_langinfo_buf
+ 2, nl_langinfo_buf
,
1879 strlen (nl_langinfo_buf
) + 1);
1880 nl_langinfo_buf
[0] = 'c';
1881 nl_langinfo_buf
[1] = 'p';
1886 return nl_langinfo_buf
;
1888 #endif /* HAVE_LANGINFO_CODESET */
1890 DEFUN ("w32-get-locale-info", Fw32_get_locale_info
,
1891 Sw32_get_locale_info
, 1, 2, 0,
1892 doc
: /* Return information about the Windows locale LCID.
1893 By default, return a three letter locale code which encodes the default
1894 language as the first two characters, and the country or regionial variant
1895 as the third letter. For example, ENU refers to `English (United States)',
1896 while ENC means `English (Canadian)'.
1898 If the optional argument LONGFORM is t, the long form of the locale
1899 name is returned, e.g. `English (United States)' instead; if LONGFORM
1900 is a number, it is interpreted as an LCTYPE constant and the corresponding
1901 locale information is returned.
1903 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1905 Lisp_Object lcid
, longform
;
1909 char abbrev_name
[32] = { 0 };
1910 char full_name
[256] = { 0 };
1912 CHECK_NUMBER (lcid
);
1914 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
1917 if (NILP (longform
))
1919 got_abbrev
= GetLocaleInfo (XINT (lcid
),
1920 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1921 abbrev_name
, sizeof (abbrev_name
));
1923 return build_string (abbrev_name
);
1925 else if (EQ (longform
, Qt
))
1927 got_full
= GetLocaleInfo (XINT (lcid
),
1928 LOCALE_SLANGUAGE
| LOCALE_USE_CP_ACP
,
1929 full_name
, sizeof (full_name
));
1931 return build_string (full_name
);
1933 else if (NUMBERP (longform
))
1935 got_full
= GetLocaleInfo (XINT (lcid
),
1937 full_name
, sizeof (full_name
));
1939 return make_unibyte_string (full_name
, got_full
);
1946 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id
,
1947 Sw32_get_current_locale_id
, 0, 0, 0,
1948 doc
: /* Return Windows locale id for current locale setting.
1949 This is a numerical value; use `w32-get-locale-info' to convert to a
1950 human-readable form. */)
1953 return make_number (GetThreadLocale ());
1956 DWORD
int_from_hex (char * s
)
1959 static char hex
[] = "0123456789abcdefABCDEF";
1962 while (*s
&& (p
= strchr(hex
, *s
)) != NULL
)
1964 unsigned digit
= p
- hex
;
1967 val
= val
* 16 + digit
;
1973 /* We need to build a global list, since the EnumSystemLocale callback
1974 function isn't given a context pointer. */
1975 Lisp_Object Vw32_valid_locale_ids
;
1977 BOOL CALLBACK
enum_locale_fn (LPTSTR localeNum
)
1979 DWORD id
= int_from_hex (localeNum
);
1980 Vw32_valid_locale_ids
= Fcons (make_number (id
), Vw32_valid_locale_ids
);
1984 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids
,
1985 Sw32_get_valid_locale_ids
, 0, 0, 0,
1986 doc
: /* Return list of all valid Windows locale ids.
1987 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1988 human-readable form. */)
1991 Vw32_valid_locale_ids
= Qnil
;
1993 EnumSystemLocales (enum_locale_fn
, LCID_SUPPORTED
);
1995 Vw32_valid_locale_ids
= Fnreverse (Vw32_valid_locale_ids
);
1996 return Vw32_valid_locale_ids
;
2000 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id
, Sw32_get_default_locale_id
, 0, 1, 0,
2001 doc
: /* Return Windows locale id for default locale setting.
2002 By default, the system default locale setting is returned; if the optional
2003 parameter USERP is non-nil, the user default locale setting is returned.
2004 This is a numerical value; use `w32-get-locale-info' to convert to a
2005 human-readable form. */)
2010 return make_number (GetSystemDefaultLCID ());
2011 return make_number (GetUserDefaultLCID ());
2015 DEFUN ("w32-set-current-locale", Fw32_set_current_locale
, Sw32_set_current_locale
, 1, 1, 0,
2016 doc
: /* Make Windows locale LCID be the current locale setting for Emacs.
2017 If successful, the new locale id is returned, otherwise nil. */)
2021 CHECK_NUMBER (lcid
);
2023 if (!IsValidLocale (XINT (lcid
), LCID_SUPPORTED
))
2026 if (!SetThreadLocale (XINT (lcid
)))
2029 /* Need to set input thread locale if present. */
2030 if (dwWindowsThreadId
)
2031 /* Reply is not needed. */
2032 PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETLOCALE
, XINT (lcid
), 0);
2034 return make_number (GetThreadLocale ());
2038 /* We need to build a global list, since the EnumCodePages callback
2039 function isn't given a context pointer. */
2040 Lisp_Object Vw32_valid_codepages
;
2042 BOOL CALLBACK
enum_codepage_fn (LPTSTR codepageNum
)
2044 DWORD id
= atoi (codepageNum
);
2045 Vw32_valid_codepages
= Fcons (make_number (id
), Vw32_valid_codepages
);
2049 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages
,
2050 Sw32_get_valid_codepages
, 0, 0, 0,
2051 doc
: /* Return list of all valid Windows codepages. */)
2054 Vw32_valid_codepages
= Qnil
;
2056 EnumSystemCodePages (enum_codepage_fn
, CP_SUPPORTED
);
2058 Vw32_valid_codepages
= Fnreverse (Vw32_valid_codepages
);
2059 return Vw32_valid_codepages
;
2063 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage
,
2064 Sw32_get_console_codepage
, 0, 0, 0,
2065 doc
: /* Return current Windows codepage for console input. */)
2068 return make_number (GetConsoleCP ());
2072 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage
,
2073 Sw32_set_console_codepage
, 1, 1, 0,
2074 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2075 The codepage setting affects keyboard input and display in tty mode.
2076 If successful, the new CP is returned, otherwise nil. */)
2082 if (!IsValidCodePage (XINT (cp
)))
2085 if (!SetConsoleCP (XINT (cp
)))
2088 return make_number (GetConsoleCP ());
2092 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage
,
2093 Sw32_get_console_output_codepage
, 0, 0, 0,
2094 doc
: /* Return current Windows codepage for console output. */)
2097 return make_number (GetConsoleOutputCP ());
2101 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage
,
2102 Sw32_set_console_output_codepage
, 1, 1, 0,
2103 doc
: /* Make Windows codepage CP be the current codepage setting for Emacs.
2104 The codepage setting affects keyboard input and display in tty mode.
2105 If successful, the new CP is returned, otherwise nil. */)
2111 if (!IsValidCodePage (XINT (cp
)))
2114 if (!SetConsoleOutputCP (XINT (cp
)))
2117 return make_number (GetConsoleOutputCP ());
2121 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset
,
2122 Sw32_get_codepage_charset
, 1, 1, 0,
2123 doc
: /* Return charset of codepage CP.
2124 Returns nil if the codepage is not valid. */)
2132 if (!IsValidCodePage (XINT (cp
)))
2135 if (TranslateCharsetInfo ((DWORD
*) XINT (cp
), &info
, TCI_SRCCODEPAGE
))
2136 return make_number (info
.ciCharset
);
2142 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts
,
2143 Sw32_get_valid_keyboard_layouts
, 0, 0, 0,
2144 doc
: /* Return list of Windows keyboard languages and layouts.
2145 The return value is a list of pairs of language id and layout id. */)
2148 int num_layouts
= GetKeyboardLayoutList (0, NULL
);
2149 HKL
* layouts
= (HKL
*) alloca (num_layouts
* sizeof (HKL
));
2150 Lisp_Object obj
= Qnil
;
2152 if (GetKeyboardLayoutList (num_layouts
, layouts
) == num_layouts
)
2154 while (--num_layouts
>= 0)
2156 DWORD kl
= (DWORD
) layouts
[num_layouts
];
2158 obj
= Fcons (Fcons (make_number (kl
& 0xffff),
2159 make_number ((kl
>> 16) & 0xffff)),
2168 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout
,
2169 Sw32_get_keyboard_layout
, 0, 0, 0,
2170 doc
: /* Return current Windows keyboard language and layout.
2171 The return value is the cons of the language id and the layout id. */)
2174 DWORD kl
= (DWORD
) GetKeyboardLayout (dwWindowsThreadId
);
2176 return Fcons (make_number (kl
& 0xffff),
2177 make_number ((kl
>> 16) & 0xffff));
2181 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout
,
2182 Sw32_set_keyboard_layout
, 1, 1, 0,
2183 doc
: /* Make LAYOUT be the current keyboard layout for Emacs.
2184 The keyboard layout setting affects interpretation of keyboard input.
2185 If successful, the new layout id is returned, otherwise nil. */)
2191 CHECK_CONS (layout
);
2192 CHECK_NUMBER_CAR (layout
);
2193 CHECK_NUMBER_CDR (layout
);
2195 kl
= (XINT (XCAR (layout
)) & 0xffff)
2196 | (XINT (XCDR (layout
)) << 16);
2198 /* Synchronize layout with input thread. */
2199 if (dwWindowsThreadId
)
2201 if (PostThreadMessage (dwWindowsThreadId
, WM_EMACS_SETKEYBOARDLAYOUT
,
2205 GetMessage (&msg
, NULL
, WM_EMACS_DONE
, WM_EMACS_DONE
);
2207 if (msg
.wParam
== 0)
2211 else if (!ActivateKeyboardLayout ((HKL
) kl
, 0))
2214 return Fw32_get_keyboard_layout ();
2220 Qhigh
= intern ("high");
2221 Qlow
= intern ("low");
2226 defsubr (&Sw32_has_winsock
);
2227 defsubr (&Sw32_unload_winsock
);
2229 defsubr (&Sw32_short_file_name
);
2230 defsubr (&Sw32_long_file_name
);
2231 defsubr (&Sw32_set_process_priority
);
2232 defsubr (&Sw32_get_locale_info
);
2233 defsubr (&Sw32_get_current_locale_id
);
2234 defsubr (&Sw32_get_default_locale_id
);
2235 defsubr (&Sw32_get_valid_locale_ids
);
2236 defsubr (&Sw32_set_current_locale
);
2238 defsubr (&Sw32_get_console_codepage
);
2239 defsubr (&Sw32_set_console_codepage
);
2240 defsubr (&Sw32_get_console_output_codepage
);
2241 defsubr (&Sw32_set_console_output_codepage
);
2242 defsubr (&Sw32_get_valid_codepages
);
2243 defsubr (&Sw32_get_codepage_charset
);
2245 defsubr (&Sw32_get_valid_keyboard_layouts
);
2246 defsubr (&Sw32_get_keyboard_layout
);
2247 defsubr (&Sw32_set_keyboard_layout
);
2249 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args
,
2250 doc
: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2251 Because Windows does not directly pass argv arrays to child processes,
2252 programs have to reconstruct the argv array by parsing the command
2253 line string. For an argument to contain a space, it must be enclosed
2254 in double quotes or it will be parsed as multiple arguments.
2256 If the value is a character, that character will be used to escape any
2257 quote characters that appear, otherwise a suitable escape character
2258 will be chosen based on the type of the program. */);
2259 Vw32_quote_process_args
= Qt
;
2261 DEFVAR_LISP ("w32-start-process-show-window",
2262 &Vw32_start_process_show_window
,
2263 doc
: /* When nil, new child processes hide their windows.
2264 When non-nil, they show their window in the method of their choice.
2265 This variable doesn't affect GUI applications, which will never be hidden. */);
2266 Vw32_start_process_show_window
= Qnil
;
2268 DEFVAR_LISP ("w32-start-process-share-console",
2269 &Vw32_start_process_share_console
,
2270 doc
: /* When nil, new child processes are given a new console.
2271 When non-nil, they share the Emacs console; this has the limitation of
2272 allowing only one DOS subprocess to run at a time (whether started directly
2273 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2274 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2275 otherwise respond to interrupts from Emacs. */);
2276 Vw32_start_process_share_console
= Qnil
;
2278 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2279 &Vw32_start_process_inherit_error_mode
,
2280 doc
: /* When nil, new child processes revert to the default error mode.
2281 When non-nil, they inherit their error mode setting from Emacs, which stops
2282 them blocking when trying to access unmounted drives etc. */);
2283 Vw32_start_process_inherit_error_mode
= Qt
;
2285 DEFVAR_INT ("w32-pipe-read-delay", &w32_pipe_read_delay
,
2286 doc
: /* Forced delay before reading subprocess output.
2287 This is done to improve the buffering of subprocess output, by
2288 avoiding the inefficiency of frequently reading small amounts of data.
2290 If positive, the value is the number of milliseconds to sleep before
2291 reading the subprocess output. If negative, the magnitude is the number
2292 of time slices to wait (effectively boosting the priority of the child
2293 process temporarily). A value of zero disables waiting entirely. */);
2294 w32_pipe_read_delay
= 50;
2296 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names
,
2297 doc
: /* Non-nil means convert all-upper case file names to lower case.
2298 This applies when performing completions and file name expansion.
2299 Note that the value of this setting also affects remote file names,
2300 so you probably don't want to set to non-nil if you use case-sensitive
2301 filesystems via ange-ftp. */);
2302 Vw32_downcase_file_names
= Qnil
;
2305 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes
,
2306 doc
: /* Non-nil means attempt to fake realistic inode values.
2307 This works by hashing the truename of files, and should detect
2308 aliasing between long and short (8.3 DOS) names, but can have
2309 false positives because of hash collisions. Note that determing
2310 the truename of a file can be slow. */);
2311 Vw32_generate_fake_inodes
= Qnil
;
2314 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes
,
2315 doc
: /* Non-nil means determine accurate link count in `file-attributes'.
2316 Note that this option is only useful for files on NTFS volumes, where hard links
2317 are supported. Moreover, it slows down `file-attributes' noticeably. */);
2318 Vw32_get_true_file_attributes
= Qt
;
2320 staticpro (&Vw32_valid_locale_ids
);
2321 staticpro (&Vw32_valid_codepages
);
2323 /* end of ntproc.c */
2325 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2326 (do not change this comment) */