1 /* Asynchronous subprocess implemenation for Win32
2 Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
3 Free Software Foundation, Inc.
4 Copyright (C) 1995 Sun Microsystems, Inc.
5 Copyright (C) 1995, 1996 Ben Wing.
7 This file is part of XEmacs.
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING. If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA. */
24 /* Written by Kirill M. Katsnelson <kkm@kis.ru>, April 1998 */
42 /* Bound by winnt.el */
43 Lisp_Object Qnt_quote_process_args;
45 /* Implemenation-specific data. Pointed to by Lisp_Process->process_data */
46 struct nt_process_data
51 #define NT_DATA(p) ((struct nt_process_data*)((p)->process_data))
53 /*-----------------------------------------------------------------------*/
55 /*-----------------------------------------------------------------------*/
57 /* This one breaks process abstraction. Prototype is in console-msw.h,
58 used by select_process method in event-msw.c */
60 get_nt_process_handle (struct Lisp_Process *p)
62 return (NT_DATA (p)->h_process);
65 /*-----------------------------------------------------------------------*/
66 /* Running remote threads. See Microsoft Systems Journal 1994 Number 5 */
67 /* Jeffrey Richter, Load Your 32-bit DLL into Another Process's Address..*/
68 /*-----------------------------------------------------------------------*/
78 * Allocate SIZE bytes in H_PROCESS address space. Fill in PMC used
79 * further by other routines. Return nonzero if successful.
81 * The memory in other process is allocated by creating a suspended
82 * thread. Initial stack of that thread is used as the memory
83 * block. The thread entry point is the routine ExitThread in
84 * kernel32.dll, so the allocated memory is freed just by resuming the
85 * thread, which immediately terminates after that.
89 alloc_process_memory (HANDLE h_process, size_t size,
92 LPTHREAD_START_ROUTINE adr_ExitThread =
93 (LPTHREAD_START_ROUTINE)
94 GetProcAddress (GetModuleHandle ("kernel32"), "ExitThread");
97 MEMORY_BASIC_INFORMATION mbi;
99 pmc->h_process = h_process;
100 pmc->h_thread = CreateRemoteThread (h_process, NULL, size,
101 adr_ExitThread, NULL,
102 CREATE_SUSPENDED, &dw_unused);
103 if (pmc->h_thread == NULL)
106 /* Get context, for thread's stack pointer */
107 context.ContextFlags = CONTEXT_CONTROL;
108 if (!GetThreadContext (pmc->h_thread, &context))
111 /* Determine base address of the committed range */
112 if (sizeof(mbi) != VirtualQueryEx (h_process,
114 (LPDWORD)context.Esp - 1,
115 #elif defined (_ALPHA_)
116 (LPDWORD)context.IntSp - 1,
118 #error Unknown processor architecture
123 /* Change the page protection of the allocated memory to executable,
125 if (!VirtualProtectEx (h_process, mbi.BaseAddress, size,
126 PAGE_EXECUTE_READWRITE, &dw_unused))
129 pmc->address = mbi.BaseAddress;
133 ResumeThread (pmc->h_thread);
139 free_process_memory (process_memory* pmc)
141 ResumeThread (pmc->h_thread);
145 * Run ROUTINE in the context of process determined by H_PROCESS. The
146 * routine is passed the address of DATA as parameter. CODE_END is the
147 * address immediately after ROUTINE's code. DATA_SIZE is the size of
150 * Note that the code must be positionally independent, and compiled
151 * without stack checks (they cause implicit calls into CRT so will
152 * fail). DATA should not refer any data in calling process, as both
153 * routine and its data are copied into remote process. Size of data
154 * and code together should not exceed one page (4K on x86 systems).
156 * Return the value returned by ROUTINE, or (DWORD)-1 if call failed.
159 run_in_other_process (HANDLE h_process,
160 LPTHREAD_START_ROUTINE routine, LPVOID code_end,
161 LPVOID data, size_t data_size)
164 size_t code_size = (LPBYTE)code_end - (LPBYTE)routine;
165 /* Need at most 3 extra bytes of memory, for data alignment */
166 size_t total_size = code_size + data_size + 3;
171 /* Allocate memory */
172 if (!alloc_process_memory (h_process, total_size, &pm))
176 if (!WriteProcessMemory (h_process, pm.address, (LPVOID)routine,
183 remote_data = (LPBYTE)pm.address + ((code_size + 4) & ~3);
184 if (!WriteProcessMemory (h_process, remote_data, data, data_size, NULL))
190 /* Execute the remote copy of code, passing it remote data */
191 h_thread = CreateRemoteThread (h_process, NULL, 0,
192 (LPTHREAD_START_ROUTINE) pm.address,
193 remote_data, 0, &dw_unused);
194 if (h_thread == NULL)
197 /* Wait till thread finishes */
198 WaitForSingleObject (h_thread, INFINITE);
200 /* Free remote memory */
201 free_process_memory (&pm);
203 /* Return thread's exit code */
206 GetExitCodeThread (h_thread, &exit_code);
207 CloseHandle (h_thread);
212 free_process_memory (&pm);
216 /*-----------------------------------------------------------------------*/
217 /* Sending signals */
218 /*-----------------------------------------------------------------------*/
221 * We handle the following signals:
223 * SIGKILL, SIGTERM, SIGQUIT, SIGHUP - These four translate to ExitProcess
224 * executed by the remote process
225 * SIGINT - The remote process is sent CTRL_BREAK_EVENT
233 void (WINAPI *adr_ExitProcess) (UINT);
237 sigkill_proc (sigkill_data* data)
239 (*data->adr_ExitProcess)(255);
243 /* Watermark in code space */
245 sigkill_code_end (void)
250 * Sending break or control c
254 BOOL (WINAPI *adr_GenerateConsoleCtrlEvent) (DWORD, DWORD);
259 sigint_proc (sigint_data* data)
261 return (*data->adr_GenerateConsoleCtrlEvent) (data->event, 0);
264 /* Watermark in code space */
266 sigint_code_end (void)
275 BOOL (WINAPI *adr_SetConsoleCtrlHandler) (LPVOID, BOOL);
279 sig_enable_proc (sig_enable_data* data)
281 (*data->adr_SetConsoleCtrlHandler) (NULL, FALSE);
285 /* Watermark in code space */
287 sig_enable_code_end (void)
292 * Send signal SIGNO to process H_PROCESS.
293 * Return nonzero if successful.
296 /* This code assigns a return value of GetProcAddress to function pointers
297 of many different types. Instead of heavy obscure casts, we just disable
298 warnings about assignments to different function pointer types. */
299 #pragma warning (disable : 4113)
302 send_signal (HANDLE h_process, int signo)
304 HMODULE h_kernel = GetModuleHandle ("kernel32");
307 assert (h_kernel != NULL);
317 d.adr_ExitProcess = GetProcAddress (h_kernel, "ExitProcess");
318 assert (d.adr_ExitProcess);
319 retval = run_in_other_process (h_process,
320 sigkill_proc, sigkill_code_end,
327 d.adr_GenerateConsoleCtrlEvent =
328 GetProcAddress (h_kernel, "GenerateConsoleCtrlEvent");
329 assert (d.adr_GenerateConsoleCtrlEvent);
330 d.event = CTRL_C_EVENT;
331 retval = run_in_other_process (h_process,
332 sigint_proc, sigint_code_end,
340 return (int)retval > 0 ? 1 : 0;
344 * Enable CTRL_C_EVENT handling in a new child process
347 enable_child_signals (HANDLE h_process)
349 HMODULE h_kernel = GetModuleHandle ("kernel32");
352 assert (h_kernel != NULL);
353 d.adr_SetConsoleCtrlHandler =
354 GetProcAddress (h_kernel, "SetConsoleCtrlHandler");
355 assert (d.adr_SetConsoleCtrlHandler);
356 run_in_other_process (h_process,
357 sig_enable_proc, sig_enable_code_end,
361 #pragma warning (default : 4113)
364 * Signal error if SIGNO is not supported
367 validate_signal_number (int signo)
369 if (signo != SIGKILL && signo != SIGTERM
370 && signo != SIGQUIT && signo != SIGINT
372 signal_simple_error ("Signal number not supported", make_int (signo));
375 /*-----------------------------------------------------------------------*/
376 /* Process methods */
377 /*-----------------------------------------------------------------------*/
380 * Allocate and initialize Lisp_Process->process_data
384 nt_alloc_process_data (struct Lisp_Process *p)
386 p->process_data = xnew_and_zero (struct nt_process_data);
390 nt_finalize_process_data (struct Lisp_Process *p, int for_disksave)
392 assert (!for_disksave);
393 if (NT_DATA(p)->h_process)
394 CloseHandle (NT_DATA(p)->h_process);
398 * Initialize XEmacs process implemenation once
401 nt_init_process (void)
403 /* Initialize winsock */
405 /* Request Winsock v1.1 Note the order: (minor=1, major=1) */
406 WSAStartup (MAKEWORD (1,1), &wsa_data);
410 * Fork off a subprocess. P is a pointer to newly created subprocess
411 * object. If this function signals, the caller is responsible for
412 * deleting (and finalizing) the process object.
414 * The method must return PID of the new proces, a (positive??? ####) number
415 * which fits into Lisp_Int. No return value indicates an error, the method
416 * must signal an error instead.
419 /* #### This function completely ignores Vprocess_environment */
422 signal_cannot_launch (Lisp_Object image_file, DWORD err)
424 mswindows_set_errno (err);
425 signal_simple_error_2 ("Error starting", image_file, lisp_strerror (errno));
429 nt_create_process (struct Lisp_Process *p,
430 Lisp_Object *argv, int nargv,
431 Lisp_Object program, Lisp_Object cur_dir)
433 HANDLE hmyshove, hmyslurp, hprocin, hprocout;
435 BOOL do_io, windowed;
437 /* Find out whether the application is windowed or not */
439 /* SHGetFileInfo tends to return ERROR_FILE_NOT_FOUND on most
440 errors. This leads to bogus error message. */
442 char *p = strrchr ((char *)XSTRING_DATA (program), '.');
444 (stricmp (p, ".exe") == 0 ||
445 stricmp (p, ".com") == 0 ||
446 stricmp (p, ".bat") == 0 ||
447 stricmp (p, ".cmd") == 0))
449 image_type = SHGetFileInfo ((char *)XSTRING_DATA (program), 0,NULL,
454 char progname[MAX_PATH];
455 sprintf (progname, "%s.exe", (char *)XSTRING_DATA (program));
456 image_type = SHGetFileInfo (progname, 0, NULL, 0, SHGFI_EXETYPE);
459 signal_cannot_launch (program, (GetLastError () == ERROR_FILE_NOT_FOUND
460 ? ERROR_BAD_FORMAT : GetLastError ()));
461 windowed = HIWORD (image_type) != 0;
464 /* Decide whether to do I/O on process handles, or just mark the
465 process exited immediately upon successful launching. We do I/O if the
466 process is a console one, or if it is windowed but windowed_process_io
468 do_io = !windowed || windowed_process_io ;
472 /* Create two unidirectional named pipes */
474 SECURITY_ATTRIBUTES sa;
476 sa.nLength = sizeof(sa);
477 sa.bInheritHandle = TRUE;
478 sa.lpSecurityDescriptor = NULL;
480 CreatePipe (&hprocin, &hmyshove, &sa, 0);
481 CreatePipe (&hmyslurp, &hprocout, &sa, 0);
483 /* Stupid Win32 allows to create a pipe with *both* ends either
484 inheritable or not. We need process ends inheritable, and local
485 ends not inheritable. */
486 DuplicateHandle (GetCurrentProcess(), hmyshove, GetCurrentProcess(), &htmp,
487 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
489 DuplicateHandle (GetCurrentProcess(), hmyslurp, GetCurrentProcess(), &htmp,
490 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
494 /* Convert an argv vector into Win32 style command line by a call to
495 lisp function `nt-quote-process-args' which see (in winnt.el)*/
498 Lisp_Object args_or_ret = Qnil;
501 GCPRO1 (args_or_ret);
503 for (i = 0; i < nargv; ++i)
504 args_or_ret = Fcons (*argv++, args_or_ret);
505 args_or_ret = Fnreverse (args_or_ret);
506 args_or_ret = Fcons (program, args_or_ret);
508 args_or_ret = call1 (Qnt_quote_process_args, args_or_ret);
510 if (!STRINGP (args_or_ret))
511 /* Luser wrote his/her own clever version */
512 error ("Bogus return value from `nt-quote-process-args'");
514 command_line = alloca_array (char, (XSTRING_LENGTH (program)
515 + XSTRING_LENGTH (args_or_ret) + 2));
516 strcpy (command_line, XSTRING_DATA (program));
517 strcat (command_line, " ");
518 strcat (command_line, XSTRING_DATA (args_or_ret));
520 UNGCPRO; /* args_or_ret */
526 PROCESS_INFORMATION pi;
530 si.dwFlags = STARTF_USESHOWWINDOW;
531 si.wShowWindow = windowed ? SW_SHOWNORMAL : SW_HIDE;
534 si.hStdInput = hprocin;
535 si.hStdOutput = hprocout;
536 si.hStdError = hprocout;
537 si.dwFlags |= STARTF_USESTDHANDLES;
540 err = (CreateProcess (NULL, command_line, NULL, NULL, TRUE,
541 CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP
543 NULL, (char *) XSTRING_DATA (cur_dir), &si, &pi)
544 ? 0 : GetLastError ());
548 /* These just have been inherited; we do not need a copy */
549 CloseHandle (hprocin);
550 CloseHandle (hprocout);
553 /* Handle process creation failure */
558 CloseHandle (hmyshove);
559 CloseHandle (hmyslurp);
561 signal_cannot_launch (program, GetLastError ());
564 /* The process started successfully */
567 NT_DATA(p)->h_process = pi.hProcess;
568 init_process_io_handles (p, (void*)hmyslurp, (void*)hmyshove, 0);
572 /* Indicate as if the process has exited immediately. */
573 p->status_symbol = Qexit;
574 CloseHandle (pi.hProcess);
578 enable_child_signals (pi.hProcess);
580 ResumeThread (pi.hThread);
581 CloseHandle (pi.hThread);
583 /* Hack to support Windows 95 negative pids */
584 return ((int)pi.dwProcessId < 0
585 ? -(int)pi.dwProcessId : (int)pi.dwProcessId);
590 * This method is called to update status fields of the process
591 * structure. If the process has not existed, this method is expected
594 * The method is called only for real child processes.
598 nt_update_status_if_terminated (struct Lisp_Process* p)
601 if (GetExitCodeProcess (NT_DATA(p)->h_process, &exit_code)
602 && exit_code != STILL_ACTIVE)
606 /* The exit code can be a code returned by process, or an
607 NTSTATUS value. We cannot accurately handle the latter since
608 it is a full 32 bit integer */
609 if (exit_code & 0xC0000000)
611 p->status_symbol = Qsignal;
612 p->exit_code = exit_code & 0x1FFFFFFF;
616 p->status_symbol = Qexit;
617 p->exit_code = exit_code;
623 * Stuff the entire contents of LSTREAM to the process ouptut pipe
626 /* #### If only this function could be somehow merged with
627 unix_send_process... */
630 nt_send_process (Lisp_Object proc, struct lstream* lstream)
632 struct Lisp_Process *p = XPROCESS (proc);
634 /* use a reasonable-sized buffer (somewhere around the size of the
635 stream buffer) so as to avoid inundating the stream with blocked
637 Bufbyte chunkbuf[512];
644 chunklen = Lstream_read (lstream, chunkbuf, 512);
646 break; /* perhaps should abort() if < 0?
647 This should never happen. */
649 /* Lstream_write() will never successfully write less than the
650 amount sent in. In the worst case, it just buffers the
652 writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
654 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
657 p->status_symbol = Qexit;
658 p->exit_code = ERROR_BROKEN_PIPE;
662 deactivate_process (proc);
663 error ("Broken pipe error sending to process %s; closed it",
664 XSTRING_DATA (p->name));
669 while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
671 /* Buffer is full. Wait, accepting input; that may allow
672 the program to finish doing output and read more. */
673 Faccept_process_output (Qnil, Qzero, make_int (wait_ms));
674 Lstream_flush (XLSTREAM (p->pipe_outstream));
675 wait_ms = min (1000, 2 * wait_ms);
682 * Send a signal number SIGNO to PROCESS.
683 * CURRENT_GROUP means send to the process group that currently owns
684 * the terminal being used to communicate with PROCESS.
685 * This is used for various commands in shell mode.
686 * If NOMSG is zero, insert signal-announcements into process's buffers
689 * If we can, we try to signal PROCESS by sending control characters
690 * down the pty. This allows us to signal inferiors who have changed
691 * their uid, for which killpg would return an EPERM error.
693 * The method signals an error if the given SIGNO is not valid
697 nt_kill_child_process (Lisp_Object proc, int signo,
698 int current_group, int nomsg)
700 struct Lisp_Process *p = XPROCESS (proc);
702 /* Signal error if SIGNO cannot be sent */
703 validate_signal_number (signo);
706 if (!send_signal (NT_DATA(p)->h_process, signo))
707 error ("Cannot send signal to process");
711 * Kill any process in the system given its PID.
713 * Returns zero if a signal successfully sent, or
714 * negative number upon failure
717 nt_kill_process_by_pid (int pid, int signo)
722 /* Signal error if SIGNO cannot be sent */
723 validate_signal_number (signo);
725 /* Try to open the process with required privileges */
726 h_process = OpenProcess (PROCESS_CREATE_THREAD
727 | PROCESS_QUERY_INFORMATION
728 | PROCESS_VM_OPERATION
731 if (h_process == NULL)
734 send_result = send_signal (h_process, signo);
736 CloseHandle (h_process);
738 return send_result ? 0 : -1;
741 /*-----------------------------------------------------------------------*/
742 /* Sockets connections */
743 /*-----------------------------------------------------------------------*/
746 /* #### Hey MS, how long Winsock 2 for '95 will be in beta? */
748 #define SOCK_TIMER_ID 666
749 #define XM_SOCKREPLY (WM_USER + 666)
752 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
755 char buf [MAXGETHOSTSTRUCT];
760 address->sin_family = AF_INET;
762 /* First check if HOST is already a numeric address */
764 unsigned long inaddr = inet_addr (XSTRING_DATA (host));
765 if (inaddr != INADDR_NONE)
767 address->sin_addr.s_addr = inaddr;
772 /* Create a window which will receive completion messages */
773 hwnd = CreateWindow ("STATIC", NULL, WS_OVERLAPPED, 0, 0, 1, 1,
774 NULL, NULL, NULL, NULL);
777 /* Post name resolution request */
778 hasync = WSAAsyncGetHostByName (hwnd, XM_SOCKREPLY, XSTRING_DATA (host),
783 /* Set a timer to poll for quit every 250 ms */
784 SetTimer (hwnd, SOCK_TIMER_ID, 250, NULL);
789 GetMessage (&msg, hwnd, 0, 0);
790 if (msg.message == XM_SOCKREPLY)
792 /* Ok, got an answer */
793 if (WSAGETASYNCERROR(msg.lParam) == NO_ERROR)
797 else if (msg.message == WM_TIMER && msg.wParam == SOCK_TIMER_ID)
801 WSACancelAsyncRequest (hasync);
802 KillTimer (hwnd, SOCK_TIMER_ID);
803 DestroyWindow (hwnd);
807 DispatchMessage (&msg);
811 KillTimer (hwnd, SOCK_TIMER_ID);
812 DestroyWindow (hwnd);
815 /* BUF starts with struct hostent */
816 struct hostent* he = (struct hostent*) buf;
817 address->sin_addr.s_addr = *(unsigned long*)he->h_addr_list[0];
823 nt_canonicalize_host_name (Lisp_Object host)
825 struct sockaddr_in address;
827 if (!get_internet_address (host, &address, ERROR_ME_NOT))
830 if (address.sin_family == AF_INET)
831 return build_string (inet_ntoa (address.sin_addr));
836 /* open a TCP network connection to a given HOST/SERVICE. Treated
837 exactly like a normal process when reading and writing. Only
838 differences are in status display and process deletion. A network
839 connection has no PID; you cannot signal it. All you can do is
840 deactivate and close it via delete-process */
843 nt_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
844 Lisp_Object family, void** vinfd, void** voutfd)
846 struct sockaddr_in address;
853 if (!EQ (family, Qtcpip))
854 error ("Unsupported protocol family \"%s\"",
855 string_data (symbol_name (XSYMBOL (family))));
858 port = htons ((unsigned short) XINT (service));
861 struct servent *svc_info;
862 CHECK_STRING (service);
863 svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
865 error ("Unknown service \"%s\"", XSTRING_DATA (service));
866 port = svc_info->s_port;
869 get_internet_address (host, &address, ERROR_ME);
870 address.sin_port = port;
872 s = socket (address.sin_family, SOCK_STREAM, 0);
874 report_file_error ("error creating socket", list1 (name));
876 /* We don't want to be blocked on connect */
878 unsigned int nonblock = 1;
879 ioctlsocket (s, FIONBIO, &nonblock);
882 retval = connect (s, (struct sockaddr *) &address, sizeof (address));
883 if (retval != NO_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
886 /* Wait while connection is established */
899 /* Poll for quit every 250 ms */
901 tv.tv_usec = 250 * 1000;
905 nsel = select (0, NULL, &fdset, &fdset, &tv);
909 /* Check was connnection successful or not */
911 nsel = select (0, NULL, NULL, &fdset, &tv);
919 /* We are connected at this point */
921 DuplicateHandle (GetCurrentProcess(), (HANDLE)s,
922 GetCurrentProcess(), (LPHANDLE)voutfd,
923 0, FALSE, DUPLICATE_SAME_ACCESS);
928 report_file_error ("connection failed", list2 (host, name));
933 /*-----------------------------------------------------------------------*/
935 /*-----------------------------------------------------------------------*/
938 process_type_create_nt (void)
940 PROCESS_HAS_METHOD (nt, alloc_process_data);
941 PROCESS_HAS_METHOD (nt, finalize_process_data);
942 PROCESS_HAS_METHOD (nt, init_process);
943 PROCESS_HAS_METHOD (nt, create_process);
944 PROCESS_HAS_METHOD (nt, update_status_if_terminated);
945 PROCESS_HAS_METHOD (nt, send_process);
946 PROCESS_HAS_METHOD (nt, kill_child_process);
947 PROCESS_HAS_METHOD (nt, kill_process_by_pid);
949 PROCESS_HAS_METHOD (nt, canonicalize_host_name);
950 PROCESS_HAS_METHOD (nt, open_network_stream);
951 #ifdef HAVE_MULTICAST
952 #error I won't do this until '95 has winsock2
953 PROCESS_HAS_METHOD (nt, open_multicast_group);
959 syms_of_process_nt (void)
961 defsymbol (&Qnt_quote_process_args, "nt-quote-process-args");
965 vars_of_process_nt (void)