(x_set_alpha): Set alpha to -1 if nil given.
[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 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
33 /* must include CRT headers *before* config.h */
34
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #undef signal
40 #undef wait
41 #undef spawnve
42 #undef select
43 #undef kill
44
45 #include <windows.h>
46 #ifdef __GNUC__
47 /* This definition is missing from mingw32 headers. */
48 extern BOOL WINAPI IsValidLocale(LCID, DWORD);
49 #endif
50
51 #ifdef HAVE_LANGINFO_CODESET
52 #include <nl_types.h>
53 #include <langinfo.h>
54 #endif
55
56 #include "lisp.h"
57 #include "character.h"
58 #include "w32.h"
59 #include "w32heap.h"
60 #include "systime.h"
61 #include "syswait.h"
62 #include "process.h"
63 #include "syssignal.h"
64 #include "w32term.h"
65 #include "dispextern.h" /* for xstrcasecmp */
66
67 #define RVA_TO_PTR(var,section,filedata) \
68 ((void *)((section)->PointerToRawData \
69 + ((DWORD)(var) - (section)->VirtualAddress) \
70 + (filedata).file_base))
71
72 /* Control whether spawnve quotes arguments as necessary to ensure
73 correct parsing by child process. Because not all uses of spawnve
74 are careful about constructing argv arrays, we make this behavior
75 conditional (off by default). */
76 Lisp_Object Vw32_quote_process_args;
77
78 /* Control whether create_child causes the process' window to be
79 hidden. The default is nil. */
80 Lisp_Object Vw32_start_process_show_window;
81
82 /* Control whether create_child causes the process to inherit Emacs'
83 console window, or be given a new one of its own. The default is
84 nil, to allow multiple DOS programs to run on Win95. Having separate
85 consoles also allows Emacs to cleanly terminate process groups. */
86 Lisp_Object Vw32_start_process_share_console;
87
88 /* Control whether create_child cause the process to inherit Emacs'
89 error mode setting. The default is t, to minimize the possibility of
90 subprocesses blocking when accessing unmounted drives. */
91 Lisp_Object Vw32_start_process_inherit_error_mode;
92
93 /* Time to sleep before reading from a subprocess output pipe - this
94 avoids the inefficiency of frequently reading small amounts of data.
95 This is primarily necessary for handling DOS processes on Windows 95,
96 but is useful for W32 processes on both Windows 95 and NT as well. */
97 int w32_pipe_read_delay;
98
99 /* Control conversion of upper case file names to lower case.
100 nil means no, t means yes. */
101 Lisp_Object Vw32_downcase_file_names;
102
103 /* Control whether stat() attempts to generate fake but hopefully
104 "accurate" inode values, by hashing the absolute truenames of files.
105 This should detect aliasing between long and short names, but still
106 allows the possibility of hash collisions. */
107 Lisp_Object Vw32_generate_fake_inodes;
108
109 /* Control whether stat() attempts to determine file type and link count
110 exactly, at the expense of slower operation. Since true hard links
111 are supported on NTFS volumes, this is only relevant on NT. */
112 Lisp_Object Vw32_get_true_file_attributes;
113 extern Lisp_Object Qlocal;
114
115 Lisp_Object Qhigh, Qlow;
116
117 #ifdef EMACSDEBUG
118 void _DebPrint (const char *fmt, ...)
119 {
120 char buf[1024];
121 va_list args;
122
123 va_start (args, fmt);
124 vsprintf (buf, fmt, args);
125 va_end (args);
126 OutputDebugString (buf);
127 }
128 #endif
129
130 typedef void (_CALLBACK_ *signal_handler)(int);
131
132 /* Signal handlers...SIG_DFL == 0 so this is initialized correctly. */
133 static signal_handler sig_handlers[NSIG];
134
135 /* Fake signal implementation to record the SIGCHLD handler. */
136 signal_handler
137 sys_signal (int sig, signal_handler handler)
138 {
139 signal_handler old;
140
141 if (sig != SIGCHLD)
142 {
143 errno = EINVAL;
144 return SIG_ERR;
145 }
146 old = sig_handlers[sig];
147 sig_handlers[sig] = handler;
148 return old;
149 }
150
151 /* Defined in <process.h> which conflicts with the local copy */
152 #define _P_NOWAIT 1
153
154 /* Child process management list. */
155 int child_proc_count = 0;
156 child_process child_procs[ MAX_CHILDREN ];
157 child_process *dead_child = NULL;
158
159 DWORD WINAPI reader_thread (void *arg);
160
161 /* Find an unused process slot. */
162 child_process *
163 new_child (void)
164 {
165 child_process *cp;
166 DWORD id;
167
168 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
169 if (!CHILD_ACTIVE (cp))
170 goto Initialise;
171 if (child_proc_count == MAX_CHILDREN)
172 return NULL;
173 cp = &child_procs[child_proc_count++];
174
175 Initialise:
176 memset (cp, 0, sizeof(*cp));
177 cp->fd = -1;
178 cp->pid = -1;
179 cp->procinfo.hProcess = NULL;
180 cp->status = STATUS_READ_ERROR;
181
182 /* use manual reset event so that select() will function properly */
183 cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
184 if (cp->char_avail)
185 {
186 cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
187 if (cp->char_consumed)
188 {
189 cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
190 if (cp->thrd)
191 return cp;
192 }
193 }
194 delete_child (cp);
195 return NULL;
196 }
197
198 void
199 delete_child (child_process *cp)
200 {
201 int i;
202
203 /* Should not be deleting a child that is still needed. */
204 for (i = 0; i < MAXDESC; i++)
205 if (fd_info[i].cp == cp)
206 abort ();
207
208 if (!CHILD_ACTIVE (cp))
209 return;
210
211 /* reap thread if necessary */
212 if (cp->thrd)
213 {
214 DWORD rc;
215
216 if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
217 {
218 /* let the thread exit cleanly if possible */
219 cp->status = STATUS_READ_ERROR;
220 SetEvent (cp->char_consumed);
221 #if 0
222 /* We used to forceably terminate the thread here, but it
223 is normally unnecessary, and in abnormal cases, the worst that
224 will happen is we have an extra idle thread hanging around
225 waiting for the zombie process. */
226 if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
227 {
228 DebPrint (("delete_child.WaitForSingleObject (thread) failed "
229 "with %lu for fd %ld\n", GetLastError (), cp->fd));
230 TerminateThread (cp->thrd, 0);
231 }
232 #endif
233 }
234 CloseHandle (cp->thrd);
235 cp->thrd = NULL;
236 }
237 if (cp->char_avail)
238 {
239 CloseHandle (cp->char_avail);
240 cp->char_avail = NULL;
241 }
242 if (cp->char_consumed)
243 {
244 CloseHandle (cp->char_consumed);
245 cp->char_consumed = NULL;
246 }
247
248 /* update child_proc_count (highest numbered slot in use plus one) */
249 if (cp == child_procs + child_proc_count - 1)
250 {
251 for (i = child_proc_count-1; i >= 0; i--)
252 if (CHILD_ACTIVE (&child_procs[i]))
253 {
254 child_proc_count = i + 1;
255 break;
256 }
257 }
258 if (i < 0)
259 child_proc_count = 0;
260 }
261
262 /* Find a child by pid. */
263 static child_process *
264 find_child_pid (DWORD pid)
265 {
266 child_process *cp;
267
268 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
269 if (CHILD_ACTIVE (cp) && pid == cp->pid)
270 return cp;
271 return NULL;
272 }
273
274
275 /* Thread proc for child process and socket reader threads. Each thread
276 is normally blocked until woken by select() to check for input by
277 reading one char. When the read completes, char_avail is signaled
278 to wake up the select emulator and the thread blocks itself again. */
279 DWORD WINAPI
280 reader_thread (void *arg)
281 {
282 child_process *cp;
283
284 /* Our identity */
285 cp = (child_process *)arg;
286
287 /* We have to wait for the go-ahead before we can start */
288 if (cp == NULL
289 || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
290 return 1;
291
292 for (;;)
293 {
294 int rc;
295
296 if (fd_info[cp->fd].flags & FILE_LISTEN)
297 rc = _sys_wait_accept (cp->fd);
298 else
299 rc = _sys_read_ahead (cp->fd);
300
301 /* The name char_avail is a misnomer - it really just means the
302 read-ahead has completed, whether successfully or not. */
303 if (!SetEvent (cp->char_avail))
304 {
305 DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
306 GetLastError (), cp->fd));
307 return 1;
308 }
309
310 if (rc == STATUS_READ_ERROR)
311 return 1;
312
313 /* If the read died, the child has died so let the thread die */
314 if (rc == STATUS_READ_FAILED)
315 break;
316
317 /* Wait until our input is acknowledged before reading again */
318 if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
319 {
320 DebPrint (("reader_thread.WaitForSingleObject failed with "
321 "%lu for fd %ld\n", GetLastError (), cp->fd));
322 break;
323 }
324 }
325 return 0;
326 }
327
328 /* To avoid Emacs changing directory, we just record here the directory
329 the new process should start in. This is set just before calling
330 sys_spawnve, and is not generally valid at any other time. */
331 static char * process_dir;
332
333 static BOOL
334 create_child (char *exe, char *cmdline, char *env, int is_gui_app,
335 int * pPid, child_process *cp)
336 {
337 STARTUPINFO start;
338 SECURITY_ATTRIBUTES sec_attrs;
339 #if 0
340 SECURITY_DESCRIPTOR sec_desc;
341 #endif
342 DWORD flags;
343 char dir[ MAXPATHLEN ];
344
345 if (cp == NULL) abort ();
346
347 memset (&start, 0, sizeof (start));
348 start.cb = sizeof (start);
349
350 #ifdef HAVE_NTGUI
351 if (NILP (Vw32_start_process_show_window) && !is_gui_app)
352 start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
353 else
354 start.dwFlags = STARTF_USESTDHANDLES;
355 start.wShowWindow = SW_HIDE;
356
357 start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
358 start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
359 start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
360 #endif /* HAVE_NTGUI */
361
362 #if 0
363 /* Explicitly specify no security */
364 if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
365 goto EH_Fail;
366 if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
367 goto EH_Fail;
368 #endif
369 sec_attrs.nLength = sizeof (sec_attrs);
370 sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
371 sec_attrs.bInheritHandle = FALSE;
372
373 strcpy (dir, process_dir);
374 unixtodos_filename (dir);
375
376 flags = (!NILP (Vw32_start_process_share_console)
377 ? CREATE_NEW_PROCESS_GROUP
378 : CREATE_NEW_CONSOLE);
379 if (NILP (Vw32_start_process_inherit_error_mode))
380 flags |= CREATE_DEFAULT_ERROR_MODE;
381 if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
382 flags, env, dir, &start, &cp->procinfo))
383 goto EH_Fail;
384
385 cp->pid = (int) cp->procinfo.dwProcessId;
386
387 /* Hack for Windows 95, which assigns large (ie negative) pids */
388 if (cp->pid < 0)
389 cp->pid = -cp->pid;
390
391 /* pid must fit in a Lisp_Int */
392 cp->pid = cp->pid & INTMASK;
393
394 *pPid = cp->pid;
395
396 return TRUE;
397
398 EH_Fail:
399 DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
400 return FALSE;
401 }
402
403 /* create_child doesn't know what emacs' file handle will be for waiting
404 on output from the child, so we need to make this additional call
405 to register the handle with the process
406 This way the select emulator knows how to match file handles with
407 entries in child_procs. */
408 void
409 register_child (int pid, int fd)
410 {
411 child_process *cp;
412
413 cp = find_child_pid (pid);
414 if (cp == NULL)
415 {
416 DebPrint (("register_child unable to find pid %lu\n", pid));
417 return;
418 }
419
420 #ifdef FULL_DEBUG
421 DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
422 #endif
423
424 cp->fd = fd;
425
426 /* thread is initially blocked until select is called; set status so
427 that select will release thread */
428 cp->status = STATUS_READ_ACKNOWLEDGED;
429
430 /* attach child_process to fd_info */
431 if (fd_info[fd].cp != NULL)
432 {
433 DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
434 abort ();
435 }
436
437 fd_info[fd].cp = cp;
438 }
439
440 /* When a process dies its pipe will break so the reader thread will
441 signal failure to the select emulator.
442 The select emulator then calls this routine to clean up.
443 Since the thread signaled failure we can assume it is exiting. */
444 static void
445 reap_subprocess (child_process *cp)
446 {
447 if (cp->procinfo.hProcess)
448 {
449 /* Reap the process */
450 #ifdef FULL_DEBUG
451 /* Process should have already died before we are called. */
452 if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
453 DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
454 #endif
455 CloseHandle (cp->procinfo.hProcess);
456 cp->procinfo.hProcess = NULL;
457 CloseHandle (cp->procinfo.hThread);
458 cp->procinfo.hThread = NULL;
459 }
460
461 /* For asynchronous children, the child_proc resources will be freed
462 when the last pipe read descriptor is closed; for synchronous
463 children, we must explicitly free the resources now because
464 register_child has not been called. */
465 if (cp->fd == -1)
466 delete_child (cp);
467 }
468
469 /* Wait for any of our existing child processes to die
470 When it does, close its handle
471 Return the pid and fill in the status if non-NULL. */
472
473 int
474 sys_wait (int *status)
475 {
476 DWORD active, retval;
477 int nh;
478 int pid;
479 child_process *cp, *cps[MAX_CHILDREN];
480 HANDLE wait_hnd[MAX_CHILDREN];
481
482 nh = 0;
483 if (dead_child != NULL)
484 {
485 /* We want to wait for a specific child */
486 wait_hnd[nh] = dead_child->procinfo.hProcess;
487 cps[nh] = dead_child;
488 if (!wait_hnd[nh]) abort ();
489 nh++;
490 active = 0;
491 goto get_result;
492 }
493 else
494 {
495 for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
496 /* some child_procs might be sockets; ignore them */
497 if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
498 && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
499 {
500 wait_hnd[nh] = cp->procinfo.hProcess;
501 cps[nh] = cp;
502 nh++;
503 }
504 }
505
506 if (nh == 0)
507 {
508 /* Nothing to wait on, so fail */
509 errno = ECHILD;
510 return -1;
511 }
512
513 do
514 {
515 /* Check for quit about once a second. */
516 QUIT;
517 active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
518 } while (active == WAIT_TIMEOUT);
519
520 if (active == WAIT_FAILED)
521 {
522 errno = EBADF;
523 return -1;
524 }
525 else if (active >= WAIT_OBJECT_0
526 && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
527 {
528 active -= WAIT_OBJECT_0;
529 }
530 else if (active >= WAIT_ABANDONED_0
531 && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
532 {
533 active -= WAIT_ABANDONED_0;
534 }
535 else
536 abort ();
537
538 get_result:
539 if (!GetExitCodeProcess (wait_hnd[active], &retval))
540 {
541 DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
542 GetLastError ()));
543 retval = 1;
544 }
545 if (retval == STILL_ACTIVE)
546 {
547 /* Should never happen */
548 DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
549 errno = EINVAL;
550 return -1;
551 }
552
553 /* Massage the exit code from the process to match the format expected
554 by the WIFSTOPPED et al macros in syswait.h. Only WIFSIGNALED and
555 WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT. */
556
557 if (retval == STATUS_CONTROL_C_EXIT)
558 retval = SIGINT;
559 else
560 retval <<= 8;
561
562 cp = cps[active];
563 pid = cp->pid;
564 #ifdef FULL_DEBUG
565 DebPrint (("Wait signaled with process pid %d\n", cp->pid));
566 #endif
567
568 if (status)
569 {
570 *status = retval;
571 }
572 else if (synch_process_alive)
573 {
574 synch_process_alive = 0;
575
576 /* Report the status of the synchronous process. */
577 if (WIFEXITED (retval))
578 synch_process_retcode = WRETCODE (retval);
579 else if (WIFSIGNALED (retval))
580 {
581 int code = WTERMSIG (retval);
582 char *signame;
583
584 synchronize_system_messages_locale ();
585 signame = strsignal (code);
586
587 if (signame == 0)
588 signame = "unknown";
589
590 synch_process_death = signame;
591 }
592
593 reap_subprocess (cp);
594 }
595
596 reap_subprocess (cp);
597
598 return pid;
599 }
600
601 /* Old versions of w32api headers don't have separate 32-bit and
602 64-bit defines, but the one they have matches the 32-bit variety. */
603 #ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
604 # define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
605 # define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
606 #endif
607
608 void
609 w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app, int * is_gui_app)
610 {
611 file_data executable;
612 char * p;
613
614 /* Default values in case we can't tell for sure. */
615 *is_dos_app = FALSE;
616 *is_cygnus_app = FALSE;
617 *is_gui_app = FALSE;
618
619 if (!open_input_file (&executable, filename))
620 return;
621
622 p = strrchr (filename, '.');
623
624 /* We can only identify DOS .com programs from the extension. */
625 if (p && xstrcasecmp (p, ".com") == 0)
626 *is_dos_app = TRUE;
627 else if (p && (xstrcasecmp (p, ".bat") == 0
628 || xstrcasecmp (p, ".cmd") == 0))
629 {
630 /* A DOS shell script - it appears that CreateProcess is happy to
631 accept this (somewhat surprisingly); presumably it looks at
632 COMSPEC to determine what executable to actually invoke.
633 Therefore, we have to do the same here as well. */
634 /* Actually, I think it uses the program association for that
635 extension, which is defined in the registry. */
636 p = egetenv ("COMSPEC");
637 if (p)
638 w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
639 }
640 else
641 {
642 /* Look for DOS .exe signature - if found, we must also check that
643 it isn't really a 16- or 32-bit Windows exe, since both formats
644 start with a DOS program stub. Note that 16-bit Windows
645 executables use the OS/2 1.x format. */
646
647 IMAGE_DOS_HEADER * dos_header;
648 IMAGE_NT_HEADERS * nt_header;
649
650 dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
651 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
652 goto unwind;
653
654 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
655
656 if ((char *) nt_header > (char *) dos_header + executable.size)
657 {
658 /* Some dos headers (pkunzip) have bogus e_lfanew fields. */
659 *is_dos_app = TRUE;
660 }
661 else if (nt_header->Signature != IMAGE_NT_SIGNATURE
662 && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
663 {
664 *is_dos_app = TRUE;
665 }
666 else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
667 {
668 IMAGE_DATA_DIRECTORY *data_dir = NULL;
669 if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
670 {
671 /* Ensure we are using the 32 bit structure. */
672 IMAGE_OPTIONAL_HEADER32 *opt
673 = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
674 data_dir = opt->DataDirectory;
675 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
676 }
677 /* MingW 3.12 has the required 64 bit structs, but in case older
678 versions don't, only check 64 bit exes if we know how. */
679 #ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
680 else if (nt_header->OptionalHeader.Magic
681 == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
682 {
683 IMAGE_OPTIONAL_HEADER64 *opt
684 = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
685 data_dir = opt->DataDirectory;
686 *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
687 }
688 #endif
689 if (data_dir)
690 {
691 /* Look for cygwin.dll in DLL import list. */
692 IMAGE_DATA_DIRECTORY import_dir =
693 data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
694 IMAGE_IMPORT_DESCRIPTOR * imports;
695 IMAGE_SECTION_HEADER * section;
696
697 section = rva_to_section (import_dir.VirtualAddress, nt_header);
698 imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
699 executable);
700
701 for ( ; imports->Name; imports++)
702 {
703 char * dllname = RVA_TO_PTR (imports->Name, section,
704 executable);
705
706 /* The exact name of the cygwin dll has changed with
707 various releases, but hopefully this will be reasonably
708 future proof. */
709 if (strncmp (dllname, "cygwin", 6) == 0)
710 {
711 *is_cygnus_app = TRUE;
712 break;
713 }
714 }
715 }
716 }
717 }
718
719 unwind:
720 close_file_data (&executable);
721 }
722
723 int
724 compare_env (const void *strp1, const void *strp2)
725 {
726 const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
727
728 while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
729 {
730 /* Sort order in command.com/cmd.exe is based on uppercasing
731 names, so do the same here. */
732 if (toupper (*str1) > toupper (*str2))
733 return 1;
734 else if (toupper (*str1) < toupper (*str2))
735 return -1;
736 str1++, str2++;
737 }
738
739 if (*str1 == '=' && *str2 == '=')
740 return 0;
741 else if (*str1 == '=')
742 return -1;
743 else
744 return 1;
745 }
746
747 void
748 merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
749 {
750 char **optr, **nptr;
751 int num;
752
753 nptr = new_envp;
754 optr = envp1;
755 while (*optr)
756 *nptr++ = *optr++;
757 num = optr - envp1;
758
759 optr = envp2;
760 while (*optr)
761 *nptr++ = *optr++;
762 num += optr - envp2;
763
764 qsort (new_envp, num, sizeof (char *), compare_env);
765
766 *nptr = NULL;
767 }
768
769 /* When a new child process is created we need to register it in our list,
770 so intercept spawn requests. */
771 int
772 sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
773 {
774 Lisp_Object program, full;
775 char *cmdline, *env, *parg, **targ;
776 int arglen, numenv;
777 int pid;
778 child_process *cp;
779 int is_dos_app, is_cygnus_app, is_gui_app;
780 int do_quoting = 0;
781 char escape_char;
782 /* We pass our process ID to our children by setting up an environment
783 variable in their environment. */
784 char ppid_env_var_buffer[64];
785 char *extra_env[] = {ppid_env_var_buffer, NULL};
786 /* These are the characters that cause an argument to need quoting.
787 Arguments with whitespace characters need quoting to prevent the
788 argument being split into two or more. Arguments with wildcards
789 are also quoted, for consistency with posix platforms, where wildcards
790 are not expanded if we run the program directly without a shell.
791 Some extra whitespace characters need quoting in Cygwin programs,
792 so this list is conditionally modified below. */
793 char *sepchars = " \t*?";
794
795 /* We don't care about the other modes */
796 if (mode != _P_NOWAIT)
797 {
798 errno = EINVAL;
799 return -1;
800 }
801
802 /* Handle executable names without an executable suffix. */
803 program = make_string (cmdname, strlen (cmdname));
804 if (NILP (Ffile_executable_p (program)))
805 {
806 struct gcpro gcpro1;
807
808 full = Qnil;
809 GCPRO1 (program);
810 openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
811 UNGCPRO;
812 if (NILP (full))
813 {
814 errno = EINVAL;
815 return -1;
816 }
817 program = full;
818 }
819
820 /* make sure argv[0] and cmdname are both in DOS format */
821 cmdname = SDATA (program);
822 unixtodos_filename (cmdname);
823 argv[0] = cmdname;
824
825 /* Determine whether program is a 16-bit DOS executable, or a w32
826 executable that is implicitly linked to the Cygnus dll (implying it
827 was compiled with the Cygnus GNU toolchain and hence relies on
828 cygwin.dll to parse the command line - we use this to decide how to
829 escape quote chars in command line args that must be quoted).
830
831 Also determine whether it is a GUI app, so that we don't hide its
832 initial window unless specifically requested. */
833 w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
834
835 /* On Windows 95, if cmdname is a DOS app, we invoke a helper
836 application to start it by specifying the helper app as cmdname,
837 while leaving the real app name as argv[0]. */
838 if (is_dos_app)
839 {
840 cmdname = alloca (MAXPATHLEN);
841 if (egetenv ("CMDPROXY"))
842 strcpy (cmdname, egetenv ("CMDPROXY"));
843 else
844 {
845 strcpy (cmdname, SDATA (Vinvocation_directory));
846 strcat (cmdname, "cmdproxy.exe");
847 }
848 unixtodos_filename (cmdname);
849 }
850
851 /* we have to do some conjuring here to put argv and envp into the
852 form CreateProcess wants... argv needs to be a space separated/null
853 terminated list of parameters, and envp is a null
854 separated/double-null terminated list of parameters.
855
856 Additionally, zero-length args and args containing whitespace or
857 quote chars need to be wrapped in double quotes - for this to work,
858 embedded quotes need to be escaped as well. The aim is to ensure
859 the child process reconstructs the argv array we start with
860 exactly, so we treat quotes at the beginning and end of arguments
861 as embedded quotes.
862
863 The w32 GNU-based library from Cygnus doubles quotes to escape
864 them, while MSVC uses backslash for escaping. (Actually the MSVC
865 startup code does attempt to recognise doubled quotes and accept
866 them, but gets it wrong and ends up requiring three quotes to get a
867 single embedded quote!) So by default we decide whether to use
868 quote or backslash as the escape character based on whether the
869 binary is apparently a Cygnus compiled app.
870
871 Note that using backslash to escape embedded quotes requires
872 additional special handling if an embedded quote is already
873 preceeded by backslash, or if an arg requiring quoting ends with
874 backslash. In such cases, the run of escape characters needs to be
875 doubled. For consistency, we apply this special handling as long
876 as the escape character is not quote.
877
878 Since we have no idea how large argv and envp are likely to be we
879 figure out list lengths on the fly and allocate them. */
880
881 if (!NILP (Vw32_quote_process_args))
882 {
883 do_quoting = 1;
884 /* Override escape char by binding w32-quote-process-args to
885 desired character, or use t for auto-selection. */
886 if (INTEGERP (Vw32_quote_process_args))
887 escape_char = XINT (Vw32_quote_process_args);
888 else
889 escape_char = is_cygnus_app ? '"' : '\\';
890 }
891
892 /* Cygwin apps needs quoting a bit more often */
893 if (escape_char == '"')
894 sepchars = "\r\n\t\f '";
895
896 /* do argv... */
897 arglen = 0;
898 targ = argv;
899 while (*targ)
900 {
901 char * p = *targ;
902 int need_quotes = 0;
903 int escape_char_run = 0;
904
905 if (*p == 0)
906 need_quotes = 1;
907 for ( ; *p; p++)
908 {
909 if (escape_char == '"' && *p == '\\')
910 /* If it's a Cygwin app, \ needs to be escaped. */
911 arglen++;
912 else if (*p == '"')
913 {
914 /* allow for embedded quotes to be escaped */
915 arglen++;
916 need_quotes = 1;
917 /* handle the case where the embedded quote is already escaped */
918 if (escape_char_run > 0)
919 {
920 /* To preserve the arg exactly, we need to double the
921 preceding escape characters (plus adding one to
922 escape the quote character itself). */
923 arglen += escape_char_run;
924 }
925 }
926 else if (strchr (sepchars, *p) != NULL)
927 {
928 need_quotes = 1;
929 }
930
931 if (*p == escape_char && escape_char != '"')
932 escape_char_run++;
933 else
934 escape_char_run = 0;
935 }
936 if (need_quotes)
937 {
938 arglen += 2;
939 /* handle the case where the arg ends with an escape char - we
940 must not let the enclosing quote be escaped. */
941 if (escape_char_run > 0)
942 arglen += escape_char_run;
943 }
944 arglen += strlen (*targ++) + 1;
945 }
946 cmdline = alloca (arglen);
947 targ = argv;
948 parg = cmdline;
949 while (*targ)
950 {
951 char * p = *targ;
952 int need_quotes = 0;
953
954 if (*p == 0)
955 need_quotes = 1;
956
957 if (do_quoting)
958 {
959 for ( ; *p; p++)
960 if ((strchr (sepchars, *p) != NULL) || *p == '"')
961 need_quotes = 1;
962 }
963 if (need_quotes)
964 {
965 int escape_char_run = 0;
966 char * first;
967 char * last;
968
969 p = *targ;
970 first = p;
971 last = p + strlen (p) - 1;
972 *parg++ = '"';
973 #if 0
974 /* This version does not escape quotes if they occur at the
975 beginning or end of the arg - this could lead to incorrect
976 behavior when the arg itself represents a command line
977 containing quoted args. I believe this was originally done
978 as a hack to make some things work, before
979 `w32-quote-process-args' was added. */
980 while (*p)
981 {
982 if (*p == '"' && p > first && p < last)
983 *parg++ = escape_char; /* escape embedded quotes */
984 *parg++ = *p++;
985 }
986 #else
987 for ( ; *p; p++)
988 {
989 if (*p == '"')
990 {
991 /* double preceding escape chars if any */
992 while (escape_char_run > 0)
993 {
994 *parg++ = escape_char;
995 escape_char_run--;
996 }
997 /* escape all quote chars, even at beginning or end */
998 *parg++ = escape_char;
999 }
1000 else if (escape_char == '"' && *p == '\\')
1001 *parg++ = '\\';
1002 *parg++ = *p;
1003
1004 if (*p == escape_char && escape_char != '"')
1005 escape_char_run++;
1006 else
1007 escape_char_run = 0;
1008 }
1009 /* double escape chars before enclosing quote */
1010 while (escape_char_run > 0)
1011 {
1012 *parg++ = escape_char;
1013 escape_char_run--;
1014 }
1015 #endif
1016 *parg++ = '"';
1017 }
1018 else
1019 {
1020 strcpy (parg, *targ);
1021 parg += strlen (*targ);
1022 }
1023 *parg++ = ' ';
1024 targ++;
1025 }
1026 *--parg = '\0';
1027
1028 /* and envp... */
1029 arglen = 1;
1030 targ = envp;
1031 numenv = 1; /* for end null */
1032 while (*targ)
1033 {
1034 arglen += strlen (*targ++) + 1;
1035 numenv++;
1036 }
1037 /* extra env vars... */
1038 sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
1039 GetCurrentProcessId ());
1040 arglen += strlen (ppid_env_var_buffer) + 1;
1041 numenv++;
1042
1043 /* merge env passed in and extra env into one, and sort it. */
1044 targ = (char **) alloca (numenv * sizeof (char *));
1045 merge_and_sort_env (envp, extra_env, targ);
1046
1047 /* concatenate env entries. */
1048 env = alloca (arglen);
1049 parg = env;
1050 while (*targ)
1051 {
1052 strcpy (parg, *targ);
1053 parg += strlen (*targ++);
1054 *parg++ = '\0';
1055 }
1056 *parg++ = '\0';
1057 *parg = '\0';
1058
1059 cp = new_child ();
1060 if (cp == NULL)
1061 {
1062 errno = EAGAIN;
1063 return -1;
1064 }
1065
1066 /* Now create the process. */
1067 if (!create_child (cmdname, cmdline, env, is_gui_app, &pid, cp))
1068 {
1069 delete_child (cp);
1070 errno = ENOEXEC;
1071 return -1;
1072 }
1073
1074 return pid;
1075 }
1076
1077 /* Emulate the select call
1078 Wait for available input on any of the given rfds, or timeout if
1079 a timeout is given and no input is detected
1080 wfds and efds are not supported and must be NULL.
1081
1082 For simplicity, we detect the death of child processes here and
1083 synchronously call the SIGCHLD handler. Since it is possible for
1084 children to be created without a corresponding pipe handle from which
1085 to read output, we wait separately on the process handles as well as
1086 the char_avail events for each process pipe. We only call
1087 wait/reap_process when the process actually terminates.
1088
1089 To reduce the number of places in which Emacs can be hung such that
1090 C-g is not able to interrupt it, we always wait on interrupt_handle
1091 (which is signaled by the input thread when C-g is detected). If we
1092 detect that we were woken up by C-g, we return -1 with errno set to
1093 EINTR as on Unix. */
1094
1095 /* From ntterm.c */
1096 extern HANDLE keyboard_handle;
1097
1098 /* From w32xfns.c */
1099 extern HANDLE interrupt_handle;
1100
1101 /* From process.c */
1102 extern int proc_buffered_char[];
1103
1104 int
1105 sys_select (int nfds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
1106 EMACS_TIME *timeout)
1107 {
1108 SELECT_TYPE orfds;
1109 DWORD timeout_ms, start_time;
1110 int i, nh, nc, nr;
1111 DWORD active;
1112 child_process *cp, *cps[MAX_CHILDREN];
1113 HANDLE wait_hnd[MAXDESC + MAX_CHILDREN];
1114 int fdindex[MAXDESC]; /* mapping from wait handles back to descriptors */
1115
1116 timeout_ms = timeout ? (timeout->tv_sec * 1000 + timeout->tv_usec / 1000) : 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]) 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 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_WIN95)
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_WIN95)
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 Win95, 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 /* extern int report_file_error (char *, Lisp_Object); */
1602
1603 /* The following two routines are used to manipulate stdin, stdout, and
1604 stderr of our child processes.
1605
1606 Assuming that in, out, and err are *not* inheritable, we make them
1607 stdin, stdout, and stderr of the child as follows:
1608
1609 - Save the parent's current standard handles.
1610 - Set the std handles to inheritable duplicates of the ones being passed in.
1611 (Note that _get_osfhandle() is an io.h procedure that retrieves the
1612 NT file handle for a crt file descriptor.)
1613 - Spawn the child, which inherits in, out, and err as stdin,
1614 stdout, and stderr. (see Spawnve)
1615 - Close the std handles passed to the child.
1616 - Reset the parent's standard handles to the saved handles.
1617 (see reset_standard_handles)
1618 We assume that the caller closes in, out, and err after calling us. */
1619
1620 void
1621 prepare_standard_handles (int in, int out, int err, HANDLE handles[3])
1622 {
1623 HANDLE parent;
1624 HANDLE newstdin, newstdout, newstderr;
1625
1626 parent = GetCurrentProcess ();
1627
1628 handles[0] = GetStdHandle (STD_INPUT_HANDLE);
1629 handles[1] = GetStdHandle (STD_OUTPUT_HANDLE);
1630 handles[2] = GetStdHandle (STD_ERROR_HANDLE);
1631
1632 /* make inheritable copies of the new handles */
1633 if (!DuplicateHandle (parent,
1634 (HANDLE) _get_osfhandle (in),
1635 parent,
1636 &newstdin,
1637 0,
1638 TRUE,
1639 DUPLICATE_SAME_ACCESS))
1640 report_file_error ("Duplicating input handle for child", Qnil);
1641
1642 if (!DuplicateHandle (parent,
1643 (HANDLE) _get_osfhandle (out),
1644 parent,
1645 &newstdout,
1646 0,
1647 TRUE,
1648 DUPLICATE_SAME_ACCESS))
1649 report_file_error ("Duplicating output handle for child", Qnil);
1650
1651 if (!DuplicateHandle (parent,
1652 (HANDLE) _get_osfhandle (err),
1653 parent,
1654 &newstderr,
1655 0,
1656 TRUE,
1657 DUPLICATE_SAME_ACCESS))
1658 report_file_error ("Duplicating error handle for child", Qnil);
1659
1660 /* and store them as our std handles */
1661 if (!SetStdHandle (STD_INPUT_HANDLE, newstdin))
1662 report_file_error ("Changing stdin handle", Qnil);
1663
1664 if (!SetStdHandle (STD_OUTPUT_HANDLE, newstdout))
1665 report_file_error ("Changing stdout handle", Qnil);
1666
1667 if (!SetStdHandle (STD_ERROR_HANDLE, newstderr))
1668 report_file_error ("Changing stderr handle", Qnil);
1669 }
1670
1671 void
1672 reset_standard_handles (int in, int out, int err, HANDLE handles[3])
1673 {
1674 /* close the duplicated handles passed to the child */
1675 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
1676 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
1677 CloseHandle (GetStdHandle (STD_ERROR_HANDLE));
1678
1679 /* now restore parent's saved std handles */
1680 SetStdHandle (STD_INPUT_HANDLE, handles[0]);
1681 SetStdHandle (STD_OUTPUT_HANDLE, handles[1]);
1682 SetStdHandle (STD_ERROR_HANDLE, handles[2]);
1683 }
1684
1685 void
1686 set_process_dir (char * dir)
1687 {
1688 process_dir = dir;
1689 }
1690
1691 #ifdef HAVE_SOCKETS
1692
1693 /* To avoid problems with winsock implementations that work over dial-up
1694 connections causing or requiring a connection to exist while Emacs is
1695 running, Emacs no longer automatically loads winsock on startup if it
1696 is present. Instead, it will be loaded when open-network-stream is
1697 first called.
1698
1699 To allow full control over when winsock is loaded, we provide these
1700 two functions to dynamically load and unload winsock. This allows
1701 dial-up users to only be connected when they actually need to use
1702 socket services. */
1703
1704 /* From nt.c */
1705 extern HANDLE winsock_lib;
1706 extern BOOL term_winsock (void);
1707 extern BOOL init_winsock (int load_now);
1708
1709 extern Lisp_Object Vsystem_name;
1710
1711 DEFUN ("w32-has-winsock", Fw32_has_winsock, Sw32_has_winsock, 0, 1, 0,
1712 doc: /* Test for presence of the Windows socket library `winsock'.
1713 Returns non-nil if winsock support is present, nil otherwise.
1714
1715 If the optional argument LOAD-NOW is non-nil, the winsock library is
1716 also loaded immediately if not already loaded. If winsock is loaded,
1717 the winsock local hostname is returned (since this may be different from
1718 the value of `system-name' and should supplant it), otherwise t is
1719 returned to indicate winsock support is present. */)
1720 (load_now)
1721 Lisp_Object load_now;
1722 {
1723 int have_winsock;
1724
1725 have_winsock = init_winsock (!NILP (load_now));
1726 if (have_winsock)
1727 {
1728 if (winsock_lib != NULL)
1729 {
1730 /* Return new value for system-name. The best way to do this
1731 is to call init_system_name, saving and restoring the
1732 original value to avoid side-effects. */
1733 Lisp_Object orig_hostname = Vsystem_name;
1734 Lisp_Object hostname;
1735
1736 init_system_name ();
1737 hostname = Vsystem_name;
1738 Vsystem_name = orig_hostname;
1739 return hostname;
1740 }
1741 return Qt;
1742 }
1743 return Qnil;
1744 }
1745
1746 DEFUN ("w32-unload-winsock", Fw32_unload_winsock, Sw32_unload_winsock,
1747 0, 0, 0,
1748 doc: /* Unload the Windows socket library `winsock' if loaded.
1749 This is provided to allow dial-up socket connections to be disconnected
1750 when no longer needed. Returns nil without unloading winsock if any
1751 socket connections still exist. */)
1752 ()
1753 {
1754 return term_winsock () ? Qt : Qnil;
1755 }
1756
1757 #endif /* HAVE_SOCKETS */
1758
1759 \f
1760 /* Some miscellaneous functions that are Windows specific, but not GUI
1761 specific (ie. are applicable in terminal or batch mode as well). */
1762
1763 /* lifted from fileio.c */
1764 #define CORRECT_DIR_SEPS(s) \
1765 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
1766 else unixtodos_filename (s); \
1767 } while (0)
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 (filename), shortname, MAX_PATH) == 0)
1785 return Qnil;
1786
1787 CORRECT_DIR_SEPS (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 (filename), longname, MAX_PATH))
1814 return Qnil;
1815
1816 CORRECT_DIR_SEPS (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 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 *nl_langinfo (nl_item item)
1883 {
1884 /* Conversion of Posix item numbers to their Windows equivalents. */
1885 static const LCTYPE w32item[] = {
1886 LOCALE_IDEFAULTANSICODEPAGE,
1887 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
1888 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
1889 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
1890 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
1891 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
1892 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12
1893 };
1894
1895 static char *nl_langinfo_buf = NULL;
1896 static int nl_langinfo_len = 0;
1897
1898 if (nl_langinfo_len <= 0)
1899 nl_langinfo_buf = xmalloc (nl_langinfo_len = 1);
1900
1901 if (item < 0 || item >= _NL_NUM)
1902 nl_langinfo_buf[0] = 0;
1903 else
1904 {
1905 LCID cloc = GetThreadLocale ();
1906 int need_len = GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1907 NULL, 0);
1908
1909 if (need_len <= 0)
1910 nl_langinfo_buf[0] = 0;
1911 else
1912 {
1913 if (item == CODESET)
1914 {
1915 need_len += 2; /* for the "cp" prefix */
1916 if (need_len < 8) /* for the case we call GetACP */
1917 need_len = 8;
1918 }
1919 if (nl_langinfo_len <= need_len)
1920 nl_langinfo_buf = xrealloc (nl_langinfo_buf,
1921 nl_langinfo_len = need_len);
1922 if (!GetLocaleInfo (cloc, w32item[item] | LOCALE_USE_CP_ACP,
1923 nl_langinfo_buf, nl_langinfo_len))
1924 nl_langinfo_buf[0] = 0;
1925 else if (item == CODESET)
1926 {
1927 if (strcmp (nl_langinfo_buf, "0") == 0 /* CP_ACP */
1928 || strcmp (nl_langinfo_buf, "1") == 0) /* CP_OEMCP */
1929 sprintf (nl_langinfo_buf, "cp%u", GetACP ());
1930 else
1931 {
1932 memmove (nl_langinfo_buf + 2, nl_langinfo_buf,
1933 strlen (nl_langinfo_buf) + 1);
1934 nl_langinfo_buf[0] = 'c';
1935 nl_langinfo_buf[1] = 'p';
1936 }
1937 }
1938 }
1939 }
1940 return nl_langinfo_buf;
1941 }
1942 #endif /* HAVE_LANGINFO_CODESET */
1943
1944 DEFUN ("w32-get-locale-info", Fw32_get_locale_info,
1945 Sw32_get_locale_info, 1, 2, 0,
1946 doc: /* Return information about the Windows locale LCID.
1947 By default, return a three letter locale code which encodes the default
1948 language as the first two characters, and the country or regionial variant
1949 as the third letter. For example, ENU refers to `English (United States)',
1950 while ENC means `English (Canadian)'.
1951
1952 If the optional argument LONGFORM is t, the long form of the locale
1953 name is returned, e.g. `English (United States)' instead; if LONGFORM
1954 is a number, it is interpreted as an LCTYPE constant and the corresponding
1955 locale information is returned.
1956
1957 If LCID (a 16-bit number) is not a valid locale, the result is nil. */)
1958 (lcid, longform)
1959 Lisp_Object lcid, longform;
1960 {
1961 int got_abbrev;
1962 int got_full;
1963 char abbrev_name[32] = { 0 };
1964 char full_name[256] = { 0 };
1965
1966 CHECK_NUMBER (lcid);
1967
1968 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
1969 return Qnil;
1970
1971 if (NILP (longform))
1972 {
1973 got_abbrev = GetLocaleInfo (XINT (lcid),
1974 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1975 abbrev_name, sizeof (abbrev_name));
1976 if (got_abbrev)
1977 return build_string (abbrev_name);
1978 }
1979 else if (EQ (longform, Qt))
1980 {
1981 got_full = GetLocaleInfo (XINT (lcid),
1982 LOCALE_SLANGUAGE | LOCALE_USE_CP_ACP,
1983 full_name, sizeof (full_name));
1984 if (got_full)
1985 return build_string (full_name);
1986 }
1987 else if (NUMBERP (longform))
1988 {
1989 got_full = GetLocaleInfo (XINT (lcid),
1990 XINT (longform),
1991 full_name, sizeof (full_name));
1992 if (got_full)
1993 return make_unibyte_string (full_name, got_full);
1994 }
1995
1996 return Qnil;
1997 }
1998
1999
2000 DEFUN ("w32-get-current-locale-id", Fw32_get_current_locale_id,
2001 Sw32_get_current_locale_id, 0, 0, 0,
2002 doc: /* Return Windows locale id for current locale setting.
2003 This is a numerical value; use `w32-get-locale-info' to convert to a
2004 human-readable form. */)
2005 ()
2006 {
2007 return make_number (GetThreadLocale ());
2008 }
2009
2010 DWORD int_from_hex (char * s)
2011 {
2012 DWORD val = 0;
2013 static char hex[] = "0123456789abcdefABCDEF";
2014 char * p;
2015
2016 while (*s && (p = strchr(hex, *s)) != NULL)
2017 {
2018 unsigned digit = p - hex;
2019 if (digit > 15)
2020 digit -= 6;
2021 val = val * 16 + digit;
2022 s++;
2023 }
2024 return val;
2025 }
2026
2027 /* We need to build a global list, since the EnumSystemLocale callback
2028 function isn't given a context pointer. */
2029 Lisp_Object Vw32_valid_locale_ids;
2030
2031 BOOL CALLBACK enum_locale_fn (LPTSTR localeNum)
2032 {
2033 DWORD id = int_from_hex (localeNum);
2034 Vw32_valid_locale_ids = Fcons (make_number (id), Vw32_valid_locale_ids);
2035 return TRUE;
2036 }
2037
2038 DEFUN ("w32-get-valid-locale-ids", Fw32_get_valid_locale_ids,
2039 Sw32_get_valid_locale_ids, 0, 0, 0,
2040 doc: /* Return list of all valid Windows locale ids.
2041 Each id is a numerical value; use `w32-get-locale-info' to convert to a
2042 human-readable form. */)
2043 ()
2044 {
2045 Vw32_valid_locale_ids = Qnil;
2046
2047 EnumSystemLocales (enum_locale_fn, LCID_SUPPORTED);
2048
2049 Vw32_valid_locale_ids = Fnreverse (Vw32_valid_locale_ids);
2050 return Vw32_valid_locale_ids;
2051 }
2052
2053
2054 DEFUN ("w32-get-default-locale-id", Fw32_get_default_locale_id, Sw32_get_default_locale_id, 0, 1, 0,
2055 doc: /* Return Windows locale id for default locale setting.
2056 By default, the system default locale setting is returned; if the optional
2057 parameter USERP is non-nil, the user default locale setting is returned.
2058 This is a numerical value; use `w32-get-locale-info' to convert to a
2059 human-readable form. */)
2060 (userp)
2061 Lisp_Object userp;
2062 {
2063 if (NILP (userp))
2064 return make_number (GetSystemDefaultLCID ());
2065 return make_number (GetUserDefaultLCID ());
2066 }
2067
2068
2069 DEFUN ("w32-set-current-locale", Fw32_set_current_locale, Sw32_set_current_locale, 1, 1, 0,
2070 doc: /* Make Windows locale LCID be the current locale setting for Emacs.
2071 If successful, the new locale id is returned, otherwise nil. */)
2072 (lcid)
2073 Lisp_Object lcid;
2074 {
2075 CHECK_NUMBER (lcid);
2076
2077 if (!IsValidLocale (XINT (lcid), LCID_SUPPORTED))
2078 return Qnil;
2079
2080 if (!SetThreadLocale (XINT (lcid)))
2081 return Qnil;
2082
2083 /* Need to set input thread locale if present. */
2084 if (dwWindowsThreadId)
2085 /* Reply is not needed. */
2086 PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETLOCALE, XINT (lcid), 0);
2087
2088 return make_number (GetThreadLocale ());
2089 }
2090
2091
2092 /* We need to build a global list, since the EnumCodePages callback
2093 function isn't given a context pointer. */
2094 Lisp_Object Vw32_valid_codepages;
2095
2096 BOOL CALLBACK enum_codepage_fn (LPTSTR codepageNum)
2097 {
2098 DWORD id = atoi (codepageNum);
2099 Vw32_valid_codepages = Fcons (make_number (id), Vw32_valid_codepages);
2100 return TRUE;
2101 }
2102
2103 DEFUN ("w32-get-valid-codepages", Fw32_get_valid_codepages,
2104 Sw32_get_valid_codepages, 0, 0, 0,
2105 doc: /* Return list of all valid Windows codepages. */)
2106 ()
2107 {
2108 Vw32_valid_codepages = Qnil;
2109
2110 EnumSystemCodePages (enum_codepage_fn, CP_SUPPORTED);
2111
2112 Vw32_valid_codepages = Fnreverse (Vw32_valid_codepages);
2113 return Vw32_valid_codepages;
2114 }
2115
2116
2117 DEFUN ("w32-get-console-codepage", Fw32_get_console_codepage,
2118 Sw32_get_console_codepage, 0, 0, 0,
2119 doc: /* Return current Windows codepage for console input. */)
2120 ()
2121 {
2122 return make_number (GetConsoleCP ());
2123 }
2124
2125
2126 DEFUN ("w32-set-console-codepage", Fw32_set_console_codepage,
2127 Sw32_set_console_codepage, 1, 1, 0,
2128 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2129 The codepage setting affects keyboard input and display in tty mode.
2130 If successful, the new CP is returned, otherwise nil. */)
2131 (cp)
2132 Lisp_Object cp;
2133 {
2134 CHECK_NUMBER (cp);
2135
2136 if (!IsValidCodePage (XINT (cp)))
2137 return Qnil;
2138
2139 if (!SetConsoleCP (XINT (cp)))
2140 return Qnil;
2141
2142 return make_number (GetConsoleCP ());
2143 }
2144
2145
2146 DEFUN ("w32-get-console-output-codepage", Fw32_get_console_output_codepage,
2147 Sw32_get_console_output_codepage, 0, 0, 0,
2148 doc: /* Return current Windows codepage for console output. */)
2149 ()
2150 {
2151 return make_number (GetConsoleOutputCP ());
2152 }
2153
2154
2155 DEFUN ("w32-set-console-output-codepage", Fw32_set_console_output_codepage,
2156 Sw32_set_console_output_codepage, 1, 1, 0,
2157 doc: /* Make Windows codepage CP be the current codepage setting for Emacs.
2158 The codepage setting affects keyboard input and display in tty mode.
2159 If successful, the new CP is returned, otherwise nil. */)
2160 (cp)
2161 Lisp_Object cp;
2162 {
2163 CHECK_NUMBER (cp);
2164
2165 if (!IsValidCodePage (XINT (cp)))
2166 return Qnil;
2167
2168 if (!SetConsoleOutputCP (XINT (cp)))
2169 return Qnil;
2170
2171 return make_number (GetConsoleOutputCP ());
2172 }
2173
2174
2175 DEFUN ("w32-get-codepage-charset", Fw32_get_codepage_charset,
2176 Sw32_get_codepage_charset, 1, 1, 0,
2177 doc: /* Return charset of codepage CP.
2178 Returns nil if the codepage is not valid. */)
2179 (cp)
2180 Lisp_Object cp;
2181 {
2182 CHARSETINFO info;
2183
2184 CHECK_NUMBER (cp);
2185
2186 if (!IsValidCodePage (XINT (cp)))
2187 return Qnil;
2188
2189 if (TranslateCharsetInfo ((DWORD *) XINT (cp), &info, TCI_SRCCODEPAGE))
2190 return make_number (info.ciCharset);
2191
2192 return Qnil;
2193 }
2194
2195
2196 DEFUN ("w32-get-valid-keyboard-layouts", Fw32_get_valid_keyboard_layouts,
2197 Sw32_get_valid_keyboard_layouts, 0, 0, 0,
2198 doc: /* Return list of Windows keyboard languages and layouts.
2199 The return value is a list of pairs of language id and layout id. */)
2200 ()
2201 {
2202 int num_layouts = GetKeyboardLayoutList (0, NULL);
2203 HKL * layouts = (HKL *) alloca (num_layouts * sizeof (HKL));
2204 Lisp_Object obj = Qnil;
2205
2206 if (GetKeyboardLayoutList (num_layouts, layouts) == num_layouts)
2207 {
2208 while (--num_layouts >= 0)
2209 {
2210 DWORD kl = (DWORD) layouts[num_layouts];
2211
2212 obj = Fcons (Fcons (make_number (kl & 0xffff),
2213 make_number ((kl >> 16) & 0xffff)),
2214 obj);
2215 }
2216 }
2217
2218 return obj;
2219 }
2220
2221
2222 DEFUN ("w32-get-keyboard-layout", Fw32_get_keyboard_layout,
2223 Sw32_get_keyboard_layout, 0, 0, 0,
2224 doc: /* Return current Windows keyboard language and layout.
2225 The return value is the cons of the language id and the layout id. */)
2226 ()
2227 {
2228 DWORD kl = (DWORD) GetKeyboardLayout (dwWindowsThreadId);
2229
2230 return Fcons (make_number (kl & 0xffff),
2231 make_number ((kl >> 16) & 0xffff));
2232 }
2233
2234
2235 DEFUN ("w32-set-keyboard-layout", Fw32_set_keyboard_layout,
2236 Sw32_set_keyboard_layout, 1, 1, 0,
2237 doc: /* Make LAYOUT be the current keyboard layout for Emacs.
2238 The keyboard layout setting affects interpretation of keyboard input.
2239 If successful, the new layout id is returned, otherwise nil. */)
2240 (layout)
2241 Lisp_Object layout;
2242 {
2243 DWORD kl;
2244
2245 CHECK_CONS (layout);
2246 CHECK_NUMBER_CAR (layout);
2247 CHECK_NUMBER_CDR (layout);
2248
2249 kl = (XINT (XCAR (layout)) & 0xffff)
2250 | (XINT (XCDR (layout)) << 16);
2251
2252 /* Synchronize layout with input thread. */
2253 if (dwWindowsThreadId)
2254 {
2255 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_SETKEYBOARDLAYOUT,
2256 (WPARAM) kl, 0))
2257 {
2258 MSG msg;
2259 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
2260
2261 if (msg.wParam == 0)
2262 return Qnil;
2263 }
2264 }
2265 else if (!ActivateKeyboardLayout ((HKL) kl, 0))
2266 return Qnil;
2267
2268 return Fw32_get_keyboard_layout ();
2269 }
2270
2271 \f
2272 syms_of_ntproc ()
2273 {
2274 DEFSYM (Qhigh, "high");
2275 DEFSYM (Qlow, "low");
2276
2277 #ifdef HAVE_SOCKETS
2278 defsubr (&Sw32_has_winsock);
2279 defsubr (&Sw32_unload_winsock);
2280 #endif
2281 defsubr (&Sw32_short_file_name);
2282 defsubr (&Sw32_long_file_name);
2283 defsubr (&Sw32_set_process_priority);
2284 defsubr (&Sw32_get_locale_info);
2285 defsubr (&Sw32_get_current_locale_id);
2286 defsubr (&Sw32_get_default_locale_id);
2287 defsubr (&Sw32_get_valid_locale_ids);
2288 defsubr (&Sw32_set_current_locale);
2289
2290 defsubr (&Sw32_get_console_codepage);
2291 defsubr (&Sw32_set_console_codepage);
2292 defsubr (&Sw32_get_console_output_codepage);
2293 defsubr (&Sw32_set_console_output_codepage);
2294 defsubr (&Sw32_get_valid_codepages);
2295 defsubr (&Sw32_get_codepage_charset);
2296
2297 defsubr (&Sw32_get_valid_keyboard_layouts);
2298 defsubr (&Sw32_get_keyboard_layout);
2299 defsubr (&Sw32_set_keyboard_layout);
2300
2301 DEFVAR_LISP ("w32-quote-process-args", &Vw32_quote_process_args,
2302 doc: /* Non-nil enables quoting of process arguments to ensure correct parsing.
2303 Because Windows does not directly pass argv arrays to child processes,
2304 programs have to reconstruct the argv array by parsing the command
2305 line string. For an argument to contain a space, it must be enclosed
2306 in double quotes or it will be parsed as multiple arguments.
2307
2308 If the value is a character, that character will be used to escape any
2309 quote characters that appear, otherwise a suitable escape character
2310 will be chosen based on the type of the program. */);
2311 Vw32_quote_process_args = Qt;
2312
2313 DEFVAR_LISP ("w32-start-process-show-window",
2314 &Vw32_start_process_show_window,
2315 doc: /* When nil, new child processes hide their windows.
2316 When non-nil, they show their window in the method of their choice.
2317 This variable doesn't affect GUI applications, which will never be hidden. */);
2318 Vw32_start_process_show_window = Qnil;
2319
2320 DEFVAR_LISP ("w32-start-process-share-console",
2321 &Vw32_start_process_share_console,
2322 doc: /* When nil, new child processes are given a new console.
2323 When non-nil, they share the Emacs console; this has the limitation of
2324 allowing only one DOS subprocess to run at a time (whether started directly
2325 or indirectly by Emacs), and preventing Emacs from cleanly terminating the
2326 subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
2327 otherwise respond to interrupts from Emacs. */);
2328 Vw32_start_process_share_console = Qnil;
2329
2330 DEFVAR_LISP ("w32-start-process-inherit-error-mode",
2331 &Vw32_start_process_inherit_error_mode,
2332 doc: /* When nil, new child processes revert to the default error mode.
2333 When non-nil, they inherit their error mode setting from Emacs, which stops
2334 them blocking when trying to access unmounted drives etc. */);
2335 Vw32_start_process_inherit_error_mode = Qt;
2336
2337 DEFVAR_INT ("w32-pipe-read-delay", &w32_pipe_read_delay,
2338 doc: /* Forced delay before reading subprocess output.
2339 This is done to improve the buffering of subprocess output, by
2340 avoiding the inefficiency of frequently reading small amounts of data.
2341
2342 If positive, the value is the number of milliseconds to sleep before
2343 reading the subprocess output. If negative, the magnitude is the number
2344 of time slices to wait (effectively boosting the priority of the child
2345 process temporarily). A value of zero disables waiting entirely. */);
2346 w32_pipe_read_delay = 50;
2347
2348 DEFVAR_LISP ("w32-downcase-file-names", &Vw32_downcase_file_names,
2349 doc: /* Non-nil means convert all-upper case file names to lower case.
2350 This applies when performing completions and file name expansion.
2351 Note that the value of this setting also affects remote file names,
2352 so you probably don't want to set to non-nil if you use case-sensitive
2353 filesystems via ange-ftp. */);
2354 Vw32_downcase_file_names = Qnil;
2355
2356 #if 0
2357 DEFVAR_LISP ("w32-generate-fake-inodes", &Vw32_generate_fake_inodes,
2358 doc: /* Non-nil means attempt to fake realistic inode values.
2359 This works by hashing the truename of files, and should detect
2360 aliasing between long and short (8.3 DOS) names, but can have
2361 false positives because of hash collisions. Note that determing
2362 the truename of a file can be slow. */);
2363 Vw32_generate_fake_inodes = Qnil;
2364 #endif
2365
2366 DEFVAR_LISP ("w32-get-true-file-attributes", &Vw32_get_true_file_attributes,
2367 doc: /* Non-nil means determine accurate file attributes in `file-attributes'.
2368 This option controls whether to issue additional system calls to determine
2369 accurate link counts, file type, and ownership information. It is only
2370 useful for files on NTFS volumes, where hard links and file security are
2371 supported.
2372
2373 Without these system calls, link count will always be reported as 1 and file
2374 ownership will be attributed to the current user.
2375 The default value `local' means only issue these system calls for files
2376 on local fixed drives. A value of nil means never issue them.
2377 Any other non-nil value means do this even on remote and removable drives
2378 where the performance impact may be noticeable even on modern hardware. */);
2379 Vw32_get_true_file_attributes = Qlocal;
2380
2381 staticpro (&Vw32_valid_locale_ids);
2382 staticpro (&Vw32_valid_codepages);
2383 }
2384 /* end of ntproc.c */
2385
2386 /* arch-tag: 23d3a34c-06d2-48a1-833b-ac7609aa5250
2387 (do not change this comment) */