(define-charset): New args :min-code and :max-code.
[bpt/emacs.git] / src / w32proc.c
1 /* Process support for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1992, 1995, 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
20
21 Drew Bliss Oct 14, 1993
22 Adapted from alarm.c by Tim Fleehart
23 */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <io.h>
29 #include <fcntl.h>
30 #include <signal.h>
31
32 /* must include CRT headers *before* config.h */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #undef signal
39 #undef wait
40 #undef spawnve
41 #undef select
42 #undef kill
43
44 #include <windows.h>
45 #ifdef __GNUC__
46 /* This definition is missing from mingw32 headers. */
47 extern BOOL WINAPI IsValidLocale(LCID, DWORD);
48 #endif
49
50 #include "lisp.h"
51 #include "w32.h"
52 #include "w32heap.h"
53 #include "systime.h"
54 #include "syswait.h"
55 #include "process.h"
56 #include "syssignal.h"
57 #include "w32term.h"
58
59 /* Control whether spawnve quotes arguments as necessary to ensure
60 correct parsing by child process. Because not all uses of spawnve
61 are careful about constructing argv arrays, we make this behaviour
62 conditional (off by default). */
63 Lisp_Object Vw32_quote_process_args;
64
65 /* Control whether create_child causes the process' window to be
66 hidden. The default is nil. */
67 Lisp_Object Vw32_start_process_show_window;
68
69 /* Control whether create_child causes the process to inherit Emacs'
70 console window, or be given a new one of its own. The default is
71 nil, to allow multiple DOS programs to run on Win95. Having separate
72 consoles also allows Emacs to cleanly terminate process groups. */
73 Lisp_Object Vw32_start_process_share_console;
74
75 /* Control whether create_child cause the process to inherit Emacs'
76 error mode setting. The default is t, to minimize the possibility of
77 subprocesses blocking when accessing unmounted drives. */
78 Lisp_Object Vw32_start_process_inherit_error_mode;
79
80 /* Time to sleep before reading from a subprocess output pipe - this
81 avoids the inefficiency of frequently reading small amounts of data.
82 This is primarily necessary for handling DOS processes on Windows 95,
83 but is useful for W32 processes on both Windows 95 and NT as well. */
84 Lisp_Object Vw32_pipe_read_delay;
85
86 /* Control conversion of upper case file names to lower case.
87 nil means no, t means yes. */
88 Lisp_Object Vw32_downcase_file_names;
89
90 /* Control whether stat() attempts to generate fake but hopefully
91 "accurate" inode values, by hashing the absolute truenames of files.
92 This should detect aliasing between long and short names, but still
93 allows the possibility of hash collisions. */
94 Lisp_Object Vw32_generate_fake_inodes;
95
96 /* Control whether stat() attempts to determine file type and link count
97 exactly, at the expense of slower operation. Since true hard links
98 are supported on NTFS volumes, this is only relevant on NT. */
99 Lisp_Object Vw32_get_true_file_attributes;
100
101 Lisp_Object Qhigh, Qlow;
102
103 #ifdef EMACSDEBUG
104 void _DebPrint (const char *fmt, ...)
105 {
106 char buf[1024];
107 va_list args;
108
109 va_start (args, fmt);
110 vsprintf (buf, fmt, args);
111 va_end (args);
112 OutputDebugString (buf);
113 }
114 #endif
115
116 typedef void (_CALLBACK_ *signal_handler)(int);
117
118 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
119 static signal_handler sig_handlers[NSIG];
120
121 /* Fake signal implementation to record the SIGCHLD handler. */
122 signal_handler
123 sys_signal (int sig, signal_handler handler)
124 {
125 signal_handler old;
126
127 if (sig != SIGCHLD)
128 {
129 errno = EINVAL;
130 return SIG_ERR;
131 }
132 old = sig_handlers[sig];
133 sig_handlers[sig] = handler;
134 return old;
135 }
136
137 /* Defined in <process.h> which conflicts with the local copy */
138 #define _P_NOWAIT 1
139
140 /* Child process management list. */
141 int child_proc_count = 0;
142 child_process child_procs[ MAX_CHILDREN ];
143 child_process *dead_child = NULL;
144
145 DWORD WINAPI reader_thread (void *arg);
146
147 /* Find an unused process slot. */
148 child_process *
149 new_child (void)
150 {
151 child_process *cp;
152 DWORD id;
153
154 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
155 if (!CHILD_ACTIVE (cp))
156 goto Initialise;
157 if (child_proc_count == MAX_CHILDREN)
158 return NULL;
159 cp = &child_procs[child_proc_count++];
160
161 Initialise:
162 memset (cp, 0, sizeof(*cp));
163 cp->fd = -1;
164 cp->pid = -1;
165 cp->procinfo.hProcess = NULL;
166 cp->status = STATUS_READ_ERROR;
167
168 /* use manual reset event so that select() will function properly */
169 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
170 if (cp->char_avail)
171 {
172 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
173 if (cp->char_consumed)
174 {
175 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
176 if (cp->thrd)
177 return cp;
178 }
179 }
180 delete_child (cp);
181 return NULL;
182 }
183
184 void
185 delete_child (child_process *cp)
186 {
187 int i;
188
189 /* Should not be deleting a child that is still needed. */
190 for (i = 0; i < MAXDESC; i++)
191 if (fd_info[i].cp == cp)
192 abort ();
193
194 if (!CHILD_ACTIVE (cp))
195 return;
196
197 /* reap thread if necessary */
198 if (cp->thrd)
199 {
200 DWORD rc;
201
202 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
203 {
204 /* let the thread exit cleanly if possible */
205 cp->status = STATUS_READ_ERROR;
206 SetEvent (cp->char_consumed);
207 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
208 {
209 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
210 "with %lu for fd %ld\n", GetLastError (), cp->fd));
211 TerminateThread (cp->thrd, 0);
212 }
213 }
214 CloseHandle (cp->thrd);
215 cp->thrd = NULL;
216 }
217 if (cp->char_avail)
218 {
219 CloseHandle (cp->char_avail);
220 cp->char_avail = NULL;
221 }
222 if (cp->char_consumed)
223 {
224 CloseHandle (cp->char_consumed);
225 cp->char_consumed = NULL;
226 }
227
228 /* update child_proc_count (highest numbered slot in use plus one) */
229 if (cp == child_procs + child_proc_count - 1)
230 {
231 for (i = child_proc_count-1; i >= 0; i--)
232 if (CHILD_ACTIVE (&child_procs[i]))
233 {
234 child_proc_count = i + 1;
235 break;
236 }
237 }
238 if (i < 0)
239 child_proc_count = 0;
240 }
241
242 /* Find a child by pid. */
243 static child_process *
244 find_child_pid (DWORD pid)
245 {
246 child_process *cp;
247
248 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
249 if (CHILD_ACTIVE (cp) && pid == cp->pid)
250 return cp;
251 return NULL;
252 }
253
254
255 /* Thread proc for child process and socket reader threads. Each thread
256 is normally blocked until woken by select() to check for input by
257 reading one char. When the read completes, char_avail is signalled
258 to wake up the select emulator and the thread blocks itself again. */
259 DWORD WINAPI
260 reader_thread (void *arg)
261 {
262 child_process *cp;
263
264 /* Our identity */
265 cp = (child_process *)arg;
266
267 /* We have to wait for the go-ahead before we can start */
268 if (cp == NULL
269 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
270 return 1;
271
272 for (;;)
273 {
274 int rc;
275
276 rc = _sys_read_ahead (cp->fd);
277
278 /* The name char_avail is a misnomer - it really just means the
279 read-ahead has completed, whether successfully or not. */
280 if (!SetEvent (cp->char_avail))
281 {
282 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
283 GetLastError (), cp->fd));
284 return 1;
285 }
286
287 if (rc == STATUS_READ_ERROR)
288 return 1;
289
290 /* If the read died, the child has died so let the thread die */
291 if (rc == STATUS_READ_FAILED)
292 break;
293
294 /* Wait until our input is acknowledged before reading again */
295 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
296 {
297 DebPrint (("reader_thread.WaitForSingleObject failed with "
298 "%lu for fd %ld\n", GetLastError (), cp->fd));
299 break;
300 }
301 }
302 return 0;
303 }
304
305 /* To avoid Emacs changing directory, we just record here the directory
306 the new process should start in. This is set just before calling
307 sys_spawnve, and is not generally valid at any other time. */
308 static char * process_dir;
309
310 static BOOL
311 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
312 int * pPid, child_process *cp)
313 {
314 STARTUPINFO start;
315 SECURITY_ATTRIBUTES sec_attrs;
316 #if 0
317 SECURITY_DESCRIPTOR sec_desc;
318 #endif
319 DWORD flags;
320 char dir[ MAXPATHLEN ];
321
322 if (cp == NULL) abort ();
323
324 memset (&start, 0, sizeof (start));
325 start.cb = sizeof (start);
326
327 #ifdef HAVE_NTGUI
328 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
329 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
330 else
331 start.dwFlags = STARTF_USESTDHANDLES;
332 start.wShowWindow = SW_HIDE;
333
334 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
335 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
336 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
337 #endif /* HAVE_NTGUI */
338
339 #if 0
340 /* Explicitly specify no security */
341 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
342 goto EH_Fail;
343 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
344 goto EH_Fail;
345 #endif
346 sec_attrs.nLength = sizeof (sec_attrs);
347 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
348 sec_attrs.bInheritHandle = FALSE;
349
350 strcpy (dir, process_dir);
351 unixtodos_filename (dir);
352
353 flags = (!NILP (Vw32_start_process_share_console)
354 ? CREATE_NEW_PROCESS_GROUP
355 : CREATE_NEW_CONSOLE);
356 if (NILP (Vw32_start_process_inherit_error_mode))
357 flags |= CREATE_DEFAULT_ERROR_MODE;
358 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
359 flags, env, dir, &start, &cp->procinfo))
360 goto EH_Fail;
361
362 cp->pid = (int) cp->procinfo.dwProcessId;
363
364 /* Hack for Windows 95, which assigns large (ie negative) pids */
365 if (cp->pid < 0)
366 cp->pid = -cp->pid;
367
368 /* pid must fit in a Lisp_Int */
369 cp->pid = (cp->pid & VALMASK);
370
371 *pPid = cp->pid;
372
373 return TRUE;
374
375 EH_Fail:
376 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
377 return FALSE;
378 }
379
380 /* create_child doesn't know what emacs' file handle will be for waiting
381 on output from the child, so we need to make this additional call
382 to register the handle with the process
383 This way the select emulator knows how to match file handles with
384 entries in child_procs. */
385 void
386 register_child (int pid, int fd)
387 {
388 child_process *cp;
389
390 cp = find_child_pid (pid);
391 if (cp == NULL)
392 {
393 DebPrint (("register_child unable to find pid %lu\n", pid));
394 return;
395 }
396
397 #ifdef FULL_DEBUG
398 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
399 #endif
400
401 cp->fd = fd;
402
403 /* thread is initially blocked until select is called; set status so
404 that select will release thread */
405 cp->status = STATUS_READ_ACKNOWLEDGED;
406
407 /* attach child_process to fd_info */
408 if (fd_info[fd].cp != NULL)
409 {
410 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
411 abort ();
412 }
413
414 fd_info[fd].cp = cp;
415 }
416
417 /* When a process dies its pipe will break so the reader thread will
418 signal failure to the select emulator.
419 The select emulator then calls this routine to clean up.
420 Since the thread signaled failure we can assume it is exiting. */
421 static void
422 reap_subprocess (child_process *cp)
423 {
424 if (cp->procinfo.hProcess)
425 {
426 /* Reap the process */
427 #ifdef FULL_DEBUG
428 /* Process should have already died before we are called. */
429 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
430 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
431 #endif
432 CloseHandle (cp->procinfo.hProcess);
433 cp->procinfo.hProcess = NULL;
434 CloseHandle (cp->procinfo.hThread);
435 cp->procinfo.hThread = NULL;
436 }
437
438 /* For asynchronous children, the child_proc resources will be freed
439 when the last pipe read descriptor is closed; for synchronous
440 children, we must explicitly free the resources now because
441 register_child has not been called. */
442 if (cp->fd == -1)
443 delete_child (cp);
444 }
445
446 /* Wait for any of our existing child processes to die
447 When it does, close its handle
448 Return the pid and fill in the status if non-NULL. */
449
450 int
451 sys_wait (int *status)
452 {
453 DWORD active, retval;
454 int nh;
455 int pid;
456 child_process *cp, *cps[MAX_CHILDREN];
457 HANDLE wait_hnd[MAX_CHILDREN];
458
459 nh = 0;
460 if (dead_child != NULL)
461 {
462 /* We want to wait for a specific child */
463 wait_hnd[nh] = dead_child->procinfo.hProcess;
464 cps[nh] = dead_child;
465 if (!wait_hnd[nh]) abort ();
466 nh++;
467 active = 0;
468 goto get_result;
469 }
470 else
471 {
472 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
473 /* some child_procs might be sockets; ignore them */
474 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
475 {
476 wait_hnd[nh] = cp->procinfo.hProcess;
477 cps[nh] = cp;
478 nh++;
479 }
480 }
481
482 if (nh == 0)
483 {
484 /* Nothing to wait on, so fail */
485 errno = ECHILD;
486 return -1;
487 }
488
489 do
490 {
491 /* Check for quit about once a second. */
492 QUIT;
493 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
494 } while (active == WAIT_TIMEOUT);
495
496 if (active == WAIT_FAILED)
497 {
498 errno = EBADF;
499 return -1;
500 }
501 else if (active >= WAIT_OBJECT_0
502 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
503 {
504 active -= WAIT_OBJECT_0;
505 }
506 else if (active >= WAIT_ABANDONED_0
507 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
508 {
509 active -= WAIT_ABANDONED_0;
510 }
511 else
512 abort ();
513
514 get_result:
515 if (!GetExitCodeProcess (wait_hnd[active], &retval))
516 {
517 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
518 GetLastError ()));
519 retval = 1;
520 }
521 if (retval == STILL_ACTIVE)
522 {
523 /* Should never happen */
524 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
525 errno = EINVAL;
526 return -1;
527 }
528
529 /* Massage the exit code from the process to match the format expected
530 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
531 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
532
533 if (retval == STATUS_CONTROL_C_EXIT)
534 retval = SIGINT;
535 else
536 retval <<= 8;
537
538 cp = cps[active];
539 pid = cp->pid;
540 #ifdef FULL_DEBUG
541 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
542 #endif
543
544 if (status)
545 {
546 *status = retval;
547 }
548 else if (synch_process_alive)
549 {
550 synch_process_alive = 0;
551
552 /* Report the status of the synchronous process. */
553 if (WIFEXITED (retval))
554 synch_process_retcode = WRETCODE (retval);
555 else if (WIFSIGNALED (retval))
556 {
557 int code = WTERMSIG (retval);
558 char *signame;
559
560 synchronize_system_messages_locale ();
561 signame = strsignal (code);
562
563 if (signame == 0)
564 signame = "unknown";
565
566 synch_process_death = signame;
567 }
568
569 reap_subprocess (cp);
570 }
571
572 reap_subprocess (cp);
573
574 return pid;
575 }
576
577 void
578 w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app, int * is_gui_app)
579 {
580 file_data executable;
581 char * p;
582
583 /* Default values in case we can't tell for sure. */
584 *is_dos_app = FALSE;
585 *is_cygnus_app = FALSE;
586 *is_gui_app = FALSE;
587
588 if (!open_input_file (&executable, filename))
589 return;
590
591 p = strrchr (filename, '.');
592
593 /* We can only identify DOS .com programs from the extension. */
594 if (p && stricmp (p, ".com") == 0)
595 *is_dos_app = TRUE;
596 else if (p && (stricmp (p, ".bat") == 0
597 || stricmp (p, ".cmd") == 0))
598 {
599 /* A DOS shell script - it appears that CreateProcess is happy to
600 accept this (somewhat surprisingly); presumably it looks at
601 COMSPEC to determine what executable to actually invoke.
602 Therefore, we have to do the same here as well. */
603 /* Actually, I think it uses the program association for that
604 extension, which is defined in the registry. */
605 p = egetenv ("COMSPEC");
606 if (p)
607 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
608 }
609 else
610 {
611 /* Look for DOS .exe signature - if found, we must also check that
612 it isn't really a 16- or 32-bit Windows exe, since both formats
613 start with a DOS program stub. Note that 16-bit Windows
614 executables use the OS/2 1.x format. */
615
616 IMAGE_DOS_HEADER * dos_header;
617 IMAGE_NT_HEADERS * nt_header;
618
619 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
620 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
621 goto unwind;
622
623 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
624
625 if ((char *) nt_header > (char *) dos_header + executable.size)
626 {
627 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
628 *is_dos_app = TRUE;
629 }
630 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
631 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
632 {
633 *is_dos_app = TRUE;
634 }
635 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
636 {
637 /* Look for cygwin.dll in DLL import list. */
638 IMAGE_DATA_DIRECTORY import_dir =
639 nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
640 IMAGE_IMPORT_DESCRIPTOR * imports;
641 IMAGE_SECTION_HEADER * section;
642
643 section = rva_to_section (import_dir.VirtualAddress, nt_header);
644 imports = RVA_TO_PTR (import_dir.VirtualAddress, section, executable);
645
646 for ( ; imports->Name; imports++)
647 {
648 char * dllname = RVA_TO_PTR (imports->Name, section, executable);
649
650 /* The exact name of the cygwin dll has changed with
651 various releases, but hopefully this will be reasonably
652 future proof. */
653 if (strncmp (dllname, "cygwin", 6) == 0)
654 {
655 *is_cygnus_app = TRUE;
656 break;
657 }
658 }
659
660 /* Check whether app is marked as a console or windowed (aka
661 GUI) app. Accept Posix and OS2 subsytem apps as console
662 apps. */
663 *is_gui_app = (nt_header->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
664 }
665 }
666
667 unwind:
668 close_file_data (&executable);
669 }
670
671 int
672 compare_env (const void *strp1, const void *strp2)
673 {
674 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
675
676 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
677 {
678 /* Sort order in command.com/cmd.exe is based on uppercasing
679 names, so do the same here. */
680 if (toupper (*str1) > toupper (*str2))
681 return 1;
682 else if (toupper (*str1) < toupper (*str2))
683 return -1;
684 str1++, str2++;
685 }
686
687 if (*str1 == '=' && *str2 == '=')
688 return 0;
689 else if (*str1 == '=')
690 return -1;
691 else
692 return 1;
693 }
694
695 void
696 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
697 {
698 char **optr, **nptr;
699 int num;
700
701 nptr = new_envp;
702 optr = envp1;
703 while (*optr)
704 *nptr++ = *optr++;
705 num = optr - envp1;
706
707 optr = envp2;
708 while (*optr)
709 *nptr++ = *optr++;
710 num += optr - envp2;
711
712 qsort (new_envp, num, sizeof (char *), compare_env);
713
714 *nptr = NULL;
715 }
716
717 /* When a new child process is created we need to register it in our list,
718 so intercept spawn requests. */
719 int
720 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
721 {
722 Lisp_Object program, full;
723 char *cmdline, *env, *parg, **targ;
724 int arglen, numenv;
725 int pid;
726 child_process *cp;
727 int is_dos_app, is_cygnus_app, is_gui_app;
728 int do_quoting = 0;
729 char escape_char;
730 /* We pass our process ID to our children by setting up an environment
731 variable in their environment. */
732 char ppid_env_var_buffer[64];
733 char *extra_env[] = {ppid_env_var_buffer, NULL};
734 char *sepchars = " \t";
735
736 /* We don't care about the other modes */
737 if (mode != _P_NOWAIT)
738 {
739 errno = EINVAL;
740 return -1;
741 }
742
743 /* Handle executable names without an executable suffix. */
744 program = make_string (cmdname, strlen (cmdname));
745 if (NILP (Ffile_executable_p (program)))
746 {
747 struct gcpro gcpro1;
748
749 full = Qnil;
750 GCPRO1 (program);
751 openp (Vexec_path, program, Vexec_suffixes, &full, 1);
752 UNGCPRO;
753 if (NILP (full))
754 {
755 errno = EINVAL;
756 return -1;
757 }
758 program = full;
759 }
760
761 /* make sure argv[0] and cmdname are both in DOS format */
762 cmdname = XSTRING (program)->data;
763 unixtodos_filename (cmdname);
764 argv[0] = cmdname;
765
766 /* Determine whether program is a 16-bit DOS executable, or a w32
767 executable that is implicitly linked to the Cygnus dll (implying it
768 was compiled with the Cygnus GNU toolchain and hence relies on
769 cygwin.dll to parse the command line - we use this to decide how to
770 escape quote chars in command line args that must be quoted).
771
772 Also determine whether it is a GUI app, so that we don't hide its
773 initial window unless specifically requested. */
774 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
775
776 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
777 application to start it by specifying the helper app as cmdname,
778 while leaving the real app name as argv[0]. */
779 if (is_dos_app)
780 {
781 cmdname = alloca (MAXPATHLEN);
782 if (egetenv ("CMDPROXY"))
783 strcpy (cmdname, egetenv ("CMDPROXY"));
784 else
785 {
786 strcpy (cmdname, XSTRING (Vinvocation_directory)->data);
787 strcat (cmdname, "cmdproxy.exe");
788 }
789 unixtodos_filename (cmdname);
790 }
791
792 /* we have to do some conjuring here to put argv and envp into the
793 form CreateProcess wants... argv needs to be a space separated/null
794 terminated list of parameters, and envp is a null
795 separated/double-null terminated list of parameters.
796
797 Additionally, zero-length args and args containing whitespace or
798 quote chars need to be wrapped in double quotes - for this to work,
799 embedded quotes need to be escaped as well. The aim is to ensure
800 the child process reconstructs the argv array we start with
801 exactly, so we treat quotes at the beginning and end of arguments
802 as embedded quotes.
803
804 The w32 GNU-based library from Cygnus doubles quotes to escape
805 them, while MSVC uses backslash for escaping. (Actually the MSVC
806 startup code does attempt to recognise doubled quotes and accept
807 them, but gets it wrong and ends up requiring three quotes to get a
808 single embedded quote!) So by default we decide whether to use
809 quote or backslash as the escape character based on whether the
810 binary is apparently a Cygnus compiled app.
811
812 Note that using backslash to escape embedded quotes requires
813 additional special handling if an embedded quote is already
814 preceeded by backslash, or if an arg requiring quoting ends with
815 backslash. In such cases, the run of escape characters needs to be
816 doubled. For consistency, we apply this special handling as long
817 as the escape character is not quote.
818
819 Since we have no idea how large argv and envp are likely to be we
820 figure out list lengths on the fly and allocate them. */
821
822 if (!NILP (Vw32_quote_process_args))
823 {
824 do_quoting = 1;
825 /* Override escape char by binding w32-quote-process-args to
826 desired character, or use t for auto-selection. */
827 if (INTEGERP (Vw32_quote_process_args))
828 escape_char = XINT (Vw32_quote_process_args);
829 else
830 escape_char = is_cygnus_app ? '"' : '\\';
831 }
832
833 /* Cygwin apps needs quoting a bit more often */
834 if (escape_char == '"')
835 sepchars = "\r\n\t\f '";
836
837 /* do argv... */
838 arglen = 0;
839 targ = argv;
840 while (*targ)
841 {
842 char * p = *targ;
843 int need_quotes = 0;
844 int escape_char_run = 0;
845
846 if (*p == 0)
847 need_quotes = 1;
848 for ( ; *p; p++)
849 {
850 if (escape_char == '"' && *p == '\\')
851 /* If it's a Cygwin app, \ needs to be escaped. */
852 arglen++;
853 else if (*p == '"')
854 {
855 /* allow for embedded quotes to be escaped */
856 arglen++;
857 need_quotes = 1;
858 /* handle the case where the embedded quote is already escaped */
859 if (escape_char_run > 0)
860 {
861 /* To preserve the arg exactly, we need to double the
862 preceding escape characters (plus adding one to
863 escape the quote character itself). */
864 arglen += escape_char_run;
865 }
866 }
867 else if (strchr (sepchars, *p) != NULL)
868 {
869 need_quotes = 1;
870 }
871
872 if (*p == escape_char && escape_char != '"')
873 escape_char_run++;
874 else
875 escape_char_run = 0;
876 }
877 if (need_quotes)
878 {
879 arglen += 2;
880 /* handle the case where the arg ends with an escape char - we
881 must not let the enclosing quote be escaped. */
882 if (escape_char_run > 0)
883 arglen += escape_char_run;
884 }
885 arglen += strlen (*targ++) + 1;
886 }
887 cmdline = alloca (arglen);
888 targ = argv;
889 parg = cmdline;
890 while (*targ)
891 {
892 char * p = *targ;
893 int need_quotes = 0;
894
895 if (*p == 0)
896 need_quotes = 1;
897
898 if (do_quoting)
899 {
900 for ( ; *p; p++)
901 if ((strchr (sepchars, *p) != NULL) || *p == '"')
902 need_quotes = 1;
903 }
904 if (need_quotes)
905 {
906 int escape_char_run = 0;
907 char * first;
908 char * last;
909
910 p = *targ;
911 first = p;
912 last = p + strlen (p) - 1;
913 *parg++ = '"';
914 #if 0
915 /* This version does not escape quotes if they occur at the
916 beginning or end of the arg - this could lead to incorrect
917 behaviour when the arg itself represents a command line
918 containing quoted args. I believe this was originally done
919 as a hack to make some things work, before
920 `w32-quote-process-args' was added. */
921 while (*p)
922 {
923 if (*p == '"' && p > first && p < last)
924 *parg++ = escape_char; /* escape embedded quotes */
925 *parg++ = *p++;
926 }
927 #else
928 for ( ; *p; p++)
929 {
930 if (*p == '"')
931 {
932 /* double preceding escape chars if any */
933 while (escape_char_run > 0)
934 {
935 *parg++ = escape_char;
936 escape_char_run--;
937 }
938 /* escape all quote chars, even at beginning or end */
939 *parg++ = escape_char;
940 }
941 else if (escape_char == '"' && *p == '\\')
942 *parg++ = '\\';
943 *parg++ = *p;
944
945 if (*p == escape_char && escape_char != '"')
946 escape_char_run++;
947 else
948 escape_char_run = 0;
949 }
950 /* double escape chars before enclosing quote */
951 while (escape_char_run > 0)
952 {
953 *parg++ = escape_char;
954 escape_char_run--;
955 }
956 #endif
957 *parg++ = '"';
958 }
959 else
960 {
961 strcpy (parg, *targ);
962 parg += strlen (*targ);
963 }
964 *parg++ = ' ';
965 targ++;
966 }
967 *--parg = '\0';
968
969 /* and envp... */
970 arglen = 1;
971 targ = envp;
972 numenv = 1; /* for end null */
973 while (*targ)
974 {
975 arglen += strlen (*targ++) + 1;
976 numenv++;
977 }
978 /* extra env vars... */
979 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
980 GetCurrentProcessId ());
981 arglen += strlen (ppid_env_var_buffer) + 1;
982 numenv++;
983
984 /* merge env passed in and extra env into one, and sort it. */
985 targ = (char **) alloca (numenv * sizeof (char *));
986 merge_and_sort_env (envp, extra_env, targ);
987
988 /* concatenate env entries. */
989 env = alloca (arglen);
990 parg = env;
991 while (*targ)
992 {
993 strcpy (parg, *targ);
994 parg += strlen (*targ++);
995 *parg++ = '\0';
996 }
997 *parg++ = '\0';
998 *parg = '\0';
999
1000 cp = new_child ();
1001 if (cp == NULL)
1002 {
1003 errno = EAGAIN;
1004 return -1;
1005 }
1006
1007 /* Now create the process. */
1008 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1009 {
1010 delete_child (cp);
1011 errno = ENOEXEC;
1012 return -1;
1013 }
1014
1015 return pid;
1016 }
1017
1018 /* Emulate the select call
1019 Wait for available input on any of the given rfds, or timeout if
1020 a timeout is given and no input is detected
1021 wfds and efds are not supported and must be NULL.
1022
1023 For simplicity, we detect the death of child processes here and
1024 synchronously call the SIGCHLD handler. Since it is possible for
1025 children to be created without a corresponding pipe handle from which
1026 to read output, we wait separately on the process handles as well as
1027 the char_avail events for each process pipe. We only call
1028 wait/reap_process when the process actually terminates.
1029
1030 To reduce the number of places in which Emacs can be hung such that
1031 C-g is not able to interrupt it, we always wait on interrupt_handle
1032 (which is signalled by the input thread when C-g is detected). If we
1033 detect that we were woken up by C-g, we return -1 with errno set to
1034 EINTR as on Unix. */
1035
1036 /* From ntterm.c */
1037 extern HANDLE keyboard_handle;
1038
1039 /* From w32xfns.c */
1040 extern HANDLE interrupt_handle;
1041
1042 /* From process.c */
1043 extern int proc_buffered_char[];
1044
1045 int
1046 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1047 EMACS_TIME *timeout)
1048 {
1049 SELECT_TYPE orfds;
1050 DWORD timeout_ms, start_time;
1051 int i, nh, nc, nr;
1052 DWORD active;
1053 child_process *cp, *cps[MAX_CHILDREN];
1054 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1055 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1056
1057 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : INFINITE;
1058
1059 /* If the descriptor sets are NULL but timeout isn't, then just Sleep. */
1060 if (rfds == NULL && wfds == NULL && efds == NULL && timeout != NULL)
1061 {
1062 Sleep (timeout_ms);
1063 return 0;
1064 }
1065
1066 /* Otherwise, we only handle rfds, so fail otherwise. */
1067 if (rfds == NULL || wfds != NULL || efds != NULL)
1068 {
1069 errno = EINVAL;
1070 return -1;
1071 }
1072
1073 orfds = *rfds;
1074 FD_ZERO (rfds);
1075 nr = 0;
1076
1077 /* Always wait on interrupt_handle, to detect C-g (quit). */
1078 wait_hnd[0] = interrupt_handle;
1079 fdindex[0] = -1;
1080
1081 /* Build a list of pipe handles to wait on. */
1082 nh = 1;
1083 for (i = 0; i < nfds; i++)
1084 if (FD_ISSET (i, &orfds))
1085 {
1086 if (i == 0)
1087 {
1088 if (keyboard_handle)
1089 {
1090 /* Handle stdin specially */
1091 wait_hnd[nh] = keyboard_handle;
1092 fdindex[nh] = i;
1093 nh++;
1094 }
1095
1096 /* Check for any emacs-generated input in the queue since
1097 it won't be detected in the wait */
1098 if (detect_input_pending ())
1099 {
1100 FD_SET (i, rfds);
1101 return 1;
1102 }
1103 }
1104 else
1105 {
1106 /* Child process and socket input */
1107 cp = fd_info[i].cp;
1108 if (cp)
1109 {
1110 int current_status = cp->status;
1111
1112 if (current_status == STATUS_READ_ACKNOWLEDGED)
1113 {
1114 /* Tell reader thread which file handle to use. */
1115 cp->fd = i;
1116 /* Wake up the reader thread for this process */
1117 cp->status = STATUS_READ_READY;
1118 if (!SetEvent (cp->char_consumed))
1119 DebPrint (("nt_select.SetEvent failed with "
1120 "%lu for fd %ld\n", GetLastError (), i));
1121 }
1122
1123 #ifdef CHECK_INTERLOCK
1124 /* slightly crude cross-checking of interlock between threads */
1125
1126 current_status = cp->status;
1127 if (WaitForSingleObject (cp->char_avail, 0) == WAIT_OBJECT_0)
1128 {
1129 /* char_avail has been signalled, so status (which may
1130 have changed) should indicate read has completed
1131 but has not been acknowledged. */
1132 current_status = cp->status;
1133 if (current_status != STATUS_READ_SUCCEEDED
1134 && current_status != STATUS_READ_FAILED)
1135 DebPrint (("char_avail set, but read not completed: status %d\n",
1136 current_status));
1137 }
1138 else
1139 {
1140 /* char_avail has not been signalled, so status should
1141 indicate that read is in progress; small possibility
1142 that read has completed but event wasn't yet signalled
1143 when we tested it (because a context switch occurred
1144 or if running on separate CPUs). */
1145 if (current_status != STATUS_READ_READY
1146 && current_status != STATUS_READ_IN_PROGRESS
1147 && current_status != STATUS_READ_SUCCEEDED
1148 && current_status != STATUS_READ_FAILED)
1149 DebPrint (("char_avail reset, but read status is bad: %d\n",
1150 current_status));
1151 }
1152 #endif
1153 wait_hnd[nh] = cp->char_avail;
1154 fdindex[nh] = i;
1155 if (!wait_hnd[nh]) abort ();
1156 nh++;
1157 #ifdef FULL_DEBUG
1158 DebPrint (("select waiting on child %d fd %d\n",
1159 cp-child_procs, i));
1160 #endif
1161 }
1162 else
1163 {
1164 /* Unable to find something to wait on for this fd, skip */
1165
1166 /* Note that this is not a fatal error, and can in fact
1167 happen in unusual circumstances. Specifically, if
1168 sys_spawnve fails, eg. because the program doesn't
1169 exist, and debug-on-error is t so Fsignal invokes a
1170 nested input loop, then the process output pipe is
1171 still included in input_wait_mask with no child_proc
1172 associated with it. (It is removed when the debugger
1173 exits the nested input loop and the error is thrown.) */
1174
1175 DebPrint (("sys_select: fd %ld is invalid! ignoring\n", i));
1176 }
1177 }
1178 }
1179
1180 count_children:
1181 /* Add handles of child processes. */
1182 nc = 0;
1183 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
1184 /* Some child_procs might be sockets; ignore them. Also some
1185 children may have died already, but we haven't finished reading
1186 the process output; ignore them too. */
1187 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
1188 && (cp->fd < 0
1189 || (fd_info[cp->fd].flags & FILE_SEND_SIGCHLD) == 0
1190 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
1191 )
1192 {
1193 wait_hnd[nh + nc] = cp->procinfo.hProcess;
1194 cps[nc] = cp;
1195 nc++;
1196 }
1197
1198 /* Nothing to look for, so we didn't find anything */
1199 if (nh + nc == 0)
1200 {
1201 if (timeout)
1202 Sleep (timeout_ms);
1203 return 0;
1204 }
1205
1206 start_time = GetTickCount ();
1207
1208 /* Wait for input or child death to be signalled. If user input is
1209 allowed, then also accept window messages. */
1210 if (FD_ISSET (0, &orfds))
1211 active = MsgWaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms,
1212 QS_ALLINPUT);
1213 else
1214 active = WaitForMultipleObjects (nh + nc, wait_hnd, FALSE, timeout_ms);
1215
1216 if (active == WAIT_FAILED)
1217 {
1218 DebPrint (("select.WaitForMultipleObjects (%d, %lu) failed with %lu\n",
1219 nh + nc, timeout_ms, GetLastError ()));
1220 /* don't return EBADF - this causes wait_reading_process_input to
1221 abort; WAIT_FAILED is returned when single-stepping under
1222 Windows 95 after switching thread focus in debugger, and
1223 possibly at other times. */
1224 errno = EINTR;
1225 return -1;
1226 }
1227 else if (active == WAIT_TIMEOUT)
1228 {
1229 return 0;
1230 }
1231 else if (active >= WAIT_OBJECT_0
1232 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
1233 {
1234 active -= WAIT_OBJECT_0;
1235 }
1236 else if (active >= WAIT_ABANDONED_0
1237 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
1238 {
1239 active -= WAIT_ABANDONED_0;
1240 }
1241 else
1242 abort ();
1243
1244 /* Loop over all handles after active (now officially documented as
1245 being the first signalled handle in the array). We do this to
1246 ensure fairness, so that all channels with data available will be
1247 processed - otherwise higher numbered channels could be starved. */
1248 do
1249 {
1250 if (active == nh + nc)
1251 {
1252 /* There are messages in the lisp thread's queue; we must
1253 drain the queue now to ensure they are processed promptly,
1254 because if we don't do so, we will not be woken again until
1255 further messages arrive.
1256
1257 NB. If ever we allow window message procedures to callback
1258 into lisp, we will need to ensure messages are dispatched
1259 at a safe time for lisp code to be run (*), and we may also
1260 want to provide some hooks in the dispatch loop to cater
1261 for modeless dialogs created by lisp (ie. to register
1262 window handles to pass to IsDialogMessage).
1263
1264 (*) Note that MsgWaitForMultipleObjects above is an
1265 internal dispatch point for messages that are sent to
1266 windows created by this thread. */
1267 drain_message_queue ();
1268 }
1269 else if (active >= nh)
1270 {
1271 cp = cps[active - nh];
1272
1273 /* We cannot always signal SIGCHLD immediately; if we have not
1274 finished reading the process output, we must delay sending
1275 SIGCHLD until we do. */
1276
1277 if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_AT_EOF) == 0)
1278 fd_info[cp->fd].flags |= FILE_SEND_SIGCHLD;
1279 /* SIG_DFL for SIGCHLD is ignore */
1280 else if (sig_handlers[SIGCHLD] != SIG_DFL &&
1281 sig_handlers[SIGCHLD] != SIG_IGN)
1282 {
1283 #ifdef FULL_DEBUG
1284 DebPrint (("select calling SIGCHLD handler for pid %d\n",
1285 cp->pid));
1286 #endif
1287 dead_child = cp;
1288 sig_handlers[SIGCHLD] (SIGCHLD);
1289 dead_child = NULL;
1290 }
1291 }
1292 else if (fdindex[active] == -1)
1293 {
1294 /* Quit (C-g) was detected. */
1295 errno = EINTR;
1296 return -1;
1297 }
1298 else if (fdindex[active] == 0)
1299 {
1300 /* Keyboard input available */
1301 FD_SET (0, rfds);
1302 nr++;
1303 }
1304 else
1305 {
1306 /* must be a socket or pipe - read ahead should have
1307 completed, either succeeding or failing. */
1308 FD_SET (fdindex[active], rfds);
1309 nr++;
1310 }
1311
1312 /* Even though wait_reading_process_output only reads from at most
1313 one channel, we must process all channels here so that we reap
1314 all children that have died. */
1315 while (++active < nh + nc)
1316 if (WaitForSingleObject (wait_hnd[active], 0) == WAIT_OBJECT_0)
1317 break;
1318 } while (active < nh + nc);
1319
1320 /* If no input has arrived and timeout hasn't expired, wait again. */
1321 if (nr == 0)
1322 {
1323 DWORD elapsed = GetTickCount () - start_time;
1324
1325 if (timeout_ms > elapsed) /* INFINITE is MAX_UINT */
1326 {
1327 if (timeout_ms != INFINITE)
1328 timeout_ms -= elapsed;
1329 goto count_children;
1330 }
1331 }
1332
1333 return nr;
1334 }
1335
1336 /* Substitute for certain kill () operations */
1337
1338 static BOOL CALLBACK
1339 find_child_console (HWND hwnd, LPARAM arg)
1340 {
1341 child_process * cp = (child_process *) arg;
1342 DWORD thread_id;
1343 DWORD process_id;
1344
1345 thread_id = GetWindowThreadProcessId (hwnd, &process_id);
1346 if (process_id == cp->procinfo.dwProcessId)
1347 {
1348 char window_class[32];
1349
1350 GetClassName (hwnd, window_class, sizeof (window_class));
1351 if (strcmp (window_class,
1352 (os_subtype == OS_WIN95)
1353 ? "tty"
1354 : "ConsoleWindowClass") == 0)
1355 {
1356 cp->hwnd = hwnd;
1357 return FALSE;
1358 }
1359 }
1360 /* keep looking */
1361 return TRUE;
1362 }
1363
1364 int
1365 sys_kill (int pid, int sig)
1366 {
1367 child_process *cp;
1368 HANDLE proc_hand;
1369 int need_to_free = 0;
1370 int rc = 0;
1371
1372 /* Only handle signals that will result in the process dying */
1373 if (sig != SIGINT && sig != SIGKILL && sig != SIGQUIT && sig != SIGHUP)
1374 {
1375 errno = EINVAL;
1376 return -1;
1377 }
1378
1379 cp = find_child_pid (pid);
1380 if (cp == NULL)
1381 {
1382 proc_hand = OpenProcess (PROCESS_TERMINATE, 0, pid);
1383 if (proc_hand == NULL)
1384 {
1385 errno = EPERM;
1386 return -1;
1387 }
1388 need_to_free = 1;
1389 }
1390 else
1391 {
1392 proc_hand = cp->procinfo.hProcess;
1393 pid = cp->procinfo.dwProcessId;
1394
1395 /* Try to locate console window for process. */
1396 EnumWindows (find_child_console, (LPARAM) cp);
1397 }
1398
1399 if (sig == SIGINT || sig == SIGQUIT)
1400 {
1401 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1402 {
1403 BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
1404 /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */
1405 BYTE vk_break_code = (sig == SIGINT) ? 'C' : VK_CANCEL;
1406 BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1407 HWND foreground_window;
1408
1409 if (break_scan_code == 0)
1410 {
1411 /* Fake Ctrl-C for SIGQUIT if we can't manage Ctrl-Break. */
1412 vk_break_code = 'C';
1413 break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
1414 }
1415
1416 foreground_window = GetForegroundWindow ();
1417 if (foreground_window)
1418 {
1419 /* NT 5.0, and apparently also Windows 98, will not allow
1420 a Window to be set to foreground directly without the
1421 user's involvement. The workaround is to attach
1422 ourselves to the thread that owns the foreground
1423 window, since that is the only thread that can set the
1424 foreground window. */
1425 DWORD foreground_thread, child_thread;
1426 foreground_thread =
1427 GetWindowThreadProcessId (foreground_window, NULL);
1428 if (foreground_thread == GetCurrentThreadId ()
1429 || !AttachThreadInput (GetCurrentThreadId (),
1430 foreground_thread, TRUE))
1431 foreground_thread = 0;
1432
1433 child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
1434 if (child_thread == GetCurrentThreadId ()
1435 || !AttachThreadInput (GetCurrentThreadId (),
1436 child_thread, TRUE))
1437 child_thread = 0;
1438
1439 /* Set the foreground window to the child. */
1440 if (SetForegroundWindow (cp->hwnd))
1441 {
1442 /* Generate keystrokes as if user had typed Ctrl-Break or
1443 Ctrl-C. */
1444 keybd_event (VK_CONTROL, control_scan_code, 0, 0);
1445 keybd_event (vk_break_code, break_scan_code,
1446 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
1447 keybd_event (vk_break_code, break_scan_code,
1448 (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
1449 | KEYEVENTF_KEYUP, 0);
1450 keybd_event (VK_CONTROL, control_scan_code,
1451 KEYEVENTF_KEYUP, 0);
1452
1453 /* Sleep for a bit to give time for Emacs frame to respond
1454 to focus change events (if Emacs was active app). */
1455 Sleep (100);
1456
1457 SetForegroundWindow (foreground_window);
1458 }
1459 /* Detach from the foreground and child threads now that
1460 the foreground switching is over. */
1461 if (foreground_thread)
1462 AttachThreadInput (GetCurrentThreadId (),
1463 foreground_thread, FALSE);
1464 if (child_thread)
1465 AttachThreadInput (GetCurrentThreadId (),
1466 child_thread, FALSE);
1467 }
1468 }
1469 /* Ctrl-Break is NT equivalent of SIGINT. */
1470 else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
1471 {
1472 DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
1473 "for pid %lu\n", GetLastError (), pid));
1474 errno = EINVAL;
1475 rc = -1;
1476 }
1477 }
1478 else
1479 {
1480 if (NILP (Vw32_start_process_share_console) && cp && cp->hwnd)
1481 {
1482 #if 1
1483 if (os_subtype == OS_WIN95)
1484 {
1485 /*
1486 Another possibility is to try terminating the VDM out-right by
1487 calling the Shell VxD (id 0x17) V86 interface, function #4
1488 "SHELL_Destroy_VM", ie.
1489
1490 mov edx,4
1491 mov ebx,vm_handle
1492 call shellapi
1493
1494 First need to determine the current VM handle, and then arrange for
1495 the shellapi call to be made from the system vm (by using
1496 Switch_VM_and_callback).
1497
1498 Could try to invoke DestroyVM through CallVxD.
1499
1500 */
1501 #if 0
1502 /* On Win95, posting WM_QUIT causes the 16-bit subsystem
1503 to hang when cmdproxy is used in conjunction with
1504 command.com for an interactive shell. Posting
1505 WM_CLOSE pops up a dialog that, when Yes is selected,
1506 does the same thing. TerminateProcess is also less
1507 than ideal in that subprocesses tend to stick around
1508 until the machine is shutdown, but at least it
1509 doesn't freeze the 16-bit subsystem. */
1510 PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
1511 #endif
1512 if (!TerminateProcess (proc_hand, 0xff))
1513 {
1514 DebPrint (("sys_kill.TerminateProcess returned %d "
1515 "for pid %lu\n", GetLastError (), pid));
1516 errno = EINVAL;
1517 rc = -1;
1518 }
1519 }
1520 else
1521 #endif
1522 PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
1523 }
1524 /* Kill the process. On W32 this doesn't kill child processes
1525 so it doesn't work very well for shells which is why it's not
1526 used in every case. */
1527 else if (!TerminateProcess (proc_hand, 0xff))
1528 {
1529 DebPrint (("sys_kill.TerminateProcess returned %d "
1530 "for pid %lu\n", GetLastError (), pid));
1531 errno = EINVAL;
1532 rc = -1;
1533 }
1534 }
1535
1536 if (need_to_free)
1537 CloseHandle (proc_hand);
1538
1539 return rc;
1540 }
1541
1542 /* extern int report_file_error (char *, Lisp_Object); */
1543
1544 /* The following two routines are used to manipulate stdin, stdout, and
1545 stderr of our child processes.
1546
1547 Assuming that in, out, and err are *not* inheritable, we make them
1548 stdin, stdout, and stderr of the child as follows:
1549
1550 - Save the parent's current standard handles.
1551 - Set the std handles to inheritable duplicates of the ones being passed in.
1552 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1553 NT file handle for a crt file descriptor.)
1554 - Spawn the child, which inherits in, out, and err as stdin,
1555 stdout, and stderr. (see Spawnve)
1556 - Close the std handles passed to the child.
1557 - Reset the parent's standard handles to the saved handles.
1558 (see reset_standard_handles)
1559 We assume that the caller closes in, out, and err after calling us. */
1560
1561 void
1562 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1563 {
1564 HANDLE parent;
1565 HANDLE newstdin, newstdout, newstderr;
1566
1567 parent = GetCurrentProcess ();
1568
1569 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1570 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1571 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1572
1573 /* make inheritable copies of the new handles */
1574 if (!DuplicateHandle (parent,
1575 (HANDLE) _get_osfhandle (in),
1576 parent,
1577 &newstdin,
1578 0,
1579 TRUE,
1580 DUPLICATE_SAME_ACCESS))
1581 report_file_error ("Duplicating input handle for child", Qnil);
1582
1583 if (!DuplicateHandle (parent,
1584 (HANDLE) _get_osfhandle (out),
1585 parent,
1586 &newstdout,
1587 0,
1588 TRUE,
1589 DUPLICATE_SAME_ACCESS))
1590 report_file_error ("Duplicating output handle for child", Qnil);
1591
1592 if (!DuplicateHandle (parent,
1593 (HANDLE) _get_osfhandle (err),
1594 parent,
1595 &newstderr,
1596 0,
1597 TRUE,
1598 DUPLICATE_SAME_ACCESS))
1599 report_file_error ("Duplicating error handle for child", Qnil);
1600
1601 /* and store them as our std handles */
1602 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1603 report_file_error ("Changing stdin handle", Qnil);
1604
1605 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1606 report_file_error ("Changing stdout handle", Qnil);
1607
1608 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1609 report_file_error ("Changing stderr handle", Qnil);
1610 }
1611
1612 void
1613 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1614 {
1615 /* close the duplicated handles passed to the child */
1616 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1617 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1618 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1619
1620 /* now restore parent's saved std handles */
1621 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1622 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1623 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1624 }
1625
1626 void
1627 set_process_dir (char * dir)
1628 {
1629 process_dir = dir;
1630 }
1631
1632 #ifdef HAVE_SOCKETS
1633
1634 /* To avoid problems with winsock implementations that work over dial-up
1635 connections causing or requiring a connection to exist while Emacs is
1636 running, Emacs no longer automatically loads winsock on startup if it
1637 is present. Instead, it will be loaded when open-network-stream is
1638 first called.
1639
1640 To allow full control over when winsock is loaded, we provide these
1641 two functions to dynamically load and unload winsock. This allows
1642 dial-up users to only be connected when they actually need to use
1643 socket services. */
1644
1645 /* From nt.c */
1646 extern HANDLE winsock_lib;
1647 extern BOOL term_winsock (void);
1648 extern BOOL init_winsock (int load_now);
1649
1650 extern Lisp_Object Vsystem_name;
1651
1652 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1653 doc: /* Test for presence of the Windows socket library `winsock'.
1654 Returns non-nil if winsock support is present, nil otherwise.
1655
1656 If the optional argument LOAD-NOW is non-nil, the winsock library is
1657 also loaded immediately if not already loaded. If winsock is loaded,
1658 the winsock local hostname is returned (since this may be different from
1659 the value of `system-name' and should supplant it), otherwise t is
1660 returned to indicate winsock support is present. */)
1661 (load_now)
1662 Lisp_Object load_now;
1663 {
1664 int have_winsock;
1665
1666 have_winsock = init_winsock (!NILP (load_now));
1667 if (have_winsock)
1668 {
1669 if (winsock_lib != NULL)
1670 {
1671 /* Return new value for system-name. The best way to do this
1672 is to call init_system_name, saving and restoring the
1673 original value to avoid side-effects. */
1674 Lisp_Object orig_hostname = Vsystem_name;
1675 Lisp_Object hostname;
1676
1677 init_system_name ();
1678 hostname = Vsystem_name;
1679 Vsystem_name = orig_hostname;
1680 return hostname;
1681 }
1682 return Qt;
1683 }
1684 return Qnil;
1685 }
1686
1687 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1688 0, 0, 0,
1689 doc: /* Unload the Windows socket library `winsock' if loaded.
1690 This is provided to allow dial-up socket connections to be disconnected
1691 when no longer needed. Returns nil without unloading winsock if any
1692 socket connections still exist. */)
1693 ()
1694 {
1695 return term_winsock () ? Qt : Qnil;
1696 }
1697
1698 #endif /* HAVE_SOCKETS */
1699
1700 \f
1701 /* Some miscellaneous functions that are Windows specific, but not GUI
1702 specific (ie. are applicable in terminal or batch mode as well). */
1703
1704 /* lifted from fileio.c */
1705 #define CORRECT_DIR_SEPS(s) \
1706 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1707 else unixtodos_filename (s); \
1708 } while (0)
1709
1710 DEFUN ("w32-short-file-name", Fw32_short_file_name, Sw32_short_file_name, 1, 1, 0,
1711 doc: /* Return the short file name version (8.3) of the full path of FILENAME.
1712 If FILENAME does not exist, return nil.
1713 All path elements in FILENAME are converted to their short names. */)
1714 (filename)
1715 Lisp_Object filename;
1716 {
1717 char shortname[MAX_PATH];
1718
1719 CHECK_STRING (filename);
1720
1721 /* first expand it. */
1722 filename = Fexpand_file_name (filename, Qnil);
1723
1724 /* luckily, this returns the short version of each element in the path. */
1725 if (GetShortPathName (XSTRING (filename)->data, shortname, MAX_PATH) == 0)
1726 return Qnil;
1727
1728 CORRECT_DIR_SEPS (shortname);
1729
1730 return build_string (shortname);
1731 }
1732
1733
1734 DEFUN ("w32-long-file-name", Fw32_long_file_name, Sw32_long_file_name,
1735 1, 1, 0,
1736 doc: /* Return the long file name version of the full path of FILENAME.
1737 If FILENAME does not exist, return nil.
1738 All path elements in FILENAME are converted to their long names. */)
1739 (filename)
1740 Lisp_Object filename;
1741 {
1742 char longname[ MAX_PATH ];
1743
1744 CHECK_STRING (filename);
1745
1746 /* first expand it. */
1747 filename = Fexpand_file_name (filename, Qnil);
1748
1749 if (!w32_get_long_filename (XSTRING (filename)->data, longname, MAX_PATH))
1750 return Qnil;
1751
1752 CORRECT_DIR_SEPS (longname);
1753
1754 return build_string (longname);
1755 }
1756
1757 DEFUN ("w32-set-process-priority", Fw32_set_process_priority,
1758 Sw32_set_process_priority, 2, 2, 0,
1759 doc: /* Set the priority of PROCESS to PRIORITY.
1760 If PROCESS is nil, the priority of Emacs is changed, otherwise the
1761 priority of the process whose pid is PROCESS is changed.
1762 PRIORITY should be one of the symbols high, normal, or low;
1763 any other symbol will be interpreted as normal.
1764
1765 If successful, the return value is t, otherwise nil. */)
1766 (process, priority)
1767 Lisp_Object process, priority;
1768 {
1769 HANDLE proc_handle = GetCurrentProcess ();
1770 DWORD priority_class = NORMAL_PRIORITY_CLASS;
1771 Lisp_Object result = Qnil;
1772
1773 CHECK_SYMBOL (priority);
1774
1775 if (!NILP (process))
1776 {
1777 DWORD pid;
1778 child_process *cp;
1779
1780 CHECK_NUMBER (process);
1781
1782 /* Allow pid to be an internally generated one, or one obtained
1783 externally. This is necessary because real pids on Win95 are
1784 negative. */
1785
1786 pid = XINT (process);
1787 cp = find_child_pid (pid);
1788 if (cp != NULL)
1789 pid = cp->procinfo.dwProcessId;
1790
1791 proc_handle = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
1792 }
1793
1794 if (EQ (priority, Qhigh))
1795 priority_class = HIGH_PRIORITY_CLASS;
1796 else if (EQ (priority, Qlow))
1797 priority_class = IDLE_PRIORITY_CLASS;
1798
1799 if (proc_handle != NULL)
1800 {
1801 if (SetPriorityClass (proc_handle, priority_class))
1802 result = Qt;
1803 if (!NILP (process))
1804 CloseHandle (proc_handle);
1805 }
1806
1807 return result;
1808 }
1809
1810
1811 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1812 Sw32_get_locale_info, 1, 2, 0,
1813 doc: /* Return information about the Windows locale LCID.
1814 By default, return a three letter locale code which encodes the default
1815 language as the first two characters, and the country or regionial variant
1816 as the third letter. For example, ENU refers to `English (United States)',
1817 while ENC means `English (Canadian)'.
1818
1819 If the optional argument LONGFORM is t, the long form of the locale
1820 name is returned, e.g. `English (United States)' instead; if LONGFORM
1821 is a number, it is interpreted as an LCTYPE constant and the corresponding
1822 locale information is returned.
1823
1824 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1825 (lcid, longform)
1826 Lisp_Object lcid, longform;
1827 {
1828 int got_abbrev;
1829 int got_full;
1830 char abbrev_name[32] = { 0 };
1831 char full_name[256] = { 0 };
1832
1833 CHECK_NUMBER (lcid);
1834
1835 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1836 return Qnil;
1837
1838 if (NILP (longform))
1839 {
1840 got_abbrev = GetLocaleInfo (XINT (lcid),
1841 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1842 abbrev_name, sizeof (abbrev_name));
1843 if (got_abbrev)
1844 return build_string (abbrev_name);
1845 }
1846 else if (EQ (longform, Qt))
1847 {
1848 got_full = GetLocaleInfo (XINT (lcid),
1849 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1850 full_name, sizeof (full_name));
1851 if (got_full)
1852 return build_string (full_name);
1853 }
1854 else if (NUMBERP (longform))
1855 {
1856 got_full = GetLocaleInfo (XINT (lcid),
1857 XINT (longform),
1858 full_name, sizeof (full_name));
1859 if (got_full)
1860 return make_unibyte_string (full_name, got_full);
1861 }
1862
1863 return Qnil;
1864 }
1865
1866
1867 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
1868 Sw32_get_current_locale_id, 0, 0, 0,
1869 doc: /* Return Windows locale id for current locale setting.
1870 This is a numerical value; use `w32-get-locale-info' to convert to a
1871 human-readable form. */)
1872 ()
1873 {
1874 return make_number (GetThreadLocale ());
1875 }
1876
1877 DWORD int_from_hex (char * s)
1878 {
1879 DWORD val = 0;
1880 static char hex[] = "0123456789abcdefABCDEF";
1881 char * p;
1882
1883 while (*s && (p = strchr(hex, *s)) != NULL)
1884 {
1885 unsigned digit = p - hex;
1886 if (digit > 15)
1887 digit -= 6;
1888 val = val * 16 + digit;
1889 s++;
1890 }
1891 return val;
1892 }
1893
1894 /* We need to build a global list, since the EnumSystemLocale callback
1895 function isn't given a context pointer. */
1896 Lisp_Object Vw32_valid_locale_ids;
1897
1898 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
1899 {
1900 DWORD id = int_from_hex (localeNum);
1901 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
1902 return TRUE;
1903 }
1904
1905 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
1906 Sw32_get_valid_locale_ids, 0, 0, 0,
1907 doc: /* Return list of all valid Windows locale ids.
1908 Each id is a numerical value; use `w32-get-locale-info' to convert to a
1909 human-readable form. */)
1910 ()
1911 {
1912 Vw32_valid_locale_ids = Qnil;
1913
1914 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
1915
1916 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
1917 return Vw32_valid_locale_ids;
1918 }
1919
1920
1921 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
1922 doc: /* Return Windows locale id for default locale setting.
1923 By default, the system default locale setting is returned; if the optional
1924 parameter USERP is non-nil, the user default locale setting is returned.
1925 This is a numerical value; use `w32-get-locale-info' to convert to a
1926 human-readable form. */)
1927 (userp)
1928 Lisp_Object userp;
1929 {
1930 if (NILP (userp))
1931 return make_number (GetSystemDefaultLCID ());
1932 return make_number (GetUserDefaultLCID ());
1933 }
1934
1935
1936 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
1937 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
1938 If successful, the new locale id is returned, otherwise nil. */)
1939 (lcid)
1940 Lisp_Object lcid;
1941 {
1942 CHECK_NUMBER (lcid);
1943
1944 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1945 return Qnil;
1946
1947 if (!SetThreadLocale (XINT (lcid)))
1948 return Qnil;
1949
1950 /* Need to set input thread locale if present. */
1951 if (dwWindowsThreadId)
1952 /* Reply is not needed. */
1953 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
1954
1955 return make_number (GetThreadLocale ());
1956 }
1957
1958
1959 /* We need to build a global list, since the EnumCodePages callback
1960 function isn't given a context pointer. */
1961 Lisp_Object Vw32_valid_codepages;
1962
1963 BOOL CALLBACK enum_codepage_fn (LPTSTR codepageNum)
1964 {
1965 DWORD id = atoi (codepageNum);
1966 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
1967 return TRUE;
1968 }
1969
1970 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
1971 Sw32_get_valid_codepages, 0, 0, 0,
1972 doc: /* Return list of all valid Windows codepages. */)
1973 ()
1974 {
1975 Vw32_valid_codepages = Qnil;
1976
1977 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
1978
1979 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
1980 return Vw32_valid_codepages;
1981 }
1982
1983
1984 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
1985 Sw32_get_console_codepage, 0, 0, 0,
1986 doc: /* Return current Windows codepage for console input. */)
1987 ()
1988 {
1989 return make_number (GetConsoleCP ());
1990 }
1991
1992
1993 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
1994 Sw32_set_console_codepage, 1, 1, 0,
1995 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
1996 The codepage setting affects keyboard input and display in tty mode.
1997 If successful, the new CP is returned, otherwise nil. */)
1998 (cp)
1999 Lisp_Object cp;
2000 {
2001 CHECK_NUMBER (cp);
2002
2003 if (!IsValidCodePage (XINT (cp)))
2004 return Qnil;
2005
2006 if (!SetConsoleCP (XINT (cp)))
2007 return Qnil;
2008
2009 return make_number (GetConsoleCP ());
2010 }
2011
2012
2013 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2014 Sw32_get_console_output_codepage, 0, 0, 0,
2015 doc: /* Return current Windows codepage for console output. */)
2016 ()
2017 {
2018 return make_number (GetConsoleOutputCP ());
2019 }
2020
2021
2022 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2023 Sw32_set_console_output_codepage, 1, 1, 0,
2024 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2025 The codepage setting affects keyboard input and display in tty mode.
2026 If successful, the new CP is returned, otherwise nil. */)
2027 (cp)
2028 Lisp_Object cp;
2029 {
2030 CHECK_NUMBER (cp);
2031
2032 if (!IsValidCodePage (XINT (cp)))
2033 return Qnil;
2034
2035 if (!SetConsoleOutputCP (XINT (cp)))
2036 return Qnil;
2037
2038 return make_number (GetConsoleOutputCP ());
2039 }
2040
2041
2042 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2043 Sw32_get_codepage_charset, 1, 1, 0,
2044 doc: /* Return charset of codepage CP.
2045 Returns nil if the codepage is not valid. */)
2046 (cp)
2047 Lisp_Object cp;
2048 {
2049 CHARSETINFO info;
2050
2051 CHECK_NUMBER (cp);
2052
2053 if (!IsValidCodePage (XINT (cp)))
2054 return Qnil;
2055
2056 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2057 return make_number (info.ciCharset);
2058
2059 return Qnil;
2060 }
2061
2062
2063 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2064 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2065 doc: /* Return list of Windows keyboard languages and layouts.
2066 The return value is a list of pairs of language id and layout id. */)
2067 ()
2068 {
2069 int num_layouts = GetKeyboardLayoutList (0, NULL);
2070 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2071 Lisp_Object obj = Qnil;
2072
2073 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2074 {
2075 while (--num_layouts >= 0)
2076 {
2077 DWORD kl = (DWORD) layouts[num_layouts];
2078
2079 obj = Fcons (Fcons (make_number (kl & 0xffff),
2080 make_number ((kl >> 16) & 0xffff)),
2081 obj);
2082 }
2083 }
2084
2085 return obj;
2086 }
2087
2088
2089 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2090 Sw32_get_keyboard_layout, 0, 0, 0,
2091 doc: /* Return current Windows keyboard language and layout.
2092 The return value is the cons of the language id and the layout id. */)
2093 ()
2094 {
2095 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2096
2097 return Fcons (make_number (kl & 0xffff),
2098 make_number ((kl >> 16) & 0xffff));
2099 }
2100
2101
2102 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2103 Sw32_set_keyboard_layout, 1, 1, 0,
2104 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2105 The keyboard layout setting affects interpretation of keyboard input.
2106 If successful, the new layout id is returned, otherwise nil. */)
2107 (layout)
2108 Lisp_Object layout;
2109 {
2110 DWORD kl;
2111
2112 CHECK_CONS (layout);
2113 CHECK_NUMBER_CAR (layout);
2114 CHECK_NUMBER_CDR (layout);
2115
2116 kl = (XINT (XCAR (layout)) & 0xffff)
2117 | (XINT (XCDR (layout)) << 16);
2118
2119 /* Synchronize layout with input thread. */
2120 if (dwWindowsThreadId)
2121 {
2122 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2123 (WPARAM) kl, 0))
2124 {
2125 MSG msg;
2126 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2127
2128 if (msg.wParam == 0)
2129 return Qnil;
2130 }
2131 }
2132 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2133 return Qnil;
2134
2135 return Fw32_get_keyboard_layout ();
2136 }
2137
2138 \f
2139 syms_of_ntproc ()
2140 {
2141 Qhigh = intern ("high");
2142 Qlow = intern ("low");
2143
2144 #ifdef HAVE_SOCKETS
2145 defsubr (&Sw32_has_winsock);
2146 defsubr (&Sw32_unload_winsock);
2147 #endif
2148 defsubr (&Sw32_short_file_name);
2149 defsubr (&Sw32_long_file_name);
2150 defsubr (&Sw32_set_process_priority);
2151 defsubr (&Sw32_get_locale_info);
2152 defsubr (&Sw32_get_current_locale_id);
2153 defsubr (&Sw32_get_default_locale_id);
2154 defsubr (&Sw32_get_valid_locale_ids);
2155 defsubr (&Sw32_set_current_locale);
2156
2157 defsubr (&Sw32_get_console_codepage);
2158 defsubr (&Sw32_set_console_codepage);
2159 defsubr (&Sw32_get_console_output_codepage);
2160 defsubr (&Sw32_set_console_output_codepage);
2161 defsubr (&Sw32_get_valid_codepages);
2162 defsubr (&Sw32_get_codepage_charset);
2163
2164 defsubr (&Sw32_get_valid_keyboard_layouts);
2165 defsubr (&Sw32_get_keyboard_layout);
2166 defsubr (&Sw32_set_keyboard_layout);
2167
2168 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args,
2169 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2170 Because Windows does not directly pass argv arrays to child processes,
2171 programs have to reconstruct the argv array by parsing the command
2172 line string. For an argument to contain a space, it must be enclosed
2173 in double quotes or it will be parsed as multiple arguments.
2174
2175 If the value is a character, that character will be used to escape any
2176 quote characters that appear, otherwise a suitable escape character
2177 will be chosen based on the type of the program. */);
2178 Vw32_quote_process_args = Qt;
2179
2180 DEFVAR_LISP ("w32-start-process-show-window",
2181 &Vw32_start_process_show_window,
2182 doc: /* When nil, new child processes hide their windows.
2183 When non-nil, they show their window in the method of their choice.
2184 This variable doesn't affect GUI applications, which will never be hidden. */);
2185 Vw32_start_process_show_window = Qnil;
2186
2187 DEFVAR_LISP ("w32-start-process-share-console",
2188 &Vw32_start_process_share_console,
2189 doc: /* When nil, new child processes are given a new console.
2190 When non-nil, they share the Emacs console; this has the limitation of
2191 allowing only one DOS subprocess to run at a time (whether started directly
2192 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2193 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2194 otherwise respond to interrupts from Emacs. */);
2195 Vw32_start_process_share_console = Qnil;
2196
2197 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2198 &Vw32_start_process_inherit_error_mode,
2199 doc: /* When nil, new child processes revert to the default error mode.
2200 When non-nil, they inherit their error mode setting from Emacs, which stops
2201 them blocking when trying to access unmounted drives etc. */);
2202 Vw32_start_process_inherit_error_mode = Qt;
2203
2204 DEFVAR_INT ("w32-pipe-read-delay", &Vw32_pipe_read_delay,
2205 doc: /* Forced delay before reading subprocess output.
2206 This is done to improve the buffering of subprocess output, by
2207 avoiding the inefficiency of frequently reading small amounts of data.
2208
2209 If positive, the value is the number of milliseconds to sleep before
2210 reading the subprocess output. If negative, the magnitude is the number
2211 of time slices to wait (effectively boosting the priority of the child
2212 process temporarily). A value of zero disables waiting entirely. */);
2213 Vw32_pipe_read_delay = 50;
2214
2215 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names,
2216 doc: /* Non-nil means convert all-upper case file names to lower case.
2217 This applies when performing completions and file name expansion.
2218 Note that the value of this setting also affects remote file names,
2219 so you probably don't want to set to non-nil if you use case-sensitive
2220 filesystems via ange-ftp. */);
2221 Vw32_downcase_file_names = Qnil;
2222
2223 #if 0
2224 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes,
2225 doc: /* Non-nil means attempt to fake realistic inode values.
2226 This works by hashing the truename of files, and should detect
2227 aliasing between long and short (8.3 DOS) names, but can have
2228 false positives because of hash collisions. Note that determing
2229 the truename of a file can be slow. */);
2230 Vw32_generate_fake_inodes = Qnil;
2231 #endif
2232
2233 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes,
2234 doc: /* Non-nil means determine accurate link count in file-attributes.
2235 This option slows down file-attributes noticeably, so is disabled by
2236 default. Note that it is only useful for files on NTFS volumes,
2237 where hard links are supported. */);
2238 Vw32_get_true_file_attributes = Qnil;
2239 }
2240 /* end of ntproc.c */