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