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