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