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