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