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