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