1 /* Process support for Windows NT port of XEMACS.
2 Copyright (C) 1992, 1995 Free Software Foundation, Inc.
4 This file is part of XEmacs.
6 XEmacs is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 XEmacs is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with XEmacs; 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 */
24 /* Adapted for XEmacs by David Hobley <david@spook-le0.cia.com.au> */
25 /* Synced with FSF Emacs 19.34.6 by Marc Paquette <marcpa@cam.org> */
41 #include "ntheap.h" /* From 19.34.6 */
43 #include "syssignal.h"
49 #include "console-msw.h"
51 /*#include "w32term.h"*/ /* From 19.34.6: sync in ? --marcpa */
53 /* #### I'm not going to play with shit. */
54 #pragma warning (disable:4013 4024 4090)
56 /* Control whether spawnve quotes arguments as necessary to ensure
57 correct parsing by child process. Because not all uses of spawnve
58 are careful about constructing argv arrays, we make this behavior
59 conditional (off by default). */
60 Lisp_Object Vwin32_quote_process_args;
62 /* Control whether create_child causes the process' window to be
63 hidden. The default is nil. */
64 Lisp_Object Vwin32_start_process_show_window;
66 /* Control whether create_child causes the process to inherit Emacs'
67 console window, or be given a new one of its own. The default is
68 nil, to allow multiple DOS programs to run on Win95. Having separate
69 consoles also allows Emacs to cleanly terminate process groups. */
70 Lisp_Object Vwin32_start_process_share_console;
72 /* Time to sleep before reading from a subprocess output pipe - this
73 avoids the inefficiency of frequently reading small amounts of data.
74 This is primarily necessary for handling DOS processes on Windows 95,
75 but is useful for Win32 processes on both Win95 and NT as well. */
76 Lisp_Object Vwin32_pipe_read_delay;
78 /* Control whether stat() attempts to generate fake but hopefully
79 "accurate" inode values, by hashing the absolute truenames of files.
80 This should detect aliasing between long and short names, but still
81 allows the possibility of hash collisions. */
82 Lisp_Object Vwin32_generate_fake_inodes;
84 Lisp_Object Qhigh, Qlow;
86 extern Lisp_Object Vlisp_EXEC_SUFFIXES;
91 void _DebPrint (const char *fmt, ...)
98 vsprintf (buf, fmt, args);
100 OutputDebugString (buf);
104 /* sys_signal moved to nt.c. It's now called mswindows_signal... */
106 /* Defined in <process.h> which conflicts with the local copy */
109 /* Child process management list. */
110 int child_proc_count = 0;
111 child_process child_procs[ MAX_CHILDREN ];
112 child_process *dead_child = NULL;
114 DWORD WINAPI reader_thread (void *arg);
116 /* Find an unused process slot. */
123 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
124 if (!CHILD_ACTIVE (cp))
126 if (child_proc_count == MAX_CHILDREN)
128 cp = &child_procs[child_proc_count++];
134 if (cp->procinfo.hProcess)
135 CloseHandle(cp->procinfo.hProcess);
136 cp->procinfo.hProcess = NULL;
137 cp->status = STATUS_READ_ERROR;
139 /* use manual reset event so that select() will function properly */
140 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
143 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
144 if (cp->char_consumed)
146 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
156 delete_child (child_process *cp)
160 /* Should not be deleting a child that is still needed. */
161 for (i = 0; i < MAXDESC; i++)
162 if (fd_info[i].cp == cp)
165 if (!CHILD_ACTIVE (cp))
168 /* reap thread if necessary */
173 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
175 /* let the thread exit cleanly if possible */
176 cp->status = STATUS_READ_ERROR;
177 SetEvent (cp->char_consumed);
178 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
180 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
181 "with %lu for fd %ld\n", GetLastError (), cp->fd));
182 TerminateThread (cp->thrd, 0);
185 CloseHandle (cp->thrd);
190 CloseHandle (cp->char_avail);
191 cp->char_avail = NULL;
193 if (cp->char_consumed)
195 CloseHandle (cp->char_consumed);
196 cp->char_consumed = NULL;
199 /* update child_proc_count (highest numbered slot in use plus one) */
200 if (cp == child_procs + child_proc_count - 1)
202 for (i = child_proc_count-1; i >= 0; i--)
203 if (CHILD_ACTIVE (&child_procs[i]))
205 child_proc_count = i + 1;
210 child_proc_count = 0;
213 /* Find a child by pid. */
214 static child_process *
215 find_child_pid (DWORD pid)
219 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
220 if (CHILD_ACTIVE (cp) && pid == cp->pid)
225 /* Function to do blocking read of one byte, needed to implement
226 select. It is only allowed on sockets and pipes. */
228 _sys_read_ahead (int fd)
233 if (fd < 0 || fd >= MAXDESC)
234 return STATUS_READ_ERROR;
238 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
239 return STATUS_READ_ERROR;
241 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET)) == 0
242 || (fd_info[fd].flags & FILE_READ) == 0)
244 /* fd is not a pipe or socket */
248 cp->status = STATUS_READ_IN_PROGRESS;
250 if (fd_info[fd].flags & FILE_PIPE)
252 rc = _read (fd, &cp->chr, sizeof (char));
254 /* Give subprocess time to buffer some more output for us before
255 reporting that input is available; we need this because Win95
256 connects DOS programs to pipes by making the pipe appear to be
257 the normal console stdout - as a result most DOS programs will
258 write to stdout without buffering, ie. one character at a
259 time. Even some Win32 programs do this - "dir" in a command
260 shell on NT is very slow if we don't do this. */
263 int wait = XINT (Vwin32_pipe_read_delay);
269 /* Yield remainder of our time slice, effectively giving a
270 temporary priority boost to the child process. */
275 if (rc == sizeof (char))
276 cp->status = STATUS_READ_SUCCEEDED;
278 cp->status = STATUS_READ_FAILED;
283 /* Thread proc for child process and socket reader threads. Each thread
284 is normally blocked until woken by select() to check for input by
285 reading one char. When the read completes, char_avail is signalled
286 to wake up the select emulator and the thread blocks itself again. */
288 reader_thread (void *arg)
293 cp = (child_process *)arg;
295 /* <matts@tibco.com> - I think the test below is wrong - we don't
296 want to wait for someone to signal char_consumed, as we haven't
297 read anything for them to consume yet! */
301 WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
313 rc = _sys_read_ahead (cp->fd);
315 /* The name char_avail is a misnomer - it really just means the
316 read-ahead has completed, whether successfully or not. */
317 if (!SetEvent (cp->char_avail))
319 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
320 GetLastError (), cp->fd));
324 if (rc == STATUS_READ_ERROR)
326 /* We are finished, so clean up handles and set to NULL so
327 that CHILD_ACTIVE will see what is going on */
328 if (cp->char_avail) {
329 CloseHandle (cp->char_avail);
330 cp->char_avail = NULL;
333 CloseHandle (cp->thrd);
336 if (cp->char_consumed) {
337 CloseHandle(cp->char_consumed);
338 cp->char_consumed = NULL;
340 if (cp->procinfo.hProcess)
342 CloseHandle (cp->procinfo.hProcess);
343 cp->procinfo.hProcess=NULL;
348 /* If the read died, the child has died so let the thread die */
349 if (rc == STATUS_READ_FAILED)
352 /* Wait until our input is acknowledged before reading again */
353 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
355 DebPrint (("reader_thread.WaitForSingleObject failed with "
356 "%lu for fd %ld\n", GetLastError (), cp->fd));
360 /* We are finished, so clean up handles and set to NULL so that
361 CHILD_ACTIVE will see what is going on */
362 if (cp->char_avail) {
363 CloseHandle (cp->char_avail);
364 cp->char_avail = NULL;
367 CloseHandle (cp->thrd);
370 if (cp->char_consumed) {
371 CloseHandle(cp->char_consumed);
372 cp->char_consumed = NULL;
374 if (cp->procinfo.hProcess)
376 CloseHandle (cp->procinfo.hProcess);
377 cp->procinfo.hProcess=NULL;
383 /* To avoid Emacs changing directory, we just record here the directory
384 the new process should start in. This is set just before calling
385 sys_spawnve, and is not generally valid at any other time. */
386 static const char * process_dir;
389 create_child (const char *exe, char *cmdline, char *env,
390 int * pPid, child_process *cp)
393 SECURITY_ATTRIBUTES sec_attrs;
394 SECURITY_DESCRIPTOR sec_desc;
395 char dir[ MAXPATHLEN ];
397 if (cp == NULL) abort ();
400 start.cb = sizeof (start);
402 if (NILP (Vwin32_start_process_show_window))
403 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
405 start.dwFlags = STARTF_USESTDHANDLES;
406 start.wShowWindow = SW_HIDE;
408 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
409 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
410 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
412 /* Explicitly specify no security */
413 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
415 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
417 sec_attrs.nLength = sizeof (sec_attrs);
418 sec_attrs.lpSecurityDescriptor = &sec_desc;
419 sec_attrs.bInheritHandle = FALSE;
421 strcpy (dir, process_dir);
422 unixtodos_filename (dir);
424 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
425 (!NILP (Vwin32_start_process_share_console)
426 ? CREATE_NEW_PROCESS_GROUP
427 : CREATE_NEW_CONSOLE),
429 &start, &cp->procinfo))
432 cp->pid = (int) cp->procinfo.dwProcessId;
434 CloseHandle (cp->procinfo.hThread);
435 CloseHandle (cp->procinfo.hProcess);
436 cp->procinfo.hThread=NULL;
437 cp->procinfo.hProcess=NULL;
439 /* pid must fit in a Lisp_Int */
447 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
452 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
468 qsort (new_envp, num, sizeof (char*), compare_env);
473 /* When a new child process is created we need to register it in our list,
474 so intercept spawn requests. */
476 sys_spawnve (int mode, const char *cmdname,
477 const char * const *argv, const char *const *envp)
479 Lisp_Object program, full;
480 char *cmdline, *env, *parg, **targ;
484 int is_dos_app, is_cygnus_app;
486 char escape_char = 0;
487 /* We pass our process ID to our children by setting up an environment
488 variable in their environment. */
489 char ppid_env_var_buffer[64];
490 char *extra_env[] = {ppid_env_var_buffer, NULL};
493 /* We don't care about the other modes */
494 if (mode != _P_NOWAIT)
500 /* Handle executable names without an executable suffix. */
501 program = make_string (cmdname, strlen (cmdname));
503 if (NILP (Ffile_executable_p (program)))
506 locate_file (Vexec_path, program, Vlisp_EXEC_SUFFIXES, &full, 1);
513 TO_EXTERNAL_FORMAT (LISP_STRING, full,
514 C_STRING_ALLOCA, cmdname,
519 cmdname = (char*)alloca (strlen (argv[0]) + 1);
520 strcpy ((char*)cmdname, argv[0]);
524 /* make sure argv[0] and cmdname are both in DOS format */
525 unixtodos_filename ((char*)cmdname);
527 ((const char**)argv)[0] = cmdname;
529 /* Determine whether program is a 16-bit DOS executable, or a Win32
530 executable that is implicitly linked to the Cygnus dll (implying it
531 was compiled with the Cygnus GNU toolchain and hence relies on
532 cygwin.dll to parse the command line - we use this to decide how to
533 escape quote chars in command line args that must be quoted). */
534 mswindows_executable_type (cmdname, &is_dos_app, &is_cygnus_app);
536 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
537 application to start it by specifying the helper app as cmdname,
538 while leaving the real app name as argv[0]. */
541 cmdname = (char*) alloca (MAXPATHLEN);
542 if (egetenv ("CMDPROXY"))
543 strcpy ((char*)cmdname, egetenv ("CMDPROXY"));
546 strcpy ((char*)cmdname, XSTRING_DATA (Vinvocation_directory));
547 strcat ((char*)cmdname, "cmdproxy.exe");
549 unixtodos_filename ((char*)cmdname);
552 /* we have to do some conjuring here to put argv and envp into the
553 form CreateProcess wants... argv needs to be a space separated/null
554 terminated list of parameters, and envp is a null
555 separated/double-null terminated list of parameters.
557 Additionally, zero-length args and args containing whitespace or
558 quote chars need to be wrapped in double quotes - for this to work,
559 embedded quotes need to be escaped as well. The aim is to ensure
560 the child process reconstructs the argv array we start with
561 exactly, so we treat quotes at the beginning and end of arguments
564 The Win32 GNU-based library from Cygnus doubles quotes to escape
565 them, while MSVC uses backslash for escaping. (Actually the MSVC
566 startup code does attempt to recognize doubled quotes and accept
567 them, but gets it wrong and ends up requiring three quotes to get a
568 single embedded quote!) So by default we decide whether to use
569 quote or backslash as the escape character based on whether the
570 binary is apparently a Cygnus compiled app.
572 Note that using backslash to escape embedded quotes requires
573 additional special handling if an embedded quote is already
574 preceded by backslash, or if an arg requiring quoting ends with
575 backslash. In such cases, the run of escape characters needs to be
576 doubled. For consistency, we apply this special handling as long
577 as the escape character is not quote.
579 Since we have no idea how large argv and envp are likely to be we
580 figure out list lengths on the fly and allocate them. */
582 if (!NILP (Vwin32_quote_process_args))
585 /* Override escape char by binding win32-quote-process-args to
586 desired character, or use t for auto-selection. */
587 if (INTP (Vwin32_quote_process_args))
588 escape_char = (char) XINT (Vwin32_quote_process_args);
590 escape_char = is_cygnus_app ? '"' : '\\';
600 int escape_char_run = 0;
608 /* allow for embedded quotes to be escaped */
611 /* handle the case where the embedded quote is already escaped */
612 if (escape_char_run > 0)
614 /* To preserve the arg exactly, we need to double the
615 preceding escape characters (plus adding one to
616 escape the quote character itself). */
617 arglen += escape_char_run;
620 else if (*p == ' ' || *p == '\t')
625 if (*p == escape_char && escape_char != '"')
633 /* handle the case where the arg ends with an escape char - we
634 must not let the enclosing quote be escaped. */
635 if (escape_char_run > 0)
636 arglen += escape_char_run;
638 arglen += strlen (*targ++) + 1;
640 cmdline = (char*) alloca (arglen);
654 if (*p == ' ' || *p == '\t' || *p == '"')
659 int escape_char_run = 0;
665 last = p + strlen (p) - 1;
668 /* This version does not escape quotes if they occur at the
669 beginning or end of the arg - this could lead to incorrect
670 behavior when the arg itself represents a command line
671 containing quoted args. I believe this was originally done
672 as a hack to make some things work, before
673 `win32-quote-process-args' was added. */
676 if (*p == '"' && p > first && p < last)
677 *parg++ = escape_char; /* escape embedded quotes */
685 /* double preceding escape chars if any */
686 while (escape_char_run > 0)
688 *parg++ = escape_char;
691 /* escape all quote chars, even at beginning or end */
692 *parg++ = escape_char;
696 if (*p == escape_char && escape_char != '"')
701 /* double escape chars before enclosing quote */
702 while (escape_char_run > 0)
704 *parg++ = escape_char;
712 strcpy (parg, *targ);
713 parg += strlen (*targ);
722 targ = (char**) envp;
723 numenv = 1; /* for end null */
726 arglen += strlen (*targ++) + 1;
729 /* extra env vars... */
730 sprintf (ppid_env_var_buffer, "__PARENT_PROCESS_ID=%d",
731 GetCurrentProcessId ());
732 arglen += strlen (ppid_env_var_buffer) + 1;
735 /* merge env passed in and extra env into one, and sort it. */
736 targ = (char **) alloca (numenv * sizeof (char*));
737 merge_and_sort_env ((char**) envp, extra_env, targ);
739 /* concatenate env entries. */
740 env = (char*) alloca (arglen);
744 strcpy (parg, *targ);
745 parg += strlen (*targ++);
758 /* Now create the process. */
759 if (!create_child (cmdname, cmdline, env, &pid, cp))
769 /* Substitute for certain kill () operations */
772 find_child_console (HWND hwnd, child_process * cp)
777 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
778 if (process_id == cp->procinfo.dwProcessId)
780 char window_class[32];
782 GetClassName (hwnd, window_class, sizeof (window_class));
783 if (strcmp (window_class,
784 mswindows_windows9x_p()
786 : "ConsoleWindowClass") == 0)
797 sys_kill (int pid, int sig)
801 int need_to_free = 0;
804 /* Only handle signals that will result in the process dying */
805 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
811 cp = find_child_pid (pid);
814 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
815 if (proc_hand == NULL)
824 proc_hand = cp->procinfo.hProcess;
825 pid = cp->procinfo.dwProcessId;
827 /* Try to locate console window for process. */
828 EnumWindows ((WNDENUMPROC)find_child_console, (LPARAM) cp);
833 if (NILP (Vwin32_start_process_share_console) && cp && cp->hwnd)
835 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
836 BYTE vk_break_code = VK_CANCEL;
837 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
838 HWND foreground_window;
840 if (break_scan_code == 0)
842 /* Fake Ctrl-C if we can't manage Ctrl-Break. */
844 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
847 foreground_window = GetForegroundWindow ();
848 if (foreground_window && SetForegroundWindow (cp->hwnd))
850 /* Generate keystrokes as if user had typed Ctrl-Break or Ctrl-C. */
851 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
852 keybd_event (vk_break_code, break_scan_code, 0, 0);
853 keybd_event (vk_break_code, break_scan_code, KEYEVENTF_KEYUP, 0);
854 keybd_event (VK_CONTROL, control_scan_code, KEYEVENTF_KEYUP, 0);
856 /* Sleep for a bit to give time for Emacs frame to respond
857 to focus change events (if Emacs was active app). */
860 SetForegroundWindow (foreground_window);
863 /* Ctrl-Break is NT equivalent of SIGINT. */
864 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
866 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
867 "for pid %lu\n", GetLastError (), pid));
874 if (NILP (Vwin32_start_process_share_console) && cp && cp->hwnd)
877 if (mswindows_windows9x_p())
880 Another possibility is to try terminating the VDM out-right by
881 calling the Shell VxD (id 0x17) V86 interface, function #4
882 "SHELL_Destroy_VM", ie.
888 First need to determine the current VM handle, and then arrange for
889 the shellapi call to be made from the system vm (by using
890 Switch_VM_and_callback).
892 Could try to invoke DestroyVM through CallVxD.
896 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
897 to hang when cmdproxy is used in conjunction with
898 command.com for an interactive shell. Posting
899 WM_CLOSE pops up a dialog that, when Yes is selected,
900 does the same thing. TerminateProcess is also less
901 than ideal in that subprocesses tend to stick around
902 until the machine is shutdown, but at least it
903 doesn't freeze the 16-bit subsystem. */
904 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
906 if (!TerminateProcess (proc_hand, 0xff))
908 DebPrint (("sys_kill.TerminateProcess returned %d "
909 "for pid %lu\n", GetLastError (), pid));
916 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
918 /* Kill the process. On Win32 this doesn't kill child processes
919 so it doesn't work very well for shells which is why it's not
920 used in every case. */
921 else if (!TerminateProcess (proc_hand, 0xff))
923 DebPrint (("sys_kill.TerminateProcess returned %d "
924 "for pid %lu\n", GetLastError (), pid));
931 CloseHandle (proc_hand);
937 /* Sync with FSF Emacs 19.34.6 note: ifdef'ed out in XEmacs */
938 extern int report_file_error (const char *, Lisp_Object);
940 /* The following two routines are used to manipulate stdin, stdout, and
941 stderr of our child processes.
943 Assuming that in, out, and err are *not* inheritable, we make them
944 stdin, stdout, and stderr of the child as follows:
946 - Save the parent's current standard handles.
947 - Set the std handles to inheritable duplicates of the ones being passed in.
948 (Note that _get_osfhandle() is an io.h procedure that retrieves the
949 NT file handle for a crt file descriptor.)
950 - Spawn the child, which inherits in, out, and err as stdin,
951 stdout, and stderr. (see Spawnve)
952 - Close the std handles passed to the child.
953 - Reset the parent's standard handles to the saved handles.
954 (see reset_standard_handles)
955 We assume that the caller closes in, out, and err after calling us. */
958 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
961 HANDLE newstdin, newstdout, newstderr;
963 parent = GetCurrentProcess ();
965 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
966 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
967 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
969 /* make inheritable copies of the new handles */
970 if (!DuplicateHandle (parent,
971 (HANDLE) _get_osfhandle (in),
976 DUPLICATE_SAME_ACCESS))
977 report_file_error ("Duplicating input handle for child", Qnil);
979 if (!DuplicateHandle (parent,
980 (HANDLE) _get_osfhandle (out),
985 DUPLICATE_SAME_ACCESS))
986 report_file_error ("Duplicating output handle for child", Qnil);
988 if (!DuplicateHandle (parent,
989 (HANDLE) _get_osfhandle (err),
994 DUPLICATE_SAME_ACCESS))
995 report_file_error ("Duplicating error handle for child", Qnil);
997 /* and store them as our std handles */
998 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
999 report_file_error ("Changing stdin handle", Qnil);
1001 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1002 report_file_error ("Changing stdout handle", Qnil);
1004 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1005 report_file_error ("Changing stderr handle", Qnil);
1009 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1011 /* close the duplicated handles passed to the child */
1012 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1013 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1014 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1016 /* now restore parent's saved std handles */
1017 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1018 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1019 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1023 set_process_dir (const char * dir)
1028 /* Some miscellaneous functions that are Windows specific, but not GUI
1029 specific (ie. are applicable in terminal or batch mode as well). */
1031 DEFUN ("win32-short-file-name", Fwin32_short_file_name, 1, 1, "", /*
1032 Return the short file name version (8.3) of the full path of FILENAME.
1033 If FILENAME does not exist, return nil.
1034 All path elements in FILENAME are converted to their short names.
1038 char shortname[MAX_PATH];
1040 CHECK_STRING (filename);
1042 /* first expand it. */
1043 filename = Fexpand_file_name (filename, Qnil);
1045 /* luckily, this returns the short version of each element in the path. */
1046 if (GetShortPathName (XSTRING_DATA (filename), shortname, MAX_PATH) == 0)
1049 CORRECT_DIR_SEPS (shortname);
1051 return build_string (shortname);
1055 DEFUN ("win32-long-file-name", Fwin32_long_file_name, 1, 1, "", /*
1056 Return the long file name version of the full path of FILENAME.
1057 If FILENAME does not exist, return nil.
1058 All path elements in FILENAME are converted to their long names.
1062 char longname[ MAX_PATH ];
1064 CHECK_STRING (filename);
1066 /* first expand it. */
1067 filename = Fexpand_file_name (filename, Qnil);
1069 if (!win32_get_long_filename (XSTRING_DATA (filename), longname, MAX_PATH))
1072 CORRECT_DIR_SEPS (longname);
1074 return build_string (longname);
1077 DEFUN ("win32-set-process-priority", Fwin32_set_process_priority, 2, 2, "", /*
1078 Set the priority of PROCESS to PRIORITY.
1079 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1080 priority of the process whose pid is PROCESS is changed.
1081 PRIORITY should be one of the symbols high, normal, or low;
1082 any other symbol will be interpreted as normal.
1084 If successful, the return value is t, otherwise nil.
1086 (process, priority))
1088 HANDLE proc_handle = GetCurrentProcess ();
1089 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1090 Lisp_Object result = Qnil;
1092 CHECK_SYMBOL (priority);
1094 if (!NILP (process))
1099 CHECK_INT (process);
1101 /* Allow pid to be an internally generated one, or one obtained
1102 externally. This is necessary because real pids on Win95 are
1105 pid = XINT (process);
1106 cp = find_child_pid (pid);
1108 pid = cp->procinfo.dwProcessId;
1110 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1113 if (EQ (priority, Qhigh))
1114 priority_class = HIGH_PRIORITY_CLASS;
1115 else if (EQ (priority, Qlow))
1116 priority_class = IDLE_PRIORITY_CLASS;
1118 if (proc_handle != NULL)
1120 if (SetPriorityClass (proc_handle, priority_class))
1122 if (!NILP (process))
1123 CloseHandle (proc_handle);
1130 DEFUN ("win32-get-locale-info", Fwin32_get_locale_info, 1, 2, "", /*
1131 "Return information about the Windows locale LCID.
1132 By default, return a three letter locale code which encodes the default
1133 language as the first two characters, and the country or regional variant
1134 as the third letter. For example, ENU refers to `English (United States)',
1135 while ENC means `English (Canadian)'.
1137 If the optional argument LONGFORM is non-nil, the long form of the locale
1138 name is returned, e.g. `English (United States)' instead.
1140 If LCID (a 16-bit number) is not a valid locale, the result is nil.
1146 char abbrev_name[32] = { 0 };
1147 char full_name[256] = { 0 };
1151 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1154 if (NILP (longform))
1156 got_abbrev = GetLocaleInfo (XINT (lcid),
1157 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1158 abbrev_name, sizeof (abbrev_name));
1160 return build_string (abbrev_name);
1164 got_full = GetLocaleInfo (XINT (lcid),
1165 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1166 full_name, sizeof (full_name));
1168 return build_string (full_name);
1175 DEFUN ("win32-get-current-locale-id", Fwin32_get_current_locale_id, 0, 0, "", /*
1176 "Return Windows locale id for current locale setting.
1177 This is a numerical value; use `win32-get-locale-info' to convert to a
1178 human-readable form.
1182 return make_int (GetThreadLocale ());
1186 DEFUN ("win32-get-default-locale-id", Fwin32_get_default_locale_id, 0, 1, "", /*
1187 "Return Windows locale id for default locale setting.
1188 By default, the system default locale setting is returned; if the optional
1189 parameter USERP is non-nil, the user default locale setting is returned.
1190 This is a numerical value; use `win32-get-locale-info' to convert to a
1191 human-readable form.
1196 return make_int (GetSystemDefaultLCID ());
1197 return make_int (GetUserDefaultLCID ());
1200 DWORD int_from_hex (char * s)
1203 static char hex[] = "0123456789abcdefABCDEF";
1206 while (*s && (p = strchr(hex, *s)) != NULL)
1208 unsigned digit = p - hex;
1211 val = val * 16 + digit;
1217 /* We need to build a global list, since the EnumSystemLocale callback
1218 function isn't given a context pointer. */
1219 Lisp_Object Vwin32_valid_locale_ids;
1221 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
1223 DWORD id = int_from_hex (localeNum);
1224 Vwin32_valid_locale_ids = Fcons (make_int (id), Vwin32_valid_locale_ids);
1228 DEFUN ("win32-get-valid-locale-ids", Fwin32_get_valid_locale_ids, 0, 0, "", /*
1229 Return list of all valid Windows locale ids.
1230 Each id is a numerical value; use `win32-get-locale-info' to convert to a
1231 human-readable form.
1235 Vwin32_valid_locale_ids = Qnil;
1237 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
1239 Vwin32_valid_locale_ids = Fnreverse (Vwin32_valid_locale_ids);
1240 return Vwin32_valid_locale_ids;
1244 DEFUN ("win32-set-current-locale", Fwin32_set_current_locale, 1, 1, "", /*
1245 Make Windows locale LCID be the current locale setting for Emacs.
1246 If successful, the new locale id is returned, otherwise nil.
1252 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1255 if (!SetThreadLocale (XINT (lcid)))
1258 /* Sync with FSF Emacs 19.34.6 note: dwWinThreadId declared in
1259 w32term.h and defined in w32fns.c, both of which are not in current
1260 XEmacs. #### Check what we lose by ifdef'ing out these. --marcpa */
1262 /* Need to set input thread locale if present. */
1264 /* Reply is not needed. */
1265 PostThreadMessage (dwWinThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
1268 return make_int (GetThreadLocale ());
1273 syms_of_ntproc (void)
1275 DEFSUBR (Fwin32_short_file_name);
1276 DEFSUBR (Fwin32_long_file_name);
1277 DEFSUBR (Fwin32_set_process_priority);
1278 DEFSUBR (Fwin32_get_locale_info);
1279 DEFSUBR (Fwin32_get_current_locale_id);
1280 DEFSUBR (Fwin32_get_default_locale_id);
1281 DEFSUBR (Fwin32_get_valid_locale_ids);
1282 DEFSUBR (Fwin32_set_current_locale);
1287 vars_of_ntproc (void)
1289 defsymbol (&Qhigh, "high");
1290 defsymbol (&Qlow, "low");
1292 DEFVAR_LISP ("win32-quote-process-args", &Vwin32_quote_process_args /*
1293 Non-nil enables quoting of process arguments to ensure correct parsing.
1294 Because Windows does not directly pass argv arrays to child processes,
1295 programs have to reconstruct the argv array by parsing the command
1296 line string. For an argument to contain a space, it must be enclosed
1297 in double quotes or it will be parsed as multiple arguments.
1299 If the value is a character, that character will be used to escape any
1300 quote characters that appear, otherwise a suitable escape character
1301 will be chosen based on the type of the program.
1303 Vwin32_quote_process_args = Qt;
1305 DEFVAR_LISP ("win32-start-process-show-window",
1306 &Vwin32_start_process_show_window /*
1307 When nil, processes started via start-process hide their windows.
1308 When non-nil, they show their window in the method of their choice.
1310 Vwin32_start_process_show_window = Qnil;
1312 DEFVAR_LISP ("win32-start-process-share-console",
1313 &Vwin32_start_process_share_console /*
1314 When nil, processes started via start-process are given a new console.
1315 When non-nil, they share the Emacs console; this has the limitation of
1316 allowing only only DOS subprocess to run at a time (whether started directly
1317 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
1318 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
1319 otherwise respond to interrupts from Emacs.
1321 Vwin32_start_process_share_console = Qt;
1323 DEFVAR_LISP ("win32-pipe-read-delay", &Vwin32_pipe_read_delay /*
1324 Forced delay before reading subprocess output.
1325 This is done to improve the buffering of subprocess output, by
1326 avoiding the inefficiency of frequently reading small amounts of data.
1328 If positive, the value is the number of milliseconds to sleep before
1329 reading the subprocess output. If negative, the magnitude is the number
1330 of time slices to wait (effectively boosting the priority of the child
1331 process temporarily). A value of zero disables waiting entirely.
1333 Vwin32_pipe_read_delay = make_int (50);
1336 DEFVAR_LISP ("win32-generate-fake-inodes", &Vwin32_generate_fake_inodes /*
1337 "Non-nil means attempt to fake realistic inode values.
1338 This works by hashing the truename of files, and should detect
1339 aliasing between long and short (8.3 DOS) names, but can have
1340 false positives because of hash collisions. Note that determining
1341 the truename of a file can be slow.
1343 Vwin32_generate_fake_inodes = Qnil;
1347 /* end of ntproc.c */